async def process_binary(self, raw): """ 处理websocket上接收到的消息 @param raw 原始的压缩数据 """ decompress = zlib.decompressobj(-zlib.MAX_WBITS) msg = decompress.decompress(raw) msg += decompress.flush() msg = msg.decode() if msg == "pong": # 心跳返回 return msg = json.loads(msg) logger.debug("msg:", msg, caller=self) # 登陆成功之后再订阅数据 if msg.get("event") == "login": if not msg.get("success"): e = Error("Websocket connection authorized failed: {}".format(msg)) logger.error(e, caller=self) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return logger.info("Websocket connection authorized successfully.", caller=self) # 获取当前等待成交和部分成交的订单信息 order_infos, error = await self._rest_api.get_open_orders(self._raw_symbol) if error: e = Error("get open orders error: {}".format(msg)) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return for order_info in order_infos: order_info["ctime"] = order_info["created_at"] order_info["utime"] = order_info["timestamp"] order = self._update_order(order_info) if self._order_update_callback: SingleTask.run(self._order_update_callback, copy.copy(order)) # 订阅 order data = { "op": "subscribe", "args": [self._order_channel] } await self.ws.send_json(data) return # 订阅返回消息 if msg.get("event") == "subscribe": if msg.get("channel") == self._order_channel: if self._init_success_callback: SingleTask.run(self._init_success_callback, True, None) else: if self._init_success_callback: e = Error("subscribe order event error: {}".format(msg)) SingleTask.run(self._init_success_callback, False, e) return # 订单更新 if msg.get("table") == "spot/order": for data in msg["data"]: data["ctime"] = data["timestamp"] data["utime"] = data["last_fill_time"] order = self._update_order(data) if order and self._order_update_callback: SingleTask.run(self._order_update_callback, copy.copy(order))
def __init__(self, **kwargs): """ 初始化 """ e = None if not kwargs.get("account"): e = Error("param account miss") if not kwargs.get("strategy"): e = Error("param strategy miss") if not kwargs.get("symbol"): e = Error("param symbol miss") if not kwargs.get("host"): kwargs["host"] = "https://www.deribit.com" if not kwargs.get("wss"): kwargs["wss"] = "wss://deribit.com" if not kwargs.get("access_key"): e = Error("param access_key miss") if not kwargs.get("secret_key"): e = Error("param secret_key miss") if e: logger.error(e, caller=self) if kwargs.get("init_success_callback"): SingleTask.run(kwargs["init_success_callback"], False, e) return self._account = kwargs["account"] self._strategy = kwargs["strategy"] self._platform = DERIBIT self._symbol = kwargs["symbol"] self._host = kwargs["host"] self._wss = kwargs["wss"] self._access_key = kwargs["access_key"] self._secret_key = kwargs["secret_key"] self._asset_update_callback = kwargs.get("asset_update_callback") self._order_update_callback = kwargs.get("order_update_callback") self._position_update_callback = kwargs.get("position_update_callback") self._init_success_callback = kwargs.get("init_success_callback") self._order_channel = "user.orders.{symbol}.raw".format( symbol=self._symbol) # 订单订阅频道 url = self._wss + "/ws/api/v2" super(DeribitTrade, self).__init__(url, send_hb_interval=5) self._assets = { } # 资产 {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} # 订单 self._position = Position(self._platform, self._account, self._strategy, self._symbol) # 仓位 self._query_id = 0 # 消息序号id,用来唯一标识请求消息 self._queries = {} # 未完成的post请求 {"request_id": future} self.initialize() # 初始化资产订阅 if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) # 注册定时任务 LoopRunTask.register(self._do_auth, 60 * 60) # 每隔1小时重新授权 LoopRunTask.register(self._check_position_update, 1) # 获取持仓 self._ok = False # 是否建立授权成功的websocket连接
def __init__(self, strategy=None, platform=None, symbol=None, host=None, wss=None, account=None, access_key=None, secret_key=None, passphrase=None, asset_update_callback=None, order_update_callback=None, position_update_callback=None, init_success_callback=None, **kwargs): """ 初始化 @param strategy 策略名称 @param platform 交易平台 @param symbol 交易对 @param host 交易平台REST API地址 @param wss 交易平台websocket地址 @param account 交易账户 @param access_key 账户 ACCESS KEY @param secret_key 账户 SECRET KEY @param passphrase 账户交易密码(OKEx使用) @param asset_update_callback 资产更新回调,async异步函数 async asset_update_callback(asset): pass @param order_update_callback 订单更新回调,async异步函数 async order_update_callback(order): pass @param position_update_callback 持仓更新回调,async异步函数 async position_update_callback(position): pass @param init_success_callback 初始化成功回调,async异步函数 async init_success_callback(success, error): pass """ kwargs["strategy"] = strategy kwargs["platform"] = platform kwargs["symbol"] = symbol kwargs["host"] = host kwargs["wss"] = wss kwargs["account"] = account kwargs["access_key"] = access_key kwargs["secret_key"] = secret_key kwargs["passphrase"] = passphrase kwargs["asset_update_callback"] = asset_update_callback kwargs["order_update_callback"] = order_update_callback kwargs["position_update_callback"] = position_update_callback kwargs["init_success_callback"] = init_success_callback if platform == OKEX: from quant.platform.okex import OKExTrade as T elif platform == OKEX_MARGIN: from quant.platform.okex_margin import OKExMarginTrade as T elif platform == OKEX_FUTURE: from quant.platform.okex_future import OKExFutureTrade as T elif platform == DERIBIT: from quant.platform.deribit import DeribitTrade as T elif platform == BITMEX: from quant.platform.bitmex import BitmexTrade as T elif platform == BINANCE: from quant.platform.binance import BinanceTrade as T elif platform == HUOBI: from quant.platform.huobi import HuobiTrade as T else: logger.error("platform error:", platform, caller=self) if init_success_callback: e = Error("platform error") SingleTask.run(init_success_callback, False, e) return kwargs.pop("platform") self._t = T(**kwargs)
def __init__(self, **kwargs): """ 初始化 """ e = None if not kwargs.get("account"): e = Error("param account miss") if not kwargs.get("strategy"): e = Error("param strategy miss") if not kwargs.get("symbol"): e = Error("param symbol miss") if not kwargs.get("host"): kwargs["host"] = "https://www.okex.com" if not kwargs.get("wss"): kwargs["wss"] = "wss://real.okex.com:10442" if not kwargs.get("access_key"): e = Error("param access_key miss") if not kwargs.get("secret_key"): e = Error("param secret_key miss") if not kwargs.get("passphrase"): e = Error("param passphrase miss") if e: logger.error(e, caller=self) if kwargs.get("init_success_callback"): SingleTask.run(kwargs["init_success_callback"], False, e) return self._account = kwargs["account"] self._strategy = kwargs["strategy"] self._platform = OKEX_FUTURE self._symbol = kwargs["symbol"] self._host = kwargs["host"] self._wss = kwargs["wss"] self._access_key = kwargs["access_key"] self._secret_key = kwargs["secret_key"] self._passphrase = kwargs["passphrase"] self._asset_update_callback = kwargs.get("asset_update_callback") self._order_update_callback = kwargs.get("order_update_callback") self._position_update_callback = kwargs.get("position_update_callback") self._init_success_callback = kwargs.get("init_success_callback") url = self._wss + "/ws/v3" super(OKExFutureTrade, self).__init__(url, send_hb_interval=5) self.heartbeat_msg = "ping" self._assets = { } # 资产 {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} # 订单 self._position = Position(self._platform, self._account, self._strategy, self._symbol) # 仓位 # 订阅频道 self._order_channel = "futures/order:{symbol}".format( symbol=self._symbol) self._position_channel = "futures/position:{symbol}".format( symbol=self._symbol) # 标记订阅订单、持仓是否成功 self._subscribe_order_ok = False self._subscribe_position_ok = False # 初始化 REST API 对象 self._rest_api = OKExFutureRestAPI(self._host, self._access_key, self._secret_key, self._passphrase) # 初始化资产订阅 if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) self.initialize()
async def process_binary(self, raw): """ 处理websocket上接收到的消息 @param raw 原始的压缩数据 """ decompress = zlib.decompressobj(-zlib.MAX_WBITS) msg = decompress.decompress(raw) msg += decompress.flush() msg = msg.decode() if msg == "pong": # 心跳返回 return msg = json.loads(msg) logger.debug("msg:", msg, caller=self) # 登陆成功之后再订阅数据 if msg.get("event") == "login": if not msg.get("success"): e = Error( "Websocket connection authorized failed: {}".format(msg)) logger.error(e, caller=self) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return logger.info("Websocket connection authorized successfully.", caller=self) # 获取当前等待成交和部分成交的订单信息 result, error = await self._rest_api.get_order_list( self._symbol, 6) if error: e = Error("get open orders error: {}".format(error)) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return for order_info in result["order_info"]: order = self._update_order(order_info) if self._order_update_callback: SingleTask.run(self._order_update_callback, order) # 获取当前持仓 position, error = await self._rest_api.get_position(self._symbol) if error: e = Error("get position error: {}".format(error)) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return if len(position["holding"]) > 0: self._update_position(position["holding"][0]) if self._position_update_callback: SingleTask.run(self._position_update_callback, self.position) # 订阅account, order, position data = { "op": "subscribe", "args": [self._order_channel, self._position_channel] } await self.ws.send_json(data) return # 订阅返回消息 if msg.get("event") == "subscribe": if msg.get("channel") == self._order_channel: self._subscribe_order_ok = True if msg.get("channel") == self._position_channel: self._subscribe_position_ok = True if self._subscribe_order_ok and self._subscribe_position_ok: if self._init_success_callback: SingleTask.run(self._init_success_callback, True, None) return # 订单更新 if msg.get("table") == "futures/order": for data in msg["data"]: order = self._update_order(data) if order and self._order_update_callback: SingleTask.run(self._order_update_callback, order) return # 持仓更新 if msg.get("table") == "futures/position": for data in msg["data"]: self._update_position(data) if self._position_update_callback: SingleTask.run(self._position_update_callback, self.position)
def __init__(self, **kwargs): """Initialize.""" e = None if not kwargs.get("account"): e = Error("param account miss") if not kwargs.get("strategy"): e = Error("param strategy miss") if not kwargs.get("symbol"): e = Error("param symbol miss") if not kwargs.get("host"): kwargs["host"] = "https://www.okex.com" if not kwargs.get("wss"): kwargs["wss"] = "wss://real.okex.com:8443" if not kwargs.get("access_key"): e = Error("param access_key miss") if not kwargs.get("secret_key"): e = Error("param secret_key miss") if not kwargs.get("passphrase"): e = Error("param passphrase miss") if e: logger.error(e, caller=self) if kwargs.get("init_success_callback"): SingleTask.run(kwargs["init_success_callback"], False, e) return self._account = kwargs["account"] self._strategy = kwargs["strategy"] self._platform = OKEX_SWAP self._symbol = kwargs["symbol"] self._host = kwargs["host"] self._wss = kwargs["wss"] self._access_key = kwargs["access_key"] self._secret_key = kwargs["secret_key"] self._passphrase = kwargs["passphrase"] self._asset_update_callback = kwargs.get("asset_update_callback") self._order_update_callback = kwargs.get("order_update_callback") self._position_update_callback = kwargs.get("position_update_callback") self._init_success_callback = kwargs.get("init_success_callback") url = self._wss + "/ws/v3" super(OKExSwapTrade, self).__init__(url, send_hb_interval=5) self.heartbeat_msg = "ping" self._assets = {} # Asset object. e.g. {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} # Order objects. e.g. {"order_no": Order, ... } self._position = Position(self._platform, self._account, self._strategy, self._symbol) # Subscribing our channels. self._order_channel = "swap/order:{symbol}".format(symbol=self._symbol) self._position_channel = "swap/position:{symbol}".format(symbol=self._symbol) # If our channels that subscribed successfully. self._subscribe_order_ok = False self._subscribe_position_ok = False # Initializing our REST API client. self._rest_api = OKExSwapRestAPI(self._host, self._access_key, self._secret_key, self._passphrase) # Subscribing our asset event. if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) self.initialize()
async def process_binary(self, raw): """ Process binary message that received from websocket. Args: raw: Binary message received from websocket. Returns: None. """ decompress = zlib.decompressobj(-zlib.MAX_WBITS) msg = decompress.decompress(raw) msg += decompress.flush() msg = msg.decode() # Heartbeat message received. if msg == "pong": return logger.debug("msg:", msg, caller=self) msg = json.loads(msg) # Authorization message received. if msg.get("event") == "login": if not msg.get("success"): e = Error("Websocket connection authorized failed: {}".format(msg)) logger.error(e, caller=self) SingleTask.run(self._init_success_callback, False, e) return logger.info("Websocket connection authorized successfully.", caller=self) # Fetch orders from server. (open + partially filled) result, error = await self._rest_api.get_order_list(self._symbol, 6) if error: e = Error("get open orders error: {}".format(error)) SingleTask.run(self._init_success_callback, False, e) return if len(result) > 100: logger.warn("order length too long! (more than 100)", caller=self) for order_info in result["order_info"]: self._update_order(order_info) # Fetch positions from server. position, error = await self._rest_api.get_position(self._symbol) if error: e = Error("get position error: {}".format(error)) SingleTask.run(self._init_success_callback, False, e) return self._update_position(position) # Subscribe order channel and position channel. data = { "op": "subscribe", "args": [self._order_channel, self._position_channel] } await self.ws.send_json(data) return # Subscribe response message received. if msg.get("event") == "subscribe": if msg.get("channel") == self._order_channel: self._subscribe_order_ok = True if msg.get("channel") == self._position_channel: self._subscribe_position_ok = True if self._subscribe_order_ok and self._subscribe_position_ok: SingleTask.run(self._init_success_callback, True, None) return # Order update message received. if msg.get("table") == "swap/order": for data in msg["data"]: self._update_order(data) return # Position update message receive. if msg.get("table") == "swap/position": for data in msg["data"]: self._update_position(data)
async def connected_callback(self): """ 建立连接之后,获取当前所有未完全成交的订单 """ logger.info("Websocket connection authorized successfully.", caller=self) order_infos, error = await self._rest_api.get_open_orders( self._raw_symbol) if error: e = Error("get open orders error: {}".format(error)) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return for order_info in order_infos: order_no = "{}_{}".format(order_info["orderId"], order_info["clientOrderId"]) if order_info["status"] == "NEW": # 部分成交 status = ORDER_STATUS_SUBMITTED elif order_info["status"] == "PARTIALLY_FILLED": # 部分成交 status = ORDER_STATUS_PARTIAL_FILLED elif order_info["status"] == "FILLED": # 完全成交 status = ORDER_STATUS_FILLED elif order_info["status"] == "CANCELED": # 取消 status = ORDER_STATUS_CANCELED elif order_info["status"] == "REJECTED": # 拒绝 status = ORDER_STATUS_FAILED elif order_info["status"] == "EXPIRED": # 过期 status = ORDER_STATUS_FAILED else: logger.warn("unknown status:", order_info, caller=self) continue info = { "platform": self._platform, "account": self._account, "strategy": self._strategy, "order_no": order_no, "action": order_info["side"], "order_type": order_info["type"], "symbol": self._symbol, "price": order_info["price"], "quantity": order_info["origQty"], "remain": float(order_info["origQty"]) - float(order_info["executedQty"]), "status": status, "ctime": order_info["time"], "utime": order_info["updateTime"] } order = Order(**info) self._orders[order_no] = order if self._order_update_callback: SingleTask.run(self._order_update_callback, order) if self._init_success_callback: SingleTask.run(self._init_success_callback, True, None)
def __init__(self, strategy=None, platform=None, symbol=None, host=None, wss=None, account=None, access_key=None, secret_key=None, passphrase=None, asset_update_callback=None, order_update_callback=None, position_update_callback=None, init_success_callback=None, **kwargs): """initialize trade object.""" kwargs["strategy"] = strategy kwargs["platform"] = platform kwargs["symbol"] = symbol kwargs["host"] = host kwargs["wss"] = wss kwargs["account"] = account kwargs["access_key"] = access_key kwargs["secret_key"] = secret_key kwargs["passphrase"] = passphrase kwargs["asset_update_callback"] = asset_update_callback kwargs["order_update_callback"] = self._on_order_update_callback kwargs["position_update_callback"] = self._on_position_update_callback kwargs["init_success_callback"] = self._on_init_success_callback self._raw_params = copy.copy(kwargs) self._order_update_callback = order_update_callback self._position_update_callback = position_update_callback self._init_success_callback = init_success_callback if platform == const.OKEX: from quant.platform.okex import OKExTrade as T elif platform == const.OKEX_MARGIN: from quant.platform.okex_margin import OKExMarginTrade as T elif platform == const.OKEX_FUTURE: from quant.platform.okex_future import OKExFutureTrade as T elif platform == const.OKEX_SWAP: from quant.platform.okex_swap import OKExSwapTrade as T elif platform == const.DERIBIT: from quant.platform.deribit import DeribitTrade as T elif platform == const.BITMEX: from quant.platform.bitmex import BitmexTrade as T elif platform == const.BINANCE: from quant.platform.binance import BinanceTrade as T elif platform == const.BINANCE_FUTURE: from quant.platform.binance_future import BinanceFutureTrade as T elif platform == const.HUOBI: from quant.platform.huobi import HuobiTrade as T elif platform == const.COINSUPER: from quant.platform.coinsuper import CoinsuperTrade as T elif platform == const.COINSUPER_PRE: from quant.platform.coinsuper_pre import CoinsuperPreTrade as T elif platform == const.KRAKEN: from quant.platform.kraken import KrakenTrade as T elif platform == const.GATE: from quant.platform.gate import GateTrade as T elif platform == const.KUCOIN: from quant.platform.kucoin import KucoinTrade as T elif platform == const.HUOBI_FUTURE: from quant.platform.huobi_future import HuobiFutureTrade as T elif platform == const.DIGIFINEX: from quant.platform.digifinex import DigifinexTrade as T else: logger.error("platform error:", platform, caller=self) e = Error("platform error") SingleTask.run(self._init_success_callback, False, e) return kwargs.pop("platform") self._t = T(**kwargs)
def __init__(self, **kwargs): """Initialize.""" self.cb = kwargs["cb"] e = None if kwargs.get("account") and (not kwargs.get("access_key") or not kwargs.get("secret_key")): e = Error("param access_key or secret_key miss") elif not kwargs.get("strategy"): e = Error("param strategy miss") elif not kwargs.get("symbols"): e = Error("param symbols miss") elif not kwargs.get("platform"): e = Error("param platform miss") if e: logger.error(e, caller=self) SingleTask.run(self.cb.on_init_success_callback, False, e) return if not kwargs.get("host"): kwargs["host"] = "https://ftx.com" if not kwargs.get("wss"): kwargs["wss"] = "wss://ftx.com" self._account = kwargs.get("account") self._access_key = kwargs.get("access_key") self._secret_key = kwargs.get("secret_key") self._subaccount_name = kwargs.get("subaccount_name") self._strategy = kwargs["strategy"] self._platform = kwargs["platform"] self._symbols = kwargs["symbols"] self._host = kwargs["host"] self._wss = kwargs["wss"] url = self._wss + "/ws" super(FTXTrader, self).__init__(url, check_conn_interval=5, send_hb_interval=0) #self.heartbeat_msg = "ping" # Initializing our REST API client. self._rest_api = FTXRestAPI(self._host, self._access_key, self._secret_key, self._subaccount_name) self.raw_kwargs = { "platform": kwargs["platform"], "account": kwargs.get("account"), "symbols": kwargs["symbols"], "strategy": kwargs["strategy"] } #订单簿深度数据 self._orderbooks: DefaultDict[str, Dict[str, DefaultDict[ float, float]]] = defaultdict( lambda: {side: defaultdict(float) for side in {'bids', 'asks'}}) self._assets = {} self.initialize()
async def process_binary(self, raw): """ Process binary message that received from websocket. Args: raw: Binary message received from websocket. Returns: None. """ decompress = zlib.decompressobj(-zlib.MAX_WBITS) msg = decompress.decompress(raw) msg += decompress.flush() msg = msg.decode() if msg == "pong": return logger.debug("msg:", msg, caller=self) msg = json.loads(msg) # Authorization message received. if msg.get("event") == "login": if not msg.get("success"): e = Error( "Websocket connection authorized failed: {}".format(msg)) logger.error(e, caller=self) SingleTask.run(self._init_success_callback, False, e) return logger.info("Websocket connection authorized successfully.", caller=self) # Fetch orders from server. (open + partially filled) order_infos, error = await self._rest_api.get_open_orders( self._raw_symbol) if error: e = Error("get open orders error: {}".format(msg)) SingleTask.run(self._init_success_callback, False, e) return if len(order_infos) > 100: logger.warn("order length too long! (more than 100)", caller=self) for order_info in order_infos: order_info["ctime"] = order_info["created_at"] order_info["utime"] = order_info["timestamp"] self._update_order(order_info) # Subscribe order channel. data = {"op": "subscribe", "args": [self._order_channel]} await self.ws.send_json(data) return # Subscribe response message received. if msg.get("event") == "subscribe": if msg.get("channel") == self._order_channel: SingleTask.run(self._init_success_callback, True, None) else: e = Error("subscribe order event error: {}".format(msg)) SingleTask.run(self._init_success_callback, False, e) return # Order update message received. if msg.get("table") == "spot/order": for data in msg["data"]: data["ctime"] = data["timestamp"] data["utime"] = data["last_fill_time"] self._update_order(data)
def __init__(self, **kwargs): """Initialize.""" e = None if not kwargs.get("account"): e = Error("param account miss") if not kwargs.get("strategy"): e = Error("param strategy miss") if not kwargs.get("symbol"): e = Error("param symbol miss") if not kwargs.get("contract_type"): e = Error("param contract_type miss") if not kwargs.get("contract_code"): e = Error("param contract_code miss") if not kwargs.get("host"): kwargs["host"] = "https://api.hbdm.com" if not kwargs.get("wss"): kwargs["wss"] = "wss://api.hbdm.com" if not kwargs.get("access_key"): e = Error("param access_key miss") if not kwargs.get("secret_key"): e = Error("param secret_key miss") if e: logger.error(e, caller=self) if kwargs.get("init_success_callback"): SingleTask.run(kwargs["init_success_callback"], False, e) return self._account = kwargs["account"] self._strategy = kwargs["strategy"] self._platform = HUOBI_FUTURE self._symbol = kwargs["symbol"] self._contract_type = kwargs["contract_type"] self._contract_code = kwargs["contract_code"] self._host = kwargs["host"] self._wss = kwargs["wss"] self._access_key = kwargs["access_key"] self._secret_key = kwargs["secret_key"] self._asset_update_callback = kwargs.get("asset_update_callback") self._order_update_callback = kwargs.get("order_update_callback") self._position_update_callback = kwargs.get("position_update_callback") self._init_success_callback = kwargs.get("init_success_callback") url = self._wss + "/notification" self._ws = Websocket(url, self.connected_callback, process_binary_callback=self.process_binary) self._ws.initialize() self._assets = { } # Asset detail, {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... }. self._orders = {} # Order objects, {"order_id": order, ...}. self._position = Position(self._platform, self._account, self._strategy, self._contract_code) self._order_channel = "orders.{symbol}".format( symbol=self._symbol.lower()) self._position_channel = "positions.{symbol}".format( symbol=self._symbol.lower()) self._subscribe_order_ok = False self._subscribe_position_ok = False self._rest_api = HuobiFutureRestAPI(self._host, self._access_key, self._secret_key) # Subscribe AssetEvent. if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update)
def __init__(self, **kwargs): """ 初始化 """ e = None if not kwargs.get("account"): e = Error("param account miss") if not kwargs.get("strategy"): e = Error("param strategy miss") if not kwargs.get("symbol"): e = Error("param symbol miss") if not kwargs.get("host"): kwargs["host"] = "https://www.okex.com" if not kwargs.get("wss"): kwargs["wss"] = "wss://real.okex.com:10442" if not kwargs.get("access_key"): e = Error("param access_key miss") if not kwargs.get("secret_key"): e = Error("param secret_key miss") if not kwargs.get("passphrase"): e = Error("param passphrase miss") if e: logger.error(e, caller=self) if kwargs.get("init_success_callback"): SingleTask.run(kwargs["init_success_callback"], False, e) return self._account = kwargs["account"] self._strategy = kwargs["strategy"] self._platform = OKEX self._symbol = kwargs["symbol"] self._host = kwargs["host"] self._wss = kwargs["wss"] self._access_key = kwargs["access_key"] self._secret_key = kwargs["secret_key"] self._passphrase = kwargs["passphrase"] self._asset_update_callback = kwargs.get("asset_update_callback") self._order_update_callback = kwargs.get("order_update_callback") self._init_success_callback = kwargs.get("init_success_callback") self._raw_symbol = self._symbol.replace("/", "-") # 转换成交易所对应的交易对格式 self._order_channel = "spot/order:{symbol}".format( symbol=self._raw_symbol) # 订单订阅频道 url = self._wss + "/ws/v3" super(OKExTrade, self).__init__(url, send_hb_interval=5) self.heartbeat_msg = "ping" self._assets = { } # 资产 {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} # 订单 {"order_no": order, ... } # 初始化 REST API 对象 self._rest_api = OKExRestAPI(self._host, self._access_key, self._secret_key, self._passphrase) # 初始化资产订阅 if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) self.initialize()
def __init__(self, **kwargs): """Initialize Trade module.""" e = None if not kwargs.get("account"): e = Error("param account miss") if not kwargs.get("strategy"): e = Error("param strategy miss") if not kwargs.get("symbol"): e = Error("param symbol miss") if not kwargs.get("host"): kwargs["host"] = "https://fapi.binance.com" if not kwargs.get("wss"): kwargs["wss"] = "wss://fstream.binance.com" if not kwargs.get("access_key"): e = Error("param access_key miss") if not kwargs.get("secret_key"): e = Error("param secret_key miss") if e: logger.error(e, caller=self) if kwargs.get("init_success_callback"): SingleTask.run(kwargs["init_success_callback"], False, e) return self._account = kwargs["account"] self._strategy = kwargs["strategy"] self._platform = BINANCE_FUTURE self._symbol = kwargs["symbol"] self._host = kwargs["host"] self._wss = kwargs["wss"] self._access_key = kwargs["access_key"] self._secret_key = kwargs["secret_key"] self._asset_update_callback = kwargs.get("asset_update_callback") self._order_update_callback = kwargs.get("order_update_callback") self._position_update_callback = kwargs.get("position_update_callback") self._init_success_callback = kwargs.get("init_success_callback") self._ok = False # Initialize successfully ? self._raw_symbol = self._symbol # Row symbol name, same as Binance Exchange. self._listen_key = None # Listen key for Websocket authentication. self._assets = { } # Asset data. e.g. {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} # Order data. e.g. {order_no: order, ... } self._position = Position(self._platform, self._account, self._strategy, self._symbol) # 仓位 # Initialize our REST API client. self._rest_api = BinanceFutureRestAPI(self._host, self._access_key, self._secret_key) # Subscribe our AssetEvent. if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) # Create a loop run task to reset listen key every 20 minutes. LoopRunTask.register(self._reset_listen_key, 60 * 20) # Create a loop run task to check position information per 1 second. LoopRunTask.register(self._check_position_update, 1) # Create a loop run task to send ping message to server per 30 seconds. # LoopRunTask.register(self._send_heartbeat_msg, 10) # Create a coroutine to initialize Websocket connection. SingleTask.run(self._init_websocket)