Download MetaTrader 5

How to set pending orders to open x pips above previous bar high

To add comments, please log in or register
clinttaylor91
55
clinttaylor91  

Hey guys, 

Ive come up empty handed after searching the correct way to write my code so that it places pending orders a certain pip distance above the previous bars H n L. 

Ive seen similar questions but they weren't resolved and i can't find any documentation in the book about this specifically.

I have my the code working fine in regards to placing them at the H n L of the previous bar but i get errors when i try to alter the code with something like * point to get the order ex 10 pips above previous high.

so I've posted the code and a picture of an example. I tried change the lines around the iHigh symbols and iLow symbols but it generates lots of errors. The examples i found

were written different to mine so they don't work. Could anyone shed any light or is there more documentation on this topic anywhere? 


Thank you. 

//+------------------------------------------------------------------+
//+                            |
//+------------------------------------------------------------------+
#property strict

#define __STRATEGY_MAGIC 1001000000
#define __SLEEP_AFTER_EXECUTION_FAIL 400

//Input variables
input double _End_Minute = 0;                   // End Minute
input double _End_Hour = 0;                     // End Hour
input double _Start_Minute = 0;                 // Start Minute
input double _Start_Hour = 0;                   // Start Hour
input double _Lot_Size_Buy = 0;                 // Lot Size Buy
input double _Step_Value = 0;                   // Step Value
input double _Take_Profit_Sell = 0;                     // Take Profit Sell
input double _Stop_Loss_Sell = 0;                       // Stop Loss Sell
input double _Lot_Size_Sell = 0;                        // Lot Size Sell
input double _Take_Profit_Buy = 0;                      // Take Profit Buy
input double _Stop_Loss_Buy = 0;                        // Stop Loss Buy
input double _Trailing_Stop = 0;                        // Trailing Stop

//Global declaration
bool _IsTime;

int init() {

   return(0);
}

int start() {

   
   //Local declaration
   bool _Simple_Trailing_Stop = false;
   bool _Buy_Stop_Pending = false;
   bool _Sell_Stop_Pending = false;
   _IsTime = IsTime(_Start_Hour, _End_Hour, _Start_Minute, _End_Minute);
   _Simple_Trailing_Stop = Simple_Trailing_Stop(0, 0, _Trailing_Stop, _Step_Value);
   if( _IsTime && !__isExist( 1, Symbol() ) ) {
      _Buy_Stop_Pending = _Lot_Size_Buy >= MarketInfo( Symbol() ,MODE_MINLOT);
      if( _Buy_Stop_Pending == true ) _Buy_Stop_Pending = OrderSend( Symbol(), 4, _Lot_Size_Buy, NormalizeDouble( iHigh(Symbol(), 0, 1), (int)MarketInfo( Symbol(), MODE_DIGITS ) ), 0, __stopLossValue( Symbol(), 4, iHigh(Symbol(), 0, 1), _Stop_Loss_Buy ), __takeProfitValue( Symbol(), 4, iHigh(Symbol(), 0, 1), _Take_Profit_Buy ), "FxProQuant" + "(" + WindowExpertName() + ") " + "", __STRATEGY_MAGIC + 1, D'1970.01.01 00:00:00' ) >= 0;
      if( _Buy_Stop_Pending == false ) Sleep(__SLEEP_AFTER_EXECUTION_FAIL); 
   }
   if( _IsTime && !__isExist( 2, Symbol() ) ) {
      _Sell_Stop_Pending = _Lot_Size_Sell >= MarketInfo( Symbol() ,MODE_MINLOT);
      if( _Sell_Stop_Pending == true ) _Sell_Stop_Pending = OrderSend( Symbol(), 5, _Lot_Size_Sell, NormalizeDouble( iLow(Symbol(), 0, 1), (int)MarketInfo( Symbol(), MODE_DIGITS ) ), 0, __stopLossValue( Symbol(), 5, iLow(Symbol(), 0, 1), _Stop_Loss_Sell ), __takeProfitValue( Symbol(), 5, iLow(Symbol(), 0, 1), _Take_Profit_Sell ), "FxProQuant" + "(" + WindowExpertName() + ") " + "", __STRATEGY_MAGIC + 2, D'1970.01.01 00:00:00' ) >= 0;
      if( _Sell_Stop_Pending == false ) Sleep(__SLEEP_AFTER_EXECUTION_FAIL); 
   }
   if( _Buy_Stop_Pending ) Alert( "" );
   if( _Sell_Stop_Pending ) Alert( "" );

   return(0);
}



bool __selectOrderByMagic(int magic, string symbol)
{
   for(int i = 0; i < OrdersTotal(); i++)
   {
      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES) && OrderMagicNumber() == __STRATEGY_MAGIC + magic && OrderSymbol() == symbol)
         return(true);
   }
   return(false);
}



