iCustom returning Empty Values but indicator works fine on chart

 
I have recently created a custom indicator in MT4. It works fine on my charts, but when using iCustom inside an EA it will not fetch the values and returns the max int value of 2123237 or whatever the standard is for empty value. The indicator code is attached below:
//+------------------------------------------------------------------+
//|                                                       Aggregate.mq4 |
//|                                                        Copyright 2023 |
//|                                                        https://www.example.com/ |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023"
#property link      "https://www.example.com/"
#property version   "1.00"
#property strict

//--- Indicator settings
#property indicator_separate_window
#property indicator_buffers 4
#property indicator_plots   4

//--- Indicator plots
#property indicator_label1 "BullishDistance"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrGreen
#property indicator_width1 1
#property indicator_style1 STYLE_SOLID

#property indicator_label2 "BearishDistance"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrRed
#property indicator_width2 1
#property indicator_style2 STYLE_SOLID

#property indicator_label3 "AverageDistance"
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrBlue
#property indicator_width3 1
#property indicator_style3 STYLE_SOLID

#property indicator_label4 "AverageDifference"
#property indicator_type4 DRAW_LINE
#property indicator_color4 clrPurple
#property indicator_width4 1
#property indicator_style4 STYLE_SOLID

//--- Indicator parameters
input int Period = 20;
input int AvgPeriod = 20;

//--- Indicator buffers
double BullishDistance[];
double BearishDistance[];
double AverageDistance[];
double AverageDifference[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function                         |
//+------------------------------------------------------------------+
int OnInit()
{
   //--- Indicator buffers
   SetIndexBuffer(0, BullishDistance);
   SetIndexBuffer(1, BearishDistance);
   SetIndexBuffer(2, AverageDistance);
   SetIndexBuffer(3, AverageDifference);

   //--- Indicator properties
   IndicatorShortName("Aggregate (" + IntegerToString(Period) + ", " + IntegerToString(AvgPeriod) + ")");

   //--- Set drawing styles for each buffer
   SetIndexStyle(0, DRAW_LINE, STYLE_SOLID, 1, clrGreen);
   SetIndexStyle(1, DRAW_LINE, STYLE_SOLID, 1, clrRed);
   SetIndexStyle(2, DRAW_LINE, STYLE_SOLID, 1, clrBlue);
   SetIndexStyle(3, DRAW_LINE, STYLE_SOLID, 1, clrPurple);

   return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Custom indicator iteration function                              |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
                const int prev_calculated,
                const datetime &time[],
                const double &open[],
                const double &high[],
                const double &low[],
                const double &close[],
                const long &tick_volume[],
                const long &volume[],
                const int &spread[])
{
    
    int start = prev_calculated - 1;
    if (start < Period)
        start = Period;

    for (int i = start; i < rates_total; i++)
    {
        double bullishSum = 0;
        double bearishSum = 0;

        for (int j = 0; j < Period; j++)
        {
            double bullDist = close[i - j] - open[i - j] > 0 ? close[i - j] - open[i - j] : 0;
            double bearDist = open[i - j] - close[i - j] > 0 ? open[i - j] - close[i - j] : 0;
            bullishSum += bullDist;
            bearishSum += bearDist;
        }

        // Assign values to plots
        BullishDistance[i - Period + 1] = bullishSum;
        BearishDistance[i - Period + 1] = bearishSum;

        // Calculate average distance and average difference
        if (i >= Period + AvgPeriod - 1)
        {
            double avgDistSum = 0;
            double avgDiffSum = 0;

            for (int j = 0; j < AvgPeriod; j++)
            {
                avgDistSum += (BullishDistance[i - Period + 1 - j] + BearishDistance[i - Period + 1 - j]);
                avgDiffSum += MathAbs(BullishDistance[i - Period + 1 - j] - BearishDistance[i - Period + 1 - j]);
            }

            AverageDistance[i - Period - AvgPeriod + 2] = avgDistSum / (2 * AvgPeriod);
            AverageDifference[i - Period - AvgPeriod + 2] = avgDiffSum / AvgPeriod;
        }
    }

    return(rates_total);
}

And for further reference, the code for the EA i am trying to create is also below:

//+------------------------------------------------------------------+
//|                                              Aggregate_Proto.mq4 |
//|                        Copyright 2023, MetaQuotes Software Corp. |
//|                                             https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2023, MetaQuotes Software Corp."
#property link      "https://www.mql5.com"
#property version   "1.00"
#property strict



input int AggPeriod = 40;
input int DiffPeriod = 40;
input double KPeriod = 1.0;
input int Sharpness = 1;
input double Profit = 80;
input double Stop = 40;
input int Risk = 1;

// Global variable to store the ticket number of the currently open trade
int tradeTicket = 0;
int stradeTicket = 0;

// Declare a global variable for the minimum stop level
int StopLevel;

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
{
    // Define the minimum stop level
    StopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL);
   
    

    return(INIT_SUCCEEDED);
}

