Telegram Trading Bot: Step-by-Step Guide
How to build a Telegram trading bot using EODHD APIs with push alerts, commands, and open-source support.
So, you want to create a Telegram trading bot — but where do you begin? Naturally, the first step is to understand what Telegram actually is.
What is Telegram?
Telegram is a cloud-based messaging platform known for its speed, strong security, and rich feature set. It supports private chats, large-scale “supergroups”, public channels, voice and video calls, and file sharing of up to 2 GB per file. What truly distinguishes Telegram is its open and well-documented APIs: the Bot API for creating chatbots and mini-apps, MTProto and TDLib for building custom clients, and the Gateway API for sending verification codes. This openness has led to a thriving ecosystem of bots, integrations, and third-party clients — all without fees or restrictive approval processes.
In contrast, platforms like WhatsApp and Viber impose tighter restrictions. WhatsApp only provides a Business API that requires going through approved vendors, using paid templates, and complying with strict session rules. Viber’s RESTful Bot API is limited to automated public accounts — it doesn’t allow full custom clients or apps. Simply put, Telegram gives developers far more flexibility and freedom than these more closed, enterprise-oriented platforms.
Download Telegram
To proceed, download the Telegram app. For the purposes of this guide, it doesn’t matter which platform you use — the Desktop and Mobile versions work equally well.
Create a Telegram Bot
Now we’ll set up a generic bot — this is the foundation for your trading bot, and it’s the same process used for creating any Telegram bot. We’ll use BotFather for this step. Open the link and click “Start”.
Next, send the /newbot
command to BotFather and follow the prompts. You’ll need to provide a name for your bot (we called itEODHDAlerts
) and assign it a unique username (e.g., eodhdalerts_bot
).
Done! Congratulations on your new bot. You will find it at t.me/eodhdalerts_bot. You can now add a description, about section and profile picture for your bot, see /help for a list of commands. By the way, when you’ve finished creating your cool bot, ping our Bot Support if you want a better username for it. Just make sure the bot is fully operational before you do this.
Use this token to access the HTTP API:
<YOUR_TOKEN>
Keep your token secure and store it safely, it can be used by anyone to control your bot.
For a description of the Bot API, see this page: https://core.telegram.org/bots/api
Make a note of your <YOUR_TOKEN>
— you’ll need it in the next step. We’ll refer to this as TELEGRAM_BOT_TOKEN
in the config.py
file.
Retrieving your Client ID is slightly trickier — and it’s a common stumbling block. You won’t be able to obtain the Client ID until you’ve sent at least one message to your bot. This is a critical step that many users overlook, often leading to confusion.
Open your bot, in our case: https://t.me/eodhdalerts_bot).
IMPORTANT:
Send at least one message to your bot (e.g., “hello”).
Then, navigate to:
https://api.telegram.org/bot<YOUR_TOKEN>/getUpdates
Make sure to replace <YOUR_TOKEN>
with your actual bot token in the URL above. This will display all messages sent to the bot.
Look for the "id"
field in the JSON response — that’s your Telegram Chat ID, which we’ll reference as TELEGRAM_CHAT_ID
in the config.py
file.
Before proceeding, make sure you have both:
TELEGRAM_BOT_TOKEN
TELEGRAM_CHAT_ID
You’ll need these values set up in your configuration file.
Key Features
When developing our Telegram trading bot, we’re aiming to implement two primary capabilities:
- Push-Based Alerts:
A background service (daemon) will continuously fetch and analyze historical market data using the EODHD API. During processing, a trading strategy will be applied to detect buy and sell signals. Whenever such a signal is triggered, the bot will automatically post a message to the designated Telegram group, notifying subscribers that a potential trade opportunity has been identified.
Important: Do not place trades blindly. Always use your own judgment and analysis before acting on any trade suggestions. - Pull-Based Commands:
In addition to automatic alerts, users should be able to request information on demand. For example, typing/get_price
into the Telegram channel could return the latest price of a specific asset.
Project Overview
This tutorial outlines how to set up the foundational structure of the bot framework and get the core functionality up and running. Future articles will go deeper into specialized Push and Pull features.
Open Source Collaboration
We’re excited to share that EODHD APIs are considering launching this as an open-source initiative. It’s a great opportunity to foster a collaborative developer community. When we built PyCryptoBot, the project attracted over 50 contributors from various backgrounds — developers, experienced traders, and passionate hobbyists. At its peak, the community had more than 1,000 active participants discussing the project in real-time. We hope this marks the beginning of another dynamic and collaborative effort. The initial project codebase is available here.
Understanding the Code
We won’t dive into every line of code in this tutorial. Instead, we’ll highlight key elements essential to understanding the bot’s architecture. If any part needs further clarification, we’re open to feedback. A basic understanding of Python, APIs, and the EODHD API will be helpful.
One of the most important files, which is not included in the repository, is config.py
. You’ll need to create this file yourself and populate it with the following:
EODHD_API_TOKEN
– your EODHD API key for retrieving historical dataTELEGRAM_BOT_TOKEN
– the Telegram bot token you generated earlierTELEGRAM_CHAT_ID
– the chat ID associated with your bot, as retrieved via Telegram API- Additional variables — parameters for processing historical data and applying a basic simple moving average (SMA) strategy
# config.py
EODHD_API_TOKEN = "<REMOVED>"
TELEGRAM_BOT_TOKEN = "<REMOVED>"
TELEGRAM_CHAT_ID = "<REMOVED>"
DEFAULT_SYMBOL = "AAPL.MX" # BTC-USD.CC
DEFAULT_INTERVAL = "d" # 1m, 5m, 1h, d, w, m
SHORT_WINDOW = 20
LONG_WINDOW = 50
The primary script that drives the application is bot.py
. This daemon handles fetching and processing historical market data, posting updates to the Telegram channel, and listening for commands sent via the chat. In this initial version, we’ve implemented the following commands: /start
, /set_symbol
, /set_interval
, and /get_price
.
# bot.py
from telegram.ext import Updater, CommandHandler
from config import TELEGRAM_BOT_TOKEN
from handlers import start, set_symbol, set_interval, get_price, analyse_market
from telegram.ext import JobQueue
def main():
updater = Updater(TELEGRAM_BOT_TOKEN)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", start))
dp.add_handler(CommandHandler("set_symbol", set_symbol))
dp.add_handler(CommandHandler("set_interval", set_interval))
dp.add_handler(CommandHandler("get_price", get_price))
job_queue: JobQueue = updater.job_queue
job_queue.run_repeating(analyse_market, interval=60, first=0)
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()
A few classes have been implemented following SOLID design principles. DataFetcher
in data_fetcher.py
manages data retrieval from the EODHD APIs. SMACrossoverStrategy
, found in strategy.py
, serves as a basic strategy example for demonstrating how the Telegram bot works. TelegramNotifier
in telegram_notifier.py
is responsible for sending messages to the Telegram bot channel (this represents the “Push” feature). Finally, there’s handlers.py
, which isn’t structured as a class but instead contains the functions that process user commands sent to the bot. The logic should be fairly straightforward.
This is an ongoing project that will be expanded in upcoming articles.
# handlers.py
from telegram import Update
from telegram.ext import CallbackContext
from config import DEFAULT_SYMBOL, DEFAULT_INTERVAL
from data_fetcher import DataFetcher
from strategy import SMACrossoverStrategy
from telegram_notifier import TelegramNotifier
symbol = DEFAULT_SYMBOL
interval = DEFAULT_INTERVAL
def start(update: Update, context: CallbackContext):
update.message.reply_text("Welcome to the Trading Bot!")
def set_symbol(update: Update, context: CallbackContext):
global symbol
if context.args:
symbol = context.args[0]
update.message.reply_text(f"Symbol set to {symbol}")
else:
update.message.reply_text("Please provide a symbol.")
def set_interval(update: Update, context: CallbackContext):
global interval
if context.args:
interval = context.args[0]
update.message.reply_text(f"Interval set to {interval}")
else:
update.message.reply_text("Please provide an interval.")
def get_price(update: Update, context: CallbackContext):
fetcher = DataFetcher(symbol, interval)
price = fetcher.fetch_price()
if price:
update.message.reply_text(f"Current price of {symbol}: {price}")
else:
update.message.reply_text("Failed to fetch data.")
def analyse_market(context: CallbackContext):
fetcher = DataFetcher(symbol, interval)
data = fetcher.fetch_ohlc()
if data.empty:
return
strategy = SMACrossoverStrategy(short_window=20, long_window=50)
signals = strategy.generate_signals(data)
latest_signal = signals["position"].iloc[-1]
notifier = TelegramNotifier()
if latest_signal == 1:
notifier.send_message(f"Buy signal for {symbol}")
elif latest_signal == -1:
notifier.send_message(f"Sell signal for {symbol}")
We hope this overview has provided a clear and helpful introduction to the project. You should be able to clone the repository, add the config.py
file, and run the bot without issues.
If you have ideas, feature suggestions, or are interested in contributing, feel free to reach out!
See you in the next article of this series. Stay tuned!
Please note that this article is for informational purposes only and should not be taken as financial advice. We do not bear responsibility for any trading decisions made based on the content of this article. Readers are advised to conduct their own research or consult with a qualified financial professional before making any investment decisions.
For those eager to delve deeper into such insightful articles and broaden their understanding of different strategies in financial markets, we invite you to follow our account and subscribe for email notifications.
Stay tuned for more valuable articles that aim to enhance your data science skills