Trailing stop only works with OrderSelect Error

 

Hello this is my first post. I've been passively reading these forums for 3 month now.... :) But this problem I just can't fix alone and it drives me insane ... ^^

My Expert Advisor should set Trailingstops according to calculated Fibonachi levels. However it seems that the trailing stop is only working, when the OrderSelect after "if(Ticket>0){" produces an error. I find that very confusing, because when the OrderSelect is working the conditions for setting Trailingstops are just ignored or whatever and without this OrderSelect the trailing stop isn't working either.... And second, the trailing stops for the sell orders never work.

I would be happy if some expert is looking into this and can give me any advice... :)

Here is the code, first the included OrderInitiation file and after that the main logic from my EA:

// ...zeroize variables... //
void OneOrderInit( int magic )
{
    int _GetLastError, _OrdersTotal = OrdersTotal()
// ...zeroize variables again... // 

    for ( int z = _OrdersTotal - 1; z >= 0; z -- )
    {
        if ( !OrderSelect( z, SELECT_BY_POS) )
        {
          _GetLastError = GetLastError();
          Print("OrderSelect( ", z, ", SELECT_BY_POS ) - Error #", 
                _GetLastError );
          continue;
        }
        if(OrderMagicNumber() == magic && OrderSymbol() == Symbol())
        {
          _Ticket    = OrderTicket();
          _Type      = OrderType();
          _Lots      = NormalizeDouble( OrderLots(), 1 );
          _OpenPrice = NormalizeDouble( OrderOpenPrice(), Digits);
          _StopLoss = NormalizeDouble( OrderStopLoss(), Digits);
          _TakeProfit = NormalizeDouble( OrderTakeProfit(), Digits);
          _OpenTime   = OrderOpenTime();
          _Profit     = NormalizeDouble( OrderProfit(), 2 );
          _Swap       = NormalizeDouble( OrderSwap(), 2 );
          _Commission = NormalizeDouble( OrderCommission(), 2 );
          _Comment    = OrderComment();
          _Expiration = OrderExpiration();
          return;
        }
    }
}

#include <OneOrderControl.mqh>

extern int slippage = 4;
extern double Lots = 2;
///////////////////////
int ThisBarTrade =  0;
int  magicNumber = 1122;
//+----------------------------------------------------------------------+
extern double SL_S=27;
extern double TP_S=33;
extern double SL_B=27;
extern double TP_B=33;
extern double StopLevel=25;
double newSL_S, newSL_B;
//+----------------------------------------------------------------------+
void StopLevelFiboSell()
  {
  -->sets newSL_S based on FiboLevels
  }
  
void StopLevelFiboBuy()
  {
  -->same
  }
//+------------------------------------------------------------------+
  void Op_Buy_Ch()
  {
   if(!OrderSend(NULL,OP_BUY,Lots,Ask,slippage,Bid-SL_B*Point,Ask+TP_B*Point," ",magicNumber,0,Blue))
     {Print("  SELL order opening error  # ",GetLastError());}
  }
//+------------------------------------------------------------------+
  void Op_Sell_Ch()
  {
   if(!OrderSend(NULL,OP_SELL,Lots,Bid,slippage,Ask+SL_S*Point,Bid-TP_S*Point," ",magicNumber,0,Red))
     {Print("  SELL order opening error  # ",GetLastError());
  }
  }
//+------------------------------------------------------------------+
void Modyf_S_lot()
  {
   if(!OrderModify(_Ticket,_OpenPrice,newSL_S,
      _TakeProfit,0,Aqua))
     {Print(" Modif.ord. Sell# ",_Ticket," Error # ",GetLastError());}return;
  }
// ----------------------------------------------------------------------+
void Modyf_B_lot()
  {
   if(!OrderModify(_Ticket,_OpenPrice,newSL_B,
      _TakeProfit,0,Aqua))
     {Print(" Modif.ord. Buy# ",_Ticket,"Error # ",GetLastError());}return;
  }
