Viewing the resource: Telegram Notifications System in MQL5

Telegram Notifications System in MQL5

Allan Munene Mutiiria 2025-06-26 11:41:32 108 Views
This MQL5 EA sends account status (equity, free margin) to a Telegram chat on initialization, using ...

Introduction

Picture maintaining vigilant oversight of your trading account, like a precision alert system delivering critical updates to your Telegram command center. The TG Notifications EA is your advanced monitoring tool, designed to integrate MetaTrader 5 with Telegram to send real-time account status updates. Upon initialization ("OnInit()"), it transmits a message to a specified Telegram chat ("chatID") using a bot token ("botTkn") via a WebRequest ("WebRequest()", "TG_API_URL"), detailing the account’s equity and free margin ("AccountInfoDouble()", "ACCOUNT_EQUITY", "ACCOUNT_FREEMARGIN"). The message is formatted for clarity, ensuring traders receive concise financial insights. No automated trades are executed, focusing solely on communication. This non-trading EA suits traders needing remote account monitoring, requiring a stable internet connection and proper Telegram API setup for reliability.

This article is crafted with a professional, engaging, and seamless narrative, flowing like a well-calibrated alert system, designed to inform and captivate readers. Tailored for both novice and experienced traders, we’ll dissect each code component with clear, precise explanations, as if guiding an apprentice operator through a monitoring project. With vivid examples—like sending EURUSD chart updates—and a polished tone, we’ll explore how the EA initializes, prepares messages, sends notifications, and ensures cleanup. Using a precision alert system metaphor, this guide will illuminate the code’s technical rigor, empowering you to monitor your account with confidence. Let’s activate the system and begin this monitoring expedition!

Strategy Blueprint

Let’s outline the EA’s notification framework, like drafting specifications for an alert system:

  • Initialization: Sets up Telegram API parameters ("TG_API_URL", "botTkn", "chatID") and prepares a message in "OnInit()".

  • Message Preparation: Formats a message with account equity and free margin ("AccountInfoDouble()", "DoubleToString()") for clarity.

  • Notification Sending: Sends the message to Telegram via "WebRequest()", using POST method and a 10-second timeout.

  • Execution: Processes in "OnInit()", with no tick-based logic ("OnTick()" empty).

  • Enhancements: Adding trade-based notifications, periodic updates, or error logging could improve functionality. This framework automates account monitoring with precision, bridging MetaTrader 5 and Telegram.

Code Implementation

Let’s step into the alert system control room and dissect the MQL5 code that powers this TG Notifications EA. We’ll guide you through each phase like expert operators, ensuring the narrative flows seamlessly with professional clarity and engaging precision that captivates readers. We’ll cover initialization, message preparation, notification sending, and cleanup, with detailed explanations and examples—like monitoring EURUSD account status—to make it accessible for beginners. Each phase will build on the last, crafting a cohesive technical narrative that transforms code into a compelling monitoring project. Let’s power up the system and begin!

Phase 1: Constructing the Framework—Initialization

We start by building the notification system, initializing Telegram API parameters.

//+------------------------------------------------------------------+
//|                                          TG NOTIFICATIONS EA.mq5 |
//|                           Copyright 2025, Allan Munene Mutiiria. |
//|                                   https://t.me/Forex_Algo_Trader |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, Allan Munene Mutiiria."
#property link      "https://t.me/Forex_Algo_Trader"
#property version   "1.00"

const string TG_API_URL = "https://api.telegram.org";
const string botTkn = "7456439661:AAELUurPxI1jloZZl3Rt-zWHRDEvBk2venc";
const string chatID = "-4273023945";

