Error in copying data from MACD buffer: 4806

 
Hello, i would really appreciate if i could get some help with my coding. I getting this message from my journal. I know where it is coming from in my code, but im not should what to change to have it resolve to get the coding pass along.
Below is my full code, along with the exact section where the code is coming from starting at the top. (just listed separately, to view easy) its not finish since i have a few more things to add in but thanks for any input on what i have wrongly setup.

//+------------------------------------------------------------------+
//| Calculate MACD and return histogram value                        |
//+------------------------------------------------------------------+
double CalculateMACDHistogram(const string symbol, ENUM_TIMEFRAMES timeframe, 
                              int fastEMA_period, int slowEMA_period, int signal_period, 
                              double &macdSignalLine) {
    // Initialize variables
    double macdHistogram;
    double macdLineArray[1], signalLineArray[1], histogramLineArray[1];

    // Calculate the MACD line as the difference between two EMAs
    double fastEMA = iMA(symbol, timeframe, fastEMA_period, 0, MODE_EMA, PRICE_CLOSE);
    double slowEMA = iMA(symbol, timeframe, slowEMA_period, 0, MODE_EMA, PRICE_CLOSE);
    macdLineArray[0] = fastEMA - slowEMA;

    // Get handle to the MACD indicator
    int macdHandle = iMACD(symbol, timeframe, fastEMA_period, slowEMA_period, signal_period, PRICE_CLOSE);
    if(macdHandle != INVALID_HANDLE) {
        // Copy the current value of the signal line and histogram to the arrays
        if(CopyBuffer(macdHandle, 1, 0, 1, signalLineArray) <= 0 ||
           CopyBuffer(macdHandle, 2, 0, 1, histogramLineArray) <= 0) {
            Print("Error in copying data from MACD buffer: ", GetLastError());
            return (0.0);
        }
    } else {
        Print("Error in MACD handle: ", GetLastError());
        return (0.0);
    }

    // Calculate the MACD Histogram
    macdHistogram = histogramLineArray[0]; // MACD line - Signal line
    macdSignalLine = signalLineArray[0]; // For output

    return macdHistogram;
}


//Full Code Below:

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>

input double FixedLotSize = 0.5; // User-defined fixed lot size
input double MaxLossPercent = 8.0; // Maximum loss percentage to stop EA
input double MaxProfitPercent = 20.0; // Maximum profit percentage to stop EA

double startingBalance;
bool useSecondaryIndicators = false;
CTrade trade; // Trade object

// Structure to hold count of buy and sell positions
struct PositionCounts {
    int buyCount;
    int sellCount;
};

// Function to count the number of buy and sell positions separately
PositionCounts CountOpenPositions() {
    PositionCounts counts;
    counts.buyCount = 0;
    counts.sellCount = 0;

    for(int i = 0; i < PositionsTotal(); i++) {
        string posSymbol = PositionGetSymbol(i);
        if(posSymbol != _Symbol) continue;

        long positionType = PositionGetInteger(POSITION_TYPE);
        if(positionType == POSITION_TYPE_BUY) {
            counts.buyCount++;
        } else if(positionType == POSITION_TYPE_SELL) {
            counts.sellCount++;
        }
    }
    return counts;
    }
    
    // Calculate EMA
double CalculateEMA(const string symbol, ENUM_TIMEFRAMES timeframe, int period, ENUM_APPLIED_PRICE priceType) {
    return iMA(symbol, timeframe, period, 0, MODE_EMA, priceType);
    }
    
    // Calculate MA
double CalculateMA(const string symbol, ENUM_TIMEFRAMES timeframe, int period, ENUM_APPLIED_PRICE priceType) {
    return iMA(symbol, timeframe, period, 0, MODE_SMA, priceType);
}


