• Home
  • Forums
  • News
  • Calendar
  • Market
  • Login
  • Join
  • 12:08pm
Menu
  • Forums
  • News
  • Calendar
  • Market
  • Login
  • Join
  • 12:08pm
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
  •  
  • Page 1 2
  • Page 1 2
  •  
  • Poll

  • Is MQL5 worth Learning
  •  
  •  
  •  
  •  
  •  
  • Post #1
  • Quote
  • First Post: Edited Jul 1, 2022 4:18am Jan 7, 2022 5:27am | Edited Jul 1, 2022 4:18am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
This thread is for posting useful user defined MQL4 functions, operators and also code blocks
It might also included some off-topic related posts
I don't take credit for all the functions I post. Some of them are ones that I created myself, others from books, articles, pdfs, somebody else's code etc.
You can use them as include files/imports/straight up copy paste...
Discussions on MQl4 programing are allowed.
You can also post an improved/different version of an already posted function.
To understand most of these posts you need to have some basic understanding of MQL4

credit: Books,Articles etc used

  1. Expert Advisor Programming by Andrew R Young



Don't spam this thread with requests for EA/Custom Indicators/Scripts creation..(Send a pm, I might do it for a fee)

CONTENT

  1. Function for converting points to pips................................................................................................#post2
  2. Function for converting Slippage points to pips................................................................................. #post3
  3. Stop Loss calculation .........................................................................................................................#post9
  4. Calculating TP and SL........................................................................................................................ #post11
  5. Alternate SL Methods ....................................using Highs and Lows of current candle.......................#post13
  6. using Highs and Lows of x no of Bars...........................#post14
  7. using indicator............................................................. #post16
  8. Lot Sizing Function............................................................................................................................ #post18
  9. Lot Size Verification...........................................................................................................................#post19
  10. Order Placement Function................................................................................................................. #post20
  11. Pending Order Placement Function.................................................................................................... #post21
  12. What are function return values? How do I use them?.......................................................................#post22
  13. Alphabetic Index of 600+ MQL4 functions......................................................................................... #post25
  14. Function that places Symbols in Market Watch into an Array.............................................................#post28
  15. stdlib.mqh..........................................................................................................................................#post30
  16. Where to use Stop Level?...................................................................................................................#post32
  17. A useful post on closing orders and loops(always countdown)..........................................................#post33
  18. Semantic Versioning 2.0.0..................................................................................................................#post34

  • Post #2
  • Quote
  • Jan 7, 2022 5:42am Jan 7, 2022 5:42am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Code for converting Points to Pips irrespective of what type of quotes the broker uses(Digits after decimal) and also what Currency you are using(The typical diff btn JPY quotes and USD quotes).
Useful when using OrderSend() to avoid errors if a broker uses a quote type that you didn't put into consideration.
especially when calculating SL and TP
The code assumes that there is already an external variable for the points.
Inserted Code
 
 double PipPoint(string Currency)
         {
         int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
         if(CalcDigits == 2 || CalcDigits == 3) double CalcPoint = 0.01;
         else if(CalcDigits == 4 || CalcDigits == 5) CalcPoint = 0.0001;
         return(CalcPoint);
         }  
          double UsePoint = PipPoint(Symbol());

Since these values will never change during program execution, we'll calculate these values in the
special function init().
The above code assumes that your EA is placing orders on one currency only. This will be the case 98% of the time,
but if you're creating an expert advisor that places orders on multiple currencies (or on a currency
other than the current chart), you'll need to use the PipPoint() functions every
time you need to calculate these values.
 
1
  • Post #3
  • Quote
  • Jan 7, 2022 5:52am Jan 7, 2022 5:52am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Similar to the Above Code but converts slippage points.
Also assumes there is an external variable for slippage
Inserted Code
   int GetSlippage(string Currency, int SlippagePips)
        {
         int CalcDigits = MarketInfo(Currency,MODE_DIGITS);
         if(CalcDigits == 2 || CalcDigits == 4) double CalcSlippage = SlippagePips;
         else if(CalcDigits == 3 || CalcDigits == 5) CalcSlippage == SlippagePips * 10;
          return(CalcSlippage);
             }


