0% found this document useful (0 votes)
454 views3 pages

Migrating From MQL4 To MQL5 - MQL5 Articles

The document provides a guide for developers on migrating trading indicators and strategies from MQL4 to MQL5, highlighting key differences and necessary code adjustments. It covers changes in chart periods, declaration of constants, predefined variables, account information, and array functions. The article aims to simplify the conversion process by offering examples and clarifications on the new MQL5 syntax and functionalities.

Uploaded by

Martin De Leo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
454 views3 pages

Migrating From MQL4 To MQL5 - MQL5 Articles

The document provides a guide for developers on migrating trading indicators and strategies from MQL4 to MQL5, highlighting key differences and necessary code adjustments. It covers changes in chart periods, declaration of constants, predefined variables, account information, and array functions. The article aims to simplify the conversion process by offering examples and clarifications on the new MQL5 syntax and functionalities.

Uploaded by

Martin De Leo
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Forum Market Signals Freelance VPS Quotes Type / to search: @user, $symbol, ...

Search Martin De English

Articles CodeBase Documentation AlgoBook NeuroBook Calendar WebTerminal Algo Trading Channel

Examples
Add a new article
Indicators

Experts Migrating from MQL4 to MQL5


Tester MetaTrader 5 — Examples | 17 May 2010, 13:32
Trading 213 431 43
Trading systems

Integration

Indicators
Sergey Pavlov
Expert Advisors
Introduction
Statistics and analysis
Many developers have accumulated a lot of indicators and trading strategies written in MQL4. To use them in Metatrader 5, they should be converted to MQL5. It's not so easy to rewrite all programs in MQL5. It would be much easier to convert them,
Machine learning if there were a translation-reference, and better with examples.

In this article I would like to suggest my version of a guide to migrate from MQL4 to MQL5.
Interviews
1. Chart Periods
My own
In MQL5 chart period constants changed, and some new time periods (M2, M3, M4, M6, M10, M12, H2, H3, H6, H8, H12) were added. To convert MQL4 time periods you can use the following function:
Do you like the article?
ENUM_TIMEFRAMES TFMigrate(int tf)
Share it with others — {
post a link to it! switch(tf)
{
Find us on Facebook! case 0: return(PERIOD_CURRENT);
Join our fan page case 1: return(PERIOD_M1);
case 5: return(PERIOD_M5);
case 15: return(PERIOD_M15);
Use new possibilities of
case 30: return(PERIOD_M30);
MetaTrader 5 case 60: return(PERIOD_H1);
case 240: return(PERIOD_H4);
case 1440: return(PERIOD_D1);
case 10080: return(PERIOD_W1);
case 43200: return(PERIOD_MN1);

case 2: return(PERIOD_M2);
case 3: return(PERIOD_M3);
case 4: return(PERIOD_M4);
case 6: return(PERIOD_M6);
case 10: return(PERIOD_M10);
case 12: return(PERIOD_M12);
case 16385: return(PERIOD_H1);
case 16386: return(PERIOD_H2);
case 16387: return(PERIOD_H3);
case 16388: return(PERIOD_H4);
case 16390: return(PERIOD_H6);
case 16392: return(PERIOD_H8);
case 16396: return(PERIOD_H12);
case 16408: return(PERIOD_D1);
case 32769: return(PERIOD_W1);
case 49153: return(PERIOD_MN1);
default: return(PERIOD_CURRENT);
}
}

It should be noted, that in MQL5 the numerical values of chart timeframe constants (from H1) are not equal to the number of minutes of a bar (for example, in MQL5, the numerical value of constant PERIOD_H1=16385, but in MQL4
PERIOD_H1=60). You should take it into account when converting to MQL5, if numerical values of MQL4 constants are used in MQL4 programs.

Similar articles To determine the number of minutes of the specified time period of the chart, divide the value, returned by function PeriodSeconds by 60.

Creating a Trading 2. Declaring Contants


Administrator Panel in MQL5
(Part IV): Login Security Layer Some of standard MQL4 constants are absent in MQL5, therefore they should be declared:

Developing a Replay System //+------------------------------------------------------------------+


(Part 48): Understanding the //| InitMQL4.mqh |
concept of a service //| Copyright DC2008 |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
MQL5 Trading Toolkit (Part 3): #property copyright "keiji"
Developing a Pending Orders #property copyright "DC2008"
Management EX5 Library #property link "https://www.mql5.com"
//--- Declaration of constants
Body in Connexus (Part 4): #define OP_BUY 0 //Buy
#define OP_SELL 1 //Sell
Adding HTTP body support
#define OP_BUYLIMIT 2 //Pending order of BUY LIMIT type
#define OP_SELLLIMIT 3 //Pending order of SELL LIMIT type
Developing a Replay System #define OP_BUYSTOP 4 //Pending order of BUY STOP type
(Part 47): Chart Trade Project #define OP_SELLSTOP 5 //Pending order of SELL STOP type
(VI) //---
#define MODE_OPEN 0
#define MODE_CLOSE 3
#define MODE_VOLUME 4
#define MODE_REAL_VOLUME 5
#define MODE_TRADES 0
#define MODE_HISTORY 1
#define SELECT_BY_POS 0
#define SELECT_BY_TICKET 1
//---
#define DOUBLE_VALUE 0
#define FLOAT_VALUE 1
#define LONG_VALUE INT_VALUE
//---
#define CHART_BAR 0
#define CHART_CANDLE 1
//---
#define MODE_ASCEND 0
#define MODE_DESCEND 1
//---
#define MODE_LOW 1
#define MODE_HIGH 2
#define MODE_TIME 5
#define MODE_BID 9
#define MODE_ASK 10
#define MODE_POINT 11
#define MODE_DIGITS 12
#define MODE_SPREAD 13
#define MODE_STOPLEVEL 14
#define MODE_LOTSIZE 15
#define MODE_TICKVALUE 16
#define MODE_TICKSIZE 17
#define MODE_SWAPLONG 18
#define MODE_SWAPSHORT 19
#define MODE_STARTING 20
#define MODE_EXPIRATION 21
#define MODE_TRADEALLOWED 22
#define MODE_MINLOT 23
#define MODE_LOTSTEP 24
#define MODE_MAXLOT 25
#define MODE_SWAPTYPE 26
#define MODE_PROFITCALCMODE 27
#define MODE_MARGINCALCMODE 28
#define MODE_MARGININIT 29
#define MODE_MARGINMAINTENANCE 30
#define MODE_MARGINHEDGED 31
#define MODE_MARGINREQUIRED 32
#define MODE_FREEZELEVEL 33
//---
#define EMPTY -1

Note: Constants in MQl4 and MQL5 differ, therefore it's better to declare them in a separate file initMQ4.mqh for futher use.

3. Predefined Variables

MQL4 MQL5 Description


MqlTick last_tick; Ask
double Ask SymbolInfoTick(_Symbol,last_tick); The latest known ask price for the current symbol.
double Ask=last_tick.ask; SymbolInfoTick
Bars
int Bars int Bars=Bars(_Symbol,_Period); Number of bars in the current chart.
Bars
MqlTick last_tick; Bid
double Bid SymbolInfoTick(_Symbol,last_tick); The latest known bid price of the current symbol.
double Bid=last_tick.bid; SymbolInfoTick

double Close[];
Close
int count; // number of elements to copy
double Close[]
ArraySetAsSeries(Close,true); Series array that contains close prices for each bar of the current chart.
CopyClose(_Symbol,_Period,0,count,Close); CopyClose, ArraySetAsSeries

Digits
Number of digits after the decimal point for the current symbol prices.
int Digits int Digits=_Digits;
_Digits

double High[];
High
int count; // number of elements to copy
double High[]
ArraySetAsSeries(High,true); Series array that contains the highest prices of each bar of the current chart.
CopyHigh(_Symbol,_Period,0,count,High); CopyHigh, ArraySetAsSeries

double Low[];
Low
int count; // number of elements to copy
double Low[]
ArraySetAsSeries(Low,true); Series array that contains the lowest prices of each bar of the current chart.
CopyLow(_Symbol,_Period,0,count,Low); CopyLow, ArraySetAsSeries

double Open[];
Open
int count; // number of elements to copy
double Open[]
ArraySetAsSeries(Open,true); Series array that contains open prices of each bar of the current chart.
CopyOpen(_Symbol,_Period,0,count,Open); CopyOpen, ArraySetAsSeries

Point
double Point double Point=_Point; The current symbol point value in the quote currency.
_Point
datetime Time[]; Time
int count; // number of elements to copy Series array that contains open time of each bar of the current chart. Data like datetime represent time, in seconds, that has passed since 00:00 a.m. of 1
datetime Time[]
ArraySetAsSeries(Time,true); January, 1970.
CopyTime(_Symbol,_Period,0,count,Time); CopyTime, ArraySetAsSeries

long Volume[];
Volume
int count; // number of elements to copy
double Volume[]
ArraySetAsSeries(Volume,true); Series array that contains tick volumes of each bar of the current chart.
CopyTickVolume(_Symbol,_Period,0,count,Volume); CopyTickVolume, ArraySetAsSeries

4. Account Information

MQL4 MQL5 Description


AccountBalance
double AccountBalance() double AccountInfoDouble(ACCOUNT_BALANCE) Returns balance value of the current account (the amount of money on the account).
AccountInfoDouble
AccountCredit
double AccountCredit() double AccountInfoDouble(ACCOUNT_CREDIT) Returns credit value of the current account.
AccountInfoDouble
AccountCompany
string AccountCompany() string AccountInfoString(ACCOUNT_COMPANY) Returns the brokerage company name where the current account was registered.
AccountInfoString
AccountCurrency
string AccountCurrency() string AccountInfoString(ACCOUNT_CURRENCY) Returns currency name of the current account.
AccountInfoString
AccountEquity
double AccountEquity() double AccountInfoDouble(ACCOUNT_EQUITY) Returns equity value of the current account. Equity calculation depends on trading server settings.
AccountInfoDouble
AccountFreeMargin
double AccountFreeMargin() double AccountInfoDouble(ACCOUNT_FREEMARGIN) Returns free margin value of the current account.
AccountInfoDouble
double AccountFreeMarginCheck(string symbol,
AccountFreeMarginCheck
int cmd, -
double volume) Returns free margin that remains after the specified position has been opened at the current price on the current account.

AccountFreeMarginMode
double AccountFreeMarginMode() -
Calculation mode of free margin allowed to open positions on the current account.
AccountLeverage
int AccountLeverage() int AccountInfoInteger(ACCOUNT_LEVERAGE) Returns leverage of the current account.
AccountInfoInteger
AccountMargin
double AccountMargin() double AccountInfoDouble(ACCOUNT_MARGIN) Returns margin value of the current account.
AccountInfoDouble
AccountName
string AccountName() string AccountInfoString(ACCOUNT_NAME) Returns the current account name.
AccountInfoString
AccountNumber
int AccountNumber() int AccountInfoInteger(ACCOUNT_LOGIN) Returns the number of the current account.
AccountInfoInteger
AccountProfit
double AccountProfit() double AccountInfoDouble(ACCOUNT_PROFIT) Returns profit value of the current account.
AccountInfoDouble
AccountServer
string AccountServer() string AccountInfoString(ACCOUNT_SERVER) Returns the connected server name.
AccountInfoString
AccountStopoutLevel
int AccountStopoutLevel() double AccountInfoDouble(ACCOUNT_MARGIN_SO_SO) Returns the value of the Stop Out level.
AccountInfoDouble
AccountStopoutMode
int AccountStopoutMode() int AccountInfoInteger(ACCOUNT_MARGIN_SO_MODE) Returns the calculation mode for the Stop Out level.
AccountInfoInteger

5. Array Functions

MQL4 MQL5 Description


int ArrayBsearch(double array[],
double value, int ArrayBsearch(double array[], ArrayBsearch
int count=WHOLE_ARRAY, double searched_value The function searches for a specified value in a one-dimension numeric array.
int start=0, ) ArrayBsearch
int direction=MODE_ASCEND)

int ArrayCopy(void dst_array[],


int ArrayCopy(object&dest[], ArrayCopy
void src_array[],
object source[], Copies an array to another one. Arrays must be of the same type, but arrays with type double[], int[],
int dst_start=0,
int start_dest=0,
int src_start=0, datetime[], color[], and bool[] can be copied as arrays of the same type. Returns the amount of copied
int start_source=0,
int cnt=WHOLE_ARRAY elements.
int count=WHOLE_ARRAY) ArrayCopy
)