//+------------------------------------------------------------------+
//| Calculate MACD and return histogram value                        |
//+------------------------------------------------------------------+
double CalculateMACDHistogram(const string symbol, ENUM_TIMEFRAMES timeframe, 
                              int fastEMA_period, int slowEMA_period, int signal_period, 
                              double &macdSignalLine) {
    // Initialize variables
    double macdHistogram;
    double macdLineArray[1], signalLineArray[1], histogramLineArray[1];

    // Calculate the MACD line as the difference between two EMAs
    double fastEMA = iMA(symbol, timeframe, fastEMA_period, 0, MODE_EMA, PRICE_CLOSE);
    double slowEMA = iMA(symbol, timeframe, slowEMA_period, 0, MODE_EMA, PRICE_CLOSE);
    macdLineArray[0] = fastEMA - slowEMA;

    // Get handle to the MACD indicator
    int macdHandle = iMACD(symbol, timeframe, fastEMA_period, slowEMA_period, signal_period, PRICE_CLOSE);
    if(macdHandle != INVALID_HANDLE) {
        // Copy the current value of the signal line and histogram to the arrays
        if(CopyBuffer(macdHandle, 1, 0, 1, signalLineArray) <= 0 ||
           CopyBuffer(macdHandle, 2, 0, 1, histogramLineArray) <= 0) {
            Print("Error in copying data from MACD buffer: ", GetLastError());
            return (0.0);
        }
    } else {
        Print("Error in MACD handle: ", GetLastError());
        return (0.0);
    }

    // Calculate the MACD Histogram
    macdHistogram = histogramLineArray[0]; // MACD line - Signal line
    macdSignalLine = signalLineArray[0]; // For output

    return macdHistogram;
}



//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit() {
    startingBalance = AccountInfoDouble(ACCOUNT_BALANCE);
    return INIT_SUCCEEDED;
}

//+------------------------------------------------------------------+
//| Check entry conditions function                                  |
//+------------------------------------------------------------------+
int CheckEntryConditions() {
    double currentClose = iClose(_Symbol, PERIOD_M5, 0);
    double currentOpen = iOpen(_Symbol, PERIOD_M5, 0);

    double ema6 = CalculateEMA(_Symbol, PERIOD_M5, 6, PRICE_OPEN);
    double ma6 = CalculateMA(_Symbol, PERIOD_M5, 6, PRICE_OPEN);

    double macdSignalLine;
    double macdHistogram = CalculateMACDHistogram(_Symbol, PERIOD_M5, 8, 10, 12, macdSignalLine);

    // Buy Conditions
    if (currentClose > currentOpen && ema6 > ma6 && macdHistogram > 0.0180) {
        return 1; // Buy Signal
    }
    // Sell Conditions
    else if (currentClose < currentOpen && ema6 < ma6 && macdHistogram < -0.0180) {
        return -1; // Sell Signal
    }

    return 0; // No Signal
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick() {
    // Get current Ask and Bid prices
    double Ask, Bid;
    if(!SymbolInfoDouble(_Symbol, SYMBOL_ASK, Ask) || !SymbolInfoDouble(_Symbol, SYMBOL_BID, Bid)) {
        Print("Error getting price data");
        return;
    }
    
    // Get the current count of buy and sell positions
    PositionCounts currentPositions = CountOpenPositions();
    
    // Account balance control
    double currentBalance = AccountInfoDouble(ACCOUNT_BALANCE);
    if (currentBalance <= startingBalance * (1.0 - MaxLossPercent / 100.0)) {
        Print("Total loss reached");
        ExpertRemove();
        return;
    } else if (currentBalance >= startingBalance * (1.0 + MaxProfitPercent / 100.0)) {
        Print("Total profit reached");
        ExpertRemove();
        return;
    }

// Check for entry conditions
    int tradeSignal = CheckEntryConditions();
    if (tradeSignal == 1) {
        // Buy Signal
        ExecuteTrade(true);
    } else if (tradeSignal == -1) {
        // Sell Signal
        ExecuteTrade(false);
    }

    // Check exit conditions for each open position
    CheckExitConditions();
}
   
//+------------------------------------------------------------------+
//| Execute trade function                                           |
//+------------------------------------------------------------------+
void ExecuteTrade(bool isBuySignal) {
    double Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double Bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    string comment = "My EA Trade"; // Custom comment for the trade

    // Assuming no stop loss and take profit for simplicity
    double stopLoss = 0;
    double takeProfit = 0;

    if (isBuySignal) {
        // Execute Buy Trade
        if (!trade.Buy(FixedLotSize, _Symbol, Ask, stopLoss, takeProfit, comment)) {
            Print("Trade Error: ", GetLastError());
        }
    } else {
        // Execute Sell Trade
        if (!trade.Sell(FixedLotSize, _Symbol, Bid, stopLoss, takeProfit, comment)) {
            Print("Trade Error: ", GetLastError());
        }
    }
}

//+------------------------------------------------------------------+
//| Check exit conditions for each open position                     |
//+------------------------------------------------------------------+
void CheckExitConditions() {
    for (int i = 0; i < PositionsTotal(); i++) {
        ulong positionTicket = PositionGetTicket(i);
        if (PositionSelectByTicket(positionTicket)) {
            double ema6 = CalculateEMA(_Symbol, PERIOD_M5, 6, PRICE_OPEN);
            double ma6 = CalculateMA(_Symbol, PERIOD_M5, 6, PRICE_OPEN);
            ENUM_POSITION_TYPE positionType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);

            // Close Buy Position
            if (positionType == POSITION_TYPE_BUY && ema6 < ma6) {
                trade.PositionClose(positionTicket);
            }
            // Close Sell Position
            else if (positionType == POSITION_TYPE_SELL && ema6 > ma6) {
                trade.PositionClose(positionTicket);
            }
        }
    }
}