//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
    //---
   
}

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
    // Calculate the values of the custom indicator
    double bullish_distance = iCustom(_Symbol, _Period, "Aggregate", AggPeriod, DiffPeriod,  0, 1);
    double bearish_distance = iCustom(_Symbol, _Period, "Aggregate", AggPeriod, DiffPeriod, 1, 1);
    double p_bullish_distance = iCustom(_Symbol, _Period, "Aggregate", AggPeriod, DiffPeriod, 0, 2);
    double p_bearish_distance = iCustom(_Symbol, _Period, "Aggregate", AggPeriod, DiffPeriod, 1, 2);
    double average_distance = iCustom(_Symbol, _Period, "Aggregate", AggPeriod, DiffPeriod, 2, 1);
    double average_difference = iCustom(_Symbol, _Period, "Aggregate", AggPeriod, DiffPeriod, 3, 1);
    // Calculate the values of the custom indicator
    double velocity = iCustom(_Symbol, _Period, "KalmanVelocity", Sharpness, KPeriod, 0, 1);
    Print("Bullish Distance: ", bullish_distance);
    Print("Bearish Distance: ", bearish_distance);
    Print("Previous Bullish Distance: ", p_bullish_distance);
    Print("Previous Bearish Distance: ", p_bearish_distance);
    Print("Velocity: ", velocity);
    
  

   
  
    // Buy trade condition
    if (tradeTicket == 0 && velocity > 0 && bullish_distance > bearish_distance && p_bullish_distance < p_bearish_distance)
    {
        // Place the buy order
        Print("buy met");
        double sl = Ask - (Stop * _Point);
        double tp = Ask + (Profit * _Point);
        double RiskPercentage = Risk; // 1% risk per trade
        double PositionSize = AccountBalance() * RiskPercentage / 100 / Stop / _Point;
        
        tradeTicket = OrderSend(_Symbol, OP_BUY, MathRound(PositionSize), Ask, 0, sl, tp, "Long Position", 0, 0, Green);
    }


    
    // Check if the currently open trade is still active
    if (tradeTicket > 0)
    {
        if (OrderSelect(tradeTicket, SELECT_BY_TICKET))
        {
            if (OrderStopLoss() < Ask - (Stop*_Point))
                OrderModify(OrderTicket(), OrderOpenPrice(), Ask - (Stop * _Point),0,0,0);
            
            // Check if the trade is closed or has been deleted
            
            if (OrderCloseTime() > 0 || !OrderTicket())
            {
                // Reset the trade ticket variable
                tradeTicket = 0;
            }
        }
    }
     if (stradeTicket == 0 && velocity < 0 && bullish_distance < bearish_distance && p_bearish_distance < p_bullish_distance)
    {
         double sl = Bid +  (Stop * _Point);
         double tp = Bid - + (Profit * _Point);
         double RiskPercentage = Risk; // 1% risk per trade
         double PositionSize = AccountBalance() * RiskPercentage / 100 / Stop / _Point;
         Print("selll met");
         
         stradeTicket = OrderSend(_Symbol, OP_SELL, MathRound(PositionSize), Bid, 0, sl, tp, "Short Position", 0, 0, Red);
    }

    
    
    // Check if the currently open trade is still active
    if (stradeTicket > 0)
    {
        if (OrderSelect(stradeTicket, SELECT_BY_TICKET))
        {
            if (OrderStopLoss() > Bid + (Stop*_Point))
                OrderModify(OrderTicket(), OrderOpenPrice(), Bid + (Stop * _Point),0,0,0);
            // Check if the trade is closed or has been deleted
            if (OrderCloseTime() > 0 || !OrderTicket())
            {
                // Reset the trade ticket variable
                stradeTicket = 0;
            }
        }
    }
 }
