Download MetaTrader 5

Indicator has different values when run with EA

To add comments, please log in or register
Hilton Global LLC
689
Sean Hilton  

Good Morning,


I'm testing an indicator with an EA (using iCustom). There's only one buffer. Basically the indicator will cross back and forth across a zero value. If the indicator is positive, I'll buy. If it's negative, I'll sell.

My trouble is that when I run the EA and indicator in visual mode the indicator will give me one set of values. And then I add the same indicator with the same inputs after the EA runs will give me a different set of values.


The entire code of the indicator:

...
#property  version   "1.00"
#property  strict
#property  description "Trendmancer is a fast and accurate trend finder."
#property  description "The current trend will remain until the price moves in a direction"
#property  description "strong enough to overcome the Delta parameter."
#property  description "Setting a low Delta (D<1) is better for scalping strategies."
#property  description "Higher Delta (D>1) is good for trend trading strategies."
#property  indicator_separate_window
#property  indicator_buffers 1
#property  indicator_color1  Blue
#property  indicator_width1 4

extern int MAPeriod = 8; //Period of the Moving Avg.
extern int VectorX = 2; //Period to measure slope.
extern double Delta = 1.0; //Delta

int MAMethod = 1; //0=Simple, 1=Exponential, 2=Smoothed, 3=Linear Weighted
int MAAppliedTo = 6; //Applied Price: 0=C 1=O 2=H 3=L 4=(HL/2) 5=(HLC/3) 6=(HLCC/4)
double prevStatic = 0.0;
int LastStatic = 0;
datetime LastTime = 0;
double prevSlope = 0.0;
double StaticMABuffer[];
class CFix { } ExtFix;
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
int init()
  {
   IndicatorBuffers(1);
   
   SetIndexStyle(0,DRAW_HISTOGRAM);
   SetIndexEmptyValue(0, 0.0);
   SetIndexLabel(0,"Trendmancer");
   
   IndicatorDigits(Digits+3);
   if(!SetIndexBuffer(0,StaticMABuffer)) {Print("cannot set indicator buffers!");}
   IndicatorShortName("Trendmancer("+IntegerToString(MAPeriod)+") VectorX:("+IntegerToString(VectorX)+") Delta:("+DoubleToStr(Delta,2)+").");
   return(0);
  }
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
int deinit(){return(0);}
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
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 counted_bars = IndicatorCounted();
   if(counted_bars < 0) {return(-1);}
   int limit= Bars - counted_bars;
   //if(counted_bars == 0) {limit--;}
   for (int i = limit - 2; i >= 0; i--)
   {
      LastStatic = iBarShift(NULL,0,LastTime);
      prevStatic = StaticMABuffer[i + 1];
      prevSlope = NormalizeDouble((iMA(NULL,0,MAPeriod,0,MAMethod,MAAppliedTo,LastStatic) - iMA(NULL,0,MAPeriod,0,MAMethod,MAAppliedTo,LastStatic + VectorX)) / VectorX,Digits+2);
      
      StaticMABuffer[i] = shouldMAChange(i, Delta, prevStatic); //Back to the MA.
      if(StaticMABuffer[i] == 0){StaticMABuffer[i] = prevSlope;} //Remain unchanged.
      
   }
   
   
   return(0);
  }
//+------------------------------------------------------------------+

double shouldMAChange(int index, double delta, double prevStatica)
{
   double DeltaUp = 1 + (delta * 0.001);
   double DeltaDn = 1 - (delta * 0.001);
   prevStatica = iMA(NULL,0,MAPeriod,0,MAMethod,MAAppliedTo,LastStatic) + (prevSlope * (LastStatic - index));
   double Value = iMA(NULL,0,MAPeriod,0,MAMethod,MAAppliedTo,index);
   double ValueUp = prevStatica * DeltaUp;
   double ValueDn = prevStatica * DeltaDn;
   if(Value > ValueUp){LastTime = Time[index]; return(0);}
   if(Value < ValueDn){LastTime = Time[index]; return(0);}
   if(Value <= ValueUp && Value >= ValueDn){return(0);}
   return(0);
}


The entire code of the EA: (Note there is a hidden takeprofit and stoploss so I can use them on new bars only. And this is only a rough draft.)

...
#property version   "1.00"
#property strict

extern int     TMPeriod = 8;
extern int     TMVector = 2;
extern double  TMDelta = 1.0;
extern double  TPMulti = 2.0;
extern double  SLMulti = 1.0;
extern double  PercentMarginLotSize = 1.0;
extern int     MagicNumber = 1111;