//+----------------------------------------------------------------------+
void OnTick()
  {
  int _GetLastError = 0;

  OneOrderInit(magicNumber);

   if (Bars!=ThisBarTrade)
   {
   ThisBarTrade = Bars;                                           //ensure only one trade opportunity per bar
     if (_Ticket>0)                                               //if order is open 
     {
        if(!OrderSelect(1,SELECT_BY_POS,MODE_TRADES))             // << trailing stop only works, when Error
        {Print("Order selection error = ",GetLastError());

        if(_Type == OP_BUY)
        {
                  // ----------------------------------------------------------------------+
                  if((High[1]-_OpenPrice)>=SL_B*Point && _Lots==Lots)Close_B_lot();
                  // ----------------------------------------------------------------------+
                  if((High[1]-_OpenPrice)/Point>=100 && _StopLoss<_OpenPrice)
                    {
                     Print("StopLoss shift #1");
                     if(!OrderModify(_Ticket,_OpenPrice,_OpenPrice+2*Point,
                        _TakeProfit,0,Aqua))
                       {Print(" at Modif.ord. 1 buy# ",_Ticket," Error # ",GetLastError());}return;
                    }
                  // ----------------------------------------------------------------------+
                                        --> next shift, etc
                  //+----------------------------------------------------------------------+
        }
        if(_Type == OP_SELL)
        {
                if((_OpenPrice-Low[1])>=SL_S*Point && OrderLots()==Lots)Close_S_lot();
                  // ----------------------------------------------------------------------+
                  if((_OpenPrice-Low[1])/Point>=100 && OrderLots()==Lots && _StopLoss>_OpenPrice)
                    {
                     if(!OrderModify(_Ticket,_OpenPrice,_OpenPrice-2*Point,_TakeProfit,0,Aqua))
                       {Print(" at Modif.ord. 1 sell# ",_Ticket," Error # ",GetLastError());}return;
                    }
                  // -----------------------------------------------------------------------+
                                            --> next shift etc. 
                  //+----------------------------------------------------------------------+
        }     
    } else 
      {
         if(condition for entry) 
         {
               [...]
         Op_Buy_Ch();
               [...]
         Op_Sell_Ch();
         }
      } return;
   } return;
  }
 
     if (_Ticket>0)                                               //if order is open 
     {
        if(!OrderSelect(1,SELECT_BY_POS,MODE_TRADES))             // << trailing stop only works, when Error
        {Print("Order selection error = ",GetLastError());

_Ticket what value does it have ??

why do you select 1 inside

OrderSelect(1,SELECT_BY_POS,MODE_TRADES)

without doing an orderloop. What is according to you happening at

if(!OrderSelect(1,SELECT_BY_POS,MODE_TRADES))

can you check also the OrderTicket() if you select 1 ??

 
OrderSelect(1,SELECT_BY_POS

This selects the second opened order (any EA/manual trades, any pair, any magic number.) If you only have one (or zero) opened this will fail.

If you already have the order data saved why do you need to select it again? Maybe to check if the order has closed (TP/SL) before modifying? Why not call your function (OneOrderInit) or select by ticket not position.

OneOrderInit should return a boolean (either if found an order or it doesn't,) or it should set _Ticket to zero.

 
deVries:

_Ticket what value does it have ??

_Ticket has the value 1 when initialised.
deVries:

why do you select 1 inside

without doing an orderloop. What is according to you happening at

if(!OrderSelect(1,SELECT_BY_POS,MODE_TRADES))

can you check also the OrderTicket() if you select 1 ??

1 could be replaced with any number greater than 1 but not 0. When I choose 0 inside the OrderSelect the trailing stop does not work. The OrderTicket() is 0 if I select 1. The strange thing is that the trailing stop only works when I do the second OrderSelect with number>0 and it is bool = false every time...
WHRoeder:

This selects the second opened order (any EA/manual trades, any pair, any magic number.) If you only have one (or zero) opened this will fail.

If you already have the order data saved why do you need to select it again? Maybe to check if the order has closed (TP/SL) before modifying? Why not call your function (OneOrderInit) or select by ticket not position.

OneOrderInit should return a boolean (either if found an order or it doesn't,) or it should set _Ticket to zero.

The thing is: I don't know why I need to select it again... simply when I don't do it, the OrderModify will not work which means it doesn't change the stoploss.

I want my trailing stop to work without a second OrderSelect. Maybe it hast to do something with zeroizing the _Ticket every time the OneOrderInit() function gets called? I tried everything from not zeroizing _Ticket to putting loops before and after thie _Ticket > 0 condition.. nothing worked. Also it is maybe important to mention that my EA should only place one order at a time, that is why I need the (Ticket > 0) { ... } else { ...}

 
dignitas123:
_Ticket has the value 1 when initialised.

if you test it with strategytester the first trade might be opend with orderticketnumber 1 but that will be only the first trade of your EA

if you place this EA yours on demo account you won't find here the value 1

dignitas123:
1 could be replaced with any number greater than 1 but not 0. When I choose 0 inside the OrderSelect the trailing stop does not work. The OrderTicket() is 0 if I select 1.

The problem is you don't understand the code in this line

OrderSelect(1,SELECT_BY_POS,MODE_TRADES)

that 1 in this line is not an orderticketnumber because the open trades are SELECT_BY_POS

if there is only one trade open then that trade has position 0 if you SELECT_BY_POS

See also the comment of WHRoeder

 

this what i can suggest for your trailing problems


//+------------------------------------------------------------------+





#property version   "1.00"

#property strict



bool     ProfitTrailing                   = true;

extern   int     TrailingStop             = 20;  //Pips

int      TrailingStep                     = 1;   //Pips

bool     UseSound                         = true;

string   NameFileSound                    = "expert.wav";

double   pBid, pAsk, pp;



//+------------------------------------------------------------------+

//| Expert initialization function                                   |

//+------------------------------------------------------------------+

int OnInit()

  {

//---

   

//---

   return(INIT_SUCCEEDED);

  }

//+------------------------------------------------------------------+

//| Expert deinitialization function                                 |

//+------------------------------------------------------------------+

void OnDeinit(const int reason)

  {

//---

   

  }

//+------------------------------------------------------------------+

//| Expert tick function                                             |

//+------------------------------------------------------------------+

void OnTick()

  {

//---

Trail();

  }

//+------------------------------------------------------------------+

//=========================================

void Trail()

//==========================================

  {

   for(int i=0; i<OrdersTotal(); i++)

     {

      if(OrderSelect(i, SELECT_BY_POS, MODE_TRADES))

        {

         TrailingPositions();

        }

     }

  }

//+------------------------------------------------------------------+

//| Ñîïðîâîæäåíèå ïîçèöèè ïðîñòûì òðàëîì                             |

//+------------------------------------------------------------------+

void TrailingPositions()

  {

   pp = MarketInfo(OrderSymbol(), MODE_POINT);

   if(OrderType()==OP_BUY && OrderSymbol()==Symbol())

     {

      pBid = MarketInfo(OrderSymbol(), MODE_BID);

      if(!ProfitTrailing || (pBid-OrderOpenPrice())>TrailingStop*pp)

        {

         if(OrderStopLoss()<pBid-(TrailingStop+TrailingStep-1)*pp)

           {

            ModifyStopLoss(pBid-TrailingStop*pp);

           }

        }

     }

   if(OrderType()==OP_SELL && OrderSymbol()==Symbol())

     {

      pAsk = MarketInfo(OrderSymbol(), MODE_ASK);

      if(!ProfitTrailing || OrderOpenPrice()-pAsk>TrailingStop*pp)

        {

         if(OrderStopLoss()>pAsk+(TrailingStop+TrailingStep-1)*pp || OrderStopLoss()==0)

           {

            ModifyStopLoss(pAsk+TrailingStop*pp);

           }

        }

     }

  }



//+------------------------------------------------------------------+

//+------------------------------------------------------------------+

void ModifyStopLoss(double ldStopLoss)

  {

   bool fm;



   fm=OrderModify(OrderTicket(),OrderOpenPrice(),ldStopLoss,OrderTakeProfit(),0,CLR_NONE);

   if(fm && UseSound)

      PlaySound(NameFileSound);

  }



//+------------------------------------------------------------------+


Discover new MetaTrader 5 opportunities with MQL5 community and services
Discover new MetaTrader 5 opportunities with MQL5 community and services
  • 2021.02.26
  • www.mql5.com
MQL5: language of trade strategies built-in the MetaTrader 5 Trading Platform, allows writing your own trading robots, technical indicators, scripts and libraries of functions
 
Please edit your post and use the code button (Alt+S) when pasting code.

EDIT your original post, please do not just post the code correctly in a new post.

Please do not bring up a topic that is nearly 7 years old for no good reason.

Reason: