why my EA does not buy and sell automatically?

why my EA does not buy and sell automatically?

Manage alerts

Loading saved threads...

Mohammad dehghani · External communityPost link
External question — Stack Overflow Stack Exchange Author: Mohammad dehghani Original post: https://stackoverflow.com/questions/78141133 License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/ Adaptation: HTML converted to plain text; contact email addresses removed. I have an EA, I want to do a back test on it in MetaTrader5, I select my EA in strategy tester section and adjust the settings, when I hit start the back testing begins and the chart starts moving but my EA does not buy and sell automatically, I don't know what the problem is, would you please help me to fix this code? Here is my code: //+------------------------------------------------------------------+ //| Property | //+------------------------------------------------------------------+ #property strict //+------------------------------------------------------------------+ //| Global variables | //+------------------------------------------------------------------+ input int MA_Period = 50; // Period for the moving average input double Risk_Percentage = 1.5; // Adjusted risk percentage per trade input double Stop_Loss = 100.0; // Initial stop loss in points input double Take_Profit = 200.0; // Take profit level in points double LotSize; // Position size based on risk int Digits; // Number of decimal places for the symbol double AccountBalance = 10000.0; // Account balance in USD //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { Digits = int(SymbolInfoInteger(_Symbol, SYMBOL_DIGITS)); // Get the number of decimal places for the symbol LotSize = CalculatePositionSize(); // Calculate initial lot size Print("Expert Advisor initialized successfully."); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { Print("Expert Advisor deinitialized successfully."); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { double closePrice[]; // Declare 'closePrice' as an array if (Bars(_Symbol, 0) < MA_Period + 2) // Check if there is enough historical data return; if (!CopyClose(_Symbol, 0, 1, 1, closePrice)) { Print("Error copying Close price: ", GetLastError()); return; } double ma = iMA(_Symbol, 0, MA_Period, 0, MODE_SMA, PRICE_CLOSE); if (closePrice[1] < ma && closePrice[0] > ma && closePrice[1] < closePrice[0] - 10) // Add condition to check price trend and other sophisticated entry conditions { MqlTradeRequest request; request.action = TRADE_ACTION_DEAL; request.magic = 123456; request.symbol = _Symbol; request.volume = LotSize; // Use calculated lot size request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK); request.type = ORDER_TYPE_BUY; request.type_filling = ORDER_FILLING_FOK; double Point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); // Define Point request.tp = NormalizeDouble(closePrice[0] + CalculateTakeProfit() * Point, Digits); // Set dynamic take profit level request.sl = NormalizeDouble(closePrice[0] - CalculateStopLoss() * Point, Digits); // Set dynamic stop loss level MqlTradeResult result; if (!OrderSend(request, result)) { Print("Buy OrderSend error: ", GetLastError()); return; } } else if (closePrice[1] > ma && closePrice[0] < ma && closePrice[1] > closePrice[0] + 10) // Add condition to check price trend and other sophisticated entry conditions { MqlTradeRequest request; request.action = TRADE_ACTION_DEAL; request.magic = 123456; request.symbol = _Symbol; request.volume = LotSize; // Use calculated lot size request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID); request.type = ORDER_TYPE_SELL; request.type_filling = ORDER_FILLING_FOK; double Point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); // Define Point request.tp = NormalizeDouble(closePrice[0] - CalculateTakeProfit() * Point, Digits); // Set dynamic take profit level request.sl = NormalizeDouble(closePrice[0] + CalculateStopLoss() * Point, Digits); // Set dynamic stop loss level MqlTradeResult result; if (!OrderSend(request, result)) { Print("Sell OrderSend error: ", GetLastError()); return; } } } //+------------------------------------------------------------------+ //| Calculate dynamic stop loss based on market conditions | //+------------------------------------------------------------------+ double CalculateStopLoss() { double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); return ((AccountBalance * Risk_Percentage / (LotSize * Stop_Loss)) / (tick_value * tick_size)); } //+------------------------------------------------------------------+ //| Calculate dynamic take profit based on market conditions | //+------------------------------------------------------------------+ double CalculateTakeProfit() { double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); return ((AccountBalance * Risk_Percentage / (LotSize * Take_Profit)) / (tick_value * tick_size)); } //+------------------------------------------------------------------+ //| Calculate dynamic position size based on risk percentage and stop loss| //+------------------------------------------------------------------+ double CalculatePositionSize() { double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double riskAmount = AccountBalance * Risk_Percentage; double maxLoss = riskAmount * LotSize * Stop_Loss; return NormalizeDouble(maxLoss / (tick_value * tick_size), 2); }
Quote
Report
Bunyo · External communityPost link
External answer — Stack Overflow Stack Exchange Author: Bunyo Original post: https://stackoverflow.com/a/78141525 License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/ Adaptation: HTML converted to plain text; contact email addresses removed. It looks like you may be using the old ordersend from mq4. Please check the documentation for mq5 here: https://www.mql5.com/en/docs/trading/ordersend Instead of passing the parameters to OrderSend, you will define an MQLTradeRequest and an MQLTradeResult and assign their parameters, and then you will pass them into OrderSend like this: // Calculate the previous values of the Moving Averages double ma8_prev = iMA(Symbol(), 0, 8, 1, MODE_SMA, PRICE_CLOSE); double ma21_prev = iMA(Symbol(), 0, 21, 1, MODE_SMA, PRICE_CLOSE); // Check if MA8 cuts MA21 from below with micrometer precision for Buy signal if (IsCutFromBelow(ma8_current, ma21_current) && IsCutFromAbove(ma8_prev, ma21_prev)) { // Check for additional confirmation before placing a Buy order if (IsAdditionalConfirmationMet()) { double lotSize = CalculateLotSize(); // Calculate dynamic lot size based on account balance and risk // Place a Buy order with precise entry and set Stop Loss/Take Profit double stopLossPrice = Bid - StopLossPips * Point; double takeProfitPrice = Bid + TakeProfitPips * Point; MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result); request.action = TRADE_ACTION_DEAL; request.symbol = Symbol(); request.volume = lotSize; request.price = Bid; request.sl = stopLossPrice; request.tp = takeProfitPrice; request.type = ORDER_TYPE_BUY; request.type_filling = ORDER_FILLING_FOK; if (OrderSend(request, result)) { if (result.retcode == TRADE_RETCODE_DONE) { Print("Buy order placed successfully"); } else { HandleError("Buy", result.retcode); } } else { HandleError("Buy", GetLastError()); } } } // Check if MA8 cuts MA21 from above with micrometer precision for Sell signal if (IsCutFromAbove(ma8_current, ma21_current) && IsCutFromBelow(ma8_prev, ma21_prev)) { // Check for additional confirmation before placing a Sell order if (IsAdditionalConfirmationMet()) { double lotSize = CalculateLotSize(); // Calculate dynamic lot size based on account balance and risk // Place a Sell order with precise entry and set Stop Loss/Take Profit double stopLossPrice = Ask + StopLossPips * Point; double takeProfitPrice = Ask - TakeProfitPips * Point; MqlTradeRequest request; MqlTradeResult result; ZeroMemory(request); ZeroMemory(result); request.action = TRADE_ACTION_DEAL; request.symbol = Symbol(); request.volume = lotSize; request.price = Ask; request.sl = stopLossPrice; request.tp = takeProfitPrice; request.type = ORDER_TYPE_SELL; request.type_filling = ORDER_FILLING_FOK; if (OrderSend(request, result)) { if (result.retcode == TRADE_RETCODE_DONE) { Print("Sell order placed successfully"); } else { HandleError("Sell", result.retcode); } } else { HandleError("Sell", GetLastError()); } } }
Quote
Report
Andres · External communityPost link
External answer — Stack Overflow Stack Exchange Author: Andres Original post: https://stackoverflow.com/a/78301261 License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/ Adaptation: HTML converted to plain text; contact email addresses removed. Also, MQL5 has a class called CTrade to simplify trading tasks. The process works like this: Import the library: #include <Trade/Trade.mqh> Create an instance: CTrade trade; Initialize the instance: trade.SetExpertMagicNumber(...); trade.SetDeviationInPoints(...); trade.SetTypeFilling(ORDER_FILLING_FOK); Use it: if (trade.PositionOpen(symbol, operation, lots, price, sl, tp, comment)) { uint result = trade.ResultRetcode(); if (result == TRADE_RETCODE_DONE) { // Check the result ... } ... } You'll find there are multiple ways to open a trade. The class documentation is very helpful.
Quote
Report

