def get_assets(self, acc_id): if self.market_name == "huobi": # base_cur, quote_cur = cur_market_name.split("_") bitex_acc = exchangeConnection.huobi.huobiService913.get_balance() a = ['usdt', 'btc', 'eth', 'eos'] a_balanc = [0] * 9 a_balanc[0] = acc_id # self.get_accountInfo() a_balanc[1] = uh.current_date_str() for i in range(len(a)): now_list = uh.find_currency( bitex_acc.get("data").get("list"), a[i]) a_balanc[i + 2] = uh.downRound( float(now_list[0].get("balance")) + float(now_list[1].get("balance")), 8) # a_balanc[i+2]=float(now_list[0].get("balance"))+float(now_list[1].get("balance")) print(a_balanc[i + 2]) # time.sleep(2) return (a_balanc) # print(bitex_acc) # return uh.downRound(float(now_list[0].get("balance")+now_list[1].get("balance")),8) #取可交易的余额 else: return None
def buy(self, security, cash_amount): # cash_amount is a string value self.timeLog("开始下达火币市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.huobi_min_cash_amount: self.timeLog("金额:%s 小于交易所最小交易金额(火币最小金额:%.2f元),因此无法下单,此处忽略该信号" % (cash_amount, self.huobi_min_cash_amount), level=logging.WARN) return None coin_type = helper.coinTypeStructure[ self.coinMarketType]["huobi"]["coin_type"] res = self.huobiService.buyMarket( coin_type, cash_amount, None, None, helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], BUY_MARKET) if helper.componentExtract(res, u"result", "") != u'success': self.timeLog( "下达火币市价买单(金额:%s)失败, 结果是:%s!" % (cash_amount, helper.componentExtract(res, u"result", "")), level=logging.ERROR) return None order_id = res[u"id"] # 查询订单执行情况 order_info = self.huobiService.getOrderInfo( coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], ORDER_INFO) self.timeLog("下达如下火币市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info[ "status"] != 2: self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.huobiService.getOrderInfo( coin_type, order_id, helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market"], ORDER_INFO) self.timeLog(str(order_info)) retry_time += 1 if float(order_info["processed_price"]) > 0: executed_qty = float(order_info["processed_amount"]) / float( order_info["processed_price"]) self.timeLog("火币市价买单已被执行,执行数量:%f,花费的现金:%.2f" % (executed_qty, float(order_info["processed_amount"]))) # self.dataLog() return executed_qty else: self.timeLog("火币市价买单未被执行", level=logging.WARN) return 0
def sell(self, security, quantity): # quantity is a string value self.timeLog("开始下达火币市价卖单...") self.timeLog("只保留下单数量的小数点后4位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 4) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.huobi_min_quantity: self.timeLog("数量:%s 小于交易所最小交易数量(火币最小数量:%f),因此无法下单,此处忽略该信号" % (quantity, self.huobi_min_quantity), level=logging.WARN) return None coin_type = helper.coinTypeStructure[ self.coinMarketType]["huobi"]["coin_type"] res = self.huobiService.sellMarket( coin_type, quantity, None, None, helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], SELL_MARKET) if helper.componentExtract(res, u"result", "") != u'success': self.timeLog( "下达火币市价卖单(数量:%s)失败, 结果是: %s!" % (quantity, helper.componentExtract(res, u"result", "")), level=logging.ERROR) return None order_id = res[u"id"] # 查询订单执行情况 order_info = self.huobiService.getOrderInfo( coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], ORDER_INFO) self.timeLog("下达如下火币市价卖单,数量:%s" % quantity) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info[ "status"] != 2: self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.huobiService.getOrderInfo( coin_type, order_id, helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market"], ORDER_INFO) self.timeLog(str(order_info)) retry_time += 1 executed_qty = float(order_info["processed_amount"]) self.timeLog("火币市价卖单已被执行,执行数量:%f,收到的现金:%.2f" % (executed_qty, executed_qty * float(order_info["processed_price"]))) # self.dataLog() return executed_qty
def buy(self, security, cash_amount): # cash_amount is a string value self.timeLog("开始下达火币市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.huobi_min_cash_amount: self.timeLog("金额:%s 小于交易所最小交易金额(火币最小金额:%.2f元),因此无法下单,此处忽略该信号" % (cash_amount, self.huobi_min_cash_amount), level=logging.WARN) return None coin_type = helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"] res = self.huobiService.buyMarket(coin_type, cash_amount, None, None, helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], BUY_MARKET) if helper.componentExtract(res, u"result", "") != u'success': self.timeLog("下达火币市价买单(金额:%s)失败, 结果是:%s!" % (cash_amount, helper.componentExtract(res, u"result", "")), level=logging.ERROR) return None order_id = res[u"id"] # 查询订单执行情况 order_info = self.huobiService.getOrderInfo(coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market"], ORDER_INFO) self.timeLog("下达如下火币市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info["status"] != 2: self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.huobiService.getOrderInfo(coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market"], ORDER_INFO) self.timeLog(str(order_info)) retry_time += 1 if float(order_info["processed_price"]) > 0: executed_qty = float(order_info["processed_amount"]) / float(order_info["processed_price"]) self.timeLog("火币市价买单已被执行,执行数量:%f,花费的现金:%.2f" % (executed_qty, float(order_info["processed_amount"]))) # self.dataLog() return executed_qty else: self.timeLog("火币市价买单未被执行", level=logging.WARN) return 0
def account_frozen(self, cur_name, cur_market_name=None): """ 获取某个currency的可用量 :param cur_name: :param cur_market_name: :return: """ if self.market_name == "huobi": # base_cur, quote_cur = cur_market_name.split("_") bitex_acc = exchangeConnection.huobi.huobiService913.get_balance() # print(bitex_acc) now_list = uh.find_currency( bitex_acc.get("data").get("list"), cur_name) return uh.downRound(float(now_list[1].get("balance")), 8) #取冻结的余额 else: return None
def sell(self, security, quantity): # quantity is a string value self.timeLog("开始下达火币市价卖单...") self.timeLog("只保留下单数量的小数点后4位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 4) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.huobi_min_quantity: self.timeLog( "数量:%s 小于交易所最小交易数量(火币最小数量:%f),因此无法下单,此处忽略该信号" % (quantity, self.huobi_min_quantity), level=logging.WARN) return None coin_type = helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"] res = self.huobiService.sellMarket(coin_type, quantity, None, None, helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], SELL_MARKET) if helper.componentExtract(res, u"result", "") != u'success': self.timeLog("下达火币市价卖单(数量:%s)失败, 结果是: %s!" % (quantity, helper.componentExtract(res, u"result", "")), level=logging.ERROR) return None order_id = res[u"id"] # 查询订单执行情况 order_info = self.huobiService.getOrderInfo(coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market"], ORDER_INFO) self.timeLog("下达如下火币市价卖单,数量:%s" % quantity) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info["status"] != 2: self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.huobiService.getOrderInfo(coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market"], ORDER_INFO) self.timeLog(str(order_info)) retry_time += 1 executed_qty = float(order_info["processed_amount"]) self.timeLog( "火币市价卖单已被执行,执行数量:%f,收到的现金:%.2f" % (executed_qty, executed_qty * float(order_info["processed_price"]))) # self.dataLog() return executed_qty
def buy(self, security, cash_amount, exchange="huobi", sell_1_price=None): if exchange == "huobi": self.timeLog("开始下达火币市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.huobi_min_cash_amount: self.timeLog("金额:%s 小于交易所最小交易金额(火币最小金额:1元),因此无法下单,此处忽略该信号" % ( cash_amount, self.huobi_min_cash_amount)) return None coin_type = helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"] res = self.huobiService.buyMarket(coin_type, cash_amount, None, None, helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], BUY_MARKET) if u"result" not in res or res[u"result"] != u'success': self.timeLog("下达火币市价买单(金额:%s)失败!" % cash_amount) return None order_id = res[u"id"] # 查询订单执行情况 order_info = self.huobiService.getOrderInfo(coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market"], ORDER_INFO) self.timeLog("下达如下火币市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) if order_info["status"] != 2: self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.huobiService.getOrderInfo(coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market"], ORDER_INFO) self.timeLog(str(order_info)) executed_qty = float( order_info["processed_amount"]) / float(order_info["processed_price"]) self.timeLog("火币市价买单已被执行,执行数量:%f,花费的现金:%.2f" % (executed_qty, float(order_info["processed_amount"]))) self.dataLog() return executed_qty elif exchange == "okcoin": if sell_1_price is None: raise ValueError( "处理okcoin市价买单之前,需要提供当前Okcoin卖一的价格信息,请检查传入的sell_1_price参数是否完备!") self.timeLog("开始下达okcoin市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.okcoin_min_quantity * sell_1_price: self.timeLog( "金额:%s 不足以购买交易所最小交易数量(okcoin最小数量:%f,当前卖一价格%.2f,最小金额要求:%.2f),因此无法下单,此处忽略该信号" % ( cash_amount, self.okcoin_min_quantity, sell_1_price, self.okcoin_min_quantity * sell_1_price)) return None res = self.okcoinService.trade(helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"], "buy_market", price=cash_amount) if "result" not in res or res["result"] != True: self.timeLog("下达okcoin市价买单(金额:%s)失败" % cash_amount) return None order_id = res["order_id"] # 查询订单执行情况 order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"], str(order_id)) self.timeLog("下达如下okcoin市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) if order_info["orders"][0]["status"] != 2: self.timeLog("等待%.1f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"], str(order_id)) self.timeLog(str(order_info)) executed_qty = order_info["orders"][0]["deal_amount"] self.timeLog("okcoin市价买单已被执行,执行数量:%f,花费的现金:%.2f" % ( executed_qty, executed_qty * order_info["orders"][0]["avg_price"])) self.dataLog() return executed_qty
def sell(self, security, quantity, exchange="huobi"): # quantity is a string value if exchange == "huobi": self.timeLog("开始下达火币市价卖单...") self.timeLog("只保留下单数量的小数点后4位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 4) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.huobi_min_quantity: self.timeLog( "数量:%s 小于交易所最小交易数量(火币最小数量:%f),因此无法下单,此处忽略该信号" % (quantity, self.huobi_min_quantity)) return None coin_type = helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"] res = self.huobiService.sellMarket(coin_type, quantity, None, None, helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], SELL_MARKET) if u"result" not in res or res[u"result"] != u'success': self.timeLog("下达火币市价卖单(数量:%s)失败!" % quantity) return None order_id = res[u"id"] # 查询订单执行情况 order_info = self.huobiService.getOrderInfo(coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market"], ORDER_INFO) self.timeLog("下达如下火币市价卖单,数量:%s" % quantity) self.timeLog(str(order_info)) if order_info["status"] != 2: self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.huobiService.getOrderInfo(coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market"], ORDER_INFO) self.timeLog(str(order_info)) executed_qty = float(order_info["processed_amount"]) self.timeLog( "火币市价卖单已被执行,执行数量:%f,收到的现金:%.2f" % (executed_qty, executed_qty * float(order_info["processed_price"]))) self.dataLog() return executed_qty elif exchange == "okcoin": self.timeLog("开始下达okcoin市价卖单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 2) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.okcoin_min_quantity: self.timeLog( "数量:%s 小于交易所最小交易数量(火币最小数量:%f),因此无法下单,此处忽略该信号" % (quantity, self.okcoin_min_quantity)) return None res = self.okcoinService.trade(helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"], "sell_market", amount=quantity) if "result" not in res or res["result"] != True: self.timeLog("下达okcoin市价卖单(数量:%s)失败" % quantity) return None order_id = res["order_id"] # 查询订单执行情况 order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"], str(order_id)) self.timeLog("下达如下okcoin市价卖单,数量:%s" % quantity) self.timeLog(str(order_info)) if order_info["orders"][0]["status"] != 2: self.timeLog("等待%.1f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"], str(order_id)) self.timeLog(str(order_info)) executed_qty = order_info["orders"][0]["deal_amount"] self.timeLog("okcoin市价卖单已被执行,执行数量:%f,收到的现金:%.2f" % ( executed_qty, executed_qty * order_info["orders"][0]["avg_price"])) self.dataLog() return executed_qty
def buy_limit(self, security, price, quantity): # TODO: implement the buy limit function self.buy(security, str(helper.downRound(float(price) * float(quantity), 2)))
def buy(self, security, cash_amount, exchange="huobi", sell_1_price=None): # cash_amount is a string value if exchange == "huobi": self.timeLog("start huobi buy order...") self.timeLog("keep quantity 2 number of decimals...") self.timeLog("orient cash:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("cash:%s" % cash_amount) if float(cash_amount) < self.huobi_min_cash_amount: self.timeLog( "cash:%s too samll to trade(huobi min:1Yuan),ignore the signal" % (cash_amount, self.huobi_min_cash_amount)) return None coin_type = helper.coinTypeStructure[ self.coinMarketType]["huobi"]["coin_type"] res = self.huobiService.buyMarket( coin_type, cash_amount, None, None, helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market"], BUY_MARKET) if u"result" not in res or res[u"result"] != u'success': self.timeLog("huobi buy order failed(cash:%s)failed!" % cash_amount) return None order_id = res[u"id"] # query order order_info = self.huobiService.getOrderInfo( coin_type, order_id, helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market"], ORDER_INFO) self.timeLog("huobi buy order, cash:%s" % cash_amount) self.timeLog(str(order_info)) if order_info["status"] != 2: self.timeLog("waiting%fs until order finished" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.huobiService.getOrderInfo( coin_type, order_id, helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market"], ORDER_INFO) self.timeLog(str(order_info)) executed_qty = float(order_info["processed_amount"]) / float( order_info["processed_price"]) self.timeLog("huobi buy order excuted, quantity:%f,cash:%.2f" % (executed_qty, float(order_info["processed_amount"]))) self.dataLog() return executed_qty elif exchange == "okcoin": if sell_1_price is None: raise ValueError("need okcoin sell1, pls check sell_1_price!") self.timeLog("start okcoin buy order...") self.timeLog("keep quantity 2 number of decimals...") self.timeLog("orient cash:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("cash:%s" % cash_amount) if float(cash_amount) < self.okcoin_min_quantity * sell_1_price: self.timeLog( "cash:%s too small to trade(okcoin min:%f,sell1:%.2f,mincash:%.2f),ignore the signal" % (cash_amount, self.okcoin_min_quantity, sell_1_price, self.okcoin_min_quantity * sell_1_price)) return None res = self.okcoinService.trade(helper.coinTypeStructure[ self.coinMarketType]["okcoin"]["coin_type"], "buy_market", price=cash_amount) if "result" not in res or res["result"] != True: self.timeLog("okcoin buy order(cash:%s)failed" % cash_amount) return None order_id = res["order_id"] # query order order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"] ["coin_type"], str(order_id)) self.timeLog("okcoin buy order cash:%s" % cash_amount) self.timeLog(str(order_info)) if order_info["orders"][0]["status"] != 2: self.timeLog("wait%.1fs until order finished" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"] ["coin_type"], str(order_id)) self.timeLog(str(order_info)) executed_qty = order_info["orders"][0]["deal_amount"] self.timeLog("okcoin buy order excuted quantity:%f,cash:%.2f" % (executed_qty, executed_qty * order_info["orders"][0]["avg_price"])) self.dataLog() return executed_qty
def go(self): self.timeLog("日志启动于 %s" % self.getStartRunningTime().strftime(self.TimeFormatForLog)) self.dataLog( content="time|huobi_cny_cash|huobi_cny_btc|huobi_cny_ltc|huobi_cny_cash_loan|huobi_cny_btc_loan|huobi_cny_ltc_loan|huobi_cny_cash_frozen|huobi_cny_btc_frozen|huobi_cny_ltc_frozen|huobi_cny_total|huobi_cny_net|okcoin_cny_cash|okcoin_cny_btc|okcoin_cny_ltc|okcoin_cny_cash_frozen|okcoin_cny_btc_frozen|okcoin_cny_ltc_frozen|okcoin_cny_total|okcoin_cny_net|total_net") self.dataLog() while True: if self.timeInterval > 0: self.timeLog("等待 %d 秒进入下一个循环..." % self.timeInterval) time.sleep(self.timeInterval) self.timeLog("记录心跳信息...") # calculate the net asset at a fixed time window time_diff = datetime.datetime.now() - self.last_data_log_time if time_diff.seconds > self.dataLogFixedTimeWindow: self.dataLog() # 查询huobi第一档深度数据 huobiDepth = self.HuobiService.getDepth(helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"], helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], depth_size=1) # 查询okcoin第一档深度数据 okcoinDepth = self.OKCoinService.depth( helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"]) huobi_sell_1_price = huobiDepth["asks"][0][0] huobi_sell_1_qty = huobiDepth["asks"][0][1] huobi_buy_1_price = huobiDepth["bids"][0][0] huobi_buy_1_qty = huobiDepth["bids"][0][1] okcoin_sell_1_price = okcoinDepth["asks"][0][0] okcoin_sell_1_qty = okcoinDepth["asks"][0][1] okcoin_buy_1_price = okcoinDepth["bids"][0][0] okcoin_buy_1_qty = okcoinDepth["bids"][0][1] spread1 = huobi_buy_1_price - okcoin_sell_1_price spread2 = okcoin_buy_1_price - huobi_sell_1_price self.spread1List = self.add_to_list( self.spread1List, spread1, self.sma_window_size) self.spread2List = self.add_to_list( self.spread2List, spread2, self.sma_window_size) max_price = np.max( [huobi_sell_1_price, huobi_buy_1_price, okcoin_sell_1_price, okcoin_buy_1_price]) if len(self.spread1List) < self.sma_window_size: self.timeLog("正在获取计算SMA所需的最小数据量(%d/%d)..." % (len(self.spread1List), self.sma_window_size)) continue # 获取当前账户信息 accountInfo = self.getAccuntInfo() # check whether current time is after the dailyExitTime, if yes, exit if self.dailyExitTime is not None and datetime.datetime.now() > datetime.datetime.strptime( datetime.date.today().strftime("%Y-%m-%d") + " " + self.dailyExitTime, "%Y-%m-%d %H:%M:%S"): self.timeLog("抵达每日终结时间:%s, 现在退出." % self.dailyExitTime) if self.auto_rebalance_on_exit: self.rebalance_position(accountInfo, max_price) break current_position_proportion = self.get_current_position_proportion( accountInfo, max_price) self.calc_sma_and_deviation() if self.auto_rebalance_on and current_position_proportion > self.position_proportion_threshold: if abs(self.spread2List[ -1] - self.spread2_mean) / self.spread2_stdev < self.spread2_close_condition_stdev_coe or abs( self.spread1List[ -1] - self.spread1_mean) / self.spread1_stdev < self.spread1_close_condition_stdev_coe: self.rebalance_position(accountInfo, max_price) continue in_or_out = self.in_or_out() if in_or_out == 0: self.timeLog("没有发现交易信号,进入下一个轮询...") continue elif in_or_out == 1: if self.current_position_direction == 0: # 当前没有持仓 self.timeLog("发现开仓信号(火币卖,OKcoin买)") elif self.current_position_direction == 1: # 当前long spread1 self.timeLog("发现增仓信号(火币卖,OKcoin买)") elif self.current_position_direction == 2: # 当前long spread2 self.timeLog("发现减仓信号(火币卖,OKcoin买)") self.timeLog("火币深度:%s" % str(huobiDepth)) self.timeLog("okcoin深度:%s" % str(okcoinDepth)) if self.current_position_direction == 0 or self.current_position_direction == 1: if current_position_proportion > self.position_proportion_alert_threshold: self.timeLog( "当前仓位比例:%f 大于仓位预警比例:%f" % ( current_position_proportion, self.position_proportion_alert_threshold), level=logging.WARN) # 每次只能吃掉一定ratio的深度 Qty = helper.downRound( min(huobi_buy_1_qty, okcoin_sell_1_qty) * self.orderRatio, 4) elif self.current_position_direction == 2: depthQty = helper.downRound( min(huobi_buy_1_qty, okcoin_sell_1_qty) * self.orderRatio, 4) Qty = min(depthQty, helper.downRound( self.spread2_pos_qty, 4)) # 每次搬砖最多只搬maximum_qty_multiplier个最小单位 if self.maximum_qty_multiplier is not None: Qty = min(Qty, max(self.huobi_min_quantity, self.okcoin_min_quantity) * self.maximum_qty_multiplier) # 每次搬砖前要检查是否有足够security和cash Qty = min(Qty, accountInfo[helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_str"]], helper.downRound(accountInfo[helper.coinTypeStructure[self.coinMarketType]["okcoin"][ "market_str"]] / okcoin_sell_1_price, 4)) Qty = helper.downRound(Qty, 4) Qty = helper.getRoundedQuantity(Qty, self.coinMarketType) if Qty < self.huobi_min_quantity or Qty < self.okcoin_min_quantity: self.timeLog( "数量:%f 小于交易所最小交易数量(火币最小数量:%f, okcoin最小数量:%f),因此无法下单并忽略该信号" % ( Qty, self.huobi_min_quantity, self.okcoin_min_quantity), level=logging.WARN) continue else: # step1: 先处理卖 executed_qty = self.sell_market( self.coinMarketType, str(Qty), exchange="huobi") if executed_qty is not None: # step2: 再执行买 Qty2 = min(executed_qty, Qty) Qty2 = max(helper.getRoundedQuantity( Qty2, self.coinMarketType), self.okcoin_min_quantity) if Qty2 < self.okcoin_min_quantity * 1.05: self.buy_market(self.coinMarketType, str(Qty2 * okcoin_sell_1_price * 1.05), exchange="okcoin", sell_1_price=okcoin_sell_1_price) else: self.buy_market(self.coinMarketType, str(Qty2 * okcoin_sell_1_price), exchange="okcoin", sell_1_price=okcoin_sell_1_price) if self.current_position_direction == 0 or self.current_position_direction == 1: self.spread1_pos_qty += Qty2 elif self.current_position_direction == 2: self.spread2_pos_qty -= Qty2 elif in_or_out == 2: if self.current_position_direction == 0: # 当前没有持仓 self.timeLog("发现开仓信号(OKcoin卖, 火币买)") elif self.current_position_direction == 2: # 当前long spread2 self.timeLog("发现增仓信号(OKcoin卖, 火币买)") elif self.current_position_direction == 1: # 当前long spread1 self.timeLog("发现减仓信号(OKcoin卖, 火币买)") self.timeLog("火币深度:%s" % str(huobiDepth)) self.timeLog("okcoin深度:%s" % str(okcoinDepth)) if self.current_position_direction == 0 or self.current_position_direction == 2: if current_position_proportion > self.position_proportion_alert_threshold: self.timeLog( "当前仓位比例:%f 大于仓位预警比例:%f" % ( current_position_proportion, self.position_proportion_alert_threshold), level=logging.WARN) # 每次只能吃掉一定ratio的深度 Qty = helper.downRound( min(huobi_sell_1_qty, okcoin_buy_1_qty) * self.orderRatio, 4) elif self.current_position_direction == 1: depthQty = helper.downRound( min(huobi_sell_1_qty, okcoin_buy_1_qty) * self.orderRatio, 4) Qty = min(depthQty, helper.downRound( self.spread1_pos_qty, 4)) # 每次搬砖最多只搬maximum_qty_multiplier个最小单位 if self.maximum_qty_multiplier is not None: Qty = min(Qty, max(self.huobi_min_quantity, self.okcoin_min_quantity) * self.maximum_qty_multiplier) # 每次搬砖前要检查是否有足够security和cash Qty = min(Qty, accountInfo[helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_str"]], helper.downRound(accountInfo[helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market_str"]] / huobi_sell_1_price), 4) Qty = helper.getRoundedQuantity(Qty, self.coinMarketType) if Qty < self.huobi_min_quantity or Qty < self.okcoin_min_quantity: self.timeLog("数量:%f 小于交易所最小交易数量(火币最小数量:%f, okcoin最小数量:%f),因此无法下单并忽略该信号" % ( Qty, self.huobi_min_quantity, self.okcoin_min_quantity), level=logging.WARN) continue else: # step1: 先处理卖 executed_qty = self.sell_market( self.coinMarketType, str(Qty), exchange="okcoin") if executed_qty is not None: # step2: 再执行买 Qty2 = min(executed_qty, Qty) self.buy_market(self.coinMarketType, str( Qty2 * huobi_sell_1_price), exchange="huobi") if self.current_position_direction == 0 or self.current_position_direction == 2: self.spread2_pos_qty += Qty2 elif self.current_position_direction == 1: self.spread1_pos_qty -= Qty2 if self.spread1_pos_qty > self.spread_pos_qty_minimum_size: self.current_position_direction = 1 elif self.spread2_pos_qty > self.spread_pos_qty_minimum_size: self.current_position_direction = 2 else: self.current_position_direction = 0
def buy_limit(self, security, price, quantity, exchange="huobi"): if exchange == "huobi": self.timeLog("开始下达火币限价买单...") self.timeLog("只保留下单数量的小数点后4位,下单价格的小数点后2位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 4) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.huobi_min_quantity: self.timeLog( "数量:%s 小于交易所最小交易数量(火币最小数量:%f),因此无法下单,此处忽略该信号" % ( quantity, self.huobi_min_quantity), level=logging.WARN) return None self.timeLog("原始下单价格:%s" % price) tmp = float(price) tmp = helper.downRound(tmp, 2) price = str(tmp) self.timeLog("做完小数点处理后的下单价格:%s" % price) symbol = helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"] # market = helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"] res = self.HuobiService.sendOrder(quantity,None,"api",symbol,HB_BUY) if helper.componentExtract(res, u"result", "") != u'success': self.timeLog( "下达火币限价买单(数量:%s,价格:%s)失败, 结果是:%s!" % ( quantity, price, helper.componentExtract(res, u"result", "")), level=logging.ERROR) return None order_id = res[u"data"] # 查询订单执行情况 order_info = self.HuobiService.getOrderInfo(order_id) self.timeLog("下达如下火币限价买单,数量:%s, 价格:%s" % (quantity, price)) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info["state"] != "filled": self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.HuobiService.getOrderInfo(order_id) self.timeLog(str(order_info)) retry_time += 1 # if order is not fully filled, cancel order if after timeout, cancel order is synchronized if order_info["state"] != 2: cancel_result = self.HuobiService.cancelOrder(order_id) retry_time = 0 while retry_time < self.huobi_order_cancel_query_retry_maximum_times and helper.componentExtract( cancel_result, u"result", "") != u'success': self.timeLog("等待%f秒直至订单取消完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) cancel_result = self.HuobiService.cancelOrder(order_id) retry_time += 1 order_info = self.HuobiService.getOrderInfo(order_id) if float(order_info["field-cash-amount"]) > 0: executed_qty = float(order_info["field-amount"]) self.timeLog("火币限价买单已被执行,执行数量:%f,花费的现金:%.2f" % ( executed_qty, float(order_info["processed_price"]) * executed_qty)) return executed_qty else: self.timeLog("火币限价买单未被执行", level=logging.WARN) return None elif exchange == "okcoin": self.timeLog("开始下达okcoin限价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 2) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.okcoin_min_quantity: self.timeLog( "数量:%s 小于交易所最小交易数量(okcoin最小数量:%f),因此无法下单,此处忽略该信号" % ( quantity, self.okcoin_min_quantity), level=logging.WARN) return None self.timeLog("原始下单价格:%s" % price) tmp = float(price) tmp = helper.downRound(tmp, 2) price = str(tmp) self.timeLog("做完小数点处理后的下单价格:%s" % price) symbol = helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"] res = self.OKCoinService.trade(symbol, OKC_BUY, price=price, amount=quantity) if helper.componentExtract(res, "result") != True: self.timeLog( "下达okcoin限价买单(数量:%s,价格:%s)失败, 结果是:%s!" % ( quantity, price, helper.componentExtract(res, "result")), level=logging.ERROR) return None order_id = res["order_id"] # 查询订单执行情况 order_info = self.OKCoinService.getOrderInfo(symbol, str(order_id)) self.timeLog("下达如下okcoin限价买单,数量:%s,价格:%s" % (quantity, price)) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.okcoin_order_query_retry_maximum_times and order_info["orders"][0]["status"] != 2: self.timeLog("等待%.1f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.OKCoinService.getOrderInfo(symbol, str(order_id)) self.timeLog(str(order_info)) retry_time += 1 if order_info["orders"][0]["status"] != 2: cancel_result = self.OKCoinService.cancelOrder(symbol, str(order_id)) retry_time = 0 while retry_time < self.okcoin_order_cancel_query_retry_maximum_times and helper.componentExtract( cancel_result, u"result", "") != True: self.timeLog("等待%f秒直至订单取消完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) cancel_result = self.OKCoinService.cancelOrder(symbol, str(order_id)) retry_time += 1 order_info = self.OKCoinService.getOrderInfo(symbol, str(order_id)) executed_qty = order_info["orders"][0]["deal_amount"] self.timeLog("okcoin限价买单已被执行,执行数量:%f,花费的现金:%.2f" % ( executed_qty, executed_qty * order_info["orders"][0]["avg_price"])) return executed_qty
def go(self): self.timeLog( "日志启动于 %s" % self.getStartRunningTime().strftime(self.TimeFormatForLog)) self.dataLog( content= "time|huobi_cny_cash|huobi_cny_btc|huobi_cny_ltc|huobi_cny_cash_loan|huobi_cny_btc_loan|huobi_cny_ltc_loan|huobi_cny_cash_frozen|huobi_cny_btc_frozen|huobi_cny_ltc_frozen|huobi_cny_total|huobi_cny_net|okcoin_cny_cash|okcoin_cny_btc|okcoin_cny_ltc|okcoin_cny_cash_frozen|okcoin_cny_btc_frozen|okcoin_cny_ltc_frozen|okcoin_cny_total|okcoin_cny_net|total_net" ) self.dataLog() while (True): # check whether current time is after the dailyExitTime, if yes, exit if self.dailyExitTime is not None and datetime.datetime.now( ) > datetime.datetime.strptime( datetime.date.today().strftime("%Y-%m-%d") + " " + self.dailyExitTime, "%Y-%m-%d %H:%M:%S"): self.timeLog("抵达每日终结时间:%s, 现在退出." % self.dailyExitTime) break self.timeLog("等待 %d 秒进入下一个循环..." % self.timeInterval) time.sleep(self.timeInterval) # calculate the net asset at a fixed time window time_diff = datetime.datetime.now() - self.last_data_log_time if time_diff.seconds > self.dataLogFixedTimeWindow: self.dataLog() # 获取当前账户信息 accountInfo = self.getAccuntInfo() # 查询huobi第一档深度数据 huobiDepth = self.huobiService.getDepth( helper.coinTypeStructure[ self.coinMarketType]["huobi"]["coin_type"], helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market"], depth_size=1) # 查询okcoin第一档深度数据 okcoinDepth = self.okcoinService.depth(helper.coinTypeStructure[ self.coinMarketType]["okcoin"]["coin_type"]) huobi_sell_1_price = huobiDepth["asks"][0][0] huobi_sell_1_qty = huobiDepth["asks"][0][1] huobi_buy_1_price = huobiDepth["bids"][0][0] huobi_buy_1_qty = huobiDepth["bids"][0][1] okcoin_sell_1_price = okcoinDepth["asks"][0][0] okcoin_sell_1_qty = okcoinDepth["asks"][0][1] okcoin_buy_1_price = okcoinDepth["bids"][0][0] okcoin_buy_1_qty = okcoinDepth["bids"][0][1] if huobi_buy_1_price > okcoin_sell_1_price: # 获利信号:OKcoin买,huobi卖 self.timeLog("发现信号") self.timeLog("火币深度:%s" % str(huobiDepth)) self.timeLog("okcoin深度:%s" % str(okcoinDepth)) # 每次只能吃掉一定ratio的深度 Qty = helper.downRound( min(huobi_buy_1_qty, okcoin_sell_1_qty) * self.orderRatio, 4) # 每次搬砖前要检查是否有足够security和cash Qty = min( Qty, accountInfo[helper.coinTypeStructure[ self.coinMarketType]["huobi"]["coin_str"]], helper.downRound( accountInfo[helper.coinTypeStructure[ self.coinMarketType]["okcoin"]["market_str"]] / okcoin_sell_1_price, 4)) Qty = helper.downRound(Qty, 4) Qty = helper.getRoundedQuantity(Qty, self.coinMarketType) if Qty < self.huobi_min_quantity or Qty < self.okcoin_min_quantity: self.timeLog( "数量:%f 小于交易所最小交易数量(火币最小数量:%f, okcoin最小数量:%f),因此无法下单并忽略该信号" % (Qty, self.huobi_min_quantity, self.okcoin_min_quantity)) continue else: # step1: 先处理卖 executed_qty = self.sell(self.coinMarketType, str(Qty), exchange="huobi") if executed_qty is not None: # step2: 再执行买 Qty2 = min(executed_qty, Qty) Qty2 = max( helper.getRoundedQuantity(Qty2, self.coinMarketType), self.okcoin_min_quantity) if Qty2 < self.okcoin_min_quantity * 1.05: self.buy(self.coinMarketType, str(Qty2 * okcoin_sell_1_price * 1.05), exchange="okcoin", sell_1_price=okcoin_sell_1_price) else: self.buy(self.coinMarketType, str(Qty2 * okcoin_sell_1_price), exchange="okcoin", sell_1_price=okcoin_sell_1_price) elif okcoin_buy_1_price > huobi_sell_1_price: # 获利信号:OKcoin卖,huobi买 self.timeLog("发现信号") self.timeLog("火币深度:%s" % str(huobiDepth)) self.timeLog("okcoin深度:%s" % str(okcoinDepth)) # 每次只能吃掉一定ratio的深度 Qty = helper.downRound( min(huobi_sell_1_qty, okcoin_buy_1_qty) * self.orderRatio, 4) # 每次搬砖前要检查是否有足够security和cash Qty = min( Qty, accountInfo[helper.coinTypeStructure[ self.coinMarketType]["okcoin"]["coin_str"]], helper.downRound(accountInfo[helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market_str"]] / huobi_sell_1_price), 4) Qty = helper.getRoundedQuantity(Qty, self.coinMarketType) if Qty < self.huobi_min_quantity or Qty < self.okcoin_min_quantity: self.timeLog( "数量:%f 小于交易所最小交易数量(火币最小数量:%f, okcoin最小数量:%f),因此无法下单并忽略该信号" % (Qty, self.huobi_min_quantity, self.okcoin_min_quantity)) continue else: # step1: 先处理卖 executed_qty = self.sell(self.coinMarketType, str(Qty), exchange="okcoin") if executed_qty is not None: # step2: 再执行买 Qty2 = min(executed_qty, Qty) self.buy(self.coinMarketType, str(Qty2 * huobi_sell_1_price), exchange="huobi")
def buy_limit(self, security, price, quantity, exchange="huobi"): if exchange == "huobi": self.timeLog("开始下达火币限价买单...") self.timeLog("只保留下单数量的小数点后4位,下单价格的小数点后2位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 4) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.huobi_min_quantity: self.timeLog( "数量:%s 小于交易所最小交易数量(火币最小数量:%f),因此无法下单,此处忽略该信号" % (quantity, self.huobi_min_quantity), level=logging.WARN) return None self.timeLog("原始下单价格:%s" % price) tmp = float(price) tmp = helper.downRound(tmp, 2) price = str(tmp) self.timeLog("做完小数点处理后的下单价格:%s" % price) coin_type = helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"] market = helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"] res = self.HuobiService.buy(coin_type, price, quantity, None, None, market, BUY) if helper.componentExtract(res, u"result", "") != u'success': self.timeLog( "下达火币限价买单(数量:%s,价格:%s)失败, 结果是:%s!" % (quantity, price, helper.componentExtract(res, u"result", "")), level=logging.ERROR) return None order_id = res[u"id"] # 查询订单执行情况 order_info = self.HuobiService.getOrderInfo(coin_type, order_id, market, ORDER_INFO) self.timeLog("下达如下火币限价买单,数量:%s, 价格:%s" % (quantity, price)) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info["status"] != 2: self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.HuobiService.getOrderInfo(coin_type, order_id, market, ORDER_INFO) self.timeLog(str(order_info)) retry_time += 1 # if order is not fully filled, cancel order if after timeout, cancel order is synchronized if order_info["status"] != 2: cancel_result = self.HuobiService.cancelOrder(coin_type, order_id, market, CANCEL_ORDER) retry_time = 0 while retry_time < self.huobi_order_cancel_query_retry_maximum_times and helper.componentExtract( cancel_result, u"result", "") != u'success': self.timeLog("等待%f秒直至订单取消完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) cancel_result = self.HuobiService.cancelOrder(coin_type, order_id, market, CANCEL_ORDER) retry_time += 1 order_info = self.HuobiService.getOrderInfo(coin_type, order_id, market, ORDER_INFO) if float(order_info["processed_price"]) > 0: executed_qty = float(order_info["processed_amount"]) self.timeLog("火币限价买单已被执行,执行数量:%f,花费的现金:%.2f" % ( executed_qty, float(order_info["processed_price"]) * executed_qty)) return executed_qty else: self.timeLog("火币限价买单未被执行", level=logging.WARN) return None elif exchange == "okcoin": self.timeLog("开始下达okcoin限价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 2) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.okcoin_min_quantity: self.timeLog( "数量:%s 小于交易所最小交易数量(okcoin最小数量:%f),因此无法下单,此处忽略该信号" % (quantity, self.okcoin_min_quantity), level=logging.WARN) return None self.timeLog("原始下单价格:%s" % price) tmp = float(price) tmp = helper.downRound(tmp, 2) price = str(tmp) self.timeLog("做完小数点处理后的下单价格:%s" % price) coin_type = helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"] res = self.OKCoinService.trade(coin_type, "buy", price=price, amount=quantity) if helper.componentExtract(res, "result") != True: self.timeLog( "下达okcoin限价买单(数量:%s,价格:%s)失败, 结果是:%s!" % (quantity, price, helper.componentExtract(res, "result")), level=logging.ERROR) return None order_id = res["order_id"] # 查询订单执行情况 order_info = self.OKCoinService.orderInfo(coin_type, str(order_id)) self.timeLog("下达如下okcoin限价买单,数量:%s,价格:%s" % (quantity, price)) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.okcoin_order_query_retry_maximum_times and order_info["orders"][0]["status"] != 2: self.timeLog("等待%.1f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.OKCoinService.orderInfo(coin_type, str(order_id)) self.timeLog(str(order_info)) retry_time += 1 if order_info["orders"][0]["status"] != 2: cancel_result = self.OKCoinService.cancelOrder(coin_type, str(order_id)) retry_time = 0 while retry_time < self.okcoin_order_cancel_query_retry_maximum_times and helper.componentExtract( cancel_result, u"result", "") != True: self.timeLog("等待%f秒直至订单取消完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) cancel_result = self.OKCoinService.cancelOrder(coin_type, str(order_id)) retry_time += 1 order_info = self.OKCoinService.orderInfo(coin_type, str(order_id)) executed_qty = order_info["orders"][0]["deal_amount"] self.timeLog("okcoin限价买单已被执行,执行数量:%f,花费的现金:%.2f" % ( executed_qty, executed_qty * order_info["orders"][0]["avg_price"])) return executed_qty
def sell(self, security, quantity, exchange="huobi"): # quantity is a string value if exchange == "huobi": self.timeLog("开始下达火币市价卖单...") self.timeLog("只保留下单数量的小数点后4位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 4) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.huobi_min_quantity: self.timeLog("数量:%s 小于交易所最小交易数量(火币最小数量:%f),因此无法下单,此处忽略该信号" % (quantity, self.huobi_min_quantity)) return None coin_type = helper.coinTypeStructure[ self.coinMarketType]["huobi"]["sell_type"] res = self.huobiService.sellMarket(coin_type, quantity) if res[u"status"] == u'error': self.timeLog("下达火币市价卖单(数量:%s)失败, 结果是: %s!" % (quantity, res[u'err-msg']), level=logging.ERROR) return None order_id = res[u"data"] # 查询订单执行情况 order_info = self.HuobiService.getOrderInfo(order_id, market) self.timeLog("下达如下火币限价卖单,数量:%s, 价格:%s" % (quantity, price)) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info[ "state"] != "filled": self.timeLog("等待 1 秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.HuobiService.getOrderInfo(order_id, market) self.timeLog(str(order_info)) retry_time += 1 # if order is not fully filled, cancel order if after timeout, cancel order is synchronized if order_info["state"] != "filled": cancel_result = self.HuobiService.cancelOrder(order_id) retry_time = 0 while retry_time < self.huobi_order_cancel_query_retry_maximum_times and helper.componentExtract( cancel_result, u"result", "") != u'success': self.timeLog("等待%f秒直至订单取消完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) cancel_result = self.HuobiService.cancelOrder(order_id) retry_time += 1 order_info = self.HuobiService.getOrderInfo(order_id, market) executed_qty = float(order_info["amount"]) self.timeLog( "火币限价卖单已被执行,执行数量:%f,收到的现金:%.2f" % (executed_qty, executed_qty * float(order_info["price"]))) return executed_qty elif exchange == "okcoin": self.timeLog("开始下达okcoin市价卖单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 2) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.okcoin_min_quantity: self.timeLog("数量:%s 小于交易所最小交易数量(火币最小数量:%f),因此无法下单,此处忽略该信号" % (quantity, self.okcoin_min_quantity)) return None res = self.okcoinService.trade(helper.coinTypeStructure[ self.coinMarketType]["okcoin"]["coin_type"], -1, amount=quantity) if res["msg"] != "success": self.timeLog("下达okcoin市价卖单(数量:%s)失败" % quantity) return None order_id = res["data"] # 查询订单执行情况 order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"] ["coin_type"], str(order_id)) self.timeLog("下达如下okcoin市价卖单,数量:%s" % quantity) self.timeLog(str(order_info)) if order_info["data"]["status"] != 2: self.timeLog("等待%.1f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"] ["coin_type"], str(order_id)) self.timeLog(str(order_info)) executed_qty = order_info["data"]["quantity"] self.timeLog( "okcoin市价卖单已被执行,执行数量:%f,收到的现金:%.2f" % (executed_qty, executed_qty * order_info["data"]["price"])) self.dataLog() return executed_qty
def buy(self, security, cash_amount, exchange="huobi", sell_1_price=None): # cash_amount is a string value if exchange == "huobi": self.timeLog("开始下达火币市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.huobi_min_cash_amount: self.timeLog("金额:%s 小于交易所最小交易金额(火币最小金额:1元),因此无法下单,此处忽略该信号" % (cash_amount, self.huobi_min_cash_amount)) return None coin_type = helper.coinTypeStructure[ self.coinMarketType]["huobi"]["coin_type"] res = self.huobiService.buyMarket(coin_type, cash_amount) if res[u"status"] == u'error': self.timeLog("下达火币市价買单(数量:%s)失败, 结果是: %s!" % (quantity, res[u'err-msg']), level=logging.ERROR) return None order_id = res[u"data"] # 查询订单执行情况 # 查询订单执行情况 order_info = self.HuobiService.getOrderInfo(order_id, market) order_info = order_info["data"][0] self.timeLog("下达如下火币限价卖单,数量:%s, 价格:%s" % (quantity, price)) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info[ "state"] != "filled": self.timeLog("等待 1 秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.HuobiService.getOrderInfo(order_id, market) self.timeLog(str(order_info)) retry_time += 1 # if order is not fully filled, cancel order if after timeout, cancel order is synchronized if order_info["status"] != "filled": cancel_result = self.HuobiService.cancelOrder(order_id) retry_time = 0 while retry_time < self.huobi_order_cancel_query_retry_maximum_times and helper.componentExtract( cancel_result, u"result", "") != u'success': self.timeLog("等待%f秒直至订单取消完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) cancel_result = self.HuobiService.cancelOrder(order_id) retry_time += 1 order_info = self.HuobiService.getOrderInfo(order_id, market) executed_qty = float(order_info["amount"]) self.timeLog("火币市价买单已被执行,执行数量:%f,花费的现金:%.2f" % (executed_qty, float(order_info["price"]))) self.dataLog() return executed_qty elif exchange == "okcoin": if sell_1_price is None: raise ValueError( "处理okcoin市价买单之前,需要提供当前Okcoin卖一的价格信息,请检查传入的sell_1_price参数是否完备!" ) self.timeLog("开始下达okcoin市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.okcoin_min_quantity * sell_1_price: self.timeLog( "金额:%s 不足以购买交易所最小交易数量(okcoin最小数量:%f,当前卖一价格%.2f,最小金额要求:%.2f),因此无法下单,此处忽略该信号" % (cash_amount, self.okcoin_min_quantity, sell_1_price, self.okcoin_min_quantity * sell_1_price)) return None res = self.okcoinService.trade(helper.coinTypeStructure[ self.coinMarketType]["okcoin"]["coin_type"], 1, price=cash_amount) if res["msg"] != "success": self.timeLog("下达okcoin市价買单(数量:%s)失败" % quantity) return None order_id = res["data"] # 查询订单执行情况 order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"] ["coin_type"], str(order_id)) self.timeLog("下达如下okcoin市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) if order_info["data"]["status"] != 2: self.timeLog("等待%.1f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"] ["coin_type"], str(order_id)) self.timeLog(str(order_info)) executed_qty = order_info["data"]["quantity"] self.timeLog( "okcoin市价买单已被执行,执行数量:%f,花费的现金:%.2f" % (executed_qty, executed_qty * order_info["data"]["price"])) self.dataLog() return executed_qty
def buy_market(self, security, cash_amount, exchange="huobi", sell_1_price=None): # cash_amount is a string value if exchange == "huobi": self.timeLog("开始下达火币市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.huobi_min_cash_amount: self.timeLog("金额:%s 小于交易所最小交易金额(火币最小金额:1元),因此无法下单,此处忽略该信号" % (cash_amount, self.huobi_min_cash_amount), level=logging.WARN) return None coin_type = helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"] market = helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"] res = self.HuobiService.buyMarket(coin_type, cash_amount, None, None, market, BUY_MARKET) if helper.componentExtract(res, u"result", "") != u'success': self.timeLog("下达火币市价买单(金额:%s)失败, 结果是:%s!" % (cash_amount, helper.componentExtract(res, u"result", "")), level=logging.ERROR) return None order_id = res[u"id"] # 查询订单执行情况 order_info = self.HuobiService.getOrderInfo(coin_type, order_id, market, ORDER_INFO) self.timeLog("下达如下火币市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info["status"] != 2: self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.HuobiService.getOrderInfo(coin_type, order_id, market, ORDER_INFO) self.timeLog(str(order_info)) retry_time += 1 if float(order_info["processed_price"]) > 0: executed_qty = float(order_info["processed_amount"]) / float(order_info["processed_price"]) self.timeLog("火币市价买单已被执行,执行数量:%f,花费的现金:%.2f" % (executed_qty, float(order_info["processed_amount"]))) return executed_qty else: self.timeLog("火币市价买单未被执行", level=logging.WARN) return 0 elif exchange == "okcoin": if sell_1_price is None: raise ValueError("处理okcoin市价买单之前,需要提供当前Okcoin卖一的价格信息,请检查传入的sell_1_price参数是否完备!") self.timeLog("开始下达okcoin市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.okcoin_min_quantity * sell_1_price: self.timeLog( "金额:%s 不足以购买交易所最小交易数量(okcoin最小数量:%f,当前卖一价格%.2f,最小金额要求:%.2f),因此无法下单,此处忽略该信号" % ( cash_amount, self.okcoin_min_quantity, sell_1_price, self.okcoin_min_quantity * sell_1_price), level=logging.WARN) return None coin_type = helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"] res = self.OKCoinService.trade(coin_type, "buy_market", price=cash_amount) if helper.componentExtract(res, "result") != True: self.timeLog("下达okcoin市价买单(金额:%s)失败, 结果是:%s!" % (cash_amount, helper.componentExtract(res, "result")), level=logging.ERROR) return None order_id = res["order_id"] # 查询订单执行情况 order_info = self.OKCoinService.orderInfo(coin_type, str(order_id)) self.timeLog("下达如下okcoin市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.okcoin_order_query_retry_maximum_times and order_info["orders"][0]["status"] != 2: self.timeLog("等待%.1f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.OKCoinService.orderInfo(coin_type, str(order_id)) self.timeLog(str(order_info)) retry_time += 1 executed_qty = order_info["orders"][0]["deal_amount"] self.timeLog("okcoin市价买单已被执行,执行数量:%f,花费的现金:%.2f" % ( executed_qty, executed_qty * order_info["orders"][0]["avg_price"])) return executed_qty
def sell_market(self, security, quantity, exchange="huobi"): # quantity is a string value if exchange == "huobi": self.timeLog("开始下达火币市价卖单...") self.timeLog("只保留下单数量的小数点后4位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 4) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.huobi_min_quantity: self.timeLog( "数量:%s 小于交易所最小交易数量(火币最小数量:%f),因此无法下单,此处忽略该信号" % ( quantity, self.huobi_min_quantity), level=logging.WARN) return None symbol = helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"] # market = helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"] res = self.HuobiService.sendOrder(quantity,None,"api",symbol,HB_SELL_MARKET) # res = self.HuobiService.sellMarket( # coin_type, quantity, None, None, market, SELL_MARKET) if helper.componentExtract(res, u"result", "") != u'success': self.timeLog("下达火币市价卖单(数量:%s)失败, 结果是: %s!" % (quantity, helper.componentExtract(res, u"result", "")), level=logging.ERROR) return None order_id = res[u"data"] # 查询订单执行情况 order_info = self.HuobiService.getOrderInfo(order_id) self.timeLog("下达如下火币市价卖单,数量:%s" % quantity) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info["state"] != "filled": self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.HuobiService.getOrderInfo(order_id) self.timeLog(str(order_info)) retry_time += 1 executed_qty = float(order_info["field-amount"]) self.timeLog( "火币市价卖单已被执行,执行数量:%f,收到的现金:%.2f" % (executed_qty, executed_qty * float(order_info["field-cash-amount"]))) return executed_qty elif exchange == "okcoin": self.timeLog("开始下达okcoin市价卖单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单数量:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 2) quantity = str(tmp) self.timeLog("做完小数点处理后的下单数量:%s" % quantity) if float(quantity) < self.okcoin_min_quantity: self.timeLog( "数量:%s 小于交易所最小交易数量(火币最小数量:%f),因此无法下单,此处忽略该信号" % ( quantity, self.okcoin_min_quantity), level=logging.WARN) return None symbol = helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"] res = self.OKCoinService.trade(symbol, OKC_SELL_MARKET, amount=quantity) if helper.componentExtract(res, "result") != True: self.timeLog("下达okcoin市价卖单(数量:%s)失败, 结果是:%s" % (quantity, helper.componentExtract(res, "result")), level=logging.ERROR) return None order_id = res["order_id"] # 查询订单执行情况 order_info = self.OKCoinService.getOrderInfo(symbol, str(order_id)) self.timeLog("下达如下okcoin市价卖单,数量:%s" % quantity) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.okcoin_order_query_retry_maximum_times and order_info["orders"][0]["status"] != 2: self.timeLog("等待%.1f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.OKCoinService.getOrderInfo(symbol, str(order_id)) self.timeLog(str(order_info)) retry_time += 1 executed_qty = order_info["orders"][0]["deal_amount"] self.timeLog("okcoin市价卖单已被执行,执行数量:%f,收到的现金:%.2f" % ( executed_qty, executed_qty * order_info["orders"][0]["avg_price"])) return executed_qty
def go(self): self.timeLog("日志启动于 %s" % self.getStartRunningTime().strftime(self.TimeFormatForLog)) self.dataLog( content="time|huobi_cny_cash|huobi_cny_btc|huobi_cny_ltc|huobi_cny_cash_loan|huobi_cny_btc_loan|huobi_cny_ltc_loan|huobi_cny_cash_frozen|huobi_cny_btc_frozen|huobi_cny_ltc_frozen|huobi_cny_total|huobi_cny_net|okcoin_cny_cash|okcoin_cny_btc|okcoin_cny_ltc|okcoin_cny_cash_frozen|okcoin_cny_btc_frozen|okcoin_cny_ltc_frozen|okcoin_cny_total|okcoin_cny_net|total_net") self.dataLog() while True: if self.timeInterval > 0: self.timeLog("等待 %d 秒进入下一个循环..." % self.timeInterval) time.sleep(self.timeInterval) self.timeLog("记录心跳信息...") # calculate the net asset at a fixed time window time_diff = datetime.datetime.now() - self.last_data_log_time if time_diff.seconds > self.dataLogFixedTimeWindow: self.dataLog() # 查询huobi第一档深度数据 huobiDepth = self.HuobiService.getDepth(helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"], helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], depth_size=1) # 查询okcoin第一档深度数据 okcoinDepth = self.OKCoinService.depth(helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"]) huobi_sell_1_price = huobiDepth["asks"][0][0] huobi_sell_1_qty = huobiDepth["asks"][0][1] huobi_buy_1_price = huobiDepth["bids"][0][0] huobi_buy_1_qty = huobiDepth["bids"][0][1] okcoin_sell_1_price = okcoinDepth["asks"][0][0] okcoin_sell_1_qty = okcoinDepth["asks"][0][1] okcoin_buy_1_price = okcoinDepth["bids"][0][0] okcoin_buy_1_qty = okcoinDepth["bids"][0][1] spread1 = huobi_buy_1_price - okcoin_sell_1_price spread2 = okcoin_buy_1_price - huobi_sell_1_price self.spread1List = self.add_to_list(self.spread1List, spread1, self.sma_window_size) self.spread2List = self.add_to_list(self.spread2List, spread2, self.sma_window_size) max_price = np.max([huobi_sell_1_price, huobi_buy_1_price, okcoin_sell_1_price, okcoin_buy_1_price]) if len(self.spread1List) < self.sma_window_size: self.timeLog("正在获取计算SMA所需的最小数据量(%d/%d)..." % (len(self.spread1List), self.sma_window_size)) continue # 获取当前账户信息 accountInfo = self.getAccuntInfo() # check whether current time is after the dailyExitTime, if yes, exit if self.dailyExitTime is not None and datetime.datetime.now() > datetime.datetime.strptime( datetime.date.today().strftime("%Y-%m-%d") + " " + self.dailyExitTime, "%Y-%m-%d %H:%M:%S"): self.timeLog("抵达每日终结时间:%s, 现在退出." % self.dailyExitTime) if self.auto_rebalance_on_exit: self.rebalance_position(accountInfo, max_price) break current_position_proportion = self.get_current_position_proportion(accountInfo, max_price) self.calc_sma_and_deviation() if self.auto_rebalance_on and current_position_proportion > self.position_proportion_threshold: if abs(self.spread2List[ -1] - self.spread2_mean) / self.spread2_stdev < self.spread2_close_condition_stdev_coe or abs( self.spread1List[ -1] - self.spread1_mean) / self.spread1_stdev < self.spread1_close_condition_stdev_coe: self.rebalance_position(accountInfo, max_price) continue in_or_out = self.in_or_out() if in_or_out == 0: self.timeLog("没有发现交易信号,进入下一个轮询...") continue elif in_or_out == 1: if self.current_position_direction == 0: # 当前没有持仓 self.timeLog("发现开仓信号(火币卖,OKcoin买)") elif self.current_position_direction == 1: # 当前long spread1 self.timeLog("发现增仓信号(火币卖,OKcoin买)") elif self.current_position_direction == 2: # 当前long spread2 self.timeLog("发现减仓信号(火币卖,OKcoin买)") self.timeLog("火币深度:%s" % str(huobiDepth)) self.timeLog("okcoin深度:%s" % str(okcoinDepth)) if self.current_position_direction == 0 or self.current_position_direction == 1: if current_position_proportion > self.position_proportion_alert_threshold: self.timeLog( "当前仓位比例:%f 大于仓位预警比例:%f" % ( current_position_proportion, self.position_proportion_alert_threshold), level=logging.WARN) # 每次只能吃掉一定ratio的深度 Qty = helper.downRound(min(huobi_buy_1_qty, okcoin_sell_1_qty) * self.orderRatio, 4) elif self.current_position_direction == 2: depthQty = helper.downRound(min(huobi_buy_1_qty, okcoin_sell_1_qty) * self.orderRatio, 4) Qty = min(depthQty, helper.downRound(self.spread2_pos_qty, 4)) # 每次搬砖最多只搬maximum_qty_multiplier个最小单位 if self.maximum_qty_multiplier is not None: Qty = min(Qty, max(self.huobi_min_quantity, self.okcoin_min_quantity) * self.maximum_qty_multiplier) # 每次搬砖前要检查是否有足够security和cash Qty = min(Qty, accountInfo[helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_str"]], helper.downRound(accountInfo[helper.coinTypeStructure[self.coinMarketType]["okcoin"][ "market_str"]] / okcoin_sell_1_price, 4)) Qty = helper.downRound(Qty, 4) Qty = helper.getRoundedQuantity(Qty, self.coinMarketType) if Qty < self.huobi_min_quantity or Qty < self.okcoin_min_quantity: self.timeLog( "数量:%f 小于交易所最小交易数量(火币最小数量:%f, okcoin最小数量:%f),因此无法下单并忽略该信号" % ( Qty, self.huobi_min_quantity, self.okcoin_min_quantity), level=logging.WARN) continue else: # step1: 先处理卖 executed_qty = self.sell_market(self.coinMarketType, str(Qty), exchange="huobi") if executed_qty is not None: # step2: 再执行买 Qty2 = min(executed_qty, Qty) Qty2 = max(helper.getRoundedQuantity(Qty2, self.coinMarketType), self.okcoin_min_quantity) if Qty2 < self.okcoin_min_quantity * 1.05: self.buy_market(self.coinMarketType, str(Qty2 * okcoin_sell_1_price * 1.05), exchange="okcoin", sell_1_price=okcoin_sell_1_price) else: self.buy_market(self.coinMarketType, str(Qty2 * okcoin_sell_1_price), exchange="okcoin", sell_1_price=okcoin_sell_1_price) if self.current_position_direction == 0 or self.current_position_direction == 1: self.spread1_pos_qty += Qty2 elif self.current_position_direction == 2: self.spread2_pos_qty -= Qty2 elif in_or_out == 2: if self.current_position_direction == 0: # 当前没有持仓 self.timeLog("发现开仓信号(OKcoin卖, 火币买)") elif self.current_position_direction == 2: # 当前long spread2 self.timeLog("发现增仓信号(OKcoin卖, 火币买)") elif self.current_position_direction == 1: # 当前long spread1 self.timeLog("发现减仓信号(OKcoin卖, 火币买)") self.timeLog("火币深度:%s" % str(huobiDepth)) self.timeLog("okcoin深度:%s" % str(okcoinDepth)) if self.current_position_direction == 0 or self.current_position_direction == 2: if current_position_proportion > self.position_proportion_alert_threshold: self.timeLog( "当前仓位比例:%f 大于仓位预警比例:%f" % ( current_position_proportion, self.position_proportion_alert_threshold), level=logging.WARN) # 每次只能吃掉一定ratio的深度 Qty = helper.downRound(min(huobi_sell_1_qty, okcoin_buy_1_qty) * self.orderRatio, 4) elif self.current_position_direction == 1: depthQty = helper.downRound(min(huobi_sell_1_qty, okcoin_buy_1_qty) * self.orderRatio, 4) Qty = min(depthQty, helper.downRound(self.spread1_pos_qty, 4)) # 每次搬砖最多只搬maximum_qty_multiplier个最小单位 if self.maximum_qty_multiplier is not None: Qty = min(Qty, max(self.huobi_min_quantity, self.okcoin_min_quantity) * self.maximum_qty_multiplier) # 每次搬砖前要检查是否有足够security和cash Qty = min(Qty, accountInfo[helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_str"]], helper.downRound(accountInfo[helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market_str"]] / huobi_sell_1_price), 4) Qty = helper.getRoundedQuantity(Qty, self.coinMarketType) if Qty < self.huobi_min_quantity or Qty < self.okcoin_min_quantity: self.timeLog("数量:%f 小于交易所最小交易数量(火币最小数量:%f, okcoin最小数量:%f),因此无法下单并忽略该信号" % ( Qty, self.huobi_min_quantity, self.okcoin_min_quantity), level=logging.WARN) continue else: # step1: 先处理卖 executed_qty = self.sell_market(self.coinMarketType, str(Qty), exchange="okcoin") if executed_qty is not None: # step2: 再执行买 Qty2 = min(executed_qty, Qty) self.buy_market(self.coinMarketType, str(Qty2 * huobi_sell_1_price), exchange="huobi") if self.current_position_direction == 0 or self.current_position_direction == 2: self.spread2_pos_qty += Qty2 elif self.current_position_direction == 1: self.spread1_pos_qty -= Qty2 if self.spread1_pos_qty > self.spread_pos_qty_minimum_size: self.current_position_direction = 1 elif self.spread2_pos_qty > self.spread_pos_qty_minimum_size: self.current_position_direction = 2 else: self.current_position_direction = 0
def buy_market(self, security, cash_amount, exchange="huobi", sell_1_price=None): if exchange == "huobi": self.timeLog("开始下达火币市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.huobi_min_cash_amount: self.timeLog("金额:%s 小于交易所最小交易金额(火币最小金额:%s元),因此无法下单,此处忽略该信号" % (cash_amount, self.huobi_min_cash_amount), level=logging.WARN) return None symbol = helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"] # market = helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"] res = self.HuobiService.sendOrder(None,cash_amount,"api",symbol,HB_BUY_MARKET) # res = self.HuobiService.buyMarket( # coin_type, cash_amount, None, None, market, BUY_MARKET) if helper.componentExtract(res, u"result", "") != u'success': self.timeLog("下达火币市价买单(金额:%s)失败, 结果是:%s!" % (cash_amount, helper.componentExtract(res, u"result", "")), level=logging.ERROR) return None order_id = res[u"data"] # 查询订单执行情况 order_info = self.HuobiService.getOrderInfo(order_id) self.timeLog("下达如下火币市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.huobi_order_query_retry_maximum_times and order_info["state"] != "filled": self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.HuobiService.getOrderInfo(order_id) self.timeLog(str(order_info)) retry_time += 1 if float(order_info["field-cash-amount"]) > 0: executed_qty = float( order_info["field-cash-amount"]) / float(order_info["field-cash-amount"]) self.timeLog("火币市价买单已被执行,执行数量:%f,花费的现金:%.2f" % ( executed_qty, float(order_info["field-cash-amount"]))) return executed_qty else: self.timeLog("火币市价买单未被执行", level=logging.WARN) return 0 elif exchange == "okcoin": if sell_1_price is None: raise ValueError( "处理okcoin市价买单之前,需要提供当前Okcoin卖一的价格信息,请检查传入的sell_1_price参数是否完备!") self.timeLog("开始下达okcoin市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.okcoin_min_quantity * sell_1_price: self.timeLog( "金额:%s 不足以购买交易所最小交易数量(okcoin最小数量:%f,当前卖一价格%.2f,最小金额要求:%.2f),因此无法下单,此处忽略该信号" % ( cash_amount, self.okcoin_min_quantity, sell_1_price, self.okcoin_min_quantity * sell_1_price), level=logging.WARN) return None symbol = helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"] res = self.OKCoinService.trade( symbol, OKC_BUY_MARKET, price=cash_amount) if helper.componentExtract(res, "result") != True: self.timeLog("下达okcoin市价买单(金额:%s)失败, 结果是:%s!" % (cash_amount, helper.componentExtract(res, "result")), level=logging.ERROR) return None order_id = res["order_id"] # 查询订单执行情况 order_info = self.OKCoinService.getOrderInfo(symbol, str(order_id)) self.timeLog("下达如下okcoin市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) retry_time = 0 while retry_time < self.okcoin_order_query_retry_maximum_times and order_info["orders"][0]["status"] != 2: self.timeLog("等待%.1f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.OKCoinService.getOrderInfo(symbol, str(order_id)) self.timeLog(str(order_info)) retry_time += 1 executed_qty = order_info["orders"][0]["deal_amount"] self.timeLog("okcoin市价买单已被执行,执行数量:%f,花费的现金:%.2f" % ( executed_qty, executed_qty * order_info["orders"][0]["avg_price"])) return executed_qty
def sell(self, security, quantity, exchange="huobi"): # quantity is a string value if exchange == "huobi": self.timeLog("sell order of huobi...") self.timeLog("keep quantity 4 number of decimals...") self.timeLog("orient quantity:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 4) quantity = str(tmp) self.timeLog("quantity:%s" % quantity) if float(quantity) < self.huobi_min_quantity: self.timeLog( "quantity:%s too samll to trade(huobi min:%f),ignore the signal" % (quantity, self.huobi_min_quantity)) return None coin_type = helper.coinTypeStructure[ self.coinMarketType]["huobi"]["coin_type"] res = self.huobiService.sellMarket( coin_type, quantity, None, None, helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market"], SELL_MARKET) if u"result" not in res or res[u"result"] != u'success': self.timeLog("huobi sell order failed(quantity:%s)!" % quantity) return None order_id = res[u"id"] # query order order_info = self.huobiService.getOrderInfo( coin_type, order_id, helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market"], ORDER_INFO) self.timeLog("huobi sell order, quantity:%s" % quantity) self.timeLog(str(order_info)) if order_info["status"] != 2: self.timeLog("waiting %fs until finished" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.huobiService.getOrderInfo( coin_type, order_id, helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market"], ORDER_INFO) self.timeLog(str(order_info)) executed_qty = float(order_info["processed_amount"]) self.timeLog("huobi sell order, quantity:%f,cash:%.2f" % (executed_qty, executed_qty * float(order_info["processed_price"]))) self.dataLog() return executed_qty elif exchange == "okcoin": self.timeLog("OK coin sell order...") self.timeLog("keep quantity 2 number of decimals...") self.timeLog("orient quantity:%s" % quantity) tmp = float(quantity) tmp = helper.downRound(tmp, 2) quantity = str(tmp) self.timeLog("quantity:%s" % quantity) if float(quantity) < self.okcoin_min_quantity: self.timeLog( "quantity:%s too small to trade(huobi quantity:%f),ignore the signal" % (quantity, self.okcoin_min_quantity)) return None res = self.okcoinService.trade(helper.coinTypeStructure[ self.coinMarketType]["okcoin"]["coin_type"], "sell_market", amount=quantity) if "result" not in res or res["result"] != True: self.timeLog("okcoin sell order(quantity:%s)failed" % quantity) return None order_id = res["order_id"] # query order order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"] ["coin_type"], str(order_id)) self.timeLog("OKcoin sell order, quantity:%s" % quantity) self.timeLog(str(order_info)) if order_info["orders"][0]["status"] != 2: self.timeLog("wait%.1fs until order finished" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"] ["coin_type"], str(order_id)) self.timeLog(str(order_info)) executed_qty = order_info["orders"][0]["deal_amount"] self.timeLog("okcoin sell order excuted,quantity:%f,cash:%.2f" % (executed_qty, executed_qty * order_info["orders"][0]["avg_price"])) self.dataLog() return executed_qty
def buy(self, security, cash_amount, exchange="huobi", sell_1_price=None): # cash_amount is a string value if exchange == "huobi": self.timeLog("开始下达火币市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.huobi_min_cash_amount: self.timeLog("金额:%s 小于交易所最小交易金额(火币最小金额:1元),因此无法下单,此处忽略该信号" % (cash_amount, self.huobi_min_cash_amount)) return None coin_type = helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"] res = self.huobiService.buyMarket(coin_type, cash_amount, None, None, helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], BUY_MARKET) if u"result" not in res or res[u"result"] != u'success': self.timeLog("下达火币市价买单(金额:%s)失败!" % cash_amount) return None order_id = res[u"id"] # 查询订单执行情况 order_info = self.huobiService.getOrderInfo(coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market"], ORDER_INFO) self.timeLog("下达如下火币市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) if order_info["status"] != 2: self.timeLog("等待%f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.huobiService.getOrderInfo(coin_type, order_id, helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market"], ORDER_INFO) self.timeLog(str(order_info)) executed_qty = float(order_info["processed_amount"]) / float(order_info["processed_price"]) self.timeLog("火币市价买单已被执行,执行数量:%f,花费的现金:%.2f" % (executed_qty, float(order_info["processed_amount"]))) self.dataLog() return executed_qty elif exchange == "okcoin": if sell_1_price is None: raise ValueError("处理okcoin市价买单之前,需要提供当前Okcoin卖一的价格信息,请检查传入的sell_1_price参数是否完备!") self.timeLog("开始下达okcoin市价买单...") self.timeLog("只保留下单数量的小数点后2位...") self.timeLog("原始下单金额:%s" % cash_amount) tmp = float(cash_amount) tmp = helper.downRound(tmp, 2) cash_amount = str(tmp) self.timeLog("做完小数点处理后的下单金额:%s" % cash_amount) if float(cash_amount) < self.okcoin_min_quantity * sell_1_price: self.timeLog( "金额:%s 不足以购买交易所最小交易数量(okcoin最小数量:%f,当前卖一价格%.2f,最小金额要求:%.2f),因此无法下单,此处忽略该信号" % ( cash_amount, self.okcoin_min_quantity, sell_1_price, self.okcoin_min_quantity * sell_1_price)) return None res = self.okcoinService.trade(helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"], "buy_market", price=cash_amount) if "result" not in res or res["result"] != True: self.timeLog("下达okcoin市价买单(金额:%s)失败" % cash_amount) return None order_id = res["order_id"] # 查询订单执行情况 order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"], str(order_id)) self.timeLog("下达如下okcoin市价买单,金额:%s" % cash_amount) self.timeLog(str(order_info)) if order_info["orders"][0]["status"] != 2: self.timeLog("等待%.1f秒直至订单完成" % self.orderWaitingTime) time.sleep(self.orderWaitingTime) order_info = self.okcoinService.orderinfo( helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"], str(order_id)) self.timeLog(str(order_info)) executed_qty = order_info["orders"][0]["deal_amount"] self.timeLog("okcoin市价买单已被执行,执行数量:%f,花费的现金:%.2f" % ( executed_qty, executed_qty * order_info["orders"][0]["avg_price"])) self.dataLog() return executed_qty
def go(self): self.timeLog( "log start at: %s" % self.getStartRunningTime().strftime(self.TimeFormatForLog)) self.dataLog( content= "time|huobi_cny_cash|huobi_cny_btc|huobi_cny_ltc|huobi_cny_cash_loan|huobi_cny_btc_loan|huobi_cny_ltc_loan|huobi_cny_cash_frozen|huobi_cny_btc_frozen|huobi_cny_ltc_frozen|huobi_cny_total|huobi_cny_net|okcoin_cny_cash|okcoin_cny_btc|okcoin_cny_ltc|okcoin_cny_cash_frozen|okcoin_cny_btc_frozen|okcoin_cny_ltc_frozen|okcoin_cny_total|okcoin_cny_net|total_net" ) self.dataLog() while (True): # check whether current time is after the dailyExitTime, if yes, exit if self.dailyExitTime is not None and datetime.datetime.now( ) > datetime.datetime.strptime( datetime.date.today().strftime("%Y-%m-%d") + " " + self.dailyExitTime, "%Y-%m-%d %H:%M:%S"): self.timeLog("end time:%s, now exiting..." % self.dailyExitTime) break self.timeLog("waiting %d s for next loop..." % self.timeInterval) time.sleep(self.timeInterval) # calculate the net asset at a fixed time window time_diff = datetime.datetime.now() - self.last_data_log_time if time_diff.seconds > self.dataLogFixedTimeWindow: self.dataLog() accountInfo = self.getAccuntInfo() huobiDepth = self.huobiService.getDepth( helper.coinTypeStructure[ self.coinMarketType]["huobi"]["coin_type"], helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market"], depth_size=1) okcoinDepth = self.okcoinService.depth(helper.coinTypeStructure[ self.coinMarketType]["okcoin"]["coin_type"]) huobi_sell_1_price = huobiDepth["asks"][0][0] huobi_sell_1_qty = huobiDepth["asks"][0][1] huobi_buy_1_price = huobiDepth["bids"][0][0] huobi_buy_1_qty = huobiDepth["bids"][0][1] okcoin_sell_1_price = okcoinDepth["asks"][0][0] okcoin_sell_1_qty = okcoinDepth["asks"][0][1] okcoin_buy_1_price = okcoinDepth["bids"][0][0] okcoin_buy_1_qty = okcoinDepth["bids"][0][1] if huobi_buy_1_price > okcoin_sell_1_price: self.timeLog("find the signal") self.timeLog("depth of huobi:%s" % str(huobiDepth)) self.timeLog("depth of okcoin:%s" % str(okcoinDepth)) Qty = helper.downRound( min(huobi_buy_1_qty, okcoin_sell_1_qty) * self.orderRatio, 4) # check security and cash Qty = min( Qty, accountInfo[helper.coinTypeStructure[ self.coinMarketType]["huobi"]["coin_str"]], helper.downRound( accountInfo[helper.coinTypeStructure[ self.coinMarketType]["okcoin"]["market_str"]] / okcoin_sell_1_price, 4)) Qty = helper.downRound(Qty, 4) Qty = helper.getRoundedQuantity(Qty, self.coinMarketType) if Qty < self.huobi_min_quantity or Qty < self.okcoin_min_quantity: self.timeLog( "quantity:%f too small to trade(huobi:%f, okcoin:%f),ignore the signal" % (Qty, self.huobi_min_quantity, self.okcoin_min_quantity)) continue else: # step1: sell executed_qty = self.sell(self.coinMarketType, str(Qty), exchange="huobi") if executed_qty is not None: # step2: buy Qty2 = min(executed_qty, Qty) Qty2 = max( helper.getRoundedQuantity(Qty2, self.coinMarketType), self.okcoin_min_quantity) if Qty2 < self.okcoin_min_quantity * 1.05: self.buy(self.coinMarketType, str(Qty2 * okcoin_sell_1_price * 1.05), exchange="okcoin", sell_1_price=okcoin_sell_1_price) else: self.buy(self.coinMarketType, str(Qty2 * okcoin_sell_1_price), exchange="okcoin", sell_1_price=okcoin_sell_1_price) elif okcoin_buy_1_price > huobi_sell_1_price: self.timeLog("find signal") self.timeLog("depth of huobi:%s" % str(huobiDepth)) self.timeLog("depth of okcoin:%s" % str(okcoinDepth)) Qty = helper.downRound( min(huobi_sell_1_qty, okcoin_buy_1_qty) * self.orderRatio, 4) Qty = min( Qty, accountInfo[helper.coinTypeStructure[ self.coinMarketType]["okcoin"]["coin_str"]], helper.downRound(accountInfo[helper.coinTypeStructure[ self.coinMarketType]["huobi"]["market_str"]] / huobi_sell_1_price), 4) Qty = helper.getRoundedQuantity(Qty, self.coinMarketType) if Qty < self.huobi_min_quantity or Qty < self.okcoin_min_quantity: self.timeLog( "quantity:%f too small to trade(huobi:%f, okcoin:%f),ignore the signal" % (Qty, self.huobi_min_quantity, self.okcoin_min_quantity)) continue else: executed_qty = self.sell(self.coinMarketType, str(Qty), exchange="okcoin") if executed_qty is not None: Qty2 = min(executed_qty, Qty) self.buy(self.coinMarketType, str(Qty2 * huobi_sell_1_price), exchange="huobi")
def go(self): self.timeLog("日志启动于 %s" % self.getStartRunningTime().strftime(self.TimeFormatForLog)) self.dataLog( content="time|huobi_cny_cash|huobi_cny_btc|huobi_cny_ltc|huobi_cny_cash_loan|huobi_cny_btc_loan|huobi_cny_ltc_loan|huobi_cny_cash_frozen|huobi_cny_btc_frozen|huobi_cny_ltc_frozen|huobi_cny_total|huobi_cny_net|okcoin_cny_cash|okcoin_cny_btc|okcoin_cny_ltc|okcoin_cny_cash_frozen|okcoin_cny_btc_frozen|okcoin_cny_ltc_frozen|okcoin_cny_total|okcoin_cny_net|total_net") self.dataLog() while (True): # check whether current time is after the dailyExitTime, if yes, exit if self.dailyExitTime is not None and datetime.datetime.now() > datetime.datetime.strptime( datetime.date.today().strftime("%Y-%m-%d") + " " + self.dailyExitTime, "%Y-%m-%d %H:%M:%S"): self.timeLog("抵达每日终结时间:%s, 现在退出." % self.dailyExitTime) break self.timeLog("等待 %d 秒进入下一个循环..." % self.timeInterval) time.sleep(self.timeInterval) # calculate the net asset at a fixed time window time_diff = datetime.datetime.now() - self.last_data_log_time if time_diff.seconds > self.dataLogFixedTimeWindow: self.dataLog() # 获取当前账户信息 accountInfo = self.getAccuntInfo() # 查询huobi第一档深度数据 huobiDepth = self.huobiService.getDepth(helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_type"], helper.coinTypeStructure[self.coinMarketType]["huobi"]["market"], depth_size=1) # 查询okcoin第一档深度数据 okcoinDepth = self.okcoinService.depth(helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_type"]) huobi_sell_1_price = huobiDepth["asks"][0][0] huobi_sell_1_qty = huobiDepth["asks"][0][1] huobi_buy_1_price = huobiDepth["bids"][0][0] huobi_buy_1_qty = huobiDepth["bids"][0][1] okcoin_sell_1_price = okcoinDepth["asks"][0][0] okcoin_sell_1_qty = okcoinDepth["asks"][0][1] okcoin_buy_1_price = okcoinDepth["bids"][0][0] okcoin_buy_1_qty = okcoinDepth["bids"][0][1] if huobi_buy_1_price > okcoin_sell_1_price: # 获利信号:OKcoin买,huobi卖 self.timeLog("发现信号") self.timeLog("火币深度:%s" % str(huobiDepth)) self.timeLog("okcoin深度:%s" % str(okcoinDepth)) # 每次只能吃掉一定ratio的深度 Qty = helper.downRound(min(huobi_buy_1_qty, okcoin_sell_1_qty) * self.orderRatio, 4) # 每次搬砖前要检查是否有足够security和cash Qty = min(Qty, accountInfo[helper.coinTypeStructure[self.coinMarketType]["huobi"]["coin_str"]], helper.downRound(accountInfo[helper.coinTypeStructure[self.coinMarketType]["okcoin"][ "market_str"]] / okcoin_sell_1_price, 4)) Qty = helper.downRound(Qty, 4) Qty = helper.getRoundedQuantity(Qty, self.coinMarketType) if Qty < self.huobi_min_quantity or Qty < self.okcoin_min_quantity: self.timeLog( "数量:%f 小于交易所最小交易数量(火币最小数量:%f, okcoin最小数量:%f),因此无法下单并忽略该信号" % ( Qty, self.huobi_min_quantity, self.okcoin_min_quantity)) continue else: # step1: 先处理卖 executed_qty = self.sell(self.coinMarketType, str(Qty), exchange="huobi") if executed_qty is not None: # step2: 再执行买 Qty2 = min(executed_qty, Qty) Qty2 = max(helper.getRoundedQuantity(Qty2, self.coinMarketType), self.okcoin_min_quantity) if Qty2 < self.okcoin_min_quantity * 1.05: self.buy(self.coinMarketType, str(Qty2 * okcoin_sell_1_price * 1.05), exchange="okcoin", sell_1_price=okcoin_sell_1_price) else: self.buy(self.coinMarketType, str(Qty2 * okcoin_sell_1_price), exchange="okcoin", sell_1_price=okcoin_sell_1_price) elif okcoin_buy_1_price > huobi_sell_1_price: # 获利信号:OKcoin卖,huobi买 self.timeLog("发现信号") self.timeLog("火币深度:%s" % str(huobiDepth)) self.timeLog("okcoin深度:%s" % str(okcoinDepth)) # 每次只能吃掉一定ratio的深度 Qty = helper.downRound(min(huobi_sell_1_qty, okcoin_buy_1_qty) * self.orderRatio, 4) # 每次搬砖前要检查是否有足够security和cash Qty = min(Qty, accountInfo[helper.coinTypeStructure[self.coinMarketType]["okcoin"]["coin_str"]], helper.downRound(accountInfo[helper.coinTypeStructure[self.coinMarketType]["huobi"][ "market_str"]] / huobi_sell_1_price), 4) Qty = helper.getRoundedQuantity(Qty, self.coinMarketType) if Qty < self.huobi_min_quantity or Qty < self.okcoin_min_quantity: self.timeLog("数量:%f 小于交易所最小交易数量(火币最小数量:%f, okcoin最小数量:%f),因此无法下单并忽略该信号" % ( Qty, self.huobi_min_quantity, self.okcoin_min_quantity)) continue else: # step1: 先处理卖 executed_qty = self.sell(self.coinMarketType, str(Qty), exchange="okcoin") if executed_qty is not None: # step2: 再执行买 Qty2 = min(executed_qty, Qty) self.buy(self.coinMarketType, str(Qty2 * huobi_sell_1_price), exchange="huobi")