TradingBot series — create a Telegram channel for your bot
In this post we show how to set up a simple Telegram channel for your trading bot. Telegram is a great way to communicate with your bot when you are on the move. It is also a good way to share the bot’s activity with selected collaborators.

Why Telegram?
Telegram is a cross-platform messaging service with encryption and has a good API. It enables you to set up a channel for your bot that you can use to talk to it, or it can post update messages for you.

What can the bot do?
Our bot should enable users to interact with the trading bot, to find out the status and manage the bot. This includes:
Posting a message when a trade is triggered.
Providing the latest positions when asked.
Providing the latest indicators and status when asked.
Changing which assets are being live traded vs paper traded.
Potentially also posting trades manually
…
Steps
We will first create a bot on Telegram using the Telegram tools.
We will then write some Python code to communicate with the Telegram bot via their API to create the capability to post messages to the Telegram bot.
We will then create a listener bot that will respond to commands that we give the bot via Telegram.
A note on privacy
Your telegram bot will be public by default. Anyone can find it when searching and can start to talk to it. However you can still lock it down so that the bot will only talk to people that you pre-approve by adding their chatID
.
First step — initialise your Telegram bot
Set up an account for yourself on Telegram, and use the Botfather to set up a new bot on Telegram. I won’t repeat the steps here as there are good tutorials elsewhere on this.
This will provide you with the Telegram bot and the tokens
Second step — Python project setup
Python has a good Telegram API library that is easy to use.
Within your virtual environment:
pip install python-telegram-bot
In your project code, create a new module or file to hold the Telegram code.
import telegramTOKEN = 'token_from_botfather_for_your_bot'CHAT_IDS = ['your_chat_id', ]
Getting your CHAT_IDS
for yourself or a collaborator is a bit of a fiddle but this tutorial shows how to do it using the getUpdates method. Maybe there is an easier way.
Note that the CHAT_IDS
are defined as a list here so that you can add multiple chat ids for different people. We will set up the bot below so that it only responds to users with the right Telegram chat_ids.
Third step — broadcasting messages using your Telegram bot
Sending messages to the Telegram bot to post, is simple. The bot can broadcast pretty much any text message you want.
We create a post_message method, which can then be imported anywhere in our project and used to send a Telegram bot message. You use it almost like a print
statement and send a string of text. This text will then be broadcast to you and your collaborators on your Telegram bot.
#telegram_bot.pyimport telegramTOKEN = 'your_bot_token'
CHAT_IDS = ['your_chat_id', ]def post_message(message):
"""
Posts a message to the telegram bot chats
:param str message: A string message
:return: None
"""
try:
bot = telegram.Bot(token=TOKEN)
for id in CHAT_IDS:
bot.send_message(id, message)
except:
... handle error ...
return
Whenever any of our trading bots have a trade signal we wish to send to the Telegram bot in real-time, we import and use the post_message method:
from telegram_bot import post_message...post_message('I found a great trade! details ... blah-blah')
Fourth step — making requests to your Telegram bot
Enabling the bot to respond to requests and commands requires a separate listener module. The idea is you want to be able to post commands to your bot in your Telegram app and it then posts a trade, shows you your balance, or kicks off some other function.
How Telegram deals with commands
- You post a command to your Telegram bot using a command in the Telegram app such as
/help
or/trade buy XBT 3.0
- Your Python listener module (using the python telegram library) sees this command has been posted via the API, parses it and then reacts accordingly.
Creating the listener
We start up a listener that will watch for Telegram commands and parse them. When it identifies a command then it calls a function that you specify
#telegram_listener.pyfrom telegram.ext import Updater, CommandHandler, MessageHandler, FiltersCHAT_IDS = [ ... ]...
[functions to do things added here or imported]
...def main(): # Create an updater object using your bot's token
updater = Updater(TOKEN)
dp = updater.dispatcher # on /help call help function and respond to anyone
dp.add_handler(CommandHandler("help", help)) # on /trade call trade function but only to CHAT_ID users
dp.add_handler(CommandHandler("trade", trade,
filters=Filters.chat(CHAT_IDS))) # log errors
dp.add_error_handler(error) # Start the Bot
updater.start_polling()
updater.idle()if __name__ == '__main__':
main()
You can add multiple add_handler
to deal with different commands.
The filters=Filters.chat()
option enables you to secure your bot so that it only responds to those people whose CHAT_ID
is in the list.
A simple help function
This is an example of the help
function that is called by the handler when a user posts /help
in the Telegram bot. This just returns a help screen explaining what the different commands do.
#telegram_listener.py
...def help(bot, update):
"""Send a message when the command /help is issued."
update.message.reply_text(
'Try these commands:\n' +
'/ticker [pair] - get latest ticker\n' +
'/balance [currency] - get latest balance\n' +
'/orderbook [pair] [depth] - get orderbook\n' +
'/limit [buy/sell] [pair] [quantity] [price] - trade\n' +
'/stop [buy/sell] [pair] [quantity] [price] - trade\n' +
'/market [buy/sell] [pair] [quantity] - trade\n' +
'/orders [pair] - show open orders\n' +
'/cancel-all [pair] - cancel all orders\n' +
'/cancel [order_id] - cancel one order\n' +
'/tradehistory - show last few closed trades\n' +
'/address [currency] - get address\n' +
'/newaddress [currency] - create new address'
)...
A simple balance display function
This is an example of a simple function that returns all the balances on a Kraken exchange account in a simple list. The user passes the command /balance
in the Telegram bot.
#telegram_listener.py
...import krakenex
from pykrakenapi import KrakenAPI# Initialise kraken api as api
api = krakenex.API( ... )
k = KrakenAPI(api)def balance(bot, update):
"""Get balance """
try:
response = api.api_get_all_balances()
message = ""
for balance in response["result"]["balances"]:
if balance.get("available"):
message = message + f'\n{balance.get("currency")}:'
+ f'{float(balance.get("available"))}'
update.message.reply_text(message)
except:
... handle error ...
There are many other commands you could wire in, for example:
/indicators
show the latest indicator values/performance symbol
show the latest performance statistics for a market/orders
list of open orders on the exchange/trades
list of recent trades/trade symbol amount price
to add a trade- …
Debugging
Telegram fails silently and therefore it can be a bit a pain to debug what is going on when the messages or commands fail.
The logging package on Python is helpful. Here is a good tutorial to get started on logging.
Fifth step — Start the bot
To listen for Telegram commands, the telegram_listener module needs to be running. To test it out run python telegram_listener.py
from the command line. Try out your Telegram bot and confirm it works correctly.
Deployment
To have your Telegram bot responding to users, your Telegram listener bot needs to be up and running 24/7.
The trading bot and Telegram listening bot would usually be deployed together on a small virtual machine so that it will be up at all times. A $5 or $10 a month virtual machine will usually be sufficient.
DigitalOcean is both easy to use and good value. Below is a promo link that gives a discount.