Help with EA development PLEASE

 

Hello


//+------------------------------------------------------------------+
//|                         TelegramCopier_GOLD Only       |
//|                        Copyright 2024,                |
//|                        Email:                   |
//+------------------------------------------------------------------+
#property copyright "Copyright 2024, "
#property link     Telegram  "@Malikusm"
#property version   "1.02"
#property strict
#include <stdlib.mqh>         // Include library for string conversion functions
input string TelegramBotToken = "7749494425:AAG1lHx2ZbFAGd6nWeq9CpCowxoppC9EiUo"; // Telegram Bot Token
input string TelegramChatID   = "-1002286425360";                                  // Telegram Chat ID
input bool UseFixedLotSize    = false;                                             // Use fixed lot size or risk-based
input double FixedLotSize1    = 0.1;                                               // Fixed lot size for the first trade
input double FixedLotSize2    = 0.05;                                              // Fixed lot size for the second trade
input double PercentRisk1     = 1.0;                                               // Percentage of account to risk on the first trade
input double PercentRisk2     = 0.5;                                               // Percentage of account to risk on the second trade
input int TimerPeriod         = 10;                                                // Timer set to check for updates every 10 seconds
input bool UseFixedSLTP       = false;                                             // Option to use fixed SL and TP
input double FixedSL          = 50;                                                // Fixed Stop Loss in pips
input double FixedTP          = 100;                                               // Fixed Take Profit in pips
char result[4096];                                                                  // Buffer for WebRequest results
string resultHeaders;                                                               // Buffer for WebRequest headers
//+------------------------------------------------------------------+
// OnInit function to initialize the EA
int OnInit()
{
    EventSetTimer(TimerPeriod); // Set timer for periodic execution
    Print("EA Initialized Successfully");
    return INIT_SUCCEEDED;
}
//+------------------------------------------------------------------+
// OnDeinit function to clean up when the EA is removed
void OnDeinit(const int reason)
{
    EventKillTimer();
    Print("EA Deinitialized");
}
//+------------------------------------------------------------------+
// Custom function to get updates from Telegram via WebRequest
string GetTelegramUpdates() 
{
    char data[1];   // Minimal data array since no data is sent in GET
    string fullURL = "http://127.0.0.1:5000/get_signal";
    int res = WebRequest(
        "GET",                   // HTTP method
        fullURL,                 // URL to request
        "",                      // Cookie placeholder (null)
        "",                      // Referer placeholder (null)
        10000,                   // Timeout in milliseconds
        data,                    // Data (empty for GET requests)
        0,                       // dataSize is 0 because we are not sending any data
        result,                  // Buffer for response data
        resultHeaders            // Buffer for response headers
    );
    if (res > 0) {
        string response = CharArrayToString(result, 0, res);
        Print("Received Signal from Server: ", response);
        return response;
    } else {
        int errorCode = GetLastError();
        Print("Failed to get updates from Local Server, Error Code: ", res, ", GetLastError Code: ", errorCode, ", Full URL: ", fullURL, ", Headers: ", resultHeaders);
        return "";
    }
}
//+------------------------------------------------------------------+
// OnTimer function to periodically check and process messages
void OnTimer()
{
    string updates = GetTelegramUpdates();
    if (StringLen(updates) > 0) {
        ProcessTelegramSignals(updates);
    }
}
//+------------------------------------------------------------------+
// Function to process Telegram signals
void ProcessTelegramSignals(string message) {
    // Here, you'd parse the actual message for trade commands
    if(StringFind(message, "GOLD SELL") >= 0) {
        double sellPrice = ExtractPriceFromMessage(message, "GOLD SELL @");
        double sl = ExtractPriceFromMessage(message, "SL @");
        double tp = ExtractPriceFromMessage(message, "TP @");
        if (UseFixedSLTP) {
            sl = sellPrice + FixedSL * Point;
            tp = sellPrice - FixedTP * Point;
        }
        // Place trade
        if(UseFixedLotSize) {
            PlaceSellOrder("GOLD", sellPrice, FixedLotSize1, sl, tp);
        } else {
            double lotSize = CalculateLotSize(sellPrice, sl, PercentRisk1);
            PlaceSellOrder("GOLD", sellPrice, lotSize, sl, tp);
        }
        Print("Sell order placed for GOLD at ", sellPrice);
    }
    // Add similar blocks for BUY orders and other instruments
}
//+------------------------------------------------------------------+
// Helper function to extract price from message based on a given prefix
double ExtractPriceFromMessage(string message, string prefix) {
    int start = StringFind(message, prefix);
    if(start >= 0) {
        start += StringLen(prefix);
        int end = StringFind(message, "\n", start);
        if (end < 0) end = StringLen(message); // Handle case where there is no newline
        string priceStr = StringSubstr(message, start, end-start);
        return StrToDouble(priceStr);
    }
    return 0;
}
//+------------------------------------------------------------------+
// Helper function to calculate lot size based on risk percentage
double CalculateLotSize(double entryPrice, double stopLoss, double riskPercent) {
    double riskAmount = AccountBalance() * riskPercent / 100.0;
    double pipValue = MarketInfo(Symbol(), MODE_TICKVALUE);
    double stopLossPips = MathAbs(entryPrice - stopLoss) / Point;
    double lotSize = riskAmount / (stopLossPips * pipValue);
    return NormalizeDouble(lotSize, 2);
}
//+------------------------------------------------------------------+
// Helper function to place a sell order
void PlaceSellOrder(string symbol, double price, double lotSize, double sl, double tp) {
    double stopLoss = UseFixedSLTP ? price - FixedSL * Point : sl;
    double takeProfit = UseFixedSLTP ? price - FixedTP * Point : tp;
    int ticket = OrderSend(symbol, OP_SELL, lotSize, price, 3, stopLoss, takeProfit, "Telegram Signal Sell", 0, 0, Red);
    if (ticket < 0) {
        Print("Error placing sell order: ", GetLastError());
    } else {
        Print("Sell order placed successfully, Ticket: ", ticket);
    }
}
//+------------------------------------------------------------------+



