Download MetaTrader 5

Shift Indicator => 1 Bar, Bool? Displacement?

To add comments, please log in or register
Razza
239
Razza  

I have recently had an EA made for me and after playing around with it, I would like to "Shift" one of my indicators to the right one bar within the EA.


I know how to access the code and have managed simple changes myslef already through trial and error.


Where can I find the code or the methodology to shift all of one of my indicators attributes one bar later?


Is this to do with bool?


Thanks

Razza
239
Razza  
Forgot to say this is for MQL5, if it makes a difference
Marco vd Heijden
Moderator
4752
Marco vd Heijden  
not with a bool but integer that represents the bar shift you simply add one for the next bar but since we are not shown any code you would have to look it up in the docs.
Razza
239
Razza  

Thank you Marco vd Heijden

My script is below, I will be looking to make the changes to the second AMA.

 RossExpertAdvisor.mq5
#property version   "1.0"
#include <Trade\Trade.mqh>
#include <Trade\SymbolInfo.mqh>
CTrade  trade;
CSymbolInfo info;

input float BuyPrecentageOfEquity=2;//Set % of equity for Buy orders
input float SellPrecentageOfEquity=2;//Set % of equity for Sell orders
input ushort LimitOrders=3;//Limit for total orders
input ushort BuyTakeprofit=50;//Set BuyTakeprofit in pips
input ushort BuyStoploss=50;//Set BuyStoploss in pips
input ushort SellTakeprofit=60;//Set SellTakeprofit in pips
input ushort SellStoploss=60;//Set SellStoploss in pips
input ushort Deviation=30;//Maximal possible deviation from price
input ushort AMAPeriod=85;//AMA Period
input ushort AMAFast=1;//AMA Fastest period
input ushort AMASlow=30;//AMA Shortest period
input ushort AMAPeriod1=85;//AMA Period
input ushort AMAFast1=1;//AMA Fastest period
input ushort AMASlow1=30;//AMA Shortest period
input ushort Magicnumber=8888;//Magic number for orders
input bool Mode=true;//True:bar 1 | False:bar 0