//+------------------------------------------------------------------+
//| Trade transaction event handler                                  |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans, const MqlTradeRequest& request, const MqlTradeResult& result) {
    // Update useSecondaryIndicators based on the result of the trade
    // ...
}



 
I just added some checks and also just change the calculated periods to static. added some print statements to see if its not getting enough data some how and all those pass it still giving me that same buffer error code. Im loss on what else to change for this 1. New edition for check listed below.

//+------------------------------------------------------------------+
//| Calculate MACD and return histogram value                        |
//+------------------------------------------------------------------+
double CalculateMACDHistogram(const string symbol, ENUM_TIMEFRAMES timeframe, 
                              double &macdSignalLine) {
    // Initialize variables
    double macdHistogram;
    double macdLineArray[1], signalLineArray[1], histogramLineArray[1];

    // Set static periods for MACD calculation
    int fastEMA_period = 8;
    int slowEMA_period = 10;
    int signal_period = 12;

    int totalBars = Bars(symbol, timeframe);
    if(totalBars < slowEMA_period + signal_period) {
    Print("Not enough data for MACD calculation");
    return (0.0);
    }

    // Calculate the MACD line as the difference between two EMAs
    double fastEMA = iMA(symbol, timeframe, fastEMA_period, 0, MODE_EMA, PRICE_CLOSE);
    double slowEMA = iMA(symbol, timeframe, slowEMA_period, 0, MODE_EMA, PRICE_CLOSE);
    macdLineArray[0] = fastEMA - slowEMA;

    // Get handle to the MACD indicator
    int macdHandle = iMACD(symbol, timeframe, fastEMA_period, slowEMA_period, signal_period, PRICE_CLOSE);
    if(macdHandle != INVALID_HANDLE) {
        // Copy the current value of the signal line and histogram to the arrays
        if(CopyBuffer(macdHandle, 1, 0, 1, signalLineArray) <= 0 ||
           CopyBuffer(macdHandle, 2, 0, 1, histogramLineArray) <= 0) {
            Print("Error in copying data from MACD buffer: ", GetLastError());
            return (0.0);
        }
    } else {
        Print("Error in MACD handle: ", GetLastError());
        return (0.0);
    }

    // Calculate the MACD Histogram
    macdHistogram = histogramLineArray[0]; // MACD line - Signal line
    macdSignalLine = signalLineArray[0]; // For output

    return macdHistogram;
}


//Since i change to static periods i also change down below for the macd section

//+------------------------------------------------------------------+
//| Check entry conditions function                                  |
//+------------------------------------------------------------------+
int CheckEntryConditions() {
    double currentClose = iClose(_Symbol, PERIOD_M5, 0);
    double currentOpen = iOpen(_Symbol, PERIOD_M5, 0);

    double ema6 = CalculateEMA(_Symbol, PERIOD_M5, 6, PRICE_OPEN);
    double ma6 = CalculateMA(_Symbol, PERIOD_M5, 6, PRICE_OPEN);

    double macdSignalLine;
    double macdHistogram = CalculateMACDHistogram(_Symbol, PERIOD_M5, macdSignalLine);

    // Buy Conditions
    if (currentClose > currentOpen && ema6 > ma6 && macdHistogram > 0.0180) {
        return 1; // Buy Signal
    }
    // Sell Conditions
    else if (currentClose < currentOpen && ema6 < ma6 && macdHistogram < -0.0180) {
        return -1; // Sell Signal
    }

    return 0; // No Signal
}
 
