Exemple #1
0
    def price_alert(self, event):
        symbol = get_mt4_symbol(event.instrument)
        for resistance_level in self.resistance_suffix:
            key = '%s_%s' % (symbol, resistance_level)
            resistance = self.prices.get(key)
            if not resistance:
                continue

            price = Decimal(str(resistance))
            if event.bid > price:
                msg = '%s up corss %s = %s' % (symbol, resistance_level, price)
                logger.info('[PRICE_ALERT] %s' % msg)
                send_to_admin(msg)
                tg.send_me(msg)
                self.remove(key)

        for support_level in self.support_suffix:
            key = '%s_%s' % (symbol, support_level)
            support = self.prices.get(key)
            if not support:
                continue

            price = Decimal(str(support))
            if event.ask < price:
                msg = '%s down corss %s = %s' % (symbol, support_level, price)
                logger.info('[PRICE_ALERT] %s' % msg)
                send_to_admin(msg)
                tg.send_me(msg)
                self.remove(key)
Exemple #2
0
def update_density(symbol, account=None):
    symbol = get_mt4_symbol(symbol)
    last_time = price_redis.get(symbol + TIME_SUFFIX)
    last_time = parse(last_time) if last_time else None
    now = datetime.utcnow()
    data = price_redis.get('%s_H1' % symbol)
    data = json.loads(data) if data else {}

    fxcm = account or SingletonFXCM(AccountType.DEMO, settings.FXCM_ACCOUNT_ID,
                                    settings.FXCM_ACCESS_TOKEN)
    if last_time:
        df = fxcm.fxcmpy.get_candles(get_fxcm_symbol(symbol),
                                     period='m1',
                                     start=last_time,
                                     end=now,
                                     columns=['askhigh', 'bidlow', 'tickqty'])
    else:
        df = fxcm.fxcmpy.get_candles(get_fxcm_symbol(symbol),
                                     period='m1',
                                     number=FXCM.MAX_CANDLES,
                                     end=now,
                                     columns=['askhigh', 'bidlow', 'tickqty'])
    _process_df(df, data, symbol)

    print('Data length = %s' % len(df))
    _save_redis(symbol, data)
    now = df.iloc[-1].name.to_pydatetime() + relativedelta(seconds=30)
    price_redis.set(symbol + TIME_SUFFIX, str(now))
    return now
Exemple #3
0
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)
Exemple #4
0
 def read(self, instrument, prices):
     instrument = get_mt4_symbol(instrument)
     if isinstance(prices, DataFrame):
         for i in range(len(prices)):
             tick = prices.iloc[i]
             price = Decimal(str(tick['Bid'])) + Decimal(str(tick['Ask']))
             price /= 2
             self.process_price(instrument, price)
Exemple #5
0
def draw_history(symbol, price):
    price = float(price)
    symbol = get_mt4_symbol(symbol)
    data = price_redis.get('%s_H1' % symbol)
    if not data:
        print('No data for %s' % symbol)
        return
    data = json.loads(data)
    filename = '%s_%s_history' % (symbol,
                                  datetime.utcnow().strftime('%Y-%m-%d %H:%M'))
    _draw(data, symbol, price, filename)
Exemple #6
0
 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)
Exemple #7
0
def draw_recent(symbol, days=30, account=None, to_plotly=False):
    symbol = get_mt4_symbol(symbol)
    now = datetime.utcnow()

    fxcm = account or SingletonFXCM(AccountType.DEMO, settings.FXCM_ACCOUNT_ID,
                                    settings.FXCM_ACCESS_TOKEN)
    df = fxcm.fxcmpy.get_candles(
        get_fxcm_symbol(symbol),
        period='m1',
        number=FXCM.MAX_CANDLES,
        end=now,
        columns=['askclose', 'askhigh', 'bidlow', 'tickqty'])
    price = df.iloc[-1].askclose
    if days:
        start = now - relativedelta(days=days)
        end = df.iloc[0].name.to_pydatetime() - relativedelta(seconds=30)
        print(end)
        while end - start > timedelta(minutes=1):
            if (end - start).days > 6:
                df2 = fxcm.fxcmpy.get_candles(
                    get_fxcm_symbol(symbol),
                    period='m1',
                    number=FXCM.MAX_CANDLES,
                    end=end,
                    columns=['askclose', 'askhigh', 'bidlow', 'tickqty'])
            else:
                df2 = fxcm.fxcmpy.get_candles(
                    get_fxcm_symbol(symbol),
                    period='m1',
                    start=start,
                    end=end,
                    columns=['askclose', 'askhigh', 'bidlow', 'tickqty'])
            df = df.append(df2, sort=True)
            end = df2.iloc[0].name.to_pydatetime() - relativedelta(seconds=30)
            print(end)

    result = {}
    _process_df(df, result, symbol)

    keylist = result.keys()
    keys = sorted(keylist)
    output = ''
    for k in keys:
        output += '    %s: %s,\n' % (k, result[k])
    output = '''{
        %s
        }''' % output
    sorted_result = eval(output)

    filename = '%s_%s days' % (symbol, days)
    _draw(sorted_result, symbol, price, filename, to_plotly)
