EA code question about CloseOrders

Hi

I learned MQL4 and now programming EA’s

The MQL4 site is down right now - I’m guessing they are on the EastCoast and have power outages from the Hurricane like many who are still without power etc.

Anyhow I feel I know what I’m doing but cannot confirm this because all EA’s that I create or even those that are supposedly already working do not want to close the orders when the signal occurs.

For example simple MACD cross.

Open when cross up, and Close when cross down, and open new Sell order etc.

It’s actually not complicated, and I even used many variations of the standards loops to address this topic.

There are some topics which I addressed such as making adjustments for 4/5 digit brokers, and also if it’s and ECN then you might not be able to open the sl and tp without some more code.

But anyhow all this is working but the darn EA’s simply will not Close when crossing.

MACD will open, but then stay in trade until sl or tp. Never close and reopen in the other direction EVER

NEVER will this happen even on supposedly working code that I downloaded from others like EMA crosses posted everywhere.

All of them are very similar and might change the method of the loop OrderSelect(Symbol() == OrderSymbol() and things like this but basically I feel that what I’ve learn is correct, however I have yet to see an actual working EA in which to learn from.

To learn why it works, to learn why it won’t work if I change it etc.

Without a working EA to base what I’ve learned I’m not sure what to do or why I cannot get a working EA ???

Any ideas would be great.

FYI I’m currently using Oanda with MT4:17:

:44::17:

Hello Agent86
Your guess as to why MQL4 is down (Hurricane) is more than likely correct. As to learning the basics so as to understanding the whys and hows is located in the documents, books, and articles located on the MQL4 site. I have much of the same problem and would like it if these items or at least the MQL4 book was available on more than one site.
Happy tradeing

MT4 has an excellent help system inside, so you won’t need online connections to look at the functions description and how to use them. There is also a nice help about the error codes which them do return.

To close, you have to select an order first and after that make sure that slippage and every price is normalized in the orderclose function, as that could be an issue.

I read the book, documents and the lessons at forex-tsd.com etc. so I feel I have an understanding of how to code EA’s, scripts, and custom indicators work, and how to code them. Also the MT4 has the dictionaries in them and don’t need to access the site for that which works ok for me so far.
Even the example EA in the lessons do not work properly without first changing the 4/5 digit broker topic which is ok, but then the (for statement)loops do not close the orders, I have worked on the simplest of EA’s from example, from scratch, from other supposedly working EA’s and cannot get a working EA model to observe.

I feel confident the code is correct. I have to assume it’s something to do with my broker, but I can’t be sure because my experience is soooo new.

This whole thing reminds me of my first experience learning how to fix and install OS on computers.

Way back in Dos, with the old 8088 XT computer.

I learned, and learned and learned and never could confirm anything that I was learning because nothing was working.
Not until I got another loaded computer that I found there was nothing wrong with anything that I learned but the computer was actually non-working LOL

So without further confirmation I’m sort of in the same boat again and will not fully understand this until I see a working EA in action.

Perhaps I’ll try another broker demo to see if there is any change on another broker

hmm, the guru’s at MQL4.com are saying not to use normalized anymore because it’s obsolete. I’ll have to do some more reading on that, however I do not think this would cause the problem that I’m having either way.

I mean the code I wrote are super simple and I dumbed them down to the point that I just wanted to see a OrderSend and then CloseOrder. Forget the (for) statement loops for now just so I could diagnose this topic.

I have to assume I have broker issues for now until I can try another broker this week sometime

I programmed an EA that closes my orders for me. I highly doubt it has anything to do with your broker except if it hasn’t been coded to recognize whether the broker uses extra digits or not which is still not the brokers problem.

Did it ever work? Have you checked the “experts” tab for any messages that might reflect any attempt to close orders? There are several ways to monitor the progress of the logic in your code and checking the value of certain variables etc while it’s running. If you like you could copy & paste here the section of the code that closes the order and we can double check that part of it for you :slight_smile:

Normalizing is a must, whatever somebody tells you. I also do hardly assume it’s a broker issue.

I had this post all typed up and used pastepound to add my code so that people could review

I have not posted 5 posts so it said I could not do that LOL
Anyhow pasting the code is not really going to help.

But the general idea which I cannot paste here yet due to the limits of the forum are located at the forex-tsd sit lesson 13 MY-FIRST_EA
This code does not work, I did edit for 4/5 digit brokers, and also got rid of the trailing stop, which really sort of lead me to re-create this code a bit, but the simplicity is still there. In fact I created a more dumbed down version because it never really worked right.

Some code I created, but also many of the code base was from supposedly working code.
I dumbed down a simple code just to see if I could make an order close.

I also have been reading and learning about this topic for about 2 weeks and approx. 60hrs of research and it’s not that complicated. Seem the various codes that I created and even others codes should work

if(total < 0)
if(faster > slower)
OrderSend

then
if(total > 0)
if (faster < slower)
OrderSelect
CloseOrder

Well not exactly but those basic and too much to go copying and pasting a ton of various hundreds of code that I’ve created, tried, downloaded, invented and still No Close Orders.

I would be happy to see without any loops or crosses at all simply 1)OrderSend and 1)CloseOrder

