• Home
  • Forums
  • News
  • Calendar
  • Market
  • Login
  • Join
  • 11:19am
Menu
  • Forums
  • News
  • Calendar
  • Market
  • Login
  • Join
  • 11:19am
Sister Sites
  • Metals Mine
  • Crypto Craft
  • Forex Factory

Options

Bookmark Thread

First Page First Unread Last Page Last Post

Print Thread

Similar Threads

Is random really random? 231 replies

Handy MQL4 utility functions 71 replies

mql4/mql5 functions question 3 replies

MQL4 Language Most Recent Version is it updated beyond the tutorial on the mql4 websi 6 replies

Define every MQL4 variables, functions? 4 replies

  • Platform Tech
  • /
  • Reply to Thread
  • Subscribe
  • 1
Attachments: Random Useful MQL4 Functions
Exit Attachments
Tags: Random Useful MQL4 Functions
Cancel

Random Useful MQL4 Functions

  • Last Post
  •  
  • 1 Page 2
  • 1 Page 2
  •  
  • Post #21
  • Quote
  • Jan 10, 2022 5:19am Jan 10, 2022 5:19am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Pending Order Placement Function
To place pending orders, we'll need to pass parameters for the pending order price as well as the order expiration time.
The PendingPrice and Expiration arguments will be added to the function.
We'll assume that the pending order price, as well as the stop loss and take profit, have been calculated and verified prior to calling this function.
The pending order placement functions will place the stop loss and take profit with the pending order, so no separate order modification function is required.
Inserted Code
int OpenBuyStopOrder(string Symbol(), double LotSize, double PendingPrice, double StopLoss, double TakeProfit, double slippage, double MagicNumber, datetime Expiration = 0, string Comment = "Buy Stop Order")
   {
       while(IsTradeContextBusy()) Sleep(10);
 
// Place Buy Stop Order
  int Ticket = OrderSend(Symbol(),OP_BUYSTOP,LotSize,PendingPrice,Slippage,StopLoss,TakeProfit,Comment,MagicNumber, Expiration,Green);
 
// Error Handling
   if(Ticket == -1)
    {
     int ErrorCode = GetLastError();
    string ErrDesc = ErrorDescription(ErrorCode);
     string ErrAlert = StringConcatenate("Open Buy Stop Order - Error ",ErrorCode,": ",ErrDesc);
     Alert(ErrAlert);
     string ErrLog = StringConcatenate("Ask: ",MarketInfo(Symbol(),MODE_ASK)," Lots: ",LotSize," Price: ",PendingPrice," Stop: ",StopLoss," Profit: ",TakeProfit,"           Expiration: ",TimeToStr(Expiration));
   Print(ErrLog);
     }
   return(Ticket);
 }

Note that we've specified a default value of 0 for Expiration. If you are not using a pending order expiration time, and you wish to use the default order comment,you can simply omit the arguments for Expiration and Comment when calling the function.
The following example will place a buy stop order with no expiration time and the default order comment, "Buy Stop Order":
Inserted Code
int Ticket = OpenBuyStopOrder(Symbol(),LotSize,PendingPrice,StopLoss,TakeProfit,UseSlippage,MagicNumber);
 
 
  • Post #22
  • Quote
  • Edited 4:24am Feb 16, 2022 3:56am | Edited 4:24am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
What are Function return values ? How do I use them ?
Source: https://www.mql5.com/en/forum/139592

I'll post a brief summary of this post and also my thoughts(in blue)

Do you ever get common warnings such as this one when compiling an EA?
return value of 'OrderSelect' should be check.
Well these warnings can be fixed by simply checking the return values from a few Functions and printing out any relevant errors.

This post mainly focuses on the Trading Functions(I came across this post because I was getting the warning from OrderSelect() Function) but the post also applies to any other function that returns a value.

A Function, just like a variable, has a type, for example, int, double, string, void, bool.
Any type other than void returns a value.
The type of the value returned depends on the type that the function is declared as , for example, a function declared as type bool will return a bool value, true or false.

An example
bool OrderSelect ( int index, int select, int pool=MODE_TRADES )
The OrderSelect() function is declared as type bool so it returns a bool value as either true or false

