EA CODING ISSUE/HELP - closes trades and open new, on new bar

 

Hi the EA needs to identify if a trade is currently running or not, im using CheckOpenOrders routine for this but when it is called in code its ignored. can anyone tell me what im doing wrong?

so the idea is that when each bar opens it checks if trade is open or not then it opens one if there is none, however it doesnt work as intended.... pls help!!!!!!!!!!!!

double price_ma_period_fast =7; //slow ema
double price_ma_period_slow =50; //fast ema  
double LotSize; //lotsize
double LotFactor = 1; //lotsize factor
double StopLoss=10; //stop loss
double TakeProfit=NULL; //take profit
int MagicNumber=1234; //magic
double pips = 0.01; //leave as default for 5 digit brokers
double adxthreshold = 28; //adx threshold - must be greater than this to trade
double adxperiod = 14; //adx period
double rsiperiod = 14; //rsi period
double rsiupper = 70; //rsi upper bound, wont buy above this value
double rsilower = 30; //rsi lower bound, wont sell below this value
int Tral_Stop=10;
//+------------------------------------------------------------------+
//| expert initialization function                                   |
//+------------------------------------------------------------------+
int init()
  {
//----

//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert deinitialization function                                 |
//+------------------------------------------------------------------+
int deinit()
  {
//----
   
//----
   return(0);
  }
//+------------------------------------------------------------------+
//| expert start function                                            |
//+------------------------------------------------------------------+
int start()
  {
//----
if(CheckOpenOrders() == true)
{
trail();
}
if(CheckOpenOrders() == false)
{
if(IsNewCandle())
{
trenddirection(); //find trend direction
logic(); //apply indicator logic
Lot_Volume(); //calc lotsize


buyorsell(); //trade - buy or sell
  return(0);
}
}
return(0);

}

//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//insuring its a new candle function
//+------------------------------------------------------------------+
bool IsNewCandle()
{
   static int BarsOnChart=0;
        if (Bars == BarsOnChart)
        return (false);
        BarsOnChart = Bars;
        return(true);
}
//+------------------------------------------------------------------+
//identifies the direction of the current trend
//+------------------------------------------------------------------+
bool trenddirection()
{

//----
double pricefastmanow,priceslowmanow;
pricefastmanow = iMA(Symbol(),0,price_ma_period_fast,0,MODE_EMA,PRICE_CLOSE,0);
priceslowmanow = iMA(Symbol(),0,price_ma_period_slow,0,MODE_EMA,PRICE_CLOSE,0);

if (pricefastmanow > priceslowmanow)// bullish
{
return(true);
}

if (pricefastmanow < priceslowmanow)// bearish
{
return(false);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////

return(0);
}
//+------------------------------------------------------------------+
//applies logic from indicators ADX and RSI to determine if we can trade
//+------------------------------------------------------------------+
int logic()
{
double adx,rsi;

adx = iADX(Symbol(),0,adxperiod,PRICE_CLOSE,MODE_MAIN,0);
rsi = iRSI(Symbol(),0,rsiperiod,PRICE_CLOSE,0);

if(adx > adxthreshold)
{

if(rsi > rsilower && rsi < rsiupper)

{

return(1);

}

}

return(0);

}
//+------------------------------------------------------------------+
//opens trades
//+------------------------------------------------------------------+
int buyorsell()
{
bool trenddirectionx, logicx;
int TicketNumber;
trenddirectionx = trenddirection();
logicx = logic();


if(CheckOpenOrders() == false)
{
if(trenddirectionx == true && logicx == 1 )

{

//buy

//TicketNumber = OrderSend(Symbol(),OP_BUY,LotSize,Ask,3,Ask-(StopLoss*pips),Ask+(TakeProfit*pips),NULL,MagicNumber,0,Green);
TicketNumber = OrderSend(Symbol(),OP_BUY,LotSize,Ask,3,Ask-(StopLoss*pips),NULL,NULL,MagicNumber,0,Green);

if( TicketNumber > 0 )
   {
   Print("Order placed # ", TicketNumber);
   }
else
   {
   Print("Order Send failed, error # ", GetLastError() );
   }


}
}
//else if(OrdersTotal() == 1)
//{
//return(0);
//}

if(CheckOpenOrders() == false)
{
if(trenddirectionx == false && logicx == 1 )
//sell
{

//TicketNumber = OrderSend(Symbol(),OP_SELL,LotSize,Bid,3,Bid+(StopLoss*pips),Bid-(TakeProfit*pips),NULL,MagicNumber,0,Red);
TicketNumber = OrderSend(Symbol(),OP_SELL,LotSize,Bid,3,Bid+(StopLoss*pips),NULL,NULL,MagicNumber,0,Red);
if( TicketNumber > 0 )
   {
   Print("Order placed # ", TicketNumber);
   }
else
   {
   Print("Order Send failed, error # ", GetLastError() );
   }

}
}
//else if(OrdersTotal() == 1)
//{
//return(0);
//}



return(0);

}

//+------------------------------------------------------------------+
//calculates lot size based on balance and factor
//+------------------------------------------------------------------+
double Lot_Volume()
{
double lot, riskpertrade, microlots;

riskpertrade=(AccountBalance()*0.01);
microlots=(riskpertrade/(StopLoss*0.0692));
lot=(microlots*0.01);
LotSize=lot;
   return(LotSize);
}

int trail()
{
   string Symb=Symbol();                        // Symbol
//------------------------------------------------------------------------------- 2 --
   for(int i=1; i<=OrdersTotal(); i++)          // Cycle searching in orders
     {
      if (OrderSelect(i-1,SELECT_BY_POS)==true) // If the next is available
        {                                       // Analysis of orders:
         int Tip=OrderType();                   // Order type
         if(OrderSymbol()!=Symb||Tip>1)continue;// The order is not "ours"
         double SL=OrderStopLoss();             // SL of the selected order
         //---------------------------------------------------------------------- 3 --
         while(true)                            // Modification cycle
           {
            double TS=Tral_Stop;                // Initial value
            int Min_Dist=MarketInfo(Symb,MODE_STOPLEVEL);//Min. distance
            if (TS < Min_Dist)                  // If less than allowed
               TS=Min_Dist;                     // New value of TS
            //------------------------------------------------------------------- 4 --
            bool Modify=false;                  // Not to be modified
            switch(Tip)                         // By order type
              {
               case 0 :                         // Order Buy
                  if (NormalizeDouble(SL,Digits)< // If it is lower than we want
                     NormalizeDouble(Bid-TS*Point,Digits))
                    {
                     SL=Bid-TS*Point;           // then modify it
                     string Text="Buy ";        // Text for Buy 
                     Modify=true;               // To be modified
                    }
                  break;                        // Exit 'switch'
               case 1 :                         // Order Sell
                  if (NormalizeDouble(SL,Digits)> // If it is higher than we want
                     NormalizeDouble(Ask+TS*Point,Digits)
                     || NormalizeDouble(SL,Digits)==0)//or equal to zero
                    {
                     SL=Ask+TS*Point;           // then modify it
                     Text="Sell ";              // Text for Sell 
                     Modify=true;               // To be modified
                    }
              }                                 // End of 'switch'
            if (Modify==false)                  // If it is not modified
               break;                           // Exit 'while'
            //------------------------------------------------------------------- 5 --
            double TP    =OrderTakeProfit();    // TP of the selected order
            double Price =OrderOpenPrice();     // Price of the selected order
            int    Ticket=OrderTicket();        // Ticket of the selected order
 
            Alert ("Modification ",Text,Ticket,". Awaiting response..");
            bool Ans=OrderModify(Ticket,Price,SL,TP,0);//Modify it!
            //------------------------------------------------------------------- 6 --
            if (Ans==true)                      // Got it! :)
              {
               Alert ("Order ",Text,Ticket," is modified:)");
               break;                           // From modification cycle.
              }
            //------------------------------------------------------------------- 7 --
            int Error=GetLastError();           // Failed :(
            switch(Error)                       // Overcomable errors
              {
               case 130:Alert("Wrong stops. Retrying.");
                  RefreshRates();               // Update data
                  continue;                     // At the next iteration
               case 136:Alert("No prices. Waiting for a new tick..");
                  while(RefreshRates()==false)  // To the new tick
                     Sleep(1);                  // Cycle delay
                  continue;                     // At the next iteration
               case 146:Alert("Trading subsystem is busy. Retrying ");
                  Sleep(500);                   // Simple solution
                  RefreshRates();               // Update data
                  continue;                     // At the next iteration
                  // Critical errors
               case 2 : Alert("Common error.");
                  break;                        // Exit 'switch'
               case 5 : Alert("Old version of the client terminal.");
                  break;                        // Exit 'switch'
               case 64: Alert("Account is blocked.");
                  break;                        // Exit 'switch'
               case 133:Alert("Trading is prohibited");
                  break;                        // Exit 'switch'
               default: Alert("Occurred error ",Error);//Other errors
              }
            break;                              // From modification cycle
           }                                    // End of modification cycle
         //---------------------------------------------------------------------- 8 --
        }                                       // End of order analysis
     }                                          // End of order search
//------------------------------------------------------------------------------- 9 --

return(0);
}
bool CheckOpenOrders(){
   //We need to scan all the open and pending orders to see if there is there is any
   //OrdersTotal return the total number of market and pending orders
   //What we do is scan all orders and check if they are of the same symbol of the one where the EA is running
   for( int i = 0 ; i < OrdersTotal() ; i++ ) {
      //We select the order of index i selecting by position and from the pool of market/pending trades
      OrderSelect( i, SELECT_BY_POS, MODE_TRADES );
      //If the pair of the order (OrderSymbol() is equal to the pair where the EA is running (Symbol()) then return true
      if( OrderSymbol() == Symbol() ) return(true);
   }
   //If the loop finishes it mean there were no open orders for that pair
   return(false);
}

            
 
ztmalick:

Hi the EA needs to identify if a trade is currently running or not, im using CheckOpenOrders routine for this but when it is called in code its ignored. can anyone tell me what im doing wrong?

so the idea is that when each bar opens it checks if trade is open or not then it opens one if there is none, however it doesnt work as intended.... pls help!!!!!!!!!!!!


Please try this :)

datetime previous_bar;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
    previous_bar=Time[0];
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
//---
   if(IsNewCandle(Time[0]))
  {
   //--your code here when get new candle.
  }
  else
  {
   //--your code here for otherwise.
  }
}