Here is how to use this function in OrderSend()
Inserted Code
   OrderSend(Symbol(),OP_BUY,LotSize,Ask,GetSlippage(Symbol(),Slippage),BuyStopLoss,BuyTakeProfit,"Buy Order",MagicNumber,0,Green);
 
 
  • Post #4
  • Quote
  • Jan 7, 2022 5:56am Jan 7, 2022 5:56am
  •  Isabella_D
  • Joined Jan 2012 | Status: Member | 1,140 Posts
thx, good idea. Have I creat an indi or script for every pair?
Or do you provide an EA?
 
 
  • Post #5
  • Quote
  • Jan 7, 2022 5:59am Jan 7, 2022 5:59am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Since these values will never change during program execution(values in the 2 previously posted codes), we'll calculate these values in the
init() function. We'll assume that the external integer variable for Slippage and points is already present:
Inserted Code
// Global variables
double UsePoint;
int UseSlippage;
int init()
{
UsePoint = PipPoint(Symbol());
UseSlippage = GetSlippage(Symbol(),Slippage);
}
From now on, we'll use UsePoint and UseSlippage to refer to these values. The above code
assumes that your EA is placing orders on one currency only. This will be the case 98% of the time,
but if you're creating an expert advisor that places orders on multiple currencies (or on a currency
other than the current chart), you'll need to use the PipPoint() and GetSlippage() functions every
time you need to calculate these values.
 
1
  • Post #6
  • Quote
  • Jan 7, 2022 6:19am Jan 7, 2022 6:19am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Quoting Isabella_D
Disliked
thx, good idea. Have I creat an indi or script for every pair?
Ignored
No, using Symbol() you can create just one EA or Indicator / script for every pair...the issue comes up if your EA is trying to open a trade for a currency other than the one for the window it is attached to.
NB: These are just small simple code blocks that you can use when creating a complex code for an EA. Not complete codes..

Quote
Disliked
Or do you provide an EA?

I currently don't have any EA that I think is worth sharing nor any that I am allowed to share.
 
1
  • Post #7
  • Quote
  • Jan 7, 2022 6:33am Jan 7, 2022 6:33am
  •  Isabella_D
  • Joined Jan 2012 | Status: Member | 1,140 Posts
[quote=Kefada;13849222]{quote} No, using Symbol() you can create just one EA or Indicator / script for every pair...
ok, I will try it to implement. Otherwise I ask for help if it does not happen.
 
 
  • Post #8
  • Quote
  • Jan 7, 2022 6:36am Jan 7, 2022 6:36am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
[quote=Isabella_D;13849236]
Quoting Kefada
Disliked
{quote} No, using Symbol() you can create just one EA or Indicator / script for every pair... ok, I will try it to implement. Otherwise I ask for help if it does not happen.
Ignored
No problem...
 
1
  • Post #9
  • Quote
  • Jan 7, 2022 6:52am Jan 7, 2022 6:52am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Here's our buy order stop loss calculation from, with the UsePoint (refer #post5 )variable added. Note that
we've assigned the Ask price to the OpenPrice variable:
Inserted Code
  double OpenPrice = Ask;
  if(StopLoss > 0) double BuyStopLoss = OpenPrice – (StopLoss * UsePoint);

And here's the calculation for a sell order. Note that we've assigned the Bid price to OpenPrice, and
that we are simply adding instead of subtracting:
Inserted Code
double OpenPrice = Bid;
if(StopLoss > 0) double SellStopLoss = OpenPrice + (StopLoss * UsePoint);
 
 
  • Post #10
  • Quote
  • Jan 7, 2022 7:10am Jan 7, 2022 7:10am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Quoting Kefada
Disliked
Here's our buy order stop loss calculation from, with the UsePoint (refer #post5 )variable added. Note that we've assigned the Ask price to the OpenPrice variable: double OpenPrice = Ask; if(StopLoss > 0) double BuyStopLoss = OpenPrice – (StopLoss * UsePoint); And here's the calculation for a sell order. Note that we've assigned the Bid price to OpenPrice, and that we are simply adding instead of subtracting: double OpenPrice = Bid; if(StopLoss > 0) double SellStopLoss =...
Ignored
For pending orders, the stop loss will be calculated relative to the pending order price. In this case,
use the variable OpenPrice to store the pending order price instead of the current market price. The
logic will be identical to the examples above.
 
 
  • Post #11
  • Quote
  • Jan 7, 2022 7:15am Jan 7, 2022 7:15am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Calculating Take Profit
Calculating the tp price is similar to calculating sl, except we'll be reversing
addition and subtraction.
For a buy order, the tp price will be above the order opening price,
and for a sell order, the tp price will be below the order opening price.
We'll assume that the appropriate price has been assigned to OpenPrice:

Inserted Code
 if(TakeProfit > 0) double BuyTakeProfit = OpenPrice + (TakeProfit * UsePoint);

Inserted Code
 if(TakeProfit > 0) double SellTakeProfit = OpenPrice - (TakeProfit * UsePoint);

Remember Usepoint from post#5
 
 
  • Post #12
  • Quote
  • Jan 7, 2022 7:22am Jan 7, 2022 7:22am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Alternative Stop Loss methods
In the above methods, SL is set using a predefined amount of points/pips.
But there are other methods of placing SL e.g A previous high or Low, or an indicator value.
Lets see how we can code this in the next posts
 
 
  • Post #13
  • Quote
  • Jan 7, 2022 7:33am Jan 7, 2022 7:33am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Lets say that we are using a system that places the SL 2 pips below the low of the current bar.
We shall use the predefined price array Low[] to retrieve the low of the bar.
Low[0] is the low of the current bar
Low[1] is the low of the previous bar and so on...
Attached Image (click to enlarge)
Click to Enlarge

Name: MetaEditor-MQL4-GetCandlePrice-1.jpg
Size: 114 KB
the image shows Price array(Timeseries) indexing of bars/candles in MQL4. 0 is the index of the latest bar.

Once we've determined the low of the current bar, we multiply 2 by UsePoint to get a decimal value,
and subtract that from our low:

Inserted Code
 double BuyStopLoss = Low[0] – (2 * UsePoint);

So if the low of the bar is 1.4760, the stop loss will be placed at 1.4758.
 
 
  • Post #14
  • Quote
  • Jan 7, 2022 7:40am Jan 7, 2022 7:40am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Suppose your system requires you to place your stop loss at the lowest low of the last x number of bars.
There's a function built into MetaTrader just for that:
iLowest() returns the shift value indicating the bar with the lowest value in a specified time range.
We can use high, low, open or close values.

Here's an example of how we would use iLowest() to find the lowest low of the last 20 bars:
Inserted Code
int CountBars = 20;
int LowestShift = iLowest(NULL,0,MODE_LOW,CountBars,0);
double BuyStopLoss = Low[LowestShift];
Here is iLowest Syntax:

Inserted Code
        int iLowest(
            string  symbol,              // symbol
            int      timeframe,          // timeframe
            int      type,                  // timeseries id
            int      count,                // count
            int       start );            // starting index

Parameters
symbol
[in] Symbol name. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the current chart timeframe.
type
[in] Series array identifier. It can be any of the Series array identifier enumeration values.
count=WHOLE_ARRAY
[in] Number of bars (in direction from the start bar to the back one) on which the search is carried out.
start=0
[in] Shift showing the bar, relative to the current bar, that the data should be taken from.
Returned value
The shift of the lowest value over a specific number of bars or -1 if error. To check errors, one has to call the GetLastError() function.
 
 
  • Post #15
  • Quote
  • Jan 7, 2022 7:48am Jan 7, 2022 7:48am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Quoting Kefada