Post Reply

Quoted from Forex.com.bd-Editorial External question — Stack Overflow Stack Exchange Author: Mohammad dehghani Source score (net votes, not local likes): 1 Original post: https://stackoverflow.com/questions/78141133 License: CC BY-SA 4.0 — https://creativecommons.org/licenses/by-sa/4.0/ Adaptation: HTML converted to plain text; contact email addresses removed. I have an EA, I want to do a back test on it in MetaTrader5, I select my EA in strategy tester section and adjust the settings, when I hit start the back testing begins and the chart starts moving but my EA does not buy and sell automatically, I don't know what the problem is, would you please help me to fix this code? Here is my code: //+------------------------------------------------------------------+ //| Property | //+------------------------------------------------------------------+ #property strict //+------------------------------------------------------------------+ //| Global variables | //+------------------------------------------------------------------+ input int MA_Period = 50; // Period for the moving average input double Risk_Percentage = 1.5; // Adjusted risk percentage per trade input double Stop_Loss = 100.0; // Initial stop loss in points input double Take_Profit = 200.0; // Take profit level in points double LotSize; // Position size based on risk int Digits; // Number of decimal places for the symbol double AccountBalance = 10000.0; // Account balance in USD //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { Digits = int(SymbolInfoInteger(_Symbol, SYMBOL_DIGITS)); // Get the number of decimal places for the symbol LotSize = CalculatePositionSize(); // Calculate initial lot size Print("Expert Advisor initialized successfully."); return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { Print("Expert Advisor deinitialized successfully."); } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { double closePrice[]; // Declare 'closePrice' as an array if (Bars(_Symbol, 0) < MA_Period + 2) // Check if there is enough historical data return; if (!CopyClose(_Symbol, 0, 1, 1, closePrice)) { Print("Error copying Close price: ", GetLastError()); return; } double ma = iMA(_Symbol, 0, MA_Period, 0, MODE_SMA, PRICE_CLOSE); if (closePrice[1] < ma && closePrice[0] > ma && closePrice[1] < closePrice[0] - 10) // Add condition to check price trend and other sophisticated entry conditions { MqlTradeRequest request; request.action = TRADE_ACTION_DEAL; request.magic = 123456; request.symbol = _Symbol; request.volume = LotSize; // Use calculated lot size request.price = SymbolInfoDouble(_Symbol, SYMBOL_ASK); request.type = ORDER_TYPE_BUY; request.type_filling = ORDER_FILLING_FOK; double Point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); // Define Point request.tp = NormalizeDouble(closePrice[0] + CalculateTakeProfit() * Point, Digits); // Set dynamic take profit level request.sl = NormalizeDouble(closePrice[0] - CalculateStopLoss() * Point, Digits); // Set dynamic stop loss level MqlTradeResult result; if (!OrderSend(request, result)) { Print("Buy OrderSend error: ", GetLastError()); return; } } else if (closePrice[1] > ma && closePrice[0] < ma && closePrice[1] > closePrice[0] + 10) // Add condition to check price trend and other sophisticated entry conditions { MqlTradeRequest request; request.action = TRADE_ACTION_DEAL; request.magic = 123456; request.symbol = _Symbol; request.volume = LotSize; // Use calculated lot size request.price = SymbolInfoDouble(_Symbol, SYMBOL_BID); request.type = ORDER_TYPE_SELL; request.type_filling = ORDER_FILLING_FOK; double Point = SymbolInfoDouble(_Symbol, SYMBOL_POINT); // Define Point request.tp = NormalizeDouble(closePrice[0] - CalculateTakeProfit() * Point, Digits); // Set dynamic take profit level request.sl = NormalizeDouble(closePrice[0] + CalculateStopLoss() * Point, Digits); // Set dynamic stop loss level MqlTradeResult result; if (!OrderSend(request, result)) { Print("Sell OrderSend error: ", GetLastError()); return; } } } //+------------------------------------------------------------------+ //| Calculate dynamic stop loss based on market conditions | //+------------------------------------------------------------------+ double CalculateStopLoss() { double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); return ((AccountBalance * Risk_Percentage / (LotSize * Stop_Loss)) / (tick_value * tick_size)); } //+------------------------------------------------------------------+ //| Calculate dynamic take profit based on market conditions | //+------------------------------------------------------------------+ double CalculateTakeProfit() { double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); return ((AccountBalance * Risk_Percentage / (LotSize * Take_Profit)) / (tick_value * tick_size)); } //+------------------------------------------------------------------+ //| Calculate dynamic position size based on risk percentage and stop loss| //+------------------------------------------------------------------+ double CalculatePositionSize() { double tick_value = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE); double tick_size = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE); double riskAmount = AccountBalance * Risk_Percentage; double maxLoss = riskAmount * LotSize * Stop_Loss; return NormalizeDouble(maxLoss / (tick_value * tick_size), 2); }

Cancel quote

Checking account access…