OrderClose() Problem, TO MichelB - page 2

 
Hello Michael:

I sent you all the EA updated with your tips. I am a new student of MQL4 and I wrote a program several years ago when I was a Student. I recognize you have more knowledge abou MQL4 however I think problem can be with OrdersTotal() or with iEnvelopes function. What do you think?

I am studing for miself if I can solve I will write you. I really appreciatte how you have helped me. Thank you

Best Regards

Gonzalo (From Colombia)


[quote]Hello Michael:

I send you all the EA. Thank you for your help.



Michael:

Thank you. now it closes a position but I have discovered some new problems:

1) If I open a position to check my EA closes that position when condictions are accomplished, it does not do it. it only works closing positions itself opens.
2) it can have a Sell and a Long opened at the same time (I do not want that)
3) When it opens a Sell, if price moves up one tick the EA closes the position. When price moves down one tick, it opens again and so and so

What Can I do?

Regards


Gonzalo




I don't have the full EA, only the CheckForClose sub. Please, post the full EA if you want to be helped...



//+------------------------------------------------------------------+
//| Sobres 1.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| https://www.metaquotes.net/ |
//+------------------------------------------------------------------+

#define MAGICMA 19730625

//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+

// La cantidad con la que se va a tranzar

extern double Lots = 1;
extern double BandsPeriod = 25;
extern double Stop;
extern double desviation=0.6;
extern int BandsShift=0;

//+------------------------------------------------------------------+
//| Calculate open positions |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
{
int buys=0,sells=0;
//----
for(int i=OrdersTotal()-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
{
if(OrderType()==OP_BUY) buys++;
if(OrderType()==OP_SELL) sells++;
}
}
//---- return orders volume
//---- return orders volume
if(buys>0) return(buys);
else return(-sells);
}
/*+------------------------------------------------------------------+
//| Calculate optimal lot size |
//+------------------------------------------------------------------+
double LotsOptimized()
{
double lot=Lots;
int orders=HistoryTotal(); // history orders total
int losses=0; // number of losses orders without a break
//---- select lot size
lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//---- calcuulate number of losses orders without a break
if(DecreaseFactor>0)
{
for(int i=orders-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in history!"); break; }
if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
//----
if(OrderProfit()>0) break;
if(OrderProfit()<0) losses++;
}
if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
}
//---- return lot size
if(lot<0.1) lot=0.1;
return(lot);
}
*/
//+------------------------------------------------------------------+
//| Check for open order conditions |
//+------------------------------------------------------------------+
void CheckForOpen()
{


// Declaraci&#243;n de variables

double takeprofit;
int i,k,error, totalOrders,count,res,handled,NoOrdenes;
double Upperband[],Lowerband[],BandaSup1,BandaInf1,BandaSup5,BandaInf5;
double sum,newres;
int limit=20;

ArrayResize(Upperband,limit);
ArrayResize(Lowerband,limit);
ArraySetAsSeries(Upperband,true);
ArraySetAsSeries(Lowerband,true);

// Calculo de la banda y de sus bandas extremas
//---- go trading only for first tiks of new bar
// if(Volume[0]>1) return;
//---- get Bandas superior e inferior de los sobres

BandaSup1=iEnvelopes(NULL,PERIOD_H1,BandsPeriod,MODE_EMA,0,PRICE_CLOSE,desviation,MODE_UPPER,1);
BandaInf1=iEnvelopes(NULL,PERIOD_H1,BandsPeriod,MODE_EMA,0,PRICE_CLOSE,desviation,MODE_LOWER,1);

BandaSup5=iEnvelopes(NULL,PERIOD_H1,BandsPeriod,MODE_EMA,0,PRICE_CLOSE,desviation,MODE_UPPER,4);
BandaInf5=iEnvelopes(NULL,PERIOD_H1,BandsPeriod,MODE_EMA,0,PRICE_CLOSE,desviation,MODE_LOWER,4);

//---- sell conditions
if((BandaInf1<=Close[1]&&Close[1]<=BandaSup1) && (Close[5]>BandaSup5)&&(Close[1]<Close[5]))
{
Stop= High[Highest(NULL,PERIOD_H1,MODE_HIGH,10,1)]+ 40*Point;
res=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,Stop,0,"Abrio un Corto",MAGICMA,0,Red);
//El siguiente condicional lo escrib&#237; en el caso de que no se pudiera abrir la orden


if(res!=TRUE)
{
error=GetLastError();
Print("No se pudo abrir el Sell = ",error);
}

if(error==135)
RefreshRates();
else error=0;

return;
}
//---- buy conditions
if((BandaSup1>=Close[1]&&Close[1]>=BandaInf1)&&(Close[4]<=BandaInf5)&&(Close[1]>Close[4]))
{
Stop= Low[Lowest(NULL,PERIOD_H1,MODE_LOW,10,1)]-40*Point;
res=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Stop,0,"",MAGICMA,0,Blue);

if(res!=TRUE)
{
error=GetLastError();
Print("No se pudo abrir el Largo = ",error);
}

if(error==135)
RefreshRates();
else error=0;