Exemple #8
0
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()
Exemple #9
0
    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)
Exemple #10
0
 def _load_trade(self, trade_id, trade):
     self.trades[str(trade_id)] = {
         'broker': self.account.broker,
         'account_id': self.account.account_id,
         'trade_id': trade.get_tradeId(),
         'instrument': get_mt4_symbol(trade.get_currency()),
         'side': OrderSide.BUY if trade.get_isBuy() else OrderSide.SELL,
         'open_time': trade.get_time(),
         'open_price': Decimal(str(trade.get_open())),
         'take_profit': Decimal(str(trade.get_limit())),
         'stop_loss': Decimal(str(trade.get_stop())),
         'current': 0,
         'max': 0,
         'min': 0,
         'profitable_seconds': 0,
         'last_profitable_start': None,
         'last_tick_time': None,
     }
Exemple #11
0
def init_density(symbol, start=datetime(2019, 1, 18, 18, 1), account=None):
    symbol = get_mt4_symbol(symbol)
    fxcm = account or SingletonFXCM(AccountType.DEMO, settings.FXCM_ACCOUNT_ID,
                                    settings.FXCM_ACCESS_TOKEN)
    now = datetime.utcnow() - relativedelta(minutes=1)  # shift 1 minute
    end = datetime.utcnow()
    result = {}

    count = 0
    while end > start:
        df = fxcm.fxcmpy.get_candles(get_fxcm_symbol(symbol),
                                     period='m1',
                                     number=FXCM.MAX_CANDLES,
                                     end=end,
                                     columns=['askhigh', 'bidlow', 'tickqty'])
        _process_df(df, result, symbol)
        count += 1
        print(count, end)
        end = df.iloc[0].name.to_pydatetime() - relativedelta(seconds=30)

    _save_redis(symbol, result)
    price_redis.set(symbol + TIME_SUFFIX, str(now))
Exemple #12
0
 def __init__(self,
              broker,
              account_id,
              trade_id,
              instrument,
              side,
              lots,
              open_time,
              open_price,
              stop_loss=None,
              take_profit=None,
              magic_number=None):
     self.broker = broker
     self.account_id = account_id
     self.trade_id = trade_id
     self.instrument = get_mt4_symbol(instrument)
     self.side = side
     self.lots = lots
     self.open_time = open_time
     self.open_price = Decimal(str(open_price))
     self.stop_loss = Decimal(str(stop_loss)) if stop_loss else None
     self.take_profit = Decimal(str(take_profit)) if take_profit else None
     self.magic_number = magic_number
     super(TradeOpenEvent, self).__init__()
Exemple #13
0
 def __init__(self,
              broker,
              account_id,
              trade_id,
              instrument,
              side,
              lots,
              profit,
              close_time,
              close_price,
              pips=None,
              open_time=None):
     self.broker = broker
     self.account_id = account_id
     self.trade_id = trade_id
     self.instrument = get_mt4_symbol(instrument)
     self.side = side
     self.lots = lots
     self.profit = Decimal(str(profit))
     self.close_price = Decimal(str(close_price))
     self.close_time = close_time
     self.open_time = open_time
     self.pips = Decimal(str(pips)) if pips else None
     super(TradeCloseEvent, self).__init__()
Exemple #14
0
 def __init__(self, queue, account=None, instruments=None, *args, **kwargs):
     super(PriceAlertHandler, self).__init__(queue)
     if instruments:
         self.instruments = [get_mt4_symbol(ins) for ins in instruments]
     self.update_price()