

How to Create Custom Telegram Alerts for MT5 in Minutes
Table of Contents
- Introduction
- What Is Custom Telegram Alert Bot for MT5
- Why Custom Telegram Alerts Matter for Traders and Investors
- Core Concepts
- Step‑by‑Step Guide
- Practical Tips for Better Results
- Common Mistakes to Avoid
- Frequently Asked Questions
- Conclusion
Introduction
When the EUR/USD pair slipped through the 1.2000 barrier on Tuesday, a handful of retail traders watched the price action on a crowded chart and missed the breakout because the platform’s built‑in pop‑up stayed hidden behind a sea of indicators. The same price movement could have triggered a phone vibration, a Slack ping, or a Telegram message—if the trader had a custom alert bot wired into the workflow.
Most MT5 users lean on the default push‑notification service, which is confined to a single device, offers only plain‑text alerts, and lacks any formatting options. In fast‑moving markets, especially when high‑impact news widens spreads on major contracts such as the S&P 500 futures or the EUR/USD, a delayed or unread alert can turn a modest profit into a rapid loss.
This guide walks you through building a Telegram alert bot that pushes strategy‑specific signals straight to your mobile device. You’ll see the exact MQL5 code required, learn how to configure the Telegram Bot API, and adopt error‑handling practices that keep the alert pipeline reliable even when volatility spikes. By the end, you’ll be able to deploy a bot that not only tells you when a trade meets your criteria but also suggests position size, stop‑loss levels, and risk‑to‑reward ratios—all in a single, richly formatted Telegram message.
What Is Custom Telegram Alert Bot for MT5?
A custom Telegram alert bot is a lightweight program that lives inside MetaTrader 5, monitors market events defined by your MQL5 script, and forwards a formatted JSON payload to a Telegram chat via the Bot API. Unlike the platform’s generic push service, the bot can embed any data you program: raw price, indicator values, suggested lot size, a link to a chart snapshot, or even a brief commentary on market context.
Example: A trader builds an MQL5 expert advisor that watches the 20‑period EMA on GBP/JPY. When the 20‑EMA crosses above the 100‑EMA, the script calls the Telegram API and delivers a message that reads:
GBP/JPY EMA crossover detected at 152.35. Suggested entry: 152.40, SL 151.80, lot 0.10.
The message arrives instantly on the trader’s phone, allowing a split‑second decision that would be impossible with a delayed desktop pop‑up.
Why Custom Telegram Alerts Matter for Traders and Investors
Professional desks at CFTC‑regulated futures markets and boutique forex firms routinely route alerts to Slack, proprietary dashboards, or dedicated messaging platforms. Retail traders, however, need a lightweight, mobile‑first solution that works on both iOS and Android without incurring additional licensing fees.
– Who benefits: day traders juggling dozens of symbols, swing traders waiting for multi‑timeframe confirmations, and systematic investors who want a human‑readable log of every rule‑trigger.
– When it matters: during fast‑moving news releases, when the spread on S&P 500 futures widens dramatically, or when a liquidity vacuum on EUR/USD creates slippage that can erode a carefully planned entry.
– What you lose by ignoring it: relying on a single‑device push may leave you blind if your phone is on silent, if the broker’s server throttles notifications, or if you trade across several accounts simultaneously. A Telegram bot decouples the alert from the broker, providing redundancy, richer context, and the ability to archive every signal for later review.
MQL5 Event Handlers – OnTick and OnTimer
MQL5 scripts react to market data through built‑in event handlers. OnTick fires for every incoming price tick, making it ideal for high‑frequency breakout strategies that need to react the instant a price breaches a level. OnTimer runs on a fixed schedule, useful for end‑of‑day summaries, hourly risk checks, or any logic that does not require tick‑by‑tick granularity.
Scenario: A breakout strategy monitors EUR/USD on a 5‑minute chart. The script places the breakout logic inside OnTick so that the moment the price exceeds 1.2000, the condition is evaluated instantly and an alert is sent. For a daily risk‑budget report, OnTimer runs at 23:55 server time, aggregates the day’s win‑loss count, and pushes a concise Telegram summary to the trader’s group.
Telegram Bot API – Webhook vs. getUpdates
Telegram offers two delivery models. A webhook pushes updates to a URL you host; getUpdates polls Telegram’s servers for new messages. For MT5, a lightweight webhook endpoint on a cloud service (AWS Lambda, Google Cloud Functions, or a modest VPS) reduces latency to a few hundred milliseconds—critical for scalping strategies. If you lack hosting, getUpdates can be run from a local script, though it introduces additional round‑trip time.
Scenario: A trader hosts a simple PHP endpoint that receives a JSON payload from MT5 and immediately forwards it to Telegram via the sendMessage method. Because the endpoint returns a 200 status within 200 ms, the round‑trip time stays under the threshold needed to capture GBP/JPY moves as small as 0.2 pip.
JSON Payload Construction for Message Formatting
Telegram expects a JSON object with fields such as chat_id, text, and optional parse_mode. Crafting the payload inside MQL5 involves concatenating strings, converting numeric values to text, and escaping characters required by MarkdownV2. Using MarkdownV2 lets you bold the entry price, italicize the stop‑loss, and embed a hyperlink to a chart image hosted on an external server.
Scenario: When a 50‑period SMA on Nasdaq futures turns bullish, the bot sends:
*Nasdaq SMA Alert*
Price: 13,450.00
Signal: SMA(50) crossed above SMA(200)
Chart: https://mycharts.com/nasdaq202408_02.png
The bold header draws immediate attention, while the chart link lets the trader verify the signal without opening MT5.
MT5 Push Notification Service vs. Telegram Integration
MT5’s native push service uses the MetaQuotes server and a mobile‑app token. It works reliably for a single device but cannot embed rich text, images, or custom fields such as risk‑to‑reward ratios. Telegram integration bypasses the broker’s server, allowing alerts to be sent to any device that runs the Telegram client and to include additional data that aids rapid decision‑making.
Scenario: A native MT5 push might read “Order executed.” The same event, routed through Telegram, could read:
✅ Long EUR/USD opened at 1.1998
RR: 1.5
Lot: 0.05
The extra data helps the trader assess trade quality at a glance, especially when juggling multiple positions.
Error Handling with try‑catch and GetLastError in MQL5
Network calls from MT5 can fail for a variety of reasons: DNS resolution problems, firewall blocks, or Telegram’s rate limits. Wrapping the HTTP request in a try‑catch block and checking GetLastError() after each call lets the script log failures to a local file and optionally retry after a short pause.
Scenario: During a high‑impact Fed announcement, the broker’s server experiences latency, causing the HTTP POST to Telegram to time out. The script catches the exception, writes “Telegram send failed – error 410” to AlertsLog.txt, and retries after five seconds. This prevents missed alerts during the most volatile periods of the trading day.
Core Concepts
Below we break down the technical building blocks that make a Telegram alert bot reliable, fast, and easy to maintain.
1. Bot Registration and Token Security
The BotFather conversation yields a token that authorizes every HTTP call to the Bot API. Treat this token like a password: store it in an encrypted configuration file, never hard‑code it in a public repository, and rotate it periodically to mitigate credential leakage.
2. Choosing Between Webhook and Polling
Webhooks excel when you can host a publicly reachable HTTPS endpoint; they push updates instantly. Polling (getUpdates) is simpler to set up but adds latency and consumes more API calls, which can be problematic under Telegram’s rate limits (≈30 messages per second per bot).
3. Message Size and Rate Limits
Telegram caps each message at 4096 bytes. Large chart images should be sent via the sendPhoto method rather than embedding them in the text payload. Exceeding the per‑second message limit triggers a “Too Many Requests” error; your script should back off and retry after the retry_after interval returned by the API.
4. Parsing and Escaping MarkdownV2
MarkdownV2 requires special characters (underscores, asterisks, brackets) to be escaped with a backslash. Failure to do so results in malformed messages that appear as raw JSON. A helper function that scans the text and adds the necessary escape characters can save hours of debugging.
5. Logging and Auditing
Every successful send should be logged with a timestamp, chat ID, and message hash. This audit trail becomes essential for compliance under CFTC rules, especially for systematic traders who need to demonstrate that alerts were generated and acted upon in a documented manner.
Step‑by‑Step Guide
## Step 1 — Register a Telegram Bot and Obtain the Token
1. Open Telegram and start a chat with @BotFather.
2. Send the command /newbot and follow the prompts to give the bot a name and a unique username.
3. BotFather replies with a token string that looks like 123456789:ABCdefGhIJKlmnoPQRstuVWXyz. Store this token securely; it authorizes every HTTP call to the Bot API.
Step 2 — Set Up a Receiving Endpoint (Webhook)
- Choose a lightweight hosting option—AWS Lambda, Google Cloud Functions, or a low‑cost VPS with a static IP.
- Deploy a script (PHP, Python, or Node.js) that accepts a POST request, extracts the JSON fields, and forwards them to
https://api.telegram.org/bot<token>/sendMessage. - Register the webhook by calling:
https://api.telegram.org/bot<token>/setWebhook?url=https://yourdomain.com/mt5alert
Verify the response contains"Webhook was set".
Tip: Use HTTPS; Telegram rejects non‑secure URLs, and SSL encryption protects the token in transit.
Step 3 — Write the MQL5 Alert Function
- In MetaEditor, create a new include file named
TelegramAlert.mqh. - Define a function
SendTelegramAlert(string message)that assembles a JSON string:
mql5
string json = "{ \"chat_id\": \"" + ChatID + "\", \"text\": \"" + message + "\", \"parse_mode\": \"MarkdownV2\" }";
- Use
WebRequest("POST", "https://api.telegram.org/bot" + BotToken + "/sendMessage", "", json)to post the payload. - After the request, capture
int err = GetLastError();and, iferr != 0, write the error code and timestamp toAlertsLog.txt.Step 4 — Hook the Alert into Your Trading Logic
Insert
SendTelegramAlertinside the condition that triggers a trade. For the EUR/USD breakout example:
mql5
if (Close[0] > 1.2000 &&
iMA(NULL,0,50,0,MODE_SMA,PRICE_CLOSE,0) > iMA(NULL,0,200,0,MODE_SMA,PRICE_CLOSE,0))
{
string msg = "EUR/USD Breakout\nPrice: 1.2000\nSuggested lot: 0.10\nSL: 1.1950";
SendTelegramAlert(msg);
}
Replace the placeholder token and chat ID with the values you stored securely in step 1.
Step 5 — Test the Bot on a Demo Account
- Attach the script to a chart on a demo account.
- Manually trigger the condition—use the strategy tester to step through price data or adjust the price via the “Modify” window.
- Confirm that the Telegram message arrives, that MarkdownV2 formatting appears as intended, and that no error is logged.
If the message fails, inspectAlertsLog.txtfor the error code and verify that the webhook URL is reachable from the broker’s server (usecurlfrom a remote machine to test connectivity).
Step 6 — Deploy to Live Trading (Optional)
- Move the
.mq5file to theMQL5\Expertsfolder of your live MT5 installation. - In MetaTrader, enable Allow DLL imports and Allow WebRequest for listed URLs under Tools → Options → Expert Advisors. Add
https://api.telegram.orgto the allowed list. - Monitor the first 24 hours closely; adjust the retry interval if you notice missed alerts during high‑volatility windows such as FOMC meetings or major economic releases.
Practical Tips for Better Results
- Dedicated group: Create a Telegram group solely for alerts and set the bot as an administrator. This avoids message throttling that can occur in personal chats.
- Escape Markdown: Encode special characters (underscores, asterisks, backticks) in MarkdownV2 to prevent formatting errors. A small helper routine that runs
StringReplaceon the message string saves time. - Payload size: Keep the JSON payload under 1 KB. Large chart images should be sent with the
sendPhotomethod; this prevents hitting the 4096‑byte limit for text messages. - Token rotation: Rotate the bot token every few months and store it in an encrypted file on the server. This reduces the risk of credential leakage if the file is ever exposed.
- Hybrid event handling: Combine
OnTickfor entry signals withOnTimerfor daily risk‑budget summaries. This balances the need for immediacy with a broader overview of performance. - Latency testing: Before attaching complex logic, send a simple “ping” message from MT5 to Telegram and measure round‑trip time. Delays above 500 ms can erode the edge of scalping strategies that rely on sub‑second execution.
- Audit logging: Log every successful send with a timestamp, chat ID, and a hash of the message content. The log becomes a valuable audit trail for compliance under CFTC rules and helps you reconcile any discrepancies between expected and actual trades.
Common Mistakes to Avoid
- Hard‑coding the chat ID: If you add the bot to a new group, the old ID becomes invalid and alerts stop. Retrieve the chat ID dynamically or store it in a configuration file that you update whenever the group changes.
- Skipping SSL verification: An insecure endpoint can be blocked by Telegram, leading to silent failures. Always serve the webhook over HTTPS with a valid certificate.
- Ignoring GetLastError: Without error checks, a failed HTTP request leaves you unaware of missed alerts. Log every non‑zero error code and implement a retry mechanism.
- Overloading the bot during news spikes: Telegram caps a bot at roughly 30 messages per second. Burst alerts during major news releases can be dropped; consider aggregating multiple signals into a single summary message.
- Using OnTick for low‑liquidity symbols: Tick frequency may be sparse for exotic pairs or thinly traded commodities, causing delayed alerts. For such markets,
OnTimerwith a reasonable interval (e.g., 30 seconds) may be more reliable.
How to create a Telegram alert bot for MT5?
Register a bot with BotFather, set up a webhook endpoint that forwards JSON to the Telegram API, and call the endpoint from an MQL5 script using WebRequest. The steps above outline the full workflow from token acquisition to live deployment.
What code is needed to send MT5 alerts to Telegram?
You need a function that builds a JSON payload containing chat_id, text, and optionally parse_mode, then posts it via WebRequest("POST", "https://api.telegram.org/bot<token>/sendMessage", "", json). Wrap the call in a try‑catch block and log GetLastError() for robustness.
Why use Telegram instead of MT5 built‑in alerts?
Telegram delivers to any device, supports rich formatting, and can include images, risk metrics, and hyperlinks. It also separates the alert channel from the broker’s server, reducing the single‑point‑failure risk inherent in the native push service.
When should I trigger a custom alert based on price levels?
Trigger alerts at moments that change your trade decision: a breakout of a key support or resistance, an EMA crossover, or a volatility spike indicated by the VIX. Align the trigger with your strategy’s entry rule to avoid noise and unnecessary chatter.
Can I backtest custom Telegram alerts in MT5?
Yes. Use the Strategy Tester to run your MQL5 script on historical data; the Print statements will appear in the tester’s log, and you can simulate the webhook by directing output to a local file. Actual Telegram delivery cannot be replayed, but you can verify logic, timing, and message composition.
Is there a limit to messages per day on Telegram bots?
Telegram enforces a rate limit of roughly 30 messages per second per bot and a daily cap of 20,000 messages for standard bots. Exceeding these limits results in “Too Many Requests” errors, which your script should catch and back off according to the retry_after value returned by the API.
Conclusion
A well‑engineered Telegram bot transforms MT5’s native alerts into a flexible, mobile‑first communication channel that gives you control over content, timing, and redundancy. The core lesson is simple: the technology is only as valuable as the strategy that drives it. Register a bot, deploy a lightweight webhook, and fire a test message from a demo chart before you go live.
Remember, an alert is a prompt, not a guarantee. False signals can arise from coding bugs or from market conditions that invalidate the underlying rule. Always size positions conservatively, respect stop‑loss levels, and treat every notification as a cue to verify the trade on your chart before acting.
—
Risk disclaimer: Trading involves substantial risk of loss. The information provided here is for educational purposes and does not constitute investment advice.
—
This article is for educational purposes only and does not constitute investment advice. Trading and investing carry risk of loss; never invest more than you can afford to lose.
Last reviewed: August 2026




















