Blu3ry #:
I just added some checks and also just change the calculated periods to static. added some print statements to see if its not getting enough data some how and all those pass it still giving me that same buffer error code. Im loss on what else to change for this 1. New edition for check listed below.

First of all, Indicator handles returned from the indicator functions should be integer not double and they should be calculated only once in the OnInit() function.

 
Elvis Wangai Muriithi #:

First of all, Indicator handles returned from the indicator functions should be integer not double and they should be calculated only once in the OnInit() function.

Oh ok, ill go edit and try that and see.
 
In mql 5 you should call the indicators by their handle first and every time you need a data you should copy the indicator handle values to a buffer
And usually it is better to add the indicator handle on the oninit() function 

In global variables add the indicator handle and buffer 

Int maHandle;
Double maBuffer[];

In OnInit()
maHamdle= iMA(……….)
And any time you need a MA value for example on OnTick function read the values from handle and copy the to the buffer 

CopyBuffer(maHandle, buffernumber, bar, maBuffer);

Read the documents for better understanding 
 
It is better to control the handle value and the copy buffer output to find out if they are done properly or an error occurred 
 
Mohammadmahmood Pirayeh #:
In mql 5 you should call the indicators by their handle first and every time you need a data you should copy the indicator handle values to a buffer
And usually it is better to add the indicator handle on the oninit() function 

In global variables add the indicator handle and buffer 

Int maHandle;
Double maBuffer[];

In OnInit()
maHamdle= iMA(……….)
And any time you need a MA value for example on OnTick function read the values from handle and copy the to the buffer 

CopyBuffer(maHandle, buffernumber, bar, maBuffer);

Read the documents for better understanding 
Thanks for your suggestions on structure. i made some changes i think is correct but im no way a pro at this, just self thought and some knowledge from binary.com bot days. If you could look over the changes i made and let me know if there still something im missing that would be very helpful. Ill post the edited sections i made everything else stated the same. If im really far off from what it should be to resolve this "Error in copying data from MACD buffer: 4806" im getting after testing if the EA enter trades, please provide me with some guidance or a link to most relevant documentation for copy buffers and handles.


//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>

input double FixedLotSize = 0.5; // User-defined fixed lot size
input double MaxLossPercent = 8.0; // Maximum loss percentage to stop EA
input double MaxProfitPercent = 20.0; // Maximum profit percentage to stop EA

double startingBalance;
bool useSecondaryIndicators = false;
int macdHandle;
double macdSignalLineBuffer[];
double macdHistogramBuffer[];

CTrade trade; // Trade object


//+------------------------------------------------------------------+
//| Calculate MACD and return histogram value                        |
//+------------------------------------------------------------------+
double CalculateMACDHistogram(const string symbol, ENUM_TIMEFRAMES timeframe, 
                              double &macdSignalLine) {
    // Initialize variables
    double macdHistogram;
    double macdLineArray[1], signalLineArray[1], histogramLineArray[1];

    // Set static periods for MACD calculation
    int fastEMA_period = 8;
    int slowEMA_period = 10;
    int signal_period = 12;

    int totalBars = Bars(symbol, timeframe);
    if(totalBars < slowEMA_period + signal_period) {
        Print("Not enough data for MACD calculation");
        return (0.0);
    }

    // Use the global MACD handle, no need to redeclare it
    // macdHandle is already initialized in OnInit()

    // Copy the current value of the signal line and histogram to the arrays
    if(CopyBuffer(macdHandle, 1, 0, 1, signalLineArray) <= 0 ||
       CopyBuffer(macdHandle, 2, 0, 1, histogramLineArray) <= 0) {
        Print("Error in copying data from MACD buffer: ", GetLastError());
        return (0.0);
    }

    // Calculate the MACD Histogram
    macdHistogram = histogramLineArray[0]; // MACD line - Signal line
    macdSignalLine = signalLineArray[0]; // For output

    return macdHistogram;
}


 
Blu3ry #:
//+------------------------------------------------------------------+ //| Expert initialization function                                   | //+------------------------------------------------------------------+ #include <Trade\Trade.mqh> input double FixedLotSize = 0.5; // User-defined fixed lot size input double MaxLossPercent = 8.0; // Maximum loss percentage to stop EA input double MaxProfitPercent = 20.0; // Maximum profit percentage to stop EA double startingBalance; bool useSecondaryIndicators = false; int macdHandle; double macdSignalLineBuffer[]; double macdHistogramBuffer[]; CTrade trade; // Trade object //+------------------------------------------------------------------+ //| Calculate MACD and return histogram value                        | //+------------------------------------------------------------------+ double CalculateMACDHistogram(const string symbol, ENUM_TIMEFRAMES timeframe,                               double &macdSignalLine) {     // Initialize variables     double macdHistogram;     double macdLineArray[1], signalLineArray[1], histogramLineArray[1];     // Set static periods for MACD calculation     int fastEMA_period = 8;     int slowEMA_period = 10;     int signal_period = 12;     int totalBars = Bars(symbol, timeframe);     if(totalBars < slowEMA_period + signal_period) {         Print("Not enough data for MACD calculation");         return (0.0);     }     // Use the global MACD handle, no need to redeclare it     // macdHandle is already initialized in OnInit()     // Copy the current value of the signal line and histogram to the arrays     if(CopyBuffer(macdHandle, 1, 0, 1, signalLineArray) <= 0 ||        CopyBuffer(macdHandle, 2, 0, 1, histogramLineArray) <= 0) {         Print("Error in copying data from MACD buffer: ", GetLastError());         return (0.0);     }     // Calculate the MACD Histogram     macdHistogram = histogramLineArray[0]; // MACD line - Signal line     macdSignalLine = signalLineArray[0]; // For output     return macdHistogram; }
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>