double AMA[];
int handleAMA;
double AMA1[];
int handleAMA1;
double buyTakeProfit;
double buyStopLoss;
double sellTakeProfit;
double sellStopLoss;
double buyVolumeOfEquity;
double sellVolumeOfEquity;
double minimalVolumeOfEquity;
ushort tempType=2;
int positionTemp;
bool work=true;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
  //Âûñ÷èòûâàåì ìèíèìàëüíî äîïóñòèìûé % îò equity, % îò equity äëÿ buy îðäåðîâ è % îò equity äëÿ sell îðäåðîâ
  minimalVolumeOfEquity=NormalizeDouble((SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN)*SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE))/AccountInfoDouble(ACCOUNT_EQUITY),2);
  buyVolumeOfEquity=NormalizeDouble(((((AccountInfoDouble(ACCOUNT_EQUITY)*AccountInfoInteger(ACCOUNT_LEVERAGE))/SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE))*BuyPrecentageOfEquity)/100),2);
  sellVolumeOfEquity=NormalizeDouble(((((AccountInfoDouble(ACCOUNT_EQUITY)*AccountInfoInteger(ACCOUNT_LEVERAGE))/SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE))*SellPrecentageOfEquity)/100),2);
 
  //Ïðîâåðÿåì åñëè ïîëüçîâàòåëü óêàçàë % íèæå äîïóñòèìîãî
  if((SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN)>buyVolumeOfEquity) || (SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN)>sellVolumeOfEquity))
  {
   Alert("Warning! To low BuyPrecentageOfEquity: ",BuyPrecentageOfEquity,", or SellPrecentageOfEquity",SellPrecentageOfEquity,", minimal PrecentageOfEquity is ",minimalVolumeOfEquity,".");
   //Ïðèñâîèì ìèíèìàëüíî äîïóñòèìûé ïðîöåíò
   buyVolumeOfEquity=minimalVolumeOfEquity;
   sellVolumeOfEquity=minimalVolumeOfEquity;
  }
  //Ïðîâåðÿåì TP è SL è ïðèñâàåâàåì ìèíèìàëüíî äîïóñòèìûé
  if(SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL)>BuyTakeprofit || SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL)>SellTakeprofit)
  {
   Alert("Warning! Minimal stops level is: ",SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL),". Your buy Takeprofit is: ",BuyTakeprofit,", sell Takeprofit is: ",SellTakeprofit,".");
   buyTakeProfit=(double)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
   buyStopLoss=(double)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
   sellTakeProfit=(double)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
   sellStopLoss=(double)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
  }
  //Çàäàåì ïåðåìåííûå äëÿ ðàáîòû ñ èíäèêàòîðîì Simple Moving Average è Adaptive Moving Average
  ArraySetAsSeries(AMA,true);
  ArraySetAsSeries(AMA1,true);
  handleAMA=iAMA(_Symbol,0,AMAPeriod,AMAFast,AMASlow,0,PRICE_CLOSE);
  handleAMA1=iAMA(_Symbol,0,AMAPeriod1,AMAFast1,AMASlow1,0,PRICE_CLOSE);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   ArrayFree(AMA);
   ArrayFree(AMA1);
   IndicatorRelease(handleAMA1);
   IndicatorRelease(handleAMA);
   Comment("");
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
 {
  //Íà êàæäîì îáíîâëåíèè ïîçèöè ïîäñè÷òûâàåì êîë-âî ïîçèöèé ñîâåòíèêà
  if(positionTemp!=PositionsTotal())
  {
   int x=0;
   positionTemp=PositionsTotal(); //Õðàíèò ïðåäûäóùåå çíà÷åíèå êîë-âà ïîçèöèé
   for(int i=0; i<PositionsTotal(); i++)
   {
    if(PositionGetSymbol(i))
    {
     if(PositionGetString(POSITION_COMMENT)==IntegerToString(Magicnumber))
      {
        x++; //Õðàíèò êîë-âî ïîçèöèé ñîâåòíèêà     
      }
    }
   }
   if(x>=LimitOrders)//Åñëè êîë-âî ïîçèöèé ñîâåòíèêà áîëüøå èëè = Ëèìèòà, òî ñîâåòíèê íå òîðãóåò
   {
    Comment("The orders limit has been reached. LimitOrder: ",LimitOrders,", current EA orders: ",x,".");
    work=false;
   }
   else
   {
    Comment("");
    work=true;
   }
  }
  //Áåðåì çíà÷åíèå èíäèêàòîðîâ
  CopyBuffer(handleAMA,0,0,3,AMA);
  CopyBuffer(handleAMA1,0,0,3,AMA1);
  if(work) //åñëè íå äîñòèíóòî ëèìèòà
   {
     if(Mode) //ðåæèì íà 1 áàðå
     {
         if(AMA[2]<AMA1[1] && AMA[1]>AMA1[1]) //Åñëè SMA ñòàëà áîëüøå AMA, çíà÷èò ìû èìååì ïðîáèòèå ââåðõ, îòêðûâàåì áàé
         {
          if(tempType!=0)//Îãðàíè÷èâàåì îòêðûòèå òîëüêî 1-ãî îðäåðà
          {
           CloseCrossOrder(); //Çàêðûòèå ïðîòèâîïîëîæíîãî îðäåðà
           OpenBuyOrder(BuyTakeprofit,BuyStoploss,buyVolumeOfEquity,Deviation,Magicnumber,IntegerToString(Magicnumber));
           tempType=0; //Çàïèøåì òî, ÷òî åñòü 1 áàé îðäåð
          }
         }
         else if(AMA[2]>AMA1[1] && AMA[1]<AMA1[1]) //Åñëè SMA ñòàëà ìåíüøå AMA, çíà÷èò ìû èìååì ïðîáèòèå âíèç, îòêðûâàåì ñåëë
         {
          if(tempType!=1)//Îãðàíè÷èâàåì îòêðûòèå òîëüêî 1-ãî îðäåðà
          {
           CloseCrossOrder();//Çàêðûòèå ïðîòèâîïîëîæíîãî îðäåðà
           OpenSellOrder(SellTakeprofit,SellStoploss,sellVolumeOfEquity,Deviation,Magicnumber,IntegerToString(Magicnumber));
           tempType=1; //Çàïèøåì òî, ÷òî åñòü 1 ñåëë îðäåð
          }
         }
     }
     else //ðåæèì ðàáîòû íà 0 áàðå
     {
         if(AMA[1]<AMA1[0] && AMA[0]>AMA1[0])
         {
          if(tempType!=0)//Îãðàíè÷èâàåì îòêðûòèå òîëüêî 1-ãî îðäåðà
          {
           CloseCrossOrder();
           OpenBuyOrder(BuyTakeprofit,BuyStoploss,buyVolumeOfEquity,Deviation,Magicnumber,IntegerToString(Magicnumber));
           tempType=0;
          }
         }
         else if(AMA[1]>AMA1[0] && AMA[0]<AMA1[0])
         {
          if(tempType!=1)//Îãðàíè÷èâàåì îòêðûòèå òîëüêî 1-ãî îðäåðà
          {
           CloseCrossOrder();
           OpenSellOrder(SellTakeprofit,SellStoploss,sellVolumeOfEquity,Deviation,Magicnumber,IntegerToString(Magicnumber));
           tempType=1;
          }
        }
     }
   } 
 }
