Exemplo n.º 1
0
def alert_hourly():

    passage = "Generation of Macdstoc Hourly Alert............."
    print(passage)
    
    errorMessage = ""
    duration = "16 D"
    period = "1 hour"
    
    for cur in CURRENCY_PAIR:
    
        symbol = cur.split("/")[0]
        currency = cur.split("/")[1]
        title = symbol + "/" + currency + "@" + period
        print("Checking on " + title + " ......")
        
        hist_data = ibkr.get_fx_data(symbol, currency, duration, period)

        if (not hist_data):
            hist_data = ibkr.get_fx_data(symbol, currency, duration, period)

        if (not hist_data):
            bot_sender.broadcast("ERROR: No Data returns for %s" % cur, testMode)
            return

        get_alert(cur, title, hist_data)
        print("Sleeping for " + str(SLEEP_PERIOD) + " seconds...")
        time.sleep(SLEEP_PERIOD)
        
    # Metal Pair
    for cur in METAL_PAIR:

        symbol = cur
        title = symbol + "@" + period
        print("Checking on " + title + " ......")

        hist_data = ibkr.get_metal_data(symbol, duration, period)
        get_alert(cur, title, hist_data)
        print("Sleeping for " + str(SLEEP_PERIOD) + " seconds...")
        time.sleep(SLEEP_PERIOD)
        
    # Futures Pair
    for cur in HKFE_PAIR:

        symbol = cur
        current_mth = datetime.datetime.today().strftime('%Y%m')
        title = symbol + "@" + period
        print("Checking on " + title + " ......")

        hist_data = ibkr.get_hkfe_data(current_mth, symbol, duration, period)
        get_alert(cur, title, hist_data)
        print("Sleeping for " + str(SLEEP_PERIOD) + " seconds...")
        time.sleep(SLEEP_PERIOD)
Exemplo n.º 2
0
def main(args):
    
    start_time = time.time()

    if (len(args) > 1 and args[1] == "gen_alert"):
        gen_alert("MHI")
    else:
        symbol = "MHI"
        #duration = "3 Y"
        duration = "6 M"        
        period = "1 hour"
        contract_mth = get_contract_month()
        #contract_mth = datetime.datetime.now().strftime('%Y%m')
        title = symbol + "@" + period + " (" + contract_mth + ")"
        print("Checking on " + title + " ......")

        hist_data = ibkr.get_hkfe_data(contract_mth, symbol, duration, period)
        run_strat(title, hist_data)
    
    print("Time elapsed: " + "%.3f" % (time.time() - start_time) + "s")    
Exemplo n.º 3
0
def alert_daily():    
    
    passage = "Generation of Macdstoc Hourly Alert............."
    print(passage)
    
    errorMessage = ""
    duration = "3 M"
    period = "1 day"
    
    dsl = []

    for cur in CURRENCY_PAIR:
    
        symbol = cur.split("/")[0]
        currency = cur.split("/")[1]
        title = symbol + "/" + currency + "@" + period
        print("Checking on " + title + " ......")

        hist_data = ibkr.get_fx_data(symbol, currency, duration, period)
 
        historic_df = format_hist_df(hist_data)
        signals = gen_signal(historic_df)
        print(signals[['sk_slow','sd_slow','xup_positions','xdown_positions','sxup_positions','sxdown_positions']].tail(20).to_string())
        dsl.append(update_latest_pos(cur, signals))
        
        print("Sleeping for " + str(SLEEP_PERIOD) + " seconds...")
        time.sleep(SLEEP_PERIOD)
        
    # Metal Pair
    for cur in METAL_PAIR:

        symbol = cur
        title = symbol + "@" + period
        print("Checking on " + title + " ......")

        hist_data = ibkr.get_metal_data(symbol, duration, period)
        
        historic_df = format_hist_df(hist_data)
        signals = gen_signal(historic_df)
        dsl.append(update_latest_pos(cur, signals))
        
        print("Sleeping for " + str(SLEEP_PERIOD) + " seconds...")
        time.sleep(SLEEP_PERIOD)
        
    # Futures Pair
    for cur in HKFE_PAIR:

        symbol = cur
        current_mth = datetime.datetime.today().strftime('%Y%m')
        title = symbol + "@" + period
        print("Checking on " + title + " ......")

        hist_data = ibkr.get_hkfe_data(current_mth, symbol, duration, period)
 
        historic_df = format_hist_df(hist_data)
        signals = gen_signal(historic_df)
        dsl.append(update_latest_pos(cur, signals))

        print("Sleeping for " + str(SLEEP_PERIOD) + " seconds...")
        time.sleep(SLEEP_PERIOD)
        
    message = "<b>Daily Macdstoc Signal</b>" + DEL
    message = message + EL.join(dsl)
    print(message)
    
    if (message):
        print(message)