input double FixedLotSize = 0.5; // User-defined fixed lot size
input double MaxLossPercent = 8.0; // Maximum loss percentage to stop EA
input double MaxProfitPercent = 20.0; // Maximum profit percentage to stop EA

double startingBalance;
bool useSecondaryIndicators = false;
int macdHandle;
double macdSignalLineBuffer[];
double macdHistogramBuffer[];

CTrade trade; // Trade object


//+------------------------------------------------------------------+
//| Calculate MACD and return histogram value                        |
//+------------------------------------------------------------------+
double CalculateMACDHistogram(const string symbol, ENUM_TIMEFRAMES timeframe, 
                              double &macdSignalLine) {
    // Initialize variables
    double macdHistogram;
    double macdLineArray[1], signalLineArray[1], histogramLineArray[1];

    // Set static periods for MACD calculation
    int fastEMA_period = 8;
    int slowEMA_period = 10;
    int signal_period = 12;

    int totalBars = Bars(symbol, timeframe);
    if(totalBars < slowEMA_period + signal_period) {
        Print("Not enough data for MACD calculation");
        return (0.0);
    }

    // Use the global MACD handle, no need to redeclare it
    // macdHandle is already initialized in OnInit()

    // Copy the current value of the signal line and histogram to the arrays
    if(CopyBuffer(macdHandle, 1, 0, 1, signalLineArray) <= 0 ||
       CopyBuffer(macdHandle, 2, 0, 1, histogramLineArray) <= 0) {
        Print("Error in copying data from MACD buffer: ", GetLastError());
        return (0.0);
    }

    // Calculate the MACD Histogram
    macdHistogram = histogramLineArray[0]; // MACD line - Signal line
    macdSignalLine = signalLineArray[0]; // For output

    return macdHistogram;
}

Arrays used for CopyBuffer() are automatically resized with the count(amount of data you are copying) so they should be static. histogramLineArray[Nothing here]

I think that's why you are getting error in copying.

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>

input double FixedLotSize = 0.5; // User-defined fixed lot size
input double MaxLossPercent = 8.0; // Maximum loss percentage to stop EA
input double MaxProfitPercent = 20.0; // Maximum profit percentage to stop EA

double startingBalance;
bool useSecondaryIndicators = false;
int macdHandle;
double macdSignalLineBuffer[];
double macdHistogramBuffer[];

CTrade trade; // Trade object


//+------------------------------------------------------------------+
//| Calculate MACD and return histogram value                        |
//+------------------------------------------------------------------+
double CalculateMACDHistogram(const string symbol, ENUM_TIMEFRAMES timeframe, 
                              double &macdSignalLine) {
    // Initialize variables
    double signalLineArray[], histogramLineArray[];

    // Set static periods for MACD calculation
    int fastEMA_period = 8;
    int slowEMA_period = 10;
    int signal_period = 12;

    int totalBars = Bars(symbol, timeframe);
    if(totalBars < slowEMA_period + signal_period) {
        Print("Not enough data for MACD calculation");
        return (0.0);
    }

    // Use the global MACD handle, no need to redeclare it
    // macdHandle is already initialized in OnInit()

    // Copy the current value of the signal line and histogram to the arrays
    if(CopyBuffer(macdHandle, 0, 0, 1,histogramLineArray) <= 0 ||
       CopyBuffer(macdHandle, 1, 0, 1, signalLineArray) <= 0) {
        Print("Error in copying data from MACD buffer: ", GetLastError());
        return (0.0);
    }

    // Calculate the MACD Histogram
    macdHistogram = histogramLineArray[0]; // MACD line - Signal line
    macdSignalLine = signalLineArray[0]; // For output

    return macdHistogram;
}

