Need errors to be fixed on my mql5 language mt5 code

Работа завершена

Время выполнения 4 часа
Отзыв от заказчика
very fast and good to work with
Отзыв от исполнителя
Nice working with you, No stress :)

Техническое задание

heres the code (#include <Trade\Trade.mqh>  // Include the CTrade class
CTrade trade;  // Declare an instance of CTrade

// Symbols to trade
string SYMBOLS[] = {"XAUUSDm", "US30m", "GBPUSDm", "USTECm", "EURUSDm"};

// Parameters for 15-minute scalping and integrated strategy
double MIN_LOT_SIZE = 0.01;  // Minimum lot size for most brokers
double TRAILING_STOP_LOSS = 5;      // Trailing stop loss (points)
double RISK_PERCENTAGE = 0.5;        // Risk per trade in percentage (smaller for scalping)
int MA_PERIOD_M5 = 10;              // Moving average period for M15
int MA_PERIOD_D1 = 100;              // Moving average period for D1 (longer-term trend)
int ATR_PERIOD = 5;                  // ATR period for volatility filter
double MIN_ATR_THRESHOLD = 0.0002;   // Minimum ATR value for high volatility (tighter for scalping)
int trade_count = 0;                 // Counter to track the number of trades
datetime last_trade_time = 0;        // Track last trade time for session filtering

// Variables to store the last detected pattern and trend
struct TradeSetup {
    string trend;
    string pattern;
};
TradeSetup last_setup[ArraySize(SYMBOLS)]; // Array to store last setup for each symbol


// Function declarations
double calculate_lot_size(double risk_percentage, double stop_loss_distance);
void log_trade(string symbol, double entry_price, double exit_price, string type);
double adjust_stop_loss(double atr_value);
int execute_trade(string symbol, string type, double lot_size);

// Function to calculate lot size based on risk percentage and stop loss distance
double calculate_lot_size(double risk_percentage, double stop_loss_distance) {
    double account_balance = AccountInfoDouble(ACCOUNT_BALANCE);
    double risk_amount = account_balance * (3 / 100);
    double lot_size = risk_amount / stop_loss_distance;
    return NormalizeDouble(lot_size, 2); // Adjust to the broker's lot size precision
}

// Function to adjust stop loss based on ATR value
double adjust_stop_loss(double atr_value) {
    return atr_value * 1.5; // Adjust this multiplier as needed
}

// Function to log trade details
void log_trade( double entry_price, double exit_price, string type) {
    Print("Trade executed: ", symbol, " Entry: ", entry_price, " Exit: ", exit_price, " Type: ", type);
}

void IntegratedStrategy(double price, double support, double resistance, 
                        double demandZone, double supplyZone,
                        bool isBullishPattern, bool isBearishPattern,
                        bool isBreakout, bool isBreakdown,
                        bool isFalseBreakout, bool isReversal,
                        bool isUptrend, bool isDowntrend,
                        double volume, double rsi)

 //--- Pure Price Action: Reversal at Key Levels
        if (isReversal) {
            // Buying Reversal at Support or Demand Zone
            if (SymbolInfoDouble(symbol, SYMBOL_BID) <= support || SymbolInfoDouble(symbol, SYMBOL_BID) <= demandZone) {
                // Confirmations: Bullish candlestick pattern, volume increase, RSI not overbought
                if (bullishSignal == "bullish_engulfing" && volume > 0 && rsi < 70) {
                    request.action = TRADE_ACTION_DEAL;
                    request.symbol = symbol;
                    request.volume = LOT_SIZE; // You can adjust lot size here
                    request.type = ORDER_TYPE_BUY;
                    request.price = SymbolInfoDouble(symbol, SYMBOL_ASK);
                    request.sl = 3; // Define stop loss (modify as needed)
                    request.tp = 15; // Define take profit (modify as needed)
                    request.deviation = 3;
                    request.comment = "Buy Reversal at Support/Demand";
                    if (!execute_trade(request, result)) {
                    Print("Failed to place Buy order at Supoort/Demand.");
                }
            }

            // Selling Reversal at Resistance or Supply Zone
            if (SymbolInfoDouble(symbol, SYMBOL_BID) >= resistance || SymbolInfoDouble(symbol, SYMBOL_BID) >= supplyZone) {
                // Confirmations: Bearish candlestick pattern, volume increase, RSI overbought
                if (bearishSignal == "bearish_engulfing" && volume > 0 && rsi > 70) {
                    request.action = TRADE_ACTION_DEAL;
                    request.symbol = symbol;
                    request.volume = LOT_SIZE; // You can adjust lot size here
                    request.type = ORDER_TYPE_SELL;
                    request.price = SymbolInfoDouble(symbol, SYMBOL_BID);
                    request.sl = 3; // Define stop loss (modify as needed)
                    request.tp = 15; // Define take profit (modify as needed)
                    request.deviation = 3;
                    request.comment = "Sell Reversal at Resistance/Supply";
                    if (!execute_trade(request, result)) {
                    Print("Failed to place Sell order at Resistance/Supply.");
                }
            }
        }

        //--- Price Action: Breakout or Breakdown
        if (isBreakout && SymbolInfoDouble(symbol, SYMBOL_BID) > resistance) {
            // Buy on confirmed breakout with strong volume
            if (volume > 0 && rsi < 70) {
                request.action = TRADE_ACTION_DEAL;
                request.symbol = symbol;
                request.volume = LOT_SIZE; // You can adjust lot size here
                request.type = ORDER_TYPE_BUY;
                request.price = SymbolInfoDouble(symbol, SYMBOL_ASK);
                request.deviation = 3;
                request.comment = "Buy Breakout";
                if (!execute_trade(request, result)) {
                    Print("Failed to place Buy order at Breakout.");
            }
        }

        if (isBreakdown && SymbolInfoDouble(symbol, SYMBOL_BID) < support) {
            // Sell on confirmed breakdown with strong volume
            if (volume > 0 && rsi > 70) {
                request.action = TRADE_ACTION_DEAL;
                request.symbol = symbol;
                request.volume = LOT_SIZE; // You can adjust lot size here
                request.type = ORDER_TYPE_SELL;
                request.price = SymbolInfoDouble(symbol, SYMBOL_BID);
                request.deviation = 3;
                request.comment = "Sell Breakdown";
                if (!execute_trade(request, result)) {
                    Print("Failed to place Sell order at Breakdown.");
            }
        }

        //--- False Breakout: Sell After False Breakout at Resistance or Buy After False Breakout at Support
        if (isFalseBreakout) {
            if (SymbolInfoDouble(symbol, SYMBOL_BID) > resistance && bearishSignal == "bearish_engulfing" && volume > 0 && rsi > 70) {
                request.action = TRADE_ACTION_DEAL;
                request.symbol = symbol;
                request.volume = LOT_SIZE; // You can adjust lot size here
                request.type = ORDER_TYPE_SELL;
                request.price = SymbolInfoDouble(symbol, SYMBOL_BID);
                request.deviation = 3;
                request.comment = "Sell False Breakout at Resistance";
                if (!execute_trade(request, result)) {
                    Print("Failed to place Sell order at Resistance.");
            }

            if (SymbolInfoDouble(symbol, SYMBOL_BID) < support && bullishSignal == "bullish_engulfing" && volume > 0 && rsi < 30) {
                request.action = TRADE_ACTION_DEAL;
                request.symbol = symbol;
                request.volume = LOT_SIZE; // You can adjust lot size here
                request.type = ORDER_TYPE_BUY;
                request.price = SymbolInfoDouble(symbol, SYMBOL_ASK);
                request.deviation = 3;
                request.comment = "Buy False Breakout at Support";
                if (!execute_trade(request, result)) {
                    Print("Failed to place Buy order at Support.");
            }
        }

        //--- Trend Continuation: Buy in Uptrend at Demand Zone or Support, Sell in Downtrend at Supply Zone or Resistance
        if (isUptrend) {
            if (SymbolInfoDouble(symbol, SYMBOL_BID) <= demandZone || SymbolInfoDouble(symbol, SYMBOL_BID) <= support) {
                if (bullishSignal == "bullish_engulfing" && volume > 0 && rsi < 70) {
                    request.action = TRADE_ACTION_DEAL;
                    request.symbol = symbol;
                    request.volume = LOT_SIZE; // You can adjust lot size here
                    request.type = ORDER_TYPE_BUY;
                    request.price = SymbolInfoDouble(symbol, SYMBOL_ASK);
                    request.deviation = 3;
                    request.comment = "Buy in Uptrend at Demand/Support";
                    if (!execute_trade(request, result)) {
                    Print("Failed to place Buy order at Demand/Support.");
                }
            }
        }

        if (isDowntrend) {
            if (SymbolInfoDouble(symbol, SYMBOL_BID) >= supplyZone || SymbolInfoDouble(symbol, SYMBOL_BID) >= resistance) {
                if (bearishSignal == "bearish_engulfing" && volume > 0 && rsi > 70) {
                    request.action = TRADE_ACTION_DEAL;
                    request.symbol = symbol;
                    request.volume = LOT_SIZE; // You can adjust lot size here
                    request.type = ORDER_TYPE_SELL;
                    request.price = SymbolInfoDouble(symbol, SYMBOL_BID);
                    request.deviation = 3;
                    request.comment = "Sell in Downtrend at Supply/Resistance";
                    if (!execute_trade(request, result)) {
                    Print("Failed to place Sell order at Supply/Resistance.");
                }
            }
        }
    }
}

//--- Function to execute trade with error checking
bool execute_trade(MqlTradeRequest &request, MqlTradeResult &result) {
    if (!OrderSend(request, result)) {
        Print("OrderSend failed with error ", GetLastError());
        return false;
    }
    if (result.retcode != TRADE_RETCODE_DONE) {
        Print("OrderSend failed, return code: ", result.retcode);
        return false;
    }
    Print("Order placed successfully with ticket ", result.order);
    return true;
}

//--- Event handler
void OnTick() {
    strategy_execution(); // Execute strategy on every tick
}
 
// Trailing stop-loss function
void apply_trailing_stop(int ticket, double trail_distance) {
    double current_price = SymbolInfoDouble(Symbol(), SYMBOL_BID);
    double stop_loss = PositionGetDouble(POSITION_SL);

    if (PositionSelectByTicket(ticket) && current_price - trail_distance > stop_loss) {
        MqlTradeRequest request;
        MqlTradeResult result;
        ZeroMemory(request);
        request.action = TRADE_ACTION_SLTP;
        request.position = ticket;
        request.sl = current_price - trail_distance;

        if (!OrderSend(request, result)) {
            Print("Trailing stop modification failed with error ", GetLastError());
        } else if (result.retcode != TRADE_RETCODE_DONE) {
            Print("Trailing stop modification failed, return code: ", result.retcode);
        } else {
            Print("Trailing stop updated successfully for ticket ", ticket);
        }
    }
}

 
// Moving average calculation for trend detection
double calculate_moving_average(string symbol, int period, int timeframe)
{
   double ma[];
   if (CopyBuffer(iMA(symbol, PERIOD_M15, period, 0, MODE_SMA, PRICE_CLOSE), 0, 0, 1, ma) > 0)
      return ma[0];
   return 0;
}

// ATR calculation for volatility filter
double calculate_atr(string symbol, int timeframe, int period)
{
   double atr[];
   if (CopyBuffer(iATR(symbol, PERIOD_M15, period), 0, 0, 1, atr) > 0)
      return atr[0];
   return 0;
}

// Detect trend based on 15-minute and daily charts
string detect_trend(string symbol)
{
   // Calculate moving averages
   double ma_m15 = calculate_moving_average(symbol, MA_PERIOD_M15, PERIOD_M15);
   double ma_d1 = calculate_moving_average(symbol, MA_PERIOD_D1, PERIOD_D1);

   // Retrieve the current price
   double price = iClose(symbol, PERIOD_M15, 0);  // Using M15 period

   // Determine trend based on the price and moving averages
   if (price > ma_m15 && price > ma_d1)
      return "uptrend";
   else if (price < ma_m15 && price < ma_d1)
      return "downtrend";

   return "";  // No clear trend
}


        // Calculate ATR and stop loss distance
        double atr_value = calculate_atr(symbol, PERIOD_M15, atr_period);
        double stop_loss_distance = adjust_stop_loss(atr_value);
        double lot_size = calculate_lot_size(risk_percentage, stop_loss_distance);


// ATR Volatility filter for M15
bool is_volatile(string symbol)
{
   double atr_value = calculate_atr(symbol, PERIOD_M15, ATR_PERIOD);
   return (atr_value >= MIN_ATR_THRESHOLD);
}

// Candlestick pattern detection (e.g., engulfing pattern)
string detect_bullish_engulfing(double &open[], double &close[])
{
   if (close[1] < open[1] && close[0] > open[0] && close[0] > open[1] && open[0] < close[1])
      return "bullish_engulfing";
   return "";
}

string detect_bearish_engulfing(double &open[], double &close[])
{
   if (close[1] > open[1] && close[0] < open[0] && close[0] < open[1] && open[0] > close[1])
      return "bearish_engulfing";
   return "";
}

// Fetch data function
bool get_data(string symbol, int timeframe, int bars, double &high[], double &low[], double &close[], double &open[])
{
   MqlRates rates[];  // Declare an array of MqlRates structures

   // Use CopyRates to fetch the data
   int copied = CopyRates(symbol, PERIOD_M15, 0, bars, rates);

   // Check if rates were successfully copied
   if (copied <= 0)
   {
      Print("Failed to copy rates for ", symbol, " on timeframe ", timeframe);
      return false;
   }

   // Resize the arrays based on the number of bars copied
   ArrayResize(high, copied);
   ArrayResize(low, copied);
   ArrayResize(close, copied);
   ArrayResize(open, copied);

   // Ensure the array is accessed from newest to oldest
   ArraySetAsSeries(rates, true);

   // Copy data into the respective arrays
   for (int i = 0; i < copied; i++)
   {
      high[i] = rates[i].high;
      low[i] = rates[i].low;
      close[i] = rates[i].close;
      open[i] = rates[i].open;
   }

   // Return true if data was successfully copied
   return true;
}

int execute_trade(string symbol, string type, double lot_size) {
    MqlTradeRequest request;
    MqlTradeResult result;
    ZeroMemory(request);
    
    request.action = TRADE_ACTION_DEAL;
    request.symbol = symbol;
    request.volume = lot_size;
    request.type = (type == "buy") ? ORDER_TYPE_BUY : ORDER_TYPE_SELL;
    request.price = (type == "buy") ? SymbolInfoDouble(symbol, SYMBOL_ASK) : SymbolInfoDouble(symbol, SYMBOL_BID);
    request.deviation = 3; // Adjust deviation as needed
    request.comment = type + " trade executed";

    if(OrderSend(request, result)) {
        trade_count++; // Increment trade count on successful trade
        return result.handle; // Return the ticket number
    } else {
        Print("Error executing trade: ", GetLastError());
        return -1; // Return -1 on failure
    }
}

// Function to check if the current time is within trading session hours
bool is_trading_session() {
    datetime current_time = TimeCurrent();
    int hour = TimeHour(current_time);
    // Example: London session (9:00 - 17:00) and New York session (15:00 - 22:00)
    return (hour >= 9 && hour < 17) || (hour >= 15 && hour < 22);
}


// Main trading loop
void OnTick() {
    if(trade_count >= 4)  // Stop execution once trade limit is reached
    {
        Print("Trading halted after opening 4 trades.");
        return;
    }

    for(int i = 0; i < ArraySize(SYMBOLS); i++) {
        string symbol = SYMBOLS[i];
        double high[1000], low[1000], close[1000], open[1000];
        int bars = 1000;  // Number of bars to retrieve

        // Retrieve data, handling the case where it fails
        if (!get_data(symbol, PERIOD_M15, bars, high, low, close, open)) {
            Print("Failed to get data for ", symbol);
            continue;  // Skip to the next symbol if data retrieval fails
        }

        
        // Perform trend detection and get candlestick patterns
        string trend = detect_trend(symbol);
        string bullishSignal = detect_bullish_engulfing(open, close);
        string bearishSignal = detect_bearish_engulfing(open, close);

        // Check if there is volatility and if we're within the trading session
        if (!is_volatile(symbol) || !is_trading_session()) {
            Print("Skipping ", symbol, " due to low volatility or out of trading session.");
            continue;
        }

        // Check if the current setup matches the last one
        if (trend == "uptrend" && bullishSignal == "bullish_engulfing") {
            // If the setup is the same as the last one, skip the trade
            if (last_setup[i].trend == trend && last_setup[i].pattern == bullishSignal) {
                Print("Skipping trade for ", symbol, " as the setup is the same as the last trade.");
                continue;
            }

            // Execute a buy trade
            int ticket = execute_trade(symbol, "buy", MIN_LOT_SIZE);
            log_trade(symbol, SymbolInfoDouble(symbol, SYMBOL_ASK), "BUY");
            apply_trailing_stop(ticket, TRAILING_STOP_LOSS);

            // Update last setup
            last_setup[i].trend = trend;
            last_setup[i].pattern = bullishSignal;
        }
        
        else if (trend == "downtrend" && bearishSignal == "bearish_engulfing") {
            // If the setup is the same as the last one, skip the trade
            if (last_setup[i].trend == trend && last_setup[i].pattern == bearishSignal) {
                Print("Skipping trade for ", symbol, " as the setup is the same as the last trade.");
                continue;
            }

            // Execute a sell trade
            int ticket = execute_trade(symbol, "sell", MIN_LOT_SIZE);
            log_trade(symbol, SymbolInfoDouble(symbol, SYMBOL_BID), "SELL");
            apply_trailing_stop(ticket, TRAILING_STOP_LOSS);

            // Update last setup
            last_setup[i].trend = trend;
            last_setup[i].pattern = bearishSignal;
        }
    }
)

Откликнулись

1
Разработчик 1
Оценка
(44)
Проекты
51
59%
Арбитраж
2
100% / 0%
Просрочено
1
2%
Свободен
Опубликовал: 5 примеров
2
Разработчик 2
Оценка
(5)
Проекты
5
0%
Арбитраж
5
0% / 40%
Просрочено
0
Свободен
3
Разработчик 3
Оценка
(51)
Проекты
71
37%
Арбитраж
4
25% / 75%
Просрочено
1
1%
Свободен
Опубликовал: 1 пример
4
Разработчик 4
Оценка
(15)
Проекты
20
35%
Арбитраж
3
0% / 100%
Просрочено
0
Свободен
Опубликовал: 1 пример
5
Разработчик 5
Оценка
Проекты
4
0%
Арбитраж
2
0% / 100%
Просрочено
2
50%
Свободен
6
Разработчик 6
Оценка
(611)
Проекты
711
33%
Арбитраж
45
49% / 42%
Просрочено
14
2%
Работает
7
Разработчик 7
Оценка
(7)
Проекты
8
0%
Арбитраж
4
0% / 100%
Просрочено
3
38%
Свободен
8
Разработчик 8
Оценка
Проекты
0
0%
Арбитраж
3
0% / 100%
Просрочено
0
Работает
9
Разработчик 9
Оценка
(14)
Проекты
15
20%
Арбитраж
1
100% / 0%
Просрочено
0
Свободен
10
Разработчик 10
Оценка
(69)
Проекты
146
34%
Арбитраж
13
8% / 62%
Просрочено
26
18%
Свободен
Опубликовал: 6 примеров
Похожие заказы
Platform MetaTrader 5 (MT5) MQL5 Source Code Required Compatible with Exness MT5 both standard and cent accounts/ICMarket accounts Works on EUR/USD only (initial version) ⸻ Objective Develop a fully automated AI Expert Advisor based on ICT Smart Money Concepts (SMC). The EA must only execute high-probability trades that satisfy all required conditions before opening a position. The EA must avoid overtrading and
Bonjour, je recherche un développeur MQL5 expérimenté pour créer un Expert Advisor pour MetaTrader 5 basé sur une stratégie de trading intégrant des principes de gestion des risques rigoureux et d'intelligence financière. Le robot doit être capable de gérer plusieurs paires de devises et d'optimiser automatiquement les entrées et sorties en fonction de conditions de marché prédéfinies."
MT4/MT5 HFT EA us30 30 - 3000 USD
Hello everybody, I'm looking for an experienced MQL4/MQL5 developer to optimize a High-Frequency Trading (HFT) Expert Advisor for both MT4 and MT5. The EA performs consistently and profitably on demo accounts, but when it is run on Raw and Standard live accounts under what appear to be the same trading conditions, it begins generating losses. I do not have the original source code (.mq4/.mq5); I only have the
I'm looking for an experienced NinjaTrader 8 (C#) developer to build a fully automated futures trading strategy. Please apply only if you have proven experience developing and testing NinjaTrader strategies. Project Overview Develop a fully automated NinjaTrader 8 strategy. Designed for Apex funded and evaluation accounts. Primary instruments: NQ/MNQ Futures (with flexibility to support other futures later). Trading
Hello I need to purchase the source code of an already built profitable mt5 EA with proven track recordIf you have something similar and you are open to selling the source code please apply to this post Please note I am not looking for a dev to build the product from scratch , but need something that is already built and have at least one year worth of track record
I need an Expert Advisor for MT5 on XAUUSD 1min timeframe using SMC concepts. STRATEGY RULES: SELL: 1. Identify previous day High/Low as liquidity 2. Entry only during London-NY session: 15:00-19:00 GMT+3 or broker clock. 3. If price sweeps previous day High and closes back below it 4. Check for bearish 1min FVG below sweep candle 5. Wait for BOS - lower low 6. Entry: Sell/buy at 50% of the FVG 7. SL: 10 pips above
Code An Loss Rate 90-100% MT5 EA , that can blow a 100 USD account a day ,with fixed TP of 3000 points and SL of 3000 For better Rate Calculations get an strategy that can lead to so
Shooter razor 30+ USD
Makes it takes trades by it self buy and sell, it must use the higher signals, also when I press stop it must not pick any trades I want it to take trades automatically when I press start also close by it self
8 cap prop firm passing 30 - 3000 USD
I am looking for an experienced MQL4/MQL5 HFT developer to build or optimize a High-Frequency Trading (HFT) Expert Advisor that can successfully pass proprietary trading firm challenges and perform consistently under live trading conditions with brokers such as 8cap or BlackBull Markets . The developer should have proven experience with HFT execution, ultra-low-latency trading, broker execution, slippage, spreads
I need a professional MT5 Expert Advisor (MQL5) for XAU/USD (Gold) only. Requirements: - Symbol: XAU/USD only - Timeframe: H1 trend, M5 entry - Smart Money Concept (SMC) - Liquidity Sweep - Break of Structure (BOS) - Order Block Retest - Confirmation Candle (Engulfing or Pin Bar) - ATR-based Stop Loss - Risk:Reward = 1:3 (adjustable) - Auto Lot (1% risk) - Break Even - Trailing Stop - Maximum 2 trades per day - One

Информация о проекте

Бюджет
30+ USD
Сроки выполнения
от 1 до 2 дн.