What is wrong with this logic? Trailingstop for half position - page 2

 

I know what does it do, it gives me the number of the error i'm incurred into:) infact i made a mistake because it was mentioned inside the print function and put it twice is a useless mistake:)

I've read a guide taken on a forum about ordersend and orderselect, but i repeat, don't know why i'm wrong writing the way i did.

 
lemming78:

I know what does it do, it gives me the number of the error

No, it returns the error . . . . from the Documentation

"The function returns the last occurred error, then the value of special last_error variable where the last error code is stored will be zeroized. So, the next call for GetLastError() will return 0. "

You call it . . .

else
         {
         GetLastError();  
         

this returns the value of the error . . . but you don't store this value to a variable . . . so now it's gone . . . then . . . you call it again, and now it is zero . . .

         Print("Errore selezionamento " +GetLastError());  
         }
 

Ah ok thanks for clarifying...

Btw i solved the problem of tickes, though in a rough way. Now i have another problem:)

It modifies the stoploss (trailingstop) just one time after the trade opened, and i don't know how to reiterate the action. I mean, it's been told to me that everything in start() is recalled every tick, so the problem shouldn't exist.

Don't be bothered by so many prints please, they help me in finding which part of the code doesn't work properly.

//+------------------------------------------------------------------+
//|                                                  Momentum_v1.mq4 |
//|                                                             Skox |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Skox"
#property link      ""
#property indicator_separate_window

double Punto;
extern bool DisplayInfo=true;
extern string    S1 ="Lotti da aprire, minimo 0.02 ";
extern double Lotti=0.02;
extern string    S2 ="Numero posizioni massime. Minimo 2";
extern int NPosMax=2;
extern   double   TrailingStep = 5;
extern double TrailingStop = 15;
int result;

int TF,i;
string cmt;
int New_Bar;
bool NoTradeFlag;
datetime Time_0;


extern int MagicNumber=987569;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
Time_0=Time[0];

// Compatibility wiht 3,4,5 digits prices
   
   if(Digits>=4) Punto = 0.0001;
   else Punto = 0.01;

//----Gestione TimeFrame, =1 fino a 4h, =2 oltre
if (Period()<=240) TF=1;
else TF=2;
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
 //---Stampa informazioni su CHART
   void PrintInfo;
   {
   bool setupBAR;
   string cmt="";
      cmt = "========================";
      cmt =  cmt + "\nAccount Name: [ " + AccountName() + " ]";            
      cmt =  cmt + "\nAccount Leverage: [ " + DoubleToStr( AccountLeverage(), 0 ) + " ]";      
      cmt =  cmt + "\nMin Lot: [ " + DoubleToStr( MarketInfo(Symbol(),MODE_MINLOT), 3 ) + " ]";      
      cmt =  cmt + "\nLot Step: [ " + DoubleToStr( MarketInfo(Symbol(),MODE_LOTSTEP), 3 ) + " ]";      
      cmt =  cmt + "\nCurrent Profit: [ " + DoubleToStr(AccountEquity()-AccountBalance(),2) + " ]";
      cmt =  cmt + "\nAccount Balance: [ " + DoubleToStr(AccountBalance(),2) + " ]";
      cmt =  cmt + "\nAccount Equity: [ " + DoubleToStr(AccountEquity(),2) + " ]";      
      cmt =  cmt + "\nSetup Bar exist?:  " + setupBAR + " ";
      cmt =  cmt + "\n========================";
      Comment(cmt);
      }

//---Indicatori      
   double Atr=iATR(NULL,0,20,0);
   double fastMA=iMA(NULL,0,20,0,MODE_SMA,PRICE_CLOSE,0);
   double slowMA=iMA(NULL,0,40,0,MODE_SMA,PRICE_CLOSE,0);
   double Adx=iADX(NULL,0,14,PRICE_CLOSE,MODE_MAIN,0);

//---Funzione Buffer
  double buffer;
  if (TF==1) buffer=2*Punto;
  else buffer=0.001*Close[0];
  
//---Controlla se è nata una nuova candela
  New_Bar=0;                                           
    if (Time_0 != Time[0])                                  
      {
      New_Bar = 1; 
      NoTradeFlag=false;                                             
      Time_0 = Time[0]; 
      }
   
   