I have also made some changes in you code on how you defined the MACD Buffers. 0 = MAIN_LINE (Histogram)and 1 = SIGNAL_LINE

I don't know exactly what you are trying to get from the MACD but you don't necessarily need to create a function for getting MACD values

 
Elvis Wangai Muriithi #:

Arrays used for CopyBuffer() are automatically resized with the count(amount of data you are copying) so they should be static. histogramLineArray[Nothing here]

I think that's why you are getting error in copying.

I have also made some changes in you code on how you defined the MACD Buffers. 0 = MAIN_LINE (Histogram)and 1 = SIGNAL_LINE

I don't know exactly what you are trying to get from the MACD but you don't necessarily need to create a function for getting MACD values

Thanks for the extra help really appreciate it. To be honest im lost on this 1 i try up to 3 different ways and still nothing same exact error code for 4806 for the buffer issue. My most recent change was below and it still a issue. If you or any one could provide the coding for receiving the current market histogram value of the MACD, that would be great. thats all i need, to get the value of the histogram. and then have my trade execution include the other moving average criteria and also to enter the trade if the MACD value is over the 0 line by 0.0180 for buys and -0.0180 for sells. Mainly being ran on the GU pair.
Most recent change was this below:

//+------------------------------------------------------------------+
//| Calculate MACD and return histogram value                        |
//+------------------------------------------------------------------+
double CalculateMACDHistogram(const string symbol, ENUM_TIMEFRAMES timeframe, 
                              double &macdSignalLine) {
    // Initialize variables
    double macdHistogram;
    double macdLineArray[], signalLineArray[];

    // Set static periods for MACD calculation
    int fastEMA_period = 8;
    int slowEMA_period = 10;
    int signal_period = 12;

    int totalBars = Bars(symbol, timeframe);
    if(totalBars < slowEMA_period + signal_period) {
        Print("Not enough data for MACD calculation");
        return (0.0);
    }

    // Use the global MACD handle, no need to redeclare it
    // macdHandle is already initialized in OnInit()

    // Copy the current values of the MACD line and signal line to the arrays
    if(CopyBuffer(macdHandle, 0, 0, 1, macdLineArray) <= 0 ||
       CopyBuffer(macdHandle, 1, 0, 1, signalLineArray) <= 0) {
        Print("Error in copying data from MACD buffer: ", GetLastError());
        return (0.0);
    }

    // Manually calculate the MACD Histogram as the difference between MACD line and Signal line
    macdHistogram = macdLineArray[0] - signalLineArray[0];
    macdSignalLine = signalLineArray[0]; // For output

    return macdHistogram;
}
But i still get the error: Error in copying data from MACD buffer: 4806 from my journal.... (its really just error 4806) the words are just printed info.
 
Blu3ry #:
    double macdLineArray[], signalLineArray[];
    double macdLineArray[], signalLineArray[];

i think that this line needs to be on global

 
Revo Trades #:

i think that this line needs to be on global

Hey thanks for your input on the issue here. I did find another article here https://www.mql5.com/en/forum/322393 and this after i made the suggested changes and i no longer get the error code. So i finally get no error from my journal when using the strategy tester. However, the strategy tester is not entering any trades now. So im gonna have to review my entry conditions and see whats blocking the trades. Gonna post the current code of how i have things structured now.
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>

input double FixedLotSize = 0.5; // User-defined fixed lot size
input double MaxLossPercent = 8.0; // Maximum loss percentage to stop EA
input double MaxProfitPercent = 20.0; // Maximum profit percentage to stop EA

double startingBalance;
bool useSecondaryIndicators = false;
int macdHandle; // Handle for the MACD indicator
double macdLineBuffer[]; // Buffer for MACD line
double macdSignalLineBuffer[]; // Buffer for MACD signal line

CTrade trade; // Trade object