//+------------------------------------------------------------------+
void OpenSellOrder(ushort takeprofit, ushort stoploss, double volume, ushort deviation, ushort magic, string comment)
{
  MqlTick tick;
  SymbolInfoTick(_Symbol,tick);
  sellTakeProfit=tick.ask-((SymbolInfoInteger(_Symbol,SYMBOL_SPREAD)+takeprofit)*SymbolInfoDouble(_Symbol, SYMBOL_POINT));
  sellStopLoss=tick.ask+(stoploss*SymbolInfoDouble(_Symbol, SYMBOL_POINT));
  MqlTradeResult result;
  MqlTradeRequest request;
  ZeroMemory(result);
  ZeroMemory(request);
  request.action=TRADE_ACTION_DEAL;
  request.magic=magic;
  request.symbol=_Symbol;
  request.price=SymbolInfoDouble(_Symbol,SYMBOL_BID);
  request.volume=volume;
  request.type=ORDER_TYPE_SELL;
  request.sl=sellStopLoss;
  request.tp=sellTakeProfit;
  request.deviation=deviation;
  request.comment=comment;
 
  if(OrderSend(request,result))
  {
      Alert("Opened Sell order, result code: ",result.retcode);
  }
   else
     {
      Alert("Can't open Sell order, result code: ",result.retcode,". Error code: ",GetLastError(),". BID: ",SymbolInfoDouble(_Symbol,SYMBOL_BID),". TP: ", sellTakeProfit,". SL: ",sellStopLoss,". Deviation: ",deviation,". Volume: ",volume,".");
      }
}

//+------------------------------------------------------------------+
void OpenBuyOrder(ushort takeprofit, ushort stoploss, double volume, ushort deviation, ushort magic, string comment)
{
  MqlTick tick;
  SymbolInfoTick(_Symbol,tick);
  buyTakeProfit=tick.bid+((SymbolInfoInteger(_Symbol,SYMBOL_SPREAD)+takeprofit)*SymbolInfoDouble(_Symbol, SYMBOL_POINT));
  buyStopLoss=tick.bid-(stoploss*SymbolInfoDouble(_Symbol, SYMBOL_POINT));
  MqlTradeResult result;
  MqlTradeRequest request;
  ZeroMemory(result);
  ZeroMemory(request);
  request.action=TRADE_ACTION_DEAL;
  request.magic=magic;
  request.symbol=_Symbol;
  request.volume=volume;
  request.price=SymbolInfoDouble(_Symbol,SYMBOL_ASK);
  request.type=ORDER_TYPE_BUY;
  request.sl=buyStopLoss;
  request.tp=buyTakeProfit;
  request.deviation=deviation;
  request.comment=comment;
 
  if(OrderSend(request,result))
  {
      Alert("Opened Buy order, result code: ",result.retcode);
  }
   else
     {
      Alert("Can't open Buy order, result code: ",result.retcode,". Error code: ",GetLastError(),". ASK: ",SymbolInfoDouble(_Symbol,SYMBOL_ASK),". TP: ", buyTakeProfit,". SL: ",buyStopLoss,". Deviation: ",deviation,". Volume: ",volume,".");
      }
}

//+------------------------------------------------------------------+
void CloseCrossOrder()
{
  if(PositionSelect(_Symbol))
  {
   if(PositionGetInteger(POSITION_MAGIC)==Magicnumber)
     {
       Print("Cross order for ",PositionGetString(POSITION_SYMBOL)," closed!");
       trade.PositionClose(_Symbol); //çàêðûâàåì ïîçèöèþ
       tempType=2; //ñáðàñûâàåì ïåðåìåííóþ çàïèñè îðäåðà
     }
  }    
}
Alain Verleyen
Moderator
31183
Alain Verleyen  

Forum on trading, automated trading systems and testing trading strategies


Hello,

Please use the SRC button when you post code. Thank you.


This time, I edited it for you.


Marco vd Heijden
Moderator
4752
Marco vd Heijden  
  handleAMA=iAMA(_Symbol,0,AMAPeriod,AMAFast,AMASlow,0,PRICE_CLOSE);
  handleAMA1=iAMA(_Symbol,0,AMAPeriod1,AMAFast1,AMASlow1,0,PRICE_CLOSE);

iAMA

The function returns the handle of the Adaptive Moving Average indicator. It has only one buffer.

