def buy_or_sell(closeList, whenTime): market_client = MarketClient() nowshould = closeList[0] < closeList[len(closeList) - 1] global contr global lastPrice global totalprofit # 买入true if contr and nowshould: now_price = market_client.get_market_trade(symbol="btcusdt") now_price = now_price[0].price lastPrice = now_price print("buy Price:", str(lastPrice) + "," + str(whenTime)) contr = False # 卖出 false if (bool(1 - contr)) and (bool(1 - nowshould)): if lastPrice == 0: contr = True else: now_price = market_client.get_market_trade(symbol="btcusdt") now_price = now_price[0].price if (now_price - lastPrice - now_price * 0.002 - lastPrice * 0.002) > 0: print("sell Price:", str(now_price) + "," + str(whenTime)) totalprofit = totalprofit + now_price - lastPrice - now_price * 0.002 - lastPrice * 0.002 print("totalprofit:", str(totalprofit) + "," + str(whenTime)) contr = True
def getTrainData(symbol, interval): market_client = MarketClient(init_log=True) list_obj = market_client.get_candlestick(symbol, interval, 2000) Id = [] High = [] Low = [] Open = [] Close = [] Count = [] Amount = [] Volume = [] if list_obj and len(list_obj): for obj in list_obj: Id.append(obj.id) High.append(obj.high) Low.append(obj.low) Open.append(obj.open) Close.append(obj.close) Count.append(obj.count) Amount.append(obj.amount) Volume.append(obj.vol) # print(obj.id) # 字典中的key值即为csv中列名 dataframe = pd.DataFrame( {'Id': Id, 'High': High, 'Low': Low, 'Open': Open, 'Close': Close, 'Count': Count, 'Amount': Amount, 'Volume': Volume}) # 将DataFrame存储为csv,index表示是否显示行名,default=True dataframe.to_csv(interval + symbol + ".csv", index=False, sep=',')
def getlastprice(buss, symbol): if buss == '安': return requests.request( "GET", f'{ab_url}/api/v3/ticker/price?symbol={symbol}USDT').json( )['price'] else: market_client = MarketClient() return market_client.get_market_trade(symbol=f"{symbol}usdt")[0].price
def check_insurance_point(): market_client = MarketClient() depth_size = 20 depth = market_client.get_pricedepth(symbol, DepthStep.STEP1, depth_size) LogInfo.output("---- Top {size} bids ----".format(size=len(depth.bids))) i = 0 for entry in depth.bids: i = i + 1 print(entry.price) #printme(depth) return False, False, 0
def get_current_price(symbol): market_client = MarketClient() depth_size = 2 depth = market_client.get_pricedepth(symbol, DepthStep.STEP0, depth_size) #LogInfo.output("---- Top {size} bids ----".format(size=len(depth.bids))) i = 0 for entry in depth.bids: i = i + 1 if i == 1: first_price = entry.price #LogInfo.output(str(i) + ": price: " + str(entry.price) + ", amount: " + str(entry.amount)) return first_price
def __init__(self, api_key, secret_key, account_id, verbose=False): super().__init__() self.account_id = account_id self.trade_client = TradeClient(api_key=api_key, secret_key=secret_key) self.account_client = AccountClient(api_key=api_key, secret_key=secret_key) self.algo_client = AlgoClient(api_key=api_key, secret_key=secret_key) self.market_client = MarketClient() self.holds = {} self.total_fee = 0 self.stop_loss_threads = [] self.long_order_threads = [] self.latest_timestamp = 0 self.client_id_counter = 0 self.verbose = verbose self.subscription = None
def __init__(self, symbol): self.symbol = symbol self.market_client = MarketClient() self.candle_tick = pd.DataFrame(columns=[ 'id', 'open', 'close', 'high', 'low', 'amount', 'count', 'vol' ]) self.mbp_tick = pd.DataFrame(columns=[ "id", "prevSeqNum", "bids_0_price", "bids_1_price", "bids_2_price", "bids_3_price", "bids_4_price", "asks_0_price", "asks_1_price", "asks_2_price", "asks_3_price", "asks_4_price", "asks_0_amount", "asks_1_amount", "asks_2_amount", "asks_3_amount", "asks_4_amount", "bids_0_amount", "bids_1_amount", "bids_2_amount", "bids_3_amount", "bids_4_amount" ]) self.trade_tick = pd.DataFrame( columns=['id', 'price', 'amount', 'direction']) self.conn = sqlite3.connect('market.db', timeout=10) self.s = sched.scheduler(time.time, time.sleep)
def get_current_price(symbol): try: market_client = MarketClient() depth_size = 2 depth = market_client.get_pricedepth(symbol, DepthStep.STEP0, depth_size) #LogInfo.output("---- Top {size} bids ----".format(size=len(depth.bids))) i = 0 if not depth: return 0 for entry in depth.bids: i = i + 1 if i == 1: first_price = entry.price return first_price #LogInfo.output(str(i) + ": price: " + str(entry.price) + ", amount: " + str(entry.amount)) except Exception as e: print("ExecuteError in get_current_price", e) return 0
def update_graph_live(n): market_client = MarketClient(url="https://api.hbdm.com") list_obj = market_client.get_candlestick("ETH_CQ", CandlestickInterval.MIN1, 1) live_data['price'].append(list_obj[-1].close) if len(live_data['price']) >= 1000: live_data['price'] = live_data['price'][-1000:] live_data['time'].append(datetime.datetime.now().strftime('%c')) fig = plotly.tools.make_subplots(rows=1, cols=1, vertical_spacing=0.2) fig['layout']['margin'] = {'l': 30, 'r': 10, 'b': 30, 't': 10} fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'} fig.append_trace( { 'x': live_data['time'], 'y': live_data['price'], 'name': 'Price', 'mode': 'lines+markers', 'type': 'scatter' }, 1, 1) return fig
def __fallback_thread__(self): if self.proxies is None: test_clt = MarketClient(url=self.url, timeout=5) else: test_clt = MarketClient(url=self.url, timeout=5, proxies=self.proxies) testing = True while testing: if not self.live: return try: test_clt.get_candlestick("btcusdt", CandlestickInterval.MIN1, 2) testing = False except: time.sleep(0.1) continue ECHO.print( "[watchdog] [fallbacker] [{}] the original api url {} has recovered" .format( time.strftime("%y-%m-%d %H:%M:%S", time.localtime(self.get_timestamp() / 1000)), self.url)) self.fallbacked = False
def update_graph(n): data = {'time': [], 'price': []} market_client = MarketClient(url="https://api.hbdm.com") list_obj = market_client.get_candlestick("ETH_CQ", CandlestickInterval.MIN1, 200) for item in list_obj: data['price'].append(item.close) data['time'].append( datetime.datetime.fromtimestamp(item.id).strftime('%c')) fig = plotly.tools.make_subplots(rows=1, cols=1, vertical_spacing=0.2) fig['layout']['margin'] = {'l': 30, 'r': 10, 'b': 30, 't': 10} fig['layout']['legend'] = {'x': 0, 'y': 1, 'xanchor': 'left'} fig.append_trace( { 'x': data['time'], 'y': data['price'], 'name': 'Price', 'mode': 'lines+markers', 'type': 'scatter' }, 1, 1) return fig
def get_current_price(symbol): try: market_client = MarketClient() depth_size = 2 depth = market_client.get_pricedepth(symbol, DepthStep.STEP0, depth_size) #LogInfo.output("---- Top {size} bids ----".format(size=len(depth.bids))) i = 0 if not depth: return 0 for entry in depth.bids: i += 1 if i == 1: first_price = entry.price return first_price #LogInfo.output(str(i) + ": price: " + str(entry.price) + ", amount: " + str(entry.amount)) except Exception as e: print("ExecuteError in get_current_price", e) send_email( "HB: " + "get_current_price Exception ", "you can have a check if it is break or not after using pass!") pass return 0
from huobi.client.market import MarketClient from huobi.constant import DepthStep def callback(price_depth_req: 'PriceDepthReq'): price_depth_req.print_object() def error(e: 'HuobiApiException'): print(e.error_code + e.error_message) sub_client = MarketClient() sub_client.req_pricedepth("btcusdt", DepthStep.STEP0, callback, error)
from huobi.model.market import MarketTicker def callback(price_depth_event: 'PriceDepthBboEvent'): price_depth_event.print_object() print() def error(e: 'HuobiApiException'): print(e.error_code + e.error_message) # market_client = MarketClient() # market_client.sub_pricedepth_bbo("btcusdt", callback, error) sub_client = MarketClient(init_log=False) list_obj = sub_client.get_market_tickers() list_obj.sort(key=lambda x: x.count, reverse=True) list_obj = list_obj[0:100] ret = [] for obj in list_obj: obj: MarketTicker = obj if obj.symbol.endswith("usdt"): ret.append(obj) # else: # print(obj.symbol +" code not found!") # print(obj.symbol) ret.sort(key=lambda x: x.count, reverse=True)
from huobi.client.market import MarketClient def callback(trade_event: 'TradeDetailEvent'): print("---- trade_event: ----") trade_event.print_object() print() market_client = MarketClient(init_log=True) market_client.sub_trade_detail("btcusdt,eosusdt", callback)
from huobi.client.market import MarketClient from huobi.constant import * from huobi.exception.huobi_api_exception import HuobiApiException import time def callback(candlestick_req: 'CandlestickReq'): candlestick_req.print_object() def error(e: 'HuobiApiException'): print(e.error_code + e.error_message) sub_client = MarketClient(init_log=True, url="https://api.huobi.li") #sub_client.request_candlestick_event("btcusdt", CandlestickInterval.MIN1, callback, from_ts_second=None, end_ts_second=None, error_handler=None) #sub_client.request_candlestick_event("btcusdt", CandlestickInterval.MIN1, callback, from_ts_second=1571124360, end_ts_second=1571129820) #sub_client.request_candlestick_event("btcusdt", CandlestickInterval.MIN1, callback, from_ts_second=1569361140, end_ts_second=0) #sub_client.request_candlestick_event("btcusdt", CandlestickInterval.MIN1, callback, from_ts_second=1569379980) while True: time.sleep(0.5) sub_client.req_candlestick("paxusdt", CandlestickInterval.MIN1, callback)
from huobi.client.market import MarketClient from huobi.constant import * from huobi.utils import * market_client = MarketClient(init_log=True) interval = CandlestickInterval.MIN5 symbol = "ethusdt" list_obj = market_client.get_candlestick(symbol, interval, 10) LogInfo.output("---- {interval} candlestick for {symbol} ----".format( interval=interval, symbol=symbol)) LogInfo.output_list(list_obj)
''' @author: HeQingsong @date: 2020-09-20 13:41 @filename: MarketQuotationUtils.py @project: huobi_Python @python version: 3.7 by Anaconda @description: ''' from huobi.client.market import MarketClient, CandlestickInterval from huobi.exception.huobi_api_exception import HuobiApiException import pandas as pd market_client = MarketClient() ''' 返回格式: [ {'id': 1600581600, 'open': 0.005888, 'close': 0.005847, 'low': 0.005833, 'high': 0.005888, 'amount': 196284.1214, 'vol': 1147.6254458782, 'count': 55}, {'id': 1600580700, 'open': 0.00588, 'close': 0.005873, 'low': 0.005873, 'high': 0.005916, 'amount': 83578.0374, 'vol': 492.5054534462, 'count': 45}, ] ''' def get_market_quotation(symbol, wtime, size=1000): try: list_obj = market_client.get_candlestick(symbol, wtime, size) df_list = [] list_length = len(list_obj) for i in range(0, list_length): obj = list_obj[list_length - i - 1]
from huobi.client.market import MarketClient from huobi.constant import * def callback(mbp_event: 'MbpIncreaseEvent'): mbp_event.print_object() def error(e: 'HuobiApiException'): print(e.error_code + e.error_message) market_client = MarketClient(init_log=True) market_client.req_mbp("btcusdt", MbpLevel.MBP5, callback, error)
from huobi.exception.huobi_api_exception import HuobiApiException from my.lesscfg import LESS_SYMBOL, LESS_INTERVAL, LESS_BASE, LESS_MAX_COUNT, LESS_LEAST_PROFIT, LESS_ADD_DIFF, \ LESS_PEAK_DIFF from my.lessdb import Lessdb, BTC_OPS_TABLE, Operation from my.organized import Organized from my.upath import UPath from huobi.client.market import MarketClient from huobi.client.account import AccountClient from huobi.client.trade import TradeClient from huobi.constant import * from my.utils import Utils account_client = AccountClient(api_key=g_api_key, secret_key=g_secret_key) market_client = MarketClient(init_log=True) trade_client = TradeClient(api_key=g_api_key, secret_key=g_secret_key) class LessTradeDirection(IntEnum): LONG = 0, SHORT = 1, INVALID = 2, symbol = LESS_SYMBOL interval = LESS_INTERVAL LOG_THROTTLE_COUNT = 1 LESSDB_FILE = "less_{0}.db".format(symbol)
from huobi.client.market import MarketClient from huobi.utils import * import time market_client = MarketClient(url="https://api.huobi.li") while True: list_obj = market_client.get_market_trade(symbol="ethusdt") LogInfo.output_list(list_obj)
def trace_profit(base_symbol, quote_symbol, amount, monitor_sleep_time, interval_upper_boundary_list, interval_rate_list, interval_delta_list, stop_loss_rate=0.05, stop_profit_rate=float("inf"), buy_sleep_time=5, sell_sleep_time=5, buy_max_times=1, sell_max_times=20, test_mode=0, test_price_vector=[]): symbol = base_symbol + quote_symbol #illegal parameter if not (len(interval_upper_boundary_list) == len(interval_rate_list) == len(interval_delta_list)): return -1 symbol_info = get_symbol_info(symbol) print("----------------------------------------------") print("Parameters:") print("1. base_symbol=%s, quote_symbol=%s, symbol=%s, amount=%f" % (base_symbol, quote_symbol, symbol, amount)) print("2. stop_loss_rate=%f, stop_profit_rate=%f" % (stop_loss_rate, stop_profit_rate)) print("3. monitor_sleep_time=%f" % monitor_sleep_time) print("4. interval_upper_boundary_list=%s" % interval_upper_boundary_list) print("5. interval_rate_list=%s" % interval_rate_list) print("6. interval_delta_list=%s" % interval_delta_list) print("7. buy_sleep_time=%d, sell_sleep_time=%d" % (buy_sleep_time, sell_sleep_time)) print("8. buy_max_times=%d, sell_max_times=%d" % (buy_max_times, sell_max_times)) print("9. test_mode=%d" % test_mode) print("10. symbol detail info:") symbol_info.print_object() print("----------------------------------------------\n") #Initial sell_dif_rate = -1 hysteresis_cnt = 0 check_times = 1 market_client = MarketClient() interval_flag_list = [ 0 for x in range(0, len(interval_upper_boundary_list)) ] #generate interval flag list according to parameter #get buy order info from the buy order API if 1 == test_mode: symbol_start_price = test_price_vector[0] else: #create buy order [symbol_start_price, filled_amount] = must_buy_sell(OrderType.BUY_MARKET, symbol, amount, 0, symbol_info.amount_precision, symbol_info.price_precision, buy_max_times, buy_sleep_time) #SELL TEST: if test_mode == 2: print('TEST_MODE2: START SELL:\n') must_buy_sell(OrderType.SELL_MARKET, symbol, filled_amount, 999999999, symbol_info.amount_precision, symbol_info.price_precision, sell_max_times, sell_sleep_time) return 0 print('\nSTART TRACING PROFIT:\n') print( 'No.\tPRICE\t\tPRICE_DIF\tPRICE_DIF_RATE\tSELL_DIF_RATE\tFLAG_LIST\tCNT\tTIME' ) #monitor the latest price and price rate while (1): if test_mode: symbol_current_price = test_price_vector[check_times] symbol_current_time = 0 else: try: list_obj = market_client.get_market_trade(symbol) symbol_current_price = list_obj[0].price symbol_current_time = list_obj[0].ts except requests.exceptions.ProxyError as e: print(e) continue except requests.exceptions.ConnectionError as e: print(e) continue except requests.exceptions.ReadTimeout as e: print(e) continue #get price dif and rate price_dif = symbol_current_price - symbol_start_price price_dif_rate = abs(price_dif / symbol_start_price) print( "%d\t%0.8f\t%0.8f\t%0.8f%%\t%0.8f%%\t%s\t%d\t" % (check_times, symbol_current_price, price_dif, 100 * price_dif_rate, 100 * sell_dif_rate, interval_flag_list, hysteresis_cnt), datetime.datetime.fromtimestamp( symbol_current_time / 1000).strftime('%Y-%m-%d %H:%M:%S.%f')) #stop loss if price_dif < 0 and price_dif_rate >= stop_loss_rate: print("------------Trigger stop loss------------\n") if not test_mode: must_buy_sell(OrderType.SELL_MARKET, symbol, filled_amount, 999999999, symbol_info.amount_precision, symbol_info.price_precision, sell_max_times, sell_sleep_time) return 0 #stop profit if price_dif > 0 and price_dif_rate >= stop_profit_rate: print("------------Trigger stop profit------------\n") if not test_mode: must_buy_sell(OrderType.SELL_MARKET, symbol, filled_amount, 999999999, symbol_info.amount_precision, symbol_info.price_precision, sell_max_times, sell_sleep_time) return 0 #update price rate and sell when get suitable profit if price_dif > 0 and price_dif_rate > sell_dif_rate: [sell_dif_rate, interval_flag_list, hysteresis_cnt] = sell_dif_rate_hysteresis( sell_dif_rate, interval_flag_list, hysteresis_cnt, price_dif, price_dif_rate, interval_upper_boundary_list, interval_rate_list, interval_delta_list) elif price_dif > 0 and price_dif_rate <= sell_dif_rate: print("------------Trigger get enough profit------------\n") if not test_mode: must_buy_sell(OrderType.SELL_MARKET, symbol, filled_amount, 999999999, symbol_info.amount_precision, symbol_info.price_precision, sell_max_times, sell_sleep_time) return 0 #loop check times check_times += 1 #loop sleep time time.sleep(monitor_sleep_time)
from huobi.client.market import MarketClient from huobi.utils import * market_client = MarketClient() list_obj = market_client.get_history_trade("btcusdt", 6) LogInfo.output_list(list_obj)
from huobi.client.market import MarketClient import time def callback(trade_req: 'TradeDetailReq'): print("---- trade_event: ----") print(trade_req[1]) print() market_client = MarketClient(url="https://api.huobi.li") while True: market_client.req_trade_detail("enjusdt", callback)
from huobi.client.market import MarketClient from huobi.constant import * def callback(mbp_event: 'MbpIncreaseEvent'): mbp_event.print_object() def error(e: 'HuobiApiException'): print(e.error_code + e.error_message) market_client = MarketClient(init_log=True) market_client.sub_mbp_increase("btcusdt,eosusdt", MbpLevel.MBP150, callback, error)
from huobi.client.market import MarketClient from huobi.constant import * def callback(price_depth_event: 'PriceDepthEvent'): price_depth_event.print_object() def error(e: 'HuobiApiException'): print(e.error_code + e.error_message) market_client = MarketClient() market_client.sub_pricedepth("btcusdt", DepthStep.STEP0, callback, error) market_client.sub_pricedepth("eosusdt", DepthStep.STEP0, callback, error) market_client.sub_pricedepth("ethusdt", DepthStep.STEP0, callback, error)
from huobi.client.trade import TradeClient generic_client = GenericClient() list_symbol = generic_client.get_exchange_symbols() list_currency = generic_client.get_reference_currencies() print(list_symbol[0]) print(list_currency[0].print_object()) a = c access_key = " " secret_key = " " # Create generic client instance and get the timestamp generic_client = GenericClient() timestamp = generic_client.get_exchange_timestamp() print(timestamp) # Create the market client instance and get the latest btcusdt‘s candlestick market_client = MarketClient() list_obj = market_client.get_candlestick("btcusdt", CandlestickInterval.MIN5, 10) LogInfo.output_list(list_obj) # // Create an AccountClient instance with APIKey account_client = AccountClient(api_key=access_key, secret_key=secret_key) # // Create a TradeClient instance with API Key and customized host trade_client = TradeClient(api_key=access_key, secret_key=secret_key, url="https://api-aws.huobi.pro")
# print() def error(e: 'HuobiApiException'): print(e.error_code + e.error_message) # class CandlestickInterval: # MIN1 = "1min" # MIN5 = "5min" # MIN15 = "15min" # MIN30 = "30min" # MIN60 = "60min" # HOUR4 = "4hour" # DAY1 = "1day" # MON1 = "1mon" # WEEK1 = "1week" # YEAR1 = "1year" # INVALID = None sub_client = MarketClient(init_log=True, url="https://api.huobiasia.vip") #sub_client.request_candlestick_event("btcusdt", CandlestickInterval.MIN1, callback, from_ts_second=None, end_ts_second=None, error_handler=None) #sub_client.request_candlestick_event("btcusdt", CandlestickInterval.MIN1, callback, from_ts_second=1571124360, end_ts_second=1571129820) #sub_client.request_candlestick_event("btcusdt", CandlestickInterval.MIN1, callback, from_ts_second=1569361140, end_ts_second=0) #sub_client.request_candlestick_event("btcusdt", CandlestickInterval.MIN1, callback, from_ts_second=1569379980) list = sub_client.req_candlestick("filusdt", CandlestickInterval.MIN30, callback) # sub_client.get_market_trade(symbol="filusdt") # print(list)
import os from huobi.client.market import MarketClient api_key = os.environ.get("API_KEY") secret_key = os.environ.get("SECRET_KEY") market_client = MarketClient(api_key=api_key, secret_key=secret_key) obj = market_client.get_market_detail("btcusdt") obj.print_object()
'btc', 'eth', 'link', 'dot', 'eos', 'trx', 'ada', 'ltc', 'bch', 'xrp', 'bsv', 'etc', 'fil' ] watch_thresh = 10 # Futures setup URL = 'https://api.hbdm.com' ACCESS_KEY = '' SECRET_KEY = '' dm = HuobiDM(URL, ACCESS_KEY, SECRET_KEY) # BB setup market_client = MarketClient() while True: for contract in contractlist: # Get BB MarketData bbsymbol = contract.lower() + 'usdt' depth = market_client.get_pricedepth(bbsymbol, DepthStep.STEP0, 20) bb_ask = depth.asks[19].price # Get Future MarketData futsymbol = contract.upper() + '_NQ' delivery_date = dm.get_contract_info( symbol=contract.upper(), contract_type="next_quarter")['data'][0]['delivery_date'] waiteday = (datetime.datetime.strptime(delivery_date, '%Y%m%d') - datetime.datetime.now()).days + 2 fut_depth = dm.get_contract_depth(symbol=futsymbol, type='step6')