def run(): logger = setup_logger() # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret. ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBTUSD", api_key=None, api_secret=None) logger.info("Instrument data: %s" % ws.get_instrument()) # Run forever while(ws.ws.sock.connected): logger.info("Ticker: %s" % ws.get_ticker()) if ws.api_key: logger.info("Funds: %s" % ws.funds()) logger.info("Market Depth: %s" % ws.market_depth()) logger.info("Recent Trades: %s\n\n" % ws.recent_trades()) sleep(10)
def run(): logger = setup_logger() # Instantiating the WS will make it connect. Be sure to add an auth method. You can use login/password # or api_key/api_secret. ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBT24H", login="******", password="******", api_key=None, api_secret=None) logger.info("Instrument data: %s" % ws.get_instrument()) # Run forever while(ws.ws.sock.connected): logger.info("Ticker: %s" % ws.get_ticker()) logger.info("Funds: %s" % ws.funds()) logger.info("Market Depth: %s" % ws.market_depth()) logger.info("Recent Trades: %s\n\n" % ws.recent_trades()) sleep(10)
def run(): logger = setup_logger() # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret. ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBTUSD", api_key=None, api_secret=None) logger.info("Instrument data: %s" % ws.get_instrument()) # Run forever while(ws.ws.sock.connected): logger.info("Ticker: %s" % ws.get_ticker()) if ws.config['api_key']: logger.info("Funds: %s" % ws.funds()) logger.info("Market Depth: %s" % ws.market_depth()) logger.info("Recent Trades: %s\n\n" % ws.recent_trades()) sleep(10)
def update_mkt(): ws_mkt = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBTUSD", api_key=None, api_secret=None) while (ws_mkt.ws.sock.connected): market=ws_mkt.market_depth() market_order=dict() market_order["symbol"]=[] market_order["id"]=[] market_order["side"]=[] market_order["size"]=[] market_order["price"]=[] for i in market: market_order["symbol"].append(i["symbol"]) market_order["id"].append(i["id"]) market_order["side"].append(i["side"]) market_order["size"].append(i["size"]) market_order["price"].append(i["price"]) db.mkt.update_one({"_id":"market"},{"$set":market_order})
def run(): logger = setup_logger() config = configparser.ConfigParser() config.read('config/config.ini') ws = BitMEXWebsocket(endpoint=config['bitmex']['endpoint'], symbol="XBTUSD", api_key=config['bitmex']['api_key'], api_secret=config['bitmex']['api_secret']) logger.info("Instrument data: %s" % ws.get_instrument()) # Run forever while(ws.ws.sock.connected): logger.info("Ticker: %s" % ws.get_ticker()) if ws.api_key: logger.info("Funds: %s" % ws.funds()) logger.info("Market Depth: %s" % ws.market_depth()) logger.info("Recent Trades: %s\n\n" % ws.recent_trades()) sleep(10)
def run(): logger = setup_logger() # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret. ws = BitMEXWebsocket( endpoint="wss://testnet.bitmex.com/realtime", symbol="XBTUSD", api_key="wwvS30igJDo6Ksxa0h2EP1Eq", api_secret="-DOHRIUObpSQilqyr2y18YcTRi5NWFIV95du4i8rG4VveOBI") logger.info("Instrument data: {}".format(ws.get_instrument())) # Run forever while (ws.ws.sock.connected): logger.info("Ticker: %s" % ws.get_ticker()) if ws.config['api_key']: logger.info("Funds: %s" % ws.funds()) logger.info("Market Depth: %s" % ws.market_depth()) logger.info("Recent Trades: %s\n\n" % ws.recent_trades()) sleep(10)
def run(): logger = setup_logger() # Instantiating the WS will make it connect. Be sure to add an auth method. You can use login/password # or api_key/api_secret. ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol="XBT24H", login="******", password="******", api_key=None, api_secret=None) logger.info("Instrument data: %s" % ws.get_instrument()) # Run forever while (ws.ws.sock.connected): logger.info("Ticker: %s" % ws.get_ticker()) logger.info("Funds: %s" % ws.funds()) logger.info("Market Depth: %s" % ws.market_depth()) logger.info("Recent Trades: %s\n\n" % ws.recent_trades()) sleep(10)
class BitMexWS(object): """ 适合订阅数据 """ def __init__(self, api_key=None, api_secret=None, symbol="XBTUSD"): endpoint = "https://testnet.bitmex.com/api/v1" if api_key: endpoint = "https://www.bitmex.com/api/v1" self.ws = BitMEXWebsocket(endpoint=endpoint, symbol=symbol, api_key=api_key, api_secret=api_secret) def run(self): logger = self.setup_logger() # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret. logger.info("Instrument data: %s" % self.ws.get_instrument()) # Run forever while self.ws.ws.sock.connected: logger.info("Ticker: %s" % self.ws.get_ticker()) if self.ws.api_key: logger.info("Funds: %s" % self.ws.funds()) logger.info("Market Depth: %s" % self.ws.market_depth()) logger.info("Recent Trades: %s\n\n" % self.ws.recent_trades()) sleep(10) def setup_logger(self): # Prints logger info to terminal logger = logging.getLogger() logger.setLevel(logging.INFO) # Change this to DEBUG if you want a lot more info ch = logging.StreamHandler() # create formatter formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s") # add formatter to ch ch.setFormatter(formatter) logger.addHandler(ch) return logger
def run(): if "BITMEX_API_KEY" not in os.environ: print("BITMEX_API_KEY env var must be set") exit(1) if "BITMEX_API_SECRET" not in os.environ: print("BITMEX_API_SECRET env var must be set") exit(1) bq = BigQuery(table="XBTUSD_orderbook", dataset="bitmex", schema=schema) logger = setup_logger() ws = BitMEXWebsocket(endpoint="https://www.bitmex.com/api/v1", symbol="XBTUSD", api_key=os.environ.get('BITMEX_API_KEY'), api_secret=os.environ.get('BITMEX_API_SECRET')) while (ws.ws.sock.connected): if ws.api_key: rows_to_insert = ws.market_depth() errors = bq.client.insert_rows(bq.tbl, rows_to_insert) if errors != []: print(errors)
def is_executed(self, order_info): symbol = order_info['symbol'] side = order_info['side'] price = None #check if the order is limit order if 'price' in order_info: price = order_info['price'] # Instantiating the WS will make it connect. Be sure to add your api_key/api_secret. ws = BitMEXWebsocket(endpoint="https://testnet.bitmex.com/api/v1", symbol=symbol, api_key=self.api_key, api_secret=self.api_secret) for order in ws.market_depth(): # checking existed orders in market glass for deal if side == 'Buy' and order['side'] == "Sell" and price == order[ 'price'] and self.accumulated_sum >= price: return True elif side == 'Sell' and order['side'] == 'Buy' and price == order[ 'price']: return True return False
class Future: def __init__(self, apiconfpth=kfpth): f = open(apiconfpth, 'r') lines = f.readlines() f.close() apikey = lines[0].replace('\r', '').replace('\n', '') secretkey = lines[1].replace('\r', '').replace('\n', '') self.client = bitmex.bitmex(test=True, api_key=apikey, api_secret=secretkey) # https://www.bitmex.com/realtime # https://www.bitmex.com/api/v1 self.ws = BitMEXWebsocket( endpoint="https://testnet.bitmex.com/realtime", symbol="XBTUSD", api_key=None, api_secret=None) self.logger = self.setup_logger() self.logger.info("Instrument data: %s" % self.ws.get_instrument()) AlarmPrice.initAlarmObj(self.ws) def startAlarm(self, price): AlarmPrice.startAlarm(price) def stopAlarm(self): AlarmPrice.stopAlarm() def isAlarmWork(self): return AlarmPrice.isWork() def setup_logger(self): # Prints logger info to terminal logger = logging.getLogger() logger.setLevel( logging.INFO) # Change this to DEBUG if you want a lot more info ch = logging.StreamHandler() # create formatter formatter = logging.Formatter( "%(asctime)s - %(name)s - %(levelname)s - %(message)s") # add formatter to ch ch.setFormatter(formatter) logger.addHandler(ch) return logger #期货下单 def future_trade(self, symbol, contractType, price='', amount='', tradeType='', matchPrice='', leverRate=''): if symbol == 'XBT': if contractType == 'XBTUSD': return self.future_trade_xbtusd(price, amount, tradeType) else: print('合约交易类型%s不可用:' % (contractType)) else: print('市场类型%s不可用:' % (symbol)) res = None return res def future_trade_xbtusd(self, price, amount, tradeType): res = None tmpprice = '%.1f' % (float(price)) print('-----------------------') print(self.client.Order.__dict__) print(dir(self.client.Order)) if tradeType == '1': #开多 print('开多:', tmpprice, amount) res = self.client.Order.Order_new(symbol='XBTUSD', orderQty=int(amount), price=float(tmpprice)).result() elif tradeType == '3': #平多 print('平多:', tmpprice, amount) res = self.client.Order.Order_new(symbol='XBTUSD', orderQty=-int(amount), execInst='Close', price=float(tmpprice)).result() elif tradeType == '2': #开空 print('开空:', tmpprice, amount) res = self.client.Order.Order_new(symbol='XBTUSD', orderQty=-int(amount), price=float(tmpprice)).result() elif tradeType == '4': #平空 print('平空:', tmpprice, amount) #Order_new res = self.client.Order.Order_new(symbol='XBTUSD', orderQty=int(amount), execInst='Close', price=float(tmpprice)).result() else: print('tradeType,下单类型设置错误:', tradeType) return res[0] #OKCoin期货市场深度信息 def future_depth(self, symbol, contractType, size): if symbol == 'XBT': if contractType == 'XBTUSD': return self.future_depth_xbtusd(size) else: print('合约交易类型%s不可用:' % (contractType)) else: print('市场类型%s不可用:' % (symbol)) return None def future_depth_xbtusd(self, size): if self.ws.ws.sock.connected: depthdat = self.ws.market_depth() # logger.info("Market Depth: %s" % depthdat) print(type(depthdat), len(depthdat)) sells = [] buys = [] for d in depthdat: if d['symbol'] == 'XBTUSD': if d['side'] == 'Buy': buys.append([d['price'], d['size']]) elif d['side'] == 'Sell': sells.append([d['price'], d['size']]) sells.sort() backsells = sells[:size] print(backsells) print('----------') buys.sort(reverse=True) backbuys = buys[:size] print(backbuys) return backbuys, backsells[::-1] else: print('websocket连接错误') # self.ws.ws.sock.connect() return None, None #期货取消所有定单订单 def future_cancel(self, symbol, contractType, orderId): res = None if orderId == '' or (not orderId): res = self.client.Order.Order_cancelAll().result() print(res) else: res = self.client.Order.Order_cancel(orderId).result() print(res) return res #期货获取订单信息 def future_orderinfo(self, symbol, contractType, orderId, status, currentPage, pageLength): pass # FUTURE_ORDERINFO = "/api/v1/future_order_info.do?" # params = { # 'api_key':self.__apikey, # 'symbol':symbol, # 'contract_type':contractType, # 'order_id':orderId, # 'status':status, # 'current_page':currentPage, # 'page_length':pageLength # } # params['sign'] = buildMySign(params,self.__secretkey) # return httpPost(self.__url,FUTURE_ORDERINFO,params) #------------- #OKCOIN期货行情信息 def future_ticker(self, symbol, contractType): pass # FUTURE_TICKER_RESOURCE = "/api/v1/future_ticker.do" # params = '' # if symbol: # params += '&symbol=' + symbol if params else 'symbol=' +symbol # if contractType: # params += '&contract_type=' + contractType if params else 'contract_type=' +symbol # return httpGet(self.__url,FUTURE_TICKER_RESOURCE,params) #OKCoin期货交易记录信息 def future_trades(self, symbol, contractType): pass # FUTURE_TRADES_RESOURCE = "/api/v1/future_trades.do" # params = '' # if symbol: # params += '&symbol=' + symbol if params else 'symbol=' +symbol # if contractType: # params += '&contract_type=' + contractType if params else 'contract_type=' +symbol # return httpGet(self.__url,FUTURE_TRADES_RESOURCE,params) #OKCoin期货指数 def future_index(self, symbol): pass # FUTURE_INDEX = "/api/v1/future_index.do" # params='' # if symbol: # params = 'symbol=' +symbol # return httpGet(self.__url,FUTURE_INDEX,params) #获取美元人民币汇率 def exchange_rate(self): pass # EXCHANGE_RATE = "/api/v1/exchange_rate.do" # return httpGet(self.__url,EXCHANGE_RATE,'') #获取预估交割价 def future_estimated_price(self, symbol): pass # FUTURE_ESTIMATED_PRICE = "/api/v1/future_estimated_price.do" # params='' # if symbol: # params = 'symbol=' +symbol # return httpGet(self.__url,FUTURE_ESTIMATED_PRICE,params) #期货全仓账户信息 def future_userinfo(self): pass # FUTURE_USERINFO = "/api/v1/future_userinfo.do?" # params ={} # params['api_key'] = self.__apikey # params['sign'] = buildMySign(params,self.__secretkey) # return httpPost(self.__url,FUTURE_USERINFO,params) #期货全仓持仓信息 def future_position(self, symbol, contractType): pass # FUTURE_POSITION = "/api/v1/future_position.do?" # params = { # 'api_key':self.__apikey, # 'symbol':symbol, # 'contract_type':contractType # } # params['sign'] = buildMySign(params,self.__secretkey) # return httpPost(self.__url,FUTURE_POSITION,params) #期货批量下单 def future_batchTrade(self, symbol, contractType, orders_data, leverRate): pass # FUTURE_BATCH_TRADE = "/api/v1/future_batch_trade.do?" # params = { # 'api_key':self.__apikey, # 'symbol':symbol, # 'contract_type':contractType, # 'orders_data':orders_data, # 'lever_rate':leverRate # } # params['sign'] = buildMySign(params,self.__secretkey) # return httpPost(self.__url,FUTURE_BATCH_TRADE,params) #期货逐仓账户信息 def future_userinfo_4fix(self): pass # FUTURE_INFO_4FIX = "/api/v1/future_userinfo_4fix.do?" # params = {'api_key':self.__apikey} # params['sign'] = buildMySign(params,self.__secretkey) # return httpPost(self.__url,FUTURE_INFO_4FIX,params) #期货逐仓持仓信息 def future_position_4fix(self, symbol, contractType, type1): pass
from bitmex_websocket import BitMEXWebsocket ws = BitMEXWebsocket(endpoint="wss://www.bitmex.com/realtime", symbol="XBTUSD") order_book = ws.market_depth() buy_order = {}; sell_order = {}; sorted_order = sorted(order_book, key=lambda order: order['price']) print("\n") for order in sorted_order: side = order['side'] size = order['size'] price = order['price'] print(side, price, size) if(side == "Buy"): buy_order[price] = size elif(side == "Sell"): sell_order[price] = size print("\n") print(buy_order.keys())
def algo_run(self): # get prices of futures with http or we can do it with websocket, now I chose http protocol XBTM20_price = self.client.Trade.Trade_get( symbol='XBTM20').result()[0][0]['price'] XBTU20_price = self.client.Trade.Trade_get( symbol='XBTU20').result()[0][0]['price'] # fixed middle spread mid_spred = (XBTU20_price - XBTM20_price) / 2 # websocket for XBTM20 ws_XBTM20 = BitMEXWebsocket( endpoint="https://testnet.bitmex.com/api/v1", symbol="XBTM20", api_key=self.api_key, api_secret=self.api_secret) # websocket for XBTU20 ws_XBTU20 = BitMEXWebsocket( endpoint="https://testnet.bitmex.com/api/v1", symbol="XBTU20", api_key=self.api_key, api_secret=self.api_secret) while ws_XBTM20.ws.sock.connected and ws_XBTU20.ws.sock.connected: # finding the best bid price for XBTM20 in the market glass best_bid_XBTM20_price = 0 depths = ws_XBTM20.market_depth() for depth in depths: if depth['side'] == 'Buy': best_bid_XBTM20_price = max(depth['price'], best_bid_XBTM20_price) # finding the best ask price for XBTM20 in the market glass best_ask_XBTM20_price = 1e10 for depth in depths: if depth['side'] == 'Sell': best_ask_XBTM20_price = min(depth['price'], best_ask_XBTM20_price) # Если открытая позиция на XBTM20 >= Максимальный размер накопленной позиции, # перестать квотировать Limit Buy order. В противном случае квотировать Buy # сторону по условиям 100% времени. if self.orders_XBTM20 * self.inventory <= best_ask_XBTM20_price: # stop quoting the Limit Buy order self.isBuyXBTM20 = False else: # quoting the Limit Buy order self.isBuyXBTM20 = True # Если открытая позиция на XBTM20 <= -Максимальный размер накопленной позиции, # перестать квотировать Limit Sell order. В противном случае квотировать Sell # сторону по условиям 100% времени. if -self.orders_XBTM20 * self.inventory >= best_bid_XBTM20_price: # stop quoting the Limit Sell order self.isSellXBTM20 = False else: # quoting the Limit Sell order self.isSellXBTM20 = True if self.isSellXBTM20: # ------------ sell limit order XBTM20 -------------- # finding best ask price for XBTU20 in market glass best_ask_XBTU20_price = 1e10 for depth in ws_XBTU20.market_depth(): if depth['side'] == 'Sell': best_ask_XBTU20_price = min(depth['price'], best_ask_XBTU20_price) # using following formula # best ask price XBTU20 - limit price XBTM20 = mid_spred - 5 limit_price_XBTM20 = best_ask_XBTU20_price - mid_spred + 5 sell_order_info_XBTM20 = { 'symbol': 'XBTM20', 'price': round(limit_price_XBTM20), 'orderQty': 1, 'side': 'Sell' } self.place_order(sell_order_info_XBTM20) if self.is_executed(sell_order_info_XBTM20): self.accumulated_sum += sell_order_info_XBTM20['price'] self.orders_XBTM20 -= 1 # --------------------------------------------------- if self.isBuyXBTM20: # ------------ buy limit order XBTM20 -------------- # finding best bid price for XBTU20 in market glass best_bid_XBTU20_price = 0 for depth in ws_XBTU20.market_depth(): if depth['side'] == 'Buy': best_bid_XBTU20_price = max(depth['price'], best_bid_XBTU20_price) # using following formula # best bid price XBTU20 - limit price XBTM20 = mid_spred - 5 limit_price_XBTM20 = best_bid_XBTU20_price - mid_spred + 5 buy_order_info_XBTM20 = { 'symbol': 'XBTM20', 'price': round(limit_price_XBTM20), 'orderQty': 1, 'side': 'Buy' } self.place_order(buy_order_info_XBTM20) if self.is_executed(buy_order_info_XBTM20): self.accumulated_sum -= buy_order_info_XBTM20['price'] self.orders_XBTM20 += 1 # --------------------------------------------------- print("OK") sleep(10)
class Main(): def __init__(self): self.ws = BitMEXWebsocket( endpoint="wss://www.bitmex.com/realtime", symbol="XBTUSD", api_key='68_LZNeK1m7TEwnksVTe_7ig', api_secret='wKJXpjr6Y28BNDF4G97TBevkzLG0HVOurFDBn2dx42Sf_Aga') self.client = MongoClient('mongodb://localhost:27017/') self.db = self.client.main_database self.order_book = self.db.orderbook self.position = self.db.position self.balance = self.db.balance #uncomment these 3 methods to check out the db #to see orderbooks #self.check_db(self.find_all_orderbook()) #to see position #self.check_db(self.find_all_positions()) #to see balance #self.check_db(self.find_all_balance()) self.__on_open() self.fetch_data() def check_db(self, objects): for object in objects: self.logger(object) def logger(self, object): print(object) def find_all_positions(self): # Returns a list return self.position.find({}) def find_all_balance(self): # Returns a list return self.balance.find({}) def find_all_orderbook(self): # Returns a list return self.order_book.find({}) def list_db_collections(self): return self.db.list_collection_names() def __on_open(self): # Called when the WS opens. self.logger("Websocket Opened.") def __on_close(self): # Called on websocket close. self.logger('Websocket Closed') def fetch_data(self): # Balance funds = self.ws.funds() # Position positions = self.ws.recent_trades() # Order Book orderbook = self.ws.market_depth() self.__on_close(funds, positions, orderbook) def __on_open(self): '''Called when the WS opens.''' self.logger("Websocket Opened.") def __on_close(self, funds, positions, orderbook): '''Called on websocket close.''' # --- SAVE TO DB ---- # self.balance.insert_one(funds) for position in positions: self.position.insert_one(position) for trade in orderbook: self.order_book.insert_one(trade) # --- SAVE TO DB ---- # self.logger('Websocket Closed')
pyclient = pymongo.MongoClient("mongodb://*****:*****@localhost:27017/") pydb = pyclient["deribit"] from bitmex_websocket import BitMEXWebsocket from time import sleep first = True import calendar; import time trdMatchIDs = [] while True: ws = BitMEXWebsocket(endpoint="https://www.bitmex.com/api/v1", symbol="XBTUSD", api_key=api_key, api_secret=api_secret) try: while(ws.ws.sock.connected): depth = (ws.market_depth()) asks = [] bids = [] for bidask in depth: if bidask['side'] == 'Buy': bids.append(bidask) else: asks.append(bidask) bidsnew = sorted(bids, key=lambda k: k['price']) asksnew = sorted(asks, key=lambda k: k['price']) bidsarr = [] asksarr = [] for i in range(0, 9): bidsarr.append(bidsnew[(i +1 ) *-1]) asksarr.append(asksnew[i])
Z17_buffer1 = np.zeros(Nbuffer) diff_buffer1 = np.zeros(Nbuffer) diff_buffer2 = np.zeros(Nbuffer) long_buffer1 = np.zeros(Nlong) long_buffer2 = np.zeros(Nlong) trade_buffer_Z17 = np.zeros(Ntrade) trade_buffer_XBT = np.zeros(Ntrade) long_std = 0.0 logging.basicConfig(filename='myTrade.log', level=logging.INFO) logging.info("############ Date ############: %s" % time.strftime("%Y:%m:%d:%H:%M:%S")) # realtime market info. depth25USD = wsUSD.market_depth() depth25Z17 = wsZ17.market_depth() # Begin Trading while (1): iter = iter + 1 [Z17_price1, Z17_tradeType1] = bit_compute(amount_usd, depth25Z17) # buy Z17 Z17_buffer1[iter % Nbuffer] = Z17_price1 std1 = np.std(Z17_buffer1) [Z17_price2, Z17_tradeType2] = bit_compute(-amount_usd, depth25Z17) # sell Z17 Z17_buffer2[iter % Nbuffer] = Z17_price2 std2 = np.std(Z17_buffer2)