from peewee import CharField, IntegerField, FloatField, BooleanField

from core.database import BaseModel, db


# 定义Target类，对应targets表
class SFGridTradeTarget(BaseModel):
    stock_code = CharField(unique=True)
    stock_name = CharField()
    market_price = FloatField()
    current_position = IntegerField()
    grid_index = IntegerField()
    last_trade_price = FloatField()
    plan_buy_price = FloatField()
    plan_sell_price = FloatField()
    current_order_price = FloatField()
    current_order_no = CharField(default='')
    current_order_type = CharField(default='')
    status = IntegerField(default=0)  # -1表示新标的，未完成交易配置，0表示新标的，已完成交易配置，1表示已建初始仓，正常交易中
    enabled = BooleanField(default=False)  # 是否启动交易线程

    grid_start_price = FloatField(default=10.0) # 基线价格
    grid_size = FloatField(default=0.1)        # 网格价位差
    grid_volume = IntegerField(default=100)    # 网格交易量
    grid_upper_count = IntegerField(default=1)  # 基线价格上方网格数
    grid_lower_count = IntegerField(default=10)  # 基线价格下方网格数

    def targetName(self):
        return f'{self.stock_code}-{self.stock_name}'
    
    def getPriceGrid(self) -> list:
        self.priceGrid: list = []
        # 网格大小，数量
        if self.priceGrid is None or len(self.priceGrid) == 0:
            for i in range(self.grid_upper_count):  # type: ignore 
                upperPrice = self.grid_start_price + (self.grid_upper_count - i) * self.grid_size
                self.priceGrid.append(upperPrice)
            
            self.priceGrid.append(self.grid_start_price)
            
            for i in range(self.grid_lower_count): # type: ignore 5
                lowerPrice = self.grid_start_price - (i + 1) * self.grid_size
                self.priceGrid.append(lowerPrice)
        
        return self.priceGrid


db.create_tables([SFGridTradeTarget])