예제 #1
0
    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连接
예제 #2
0
    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)
예제 #3
0
    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()
예제 #4
0
    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)
예제 #5
0
    def __init__(self, account, strategy, symbol, host=None, wss=None, access_key=None, secret_key=None,
                 order_update_callback=None, position_update_callback=None):
        """ 初始化
        @param account 账户
        @param strategy 策略名称
        @param symbol 交易对(合约名称)
        @param host HTTP请求主机地址
        @param wss websocket连接地址
        @param access_key ACCESS KEY
        @param secret_key SECRET KEY
        @param order_update_callback 订单更新回调
        @param position_update_callback 持仓更新回调
        """
        self._account = account
        self._strategy = strategy
        self._platform = BITMEX
        self._symbol = symbol
        self._host = host
        self._wss = wss
        self._access_key = access_key
        self._secret_key = secret_key

        self._order_update_callback = order_update_callback
        self._position_update_callback = position_update_callback

        super(BitmexTrade, self).__init__(self._wss, send_hb_interval=5)
        self.heartbeat_msg = "ping"

        self._orders = {}
        self._position = Position(self._platform, self._account, strategy, symbol)  # 仓位

        # 初始化REST API对象
        self._rest_api = BitmexAPI(self._host, self._access_key, self._secret_key)

        self.initialize()
예제 #6
0
    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)  # 获取持仓
예제 #7
0
    def __init__(self,
                 account,
                 strategy,
                 symbol,
                 host=None,
                 wss=None,
                 access_key=None,
                 secret_key=None,
                 passphrase=None,
                 order_update_callback=None,
                 position_update_callback=None):
        """ 初始化
        @param account 账户
        @param strategy 策略名称
        @param symbol 交易对(合约名称)
        @param host HTTP请求主机地址
        @param wss websocket连接地址
        @param access_key ACCESS KEY
        @param secret_key SECRET KEY
        @param passphrase 密码
        @param order_update_callback 订单更新回调
        @param position_update_callback 持仓更新回调
        """
        self._account = account
        self._strategy = strategy
        self._platform = OKEX_FUTURE
        self._symbol = symbol
        self._host = host if host else "https://www.okex.com"
        self._wss = wss if wss else "wss://real.okex.com:10442/ws/v3"
        self._access_key = access_key
        self._secret_key = secret_key
        self._passphrase = passphrase

        self._order_update_callback = order_update_callback
        self._position_update_callback = position_update_callback

        super(OKExFutureTrade, self).__init__(self._wss, send_hb_interval=5)
        self.heartbeat_msg = "ping"

        self._orders = {}  # 订单
        self._position = Position(self._platform, self._account, strategy,
                                  symbol)  # 仓位

        # 初始化 REST API 对象
        self._rest_api = OKExFutureRestAPI(self._host, self._access_key,
                                           self._secret_key, self._passphrase)

        self.initialize()
예제 #8
0
    async def get_position(self, symbol):
        """ 获取当前持仓

        Args:
            symbol: Trade target

        Returns:
            position: Position if successfully, otherwise it's None.
            error: Error information, otherwise it's None.
        """

        #{"result": [{"collateralUsed": 0.35986, "cost": -1.7984, "entryPrice": 179.84, "estimatedLiquidationPrice": 11184.0123266, "future": "ETH-PERP", "initialMarginRequirement": 0.2, "longOrderSize": 0.0, "maintenanceMarginRequirement": 0.03, "netSize": -0.01, "openSize": 0.01, "realizedPnl": 0.01866927, "recentAverageOpenPrice": 179.84, "recentPnl": -0.0009, "shortOrderSize": 0.0, "side": "sell", "size": 0.01, "unrealizedPnl": -0.0009}], "success": true}

        success, error = await self._rest_api.get_positions(True)
        if error:
            return None, error
        if not success["success"]:
            return None, "get_position error"

        p = next(filter(lambda x: x['future'] == symbol, success["result"]),
                 None)
        if p == None:
            return None, "symbol not exist"

        if p["netSize"] == 0:
            return None, "currently no positions"

        pos = Position(self._platform, self._account, self._strategy, symbol)
        if p["netSize"] < 0:
            #空头仓位
            pos.update(short_quantity=abs(p["netSize"]),
                       short_avg_price=p["recentAverageOpenPrice"],
                       liquid_price=p["estimatedLiquidationPrice"])
        else:
            #多头仓位
            pos.update(long_quantity=abs(p["netSize"]),
                       long_avg_price=p["recentAverageOpenPrice"],
                       liquid_price=p["estimatedLiquidationPrice"])

        #因为ftx websocket接口里面没有仓位通知,所以只能这样模拟
        SingleTask.run(self.cb.on_position_update_callback, pos)

        return pos, None
