for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if (OrderType() == OP_BUY) {OrderClose(OrderTicket(), OrderLots(), Bid, 13, White);}
else if (OrderType() == OP_SELL) {OrderClose(OrderTicket(), OrderLots(), Ask, 13, White);}
}
Backtest result:
# Time Type Order Lots Price S/L T/P Profit
33 2004.12.30 00:00 sell 17 6.10 1.9185 0.0000 0.0000 0.00
34 2004.12.31 00:00 sell 18 6.10 1.9247 0.0000 0.0000 0.00
35 2005.01.03 00:00 sell 19 6.10 1.9187 0.0000 0.0000 0.00
36 2005.01.12 00:00 close 19 6.10 1.8790 0.0000 0.0000 23864.72
37 2005.01.12 00:00 close 17 6.10 1.8790 0.0000 0.0000 23678.67
38 2005.01.13 00:00 close 18 6.10 1.8907 0.0000 0.0000 20323.67
Order 18 is closed on 2005.01.13 00:00, one day after Order 19 and 17. Can anyone explain why is that? How can I close all 3 orders on the same day?
It should be usefull to see the whole EA : it seems you are in closing conditions only at 00:00. If that is true, if you don't have time to close all trades, the others will be closed next day.
I think a good way to close all trades is what I have already answerd to you at "OrderOpenPrice() bug ? v4 b 186"
The EA is used for trading on daily chart, and every day starts at 00:00.
Gonzalo
//+------------------------------------------------------------------+
//| Check for close order conditions |
//+------------------------------------------------------------------+
void CheckForClose()
{
double ma;
double Upperband[],Lowerband[],BandaSup1,BandaInf1,BandaSup2,BandaInf2;
int limit=20, i,k,error;
static datetime prevtime=0;
bool result;
//ArrayResize(Upperband,limit);
//ArrayResize(Lowerband,limit);
//---- get Bandas superior e inferior de los sobres
// for(k=0; k<limit; k++)
// {
// Upperband[k]=iEnvelopes(NULL,PERIOD_H1,BandsPeriod,MODE_EMA,0,PRICE_CLOSE,desviation,MODE_UPPER,i);
// Lowerband[k]=iEnvelopes(NULL,PERIOD_H1,BandsPeriod,MODE_EMA,0,PRICE_CLOSE,desviation,MODE_LOWER,i);
// }
//---- go trading only for first tiks of new bar
//if(prevtime == Time[0])
//return;
//prevtime = Time[0];
//----
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
if(OrderType()==OP_BUY)
{
// if((Upperband[1]>Close[1]>Lowerband[1])&&(Close[2]>=Upperband[2])&&(Close[2]>=Close[1]))
if((BandaSup1>=Close[1]>=BandaInf1)&&(Close[2]>=BandaSup2)&&(Close[2]>=Close[1]))
result= OrderClose(OrderTicket(),OrderLots(),Bid,3,White);
}
if(OrderType()==OP_SELL)
{
// if((Upperband[1]>Close[1]>Lowerband[1])&&(Close[2]<=Lowerband[2])&&(Close[2]<=Close[1]))
if((BandaSup1>=Close[1]>=BandaInf1)&&(Close[2]<=BandaInf2)&&(Close[2]<=Close[1]))
result= OrderClose(OrderTicket(),OrderLots(),Ask,3,White);
}
if(result!=TRUE)
{
error=GetLastError();
Print("LastError = ",error);
}
}
else
Print( "Error when order select ", GetLastError());
//----
}
return;
}
First at all You have my gratitude for answering my question. The problem is I can open the position but then when the condictions are accomplished, it does not close the position. When I compiled the EA I did not have any problem with the syntax. I do not have experience with MQL4 I did what i used programing C++, 8 years ago.
I do not understand what you say about a "second error" Can you explain it to me? How can I solve it. Maybe I have to use a break or a return instruction?
I am going to change the syntax. Maybe this is the solution for the first problem
Regards,
Gonzalo Moreno
I think this syntax is wrong :
if((BandaSup1>=Close[1]>=BandaInf1)&&(
Try BandaSup1>=Close[1] && Close[1]>=BandaInf1 &&(
You may have a second error if you close a long succesfully, then you check OrderType(), but the trade doesn't exist anymore.
if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White) Print("LastError = ", GetLastError() );
Return;
The return statement is neccessary because if you close the trade, you cannot anymore test if it's type is OP_SELL
I have implemented all your tips. I think it will work.
Best regads,
Gonzalo
if(!OrderClose(OrderTicket(),OrderLots(),Ask,3,White) Print("LastError = ", GetLastError() );
Return;
The return statement is neccessary because if you close the trade, you cannot anymore test if it's type is OP_SELL
Thank you. now it closes a position but I have a discovered something 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
Thank you. now it closes a position but I have a discovered something 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...
I send you all the EA. Thank you for your help.
[quote]
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ó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í 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á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ó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();
//----
}
//+------------------------------------------------------------------+
- Free trading apps
- Over 8,000 signals for copying
- Economic news for exploring financial markets
You agree to website policy and terms of use
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
if(!OrderSelect(i, SELECT_BY_POS, MODE_TRADES)) continue;
if (OrderType() == OP_BUY) {OrderClose(OrderTicket(), OrderLots(), Bid, 13, White);}
else if (OrderType() == OP_SELL) {OrderClose(OrderTicket(), OrderLots(), Ask, 13, White);}
}
Backtest result:
# Time Type Order Lots Price S/L T/P Profit
33 2004.12.30 00:00 sell 17 6.10 1.9185 0.0000 0.0000 0.00
34 2004.12.31 00:00 sell 18 6.10 1.9247 0.0000 0.0000 0.00
35 2005.01.03 00:00 sell 19 6.10 1.9187 0.0000 0.0000 0.00
36 2005.01.12 00:00 close 19 6.10 1.8790 0.0000 0.0000 23864.72
37 2005.01.12 00:00 close 17 6.10 1.8790 0.0000 0.0000 23678.67
38 2005.01.13 00:00 close 18 6.10 1.8907 0.0000 0.0000 20323.67
Order 18 is closed on 2005.01.13 00:00, one day after Order 19 and 17. Can anyone explain why is that? How can I close all 3 orders on the same day?