//+------------------------------------------------------------------+
bool IsNewCandle(datetime current_candle)
{
  if(Time[0]!=previous_bar) 
  {
     previous_bar=current_candle;
     return(true);    //-- send you new candle 
  }
  else
     return(false);
}//--IsNewCandle
 
Yohana Parmi:

Please try this :)


int OnInit()
  {
//---
    previous_bar=Time[0];
//---
   return(INIT_SUCCEEDED);
  }

You should avoid using anything like Time[] in OnInit as it may not be loaded/updated yet.

 
Keith Watford:

You should avoid using anything like Time[] in OnInit as it may not be loaded/updated yet.


yes, you're right :)

variable name is "previous" then I should write it as previous bar at [1],

I got mistake by [0] 

thank you :)

datetime previous_bar;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
    previous_bar=Time[1];
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
//| Expert tick function                                             |
//+------------------------------------------------------------------+
void OnTick()
{
//---
   if(IsNewCandle(Time[0]))
  {
   //--your code here when get new candle.
  }
  else
  {
   //--your code here for otherwise.
  }
}

//+------------------------------------------------------------------+
bool IsNewCandle(datetime current_candle)
{
  if(Time[0]!=previous_bar) 
  {
     previous_bar=current_candle;
     return(true);    //-- send you new candle 
  }
  else
     return(false);
}//--IsNewCandle
 
Yohana Parmi:

yes, you're right :)

variable name is "previous" then I should write it as previous bar at [1],

I got mistake by [0] 

thank you :)

int OnInit()
  {
//---
    previous_bar=Time[1];
//---
   return(INIT_SUCCEEDED);
  }

You should avoid using anything like Time[], Open[], Close[] etc in OnInit as it may not be loaded/updated yet.

 
Keith Watford:

You should avoid using anything like Time[], Open[], Close[] etc in OnInit as it may not be loaded/updated yet.


oh ... okay, I will do as you said.

thanks for your advise :)

Btw. function at IsNewCandle() still works, right?

because of initial value in previous_bar is different with current candle in OnTick()

bool IsNewCandle(datetime current_candle)
{
  if(Time[0]!=previous_bar) //-- will not equal when new candle to come
  {
     previous_bar=current_candle; //-- initial new time
     return(true);    //-- send you new candle 
  }
  else
     return(false);
}//--IsNewCandle
 
Yohana Parmi:

Btw. function at IsNewCandle() still works, right?

because of initial value in previous_bar is different with current candle in OnTick()

It depends whether you want to wait for a new bar before doing anything.

If you assign a value to previous_bar in OnInit, then it may be given the wrong value. In this case your code will "detect" a new bar when there isn't actually a new bar, but Time[0] has just updated.