bool __isExist(int magic, string symbol)
{
   return(__selectOrderByMagic(magic, symbol));
}



double __takeProfitValue(string symbol,int orderType, double price, double points)
{
   if (points == 0)
      return (0);
   else if (orderType == 0 || orderType == 2 || orderType == 4)
      return ( NormalizeDouble( price + MarketInfo( symbol, MODE_POINT ) * points, (int)MarketInfo( symbol, MODE_DIGITS ) ) );
   else 
      return ( NormalizeDouble( price - MarketInfo( symbol, MODE_POINT ) * points, (int)MarketInfo( symbol, MODE_DIGITS ) ) );
}



double __stopLossValue(string symbol, int orderType, double price, double points)
{
   if (points == 0)
      return (0);
   else if (orderType == 0 || orderType == 2 || orderType == 4)
      return ( NormalizeDouble( price - MarketInfo( symbol, MODE_POINT ) * points, (int)MarketInfo( symbol, MODE_DIGITS ) ) );
   else 
      return ( NormalizeDouble( price + MarketInfo( symbol, MODE_POINT ) * points, (int)MarketInfo( symbol, MODE_DIGITS ) ) );
}



bool IsTime (int startHour, int endHour, int startMinute, int endMinute)
{
   if (startHour < 0 || startHour > 23 || endHour < 0 || endHour > 23 ||
       startMinute < 0 || startMinute > 59 || endMinute < 0 || endMinute > 59)
       return false;
   
   int startTime = startHour*60 + startMinute;
   int endTime = endHour*60 + endMinute;
   int time = Hour()*60 + Minute();
   
   if (startTime < endTime)
      return (time >= startTime && time <= endTime);
   else if (startTime > endTime)
      return (time >= startTime || time <= endTime);
   else
      return (time == startTime);
}


bool Simple_Trailing_Stop(int MagicIndex, int WaitForProfit, int TrailingStopPoints, int MinAdjustmentPoints)
{   
   double pnlPoints=0;   
   double price, sl, tp;
   double point = MarketInfo(Symbol(),MODE_POINT);
   int stopLevel = int(MarketInfo(Symbol(),MODE_STOPLEVEL) + MarketInfo(Symbol(),MODE_SPREAD));  
   int cmd; 
      
   bool result = true;   
   double newSl;

   int total = OrdersTotal();
      for(int i=total-1;i>=0;i--){
      if (!OrderSelect(i, SELECT_BY_POS)) continue;
      if(OrderMagicNumber() != __STRATEGY_MAGIC + MagicIndex || OrderSymbol() != Symbol()) continue;
      
      cmd = OrderType();      
      sl = NormalizeDouble(OrderStopLoss(),Digits);
      tp = OrderTakeProfit();
       
      if (OrderType() == OP_BUY)
      {
         price = MarketInfo(Symbol(),MODE_BID);
         newSl = NormalizeDouble(price - TrailingStopPoints * point, Digits);    
         if(((tp - price)/point) < stopLevel && tp != 0) continue;         
         if(((price - newSl)/point) < stopLevel)continue; 
         if(WaitForProfit == 0)
         {        
            pnlPoints = (price - OrderOpenPrice())/point; 
            if (pnlPoints < TrailingStopPoints ) continue;  
         }        
         if (sl + MinAdjustmentPoints*point>= newSl) continue;       
         
         if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSl, tp, 0))
         {
            printf("Error: Failed to modify trade. Ticket #%i, error code: %i", OrderTicket(), GetLastError());
            result = false;
            Sleep(__SLEEP_AFTER_EXECUTION_FAIL);
         }
      }  
      else if (OrderType() == OP_SELL)
      {
         price = MarketInfo(Symbol(),MODE_ASK);
         newSl = NormalizeDouble(price+ TrailingStopPoints * point, Digits);
         if(((price - tp)/point) < stopLevel) continue;
         if(((newSl - price)/point) < stopLevel) continue;
         if(WaitForProfit == 0)
         {              
            pnlPoints = (OrderOpenPrice() - price)/point;
            if (pnlPoints < TrailingStopPoints) continue; 
         }         
         if (sl - MinAdjustmentPoints*point <= newSl && sl != 0) continue;
         
         if(!OrderModify(OrderTicket(), OrderOpenPrice(), newSl, tp, 0))
         {
            printf("Error: Failed to modify trade. Ticket #%i, error code: %i", OrderTicket(), GetLastError());
            result = false;
            Sleep(__SLEEP_AFTER_EXECUTION_FAIL);
         }         
       }      
   }   
   return(result);
}
Yohana Parmi
3095
Yohana Parmi  
clinttaylor91:

Hey guys, 

