def test_instrument(self): # list_instruments instruments = self.account.list_instruments() self.assertTrue(isinstance(instruments, dict)) print(instruments[self.currency]) # pip unit pip_unit = pip(self.currency) self.assertEqual(pip_unit, Decimal('0.0001')) pips = pip(self.currency, 0.00315) self.assertEqual(pips, 31.5) # calculate_price price = calculate_price(1.11325, OrderSide.BUY, 31.4, self.currency) self.assertEqual(price, Decimal('1.11639')) # get_candle from_time = datetime.utcnow() to_time = from_time - relativedelta(minutes=101) count = 20 # get_candle candles = self.account.get_candle(self.currency, PERIOD_M5, count=count, fromTime=to_time, toTime=to_time) self.assertTrue(isinstance(candles, DataFrame)) self.assertEqual(len(candles), count)
def _draw(data, symbol, price, filename=None, to_plotly=False): symbol = get_mt4_symbol(symbol) pip_unit = pip(symbol) fig = plt.figure() ax = plt.axes() items = data.items() y = [ float(v) for k, v in items if pip(symbol, float(k) - price, True) < 100 ] x = [ float(k) for k, v in items if pip(symbol, float(k) - price, True) < 100 ] ax.plot(x, y) plt.axvline(x=price, color='r') plt.xticks(np.arange(min(x), max(x), float(pip_unit * 10)), rotation=90) fig.show() if filename: fig.savefig('/tmp/%s.png' % filename) if to_plotly: trace = go.Bar(x=x, y=y) result = py.iplot([trace], filename=filename) print(result.embed_code)
def _process_price(self, price): instrument = price.instrument time = dateparser.parse(price.time) bid = Decimal(str(price.bids[0].price)) ask = Decimal(str(price.asks[0].price)) spread = pip(instrument, ask - bid) self._prices[instrument] = {'time': time, 'bid': bid, 'ask': ask, 'spread': spread}
def get_lots(self, instrument, stop_loss_pips=None, risk_ratio=Decimal('0.05')): max_trade = 5 if len(self.get_trades()) >= max_trade: return 0 equity = self.get_balance() if not stop_loss_pips: return equity / 1000 * Decimal('0.1') instrument = get_fxcm_symbol(instrument) pip_unit = pip(instrument) risk = equity * risk_ratio value = risk / stop_loss_pips / pip_unit if instrument.upper().endswith('USD'): price = self.get_price(instrument) value = value * price elif instrument.upper().startswith('USD'): lots = equity / 1000 * Decimal('0.1') return lots.quantize(Decimal("0.01")) else: # cross pair raise NotImplementedError units = int(value / 100) * 100 return units_to_lots(units).quantize(Decimal("0.01"))
def tick_to_kinesis(tick, dataframe): instrument = get_mt4_symbol(tick['Symbol']) bid = str(Decimal(str(tick['Rates'][0])).quantize(pip(instrument)/10)) ask = str(Decimal(str(tick['Rates'][1])).quantize(pip(instrument)/10)) data = { 'timestamp': int(tick['Updated']) / 1000.0, 'bid': bid, 'ask': ask } data = json.dumps(data) records.append({'Data': bytes(data, 'utf-8'), 'PartitionKey': instrument}) if len(records) == 10: print(records) kinesis.put_records(StreamName=inputStream, Records=records) records.clear()
def tick_data(self, data, dataframe): try: instrument = get_mt4_symbol(data['Symbol']) time = datetime.utcfromtimestamp(int(data['Updated']) / 1000.0) bid = Decimal(str(data['Rates'][0])).quantize(pip(instrument)) ask = Decimal(str(data['Rates'][1])).quantize(pip(instrument)) tick = TickPriceEvent(self.broker, instrument, time, bid, ask) self.put(tick) data = json.dumps( {'ask': float(ask), 'bid': float(bid), 'time': time.strftime('%Y-%m-%d %H:%M:%S:%f')}) set_tick_price(instrument, data) set_last_tick(time.strftime('%Y-%m-%d %H:%M:%S:%f')) self.last_tick_time = datetime.utcnow() except Exception as ex: logger.error('tick_data error = %s' % ex)
def get_spread(self, instrument): tick_price = get_tick_price(instrument) if tick_price: spread = tick_price['ask'] - tick_price['bid'] spread_pips = pip(instrument, spread, _abs=True) return spread_pips return None
def _process_df(df, result, symbol): pip_unit = pip(symbol) for index, row in df.iterrows(): high = Decimal(str(row['askhigh'])).quantize(pip_unit, rounding=ROUND_HALF_EVEN) low = Decimal(str(row['bidlow'])).quantize(pip_unit, rounding=ROUND_HALF_EVEN) volume = Decimal(str(row['tickqty'])) if not volume: continue distance = pip(symbol, high - low, True) avg_vol = (volume / distance).quantize(pip_unit) for i in range(int(distance) + 1): target = low + i * pip_unit if str(target) not in result: result[str(target)] = 0 result[str(target)] = Decimal(str(result[str(target)])) + avg_vol
def get_price(self, instrument, type='mid'): instrument = get_mt4_symbol(instrument) pip_u = pip(instrument) price = get_tick_price(instrument) if not price: raise Exception('get_price, %s price is None' % instrument) if type == 'ask': return Decimal(str(price.get('ask'))).quantize(pip_u) elif type == 'bid': return Decimal(str(price.get('bid'))).quantize(pip_u) elif type == 'mid': price = (price.get('bid') + price.get('ask')) / 2 return Decimal(str(price)).quantize(pip_u)
def trade_units(self, instrument, stop_loss_pips): """get max units for this instrument""" instrument = get_symbol(instrument) pip_unit = pip(instrument) risk = self.equity * self.risk_ratio value = risk / stop_loss_pips / pip_unit if instrument.upper().startswith('USD'): price = self.account.get_price(instrument) value = value * price elif instrument.upper().endswith('USD'): pass else: # cross pair raise NotImplementedError return int(value / 100) * 100
def process_price(self, instrument, price, volume=None): _pip = pip(instrument) price = Decimal(str(price)).quantize(_pip) volume = volume or 0 if price in self.density.index: count = self.density.loc[1]['count'] old_volume = self.density.loc[1]['volume'] temp_df = pd.DataFrame( { 'count': [count + 1], 'volume': [old_volume + volume] }, index=[price]) self.density.update(temp_df) else: temp_df = pd.DataFrame([[price, 1, volume]], columns=['price', 'count', 'volume']) temp_df = temp_df.set_index('price') self.density = pd.concat([self.density, temp_df])
def _process_order_paramters(self, **kwargs): data = {} instrument = None pip_unit = None if kwargs.get('instrument'): instrument = get_symbol(kwargs['instrument']) data['instrument'] = instrument if kwargs.get('trade_id'): data['tradeID'] = str(kwargs['trade_id']) trade = self.trades.get(data['tradeID']) or self.get_trade( data['tradeID']) instrument = trade.instrument if instrument: pip_unit = pip(instrument) if kwargs.get('lots'): units = lots_to_units(kwargs['lots'], kwargs.get('side') or OrderSide.BUY) data['units'] = str(units) if kwargs.get('type'): data['type'] = kwargs['type'] if kwargs.get('timeInForce'): data['timeInForce'] = kwargs['timeInForce'] or TimeInForce.FOK if kwargs.get('priceBound'): data['priceBound'] = str(kwargs['priceBound']) if kwargs.get('price'): data['price'] = str(kwargs['price']) if kwargs.get('positionFill'): data['positionFill'] = kwargs[ 'positionFill'] or OrderPositionFill.DEFAULT # The Client Extensions to update for the Order. Do not set, modify, or # delete clientExtensions if your account is associated with MT4. if kwargs.get('client_id') or kwargs.get('client_tag') or kwargs.get( 'client_comment'): data['clientExtensions'] = ClientExtensions( id=kwargs['client_id'], tag=kwargs['client_tag'], comment=kwargs['client_comment']) if kwargs.get('trade_client_id') or kwargs.get( 'trade_client_tag') or kwargs.get('trade_client_comment'): data['tradeClientExtensions'] = ClientExtensions( id=kwargs['trade_client_id'], tag=kwargs['trade_client_tag'], comment=kwargs['trade_client_comment']) if kwargs.get('take_profit_price'): data['takeProfitOnFill'] = TakeProfitDetails( price=str(kwargs['take_profit_price']), clientExtensions=data.get('clientExtensions')) if kwargs.get('stop_loss_pip') and pip_unit: stop_loss_price = pip_unit * Decimal(str(kwargs['stop_loss_pip'])) data['stopLossOnFill'] = StopLossDetails( distance=str(stop_loss_price), clientExtensions=data.get('clientExtensions')) if kwargs.get('stop_loss_distance'): data['stopLossOnFill'] = StopLossDetails( distance=str(kwargs['stop_loss_distance']), clientExtensions=data.get('clientExtensions')) if kwargs.get('trailing_pip'): trailing_distance_price = pip_unit * Decimal( str(kwargs['trailing_pip'])) data['trailingStopLossOnFill'] = TrailingStopLossDetails( distance=str(trailing_distance_price), clientExtensions=data.get('clientExtensions')) if kwargs.get('trigger_condition'): data['triggerCondition'] = kwargs[ 'trigger_condition'] or OrderTriggerCondition.DEFAULT if kwargs.get('gtd_time'): # todo confirm gtdTime format data['gtdTime'] = str(kwargs['gtd_time']) if kwargs.get('client_trade_id'): data['clientTradeID'] = kwargs['client_trade_id'] if kwargs.get('guaranteed'): data['guaranteed'] = kwargs['guaranteed'] if kwargs.get('distance'): data['distance'] = kwargs['distance'] return data