int ArrayCopyRates(double&dest_array[], ArrayCopyRates


string symbol=NULL, - Copies data of the current chart bars to the two-dimensional array of RateInfo[][6] type and returns copied bars
int timeframe=0) amount, or -1 if failed.

int ArrayCopySeriesMQL4(double &array[],


int series_index,
string symbol=NULL,
int tf=0)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int count=Bars(symbol,timeframe);
switch(series_index)
{
int ArrayCopySeries(double&array[], case MODE_OPEN:
ArrayCopySeries
int series_index, return(CopyOpen(symbol,timeframe,0,count,array));
string symbol=NULL, case MODE_LOW: Copies a timeseries array to a custom array and returns the count of the copied elements.
int timeframe=0) return(CopyLow(symbol,timeframe,0,count,array)); CopyOpen, CopyLow, CopyHigh, CopyClose, Bars
case MODE_HIGH:
return(CopyHigh(symbol,timeframe,0,count,array));
case MODE_CLOSE:
return(CopyClose(symbol,timeframe,0,count,array));

default: return(0);
}
return(0);
}

ArrayDimension
int ArrayDimension( object array[]) -
Returns the multidimensional array rank.
ArrayGetAsSeries
Returns TRUE if an array is organized as a timeseries array (array elements are indexed from the last to the first
bool ArrayGetAsSeries( object array[]) bool ArrayGetAsSeries(void array)
one), otherwise returns FALSE.
ArrayGetAsSeries
int ArrayInitializeMQL4(double &array[],
double value)
ArrayInitialize
int ArrayInitialize(double &array[], {
double value) ArrayInitialize(array,value); Sets all elements of a numeric array to the same value. Returns the count of initialized elements.
return(ArraySize(array)); ArrayInitialize, ArraySize
}

ArrayIsSeries
Returns TRUE if the array under check is a timeseries array (Time[],Open[],Close[],High[],Low[], or Volume[]),
bool ArrayIsSeries( object array[]) bool ArrayIsSeries(void array[])
otherwise returns FALSE.
ArrayIsSeries
int ArrayMaximumMQL4(double &array[],
int count=WHOLE_ARRAY, ArrayMaximum
int ArrayMaximum(double array[],
int start=0) Searches for the element with the maximal value. The function returns position of this maximal element in the
int count=WHOLE_ARRAY,
int start=0)
{ array.
return(ArrayMaximum(array,start,count)); ArrayMaximum
}

int ArrayMinimumMQL4(double &array[],


int count=WHOLE_ARRAY, ArrayMinimum
int ArrayMinimum(double array[],
int start=0) Searches for the element with the minimal value. The function returns position of this minimal element in the
int count=WHOLE_ARRAY,
int start=0)
{ array.
return(ArrayMinimum(array,start,count)); ArrayMinimum
}

int ArrayRange(void array[], ArrayRange


int ArrayRange(object array[],
int range_index)
int rank_index Returns the count of elements in the given dimension of the array.
) ArrayRange

int ArrayResize(void array[],


ArrayResize
int ArrayResize(object &array[], int new_size,
int new_size) int allocated_size=0 Sets a new size for the first dimension.
) ArrayResize

ArraySetAsSeries
bool ArraySetAsSeries(void array[],
bool ArraySetAsSeries(double &array[], Returns the count of elements in the given dimension of the array. Since indexes are zero-based, the size of
bool set
bool set)
) dimension is 1 greater than the largest index.
ArraySetAsSeries
ArraySize
int ArraySize( object array[]) int ArraySize(void array[]) Returns the count of elements contained in the array.
ArraySize
int ArraySortMQL4(double &array[],
int count=WHOLE_ARRAY,
int start=0,
int sort_dir=MODE_ASCEND)
{
switch(sort_dir)
{
int ArraySort(double &array[],
case MODE_ASCEND: ArraySort
int count=WHOLE_ARRAY,
int start=0,
ArraySetAsSeries(array,true); Sorts numeric arrays by first dimension. Series arrays cannot be sorted by ArraySort().
case MODE_DESCEND: ArraySort, ArraySetAsSeries
int sort_dir=MODE_ASCEND)
ArraySetAsSeries(array,false);

default: ArraySetAsSeries(array,true);
}
ArraySort(array);
return(0);
}

6. Checkup

MQL4 MQL5 Description


GetLastError
The function returns the last occurred error, then the value of special last_error variable where the last error code is
int GetLastError() int GetLastError()
stored will be zeroized.
GetLastError
IsConnected
The function returns the status of the main connection between the client terminal and the server that performs data
bool IsConnected() bool TerminalInfoInteger(TERMINAL_CONNECTED)
pumping. It returns TRUE if connection to the server was successfully established, otherwise, it returns FALSE.
TerminalInfoInteger
bool IsDemoMQL4()
{
if(AccountInfoInteger(ACCOUNT_TRADE_MODE)==ACCOUNT_TRADE_MODE_DEMO) IsDemo
bool IsDemo() return(true); Returns TRUE if the expert runs on a demo account, otherwise returns FALSE.
else AccountInfoInteger
return(false);
}

IsDllsAllowed
bool IsDllsAllowed() bool TerminalInfoInteger(TERMINAL_DLLS_ALLOWED) Returns TRUE if the function DLL call is allowed for the Expert Advisor, otherwise returns FALSE.
TerminalInfoInteger
IsExpertEnabled
bool IsExpertEnabled() bool AccountInfoInteger(ACCOUNT_TRADE_EXPERT) Returns TRUE if use of Expert Advisors is enabled in the client terminal, otherwise returns FALSE.
AccountInfoInteger
IsLibrariesAllowed
bool IsLibrariesAllowed() bool MQLInfoInteger(MQL5_DLLS_ALLOWED) Returns TRUE if an Expert Advisor can call library function, otherwise returns FALSE.
MQLInfoInteger
IsOptimization
bool IsOptimization() bool MQLInfoInteger(MQL5_OPTIMIZATION) Returns TRUE if an Expert Advisor is running in the strategy tester optimization mode, otherwise returns FALSE.
MQLInfoInteger
IsStopped
Returns TRUE if the program (an Expert Advisor or a script) has been commanded to stop its operation, otherwise
bool IsStopped() bool IsStopped()
returns FALSE.
IsStopped
IsTesting
bool IsTesting() bool MQLInfoInteger(MQL5_TESTING) Returns TRUE if an Expert Advisor is running in the testing mode, otherwise returns FALSE.
MQLInfoInteger
IsTradeAllowed
bool IsTradeAllowed() bool MQLInfoInteger(MQL5_TRADE_ALLOWED) Returns TRUE if trading by Expert Advisors is allowed and a thread for trading is not occupied, otherwise returns FALSE.
MQLInfoInteger
IsTradeContextBusy
bool IsTradeContextBusy() -
Returns TRUE if a thread for trading is occupied by another Expert Advisor, otherwise returns FALSE.
IsVisualMode
bool IsVisualMode() bool MQLInfoInteger(MQL5_VISUAL_MODE) Returns TRUE if the Expert Advisor is tested with checked "Visual Mode" button, otherwise returns FALSE.
MQLInfoInteger
UninitializeReason
int UninitializeReason() int UninitializeReason() Returns the code of the uninitialization reason for Expert Advisors, custom indicators, and scripts.
UninitializeReason

7. Client Terminal

MQL4 MQL5 Description


TerminalCompany
string TerminalCompany() string TerminalInfoString(TERMINAL_COMPANY) Returns the name of company owning the client terminal.
TerminalInfoString
TerminalName
string TerminalName() string TerminalInfoString(TERMINAL_NAME) Returns client terminal name.
TerminalInfoString
TerminalPath
string TerminalPath() string TerminalInfoString(TERMINAL_PATH) Returns the directory, from which the client terminal was launched.
TerminalInfoString

8. Common Functions

MQL4 MQL5 Description


Alert
void Alert(...) void Alert(argument,...) Displays a dialog box containing the user-defined data. Parameters can be of any type.
Alert
Comment
void Comment(...) void Comment(argument,...) The function outputs the comment defined by the user in the left top corner of the chart.
Comment
GetTickCount
The GetTickCount() function retrieves the number of milliseconds that have elapsed since the system was
int GetTickCount() uint GetTickCount()
started.
GetTickCount
double MarketInfoMQL4(string symbol,
int type)
{
switch(type)
{
case MODE_LOW:
return(SymbolInfoDouble(symbol,SYMBOL_LASTLOW));
case MODE_HIGH:
return(SymbolInfoDouble(symbol,SYMBOL_LASTHIGH));
case MODE_TIME:
return(SymbolInfoInteger(symbol,SYMBOL_TIME));
case MODE_BID:
return(Bid);
case MODE_ASK:
return(Ask);
case MODE_POINT:
return(SymbolInfoDouble(symbol,SYMBOL_POINT));
case MODE_DIGITS:
return(SymbolInfoInteger(symbol,SYMBOL_DIGITS));
case MODE_SPREAD:
return(SymbolInfoInteger(symbol,SYMBOL_SPREAD));
case MODE_STOPLEVEL:
return(SymbolInfoInteger(symbol,SYMBOL_TRADE_STOPS_LEVEL));
case MODE_LOTSIZE:
return(SymbolInfoDouble(symbol,SYMBOL_TRADE_CONTRACT_SIZE));
case MODE_TICKVALUE:
return(SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_VALUE));
case MODE_TICKSIZE:
return(SymbolInfoDouble(symbol,SYMBOL_TRADE_TICK_SIZE));
case MODE_SWAPLONG:
return(SymbolInfoDouble(symbol,SYMBOL_SWAP_LONG));
case MODE_SWAPSHORT:
MarketInfo
double MarketInfo(string symbol, return(SymbolInfoDouble(symbol,SYMBOL_SWAP_SHORT));
int type) case MODE_STARTING: Returns various data about securities listed in the Market Watch window.
return(0); SymbolInfoInteger, SymbolInfoDouble, Bid, Ask
case MODE_EXPIRATION:
return(0);
case MODE_TRADEALLOWED:
return(0);
case MODE_MINLOT:
return(SymbolInfoDouble(symbol,SYMBOL_VOLUME_MIN));
case MODE_LOTSTEP:
return(SymbolInfoDouble(symbol,SYMBOL_VOLUME_STEP));
case MODE_MAXLOT:
return(SymbolInfoDouble(symbol,SYMBOL_VOLUME_MAX));
case MODE_SWAPTYPE:
return(SymbolInfoInteger(symbol,SYMBOL_SWAP_MODE));
case MODE_PROFITCALCMODE:
return(SymbolInfoInteger(symbol,SYMBOL_TRADE_CALC_MODE));
case MODE_MARGINCALCMODE:
return(0);
case MODE_MARGININIT:
return(0);
case MODE_MARGINMAINTENANCE:
return(0);
case MODE_MARGINHEDGED:
return(0);
case MODE_MARGINREQUIRED:
return(0);
case MODE_FREEZELEVEL:
return(SymbolInfoInteger(symbol,SYMBOL_TRADE_FREEZE_LEVEL));

default: return(0);
}
return(0);
}

int MessageBox(string text=NULL, int MessageBox(string text, MessageBox


string caption=NULL, string caption=NULL, The MessageBox function creates, displays, and operates message box.
int flags=EMPTY) int flags=0) MessageBox
PlaySound
void PlaySound(string filename) bool PlaySound(string filename) Function plays a sound file.
PlaySound
Print
void Print(...) void Print(argument,...) Prints a message to the experts log.
Print
SendFTP
bool SendFTP(string filename, bool SendFTP(string filename,
string ftp_path=NULL) string ftp_path=NULL) Sends the file to the FTP server set in the Tools->Options->Publisher tab. If the attempt fails, it retuns FALSE.
SendFTP
SendMail
void SendMail(string subject, bool SendMail(string subject,
string some_text) string some_text) Sends a message to the e-mail set in the Tools->Options->EMail tab.
SendMail
Sleep
void Sleep(int milliseconds) void Sleep(int milliseconds) The Sleep() function suspends execution of the current expert within the specified interval.
Sleep

9. Conversion Functions

MQL4 MQL5 Description


