code is not working

 
//+------------------------------------------------------------------+
//|                                                          ma.mq5 |
//|                                                        aniruddha |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "aniruddha"
#property link      "https://www.mql5.com"
#property version   "1.00"

#include <Trade/Trade.mqh>
CTrade obj_Trade;

// Input parameters
input double LotSize = 0.01; // Lot size for each trade

int handleFast;
double bufferFast[];
int handleSlow;
double bufferSlow[];

int totalBars = 0;
int magic_No = 1234567;

// Function to calculate ATR
double ATR(int period) {
    double atr = iATR(_Symbol, _Period, period);
    return atr;
}

int OnInit() {
    handleFast = iMA(_Symbol, _Period, 20, 0, MODE_SMA, PRICE_CLOSE);
    if (handleFast == INVALID_HANDLE) return (INIT_FAILED);
    handleSlow = iMA(_Symbol, _Period, 200, 0, MODE_SMA, PRICE_CLOSE);
    if (handleSlow == INVALID_HANDLE) return (INIT_FAILED);
    ArraySetAsSeries(bufferFast, true);
    ArraySetAsSeries(bufferSlow, true);

    obj_Trade.SetExpertMagicNumber(magic_No);
    return (INIT_SUCCEEDED);
}

void OnDeinit(const int reason) {
    IndicatorRelease(handleFast);
    IndicatorRelease(handleSlow);

    ArrayFree(bufferFast);
    ArrayFree(bufferSlow);
}

void OnTick() {
    int bars = iBars(_Symbol, _Period);
    if (totalBars == bars) return;
    totalBars = bars;
    if (!CopyBuffer(handleFast, 0, 0, 3, bufferFast)) {
        Print("problem loading Fast MA");
        return;
    }
    if (!CopyBuffer(handleSlow, 0, 0, 3, bufferSlow)) {
        Print("problem loading Slow MA");
        return;
    }

    // Use data to trade
    double fastMA1 = bufferFast[1];
    double slowMA1 = bufferSlow[1];

    double currentClose = iClose(_Symbol, _Period, 0);
    double prevClose = iClose(_Symbol, _Period, 1);
    double atr = ATR(14);

    // Ensure no positions in the no-trade zone
    if ((currentClose > slowMA1 && currentClose < fastMA1) || 
        (currentClose < slowMA1 && currentClose > fastMA1)) {
        for (int i = PositionsTotal() - 1; i >= 0; i--) {
            ulong ticket = PositionGetTicket(i);
            if (ticket > 0) {
                if (PositionGetString(POSITION_SYMBOL) == _Symbol &&
                    PositionGetInteger(POSITION_MAGIC) == magic_No) {
                    obj_Trade.PositionClose(ticket);
                }
            }
        }
        return; // Exit OnTick if in no-trade zone
    }

    // Buy condition: candle closes above both MAs
    if (prevClose <= fastMA1 || prevClose <= slowMA1) {
        if (currentClose > fastMA1 && currentClose > slowMA1) {
            for (int i = PositionsTotal() - 1; i >= 0; i--) {
                ulong ticket = PositionGetTicket(i);
                if (ticket > 0) {
                    if (PositionGetString(POSITION_SYMBOL) == _Symbol &&
                        PositionGetInteger(POSITION_MAGIC) == magic_No) {
                        if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL) {
                            obj_Trade.PositionClose(ticket);
                        }
                    }
                }
            }

            double ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            double stopLoss = ask - (atr * 2.0);
            double takeProfit = ask + (atr * 2.0);
            obj_Trade.Buy(LotSize, _Symbol, ask, stopLoss, takeProfit);
        }
    }

    // Sell condition: candle closes below both MAs
    if (prevClose >= fastMA1 || prevClose >= slowMA1) {
        if (currentClose < fastMA1 && currentClose < slowMA1) {
            for (int i = PositionsTotal() - 1; i >= 0; i--) {
                ulong ticket = PositionGetTicket(i);
                if (ticket > 0) {
                    if (PositionGetString(POSITION_SYMBOL) == _Symbol &&
                        PositionGetInteger(POSITION_MAGIC) == magic_No) {
                        if (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) {
                            obj_Trade.PositionClose(ticket);
                        }
                    }
                }
            }

            double bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
            double stopLoss = bid + (atr * 2.0);
            double takeProfit = bid - (atr * 2.0);
            obj_Trade.Sell(LotSize, _Symbol, bid, stopLoss, takeProfit);
        }
    }
}

in above code , i try to take trade when candle closes above 20 MA and 200MA with dynamic trailing stop loss and vice versa for selling,

Can anybody help me wrt to correct above code .

Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2024.07.25
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
 
  1. “Doesn't work” is meaningless — just like saying the car doesn't work. Doesn't start, won't go in gear, no electrical, missing the key, flat tires — could be anything, meaningless.

    We can't read your mind nor see your machine; only what you give us on this forum.
         How To Ask Questions The Smart Way. (2004)
              When asking about code


              Be precise and informative about your problem

  2.     double atr = iATR(_Symbol, _Period, period);

    Function does not return a double.

  3.     int bars = iBars(_Symbol, _Period);
        if (totalBars == bars) return;
        totalBars = bars;

    You can't know when a candle closes. Only when a new tick arrives that starts a new bar is the old bar closed, and that tick could arrive almost at the end of a bar's duration.

    For a new bar test, Bars is unreliable (a refresh/reconnect can change number of bars on chart), volume is unreliable (miss ticks), Price is unreliable (duplicate prices and The == operand. - MQL4 programming forum.) Always use time.
              MT4: New candle - MQL4 programming forum #3 (2014)
              MT5: Accessing variables - MQL4 programming forum #3 (2022)

    I disagree with making a new bar function, because it can only be called once per tick (second call returns false). A variable can be tested multiple times.
              Running EA once at the start of each bar - MQL4 programming forum (2011)

  4.             double stopLoss = ask - (atr * 2.0);
                double takeProfit = ask + (atr * 2.0);
    

    You buy at the Ask and sell at the Bid. Pending Buy Stop orders become market orders when hit by the Ask.

    1. Your buy order's TP/SL (or Sell Stop's/Sell Limit's entry) are triggered when the Bid / OrderClosePrice reaches it. Using Ask±n, makes your SL shorter and your TP longer, by the spread. Don't you want the specified amount used in either direction?

    2. Your sell order's TP/SL (or Buy Stop's/Buy Limit's entry) will be triggered when the Ask / OrderClosePrice reaches it. To trigger close at a specific Bid price, add the average spread.
                MODE_SPREAD (Paul) - MQL4 programming forum - Page 3 #25

    3. The charts show Bid prices only. Turn on the Ask line to see how big the spread is (Tools → Options (control+O) → charts → Show ask line.)

      Most brokers with variable spreads widen considerably at end of day (5 PM ET) ± 30 minutes.
      My GBPJPY shows average spread = 26 points, average maximum spread = 134.
      My EURCHF shows average spread = 18 points, average maximum spread = 106.
      (your broker will be similar).
                Is it reasonable to have such a huge spreads (20 PIP spreads) in EURCHF? - General - MQL5 programming forum (2022)

 

Sorry about half information, and thanks for reply.

i am new in programming,

there is one condition in program ,

if (prevClose <= fastMA1 || prevClose <= slowMA1) {
        if (currentClose > fastMA1 && currentClose > slowMA1) {

this condition is used to verify , theoretically its good but while running the its not taking any trades.

or its taking trade anywhere leaving this conditions odd, does this happening because of same condition.