Viewing the resource: Telegram Bot Chart Screenshot System in MQL5

Telegram Bot Chart Screenshot System in MQL5

Allan Munene Mutiiria 2025-06-26 10:32:25 107 Views
This MQL5 EA captures a chart screenshot (1366x768) and sends it to a Telegram chat with a caption, ...

Introduction

Imagine establishing a seamless communication bridge between your trading platform and Telegram, delivering real-time chart visuals with the precision of a skilled operator. The Telegram Bot EA is your advanced communication tool, designed to capture and send chart screenshots from MetaTrader 5 to a specified Telegram chat. Upon initialization ("OnInit()"), it takes a high-resolution screenshot ("ChartScreenShot()", 1366x768 pixels, "SCREENSHOT_FILE_NAME") and sends it to a Telegram chat ("CHAT_ID") using a bot token ("BOT_TOKEN") via a WebRequest ("WebRequest()", "TG_API_URL") with a caption ("CAPTION") detailing the symbol, timeframe, and timestamp. The screenshot is encoded in base64 ("CryptEncode(CRYPT_BASE64)") with a multipart/form-data boundary ("hash", MD5-based), ensuring reliable transmission. No automated trades are executed, focusing solely on communication. This non-trading EA suits traders needing remote chart monitoring or team collaboration, requiring proper Telegram API setup and a stable internet connection for reliability.

This article is crafted with a professional, engaging, and seamless narrative, flowing like a well-calibrated communication bridge, 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 communication project. With vivid examples—like sending EURUSD charts—and a polished tone, we’ll explore how the EA initializes, captures screenshots, prepares data, sends messages, and ensures cleanup. Using a precision communication bridge metaphor, this guide will illuminate the code’s technical rigor, empowering you to connect your trading with confidence. Let’s activate the system and begin this communication expedition!

Strategy Blueprint

Let’s outline the EA’s communication framework, like drafting specifications for a data relay system:

  • Initialization: Sets up Telegram API parameters ("TG_API_URL", "BOT_TOKEN", "CHAT_ID") and initializes screenshot capture ("ChartScreenShot()") in "OnInit()".

  • Screenshot Capture: Takes a 1366x768 chart screenshot ("SCREENSHOT_FILE_NAME") and verifies its existence ("FileIsExist()", "FileOpen()", "FileSize()").

  • Data Preparation: Encodes the screenshot in base64 ("CryptEncode(CRYPT_BASE64)"), creates an MD5-based boundary ("CryptEncode(CRYPT_HASH_MD5)"), and formats multipart/form-data ("ArrayAdd()", "DATA").

  • Message Sending: Sends the screenshot to Telegram with a caption ("CAPTION", symbol/timeframe/timestamp) via "WebRequest()".

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

  • Enhancements: Adding periodic screenshots, trade-based triggers, or error logging could improve functionality. This framework automates chart communication with precision, bridging MetaTrader 5 and Telegram.

Code Implementation

Let’s step into the communication control room and dissect the MQL5 code that powers this Telegram Bot 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, screenshot capture, data preparation, message sending, and cleanup, with detailed explanations and examples—like sending EURUSD charts—to make it accessible for beginners. Each phase will build on the last, crafting a cohesive technical narrative that transforms code into a compelling communication project. Let’s power up the system and begin!

Phase 1: Constructing the Framework—Initialization

We start by building the communication system, setting up Telegram API and screenshot preparation.

//+------------------------------------------------------------------+
//|                                              TELEGRAM BOT 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 BOT_TOKEN = "6830142565:AAGXN3HmD5TMzgRBTgEE8_3hauBRV4v0Lv0";
const string CHAT_ID = "-4142250840";
const string METHOD = "POST";
const int TIMEOUT = 10000;
const string SCREENSHOT_FILE_NAME = "My Screenshot.jpg";
string HEADERS = NULL;
string URL = NULL;
string TEXT_MSG = NULL;
string CAPTION = NULL;
char DATA[];
char RESULT[];
string RESULT_HEADERS = NULL;