// Structure to hold count of buy and sell positions
struct PositionCounts {
    int buyCount;
    int sellCount;
};

// Function to count the number of buy and sell positions separately
PositionCounts CountOpenPositions() {
    PositionCounts counts;
    counts.buyCount = 0;
    counts.sellCount = 0;

    for(int i = 0; i < PositionsTotal(); i++) {
        string posSymbol = PositionGetSymbol(i);
        if(posSymbol != _Symbol) continue;

        long positionType = PositionGetInteger(POSITION_TYPE);
        if(positionType == POSITION_TYPE_BUY) {
            counts.buyCount++;
        } else if(positionType == POSITION_TYPE_SELL) {
            counts.sellCount++;
        }
    }
    return counts;
    }
    
    // Calculate EMA
double CalculateEMA(const string symbol, ENUM_TIMEFRAMES timeframe, int period, ENUM_APPLIED_PRICE priceType) {
    return iMA(symbol, timeframe, period, 0, MODE_EMA, priceType);
    }
    
    // Calculate MA
double CalculateMA(const string symbol, ENUM_TIMEFRAMES timeframe, int period, ENUM_APPLIED_PRICE priceType) {
    return iMA(symbol, timeframe, period, 0, MODE_SMA, priceType);
}


//+------------------------------------------------------------------+
//| Calculate MACD and return histogram value                        |
//+------------------------------------------------------------------+
double CalculateMACDHistogram(const string symbol, ENUM_TIMEFRAMES timeframe, 
                              double &macdSignalLine) {
    // Initialize variables
    double macdHistogram;
    double macdLineArray[], signalLineArray[];

    // Set static periods for MACD calculation
    int fastEMA_period = 8;
    int slowEMA_period = 10;
    int signal_period = 12;

    int totalBars = Bars(symbol, timeframe);
    if(totalBars < slowEMA_period + signal_period) {
        Print("Not enough data for MACD calculation");
        return (0.0);
    }

    // Use the global MACD handle, no need to redeclare it
    // macdHandle is already initialized in OnInit()

    // Copy the current values of the MACD line and signal line to the arrays
    if(CopyBuffer(macdHandle, 0, 0, 1, macdLineArray) <= 0 ||
       CopyBuffer(macdHandle, 1, 0, 1, signalLineArray) <= 0) {
        Print("Error in copying data from MACD buffer: ", GetLastError());
        return (0.0);
    }

    // Manually calculate the MACD Histogram as the difference between MACD line and Signal line
    macdHistogram = macdLineArray[0] - signalLineArray[0];
    macdSignalLine = signalLineArray[0]; // For output

    return macdHistogram;
}

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit() {
    // Initialize MACD handle
    macdHandle = iMACD(_Symbol, _Period, 8, 10, 12, PRICE_CLOSE);
    if(macdHandle == INVALID_HANDLE) {
        Print("Error creating MACD handle: ", GetLastError());
        return INIT_FAILED;
    }

    // Resize buffers
    ArraySetAsSeries(macdLineBuffer, true);
    ArraySetAsSeries(macdSignalLineBuffer, true);
    ArrayResize(macdLineBuffer, 1);
    ArrayResize(macdSignalLineBuffer, 1);

    startingBalance = AccountInfoDouble(ACCOUNT_BALANCE);
    return INIT_SUCCEEDED;
}

// Calculate MACD Histogram function
double CalculateMACDHistogram() {
    // Calculate the MACD Histogram as the difference between the MACD Line and the MACD Signal Line
    return macdLineBuffer[0] - macdSignalLineBuffer[0];
}

