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://api.gateio.ws" if not kwargs.get("wss"): kwargs["wss"] = "wss://fx-ws.gateio.ws" 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 = GATE_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._contract_update_callback = kwargs.get('contract_update_callback') self._user_id = None url = self._wss + "/v4/ws" super(GateFutureTrade, 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, ... } self._position = Position(self._platform, self._account, self._strategy, self._symbol) # 初始化 REST API 对象 self._rest_api = GateFutureRestAPI(self._host, self._access_key, self._secret_key) # 初始化资产订阅 if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) # 注册定时任务 LoopRunTask.register(self._check_position_update, 1) # 获取持仓
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://api.testnet.fmex.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 = FCOIN_FUTURE self._symbol = kwargs["symbol"] self._host = kwargs["host"] 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._update_order_interval = kwargs.get("update_order_interval", 1) 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._subscribe_order_ok = False self._subscribe_position_ok = False # 初始化 REST API 对象 self._rest_api = FCoinFutureRestAPI(self._host, self._access_key, self._secret_key) # 初始化资产订阅 if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) # 注册定时任务,定时查询订单更新、仓位更新情况 if self._position_update_callback: LoopRunTask.register(self._check_position_update, 60) # 初始化订单订阅 if self._order_update_callback: LoopRunTask.register(self.check_order_update, self._update_order_interval)
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.bitmex.com" if not kwargs.get("wss"): kwargs["wss"] = "wss://www.bitmex.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 = BITMEX 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") url = self._wss + "/realtime" super(BitmexTrade, self).__init__(url, send_hb_interval=5) self.heartbeat_msg = "ping" self._order_channel = "order:{symbol}".format(symbol=self._symbol) # 订单订阅频道 self._position_channel = "position:{symbol}".format(symbol=self._symbol) # 持仓订阅频道 # 标记订阅订单、持仓是否成功 self._subscribe_order_ok = False self._subscribe_position_ok = False self._assets = {} # 资产 {"XBT": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} self._position = Position(self._platform, self._account, self._strategy, self._symbol) # 仓位 # 初始化REST API对象 self._rest_api = BitmexAPI(self._host, self._access_key, self._secret_key) # 初始化资产订阅 if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) self.initialize()
async def _initialize(self): """ Initialize of Fetching open orders information. """ order_nos, error = await self._rest_api.get_open_order_nos( self._raw_symbol) if error: e = Error("get open order nos failed: {}".format(error)) logger.error(e, caller=self) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return while order_nos: nos = order_nos[:50] order_nos = order_nos[50:] success, error = await self._rest_api.get_order_list(nos) if error: e = Error("get order infos failed: {}".format(error)) logger.error(e, caller=self) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return for order_info in success: await self._update_order(order_info) if self._init_success_callback: SingleTask.run(self._init_success_callback, True, None)
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, **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://api.binance.com" if not kwargs.get("wss"): kwargs["wss"] = "wss://stream.binance.com:9443" 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 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._init_success_callback = kwargs.get("init_success_callback") super(BinanceTrade, self).__init__(self._wss) self._raw_symbol = self._symbol.replace( "/", "") # 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, ... } # Initialize our REST API client. self._rest_api = BinanceRestAPI(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 30 minutes. LoopRunTask.register(self._reset_listen_key, 60 * 30) # Create a coroutine to initialize Websocket connection. SingleTask.run(self._init_websocket)
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://api.binance.com" if not kwargs.get("wss"): kwargs["wss"] = "wss://stream.binance.com:9443" 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 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._init_success_callback = kwargs.get("init_success_callback") super(BinanceTrade, self).__init__(self._wss) self._raw_symbol = self._symbol.replace("/", "") # 原始交易对 self._listen_key = None # websocket连接鉴权使用 self._assets = { } # 资产 {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} # 订单 # 初始化 REST API 对象 self._rest_api = BinanceRestAPI(self._host, self._access_key, self._secret_key) # 初始化资产订阅 if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) # 30分钟重置一下listen key LoopRunTask.register(self._reset_listen_key, 60 * 30) # 获取listen key SingleTask.run(self._init_websocket)
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://api.huobi.pro" if not kwargs.get("wss"): kwargs["wss"] = "wss://api.huobi.pro" 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 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._init_success_callback = kwargs.get("init_success_callback") self._raw_symbol = self._symbol.replace("/", "").lower() # 转换成交易所对应的交易对格式 self._order_channel = "orders.{}".format(self._raw_symbol) # 订阅订单更新频道 url = self._wss + "/ws/v1" super(HuobiTrade, self).__init__(url, send_hb_interval=0) self._assets = { } # 资产 {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} # 订单 # 初始化 REST API 对象 self._rest_api = HuobiRestAPI(self._host, self._access_key, self._secret_key) # 初始化资产订阅 if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) self.initialize()
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://api.coinsuper.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 = COINSUPER self._symbol = kwargs["symbol"] self._host = kwargs["host"] 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._init_success_callback = kwargs.get("init_success_callback") self._check_order_interval = kwargs.get("check_order_interval", 2) # 检查订单状态更新时间间隔(秒),默认2秒 self._raw_symbol = self._symbol # 原始交易对 self._assets = { } # 资产 {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} # 订单 # 初始化 REST API 对象 self._rest_api = CoinsuperRestAPI(self._host, self._access_key, self._secret_key) # 循环更新订单状态 LoopRunTask.register(self._check_order_update, self._check_order_interval) # 初始化资产订阅 if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) SingleTask.run(self._initialize)
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://api.gateio.co" 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 = GATE self._symbol = kwargs["symbol"] self._host = kwargs["host"] 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._init_success_callback = kwargs.get("init_success_callback") self._check_order_interval = kwargs.get("check_order_interval", 2) self._raw_symbol = self._symbol.replace( "/", "_").lower() # Raw symbol name for Exchange platform. self._assets = { } # Asset information. e.g. {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} # Order details. e.g. {order_no: order-object, ... } # Initialize our REST API client. self._rest_api = GateRestAPI(self._host, self._access_key, self._secret_key) # Create a loop run task to check order status. LoopRunTask.register(self._check_order_update, self._check_order_interval) # Subscribe asset event. if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update) SingleTask.run(self._initialize)
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://api.fcoin.com/v2/' 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 = FCOIN_MARGIN self._symbol = kwargs["symbol"] self._host = kwargs["host"] 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._init_success_callback = kwargs.get("init_success_callback") self._update_order_interval = kwargs.get("update_order_interval", 1) self._raw_symbol = self._symbol.replace("/", "").lower() # 转换成交易所对应的交易对格式 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 = FCoinMarginRestAPI(self._host, self._access_key, self._secret_key) # 初始化资产订阅 if self._asset_update_callback: AssetSubscribe(self._platform, self._account, self.on_event_asset_update)
def __init__(self, **kwargs): """initialize trader object. Args: strategy: 策略名称,由哪个策略发起 platform: 交易平台 symbols: 策略需要订阅和交易的币种 account: 交易所登陆账号,如果为空就只是订阅市场公共行情数据,不进行登录认证,所以也无法进行交易等 access_key: 登录令牌 secret_key: 令牌密钥 cb: ExchangeGateway.ICallBack { on_init_success_callback: `初始化是否成功`回调通知函数 on_kline_update_callback: `K线数据`回调通知函数 (值为None就不启用此通知回调) on_orderbook_update_callback: `订单簿深度数据`回调通知函数 (值为None就不启用此通知回调) on_trade_update_callback: `市场最新成交`回调通知函数 (值为None就不启用此通知回调) on_ticker_update_callback: `市场行情tick`回调通知函数 (值为None就不启用此通知回调) on_order_update_callback: `用户挂单`回调通知函数 (值为None就不启用此通知回调) on_fill_update_callback: `用户挂单成交`回调通知函数 (值为None就不启用此通知回调) on_position_update_callback: `用户持仓`回调通知函数 (值为None就不启用此通知回调) on_asset_update_callback: `用户资产`回调通知函数 (值为None就不启用此通知回调) } """ T = gateway_class(kwargs["platform"]) if T == None: logger.error("platform not found:", kwargs["platform"], caller=self) cb = kwargs["cb"] SingleTask.run(cb.on_init_success_callback, False, Error("platform not found")) return self._t = T(**kwargs)
async def _auth_success_callback(self): """ 授权成功之后回调 """ # 获取当前未完成订单 success, 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 success: data = { "order-id": order_info["id"], "order-type": order_info["type"], "order-state": order_info["state"], "unfilled-amount": float(order_info["amount"]) - float(order_info["filled-amount"]), "order-price": float(order_info["price"]), "price": float(order_info["price"]), "order-amount": float(order_info["amount"]), "created-at": order_info["created-at"], "utime": order_info["created-at"], } self._update_order(data) # 订阅订单更新数据 params = { "op": "sub", "topic": self._order_channel } await self.ws.send_json(params)
async def revoke_all_order(self): data, error = await self._rest_api.get_order_list(self._symbol) if error: return None, error else: open_order_ids = [item['id'] for item in data['data']['list']] if len(open_order_ids) == 0: return [], None result, error = await self._rest_api.revoke_orders(*open_order_ids) if error: return None, error else: revoked_order_ids = result.get('data', []) if revoked_order_ids == open_order_ids: return [], None else: unrevoked_num = len(open_order_ids) - len( revoked_order_ids) if unrevoked_num > 0: unrevoked_orders = [ id for id in open_order_ids if id not in revoked_order_ids ] return None, Error('还剩余{}个订单等待撤销,订单号为 {}'.format( unrevoked_num, unrevoked_orders)) else: return [], 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._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.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 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)
async def process(self, msg): """ 处理websocket上接收到的消息 """ if not isinstance(msg, dict): return logger.debug("msg:", json.dumps(msg), caller=self) # 请求授权、订阅 if msg.get("request"): if msg["request"]["op"] == "authKeyExpires": # 授权 if msg["success"]: # 订阅order和position data = { "op": "subscribe", "args": [self._order_channel, self._position_channel] } await self.ws.send_json(data) logger.info( "Websocket connection authorized successfully.", caller=self) else: 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) if msg["request"]["op"] == "subscribe": # 订阅 if msg["subscribe"] == self._order_channel and msg["success"]: self._subscribe_order_ok = True logger.info("subscribe order successfully.", caller=self) if msg["subscribe"] == self._position_channel and msg[ "success"]: self._subscribe_position_ok = True logger.info("subscribe position successfully.", caller=self) 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") == "order": for data in msg["data"]: order = self._update_order(data) if order and self._order_update_callback: SingleTask.run(self._order_update_callback, copy.copy(order)) return # 持仓更新 if msg.get("table") == "position": for data in msg["data"]: self._update_position(data) if self._position_update_callback: SingleTask.run(self._position_update_callback, copy.copy(self.position))
async def connected_callback(self): """ 建立连接之后,授权登陆,然后订阅order和position """ # 授权 success, error = await self._do_auth() if error or not success.get("access_token"): e = Error("Websocket connection authorized failed: {}".format(error)) 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) self._ok = True # 获取未完全成交的订单 success, error = await self.get_open_orders() 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 success: order = self._update_order(order_info) if self._order_update_callback: SingleTask.run(self._order_update_callback, copy.copy(order)) # 获取持仓 await self._check_position_update() # 授权成功之后,订阅数据 method = "private/subscribe" params = { "channels": [ self._order_channel ] } _, error = await self._send_message(method, params) if error: e = Error("subscribe order error: {}".format(error)) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) else: if self._init_success_callback: SingleTask.run(self._init_success_callback, True, None)
async def process(self, msg): """ Process message that received from websocket. Args: msg: message received from websocket. Returns: None. """ if not isinstance(msg, dict): return logger.debug("msg:", json.dumps(msg), caller=self) #{"type": "error", "code": 400, "msg": "Invalid login credentials"} if msg["type"] == "error": e = Error("Websocket connection failed: {}".format(msg)) logger.error(e, caller=self) SingleTask.run(self.cb.on_init_success_callback, False, e, **self.raw_kwargs) return if msg["type"] == "info" and msg["code"] == 20001: #交易所重启了,我们就断开连接,websocket会自动重连 @async_method_locker("FTXTrader._ws_close.locker") async def _ws_close(self): await self.ws.close() SingleTask.run(self._ws_close) return #{'type': 'subscribed', 'channel': 'trades', 'market': 'BTC-PERP'} if msg["type"] == "unsubscribed": return if msg["type"] == "subscribed": for sym in self._symbols: if self.cb.on_order_update_callback != None: orders, err = await self.get_orders(sym) if not err: for o in orders: SingleTask.run(self.cb.on_order_update_callback, o) #end for return channel = msg['channel'] if channel == 'orderbook': self._update_orderbook(msg) elif channel == 'trades': self._update_trades(msg) elif channel == 'ticker': self._update_ticker(msg) elif channel == 'orders': self._update_order(msg) elif channel == 'fills': self._update_fill(msg)
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 elif platform == COINSUPER: from quant.platform.coinsuper import CoinsuperTrade 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)
async def sub_callback(self, data): if data["err-code"] != 0: e = Error("subscribe {} failed!".format(data["topic"])) logger.error(e, caller=self) SingleTask.run(self._init_success_callback, False, e) return if data["topic"] == self._order_channel: self._subscribe_order_ok = True elif data["topic"] == self._position_channel: self._subscribe_position_ok = True if self._subscribe_order_ok and self._subscribe_position_ok: success, error = await self._rest_api.get_open_orders(self._symbol) if error: e = Error("get open orders failed!") SingleTask.run(self._init_success_callback, False, e) for order_info in success["data"]["orders"]: order_info["ts"] = order_info["created_at"] self._update_order(order_info) SingleTask.run(self._init_success_callback, True, None)
async def process(self, msg): channel = msg['channel'] event = msg['event'] result = msg['result'] if channel == "futures.orders": # 订单订阅返回消息 if event == "subscribe": error = msg['error'] if error: if self._init_success_callback: e = Error( "subscribe order event error: {}".format(error)) SingleTask.run(self._init_success_callback, False, e) else: # 获取之前未完成的订单信息并推送 result, error = await self._rest_api.get_order_list( self._symbol, open) 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: is_update, order = self._update_order(order_info) if is_update: if self._order_update_callback: SingleTask.run(self._order_update_callback, copy.copy(order)) # 订单更新推送 else: for data in result: is_update, order = self._update_order(data) if is_update: if order and self._order_update_callback: SingleTask.run(self._order_update_callback, copy.copy(order)) return else: logger.warn("unhandle msg:", msg, caller=self)
async def _initialize(self): """ Initialize. fetch all open order information.""" result, error = await self._rest_api.get_open_orders(self._raw_symbol) if error: e = Error("get open order nos failed: {}".format(error)) logger.error(e, caller=self) SingleTask.run(self._init_success_callback, False, e) return for order_info in result["data"]: await self._update_order(order_info) SingleTask.run(self._init_success_callback, True, None)
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 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 = { } # Asset object. e.g. {"BTC": {"free": "1.1", "locked": "2.2", "total": "3.3"}, ... } self._orders = {} # Order objects. e.g. {"order_no": Order, ... } # Initializing our REST API client. self._rest_api = OKExRestAPI(self._host, self._access_key, self._secret_key, self._passphrase) # Subscribing AssetEvent. 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 原始的压缩数据 """ msg = json.loads(gzip.decompress(raw).decode()) logger.debug("msg:", msg, caller=self) op = msg.get("op") if op == "auth": # 授权 if msg["err-code"] != 0: 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) await self._auth_success_callback() elif op == "ping": # ping params = { "op": "pong", "ts": msg["ts"] } await self.ws.send_json(params) elif op == "sub": # 订阅频道返回消息 if msg["topic"] != self._order_channel: return if msg["err-code"] != 0: if self._init_success_callback: e = Error("subscribe order event error: {}".format(msg)) SingleTask.run(self._init_success_callback, False, e) else: if self._init_success_callback: SingleTask.run(self._init_success_callback, True, None) elif op == "notify": # 订单更新通知 if msg["topic"] != self._order_channel: return data = msg["data"] data["utime"] = msg["ts"] 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("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._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() LoopRunTask.register(self.send_heartbeat_msg, 5) 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._symbol + '/' + self._contract_type) 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)
async def connected_callback(self): """ After websocket connection created successfully, pull back all open order information. """ 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, copy.copy(order)) if self._init_success_callback: SingleTask.run(self._init_success_callback, True, None)
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_MARGIN 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(OKExMarginTrade, 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 = OKExMarginRestAPI(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 _init_websocket(self): """ Initialize Websocket connection. """ # Get listen key first. success, error = await self._rest_api.get_listen_key() if error: e = Error("get listen key failed: {}".format(error)) logger.error(e, caller=self) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return self._listen_key = success["listenKey"] uri = "/ws/" + self._listen_key self._url = urljoin(self._wss, uri) self.initialize()
async def _initialize(self): """ 初始化 """ # 获取当前所有未完全成交的订单 order_nos, error = await self._rest_api.get_open_order_nos( self._raw_symbol) if error: e = Error("get open order nos failed: {}".format(error)) logger.error(e, caller=self) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return if order_nos: success, error = await self._rest_api.get_order_list(order_nos) if error: e = Error("get order infos failed: {}".format(error)) logger.error(e, caller=self) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return for order_info in success: await self._update_order(order_info) if self._init_success_callback: SingleTask.run(self._init_success_callback, True, None)
async def _initialize(self): """ Initialize. fetch all open order information.""" result, error = await self._rest_api.get_open_orders() if error: e = Error("get open order nos failed: {}".format(error)) logger.error(e, caller=self) if self._init_success_callback: SingleTask.run(self._init_success_callback, False, e) return for order_no, order_info in result["open"].items(): if order_info["descr"]["pair"] != self._raw_symbol: continue await self._update_order(order_no, order_info) if self._init_success_callback: SingleTask.run(self._init_success_callback, True, None)