But the order will Open no problem and close on sl and tp but NEVER closed on reversal or simply a new signal forget the cross or reversal topic for now. But even something as simply as a new signal and CloseOrder will not do it.
with or without return(0); for each block etc. no different.

and no errors in the code or I should say MQL4 editor does not complain.

I would be satisfied if I knew that I had something wrong and could fix it, but I keep seeing all the same stuff and typical coding practices for CloseOrders and it seems fairly straight forward especially on simply crosses like EMA cross.

Does not seem complicated.

So I’ll test on 2 other brokers and at least try to narrow this down a bit to see if there is any difference. Would be nice to know at least if there was a problem with the code or the broker either way would be good so I can move on from this and start coding my ideas. I really don’t think there is a problem with the code especially since I’ve tried sooo many other codes and also created my own with the same results.

This is actually the only thing holding me back from coding my ideas at this point.

ARRRGGGGGG, this is driving me crazy LOL

No difference on Alpari I have to assume something wrong with the codes. Question is why so many of them do not work ?

Anyhow Here is a sample code of something but I used the examples in the lessons as a sort of template:

//±-----------------------------------------------------------------+
//|
//±-----------------------------------------------------------------+

//---- input parameters
extern double TakeProfit=300.0;
extern double Lots=0.1;
extern double StopLoss=20.0;
extern int MagicNumber=12345;

//++++ These are adjusted for 5 digit brokers.

int pips2points; // slippage 3 pips 3=points 30=points
double pips2dbl; // Stoploss 15 pips 0.0015 0.00150
int Digits.pips; // DoubleToStr(dbl/pips2dbl, Digits.pips)

// OrderSend(... Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl

//±-----------------------------------------------------------------+
//| expert initialization function |
//±-----------------------------------------------------------------+
int init()
{
if (Digits == 5 || Digits == 3)
{ // Adjust for five (5) digit brokers.
pips2dbl = Point*10; pips2points = 10; Digits.pips = 1;
}
else
{
pips2dbl = Point; pips2points = 1; Digits.pips = 0;
}
// OrderSend(… Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl
//----

//----
return(0);
}
//±-----------------------------------------------------------------+
//| expert deinitialization function |
//±-----------------------------------------------------------------+
int deinit()
{

//----

//----
return(0);
}

int Crossed (double line1 , double line2)
{
static int last_direction = 0;
static int current_direction = 0;

  if(line1&gt;line2)current_direction = 1; //up   //might need to add here for second macd agreement
  if(line1&lt;line2)current_direction = 2; //down



  if(current_direction != last_direction) //changed 
  {
        last_direction = current_direction;
        return (last_direction);
  }
  else
  {
        return (0);
  }

}

int Crossed_2 (double line1 , double line2) //i’ll use this later for macd agreement on 2 timeframes
{
static int last_direction_2 = 0;
static int current_direction_2 = 0;

  if(line1&gt;line2)current_direction_2 = 1; //up
  if(line1&lt;line2)current_direction_2 = 2; //down



  if(current_direction_2 != last_direction_2) //changed 
  {
        last_direction_2 = current_direction_2;
        return (last_direction_2);
  }
  else
  {
        return (0);
  }

}

//±-----------------------------------------------------------------+
//| expert start function |
//±-----------------------------------------------------------------+
int start()
{
//----

int cnt, ticket, total, mrmagic, pos;
double faster, slower, faster_2, slower_2;

if(Bars<100)
{
Print(“bars less than 100”);
return(0);
}
if(TakeProfit<10)
{
Print(“TakeProfit less than 10”);
return(0); // check TakeProfit
}

faster = iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1); //MODE_MAIN
slower = iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1); //MODE_SIGNAL
faster_2 = iMACD(NULL,PERIOD_H4,12,26,9,PRICE_CLOSE,MODE_MAIN,1); //MODE_MAIN
slower_2 = iMACD(NULL,PERIOD_H4,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1); //MODE_SIGNAL

int isCrossed = Crossed (faster,slower);
int isCrossed_2 = Crossed_2 (faster_2,slower_2); // i’ll use this later for macd agreement on separate timeframes

