def say(): while(1): global k global sell global buy global numvar global trading price=HuobiService.getPrice() price=eval(price) ticker=price['ticker'] sell=round(ticker['sell'],2) buy=round(ticker['buy'],2) if stage==2 or stage==3: if text[1]=='M': if text[0]=='B': numvar=sell if text[0]=='S': numvar=buy if text[1]=='H': numvar=round(((sell+buy)/2),2) if text[1]=='B': if text[0]=='B': numvar=buy if text[0]=='S': numvar=sell global comment ordStatus=HuobiService.getOrders(1,GET_ORDERS) k=k+1 if str(ordStatus)=='[]' and trading==1 and k>=6: k=0 trading=0 comment=comment+'Done!' show(text,sell,buy,stage,way,method,numvar,amounttp,offset,comment) sleep(0.5)
def getBalance(): result = huobi.get_balance(huobi.ACCOUNT_ID) data = result['data'] list = data['list'] for account in list: if account['currency'] == 'usdt' and account['type'] == 'trade': return account['balance']
def sendOrder(amount, price, symbol, types): result = huobi.send_order(amount, "api", symbol, types, price) if result['status'] == 'ok': return result['data'] return 0
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 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 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 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 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 getBalance(bi): balance = huobi.get_balance() data = balance['data'] list = data['list'] for account in list: currency = account['currency'] accountBalance = account['balance'] type = account['type'] if currency == bi and type == 'trade': return accountBalance
def checkOrderIsFilled(env, orderId): if "pro" == env: result = huobi.order_info(orderId) data = result['data'] state = data['state'] if state == 'filled': return True else: return True return False
def checkGetBalance(): balances = HuobiService.get_balance() #print balances tradeBalance = 0 frozenBalance = 0 #print balances for item in balances["data"]["list"]: if item["currency"] == "usdt" and item["type"] == "trade": tradeBalance = item["balance"] if item["currency"] == "usdt" and item["type"] == "frozen": frozenBalance = item["balance"] return jsonify({ "tradeBalance": tradeBalance, "frozenBalance": frozenBalance })
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 getAllOrder(symbol): result = huobi.orders_matchresults(symbol, "buy-limit", "2017-04-09") buyPackage = [] if result['status'] == 'ok': datas = result['data'] for order in datas: index = order['created-at'] price = order['price'] amount = order['filled-amount'] orderId = order['order-id'] transaction = Transaction(price, index, amount, orderId, 0) buyPackage.append(transaction) return buyPackage
def getKline(): symbol = request.args.get("symbol", default="btcusdt") period = request.args.get("period", default="1min") size = request.args.get("size", type=int, default=300) ret = {} data_pre = HuobiService.get_kline(symbol, period, size) kline = [] for item in data_pre["data"]: temp = [] time = ts_to_time(item['id']) temp.append(time) temp.append(item['open']) temp.append(item['close']) temp.append(item['low']) temp.append(item['high']) kline.append(temp) ret['data'] = kline return jsonify(ret)
#from huobi.Util import * #from huobi import HuobiService # from Util import * import HuobiService if __name__ == "__main__": #print "提交限价单接口" #print HuobiService.buy(1,"2355","0.01",None,None,BUY) #print "提交市价单接口" #print HuobiService.buyMarket(2,"30",None,None,BUY_MARKET) #print "取消订单接口" #print HuobiService.cancelOrder(1,68278313,CANCEL_ORDER) print("获取账号详情") print(HuobiService.getAccountInfo(ACCOUNT_INFO)) #print "查询个人最新10条成交订单" #print HuobiService.getNewDealOrders(1,NEW_DEAL_ORDERS) #print "根据trade_id查询order_id" #print HuobiService.getOrderIdByTradeId(1,274424,ORDER_ID_BY_TRADE_ID) #print "获取所有正在进行的委托" #print HuobiService.getOrders(1,GET_ORDERS) #print "获取订单详情" #print HuobiService.getOrderInfo(1,68278313,ORDER_INFO) #print "现价卖出" #print HuobiService.sell(2,"22.1","0.2",None,None,SELL) #print "市价卖出" #print HuobiService.sellMarket(2,"1.3452",None,None,SELL_MARKET)
lastK.append(K) lastJ.append(J) lastD.append(D) if len(lastK)>10: lastK = lastK[1:] lastD = lastD[1:] lastJ = lastJ[1:] last100.append(data['close']) last100.sort() if len(last100) >101: last100 = last100[1:] return isBuy if __name__ == '__main__': test = huobi.get_kline('eosusdt','1min',100) test['data'].reverse() for i in test['data']: judgeBuy(i,test['data'].index(i))
def sellMarket(current_ltc): # 卖出 if float(current_ltc) >= 0.01: print "卖出" HuobiService.sellMarket(2, current_ltc, None, None, SELL_MARKET)
f.close() if __name__ == '__main__': api_key = 'fe31ff24-fcf3-4160-81e9-69f1d0509dc3' spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True) amount = 2.0 symbol = "btmusdt" symbol2 = "BTM-USDT" while True: try: okexResult = spotAPI.get_specific_ticker(symbol2) huobiResult = huobi.get_ticker(symbol) okClose = float(okexResult['last']) huoBiClose = float(huobiResult['tick']['close']) okCharge = okClose * 0.0015 huoBiCharge = huoBiClose * 0.002 charge = okCharge + huoBiCharge logging.info(('okClose={} huoBiClose={} charge={}').format( okClose, huoBiClose, charge)) if (okClose - huoBiClose) > charge: #OK卖出 火币买入 result = spotAPI.take_order('limit', 'sell', symbol2,
def sellit(sellat): print ("限价卖出:"+str(sellat)) print (HuobiService.sell(1,str(sellat),amount,Trade_Pass,None,SELL))
def buyMarket(current_amount): # 买入 if float(current_amount) >= 0.01: print "买入" HuobiService.buyMarket(2, current_amount, None, None, BUY_MARKET)
def buyit(buyat): print ("限价买入:"+str(buyat)) print (HuobiService.buy(1,str(buyat),amount,Trade_Pass,None,BUY))
import HuobiService as huobi if __name__ == '__main__': # A EOS B HT C USDT firstLine = huobi.get_kline('htusdt', '1min', 2000) secondLine = huobi.get_kline('eosusdt', '1min', 2000) threeLine = huobi.get_kline('eosht', '1min', 2000) firstData = firstLine['data'] secondData = secondLine['data'] threeData = threeLine['data'] firstData.reverse() secondData.reverse() threeData.reverse() usdt = 0 ht = 5 eos = 5 balance = 0 buyAmount = 50 fei = 0 for i in range(0, 2000): p1 = float(firstData[i]['close']) p2 = float(secondData[i]['close']) p3 = float(threeData[i]['close']) if (p2 / p1 - p3) > (p3 * 0.003): eos += buyAmount # 买入 EOS
def __getBalanceList(self): result = HuobiService.get_balance(HuobiUtil.ACCOUNT_ID) if result is None or result["status"] != "ok": return None else: return result["data"]["list"]
def hello_world(): #code = getEmails(); #print("您转让点卡的验证码为:"+code); HuobiService.login(); #print(HuobiService.send_ponter_transfer_order(123456,'usdt', '18525424152', "123", "123", 10)) return "hello"
#coding=utf-8 ''' 本程序在 Python 3.3.0 环境下测试成功 使用方法:python HuobiMain.py ''' from Util import * import HuobiService if __name__ == "__main__": print ("获取账号详情") print (HuobiService.getAccountInfo(ACCOUNT_INFO)) print ("获取所有正在进行的委托") print (HuobiService.getOrders(1,GET_ORDERS)) print ("获取订单详情") print (HuobiService.getOrderInfo(1,68278313,ORDER_INFO)) print ("限价买入") print (HuobiService.buy(1,"1","0.01",None,None,BUY)) print ("限价卖出") print (HuobiService.sell(2,"100","0.2",None,None,SELL)) print ("市价买入") print (HuobiService.buyMarket(2,"30",None,None,BUY_MARKET)) print ("市价卖出") print (HuobiService.sellMarket(2,"1.3452",None,None,SELL_MARKET)) print ("查询个人最新10条成交订单") print (HuobiService.getNewDealOrders(1,NEW_DEAL_ORDERS)) print ("根据trade_id查询order_id") print (HuobiService.getOrderIdByTradeId(1,274424,ORDER_ID_BY_TRADE_ID)) print ("取消订单接口") print (HuobiService.cancelOrder(1,68278313,CANCEL_ORDER))
import HuobiService as huobi def writeSymbolRecord(msg): f = open('pairTxt', 'a', encoding='utf-8') f.write("{0}\n".format(msg)) f.flush() f.close() def takeKey(tranPairs): return tranPairs.pvalue if __name__ == '__main__': symbols = huobi.get_symbols() datas = symbols['data'] symbolsList = [] for data in datas: quote_currency = data['quote-currency'] if quote_currency == 'usdt': symbolsList.append(data['symbol']) print(symbolsList) print(len(symbolsList)) pairList = [] for index in range(len(symbolsList)): for index2 in range(index + 1, len(symbolsList)):
def getOrderStatus(orderId): result = huobi.order_info(orderId) data = result['data'] state = data['state'] return state
# -*- coding: utf-8 -*- import HuobiService as huobi import spot_api as spot if __name__ == '__main__': api_key = 'fe31ff24-fcf3-4160-81e9-69f1d0509dc3' spotAPI = spot.SpotAPI(api_key, seceret_key, passphrase, True) test = spotAPI.get_kline('eos-USDT', '', '', 60) data = test data.reverse() print(data) test2 = huobi.get_kline('eosusdt', '1min', 200) data2 = test2['data'] data2.reverse() print(data2) count = 0 amount = 1 for i in range(0, 200): close1 = float(data[i][4]) close2 = float(data2[i]['close']) if close1 > close2: fei = close1 * 0.0015 + close2 * 0.002 gap = close1 - close2 if gap > fei:
isSend = False if buy== 0: if (D<K and lastK<lastD or J>100 ) : isSend = True if J < lastJ and J>50 and J>K: isSend = True return isSend if __name__ == '__main__': fig = plt.figure() symbols = 'eosusdt' test = huobi.get_kline(symbols,'1min',2000) # test = aa.test0 test['data'].reverse() # test = client.getKline(1200,"eos_usdt") xmajorLocator = MultipleLocator(100); klineXY = get_kline_xy(test['data']) klinex = klineXY[0] kliney = klineXY[1] MA60XY = get_MA(test['data'],60) MA30XY = get_MA(test['data'],30) MA10XY = get_MA(test['data'],5)
cash = pd.Series(cash, index=position.index) shareY = pd.Series(shareY, index=position.index) shareX = pd.Series(shareX, index=position.index) asset = cash + shareY * priceY + shareX * priceX account = pd.DataFrame({ 'Position': position, 'ShareY': shareY, 'ShareX': shareX, 'Cash': cash, 'Asset': asset }) return (account) if __name__ == '__main__': firstLine = huobi.get_kline('xlmusdt', '1min', 100) secondLine = huobi.get_kline('omgusdt', '1min', 100) firstLine['data'].reverse() secondLine['data'].reverse() firstData = [] secondData = [] firstCount = 0 secondCount = 0 balance = 0 score = [] firstClose = 0 secondClose = 0 ratioList = [] b = 0
#coding=utf-8 ''' 本程序在 Python 3.3.0 环境下测试成功 使用方法:python HuobiMain.py ''' from Util import * import HuobiService import json if __name__ == "__main__": while (True): res = HuobiService.getDepth() res = json.loads(res)['tick'] print('buy :%.2f' % res['bids'][0][0]) print('sell :%.2f' % res['asks'][0][0]) time.sleep(1) print("获取账号详情") print(HuobiService.getAccountInfo(ACCOUNT_INFO)) print("获取所有正在进行的委托") print(HuobiService.getOrders(1, GET_ORDERS)) print("获取订单详情") print(HuobiService.getOrderInfo(1, 68278313, ORDER_INFO)) print("限价买入") print(HuobiService.buy(1, "1", "0.01", None, None, BUY)) print("限价卖出") print(HuobiService.sell(2, "100", "0.2", None, None, SELL)) print("市价买入") print(HuobiService.buyMarket(2, "30", None, None, BUY_MARKET)) print("市价卖出") print(HuobiService.sellMarket(2, "1.3452", None, None, SELL_MARKET))
import numpy as np import HuobiService as huobi if __name__ == '__main__': symbols = huobi.get_symbols() datas = symbols['data'] symbolsList = [] for data in datas: quote_currency = data['quote-currency'] if quote_currency == 'usdt': symbolsList.append(data['symbol']) print(symbolsList)
import HuobiService as huobi import numpy as np from AmplitudeModel import AmplitudeModel def takeKey(amplitudeModel): return amplitudeModel.amplitude if __name__ == '__main__': symbols = huobi.get_symbols() datas = symbols['data'] symbolsList = [] for data in datas: quote_currency = data['quote-currency'] if quote_currency == 'usdt': symbolsList.append(data['symbol']) amplitudeModelList = [] lineLen = 2000 for symbol in symbolsList: lastClose = 0 kLine = huobi.get_kline(symbol, '15min', lineLen) if kLine is None: continue print(symbol)
def get(): global text global stage global way global method global numvar global offset global amounttp global amount global comment global trading while(1): newchar=getch() if newchar=='=': newchar='+' if newchar.encode('utf')!=b'\x7f': if newchar.isdigit() or newchar.isalpha() or newchar==' ' or newchar=='.' or newchar=='+' or newchar=='-' : newchar=newchar.upper() if stage!=8: if len(text)>=3: if stage==3: if newchar.isdigit(): text=text+newchar offsetnum=eval(text[3:len(text)]) offset=round(pfix*offsetnum/100,2) if len(text)==2: if newchar=='+' or newchar=='-': if newchar=='+': pfix=1 if newchar=='-': pfix=-1 text=text+newchar stage=3 offset=0 if len(text)==1: if newchar=='M': text=text+newchar method=newchar if text[0]=='B': numvar=sell if text[0]=='S': numvar=buy stage=2 if newchar=='H': text=text+newchar method=newchar stage=2 numvar=round(((sell+buy)/2),2) if newchar=='B': text=text+newchar method=newchar if text[0]=='B': numvar=buy if text[0]=='S': numvar=sell stage=2 if stage==8: if newchar.isdigit(): text=text+newchar amounttp=float(text[1:len(text)]) if len(text)==0: if newchar=='S' or newchar=='B' : text=text+newchar way=newchar stage=1 if newchar=='A': text=text+newchar way=newchar stage=8 if newchar.encode('utf')==b'\x03': text='QUIT' quit() if newchar.encode('utf')==b'\n': if stage==8 and len(text)>1: amount=round(amounttp/1000,3) if stage==2 or stage==3: p=round(offset+numvar,2) if way=='S': print(HuobiService.sell(1,str(p),amount,PASSWORD,None,SELL)) comment=comment+'\n Sell'+str(amount)+'BTC at'+str(p)+'...' if way=='B': print(HuobiService.buy(1,str(p),amount,PASSWORD,None,BUY)) comment=comment+'\n Buy'+str(amount)+'BTC at'+str(p)+'...' trading=1 offset=0 text='' stage=0 method='' numvar=0 way='' ###Execution else: text=text[0:len(text)-1] if len(text)==0: stage=0 method='' numvar=0 way='' offset=0 if stage!=8: if len(text)==1: stage=1 method='' numvar=0 offset=0 if len(text)==2: stage=2 offset=0 if len(text)>3 and stage==3: offsetnum=eval(text[3:len(text)]) offset=round(pfix*offsetnum/100,2) if len(text)==3 and stage==3: offset=0 if stage==8: if len(text)==1: amounttp=0 else: amounttp=float(text[1:len(text)]) show(text,sell,buy,stage,way,method,numvar,amounttp,offset,comment) #b'\x7f'
#print HuobiService.getAccountInfo(ACCOUNT_INFO) #print "查询个人最新10条成交订单" #print HuobiService.getNewDealOrders(2,NEW_DEAL_ORDERS) #print "根据trade_id查询order_id" #print HuobiService.getOrderIdByTradeId(1,274424,ORDER_ID_BY_TRADE_ID) #print "获取所有正在进行的委托" #print HuobiService.getOrders(1,GET_ORDERS) #print "获取订单详情" #print HuobiService.getOrderInfo(1,68278313,ORDER_INFO) #print "现价卖出" #print HuobiService.sell(2,"22.1","0.2",None,None,SELL) #print "市价卖出" #print HuobiService.sellMarket(2,"1.3452",None,None,SELL_MARKET) # 获取账号详情 MyInfo = HuobiService.getAccountInfo(ACCOUNT_INFO) # 获取当前余额与莱特币数量,返回Str current_amount = MyInfo["available_cny_display"] # 获取当前莱特币数量 current_ltc = MyInfo["available_ltc_display"] print MyInfo["available_cny_display"], MyInfo["available_ltc_display"] # 获取三分钟内的莱特币走势 ltc_kline_json = requests.get(GET_LTC_KLINE_URL).text ltc_kline_json = json.loads(ltc_kline_json) kline_dict = {} key = 1 for per_ltc_kline in ltc_kline_json: kline_dict[key] = per_ltc_kline[4] - per_ltc_kline[1] key += 1
#coding=utf-8 from Util import * import HuobiService if __name__ == "__main__": print "提交限价单接口" #print HuobiService.buy(1,"2355","0.01",None,None,BUY) print "提交市价单接口" #print HuobiService.buyMarket(2,"30",None,None,BUY_MARKET) print "取消订单接口" #print HuobiService.cancelOrder(1,68278313,CANCEL_ORDER) print "获取账号详情" print HuobiService.getAccountInfo(ACCOUNT_INFO) print "查询个人最新10条成交订单" print HuobiService.getNewDealOrders(1, NEW_DEAL_ORDERS) print "根据trade_id查询order_id" #print HuobiService.getOrderIdByTradeId(1,274424,ORDER_ID_BY_TRADE_ID) print "获取所有正在进行的委托" print HuobiService.getOrders(1, GET_ORDERS) print "获取订单详情" #print HuobiService.getOrderInfo(1,68278313,ORDER_INFO) print "限价卖出" #print HuobiService.sell(2,"22.1","0.2",None,None,SELL) print "市价卖出" #print HuobiService.sellMarket(2,"1.3452",None,None,SELL_MARKET)
amount="0.005" c=0 ping=0 canned=0 Trade_Pass='******' def sellit(sellat): print ("限价卖出:"+str(sellat)) print (HuobiService.sell(1,str(sellat),amount,Trade_Pass,None,SELL)) def buyit(buyat): print ("限价买入:"+str(buyat)) print (HuobiService.buy(1,str(buyat),amount,Trade_Pass,None,BUY)) if __name__ == "__main__": #print("获取所有正在进行的委托") print(HuobiService.getOrders(1,GET_ORDERS)) while(1): sleep(0.3) price=HuobiService.getPrice() price=eval(price) ticker=price['ticker'] sell=round(ticker['sell'],2) buy=round(ticker['buy'],2) print('Ask:'+str(sell)) print('Bid:'+str(buy)) sellat=round(sell-0.02,2) buyat=round(buy+0.02,2) spread=(sell*100-buy*100)/100 print('Spread:'+str(spread)) ordStatus=HuobiService.getOrders(1,GET_ORDERS) if(str(ordStatus)=='[]'):