Trading Systems

EA – Time Series Forecast

Lo scorso anno abbiamo dedicato un articolo ad un indicatore poco noto denominato “Time series forecast” comprensivo di codice Power Language e statistiche su futures. Potete leggerlo qui.
Alleghiamo anche il listato Expert Advisor per Metatrader in modo che possiate testarlo sul Forex e su CFD.
Dovete copiare e incollare il listato nell’editor Metaquotes e compilarlo.
Buon testing.
NB: L’utilizzo su fonti dati diverse da eSignal e Swissquote, diversi sottostanti o time frame può generare risultati completamente differenti. In questo caso si consiglia una completa ritaratura degli input.


//+——————————————————————+
//|                                           TimeSeriesForecast.mq4 |
//|                                  Copyright 2016, Fabio Pacchioni |
//|                                            http://www.mql4academy.blogspot.it |
//+——————————————————————+
#property copyright “Copyright 2016, Fabio Pacchioni”
#property link      “https://www.mql4academy.blogspot.it”
#property version   “1.00”
#property strict
//— input parameters
extern string sez1 = “————-Input Parameters—————-“;
input int      Length=9;
input int      BarsPlus=7;
input int      Price = PRICE_CLOSE;
extern string sez3 = “————-General Data—————-“;
input double   Lots              = 1;                              // Lot Size
extern int     MagicNumber       = 113854;                           // Magic number
extern int     Slippage          = 5;                                // Slippage
//extern int     ExpDate           = 3;                                // Expiration Hour Order

double p, iStopLevel;
int error, iSlipp;
double TSFbuffer[], TSF1, TSF2, TSF3;
static int BARS;
//+——————————————————————+
//| Expert initialization function                                   |
//+——————————————————————+
int OnInit()
{
double vpoint = MarketInfo(Symbol(), MODE_POINT);

if (vpoint == 0.00001)
p = 0.0001;
else if (vpoint == 0.001)
p = 0.01;
else
p = vpoint;

if(p == vpoint)
{
iStopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL);
iSlipp=Slippage;
}
if(p != vpoint)
{
iStopLevel = MarketInfo(Symbol(), MODE_STOPLEVEL)/10;
iSlipp=Slippage*10;
}

p = vpoint;

ArraySetAsSeries(TSFbuffer,true);

return(INIT_SUCCEEDED);
}
//+——————————————————————+
//| Expert deinitialization function                                 |
//+——————————————————————+
void OnDeinit(const int reason)
{
//—
}
//+——————————————————————+
//| Expert tick function                                             |
//+——————————————————————+
void OnTick()
{
int LongOpenOrders = 0;
int ShortOpenOrders = 0;
int DimAr =0;

if ( IsNewBar() )
{
TSF();
//TSF1 = iCustom(Symbol(),Period(),”TSF-Forecast”,Length,BarsPlus,0,1);
//TSF2 = iCustom(Symbol(),Period(),”TSF-Forecast”,Length,BarsPlus,0,2);
//TSF3 = iCustom(Symbol(),Period(),”TSF-Forecast”,Length,BarsPlus,0,3);
DimAr = ArrayRange(TSFbuffer,0);
LongOpenOrders = CheckLongOrders(Symbol(), MagicNumber);
ShortOpenOrders = CheckShortOrders(Symbol(), MagicNumber);

if ( iClose(Symbol(), Period(), 1) > TSF1 && TSF1 > TSF2 && TSF2 <= TSF3 && ShortOpenOrders == 0)
{
if (LongOpenOrders > 0)
CloseAllOpenOrders(MagicNumber);

if (OrderSend(Symbol(),OP_SELL,Lots,Bid,iSlipp,0,0,”TSF Short”,MagicNumber,0,Red) < 0)
error = GetLastError();
}
else if ( iClose(Symbol(), Period(), 1) < TSF1 && TSF1 < TSF2 && TSF2 >= TSF3 && LongOpenOrders == 0)
{
if (ShortOpenOrders > 0)
CloseAllOpenOrders(MagicNumber);

if (OrderSend(Symbol(),OP_BUY,Lots,Ask,iSlipp,0,0,”TSF Long”,MagicNumber,0,Green) < 0)
error = GetLastError();
}
}
}
//+——————————————————————+

//+——————————————————————+
//| NewBar function                                                  |
//+——————————————————————+
bool IsNewBar()
{
if(BARS!=Bars(_Symbol,_Period))
{
BARS=Bars(_Symbol,_Period);
return(true);
}
return(false);
}