int OnInit(){
   if (FileIsExist(SCREENSHOT_FILE_NAME)){
      FileDelete(SCREENSHOT_FILE_NAME);
      ChartRedraw(0);
   }
   ChartScreenShot(0,SCREENSHOT_FILE_NAME,1366,768,ALIGN_RIGHT);
   int wait = 60;
   while(!FileIsExist(SCREENSHOT_FILE_NAME) && --wait > 0){
      Sleep(500);
   }
   if (!FileIsExist(SCREENSHOT_FILE_NAME)){
      Print("SPECIFIED SCREENSHOT DOES NOT EXIST. REVERTING NOW");
      return (INIT_FAILED);
   }

The system begins with the #property header, establishing copyright and contact details, like calibrating a communication bridge’s core. The "OnInit()" function initializes the setup, defining Telegram API constants ("TG_API_URL", "BOT_TOKEN", "CHAT_ID", "METHOD", "TIMEOUT"=10000) and screenshot parameters ("SCREENSHOT_FILE_NAME", "My Screenshot.jpg"). It deletes any existing screenshot ("FileIsExist()", "FileDelete()", "ChartRedraw()") and captures a new 1366x768 screenshot ("ChartScreenShot()", right-aligned). It waits up to 30 seconds ("wait"=60, "Sleep(500)") for the file to appear, exiting with "Print()" and "INIT_FAILED" if it fails. This primes the EA for Telegram communication, like a relay station poised for action. Note: The commented code for sending text messages and chart manipulation is not active but suggests potential enhancements.

Phase 2: Capturing Visuals—Reading Screenshot Data

With the system initialized, we read the screenshot file for transmission, like preparing a visual dispatch.

int OnInit(){
   // ... (screenshot capture)
   int screenshot_Handle = FileOpen(SCREENSHOT_FILE_NAME,FILE_READ|FILE_BIN);
   if (screenshot_Handle == INVALID_HANDLE){
      Print("INVALID SCREENSHOT HANDLE. REVERTING NOW!");
      return (INIT_FAILED);
   }
   int screenshot_Handle_Size = (int)FileSize(screenshot_Handle);
   uchar photoArr_Data[];
   ArrayResize(photoArr_Data,screenshot_Handle_Size);
   FileReadArray(screenshot_Handle,photoArr_Data,0,screenshot_Handle_Size);
   FileClose(screenshot_Handle);

In the visual capture hub, "OnInit()" opens the screenshot file ("FileOpen()", "SCREENSHOT_FILE_NAME", binary read) and checks for validity ("INVALID_HANDLE"), exiting with "Print()" and "INIT_FAILED" if it fails. It reads the file’s size ("FileSize()", "screenshot_Handle_Size") into an array ("photoArr_Data", "FileReadArray()", "ArrayResize()") and closes the handle ("FileClose()"). For example, on EURUSD H1, it reads a 1366x768 screenshot into "photoArr_Data", like preparing a chart image for dispatch.

Phase 3: Preparing Data—Encoding for Telegram

With the screenshot captured, we encode and format data for Telegram, like packaging a transmission.

int OnInit(){
   // ... (file reading)
   uchar base64[];
   uchar key[];
   CryptEncode(CRYPT_BASE64,photoArr_Data,key,base64);
   uchar temporaryArr[1024] = {0};
   ArrayCopy(temporaryArr,base64,0,0,1024);
   uchar md5[];
   CryptEncode(CRYPT_HASH_MD5,temporaryArr,key,md5);
   string hash = NULL;
   int total = ArraySize(md5);
   for (int i=0; i<total; i++){
      hash+=StringFormat("%02X",md5[i]);
   }
   hash = StringSubstr(hash,0,16);
   URL = TG_API_URL+"/bot"+BOT_TOKEN+"/sendPhoto";
   ArrayAdd(DATA,"\r\n");
   ArrayAdd(DATA,"--"+hash+"\r\n");
   ArrayAdd(DATA,"Content-Disposition: form-data; name=\"chat_id\"\r\n");
   ArrayAdd(DATA,"\r\n");
   ArrayAdd(DATA,CHAT_ID);
   ArrayAdd(DATA,"\r\n");
   CAPTION = "Screenshot of symbol: "+Symbol()+
             " ("+EnumToString(ENUM_TIMEFRAMES(Period()))+
             ") @ Time: "+TimeToString(TimeCurrent());
   if (StringLen(CAPTION) > 0){
      ArrayAdd(DATA,"--"+hash+"\r\n");
      ArrayAdd(DATA,"Content-Disposition: form-data; name=\"caption\"\r\n");
      ArrayAdd(DATA,"\r\n");
      ArrayAdd(DATA,CAPTION);
      ArrayAdd(DATA,"\r\n");
   }
   ArrayAdd(DATA,"--"+hash+"\r\n");
   ArrayAdd(DATA,"Content-Disposition: form-data; name=\"photo\"; filename=\"Upload_Screenshot.jpg\"\r\n");
   ArrayAdd(DATA,"\r\n");
   ArrayAdd(DATA,photoArr_Data);
   ArrayAdd(DATA,"\r\n");
   ArrayAdd(DATA,"--"+hash+"--\r\n");
   HEADERS = "Content-Type: multipart/form-data; boundary="+hash+"\r\n";

In the data preparation hub, "OnInit()" encodes the screenshot ("photoArr_Data") into base64 ("CryptEncode(CRYPT_BASE64)", "base64") for HTTP transmission. It copies the first 1024 bytes ("temporaryArr", "ArrayCopy()") and creates an MD5 hash ("CryptEncode(CRYPT_HASH_MD5)", "md5") to form a 16-character boundary ("hash", "StringFormat()", "StringSubstr()"). The Telegram URL ("URL", "TG_API_URL", "BOT_TOKEN", "sendPhoto") is set, and a multipart/form-data payload ("DATA") is built using "ArrayAdd()", including the chat ID ("CHAT_ID"), a caption ("CAPTION", symbol, timeframe, timestamp via "Symbol()", "EnumToString()", "TimeToString()"), and the screenshot ("photoArr_Data"), separated by boundaries ("--"+hash). The HTTP header ("HEADERS") specifies the boundary. For example, on EURUSD H1, it formats a payload with caption “Screenshot of symbol: EURUSD (H1) @ Time: 2025.06.26 01:58:00”, like packaging a chart for transmission.

Phase 4: Sending Messages—Transmitting to Telegram

With data prepared, we send the screenshot to Telegram, like dispatching a critical message.

int OnInit(){
   // ... (data preparation)
   int res_WebReq = WebRequest(METHOD,URL,HEADERS,TIMEOUT,DATA,RESULT,RESULT_HEADERS);
   if (res_WebReq == 200){
      string result = CharArrayToString(RESULT,0,WHOLE_ARRAY,CP_UTF8);
      Print(result);
      Print("SUCCESS SENDING THE SCREENSHOT TO TELEGRAM");
   }
   else{
      if (res_WebReq == -1){
         string result = CharArrayToString(RESULT,0,WHOLE_ARRAY,CP_UTF8);
         Print(result);
         Print("ERROR ",_LastError," IN WEBREQUEST");
         if (_LastError == 4014){
            Print("API URL NOT LISTED. PLEASE ALLOW/ADD IT IN THE TELEGRAM");
            return (INIT_FAILED);
         }
      }
      else {
         string result = CharArrayToString(RESULT,0,WHOLE_ARRAY,CP_UTF8);
         Print(result);
         Print("UNEXPECTED ERROR: ",_LastError);
         return (INIT_FAILED);
      }
   }
   return(INIT_SUCCEEDED);
}

void ArrayAdd(uchar &destinationArr[],const uchar &sourceArr[]){
   int sourceArr_Size = ArraySize(sourceArr);
   if (sourceArr_Size == 0){
      return;
   }
   int destinationArr_Size = ArraySize(destinationArr);
   ArrayResize(destinationArr,destinationArr_Size+sourceArr_Size,500);
   ArrayCopy(destinationArr,sourceArr,destinationArr_Size,0,sourceArr_Size);
}

void ArrayAdd(char &destinationArr[],const string text){
   int length = StringLen(text);
   if (length > 0){
      uchar sourceArr[];
      for (int i=0; i<length; i++){
         ushort character = StringGetCharacter(text,i);
         uchar array[];
         int total = ShortToUTF8(character,array);
         int sourceArr_size = ArraySize(sourceArr);
         ArrayResize(sourceArr,sourceArr_size+total);
         ArrayCopy(sourceArr,array,sourceArr_size,0,total);
      }
      ArrayAdd(destinationArr,sourceArr);
   }
}

int ShortToUTF8(const ushort character,uchar &output[]){
   if (character < 0x80){
      ArrayResize(output,1);
      output[0] = (uchar)character;
      return (1);
   }
   if (character < 0x800){
      ArrayResize(output,2);
      output[0] = (uchar)((character >> 6)|0xC0);
      output[1] = (uchar)((character & 0x3F)|0x80);
      return (2);
   }
   if (character < 0xFFFF){
      if (character >= 0xD800 && character <= 0xDFFF){
         ArrayResize(output,1);
         output[0] = ' ';
         return (1);
      }
      else if (character >= 0xE000 && character <= 0xF8FF){
         int character_int = 0x1000|character;
         ArrayResize(output,4);
         output[0] = (uchar)(0xF0 | (character_int >> 18));
         output[1] = (uchar)(0x80 | ((character_int >> 12) & 0x3F));
         output[2] = (uchar)(0x80 | ((character_int >> 6) & 0x3F));
         output[3] = (uchar)(0x80 | ((character_int & 0x3F)));
         return (4);
      }
      else {
         ArrayResize(output,3);
         output[0] = (uchar)((character >> 12)|0xE0);
         output[1] = (uchar)(((character >> 6)|0x3F)|0x80);
         output[2] = (uchar)(((character)|0x3F)|0x80);
         return (3);
      }
   }
   ArrayResize(output,3);
   output[0] = 0xEF;
   output[1] = 0xBF;
   output[2] = 0xBD;
   return (3);
}

In the message dispatch hub, "OnInit()" sends the payload via "WebRequest()", using "METHOD"=POST, "URL", "HEADERS", "TIMEOUT", and "DATA". On success ("res_WebReq"=200), it logs the response ("CharArrayToString()", "RESULT", UTF-8) and “SUCCESS SENDING THE SCREENSHOT TO TELEGRAM”. On failure ("res_WebReq=-1"), it logs the error ("_LastError"), with a specific message for 4014 (URL not allowed, "INIT_FAILED") or a generic error. The "ArrayAdd()" functions append arrays or UTF-8 encoded strings ("ShortToUTF8()") to "DATA", handling ASCII, 2-byte, 3-byte, emoji, and surrogate pair characters. For example, on EURUSD H1, the screenshot sends to Telegram with a caption, like dispatching a chart to a command center.

Phase 5: 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, leaving the screenshot file on disk, like an active relay station. Adding cleanup would ensure a clean slate:

if (FileIsExist(SCREENSHOT_FILE_NAME)){
   FileDelete(SCREENSHOT_FILE_NAME);
}
ArrayFree(DATA);
ArrayFree(RESULT);

This would delete the screenshot ("FileDelete()") and free arrays ("ArrayFree()", "DATA", "RESULT"), like dismantling a communication system, ready for the next task.

Why This EA is a Communication Triumph

The Telegram Bot EA is a communication triumph, bridging MetaTrader 5 and Telegram with precision, like a master-crafted relay system. Its robust screenshot capture ("ChartScreenShot()") and encoding ("CryptEncode()") ensure reliable transmission, with potential for periodic sends or trade triggers. Picture sending an EURUSD H1 chart to Telegram—strategic brilliance! Beginners will value the simplicity, while experts can enhance its functionality, making it essential for traders needing real-time chart updates.

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 ("BOT_TOKEN") and chat ID ("CHAT_ID") in Telegram (use /getUpdates to find the chat ID).

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

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

  5. Attach the EA to your chart and check Telegram for the screenshot with caption.

  6. Monitor logs (e.g., “SUCCESS SENDING THE SCREENSHOT TO TELEGRAM”) for transmission tracking, like relay diagnostics.

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

Conclusion

We’ve engineered a Telegram Bot Trader that connects trading with Telegram with precision, like a master-crafted communication bridge. 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 trading connectivity. Whether you’re a novice operator or a seasoned market strategist, this EA empowers you to share charts with confidence. Ready to connect? Watch our video guide on the website for a step-by-step creation process. Now, bridge your trading with precision! 🔍

Disclaimer: Trading is like navigating complex markets—challenging and risky. 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!