Disliked
Suppose your system requires you to place your stop loss at the lowest low of the last x number of bars. There's a function built into MetaTrader just for that: iLowest() returns the shift value indicating the bar with the lowest value in a specified time range. We can use high, low, open or close values. Here's an example of how we would use iLowest() to find the lowest low of the last 20 bars: int CountBars = 20; int LowestShift = iLowest(NULL,0,MODE_LOW,CountBars,0); double BuyStopLoss = Low[LowestShift]; Here is iLowest Syntax: int iLowest(...
Ignored
If you wanted to calculate a stop loss for a sell order using this method, the iHighest() function
works the same way. Referencing the example above, you would use MODE_HIGH for your series array parameter.
 
 
  • Post #16
  • Quote
  • Jan 7, 2022 7:52am Jan 7, 2022 7:52am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
An example using an indicator.
Let's say we have a moving average, and we want to use the moving average line as our stop loss.
We'll use the variable MA to represent the moving average value for the current bar.
All you need to do is assign the current moving average value to the stop loss:

Inserted Code
 double BuyStopLoss = MA;

If the moving average line is currently at 1.6894, then that will be our stop loss.
 
 
  • Post #17
  • Quote
  • Jan 7, 2022 7:53am Jan 7, 2022 7:53am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
These are simply the most common methods of determining a stop loss or take profit price. Other methods can be developed using your knowledge of technical analysis or your imagination.
 
 
  • Post #18
  • Quote
  • Edited 1:23am Jan 10, 2022 12:45am | Edited 1:23am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Lot Sizing Function
Note that DynamicLotSize, EquityPercent, FixedLotSize and StopLoss are external variables

Inserted Code
double CalcLotSize(bool DynamicLotSize, double EquityPercent, double StopLoss,
double FixedLotSize)
{
if(DynamicLotSize == true)
{
double RiskAmount = AccountEquity() * (EquityPercent / 100);
double TickValue = MarketInfo(Symbol(),MODE_TICKVALUE);
if(Point == 0.001 || Point == 0.00001) TickValue *= 10;
double LotSize = (RiskAmount / argStopLoss) / TickValue;
}
else LotSize = FixedLotSize;
return(LotSize);
}
 
 
  • Post #19
  • Quote
  • Jan 10, 2022 1:27am Jan 10, 2022 1:27am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Lot Size Verification Function
The LotSize variable is from the above function

Inserted Code
double VerifyLotSize(double LotSize)
{
if(LotSize < MarketInfo(Symbol(),MODE_MINLOT))
{
LotSize = MarketInfo(Symbol(),MODE_MINLOT);
}
else if(LotSize > MarketInfo(Symbol(),MODE_MAXLOT))
{
LotSize = MarketInfo(Symbol(),MODE_MAXLOT);
}
if(MarketInfo(Symbol(),MODE_LOTSTEP) == 0.1)
{
LotSize = NormalizeDouble(LotSize,1);
}
else LotSize = NormalizeDouble(LotSize,2);
 
return(LotSize);
}
 
 
  • Post #20
  • Quote
  • Jan 10, 2022 3:47am Jan 10, 2022 3:47am
  •  Kefada
  • Joined Jul 2021 | Status: Coder for Hire | 156 Posts
Order Placement Function
We are specifying the order symbol using the Symbol argument, instead of simply using the current chart symbol.
This way, if you decide to place an order on another symbol, you can do so easily.
Instead of using the predefined Bid and Ask variables, we'll need to use the MarketInfo() function with the MODE_ASK and MODE_BID parameters to retrieve the Bid and Ask price for that particular symbol.
We have also specified a default value for the order comment. The argument Comment has a default value, "Buy Order". If no value is specified for this argument, then the default is used.
We'll assume that the lot size and slippage have been calculated and verified prior to calling this function
Inserted Code
int OpenBuyOrder(string Symbol(), double LotSize, double Slippage, double MagicNumber, string Comment = "Buy Order")
{
  while(IsTradeContextBusy()) Sleep(10);
   
// Place Buy Order
    int Ticket = OrderSend(Symbol(),OP_BUY,LotSize,MarketInfo(Symbol(),MODE_ASK), Slippage,0,0,Comment,MagicNumber,0,Green);
   
  // Error Handling
     if(Ticket == -1)
      {
    int ErrorCode = GetLastError();
    string ErrDesc = ErrorDescription(ErrorCode);
    string ErrAlert = StringConcatenate("Open Buy Order – Error ",
    ErrorCode,": ",ErrDesc);
  Alert(ErrAlert);
      string ErrLog = StringConcatenate("Bid: ",MarketInfo(Symbol(),MODE_BID)," Ask: ",MarketInfo(Symbol(),MODE_ASK)," Lots: ",LotSize);
   Print(ErrLog);
      }
   return(Ticket);
In the OrderSend() function, note that we've used the MarketInfo() function with the MODE_ASK parameter, in place of the predefined Ask variable. This will retrieve the current Ask price for the currency symbol indicated by Symbol().
If the trade was not placed successfully, the error handling routine will be run. Otherwise the order ticket will be returned to the calling function, or -1 if the order was not placed.
 
 
  • Platform Tech
  • /
  • Random Useful MQL4 Functions
  • Reply to Thread
    • Page 1 2
    • Page 1 2
0 traders viewing now
  • More
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