def fetch_market(self, epic): """ Fetch and cache it. It rarely changes, except for base exchange rate, so assume it once for all. """ market_info = self._connector.market(epic) instrument = market_info['instrument'] snapshot = market_info['snapshot'] dealing_rules = market_info['dealingRules'] market = Market(epic, instrument['marketId']) # cannot interpret this value because IG want it as it is market.expiry = instrument['expiry'] # not perfect but IG does not provides this information if instrument["marketId"].endswith(instrument["currencies"][0]["name"]): base_symbol = instrument["marketId"][:-len(instrument["currencies"][0]["name"])] else: base_symbol = instrument["marketId"] market.base_exchange_rate = instrument['currencies'][0]['baseExchangeRate'] # "exchangeRate": 0.77 market.one_pip_means = float(instrument['onePipMeans'].split(' ')[0]) # "1 Index Point", "0.0001 USD/EUR" market.value_per_pip = float(instrument['valueOfOnePip']) market.contract_size = float(instrument['contractSize']) market.lot_size = float(instrument['lotSize']) market.set_base( base_symbol, base_symbol, decimal_place(market.one_pip_means)) if instrument['type'] in ('CURRENCIES'): pass # quote_precision = elif instrument['type'] in ('INDICES', 'COMMODITIES', 'SHARES', 'RATES', 'SECTORS'): pass # quote_precision = market.set_quote( instrument["currencies"][0]["name"], instrument["currencies"][0]['symbol'], decimal_place(market.one_pip_means)) # "forceOpenAllowed": true, # "stopsLimitsAllowed": true, # "controlledRiskAllowed": true, # "streamingPricesAvailable": true, if snapshot: market.is_open = snapshot["marketStatus"] == "TRADEABLE" market.bid = snapshot['bid'] market.ofr = snapshot['offer'] # "marginFactorUnit": "PERCENTAGE" not avalaible if market is down if instrument.get('marginFactor') and market.is_open: market.margin_factor = float(instrument['marginFactor']) margin_factor = instrument['marginFactor'] elif instrument.get('margin') and market.is_open: market.margin_factor = 0.1 / float(instrument['margin']) margin_factor = str(market.margin_factor) else: # we don't want this when market is down because it could overwrite the previous stored value margin_factor = None if instrument['unit'] == 'AMOUNT': market.unit_type = Market.UNIT_AMOUNT elif instrument['unit'] == 'CONTRACTS': market.unit_type = Market.UNIT_CONTRACTS elif instrument['unit'] == 'SHARES': market.unit_type = Market.UNIT_SHARES # BINARY OPT_* BUNGEE_* if instrument['type'] == 'CURRENCIES': market.market_type = Market.TYPE_CURRENCY elif instrument['type'] == 'INDICES': market.market_type = Market.TYPE_INDICE elif instrument['type'] == 'COMMODITIES': market.market_type = Market.TYPE_COMMODITY elif instrument['type'] == 'SHARES': market.market_type = Market.TYPE_STOCK elif instrument['type'] == 'RATES': market.market_type = Market.TYPE_RATE elif instrument['type'] == 'SECTORS': market.market_type = Market.TYPE_SECTOR market.trade = Market.TRADE_MARGIN | Market.TRADE_POSITION market.contract_type = Market.CONTRACT_CFD # take minDealSize as tick size market.set_size_limits(dealing_rules["minDealSize"]["value"], 0.0, dealing_rules["minDealSize"]["value"]) # @todo there is some limits in contract size market.set_notional_limits(0.0, 0.0, 0.0) # use one pip means for minimum and tick price size market.set_price_limits(market.one_pip_means, 0.0, market.one_pip_means) # commission for stocks @todo commission = "0.0" # store the last market info to be used for backtesting if not self._read_only: Database.inst().store_market_info((self.name, epic, market.symbol, market.market_type, market.unit_type, market.contract_type, # type market.trade, market.orders, # type market.base, market.base_display, market.base_precision, # base market.quote, market.quote_display, market.quote_precision, # quote market.expiry, int(market.last_update_time * 1000.0), # expiry, timestamp instrument['lotSize'], instrument['contractSize'], str(market.base_exchange_rate), instrument['valueOfOnePip'], instrument['onePipMeans'].split(' ')[0], margin_factor, dealing_rules["minDealSize"]["value"], "0.0", dealing_rules["minDealSize"]["value"], # size limits "0.0", "0.0", "0.0", # notional limits "0.0", "0.0", "0.0", # price limits "0.0", "0.0", commission, commission) # fees ) # print(market.symbol, market._size_limits, market._price_limits) # notify for strategy self.service.notify(Signal.SIGNAL_MARKET_INFO_DATA, self.name, (epic, market)) return market
def fetch_market(self, market_id): """ Fetch and cache it. It rarely changes, except for base exchange rate, so assume it once for all. @todo min/max/step/min_notional """ instrument = self.connector.ws.get_instrument(market_id) # funds = self.connector.ws.funds() # to get account base currency (if XBt or XBT) xbt_usd = self.connector.ws.get_instrument("XBTUSD") if instrument: # tickSize is the minimum price increment (0.5USD for XBTUSD) tradeable = instrument.get('state', 'Closed') == 'Open' update_time = self._parse_datetime(instrument.get('timestamp')).timestamp() symbol = instrument.get('symbol', '') base_symbol = instrument.get('rootSymbol', '') quote_symbol = symbol[-3:] # if funds['currency'] == 'XBt': # # XBt to XBT # ratio = 1.0 / 100000000.0 # if base_symbol == 'USD': # # USD is base then convert to XBT # ratio *= to_base_rate bid = instrument.get('bidPrice') ofr = instrument.get('askPrice') market = Market(market_id, symbol) # compute base precision from the tick size, example 0.05 => 2 base_precision = -math.floor(math.log10(instrument.get('tickSize', 1.0))) market.set_base(base_symbol, base_symbol, base_precision) market.set_quote(quote_symbol, quote_symbol) # base to XBT market.base_exchange_rate = 1.0 # base instrument base_market_id = "XBT" + quote_symbol base_market = self.connector.ws.get_instrument(base_market_id) if base_market_id != symbol and base_market: market.base_exchange_rate = base_market.get('lastPrice', 1.0) / instrument.get('lastPrice', 1.0) # @todo 'multiplier', 'riskStep', 'riskLimit' # limits min_notional = 1.0 # $ if quote_symbol != "USD" and base_market_id != "XBT": # any contract on futur XBT quote min_notional = 0.0001 # BCHXBT 'maxOrderQty': 100000000, 'maxPrice': 10, 'lotSize': 1, 'tickSize': 0.0001, # XBCUSD 'maxOrderQty': 10000000, 'maxPrice': 1000000, 'lotSize': 1, 'tickSize': 0.5, market.set_size_limits(instrument.get('tickSize', 1.0), instrument.get('maxOrderQty', 0.0), instrument.get('tickSize', 1.0)) market.set_notional_limits(min_notional, instrument.get('maxPrice', 0.0), 0.0) market.set_price_limits(0.0, 0.0, instrument.get('tickSize', 1.0)) # need to divided by account currency XBt = 100000000 market.margin_factor = instrument.get('initMargin', 1.0) # market.max_margin_factor = 1.0 / (instrument.get('riskLimit', 1.0) * ratio) # ex: 20000000000 for max leverage 200 # '-' if perpetual else match the regexp and keep the expiry part only expiry = BitMexWatcher.EXPIRY_RE.match(market_id) # or instrument.get(expiry') == '2018-12-28T12:00:00.000Z' for Z18 its 28 of month Z (december) and year 2018 if expiry is None: market.expiry = '-' else: market.expiry = expiry.group(2) + expiry.group(3) market.market_type = Market.TYPE_CRYPTO market.unit_type = Market.UNIT_CONTRACTS market.contract_type = Market.CONTRACT_CFD # and FUTUR market.trade = Market.TRADE_IND_MARGIN if bid is not None and ofr is not None: market.bid = bid market.ofr = ofr market.last_update_time = update_time market.lot_size = instrument.get('lotSize', 1.0) # ex: 1.0 for XBTUSD market.contract_size = 1.0 market.value_per_pip = 1.0 market.one_pip_means = instrument.get('tickSize', 1.0) # contract_size need to be updated as price changes # @todo this is wrong... same on update part above if quote_symbol == 'USD' and base_market_id == symbol: # XBTUSD... market.contract_size = 1.0 / instrument.get('lastPrice', 1.0) elif quote_symbol == 'USD' and base_market_id != symbol: # ETHUSD... market.contract_size = (0.001 * 0.01) * instrument.get('lastPrice', 1.0) elif base_market and base_market_id != symbol: # ADAZ18... market.contract_size = 1.0 / instrument.get('lastPrice', 1.0) market.value_per_pip = market.contract_size / instrument.get('lastPrice', 1.0) market.maker_fee = instrument.get('makerFee', 0.0) market.taker_fee = instrument.get('takerFee', 0.0) # store the last market info to be used for backtesting if not self._read_only: Database.inst().store_market_info((self.name, market_id, market.symbol, market.market_type, market.unit_type, market.contract_type, # type market.trade, market.orders, # type market.base, market.base_display, market.base_precision, # base market.quote, market.quote_display, market.quote_precision, # quote market.expiry, int(market.last_update_time * 1000.0), # expiry, timestamp str(market.lot_size), str(market.contract_size), str(market.base_exchange_rate), str(market.value_per_pip), str(market.one_pip_means), str(market.margin_factor), str(market.min_size), str(market.max_size), str(market.step_size), # size limits str(market.min_notional), str(market.max_notional), str(market.step_notional), # notional limits str(market.min_price), str(market.max_price), str(market.tick_price), # price limits str(market.maker_fee), str(market.taker_fee), str(market.maker_commission), str(market.taker_commission)) # fees ) # notify for strategy self.service.notify(Signal.SIGNAL_MARKET_INFO_DATA, self.name, (market_id, market)) return market
def fetch_market(self, market_id): """ Fetch and cache it. It rarely changes. """ symbol = self._symbols_data.get(market_id) ticker = self._tickers_data.get(market_id) account = self._acount_data market = None if symbol and ticker and account: market = Market(symbol['symbol'], symbol['symbol']) market.is_open = symbol['status'] == "TRADING" market.expiry = '-' base_asset = symbol['baseAsset'] market.set_base(base_asset, base_asset, symbol['baseAssetPrecision']) quote_asset = symbol['quoteAsset'] market.set_quote(quote_asset, symbol.get('quoteAssetUnit', quote_asset), symbol['quotePrecision']) # tick size at the base asset precision market.one_pip_means = math.pow(10.0, -symbol['baseAssetPrecision']) market.value_per_pip = 1.0 market.contract_size = 1.0 market.lot_size = 1.0 # @todo add margin support market.margin_factor = 1.0 size_limits = ["1.0", "0.0", "1.0"] notional_limits = ["1.0", "0.0", "0.0"] price_limits = ["0.0", "0.0", "0.0"] # size min/max/step for afilter in symbol["filters"]: if afilter['filterType'] == "LOT_SIZE": size_limits = [ afilter['minQty'], afilter['maxQty'], afilter['stepSize'] ] elif afilter['filterType'] == "MIN_NOTIONAL": notional_limits[0] = afilter['minNotional'] elif afilter['filterType'] == "PRICE_FILTER": price_limits = [ afilter['minPrice'], afilter['maxPrice'], afilter['tickSize'] ] market.set_size_limits(float(size_limits[0]), float(size_limits[1]), float(size_limits[2])) market.set_price_limits(float(price_limits[0]), float(price_limits[1]), float(price_limits[2])) market.set_notional_limits(float(notional_limits[0]), 0.0, 0.0) market.unit_type = Market.UNIT_AMOUNT market.market_type = Market.TYPE_CRYPTO market.contract_type = Market.CONTRACT_SPOT market.trade = 0 if symbol.get('isSpotTradingAllowed', False): market.trade |= Market.TRADE_ASSET if symbol.get('isMarginTradingAllowed', False): market.trade |= Market.TRADE_IND_MARGIN # @todo orders capacities # symbol['orderTypes'] in ['LIMIT', 'LIMIT_MAKER', 'MARKET', 'STOP_LOSS_LIMIT', 'TAKE_PROFIT_LIMIT'] # market.orders = if symbol.get('ocoAllowed', False): market.orders |= Market.ORDER_ONE_CANCEL_OTHER market.maker_fee = account['makerCommission'] * 0.0001 market.taker_fee = account['takerCommission'] * 0.0001 # market.buyer_commission = account['buyerCommission'] # market.seller_commission = account['sellerCommission'] # only order book can give us bid/ofr market.bid = float(ticker['price']) market.ofr = float(ticker['price']) mid_price = float(ticker['price']) if quote_asset != self.BASE_QUOTE: if self._tickers_data.get(quote_asset + self.BASE_QUOTE): market.base_exchange_rate = float( self._tickers_data.get(quote_asset + self.BASE_QUOTE, {'price', '1.0'})['price']) elif self._tickers_data.get(self.BASE_QUOTE + quote_asset): market.base_exchange_rate = 1.0 / float( self._tickers_data.get(self.BASE_QUOTE + quote_asset, {'price', '1.0'})['price']) else: market.base_exchange_rate = 1.0 else: market.base_exchange_rate = 1.0 market.contract_size = 1.0 / mid_price market.value_per_pip = market.contract_size / mid_price # volume 24h # in client.get_ticker but cost is 40 for any symbols then wait it at all-tickets WS event # vol24_base = ticker24h('volume') # vol24_quote = ticker24h('quoteVolume') # notify for strategy self.service.notify(Signal.SIGNAL_MARKET_INFO_DATA, self.name, (market_id, market)) # store the last market info to be used for backtesting if not self._read_only: Database.inst().store_market_info(( self.name, market.market_id, market.symbol, market.market_type, market.unit_type, market.contract_type, # type market.trade, market.orders, # type market.base, market.base_display, market.base_precision, # base market.quote, market.quote_display, market.quote_precision, # quote market.expiry, int(market.last_update_time * 1000.0), # expiry, timestamp str(market.lot_size), str(market.contract_size), str(market.base_exchange_rate), str(market.value_per_pip), str(market.one_pip_means), '-', *size_limits, *notional_limits, *price_limits, str(market.maker_fee), str(market.taker_fee), str(market.maker_commission), str(market.taker_commission))) return market