how to get value of this indicator?

 

when i want to get value of first buffer, it always shows empty value but in Data window shows that it ( buffer 0 ) has a value!

this is the code of indicator:

//+--------------------------------------------------------------------------------------+
//|                                                                 Nearest_Neighbor.mq5 |
//|                                                                 Copyright 2010, gpwr |
//+--------------------------------------------------------------------------------------+
#property copyright "gpwr"
#property version   "1.00"
#property description "Prediction of future based on the nearest neighbor in the past"
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_plots   2
//--- future model outputs
#property indicator_label1  "NN future"
#property indicator_type1   DRAW_LINE
#property indicator_color1  Red
#property indicator_style1  STYLE_SOLID
#property indicator_width1  1
//--- past model outputs
#property indicator_label2  "NN past"
#property indicator_type2   DRAW_LINE
#property indicator_color2  Blue
#property indicator_style2  STYLE_SOLID
#property indicator_width2  1

//Global constants
#define pi 3.141592653589793238462643383279502884197169399375105820974944592

//===================================== INPUTS ===========================================
input int    Npast   =300; // # of past bars in a pattern
input int    Nfut    =50;  // # of future bars in a pattern (must be < Npast)

// Global variables
int bars,PrevBars;
double mx[],sxx[],denx[];
bool FirstTime;

// Indicator buffers
double ynn[],xnn[];

// Custom indicator initialization function ---------------------------------------------+
void OnInit()
{
// Initialize global variables
   PrevBars=Bars(_Symbol,_Period)-1;
   FirstTime=true;

// Map indicator buffers
   SetIndexBuffer(0,ynn,INDICATOR_DATA);
   SetIndexBuffer(1,xnn,INDICATOR_DATA);
   IndicatorSetInteger(INDICATOR_DIGITS,_Digits);
   IndicatorSetString(INDICATOR_SHORTNAME,"1NN("+string(Npast)+")");
   PlotIndexSetInteger(0,PLOT_SHIFT,Nfut);
}

//====================================== MAIN ============================================
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[])
{
// Check for insufficient data and new bar
   int bars=rates_total;
   if(bars<Npast+Nfut)
   {
      Print("Error: not enough bars in history!");
      return(0);
   }
   if(PrevBars==bars) return(rates_total);
   PrevBars=bars;

// Initialize indicator buffers to EMPTY_VALUE
   ArrayInitialize(xnn,EMPTY_VALUE);
   ArrayInitialize(ynn,EMPTY_VALUE);

// Main cycle ---------------------------------------------------------------------------+
   // Compute correlation sums for current pattern
   // Current pattern starts at i=bars-Npast and ends at i=bars-1
   double my=0.0;
   double syy=0.0;
   for(int i=0;i<Npast;i++)
   {
      double y=Open[bars-Npast+i];
      my +=y;
      syy+=y*y;
   }
   double deny=syy*Npast-my*my;
   if(deny<=0)
   {
      Print("Zero or negative syy*Npast-my*my = ",deny);
      return(0);
   }
   deny=MathSqrt(deny);
   
   // Compute correlation sums for past patterns
   // Past patterns start at k=0 and end at k=bars-Npast-Nfut
   ArrayResize(mx,bars-Npast-Nfut+1);
   ArrayResize(sxx,bars-Npast-Nfut+1);
   ArrayResize(denx,bars-Npast-Nfut+1);
   int kstart;
   if(FirstTime) kstart=0;
   else kstart=bars-Npast-Nfut;
   FirstTime=false;
   for(int k=kstart;k<=bars-Npast-Nfut;k++)
   {
      if(k==0)
      {
         mx[0] =0.0;
         sxx[0]=0.0;
         for(int i=0;i<Npast;i++)
         {
            double x =Open[i];
            mx[0] +=x;
            sxx[0]+=x*x;
         }
      }
      else
      {
         double xnew=Open[k+Npast-1];
         double xold=Open[k-1];
         mx[k] =mx[k-1]+xnew-xold;
         sxx[k]=sxx[k-1]+xnew*xnew-xold*xold;
      }
      denx[k]=sxx[k]*Npast-mx[k]*mx[k];
   }
   
   // Compute cross-correlation sums and correlation coefficients and find NN
   double sxy[];
   ArrayResize(sxy,bars-Npast-Nfut+1);
   double b,corrMax=0;
   int knn=0;
   for(int k=0;k<=bars-Npast-Nfut;k++)
   {
      // Compute sxy
      sxy[k]=0.0;
      for(int i=0;i<Npast;i++) sxy[k]+=Open[k+i]*Open[bars-Npast+i];
      
      // Compute corr coefficient
      if(denx[k]<=0)
      {
         Print("Zero or negative sxx[k]*Npast-mx[k]*mx[k]. Skipping pattern # ",k);
         continue;
      }
      double num=sxy[k]*Npast-mx[k]*my;
      double corr=num/MathSqrt(denx[k])/deny;
      if(corr>corrMax)
      {
         corrMax=corr;
         knn=k;
         b=num/denx[k];
      }
   }
   Print("Nearest neighbor is dated ",Time[knn]," and has correlation with current pattern of ",corrMax);

   // Compute xm[] and ym[] by scaling the nearest neighbor
   double delta=Open[bars-1]-b*Open[knn+Npast-1];
   for(int i=0;i<Npast+Nfut;i++)
   {
      if(i<=Npast-1) xnn[bars-Npast+i]=b*Open[knn+i]+delta;
      if(i>=Npast-1) ynn[bars-Npast-Nfut+i]=b*Open[knn+i]+delta;
   }
   
   return(rates_total);
}

