def getCanBuyStopLoss(price, symbol, env): stopLossPackage = [] try: sellPackage = modelUtil.getStopLossModel(symbol, env) # 查询卖出历史 for stopLossModel in sellPackage: status = int(stopLossModel.status) if status == 1: continue sellPrice = float(stopLossModel.sellPrice) minIncome = 0.03 #暂定 3个百分点 gap = sellPrice - price gap = gap / sellPrice if gap >= float(minIncome): stopLossPackage.append(stopLossModel) except Exception as err: logUtil.error("commonUtil--getCanBuyStopLoss" + err) return stopLossPackage
def sell(env, sellPrice, sellIndex, buyModel, transactionModel): try: symbol = transactionModel.symbol decimalLength = transactionModel.pricePrecision if "pro" == env: sellPrice = round( float(buyModel.price) * (1 + float(buyModel.minIncome)), decimalLength) newBuyModel = BuyModel(buyModel.id, buyModel.symbol, buyModel.price, buyModel.oriPrice, buyModel.index, buyModel.amount, buyModel.orderId, buyModel.minIncome, buyModel.lastPrice, 3) # newJumpModel = JumpQueueModel(2, buyModel.orderId, round(sellPrice * 0.992, decimalLength), # round(sellPrice * 0.995, decimalLength), round(sellPrice * 1.01, decimalLength), 0, # time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(sellIndex)),sellPrice) #统计发现,因为提高了最低收入值,因此不大可能会再次触发跳跃 newJumpModel = JumpQueueModel(0, symbol, 2, buyModel.orderId, sellPrice, sellPrice, round(sellPrice * 1.01, decimalLength), 0, sellPrice) if modelUtil.modBuyModel(newBuyModel): modelUtil.insertJumpQueueModel(newJumpModel) else: logUtil.error("BiTradeUtil--sell modBuyModel 0 orderId=", buyModel.orderId) except Exception as err: logUtil.error("BiTradeUtil--sell" + err)
def dealStopLoss(data, transactionModel, env): try: price = float(data['close']) needStopLossPackage = commonUtil.getStopLossBuyModel( data['close'], transactionModel.symbol, transactionModel.stopLoss, env) if len(needStopLossPackage) > 0: # 价格到达止损点 mergeBuyModel = commonUtil.mergeBuyModel(env, needStopLossPackage, transactionModel, price) for buyModel in mergeBuyModel: logUtil.info("can stop loss ", buyModel) biTradeUtil.stopLossSell(env, price, buyModel, transactionModel.symbol) stopLossPackage = commonUtil.getCanBuyStopLoss(data['close'], transactionModel.symbol, env) if len(stopLossPackage) > 0: for stopLoss in stopLossPackage: logUtil.info("buy stop loss ", stopLoss) biTradeUtil.stopLossBuy(price, stopLoss, transactionModel) except Exception as err: logUtil.error('dealStopLoss error', err, data)
def canSell(price, symbol, env): sellPackage = [] try: buyPackage = modelUtil.getBuyModel(symbol, env) # 查询购买历史 #查询购买历史 for buyModel in buyPackage: minIncome = float(buyModel.minIncome) status = int(buyModel.status) if status != 0: continue if "pro" == env: minIncome = minIncome - 0.01 #生产环境提前先挂单 buyModelPrice = buyModel.price gap = price - float(buyModelPrice) gap = gap / float(buyModelPrice) if gap >= minIncome: sellPackage.append(buyModel) except Exception as err: logUtil.error("commonUtil--canSell" + err) return sellPackage
def buy(buyPrice, amount, index, transactionModel): try: symbol = transactionModel.symbol minIncome = transactionModel.minIncome decimalLength = transactionModel.pricePrecision orderId = commonUtil.getRandomOrderId() # 已经不存在这个交易对的买入 说明是第一次买入 需要降低买入的花费 if modelUtil.getBuyModelBySymbolAndStatus(transactionModel.symbol, 0) is None: amount = round( float(transactionModel.everyExpense) * 0.6 / buyPrice, int(transactionModel.precision)) buyModel = BuyModel(0, symbol, buyPrice, buyPrice, index, amount, orderId, minIncome, buyPrice, 2) newJumpModel = JumpQueueModel(0, symbol, 1, orderId, round(buyPrice * 1.005, decimalLength), round(buyPrice * 1.008, decimalLength), round(buyPrice * 0.995, decimalLength), 0, buyPrice) if modelUtil.insertBuyModel(buyModel): modelUtil.insertJumpQueueModel(newJumpModel) else: logUtil.error("BiTradeUtil--buy insert 0") return True except Exception as err: logUtil.error("BiTradeUtil--buy" + err) return False
def getStopLossBuyModel(price, symbol, stopLoss, env): stopLossPackage = [] stopLoss = float(stopLoss) try: buyPackage = modelUtil.getBuyModel(symbol, env) # 查询购买历史 for buyModel in buyPackage: buyModelPrice = float(buyModel.price) status = int(buyModel.status) lastPrice = float(buyModel.lastPrice) stopLosssTemp = stopLoss if status != 0 or buyModelPrice <= price: continue stoplossCount = modelUtil.getStopLossModelCountByOrderId( buyModel.orderId) #判断有没有进行过止损 if stoplossCount > 0: if price < lastPrice: stopLosssTemp = stopLoss / 2 buyModelPrice = lastPrice else: #与上一次买的价差率 lastGap = price - lastPrice lastGap = lastGap / lastPrice #与当前价格的价差率 nowGap = buyModelPrice - price nowGap = nowGap / buyModelPrice if lastGap < 0.02 or nowGap < stopLoss: continue gap = buyModelPrice - price gap = gap / buyModelPrice if gap >= stopLosssTemp: if "pro" == env: result = huobi.order_info(buyModel.orderId) data = result['data'] state = data['state'] logUtil.info("order_info result", buyModel.orderId, result, symbol) if state != 'filled': continue stopLossPackage.append(buyModel) except Exception as err: logUtil.error("commonUtil--getStopLossBuyModel" + err) return stopLossPackage
def dealData(data, transactionModel, env): try: kdjFlag = kDJUtil.judgeBuy(transactionModel.symbol) rSIFlag = rSIUtil.rsiJudgeBuy(transactionModel.symbol, 12) maFlag = mAUtil.maJudgeBuy(data, transactionModel.symbol) avgFlag = commonUtil.juideAllGap(data['close'], transactionModel.symbol, transactionModel.tradeGap, env) highFlag = commonUtil.juideHighest(data['close'], transactionModel.symbol) bollFlag = bollUtil.judgeBollBuy(data['close'], transactionModel.symbol) lowFlag = commonUtil.juideLowest(data['close'], transactionModel.symbol) riskFlag = amountUtil.judgeRisk(transactionModel.symbol) # sellFlag = kDJUtil.judgeSell(transactionModel.symbol) logUtil.info(( "kdjFlag={}, rSIFlag={}, maFlag={}, avgFlag={}, highFlag={}, bollFlag={}, lowFlag={}, riskFlag={}" ).format(kdjFlag, rSIFlag, maFlag, avgFlag, highFlag, bollFlag, lowFlag, riskFlag)) price = float(data['close']) if commonUtil.nextBuy and avgFlag: amount = round( float(transactionModel.everyExpense) / price, int(transactionModel.precision)) isSuccess = biTradeUtil.buy(price, amount, data['id'], transactionModel) logUtil.info( ("is next buy symbol={},price={},data['id']={} issuccess={}" ).format(transactionModel.symbol, price, data['id'], isSuccess)) if isSuccess: commonUtil.nextBuy = False elif kdjFlag and rSIFlag and maFlag and avgFlag and highFlag: amount = round( float(transactionModel.everyExpense) / price, int(transactionModel.precision)) isSuccess = biTradeUtil.buy(price, amount, data['id'], transactionModel) logUtil.info( ("is first buy symbol={},price={},data['id']={} issuccess={}" ).format(transactionModel.symbol, price, data['id'], isSuccess)) elif avgFlag and lowFlag and bollFlag and riskFlag and highFlag: commonUtil.nextBuy = True except Exception as err: logUtil.error('deal error', err)
def jumpBuy(env, buyPrice, jumpQueueModel, transactionModel, index): try: symbol = transactionModel.symbol orderId = jumpQueueModel.orderId buyModel = modelUtil.getBuyModelByOrderId(orderId) if buyModel is None: logUtil.info("orderId is null", orderId) return newAmount = round( float(transactionModel.everyExpense) / buyPrice, int(transactionModel.precision)) # 已经不存在这个交易对的买入 说明是第一次买入 需要降低买入的花费 if modelUtil.getBuyModelBySymbolAndStatus(transactionModel.symbol, 0) is None: newAmount = round( float(transactionModel.everyExpense) * 0.6 / buyPrice, int(transactionModel.precision)) if "pro" == env: result = huobi.send_order(newAmount, "api", symbol, "buy-limit", buyPrice) logUtil.info("buy result", result, symbol, newAmount, buyPrice) if result['status'] == 'ok': orderId = result['data'] else: return False else: huobi.send_order_dev(newAmount, 1, buyPrice) newBuyModel = BuyModel(buyModel.id, buyModel.symbol, buyPrice, buyModel.oriPrice, index, newAmount, orderId, transactionModel.minIncome, buyPrice, 0) if modelUtil.modBuyModel(newBuyModel): modelUtil.delJumpModelById(jumpQueueModel.id) jumpProfit = (float(jumpQueueModel.oriPrice) - buyPrice) * float(newAmount) huobi.jumpProfit = huobi.jumpProfit + jumpProfit jumpQueueModel.orderId = orderId modelUtil.insertHistoryJumpQueueModel(jumpQueueModel, buyPrice, newAmount) modelUtil.insertBuySellReocrd(buyModel.symbol, 1, buyPrice, 0, orderId, 0, newAmount, index) else: logUtil.error("BiTradeUtil--jumpBuy modBuyModel 0 orderId=", orderId) return True except Exception as err: logUtil.error("BiTradeUtil--jumpBuy" + err) return False
def jumpSell(env, sellPrice, jumpQueueModel, transactionModel, index): try: sellOrderId = commonUtil.getRandomOrderId() symbol = transactionModel.symbol orderId = jumpQueueModel.orderId buyModel = modelUtil.getBuyModelByOrderId(orderId) if "pro" == env: #{'status': 'ok', 'data': {'symbol': 'xrpusdt', 'source': 'api', 'field-cash-amount': '0.0', 'price': '0.1972', # 'canceled-at': 0, 'field-amount': '0.0', 'type': 'sell-limit', 'state': 'submitted', 'client-order-id': '', 'field-fees': '0.0', # 'created-at': 1587721600720, 'account-id': account-id, 'id': 82495000363, 'amount': '26.0000', 'finished-at': 0}} result = huobi.order_info(buyModel.orderId) data = result['data'] state = data['state'] logUtil.info("order_info result", result, symbol) if state == 'filled': #{'status': 'ok', 'data': 'orderId'} result = huobi.send_order(buyModel.amount, "api", symbol, 'sell-limit', sellPrice) logUtil.info("send_order result", result, symbol) if result['status'] != 'ok': return sellOrderId = result['data'] else: return else: huobi.send_order_dev(buyModel.amount, 0, sellPrice) sellOrderModel = SellOrderModel(0, buyModel.symbol, buyModel.price, sellPrice, buyModel.index, index, buyModel.orderId, sellOrderId, buyModel.amount) newBuyModel = BuyModel(buyModel.id, buyModel.symbol, buyModel.price, buyModel.oriPrice, buyModel.index, buyModel.amount, buyModel.orderId, buyModel.minIncome, buyModel.lastPrice, 4) if modelUtil.modBuyModel(newBuyModel): modelUtil.delJumpModelById(jumpQueueModel.id) modelUtil.insertHistoryJumpQueueModel(jumpQueueModel, sellPrice, buyModel.amount) modelUtil.insertSellOrderReocrd(sellOrderModel) else: logUtil.error("BiTradeUtil--sell jumpSell 0 orderId=", buyModel.orderId) except Exception as err: logUtil.error("BiTradeUtil--jumpSell" + err)
def run(self): while True: try: transactionModels = refresh.getAllPairAndRefresh() self.doCheck(transactionModels) except Exception as err: logUtil.error('checkOrderStatusThread error', err.__traceback__) time.sleep(5)
def dealSell(data, transactionModel, env): try: price = float(data['close']) sellPackage = commonUtil.canSell(data['close'], transactionModel.symbol, env) if len(sellPackage) > 0: for buyModel in sellPackage: biTradeUtil.sell(env, price, data['id'], buyModel, transactionModel) except Exception as err: logUtil.error('dealSell error', err)
def chechOrder(self, orderId): try: if "pro" == self.env: result = huobi.order_info(orderId) data = result['data'] state = data['state'] logUtil.info("chechOrder", result) if state == 'filled': return True else: return True except Exception as err: logUtil.error('chechOrder error', err) return False
def getConn(): global __pool """ @summary: 静态方法,从连接池中取出连接 @return MySQLdb.connection """ if __pool is None: logUtil.error("is None") __pool = PooledDB(creator=pymysql, mincached=5, maxcached=20, host=DBConfig.DBHOST, port=DBConfig.DBPORT, user=DBConfig.DBUSER, passwd=DBConfig.DBPWD, db=DBConfig.DBNAME, use_unicode=True, charset=DBConfig.DBCHAR, cursorclass=DictCursor) return __pool.connection()
def stopLossBuy(price, stopLossModel, transactionModel): try: symbol = transactionModel.symbol decimalLength = transactionModel.pricePrecision newStopLossModel = StopLossModel( stopLossModel.id, stopLossModel.symbol, stopLossModel.sellPrice, stopLossModel.oriPrice, stopLossModel.oriAmount, stopLossModel.oriOrderId, stopLossModel.orderId, 1) newJumpModel = JumpQueueModel(0, symbol, 3, stopLossModel.orderId, round(price * 1.005, decimalLength), round(price * 1.008, decimalLength), round(price * 0.99, decimalLength), 0, price) if modelUtil.modStopLossModel(newStopLossModel): modelUtil.insertJumpQueueModel(newJumpModel) else: logUtil.error("BiTradeUtil--modStopLossModel=", newStopLossModel) except Exception as err: logUtil.error("BiTradeUtil--stopLossBuy" + err)
def stopLossSell(env, sellPrice, buyModel, symbol): try: orderId = commonUtil.getRandomOrderId() if "pro" == env: result = huobi.order_info(buyModel.orderId) data = result['data'] state = data['state'] logUtil.info("stopLossSell result", result, symbol) if state == 'filled': result = huobi.send_order(buyModel.amount, "api", symbol, 'sell-limit', sellPrice) if result['status'] == 'ok': orderId = result['data'] else: return else: return else: huobi.send_order_dev(buyModel.amount, 0, sellPrice) newBuyModel = BuyModel(buyModel.id, buyModel.symbol, buyModel.price, buyModel.oriPrice, buyModel.index, buyModel.amount, buyModel.orderId, buyModel.minIncome, buyModel.lastPrice, 1) if modelUtil.modBuyModel(newBuyModel): #在{什么时候} 以 {什么价格} 卖出 {原价是什么} 的 {多少个} {原来的orderId} {这次的orderId} {状态} insertResult = modelUtil.insertStopLossReocrd( symbol, sellPrice, buyModel.price, buyModel.amount, buyModel.orderId, orderId, 0) if insertResult is False: logUtil.error("insertResult is false", buyModel.orderId) #记录日志 modelUtil.insertStopLossHistoryReocrd(symbol, 0, sellPrice, buyModel.price, buyModel.amount, buyModel.orderId, orderId) else: logUtil.error("BiTradeUtil--sell stopLossSell 0 orderId=", buyModel.orderId, " id=", buyModel.id) except Exception as err: logUtil.error("BiTradeUtil--stopLossSell" + err)
def doTrade(env, price, index, transactionModel): try: jumpModelList = modelUtil.getJumpModel(transactionModel.symbol, env) if len(jumpModelList) > 0: for jumpModel in jumpModelList: lowPrice = float(jumpModel.lowPrice) highPrice = float(jumpModel.highPrice) jumpPrice = float(jumpModel.jumpPrice) jumpCount = int(jumpModel.jumpCount) type = int(jumpModel.type) # 达到需要操作的价格区间 if (price >= lowPrice and price <= highPrice) or jumpCount >= 20: doOper(env, price, transactionModel, jumpModel, index) continue #买类型 if type % 2 == 1 and lowPrice == highPrice: doOper(env, lowPrice, transactionModel, jumpModel, index) continue # 卖类型 if type % 2 == 0 and lowPrice == highPrice: doOper(env, lowPrice, transactionModel, jumpModel, index) continue highGap = 0.008 lowGap = 0.005 # 为单数即为买,到达跳跃点,需要不断下调jumpPrice价格 if type % 2 == 1 and jumpPrice >= price: length = transactionModel.pricePrecision if jumpCount > 2: highGap = 0.015 lowGap = 0.01 lowPrice = round(price + price * lowGap, length) #重新计算可操作区间 highPrice = round(price + price * highGap, length) jumpCount = jumpCount + 1 jumpPrice = round(price - price * 0.01, length) #下调jumpPrice价格 newJumpModel = JumpQueueModel( jumpModel.id, jumpModel.symbol, jumpModel.type, jumpModel.orderId, lowPrice, highPrice, jumpPrice, jumpCount, jumpModel.oriPrice) modelUtil.modJumpModel(newJumpModel) # 为双数即为卖,到达跳跃点,需要不断上调jumpPrice价格 if type % 2 == 0 and jumpPrice <= price: length = transactionModel.pricePrecision if jumpCount > 2: highGap = 0.015 lowGap = 0.01 lowPrice = round(price - price * highGap, length) #重新计算可操作区间 highPrice = round(price - price * lowGap, length) jumpCount = jumpCount + 1 jumpPrice = round(price + price * 0.01, length) #上调jumpPrice价格 newJumpModel = JumpQueueModel( jumpModel.id, jumpModel.symbol, jumpModel.type, jumpModel.orderId, lowPrice, highPrice, jumpPrice, jumpCount, jumpModel.oriPrice) modelUtil.modJumpModel(newJumpModel) except Exception as err: logUtil.error("JumpUtil--doTrade" + err)
if env == "pro": logUtil.info(thisData['data'], transactionModel.symbol) logUtil.kLineData(transactionModel.symbol + "-->" + str(thisData['data'][0])) dealStopLoss(lastData['data'][0], transactionModel, env) #止损模块处理 if lastId != thisData['data'][0]['id']: #策略模块1处理 commonUtil.addSymbol(lastData['data'][0], transactionModel, True) dealData(lastData['data'][0], transactionModel, env) # 策略模块2处理 dealSell(lastData['data'][0], transactionModel, env) #交割模块处理 doTrade(lastData['data'][0], transactionModel, env) commonUtil.lastDataDict[transactionModel.symbol] = thisData commonUtil.lastIdDict[ transactionModel.symbol] = thisData['data'][0]['id'] if env != "pro": logUtil.info(huobi.balance, " ", huobi.maxBalance, " ", huobi.minBalance, " ", huobi.jumpProfit) except Exception as err: logUtil.error('connect https error,retry...', err) # time.sleep(1)
def doTrade(data, transactionModel, env): try: price = float(data['close']) jumpUtil.doTrade(env, price, data['id'], transactionModel) except Exception as err: logUtil.error('doTrade error', err)
def stopLossJumpBuy(env, buyPrice, jumpQueueModel, transactionModel, index): try: symbol = transactionModel.symbol orderId = jumpQueueModel.orderId stopLossModel = modelUtil.getStopLossModelByOrderId(orderId) if stopLossModel is None: logUtil.error("jumpQueueModel=", jumpQueueModel, " is none") return buyModel = modelUtil.getBuyModelByOrderId(stopLossModel.oriOrderId) minAmount = round(5.1 / buyPrice, int(transactionModel.precision)) buyAmount = float(buyModel.amount) oldAmount = float(buyModel.amount) if minAmount > oldAmount: buyAmount = minAmount if "pro" == env: result = huobi.send_order(buyAmount, "api", symbol, "buy-limit", buyPrice) logUtil.info("buy result", result, symbol, buyAmount, buyPrice) if result['status'] == 'ok': orderId = result['data'] else: return False else: huobi.send_order_dev(buyAmount, 1, buyPrice) # 计算新的价格 length = transactionModel.pricePrecision #原本用掉的钱 - (止损卖出等到的钱 - 这次买回来花费的钱)/目前的数量 newPrice = round((float(buyModel.price) * oldAmount - (float(stopLossModel.sellPrice) * oldAmount - float(buyPrice) * buyAmount)) / buyAmount, length) newBuyModel = BuyModel(buyModel.id, buyModel.symbol, newPrice, buyModel.oriPrice, buyModel.index, buyModel.amount, buyModel.orderId, transactionModel.minIncome, buyPrice, 0) if modelUtil.modBuyModel(newBuyModel): if modelUtil.delStopLossModelById(stopLossModel.id): modelUtil.delJumpModelById(jumpQueueModel.id) modelUtil.insertHistoryJumpQueueModel(jumpQueueModel, buyPrice, buyModel.amount) jumpProfit = (float(jumpQueueModel.oriPrice) - buyPrice) * float(buyModel.amount) huobi.jumpProfit = huobi.jumpProfit + jumpProfit # 记录止损买日志 modelUtil.insertStopLossHistoryReocrd(symbol, 1, buyPrice, stopLossModel.oriPrice, stopLossModel.oriAmount, stopLossModel.oriOrderId, orderId) else: logUtil.error("BiTradeUtil--delStopLossModelById 0 =", stopLossModel) else: logUtil.error("BiTradeUtil--stopLossJumpBuy 0 orderId=", buyModel.orderId) except Exception as err: logUtil.error("BiTradeUtil--stopLossJumpBuy" + err)