I use a Global variable FirstTick and do all my checks in OnTick when FirstTick is true. When checks are completed I set FirstTick to false.

 
Keith Watford:

It depends whether you want to wait for a new bar before doing anything.

If you assign a value to previous_bar in OnInit, then it may be given the wrong value. In this case your code will "detect" a new bar when there isn't actually a new bar, but Time[0] has just updated.

I use a Global variable FirstTick and do all my checks in OnTick when FirstTick is true. When checks are completed I set FirstTick to false.


Yes, you're right,

I just lucky my function is works even I have a mistake at OnInit :))

I thought with easy logical that initial time at variable previous_bar should be different with time at current/running candle to come.

I just lucky :)

thanks

 
Yohana Parmi:

Yes, you're right,

I just lucky my function is works even I have a mistake at OnInit :))

I thought with easy logical that initial time at variable previous_bar should be different with time at current/running candle to come.

I just lucky :)

thanks


hi, thanks both for your help so far, i am also struggling to understand why the code when a trade is open and conditions for new trade are ok it closes the current trade and opens a new one on new bar?????

I want it to hold the trade until the the trailing stop is reached........any further help will be appreciated. 


Thanks.

 
Keith Watford:

It depends whether you want to wait for a new bar before doing anything.

If you assign a value to previous_bar in OnInit, then it may be given the wrong value. In this case your code will "detect" a new bar when there isn't actually a new bar, but Time[0] has just updated.

I use a Global variable FirstTick and do all my checks in OnTick when FirstTick is true. When checks are completed I set FirstTick to false.


hi, thanks for your help so far, i am also struggling to understand why the code when a trade is open and conditions for new trade are ok it closes the current trade and opens a new one on new bar?????

I want it to hold the trade until the the trailing stop is reached........any further help will be appreciated. 


Thanks.

 
ztmalick:

hi, thanks both for your help so far, i am also struggling to understand why the code when a trade is open and conditions for new trade are ok it closes the current trade and opens a new one on new bar?????

I want it to hold the trade until the the trailing stop is reached........any further help will be appreciated. 


Thanks.


hi, what is that meant your requirement to check on each new candle was solved by my code above?

I tried here, and it works.