Ive come up empty handed after searching the correct way to write my code so that it places pending orders a certain pip distance above the previous bars H n L. 

Ive seen similar questions but they weren't resolved and i can't find any documentation in the book about this specifically.

I have my the code working fine in regards to placing them at the H n L of the previous bar but i get errors when i try to alter the code with something like * point to get the order ex 10 pips above previous high.

so I've posted the code and a picture of an example. I tried change the lines around the iHigh symbols and iLow symbols but it generates lots of errors. The examples i found

were written different to mine so they don't work. Could anyone shed any light or is there more documentation on this topic anywhere? 


Thank you. 


Hi Clint,

I created a function for you, hope it useful :)

//+---------------------+
//|  Function BUY STOP  |
//+---------------------+
bool Buy_Stop(double xhigh,  //-- your previous high
              int xrange,    //-- pips range above the high
              double xlot,   //--lot size should be checked for minimum and maximum lot that allowed in trade
              int xsl,       //-- stoploss in pips
              int xtp,       //-- target in pips
              int xmagic,    //-- magic number
              string xlog,   //-- log comment in trade
              int xslippage, //-- slippage
              string xdesc)  //-- description : more detail in "Print()"
{
    ResetLastError();
    Print("* Opening Buy_Stop: ",xdesc," at ",xrange," pips above last high ",NormalizeDouble(xhigh, Digits));
    int Dgt;
    if (Digits==4) Dgt=1;
    else
    if (Digits==5||Digits==2||Digits==3) Dgt=10;
    
    double position=xhigh+(xrange*Dgt*Point);//--price at xrange pips above xhigh
    double target=position+(xtp*Dgt*Point);//--target at xtp pips above position
    double stop=position-(xsl*Dgt*Point);//--stoploss at xsl pips below position
    
    int ticket=OrderSend(Symbol(),OP_BUYSTOP,
               xlot, 
               NormalizeDouble(position,Digits), 
               xslippage,
               NormalizeDouble(stop,Digits),
               NormalizeDouble(target,Digits),
               xlog,xmagic,0,clrBlue);
     
     if(ticket<=0)
     { 
      Print("! Buy_Stop failed with error #",GetLastError());
      return(false);
     }
     else 
     { Print("* Position Buy_Stop ",xdesc," .. ticket #",ticket," placed successfully.");
       return(true);
     }
}

By that way, you can copy and make minor update for Sell Stop.

Kind regards,

Yohana

clinttaylor91
55
clinttaylor91  
Yohana Parmi:

Hi Clint,

I created a function for you, hope it useful :)

By that way, you can copy and make minor update for Sell Stop.

Kind regards,

Yohana


Wow thank you for the reply.

Fantastic work by the way. May i ask did you just come up with this from scratch or is this kind information referenced somewhere. 

Im so keen to learn how to program from scratch but it seems sooo difficult.


Thanks again. 

Yohana Parmi
3095
Yohana Parmi  
clinttaylor91:

Wow thank you for the reply.

Fantastic work by the way. May i ask did you just come up with this from scratch or is this kind information referenced somewhere. 

Im so keen to learn how to program from scratch but it seems sooo difficult.


Thanks again. 


Hi Clint,

Please tell me if you can't use that function, then I will explain it more detail with example how to call it :)

Btw, all about MQL4 is at https://docs.mql4.com

MQL4 Reference
MQL4 Reference
  • docs.mql4.com
MQL4 Reference
clinttaylor91
55
clinttaylor91  
Yohana Parmi:

Hi Clint,

Please tell me if you can't use that function, then I will explain it more detail with example how to call it :)

Btw, all about MQL4 is at https://docs.mql4.com


Yohana, 

I tried to implement the code you gave but no success. To be honesty i don't think i have any idea what i was doing ha,

I created the code to start using fx quant so that takes care of most of the layout for me as i don't know how to build from scratch yet. 


thanks 

Yohana Parmi
3095
Yohana Parmi  
clinttaylor91:

Yohana, 

I tried to implement the code you gave but no success. To be honesty i don't think i have any idea what i was doing ha,

I created the code to start using fx quant so that takes care of most of the layout for me as i don't know how to build from scratch yet. 


thanks 


Okay, please you can wait for a while, I am now writing code as example for more detail.

Kind regards

Yohana Parmi
3095
Yohana Parmi  
clinttaylor91:

Yohana, 

I tried to implement the code you gave but no success. To be honesty i don't think i have any idea what i was doing ha,

I created the code to start using fx quant so that takes care of most of the layout for me as i don't know how to build from scratch yet. 


thanks 


Hi Clint,

Here is more complete example for you,

Good luck :)

