TradingBot series — create a Telegram channel for your bot

Matt Gosden
Aug 15, 2019 · 6 min read

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.

Image for post
Image for post

Why Telegram?

Image for post
Image for post

What can the bot do?

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


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

First step — initialise your Telegram bot

This will provide you with the Telegram bot and the tokens

Second step — Python project setup

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

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
bot = telegram.Bot(token=TOKEN)
for id in CHAT_IDS:
bot.send_message(id, message)
... handle error ...

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

How Telegram deals with commands

  1. 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

#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,
# log errors
# Start the Bot
if __name__ == '__main__':

You can add multiple add_handler to deal with different commands.

The 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
def help(bot, update):
"""Send a message when the command /help is issued."

'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
import krakenex
from pykrakenapi import KrakenAPI
# Initialise kraken api as api
api = krakenex.API( ... )
k = KrakenAPI(api)
def balance(bot, update):
"""Get balance """
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"))}'
... 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


The logging package on Python is helpful. Here is a good tutorial to get started on logging.

Fifth step — Start the bot


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.

Data Driven Investor

empower you with data, knowledge, and expertise

Sign up for DDIntel

By Data Driven Investor

In each issue we share the best stories from the Data-Driven Investor's expert community. Take a look

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Matt Gosden

Written by

Insurance meets tech meets music. #insurtech

Data Driven Investor

empower you with data, knowledge, and expertise

Matt Gosden

Written by

Insurance meets tech meets music. #insurtech

Data Driven Investor

empower you with data, knowledge, and expertise

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store