예제 #9
0
    def __init__(self, account, strategy, symbol, host=None, wss=None, access_key=None, secret_key=None,
                 order_update_callback=None, position_update_callback=None):
        """ 初始化
        @param account 账户
        @param strategy 策略名称
        @param symbol 交易对(合约名称)
        @param host HTTP请求主机地址
        @param wss websocket连接地址
        @param access_key ACCESS KEY
        @param secret_key SECRET KEY
        @param order_update_callback 订单更新回调
        @param position_update_callback 持仓更新回调
        """
        self._account = account
        self._strategy = strategy
        self._platform = DERIBIT
        self._symbol = symbol
        self._host = host if host else "https://www.deribit.com"
        self._wss = wss if wss else "wss://deribit.com/ws/api/v2"
        self._access_key = access_key
        self._secret_key = secret_key

        self._order_update_callback = order_update_callback
        self._position_update_callback = position_update_callback

        self._order_channel = "user.orders.{symbol}.raw".format(symbol=symbol)  # 订单订阅频道

        super(DeribitTrade, self).__init__(self._wss, send_hb_interval=5)

        self._orders = {}  # 订单
        self._position = Position(self._platform, self._account, strategy, symbol)  # 仓位

        self._query_id = 0  # 消息序号id,用来唯一标识请求消息
        self._queries = {}  # 未完成的post请求 {"request_id": future}

        self.initialize()

        # 注册定时任务
        LoopRunTask.register(self._do_auth, 60 * 60)  # 每隔1小时重新授权
        LoopRunTask.register(self._check_position_update, 1)  # 获取持仓

        self._ok = False  # 是否建立授权成功的websocket连接
예제 #10
0
    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._orders = {}  # 订单
        self._position = Position(self._platform, self._account,
                                  self._strategy, self._symbol)  # 仓位

        # 订阅频道
        # ch_account = "futures/account:BTC"
        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)

        self.initialize()
예제 #11
0
    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_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 = {
        }  # 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 = "futures/order:{symbol}".format(
            symbol=self._symbol)
        self._position_channel = "futures/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 = OKExFutureRestAPI(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()
예제 #12
0
 def parse(self):
     """ Parse self._data to Order object.
     """
     position = Position(**self.data)
     return position
예제 #13
0
    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)
예제 #14
0
파일: ftx.py 프로젝트: zone21/alphahunter
    async def get_position(self, symbol):
        """ 获取当前持仓

        Args:
            symbol: Trade target

        Returns:
            position: Position if successfully, otherwise it's None.
            error: Error information, otherwise it's None.
        """

        #{"result": [{"collateralUsed": 0.35986, "cost": -1.7984, "entryPrice": 179.84, "estimatedLiquidationPrice": 11184.0123266, "future": "ETH-PERP", "initialMarginRequirement": 0.2, "longOrderSize": 0.0, "maintenanceMarginRequirement": 0.03, "netSize": -0.01, "openSize": 0.01, "realizedPnl": 0.01866927, "recentAverageOpenPrice": 179.84, "recentPnl": -0.0009, "shortOrderSize": 0.0, "side": "sell", "size": 0.01, "unrealizedPnl": -0.0009}], "success": true}
        success, error = await self._rest_api.get_positions(True)
        if error:
            return None, error
        if not success["success"]:
            return None, "get_position error"

        p = next(filter(lambda x: x['future'] == symbol, success["result"]),
                 None)
        if p == None:
            return Position(self._platform, self._account, self._strategy,
                            symbol), None

        if p["netSize"] == 0:
            return Position(self._platform, self._account, self._strategy,
                            symbol), None

        pos = Position(self._platform, self._account, self._strategy, symbol)
        pos.margin_mode = MARGIN_MODE_CROSSED  #ftx只有全仓模式,如果想要逐仓模式的话就用子账户的方式来实现
        pos.utime = tools.get_cur_timestamp_ms()
        if p["netSize"] < 0:  #空头仓位
            pos.long_quantity = 0
            pos.long_avail_qty = 0
            pos.long_open_price = 0
            pos.long_hold_price = 0
            pos.long_liquid_price = 0
            pos.long_unrealised_pnl = 0
            pos.long_leverage = 0
            pos.long_margin = 0
            #
            pos.short_quantity = abs(p["netSize"])
            pos.short_avail_qty = pos.short_quantity - p["longOrderSize"] if p[
                "longOrderSize"] < pos.short_quantity else 0
            pos.short_open_price = p["recentAverageOpenPrice"]
            pos.short_hold_price = p["entryPrice"]
            pos.short_liquid_price = p["estimatedLiquidationPrice"]
            pos.short_unrealised_pnl = p["unrealizedPnl"]
            pos.short_leverage = int(1 / p["initialMarginRequirement"])
            pos.short_margin = p["collateralUsed"]
        else:  #多头仓位
            pos.long_quantity = abs(p["netSize"])
            pos.long_avail_qty = pos.long_quantity - p["shortOrderSize"] if p[
                "shortOrderSize"] < pos.long_quantity else 0
            pos.long_open_price = p["recentAverageOpenPrice"]
            pos.long_hold_price = p["entryPrice"]
            pos.long_liquid_price = p["estimatedLiquidationPrice"]
            pos.long_unrealised_pnl = p["unrealizedPnl"]
            pos.long_leverage = int(1 / p["initialMarginRequirement"])
            pos.long_margin = p["collateralUsed"]
            #
            pos.short_quantity = 0
            pos.short_avail_qty = 0
            pos.short_open_price = 0
            pos.short_hold_price = 0
            pos.short_liquid_price = 0
            pos.short_unrealised_pnl = 0
            pos.short_leverage = 0
            pos.short_margin = 0

        return pos, None