CharToStr
string CharToStr(int char_code) string CharToString(int char_code) Conversion of the symbol code into a one-character string.
CharToString
DoubleToStr
string DoubleToStr(double value, string DoubleToString(double value,
int digits) int digits=8) Returns text string with the specified numerical value converted into a specified precision format.
DoubleToString
NormalizeDouble
double NormalizeDouble(double value, double NormalizeDouble(double value,
int digits) int digits) Rounds the floating point value to the given precision. Returns normalized value of the double type.
NormalizeDouble
StrToDouble
double StrToDouble(string value) double StringToDouble(string value) Converts string representation of number to double type (double-precision format with floating point).
StringToDouble
StrToInteger
int StrToInteger(string value) long StringToInteger(string value) Converts string containing the value character representation into a value of the int (integer) type.
StringToInteger
StrToTime
Converts string in the format "yyyy.mm.dd hh:mi" to datetime type (the amount of seconds that have passed
datetime StrToTime(string value) datetime StringToTime(string value)
since 1 Jan., 1970).
StringToTime
TimeToStr
string TimeToStr(datetime value, string TimeToString(datetime value, Converts value containing time in seconds that has passed since January 1, 1970, into a string of "yyyy.mm.dd
int mode=TIME_DATE|TIME_MINUTES) int mode=TIME_DATE|TIME_MINUTES) hh:mi" format.
TimeToString

10. Custom Indicators

MQL4 MQL5 Description


IndicatorBuffers
void IndicatorBuffers(int count) -
Allocates memory for buffers used for custom indicator calculations.
int IndicatorCountedMQL4()
{
IndicatorCounted
if(prev_calculated>0) return(prev_calculated-1);
int IndicatorCounted()
if(prev_calculated==0) return(0); The function returns the amount of bars not changed after the indicator had been launched last.
return(0); OnCalculate
}

IndicatorDigits
void IndicatorDigits(int digits) bool IndicatorSetInteger(INDICATOR_DIGITS,digits) Sets precision format (the count of digits after decimal point) to visualize indicator values.
IndicatorSetInteger
IndicatorShortName
void IndicatorShortName(string name) bool IndicatorSetString(INDICATOR_SHORTNAME,name) Sets the "short" name of a custom indicator to be shown in the DataWindow and in the chart subwindow.
IndicatorSetString
SetIndexArrow
void SetIndexArrow(int index,
int code)
bool PlotIndexSetInteger(index,PLOT_ARROW,code) Sets an arrow symbol for indicators line of the DRAW_ARROW type.
PlotIndexSetInteger
SetIndexBuffer
bool SetIndexBuffer(int index,
double array[])
bool SetIndexBuffer(index,array,INDICATOR_DATA) Binds the array variable declared at a global level to the custom indicator pre-defined buffer.
SetIndexBuffer
SetIndexDrawBegin
void SetIndexDrawBegin(int index, Sets the bar number (from the data beginning) from which the drawing of the given indicator line must
bool PlotIndexSetInteger(index,PLOT_DRAW_BEGIN,begin)
int begin) start.
PlotIndexSetInteger
SetIndexEmptyValue
void SetIndexEmptyValue(int index,
double value)
bool PlotIndexSetDouble(index,PLOT_EMPTY_VALUE,value) Sets drawing line empty value.
PlotIndexSetDouble
SetIndexLabel
void SetIndexLabel(int index,
string text)
bool PlotIndexSetString(index,PLOT_LABEL,text) Sets drawing line description for showing in the DataWindow and in the tooltip.
PlotIndexSetString
SetIndexShift
void SetIndexShift(int index,
int shift)
bool PlotIndexSetInteger(index,PLOT_SHIFT,shift) Sets offset for the drawing line.
PlotIndexSetInteger
void SetIndexStyleMQL4(int index,
int type,
int style=EMPTY,
int width=EMPTY,
color clr=CLR_NONE)
{
if(width>-1)
PlotIndexSetInteger(index,PLOT_LINE_WIDTH,width);
if(clr!=CLR_NONE)
PlotIndexSetInteger(index,PLOT_LINE_COLOR,clr);
switch(type)
{
case 0:
PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_LINE);
case 1:
PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_SECTION);
case 2:
PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_HISTOGRAM);
case 3:
void SetIndexStyle(int index, PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_ARROW);
int type, case 4: SetIndexStyle
int style=EMPTY, PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_ZIGZAG); Sets the new type, style, width and color for a given indicator line.
int width=EMPTY, case 12: PlotIndexSetInteger
color clr=CLR_NONE) PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_NONE);

default:
PlotIndexSetInteger(index,PLOT_DRAW_TYPE,DRAW_LINE);
}
switch(style)
{
case 0:
PlotIndexSetInteger(index,PLOT_LINE_STYLE,STYLE_SOLID);
case 1:
PlotIndexSetInteger(index,PLOT_LINE_STYLE,STYLE_DASH);
case 2:
PlotIndexSetInteger(index,PLOT_LINE_STYLE,STYLE_DOT);
case 3:
PlotIndexSetInteger(index,PLOT_LINE_STYLE,STYLE_DASHDOT);
case 4:
PlotIndexSetInteger(index,PLOT_LINE_STYLE,STYLE_DASHDOTDOT);

default: return;
}

void SetLevelStyleMQL4(int draw_style,


int line_width,
color clr=CLR_NONE)
{
IndicatorSetInteger(INDICATOR_LEVELWIDTH,line_width);
if(clr!=CLR_NONE)
IndicatorSetInteger(INDICATOR_LEVELCOLOR,clr);
switch(draw_style)
{
case 0:
SetLevelStyle
void SetLevelStyle(int draw_style, IndicatorSetInteger(INDICATOR_LEVELSTYLE,STYLE_SOLID);
int line_width, case 1: The function sets a new style, width and color of horizontal levels of indicator to be output in a separate
color clr=CLR_NONE) IndicatorSetInteger(INDICATOR_LEVELSTYLE,STYLE_DASH); window.
case 2: IndicatorSetInteger
IndicatorSetInteger(INDICATOR_LEVELSTYLE,STYLE_DOT);
case 3:
IndicatorSetInteger(INDICATOR_LEVELSTYLE,STYLE_DASHDOT);
case 4:
IndicatorSetInteger(INDICATOR_LEVELSTYLE,STYLE_DASHDOTDOT);

default: return;
}
}

SetLevelValue
void SetLevelValue(int level,
double value)
bool IndicatorSetDouble(INDICATOR_LEVELVALUE,level,value) The function sets a value for a given horizontal level of the indicator to be output in a separate window.
IndicatorSetDouble

11. Date and Time Functions

MQL4 MQL5 Description


int DayMQL4()
{
Day
MqlDateTime tm;
int Day()
TimeCurrent(tm); Returns the current day of the month, i.e., the day of month of the last known server time.
return(tm.day); TimeCurrent, MqlDateTime
}

int DayOfWeekMQL4()
{
DayOfWeek
MqlDateTime tm;
int DayOfWeek()
TimeCurrent(tm); Returns the current zero-based day of the week (0-Sunday,1,2,3,4,5,6) of the last known server time.
return(tm.day_of_week); TimeCurrent, MqlDateTime
}

int DayOfYearMQL4()
{
DayOfYear
MqlDateTime tm;
int DayOfYear()
TimeCurrent(tm); Returns the current day of the year (1 means 1 January,..,365(6) does 31 December), i.e., the day of year of the last known server time.
return(tm.day_of_year); TimeCurrent, MqlDateTime
}

int HourMQL4()
{ Hour
MqlDateTime tm; Returns the hour (0,1,2,..23) of the last known server time by the moment of the program start (this value will not change within the time of the program
int Hour()
TimeCurrent(tm); execution).
return(tm.hour); TimeCurrent, MqlDateTime
}

int MinuteMQL4()
{ Minute
MqlDateTime tm; Returns the current minute (0,1,2,..59) of the last known server time by the moment of the program start (this value will not change within the time of
int Minute()
TimeCurrent(tm); the program execution).
return(tm.min); TimeCurrent, MqlDateTime
}

int MonthMQL4()
{
Month
MqlDateTime tm;
int Month()
TimeCurrent(tm); Returns the current month as number (1-January,2,3,4,5,6,7,8,9,10,11,12), i.e., the number of month of the last known server time.
return(tm.mon); TimeCurrent, MqlDateTime
}

int SecondsMQL4()
{ Seconds
MqlDateTime tm; Returns the amount of seconds elapsed from the beginning of the current minute of the last known server time by the moment of the program start (this
int Seconds()
TimeCurrent(tm); value will not change within the time of the program execution).
return(tm.sec); TimeCurrent, MqlDateTime
}

TimeCurrent
datetime TimeCurrent() datetime TimeCurrent() Returns the last known server time (time of incoming of the latest quote) as number of seconds elapsed from 00:00 January 1, 1970.
TimeCurrent
int TimeDayMQL4(datetime date)
{
TimeDay
MqlDateTime tm;
int TimeDay(datetime date)
TimeToStruct(date,tm); Returns day of month (1 - 31) for the specified date.
return(tm.day); TimeToStruct, MqlDateTime
}

int TimeDayOfWeekMQL4(datetime date)


{
TimeDayOfWeek
MqlDateTime tm;
int TimeDayOfWeek(datetime date)
TimeToStruct(date,tm); Returns the zero-based day of week (0 means Sunday,1,2,3,4,5,6) for the specified date.
return(tm.day_of_week); TimeToStruct, MqlDateTime
}

int TimeDayOfYearMQL4(datetime date)


{
TimeDayOfYear
MqlDateTime tm;
int TimeDayOfYear(datetime date)
TimeToStruct(date,tm); Returns day (1 means 1 January,..,365(6) does 31 December) of year for the specified date.
return(tm.day_of_year); TimeToStruct, MqlDateTime
}

int TimeHourMQL4(datetime date)


{
TimeHour
MqlDateTime tm;
int TimeHour(datetime time)
TimeToStruct(date,tm); Returns the hour for the specified time.
return(tm.hour); TimeToStruct, MqlDateTime
}

TimeLocal
datetime TimeLocal() datetime TimeLocal() Returns local computer time as number of seconds elapsed from 00:00 January 1, 1970.
TimeLocal
int TimeMinuteMQL4(datetime date)
{
TimeMinute
MqlDateTime tm;
int TimeMinute(datetime time)
TimeToStruct(date,tm); Returns the minute for the specified time.
return(tm.min); TimeToStruct, MqlDateTime
}

int TimeMonthMQL4(datetime date)


{
TimeMonth
MqlDateTime tm;
int TimeMonth(datetime time)
TimeToStruct(date,tm); Returns the month number for the specified time.
return(tm.mon); TimeToStruct, MqlDateTime
}

int TimeSecondsMQL4(datetime date)


{
TimeSeconds
MqlDateTime tm;
int TimeSeconds(datetime time)
TimeToStruct(date,tm); Returns the amount of seconds elapsed from the beginning of the minute for the specified time.
return(tm.sec); TimeToStruct, MqlDateTime
}

int TimeYearMQL4(datetime date)


{
TimeYear
MqlDateTime tm;
int TimeYear(datetime time)
TimeToStruct(date,tm); Returns year for the specified date. The returned value can be within the range of 1970 to 2037.
return(tm.year); TimeToStruct, MqlDateTime
}

int YearMQL4()
{
Year
MqlDateTime tm;
int Year()
TimeCurrent(tm); Returns the current year, i.e., the year of the last known server time.
return(tm.year); TimeCurrent, MqlDateTime
}

12. File Functions

MQL4 MQL5 Description


FileClose
void FileClose(int handle) void FileClose(int file_handle) Closes file previously opened by the FileOpen() function.
FileClose
FileDelete
bool FileDelete(string file_name
void FileDelete(string filename)
int common_flag=0) Removes specified file name.
FileDelete
FileFlush
void FileFlush(int handle) void FileFlush(int file_handle) Flushes all data stored in the file buffer to the disk.
FileFlush
FileIsEnding
bool FileIsEnding(int handle) bool FileIsEnding(int file_handle) Returns logical true if file pointer is at the end of the file, otherwise returns false.
FileIsEnding
FileIsLineEnding
bool FileIsLineEnding(int handle) bool FileIsLineEnding(int file_handle) For CSV file returns logical true if file pointer is at the end of the line, otherwise returns false.
FileIsLineEnding
int FileOpen(string ile_name,
int FileOpen(string filename, FileOpen
int pen_flags,
int mode,
short delimiter='\t' Opens file for input and/or output. Returns a file handle for the opened file or -1 (if the function fails).
int delimiter=';')
uint codepage=CP_ACP) FileOpen

int FileOpenHistory(string filename, FileOpenHistory


int mode, - Opens file in the current history directory (terminal_directory\history\server_name) or in its subfolders. Returns the file
int delimiter=';') handle for the opened file. If the function fails, the returned value is -1.

int FileReadArray(int handle, uint FileReadArray(int file_handle,


FileReadArray
object &array[], void array[],
int start, int start_item=0, Reads the specified amount of elements from the binary file into array.
int count) int items_count=WHOLE_ARRAY) FileReadArray

double FileReadDoubleMQL4(int handle,


int size=DOUBLE_VALUE) FileReadDouble
double FileReadDouble(int handle,
int size=DOUBLE_VALUE)
{ Reads the double-precision number with floating point from the current binary file position.
return(FileReadDouble(handle)); FileReadDouble
}

FileReadInteger
int FileReadInteger(int handle, int FileReadInteger(int file_handle,
int size=LONG_VALUE) int size=INT_VALUE) The function reads the integer from the current binary file position.
FileReadInteger
FileReadNumber
double FileReadNumber(int handle) double FileReadNumber(int file_handle) Read the number from the current file position before the delimiter. Only for CSV files.
FileReadNumber
FileReadString
string FileReadString(int handle, string FileReadString(int file_handle,
int length=0) int size=-1) Функция читает строку с текущей позиции файла.
FileReadString
bool FileSeekMQL4(long handle,
int offset,
FileSeek
bool FileSeek(int handle, ENUM_FILE_POSITION origin)
int offset, { The function moves the file pointer to a new position that is an offset, in bytes, from the beginning, the end or the current
int origin) FileSeek(handle,offset,origin); file position.
return(true); FileSeek
}

FileSize
int FileSize(int handle) ulong FileSize(int file_handle) The function returns file size in bytes.
FileSize
FileTell
int FileTell(int handle) ulong FileTell(int file_handle) Returns the current position of the file pointer.
FileTell
FileWrite
int FileWrite(int handle,...) uint FileWrite(int file_handle,...) The function is intended for writing of data into a CSV file, delimiter being inserted automatically.
FileWrite
int FileWriteArray(int handle, int FileWriteArray(int file_handle,
FileWriteArray
object array[], void array[],
int start, int start_item=0, The function writes the array to a binary file.
int count) int items_count=WHOLE_ARRAY) FileWriteArray

int FileWriteDouble(int handle, FileWriteDouble


uint FileWriteDouble(int file_handle,
double value,
double dvalue) The function writes a double value with floating point to a binary file.
int size=DOUBLE_VALUE) FileWriteDouble

int FileWriteInteger(int handle, uint FileWriteInteger(int file_handle, FileWriteInteger


int value, int ivalue, The function writes the integer value to a binary file.
int size=LONG_VALUE) int size=INT_VALUE) FileWriteInteger

int FileWriteString(int handle, uint FileWriteString(int file_handle, FileWriteString


string value, string svalue, The function writes the string to a binary file from the current file position.
int size) int size=-1) FileWriteString

13. Global Variables

MQL4 MQL5 Description


GlobalVariableCheck
bool GlobalVariableCheck(string name) bool GlobalVariableCheck(string name) Returns TRUE if the global variable exists, otherwise, returns FALSE.
GlobalVariableCheck
GlobalVariableDel
bool GlobalVariableDel(string name) bool GlobalVariableDel(string name) Deletes the global variable.
GlobalVariableDel
GlobalVariableGet
double GlobalVariableGet(string name) double GlobalVariableGet(string name) Returns the value of an existing global variable or 0 if an error occurs.
GlobalVariableGet
GlobalVariableName
string GlobalVariableName(int index) string GlobalVariableName(int index) The function returns the name of a global variable by its index in the list of global variables.
GlobalVariableName
GlobalVariableSet
datetime GlobalVariableSet(string name, datetime GlobalVariableSet(string name,
double value) double value) Sets a new value of the global variable. If it does not exist, the system creates a new global variable.
GlobalVariableSet
GlobalVariableSetOnCondition
bool GlobalVariableSetOnCondition(string name, bool GlobalVariableSetOnCondition(string name,
Sets the new value of the existing global variable if the current value equals to the third parameter
double value, double value,
double check_value) double check_value) check_value.
GlobalVariableSetOnCondition
GlobalVariablesDeleteAll
int GlobalVariablesDeleteAll(string prefix_name=NULL
int GlobalVariablesDeleteAll(string prefix_name=NULL)
datetime limit_data=0) Deletes global variables.
GlobalVariablesDeleteAll
GlobalVariablesTotal
int GlobalVariablesTotal() int GlobalVariablesTotal() The function returns the total count of global variables.
GlobalVariablesTotal

14. Mathematical Functions

MQL4 MQL5 Description


MathAbs
double MathAbs(double value) double MathAbs(double value) Returns the absolute value (modulus) of the specified numeric value.
MathAbs
MathArccos
double MathArccos(double x) double MathArccos(double val) The MathArccos function returns the arccosine of x within the range 0 to Pi (in radians).
MathArccos
MathArcsin
double MathArcsin(double x) double MathArcsin(double val) The MathArcsin function returns the arcsine of x in the range -Pi/2 to Pi/2 radians.
MathArcsin
MathArctan
double MathArctan(double x) double MathArctan(double value) The MathArctan returns the arctangent of x.
MathArctan
MathCeil
double MathCeil(double x) double MathCeil(double val) The MathCeil function returns a numeric value representing the smallest integer that exceeds or equals to x.
MathCeil
MathCos
double MathCos(double value) double MathCos(double value) Returns the cosine of the specified angle.
MathCos
MathExp
double MathExp(double d) double MathExp(double value) Returns the value of e raised to the power of d.
MathExp
MathFloor
double MathFloor(double x) double MathFloor(double val) The MathFloor function returns a numeric value representing the largest integer that is less than or equal to x.
MathFloor
MathLog
double MathLog(double x) double MathLog(double val) The MathLog function returns the natural logarithm of x if successful.
MathLog
MathMax
double MathMax(double value1, double MathMax(double value1,
double value2) double value2) Returns the maximum value of two numeric values.
MathMax
MathMin
double MathMin(double value1, double MathMin(double value1,
double value2) double value2) Returns the minimum value of two numeric values.
MathMin
MathMod
double MathMod(double value1, double MathMod(double value1,
double value2) double value2) The function returns the floating-point remainder of division of two numbers.
MathMod
MathPow
double MathPow(double base, double MathPow(double base,
double exponent) double exponent) Returns the value of the base expression raised to the specified power (exponent value).
MathPow
MathRand
int MathRand() int MathRand() The MathRand function returns a pseudorandom integer within the range of 0 to 32767.
MathRand
MathRound
double MathRound(double value) double MathRound(double value) Returns value rounded to the nearest integer of the specified numeric value.
MathRound
MathSin
double MathSin(double value) double MathSin(double value) Returns the sine of the specified angle.
MathSin
MathSqrt
double MathSqrt(double x) double MathSqrt(double value) The MathSqrt function returns the square root of x.
MathSqrt
MathSrand
void MathSrand(int seed) void MathSrand(int seed) The MathSrand() function sets the starting point for generating a series of pseudorandom integers.
MathSrand
MathTan
double MathTan(double x) double MathTan(double rad) MathTan returns the tangent of x.
MathTan

15. Object Functions

MQL4 MQL5 Description


bool ObjectCreateMQL4(string name,
ENUM_OBJECT type,
bool ObjectCreate(string name, int window,
int type, datetime time1,
int window, double price1,
ObjectCreate
datetime time1, datetime time2=0,
double price1, double price2=0, Creation of an object with the specified name, type and initial coordinates in the
datetime time2=0, datetime time3=0, specified window.
double price2=0, double price3=0) ObjectCreate
datetime time3=0, {
double price3=0) return(ObjectCreate(0,name,type,window,
time1,price1,time2,price2,time3,price3));
}

bool ObjectDeleteMQL4(string name)


ObjectDelete
{
bool ObjectDelete(string name)
return(ObjectDelete(0,name)); Deletes object having the specified name.
} ObjectDelete

string ObjectDescriptionMQL4(string name)


ObjectDescription
{
string ObjectDescription(string name)
return(ObjectGetString(0,name,OBJPROP_TEXT)); Return object description.
} ObjectGetString

int ObjectFindMQL4(string name)


ObjectFind
{
int ObjectFind(string name)
return(ObjectFind(0,name)); Search for an object having the specified name.
} ObjectFind

double ObjectGetMQL4(string name,


int index)
{
switch(index)
{
case OBJPROP_TIME1:
return(ObjectGetInteger(0,name,OBJPROP_TIME));
case OBJPROP_PRICE1:
return(ObjectGetDouble(0,name,OBJPROP_PRICE));
case OBJPROP_TIME2:
return(ObjectGetInteger(0,name,OBJPROP_TIME,1));
case OBJPROP_PRICE2:
return(ObjectGetDouble(0,name,OBJPROP_PRICE,1));
case OBJPROP_TIME3:
return(ObjectGetInteger(0,name,OBJPROP_TIME,2));
case OBJPROP_PRICE3:
return(ObjectGetDouble(0,name,OBJPROP_PRICE,2));
case OBJPROP_COLOR:
return(ObjectGetInteger(0,name,OBJPROP_COLOR));
case OBJPROP_STYLE:
return(ObjectGetInteger(0,name,OBJPROP_STYLE));
case OBJPROP_WIDTH:
return(ObjectGetInteger(0,name,OBJPROP_WIDTH));
case OBJPROP_BACK:
return(ObjectGetInteger(0,name,OBJPROP_WIDTH));
case OBJPROP_RAY:
return(ObjectGetInteger(0,name,OBJPROP_RAY_RIGHT));
ObjectGet
case OBJPROP_ELLIPSE:
double ObjectGet(string name,
return(ObjectGetInteger(0,name,OBJPROP_ELLIPSE)); The function returns the value of the specified object property.
int prop_id)
case OBJPROP_SCALE: ObjectGetInteger, ObjectGetDouble
return(ObjectGetDouble(0,name,OBJPROP_SCALE));
case OBJPROP_ANGLE:
return(ObjectGetDouble(0,name,OBJPROP_ANGLE));
case OBJPROP_ARROWCODE:
return(ObjectGetInteger(0,name,OBJPROP_ARROWCODE));
case OBJPROP_TIMEFRAMES:
return(ObjectGetInteger(0,name,OBJPROP_TIMEFRAMES));
case OBJPROP_DEVIATION:
return(ObjectGetDouble(0,name,OBJPROP_DEVIATION));
case OBJPROP_FONTSIZE:
return(ObjectGetInteger(0,name,OBJPROP_FONTSIZE));
case OBJPROP_CORNER:
return(ObjectGetInteger(0,name,OBJPROP_CORNER));
case OBJPROP_XDISTANCE:
return(ObjectGetInteger(0,name,OBJPROP_XDISTANCE));
case OBJPROP_YDISTANCE:
return(ObjectGetInteger(0,name,OBJPROP_YDISTANCE));
case OBJPROP_FIBOLEVELS:
return(ObjectGetInteger(0,name,OBJPROP_LEVELS));
case OBJPROP_LEVELCOLOR:
return(ObjectGetInteger(0,name,OBJPROP_LEVELCOLOR));
case OBJPROP_LEVELSTYLE:
return(ObjectGetInteger(0,name,OBJPROP_LEVELSTYLE));
case OBJPROP_LEVELWIDTH:
return(ObjectGetInteger(0,name,OBJPROP_LEVELWIDTH));
}
}

string ObjectGetFiboDescriptionMQL4(string name,


int index) ObjectGetFiboDescription
string ObjectGetFiboDescription(string name,
int index)
{ The function returns the level description of a Fibonacci object.
return(ObjectGetString(0,name,OBJPROP_LEVELTEXT,index)); ObjectGetString
}

int ObjectGetShiftByValueMQL4(string name,


double value)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(PERIOD_CURRENT);
datetime Arr[];
int shift; ObjectGetShiftByValue
int ObjectGetShiftByValue(string name, MqlRates mql4[]; The function calculates and returns bar index (shift related to the current bar) for the
double value) if(ObjectGetTimeByValue(0,name,value)<0) return(-1); given price.
CopyRates(NULL,timeframe,0,1,mql4); MqlRates, ObjectGetTimeByValue, CopyRates, CopyTime, ArraySize
if(CopyTime(NULL,timeframe,mql4[0].time,
ObjectGetTimeByValue(0,name,value),Arr)>0)
return(ArraySize(Arr)-1);
else return(-1);
}

double ObjectGetValueByShiftMQL4(string name,


int shift)
{ ObjectGetValueByShift
double ObjectGetValueByShift(string name, ENUM_TIMEFRAMES timeframe=TFMigrate(PERIOD_CURRENT); The function calculates and returns the price value for the specified bar (shift related
int shift) MqlRates mql4[]; to the current bar).
CopyRates(NULL,timeframe,shift,1,mql4); MqlRates, CopyRates, ObjectGetValueByTime
return(ObjectGetValueByTime(0,name,mql4[0].time,0));
}

bool ObjectMoveMQL4(string name,


int point,
bool ObjectMove(string name, ObjectMove
datetime time1,
int point,
double price1) The function moves an object coordinate in the chart. Objects can have from one to
datetime time1,
{ three coordinates depending on their types.
double price1) ObjectMove
return(ObjectMove(0,name,point,time1,price1));
}

string ObjectNameMQL4(int index)


ObjectName
{
string ObjectName(int index)
return(ObjectName(0,index)); The function returns the object name by its index in the objects list.
} ObjectName

int ObjectsDeleteAllMQL4(int window=EMPTY,


int type=EMPTY) ObjectsDeleteAll
int ObjectsDeleteAll(int window=EMPTY,
int type=EMPTY)
{ Removes all objects of the specified type and in the specified sub-window of the chart.
return(ObjectsDeleteAll(0,window,type)); ObjectsDeleteAll
}

bool ObjectSetMQL4(string name,


int index,
double value)
{
switch(index)
{
case OBJPROP_TIME1:
ObjectSetInteger(0,name,OBJPROP_TIME,(int)value);return(true);
case OBJPROP_PRICE1:
ObjectSetDouble(0,name,OBJPROP_PRICE,value);return(true);
case OBJPROP_TIME2:
ObjectSetInteger(0,name,OBJPROP_TIME,1,(int)value);return(true);
case OBJPROP_PRICE2:
ObjectSetDouble(0,name,OBJPROP_PRICE,1,value);return(true);
case OBJPROP_TIME3:
ObjectSetInteger(0,name,OBJPROP_TIME,2,(int)value);return(true);
case OBJPROP_PRICE3:
ObjectSetDouble(0,name,OBJPROP_PRICE,2,value);return(true);
case OBJPROP_COLOR:
ObjectSetInteger(0,name,OBJPROP_COLOR,(int)value);return(true);
case OBJPROP_STYLE:
ObjectSetInteger(0,name,OBJPROP_STYLE,(int)value);return(true);
case OBJPROP_WIDTH:
ObjectSetInteger(0,name,OBJPROP_WIDTH,(int)value);return(true);
case OBJPROP_BACK:
ObjectSetInteger(0,name,OBJPROP_BACK,(int)value);return(true);
case OBJPROP_RAY:
ObjectSetInteger(0,name,OBJPROP_RAY_RIGHT,(int)value);return(true);
case OBJPROP_ELLIPSE:
bool ObjectSet(string name, ObjectSetInteger(0,name,OBJPROP_ELLIPSE,(int)value);return(true); ObjectSet
int prop_id, case OBJPROP_SCALE: Changes the value of the specified object property.
double value) ObjectSetDouble(0,name,OBJPROP_SCALE,value);return(true); ObjectSetInteger, ObjectSetDouble
case OBJPROP_ANGLE:
ObjectSetDouble(0,name,OBJPROP_ANGLE,value);return(true);
case OBJPROP_ARROWCODE:
ObjectSetInteger(0,name,OBJPROP_ARROWCODE,(int)value);return(true);
case OBJPROP_TIMEFRAMES:
ObjectSetInteger(0,name,OBJPROP_TIMEFRAMES,(int)value);return(true);
case OBJPROP_DEVIATION:
ObjectSetDouble(0,name,OBJPROP_DEVIATION,value);return(true);
case OBJPROP_FONTSIZE:
ObjectSetInteger(0,name,OBJPROP_FONTSIZE,(int)value);return(true);
case OBJPROP_CORNER:
ObjectSetInteger(0,name,OBJPROP_CORNER,(int)value);return(true);
case OBJPROP_XDISTANCE:
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,(int)value);return(true);
case OBJPROP_YDISTANCE:
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,(int)value);return(true);
case OBJPROP_FIBOLEVELS:
ObjectSetInteger(0,name,OBJPROP_LEVELS,(int)value);return(true);
case OBJPROP_LEVELCOLOR:
ObjectSetInteger(0,name,OBJPROP_LEVELCOLOR,(int)value);return(true);
case OBJPROP_LEVELSTYLE:
ObjectSetInteger(0,name,OBJPROP_LEVELSTYLE,(int)value);return(true);
case OBJPROP_LEVELWIDTH:
ObjectSetInteger(0,name,OBJPROP_LEVELWIDTH,(int)value);return(true);

default: return(false);
}
return(false);
}

bool ObjectSetFiboDescriptionMQL4(string name,


int index,
bool ObjectSetFiboDescription(string name, ObjectSetFiboDescription
string text)
int index,
{ The function assigns a new description to a level of a Fibonacci object.
string text)
return(ObjectSetString(0,name,OBJPROP_LEVELTEXT,index,text)); ObjectSetString
}

bool ObjectSetTextMQL4(string name,


string text,
int font_size,
string font="",
color text_color=CLR_NONE)
{
int tmpObjType=(int)ObjectGetInteger(0,name,OBJPROP_TYPE);
if(tmpObjType!=OBJ_LABEL && tmpObjType!=OBJ_TEXT) return(false);
if(StringLen(text)>0 && font_size>0)
{
bool ObjectSetText(string name, if(ObjectSetString(0,name,OBJPROP_TEXT,text)==true
string text, && ObjectSetInteger(0,name,OBJPROP_FONTSIZE,font_size)==true) ObjectSetText
int font_size, { Changes the object description.
string font_name=NULL, if((StringLen(font)>0) ObjectGetInteger, ObjectSetString, ObjectSetInteger StringLen
color text_color=CLR_NONE) && ObjectSetString(0,name,OBJPROP_FONT,font)==false)
return(false);
if(text_color>-1
&& ObjectSetInteger(0,name,OBJPROP_COLOR,text_color)==false)
return(false);
return(true);
}
return(false);
}
return(false);
}

int ObjectsTotalMQL4(int type=EMPTY,


int window=-1) ObjectsTotal
int ObjectsTotal(int type=EMPTY) { Returns total amount of objects of the specified type in the chart.
return(ObjectsTotal(0,window,type)); ObjectsTotal
}

int ObjectTypeMQL4(string name)


ObjectType
{
int ObjectType(string name)
return((int)ObjectGetInteger(0,name,OBJPROP_TYPE)); The function returns the object type value.
} ObjectGetInteger

16. String Functions

MQL4 MQL5 Description


int StringConcatenate(string &string_var,
StringConcatenate
void argument1
string StringConcatenate(...)
void argument2 Forms a string of the data passed and returns it.
...) StringConcatenate

StringFind
int StringFind(string text, int StringFind(string string_value,
Search for a substring. Returns the position in the string from which the searched substring begins, or -1 if the substring has not been
string matched_text, string match_substring,
int start=0) int start_pos=0) found.
StringFind
StringGetChar
int StringGetChar(string text, ushort StringGetCharacter(string string_value,
int pos) int pos) Returns character (code) from the specified position in the string.
StringGetCharacter
StringLen
int StringLen(string text) int StringLen(string string_value) Returns character count in a string.
StringLen
string StringSetChar(string text, bool StringSetCharacter(string &string_var, StringSetChar
int pos, int pos, Returns the string copy with changed character in the specified position.
int value) ushort character) StringSetCharacter

string StringSubstr(string text, string StringSubstr(string string_value, StringSubstr


int start, int start_pos, Extracts a substring from text string starting from the given position.
int length=0) int length=-1) StringSubstr
StringTrimLeft
string StringTrimLeft(string text) int StringTrimLeft(string& string_var) The function cuts line feed characters, spaces and tabs in the left part of the string.
StringTrimLeft
StringTrimRight
string StringTrimRight(string text) int StringTrimRight(string& string_var) The function cuts line feed characters, spaces and tabs in the right part of the string.
StringTrimRight

17. Technical Indicators

The principles of use of the technical indicators in Expert Advisors are considered in the article MQL5 for Newbies: Guide to Using Technical Indicators in Expert Advisors. The method, used in this reference is sufficient to get the indicator
calculation results for the specified price. To use this method, we need the auxiliary function:

double CopyBufferMQL4(int handle,int index,int shift)


{
double buf[];
switch(index)
{
case 0: if(CopyBuffer(handle,0,shift,1,buf)>0)
return(buf[0]); break;
case 1: if(CopyBuffer(handle,1,shift,1,buf)>0)
return(buf[0]); break;
case 2: if(CopyBuffer(handle,2,shift,1,buf)>0)
return(buf[0]); break;
case 3: if(CopyBuffer(handle,3,shift,1,buf)>0)
return(buf[0]); break;
case 4: if(CopyBuffer(handle,4,shift,1,buf)>0)
return(buf[0]); break;
default: break;
}
return(EMPTY_VALUE);
}

let's declare the following constants:

ENUM_MA_METHOD MethodMigrate(int method)


{
switch(method)
{
case 0: return(MODE_SMA);
case 1: return(MODE_EMA);
case 2: return(MODE_SMMA);
case 3: return(MODE_LWMA);
default: return(MODE_SMA);
}
}
ENUM_APPLIED_PRICE PriceMigrate(int price)
{
switch(price)
{
case 1: return(PRICE_CLOSE);
case 2: return(PRICE_OPEN);
case 3: return(PRICE_HIGH);
case 4: return(PRICE_LOW);
case 5: return(PRICE_MEDIAN);
case 6: return(PRICE_TYPICAL);
case 7: return(PRICE_WEIGHTED);
default: return(PRICE_CLOSE);
}
}
ENUM_STO_PRICE StoFieldMigrate(int field)
{
switch(field)
{
case 0: return(STO_LOWHIGH);
case 1: return(STO_CLOSECLOSE);
default: return(STO_LOWHIGH);
}
}
//+------------------------------------------------------------------+
enum ALLIGATOR_MODE { MODE_GATORJAW=1, MODE_GATORTEETH, MODE_GATORLIPS };
enum ADX_MODE { MODE_MAIN, MODE_PLUSDI, MODE_MINUSDI };
enum UP_LOW_MODE { MODE_BASE, MODE_UPPER, MODE_LOWER };
enum ICHIMOKU_MODE { MODE_TENKANSEN=1, MODE_KIJUNSEN, MODE_SENKOUSPANA, MODE_SENKOUSPANB, MODE_CHINKOUSPAN };
enum MAIN_SIGNAL_MODE{ MODE_MAIN, MODE_SIGNAL };

MQL4 MQL5 Decsription