total = OrdersTotal();
if(total < 1)
{
if(isCrossed == 1){ // I want to add && isCrossed_2 == 1) but 0 trades occur with the note below
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3pips2points,Bid-StopLosspips2dbl,Bid+TakeProfitpips2dbl,“Agent86”,12345,0,Green);
if(ticket>0){
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
}
else Print("Error opening BUY order : ",GetLastError());
}
if(isCrossed == 2){ // I want to add && isCrossed_2 == 2) but 0 trades occur with the note above
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3
pips2points,Ask+StopLosspips2dbl,Ask-TakeProfitpips2dbl,“Agent86”,12345,0,Red);
if(ticket>0){
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
}
else Print("Error opening SELL order : ",GetLastError());
}

for(cnt=0; cnt<total; cnt++){
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderSymbol()== Symbol() && OrderMagicNumber() == MagicNumber){
if(OrderType()==OP_BUY
&& isCrossed == 2)
OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
return(0);
}
if(OrderType()== OP_SELL
&& isCrossed == 1)
OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
return(0); // exit
}

  }

return(0);
}

//±-----------------------------------------------------------------+

Try putting in the following code (in red) for each of your OrderClose statements:

result = OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet);
if(result == false)
{
Alert(“Order " , OrderTicket() , " failed to close. Error:” , GetLastError() );
}

Then when it’s supposed to close the orders and doesn’t, it should give you an error code. If the alert doesnt’ alert you, then it’s a problem with the contents of your variables…which we can check after we rule this out.

Ok, I’m running on the tester, I’ll put it on the chart and see what the Alert says and post back

Thanks

I changed the Alert to Print so I could see it in the tester

There is NO CloseOrders

However, when the tester starts I get numerous line items in the journal which says this:
2011.09.01 20:03:24 TestGenerator: unmatched data error (volume limit 99 at 2011.08.25 20:15 exceeded)

I don’t recall it saying this before.

Anyhow here is the code now:

//---- input parameters
extern double TakeProfit=300.0;
extern double Lots=0.1;
extern double StopLoss=20.0;
extern int MagicNumber=12345;

//++++ These are adjusted for 5 digit brokers.

int pips2points; // slippage 3 pips 3=points 30=points
double pips2dbl; // Stoploss 15 pips 0.0015 0.00150
int Digits.pips; // DoubleToStr(dbl/pips2dbl, Digits.pips)

// OrderSend(... Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl

//±-----------------------------------------------------------------+
//| expert initialization function |
//±-----------------------------------------------------------------+
int init()
{
if (Digits == 5 || Digits == 3)
{ // Adjust for five (5) digit brokers.
pips2dbl = Point*10; pips2points = 10; Digits.pips = 1;
}
else
{
pips2dbl = Point; pips2points = 1; Digits.pips = 0;
}
// OrderSend(… Slippage.Pips * pips2points, Bid - StopLossPips * pips2dbl
//----

//----
return(0);
}
//±-----------------------------------------------------------------+
//| expert deinitialization function |
//±-----------------------------------------------------------------+
int deinit()
{

//----

//----
return(0);
}

int Crossed (double line1 , double line2)
{
static int last_direction = 0;
static int current_direction = 0;

  if(line1&gt;line2)current_direction = 1; //up   //might need to add here for second macd agreement
  if(line1&lt;line2)current_direction = 2; //down



  if(current_direction != last_direction) //changed 
  {
        last_direction = current_direction;
        return (last_direction);
  }
  else
  {
        return (0);
  }

}

int Crossed_2 (double line1 , double line2) //i’ll use this later for macd agreement on 2 timeframes
{
static int last_direction_2 = 0;
static int current_direction_2 = 0;

  if(line1&gt;line2)current_direction_2 = 1; //up
  if(line1&lt;line2)current_direction_2 = 2; //down



  if(current_direction_2 != last_direction_2) //changed 
  {
        last_direction_2 = current_direction_2;
        return (last_direction_2);
  }
  else
  {
        return (0);
  }

}

//±-----------------------------------------------------------------+
//| expert start function |
//±-----------------------------------------------------------------+
int start()
{
//----

int cnt, ticket, total, mrmagic, pos, result;
double faster, slower, faster_2, slower_2;

if(Bars<100)
{
Print(“bars less than 100”);
return(0);
}
if(TakeProfit<10)
{
Print(“TakeProfit less than 10”);
return(0); // check TakeProfit
}

faster = iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1); //MODE_MAIN
slower = iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1); //MODE_SIGNAL
faster_2 = iMACD(NULL,PERIOD_H4,12,26,9,PRICE_CLOSE,MODE_MAIN,1); //MODE_MAIN
slower_2 = iMACD(NULL,PERIOD_H4,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1); //MODE_SIGNAL

