def __init__(self): BaseStrategy.__init__(self) FileReadAndWrite.__init__(self) self.request_client = RequestClient(api_key=self.get_config_value("huobi", "api_key"), secret_key=self.get_config_value("huobi", "secret_key")) self.strategy = 'KeepBalance' self.timeout = float(self.get_config_value("strategy", "timeout"))
def make_order(symbol=CoinSymbol.Btcusdt, sell=True, amount=0): try: request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) if not test_flag: if sell: order_id = request_client.create_order(symbol.symbol, AccountType.MARGIN, OrderType.SELL_MARKET, amount, price=0) else: order_id = request_client.create_order(symbol.symbol, AccountType.MARGIN, OrderType.BUY_MARKET, amount, price=0) else: print("test mode on") order_info.order_id = order_id except Exception as e: print(e) print("retrying in 1s") time.sleep(1) return make_order()
def get_latest_price(symbol=CoinSymbol.Btcusdt): try: request_client = RequestClient() depth = request_client.get_price_depth(symbol.symbol, 1) market_info.bid = depth.bids[0].price market_info.ask = depth.asks[0].price average_price = (depth.bids[0].price + depth.asks[0].price) / 2 return average_price except Exception as e: print(e) print("retrying in 1s") time.sleep(1) return get_latest_price()
def __init__(self, logger): self.logger = logger self.api = RequestClient(url="https://api-aws.huobi.pro", api_key=g_api_key, secret_key=g_secret_key) self.buy_price = 7314 self.profit = 100 self.avg_price = 0 self.open_price = 0 self.ask = 0 self.bid = 0 self.second_max = 0 self.second_min = 0 self.max = 0 self.min = 0
def __init__(self, logger, wechat): self.logger = logger self.api = RequestClient(url="https://api-aws.huobi.pro", api_key=g_api_key, secret_key=g_secret_key) self.buy_price = 7314 self.profit = 100 self.init_balance = 1.257 self.update_interval = 6 * 60 self.avg_price = 0 self.open_price = 0 self.ask = 0 self.bid = 0 self.second_max = 0 self.second_min = 0 self.second_max_t = datetime.datetime.now() self.second_min_t = datetime.datetime.now() self.wechat = wechat self.orders = queue.Queue() self.status_thread = StatusThread(self.api, self.init_balance, self.orders, logger, wechat) self.status_thread.start()
def get_account_balance(symbol=CoinSymbol.Btcusdt): try: request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) account_balance_list = request_client.get_account_balance() if account_balance_list and len(account_balance_list): for account in account_balance_list: if account.account_type == AccountType.MARGIN and account.subtype == symbol.symbol: if account.balances and len(account.balances): for balance in account.balances: if balance.currency == CoinSymbol.Btcusdt.coin and balance.balance_type == "trade": balance_info.coin = balance.balance if balance.currency == CoinSymbol.Btcusdt.cash and balance.balance_type == "trade": balance_info.cash = balance.balance except Exception as e: print(e) print("retrying in 1s") time.sleep(1) return get_account_balance()
def getloaninfo(symbol=CoinSymbol.Btcusdt): request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) try: result_list = request_client.get_margin_loan_info(symbol.symbol) if result_list and len(result_list): for loan_item in result_list: for item_info in loan_item.currencies: if item_info.currency == symbol.coin: loan_info.coin = item_info.loanable_amt loan_info.min_coin = item_info.min_loan_amt if item_info.currency == symbol.cash: loan_info.cash = item_info.loanable_amt loan_info.min_cash = item_info.min_loan_amt return loan_info except Exception as e: print(e) print("retrying in 1s") time.sleep(1) return getloaninfo()
def __init__(self, logger, wechat): self.logger = logger self.api = RequestClient(url="https://api-aws.huobi.pro", api_key=g_api_key, secret_key=g_secret_key) self.buy_price = 7314 self.profit = 300 self.init_balance = 1.257 self.update_interval = 6 * 60 self.avg_price = 0 self.open_price = 0 self.ask = 0 self.bid = 0 self.wechat = wechat self.lastTd = None self.resetCountdownOnTDST = True self.resetSetupCounterAfterCountdownHit13 = True self.result = list() self.orders = queue.Queue() self.status_thread = StatusThread(self.api, self.init_balance, self.orders, logger, wechat) self.status_thread.start()
def postloan(symbol=CoinSymbol.Btcusdt, currency="coin", amount=0.02): if currency == "coin": currency = symbol.coin if loan_info.min_coin > amount or amount > loan_info.coin: return False if currency == "cash": currency = symbol.cash or amount > loan_info.cash if loan_info.min_cash > amount: return False try: request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) loan_order_id = request_client.apply_loan(symbol=symbol.symbol, currency=currency, amount=amount) PrintBasic.print_basic(loan_order_id, "Loan Order Id") except Exception as e: print(e) print("retrying in 1s") time.sleep(1) return postloan()
from huobi import RequestClient request_client = RequestClient() depth = request_client.get_price_depth("btcusdt", 5) print("---- Top 5 bids ----") i = 0 for entry in depth.bids: i = i + 1 print( str(i) + ": price: " + str(entry.price) + ", amount: " + str(entry.amount)) print("---- Top 5 asks ----") i = 0 for entry in depth.asks: i = i + 1 print( str(i) + ": price: " + str(entry.price) + ", amount: " + str(entry.amount))
from huobi import RequestClient from huobi.constant.test import * def print_obj_list(list_obj): if list_obj and len(list_obj): for obj in list_obj: obj.print_object() print() client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) list_obj = client.get_account_deposit_address(currency="usdt") print_obj_list(list_obj)
from huobi import RequestClient from huobi.constant.test import * request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) account_history_list = request_client.get_account_history(account_id=g_account_id) if account_history_list and len(account_history_list): for account_history in account_history_list: account_history.print_object() print()
from huobi import RequestClient from huobi.constant.test import * from huobi.base.printobject import * from huobi.model import Account request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) account_balance_list = request_client.get_account_balance() if account_balance_list and len(account_balance_list): for account in account_balance_list: print("======= ID", account.id, "=======") print("Account Status", account.account_state) print("Account Type", account.account_type) print("Subtype", account.subtype) if account.balances and len(account.balances): for balance in account.balances: print("\tBalance Currency", balance.currency) print("\tBalance Type", balance.balance_type) print("\tBalance", balance.balance) print() print()
from huobi import RequestClient request_client = RequestClient() trade_list = request_client.get_historical_trade("btcusdt", 5) for trade in trade_list: print("Trade at: " + str(trade.timestamp)) print("Id: " + str(trade.trade_id)) print("Price: " + str(trade.price)) print("Amount: " + str(trade.amount)) print("Direction: " + trade.direction) print()
from huobi import RequestClient from huobi.constant.test import * request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) market_ticker_list = request_client.get_market_tickers() if market_ticker_list and len(market_ticker_list): for market_ticker in market_ticker_list: market_ticker.print_object() print()
from huobi import RequestClient from huobi.constant.test import * from huobi.model import * request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) symbol_test = "btcusdt" order_id = request_client.create_order(symbol_test, AccountType.MARGIN, OrderType.BUY_LIMIT, amount=0.001, price=8800) print(order_id) request_client.cancel_order(symbol_test, order_id)
from huobi import RequestClient from huobi.model import * from huobi.base.printobject import PrintMix request_client = RequestClient() symbol_list = request_client.get_exchange_symbol_list() PrintMix.print_data(symbol_list)
from huobi import RequestClient from huobi.model import * from huobi.base.printobject import PrintMix request_client = RequestClient(api_key="xxxxxx", secret_key="xxxxxx") orders = request_client.get_historical_orders(symbol="eosht", order_state=OrderState.CANCELED, order_type=None, start_date=None, end_date=None, start_id=None, size=None) PrintMix.print_data(orders)
from huobi import RequestClient from huobi.constant.test import * from huobi.model import * from huobi.base.printobject import PrintMix request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) match_list = request_client.get_match_result(symbol="eosusdt") PrintMix.print_data(match_list)
from huobi import RequestClient from huobi.constant.test import * """ GET https://status.huobigroup.com/api/v2/summary.json """ request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) system_status = request_client.get_system_status() print(system_status)
class Trader(): def __init__(self, logger, wechat): self.logger = logger self.api = RequestClient(url="https://api-aws.huobi.pro", api_key=g_api_key, secret_key=g_secret_key) self.buy_price = 7314 self.profit = 100 self.init_balance = 1.257 self.update_interval = 6 * 60 self.avg_price = 0 self.open_price = 0 self.ask = 0 self.bid = 0 self.second_max = 0 self.second_min = 0 self.second_max_t = datetime.datetime.now() self.second_min_t = datetime.datetime.now() self.wechat = wechat self.orders = queue.Queue() self.status_thread = StatusThread(self.api, self.init_balance, self.orders, logger, wechat) self.status_thread.start() def get_float(self, f_str, n): f_str = str(f_str) a, b, c = f_str.partition('.') c = (c + "0" * n)[:n] tmp = ".".join([a, c]) return float(tmp) def trade(self): self.update_candles() time.sleep(6) result = self.desicion() self.do_trade(result) def get_current_price(self, symbol="btcusdt"): return self.api.get_best_quote(symbol) def update_candles(self): ct = datetime.datetime.now() if self.ask > 0 and (ct - self.second_max_t).seconds < self.update_interval and (ct - self.second_min_t).seconds < self.update_interval: return candles = self.api.get_candlestick("btcusdt", CandlestickInterval.MIN60, 7) highs = [candle.high for candle in candles] lows = [candle.low for candle in candles] highs.sort() lows.sort() self.second_max = highs[-2] self.second_min = lows[1] self.logger.info("【更新】second_max:" + str(self.second_max)) self.logger.info("【更新】second_min:" + str(self.second_min)) def desicion(self, symbol="btcusdt"): current = self.get_current_price(symbol) self.ask = current.ask_price #卖1 self.bid = current.bid_price #买1 self.logger.info("买1:" + str(self.bid)) self.logger.info("卖1:" + str(self.ask)) if self.ask >= self.second_max and self.ask - self.buy_price > self.profit: return TradeOpt.Sell elif self.bid <= self.second_min: return TradeOpt.Buy return TradeOpt.Hold def do_trade(self, opt, symbol="btcusdt"): if opt == TradeOpt.Hold: return if opt == TradeOpt.Sell: position = self.api.get_position() position = self.get_float(position, 2) self.wechat.send_message("【决策】:卖出\n") if position <= 0.01: self.wechat.send_message("仓位不足:" + str(position)) return order = self.api.create_order(symbol=symbol, account_type=AccountType.SPOT, order_type=OrderType.SELL_LIMIT, amount=position, price=self.ask) message = "【新建订单】\n 方向:卖出\n 数量:{0}\n 价格:{1}".format(position, self.ask) self.wechat.send_message(message) self.orders.put(order) else: self.wechat.send_message("【决策】:买入\n") cash = self.api.get_cash() if cash < 20: self.wechat.send_message("现金不足:" + str(cash)) return amount = cash / self.bid amount = self.get_float(amount, 2) order = self.api.create_order(symbol=symbol, account_type=AccountType.SPOT, order_type=OrderType.BUY_LIMIT, amount=amount, price=self.bid) self.buy_price = self.bid message = "【新建订单】\n 方向:买入\n 数量:{0}\n 价格:{1}".format(amount, self.bid) self.wechat.send_message(message) self.orders.put(order)
from huobi import RequestClient from huobi.constant.test import * from huobi.base.printobject import PrintMix from huobi.model import QueryDirection request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) result = request_client.get_deposit_history(currency=None, from_id=0, size=100, direct=QueryDirection.PREV) if result and len(result): for row in result: row.print_object()
from huobi import RequestClient from huobi.constant.test import * from huobi.model import * request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) symbol_test = "eosusdt" order_id = request_client.create_order(symbol_test, AccountType.SPOT, OrderType.BUY_LIMIT, amount=1, price=1.011) print(order_id) request_client.cancel_order(symbol_test, order_id) symbol_test = "xrpusdt" order_id = request_client.create_order(symbol_test, AccountType.MARGIN, OrderType.BUY_LIMIT, amount=101, price=0.01) print(order_id) request_client.cancel_order(symbol_test, order_id) symbol_test = "xrpusdt" order_id = request_client.create_order(symbol_test, AccountType.SUPER_MARGIN, OrderType.BUY_LIMIT, amount=101, price=0.011) print(order_id)
class OrderRouter(object): def __init__(self, apikey, secretkey, password): self._api = RequestClient(api_key=apikey, secret_key=secretkey) self.account_type = AccountType.SPOT def _format_instrument_id(self, instrument_id): return instrument_id.lower().replace('-', '') def _decode_type(self, order_type): if not order_type: return None, None tmp = order_type.split('-') side = tmp[0] o_type = tmp[1] if side not in ['buy', 'sell']: side = None if o_type not in ['limit', 'market', 'ioc']: o_type = None return side, o_type def _decode_state(self, state): if state == 'submitted': return 'open' return state def _timestamp_to_datetime(self, timestamp): return datetime.datetime.fromtimestamp((timestamp + 28800000) / 1000) def _format_order(self, instrument_id, order_info): def fill_obj(o): side, o_type = self._decode_type(o.order_type) return { 'instrument_id': instrument_id, 'order_id': str(o.order_id), 'client_oid': '', 'price': o.price, 'size': o.amount, 'timestamp': o.created_timestamp, 'finished_timestamp': o.finished_timestamp, 'finished_datetime': self._timestamp_to_datetime(o.finished_timestamp), 'canceled_timestamp': o.canceled_timestamp, 'datetime': self._timestamp_to_datetime(o.created_timestamp), 'filled_size': o.filled_amount, 'filled_notional': o.filled_cash_amount, 'side': side, 'type': o_type, 'state': o.state, 'status': self._decode_state(o.state), 'created_at': datetime.datetime.now(), 'updated_at': datetime.datetime.now() } if isinstance(order_info, list): ret = [] for o in order_info: ret.append(fill_obj(o)) else: ret = fill_obj(order_info) return ret def check_position(self, symbol): psss def submit_spot_order(self, client_oid, type, side, instrument_id, price, size, notional, order_type='0', timeout=20, wait_flag=False): instrument_id = self._format_instrument_id(instrument_id) order_type = '{}-{}'.format(param['side'], param['type']) order_id = self._api.create_order(instrument_id, self.account_type, order_type, size, price) return {'order_id': order_id} # take orders # 市价单 # params = [ # {"client_oid":"20180728","instrument_id":"btc-usdt","side":"sell","type":"market"," size ":"0.001"," notional ":"10001","margin_trading ":"1"}, # {"client_oid":"20180728","instrument_id":"btc-usdt","side":"sell","type":"limit"," size ":"0.001","notional":"10002","margin_trading ":"1"} # ] # 限价单 # params = [ # {"client_oid":"20180728","instrument_id":"btc-usdt","side":"sell","type":"limit","size":"0.001","price":"10001","margin_trading ":"1"}, # {"client_oid":"20180728","instrument_id":"btc-usdt","side":"sell","type":"limit","size":"0.001","price":"10002","margin_trading ":"1"} # ] def submit_orders(self, params): ret = [] for param in params: instrument_id = self._format_instrument_id(param['instrument_id']) order_type = '{}-{}'.format(param['side'], param['type']) try: order_id = self._api.create_order(instrument_id, self.account_type, order_type, param['size'], param['price']) order_id = str(order_id) print('submit order id: {}, order_type: {}, price: {}'.format( order_id, order_type, param['price'])) ret.append({ 'order_id': order_id, 'side': param['side'], 'price': param['price'] }) except Exception as e: print('submit_orders err: {}'.format(e)) print('account type:{}, order_type:{}, size:{}, price:{}'.format(self.account_type, order_type, param['size'], param['price'])) time.sleep(0.01) return ret def get_order_info(self, order_id, instrument_id, client_oid=''): order_info = self._api.get_order( self._format_instrument_id(instrument_id), order_id) return self._format_order(instrument_id, order_info) def cancel_order(self, order_id, instrument_id): return self._api.cancel_order( self._format_instrument_id(instrument_id), order_id) # revoke orders # params example: # [ # {"instrument_id":"btc-usdt","order_ids":[1600593327162368,1600593327162369]}, # {"instrument_id":"ltc-usdt","order_ids":[243464,234465]} # ] def cancel_orders(self, params): ret = [] for param in params: instrument_id = self._format_instrument_id(param['instrument_id']) ret.append( self._api.cancel_orders(instrument_id, param['order_ids'])) time.sleep(0.01) return ret def get_orders_pending(self, instrument_id): ret = [] open_orders = self._api.get_open_orders( self._format_instrument_id(instrument_id), self.account_type, size=100) return self._format_order(instrument_id, open_orders) def get_kline(self, instrument_id, start, end, granularity): pass def get_ticker(self, instrument_id): last_trade = self._api.get_last_trade( self._format_instrument_id(instrument_id)) return {'last': last_trade.price} def get_coin_info(self, instrument_id='all'): # TODO 把sdk方法get_exchange_info的symobl和currency分离出来 exchange_info = self._api.get_exchange_info() symbol_list = exchange_info.symbol_list for sl in symbol_list: if sl.symbol == self._format_instrument_id(instrument_id): return { 'instrument_id': instrument_id, 'base_currency': sl.base_currency, 'quote_currency': sl.quote_currency, 'tick_size': sl.price_precision, 'size_increment': sl.amount_precision } return None def get_account_info(self): account_balances = self._api.get_account_balance_by_account_type( self.account_type) details_obj = {} for b in account_balances.balances: if b.balance: if b.currency not in details_obj: if b.balance_type == BalanceType.TRADE: details_obj[b.currency] = { 'currency': b.currency.upper(), 'frozen': 0, 'balance': b.balance, 'available': b.balance } elif b.balance_type == BalanceType.FROZEN: details_obj[b.currency] = { 'currency': b.currency.upper(), 'frozen': b.balance, 'balance': b.balance, 'available': 0 } else: if b.balance_type == BalanceType.TRADE: details_obj[b.currency]['available'] += b.balance details_obj[b.currency]['balance'] += b.balance elif b.balance_type == BalanceType.FROZEN: details_obj[b.currency]['frozen'] += b.balance details_obj[b.currency]['balance'] += b.balance return list(details_obj.values()) def get_coin_account_info(self, symbol): balances = self._api.get_account_balance_by_account_type( self.account_type) ret = {'currency': symbol, 'frozen': 0, 'balance': 0, 'available': 0} for b in balances.get_balance(symbol.lower()): if b.balance_type == BalanceType.TRADE: ret['balance'] += b.balance ret['available'] = b.balance elif b.balance_type == BalanceType.FROZEN: ret['balance'] += b.balance ret['frozen'] = b.balance return ret def get_coin_balance(self, symbol): return self.get_coin_account_info(symbol)['balance'] def get_coin_available(self, symbol): return self.get_coin_account_info(symbol)['available'] def get_oneday_orders(self, instrument_id, stime, state): if stime > datetime.datetime.now(): return [] start_date = stime.strftime('%Y-%m-%d') end_date = start_date # (stime + datetime.timedelta(days=1)).strftime('%Y-%m-%d') orders = [] start_id = None size = 100 format_instrument_id = self._format_instrument_id(instrument_id) while True: order = self._api.get_historical_orders( format_instrument_id, state, start_date=start_date, end_date=end_date, start_id=start_id, size=size) #print('Fetched orders, date: {}, pair: {}, total: {}'.format(start_date, instrument_id, len(order))) format_orders = self._format_order(instrument_id, order) orders += format_orders # print('Fetched orders, pair: %s, total: %d', instrument_id, len(format_orders)) if len(format_orders) < size: break else: start_id = min([o['order_id'] for o in format_orders]) time.sleep(0.5) return orders def get_orders(self, instrument_id, stime, etime, state): date_list = pd.date_range( stime.replace(hour=0, minute=0, second=0, microsecond=0), etime.replace(hour=0, minute=0, second=0, microsecond=0)) orders = [] for d in date_list: orders += self.get_oneday_orders(instrument_id, d, state) return [ o for o in orders if o['datetime'] >= stime and o['datetime'] < etime ]
from huobi import RequestClient from huobi.model import * from huobi.base.printobject import PrintMix request_client = RequestClient() trades = request_client.get_market_trade(symbol="btcusdt") if len(trades): for trade in trades: trade.print_object() print()
def __init__(self, apikey, secretkey, password): self._api = RequestClient(api_key=apikey, secret_key=secretkey) self.account_type = AccountType.SPOT
from huobi import RequestClient from huobi.model import * request_client = RequestClient() candlestick_list = request_client.get_latest_candlestick( "BTC_CQ", CandlestickInterval.MIN1, 150) print("---- 1 min candlestick for btcusdt ----") for item in candlestick_list: item.print_object() """ print("Timestamp: " + str(item.timestamp)) print("High: " + str(item.high)) print("Low: " + str(item.low)) print("Open: " + str(item.open)) print("Close: " + str(item.close)) print("Volume: " + str(item.volume)) """ print()
from huobi import RequestClient from huobi.model import * request_client = RequestClient(api_key="xxxxxx", secret_key="xxxxxx") trans_id_one = request_client.transfer_between_futures_and_pro(amount=0.35, currency="eos", transfer_type=TransferFuturesPro.TO_FETURES) print (trans_id_one) trans_id_two = request_client.transfer_between_futures_and_pro(amount=0.35, currency="eos", transfer_type=TransferFuturesPro.TO_PRO) print (trans_id_two)
from huobi import RequestClient from huobi.model import * request_client = RequestClient() candlestick_list = request_client.get_latest_candlestick("btcusdt", CandlestickInterval.MIN1, 10) print("---- 1 min candlestick for btcusdt ----") for item in candlestick_list: item.print_object() """ print("Timestamp: " + str(item.timestamp)) print("High: " + str(item.high)) print("Low: " + str(item.low)) print("Open: " + str(item.open)) print("Close: " + str(item.close)) print("Volume: " + str(item.volume)) """ print()
from huobi import RequestClient from huobi.constant.test import * from huobi.model import * from huobi.base.printobject import PrintMix request_client = RequestClient(api_key=g_api_key, secret_key=g_secret_key) #match_list = request_client.get_match_result(symbol="eosusdt") match_list = request_client.get_match_result(symbol="stketh", start_date="2019-10-30", from_id=8167494327, size=20, direct=QueryDirection.PREV) PrintMix.print_data(match_list)