user6534695
user6534695

Reputation:

Is there a way to use try catch block in MQL4 expert advisor code?

In my MQL4 expert advisor I need to check this code before it is executing, weather it is correct or not. Is there a way to use a try/catch blocks for this? It is written in C language.

OrderSelect( i, SELECT_BY_POS );
if (  OrderType() == OP_SELL ){
      OrderClose( OrderTicket(), OrderLots(), Ask, 3 );
}

Upvotes: 0

Views: 1341

Answers (3)

Hasindu Gajanayake
Hasindu Gajanayake

Reputation: 337

On my point of view in the MQL4 expert advisor functions there is no way to use try catch method as java.you can only catch the errors before executing via other methods like checking the validity of the orderticket and etc

Upvotes: 0

user3666197
user3666197

Reputation: 1

Well, let me have a different view - there is a way to do it:

Given your plan is to find a way, how to enable a use of the try/catch clause in MQL4/5 domain, there is a way to do it.

While many pieces of advice say it is not possible or it is not needed, let's accept a fact the O/P asked for it and focus on how.

In case, there is indeed a need to have a try/catch fused part of code, I would implement such code inside an externally #import-ed code, via DLL and select such the target eco-system, that has the native try/catch language constructors available for algorithm that wishes to work within it's fused code-blocks.


Daniel's example about intentional throwing the MQL4-system execution to trash, by an explicit attempt to access Array[EMPTY] is interesting, so far it was enough to call ExpertRemove() and enjoy the proper system termination of the code, including an OnDeinit(){...} handle pass-through. Suiccidal call seems to be quite a brutal mode bypass of the system code termination +1 for that @DanielKniaz.

Cool Man, indeed!

Upvotes: 0

Daniel Kniaz
Daniel Kniaz

Reputation: 4681

As it was suggested in comments, try/catch is done to let your code to throw an exception and catch it. If not catching your program would shutdown, if not throwing then result might be unknown.

The MQL4 programming language does not have exceptions at all (but it is possible to shutdown by invoking a critical error like calling -1 element of the array or dividing by zero). You do not need to throw an exception here even if you could.

OrderSelect() returns boolean value so you may check if it is false then continue the loop or return. OrderClose() returns boolean (the result - succesful closing or not) so you are advised to check if that function returns true of false, if false - need to log an error and try again

Upvotes: 3

Related Questions