int  iAMA(    string              symbol,             // symbol name    ENUM_TIMEFRAMES     period,             // period    int                 ama_period,         // average period for AMA    int                 fast_ma_period,     // fast MA period    int                 slow_ma_period,     // slow MA period    int                 ama_shift,          // horizontal shift of the indicator    ENUM_APPLIED_PRICE  applied_price       // type of the price or handle    );

  CopyBuffer(handleAMA,0,0,3,AMA);
  CopyBuffer(handleAMA1,0,0,3,AMA1);
Call by the first position and the number of required elements
int  CopyBuffer(
   int       indicator_handle,     // indicator handle
   int       buffer_num,           // indicator buffer number
   int       start_pos,            // start position
   int       count,                // amount to copy
   double    buffer[]              // target array to copy
   );
Razza
239
Razza  

Thank you very much Marco vd Heijden

I changed the highlighted scetion below from a "0" to a "1"

  handleAMA=iAMA(_Symbol,0,AMAPeriod,AMAFast,AMASlow,0,PRICE_CLOSE);
  handleAMA1=iAMA(_Symbol,0,AMAPeriod1,AMAFast1,AMASlow1,0,PRICE_CLOSE);

Razza
239
Razza  

I also changed the highlighted scetion below from a "0" to a "1"


//--- inputs for main signal
input int                Signal_ThresholdOpen =10;          // Signal threshold value to open [0...100]
input int                Signal_ThresholdClose=10;          // Signal threshold value to close [0...100]
input double             Signal_PriceLevel    =0.0;         // Price level to execute a deal
input double             Signal_StopLevel     =50.0;        // Stop Loss level (in points)
input double             Signal_TakeLevel     =50.0;        // Take Profit level (in points)
input int                Signal_Expiration    =4;           // Expiration of pending orders (in bars)
input int                Signal_AMA_PeriodMA  =80;          // Adaptive Moving Average(80,...) Period of averaging
input int                Signal_AMA_PeriodFast=2;           // Adaptive Moving Average(80,...) Period of fast EMA
input int                Signal_AMA_PeriodSlow=30;          // Adaptive Moving Average(80,...) Period of slow EMA
input int                Signal_AMA_Shift     =0;           // Adaptive Moving Average(80,...) Time shift
input ENUM_APPLIED_PRICE Signal_AMA_Applied   =PRICE_CLOSE; // Adaptive Moving Average(80,...) Prices series
input double             Signal_AMA_Weight    =1.0;         // Adaptive Moving Average(80,...) Weight [0...1.0]
input int                Signal_MA_PeriodMA   =2;           // Moving Average(2,0,MODE_SMA,...) Period of averaging
input int                Signal_MA_Shift      =1;           // Moving Average(2,0,MODE_SMA,...) Time shift
input ENUM_MA_METHOD     Signal_MA_Method     =MODE_SMA;    // Moving Average(2,0,MODE_SMA,...) Method of averaging
input ENUM_APPLIED_PRICE Signal_MA_Applied    =PRICE_CLOSE; // Moving Average(2,0,MODE_SMA,...) Prices series
input double             Signal_MA_Weight     =1.0;         // Moving Average(2,0,MODE_SMA,...) Weight [0...1.0]
//--- inputs for money
input double             Money_FixLot_Lots    =0.1;         // Fixed volume
Razza
239
Razza  

I have changed nothing else,

I'm not sure if I should have?


In testing the EA, I can see that the second AMA is moving one bar later than the first, however no trades are being activated now from indicator crosses?


Have I missed something in the code? ....is it to do with copy buffer?

Marco vd Heijden
Moderator
4752
Marco vd Heijden  
  CopyBuffer(handleAMA,0,0,3,AMA);
  CopyBuffer(handleAMA1,0,0,3,AMA1);
Call by the first position and the number of required elements
int  CopyBuffer(
   int       indicator_handle,     // indicator handle
   int       buffer_num,           // indicator buffer number
   int       start_pos,            // start position
   int       count,                // amount to copy
   double    buffer[]              // target array to copy
   );

Start pos == 0;

Amount to copy == 3;

 

Your code is confusing i see you

input int                Signal_MA_Shift      =1;           // Moving Average(2,0,MODE_SMA,...) Time shift

 but the Signal_MA_Shift isnt found in the function in the code above.

it looks like your mixing things up. 


Razza
239
Razza  

Marco vd Heijden I had the code written by "professionals" in Moldova found on this MQL5 website.

I'm just trying to have two moving averages, with the second delayed by one bar to create Buy and Sell signals.

Could you reccomend a trustworthy coder to either edit the code I have or to re-write it for me?

thank you, Ross

To add comments, please log in or register