Download MetaTrader 5

Close all opening orders with EA

To add comments, please log in or register
They are already making profit using the Market. You can join them!
Minh
140
Minh 2014.03.25 04:56 

Hi guy. Can someone help me out?

So when I call the "sell" function, I want to place 1 sell order and then close all the currently opening order (if any). But somehow, with this code, the system doesn't close the currently running "buy" order.

void sell()
{
   int ticket = OrderSend(Symbol(), OP_SELL, volume, Bid, Slippage, 0, 0, "",magic,0,clrNONE);
   if(ticket<0)
     {
      Print("OrderSend failed when try to SELL with error #",GetLastError());
     }
   else
   {
      Print("OrderSend placed successfully");
      int PositionIndex;
      int TotalNumberOfOrders;
      TotalNumberOfOrders = OrdersTotal(); 

//    Close all buy open order
      for(PositionIndex = TotalNumberOfOrders - 1; PositionIndex >= 0 ; PositionIndex --)
         {
         if( ! OrderSelect(PositionIndex, SELECT_BY_POS, MODE_TRADES) ) continue;
   
         if( OrderMagicNumber() == magic
            && OrderSymbol() == Symbol()
            && OrderType() == OP_BUY)
            {
               if ( ! OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(), Slippage ) )
               {
               Print("Order Close failed when try to close "buy order", order number: ", OrderTicket(), " Error: ", GetLastError() );
               }
            }
         }
   }
}
SYED NAUFAL GADDAFI
1401
SYED NAUFAL GADDAFI 2014.03.25 06:45  

Try this ...

//    Close all buy open order
   for(PositionIndex=TotalNumberOfOrders-1; PositionIndex>=0; PositionIndex --)
     {
      if(OrderSelect(PositionIndex,SELECT_BY_POS,MODE_TRADES))
        {
         if(OrderMagicNumber()==magic && OrderSymbol()==Symbol() && OrderType()==OP_BUY)
           {
            if(!OrderClose(OrderTicket(),OrderLots(),OrderClosePrice(),Slippage))
              {
               Print("Order Close failed when try to close "buy order", order number: ",OrderTicket()," Error: ",GetLastError());
              }
           }
        }
     }

I think the culprit is the OrderSelect function, so I have adjusted it a little bit.

Not tested though.

Tjipke de Vries
6315
Tjipke de Vries 2014.03.25 08:07  
nguye235:

But somehow, with this code, the system doesn't close the currently running "buy" order.

               if ( ! OrderClose( OrderTicket(), OrderLots(), OrderClosePrice(), Slippage ) )
               {
               Print("Order Close failed when try to close "buy order", order number: ", OrderTicket(), " Error: ", GetLastError() );
               }

?? What kind of error(s) do you have,.... moments it fails ??

Print("Order Close failed when try to close "buy order", order number: ", OrderTicket(), " Error: ", GetLastError() );

is this correct ??

or has it to be

Print("Order Close failed when try to close buy order, order number: ", OrderTicket(), " Error: ", GetLastError() );
Minh
140
Minh 2014.03.27 22:01  

Thanks guy I think I found out where the problem is.. sort of. It never close any order because it never got executed.

//--- input parameters
#define magic  2049485321
extern double   volume=0.5;
extern int      Slippage=10;
extern int      MA_Period=20;
extern int      MA_Shift=0;
extern int      MA_Method=0;
extern int      Contract_Step=150;
extern int      Precision=10;
extern int      Shift_Bars=1;
double ExtMapBuffer[];
int ExtCountedBars=0;
int count;
bool current;
double v1[];
double v2[];
double val1;
double val2;
//+------------------------------------------------------------------+
//| Expert initialization function                                   |
//+------------------------------------------------------------------+
int OnInit()
  {
//---
   SetIndexBuffer(0,ExtMapBuffer);
//---
   return(INIT_SUCCEEDED);
  }
//+------------------------------------------------------------------+
//| Expert deinitialization function                                 |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
  {
//---
   
  }
