//+------------------------------------------------------------------+ //| 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 }
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.
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
//+------------------------------------------------------------------+ //| 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; }
//+------------------------------------------------------------------+ //| 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
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
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.
//+------------------------------------------------------------------+ //| 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 // ... }

- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
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.