int isCrossed = Crossed (faster,slower);
int isCrossed_2 = Crossed_2 (faster_2,slower_2); // i’ll use this later for macd agreement on separate timeframes

total = OrdersTotal();
if(total < 1)
{
if(isCrossed == 1){ // I want to add && isCrossed_2 == 1) but 0 trades occur with the note below
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3pips2points,Ask-StopLosspips2dbl,Ask+TakeProfitpips2dbl,“Agent86”,12345,0,Green);
if(ticket>0){
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order opened : ",OrderOpenPrice());
}
else Print("Error opening BUY order : ",GetLastError());
}
if(isCrossed == 2){ // I want to add && isCrossed_2 == 2) but 0 trades occur with the note above
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3
pips2points,Bid+StopLosspips2dbl,Bid-TakeProfitpips2dbl,“Agent86”,12345,0,Red);
if(ticket>0){
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order opened : ",OrderOpenPrice());
}
else Print("Error opening SELL order : ",GetLastError());
}

for(cnt=0; cnt<total; cnt++){
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderSymbol()== Symbol()){
if(OrderType()==OP_BUY
&& isCrossed == 2)
result = OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
if(result == false){
Print(“Order”,OrderTicket(),“failed to close Error”,GetLastError());
return(0);
}

     if(OrderType()== OP_SELL
       && isCrossed == 1)
       result = OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
        if(result == false){
           Print("Order",OrderTicket(),"failed to close Error",GetLastError());
           return(0); // exit
        }           
     }
  }           
  }

return(0);
}

//±-----------------------------------------------------------------+[/QUOTE]

Ok I dumbed it down got rid of the loop and only want to see an open and close

Paste #11911 | LodgeIt!

So anyhow, I do get failed errors now with error 138 which appears to mean the sever rejected the price at which I wanted to close. I’ll work on it some more.

Let me know if you see anything obvious that I’m missing.

I changed some variation of it with the OrderClose with (SELECT_BY_TICKET and more same effect

Thanks

Ok, what is that code I’ve got circled? … 3*pips2points?


That is where the “Bid Price” is supposed to go…you have to put a price in there not a calculation. The order of parameters is important. Perhaps you meant it to go after the bid for the “slippage” parameter? I have found that those data mismatch errors can mean the parameters are in the wrong order, so that could be part of the problem. So what error code are you getting?

Just to let you know I’m off work now so, and have a lot to do this evening so it may be awhile before I can respond again. Keep working on it :wink:

Ahhh, I see that, yep on the dumbed down code it’s wrong. But the others are correct and I’ll review them again to to see if there is anything similar

The dumbed down code after a few more changes and your circled code error that I had in there is not giving Close errors as directed.

But it’s actually closing the trades it would appear. So I’m on the right track now

Thanks and enjoy

Home now and have a moment…that formula above…is it for the slippage parameter? If so, just thinking, you don’t need to adjust it to points because apparently using the integer 3 is fine…so remove the “*pips2points” part of it.

Ok, I have it changed, and kept working it and working it over and over. HA HA.

Strange that I had it actually opening trades last night, and closing trades, but with CloseOrder errors, although it was actually closing the trades. But this morning I had to rework it again because it was only opening 1) trade and thats it, no sl. or tp for what seems like no reason at all.

Anyhow, I got it trading again.
See code here:
Paste #11939 | LodgeIt!

And disregard the title and the web links, thats something I was going to do when I was manually trading, but I lost interest in that for now, and may post my EA signals to that site sometime, or maybe just delete that site anyhow FYI it’s irrelevant.

Anyhow
So I get (failed to close Error 4108) then followed by the (unknown ticket for OrderClose Function)
Yes the orders are closing

But it is trading

I traced this to a few topics on the web regarding this and seems to be invalid ticket:
Expert Advisor MetaTrader Error Codes

I attempted to use the IsTradeContextBusy() to find something out but no errors on that so I removed it.
And considered the requote function but I don’t think that is my problem

LOL, all I can do is laugh at myself, I’ve been working on this for 2 weeks just to learn how to code, and I want soooooo bad to code my ideas. Mostly for a hobby and to learning enjoyment, but DARRRRRRN this is frustrating. :10:

Oh well, Back to the Drawing Board LOL

WHOOOOO! mql4 site back up LOL

SweetPips-
Ok I got part of this figured out.
Seems I did not even have the code block correct with the count braces, oops !

No errors now thanks a bunch you got me on the right track.

for (i = OrdersTotal()-1; i >= 0; i–){ <<<seem if forgot this brace here and this caused all this craziness. OUCH !

And only took me 2 weeks to figure this out. Let me put my dunce cap on for a couple weeks and stand in the corner

:35:

And thanks everyone for the help