//--- Se setup bar esiste setupBAR=true, altrimenti false  

   if (Low[1]>fastMA && Low[1]>slowMA && Close[1]>Open[1] && Close[1]>(High[1]-Low[1])*0.7 && High[1]<High[iHighest(Symbol(),0,MODE_HIGH,5,1)] && (Close[1]-Open[1])<1.5*Atr && Adx>25) 
     {setupBAR = true;}
   else{setupBAR = false;}

//--- Se il targetprofit non viene raggiunto entro 5 candele, la posizione si chiude al close della 5°  
   double prezzo;
   datetime open= OrderOpenTime();
   
   if(OrderType()==OP_BUY) prezzo=Ask;
   else prezzo=Bid;
   
//---Gestione stoploss. Prima di piazzarlo in reale ricordarsi di cambiare 10 pips con MarketInfo(Symbol(),MODE_STOPLEVEL)
   double StopLoss=20*Punto;
   if(Close[1]-(Low[1]-buffer)<15*Punto)
   {StopLoss=Low[1]-15*Punto;}
   else StopLoss=(Low[1]-buffer);


//--- Controllo numero ordini
   double Spread=Bid-Ask;
   int ordtot=OrdersTotal();
   int ticket, ticketTL, ticketTL2;
//---Gestione TrailingStop. La variabile TrailingStop è external. Trailing è il nuovo livello di stoploss per ordini con trailingstop 
   double TSTP=TrailingStop*Punto;
   double Trailing;
   
//---Gestione ordini e modifica di trailingstop e targetprofit 
   if(ordtot<NPosMax)
     {
       if (setupBAR==true && NoTradeFlag==false)
         {
          /* ticket=OrderSend(Symbol(),OP_BUY,Lotti/2,prezzo,3,StopLoss,prezzo+Atr,"Momentum Method",MagicNumber,0);
             OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);
                if (ordtot>=1)
                  {
                    if(OrderTicket()==ticket)
                      { 
                        if (prezzo>(OrderOpenPrice()+Spread+10*Punto)) 
                          {
                           OrderModify(ticket,OrderOpenPrice(),OrderOpenPrice()+Spread,OrderTakeProfit(),0,Green);
                          }
                      }    
                  }*/
            ticketTL=OrderSend(Symbol(),OP_BUY,Lotti/2,prezzo,3,prezzo-15*Punto,0,"Momentum Method",MagicNumber,0);
            OrderSelect(ticketTL,SELECT_BY_TICKET,MODE_TRADES);
            Print("ordine aperto con ticket"+OrderTicket());
            ticketTL2=OrderTicket();
            Print("valore ticketTL"+ticketTL2);

         }
     }
  
    if (ordtot>=1)
       {
         if(OrderSelect(ticketTL2,SELECT_BY_TICKET,MODE_TRADES)==true)
         {
         Print("orderselect success   "+ticketTL2);
            
             if(prezzo - OrderOpenPrice() > TSTP &&  OrderStopLoss() <  StopLoss )
                 {  Print("condizioni spostamento ts ok");
                    OrderModify(OrderTicket(),OrderOpenPrice(),StopLoss,OrderTakeProfit(),0,Green);
                    Print ("Trailing stop modified at " +DoubleToStr(OrderStopLoss(),4));
                 }
             else{Print("condizioni non verificate");}
          }       
                                   
          
      }       
   
    
    
                              


                        
 
 
 
 
 }
  
                 
   

  
 
    if (ordtot>=1)
       {
         if(OrderSelect(ticketTL2,SELECT_BY_TICKET,MODE_TRADES)==true)
         {
         Print("orderselect success   "+ticketTL2);
            
             if(prezzo - OrderOpenPrice() > TSTP &&  OrderStopLoss() <  StopLoss )
                 {  Print("condizioni spostamento ts ok");
                    OrderModify(OrderTicket(),OrderOpenPrice(),StopLoss,OrderTakeProfit(),0,Green);
                    Print ("Trailing stop modified at " +DoubleToStr(OrderStopLoss(),4));
                 }
             else{Print("condizioni non verificate");}

/*


Here in this part you can make conditions for trailingstop modtfy    If orderstoploss >= orderopenprice and orderstoploss>.......



*/
          }       
                                   
          
      }       
 
deVries:


I'm sorry i thought i already wrote conditions in the previous post... what's wrong with them?

IF there is at least one order, IF ea can select successfully the order, IF there are some conditions (for TLS), modify the order with stoploss that goes up.

 
lemming78:


I'm sorry i thought i already wrote conditions in the previous post... what's wrong with them?

IF there is at least one order, IF ea can select successfully the order, IF there are some conditions (for TLS), modify the order with stoploss that goes up.

You select the order based on the ticket number . . .

if (ordtot>=1)
       {
         if(OrderSelect(ticketTL2,SELECT_BY_TICKET,MODE_TRADES)==true)

this is fine and works during the tick where you placed the order . . . . on the next tick the variable holding the ticket number is declared again and the previous value is lost. Making this variable static or globally declared might address your issue . . . . read your code through and see if it would work.

 
RaptorUK:

You select the order based on the ticket number . . .

this is fine and works during the tick where you placed the order . . . . on the next tick the variable holding the ticket number is declared again and the previous value is lost. Making this variable static or globally declared might address your issue . . . . read your code through and see if it would work.


Thanks Simon, didn't check that by my last post here

Selecting on ticket number can only be done if variable ticket number is declared at the beginning of the program before start( ) function

by using magicnumber and symbol you can select all the trades of the EA in a loop and if needed modify then

 
RaptorUK:

You select the order based on the ticket number . . .

this is fine and works during the tick where you placed the order . . . . on the next tick the variable holding the ticket number is declared again and the previous value is lost. Making this variable static or globally declared might address your issue . . . . read your code through and see if it would work.


GENIUS! i Solved it!... thanks
 

That problem was solved, but now sometimes it gives me an error

2012.03.16 13:27:00     2012.01.03 10:43  Momentum_v1 EURUSD,M15: unknown ticket 10 for OrderModify function

This is how i corrected it

//+------------------------------------------------------------------+
//|                                                  Momentum_v1.mq4 |
//|                                                             Skox |
//|                                                                  |
//+------------------------------------------------------------------+
#property copyright "Skox"
#property link      ""
#property indicator_separate_window

double Punto;
extern bool DisplayInfo=true;
extern string    S1 ="Lotti da aprire, minimo 0.02 ";
extern double Lotti=0.02;
extern string    S2 ="Numero posizioni massime. Minimo 2";
extern int NPosMax=2;
extern   double   TrailingStep = 5;
extern double TrailingStop = 15;
static int ticketTL, ticketTL2;

int TF,i;
string cmt;
int New_Bar;
bool NoTradeFlag;
datetime Time_0;


extern int MagicNumber=987569;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
Time_0=Time[0];

// Compatibility wiht 3,4,5 digits prices
   
   if(Digits>=4) Punto = 0.0001;
   else Punto = 0.01;

//----Gestione TimeFrame, =1 fino a 4h, =2 oltre
if (Period()<=240) TF=1;
else TF=2;
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
{
 //---Stampa informazioni su CHART
   void PrintInfo;
   {
   bool setupBAR;
   string cmt="";
      cmt = "========================";
      cmt =  cmt + "\nAccount Name: [ " + AccountName() + " ]";            
      cmt =  cmt + "\nAccount Leverage: [ " + DoubleToStr( AccountLeverage(), 0 ) + " ]";      
      cmt =  cmt + "\nMin Lot: [ " + DoubleToStr( MarketInfo(Symbol(),MODE_MINLOT), 3 ) + " ]";      
      cmt =  cmt + "\nLot Step: [ " + DoubleToStr( MarketInfo(Symbol(),MODE_LOTSTEP), 3 ) + " ]";      
      cmt =  cmt + "\nCurrent Profit: [ " + DoubleToStr(AccountEquity()-AccountBalance(),2) + " ]";
      cmt =  cmt + "\nAccount Balance: [ " + DoubleToStr(AccountBalance(),2) + " ]";
      cmt =  cmt + "\nAccount Equity: [ " + DoubleToStr(AccountEquity(),2) + " ]";      
      cmt =  cmt + "\nSetup Bar exist?:  " + setupBAR + " ";
      cmt =  cmt + "\n========================";
      Comment(cmt);
      }

//---Indicatori      
   double Atr=iATR(NULL,0,20,0);
   double fastMA=iMA(NULL,0,20,0,MODE_SMA,PRICE_CLOSE,0);
   double slowMA=iMA(NULL,0,40,0,MODE_SMA,PRICE_CLOSE,0);
   double Adx=iADX(NULL,0,14,PRICE_CLOSE,MODE_MAIN,0);

//---Funzione Buffer
  double buffer;
  if (TF==1) buffer=2*Punto;
  else buffer=0.001*Close[0];
  
//---Controlla se è nata una nuova candela
  New_Bar=0;                                           
    if (Time_0 != Time[0])                                  
      {
      New_Bar = 1; 
      NoTradeFlag=false;                                             
      Time_0 = Time[0]; 
      }
   
   
//--- Se setup bar esiste setupBAR=true, altrimenti false  

   if (Low[1]>fastMA && Low[1]>slowMA && Close[1]>Open[1] && Close[1]>(High[1]-Low[1])*0.7 && High[1]<High[iHighest(Symbol(),0,MODE_HIGH,5,1)] && (Close[1]-Open[1])<1.5*Atr && Adx>25) 
     {setupBAR = true;}
   else{setupBAR = false;}

//--- Se il targetprofit non viene raggiunto entro 5 candele, la posizione si chiude al close della 5°  
   double prezzo;
   datetime open= OrderOpenTime();
   
   if(OrderType()==OP_BUY) prezzo=Ask;
   else prezzo=Bid;
   
//---Gestione stoploss. Prima di piazzarlo in reale ricordarsi di cambiare 10 pips con MarketInfo(Symbol(),MODE_STOPLEVEL)
   double StopLoss=20*Punto;
   if(Close[1]-(Low[1]-buffer)<15*Punto)
   {StopLoss=Low[1]-15*Punto;}
   else StopLoss=(Low[1]-buffer);


//--- Controllo numero ordini
   double Spread=Bid-Ask;
   int ordtot=OrdersTotal();
   int ticket;
//---Gestione TrailingStop. La variabile TrailingStop è external. Trailing è il nuovo livello di stoploss per ordini con trailingstop 
   double TSTP=TrailingStop*Punto;
  // double Trailing;
   
//---Gestione ordini e modifica di trailingstop e targetprofit 
   if(ordtot<NPosMax)
     {
       if (setupBAR==true && NoTradeFlag==false)
         {
           ticket=OrderSend(Symbol(),OP_BUY,Lotti/2,prezzo,3,StopLoss,prezzo+Atr,"Momentum Method",MagicNumber,0);
             OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES);
               
            ticketTL=OrderSend(Symbol(),OP_BUY,Lotti/2,prezzo,3,prezzo-TSTP,0,"Momentum Method",MagicNumber,0);
            OrderSelect(ticketTL,SELECT_BY_TICKET,MODE_TRADES);
            Print("ordine aperto con ticket"+OrderTicket());
            ticketTL2=OrderTicket();
            Print("valore ticketTL"+ticketTL2);

         }
     }
  
    if (ordtot>=1)
       {
         if(OrderSelect(ticketTL2,SELECT_BY_TICKET,MODE_TRADES)==true)
         {
           if(prezzo - OrderOpenPrice() > TSTP &&  OrderStopLoss() <  StopLoss )
                 { 
                    OrderModify(OrderTicket(),OrderOpenPrice(),StopLoss,OrderTakeProfit(),0,Green);
                    Print ("Trailing stop modified at " +DoubleToStr(OrderStopLoss(),4));
                 }
            
          }       
                                   
          
      }       
        if (ordtot>=1)
       {
         if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)==true)
         {
           if(prezzo - OrderOpenPrice() > 10*Punto )
                 {  
                    OrderModify(OrderTicket(),OrderOpenPrice(),OrderOpenPrice()+buffer,OrderTakeProfit(),0,Green);
                    Print ("Trailing stop modified at " +DoubleToStr(OrderStopLoss(),4));
                 }
          
          }       
                                   
          
      }       
   
}