Loading ...

模拟盘环境

Author: 卧野望平川, Date: 2022-04-04 10:34:30
Tags:

API文档:https://www.fmz.com/bbs-topic/9183



import time
class Simulation:
    def __init__(self,index):
        self.index = index
        self.HangingOrder = _G(f'{self.index}HangingOrder') # 未完成订单
        self.Order = _G(f'{self.index}Order') # 订单结构
        self.MarginLevel =  _G(f'{self.index}MarginLevel') # 杠杆倍数
        self.futures =  _G(f'{self.index}futures') # 设置合约类型
        self.SideDirection =  _G(f'{self.index}SideDirection') # 下单方向
        self.Account =  _G(f'{self.index}Account')
        self.position =  _G(f'{self.index}position') # 仓位信息
        self.Balance =  _G(f'{self.index}Balance') # 计价币余额
        self.feeCcy =  _G(f'{self.index}feeCcy') # 手续费
        self.Spread =  _G(f'{self.index}Spread') # 点差

    # 设置合约类型
    def SetContractType(self,text):
        self.futures = True
        _G(f'{self.index}futures',self.futures)

    # 期货下单方向
    def SetDirection(self,text):
        self.SideDirection = str(text)
        _G(f'{self.index}SideDirection',self.SideDirection)

    # 买入
    def Buy(self,price,account):
        if price == -1: # 如果是市价
            ticker = exchanges[self.index].GetTicker() # 获取当前价格
            if self.futures == True: # 如果期货模式开启
                if str(self.SideDirection) == "buy":
                    if self.Account["Balance"] >= ticker["Last"]*float(account)/self.MarginLevel: # 如果计价币余额大于等于买入金额
                        # 增加持仓
                        already = False # 加仓标记
                        for i in range(len(self.position)):
                            if self.position[i]["Type"] == "LONG":
                                # 更新持仓均价
                                self.position[i]["Price"] = (self.position[i]["Price"] + (ticker["Last"]*(account/self.position[i]["Amount"])))/(1+(account/self.position[i]["Amount"]))
                                self.Account["Balance"] = self.Account["Balance"] - (ticker["Last"]*float(account)/self.MarginLevel) - ticker["Last"]*float(account)*self.feeCcy # 扣除余额保证金
                                _G(f'{self.index}Account',self.Account)
                                self.position[i]["Amount"] = self.position[i]["Amount"] + account
                                _G(f'{self.index}position',self.position)
                                already = True
                        if already == False:
                            self.Account["Balance"] = self.Account["Balance"] - (ticker["Last"]*float(account)/self.MarginLevel) - ticker["Last"]*float(account)*self.feeCcy # 扣除余额保证金
                            _G(f'{self.index}Account',self.Account)
                            self.position.append({"MarginLevel":self.MarginLevel,"Amount":account,"FrozenAmount":0,"Price":ticker["Last"],"Profit":0,"Type":"LONG","Margin":_N(float(account)*ticker["Last"]/self.MarginLevel,3)})
                            _G(f'{self.index}position',self.position)
                        self.Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"BUY","Type":"LONG","profit":0,"feeCcy":(ticker["Last"]*float(account)*self.feeCcy)})
                        _G(f'{self.index}Order',self.Order)
                        exchanges[self.index].Log(LOG_TYPE_BUY, -1, account, f"{exchanges[self.index].GetCurrency()}买入开多")
                        self.SideDirection = "null"
                        return self.Order[-1]["Id"]
                    else:
                        Log("买入失败 原因:余额不足")
                elif str(self.SideDirection) == "closesell":
                    # 减少持仓
                    already = False # 减仓标记
                    if len(self.position) > 0:
                        for i in range(len(self.position)): # 如果持仓存在空头且数量等于或小于或大于存在数量
                            if self.position[i]["Type"] == "SHORT" and account == self.position[i]["Amount"] - self.position[i]["FrozenAmount"]:
                                self.Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"BUY","Type":"SHORT","profit":((self.position[i]["Price"]-ticker["Last"])*account),"feeCcy":(ticker["Last"]*float(account)*self.feeCcy)})
                                _G(f'{self.index}Order',self.Order)
                                exchanges[self.index].Log(LOG_TYPE_BUY, -1, account, f"{exchanges[self.index].GetCurrency()}买入平空")
                                self.SideDirection = "null"
                                del self.position[i]
                                _G(f'{self.index}position',self.position)
                                return self.Order[-1]["Id"]
                            elif self.position[i]["Type"] == "SHORT" and account < self.position[i]["Amount"] - self.position[i]["FrozenAmount"]:
                                self.position[i]["Amount"] = self.position[i]["Amount"] - float(account)
                                _G(f'{self.index}position',self.position)
                                already = True
                            elif self.position[i]["Type"] == "SHORT" and account > self.position[i]["Amount"] - self.position[i]["FrozenAmount"]:
                                Log("买入失败 原因:数量大于最大可买数量")
                                return
                        if already == True:
                            self.Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"BUY","Type":"SHORT","profit":((self.position[i]["Price"]-ticker["Last"])*account),"feeCcy":(ticker["Last"]*float(account)*self.feeCcy)})
                            _G(f'{self.index}Order',self.Order)
                            exchanges[self.index].Log(LOG_TYPE_BUY, -1, account, f"{exchanges[self.index].GetCurrency()}买入平空")
                            self.SideDirection = "null"
                            return self.Order[-1]["Id"]
                        else:
                            Log("买入失败 原因:持仓不存在")
                    else:
                        Log("买入失败 原因:持仓不存在")
                else:
                    Log("期货品种订阅失败")
            else:
                if self.Account["Balance"] >= ticker["Last"]*float(account): # 如果计价币余额大于等于买入金额
                    # 更新计价币余额
                    self.Account["Balance"] = self.Account["Balance"] - (ticker["Last"]*float(account))
                    # 更新币种余额
                    self.Account["Stocks"] = self.Account["Stocks"] + ((ticker["Last"]*float(account)-(ticker["Last"]*float(account)*self.feeCcy))/ticker["Last"])
                    _G(f'{self.index}Account',self.Account)
                    self.Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(self.Account["Stocks"]),"DealAmount":float(self.Account["Stocks"]),"AvgPrice":ticker["Last"],"Side":"BUY","Type":"NULL","profit":"NULL","feeCcy":(ticker["Last"]*float(account)*self.feeCcy)})
                    _G(f'{self.index}Order',self.Order)
                    exchanges[self.index].Log(LOG_TYPE_BUY, -1, account, f"{exchanges[self.index].GetCurrency()}现货")
                    self.SideDirection = "null"
                    return self.Order[-1]["Id"]
                else:
                    Log("买入失败 原因:余额不足")
        else:
            if self.futures == True:
                if str(self.SideDirection) == "buy": # 如果方向为开多
                    if self.Account["Balance"] >= price*float(account)/self.MarginLevel: # 如果计价币余额大于等于买入金额
                        # 加入未完成订单
                        self.HangingOrder.append({"Side":"BUY","Type":"LONG","Price":float(price),"Amount":float(account),"Id":int(round(time.time()* 1000000))})
                        _G(f'{self.index}HangingOrder',self.HangingOrder)
                        exchanges[self.index].Log(LOG_TYPE_BUY, price, account, f"{exchanges[self.index].GetCurrency()}买入开多")
                        # 冻结资金
                        self.Account["FrozenBalance"] = self.Account["FrozenBalance"] + (price*float(account)/self.MarginLevel)
                        self.Account["Balance"] = self.Account["Balance"] - self.Account["FrozenBalance"]
                        _G(f'{self.index}Account',self.Account)
                        self.SideDirection = "null"
                        return self.HangingOrder[-1]["Id"]
                    else:
                        Log("买入失败 原因:余额不足")
                elif str(self.SideDirection) == "closesell": # 如果方向为平空
                    if len(self.position)>0: # 如果存在持仓
                        sign = False # 遍历标记
                        for i in range(len(self.position)): # 遍历持仓
                            # 如果符合条件
                            if self.position[i]["Type"] == "SHORT" and self.position[i]["Amount"] - self.position[i]["FrozenAmount"] >= float(account):
                                # 冻结资金
                                self.position[i]["FrozenAmount"] = self.position[i]["FrozenAmount"] + account
                                _G(f'{self.index}position',self.position)
                                # 加入未完成订单
                                self.HangingOrder.append({"Side":"BUY","Type":"SHORT","Price":float(price),"Amount":float(account),"Id":int(round(time.time()* 1000000))})
                                _G(f'{self.index}HangingOrder',self.HangingOrder)
                                exchanges[self.index].Log(LOG_TYPE_BUY, price, account, f"{exchanges[self.index].GetCurrency()}买入平空")
                                self.SideDirection = "null"
                                sign = True
                                return self.HangingOrder[-1]["Id"]
                            elif self.position[i]["Type"] == "SHORT" and self.position[i]["Amount"] < float(account):
                                sign = True 
                                Log("买入失败 原因:买入数量大于最多可买入数量")
                        if sign == True:
                            Log("买入失败 原因:持仓不存在")
                    else:
                        Log("买入失败 原因:持仓不存在")
                else:
                    Log("期货品种订阅失败")
            else:
                if self.Account["Balance"] >= price*float(account):
                    self.HangingOrder.append({"Side":"BUY","Type":"NULL","Price":float(price),"Amount":float(account),"Id":int(round(time.time()* 1000000))})
                    _G(f'{self.index}HangingOrder',self.HangingOrder)
                    # 冻结资金
                    self.Account["FrozenBalance"] = self.Account["FrozenBalance"] + (price*float(account))
                    self.Account["Balance"] = self.Account["Balance"] - self.Account["FrozenBalance"]
                    _G(f'{self.index}Account',self.Account)
                    exchanges[self.index].Log(LOG_TYPE_BUY, price, account, f"{exchanges[self.index].GetCurrency()}现货")
                    self.SideDirection = "null"
                    return self.HangingOrder[-1]["Id"]
                else:
                    Log("买入失败 原因:买入数量大于最大可买数量")
        self.SideDirection = "null"
    
    # 卖出
    def Sell(self,price,account):
        if price == -1:
            ticker = exchanges[self.index].GetTicker() # 获取当前价格
            if self.futures == True:
                if str(self.SideDirection) == "sell":
                    if self.Account["Balance"] >= ticker["Last"]*float(account)/self.MarginLevel: # 如果计价币余额大于等于买入余额
                        # 如果存在空头持仓
                        already = False # 加仓标记
                        for i in range(len(self.position)):
                            if self.position[i]["Type"] == "SHORT":
                                # 更新持仓均价
                                self.position[i]["Price"] = (self.position[i]["Price"] + (ticker["Last"]*(account/self.position[i]["Amount"])))/(1+(account/self.position[i]["Amount"]))
                                self.Account["Balance"] = self.Account["Balance"] - (ticker["Last"]*float(account)/self.MarginLevel) - ticker["Last"]*float(account)*self.feeCcy # 减少计价币余额
                                _G(f'{self.index}Account',self.Account)
                                self.position[i]["Amount"] = self.position[i]["Amount"] + account # 增加持仓
                                _G(f'{self.index}position',self.position)
                                self.Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"SELL","Type":"SHORT","profit":0,"feeCcy":ticker["Last"]*float(account)*self.feeCcy})
                                _G(f'{self.index}Order',self.Order)
                                already = True
                        if already == False:
                            self.Account["Balance"] = self.Account["Balance"] - (ticker["Last"]*float(account)/self.MarginLevel) - ticker["Last"]*float(account)*self.feeCcy # 减少计价币余额
                            _G(f'{self.index}Account',self.Account)
                            self.position.append({"MarginLevel":self.MarginLevel,"Amount":account,"FrozenAmount":0,"Price":ticker["Last"],"Profit":0,"Type":"SHORT","Margin":_N(float(account)*ticker["Last"]/self.MarginLevel,3)})
                            _G(f'{self.index}position',self.position)
                            self.Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"SELL","Type":"SHORT","profit":0,"feeCcy":ticker["Last"]*float(account)*self.feeCcy})
                            _G(f'{self.index}Order',self.Order)
                            exchanges[self.index].Log(LOG_TYPE_SELL, -1, account, f"{exchanges[self.index].GetCurrency()}卖出开空")
                        self.SideDirection = "null"
                        return self.Order[-1]["Id"]
                    else:
                        Log("卖出失败 原因:余额不足")
                elif str(self.SideDirection) == "closebuy":
                    # 减少持仓
                    already = False # 减仓标记
                    if len(self.position) > 0:
                        for i in range(len(self.position)): # 如果持仓存在空头且数量等于或小于或大于存在数量
                            if self.position[i]["Type"] == "LONG" and account == self.position[i]["Amount"] - self.position[i]["FrozenAmount"]:
                                self.Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"SELL","Type":"LONG","profit":((ticker["Last"]-self.position[i]["Price"])*account),"feeCcy":(ticker["Last"]*float(account)*self.feeCcy)})
                                _G(f'{self.index}Order',self.Order)
                                exchanges[self.index].Log(LOG_TYPE_SELL, -1, account, f"{exchanges[self.index].GetCurrency()}卖出平多")
                                self.SideDirection = "null"
                                self.Account["Balance"] = self.Account["Balance"] + self.position[i]["Margin"] - (ticker["Last"]*float(account)*self.feeCcy) # 增加计价币余额
                                _G(f'{self.index}Account',self.Account)
                                del self.position[i]
                                _G(f'{self.index}position',self.position)
                                return self.Order[-1]["Id"]
                            elif self.position[i]["Type"] == "LONG" and account < self.position[i]["Amount"] - self.position[i]["FrozenAmount"]:
                                self.Account["Balance"] = self.Account["Balance"] + (ticker["Last"]*float(account)/self.MarginLevel) - (ticker["Last"]*float(account)*self.feeCcy) # 增加计价币余额
                                _G(f'{self.index}Account',self.Account)
                                self.position[i]["Amount"] = self.position[i]["Amount"] - float(account)
                                _G(f'{self.index}position',self.position)
                                already = True
                            elif self.position[i]["Type"] == "LONG" and account > self.position[i]["Amount"] - self.position[i]["FrozenAmount"]:
                                Log("卖出失败 原因:数量大于最大可卖数量")
                                return
                        if already == True:
                            self.Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"SELL","Type":"LONG","profit":((ticker["Last"]-self.position[i]["Price"])*account),"feeCcy":(ticker["Last"]*float(account)*self.feeCcy)})
                            _G(f'{self.index}Order',self.Order)
                            exchanges[self.index].Log(LOG_TYPE_SELL, -1, account, f"{exchanges[self.index].GetCurrency()}卖出平多")
                            self.SideDirection = "null"
                            return self.Order[-1]["Id"]
                        else:
                            Log("卖出失败 原因:持仓不存在")
                    else:
                        Log("卖出失败 原因:持仓不存在")
                else:
                    Log("期货品种订阅失败")
            else:
                if self.Account["Stocks"] >= float(account):
                    # 更新计价币余额
                    self.Account["Balance"] = self.Account["Balance"] + (ticker["Last"]*float(account)*(1-self.feeCcy))
                    # 更新币种余额
                    self.Account["Stocks"] = self.Account["Stocks"] - float(account)
                    _G(f'{self.index}Account',self.Account)
                    self.Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"SELL","Type":"NULL","profit":"NULL","feeCcy":(ticker["Last"]*float(account)*self.feeCcy)})
                    _G(f'{self.index}Order',self.Order)
                    exchanges[self.index].Log(LOG_TYPE_SELL, -1, account, f"{exchanges[self.index].GetCurrency()}现货")
                    self.SideDirection = "null"
                    return self.Order[-1]["Id"]
                else:
                    Log("卖出失败 原因:数量大于最大可卖数量")
        else:
            if self.futures == True:
                if str(self.SideDirection) == "sell": # 如果方向为开空
                    if self.Account["Balance"] >= price*float(account)/self.MarginLevel: # 如果计价币余额大于等于卖出金额
                        # 加入未完成订单
                        self.HangingOrder.append({"Side":"SELL","Type":"SHORT","Price":float(price),"Amount":float(account),"Id":int(round(time.time()* 1000000))})
                        _G(f'{self.index}HangingOrder',self.HangingOrder)
                        exchanges[self.index].Log(LOG_TYPE_SELL, price, account, f"{exchanges[self.index].GetCurrency()}卖出开空")
                        # 冻结资金
                        self.Account["FrozenBalance"] = self.Account["FrozenBalance"] + (price*float(account)/self.MarginLevel)
                        self.Account["Balance"] = self.Account["Balance"] - self.Account["FrozenBalance"]
                        _G(f'{self.index}Account',self.Account)
                        self.SideDirection = "null"
                        return self.HangingOrder[-1]["Id"]
                    else:
                        Log("卖出失败 原因:余额不足")
                elif str(self.SideDirection) == "closebuy": # 如果方向为平多
                    if len(self.position) > 0: # 如果存在持仓
                        sign = False # 遍历标记
                        for i in range(len(self.position)): # 遍历持仓
                            # 如果符合条件
                            if self.position[i]["Type"] == "LONG" and self.position[i]["Amount"] - self.position[i]["FrozenAmount"] >= float(account):
                                # 冻结资金
                                self.position[i]["FrozenAmount"] = self.position[i]["FrozenAmount"] + account
                                _G(f'{self.index}position',self.position)
                                # 加入未完成订单
                                self.HangingOrder.append({"Side":"SELL","Type":"LONG","Price":float(price),"Amount":float(account),"Id":int(round(time.time()* 1000000))})
                                _G(f'{self.index}HangingOrder',self.HangingOrder)
                                exchanges[self.index].Log(LOG_TYPE_SELL, price, account, f"{exchanges[self.index].GetCurrency()}卖出平多")
                                self.SideDirection = "null"
                                sign = True
                                return self.HangingOrder[-1]["Id"]
                            elif self.position[i]["Type"] == "LONG" and self.position[i]["Amount"] < float(account):
                                sign = True 
                                Log("卖出失败 原因:卖出数量大于最多可卖入数量")
                        if sign == False:
                            Log("卖出失败 原因:持仓不存在")
                    else:
                        Log("卖出失败 原因:持仓不存在")
                else:
                    Log("期货品种订阅失败")
            else:
                if self.Account["Stocks"] >= float(account): # 如果币种余额大于等于币种余额
                    self.HangingOrder.append({"Side":"SELL","Type":"NULL","Price":float(price),"Amount":float(account),"Id":int(round(time.time()* 1000000))})
                    _G(f'{self.index}HangingOrder',self.HangingOrder)
                    # 冻结资金
                    self.Account["FrozenStocks"] = self.Account["FrozenStocks"] + float(account)
                    self.Account["Stocks"] = self.Account["Stocks"] - self.Account["FrozenStocks"]
                    _G(f'{self.index}Account',self.Account)
                    exchanges[self.index].Log(LOG_TYPE_SELL, price, account, f"{exchanges[self.index].GetCurrency()}现货")
                    self.SideDirection = "null"
                    return self.HangingOrder[-1]["Id"]
                else:
                    Log("卖出失败 原因:余额不足")
        self.SideDirection = "null"
    
    # 撤销订单
    def CancelOrder(self,id):
        for i in range(len(self.HangingOrder)):
            if self.HangingOrder[i]["Id"] == int(id):
                del self.HangingOrder[i]
                exchanges[self.index].Log(LOG_TYPE_CANCEL, 123)

    # 获取已完成订单
    def GetOrder(self,id=0):
        if id != 0:
            for i in range(len(self.Order)):
                if self.Order[i]["Id"] == int(id):
                    return self.Order[i]
        else:
            return self.Order
    
    # 获取未完成订单
    def GetOrders(self,id=0):
        if id != 0:
            for i in range(len(self.HangingOrder)):
                if self.HangingOrder[i]["Id"] == int(id):
                    return self.HangingOrder[i]
        else:
            return self.HangingOrder

    # 获取账户信息
    def GetAccount(self):
        return self.Account

    # 获取持仓信息
    def GetPosition(self):
        return self.position

    # 设置杠杆倍数
    def SetMarginLevel(self,level):
        if len(self.position) == 0:
            self.MarginLevel = int(level)
            _G(f'{self.index}MarginLevel',self.MarginLevel)
        else:
            Log("设置杠杆失败 原因:存在持仓")
    
    # 设置手续费
    def SetServiceCharge(self,data):
        if len(self.position) == 0:
            self.feeCcy = float(data)
            _G(f'{self.index}feeCcy',self.feeCcy)
        else:
            Log("设置手续费失败 原因:存在持仓")
    
    # 设置余额
    def SetBalance(self,data):
        if len(self.position) == 0:
            self.Balance = float(data)
            _G(f'{self.index}Balance',self.Balance)
        else:
            Log("设置余额失败 原因:存在持仓")

    # 设置点差
    def SetSpread(self,data):
        if len(self.position) == 0:
            self.Spread = float(data)
            _G(f'{self.index}Spread',self.Spread)
        else:
            Log("设置点差失败 原因:存在持仓")