int OnInit(){
   char data[];
   char res[];
   string resHeaders;
   double accountEquity = AccountInfoDouble(ACCOUNT_EQUITY);
   double accountFreeMargin = AccountInfoDouble(ACCOUNT_FREEMARGIN);
   string msg = "📊 Account Status 📊; Equity: $" + DoubleToString(accountEquity, 2) + "; Free Margin: $" + DoubleToString(accountFreeMargin, 2);
   const string url = TG_API_URL + "/bot" + botTkn + "/sendmessage?chat_id=" + chatID + "&text=" + msg;
   int send_res = WebRequest("POST", url, "", 10000, data, res, resHeaders);

The system begins with the #property header, establishing copyright and contact details, like calibrating an alert system’s core. The "OnInit()" function initializes the setup, defining Telegram API constants ("TG_API_URL", "botTkn", "chatID") and preparing arrays for the WebRequest ("data", "res", "resHeaders") with a 10-second timeout (10000). It retrieves account equity and free margin ("AccountInfoDouble()", "ACCOUNT_EQUITY", "ACCOUNT_FREEMARGIN") and formats a message ("msg") using "DoubleToString()". The Telegram URL ("url") is constructed for the sendmessage endpoint. This primes the EA for notification sending, like an alert system poised for action. Note: Commented code suggests additional notification types (e.g., trade signals, balance updates) for potential enhancements.

Phase 2: Preparing Messages—Formatting Account Status

With the system initialized, we prepare the notification message, like crafting an alert dispatch.

int OnInit(){
   // ... (initialization)
   double accountEquity = AccountInfoDouble(ACCOUNT_EQUITY);
   double accountFreeMargin = AccountInfoDouble(ACCOUNT_FREEMARGIN);
   string msg = "📊 Account Status 📊; Equity: $" + DoubleToString(accountEquity, 2) + "; Free Margin: $" + DoubleToString(accountFreeMargin, 2);
   const string url = TG_API_URL + "/bot" + botTkn + "/sendmessage?chat_id=" + chatID + "&text=" + msg;

In the message preparation hub, "OnInit()" fetches equity and free margin ("AccountInfoDouble()") and formats a concise message ("msg") with emoji decoration ("📊") and two-decimal precision ("DoubleToString()", e.g., “Equity: $1000.50; Free Margin: $950.25”). The URL combines "TG_API_URL", "botTkn", "chatID", and "msg" for the Telegram API. For example, on an EURUSD chart with equity=1000.50 and free margin=950.25, it prepares a message for dispatch, like crafting a status alert.

Phase 3: Sending Notifications—Transmitting to Telegram

With the message prepared, we send it to Telegram, like dispatching an alert.

int OnInit(){
   // ... (message preparation)
   int send_res = WebRequest("POST", url, "", 10000, data, res, resHeaders);
   if (send_res == 200){
      Print("TELEGRAM MESSAGE SENT SUCCESSFULLY");
   } else if (send_res == -1){
      if (GetLastError() == 4014){
         Print("PLEASE ADD THE ", TG_API_URL, " TO THE TERMINAL");
      }
      Print("UNABLE TO SEND THE TELEGRAM MESSAGE");
   } else if (send_res != 200){
      Print("UNEXPECTED RESPONSE ", send_res, " ERR CODE = ", GetLastError());
   }
   return(INIT_SUCCEEDED);
}

In the notification dispatch hub, "OnInit()" sends the message via "WebRequest()", using "POST", "url", empty headers, a 10-second timeout, and empty "data". On success ("send_res"=200), it logs “TELEGRAM MESSAGE SENT SUCCESSFULLY” with "Print()". On failure ("send_res=-1"), it checks for error 4014 (URL not allowed, suggesting to add "TG_API_URL") or logs a generic failure. Other errors log the response code and error ("GetLastError()"). For example, on EURUSD, a successful send delivers “📊 Account Status 📊; Equity: $1000.50; Free Margin: $950.25” to Telegram, like dispatching an alert to a command center.

Phase 4: Shutting Down the System—Cleaning Up Resources

As our expedition concludes, we shut down the system, ensuring resources are cleared.

void OnDeinit(const int reason){
}

In the shutdown control room, "OnDeinit()" is empty, requiring no cleanup as no persistent resources (e.g., files, arrays) are used, like a lightweight alert system. For completeness, a cleanup check could be added:

void OnDeinit(const int reason){
   // No persistent resources to clean up
}

This ensures the system shuts down cleanly, ready for the next task.

Why This EA is an Alert System Triumph

The TG Notifications EA is a monitoring triumph, delivering account status updates with precision, like a master-crafted alert system. Its simple yet effective notification logic ("WebRequest()", "AccountInfoDouble()") ensures reliable communication, with potential for trade-based or periodic alerts. Picture receiving an equity update on Telegram—strategic brilliance! Beginners will value the simplicity, while experts can enhance its functionality, making it essential for traders needing remote account insights.

Putting It All Together

To deploy this EA:

  1. Add "https://api.telegram.org" to MetaTrader 5’s allowed URLs (Tools > Options > Expert Advisors).

  2. Verify the bot token ("botTkn") and chat ID ("chatID") in Telegram (use /getUpdates to find the chat ID).

  3. Open MetaEditor in MetaTrader 5, like entering your alert system control room.

  4. Copy the code, compile with F5, and verify no errors—no operator wants a faulty system!

  5. Attach the EA to your chart and check Telegram for the account status message.

  6. Monitor logs (e.g., “TELEGRAM MESSAGE SENT SUCCESSFULLY”) for transmission tracking, like alert diagnostics.

  7. Test on a demo account first—real communication deserves a trial run!

Conclusion

We’ve engineered a Telegram Notifications system that delivers account updates with precision, like a master-crafted alert system. This MQL5 code is your strategic tool, brought to life with a seamless, professional narrative packed with clear explanations and vivid examples to fuel your monitoring confidence. Whether you’re a novice trader or a seasoned market strategist, this EA empowers you to stay informed remotely with ease. Ready to monitor? Watch our video guide on the website for a step-by-step creation process. Now, keep your trading informed with precision! 🔍

Disclaimer: Trading is like navigating complex markets—challenging and risky. Losses can exceed deposits. Test strategies on a demo account before going live.

Disclaimer: The ideas and strategies presented in this resource are solely those of the author and are intended for informational and educational purposes only. They do not constitute financial advice, and past performance is not indicative of future results. All materials, including but not limited to text, images, files, and any downloadable content, are protected by copyright and intellectual property laws and are the exclusive property of Forex Algo-Trader or its licensors. Reproduction, distribution, modification, or commercial use of these materials without prior written consent from Forex Algo-Trader is strictly prohibited and may result in legal action. Users are advised to exercise extreme caution, perform thorough independent research, and consult with qualified financial professionals before implementing any trading strategies or decisions based on this resource, as trading in financial markets involves significant risk of loss.

Recent Comments

Go to discussion to Comment or View other Comments

No comments yet. Be the first to comment!