//Non-External Variables
double         MinTP = 0.0001;
double         MinSL = 0.0001;
double         TMVote = 0.0;
double         TPCalc;
double         SLCalc;
double         takeprofit;
double         stoploss;
double         pips;
double         RiskedAmount;
double         LotSizeBuy;
double         LotSizeSell;
double         LotStep;
int            buyticket = 0;
int            sellticket = 0;
string         SLOPE = "NONE";

//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
   //##### Calculate pips for 4 or 5 digit brokers. #####
   if(Digits == 5 || Digits == 3){pips = Point * 10;}
   else{pips = Point;}
   //#####
   
   LotStep = MarketInfo(Symbol(),MODE_LOTSTEP);
   
   return(INIT_SUCCEEDED);
  }
  
  
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason){}


//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   AccountInfoComment();
   
   if(OrdersTotal() == 0){buyticket = 0; sellticket = 0;}
   
   if(IsNewCandle())
   {
    TMVote = iCustom(NULL,0,"Trendmancer2",TMPeriod,TMVector,TMDelta,0,0);
    RefreshRates();
    TPCalc = MathAbs((Ask - Bid) + (TMVote * TPMulti));
    if(TPCalc < MinTP){TPCalc = MinTP;}
    SLCalc = MathAbs((Ask - Bid) + (TMVote * SLMulti));
    if(SLCalc < MinSL){SLCalc = MinSL;}
    
    FakeProfit();
    ChopLoss();
    
    if(TMVote > 0){OrderCloser(1); OrderEntry(0); SLOPE = "UP";} //Try to close a Sell, open a BUY.
    if(TMVote < 0){OrderCloser(0); OrderEntry(1); SLOPE = "DOWN";} //Try to close a Buy, open a SELL.
    if(TMVote == EMPTY_VALUE || TMVote == 0){OrderCloser(0); OrderCloser(1); SLOPE = "FLAT";} //Try to close anything.
   }
   
   
  }
  
  //+ CUSTOM FUNCTIONS ------------------------------------------------+