Exemplo n.º 4
0
def gen_alert(symbol="MHI"):     
    
    duration = "1 M"        
    period = "1 hour"
    current_mth = get_contract_month()
    #current_mth = "201802"
    title = symbol + "@" + period + " (Contract: " + current_mth + ")"
    print("Checking on " + title + " ......")

    historic_data = ibkr.get_hkfe_data(current_mth, symbol, duration, period)
    
    if (not historic_data):
        print("Historic Data is empty!!!")
        return

    # Data pre-processing
    bars = pd.DataFrame(historic_data, columns=['datetime', 'open', 'high', 'low', 'close', 'volume'])
    bars.set_index('datetime', inplace=True)
    bars.index = pd.to_datetime(bars.index)
    
    ema_strats = ema_xover_strategy(symbol, bars, 25)
    signals = ema_strats.generate_signals()
    
    latest_signal = signals.iloc[-2:].head(1)
    lts = latest_signal.index[0]
    lrec = latest_signal.iloc[0]
    lxup = int(lrec['xup_pos'])
    lxdown = int(lrec['xdown_pos'])
    lopen = "%.0f" % lrec['open']
    lhigh = "%.0f" % lrec['high']
    llow = "%.0f" % lrec['low']
    lclose = "%.0f" % lrec['close']
    lmacd = "%.2f" % lrec['macd']
    lemas = "%.2f" % lrec['emaSmooth']
    lskslow = "%.2f" % lrec['k_slow']
    lsdslow = "%.2f" % lrec['d_slow']
    lema25 = "%.2f" % lrec['ema25']

    print(signals[['open', 'close', 'nopen', 'ema25', 'xup_pos', 'xdown_pos']].to_string())
    print(latest_signal[['open', 'close', 'nopen', 'ema25', 'xup_pos', 'xdown_pos']].to_string())
    
    message_tmpl = "<b>" + u'\U0001F514' + " %s: \nMA Strategy X%s%s</b>\n<i>at %s%s</i>"
    message_nil_tmpl = "%s: NO MA Strategy Alert at %s"
    signals_list = ["<b>OPEN:</b> " + lopen
                    , "<b>HIGH:</b> " + lhigh
                    , "<b>LOW:</b> " + llow
                    , "<b>CLOSE:</b> " + lclose
                    , "<b>MA Signal:</b> " + lema25
                    #, "<b>MACD:</b> " + lmacd
                    #, "<b>emaSmooth:</b> " + lemas
                    #, "<b>STOC:</b> " + lskslow + "/" + lsdslow
                    , "<b>TS:</b> " + datetime.datetime.now().strftime("%H:%M:%S") + "HKT"
                    , "<b>CH:</b> https://goo.gl/yAtFvH"
                    ]
    signals_stmt = EL.join(signals_list)
    message = ""    
    
    if (lxup):
        message = (message_tmpl % (title, "Up", u'\U0001F332', lts, "HKT"))
        message = message + DEL + signals_stmt + EL
    elif (lxdown):
        message = (message_tmpl % (title, "Down", u'\U0001F53B', lts, "HKT"))
        message = message + DEL + signals_stmt + EL
    else:
        print(message_nil_tmpl % (title, lts))        
       
    if (message):
        print(message)
        bot_sender.broadcast_list(message, "telegram-pt")
