Need Help regarding the MT5 Coding

 
Hi, How are you?
I am now coding with my own logic and have faced some problems.
I tried several times, but I am new to this language.
So if someone can help me, I would be really thank you.
// Moving Average Crossover EA for MT5 (MQL5)
// Executes trades based on crossover of 10-period and 100-period MAs

// --- Input Parameters ---
input double LotSize = 0.1;
input int StopLossPoints = 50;
input int StopLossAdjustmentPoints = 20;

// --- Global Variables ---
double maFast, maSlow;
ulong ticket;

// --- Function to Get Moving Averages ---
void CalculateMovingAverages() {
    // Corrected iMA function usage with appropriate parameters
    maFast = iMA(_Symbol, PERIOD_CURRENT, 10, 0, MODE_LWMA, 0);
    maSlow = iMA(_Symbol, PERIOD_CURRENT, 100, 0, MODE_LWMA, 0);
}

// --- Function to Close Existing Trade ---
void CloseExistingTrade() {
    // Iterate through all open positions
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        // Get the ticket for the current position
        ulong positionTicket = PositionGetTicket(i);

        // Select the position by ticket
        if (PositionSelectByTicket(positionTicket)) {
            // Get position details
            long positionType = PositionGetInteger(POSITION_TYPE);
            double volume = PositionGetDouble(POSITION_VOLUME);
            double price = (positionType == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
            
            // Close the position
            MqlTradeRequest request;
            MqlTradeResult result;

            request.action = TRADE_ACTION_CLOSE_BY;
            request.symbol = _Symbol;
            request.volume = volume;
            request.position = positionTicket;
            request.price = price;
            request.deviation = 2;
            request.magic = 123456;
            request.comment = "Close Existing Position";
            request.type_filling = ORDER_FILLING_FOK;
            request.type_time = ORDER_TIME_GTC;

            if (OrderSend(request, result)) {
                Print("Position closed successfully");
            } else {
                Print("Error closing position: ", GetLastError());
            }
        }
    }
}

// --- Function to Place Trade ---
void OpenTrade(int direction) {
    CloseExistingTrade();
    
    double price = (direction == ORDER_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_ASK) : SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double stopLoss = (direction == ORDER_TYPE_BUY) ? price - StopLossPoints * _Point : price + StopLossPoints * _Point;
    
    MqlTradeRequest request;
    MqlTradeResult result;
    
    request.action = TRADE_ACTION_DEAL;
    request.symbol = _Symbol;
    request.volume = LotSize;
    request.type = (ENUM_ORDER_TYPE)direction;
    request.price = price;
    request.sl = stopLoss;
    request.tp = 0;
    request.deviation = 2;
    request.magic = 123456;
    request.comment = "MA Crossover EA";
    request.type_filling = ORDER_FILLING_FOK;
    request.type_time = ORDER_TIME_GTC;

    if (OrderSend(request, result)) {
        ticket = result.order;
    }
}

// --- Function to Adjust Stop Loss ---
void AdjustStopLoss() {
    for (int i = PositionsTotal() - 1; i >= 0; i--) {
        if (bool PositionGetInteger(i)) {
            double entryPrice = PositionGetDouble(POSITION_PRICE_OPEN);
            double currentPrice = (PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_BUY) 
                ? SymbolInfoDouble(_Symbol, SYMBOL_BID) 
                : SymbolInfoDouble(_Symbol, SYMBOL_ASK);

            if (PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_BUY && currentPrice >= entryPrice + StopLossAdjustmentPoints * _Point) {
                PositionModify(PositionGetTicket(i), entryPrice, 0);
            } else if (PositionGetInteger(POSITION_TYPE) == ORDER_TYPE_SELL && currentPrice <= entryPrice - StopLossAdjustmentPoints * _Point) {
                PositionModify(PositionGetTicket(i), entryPrice, 0);
            }
        }
    }
}

// --- Main Execution Function ---
void OnTick() {
    CalculateMovingAverages();
    static bool lastTradeBuy = false, lastTradeSell = false;
    
    if (maFast > maSlow && !lastTradeBuy) {
        OpenTrade(ORDER_TYPE_BUY);
        lastTradeBuy = true;
        lastTradeSell = false;
    } else if (maFast < maSlow && !lastTradeSell) {
        OpenTrade(ORDER_TYPE_SELL);
        lastTradeSell = true;
        lastTradeBuy = false;
    }
    AdjustStopLoss();
}
 
james_lee: I am now coding with my own logic and have faced some problems. I tried several times, but I am new to this language.

To better understand how this works, the "Moving Average.mq5" file is a helpful example (You can find it in the Examples folder) especially regarding how to declare the custom moving average handle in the OnInit function. Please also make sure to post this topic in the appropriate section of the forum.

 
Your topic has been moved to the section: Expert Advisors and Automated Trading
Please consider which section is most appropriate — https://www.mql5.com/en/forum/172166/page6#comment_49114893
 
When you use iMA in an EA, you will need to use copybuffer to copy the data into a designated buffer.
It's different to MQL4. Please look at moving average based EAs in the mql5 codebase section.