def SimGo():
    for i in range(len(exchange)):
        ticker = exchanges[i].GetTicker()
        # 遍历未成交订单
        for j in range(len(exchange[i].HangingOrder)):
            if ticker["Last"] < (exchange[i].HangingOrder[j]["Price"])*(1+exchange[i].Spread) and ticker["Last"] > (exchange[i].HangingOrder[j]["Price"])*(1-exchange[i].Spread):
                account = exchange[i].HangingOrder[j]["Amount"]
                # 判断交易类型
                if exchange[i].HangingOrder[j]["Side"] == "BUY":
                    if exchange[i].HangingOrder[j]["Type"] == "LONG": 
                        # 增加持仓
                        already = False # 加仓标记
                        for k in range(len(exchange[i].position)): # 遍历持仓
                            if exchange[i].position[k]["Type"] == "LONG": # 如果存在持仓
                                # 更新持仓均价
                                exchange[i].position[k]["Price"] = (exchange[i].position[k]["Price"] + (ticker["Last"]*(account/exchange[i].position[k]["Amount"])))/(1+(account/exchange[i].position[k]["Amount"]))
                                # 更新持仓数量
                                exchange[i].position[k]["Amount"] = exchange[i].position[k]["Amount"] + account
                                _G(f'{i}position',exchange[i].position)
                                already = True
                        # 如果标记未更新则证明无持仓
                        if already == False:
                            # 添加仓位数据
                            exchange[i].position.append({"MarginLevel":exchange[i].MarginLevel,"Amount":account,"FrozenAmount":0,"Price":ticker["Last"],"Profit":0,"Type":"LONG","Margin":_N(float(account)*ticker["Last"]/exchange[i].MarginLevel,3)})
                            _G(f'{i}position',exchange[i].position)
                        exchange[i].Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"BUY","Type":"LONG","feeCcy":(ticker["Last"]*float(account)*exchange[i].feeCcy)})
                        exchange[i].Account["FrozenBalance"] = exchange[i].Account["FrozenBalance"] - (exchange[i].HangingOrder[j]["Price"]*account/exchange[i].MarginLevel) # 解冻资金
                        # 扣除手续费
                        exchange[i].Account["Balance"] = exchange[i].Account["Balance"] - (ticker["Last"]*account*exchange[i].feeCcy)
                        _G(f'{i}Account',exchange[i].Account)
                        _G(f'{i}Order',exchange[i].Order)

                    elif exchange[i].HangingOrder[j]["Type"] == "SHORT":
                        # 减少持仓
                        already = False # 减仓标记
                        if len(exchange[i].position) > 0: # 如果存在持仓
                            for k in range(len(exchange[i].position)): # 如果持仓存在空头且数量等于或小于或大于存在数量
                                if exchange[i].position[k]["Type"] == "SHORT" and account == exchange[i].position[k]["Amount"]:
                                    exchange[i].Account["Balance"] = exchange[i].Account["Balance"] + ((exchange[i].position[k]["Price"]-ticker["Last"])*account)
                                    del exchange[i].position[k]
                                    _G(f'{i}position',exchange[i].position)
                                    _G(f'{i}Account',exchange[i].Account)
                                    # 添加订单信息
                                    exchange[i].Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"BUY","Type":"SHORT","feeCcy":(ticker["Last"]*float(account)*exchange[i].feeCcy)})
                                    _G(f'{i}Order',exchange[i].Order)
                                    return
                                elif exchange[i].position[k]["Type"] == "SHORT" and account < exchange[i].position[k]["Amount"]:
                                    # 解冻资金
                                    exchange[i].position[k]["FrozenAmount"] = exchange[i].position[k]["FrozenAmount"] - account
                                    exchange[i].Account["Balance"] = exchange[i].Account["Balance"] + ((exchange[i].position[k]["Price"]-ticker["Last"])*account)
                                    exchange[i].position[k]["Amount"] = exchange[i].position[k]["Amount"] - float(account)
                                    _G(f'{i}position',exchange[i].position)
                                    _G(f'{i}Account',exchange[i].Account)
                                    already = True
                            if already == True:
                                # 添加订单信息
                                exchange[i].Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"BUY","Type":"SHORT","feeCcy":(ticker["Last"]*float(account)*exchange[i].feeCcy)})
                                _G(f'{i}Order',exchange[i].Order)
                            # 扣除手续费
                            exchange[i].Account["Balance"] = exchange[i].Account["Balance"] - (ticker["Last"]*account*exchange[i].feeCcy)
                            exchange[i].Account["Balance"] = exchange[i].Account["Balance"] + (ticker["Last"]*float(account)/exchange[i].MarginLevel) # 增加计价币余额
                            _G(f'{i}Account',exchange[i].Account)

                    elif exchange[i].HangingOrder[j]["Type"] == "NULL":
                        # 更新冻结资金余额
                        exchange[i].Account["FrozenBalance"] = exchange[i].Account["FrozenBalance"] - (exchange[i].HangingOrder[j]["Price"]*float(account))
                        # 更新币种余额
                        exchange[i].Account["Stocks"] = exchange[i].Account["Stocks"] + ((ticker["Last"]*float(account)-(ticker["Last"]*float(account)*exchange[i].feeCcy))/ticker["Last"])
                        exchange[i].Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(exchange[i].Account["Stocks"]),"DealAmount":float(exchange[i].Account["Stocks"]),"AvgPrice":ticker["Last"],"Side":"BUY","Type":"NULL","feeCcy":(ticker["Last"]*float(account)*exchange[i].feeCcy)})
                        _G(f'{i}Account',exchange[i].Account)
                        _G(f'{i}Order',exchange[i].Order)
                            
                if exchange[i].HangingOrder[j]["Side"] == "SELL":
                    if exchange[i].HangingOrder[j]["Type"] == "LONG":
                        # 减少持仓
                        already = False # 减仓标记
                        if len(exchange[i].position) > 0:
                            for k in range(len(exchange[i].position)): # 如果持仓存在空头且数量等于或小于或大于存在数量
                                if exchange[i].position[k]["Type"] == "LONG" and account == exchange[i].position[k]["FrozenAmount"]:
                                    exchange[i].Account["Balance"] = exchange[i].Account["Balance"] + ((ticker["Last"]-exchange[i].position[k]["Price"])*account)
                                    del exchange[i].position[k]
                                    _G(f'{i}position',exchange[i].position)
                                    _G(f'{i}Account',exchange[i].Account)
                                    exchange[i].Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"SELL","Type":"LONG","feeCcy":(ticker["Last"]*float(account)*exchange[i].feeCcy)})
                                    _G(f'{i}Order',exchange[i].Order)
                                    return
                                elif exchange[i].position[k]["Type"] == "LONG" and account < exchange[i].position[k]["FrozenAmount"]:
                                    exchange[i].position[k]["Amount"] = exchange[i].position[k]["Amount"] - float(account)
                                    exchange[i].Account["Balance"] = exchange[i].Account["Balance"] + ((ticker["Last"]-exchange[i].position[k]["Price"])*account)
                                    # 解冻资金
                                    exchange[i].position[k]["FrozenAmount"] = exchange[i].position[k]["FrozenAmount"] - account
                                    _G(f'{i}position',exchange[i].position)
                                    _G(f'{i}Account',exchange[i].Account)
                                    already = True
                            if already == True:
                                exchange[i].Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"SELL","Type":"LONG","feeCcy":(ticker["Last"]*float(account)*exchange[i].feeCcy)})
                                _G(f'{i}Order',exchange[i].Order)
                            # 扣除手续费
                            exchange[i].Account["Balance"] = exchange[i].Account["Balance"] - (ticker["Last"]*account*exchange[i].feeCcy)
                            exchange[i].Account["Balance"] = exchange[i].Account["Balance"] + (ticker["Last"]*float(account)/exchange[i].MarginLevel) # 增加计价币余额
                            _G(f'{i}Account',exchange[i].Account)
                
                    elif exchange[i].HangingOrder[j]["Type"] == "SHORT":
                        # 如果存在空头持仓
                        already = False # 加仓标记
                        for k in range(len(exchange[i].position)):
                            if exchange[i].position[k]["Type"] == "SHORT":
                                # 更新持仓均价
                                exchange[i].position[k]["Price"] = (exchange[i].position[k]["Price"] + (ticker["Last"]*(account/exchange[i].position[k]["Amount"])))/(1+(account/exchange[i].position[k]["Amount"]))
                                # 更新持仓
                                exchange[i].position[k]["Amount"] = exchange[i].position[k]["Amount"] + account
                                _G(f'{i}position',exchange[i].position)
                                exchange[i].Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"SELL","Type":"SHORT","feeCcy":ticker["Last"]*float(account)*exchange[i].feeCcy})
                                already = True
                                _G(f'{i}Order',exchange[i].Order)
                        # 如果不存在持仓
                        if already == False:
                            exchange[i].position.append({"MarginLevel":exchange[i].MarginLevel,"Amount":account,"FrozenAmount":0,"Price":ticker["Last"],"Profit":0,"Type":"SHORT","Margin":_N(float(account)*ticker["Last"]/exchange[i].MarginLevel,3)})
                            _G(f'{i}position',exchange[i].position)
                            exchange[i].Order.append({"Id":int(round(time.time()* 1000000)),"Price":ticker["Last"],"Amount":float(account),"DealAmount":float(account),"AvgPrice":ticker["Last"],"Side":"SELL","Type":"SHORT","feeCcy":ticker["Last"]*float(account)*exchange[i].feeCcy})
                            _G(f'{i}Order',exchange[i].Order)
                        # 扣除手续费
                        exchange[i].Account["Balance"] = exchange[i].Account["Balance"] - (ticker["Last"]*account*exchange[i].feeCcy)
                        # 解冻资金
                        exchange[i].Account["FrozenBalance"] = exchange[i].Account["FrozenBalance"] - (exchange[i].HangingOrder[j]["Price"]*account/exchange[i].MarginLevel)
                        _G(f'{i}Account',exchange[i].Account)

                elif exchange[i].HangingOrder[j]["Side"] == "NULL":
                    # 解冻资金
                    exchange[i].Account["FrozenStocks"] = exchange[i].Account["FrozenStocks"] - float(account)
                    exchange[i].Account["Stocks"] = exchange[i].Account["Stocks"] + float(account)
                    _G(f'{i}Account',exchange[i].Account)

                # 删除未完成订单
                del exchange[i].HangingOrder[j]
                _G(f'{i}HangingOrder',exchange[i].HangingOrder)

        # 更新持仓信息
        if len(exchange[i].position) > 0:
            Margins = 0
            for n in range(len(exchange[i].position)):
                if exchange[i].position[n]["Type"] == "LONG":
                    # 更新利润
                    exchange[i].position[n]["Profit"] = (exchange[i].position[n]["Amount"]*ticker["Last"])-(exchange[i].position[n]["Amount"]*exchange[i].position[n]["Price"])
                    shorttime = (exchange[i].position[n]["Amount"]*ticker["Last"])/exchange[i].MarginLevel
                    # 计算保证金差值
                    cha = shorttime - exchange[i].position[n]["Margin"]
                    exchange[i].position[n]["Margin"] = exchange[i].position[n]["Margin"] + cha
                    exchange[i].Account["Balance"] = exchange[i].Account["Balance"] - cha
                    _G(f'{i}position',exchange[i].position)
                    _G(f'{i}Account',exchange[i].Account)
                elif exchange[i].position[n]["Type"] == "SHORT":
                    # 更新利润
                    exchange[i].position[n]["Profit"] = (exchange[i].position[n]["Amount"]*exchange[i].position[n]["Price"])-(exchange[i].position[n]["Amount"]*ticker["Last"])
                    shorttime = (exchange[i].position[n]["Amount"]*ticker["Last"])/exchange[i].MarginLevel
                    # 计算保证金差值
                    cha = shorttime - exchange[i].position[n]["Margin"]
                    exchange[i].position[n]["Margin"] = exchange[i].position[n]["Margin"] + cha
                    exchange[i].Account["Balance"] = exchange[i].Account["Balance"] - cha
                    _G(f'{i}position',exchange[i].position)
                    _G(f'{i}Account',exchange[i].Account)
                Margins = Margins + exchange[i].position[n]["Margin"]
            # 如果当前保证金低于最低维持保证金
            if Margins + exchange[i].Account["Balance"] < (exchange[i].position[n]["Amount"]*ticker["Last"])/exchange[i].MarginLevel:
                Log("警报:当前保证金低于最低维持保证金,仓位已被强制平仓")
                exchange[i].position.clear()
                exchange[i].Account["Balance"] = 0
                exchange[i].HangingOrder.clear()
                _G(f'{i}position',exchange[i].position)
                _G(f'{i}Account',exchange[i].Account)
                _G(f'{i}HangingOrder',exchange[i].HangingOrder)
        Sleep(100)