//+------------------------------------------------------------------+
//| Check entry conditions function                                  |
//+------------------------------------------------------------------+
// Check entry conditions function
int CheckEntryConditions() {
    double currentOpen = iOpen(_Symbol, PERIOD_M5, 0);
    double currentBid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    double currentAsk = SymbolInfoDouble(_Symbol, SYMBOL_ASK);

    double ema6 = CalculateEMA(_Symbol, PERIOD_M5, 6, PRICE_OPEN);
    double ma6 = CalculateMA(_Symbol, PERIOD_M5, 6, PRICE_OPEN);

    // Copy MACD data to buffers
    if(CopyBuffer(macdHandle, 0, 0, 1, macdLineBuffer) <= 0 ||
       CopyBuffer(macdHandle, 1, 0, 1, macdSignalLineBuffer) <= 0) {
        Print("Error in copying data from MACD buffer: ", GetLastError());
        return 0; // No Signal
    }

    double macdSignalLine = macdSignalLineBuffer[0];
    double macdHistogram = macdLineBuffer[0] - macdSignalLine;

    // Buy Conditions
    if (currentAsk > currentOpen && ema6 > ma6 && macdHistogram > 0.0080) {
        return 1; // Buy Signal
    }
    // Sell Conditions
    else if (currentBid < currentOpen && ema6 < ma6 && macdHistogram < -0.0080) {
        return -1; // Sell Signal
    }

    return 0; // No Signal
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick() {
    // Get current Ask and Bid prices
    double Ask, Bid;
    if(!SymbolInfoDouble(_Symbol, SYMBOL_ASK, Ask) || !SymbolInfoDouble(_Symbol, SYMBOL_BID, Bid)) {
        Print("Error getting price data");
        return;
    }
    
    // Get the current count of buy and sell positions
    PositionCounts currentPositions = CountOpenPositions();
    
    // Account balance control
    double currentBalance = AccountInfoDouble(ACCOUNT_BALANCE);
    if (currentBalance <= startingBalance * (1.0 - MaxLossPercent / 100.0)) {
        Print("Total loss reached");
        ExpertRemove();
        return;
    } else if (currentBalance >= startingBalance * (1.0 + MaxProfitPercent / 100.0)) {
        Print("Total profit reached");
        ExpertRemove();
        return;
    }
    
    // Copy MACD data to buffers
    if(CopyBuffer(macdHandle, 0, 0, 1, macdLineBuffer) <= 0 ||
       CopyBuffer(macdHandle, 1, 0, 1, macdSignalLineBuffer) <= 0) {
        Print("Error in copying data from MACD buffer: ", GetLastError());
        return;
    }

    // Now you can safely call CalculateMACDHistogram() here to get the MACD histogram value
    double macdHistogram = CalculateMACDHistogram();

// Check for entry conditions
    int tradeSignal = CheckEntryConditions();
    if (tradeSignal == 1) {
        // Buy Signal
        ExecuteTrade(true);
    } else if (tradeSignal == -1) {
        // Sell Signal
        ExecuteTrade(false);
    }

    // Check exit conditions for each open position
    CheckExitConditions();
}
   
//+------------------------------------------------------------------+
//| Execute trade function                                           |
//+------------------------------------------------------------------+
void ExecuteTrade(bool isBuySignal) {
    double Ask = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
    double Bid = SymbolInfoDouble(_Symbol, SYMBOL_BID);
    string comment = "My EA Trade"; // Custom comment for the trade

    // Assuming no stop loss and take profit for simplicity
    double stopLoss = 0;
    double takeProfit = 0;

    if (isBuySignal) {
        // Execute Buy Trade
        if (!trade.Buy(FixedLotSize, _Symbol, Ask, stopLoss, takeProfit, comment)) {
            Print("Trade Error: ", GetLastError());
        }
    } else {
        // Execute Sell Trade
        if (!trade.Sell(FixedLotSize, _Symbol, Bid, stopLoss, takeProfit, comment)) {
            Print("Trade Error: ", GetLastError());
        }
    }
}

//+------------------------------------------------------------------+
//| Check exit conditions for each open position                     |
//+------------------------------------------------------------------+
void CheckExitConditions() {
    for (int i = 0; i < PositionsTotal(); i++) {
        ulong positionTicket = PositionGetTicket(i);
        if (PositionSelectByTicket(positionTicket)) {
            double ema6 = CalculateEMA(_Symbol, PERIOD_M5, 6, PRICE_OPEN);
            double ma6 = CalculateMA(_Symbol, PERIOD_M5, 6, PRICE_OPEN);
            ENUM_POSITION_TYPE positionType = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);

            // Close Buy Position
            if (positionType == POSITION_TYPE_BUY && ema6 < ma6) {
                trade.PositionClose(positionTicket);
            }
            // Close Sell Position
            else if (positionType == POSITION_TYPE_SELL && ema6 > ma6) {
                trade.PositionClose(positionTicket);
            }
        }
    }
}


//+------------------------------------------------------------------+
//| Trade transaction event handler                                  |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction& trans, const MqlTradeRequest& request, const MqlTradeResult& result) {
    // Update useSecondaryIndicators based on the result of the trade
    // ...
}

Reason: