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 run(self): while True: try: result = huobi.get_trade(self.transactionModel.symbol) tickUtil.add(result, self.transactionModel.symbol) except Exception as err: logUtil.info('TradeThread error', err)
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 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 addSymbol(data, transactionModel, needInserDb): logUtil.info(data, "new data-----", transactionModel.symbol) klineUtil.add(data, transactionModel.symbol) kDJUtil.add(data, transactionModel.symbol) rSIUtil.add(transactionModel.symbol, 12) mAUtil.add(transactionModel.symbol, 10) mAUtil.add(transactionModel.symbol, 30) mAUtil.add(transactionModel.symbol, 60) amountUtil.add(data, transactionModel.symbol) if needInserDb: modelUtil.insertKLineReocrd(data, transactionModel.symbol)
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 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 doCheck(self, transactionModels): for transactionModel in transactionModels: symbol = transactionModel.symbol sellOrderModels = modelUtil.getSellOrderModels(symbol, self.env) if len(sellOrderModels) > 0: for sellOrderModel in sellOrderModels: orderStatus = self.chechOrder(sellOrderModel.sellOrderId) logUtil.info("orderId=", sellOrderModel.sellOrderId, " status=", orderStatus) if orderStatus: buyModel = modelUtil.getBuyModelByOrderId( sellOrderModel.buyOrderId) modelUtil.delBuyModel(buyModel.id) modelUtil.delSellOrderById(sellOrderModel.id) modelUtil.insertBuySellReocrd( buyModel.symbol, 0, sellOrderModel.buyPrice, sellOrderModel.sellPrice, sellOrderModel.buyOrderId, sellOrderModel.sellOrderId, sellOrderModel.amount, int(time.time())) continue # 测试环境不会走到这里,因为测试环境能直接卖成功 kline = huobi.get_kline(symbol, transactionModel.period, 1) if kline['status'] == 'ok' and kline['data'] and len( kline['data']) >= 1: kline['data'].reverse() price = float(kline['data'][0]['close']) buyPrice = float(sellOrderModel.buyPrice) if buyPrice > price: # 当前价格比买入的时候低才需要判断要不要撤单 gap = (buyPrice - price) / buyPrice if gap > 0.05: # 比买入的时候还要低5%就撤单 #{'status': 'ok', 'data': '82495000363'} result = huobi.cancel_order( sellOrderModel.sellOrderId) if result['status'] == 'ok': modelUtil.delSellOrderById( sellOrderModel.id) buyModel = modelUtil.getBuyModelByOrderId( sellOrderModel.buyOrderId) buyModel.status = 0 modelUtil.modBuyModel(buyModel)
def doMerge(env, list, transactionModel): if len(list) < 1: return None decimallength = transactionModel.pricePrecision price = 0.0 amount = 0.0 index = 0 orderId = 0 shouldDel = [] for buyModel in list: if checkOrderIsFilled(env, buyModel.orderId): logUtil.info("doMerge=", buyModel) shouldDel.append(buyModel) price = price + float(buyModel.price) * float(buyModel.amount) amount = amount + float(buyModel.amount) index = buyModel.index #这两个随便 orderId = buyModel.orderId if len(shouldDel) < 2: return None amount = round(amount, int(transactionModel.precision)) avgPrice = round(price / amount, decimallength) newBuyModel = BuyModel(0, list[0].symbol, avgPrice, avgPrice, index, amount, orderId, transactionModel.minIncome, avgPrice, 0) for shouldDelBuyModel in shouldDel: modelUtil.delBuyModel(shouldDelBuyModel.id) id = modelUtil.insertBuyModel(newBuyModel) newBuyModel.id = id return newBuyModel
def addSymbol(needAdd): logUtil.info("needAdd={}".format(needAdd)) for model in needAdd: logUtil.info("begin add={}".format(model)) kline = huobi.get_kline(model.symbol, model.period, 1000) datas = kline['data'] datas.reverse() for data in datas: commonUtil.addSymbol(data, model, False) logUtil.info("end add={}".format(model))
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 delSymbol(needDel): logUtil.info("needDel={}".format(needDel)) for model in needDel: logUtil.info("begin del={}".format(model)) commonUtil.delSymbol(model) logUtil.info("end del={}".format(model))
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)
lastData = huobi.get_kline(transactionModel.symbol, transactionModel.period, 1) #{'ch': 'market.xrpusdt.kline.1min', 'status': 'ok', 'ts': 1587722033132, # 'data': [{'open': 0.19629, 'id': 1587721980, 'count': 29, 'amount': 36697.23, 'close': 0.1963, 'vol': 7200.5755178, 'high': 0.1963, 'low': 0.19613}]} thisData = huobi.get_kline(transactionModel.symbol, transactionModel.period, 1) if thisData['status'] == 'ok' and thisData['data'] and len( thisData['data']) >= 1: thisData['data'].reverse() else: continue 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) #交割模块处理
import RSIUtil as rSIUtil import MAUtil as mAUtil import commonUtil as commonUtil import BiTradeUtil as biTradeUtil import fileOperUtil as fileOperUtil import BollUtil as bollUtil import AmountUtil as amountUtil import logUtil if __name__ == '__main__': transactionModels = modelUtil.getAllPair() env = "dev" lastIndex = 0 for transactionModel in transactionModels: logUtil.info(transactionModel) kline = huobi.get_kline(transactionModel.symbol, transactionModel.period, 2000) datas = kline['data'] datas.reverse() for data in datas: commonUtil.addSymbol(data ,transactionModel) 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) highFlag = commonUtil.juideHighest(data['close'],transactionModel.symbol) bollFlag = bollUtil.judgeBoll(data['close'],transactionModel.symbol) lowFlag = commonUtil.juideLowest(data['close'],transactionModel.symbol)