Files
strategy-lab/to_explore/notebooks/TelegramSignals.ipynb

9.9 KiB

In this example, we will build a Telegram bot that sends a signal once any Bollinger Band has been crossed. We will periodically query for the latest OHLCV data of the selected cryptocurrencies and append this data to our data pool. Additionally to receiving signals, any Telegram user can join the group and ask the bot to provide him with the current information. If the price change is higher than some number of standard deviations from the mean, while crossing the band, the bot sends a funny GIF.

In [ ]:
from telegram import __version__ as TG_VER

try:
    from telegram import __version_info__
except ImportError:
    __version_info__ = (0, 0, 0, 0, 0)

if __version_info__ >= (20, 0, 0, "alpha", 1):
    raise RuntimeError(f"This example is not compatible with your current PTB version {TG_VER}")
In [ ]:
from vectorbtpro import *
# whats_imported()

import logging
In [ ]:
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
In [ ]:
# Telegram
vbt.settings.messaging['telegram']['token'] = "YOUR_TOKEN"

# Giphy
vbt.settings.messaging['giphy']['api_key'] = "YOUR_API_KEY"

# Data
SYMBOLS = ['BTC/USDT', 'ETH/USDT', 'ADA/USDT']
START = '1 hour ago UTC'
TIMEFRAME = '1m'
UPDATE_EVERY = vbt.utils.datetime_.interval_to_ms(TIMEFRAME) // 1000  # in seconds
DT_FORMAT = '%d %b %Y %H:%M:%S %z'
IND_PARAMS = dict(
    timeperiod=20, 
    nbdevup=2, 
    nbdevdn=2
)
CHANGE_NBDEV = 2
In [ ]:
data = vbt.CCXTData.pull(SYMBOLS, start=START, timeframe=TIMEFRAME)

print(data.wrapper.index)
In [ ]:
def get_bbands(data):
    return vbt.IndicatorFactory.from_talib('BBANDS').run(
        data.get('Close'), **IND_PARAMS, hide_params=list(IND_PARAMS.keys()))


def get_info(bbands):
    info = dict()
    info['last_price'] = bbands.close.iloc[-1]
    info['last_change'] = (bbands.close.iloc[-1] - bbands.close.iloc[-2]) / bbands.close.iloc[-1]
    info['last_crossed_above_upper'] = bbands.close_crossed_above(bbands.upperband).iloc[-1]
    info['last_crossed_below_upper'] = bbands.close_crossed_below(bbands.upperband).iloc[-1]
    info['last_crossed_below_lower'] = bbands.close_crossed_below(bbands.lowerband).iloc[-1]
    info['last_crossed_above_lower'] = bbands.close_crossed_above(bbands.lowerband).iloc[-1]
    info['bw'] = (bbands.upperband - bbands.lowerband) / bbands.middleband
    info['last_bw_zscore'] = info['bw'].vbt.zscore().iloc[-1]
    info['last_change_zscore'] = bbands.close.vbt.pct_change().vbt.zscore().iloc[-1]
    info['last_change_pos'] = info['last_change_zscore'] >= CHANGE_NBDEV
    info['last_change_neg'] = info['last_change_zscore'] <= -CHANGE_NBDEV
    return info


def format_symbol_info(symbol, info):
    last_change = info['last_change'][symbol]
    last_price = info['last_price'][symbol]
    last_bw_zscore = info['last_bw_zscore'][symbol]
    return "{} ({:.2%}, {}, {:.2f})".format(symbol, last_change, last_price, last_bw_zscore)


def format_signals_info(emoji, signals, info):
    symbols = signals.index[signals]
    symbol_msgs = []
    for symbol in symbols:
        symbol_msgs.append(format_symbol_info(symbol, info))
    return "{} {}".format(emoji, ', '.join(symbol_msgs))
In [ ]:
from telegram.ext import CommandHandler

class MyTelegramBot(vbt.TelegramBot):
    def __init__(self, data, **kwargs):
        super().__init__(data=data, **kwargs)
        
        self.data = data
        self.update_ts = data.wrapper.index[-1]
        
    @property
    def custom_handlers(self):
        return (CommandHandler('info', self.info_callback),)
    
    def info_callback(self, update, context):
        chat_id = update.effective_chat.id
        if len(context.args) != 1:
            await self.send_message(chat_id, "Please provide one symbol.")
            return
        symbol = context.args[0]
        if symbol not in SYMBOLS:
            await self.send_message(chat_id, f"There is no such symbol as \"{symbol}\".")
            return
            
        bbands = get_bbands(self.data)
        info = get_info(bbands)
        messages = [format_symbol_info(symbol, info)]
        message = '\n'.join(["{}:".format(self.update_ts.strftime(DT_FORMAT))] + messages)
        await self.send_message(chat_id, message)
        
    @property
    def start_message(self):
        index = self.data.wrapper.index
        return f"""Hello! 

Starting with {len(index)} rows from {index[0].strftime(DT_FORMAT)} to {index[-1].strftime(DT_FORMAT)}."""
        
    @property
    def help_message(self):
        return """Message format:
[event] [symbol] ([price change], [new price], [bandwidth z-score])
    
Event legend:
⬆️ - Price went above upper band
⤵️ - Price retraced below upper band
⬇️ - Price went below lower band
⤴️ - Price retraced above lower band

GIF is sent once a band is crossed and the price change is 2 stds from the mean."""
In [ ]:
telegram_bot = MyTelegramBot(data)
telegram_bot.start(in_background=True)
In [ ]:
class MyDataUpdater(vbt.DataUpdater):
    _expected_keys=None
    
    def __init__(self, data, telegram_bot, **kwargs):
        super().__init__(data, telegram_bot=telegram_bot, **kwargs)
        
        self.telegram_bot = telegram_bot
        self.update_ts = data.wrapper.index[-1]
        
    def update(self):
        super().update()
        self.update_ts = vbt.timestamp(tz=self.update_ts.tz)
        self.telegram_bot.data = self.data
        self.telegram_bot.update_ts = self.update_ts
        
        bbands = get_bbands(self.data)
        info = get_info(bbands)
        
        messages = []
        if info['last_crossed_above_upper'].any():
            messages.append(format_signals_info('⬆️', info['last_crossed_above_upper'], info))
        if info['last_crossed_below_upper'].any():
            messages.append(format_signals_info('⤵️', info['last_crossed_below_upper'], info))
        if info['last_crossed_below_lower'].any():
            messages.append(format_signals_info('⬇️', info['last_crossed_below_lower'], info))
        if info['last_crossed_above_lower'].any():
            messages.append(format_signals_info('⤴️', info['last_crossed_above_lower'], info))
            
        if len(messages) > 0:
            message = '\n'.join(["{}:".format(self.update_ts.strftime(DT_FORMAT))] + messages)
            self.telegram_bot.send_message_to_all(message)
        if (info['last_crossed_above_upper'] & info['last_change_pos']).any():
            self.telegram_bot.send_giphy_to_all("launch")
        if (info['last_crossed_below_lower'] & info['last_change_neg']).any():
            self.telegram_bot.send_giphy_to_all("fall")
In [ ]:
data_updater = MyDataUpdater(data, telegram_bot)
data_updater.update_every(UPDATE_EVERY)
In [ ]:
telegram_bot.stop()
In [ ]: