Hands-On Guide: Connecting a Python Market Scanner to Telegram Bot Alerts
Running a market scanner on Termux is efficient, but checking terminal logs manually defeats the purpose of automation. The most effective setup sends real-time push notifications straight to your mobile device via a custom Telegram Bot.
In this practical guide, we will set up a Telegram Bot using BotFather and integrate its API into our Termux Python script.
---------------------------------------------------
1. Creating Your Bot with BotFather
To set up a dedicated alert bot on Telegram:
1. Open the Telegram app and search for @BotFather.
2. Start a chat and send the command: /newbot
3. Follow the prompts to set a display name and unique username (e.g., MyMarketAlert_bot).
4. BotFather will generate an HTTP API Token (e.g., 123456789:ABCdefGhIJKlmNoPQ-RSTuvw). Save this token securely.
---------------------------------------------------
2. Finding Your Telegram Chat ID
Your bot needs to know where to send the alerts:
1. Search for @userinfobot or @raw_data_bot in Telegram and tap Start.
2. Copy your numerical User ID (Chat ID).
3. Alternatively, send a direct message to your new bot, open your mobile browser, and visit:
https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
4. Locate the "id" integer inside the "chat" object.
---------------------------------------------------
3. Python Code with Telegram Alert Integration
Open Termux, edit your scanner file (nano telegram_scanner.py), and paste the following code:
import time
import requests
# --- Configuration Setup ---
BOT_TOKEN = "YOUR_BOT_TOKEN_HERE"
CHAT_ID = "YOUR_CHAT_ID_HERE"
SYMBOL = "VOLATILITY_INDEX"
TARGET_PRICE = 1500.00 # Set your target alert level
def send_telegram_alert(message):
"""Sends a formatted message to your Telegram chat."""
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
payload = {
"chat_id": CHAT_ID,
"text": message,
"parse_mode": "Markdown"
}
try:
response = requests.post(url, json=payload, timeout=10)
if response.status_code == 200:
print("Telegram alert sent successfully!")
else:
print(f"Failed to send alert: {response.text}")
except Exception as e:
print(f"Network error sending Telegram notification: {e}")
def check_market_conditions():
"""
Placeholder function for price retrieval.
Connect this to your preferred broker REST API endpoint.
"""
# Example mock logic returning current price
return 1505.50
def main():
print(f"--- Telegram Market Bot Active for {SYMBOL} ---")
alert_triggered = False
while True:
current_price = check_market_conditions()
if current_price:
print(f"[{time.strftime('%H:%M:%S')}] Monitoring {SYMBOL}: {current_price}")
# Alert Logic
if current_price >= TARGET_PRICE and not alert_triggered:
alert_text = (
f"🚨 *MARKET ALERT TRIGGERED* 🚨\n\n"
f"*Asset:* {SYMBOL}\n"
f"*Target Price:* {TARGET_PRICE}\n"
f"*Current Price:* {current_price}\n"
f"*Time:* {time.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
f"Check MetaTrader 5 terminal for trade setup."
)
send_telegram_alert(alert_text)
alert_triggered = True # Prevent repeated alert spamming
time.sleep(30) # Check every 30 seconds
if __name__ == "__main__":
main()
---------------------------------------------------
4. Running in Background on Termux
1. Save the file in nano (Ctrl + O, Enter, Ctrl + X).
2. Execute the script:
python telegram_scanner.py
3. Enable background execution so Android doesn't stop the process when your screen locks:
termux-wake-lock
---------------------------------------------------
Final Thoughts
Combining Termux Python execution with Telegram HTTP endpoints gives you a completely free, self-hosted mobile notification system. You can easily adjust the logic to monitor indicator values like RSI overbought/oversold levels or Moving Average crossovers.
Stay tuned for our next tutorial on adding Stop Loss, Take Profit, and auto-execution to your MQL5 Expert Advisor!
Comments
Post a Comment