def SimSign():
    global exchange
    exchange = []
    for i in range(len(exchanges)):
        # 写入对象
        exchange.append(Simulation(i))

def IFsign():
    _G(None)
    for i in range(len(exchanges)):
        _G(f'{i}HangingOrder',[]) # 未完成订单
        _G(f'{i}Order',[]) # 订单结构
        _G(f'{i}MarginLevel',3) # 杠杆倍数
        _G(f'{i}futures',False) # 设置合约类型
        _G(f'{i}SideDirection',"null") # 下单方向
        _G(f'{i}Account',{"Balance":10000,"FrozenBalance":0,"Stocks":0,"FrozenStocks":0})
        _G(f'{i}position',[]) # 仓位信息
        _G(f'{i}Balance',10000) # 计价币余额
        _G(f'{i}feeCcy',0.0003) # 手续费
        _G(f'{i}Spread',0.005) # 点差

def main():
    if Sign == True:
        IFsign()
    SimSign()
    #######示例#######
    exchange[0].SetContractType("swap") # 设置合约类型
    exchange[0].SetMarginLevel(10) # 设置杠杆倍数
    # 下多单
    exchange[0].SetDirection("buy")
    exchange[0].Buy(-1, 0.01)
    # 平多单
    exchange[0].SetDirection("closebuy")
    exchange[0].Sell(-1, 0.01)
    while True:
        SimGo()

More