(I guess I was getting the error because in my code I wasn't declaring the type, I'll post part of the code below, it's just a simple function to check whether the max number of trades the EA is allowed to trade has been reached)


bool OrdersMaxReached()
{
int i = OrdersTotal();
int OrderCount=0;
while(i>0)
{
i--;
OrderSelect(i,SELECT_BY_POS);
if (OrderMagicNumber()==myMagicNumber)
OrderCount++;
}
if(OrderCount>=maxTrades)
{
return(true);
}
else
{
return(false);
}
}

Another Example
int OrderSend ( string symbol, int cmd, double volume, double price, int slippage, double stoploss, double takeprofit, string comment=NULL, int magic=0, datetime expiration=0, color arrow_color=CLR_NONE)

The OrderSend() function is declared as type int so it returns a value that is an integer, this integer is the ticket number if the OrderSend function has worked correctly, if it encountered an error the returned integer is set to -1.


How do we use these Return Values?
Where a function returns a bool, such as OrderSelect(), we can use code such as this to check if the function worked or did not work . . .

if ( OrderSelect(OrderPosition, SELECT_BY_POS) == true) // do something if the OrderSelect has worked
if ( OrderSelect(OrderPosition, SELECT_BY_POS) ) // simpler version

if ( OrderSelect(OrderPosition, SELECT_BY_POS) == false) // do something if the OrderSelect did not work
if ( ! OrderSelect(OrderPosition, SELECT_BY_POS) ) // simpler version, note the ! meaning NOT



Where a function returns an int, such as OrderSend(), we can use code such as this to check that the function worked and report an error to the logs if it did not work . . .

int TicketNumber; TicketNumber = OrderSend( . . . . . . . . );
if( TicketNumber > 0 )
{
Print("Order placed # ", TicketNumber);
}
else
{
Print("Order Send failed, error # ", GetLastError() );
}

. . . or a more concise version without using the intermediate variable TicketNumber . . .

if( OrderSend( . . . . . . . . ) < 0 ) // OrderSend has failed and has returned a value of -1
{
Print("Order Send failed, error # ", GetLastError() );
}


In either version, if the OrderSend() fails for whatever reason, the error number will be printed to the log and, if running in the Strategy Tester the error will also be visible in the Journal tab, if running Demo or Live the error will be visible in the Experts tab.
When a function isn't performing as expected, for example orders are not being placed, the log or the Journal/Experts tab can be looked at and any errors will be easily seen, a quick analysis of the relevant error will then allow you to correct the issue with your code or code logic.
 
 
  • Post #23
  • Quote
  • Feb 16, 2022 8:59pm Feb 16, 2022 8:59pm
  •  RedLineFred
  • Joined Sep 2012 | Status: Member | 327 Posts
Quoting Kefada
Disliked
if(LotSize < MarketInfo(Symbol(),MODE_MINLOT)) { LotSize = MarketInfo(Symbol(),MODE_MINLOT); }
Ignored
this is one approach, but i prefer to set the lot size to zero if less than miniot to avoid over risking the trade.

you could get caught out if you trade a commodity and its min lot size = 1.
" check out The Traders Outpost "
 
 
  • Post #24
  • Quote
  • Feb 17, 2022 1:29am Feb 17, 2022 1:29am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Quoting RedLineFred
Disliked
{quote} this is one approach, but i prefer to set the lot size to zero if less than miniot to avoid over risking the trade. you could get caught out if you trade a commodity and its min lot size = 1.
Ignored
Yeah, I can't believe I never thought of that...I'll have to update the programs I have worked on
 
 
  • Post #25
  • Quote
  • Feb 17, 2022 11:36am Feb 17, 2022 11:36am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Alphabetic index of 600+ mql4 functions
https://www.mql5.com/en/forum/150098
 
 
  • Post #26
  • Quote
  • Feb 17, 2022 1:55pm Feb 17, 2022 1:55pm
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Quoting Kefada
Disliked
Alphabetic index of 600+ mql4 functions https://www.mql5.com/en/forum/150098
Ignored
A small post about the creator of this index William Roeder.
I think anybody who is interested in MQL4 should read his posts in MQL5.com
Here is a link to his profile https://www.mql5.com/en/users/whroeder
He has over 26k comments and the ones I have read so far are pretty educative.(I am currently trying to understand some post where he said we should never use NormalizeDouble.(Check comment #4 in this post https://www.mql5.com/en/forum/158834)
I haven't personally interacted with him but his posts sort of inspire/motivate me to keep programming, practising and learning MQL4.
I hope my thread will one day boast of having over 600 functions .
 
1
  • Post #27
  • Quote
  • Feb 18, 2022 2:56pm Feb 18, 2022 2:56pm
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Quoting Kefada
Disliked
{quote} A small post about the creator of this index William Roeder. I think anybody who is interested in MQL4 should read his posts in MQL5.com Here is a link to his profile https://www.mql5.com/en/users/whroeder He has over 26k comments and the ones I have read so far are pretty educative.(I am currently trying to understand some post where he said we should never use NormalizeDouble.(Check comment #4 in this post https://www.mql5.com/en/forum/158834) I haven't personally interacted...
Ignored
Apparently the 600 functions aren't user defined but it's still impressive and useful, I still aim to having such a number of user defined ones
 
 
  • Post #28
  • Quote
  • Edited Feb 20, 2022 4:01am Feb 19, 2022 11:57am | Edited Feb 20, 2022 4:01am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Function that places Symbols in Market Watch into an Array
https://www.mql5.com/en/forum/151867
I tweaked the function in the above link a little bit as I did not like they way it was listing the functions
The array mwSymbols has to be initialized earlier on
Inserted Code
int GetSymbols()
      {
   HowManySymbols=SymbolsTotal(true);            
   string ListSymbols=" ";
   ArrayResize( mwSymbols, HowManySymbols);
  
   for(int i=0;i<HowManySymbols;i++)
     {
      ListSymbols=SymbolName(i,true);
      mwSymbols[i]=ListSymbols;
     }
     return(HowManySymbols);
      }
 
2
  • Post #29
  • Quote
  • Mar 17, 2022 1:30pm Mar 17, 2022 1:30pm
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
I have a function idea I want to work on.
So we have the inbuilt error handling function GetLastError() but it only returns Error codes.
What if It would return detailed error messages?
I want to build a function that an ea calls when error handling and the function runs the GetLastError and refers to an array containing the error codes and their detailed meaning.
The function then returns the Error Code and it's detailed meaning.
This would save sometime when testing the code as one doesnt have to refer to the mql4/5 website for error codes meanings.
I currently dont have much free time so this one will take sometime to create.
 
 
  • Post #30
  • Quote
  • Mar 17, 2022 1:54pm Mar 17, 2022 1:54pm
  •  mladen
  • Joined Apr 2007 | Status: ... | 801 Posts
Quoting Kefada
Disliked
I have a function idea I want to work on. So we have the inbuilt error handling function GetLastError() but it only returns Error codes. What if It would return detailed error messages? I want to build a function that an ea calls when error handling and the function runs the GetLastError and refers to an array containing the error codes and their detailed meaning. The function then returns the Error Code and it's detailed meaning. This would save sometime when testing the code as one doesnt have to refer to the mql4/5 website for error codes meanings....
Ignored
Include stdlib.mqh and use the :

string ErrorDescription(int error_code);

function for that

Or see the stdlib.mq4 file in the libraries folder
 
1
  • Post #31
  • Quote
  • Mar 17, 2022 2:58pm Mar 17, 2022 2:58pm
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Quoting mladen
Disliked
{quote} Include stdlib.mqh and use the : string ErrorDescription(int error_code); function for that Or see the stdlib.mq4 file in the libraries folder
Ignored
Thank you. I have been looking for something like this.
 
 
  • Post #32
  • Quote
  • May 18, 2022 8:53am May 18, 2022 8:53am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Where to use Stop Level?
A stop level is one of the Symbol Properties in MQL4 which means its one of MarketInfo() identifiers.

Inserted Code
double MarketInfo(Symbol(),MODE_STOPLEVEL)

Always remember that a stop level can be zero(ECN).
A zero value of MODE_STOPLEVEL means either absence of any restrictions on the minimal distance for Stop Loss/Take Profit or the fact that a trade server utilizes some external mechanisms for dynamic level control, which cannot be translated in the client terminal. In the second case, GetLastError() can return error 130, because MODE_STOPLEVEL is actually "floating" here.

1. You can't move stops (or pending prices) closer to the market than the minimum (MODE_STOPLEVEL * _Point.)
Requirements and Limitations in Making Trades - Appendixes - MQL4 Tutorial
2. You can't delete pending orders when the market is closer to price than stop level.
3.You can't close open orders when the market is closer to TP/SL than stop level.

So it's good practice to check stop level before using :

  1. OrderSend
  2. OrderModify
  3. OrderClose
  4. OrderDelete

and since it can be returned as zero dont forget to add if statements to deal with that. I learnt that the add way lol

Freeze Level seems similar to stop level but I haven't understood it well yet.

 
1
  • Post #33
  • Quote
  • May 18, 2022 1:46pm May 18, 2022 1:46pm
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
A useful post on closing orders and loops
https://www.mql5.com/en/forum/139654
 
 
  • Post #34
  • Quote
  • Jul 1, 2022 4:15am Jul 1, 2022 4:15am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Semantic Versioning 2.0.0
Source: click here
As a programmer, we need to be able to track different versions effectively especially when the current version is not compatible with the previous one or when you need to rewrite part of the code.
Semantic versioning seems to be the best practice.
I would like to see if it can be applied in mql4.

This is not a new or revolutionary idea. In fact, you probably do something close to this already. The problem is that “close” isn’t good enough. Without compliance to some sort of formal specification, version numbers are essentially useless for dependency management. By giving a name and clear definition to the ideas below, it becomes easy to communicate your intentions to the users of your software. Once these intentions are clear, flexible (but not too flexible) dependency specifications can finally be made.

"In the world of software management there exists a dreaded place called “dependency hell.” The bigger your system grows and the more packages you integrate into your software, the more likely you are to find yourself, one day, in this pit of despair. (I found myself in it recently lol)
In systems with many dependencies, releasing new package versions can quickly become a nightmare. If the dependency specifications are too tight, you are in danger of version lock (the inability to upgrade a package without having to release new versions of every dependent package). If dependencies are specified too loosely, you will inevitably be bitten by version promiscuity (assuming compatibility with more future versions than is reasonable). Dependency hell is where you are when version lock and/or version promiscuity prevent you from easily and safely moving your project forward.

As a solution to this problem, we propose a simple set of rules and requirements that dictate how version numbers are assigned and incremented. These rules are based on but not necessarily limited to pre-existing widespread common practices in use in both closed and open-source software. For this system to work, you first need to declare a public API. This may consist of documentation or be enforced by the code itself. Regardless, it is important that this API be clear and precise. Once you identify your public API, you communicate changes to it with specific increments to your version number. Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version."

Version numbers and the way they change convey meaning about the underlying code and what has been modified from one version to the next.
Given a version number MAJOR.MINOR.PATCH, increment the:

  1. MAJOR version when you make incompatible API changes,
  2. MINOR version when you add functionality in a backwards compatible manner, and
  3. PATCH version when you make backwards compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

Semantic Versioning Specification (SemVer)

The key words “MUST”, “MUST NOT”, “REQUIRED”, “SHALL”, “SHALL NOT”, “SHOULD”, “SHOULD NOT”, “RECOMMENDED”, “MAY”, and “OPTIONAL” in this document are to be interpreted as described in RFC 2119.

  1. Software using Semantic Versioning MUST declare a public API. This API could be declared in the code itself or exist strictly in documentation. However it is done, it SHOULD be precise and comprehensive.
  2. A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor version, and Z is the patch version. Each element MUST increase numerically. For instance: 1.9.0 -> 1.10.0 -> 1.11.0.
  3. Once a versioned package has been released, the contents of that version MUST NOT be modified. Any modifications MUST be released as a new version.
  4. Major version zero (0.y.z) is for initial development. Anything MAY change at any time. The public API SHOULD NOT be considered stable.
  5. Version 1.0.0 defines the public API. The way in which the version number is incremented after this release is dependent on this public API and how it changes.
  6. Patch version Z (x.y.Z | x > 0) MUST be incremented if only backwards compatible bug fixes are introduced. A bug fix is defined as an internal change that fixes incorrect behavior.
  7. Minor version Y (x.Y.z | x > 0) MUST be incremented if new, backwards compatible functionality is introduced to the public API. It MUST be incremented if any public API functionality is marked as deprecated. It MAY be incremented if substantial new functionality or improvements are introduced within the private code. It MAY include patch level changes. Patch version MUST be reset to 0 when minor version is incremented.
  8. Major version X (X.y.z | X > 0) MUST be incremented if any backwards incompatible changes are introduced to the public API. It MAY also include minor and patch level changes. Patch and minor versions MUST be reset to 0 when major version is incremented.
  9. A pre-release version MAY be denoted by appending a hyphen and a series of dot separated identifiers immediately following the patch version. Identifiers MUST comprise only ASCII alphanumerics and hyphens [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers MUST NOT include leading zeroes. Pre-release versions have a lower precedence than the associated normal version. A pre-release version indicates that the version is unstable and might not satisfy the intended compatibility requirements as denoted by its associated normal version. Examples: 1.0.0-alpha, 1.0.0-alpha.1, 1.0.0-0.3.7, 1.0.0-x.7.z.92, 1.0.0-x-y-z.–.
  10. Build metadata MAY be denoted by appending a plus sign and a series of dot separated identifiers immediately following the patch or pre-release version. Identifiers MUST comprise only ASCII alphanumerics and hyphens [0-9A-Za-z-]. Identifiers MUST NOT be empty. Build metadata MUST be ignored when determining version precedence. Thus two versions that differ only in the build metadata, have the same precedence. Examples: 1.0.0-alpha+001, 1.0.0+20130313144700, 1.0.0-beta+exp.sha.5114f85, 1.0.0+21AF26D3—-117B344092BD.
  11. Precedence refers to how versions are compared to each other when ordered.

    1. Precedence MUST be calculated by separating the version into major, minor, patch and pre-release identifiers in that order (Build metadata does not figure into precedence).
    2. Precedence is determined by the first difference when comparing each of these identifiers from left to right as follows: Major, minor, and patch versions are always compared numerically.
      Example: 1.0.0 < 2.0.0 < 2.1.0 < 2.1.1.
    3. When major, minor, and patch are equal, a pre-release version has lower precedence than a normal version:
      Example: 1.0.0-alpha < 1.0.0.
    4. Precedence for two pre-release versions with the same major, minor, and patch version MUST be determined by comparing each dot separated identifier from left to right until a difference is found as follows:

      1. Identifiers consisting of only digits are compared numerically.
      2. Identifiers with letters or hyphens are compared lexically in ASCII sort order.
      3. Numeric identifiers always have lower precedence than non-numeric identifiers.
      4. A larger set of pre-release fields has a higher precedence than a smaller set, if all of the preceding identifiers are equal.

      Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0.

 
1
  • Post #35
  • Quote
  • Jul 6, 2022 3:09am Jul 6, 2022 3:09am
  •  clemmo17
  • Joined Jul 2016 | Status: Member | 2,487 Posts
This seems logical, but why is there so much emphasis on releasing a public API? What does it have to do with version numbering?
 
 
  • Post #36
  • Quote
  • Last Post: Jul 6, 2022 4:28am Jul 6, 2022 4:28am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Quoting clemmo17
Disliked
This seems logical, but why is there so much emphasis on releasing a public API? What does it have to do with version numbering?
Ignored
I personally view most API changes as minor updates since the changes in API are usually:

  1. a change in the format of the response data for one or more calls
  2. a change in the request or response type (i.e. changing an integer to a float or double)
  3. removing any part of the API.

But most sites say that these changes are a major breaking updates.
Ignoring the API parts, I liked semantics MAJOR.MINOR.PATCH version numbering format.
And in mql programming, API isn't really a very important part of the code

 
1
  • Platform Tech
  • /
  • Random Useful MQL4 Functions
  • Reply to Thread
    • 1 Page 2
    • 1 Page 2
0 traders viewing now
Top of Page
  • Facebook
  • Twitter
About EE
  • Mission
  • Products
  • User Guide
  • Blog
  • Contact
EE Products
  • Forums
  • Calendar
  • News
  • Market
EE Website
  • Homepage
  • Search
  • Members
  • Report a Bug
Follow EE
  • Facebook
  • Twitter

EE Sister Sites:

  • Metals Mine
  • Crypto Craft
  • Forex Factory

Energy EXCH™ is a brand of Fair Economy, Inc.

Terms of Service / ©2023