i get buffer by this code:

double a = iCustom(_Symbol,PERIOD_CURRENT,"nearest-neighbor");
double ma[];
ArraySetAsSeries(ma,true);
CopyBuffer(a,0,0,5,ma);
double maval =ma[1];
Print(maval);
 
Your attached executable files was removed. Only attach source code files, not executable ones.
 

iCustom might not be finding the indicator, look to see if there's any errors in the journal


better code:

input int    Npast   =300; // # of past bars in a pattern
input int    Nfut    =50;  // # of future bars in a pattern (must be < Npast)

string ind_name =  "Nearest_Neighbor";
int handle = iCustom(_Symbol,PERIOD_CURRENT,ind_name, Npast, Nfut);

https://www.mql5.com/en/docs/indicators/icustom

Documentation on MQL5: Technical Indicators / iCustom
Documentation on MQL5: Technical Indicators / iCustom
  • www.mql5.com
The function returns the handle of a specified custom indicator. Parameters symbol [in] The symbol name of the security, the data of which should...
 
tom standly:

when i want to get value of first buffer, it always shows empty value but in Data window shows that it ( buffer 0 ) has a value!

this is the code of indicator:

i get buffer by this code:

I ran your code through the debugger - according to the debugger watch window, only the first bar of the future buffer contains a value, everything else is EMPTY_VALUE. The issue is in your indicator. 

 
  1. //|                                                                 Nearest_Neighbor.mq5 |
    
    double a = iCustom(_Symbol,PERIOD_CURRENT,"nearest-neighbor");

    Perhaps you should read the manual, especially the examples.
       How To Ask Questions The Smart Way. (2004)
          How To Interpret Answers.
             RTFM and STFW: How To Tell You've Seriously Screwed Up.

    They all (including iCustom) return a handle (an int). You get that in OnInit. In OnTick/OnCalculate/OnStart (after the indicator has updated its buffers), you use the handle, shift and count to get the data.
              Technical Indicators - Reference on algorithmic/automated trading language for MetaTrader 5
              Timeseries and Indicators Access / CopyBuffer - Reference on algorithmic/automated trading language for MetaTrader 5
              How to start with MQL5 - General - MQL5 programming forum - Page 3 #22 (2020)
              How to start with MQL5 - MetaTrader 5 - General - MQL5 programming forum - Page 7 #61 (2020)
              MQL5 for Newbies: Guide to Using Technical Indicators in Expert Advisors - MQL5 Articles (2010)
              How to call indicators in MQL5 - MQL5 Articles (2010)


  2.                 const double& Open[],
    ⋮
          double y=Open[bars-Npast+i];

    In MT5, you must set the direction.

    To define the indexing direction in the time[], open[], high[], low[], close[], tick_volume[], volume[] and spread[] and other arrays (copyXXXX functions), call the ArrayGetAsSeries() function. In order not to depend on defaults, call the ArraySetAsSeries() function for the arrays to work with.
              Event Handling / OnCalculate - Reference on algorithmic/automated trading language for MetaTrader 5
 
ceejay1962 #:

I ran your code through the debugger - according to the debugger watch window, only the first bar of the future buffer contains a value, everything else is EMPTY_VALUE. The issue is in your indicator. 

but in Data Window future buffer shows value. i attached image that shows it.
Files:
Untitled.png  34 kb
 
Conor Mcnamara #:

iCustom might not be finding the indicator, look to see if there's any errors in the journal


better code:

https://www.mql5.com/en/docs/indicators/icustom

It find the indicator. it shows buffer 1 but it shows empty value for buffer 0. my problem is buffer 0 value.
 

You're basically getting the data of the last (current) bar in the EA.

If you look at the two buffers

They give the same value on that last bar. 


I see it working fine.

#include <Trade/Trade.mqh>

#resource "\\Indicators\\Examples\\Nearest Neighbor.ex5"

input int    Npast   =300; // # of past bars in a pattern
input int    Nfut    =50;  // # of future bars in a pattern (must be < Npast)


int handle = INVALID_HANDLE;

double first_buf[];
double second_buf[];
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   handle = iCustom(_Symbol, _Period, "::Indicators\\Examples\\Nearest Neighbor", Npast, Nfut);
   
   ArraySetAsSeries(first_buf, true);
   ArraySetAsSeries(second_buf, true); 

//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   IndicatorRelease(handle);
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
      if(!CopyBuffer(handle, 0, 0, 1, first_buf)){
      
         Print("Something wrong retrieving data from buffer 0");
      }
      
      if(!CopyBuffer(handle, 1, 0, 1, second_buf)){
      
         Print("Something wrong retrieving data from buffer 1");
      }
          
      double b0 = first_buf[0];       
      double b1 = second_buf[0];    
      
 
      string debug = "Buffer 0 value: " + DoubleToString(b0) + "\n" + "Buffer 1 value: " + DoubleToString(b1);
      
      Comment(debug);    
  }
//+------------------------------------------------------------------+


If you want to test this when the markets are closed, you will have to use strategy tester visual mode. There are no incoming ticks on forex markets at the weekend.