//+------------------------------------------------------------------+
int start()
  {
   if(Bars<=MA_Period) 
   {return(0);}
   ExtCountedBars=IndicatorCounted();
//---- check for possible errors
   if (ExtCountedBars<0) {
//Somehow, things got stuck right here. function return -1 and the rest of the start function never got executed
   return(-1);}
//---- last counted bar will be recounted
   if (ExtCountedBars>0) ExtCountedBars--;
//Do some more stuff
   
   

I don't know why does the IndicatorCounted() keep return -1.

Tjipke de Vries
6315
Tjipke de Vries 2014.03.27 22:43  
nguye235:

Thanks guy I think I found out where the problem is.. sort of. It never close any order because it never got executed.

I don't know why does the IndicatorCounted() keep return -1.


So you wanna place trades with an ...... indicator

That was before build 625 never possible...

and if it is right then also with the build 625 it might be not possible

IndicatorCounted

The function returns the amount of bars not changed after the indicator had been launched last.

int IndicatorCounted();

Returned value

The amount of bars not changed after the indicator had been launched last.

Simon Gniadkowski
Moderator
18001
Simon Gniadkowski 2014.03.27 23:09  
nguye235:

Thanks guy I think I found out where the problem is.. sort of. It never close any order because it never got executed.

I don't know why does the IndicatorCounted() keep return -1.

Is this an Indicator or EA ? Indicators cannot trade, EAs can't use Indicator specific functions . . .
Minh
140
Minh 2014.03.28 00:25  

Oh yes. I have create an indicator before. Basically, what it does it

if(condition1)
{
Alert("buy");
}else{
Alert("sell");
}

now I want it to do the trading automatically so I just copy and paste the code from my indicator. Is this kind of thinking correct? Sorry, just a newbie :P

if(condition1)
{
buy();
}else{
sell();
}
whroeder1
14514
whroeder1 2014.03.28 01:03  
nguye235: Oh yes. I have create an indicator before. Basically, what it does it ..

Oh no you haven't. You created an EA that READ indicator values.

Indicators can not wait, therefor Indicators cannot trade, EAs can't use Indicator specific functions .

SYED NAUFAL GADDAFI
1401
SYED NAUFAL GADDAFI 2014.03.28 01:52  

Indicator = Gives info only

EA = Uses captured info from Indicator (if any) and determine what to do next

Minh
140
Minh 2014.03.28 03:25  

hmm interesting. In my past indicator, I calculate the Support and Resistance of the market. That's why I need those "indicator" function. After a while, I discover a function call "iCustom" which can return a value from an indicator. Does anyone know how this work? If it works like the way I think it is, then my life would be much more simpler. For example, if this file is in my directory. (File can be downloaed from https://www.mql5.com/en/code/7530 )

//+------------------------------------------------------------------+
//|                SuperSR 6.mq4                                     |
//|                Copyright © 2006  Scorpion@fxfisherman.com        |
//+------------------------------------------------------------------+
#property copyright "FxFisherman.com"
#property link      "http://www.fxfisherman.com"
//----
#property indicator_chart_window
#property indicator_buffers 2
#property indicator_color1 clrRed
#property indicator_color2 clrBlue
//----
extern int Contract_Step=150;
extern int Precision=10;
extern int Shift_Bars=1;
//---- buffers
double v1[];
double v2[];
double val1;
double val2;
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int init()
  {
   IndicatorBuffers(2);
   SetIndexArrow(0, 159);
   SetIndexStyle(0,DRAW_ARROW,STYLE_SOLID,1,Red);
   SetIndexDrawBegin(0,-1);
   SetIndexBuffer(0, v1);
   SetIndexLabel(0,"Resistance");
   //
   SetIndexArrow(1, 159);
   SetIndexStyle(1,DRAW_ARROW,STYLE_SOLID,1,Blue);
   SetIndexDrawBegin(1,-1);
   SetIndexBuffer(1, v2);
   SetIndexLabel(1,"Support");
   //  
   watermark();
//-----
   return(0);
  }
//+------------------------------------------------------------------+
//|                                                                  |
//+------------------------------------------------------------------+
int start()
  {
   double gap;
   double contract=(Contract_Step + Precision) * Point;
   int i=Bars-5-Shift_Bars;
   int shift;
   bool fractal;
   double price;
   while(i>=0)
     {
      shift=i + Shift_Bars;
      // Resistance
      price=High[shift+2];
      fractal=price>=High[shift+4] &&
      price>=High[shift+3] &&
      price > High[shift+1] &&
      price > High[shift];
      gap=v1[i+1] - price;
      if (fractal && (gap>=contract || gap < 0))
        {
         v1[i]=price + (Precision * Point);
         }else{
         v1[i]=v1[i+1];
        }
      // Support
      price=Low[shift+2];
      fractal=price<=Low[shift+4] &&
      price<=Low[shift+3] &&
      price < Low[shift+1] &&
      price < Low[shift];
      gap=price - v2[i+1];
      if (fractal && (gap>=contract || gap < 0))
        {
         v2[i]=price - (Precision * Point);
         }else{
         v2[i]=v2[i+1];
        }
      i--;
     }
   return(0);
  }
//+------------------------------------------------------------------+
void watermark()
  {
   ObjectCreate("fxfisherman", OBJ_LABEL, 0, 0, 0);
   ObjectSetText("fxfisherman", "fxfisherman.com", 11, "Lucida Handwriting", RoyalBlue);
   ObjectSet("fxfisherman", OBJPROP_CORNER, 2);
   ObjectSet("fxfisherman", OBJPROP_XDISTANCE, 5);
   ObjectSet("fxfisherman", OBJPROP_YDISTANCE, 10);
   return;
  }
//+------------------------------------------------------------------+

How can I get the Resistance and the Support value?

double Rval=iCustom(...);
double Sval = iCustom(...);
//Something like this? I have no idea what to fill in for the parameter to get the desired value.
Minh
140
Minh 2014.03.28 06:10  
Never mind. I found the solution. Thanks guy
12
To add comments, please log in or register