//+——————————————————————+
//| Time Series Forecast calculation                                 |
//+——————————————————————+
void TSF()
{
int limit, i, k;
double sumXSqr, sumX, sumXY, sumY, price, slope, divisor, intercept;

if(Bars < Length)
return;

limit = MathMin(Bars, Bars-Length);
ArrayResize(TSFbuffer, limit+1);

sumXSqr = Length * (Length – 1) * (2*Length – 1) / 6.0;
sumX    = Length * (Length – 1) * 0.5;
for(i = limit; i > 0; i–)
{
sumXY   = 0;
sumY    = 0;

for (k = 0; k < Length; k++)
{
price = iMA(NULL,0,1,0,MODE_SMA,Price,i+k);
sumXY += k*price;
sumY  +=   price;
}
divisor  = sumX*sumX – Length*sumXSqr;
if( divisor != 0 )
slope = (Length*sumXY – sumX*sumY) / divisor;
else
slope = 0;

intercept = (sumY – slope*sumX) / Length ;
TSFbuffer[i] = intercept  + slope * (Length – 1 – BarsPlus);
if (i == 1)
{
TSF1 = TSFbuffer[1];
//Print(“TSF1: “,TSF1);
}
if (i == 2)
{
TSF2 = TSFbuffer[2];
//Print(“TSF2: “,TSF2);
}
if (i == 3)
{
TSF3 = TSFbuffer[3];
//Print(“TSF3: “,TSF3);
}
}
return;
}

//+———————————————————————————————————————-+
//| The function check for existing open long trades                                                                     |
//| symbol      – current symbol.                                                                                        |
//| magicAd     – Magic number of this EA.                                                                               |
//+———————————————————————————————————————-+
int CheckLongOrders(string symbol, int magicAd = 0)
{
int NLongOrders = 0;
for (int i = 0; i < OrdersTotal(); i++)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderSymbol() == symbol && OrderMagicNumber() == magicAd)
{
if (OrderType() == OP_BUY)
{
NLongOrders++;
}
}
}
}
return(NLongOrders);
}

//+———————————————————————————————————————-+
//| The function check for existing open short trades                                                                    |
//| symbol      – current symbol.                                                                                        |
//| magicAd     – Magic number of this EA.                                                                               |
//+———————————————————————————————————————-+
int CheckShortOrders(string symbol, int magicAd = 0)
{
int NShortOrders = 0;
for (int i = 0; i < OrdersTotal(); i++)
{
if (OrderSelect(i, SELECT_BY_POS, MODE_TRADES))
{
if (OrderSymbol() == symbol && OrderMagicNumber() == magicAd)
{
if (OrderType() == OP_SELL)
{
NShortOrders++;
}
}
}
}
return(NShortOrders);
}

//+———————————————————————————————————————-+
//| The function try to close all opened orders                                                                          |
//| MagicNumber – Magic number of this EA.                                                                               |
//+———————————————————————————————————————-+
bool CloseAllOpenOrders(int magicNum = 0)
{
int total = OrdersTotal();
int type;
bool result = false;

for(int i=total-1;i>=0;i–)
{
  if (!OrderSelect(i, SELECT_BY_POS))
   continue;
  else if (OrderSymbol() == Symbol() && OrderMagicNumber() == magicNum)
  {
   type = OrderType();

   result = false;

   switch(type)
   {
    //Close opened long positions
    case OP_BUY:
     result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_BID), 5, Red );
     break;

    //Close opened short positions
    case OP_SELL:
     result = OrderClose( OrderTicket(), OrderLots(), MarketInfo(OrderSymbol(), MODE_ASK), 5, Red );
     break;
   }

   if(result == false)
   {
    Alert(“Order ” , OrderTicket() , ” failed to close. Error:” , GetLastError() );
    Sleep(3000);
   }
  }
}

return (result);
}
/*
inputs:
Length( 9 ),
BarsPlus( 7 ) ;
variables:
var0( 0 ) ;
var0 = TimeSeriesForecast( Length, BarsPlus ) ;
condition1 = Close > var0 and var0 > var0[1] and var0[1] <= var0[2] ;
if condition1 then
sellshort next bar at market
else
begin
condition1 = Close < var0 and var0 < var0[1] and var0[1] >= var0[2] ;
if condition1 then
buy next bar at market;
end;
*/

Leave a Comment