//Order Sending Function
bool OrderEntry(int direction)
  {//double minstoplevel = MarketInfo(Symbol(),MODE_STOPLEVEL);
   
   if(direction==0)
         if(buyticket==0 && sellticket==0)
         {
         LotSizeBuy = NormalizeDouble(RiskedAmount(),2);
         LotSizeBuy = MathRound(LotSizeBuy / LotStep) * LotStep;
         if(LotSizeBuy > MarketInfo(Symbol(),MODE_MAXLOT)){LotSizeBuy = MarketInfo(Symbol(),MODE_MAXLOT);}
         if(LotSizeBuy < MarketInfo(Symbol(),MODE_MINLOT)){LotSizeBuy = MarketInfo(Symbol(),MODE_MINLOT);}
         
         takeprofit = iMA(NULL,0,1,0,0,0,0) + TPCalc;
         takeprofit = NormalizeDouble(takeprofit,Digits);
         
         stoploss = iMA(NULL,0,1,0,0,0,0) - SLCalc;
         stoploss = NormalizeDouble(stoploss,Digits);
         
         if(takeprofit > 0)
         {
          if(takeprofit - Bid < MarketInfo(Symbol(), MODE_STOPLEVEL))
          {
           Print("takeprofit is less than allowed stop level of ", MarketInfo(Symbol(), MODE_STOPLEVEL), " changing to: ", MarketInfo(Symbol(), MODE_STOPLEVEL));
           takeprofit = MarketInfo(Symbol(), MODE_STOPLEVEL);
          }
          if(takeprofit - Bid <= MarketInfo(Symbol(), MODE_FREEZELEVEL))
          {
           Print("takeprofit is less than allowed freeze level of ", MarketInfo(Symbol(), MODE_FREEZELEVEL), " changing to: ", MarketInfo(Symbol(), MODE_FREEZELEVEL));
           takeprofit = MarketInfo(Symbol(), MODE_FREEZELEVEL);
          }
         }
         
         if(stoploss > 0)
         {
          if(Bid - stoploss < MarketInfo(Symbol(), MODE_STOPLEVEL))
          {
           Print("stoploss is less than allowed stop level of ", MarketInfo(Symbol(), MODE_STOPLEVEL), " changing to: ", MarketInfo(Symbol(), MODE_STOPLEVEL));
           stoploss = MarketInfo(Symbol(), MODE_STOPLEVEL);
          }
          if(Bid - stoploss <= MarketInfo(Symbol(), MODE_FREEZELEVEL))
          {
           Print("stoploss is less than allowed freeze level of ", MarketInfo(Symbol(), MODE_FREEZELEVEL), " changing to: ", MarketInfo(Symbol(), MODE_FREEZELEVEL));
           stoploss = MarketInfo(Symbol(), MODE_FREEZELEVEL);
          }
         }
         
         Print(LotSizeBuy);
         
         buyticket = OrderSend(Symbol(),OP_BUY,LotSizeBuy,Ask,3,0,0,NULL,MagicNumber,0,Blue);
         
         if(buyticket<0){Print("OrderSend (buy) failed with error #",GetLastError()); return(False);}
         else{Print("Buy on buy signal!! #",buyticket,"."); return(True);}
         }
         
   if(direction==1)
         if(sellticket==0 && buyticket==0)
         {
         LotSizeSell = NormalizeDouble(RiskedAmount(),2);
         LotSizeSell = MathRound(LotSizeSell / LotStep) * LotStep;
         if(LotSizeSell > MarketInfo(Symbol(),MODE_MAXLOT)){LotSizeSell = MarketInfo(Symbol(),MODE_MAXLOT);}
         if(LotSizeSell < MarketInfo(Symbol(),MODE_MINLOT)){LotSizeSell = MarketInfo(Symbol(),MODE_MINLOT);}
         
         takeprofit = iMA(NULL,0,1,0,0,0,0) - TPCalc;
         takeprofit = NormalizeDouble(takeprofit,Digits);
         
         stoploss = iMA(NULL,0,1,0,0,0,0) + SLCalc;
         stoploss = NormalizeDouble(stoploss,Digits);
         
         if(takeprofit > 0)
         {
          if(Ask - takeprofit < MarketInfo(Symbol(), MODE_STOPLEVEL))
          {
           Print("takeprofit is less than allowed stop level of ", MarketInfo(Symbol(), MODE_STOPLEVEL), " changing to: ", MarketInfo(Symbol(), MODE_STOPLEVEL));
           takeprofit = MarketInfo(Symbol(), MODE_STOPLEVEL);
          }
          if(Ask - takeprofit <= MarketInfo(Symbol(), MODE_FREEZELEVEL))
          {
           Print("takeprofit is less than allowed freeze level of ", MarketInfo(Symbol(), MODE_FREEZELEVEL), " changing to: ", MarketInfo(Symbol(), MODE_FREEZELEVEL));
           takeprofit = MarketInfo(Symbol(), MODE_FREEZELEVEL);
          }
         }
         
         if(stoploss > 0)
         {
          if(stoploss - Ask < MarketInfo(Symbol(), MODE_STOPLEVEL))
          {
           Print("stoploss is less than allowed stop level of ", MarketInfo(Symbol(), MODE_STOPLEVEL), " changing to: ", MarketInfo(Symbol(), MODE_STOPLEVEL));
           stoploss = MarketInfo(Symbol(), MODE_STOPLEVEL);
          }
          if(stoploss - Ask <= MarketInfo(Symbol(), MODE_FREEZELEVEL))
          {
           Print("stoploss is less than allowed freeze level of ", MarketInfo(Symbol(), MODE_FREEZELEVEL), " changing to: ", MarketInfo(Symbol(), MODE_FREEZELEVEL));
           stoploss = MarketInfo(Symbol(), MODE_FREEZELEVEL);
          }
         }
         
         Print(LotSizeSell);
         
         sellticket = OrderSend(Symbol(),OP_SELL,LotSizeSell,Bid,3,0,0,NULL,MagicNumber,0,Red);
         
         if(sellticket<0){Print("OrderSend (sell) failed with error #",GetLastError()); return(False);}
         else{Print("Sell on sell signal!! #",sellticket,"."); return(True);}
         }
   return(False);
  }
  