Exemplo n.º 5
0
def trade_monitor_hkfe(json_args):

    symbol = json_args['symbol']
    duration = json_args['duration']
    period = json_args['period']
    signal = json_args['signal']

    signal_gap = signal['gap']
    signal_date = signal['date']
    signal_trigger = "%.0f" % signal['trigger']

    current_mth = get_contract_month()
    #current_mth = "201802"
    title = symbol + "@" + period + " (Contract: " + current_mth + ")"
    print("Checking on " + title + " ......")

    historic_data = ibkr.get_hkfe_data(current_mth, symbol, duration, period)

    if (not historic_data):
        print("Historic Data is empty!!!")
        return

    # Data pre-processing
    bars = pd.DataFrame(
        historic_data,
        columns=['datetime', 'open', 'high', 'low', 'close', 'volume'])
    bars.set_index('datetime', inplace=True)
    bars.index = pd.to_datetime(bars.index)

    print(bars.tail())

    latest_bar = bars.iloc[-2:].head(1)
    lts = str(latest_bar.index[0])
    ldt = str(latest_bar.index[0]).split()[0]
    lrec = latest_bar.iloc[0]
    lopen = "%.0f" % lrec['open']
    lhigh = "%.0f" % lrec['high']
    llow = "%.0f" % lrec['low']
    lclose = "%.0f" % lrec['close']

    print("\nSignal:[\n%s]" % signal)
    print("\nLast Bar:[\n%s]" % latest_bar)
    print("Last Bar Date: [%s]" % ldt)

    # Test case {'date': '2018-04-06', 'gap': 'UP', 'trigger': 30064.0}

    message = ""
    message_tmpl = "<b>" + u'\U0001F514' + " GAP %s Trade Trigger Hit : %s %s %s</b>\n<i>at %s</i>"

    if (ldt == signal_date):
        print("Signal Date Check Passed [%s / %s]" % (ldt, signal_date))
        if (signal_gap == "UP"):
            if (lclose < signal_trigger):
                print("GAP UP Trade Trigger Hit %s < %s" %
                      (lclose, signal_trigger))
                message = message_tmpl % (signal_gap, lclose, "&lt;",
                                          signal_trigger, lts)
            else:
                print("GAP UP Trade Trigger NOT Hit %s < %s" %
                      (lclose, signal_trigger))
        elif (signal_gap == "DOWN"):
            if (lclose > signal_trigger):
                print("GAP DOWN Trade Trigger Hit %s > %s" %
                      (lclose, signal_trigger))
                message = message_tmpl % (signal_gap, lclose, "&gt;",
                                          signal_trigger, lts)
            else:
                print("GAP DOWN Trade Trigger NOT Hit %s < %s" %
                      (lclose, signal_trigger))
        else:
            print("Signal Gap is invalid: [%s]" % signal_gap)
    else:
        print("Signal Date Check Failed [%s / %s]" % (ldt, signal_date))

    if (message):
        print(message)
        #bot_sender.broadcast_list(message, "telegram-chat-test")
        bot_sender.broadcast_list(message, "telegram-pt")
