def buy(amount, symbol): if not DEBUG: HuobiService.send_order(amount, '', symbol, 'buy-market') coinid = symbol.replace('usdt', '') usdtcoins[coinid]['buyprice'] = kline[symbol]['close'] usdtcoins[coinid]['buy'] = True usdtcoins['usdt']['balance'] -= amount usdtcoins[coinid]['balance'] += amount / kline[symbol]['close'] print 'buy', amount, symbol
def sell(amount, symbol): if not DEBUG: HuobiService.send_order(amount, '', symbol, 'sell-market') coinid = symbol.replace('usdt', '') usdtcoins[coinid]['buyprice'] = 0 usdtcoins[coinid]['buy'] = False usdtcoins['usdt']['balance'] += amount * kline[symbol]['close'] usdtcoins[coinid]['balance'] -= amount print 'sell', amount, symbol
def doWork(): period_window = 14 standard_deviation_range = 2 bbands_opt_width_m = 60 prices = np.array(HuobiService.get4hHistoryPrice(COINTYPE_LTC, period_window + bbands_opt_width_m), dtype=float) if len(prices) < period_window + bbands_opt_width_m: print("bar的数量不足,等待下一根bar...") return upper, middle, lower = talib.BBANDS(prices, timeperiod=period_window, nbdevup=standard_deviation_range, nbdevdn=standard_deviation_range, matype=talib.MA_Type.SMA) current_price = HuobiService.getCurrentPrice(COINTYPE_LTC) print("当前价格为:%s,上轨为:%s,下轨为:%s" % (current_price, upper[-1], lower[-1])) if current_price < lower[-1]: print("价格穿越下轨,产生卖出信号") account_info = HuobiService.getAccountInfo(ACCOUNT_INFO) if float(account_info['available_ltc_display']) > MIN_UNIT_LTC: print("正在卖出,卖出数量为%s" % account_info['available_ltc_display'].encode("utf-8")) print HuobiService.sellMarket(COINTYPE_LTC, account_info['available_ltc_display'], None, None, SELL_MARKET) else: print("仓位不足,无法卖出") elif current_price > upper[-1]: print("价格穿越上轨,产生买入信号") account_info = HuobiService.getAccountInfo(ACCOUNT_INFO) if float(account_info['available_cny_display']) > MIN_UNIT_LTC * current_price: print("正在买入,下单金额为%s元" % account_info['available_cny_display'].encode("utf-8")) print HuobiService.buyMarket(COINTYPE_LTC, account_info['available_cny_display'], None, None, BUY_MARKET) else: print("现金不足,无法下单") else: print("无交易信号,进入下一根bar")
def get_order_status(order_id, order_price): while True: resp = HuobiService.getOrderInfo(1, order_id, ORDER_INFO) if resp is not None and 'msg' not in resp and 'status' in resp: return resp break sleep_time = get_sleep_time(abs(CURR_PRICE - order_price)) sleep(sleep_time)
def get_huobi_price_old(symbol, prin): huobi_price = 0 try: huobi_content = HuobiService.get_trade(symbol) huobi_price = huobi_content["tick"]["data"][0]["price"] if prin: print json.dumps(huobi_content, default=map) except Exception, e: print "获取火币的%s价格出错:%s" % (symbol, e.message)
def sure_cancel(order_id): while True: resp = HuobiService.cancelOrder(1, order_id, CANCEL_ORDER) if resp is not None and 'result' in resp: break if resp is not None and 'msg' in resp: if resp['msg'] == unicode('该委托不存在', "utf-8"): break sleep(3)
def sure_order_success(coin_type, order_id, order_price): global CURR_PRICE while True: resp = HuobiService.getOrderInfo(coin_type, order_id, ORDER_INFO) # print resp if resp is not None and 'msg' not in resp and 'status' in resp: # all success if resp['status'] == 2: break sleep_time = get_sleep_time(abs(CURR_PRICE - order_price)) sleep(sleep_time)
def get_coin_balance(coin): balance = HuobiService.get_balance() result = 0 for e in balance["data"]["list"]: if e["type"] == "trade" and e["currency"] == coin: # result = float(int(float(e["balance"]) * 10000)) / 10000 result = common_utils.get_round(float(e["balance"]), 4) if result: # 获取到想要的值, 跳出循环 break return result
def get_buy_count(order_id): orders = HuobiService.order_matchresults(order_id) if orders['status'] == 'ok': count = 0 for i in xrange(len(orders['data'])): count = count + float(orders['data'][i]['filled-amount']) - float( orders['data'][i]['filled-fees']) return count else: # 如果一次不成功, 再试一次 orders = HuobiService.order_matchresults(order_id) if orders['status'] == 'ok': count = 0 for i in xrange(len(orders['data'])): count = count + orders['data'][i]['filled-amount'] - orders[ 'data'][i]['filled-fees'] return count else: # 第二次还不成功, 返回-1 return -1
def sure_buy(price, amount): trade_id = 0 resp = {} while True: trade_id = int(1000000 * random()) amount = format_amount(amount) resp = HuobiService.buy(1, str(price), str(amount), None, trade_id, BUY) # print resp if resp is not None and 'msg' not in resp and 'id' in resp: break sleep(1) return trade_id, resp['id']
def sell_soc(sell_nums): # 限价卖 币币交易使用‘spot’账户的 # buy_soc_result = HuobiService.send_order(amount = "1",source = "api", symbol = "socusdt",_type = "sell-limit",price = "0.0650") # 市价卖 sell_result = HuobiService.send_order(amount=str(sell_nums), source="api", symbol="socusdt", _type="sell-market") print common_utils.get_json(sell_result, map) if sell_result["status"] == "ok": return str(sell_result["data"]) return ""
def get_coin_balance(coin): if not is_debug: # 正式请求 balance = HuobiService.get_balance() if balance['status'] == 'ok': result = 0 for e in balance["data"]["list"]: if e["type"] == "trade" and e["currency"] == coin: # result = float(int(float(e["balance"]) * 10000)) / 10000 result = common_utils.get_round(float(e["balance"]), 2) if result: # 获取到想要的值, 跳出循环 break return result else: time.sleep(2) # 第一次请求失败, 再试一次 balance = HuobiService.get_balance() if balance['status'] == 'ok': result = 0 for e in balance["data"]["list"]: if e["type"] == "trade" and e["currency"] == coin: # result = float(int(float(e["balance"]) * 10000)) / 10000 result = common_utils.get_round(float(e["balance"]), 2) if result: # 获取到想要的值, 跳出循环 break return result else: # 第二次还失败, 这里停掉程序 return -100 else: # 测试模式, 设置 回测的数据 json_count = common_utils.read_json("debug_count.json") if "soc" == coin: return json_count['soc_count'] if "wicc" == coin: return json_count['wicc_count'] return -100
def buy_wicc(): usdt_balance = get_coin_balance("usdt") print common_utils.get_json(usdt_balance, map) if usdt_balance: # 这里不抓异常, 出错就把程序停掉, 避免更大的损失 buy_result = HuobiService.send_order(usdt_balance, source="api", symbol="wiccusdt", _type="buy-market") print common_utils.get_json(buy_result, map) if buy_result["status"] == "ok": return str(buy_result["data"]) return ""
def sell_wicc(sell_nums): # 限价卖 币币交易使用‘spot’账户的 # buy_soc_result = HuobiService.send_order(amount = "1",source = "api", symbol = "wiccusdt",_type = "sell-limit",price = "0.0650") # 市价卖 print "sell_wicc方法中sell_nums:%s" % (str(sell_nums)) sell_result = HuobiService.send_order(amount=float(sell_nums), source="api", symbol="wiccusdt", _type="sell-market") print common_utils.get_json(sell_result, map) if sell_result["status"] == "ok": return True return False
def sure_sell(price, amount): trade_id = 0 resp = {} while True: trade_id = int(1000000 * random()) amount = format_amount2(amount) # print "before sell" resp = HuobiService.sell(1, str(price), str(amount), None, trade_id, SELL) # print resp # a bug resp can be none if resp is not None and 'msg' not in resp and 'id' in resp: break sleep(1) return trade_id, resp['id']
def sure_order_success(coin_type, order_id, order_price, is_forword=False): global CURR_PRICE while True: resp = HuobiService.getOrderInfo(coin_type, order_id, ORDER_INFO) # print resp if resp is not None and 'msg' not in resp and 'status' in resp: # all success if resp['status'] == 2: return float(resp['processed_price']) diff = abs(CURR_PRICE - order_price) if diff > 10 and is_forword: return False #means this order_price is far away from current_price sleep_time = get_sleep_time(diff) sleep(sleep_time)
def get_soc_wicc_day_prices(): # 2018-09-12 今天取前百日(本来想取200, 但是soc和wicc对usdt的交易没这么多数据)的数据算出 k = 9.0902; n = 0.0468 # soc_kline = HuobiService.get_kline("socusdt", "1day", "100") ''' 2018-09-18 11:11 今天取百日数据算的 k = 6.9950; n = 0.1150; 用这组数据回测收益较低, 所以这里取106日的数据试试 2018-09-18 106日的数据算出来 k = 9.1002; n = 0.0458 ''' days = 106 soc_kline = HuobiService.get_kline("socusdt", "1day", "%d" % days) soc_day_prices = [] for soc_bean in soc_kline['data']: soc_day_prices.append(float(soc_bean['close'])) print soc_day_prices common_utils.write_json("soc_day_prices.txt", soc_day_prices, list) time.sleep(5) wicc_kline = HuobiService.get_kline("wiccusdt", "1day", "%d" % days) wicc_day_prices = [] for wicc_bean in wicc_kline['data']: wicc_day_prices.append(float(wicc_bean['close'])) print wicc_day_prices common_utils.write_json("wicc_day_prices.txt", wicc_day_prices, list)
def get_huobi_price(symbol, prin): # 买盘价格 buy_price = 0 sell_price = 0 try: huobi_content = HuobiService.get_depth(symbol, 'step0') # 这里拿的是买盘的第二个价格 buy_price = huobi_content["tick"]["bids"][1][0] # 这里拿的是卖盘的第二个价格 sell_price = huobi_content["tick"]["asks"][1][0] if prin: print json.dumps(huobi_content, default=map) except Exception, e: print "获取火币的%s价格出错:%s" % (symbol, e.message)
def __init__(self, uid): try: ticker_ltc = requests.get( r'http://api.huobi.com/staticmarket/ticker_ltc_json.js', timeout=5) self.ticker_ltc = json.loads(ticker_ltc.text) ticker_ltc.close() self.account_info = HuobiService.getAccountInfo(ACCOUNT_INFO) self.getOrder = HuobiService.getOrders(2, GET_ORDERS) #卖单数量 self.sellOne_count = [ order for order in self.getOrder if order['type'] == 2 ] #买单数量 self.buyOne_count = [ order for order in self.getOrder if order['type'] == 1 ] #已完成的委托 self.dealOrders = HuobiService.getNewDealOrders(2, NEW_DEAL_ORDERS) #资产折合 self.total = float(self.account_info['total']) #卖一价 self.limit_price = self.ticker_ltc['ticker']['sell'] #买一价 self.buyone_price = self.ticker_ltc['ticker']['buy'] #总量 self.trade_total = self.ticker_ltc['ticker']['vol'] #限制挂单数量 self.orderCount = self.handler_orderCount() #可用资金 self.a_cny_display = float( self.account_info['available_cny_display']) #可用莱特币 self.a_ltc_display = float( self.account_info['available_ltc_display']) except BaseException as e: print u'无法获取数据', e
def get_soc_wicc_balance(): balance = HuobiService.get_balance() soc_balance = 0 wicc_balance = 0 for e in balance["data"]["list"]: if e["type"] == "trade" and e["currency"] == "soc": soc_balance = int(float(e["balance"])) if e["type"] == "trade" and e["currency"] == "wicc": wicc_balance = int(float(e["balance"])) if soc_balance and wicc_balance: break j_balance = common_utils.get_json(balance, map) # print j_balance print "soc_balance = %s; wicc_balance = %s" % (str(soc_balance), str(wicc_balance))
def getAccountInfo(): result = {} result['huobi'] = {} account = HuobiService.accountInfo() for info in account['data']['list']: if (info['currency'] == 'cny' and info['type'] == 'trade'): result['huobi']['cny'] = info['balance'] if (info['currency'] == 'etc' and info['type'] == 'trade'): result['huobi']['etc'] = info['balance'] result['okcoin'] = {} okcoinSpot = OKCoinSpot() account = okcoinSpot.userinfo() result['okcoin']['cny'] = account['info']['funds']['free']['cny'] result['okcoin']['etc'] = account['info']['funds']['free']['etc'] return result
from huobi.Util import * from huobi import HuobiService if __name__ == "__main__": ret = HuobiService.sell(1, 8000, 0.0038, "", 11, SELL) print ret #ret = HuobiService.getOrderIdByTradeId(1, 2, ORDER_ID_BY_TRADE_ID) #ret = HuobiService.getOrderInfo(1, ret['id'], ORDER_INFO) #print(ret)
def get_balance(): if not DEBUG: return HuobiService.get_balance()['data']['list'] else: return {'usdt': {'type': 'trace', 'balance': 10000.0}}
def on_minute(): global kline, usdt, buythresh, sellupthresh, selldownthresh Timer(60, on_minute).start() curtime = int(time()) # 更新价格 try: for symbol in kline: klinedata = HuobiService.get_kline(symbol, '1min', 1)['data'][0] kline[symbol]['time'] = klinedata['id'] kline[symbol]['high'] = klinedata['high'] kline[symbol]['low'] = klinedata['low'] kline[symbol]['open'] = klinedata['open'] kline[symbol]['close'] = klinedata['close'] print symbol, kline[symbol], kline[symbol] if curtime - klinedata['id'] > 120: print 'Time different from server:', symbol coinid = symbol.replace('usdt', '') # 如果购买则更新maxprice if coinid in usdtcoins and usdtcoins[coinid]['buy']: if klinedata['high'] > usdtcoins[coinid]['maxprice']: usdtcoins[coinid]['maxprice'] = klinedata['high'] except Exception as e: print 'Error in get_kline', e.message return # 更新当前货币量 try: balancedata = get_balance() for item in balancedata: if item['type'] == 'trace' and ( item['currency']) in usdtcoins: # 不算冻结资金 usdtcoins[item]['balance'] = float(item['balance']) except Exception as e: pass # 检测哪些币要卖 buyable_symbols = [] for symbol in kline: # 策略2 => 1分钟内涨幅降幅超过各自门限的多个币 均摊 optype = 'none' # none buy sell if symbol.endswith('usdt') and symbol != 'usdt': coinid = symbol.replace('usdt', '') op = kline[symbol]['open'] # 开盘价 cp = kline[symbol]['close'] # 收盘价 bp = usdtcoins[coinid]['buyprice'] mp = usdtcoins[coinid]['maxprice'] if cp / op > buythresh: # 涨到一定程度则入手 buyable_symbols.append(symbol) #elif bp > 0.0 and (cp / bp > sellupthresh or cp / bp < selldownthresh): # 已经入手且降到一定程度则出手 # optype = 'buy-market' elif mp > 0.0 and cp / mp < selldownthresh: # 市价卖出,清除数据 sell(usdtcoins[coinid]['balance'], symbol) usdtcoins[coinid] = { 'buyprice': 0.0, 'maxprice': 0.0, 'balance': 0.0, 'optype': 'none' } # 更新卖出后的usdt数量 #需要等待吗? usdtamount = 0.0 try: balancedata = get_balance() for item in balancedata: coinid = item['currency'] if item['type'] == 'trace' and coinid in usdtcoins: # 不算冻结资金 usdtcoins[item]['balance'] = float(item['balance']) if coinid == 'usdt': usdtamount = float(item['balance']) except Exception as e: pass if usdtamount > 1.0 and len(buyable_symbols) > 0: # 如果有可买货币则进行对冲 splitamount = usdtamount / len(buyable_symbols) for symbol in buyable_symbols: coinid = symbol.replace('usdt', '') buy(splitamount, symbol) usdtcoins[coinid]['buy'] = True
#coding=utf-8 from huobi.Util import * from huobi 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)
# soc_kline = HuobiService.get_kline("socusdt", "1day", "100") ''' 2018-09-18 11:11 今天取百日数据算的 k = 6.9950; n = 0.1150; 用这组数据回测收益较低, 所以这里取106日的数据试试 2018-09-18 106日的数据算出来 k = 9.1002; n = 0.0458 ''' days = 106 soc_kline = HuobiService.get_kline("socusdt", "1day", "%d" % days) soc_day_prices = [] for soc_bean in soc_kline['data']: soc_day_prices.append(float(soc_bean['close'])) print soc_day_prices common_utils.write_json("soc_day_prices.txt", soc_day_prices, list) time.sleep(5) wicc_kline = HuobiService.get_kline("wiccusdt", "1day", "%d" % days) wicc_day_prices = [] for wicc_bean in wicc_kline['data']: wicc_day_prices.append(float(wicc_bean['close'])) print wicc_day_prices common_utils.write_json("wicc_day_prices.txt", wicc_day_prices, list) if __name__ == "__main__": print "test main start" # get_soc_wicc_day_prices() # content = HuobiService.orders_matchresults("socusdt") # 12350913620 content = HuobiService.order_matchresults("12808178820") print common_utils.get_json(content, map)
def getCurrentPrice(): print HuobiService.getCurrentMarket()['ticker']['last']
#coding=utf-8 from huobi.Util import * from huobi import HuobiService if __name__ == "__main__": print "提交限价单接口" ret = HuobiService.buy(1, "6000", "0.01", None, None, BUY) print ret['msg'] #解析回傳訊息成中文 print ret['message'] #解析回傳訊息成中文 # 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(1,"7300","0.2",None,None,SELL) # print "市价卖出" # print HuobiService.sellMarket(2,"1.3452",None,None,SELL_MARKET)
def get_current_price(): return HuobiService.getCurrentMarket()['ticker']['last']
# coding=utf-8 ''' 本程序在 Python 3.3.0 环境下测试成功 使用方法:python HuobiMain.py ''' from huobi import HuobiService from .Util import * 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))
def test(): ret = HuobiService.getCurrentMarket() print ret