//Order Closing Function.
void OrderCloser(int direction)
  {
   if(direction==0)
         if(OrderSelect(buyticket,SELECT_BY_TICKET,0)==true)
            if(OrderType()==OP_BUY)
            {
               int closebuyticket = OrderClose(buyticket,LotSizeBuy,Bid,3,Gold);
               if(closebuyticket>0)
               {
                  buyticket=0;
                  Print("OrderClose [closing buy order] Success!");
               }
               else {Print("OrderClose [closing buy order] failed error code is ",GetLastError());}
            }
   if(direction==1)
         if(OrderSelect(sellticket,SELECT_BY_TICKET,0)==true)
            if(OrderType()==OP_SELL)
            {
               int closesellticket = OrderClose(sellticket,LotSizeSell,Ask,3,Gold);
               if(closesellticket>0)
               {
                  sellticket=0;
                  Print("OrderClose [closing sell order] Success!");
               }
               else {Print("OrderClose [closing sell order] failed error code is ",GetLastError());}
            }
  }
  
//FakeProfit is a hidden TakeProfit... Sneaky!
void FakeProfit()
  {
   if(OrdersTotal() != 0)
   {
    if(OrderSelect(buyticket,SELECT_BY_TICKET,0) == true)
     if(OrderType()==OP_BUY)
      if(Bid >= takeprofit)
      {
       if(OrderClose(buyticket,OrderLots(),Bid,3,Gold)){Print("OrderClose [closing buy order] Success! FakeProfit.");}
       else{Print("OrderClose [closing buy order] failed error code is ",GetLastError(),"  FakeProfit.");}
      }
    if(OrderSelect(sellticket,SELECT_BY_TICKET,0) == true)
     if(OrderType()==OP_SELL)
      if(Ask <= takeprofit)
      {
       if(OrderClose(sellticket,OrderLots(),Ask,3,Gold)){Print("OrderClose [closing sell order] Success! FakeProfit.");}
       else{Print("OrderClose [closing sell order] failed error code is ",GetLastError(),"  FakeProfit.");}
      }
   }
  }
  
//ChopLoss is a hidden StopLoss... Sneaky!
void ChopLoss()
  {
   if(OrdersTotal() != 0)
   {
    if(OrderSelect(buyticket,SELECT_BY_TICKET,0) == true)
     if(OrderType()==OP_BUY)
      if(Bid <= stoploss)
      {
       if(OrderClose(buyticket,OrderLots(),Bid,3,Gold)){Print("OrderClose [closing buy order] Success! ChopLoss.");}
       else{Print("OrderClose [closing buy order] failed error code is ",GetLastError(),"  FakeProfit.");}
      }
    if(OrderSelect(sellticket,SELECT_BY_TICKET,0) == true)
     if(OrderType()==OP_SELL)
      if(Ask >= stoploss)
      {
       if(OrderClose(sellticket,OrderLots(),Ask,3,Gold)){Print("OrderClose [closing sell order] Success! ChopLoss.");}
       else{Print("OrderClose [closing sell order] failed error code is ",GetLastError(),"  FakeProfit.");}
      }
   }
  }

//Comments
void AccountInfoComment()
  {
   double E = AccountEquity();
   double M = AccountFreeMargin();
   Comment("Account equity is currently: "+DoubleToStr(NormalizeDouble(E,2),2)+". Account Free Margin is currently: "+DoubleToStr(NormalizeDouble(M,2),2)+".\n",
   "The Slope is: "+SLOPE+".\nFakeProfit is: "+DoubleToStr(NormalizeDouble(takeprofit,Digits),5)+"\n",
   "ChopLoss is: "+DoubleToStr(NormalizeDouble(stoploss,Digits),5)+"\n",
   "Trendmancer: "+DoubleToStr(TMVote));
  }

//Checking if the candle is new.
bool IsNewCandle()
  {
   static int BarsOnChart=0;
   if (Bars == BarsOnChart){return(false);}
   BarsOnChart = Bars;
   return(true);
  }
  
//Calculate Lot Size.
double RiskedAmount()
  {
   RiskedAmount = AccountFreeMargin() * PercentMarginLotSize * 0.0001;
   return(RiskedAmount);
  }
  


Thanks in advance for any advice you can offer!

Hilton Global LLC
689
Sean Hilton  

Oh I think I see what's going on...

The indicator is dependent on all previous bars to get to where it is right now. If I drop it on the chart after the fact, then it's starting on a different bar all together. No wonder the values are all different.

It's doing what it should. That's just the nature of the indi.

Thanks.

whroeder1
14779
whroeder1  
Hiltos: No wonder the values are all different.
LastStatic = iBarShift(NULL,0,LastTime);
prevStatic = StaticMABuffer[i + 1];
  1. If the indicator is that sensitive, it likely useless.
  2. Perhaps prevStatic should be based on LastStatic.
To add comments, please log in or register