//+------------------------------------------------------------------+
//|                                                    For_Clint.mq4 |
//|                                           Copyright 2017, Yohana |
//+------------------------------------------------------------------+
#property copyright "Copyright 2017, Yohana"
#property link      "https://www.mql5.com/en/users/yohana/seller#products"
#property version   "1.00"
#property strict

//--- input parameters
input int MagicNo=0;//Magic Number
input double Lot=0.01;//Lot size
input int Slip=3;//Slippage
input int StopRange=10;//Pips to place stop order
input int TP=20;//Pips target
input int SL=20;//Pips stoploss
input string TradeLog="ClintTaylor91";//Trade Comment
input bool alert_hp=false;//Send trade notification to smartphone
input bool alert_email=false;//Send trade notification to email 

int ticket, Dgt;
double position, target, stop;
double newlot;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   CheckVolumeValue(Lot);
   if (Digits==4) Dgt=1;
   else
   if (Digits==5||Digits==2||Digits==3) Dgt=10;
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
   //--clear your screen when EA exit, etc.
  }

//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
  {
   //--- your criteria to place pending order
   if(............)       //<--write here for your criteria before placing buy_stop 
   {
     if(Buy_Stop(High[1],StopRange,newlot,SL,TP,MagicNo,TradeLog,Slip,"Your description"))
     {
       //--succeed
       //--send alert notification
     }
     else
     {
       //--failed
       //--send alert notification
     }
   }
   //---
   
  }//--end of OnTick

//+---------------------+ //|  Function BUY STOP  | //+---------------------+ bool Buy_Stop(double xhigh,  //-- your previous high               int xrange,    //-- pips above the high               double xlot,   //--lot size should be checked for minimum and maximum lot that allowed in trade               int xsl,       //-- stoploss in pips               int xtp,       //-- target in pips               int xmagic,    //-- magic number               string xlog,   //-- log comment in trade               int xslippage, //-- slippage               string xdesc)  //-- description more detail in "Print()" {     ResetLastError();     Print("* Opening Buy_Stop: ",xdesc," at ",xrange," pips above last high ",NormalizeDouble(xhigh, Digits));          position=xhigh+(xrange*Dgt*Point);//--price at xrange pips above xhigh     target=position+(xtp*Dgt*Point);//--target at xtp pips above position     stop=position-(xsl*Dgt*Point);//--stoploss at xsl pips below position          ticket=OrderSend(Symbol(),OP_BUYSTOP,            xlot,            NormalizeDouble(position,Digits),            xslippage,            NormalizeDouble(stop,Digits),            NormalizeDouble(target,Digits),            xlog,xmagic,0,clrBlue);           if(ticket<=0)      {       Print("! Buy_Stop failed with error #",GetLastError());       return(false);      }      else      { Print("* Position Buy_Stop ",xdesc," .. ticket #",ticket," placed successfully.");        return(true);      } }//--end of Buy_Stop

//+------------------------------------------------------------------+ //| Check the correctness of the order volume                        | //+------------------------------------------------------------------+ void CheckVolumeValue(double volume) { //--- minimal allowed volume for trade operations    double min_volume=SymbolInfoDouble(Symbol(),SYMBOL_VOLUME_MIN);    if(volume<min_volume)      {       if(alert_email==true) SendMail("Lot volume changed.","Lot volume has changed to "+DoubleToString(min_volume,2)+" as minimum volume that allowed by broker.");       if(alert_hp==true) SendNotification("Lot volume has changed to "+DoubleToString(min_volume,2)+" as minimum volume that allowed by broker.");       Print("Lot volume has changed to "+DoubleToString(min_volume,2)+" as minimum volume that allowed by broker.");       newlot=min_volume;      }    else      newlot=Lot; }//--end of CheckVolumeValue

whroeder1
15923
whroeder1  
Yohana Parmi: I created a function for you, hope it useful :)
    if (Digits==4) Dgt=1;
    else
    if (Digits==5||Digits==2||Digits==3) Dgt=10;
    
    double position=xhigh+(xrange*Dgt*Point);//--price at xrange pips above xhigh
Digits are 1,2,3,4,5. Has nothing to do with the definition of a PIP. Define PIP properly and your done. See adjusting SL, TP, and slippage; for 4/5 digit brokers and for JPY pairs.
Yohana Parmi
3095
Yohana Parmi  
whroeder1:
Digits are 1,2,3,4,5. Has nothing to do with the definition of a PIP. Define PIP properly and your done. See adjusting SL, TP, and slippage; for 4/5 digit brokers and for JPY pairs.

Thank you,

I just wanted to give a simpler way to make it easier for a beginner to understand, and it works :)

Your technique is good, expert and useful.

clinttaylor91
55
clinttaylor91  

I managed to get it working guys, works a charm


Thank you for all your help Yohana, i appreciate your work and thank you whroeder1! 

To add comments, please log in or register