double iACMQL4(string symbol,
int tf,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int handle=iAC(symbol,timeframe);
double iAC(string symbol, iAC
if(handle<0)
int timeframe,
{ Calculates the Bill Williams' Accelerator/Decelerator oscillator.
int shift)
Print("The iAC object is not created: Error",GetLastError()); iAC
Use the ideas from this article return(-1);
to order your own robot }
on Freelance else
return(CopyBufferMQL4(handle,0,shift));
}
Go to Freelance
double iADMQL4(string symbol,
int tf,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int handle=(int)iAD(symbol,timeframe,VOLUME_TICK);
double iAD(string symbol, iAD
if(handle<0)
int timeframe,
{ Calculates the Accumulation/Distribution indicator and returns its value.
int shift)
Print("The iAD object is not created: Error",GetLastError()); iAD
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iAlligatorMQL4(string symbol,


int tf,
int jaw_period,
int jaw_shift,
int teeth_period,
int teeth_shift,
int lips_period,
int lips_shift,
double iAlligator(string symbol, int method,
int timeframe, int price,
int jaw_period, int mode,
int jaw_shift, int shift)
int teeth_period, {
iAlligator
int teeth_shift, ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int lips_period, ENUM_MA_METHOD ma_method=MethodMigrate(method); Calculates the Bill Williams' Alligator and returns its value.
int lips_shift, ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); iAlligator
int ma_method, int handle=iAlligator(symbol,timeframe,jaw_period,jaw_shift,
int applied_price, teeth_period,teeth_shift,
int mode, lips_period,lips_shift,
int shift) ma_method,applied_price);
if(handle<0)
{
Print("The iAlligator object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,mode-1,shift));
}

double iADXMQL4(string symbol,


int tf,
int period,
int price,
int mode,
int shift)
double iADX(string symbol,
{
int timeframe,
ENUM_TIMEFRAMES timeframe=TFMigrate(tf); iADX
int period,
int applied_price,
int handle=iADX(symbol,timeframe,period); Calculates the Movement directional index and returns its value.
if(handle<0) iADX
int mode,
{
int shift)
Print("The iADX object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,mode,shift));
}

double iATRMQL4(string symbol,


int tf,
int period,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
double iATR(string symbol,
int handle=iATR(symbol,timeframe,period); iATR
int timeframe,
int period,
if(handle<0) Calculates the Indicator of the average true range and returns its value.
{ iATR
int shift)
Print("The iATR object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iAOMQL4(string symbol,


int tf,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int handle=iAO(symbol,timeframe);
double iAO(string symbol, iAO
if(handle<0)
int timeframe,
{ Calculates the Bill Williams' Awesome oscillator and returns its value.
int shift)
Print("The iAO object is not created: Error",GetLastError()); iAO
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iBearsPowerMQL4(string symbol,


int tf,
int period,
int price,
int shift)
{
double iBearsPower(string symbol,
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int timeframe, iBearsPower
int handle=iBearsPower(symbol,timeframe,period);
int period,
if(handle<0) Calculates the Bears Power indicator and returns its value.
int applied_price,
{ iBearsPower
int shift)
Print("The iBearsPower object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iBandsMQL4(string symbol,


int tf,
int period,
double deviation,
int bands_shift,
int method,
int mode,
double iBands(string symbol,
int shift)
int timeframe,
{
int period,
ENUM_TIMEFRAMES timeframe=TFMigrate(tf); iBands
int deviation,
int bands_shift,
ENUM_MA_METHOD ma_method=MethodMigrate(method); Calculates the Bollinger bands indicator and returns its value.
int handle=iBands(symbol,timeframe,period, iBands
int applied_price,
bands_shift,deviation,ma_method);
int mode,
if(handle<0)
int shift)
{
Print("The iBands object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,mode,shift));
}

double iBandsOnArray(double array[],


int total,
int period,
iBandsOnArray
int deviation, -
int bands_shift, Calculation of the Bollinger Bands indicator on data stored in a numeric array.
int mode,
int shift)

double iBullsPowerMQL4(string symbol,


int tf,
int period,
int price,
int shift)
{
double iBullsPower(string symbol,
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int timeframe, iBullsPower
int handle=iBullsPower(symbol,timeframe,period);
int period,
if(handle<0) Calculates the Bulls Power indicator and returns its value.
int applied_price,
{ iBullsPower
int shift)
Print("The iBullsPower object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iCCIMQL4(string symbol,


int tf,
int period,
int price,
int shift)
{
double iCCI(string symbol, ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int timeframe, ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); iCCI
int period, int handle=iCCI(symbol,timeframe,period,price); Calculates the Commodity channel index and returns its value.
int applied_price, if(handle<0) iCCI
int shift) {
Print("The iCCI object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iCCIOnArray(double array[],


int total, iCCIOnArray
-
int period, Calculation of the Commodity Channel Index on data stored in a numeric array.
int shift)

double iCustom(string symbol,


int timeframe, int iCustom(string symbol,
iCustom
string name, ENUM_TIMEFRAMES period,
..., string name Calculates the specified custom indicator and returns its value.
int mode, ...) iCustom
int shift)

double iDeMarkerMQL4(string symbol,


int tf,
int period,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
double iDeMarker(string symbol,
int handle=iDeMarker(symbol,timeframe,period); iDeMarker
int timeframe,
int period,
if(handle<0) Calculates the DeMarker indicator and returns its value.
{ iDeMarker
int shift)
Print("The iDeMarker object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double EnvelopesMQL4(string symbol,


int tf,
int ma_period,
int method,
int ma_shift,
int price,
double deviation,
int mode,
double iEnvelopes(string symbol,
int shift)
int timeframe,
{
int ma_period,
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int ma_method, iEnvelopes
ENUM_MA_METHOD ma_method=MethodMigrate(method);
int ma_shift,
ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); Calculates the Envelopes indicator and returns its value.
int applied_price,
int handle=iEnvelopes(symbol,timeframe, iEnvelopes
double deviation,
ma_period,ma_shift,ma_method,
int mode,
applied_price,deviation);
int shift)
if(handle<0)
{
Print("The iEnvelopes object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,mode-1,shift));
}

double iEnvelopesOnArray(double array[],


int total,
int ma_period,
int ma_method, iEnvelopesOnArray
-
int ma_shift, Calculation of the Envelopes indicator on data stored in a numeric array.
double deviation,
int mode,
int shift)

double iForceMQL4(string symbol,


int tf,
int period,
int method,
int price,
int shift)
double iForce(string symbol, {
int timeframe, ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
iForce
int period, ENUM_MA_METHOD ma_method=MethodMigrate(method);
int ma_method, int handle=iForce(symbol,timeframe,period,ma_method,VOLUME_TICK); Calculates the Force index and returns its value.
int applied_price, if(handle<0) iForce
int shift) {
Print("The iForce object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iFractalsMQL4(string symbol,


int tf,
int mode,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
double iFractals(string symbol,
int handle=iFractals(symbol,timeframe); iFractals
int timeframe,
int mode,
if(handle<0) Calculates the Fractals and returns its value.
{ iFractals
int shift)
Print("The iFractals object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,mode-1,shift));
}

double iGatorMQL4(string symbol,


int tf,
int jaw_period,
int jaw_shift,
int teeth_period,
int teeth_shift,
int lips_period,
int lips_shift,
double iGator(string symbol, int method,
int timeframe, int price,
int jaw_period, int mode,
int jaw_shift, int shift)
int teeth_period, {
iGator
int teeth_shift, ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int lips_period, ENUM_MA_METHOD ma_method=MethodMigrate(method); Gator oscillator calculation.
int lips_shift, ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); iGator
int ma_method, int handle=iGator(symbol,timeframe,jaw_period,jaw_shift,
int applied_price, teeth_period,teeth_shift,
int mode, lips_period,lips_shift,
int shift) ma_method,applied_price);
if(handle<0)
{
Print("The iGator object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,mode-1,shift));
}

double iIchimokuMQL4(string symbol,


int tf,
int tenkan_sen,
int kijun_sen,
int senkou_span_b,
int mode,
double iIchimoku(string symbol, int shift)
int timeframe, {
int tenkan_sen, ENUM_TIMEFRAMES timeframe=TFMigrate(tf); iIchimoku
int kijun_sen, int handle=iIchimoku(symbol,timeframe, Calculates the Ichimoku Kinko Hyo and returns its value.
int senkou_span_b, tenkan_sen,kijun_sen,senkou_span_b); iIchimoku
int mode, if(handle<0)
int shift) {
Print("The iIchimoku object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,mode-1,shift));
}

double iBWMFIMQL4(string symbol,


int tf,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int handle=(int)iBWMFI(symbol,timeframe,VOLUME_TICK);
double iBWMFI(string symbol, iBWMFI
if(handle<0)
int timeframe,
{ Calculates the Bill Williams Market Facilitation index and returns its value.
int shift)
Print("The iBWMFI object is not created: Error",GetLastError()); iBWMFI
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iMomentumMQL4(string symbol,


int tf,
int period,
int price,
int shift)
{
double iMomentum(string symbol, ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int timeframe, ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); iMomentum
int period, int handle=iMomentum(symbol,timeframe,period,applied_price); Calculates the Momentum indicator and returns its value.
int applied_price, if(handle<0) iMomentum
int shift) {
Print("The iMomentum object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iMomentumOnArray(double array[],


int total, iMomentumOnArray
-
int period, Calculation of the Momentum indicator on data stored in a numeric array.
int shift)

double iMFIMQL4(string symbol,


int tf,
int period,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
double iMFI(string symbol,
int handle=(int)iMFI(symbol,timeframe,period,VOLUME_TICK); iMFI
int timeframe,
int period,
if(handle<0) Calculates the Money flow index and returns its value.
{ iMFI
int shift)
Print("The iMFI object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iMAMQL4(string symbol,


int tf,
int period,
int ma_shift,
int method,
int price,
int shift)
double iMA(string symbol, {
int timeframe, ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int period, ENUM_MA_METHOD ma_method=MethodMigrate(method); iMA
int ma_shift, ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); Calculates the Moving average indicator and returns its value.
int ma_method, int handle=iMA(symbol,timeframe,period,ma_shift, iMA
int applied_price, ma_method,applied_price);
int shift) if(handle<0)
{
Print("The iMA object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iMAOnArrayMQL4(double &array[],


int total,
int period,
int ma_shift,
int ma_method,
int shift)
{
double buf[],arr[];
if(total==0) total=ArraySize(array);
if(total>0 && total<=period) return(0);
if(shift>total-period-ma_shift) return(0);
switch(ma_method)
{
case MODE_SMA :
{
total=ArrayCopy(arr,array,0,shift+ma_shift,period);
if(ArrayResize(buf,total)<0) return(0);
double sum=0;
int i,pos=total-1;
for(i=1;i<period;i++,pos--)
sum+=arr[pos];
while(pos>=0)
{
sum+=arr[pos];
buf[pos]=sum/period;
sum-=arr[pos+period-1];
pos--;
}
return(buf[0]);
}
case MODE_EMA :
{
if(ArrayResize(buf,total)<0) return(0);
double pr=2.0/(period+1);
int pos=total-2;
while(pos>=0)
{
if(pos==total-2) buf[pos+1]=array[pos+1];
buf[pos]=array[pos]*pr+buf[pos+1]*(1-pr);
pos--;
}
return(buf[shift+ma_shift]);
}
case MODE_SMMA :
{
if(ArrayResize(buf,total)<0) return(0);
double iMAOnArray(double array[],
double sum=0;
int total,
int i,k,pos;
int period,
pos=total-period;
int ma_shift,
while(pos>=0)
int ma_method,
{
int shift)
if(pos==total-period)
{
for(i=0,k=pos;i<period;i++,k++)
{
sum+=array[k];
buf[k]=0;
}
}
else sum=buf[pos+1]*(period-1)+array[pos];
buf[pos]=sum/period;
pos--;
}
return(buf[shift+ma_shift]);
}
case MODE_LWMA :
{
if(ArrayResize(buf,total)<0) return(0);
double sum=0.0,lsum=0.0;
double price;
int i,weight=0,pos=total-1;
for(i=1;i<=period;i++,pos--)
{
price=array[pos];
sum+=price*i;
lsum+=price;
weight+=i;
}
pos++;
i=pos+period;
while(pos>=0)
{
buf[pos]=sum/weight;
if(pos==0) break;
pos--;
i--;
price=array[pos];
sum=sum-lsum+price*period;
lsum-=array[i];
lsum+=price;
}
return(buf[shift+ma_shift]);
}
default: return(0);
}
return(0);
}

double iOsMAMQL4(string symbol,


int tf,
int fast_ema_period,
int slow_ema_period,
int signal_period,
int price,
int shift)
double iOsMA(string symbol, {
int timeframe, ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int fast_ema_period, ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); iOsMA
int slow_ema_period, int handle=iOsMA(symbol,timeframe, Calculates the Moving Average of Oscillator and returns its value.
int signal_period, fast_ema_period,slow_ema_period, iOsMA
int applied_price, signal_period,applied_price);
int shift) if(handle<0)
{
Print("The iOsMA object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iMACDMQL4(string symbol,


int tf,
int fast_ema_period,
int slow_ema_period,
int signal_period,
int price,
int mode,
double iMACD(string symbol, int shift)
int timeframe, {
int fast_ema_period, ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
iMACD
int slow_ema_period, ENUM_APPLIED_PRICE applied_price=PriceMigrate(price);
int signal_period, int handle=iMACD(symbol,timeframe, Calculates the Moving averages convergence/divergence and returns its value.
int applied_price, fast_ema_period,slow_ema_period, iMACD
int mode, signal_period,applied_price);
int shift) if(handle<0)
{
Print("The iMACD object is not created: Error ",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,mode,shift));
}

double iOBVMQL4(string symbol,


int tf,
int price,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
double iOBV(string symbol,
int handle=iOBV(symbol,timeframe,VOLUME_TICK); iOBV
int timeframe,
int applied_price,
if(handle<0) Calculates the On Balance Volume indicator and returns its value.
{ iOBV
int shift)
Print("The iOBV object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iSARMQL4(string symbol,


int tf,
double step,
double maximum,
int shift)
{
double iSAR(string symbol,
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int timeframe, iSAR
int handle=iSAR(symbol,timeframe,step,maximum);
double step,
if(handle<0) Calculates the Parabolic Stop and Reverse system and returns its value.
double maximum,
{ iSAR
int shift)
Print("The iSAR object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iRSIMQL4(string symbol,


int tf,
int period,
int price,
int shift)
{
double iRSI(string symbol, ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int timeframe, ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); iRSI
int period, int handle=iRSI(symbol,timeframe,period,applied_price); Calculates the Relative strength index and returns its value.
int applied_price, if(handle<0) iRSI
int shift) {
Print("The iRSI object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iRSIOnArray(double array[],


int total, iRSIOnArray
-
int period, Calculation of the Relative Strength Index on data stored in a numeric array.
int shift)

double iRVIMQL4(string symbol,


int tf,
int period,
int mode,
int shift)
{
double iRVI(string symbol,
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int timeframe, iRVI
int handle=iRVI(symbol,timeframe,period);
int period,
if(handle<0) Calculates the Relative Vigor index and returns its value.
int mode,
{ iRVI
int shift)
Print("The iRVI object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,mode,shift));
}

double iStdDevMQL4(string symbol,


int tf,
int ma_period,
int ma_shift,
int method,
int price,
int shift)
double iStdDev(string symbol, {
int timeframe, ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int ma_period, ENUM_MA_METHOD ma_method=MethodMigrate(method); iStdDev
int ma_shift, ENUM_APPLIED_PRICE applied_price=PriceMigrate(price); Calculates the Standard Deviation indicator and returns its value.
int ma_method, int handle=iStdDev(symbol,timeframe,ma_period,ma_shift, iStdDev
int applied_price, ma_method,applied_price);
int shift) if(handle<0)
{
Print("The iStdDev object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

double iStdDevOnArray(double array[],


int total,
int ma_period, iStdDevOnArray
-
int ma_shift, Calculation of the Standard Deviation indicator on data stored in a numeric array.
int ma_method,
int shift)

double iStochasticMQL4(string symbol,


int tf,
int Kperiod,
int Dperiod,
int slowing,
int method,
int field,
double iStochastic(string symbol, int mode,
int timeframe, int shift)
int%Kperiod, {
int%Dperiod, ENUM_TIMEFRAMES timeframe=TFMigrate(tf); iStochastic
int slowing, ENUM_MA_METHOD ma_method=MethodMigrate(method); Calculates the Stochastic oscillator and returns its value.
int method, ENUM_STO_PRICE price_field=StoFieldMigrate(field); iStochastic
int price_field, int handle=iStochastic(symbol,timeframe,Kperiod,Dperiod,
int mode, slowing,ma_method,price_field);
int shift) if(handle<0)
{
Print("The iStochastic object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,mode,shift));
}

double iWPRMQL4(string symbol,


int tf,
int period,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
double iWPR(string symbol,
int handle=iWPR(symbol,timeframe,period); iWPR
int timeframe,
int period,
if(handle<0) Calculates the Larry William's percent range indicator and returns its value.
{ iWPR
int shift)
Print("The iWPR object is not created: Error",GetLastError());
return(-1);
}
else
return(CopyBufferMQL4(handle,0,shift));
}

18. Timeseries Access

MQL4 MQL5 Description


int iBarsMQL4(string symbol,int tf)
{
int iBarsMQL4(string symbol,int tf) ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
{ return(Bars(symbol,timeframe));
int iBars(string symbol,
ENUM_TIMEFRAMES timeframe=TFMigrate(tf); }
int timeframe)
return(Bars(symbol,timeframe));
} Bars
Returns the number of bars on the specified chart.
Bars
int iBarShiftMQL4(string symbol,
int tf,
datetime time,
bool exact=false)
{
if(time<0) return(-1);
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int iBarShift(string symbol, datetime Arr[],time1;
iBarShift
int timeframe, CopyTime(symbol,timeframe,0,1,Arr);
datetime time, time1=Arr[0]; Search for bar by open time.
bool exact=false if(CopyTime(symbol,timeframe,time,time1,Arr)>0) CopyTime, ArraySize
{
if(ArraySize(Arr)>2) return(ArraySize(Arr)-1);
if(time<time1) return(1);
else return(0);
}
else return(-1);
}

double iCloseMQL4(string symbol,int tf,int index)


{
if(index < 0) return(-1);
Close
double iClose(string symbol, double Arr[];
int timeframe, ENUM_TIMEFRAMES timeframe=TFMigrate(tf); Returns Close value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded),
int shift) if(CopyClose(symbol,timeframe, index, 1, Arr)>0) function returns 0.
return(Arr[0]); CopyRates, MqlRates
else return(-1);
}

double iHighMQL4(string symbol,int tf,int index)

{
if(index < 0) return(-1); High
double iHigh(string symbol,
double Arr[]; Returns High value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function
int timeframe,
int shift)
ENUM_TIMEFRAMES timeframe=TFMigrate(tf); returns 0.
if(CopyHigh(symbol,timeframe, index, 1, Arr)>0) CopyRates, MqlRates
return(Arr[0]);
else return(-1);
}

int iHighestMQL4(string symbol,


int tf,
int type,
int count=WHOLE_ARRAY,
int start=0)
{
if(start<0) return(-1);
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
if(count<=0) count=Bars(symbol,timeframe);
if(type<=MODE_OPEN)
{
double Open[];
ArraySetAsSeries(Open,true);
CopyOpen(symbol,timeframe,start,count,Open);
return(ArrayMaximum(Open,0,count)+start);
}
if(type==MODE_LOW)
{
double Low[];
ArraySetAsSeries(Low,true);
CopyLow(symbol,timeframe,start,count,Low);
return(ArrayMaximum(Low,0,count)+start);
}
if(type==MODE_HIGH)
{
int iHighest(string symbol, double High[];
int timeframe, ArraySetAsSeries(High,true); iHighest
int type, CopyHigh(symbol,timeframe,start,count,High); Returns the shift of the maximum value over a specific number of periods depending on type.
int count=WHOLE_ARRAY, return(ArrayMaximum(High,0,count)+start); CopyOpen, CopyLow, CopyHigh, CopyClose, CopyTickVolume, CopyTime, ArrayMaximum
int start=0) }
if(type==MODE_CLOSE)
{
double Close[];
ArraySetAsSeries(Close,true);
CopyClose(symbol,timeframe,start,count,Close);
return(ArrayMaximum(Close,0,count)+start);
}
if(type==MODE_VOLUME)
{
long Volume[];
ArraySetAsSeries(Volume,true);
CopyTickVolume(symbol,timeframe,start,count,Volume);
return(ArrayMaximum(Volume,0,count)+start);
}
if(type>=MODE_TIME)
{
datetime Time[];
ArraySetAsSeries(Time,true);
CopyTime(symbol,timeframe,start,count,Time);
return(ArrayMaximum(Time,0,count)+start);
//---
}
return(0);
}

double iLowMQL4(string symbol,int tf,int index)

{
if(index < 0) return(-1); iLow
double iLow(string symbol,
double Arr[]; Returns Low value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function
int timeframe,
int shift)
ENUM_TIMEFRAMES timeframe=TFMigrate(tf); returns 0.
if(CopyLow(symbol,timeframe, index, 1, Arr)>0) CopyRates, MqlRates
return(Arr[0]);
else return(-1);
}

int iLowestMQL4(string symbol,


int tf,
int type,
int count=WHOLE_ARRAY,
int start=0)
{
if(start<0) return(-1);
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
if(count<=0) count=Bars(symbol,timeframe);
if(type<=MODE_OPEN)
{
double Open[];
ArraySetAsSeries(Open,true);
CopyOpen(symbol,timeframe,start,count,Open);
return(ArrayMinimum(Open,0,count)+start);
}
if(type==MODE_LOW)
{
double Low[];
ArraySetAsSeries(Low,true);
CopyLow(symbol,timeframe,start,count,Low);
return(ArrayMinimum(Low,0,count)+start);
}
if(type==MODE_HIGH)
{
int iLowest(string symbol, double High[];
int timeframe, ArraySetAsSeries(High,true); iLowest
int type, CopyHigh(symbol,timeframe,start,count,High); Returns the shift of the lowest value over a specific number of periods depending on type.
int count=WHOLE_ARRAY, return(ArrayMinimum(High,0,count)+start); CopyOpen, CopyLow, CopyHigh, CopyClose, CopyTickVolume, CopyTime, ArrayMinimum
int start=0) }
if(type==MODE_CLOSE)
{
double Close[];
ArraySetAsSeries(Close,true);
CopyClose(symbol,timeframe,start,count,Close);
return(ArrayMinimum(Close,0,count)+start);
}
if(type==MODE_VOLUME)
{
long Volume[];
ArraySetAsSeries(Volume,true);
CopyTickVolume(symbol,timeframe,start,count,Volume);
return(ArrayMinimum(Volume,0,count)+start);
}
if(type>=MODE_TIME)
{
datetime Time[];
ArraySetAsSeries(Time,true);
CopyTime(symbol,timeframe,start,count,Time);
return(ArrayMinimum(Time,0,count)+start);
}
//---
return(0);
}

double iOpenMQL4(string symbol,int tf,int index)

{
if(index < 0) return(-1); iOpen
double iOpen(string symbol,
double Arr[]; Returns Open value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded),
int timeframe,
int shift)
ENUM_TIMEFRAMES timeframe=TFMigrate(tf); function returns 0.
if(CopyOpen(symbol,timeframe, index, 1, Arr)>0) CopyRates, MqlRates
return(Arr[0]);
else return(-1);
}

datetime iTimeMQL4(string symbol,int tf,int index)

{
if(index < 0) return(-1); iTime
datetime iTime(string symbol,
ENUM_TIMEFRAMES timeframe=TFMigrate(tf); Returns Time value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded),
int timeframe,
int shift)
datetime Arr[]; function returns 0.
if(CopyTime(symbol, timeframe, index, 1, Arr)>0) CopyRates, MqlRates
return(Arr[0]);
else return(-1);
}

int iVolumeMQL4(string symbol,int tf,int index)

{
if(index < 0) return(-1); iVolume
double iVolume(string symbol,
long Arr[]; Returns Tick Volume value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded),
int timeframe,
int shift)
ENUM_TIMEFRAMES timeframe=TFMigrate(tf); function returns 0.
if(CopyTickVolume(symbol, timeframe, index, 1, Arr)>0) CopyRates, MqlRates
return(Arr[0]);
else return(-1);
}

19. Chart Operations

MQL4 MQL5 Description


HideTestIndicators
void HideTestIndicators(bool hide) -
The function sets a flag hiding indicators called by the Expert Advisor.
Period
int Period() ENUM_TIMEFRAMES Period() Returns the amount of minutes determining the used period (chart timeframe).
Period
RefreshRates
bool RefreshRates() -
Refreshing of data in pre-defined variables and series arrays.
Symbol
string Symbol() string Symbol() Returns a text string with the name of the current financial instrument.
Symbol
WindowBarsPerChart
int WindowBarsPerChart() int ChartGetInteger(0,CHART_VISIBLE_BARS,0) Function returns the amount of bars visible on the chart.
ChartGetInteger
WindowExpertName
Returns name of the executed expert, script, custom indicator, or library, depending on
string WindowExpertName() string MQLInfoString(MQL5_PROGRAM_NAME) the MQL4 program, from which this function has been called.
MQLInfoString

int WindowFindMQL4(string name)


{
int window=-1;
if((ENUM_PROGRAM_TYPE)MQLInfoInteger(MQL5_PROGRAM_TYPE)==PROGRAM_INDICATOR)
{
window=ChartWindowFind(); WindowFind
} If indicator with name was found, the function returns the window index containing this
int WindowFind(string name)
else specified indicator, otherwise it returns -1.
{ ChartWindowFind, MQLInfoInteger
window=ChartWindowFind(0,name);
if(window==-1) Print(__FUNCTION__+"(): Error = ",GetLastError());
}
return(window);
}

WindowFirstVisibleBar
int WindowFirstVisibleBar() int ChartGetInteger(0,CHART_FIRST_VISIBLE_BAR,0) The function returns the first visible bar number in the current chart window.
ChartGetInteger
int WindowHandleMQL4(string symbol,
int tf)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
long currChart,prevChart=ChartFirst();
int i=0,limit=100;
while(i<limit)
{
WindowHandle
int WindowHandle(string symbol, currChart=ChartNext(prevChart);
int timeframe) if(currChart<0) break; Returns the system window handle of the specified chart.
if(ChartSymbol(currChart)==symbol ChartFirst, ChartNext, ChartSymbol, ChartPeriod
&& ChartPeriod(currChart)==timeframe)
return((int)currChart);
prevChart=currChart;
i++;
}
return(0);
}

WindowIsVisible
bool WindowIsVisible(int index) bool ChartGetInteger(0,CHART_WINDOW_IS_VISIBLE,index) Returns TRUE if the chart subwindow is visible, otherwise returns FALSE.
ChartGetInteger
WindowOnDropped
int WindowOnDropped() int ChartWindowOnDropped() Returns window index where expert, custom indicator or script was dropped.
ChartWindowOnDropped
WindowPriceMax
Returns maximal value of the vertical scale of the specified subwindow of the current
double WindowPriceMax(int index=0) double ChartGetDouble(0,CHART_PRICE_MAX,index)
chart (0-main chart window, the indicators' subwindows are numbered starting from 1).
ChartGetDouble
WindowPriceMin
Returns minimal value of the vertical scale of the specified subwindow of the current chart
double WindowPriceMin(int index=0) double ChartGetDouble(0,CHART_PRICE_MIN,index)
(0-main chart window, the indicators' subwindows are numbered starting from 1).
ChartGetDouble
WindowPriceOnDropped
double WindowPriceOnDropped() double ChartPriceOnDropped() Returns the price part of the chart point where expert or script was dropped.
ChartPriceOnDropped
WindowRedraw
void WindowRedraw() void ChartRedraw(0) Redraws the current chart forcedly.
ChartRedraw
bool WindowScreenShotMQL4(string filename,
int size_x,
int size_y,
int start_bar=-1,
int chart_scale=-1,
int chart_mode=-1)
{
bool WindowScreenShot(string filename, if(chart_scale>0 && chart_scale<=5)
int size_x, ChartSetInteger(0,CHART_SCALE,chart_scale);
WindowScreenShot
int size_y, switch(chart_mode)
int start_bar=-1, { Saves current chart screen shot as a GIF file.
int chart_scale=-1, case 0: ChartSetInteger(0,CHART_MODE,CHART_BARS); ChartSetInteger, ChartScreenShot
int chart_mode=-1) case 1: ChartSetInteger(0,CHART_MODE,CHART_CANDLES);
case 2: ChartSetInteger(0,CHART_MODE,CHART_LINE);
}
if(start_bar<0)
return(ChartScreenShot(0,filename,size_x,size_y,ALIGN_RIGHT));
else
return(ChartScreenShot(0,filename,size_x,size_y,ALIGN_LEFT));
}

WindowTimeOnDropped
datetime WindowTimeOnDropped() datetime ChartTimeOnDropped() Returns the time part of the chart point where expert or script was dropped.
ChartTimeOnDropped
WindowsTotal
int WindowsTotal() int ChartGetInteger(0,CHART_WINDOWS_TOTAL) Returns count of indicator windows on the chart (including main chart).
ChartGetInteger
WindowXOnDropped
Returns the value at X axis in pixels for the chart window client area point at which the
int WindowXOnDropped() int ChartXOnDropped()
expert or script was dropped.
ChartXOnDropped
WindowYOnDropped
Returns the value at Y axis in pixels for the chart window client area point at which the
int WindowYOnDropped() int ChartYOnDropped()
expert or script was dropped.
ChartYOnDropped

Conclusion

1. We haven't considered trading functions, because in MQL5 the concept is different, and the original should be used! It's possible to convert them, but the trading logic should be changed. In other words, there is no sense in converting them.
2. The conversion of programs from one language to another is always associated with the loss of functionality and performance. Therefore, use this guide for the quick search for the functions analogues.
3. I have plans to develop the MQL4 emulator, which will allow you to run your MQL4 programs in new MetaTrader 5 client terminal.

Credits: keiji, A. Williams.

Translated from Russian by MetaQuotes Ltd.


Original article: https://www.mql5.com/ru/articles/81

Attached files | Download ZIP


initmql4.mqh (7.5 KB)

Warning: All rights to these materials are reserved by MetaQuotes Ltd. Copying or reprinting of these materials in whole or in part is prohibited.

Other articles by this author

Developing multi-module Expert Advisors


3D Modeling in MQL5
Statistical distributions in the form of histograms without indicator buffers and arrays
The ZigZag Indicator: Fresh Approach and New Solutions
Calculation of Integral Characteristics of Indicator Emissions
Testing Performance of Moving Averages Calculation in MQL5

Last comments | Go to discussion (43)

Maxime Francois Patrice Ritter | 5 Sep 2021 at 21:45 ES

Hello,

This old article (may 2010, more than 11 years ago !) was one of the first trying to simplify the process of migrating a script/EA from MQL4 to MQL5. Meantime, the popular mql4compat.mqh has been created, and I just published a
maintained version of mql4compat on github for people interested : https://github.com/eromawyn/mql4compat

Samson Mthande Mashabane | 21 Nov 2021 at 21:05 ES

Hi I am struggling with these functions (please see below) I keep on getting these errors. Please help resolve it.

Vladimir Karputov | 22 Nov 2021 at 16:36 ES

Samson Mthande Mashabane # :


Hi I am struggling with these functions (please see below) I keep on getting these errors. Please help resolve it.

A picture is good, but you need an MQL5 code. You need to insert the code using the button

Aldo Marco Ronchese | 22 Sep 2023 at 22:00 ES

Hi Guys , thanks a stack for the great work.

I was having an issue getting fractals to work when converting from MT4 .. this helps by returning 0 instead of EMPTY_VALUE .. hope this is the right place to post thanks

double iFractals4(string symbol,


int tf,
int mode,
int shift)
{
ENUM_TIMEFRAMES timeframe=TFMigrate(tf);
int handle=iFractals(symbol,timeframe);
if(handle<0)
{
Print("The iFractals object is not created: Error",GetLastError());
return(-1);
}
else
{
double buffer=CopyBufferMQL4(handle,mode-1,shift);
if (buffer!=EMPTY_VALUE) return(CopyBufferMQL4(handle,mode-1,shift));
else return(0);
}
}

billz_billz | 8 Oct 2023 at 17:11 ES

I am benefited a lot from this great guide. Here is my little improvement on function to share.

double iMAOnArrayMQL4(double &array[],


int total,
int period,
int ma_shift,
int ma_method,
int shift)
{
double buf[],arr[];
if(total==0) total=ArraySize(array);
if(total>0 && total<=period) return(0);
if(shift>total-period-ma_shift) return(0);
switch(ma_method)
{
case MODE_SMA :
{
total=ArrayCopy(arr,array,0,shift+ma_shift,period);
if(ArrayResize(buf,total)<0) return(0);
double sum=0;
int i,pos=total-1;
for(i=1;i<period;i++,pos--)
sum+=arr[pos];
while(pos>=0)
{
sum+=arr[pos];
buf[pos]=sum/period;
sum-=arr[pos+period-1];
pos--;
}
return(buf[0]);
}
case MODE_EMA :
{
if(ArrayResize(buf,total)<0) return(0);
double pr=2.0/(period+1);
int pos=total-2;
while(pos>=0)
{
if(pos==total-2) buf[pos+1]=array[pos+1];
buf[pos]=array[pos]*pr+buf[pos+1]*(1-pr);
pos--;

// optimization
if(pos < (shift+ma_shift))
break;
}
return(buf[shift+ma_shift]);
}
case MODE_SMMA :
{
if(ArrayResize(buf,total)<0) return(0);
double sum=0;
int i,k,pos;
pos=total-period;
while(pos>=0)
{
if(pos==total-period)
{
for(i=0,k=pos;i<period;i++,k++)
{
sum+=array[k];
buf[k]=0;
}
}
else sum=buf[pos+1]*(period-1)+array[pos];
buf[pos]=sum/period;
pos--;

// optimization
if(pos < (shift+ma_shift))
break;
}
return(buf[shift+ma_shift]);
}
case MODE_LWMA :
{
if(ArrayResize(buf,total)<0) return(0);
double sum=0.0,lsum=0.0;
double price;
int i,weight=0,pos=total-1;
for(i=1;i<=period;i++,pos--)
{
price=array[pos];
sum+=price*i;
lsum+=price;
weight+=i;
}
pos++;
i=pos+period;
while(pos>=0)
{
buf[pos]=sum/weight;
if(pos==0) break;
pos--;
i--;
price=array[pos];
sum=sum-lsum+price*period;
lsum-=array[i];
lsum+=price;

// optimization
if(pos < (shift+ma_shift))
break;
}
return(buf[shift+ma_shift]);
}
default: return(0);
}
return(0);
}

My optimization removes unnecessary calculation.

Practical Application Of Databases For Markets Analysis A Virtual Order Manager to track orders within the position-centric MetaTrader 5 environment
Working with data has become the main task for modern software - both for standalone and network applications. To This class library can be added to an MetaTrader 5 Expert Advisor to enable it to be written with an order-centric
solve this problem a specialized software were created. These are Database Management Systems (DBMS), that can approach broadly similar to MetaTrader 4, in comparison to the position-based approach of MetaTrader 5. It does this
structure, systematize and organize data for their computer storage and processing. As for trading, the most of by keeping track of virtual orders at the MetaTrader 5 client terminal, while maintaining a protective broker stop for
analysts don't use databases in their work. But there are tasks, where such a solution would have to be handy. This each position for disaster protection.
article provides an example of indicators, that can save and load data from databases both with client-server and
file-server architectures.

Creating Active Control Panels in MQL5 for Trading Creating an Indicator with Graphical Control Options
The article covers the problem of development of active control panels in MQL5. Interface elements are managed by Those who are familiar with market sentiments, know the MACD indicator (its full name is Moving Average
the event handling mechanism. Besides, the option of a flexible setup of control elements properties is available. The Convergence/Divergence) - the powerful tool for analyzing the price movement, used by traders from the very first
active control panel allows working with positions, as well setting, modifying and deleting market and pending orders. moments of appearance of the computer analysis methods. In this article we'll consider possible modifications of
MACD and implement them in one indicator with the possibility to graphically switch between the modifications.

Online trading / WebTerminal MetaTrader 5 Trading Platform About MetaTrader 5


Free technical indicators and robots MetaTrader 5 latest updates Timeline
Articles about programming and trading News, implementations and technology Terms and Conditions
MQL5 Channels Economic Calendar
Order trading robots on the Freelance MetaTrader 5 User Manual Recurring Payment Agreement
Market of Expert Advisors and applications MQL5 language of trading strategies Agency Agreement – Offer
Follow forex signals MQL5 Cloud Network Privacy and Data Protection Policy
Follow us on socials for top articles
Low latency forex VPS End-to-End Analytics Cookies Policy and CodeBase updates
Traders forum Download MetaTrader 5 Contacts and requests
Not a broker, no real trading accounts
Trading blogs Install Platform
35 Dodekanisou str, Germasogeia, 4043, Limassol, Cyprus
Charts Uninstall Platform
Copyright 2000-2024, MetaQuotes Ltd

You might also like