return;
}
//----
}
//+------------------------------------------------------------------+
//| Check for close order conditions |
//+------------------------------------------------------------------+

void CheckForClose()
{
double ma;
double Upperband[],Lowerband[],BandaSup1,BandaInf1,BandaSup2,BandaInf2;
int limit=20, i,k,error;
bool result;




//----

BandaSup1=iEnvelopes(NULL,PERIOD_H1,BandsPeriod,MODE_EMA,0,PRICE_CLOSE,desviation,MODE_UPPER,1);
BandaInf1=iEnvelopes(NULL,PERIOD_H1,BandsPeriod,MODE_EMA,0,PRICE_CLOSE,desviation,MODE_LOWER,1);

BandaSup2=iEnvelopes(NULL,PERIOD_H1,BandsPeriod,MODE_EMA,0,PRICE_CLOSE,desviation,MODE_UPPER,2);
BandaInf2=iEnvelopes(NULL,PERIOD_H1,BandsPeriod,MODE_EMA,0,PRICE_CLOSE,desviation,MODE_LOWER,2);

for(i=OrdersTotal()-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true)
{

//---- check order type

/* Ojo con la sintaxis en MQL4 y en C++ no se puede usar intervalos como condicionales ej (a<=x<=b)
lo que toca hacer es partirlos en dos condiciones (a<=x && x<=b)

Adem&#225;s michael recomienda que despues de cerrar la orden haga el return para asi poder verificar si hay otra orden abierta
esa es la raz&#243;n de escribir las instrucciones tanto para el Buy como para el Sell:

if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
Print("LastError = ", GetLastError() );
return;

*/
if(OrderType()==OP_BUY)
{

if((BandaSup1>=Close[1]&& Close[1]>=BandaInf1)&&(Close[2]>=BandaSup2)&&(Close[2]>=Close[1]))
result= OrderClose(OrderTicket(),OrderLots(),Bid,3,White);
if(!OrderClose(OrderTicket(),OrderLots(),Bid,3,White))
Print("No pudo cerrar el Buy = ", GetLastError() );
return;

}


if(OrderType()==OP_SELL)
{

if((BandaSup1>=Close[1]&& Close[1]>=BandaInf1)&&(Close[2]<=BandaInf2)&&(Close[2]<=Close[1]))
result= OrderClose(OrderTicket(),OrderLots(),Ask,3,White);
if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White))
Print("No se pudo cerrar el Sell = ", GetLastError() );
return;

}


}
else
Print( "Error when order select ", GetLastError());
return;
//----
}
return;
}

//+------------------------------------------------------------------+
//| Start function |
//+------------------------------------------------------------------+
void start()
{
//---- check for history and trading
if(Bars<100 || IsTradeAllowed()==false) return;
//---- calculate open orders by current symbol
if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
else CheckForClose();
//----
}
//+------------------------------------------------------------------+

 
1) If I open a position to check my EA closes that position when condictions are accomplished, it does not do it. it only works closing positions itself opens.
2) it can have a Sell and a Long opened at the same time (I do not want that)
3) When it opens a Sell, if price moves up one tick the EA closes the position. When price moves down one tick, it opens again and so and so


1) Your EA is using MagicNumbers to identifies orders. When you enter a position manually, do you use the same Magic ? I think no and that's why EA doesn't reconize your orders.

2) - if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
Don't use 'break' statement, use 'continue' instead.
- if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
Your function has as argument 'string symbol', so use 'symbol' instead of Symbol() if you want to count trades from other symbol chart.

3) Check better your conditions. Generally speaking, you are uselessy very complicate ! Keeping all as simple as possible is the best way to build an efficient expert.
 
Dear Michael:

Thank you. I did not know what to do, but with your tips next time I will do it better.
When you wrote about my "complicate condictions", Are you speaking about my condictions to open or to close a position?Can you explain it better? I will check it, anyway.

You have focus your time to help me with my first EA. I really appreciatte it. Thank you because to learn to program and EA it very frustrating at the begining. I have two week working in this EA because I had to learn MQL4. Thank you and God Bless you.


Best regards

Gonzalo Moreno



1) If I open a position to check my EA closes that position when condictions are accomplished, it does not do it. it only works closing positions itself opens.
2) it can have a Sell and a Long opened at the same time (I do not want that)
3) When it opens a Sell, if price moves up one tick the EA closes the position. When price moves down one tick, it opens again and so and so


1) Your EA is using MagicNumbers to identifies orders. When you enter a position manually, do you use the same Magic ? I think no and that's why EA doesn't reconize your orders.

2) - if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
Don't use 'break' statement, use 'continue' instead.
- if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
Your function has as argument 'string symbol', so use 'symbol' instead of Symbol() if you want to count trades from other symbol chart.

3) Check better your conditions. Generally speaking, you are uselessy very complicate ! Keeping all as simple as possible is the best way to build an efficient expert.
 
Gonzalo,
For your next EA, don't use user functions unless neccessary. For simple EAs, try using this simple structure and implement errors handling only when your expert is working:

start()
{
//check for closing orders
.........
//count existing orders
........
if(count > 0) return(0);
//check for opening orders
........
return(0);
}

Ciao !
Reason: