Code: Select all
//:::::::::::::::::::::::::::::::::::::::::::::
#property indicator_buffers 2
#property indicator_color1 Red
#property indicator_color2 Black
#property indicator_minimum -1
#property indicator_maximum 1
#property indicator_separate_window
#include <mt4R.mqh>
extern int GdvPeriod = 20;
extern int GdvLookBack = 500;
extern double GdvAlpha = 1000;
extern string Rpath = "C:/Program Files/R/R-3.2.3/bin/x64/Rterm.exe --no-save";
extern int RDebugLevel = 1;// 0,1,2
extern string RTempDir = "";//
//:::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::::::::::::::
string IndName= "GradientVolatility0";
string IndVer= "0.1.0";
double ExtMapBuffer1[];
double ExtMapBuffer2[];
int nextBarTime;
int R;
int init()
{
IndicatorBuffers(2);
IndicatorDigits(Digits+10);
IndicatorShortName(StringConcatenate(IndName," ",IndVer));
SetIndexStyle( 0 , DRAW_LINE );
SetIndexStyle( 1 , DRAW_NONE );
SetIndexDrawBegin( 0 , GdvPeriod );
SetIndexDrawBegin( 1 , GdvPeriod );
SetIndexBuffer( 0 , ExtMapBuffer1 );
SetIndexBuffer( 1 , ExtMapBuffer2 );
//string Rterm = StringConcatenate(Rpath, " --no-save" );
R = RInit(Rpath,RDebugLevel);
// R check
RExecute(R, "ret <- TRUE");
bool ret = RGetBool(R,"ret");
if(!ret){
Alert("Rterm.exe path maybe wrong..");
Comment("Rterm.exe path maybe wrong..");
return(0);
}
RExecute(R, "histNum <- numeric(0)" );
RExecute(R, "library(zoo)" );
return(0);
}
//:::::::::::::::::::::::::::::::::::::::::::::
int start()
{
int i;
double hist[] ;
double ret[] ;
int unused_bars;
int used_bars=IndicatorCounted();
if (used_bars<0) return(-1);
if (used_bars>0) used_bars--;
unused_bars=Bars-used_bars;
if(RIsBusy(R)) return(0);
ArrayResize(ret,GdvLookBack);
int len= RGetInteger(R, "length(histNum)" );
if( RGetInteger(R, "as.integer(exists('model'))" ) ==1)
{
RGetVector(R, StringConcatenate( "rev(model)[1:" ,GdvLookBack, "]" ),ret,GdvLookBack);
for(i=0;i<GdvLookBack;i++)
{
ExtMapBuffer1[i] = ret[i];
}
}
if( isNewBar()==true )
{
ArrayResize(hist, GdvLookBack );
for(i= GdvLookBack -1;i>=0;i--)
{
hist[i] = Close[i];
}
RAssignVector(R, "hNum" ,hist,ArraySize(hist) );
RExecute(R, "hNum <- rev(hNum)" );
RExecute(R, "histNum <- c(hNum)" );
RExecuteAsync(R, "model <- rollapply(histNum,"+GdvPeriod+",function(x) as.numeric(lm(x ~ seq_along(x))$coeff[2]))*"+GdvAlpha+" " );
}
return(0);
}
int isNewBar()
{
if( nextBarTime == Time[0] )
return(false);
else
nextBarTime = Time[0];
return(true);
}
//:::::::::::::::::::::::::::::::::::::::::::::
//:::::::::::::::::::::::::::::::::::::::::::::
int deinit()
{
RDeinit(R);
return(0);
}
//:::::::::::::::::::::::::::::::::::::::::::::