//+------------------------------------------------------------------+




I am pretty new to coding so I'm sure its something simple, however I cannot seem to figure it out and don't understand what would cause this. When I add the print functions, it prints:

2023.04.22 15:37:46.358 BTCUSDT,M1: 7363 tick events (211 bars, 264973 bar states) processed in 0:00:01.610 (total time 0:00:03.672)
2023.04.22 15:37:46.358 2023.04.17 03:52:21  Aggregate_Proto BTCUSDT,M1: Velocity: 0.0
2023.04.22 15:37:46.358 2023.04.17 03:52:21  Aggregate_Proto BTCUSDT,M1: Previous Bearish Distance: 2147483647.0
2023.04.22 15:37:46.358 2023.04.17 03:52:21  Aggregate_Proto BTCUSDT,M1: Previous Bullish Distance: 0.0
2023.04.22 15:37:46.358 2023.04.17 03:52:21  Aggregate_Proto BTCUSDT,M1: Bearish Distance: 2147483647.0
2023.04.22 15:37:46.358 2023.04.17 03:52:21  Aggregate_Proto BTCUSDT,M1: Bullish Distance: 2147483647.0
2023.04.22 15:37:46.358 2023.04.17 03:52:20  Aggregate_Proto BTCUSDT,M1: Velocity: 0.0

And then just repeats over and over, not accessing the indicator values but shows them perfectly on the chart when running the strategy tester. It appears I am having an issue with the custom 'velocity' indicator as well, however that one is just repeating 0.0 instead of the 214xxx number. If anyone could figure out what is going on and give me a hand with this, I would be eternally grateful. This has been a huge headache. As I stated I am new to this so I would like to know what I am doing wrong and how I can prevent this from happening with future projects.


Thank you!

Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2023.04.23
  • 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
 

Please don't post randomly in any section. Your question is not related to the section you posted.

MT4/mql4 has it's own section on the forum.

I have moved your topic to the correct section, so please don't create another topic.

 
Skate:
I have recently created a custom indicator in MT4. It works fine on my charts, but when using iCustom inside an EA it will not fetch the values and returns the max int value of 2123237 or whatever the standard is for empty value. The indicator code is attached below:

And for further reference, the code for the EA i am trying to create is also below:




I am pretty new to coding so I'm sure its something simple, however I cannot seem to figure it out and don't understand what would cause this. When I add the print functions, it prints:

And then just repeats over and over, not accessing the indicator values but shows them perfectly on the chart when running the strategy tester. It appears I am having an issue with the custom 'velocity' indicator as well, however that one is just repeating 0.0 instead of the 214xxx number. If anyone could figure out what is going on and give me a hand with this, I would be eternally grateful. This has been a huge headache. As I stated I am new to this so I would like to know what I am doing wrong and how I can prevent this from happening with future projects.


Thank you!

if you edit all comparisons accordingly, the problem is solved. You edit the remaining code. Example

if(bullish_distance!= 2147483647.0 && bullish_distance>0) ....
 
  1. if(bullish_distance!= 2147483647.0 && bullish_distance>0) ....

    Do not hard code numbers. Use the provided symbols (EMPTY_VALUE).

  2.        double sl = Ask - (Stop * _Point);
            double tp = Ask + (Profit * _Point);

    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)