Need help with this "trail to breakeven" code

 

Hello Dear Friends,

I need help with the code below. I have included "if(Bars>BarsCounted)......BarsCounted=Bars" condition to trade only at the close of bars, this is OK, however the piece of code commented as Breakeven (blue part) also works at the close of bars, even though I have written it outside the "if(Bars>BarsCounted)......BarsCounted=Bars" condition. I want this piece of code to trail the SL to breakeven at every tick. When it moves the SL to breakeven, it must stop functioning and I will trail the SL with another method then. With this code, it only moves the SL to breakeven at the close of the bars. Any suggestions?

Thank you

...

extern int MAperiod=21;
extern int FilterMAperiod=200;
extern int ATRPeriod=14;
extern double SL_ATR_Factor=1.2;
extern int MinBreakEvenMove=15;
extern double orderleverage=1.0; //Leverage to use per order
extern int FirstSessionStart= 8;
extern int FirstSessionEnd= 12;
extern int SecondSessionStart= 16;
extern int SecondSessionEnd= 21;
int BarsCounted=0; //Global variable for trading once per bar, not per tick.

//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
if (Bars>BarsCounted) //The first part of the condition to trade once per bar, not per tick.
{
double closeprice = Close[1];
double openprice = Open[1];
double barbody = MathAbs(closeprice - openprice);
double Norm_MA = NormalizeDouble(iMA(NULL, 0, MAperiod, 0, MODE_SMA, PRICE_CLOSE, 1), Digits);
double FilterMA = iMA(NULL, 0, FilterMAperiod, 0, MODE_SMA, PRICE_CLOSE, 1);
double ATR= NormalizeDouble(iATR(NULL, 0, ATRPeriod, 1), Digits);
double Lots = NormalizeDouble((AccountBalance()/10000.0*orderleverage), 2);
double Stoploss= NormalizeDouble(ATR*SL_ATR_Factor, Digits);
if (OrdersTotal() < 1 && ((TimeHour(TimeCurrent()) >= FirstSessionStart && TimeHour(TimeCurrent()) <= FirstSessionEnd) || (TimeHour(TimeCurrent()) >= SecondSessionStart && TimeHour(TimeCurrent()) <= SecondSessionEnd)))
{
if (closeprice > Norm_MA && closeprice > openprice && barbody >= ATR && openprice < Norm_MA + ATR) OrderSend(Symbol(), OP_BUY, Lots, NormalizeDouble(Ask, Digits), 1, NormalizeDouble((Ask - barbody*SL_ATR_Factor*SL_ATR_Factor), Digits), NormalizeDouble((Ask + 1.5*barbody*SL_ATR_Factor), Digits),"1", 1, Blue);
if (closeprice < Norm_MA && closeprice < openprice && barbody >= ATR && openprice > Norm_MA - ATR) OrderSend(Symbol(), OP_SELL, Lots, NormalizeDouble(Bid, Digits), 1, NormalizeDouble((Bid + barbody*SL_ATR_Factor*SL_ATR_Factor), Digits), NormalizeDouble((Bid - 1.5*barbody*SL_ATR_Factor), Digits),"1", 1, Red);


BarsCounted=Bars; //Second part of the condition to trade once per bar, not per tick.

//Breakeven:

int cnt, total = OrdersTotal();
double BreakEven;
if (ATR < MinBreakEvenMove/10000.0) BreakEven=MinBreakEvenMove/10000.0;
else BreakEven=ATR;
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);

if (OrderMagicNumber()==1 && OrderStopLoss() != OrderOpenPrice())
{
if (OrderType()==OP_BUY)
{
if (Close[0] >= BreakEven+OrderOpenPrice()) OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0,Green);

}
else if (OrderType()==OP_SELL)
{
if (Close[0] <= OrderOpenPrice()-BreakEven) OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0,Yellow);
}
}
}
}
//----
return(0);
}
//+------------------------------------------------------------------+

 

Use a function like this to identify newbars...

//+------------------------------------------------------------------+
//  NEW BAR FUNCTION
//+------------------------------------------------------------------+
   // Identify new bars
   bool Fun_New_Bar()
      {
      static datetime New_Time = 0;
      bool New_Bar = false;
      if (New_Time!= Time[0])
         {
         New_Time = Time[0];
         New_Bar = true;
         }
      return(New_Bar);
      }

Then in start()

New_Bar=Fun_New_Bar();
   if (New_Bar)
      {
      // Actions on new bar
      }

By setting the variable, you can step in and out of newbar and current tick without running the function every time.

hth

V

 
Viffer:

Use a function like this to identify newbars...

Then in start()

By setting the variable, you can step in and out of newbar and current tick without running the function every time.

hth

V


THank you for your interest Viffer!
 

It seems to work now, but I get millions of "OrderModify Error 1" with the code below. What may be the reason?

int cnt, total = OrdersTotal();
double BreakEven;
if (ATR < MinBreakEvenMove/10000.0) BreakEven=MinBreakEvenMove/10000.0;
else BreakEven=ATR;
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);

if (OrderMagicNumber()==1)
{
if (OrderType()==OP_BUY && OrderStopLoss() < OrderOpenPrice())
{
if (Close[0] >= BreakEven+OrderOpenPrice()) OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0,Green);

}
else if (OrderType()==OP_SELL && OrderStopLoss() > OrderOpenPrice())
{
if (Close[0] <= OrderOpenPrice()-BreakEven) OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0,Yellow);
}
}
}

 
savastekin:

It seems to work now, but I get millions of "OrderModify Error 1" with the code below. What may be the reason?

.....



https://book.mql4.com/trading/ordermodify


Book:

If you pass unchanged values as the function parameters, the terminal will generate error 1 (ERR_NO_RESULT).

V

 

Thank you...

 

Ok guys. I have the same problem.

Do you know whether there is a solution ?

Thanks

Pablo

 
Post your code, be specific about your problem, even better create a new thread about YOUR issues.
 
savastekin:
I need help with the code below. I have included "if(Bars>BarsCounted)......BarsCounted=Bars" condition to trade only at the close of bars,
I want this piece of code to trail the SL to breakeven at every tick.
  1. or attach large files
  2. Bars is unreliable (won't change when you reach max bars in chart.) Volume is unreliable (you can miss ticks) Always use time.
    int start(){
       static datetime Time0;
       bool newBar = (Time0 != Time[0]);  Time0 = Time[0];

    I don't use a function here because it can only be called once per tick, (subsequent calls will always return false.) Alternatively:

    int start(){
       static datetime Time0;
       if (Time0 == Time[0]) return;  Time0 = Time[0];

    if (Close[0] <= OrderOpenPrice()-BreakEven)
      OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice(),OrderTakeProfit(),0,Yellow);
    This is not correct. For a sell you must place stops at the ask price. you're setting it to OOP (a bid price) Add the spread.
  3. Always test return codes (orderSelect AND orderModify.) You MUST count down in the presence of multiple orders (multiple charts.) Doubles rarely compare equal.
    //for(cnt=0;cnt<total;cnt++)
    //{
    //OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
    //if (OrderMagicNumber()==1 && OrderStopLoss() != OrderOpenPrice())
        for(pos = OrdersTotal()-1; pos >= 0 ; pos--) if (
            OrderSelect(pos, SELECT_BY_POS)                 // Only my orders w/
        &&  OrderMagicNumber()  == magic.number             // my magic number
        &&  OrderSymbol()       == Symbol() ){              // and my pair.
    
  4. Don't keep moving it to the same position (error 1)
    if (Close[0] <= OrderOpenPrice()-BreakEven
       && OrderStopLoss() > OrderOpenPrice() + spread)