I am trying to compile an EA that can execute 2 trades at same time as per the format;

p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px 'Helvetica Neue'; color: #000000} p.p2 {margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px 'Helvetica Neue'; color: #000000; min-height: 15.0px}

GOLD SELL @ 2755


💵SECOND SELL LIMIT @ 2761


SL @ 2766

TP @ 2745


🛡FOLLOW MONEY MANAGEMENT


I have used ;

  1. http://127.0.0.1:5000/get_signal OR. http://localhost:5000/get_signal (Webrequest Using a local Host server)
  2. https://smee.io/OFSJrd4xSajjiy1t


The functionality was tested, and telegram to the server have been working fine, but not able to execute on MT4. Appreciate if someone can help

I have tried mutiple approaches but I have failed. 

Getting this error on MT4 logs;

2024.11.01 19:23:13.272 TelegramCopierEA_Custom_XAU 1.6 XAUUSD,H1: Failed to get updates from Local Server, Error Code: -1, GetLastError Code: 4051, Full URL: http://127.0.0.1:5000/get_signal, Headers: 


 

NOTE1: you need to use designated field (Code Alt+S) to insert your code.

NOTE2: Traders and coders are coding for free:

  • if it is interesting for them personally, or
  • if it is interesting for many members of this forum.

Freelance section of the forum should be used in most of the cases.

Trading applications for MetaTrader 5 to order
Trading applications for MetaTrader 5 to order
  • 2024.11.01
  • www.mql5.com
The largest freelance service with MQL5 application developers
 
Your topic has been moved to the section: MQL4 and MetaTrader 4
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 
maybe your error reporting could be better. see example of function "postRequest" at this article here
https://www.mql5.com/en/articles/15750
Creating an MQL5-Telegram Integrated Expert Advisor (Part 5): Sending Commands from Telegram to MQL5 and Receiving Real-Time Responses
Creating an MQL5-Telegram Integrated Expert Advisor (Part 5): Sending Commands from Telegram to MQL5 and Receiving Real-Time Responses
  • www.mql5.com
In this article, we create several classes to facilitate real-time communication between MQL5 and Telegram. We focus on retrieving commands from Telegram, decoding and interpreting them, and sending appropriate responses back. By the end, we ensure that these interactions are effectively tested and operational within the trading environment