Exemplo n.º 6
0
def gen_alert(symbol="MHI"):     
    
    duration = "2 M"        
    period = "5 mins"
    contract_mth = get_contract_month()
    title = symbol + "@" + period + " (" + contract_mth + ")"
    print("Checking on " + title + " ......")
    time.sleep(5)

    historic_data = ibkr.get_hkfe_data(contract_mth, symbol, duration, period)
    
    if (not historic_data):
        print("Historic Data is empty!!!")
        return

    # Data pre-processing
    bars = pd.DataFrame(historic_data, columns=['datetime', 'open', 'high', 'low', 'close', 'volume'])
    bars.set_index('datetime', inplace=True)
    bars.index = pd.to_datetime(bars.index)
    
    # get today time    
    now = datetime.datetime.now()
    mkt_open_str = now.strftime('%Y-%m-%d 09:20:00')
    
    # test data
    #mkt_open_str = '2018-03-29 09:20:00'
    
    # get mkt open bars
    mkt_open_bars = (bars.loc[bars.index <= mkt_open_str]).tail(3)
   
    last_bar = mkt_open_bars.tail(1)
    last_2nd_bar = mkt_open_bars.tail(2).head(1)
    last_3rd_bar = mkt_open_bars.tail(3).head(1)
    
    print(last_bar)
    print(last_2nd_bar)
    print(last_3rd_bar)
    
    signal_gap = 0
    signal_change = 0
    signal_price = 0
    
    if (
            last_bar.tail(1).index == mkt_open_str 
            and "09:15" in str(last_2nd_bar.tail(1).index) 
            and "16:25" in str(last_3rd_bar.tail(1).index)
        ):
        print("Processing Mkt Open bar %s ......" % mkt_open_str )
        last_mkt_close = last_3rd_bar.iloc[0]['close']
        today_mkt_open = last_2nd_bar.iloc[0]['open']
        
        print("Last Mkt Close %s, Today Mkt Open %s" % (last_mkt_close, today_mkt_open))
        
        signal_gap = today_mkt_open - last_mkt_close
        
        if abs(signal_gap) >= GAP_THRESHOLD:
            print("Gap threshold limit satisfied [%s]" % signal_gap)
        else:
            print("Gap threshold limit NOT satisfied [%s]" % signal_gap)
            return
        
        signal_change = last_2nd_bar.iloc[0]['close'] - last_2nd_bar.iloc[0]['open']
        
        if (signal_gap > 0 and signal_change < 0):
            print("Upward Gap and Reversal (-ve) identified")
            signal_price = last_2nd_bar.iloc[0]['low']
        elif (signal_gap < 0 and signal_change > 0):
            print("Downward Gap and Reversal (+ve) identified")
            signal_price = last_2nd_bar.iloc[0]['high']
        else:
            print("NOT hitting any reversal scenario!")
            return
    else:
        print("No Mkt Open bar is found, terminate!")
        return
    
    message = ""
    
    if (signal_change != 0 and signal_price != 0):
    
        message = "Reversal Strategy Monitor \n@ %s" % mkt_open_str 
        signals_list = ["<b>Gap:</b> " + str(signal_gap)
                        , "<b>Mkt Open Change:</b> " + str(signal_change)
                        , "<b>Reversal Price:</b> " + str(signal_price)
                        , "<b>TS:</b> " + datetime.datetime.now().strftime("%H:%M:%S") + "HKT"
                        ]
        signals_stmt = EL.join(signals_list)
        message = message + DEL + signals_stmt + EL
        
        signal_json = {}
        signal_json['date'] = now.strftime('%Y-%m-%d')
        if (signal_gap > 0):
            signal_json['gap'] = 'UP'
        else:
            signal_json['gap'] = 'DOWN'
        
        signal_json['trigger'] = signal_price
        json_data = json.dumps(signal_json)
        print(json_data)
        redis_pool.setV("MRS:" + symbol, json_data)
        
        # send alert first
        if (message):
            print(message)
            #bot_sender.broadcast_list(message, "telegram-chat-test")        
            bot_sender.broadcast_list(message, "telegram-pt")

        # add to trigger monitor
        
        json_args = {"symbol": "MHI", "duration": "28800 S", "period": "1 min", "signal": signal_json}
        print("Json args: [%s]" % json_args)
        strat_trade_monitor.strat_scheduler(strat_trade_monitor.trade_monitor_hkfe, json_args, 60.0, 20)