MQL 4
MQL 4
MQL4 Reference
MetaQuotes Language 4 (MQL4) is a built-in language for
programming trading strategies. This language is
developed by MetaQuotes Software Corp. based on their
long experience in the creation of online trading
platforms. Using this language, you can create your own
Expert Advisors that make trading management
automated and are perfectly suitable for implementing
your own trading strategies. Besides, using MQL4 you can
create your own technical indicators (custom indicators),
scripts and libraries.
MQL4 contains a large number of functions necessary for
analyzing current and previously received quotes, and has
built-in basic indicators and functions for managing trade
orders and controlling them. The MetaEditor (text editor)
that highlights different constructions of MQL4 language is
used for writing the program code. It helps users to
orientate themselves in the expert system text quite
easily.
The brief guide contains functions, operations, reserved
words, and other language constructions divided into
categories, and allows finding the description of every
used element of the language.
Programs written in MetaQuotes Language 4 have
different features and purposes:
Expert Advisor is a mechanical trading system linked
up to a certain chart. An Expert Advisor starts to run
when an event happens that can be handled by it:
events of initialization and deinitialization, event of a
new tick receipt, a timer event, depth of market
changing event, chart event and custom events. An
Expert Advisor can both inform you about a possibility
to trade and automatically trade on an account sending
orders directly to a trade server. Expert Advisors are
stored in terminal_directory\MQL4\Experts.
Custom Indicator is a technical indicator written
independently in addition to those already integrated
into the client terminal. Like built-in indicators, they
cannot trade automatically and are intended for
implementing of analytical functions only.
Custom indicators are stored in
terminal_directory\MQL4\Indicators
Script is a program intended for a single execution of
some actions. Unlike Expert Advisors, scripts do not
process any actions, except for the start event (this
requires the OnStart handler function in a script).
Scripts are stored in terminal_directory\MQL4\Scripts
Library is a set of custom functions intended for
storing and distributing frequently used blocks of
custom programs. Libraries cannot start executing by
themselves.
Libraries are stored in
terminal_directory\MQL4\Libraries
Include File is a source text of the most frequently
used blocks of custom programs. Such files can be
included into the source texts of Expert Advisors,
scripts, custom indicators, and libraries at the
compiling stage. The use of included files is more
preferable than the use of libraries because of
additional burden occurring at calling library functions.
Include files can be stored in the same directory as a
source file - in this case the #include directive with
double quotes is used. Another place to store include
files is terminal_directory\MQL4\Include, in this case
the #include directive is used with angle brackets.
© 2000-2023, MetaQuotes Ltd
MQL4 Reference / MQL5 features
MQL5 charts
The new generation platform has two times more
timeframes (21 vs 9), as well as the precise time scale. Now
graphical objects are not necessarily linked to bars. Object
anchors can be placed in any position between the chart
bars. Moreover, when switching between timeframes, the
accurate positioning of the control points of the object is
preserved. New built-in indicators and analytical tools have
also been added.
The new OBJ_CHART graphical object is most notable in
terms of the complex technical analysis. It allows creating
an unlimited number of nested charts, set all the necessary
properties (color scheme, timeframe, symbol) and even
impose indicators on them. Thus, a usual price chart can be
turned into a complex analytical tool by quickly switching
between symbols and timeframes in a single mouse click.
If you use several monitors for trading, then you will
certainly appreciate another advantage of the new platform
floating chart windows. Any symbol chart can now be
detached from the terminal window and moved to the
necessary monitor. An example of such a chart is shown in
the image. Add indicators and an EA with the graphical
panel to a floating chart to get a real trading control center.
Floating windows can also be moved and resized from MQL5
programs using the chart properties (CHART_IS_DOCKED and
others).
The third distinctive feature of the fifth generation platform
is the ability to create custom symbols or synthetic indices.
To do that, simply enter the calculation formula or
download files with minute bars or tick history. You can also
work with custom symbols using MQL5 language. The
appropriate functions allow you to automate collecting and
preparing history data, open charts and update them in real
time, as well as test your EAs in the strategy tester using
custom symbols.
Explore MQL5 language features and take your programming
skills to the next level.
MQL4 Reference / MQL5 features / Indicators
MQL5 indicators
In the new terminal, the number of built-in technical
indicators has been increased from 30 to 38, while the
number of drawing styles of custom indicators has been
increased 3 times from 6 to 18. Now custom indicators are
able to use up to 512 indicator buffers. A separate color on
each bar can be specified for color styles.
MQL4 Reference / MQL5 features / MQL5 functions / Common
Functions
Common Functions
General-purpose functions not included into any
specialized group are listed here.
Function Action
Displays a message in a separate
Alert
window
CheckPointer Returns the type of the object pointer
Outputs a comment in the left top
Comment
corner of the chart
Transforms the data from array with
CryptEncode
the specified method
Performs the inverse transformation of
CryptDecode
the data from array
DebugBreak Program breakpoint in debugging
Stops Expert Advisor and unloads it
ExpertRemove
from the chart
GetPointer Returns the object pointer
Returns the number of milliseconds
GetTickCount that have elapsed since the system was
started
Returns the number of microseconds
GetMicrosecondCount that have elapsed since the start of
MQL5 program
Creates, displays a message box and
MessageBox
manages it
Function Action
Returns the number of seconds in the
PeriodSeconds
period
PlaySound Plays a sound file
Print Displays a message in the log
Formats and prints the sets of symbols
PrintFormat and values in a log file in accordance
with a preset format
Sets the value of a predetermined
ResetLastError
variable _LastError to zero
Creates an image resource based on a
ResourceCreate
data set
Deletes dynamically created resource
ResourceFree
(freeing the memory allocated for it)
Reads data from the graphical resource
ResourceReadImage created by ResourceCreate() function
or saved in EX5 file during compilation
ResourceSave Saves a resource into the specified file
Sets the predefined variable _LastError
SetUserError into the value equal to
ERR_USER_ERROR_FIRST + user_error
Sets the code that returns the terminal
SetReturnError process when completing the
operation.
Suspends execution of the current
Sleep Expert Advisor or script within a
specified interval
Commands the terminal to complete
TerminalClose
operation
Function Action
Sets the mode of displaying/hiding
TesterHideIndicators
indicators used in an EA
It returns the value of a specified
TesterStatistics statistic calculated based on testing
results
Gives program operation completion
TesterStop
command when testing
Emulates the operation of money
TesterWithdrawal
withdrawal in the process of testing
Returns a Unicode character by a
TranslateKey
virtual key code
Resets a variable passed to it by
reference. The variable can be of any
ZeroMemory
type, except for classes and structures
that have constructors.
MQL4 Reference / MQL5 features / MQL5 functions / Array Functions
Conversion Functions
This is a group of functions that provide conversion of
data from one format into another.
Function Action
Converting a symbol code into a one-
CharToString
character string
Converting a numeric value to a text
DoubleToString
line with a specified accuracy
Converting an enumeration value of any
EnumToString
type to string
Rounding of a floating point number to
NormalizeDouble
a specified accuracy
Converting a string containing a symbol
StringToDouble representation of number into number
of double type
Converting a string containing a symbol
StringToInteger representation of number into number
of int type
Converting a string containing time or
StringToTime date in "yyyy.mm.dd [hh:mi]" format
into datetime type
Converting a value containing time in
TimeToString seconds elapsed since 01.01.1970 into a
string of "yyyy.mm.dd hh:mi" format
Converting int into a string of preset
IntegerToString
length
Function Action
Converting symbol code (unicode) into
ShortToString
one-symbol string
ShortArrayToString Copying array part into a string
Symbol-wise copying a string to a
StringToShortArray
selected part of array of ushort type
Converting symbol code (ansi) into one-
CharArrayToString
symbol array
Symbol-wise copying a string converted
StringToCharArray from Unicode to ANSI, to a selected
place of array of uchar type
CharArrayToStruct Copy uchar type array to POD structure
StructToCharArray Copy POD structure to uchar type array
Converting color type to uint type to
ColorToARGB receive ARGB representation of the
color.
Converting color value into string as
ColorToString
"R,G,B"
Converting "R,G,B" string or string with
StringToColor
color name into color type value
Converting number into string
StringFormat
according to preset format
MQL4 Reference / MQL5 features / MQL5 functions / Math Functions
Mathematical Functions
A set of mathematical and trigonometric functions.
Function Action
MathAbs Returns absolute value (modulus) of the
specified numeric value
MathArccos Returns the arc cosine of x in radians
MathArcsin Returns the arc sine of x in radians
MathArctan Returns the arc tangent of x in radians
MathCeil Returns integer numeric value closest
from above
MathCos Returns the cosine of a number
MathExp Returns exponent of a number
MathFloor Returns integer numeric value closest
from below
MathLog Returns natural logarithm
MathLog10 Returns the logarithm of a number by
base 10
MathMax Returns the maximal value of the two
numeric values
MathMin Returns the minimal value of the two
numeric values
MathMod Returns the real remainder after the
division of two numbers
MathPow Raises the base to the specified power
Function Action
MathRand Returns a pseudorandom value within
the range of 0 to 32767
MathRound Rounds of a value to the nearest
integer
MathSin Returns the sine of a number
MathSqrt Returns a square root
MathSrand Sets the starting point for generating a
series of pseudorandom integers
MathTan Returns the tangent of a number
MathIsValidNumber Checks the correctness of a real
number
MathExpm1 Returns the value of the expression
MathExp(x)-1
MathLog1p Returns the value of the expression
MathLog(1+x)
MathArccosh Returns the hyperbolic arccosine
MathArcsinh Returns the hyperbolic arcsine
MathArctanh Returns the hyperbolic arctangent
MathCosh Returns the hyperbolic cosine
MathSinh Returns the hyperbolic sine
MathTanh Returns the hyperbolic tangent
MathSwap Change the order of bytes in the
ushort/uint/ushort types value
MQL4 Reference / MQL5 features / MQL5 functions / String Functions
String Functions
This is a group of functions intended for working with data
of the string type.
Function Action
StringAdd Adds a string to the end of another
string
StringBufferLen Returns the size of buffer allocated for
the string
StringCompare Compares two strings and returns 1 if
the first string is greater than the
second; 0 - if the strings are equal; -1
(minus 1) - if the first string is less than
the second one
StringConcatenate Forms a string of parameters passed
StringFill Fills out a specified string by selected
symbols
StringFind Search for a substring in a string
StringGetCharacter Returns the value of a number located
in the specified string position
StringInit Initializes string by specified symbols
and provides the specified string length
StringLen Returns the number of symbols in a
string
StringSetLength Sets a specified length (in characters)
for a string
Function Action
StringReplace Replaces all the found substrings of a
string by a set sequence of symbols
StringReserve Reserves the buffer of a specified size
for a string in memory.
StringSetCharacter Returns a copy of a string with a
changed value of a symbol in a
specified position
StringSplit Gets substrings by a specified separator
from the specified string, returns the
number of substrings obtained
StringSubstr Extracts a substring from a text string
starting from a specified position
StringToLower Transforms all symbols of a selected
string to lowercase
StringToUpper Transforms all symbols of a selected
string into capitals
StringTrimLeft Cuts line feed characters, spaces and
tabs in the left part of the string
StringTrimRight Cuts line feed characters, spaces and
tabs in the right part of the string
MQL4 Reference / MQL5 features / MQL5 functions / Date and Time
Account Information
Functions that return parameters of the current account.
Function Action
AccountInfoDouble Returns a value of double type of the
corresponding account property
AccountInfoInteger Returns a value of integer type (bool,
int or long) of the corresponding
account property
AccountInfoString Returns a value string type
corresponding account property
MQL4 Reference / MQL5 features / MQL5 functions / Checkup
State Checking
Functions that return parameters of the current state of
the client terminal
Function Action
GetLastError Returns the last error
IsStopped Returns true, if an mql5 program has
been commanded to stop its operation
UninitializeReason Returns the code of the reason for
deinitialization
TerminalInfoInteger Returns an integer value of a
corresponding property of the mql5
program environment
TerminalInfoDouble Returns a double value of a
corresponding property of the mql5
program environment
TerminalInfoString Returns a string value of a
corresponding property of the mql5
program environment
MQLInfoInteger Returns an integer value of a
corresponding property of a running
mql5 program
MQLInfoString Returns a string value of a
corresponding property of a running
mql5 program
Symbol Returns the name of a symbol of the
current chart
Function Action
Period Returns the current chart timeframe
Digits Returns the number of decimal digits
determining the accuracy of the price
value of the current chart symbol
Point Returns the point size of the current
symbol in the quote currency
MQL4 Reference / MQL5 features / MQL5 functions / Event Handling
Event Handling
The MQL5 language provides handling of certain
predefined events. The functions for handling these
events should be defined in an MQL5 program: function
name, return type, a set of parameters (if any) and their
types should strictly correspond to the description of an
event handling function.
The client terminal event handler uses the return and
parameter types to identify functions processing an event.
If a certain function has some parameters or a return type
not corresponding to the descriptions below, such a
function cannot be used for handling an event.
Function Action
The function is called when the Start
OnStart event occurs to perform actions set in
the script
The function is called in indicators and
OnInit EAs when the Init event occurs to
initialize a launched MQL5 program
The function is called in indicators and
OnDeinit EAs when the Deinit event occurs to de-
initialize a launched MQL5 program
The function is called in EAs when the
OnTick NewTick event occurs to handle a new
quote
Function Action
The function is called in indicators
OnCalculate when the Calculate event occurs to
handle price data changes
The function is called in indicators and
EAs during the Timer periodic event
OnTimer
generated by the terminal at fixed time
intervals
The function is called in EAs during the
OnTrade Trade event generated at the end of a
trading operation on a trade server
The function is called in EAs when the
TradeTransaction event occurs to
OnTradeTransaction
process a trade request execution
results
The function is called in EAs when the
OnBookEvent BookEvent event occurs to process
changes in the market depth
The function is called in indicators and
EAs when the ChartEvent event occurs
OnChartEvent
to process chart changes made by a
user or an MQL5 program
The function is called in EAs when the
Tester event occurs to perform
OnTester
necessary actions after testing an EA on
history data
The function is called in EAs when the
TesterInit event occurs to perform
OnTesterInit
necessary actions before optimization
in the strategy tester
Function Action
The function is called in EAs when the
OnTesterDeinit TesterDeinit event occurs after EA
optimization in the strategy tester
The function is called in EAs when the
TesterPass even occurs to handle an
OnTesterPass
arrival of a new data frame during EA
optimization in the strategy tester
MQL4 Reference / MQL5 features / MQL5 functions / Economic
Calendar
MQL4 Reference / MQL5 features / MQL5 functions / Custom Symbols
Custom symbols
Functions for creating and editing the custom symbol
properties.
When connecting the terminal to a certain trade server, a
user is able to work with time series of the financial
symbols provided by a broker. Available financial symbols
are displayed as a list in the Market Watch window. A
separate group of functions allows receiving data on the
symbol properties, trading sessions and market depth
updates.
The group of functions described in this section allows
creating custom symbols. To do this, users are able to
apply the trade server's existing symbols, text files or
external data sources.
Function Action
Create a custom symbol with
CustomSymbolCreate the specified name in the
specified group
Delete a custom symbol with
CustomSymbolDelete
the specified name
Set the integer type property
CustomSymbolSetInteger
value for a custom symbol
Set the real type property
CustomSymbolSetDouble
value for a custom symbol
Set the string type property
CustomSymbolSetString
value for a custom symbol
Function Action
Set the margin rates
depending on the order type
CustomSymbolSetMarginRate
and direction for a custom
symbol
Set the start and end time of
the specified quotation
CustomSymbolSetSessionQuote
session for the specified
symbol and week day
Set the start and end time of
the specified trading session
CustomSymbolSetSessionTrade
for the specified symbol and
week day
Delete all bars from the price
CustomRatesDelete history of the custom symbol
in the specified time interval
Fully replace the price history
of the custom symbol within
CustomRatesReplace the specified time interval
with the data from
the MqlRates type array
Add missing bars to the
custom symbol history and
CustomRatesUpdate replace existing data with the
ones from the MqlRates type
array
Adds data from an array of
the MqlTick type to the price
history of a custom symbol.
CustomTicksAdd
The custom symbol must be
selected in the Market Watch
window
Function Action
Delete all ticks from the price
CustomTicksDelete history of the custom symbol
in the specified time interval
Fully replace the price history
of the custom symbol within
CustomTicksReplace the specified time interval
with the data from
the MqlTick type array
Passes the status of the Depth
CustomBookAdd
of Market for a custom symbol
MQL4 Reference / MQL5 features / MQL5 functions / Chart
Operations
Chart Operations
Functions for setting chart properties (ChartSetInteger,
ChartSetDouble, ChartSetString) are asynchronous and are
used for sending update commands to a chart. If these
functions are executed successfully, the command is
included in the common queue of the chart events. Chart
property changes are implemented along with handling of
the events queue of this chart.
Function Action
Applies a specific template from a
ChartApplyTemplate
specified file to the chart
Saves current chart settings in a
ChartSaveTemplate
template with a specified name
Returns the number of a subwindow
ChartWindowFind
where an indicator is drawn
Converts the coordinates of a chart
ChartTimePriceToXY from the time/price representation to
the X and Y coordinates
Converts the X and Y coordinates on a
ChartXYToTimePrice
chart to the time and price values
Opens a new chart with the specified
ChartOpen
symbol and period
ChartClose Closes the specified chart
Returns the ID of the first chart of the
ChartFirst
client terminal
Function Action
Returns the chart ID of the chart next
ChartNext
to the specified one
Returns the symbol name of the
ChartSymbol
specified chart
Returns the period value of the
ChartPeriod
specified chart
Calls a forced redrawing of a specified
ChartRedraw
chart
Sets the double value for a
ChartSetDouble corresponding property of the
specified chart
Sets the integer value (datetime, int,
color, bool or char) for a
ChartSetInteger
corresponding property of the
specified chart
Sets the string value for a
ChartSetString corresponding property of the
specified chart
Returns the double value property of
ChartGetDouble
the specified chart
Returns the integer value property of
ChartGetInteger
the specified chart
Returns the string value property of
ChartGetString
the specified chart
Performs shift of the specified chart
by the specified number of bars
ChartNavigate
relative to the specified position in
the chart
ChartID Returns the ID of the current chart
Function Action
Adds an indicator with the specified
ChartIndicatorAdd
handle into a specified chart window
Removes an indicator with a specified
ChartIndicatorDelete
name from the specified chart window
Returns the handle of the indicator
ChartIndicatorGet with the specified short name in the
specified chart window
Returns the short name of the
indicator by the number in the
ChartIndicatorName
indicators list on the specified chart
window
Returns the number of all indicators
ChartIndicatorsTotal
applied to the specified chart window.
Returns the number (index) of the
ChartWindowOnDropped chart subwindow the Expert Advisor or
script has been dropped to
Returns the price coordinate of the
ChartPriceOnDropped chart point the Expert Advisor or
script has been dropped to
Returns the time coordinate of the
ChartTimeOnDropped chart point the Expert Advisor or
script has been dropped to
Returns the X coordinate of the chart
ChartXOnDropped point the Expert Advisor or script has
been dropped to
Returns the Y coordinate of the chart
ChartYOnDropped point the Expert Advisor or script has
been dropped to
Function Action
Changes the symbol value and a
ChartSetSymbolPeriod
period of the specified chart
Provides a screenshot of the chart of
its current state in a GIF, PNG or BMP
ChartScreenShot
format depending on specified
extension
MQL4 Reference / MQL5 features / MQL5 functions / Trade Functions
Trade Functions
This is the group of functions intended for managing
trading activities. Trading functions can be called only if
in the properties of the Expert Advisor or script the "Allow
live trading" checkbox is enabled.
Trading can be allowed or prohibited depending on various
factors described in the Trade Permission section.
Function Action
Calculates the margin required for
OrderCalcMargin the specified order type, in the
deposit currency
Calculates the profit based on the
OrderCalcProfit parameters passed, in the deposit
currency
Checks if there are enough funds to
OrderCheck execute the required trade
operation.
OrderSend Sends trade requests to a server
Asynchronously sends trade requests
OrderSendAsync without waiting for the trade
response of the trade server
PositionsTotal Returns the number of open positions
Returns the symbol corresponding to
PositionGetSymbol
the open position
Chooses an open position for further
PositionSelect
working with it
Function Action
Selects a position to work with by the
PositionSelectByTicket
ticket number specified in it
Returns the requested property of an
PositionGetDouble
open position (double)
Returns the requested property of an
PositionGetInteger
open position (datetime or int)
Returns the requested property of an
PositionGetString
open position (string)
Returns the ticket of the position
PositionGetTicket with the specified index in the list of
open positions
OrdersTotal Returns the number of orders
Return the ticket of a corresponding
OrderGetTicket
order
Selects a order for further working
OrderSelect
with it
Returns the requested property of
OrderGetDouble
the order (double)
Returns the requested property of
OrderGetInteger
the order (datetime or int)
Returns the requested property of
OrderGetString
the order (string)
Retrieves the history of transactions
HistorySelect and orders for the specified period of
the server time
Requests the history of deals with a
HistorySelectByPosition
specified position identifier.
Function Action
Selects an order in the history for
HistoryOrderSelect
further working with it
Returns the number of orders in the
HistoryOrdersTotal
history
Return order ticket of a
HistoryOrderGetTicket
corresponding order in the history
Returns the requested property of an
HistoryOrderGetDouble
order in the history (double)
Returns the requested property of an
HistoryOrderGetInteger
order in the history (datetime or int)
Returns the requested property of an
HistoryOrderGetString
order in the history (string)
Selects a deal in the history for
HistoryDealSelect further calling it through appropriate
functions
Returns the number of deals in the
HistoryDealsTotal
history
Returns a ticket of a corresponding
HistoryDealGetTicket
deal in the history
Returns the requested property of a
HistoryDealGetDouble
deal in the history (double)
Returns the requested property of a
HistoryDealGetInteger
deal in the history (datetime or int)
Returns the requested property of a
HistoryDealGetString
deal in the history (string)
MQL4 Reference / MQL5 features / MQL5 functions / Trade Signals
Trade Signals
This is the group of functions intended for managing trade
signals. The functions allow:
get information about trade signals, available for
copying,
get and set the signal copy settings,
subscribe and unsubscribe to the signal copying using
MQL5 language functions.
Function Action
SignalBaseGetDouble Returns the value of double type
property for selected signal
SignalBaseGetInteger Returns the value of integer type
property for selected signal
SignalBaseGetString Returns the value of string type
property for selected signal
SignalBaseSelect Selects a signal from signals, available
in terminal for further working with it
SignalBaseTotal Returns the total amount of signals,
available in terminal
SignalInfoGetDouble Returns the value of double type
property of signal copy settings
SignalInfoGetInteger Returns the value of integer type
property of signal copy settings
SignalInfoGetString Returns the value of string type
property of signal copy settings
Function Action
SignalInfoSetDouble Sets the value of double type property
of signal copy settings
SignalInfoSetInteger Sets the value of integer type property
of signal copy settings
SignalSubscribe Subscribes to the trading signal
SignalUnsubscribe Cancels subscription
MQL4 Reference / MQL5 features / MQL5 functions / Network
Functions
Network functions
MQL5 programs can exchange data with remote servers,
as well as send push notifications, emails and data via
FTP.
Add an explicit message to the MQL5 program to notify a
user of the need for additional configuration. You can do
that via #property description, Alert or Print.
Function Action
Create a socket with specified flags
SocketCreate
and return its handle
SocketClose Close a socket
Connect to the server with timeout
SocketConnect
control
Checks if the socket is currently
SocketIsConnected
connected
Get a number of bytes that can be
SocketIsReadable
read from a socket
Check whether data can be written
SocketIsWritable
to a socket at the current time
Set timeouts for receiving and
SocketTimeouts sending data for a socket system
object
SocketRead Read data from a socket
SocketSend Write data to a socket
Function Action
Initiate secure TLS (SSL) connection
SocketTlsHandshake to a specified host via TLS Handshake
protocol
Get data on the certificate used to
SocketTlsCertificate
secure network connection
Read data from secure TLS
SocketTlsRead
connection
Read all available data from secure
SocketTlsReadAvailable
TLS connection
SocketTlsSend Send data via secure TLS connection
Send an HTTP request to a specified
WebRequest
server
Send a file to an address specified on
SendFTP
the FTP tab
Send an email to an address specified
SendMail in the Email tab of the options
window
Send push notifications to mobile
SendNotification terminals whose MetaQuotes IDs are
specified in the Notifications tab
MQL4 Reference / MQL5 features / MQL5 functions / Global Variables
of the Terminal
File Functions
This is a group of functions for working with files. File
functions allow working with so-called "named pipes". To
do this, simply call FileOpen() function with appropriate
parameters.
Function Action
Starts the search of files in a directory
FileFindFirst
in accordance with the specified filter
Continues the search started by the
FileFindNext
FileFindFirst() function
FileFindClose Closes search handle
Opens a file with a specified name and
FileOpen
flag
FileDelete Deletes a specified file
Writes to a disk all data remaining in
FileFlush
the input/output file buffer
FileGetInteger Gets an integer property of a file
Defines the end of a file in the process
FileIsEnding
of reading
Defines the end of a line in a text file
FileIsLineEnding
in the process of reading
FileClose Closes a previously opened file
FileIsExist Checks the existence of a file
Copies the original file from a local or
FileCopy
shared folder to another file
Function Action
FileMove Moves or renames a file
Reads arrays of any type except for
FileReadArray
string from the file of the BIN type
Reads from the file of the CSV type a
string from the current position till a
FileReadBool delimiter (or till the end of a text line)
and converts the read string to a value
of bool type
Reads from the file of the CSV type a
string of one of the formats:
FileReadDatetime "YYYY.MM.DD HH:MM:SS", "YYYY.MM.DD"
or "HH:MM:SS" - and converts it into a
datetime value
Reads a double value from the current
FileReadDouble
position of the file pointer
Reads a float value from the current
FileReadFloat
position of the file pointer
Reads int, short or char value from the
FileReadInteger
current position of the file pointer
Reads a long type value from the
FileReadLong
current position of the file pointer
Reads from the file of the CSV type a
string from the current position till a
FileReadNumber delimiter (or til the end of a text line)
and converts the read string into
double value
Reads a string from the current position
FileReadString
of a file pointer from a file
Function Action
Reads the contents from a binary file
into a structure passed as a parameter,
FileReadStruct
from the current position of the file
pointer
Moves the position of the file pointer
FileSeek by a specified number of bytes relative
to the specified position
Returns the size of a corresponding
FileSize
open file
Returns the current position of the file
FileTell
pointer of a corresponding open file
FileWrite Writes data to a file of CSV or TXT type
Writes arrays of any type except for
FileWriteArray
string into a file of BIN type
Writes value of the double type from
FileWriteDouble the current position of a file pointer
into a binary file
Writes value of the float type from the
FileWriteFloat current position of a file pointer into a
binary file
Writes value of the int type from the
FileWriteInteger current position of a file pointer into a
binary file
Writes value of the long type from the
FileWriteLong current position of a file pointer into a
binary file
Writes the value of a string parameter
FileWriteString into a BIN or TXT file starting from the
current position of the file pointer
Function Action
Writes the contents of a structure
passed as a parameter into a binary
FileWriteStruct
file, starting from the current position
of the file pointer
Reads all data of a specified binary file
FileLoad into a passed array of numeric types or
simple structures
Writes to a binary file all elements of
FileSave
an array passed as a parameter
FolderCreate Creates a folder in the Files directory
Removes a selected directory. If the
FolderDelete folder is not empty, then it can't be
removed
FolderClean Deletes all files in the specified folder
Custom Indicators
This is the group functions used in the creation of custom
indicators. These functions can't be used when writing
Expert Advisors and Scripts.
Function Action
SetIndexBuffer Binds the specified indicator buffer with
one-dimensional dynamic array of the
double type
IndicatorSetDouble Sets the value of an indicator property
of the double type
IndicatorSetInteger Sets the value of an indicator property
of the int type
IndicatorSetString Sets the value of an indicator property
of the string type
PlotIndexSetDouble Sets the value of an indicator line
property of the type double
PlotIndexSetInteger Sets the value of an indicator line
property of the int type
PlotIndexSetString Sets the value of an indicator line
property of the string type
PlotIndexGetInteger Returns the value of an indicator line
property of the integer type
Object Functions
This is the group of functions intended for working with
graphic objects relating to any specified chart.
The functions defining the properties of graphical objects,
as well as ObjectCreate() and ObjectMove() operations for
creating and moving objects along the chart are actually
used for sending commands to the chart. If these
functions are executed successfully, the command is
included in the common queue of the chart events. Visual
changes in the properties of graphical objects are
implemented when handling the queue of the chart
events.
Thus, do not expect an immediate visual update of
graphical objects after calling these functions. Generally,
the graphical objects on the chart are updated
automatically by the terminal following the change events
- a new quote arrival, resizing the chart window, etc. Use
ChartRedraw() function to forcefully update the graphical
objects.
Function Action
Creates an object of the specified
ObjectCreate
type in a specified chart
Returns the name of an object of the
ObjectName corresponding type in the specified
chart (specified chart subwindow)
Function Action
Removes the object with the
specified name from the specified
ObjectDelete
chart (from the specified chart
subwindow)
Removes all objects of the specified
ObjectsDeleteAll type from the specified chart (from
the specified chart subwindow)
Searches for an object with the
ObjectFind
specified ID by the name
Returns the time value for the
ObjectGetTimeByValue
specified object price value
Returns the price value of an object
ObjectGetValueByTime
for the specified time
Changes the coordinates of the
ObjectMove
specified object anchor point
Returns the number of objects of the
ObjectsTotal specified type in the specified chart
(specified chart subwindow)
Returns the double value of the
ObjectGetDouble
corresponding object property
Returns the integer value of the
ObjectGetInteger
corresponding object property
Returns the string value of the
ObjectGetString
corresponding object property
Sets the value of the corresponding
ObjectSetDouble
object property
Sets the value of the corresponding
ObjectSetInteger
object property
Function Action
Sets the value of the corresponding
ObjectSetString
object property
Sets the font for displaying the text
TextSetFont using drawing methods (Arial 20 used
by default)
Transfers the text to the custom array
TextOut (buffer) designed for creation of a
graphical resource
Returns the string's width and height
TextGetSize
at the current font settings
MQL4 Reference / MQL5 features / MQL5 functions / Working with
Optimization Results
Event Functions
This group contains functions for working with custom
events and timer events. Besides this group, there are
special functions for handling predefined events.
Function Action
EventSetMillisecondTimer Launches event generator of the
high-resolution timer with a period
less than 1 second for the current
chart
EventSetTimer Starts the timer event generator
with the specified periodicity for
the current chart
EventKillTimer Stops the generation of events by
the timer in the current chart
EventChartCustom Generates a custom event for the
specified chart
MQL4 Reference / MQL5 features / MQL5 functions / Working with
OpenCL
MQL4 Reference / Language Basics
Language Basics
The MetaQuotes Language 4 (MQL4) is an object-oriented
high-level programming language intended for writing
automated trading strategies, custom technical indicators
for the analysis of various financial markets. It allows not
only to write a variety of expert systems, designed to
operate in real time, but also create their own graphical
tools to help you make trade decisions.
MQL4 is based on the concept of the popular programming
language C++. The language has enumerations, structures,
classes and event handling. By increasing the number of
embedded main types, the interaction of executable
programs in MQL4 with other applications through dll is
now as easy as possible. MQL4 syntax is similar to the
syntax of C++, and this makes it easy to translate into it
programs from modern programming languages.
To help you study the MQL4 language, all topics are
grouped into the following sections:
Syntax
Data Types
Operations and Expressions
Operators
Functions
Variables
Preprocessor
Object-Oriented Programming
Updated MQL4
MQL4 Reference / Language Basics / Syntax
Syntax
As to the syntax, THE MQL4 language for programming
trading strategies is very much similar to the C++
programming language, except for some features:
no address arithmetic;
no goto operator;
an anonymous enumeration can't be declared;
no multiple inheritance.
See also
Enumerations, Structures and Classes, Inheritance
MQL4 Reference / Language Basics / Syntax / Comments
Comments
Multi-line comments start with the /* pair of symbols and
end with the */ one. Such kind of comments cannot be
nested. Single-line comments begin with the // pair of
symbols and end with the newline character, they can be
nested in other multi-line comments. Comments are
allowed everywhere where the spaces are allowed, they
can have any number of spaces in them.
Examples:
//--- Single-line comment /* Multi-
line // Nested single-line comment
comment
*/
MQL4 Reference / Language Basics / Syntax / Identifiers
Identifiers
Identifiers are used as names of variables and functions.
The length of the identifier can not exceed 63 characters.
Characters allowed to be written in an identifier: figures
0-9, the Latin uppercase and lowercase letters a-z and A-
Z, recognized as different characters, the underscore
character (_).The first character can not be a digit.
The identifier must not coincide with reserved word.
Examples:
NAME1 namel Total_5 Paper
See also
Variables, Functions
MQL4 Reference / Language Basics / Syntax / Reserved Words
Reserved Words
The following identifiers are recorded as reserved words,
each of them corresponds to a certain action, and cannot
be used in another meaning:
Data Types
bool enum struct
char float uchar
class int uint
color long ulong
datetime short ushort
double string void
Access Specificators
const private protected
public virtual
Memory Classes
extern input static
Operators
break dynamic_cast return
case else sizeof
break dynamic_cast return
continue for switch
default if while
delete new
do operator
Other
false #define #property
this #import template
true #include typename
strict
MQL4 Reference / Language Basics / Data Types
Data Types
Any program operates with data. Data can be of different
types depending on their purposes. For example, integer
data are used to access to array components. Price data
belong to those of double precision with floating point.
This is related to the fact that no special data type for
price data is provided in MQL4.
Data of different types are processed with different rates.
Integer data are processed at the fastest. To process the
double precision data, a special co-processor is used.
However, because of complexity of internal
representation of data with floating point, they are
processed slower than the integer ones.
String data are processed at the longest because of
dynamic computer memory allocation/reallocation.
The basic data types are:
integers (char, short, int, long, uchar, ushort, uint,
ulong);
logical (bool);
literals (ushort);
strings (string);
floating-point numbers (double, float);
color (color);
date and time (datetime);
enumerations (enum).
Complex data types are:
structures;
classes.
In terms of OOP complex data types are called abstract
data types.
The color and datetime types make sense only to
facilitate visualization and input of parameters defined
from outside - from the table of Expert Advisor or custom
indicator properties (the Inputs tab). Data of color and
datetime types are represented as integers. Integer types
and floating-point types are called arithmetic (numeric)
types.
Only implicit type casting is used in expressions, unless
the explicit casting is specified.
See also
Typecasting
MQL4 Reference / Language Basics / Data Types / Integer Types
Integer Types
In MQL4 integers are represented by eleven types. Some
types can be used together with other ones, if required by
the program logic, but in this case it's necessary to
remember the rules of typecasting.
The table below lists the characteristics of each type.
Besides, the last column features a type in C++
corresponding to each type.
Type Size Minimum Maximum Value C++
in Value Analog
Bytes
char 1 -128 127 char
uchar 1 0 255 unsigned
char, BYTE
bool 1 0(false) 1(true) bool
short 2 -32 768 32 767 short,
wchar_t
ushort 2 0 65 535 unsigned
short,
WORD
int 4 - 2 147 483 2 147 483 647 int
648
uint 4 0 4 294 967 295 unsigned
int,
DWORD
Type Size Minimum Maximum Value C++
in Value Analog
Bytes
color 4 -1 16 777 215 int,
COLORREF
long 8 -9 223 372 9 223 372 036 __int64
036 854 775 854 775 807
808
ulong 8 0 18 446 744 073 unsigned
709 551 615 __int64
datetime 8 0 32 535 244 799 __time64_t
(1970.01.01 (3000.12.31
0:00:00) 23:59:59)
uchar
The uchar integer type also occupies 1 byte of memory, as
well as the char type, but unlike it uchar is intended only for
positive values. The minimum value is zero, the maximum
value is 255. The first letter u in the name of the uchar type
is the abbreviation for unsigned.
short
The size of the short type is 2 bytes (16 bits) and,
accordingly, it allows expressing the range of values equal to
2 to the power 16: 2^16 = 65 536.Since the short type is a
signed one, and contains both positive and negative values,
the range of values is between -32 768 and 32 767.
ushort
The unsigned short type is the type ushort, which also has a
size of 2 bytes. The minimum value is 0, the maximum value
is 65 535.
int
The size of the int type is 4 bytes (32 bits). The minimal
value is -2 147 483 648, the maximal one is 2 147 483 647.
uint
The unsigned integer type is uint. It takes 4 bytes of memory
and allows expressing integers from 0 to 4 294 967 295.
long
The size of the long type is 8 bytes (64 bits). The minimum
value is -9 223 372 036 854 775 808, the maximum value is 9
223 372 036 854 775 807.
ulong
The ulong type also occupies 8 bytes and can store values
from 0 to 18 446 744 073 709 551 615.
Examples:
char ch=12; short sh=-5000;
int in=2445777;
Since the unsigned integer types are not designed for storing
negative values, the attempt to set a negative value can lead
to unexpected consequences. Such a simple script will lead
to an infinite loop:
//--- Infinite loop
void OnStart()
{
uchar u_ch;
for(char ch=-128;ch<128;ch++)
{
u_ch=ch;
Print("ch = ",ch," u_ch = ",u_ch);
}
}
for(char ch=-128;ch<=127;ch++)
{
u_ch=ch;
Print("ch = ",ch," u_ch = ",u_ch);
if(ch==127) break;
}
}
Result:
ch= -128 u_ch= 128
ch= -127 u_ch= 129
ch= -126 u_ch= 130
ch= -125 u_ch= 131
ch= -124 u_ch= 132
ch= -123 u_ch= 133
ch= -122 u_ch= 134
ch= -121 u_ch= 135
ch= -120 u_ch= 136
ch= -119 u_ch= 137
ch= -118 u_ch= 138
ch= -117 u_ch= 139
ch= -116 u_ch= 140
ch= -115 u_ch= 141
ch= -114 u_ch= 142
ch= -113 u_ch= 143
ch= -112 u_ch= 144
ch= -111 u_ch= 145
...
Examples:
//--- Negative values can not be stored in unsigned types
uchar u_ch=-120;
ushort u_sh=-5000;
uint u_in=-401280;
See also
Typecasting
MQL4 Reference / Language Basics / Data Types / Integer Types / Character Constants
Character Constants
Characters as elements of a string in MQL4 are indexes in the Unicode character set.
They are hexadecimal values that can be cast into integers, and that can be manipulated
by integer operations like addition and subtraction.
Any single character in quotation marks or a hexadecimal ASCII code of a character as
'\x10' is a character constant and is of ushort type. For example, a record of '0' type is a
numerical value 30, that corresponds to the index of zero in the table of characters.
Example:
void OnStart() {
//--- define character constants
int symbol_0='0';
int symbol_9=symbol_0+9; // get symbol '9'
//--- output values of constants
printf("In a decimal form: symbol_0 = %d, symbol_9 = %d",symbol_0,symbol_9);
printf("In a hexadecimal form: symbol_0 = 0x%x, symbol_9 = 0x%x",symbol_0,symbol_
//--- enter constants into a string
string test="";
StringSetCharacter(test,0,symbol_0);
StringSetCharacter(test,1,symbol_9);
//--- this is what they look like in a string
Print(test);
}
A backslash is a control character for a compiler when dealing with constant strings and
character constants in a source text of a program. Some symbols, for example a single
quote ('), double quotes ("), backslash (\) and control characters can be represented as a
combination of symbols that start with a backslash (\), according to the below table:
Character name Mnemonic code or Record in Numeric value
image MQL4
new line (line LF '\n' 10
feed)
horizontal tab HT '\t' 9
carriage return CR '\r' 13
backslash \ '\\' 92
single quote ' '\'' 39
double quote " '\"' 34
hexadecimal code hhhh '\xhhhh' 1 to 4 hexadecimal characters
decimal code d '\d' decimal number from 0 to
65535
As it was mentioned above, the value of a character constant (or variable) is an index in
the table of characters. Index being an integer, it can be written in different ways.
void OnStart()
{
//---
int a=0xAE; // the code of ® corresponds to the '\xAE' literal
int b=0x24; // the code of $ corresponds to the '\x24' literal
int c=0xA9; // the code of © corresponds to the '\xA9' literal
int d=0x263A; // the code of ☺ corresponds to the '\x263A' literal
//--- show values
Print(a,b,c,d);
//--- add a character to the string
string test="";
StringSetCharacter(test,0,a);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,b);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,c);
Print(test);
//--- replace a character in a string
StringSetCharacter(test,0,d);
Print(test);
//--- codes of suits
int a1=0x2660;
int b1=0x2661;
int c1=0x2662;
int d1=0x2663;
//--- add a character of spades
StringSetCharacter(test,1,a1);
Print(test);
//--- add a character of hearts
StringSetCharacter(test,2,b1);
Print(test);
//--- add a character of diamonds
StringSetCharacter(test,3,c1);
Print(test);
//--- add a character of clubs
StringSetCharacter(test,4,d1);
Print(test);
//--- Example of character literals in a string
test="Queen\x2660Ace\x2662";
printf("%s",test);
}
The internal representation of a character literal is the ushort type. Character constants
can accept values from 0 to 65535.
See also
StringSetCharacter(), StringGetCharacter(), ShortToString(), ShortArrayToString(),
StringToShortArray()
MQL4 Reference / Language Basics / Data Types / Integer Types / Datetime Type
Datetime Type
The datetime type is intended for storing the date and time as the number of seconds
elapsed since January 01, 1970. This type occupies 8 bytes of memory.
Constants of the date and time can be represented as a literal string, which consists of 6
parts showing the numerical value of the year, month, day (or day, month, year), hours,
minutes and seconds. The constant is enclosed in single quotation marks and starts with
the D character.
Values range from 1 January, 1970 to 31 December, 3000. Either date (year , month, day)
or time (hours, minutes, seconds), or all together can be omitted.
With literal date specification, it is desirable that you specify year, month and day.
Otherwise the compiler returns a warning about an incomplete entry.
Examples:
datetime NY=D'2015.01.01 00:00'; // Time of beginning of year 2015 datetime d1=D'1
datetime d2=D'19.07.1980 12:30:27'; // Equal to D'1980.07.19 12:30:27';
datetime d3=D'19.07.1980 12'; // Equal to D'1980.07.19 12:00:00'
datetime d4=D'01.01.2004'; // Equal to D'01.01.2004 00:00:00'
datetime compilation_date=__DATE__; // Compilation date
datetime compilation_date_time=__DATETIME__; // Compilation date and time
datetime compilation_time=__DATETIME__-__DATE__;// Compilation time
//--- Examples of declarations after which compiler warnings will be returned
datetime warning1=D'12:30:27'; // Equal to D'[date of compilation] 12:30:27'
datetime warning2=D''; // Equal to __DATETIME__
See also
Structure of the Date Type, Date and Time, TimeToString, StringToTime
MQL4 Reference / Language Basics / Data Types / Integer Types /
Color Type
Color Type
The color type is intended for storing information about
color and occupies 4 bytes in memory. The first byte is
ignored, the remaining 3 bytes contain the RGB-
components.
Color constants can be represented in three ways:
literally, by integers, or by name (for named Web-colors
only).
Literal representation consists of three parts representing
numerical rate values of the three main color
components: red, green, blue. The constant starts with C
and is enclosed in single quotes. Numerical rate values of
a color component lie in the range from 0 to 255.
Integer-valued representation is written in a form of
hexadecimal or a decimal number. A hexadecimal number
looks like 0x00BBGGRR, where RR is the rate of the red
color component, GG - of the green one, and BB - of the
blue one. Decimal constants are not directly reflected in
the RGB. They represent a decimal value of the
hexadecimal integer representation.
Specific colors reflect the so-called Web-colors set.
Examples:
//--- Literals C'128,128,128' // Gray
C'0x00,0x00,0xFF' // Blue
//color names
clrRed // Red
clrYellow // Yellow
clrBlack // Black
//--- Integral representations
0xFFFFFF // White
16777215 // White
0x008000 // Green
32768 // Green
See also
Web Colors, ColorToString, StringToColor, Typecasting
MQL4 Reference / Language Basics / Data Types / Integer Types /
Bool Type
Bool Type
The bool type is intended to store the logical values of
true or false, numeric representation of them is 1 or 0,
respectively.
Examples:
bool a = true; bool b = false;
bool c = 1;
i=0;
if(i) Print("i = ",i," and has the true value");
else Print("i = ",i," and has the false value");
d=0.0;
if(d) Print("d = ",d," and has the true value");
else Print("d = ",d," and has the false value");
See also
Boolean Operations, Precedence Rules
MQL4 Reference / Language Basics / Data Types / Integer Types /
Enumerations
Enumerations
Data of the enum type belong to a certain limited set of
data. Defining the enumeration type:
enum name of enumerable type {
list of values
};
Notes
Unlike C++, the size of the internal representation of
the enumerated type in MQL4 is always equal to 4
bytes. That is, sizeof(months) returns the value 4.
Unlike C++, an anonymous enumeration can't be
declared in MQL4. That is, a unique name must be
always specified after the enum keyword.
See also
Typecasting
MQL4 Reference / Language Basics / Data Types / Real Types (double, float)
The double name means that the accuracy of these numbers is twice the accuracy of the
float type numbers. In most cases, the double type is the most convenient one. In many
cases the limited precision of float numbers is not enough. The reason why the float type
is still used is saving the memory (this is important for large arrays of real numbers).
Floating-point constants consist of an integer part, a point (.) and the fractional part.
The integer and fractional parts are sequences of decimal digits.
Examples:
double a=12.111; double b=-956.1007;
float c =0.0001;
float d =16;
There is a scientific way of writing real constants, often this method of recording is more
compact than the traditional one.
Example:
double c1=1.12123515e-25;
double c2=0.000000000000000000000000112123515; // 24 zero after the decimal point
Print("1. c1 =",DoubleToString(c1,16));
// Result: 1. c1 = 0.0000000000000000
Print("2. c1 =",DoubleToString(c1,-16));
// Result: 2. c1 = 1.1212351499999999e-025
Print("3. c2 =",DoubleToString(c2,-16));
// Result: 3. c2 = 1.1212351499999999e-025
It should be remembered that real numbers are stored in memory with some limited
accuracy in the binary system, while generally the decimal notation is used. That's why
many numbers that are precisely represented in the decimal system can be written only
as an infinite fraction in the binary system.
For example, numbers 0.3 and 0.7 are represented in the computer as infinite fractions,
while the number of 0.25 is stored exactly, because it represents the power of two.
In this regard, it is strongly recommended not to compare two real numbers for equality,
because such a comparison is not correct.
Example:
void OnStart()
{
//---
double three=3.0;
double x,y,z;
x=1/three;
y=4/three;
z=5/three;
if(x+y==z) Print("1/3 + 4/3 == 5/3");
else Print("1/3 + 4/3 != 5/3");
// Result: 1/3 + 4/3 != 5/3
}
If you still need to compare the equality of two real numbers, then you can do this in
two different ways. The first way is to compare the difference between two numbers
with some small quantity that specifies the accuracy of comparison.
Example:
bool EqualDoubles(double d1,double d2,double epsilon)
{
if(epsilon<0) epsilon=-epsilon;
//---
if(d1-d2>epsilon) return false;
if(d1-d2<-epsilon) return false;
//---
return true;
}
void OnStart()
{
double d_val=0.7;
float f_val=0.7;
if(EqualDoubles(d_val,f_val,0.000000000000001)) Print(d_val," equals ",f_val);
else Print("Different: d_val = ",DoubleToString(d_val,16),
" f_val = ",DoubleToString(f_val,16));
// Result: Different: d_val= 0.7000000000000000 f_val= 0.6999999880790710
}
Note that the value of epsilon in the above example can not be less than the predefined
constant DBL_EPSILON. The value of this constant is 2.2204460492503131e-016. The
constant corresponding to the float type is FLT_EPSILON = 1.192092896e-07. The
meaning of these values is the following: it is the lowest value that satisfies the
condition 1.0 + DBL_EPSILON! = 1.0 (for numbers of float type 1.0 + FLT_EPSILON! =
1.0).
The second way offers comparing the normalized difference of two real numbers with
zero. It's meaningless to compare the difference of normalized numbers with a zero,
because any mathematical operation with normalized numbers gives a non-normalized
result.
Example:
bool CompareDoubles(double number1,double number2)
{
if(NormalizeDouble(number1-number2,8)==0) return(true);
else return(false);
}
void OnStart()
{
double d_val=0.3;
float f_val=0.3;
if(CompareDoubles(d_val,f_val)) Print(d_val," equals ",f_val);
else Print("Different: d_val = ",DoubleToString(d_val,16),
" f_val = ",DoubleToString(f_val,16));
// Result: Different: d_val= 0.3000000000000000 f_val= 0.3000000119209290
}
Some operations of the mathematical co-processor can result in the invalid real number,
which can't be used in mathematical operations and operations of comparison, because
the result of operations with invalid real numbers is undefined. For example, when
trying to calculate the arcsine of 2, the result is the negative infinity.
Example:
double abnormal = MathArcsin(2.0);
Print("MathArcsin(2.0) =",abnormal);
// Result: MathArcsin(2.0) = -1.#IND
Besides the minus infinity there is the plus infinity and NaN (not a number). To
determine that this number is invalid, you can use MathIsValidNumber(). According to
the IEEE standard, they have a special machine representation. For example, plus
infinity for the double type has the bit representation of 0x7FF0 0000 0000 0000.
Examples:
struct str1
{
double d;
};
struct str2
{
long l;
};
//--- Start
str1 s1;
str2 s2;
//---
s1.d=MathArcsin(2.0); // Get the invalid number -1.#IND
s2=s1;
printf("1. %f %I64X",s1.d,s2.l);
//---
s2.l=0xFFFF000000000000; // invalid number -1.#QNAN
s1=s2;
printf("2. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF7000000000000; // greatest non-number SNaN
s1=s2;
printf("3. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF8000000000000; // smallest non-number QNaN
s1=s2;
printf("4. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FFF000000000000; // greatest non-number QNaN
s1=s2;
printf("5. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FF0000000000000; // Positive infinity 1.#INF and smallest non-number S
s1=s2;
printf("6. %f %I64X",s1.d,s2.l);
//---
s2.l=0xFFF0000000000000; // Negative infinity -1.#INF
s1=s2;
printf("7. %f %I64X",s1.d,s2.l);
//---
s2.l=0x8000000000000000; // Negative zero -0.0
s1=s2;
printf("8. %f %I64X",s1.d,s2.l);
//---
s2.l=0x3FE0000000000000; // 0.5
s1=s2;
printf("9. %f %I64X",s1.d,s2.l);
//---
s2.l=0x3FF0000000000000; // 1.0
s1=s2;
printf("10. %f %I64X",s1.d,s2.l);
//---
s2.l=0x7FEFFFFFFFFFFFFF; // Greatest normalized number (MAX_DBL)
s1=s2;
printf("11. %.16e %I64X",s1.d,s2.l);
//---
s2.l=0x0010000000000000; // Smallest positive normalized (MIN_DBL)
s1=s2;
printf("12. %.16e %.16I64X",s1.d,s2.l);
//---
s1.d=0.7; // Show that the number of 0.7 - endless fraction
s2=s1;
printf("13. %.16e %.16I64X",s1.d,s2.l);
/*
1. -1.#IND00 FFF8000000000000
2. -1.#QNAN0 FFFF000000000000
3. 1.#SNAN0 7FF7000000000000
4. 1.#QNAN0 7FF8000000000000
5. 1.#QNAN0 7FFF000000000000
6. 1.#INF00 7FF0000000000000
7. -1.#INF00 FFF0000000000000
8. -0.000000 8000000000000000
9. 0.500000 3FE0000000000000
10. 1.000000 3FF0000000000000
11. 1.7976931348623157e+308 7FEFFFFFFFFFFFFF
12. 2.2250738585072014e-308 0010000000000000
13. 6.9999999999999996e-001 3FE6666666666666
*/
See also
DoubleToString, NormalizeDouble, Numeric Type Constants
MQL4 Reference / Language Basics / Data Types / String Type
String Type
The string type is used for storing text strings. A text string is a sequence of characters
in the Unicode format with the final zero at the end of it. A string constant can be
assigned to a string variable. A string constant is a sequence of Unicode characters
enclosed in double quotes: "This is a string constant".
If you need to include a double quote (") into a string, the backslash character (\) must
be put before it. Any special character constants can be written in a string, if the
backslash character (\) is typed before them.
Examples:
string svar="This is a character string"; string svar2=StringSubstr(svar,0,4);
Print("Copyright symbol\t\x00A9");
FileWrite(handle,"This string contains a new line symbols \n");
string MT4path="C:\\Program Files\\MetaTrader 4";
To make the source code readable, long constant strings can be split into parts without
addition operation. During compilation, these parts will be combined into one long
string:
//--- Declare a long constant string
string HTML_head="<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n"
"<html xmlns=\"http://www.w3.org/1999/xhtml\">\n"
"<head>\n"
"<meta http-equiv=\"Content-Type\" content=\"text/html; charset=u
"<title>Trade Operations Report</title>\n"
"</head>";
//--- Output the constant string into log
Print(HTML_head);
}
See also
Conversion Functions, String Functions, FileOpen(), FileReadString(), FileWriteString()
MQL4 Reference / Language Basics / Data Types / Structures, Classes and Interfaces
If you want to do another alignment in the structure, use auxiliary members, "fillers" to
the right size.
Example:
struct trade_settings
{
uchar slippage; // value of the permissible slippage-size 1 byte
char reserved1; // skip 1 byte
short reserved2; // skip 2 bytes
int reserved4; // another 4 bytes are skipped. ensure alignment of the bound
double take; // values of the price of profit fixing
double stop; // price value of the protective stop
};
Such a description of aligned structures is necessary only for transferring to imported dll-
functions.
Attention: This example illustrates incorrectly designed data. It would be better first to
declare the take and stop large data of the double type, and then declare the slippage
member of the uchar type. In this case, the internal representation of data will always
be the same regardless of the value specified in #pragma pack().
If a structure contains variables of the string type and/or object of a dynamic array, the
compiler assigns an implicit constructor to such a structure. This constructor resets all
the structure members of string type and correctly initializes objects of the dynamic
array.
Simple Structures
Structures that do not contain strings or objects of dynamic arrays are called simple
structures; variables of such structures can be freely copied to each other, even if they
are different structures. Variables of simple structures, as well as their array can be
passed as parameters to functions imported from DLL.
Access to Structure Members
The name of a structure becomes a new data type, so you can declare variables of this
type. The structure can be declared only once within a project. The structure members
are accessed using thepoint operation (.).
Example:
struct trade_settings
{
double take; // values of the profit fixing price
double stop; // value of the protective stop price
uchar slippage; // value of the acceptable slippage
};
//--- create up and initialize a variable of the trade_settings type
trade_settings my_set={0.0,0.0,5};
if (input_TP>0) my_set.take=input_TP;
Classes
Classes differ from structures in the following:
the keyword class is used in declaration;
by default, all class members have access specifier private, unless otherwise
indicated. Data-members of the structure have the default type of access as public,
unless otherwise indicated;
class objects always have a table of virtual functions, even if there are no virtual
functions declared in the class. Structures cannot have virtual functions;
the new operator can be applied to class objects; this operator cannot be applied to
structures;
classes can be inherited only from classes, structures can be inherited only from
structures.
Classes and structures can have an explicit constructor and destructor. If your
constructor is explicitly defined, the initialization of a structure or class variable using
the initializing sequence is impossible.
Example:
struct trade_settings
{
double take; // values of the profit fixing price
double stop; // value of the protective stop price
uchar slippage; // value of the acceptable slippage
//--- Constructor
trade_settings() { take=0.0; stop=0.0; slippage=5; }
//--- Destructor
~trade_settings() { Print("This is the end"); }
};
//--- Compiler will generate an error message that initialization is impossible
trade_settings my_set={0.0,0.0,5};
A constructor can be declared in the class description and then its body can be defined.
For example, two constructors of MyDateClass can be defined the following way:
//+------------------------------------------------------------------+
//| Default constructor |
//+------------------------------------------------------------------+
MyDateClass::MyDateClass(void)
{
//---
MqlDateTime mdt;
datetime t=TimeCurrent(mdt);
m_year=mdt.year;
m_month=mdt.mon;
m_day=mdt.day;
m_hour=mdt.hour;
m_minute=mdt.min;
m_second=mdt.sec;
Print(__FUNCTION__);
}
//+------------------------------------------------------------------+
//| Parametric constructor |
//+------------------------------------------------------------------+
MyDateClass::MyDateClass(int h,int m,int s)
{
MqlDateTime mdt;
datetime t=TimeCurrent(mdt);
m_year=mdt.year;
m_month=mdt.mon;
m_day=mdt.day;
m_hour=h;
m_minute=m;
m_second=s;
Print(__FUNCTION__);
}
In the default constructor, all members of the class are filled using the TimeCurrent()
function. In the parametric constructor only hour values are filled in. Other members of
the class (m_year, m_month and m_day) will be automatically initialized with the
current date.
The default constructor has a special purpose when initializing an array of objects of its
class. The constructor, all parameters of which have default values, is not a default
constructor. Here is an example:
//+------------------------------------------------------------------+
//| Class with a default constructor |
//+------------------------------------------------------------------+
class CFoo
{
datetime m_call_time; // Time of the last object call
public:
//--- Constructor with a parameter that has a default value is not a default const
CFoo(const datetime t=0){m_call_time=t;};
//--- Copy constructor
CFoo(const CFoo &foo){m_call_time=foo.m_call_time;};
string ToString(){return(TimeToString(m_call_time,TIME_DATE|TIME_SECONDS));};
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
// CFoo foo; // This variant cannot be used - a default constructor is not set
//--- Possible options to create the CFoo object
CFoo foo1(TimeCurrent()); // An explicit call of a parametric constructor
CFoo foo2(); // An explicit call of a parametric constructor with
CFoo foo3=D'2009.09.09'; // An implicit call of a parametric constructor
CFoo foo40(foo1); // An explicit call of a copy constructor
CFoo foo41=foo1; // An implicit call of a copy constructor
CFoo foo5; // An explicit call of a default constructor (if the
// then a parametric constructor with a default valu
//--- Possible options to receive CFoo pointers
CFoo *pfoo6=new CFoo(); // Dynamic creation of an object and receiving of a
CFoo *pfoo7=new CFoo(TimeCurrent());// Another option of dynamic object creation
CFoo *pfoo8=GetPointer(foo1); // Now pfoo8 points to object foo1
CFoo *pfoo9=pfoo7; // pfoo9 and pfoo7 point to one and the same object
// CFoo foo_array[3]; // This option cannot be used - a default constructo
//--- Show the value of m_call_time
Print("foo1.m_call_time=",foo1.ToString());
Print("foo2.m_call_time=",foo2.ToString());
Print("foo3.m_call_time=",foo3.ToString());
Print("foo4.m_call_time=",foo4.ToString());
Print("foo5.m_call_time=",foo5.ToString());
Print("pfoo6.m_call_time=",pfoo6.ToString());
Print("pfoo7.m_call_time=",pfoo7.ToString());
Print("pfoo8.m_call_time=",pfoo8.ToString());
Print("pfoo9.m_call_time=",pfoo9.ToString());
//--- Delete dynamically created arrays
delete pfoo6;
delete pfoo7;
//delete pfoo8; // You do not need to delete pfoo8 explicitly, since it points to
//delete pfoo9; // You do not need to delete pfoo9 explicitly. since it points to
}
or
//CFoo foo_dyn_array[]; // This variant cannot be used - a default constructor is
then the compiler will return an error for them "default constructor is not defined".
If a class has a user-defined constructor, the default constructor is not generated by the
compiler. This means that if a parametric constructor is declared in a class, but a default
constructor is not declared, you can not declare the arrays of objects of this class. The
compiler will return an error for this script:
//+------------------------------------------------------------------+
//| Class without a default constructor |
//+------------------------------------------------------------------+
class CFoo
{
string m_name;
public:
CFoo(string name) { m_name=name;}
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Get the "default constructor is not defined" error during compilation
CFoo badFoo[5];
}
In this example, the CFoo class has a declared parametric constructor - in such cases,
the compiler does not create a default constructor automatically during compilation. At
the same time when you declare an array of objects, it is assumed that all objects
should be created and initialized automatically. During auto-initialization of an object, it
is necessary to call a default constructor, but since the default constructor is not
explicitly declared and not automatically generated by the compiler, it is impossible to
create such an object. For this reason, the compiler generates an error at the
compilation stage.
There is a special syntax to initialize an object using a constructor. Constructor
initializers (special constructions for initialization) for the members of a struct or class
can be specified in the initialization list.
An initialization list is a list of initializers separated by commas, which comes after the
colon after the list of parameters of a constructor and precedes the body (goes before
an opening brace). There are several requirements:
Initialization lists can be used only in constructors;
Parent members cannot be initialized in the initialization list;
The initialization list must be followed by a definition (implementation) of a function.
Here is an example of several constructors for initializing class members.
//+------------------------------------------------------------------+
//| Class for storing the name of a character |
//+------------------------------------------------------------------+
class CPerson
{
string m_first_name; // First name
string m_second_name; // Second name
public:
//--- An empty default constructor
CPerson() {Print(__FUNCTION__);};
//--- A parametric constructor
CPerson(string full_name);
//--- A constructor with an initialization list
CPerson(string surname,string name): m_second_name(surname), m_f
void PrintName(){PrintFormat("Name=%s Surname=%s",m_first_name,m_second_name);};
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
CPerson::CPerson(string full_name)
{
int pos=StringFind(full_name," ");
if(pos>=0)
{
m_first_name=StringSubstr(full_name,0,pos);
m_second_name=StringSubstr(full_name,pos+1);
}
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Get an error "default constructor is not defined"
CPerson people[5];
CPerson Tom="Tom Sawyer"; // Tom Sawyer
CPerson Huck("Huckleberry","Finn"); // Huckleberry Finn
CPerson *Pooh = new CPerson("Winnie","Pooh"); // Winnie the Pooh
//--- Output values
Tom.PrintName();
Huck.PrintName();
Pooh.PrintName();
In the initialization list, members can go in any order, but all members of the class will
be initialized according to the order of their announcement. This means that in the third
constructor, first the m_first_name member will be initialized, as it is announced first,
and only after it m_second_name is initialized. This should be taken into account in
cases where the initialization of some members of the class depends on the values in
other class members.
If a default constructor is not declared in the base class, and at the same time one or
more constructors with parameters are declared, you should always call one of the base
class constructors in the initialization list. It goes through the comma as ordinary
members of the list and will be called first during object initialization, no matter where
in the initialization list it is located.
//+------------------------------------------------------------------+
//| Base class |
//+------------------------------------------------------------------+
class CFoo
{
string m_name;
public:
//--- A constructor with an initialization list
CFoo(string name) : m_name(name) { Print(m_name);}
};
//+------------------------------------------------------------------+
//| Class derived from CFoo |
//+------------------------------------------------------------------+
class CBar : CFoo
{
CFoo m_member; // A class member is an object of the parent
public:
//--- A default constructor in the initialization list calls the constructor of a
CBar(): m_member(_Symbol), CFoo("CBAR") {Print(__FUNCTION__);}
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
CBar bar;
}
In this example, when creating the bar object, a default constructor CBar() will be
called, in which first a constructor for the parent CFoo is called, and then comes a
constructor for the m_member class member.
A destructor is a special function that is called automatically when a class object is
destroyed. The name of the destructor is written as a class name with a tilde (~).
Strings, dynamic arrays and objects, requiring deinitialization, will be de-initialized
anyway, regardless of the destructor presence or absence. If there is a destructor, these
actions will be performed after calling the destructor.
Destructors are always virtual, regardless of whether they are declared with the virtual
keyword or not.
Defining Class Methods
Class function-methods can be defined both inside the class and outside the class
declaration. If the method is defined within a class, then its body comes right after the
method declaration.
Example:
class CTetrisShape
{
protected:
int m_type;
int m_xpos;
int m_ypos;
int m_xsize;
int m_ysize;
int m_prev_turn;
int m_turn;
int m_right_border;
public:
void CTetrisShape();
void SetRightBorder(int border) { m_right_border=border; }
void SetYPos(int ypos) { m_ypos=ypos; }
void SetXPos(int xpos) { m_xpos=xpos; }
int GetYPos() { return(m_ypos); }
int GetXPos() { return(m_xpos); }
int GetYSize() { return(m_ysize); }
int GetXSize() { return(m_xsize); }
int GetType() { return(m_type); }
void Left() { m_xpos-=SHAPE_SIZE; }
void Right() { m_xpos+=SHAPE_SIZE; }
void Rotate() { m_prev_turn=m_turn; if(++m_turn>3)
virtual void Draw() { return; }
virtual bool CheckDown(int& pad_array[]);
virtual bool CheckLeft(int& side_row[]);
virtual bool CheckRight(int& side_row[]);
};
Functions from SetRightBorder(int border) to Draw() are declared and defined directly
inside the CTetrisShape class.
The CTetrisShape() constructor and methods CheckDown(int& pad_array[]),
CheckLeft(int& side_row[]) and CheckRight(int& side_row[]) are only declared inside the
class, but not defined yet. Definitions of these functions will be further in the code. In
order to define the method outside the class, the scope resolution operator is used, the
class name is used as the scope.
Example:
//+------------------------------------------------------------------+
//| Constructor of the basic class |
//+------------------------------------------------------------------+
void CTetrisShape::CTetrisShape()
{
m_type=0;
m_ypos=0;
m_xpos=0;
m_xsize=SHAPE_SIZE;
m_ysize=SHAPE_SIZE;
m_prev_turn=0;
m_turn=0;
m_right_border=0;
}
//+------------------------------------------------------------------+
//| Checking ability to move down (for the stick and cube) |
//+------------------------------------------------------------------+
bool CTetrisShape::CheckDown(int& pad_array[])
{
int i,xsize=m_xsize/SHAPE_SIZE;
//---
for(i=0; i<xsize; i++)
{
if(m_ypos+m_ysize>=pad_array[i]) return(false);
}
//---
return(true);
}
Any class members and methods declared after the specifier public: (and before the
next access specifier) are available in any reference to the class object by the program.
In this example these are the following members: functions CTetrisField(), Init(),
Deinit(), Down(), Left(), Right(), Rotate() and Drop().
Any members that are declared after the access specifier to the elements private: (and
before the next access specifier) are available only to members-functions of this class.
Specifiers of access to elements always end with a colon (:) and can appear in the class
definition many times.
Access to the members of the basis class can be redefined during inheritance in derived
classes.
Modifier 'final'
The use of the 'final' modifier during class declaration prohibits further inheritance from
this class. If the class interface requires no further modifications, or modifications are
not allowed for security reasons, declare this class with the 'final' modifier. In addition,
all the members of the class will also be implicitly considered final.
class CFoo final
{
//--- Class body
};
If you try to inherit form a class with the 'final' modifier as shown in the above example,
the compiler will return an error:
cannot inherit from 'CFoo' as it has been declared as 'final'
see declaration of 'CFoo'
Unions (union)
Union is a special data type consisting of several variables sharing the same memory
area. Therefore, the union provides the ability to interpret the same bit sequence in two
(or more) different ways. Union declaration is similar to structure declaration and starts
with the union keyword.
union LongDouble
{
long long_value;
double double_value;
};
Unlike the structure, various union members belong to the same memory area. In this
example, the union of LongDouble is declared with long and double type values sharing
the same memory area. Please note that it is impossible to make the union store a long
integer value and a double real value simultaneously (unlike a structure), since
long_value and double_value variables overlap (in memory). On the other hand, an MQL5
program is able to process data containing in the union as an integer (long) or real
(double) value at any time. Therefore, the union allows receiving two (or more) options
for representing the same data sequence.
During the union declaration, the compiler automatically allocates the memory area
sufficient to store the largest type (by volume) in the variable union. The same syntax is
used for accessing the union element as for the structures point operator.
union LongDouble
{
long long_value;
double double_value;
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
LongDouble lb;
//--- get and display the invalid -nan(ind) number
lb.double_value=MathArcsin(2.0);
printf("1. double=%f integer=%I64X",lb.double_value,lb.long_value)
//--- largest normalized value (DBL_MAX)
lb.long_value=0x7FEFFFFFFFFFFFFF;
printf("2. double=%.16e integer=%I64X",lb.double_value,lb.long_value);
//--- smallest positive normalized (DBL_MIN)
lb.long_value=0x0010000000000000;
printf("3. double=%.16e integer=%.16I64X",lb.double_value,lb.long_value);
}
/* Execution result
1. double=-nan(ind) integer=FFF8000000000000
2. double=1.7976931348623157e+308 integer=7FEFFFFFFFFFFFFF
3. double=2.2250738585072014e-308 integer=0010000000000000
*/
Since the unions allow the program to interpret the same memory data in different
ways, they are often used when an unusual type conversion is required.
The unions cannot be involved in the inheritance, and they also cannot have static
members due to their very nature. In all other aspects, the union behaves like a
structure with all its members having a zero offset. The following types cannot be the
union members:
dynamic arrays
strings
pointers to objects and functions
class objects
structure objects having constructors or destructors
structure objects having members from the points 1-5
Similar to classes, the union is capable of having constructors and destructors, as well as
methods. By default, the union members are of public access type. In order to create
private elements, use the private keyword. All these possibilities are displayed in the
example illustrating how to convert a color of the color type to ARGB as does the
ColorToARGB() function.
//+------------------------------------------------------------------+
//| Union for color(BGR) conversion to ARGB |
//+------------------------------------------------------------------+
union ARGB
{
uchar argb[4];
color clr;
//--- constructors
ARGB(color col,uchar a=0){Color(col,a);};
~ARGB(){};
//--- public methods
public:
uchar Alpha(){return(argb[3]);};
void Alpha(const uchar alpha){argb[3]=alpha;};
color Color(){ return(color(clr));};
//--- private methods
private:
//+------------------------------------------------------------------+
//| set the alpha channel value and color |
//+------------------------------------------------------------------+
void Color(color col,uchar alpha)
{
//--- set color to clr member
clr=col;
//--- set the Alpha component value - opacity level
argb[3]=alpha;
//--- interchange the bytes of R and B components (Red and Blue)
uchar t=argb[0];argb[0]=argb[2];argb[2]=t;
};
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- 0x55 means 55/255=21.6 % (0% - fully transparent)
uchar alpha=0x55;
//--- color type is represented as 0x00BBGGRR
color test_color=clrDarkOrange;
//--- values of bytes from the ARGB union are accepted here
uchar argb[];
PrintFormat("0x%.8X - here is how the 'color' type look like for %s, BGR=(%s)",
test_color,ColorToString(test_color,true),ColorToString(test_color));
//--- ARGB type is represented as 0x00RRGGBB, RR and BB components are swapped
ARGB argb_color(test_color);
//--- copy the bytes array
ArrayCopy(argb,argb_color.argb);
//--- here is how it looks in ARGB representation
PrintFormat("0x%.8X - ARGB representation with the alpha channel=0x%.2x, ARGB=(%d,
argb_color.clr,argb_color.Alpha(),argb[3],argb[2],argb[1],argb[0]);
//--- add opacity level
argb_color.Alpha(alpha);
//--- try defining ARGB as 'color' type
Print("ARGB as color=(",argb_color.clr,") alpha channel=",argb_color.Alpha());
//--- copy the bytes array
ArrayCopy(argb,argb_color.argb);
//--- here is how it looks in ARGB representation
PrintFormat("0x%.8X - ARGB representation with the alpha channel=0x%.2x, ARGB=(%d,
argb_color.clr,argb_color.Alpha(),argb[3],argb[2],argb[1],argb[0]);
//--- check with the ColorToARGB() function results
PrintFormat("0x%.8X - result of ColorToARGB(%s,0x%.2x)",ColorToARGB(test_color,alp
ColorToString(test_color,true),alpha);
}
/* Execution result
0x00008CFF - here is how the color type looks for clrDarkOrange, BGR=(255,140,0)
0x00FF8C00 - ARGB representation with the alpha channel=0x00, ARGB=(0,255,140,0)
ARGB as color=(0,140,255) alpha channel=85
0x55FF8C00 - ARGB representation with the alpha channel=0x55, ARGB=(85,255,140,0)
0x55FF8C00 - result of ColorToARGB(clrDarkOrange,0x55)
*/
Interfaces
An interface allows determining specific functionality, which a class can then implement.
In fact, an interface is a class that cannot contain any members, and may not have a
constructor and/or a destructor. All methods declared in an interface are purely virtual,
even without an explicit definition.
An interface is defined using the "interface" keyword. Example:
//--- Basic interface for describing animals
interface IAnimal
{
//--- The methods of the interface have public access by default
void Sound(); // The sound produced by the animal
};
//+------------------------------------------------------------------+
//| The CCat class is inherited from the IAnimal interface |
//+------------------------------------------------------------------+
class CCat : public IAnimal
{
public:
CCat() { Print("Cat was born"); }
~CCat() { Print("Cat is dead"); }
//--- Implementing the Sound method of the IAnimal interface
void Sound(){ Print("meou"); }
};
//+------------------------------------------------------------------+
//| The CDog class is inherited from the IAnimal interface |
//+------------------------------------------------------------------+
class CDog : public IAnimal
{
public:
CDog() { Print("Dog was born"); }
~CDog() { Print("Dog is dead"); }
//--- Implementing the Sound method of the IAnimal interface
void Sound(){ Print("guaf"); }
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- An array of pointers to objects of the IAnimal type
IAnimal *animals[2];
//--- Creating child classes of IAnimal and saving pointers to them into an array
animals[0]=new CCat;
animals[1]=new CDog;
//--- Calling the Sound() method of the basic IAnimal interface for each child
for(int i=0;i<ArraySize(animals);++i)
animals[i].Sound();
//--- Deleting objects
for(int i=0;i<ArraySize(animals);++i)
delete animals[i];
//--- Execution result
/*
Cat was born
Dog was born
meou
guaf
Cat is dead
Dog is dead
*/
}
Like with abstract classes, an interface object cannot be created without inheritance.
An interface can only be inherited from other interfaces and can be a parent for a class.
An interface is always publicly visible.
An interface cannot be declared within a class or structure declaration, but a pointer to
the interface can be saved in a variable of type void *. Generally speaking, a pointer to
an object of any class can be saved into a variable of type void *. In order to convert a
void * pointer to a pointer to an object of a particular class, use the dynamic_cast
operator. If conversion is not possible, the result of the dynamic_cast operation will be
NULL.
See also
Object-Oriented Programming
MQL4 Reference / Language Basics / Data Types / Dynamic Array Object
Static Arrays
When all significant array dimensions are explicitly specified, the compiler pre-allocates
the necessary memory size. Such an array is called static. Nevertheless, the compiler
allocates additional memory for the object of a dynamic array, which (object) is
associated with the pre-allocated static buffer (memory part for storing the array).
Creating a dynamic array object is due to the possible need to pass this static array as a
parameter to some function.
Examples:
double stat_array[5]; // 1-dimensional static array
some_function(stat_array);
...
bool some_function(double& array[])
{
if(ArrayResize(array,100)<0) return(false);
...
return(true);
}
Arrays in Structures
When a static array is declared as a member of a structure, a dynamic array object is
not created. This is done to ensure compatibility of data structures used in the Windows
API.
However, static arrays that are declared as members of structures can also be passed to
MQL5 functions. In this case, when passing the parameter, a temporary object of a
dynamic array will be created. Such an object is linked with the static array - member of
structure.
See also
Array Functions, Initialization of Variables, Visibility Scope and Lifetime of Variables,
Creating and Deleting Objects
MQL4 Reference / Language Basics / Data Types / Typecasting
Typecasting
Casting Numeric Types
Often a necessity occurs to convert one numeric type into another. Not all numeric types
can be converted into another. Here is the scheme of allowed casting:
Solid lines with arrows indicate changes that are performed almost without any loss of
information. Instead of the char type, the bool type can be used (both take 1 byte of
memory), instead of type int, the color type can be used (4 bytes), instead of the long
type, datetime can be used (take 8 bytes). The four dashed grey lines, also arrowed,
denote conversions, when the loss of precision can occur. For example, the number of
digits in an integer equal to 123456789 (int) is higher than the number of digits that can
be represented by float.
int n=123456789; float f=n; // the content of f is equal to 1.234567892E8
Print("n = ",n," f = ",f);
// result n= 123456789 f= 123456792.00000
A number converted into float has the same order, but is less accurate. Conversions,
contrary to black arrows, can be performed with possible data loss. Conversions between
char and uchar, short and ushort, int and uint, long and ulong (conversions to both
sides), may lead to the loss of data.
As a result of converting floating point values to integer type, the fractional part is
always deleted. If you want to round off a float to the nearest whole number (which in
many cases is more useful), you should use MathRound().
Example:
//--- Gravitational acceleration
double g=9.8;
double round_g=(int)g;
double math_round_g=MathRound(g);
Print("round_g = ",round_g);
Print("math_round_g = ",math_round_g);
/*
Result:
round_g = 9
math_round_g = 10
*/
If two values are combined by a binary operator, before the operation execution the
operand of a lower type is converted to the higher type in accordance with the priority
given in the below scheme:
The data types char, uchar, short, and ushort unconditionally are converted to the int
type.
Examples:
char c1=3;
//--- First example
double d2=c1/2+0.3;
Print("c1/2 + 0.3 = ",d2);
// Result: c1/2+0.3 = 1.3
The calculated expression consists of two operations. In the first example, the variable
c1 of the char type is converted to a temporary variable of the int type, because the
second operand in the division operation, the constant 2, is of the higher type int. As a
result of the integer division 3/2 we get the value 1, which is of the int type.
In the second operation of the first example, the second operand is the constant 0.3,
which is of the double type, so the result of the first operation is converted into a
temporary variable of the double type with a value of 1.0.
In the second example the variable of the char type c1 is converted to a temporary
variable of the double type, because the second operand in the division operation, the
constant 2.0, is of the double type; no further conversions are made.
Typecasting of Numeric Types
In the expressions of the MQL4 language both explicit and implicit typecasting can be
used. The explicit typecasting is written as follows:
var_1 = (type)var_2;
An expression or function execution result can be used as the var_2 variable. The
function style notation of the explicit typecasting is also possible:
var_1 = type(var_2);
Before the division operation is performed, the c1 variable is explicitly cast to the
double type. Now the integer constant 2 is cast to the value 2.0 of the double type,
because as a result of converting the first operand has taken the double type. In fact,
the explicit typecasting is a unary operation.
Besides, when trying to cast types, the result may go beyond the permissible range. In
this case, the truncation occurs. For example:
char c;
uchar u;
c=400;
u=400;
Print("c = ",c); // Result c=-112
Print("u = ",u); // Result u=144
Before operations (except for the assignment ones) are performed, the data are
converted into the maximum priority type. Before assignment operations are performed,
the data are cast into the target type.
Examples:
int i=1/2; // no types casting, the result is 0
Print("i = 1/2 ",i);
double x=1/2; // the expression of the int type is cast to the double targe
Print("x = 1/2; ",x); // the result is 0.0
When converting long/ulong type into double, precision may be lost in case the integer
value is greater than 9223372036854774784 or less than -9223372036854774784.
void OnStart()
{
long l_max=LONG_MAX;
long l_min=LONG_MIN+1;
//--- define the highest integer value, which does not lose accuracy when being cast
while(l_max!=long((double)l_max))
l_max--;
//--- define the lowest integer value, which does not lose accuracy when being cast t
while(l_min!=long((double)l_min))
l_min++;
//--- derive the found interval for integer values
PrintFormat("When casting an integer value to double, it must be "
"within [%I64d, %I64d] interval",l_min,l_max);
//--- now, let's see what happens if the value falls out of this interval
PrintFormat("l_max+1=%I64d, double(l_max+1)=%.f, ulong(double(l_max+1))=%I64d",
l_max+1,double(l_max+1),long(double(l_max+1)));
PrintFormat("l_min-1=%I64d, double(l_min-1)=%.f, ulong(double(l_min-1))=%I64d",
l_min-1,double(l_min-1),long(double(l_min-1)));
//--- receive the following result
// When casting an integer value to double, it should be within [-9223372036854774784
// l_max+1=9223372036854774785, double(l_max+1)=9223372036854774800, ulong(double(l_m
// l_min-1=-9223372036854774785, double(l_min-1)=-9223372036854774800, ulong(double(l
}
Typecasting for the String Type
The string type has the highest priority among simple types. Therefore, if one of
operands of an operation is of the string type, the second operand will be cast to a string
automatically. Note that for a string, a single dyadic two-place operation of addition is
possible. The explicit casting of string to any numeric type is allowed.
Examples:
string s1=1.0/8; // the expression is cast to the double type,
Print("s1 = 1.0/8; ",s1); // then is to the target type of string,
// result is "0.12500000" (a string containing 10 characters)
string str1="true";
string str2="0,255,0";
string str3="2009.06.01";
string str4="1.2345e2";
Print(bool(str1));
Print(color(str2));
Print(datetime(str3));
Print(double(str4));
Typecasting of Simple Structure Types
Data of the simple structures type can be assigned to each other only if all the members
of both structures are of numeric types. In this case both operands of the assignment
operation (left and right) must be of the structures type. The member-wise casting is not
performed, a simple copying is done. If the structures are of different sizes, the number
of bytes of the smaller size is copied. Thus the absence of union in MQL4 is
compensated.
Examples:
struct str1
{
double d;
};
//---
struct str2
{
long l;
};
//---
struct str3
{
int low_part;
int high_part;
};
//---
struct str4
{
string s;
};
//+------------------------------------------------------------------+
void OnStart()
{
str1 s1;
str2 s2;
str3 s3;
str4 s4;
//---
s1.d=MathArcsin(2.0); // get the invalid number -1. # IND
s2=s1;
printf("1. %f %I64X",s1.d,s2.l);
//---
s3=s2;
printf("2. high part of long %.8X low part of long %.8X",
s3.high_part,s3.low_part);
//---
s4.s="some constant string";
s3=s4;
printf("3. buffer len is %d constant string address is 0x%.8X",
s3.low_part,s3.high_part);
}
Another example illustrates the method of organizing a custom function for receiving
RGB (Red, Green, Blue) representation from the color type. Create two structures of the
same size but with different contents. For convenience, let's add a function returning
the RGB representation of a color as a string.
#property script_show_inputs
input color testColor=clrBlue;// set color for testing
//--- structure for representing color as RGB
struct RGB
{
uchar blue; // blue component of color
uchar green; // green component of color
uchar red; // red component of color
uchar empty; // this byte is not used
string toString(); // function for receiving a string
};
//--- function for showing color as a string
string RGB::toString(void)
{
string out="("+(string)red+":"+(string)green+":"+(string)blue+")";
return out;
}
//--- structure for storing of the built-in color type
struct builtColor
{
color c;
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- a variable for storing in RGB
RGB colorRGB;
//--- variable for storing the color type
builtColor test;
test.c=testColor;
//--- casting two structures by copying contents
colorRGB=test;
Print("color ",test.c,"=",colorRGB.toString());
//---
}
Typecasting of Base Class Pointers to Pointers of Derivative Classes
Objects of the open generated class can also be viewed as objects of the corresponding
base class. This leads to some interesting consequences. For example, despite the fact
that objects of different classes, generated by a single base class, may differ
significantly from each other, we can create a linked list (List) of them, as we view them
as objects of the base type. But the converse is not true: the base class objects are not
automatically objects of a derived class.
You can use the explicit casting to convert the base class pointers to the pointers of a
derived class. But you must be fully confident in the admissibility of such a
transformation, because otherwise a critical runtime error will occur and the mql4
program will be stopped.
Dynamic typecasting using dynamic_cast operator
Dynamic typecasting is performed using dynamic_cast operator that can be applied only
to pointers to classes. Type validation is performed at runtime. This means that the
compiler does not check the data type applied for typecasting when dynamic_cast
operator is used. If a pointer is converted to a data type which is not the actual type of
an object, the result is NULL.
dynamic_cast <type-id> ( expression )
The type-id parameter in angle brackets should point to a previously defined class type.
Unlike C++, expression operand type can be of any value except for void.
Example:
class CBar { };
class CFoo : public CBar { };
void OnStart()
{
CBar bar;
//--- dynamic casting of *bar pointer type to *foo pointer is allowed
CFoo *foo = dynamic_cast<CFoo *>(&bar); // no critical error
Print(foo); // foo=NULL
//--- an attempt to explicitly cast a Bar type object reference to a Foo type object
foo=(CFoo *)&bar; // critical runtime error
Print(foo); // this string is not executed
}
See also
Data Types
MQL4 Reference / Language Basics / Data Types / Void Type and NULL Constant
Also NULL can be compared to pointers to objects created with the new operator.
See also
Variables, Functions
MQL4 Reference / Language Basics / Data Types / User-defined Types
User-defined types
The typedef keyword in C++ allows creating user-defined data types. To do this, simply
specify a new data type name for an already existing data type. The new data type is
not created. A new name for the existing type is defined instead. User-defined types
make applications more flexible: sometimes, it is enough to change typedef instructions
using substitution macros (#define). User-defined types also improve code readability
since it is possible to apply custom names to standard data types using typedef. The
general format of the entry for creating a user-defined type:
typedef type new_name;
Here, type means any acceptable data type, while new_name is a new name of the type.
A new name is set only as an addition (not as a replacement) to an existing type name.
MQL5 allows creating pointers to functions using typedef.
where after typedef, the function signature (number and type of input parameters, as
well as a type of a result returned by the function) is set. Below is a simple example of
creating and applying a pointer to a function:
//--- declare a pointer to a function that accepts two int parameters typedef int
//--- TFunc is a type, and it is possible to declare the variable pointer to the func
TFunc func_ptr; // pointer to the function
//--- declare the functions corresponding to the TFunc description
int sub(int x,int y) { return(x-y); } // subtract one number from another
int add(int x,int y) { return(x+y); } // addition of two numbers
int neg(int x) { return(~x); } // invert bits in the variable
//--- the func_ptr variable may store the function address to declare it later
func_ptr=sub;
Print(func_ptr(10,5));
func_ptr=add;
Print(func_ptr(10,5));
func_ptr=neg; // error: neg does not have int (int,int) type
Print(func_ptr(10)); // error: two parameters needed
In this example, the func_ptr variable may receive the sub and add functions since they
have two inputs each of int type as defined in the TFunc pointer to the function. On the
contrary, the neg function cannot be assigned to the func_ptr pointer since its signature
is different.
Arranging event models in the user interface
Pointers to functions allow you to easily create processing of events when creating a user
interface. First, define a pointer to the TAction function to be called by pressing the
button and create three functions according to the TAction description.
//--- create a custom function type
typedef int(*TAction)(string,int);
//+------------------------------------------------------------------+
//| Open the file |
//+------------------------------------------------------------------+
int Open(string name,int id)
{
PrintFormat("%s function called (name=%s id=%d)",__FUNCTION__,name,id);
return(1);
}
//+------------------------------------------------------------------+
//| Save the file |
//+------------------------------------------------------------------+
int Save(string name,int id)
{
PrintFormat("%s function called (name=%s id=%d)",__FUNCTION__,name,id);
return(2);
}
//+------------------------------------------------------------------+
//| Close the file |
//+------------------------------------------------------------------+
int Close(string name,int id)
{
PrintFormat("%s function called (name=%s id=%d)",__FUNCTION__,name,id);
return(3);
}
Then, create the MyButton class from CButton, where we should add the TAction pointer
to the function.
//+------------------------------------------------------------------+
//| Create the button class with the events processing function |
//+------------------------------------------------------------------+
class MyButton: public CButton
{
private:
TAction m_action; // chart events handler
public:
MyButton(void){}
~MyButton(void){}
//--- constructor specifying the button text and the pointer to the events handlin
MyButton(string text, TAction act)
{
Text(text);
m_action=act;
}
//--- set the custom function called from the OnEvent() events handler
void SetAction(TAction act){m_action=act;}
//--- standard chart events handler
virtual bool OnEvent(const int id,const long &lparam,const double &dparam,con
{
if(m_action!=NULL && lparam==Id())
{
//--- call the custom m_action() handler
m_action(sparam,(int)lparam);
return(true);
}
else
//--- return the result of calling the handler from the CButton parent class
return(CButton::OnEvent(id,lparam,dparam,sparam));
}
};
Create the CControlsDialog derivative class from CAppDialog, add the m_buttons array to
it for storing the buttons of the MyButton type, as well as the AddButton(MyButton
&button) and CreateButtons() methods.
//+------------------------------------------------------------------+
//| CControlsDialog class |
//| Objective: graphical panel for managing the application |
//+------------------------------------------------------------------+
class CControlsDialog : public CAppDialog
{
private:
CArrayObj m_buttons; // button array
public:
CControlsDialog(void){};
~CControlsDialog(void){};
//--- create
virtual bool Create(const long chart,const string name,const int subwin,const
//--- add the button
bool AddButton(MyButton &button){return(m_buttons.Add(GetPointer(butt
protected:
//--- create the buttons
bool CreateButtons(void);
};
//+------------------------------------------------------------------+
//| Create the CControlsDialog object on the chart |
//+------------------------------------------------------------------+
bool CControlsDialog::Create(const long chart,const string name,const int subwin,cons
{
if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
return(false);
return(CreateButtons());
//---
}
//+------------------------------------------------------------------+
//| defines |
//+------------------------------------------------------------------+
//--- indents and gaps
#define INDENT_LEFT (11) // indent from left (with allow
#define INDENT_TOP (11) // indent from top (with allowa
#define CONTROLS_GAP_X (5) // gap by X coordinate
#define CONTROLS_GAP_Y (5) // gap by Y coordinate
//--- for buttons
#define BUTTON_WIDTH (100) // size by X coordinate
#define BUTTON_HEIGHT (20) // size by Y coordinate
//--- for the indication area
#define EDIT_HEIGHT (20) // size by Y coordinate
//+------------------------------------------------------------------+
//| Create and add buttons to the CControlsDialog panel |
//+------------------------------------------------------------------+
bool CControlsDialog::CreateButtons(void)
{
//--- calculate buttons coordinates
int x1=INDENT_LEFT;
int y1=INDENT_TOP+(EDIT_HEIGHT+CONTROLS_GAP_Y);
int x2;
int y2=y1+BUTTON_HEIGHT;
//--- add buttons objects together with pointers to functions
AddButton(new MyButton("Open",Open));
AddButton(new MyButton("Save",Save));
AddButton(new MyButton("Close",Close));
//--- create the buttons graphically
for(int i=0;i<m_buttons.Total();i++)
{
MyButton *b=(MyButton*)m_buttons.At(i);
x1=INDENT_LEFT+i*(BUTTON_WIDTH+CONTROLS_GAP_X);
x2=x1+BUTTON_WIDTH;
if(!b.Create(m_chart_id,m_name+"bt"+b.Text(),m_subwin,x1,y1,x2,y2))
{
PrintFormat("Failed to create button %s %d",b.Text(),i);
return(false);
}
//--- add each button to the CControlsDialog container
if(!Add(b))
return(false);
}
//--- succeed
return(true);
}
Now, we can develop the program using the CControlsDialog control panel having 3
buttons: Open, Save and Close. When clicking a button, the appropriate function in the
form of the TAction pointer is called.
//--- declare the object on the global level to automatically create it when launchin
CControlsDialog MyDialog;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- now, create the object on the chart
if(!MyDialog.Create(0,"Controls",0,40,40,380,344))
return(INIT_FAILED);
//--- launch the application
MyDialog.Run();
//--- application successfully initialized
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- clear comments when the application shuts down
Comment("");
//--- destroy dialog
MyDialog.Destroy(reason);
}
//+------------------------------------------------------------------+
//| Expert chart event function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, // event ID
const long& lparam, // event parameter of the long type
const double& dparam, // event parameter of the double type
const string& sparam) // event parameter of the string type
{
//--- call the handler from the parent class (here it is CAppDialog) for the chart ev
MyDialog.ChartEvent(id,lparam,dparam,sparam);
}
The launched application's appearance and button clicking results are provided on the
screenshot.
The full source code of the program
//+------------------------------------------------------------------+
//| Panel_Buttons.mq5 |
//| Copyright 2017, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
See also
Variables, Functions
MQL4 Reference / Language Basics / Data Types / Object Pointers
Object Pointers
In MQL4, there is a possibility to dynamically create objects of complex type. This is
done by the new operator, which returns a descriptor of the created object. Descriptor
is 8 bytes large. Syntactically, object descriptors in MQL4 are similar to pointers in C++.
Examples:
MyObject* hobject= new MyObject();
In contrast to C++, the hobject variable from example above is not a pointer to memory,
but rather an object descriptor. Furthermore, in MQL5 all objects in function parameters
must be passed by reference. Below are examples of passing objects as function
parameters:
class Foo {
public:
string m_name;
int m_id;
static int s_counter;
//--- constructors and desctructors
Foo(void){Setup("noname");};
Foo(string name){Setup(name);};
~Foo(void){};
//--- initializes object of type Foo
void Setup(string name)
{
m_name=name;
s_counter++;
m_id=s_counter;
}
};
int Foo::s_counter=0;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare an object as variable with its automatic creation
Foo foo1;
//--- variant of passing an object by reference
PrintObject(foo1);
//--- declare a pointer to an object and create it using the 'new' operator
Foo *foo2=new Foo("foo2");
//--- variant of passing a pointer to an object by reference
PrintObject(foo2); // pointer to an object is converted automatically by compiler
See also
Variables, Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating
and Deleting Objects
MQL4 Reference / Language Basics / Data Types / References: Modifier & and Keyword this
public:
void setArray(double &array[]);
};
//+------------------------------------------------------------------+
//| filling the array |
//+------------------------------------------------------------------+
void CDemoClass::setArray(double &array[])
{
if(ArraySize(array)>0)
{
ArrayResize(m_array,ArraySize(array));
ArrayCopy(m_array, array);
}
}
Keyword this
A variable of class type (object) can be passed both by reference and by
pointer. As well as reference, the pointer allows having access to an
object. After the object pointer is declared, the new operator should be
applied to it to create and initialize it.
The reserved word this is intended for obtaining the reference of the
object to itself, which is available inside class or structure methods. this
always references to the object, in the method of which it is used, and the
expression GetPointer(this) gives the pointer of the object, whose member
is the function, in which call of GetPointer() is performed. In MQL4
functions can't return objects, but they can return the object pointer.
Thus, if we need a function to return an object, we can return the pointer
of this object in the form of GetPointer(this). Let's add function
getDemoClass() that returns pointer of the object of this class, into the
description of CDemoClass.
class CDemoClass
{
private:
double m_array[];
public:
void setArray(double &array[]);
CDemoClass *getDemoClass();
};
//+------------------------------------------------------------------+
//| filling the array |
//+------------------------------------------------------------------+
void CDemoClass::setArray(double &array[])
{
if(ArraySize(array)>0)
{
ArrayResize(m_array,ArraySize(array));
ArrayCopy(m_array,array);
}
}
//+------------------------------------------------------------------+
//| returns its own pointer |
//+------------------------------------------------------------------+
CDemoClass *CDemoClass::getDemoClass(void)
{
return(GetPointer(this));
}
Structures don't have pointers, operators new and delete can't be applied
to them, GetPointer(this) can't be used.
See also
Object Pointers, Creating and Deleting Objects, Visibility Scope and
Lifetime of Variables
MQL4 Reference / Language Basics / Operations and Expressions
Operation symbols are used in expressions and have sense when appropriate operands
are given to them. Punctuation marks are emphasized, as well. These are parentheses,
braces, comma, colon, and semicolon.
Operation symbols, punctuation marks, and spaces are used to separate language
elements from each other.
This section contains the description of the following topics:
Expressions
Arithmetic Operations
Assignment Operations
Operations of Relation
Boolean Operations
Bitwise Operations
Other Operations
Priorities and Operations Order
MQL4 Reference / Language Basics / Operations and Expressions / Expressions
Expressions
An expression consists of one or more operands and operation symbols. An expression
can be written in several lines.
Examples:
a++; b = 10; // several expressions are located in one line //--- one express
x = (y * z) /
(w + 2) + 127;
Arithmetic Operations
Arithmetic operations include additive and multiplicative operations:
Sum of variables i = j + 2; Difference of variables
Changing the sign x = - x;
Product of variables z = 3 * x;
Division quotient i = j / 5;
Remainder of division minutes = time % 60;
Adding 1 to the variable value i++;
Adding 1 to the variable value ++i;
Subtracting 1 from the variable value k--;
Subtracting 1 from the variable value --k;
Increment and decrement operations are applied only to variables, they can't be applied
to constants. The prefix increment (++i) and decrement (--k) are applied to the variable
right before this variable is used in an expression.
Post-increment (i++) and post-decrement (k--) are applied to the variable right after this
variable is used in an expression.
Important Notice
int i=5;
int k = i++ + ++i;
Computational problems may occur while moving the above expression from one
programming environment to another one (for example, from Borland C++ to MQL4). In
general, the order of computations depends on the compiler implementation. In
practice, there are two ways to implement the post-decrement (post-increment):
1. The post-decrement (post-increment) is applied to the variable after calculating the
whole expression.
2. The post-decrement (post-increment) is applied to the variable immediately at the
operation.
Currently the first way of post-decrement (post-increment) calculation is implemented
in MQL4. But even knowing this peculiarity, it is not recommended to experiment with its
use.
Examples:
int a=3;
a++; // valid expression
int b=(a++)*3; // invalid expression
See also
Precedence Rules
MQL4 Reference / Language Basics / Operations and Expressions / Assignment Operations
Assignment Operations
The value of the expression that includes the given operation is the value of the left
operand after assignment:
Assigning the value of x to the y variable y = x;
Bitwise operations can be applied to integers only. When performing the operation of the
logical shift of the y representation to the right/left by x bits, the 5 smallest binary
digits of the x value are used, the highest ones are dropped, i.e. the shift is made to 0-
31 bits.
By %= operation (y value by module of x), the result sign is equal to the sign of divided
number.
The assignment operator can be used several times in an expression . In this case the
processing of the expression is performed from left to right:
y=x=3;
First, the variable x will be assigned the value 3, then the y variable will be assigned the
value of x, i.e. also 3.
See also
Precedence Rules
MQL4 Reference / Language Basics / Operations and Expressions / Operations of Relation
Operations of Relation
Boolean FALSE is represented with an integer zero value, while the boolean TRUE is
represented by any non-zero value.
The value of expressions containing operations of relation or logical operations is FALSE
(0) or TRUE (1).
True if a is equal to b a == b; True if a is not equal to b
True if a is less than b a < b;
True if a is greater than b a > b;
True if a is less than or equal to b a <= b;
True if a is greater than or equal to b a >= b;
The equality of two real numbers can't be compared. In most cases, two seemingly
identical numbers can be unequal because of different values in the 15th decimal place.
In order to correctly compare two real numbers, compare the normalized difference of
these numbers with zero.
Example:
bool CompareDoubles(double number1,double number2)
{
if(NormalizeDouble(number1-number2,8)==0) return(true);
else return(false);
}
void OnStart()
{
double first=0.3;
double second=3.0;
double third=second-2.7;
if(first!=third)
{
if(CompareDoubles(first,third))
printf("%.16f and %.16f are equal",first,third);
}
}
// Result: 0.3000000000000000 0.2999999999999998 are equal
See also
Precedence Rules
MQL4 Reference / Language Basics / Operations and Expressions / Boolean Operations
Boolean Operations
Logical Negation NOT (!)
Operand of the logical negation (!) must be of arithmetic type. The result is TRUE (1), if
the operand value is FALSE (0); and it is equal to FALSE (0), if the operand differs from
FALSE (0).
if(!a) Print("not 'a'");
See also
Precedence Rules
MQL4 Reference / Language Basics / Operations and Expressions /
Bitwise Operations
Bitwise Operations
Complement to One
Complement of the variable value up to one. The value of
the expression contains 1 in all digits where the variable
value contains 0, and 0 in all digits where the variable
contains 1.
b = ~n;
Example:
char a='a',b; b=~a;
Print("a = ",a, " b = ",b);
// The result will be:
// a = 97 b = -98
Right Shift
The binary representation of x is shifted to the right by y
digits. If the value to shift is of the unsigned type, the
logical right shift is made, i.e. the freed left-side bits will
be filled with zeroes.
If the value to shift is of a sign type, the arithmetic right
shift is made, i.e. the freed left-side digits will be filled
with the value of a sign bit (if the number is positive, the
value of the sign bit is 0; if the number is negative, the
value of the sign bit is 1).
x = x >> y;
Example:
char a='a',b='b';
Print("Before: a = ",a, " b = ",b);
//--- shift to the right
b=a>>1;
Print("After: a = ",a, " b = ",b);
// The result will be:
// Before: a = 97 b = 98
// After: a = 97 b = 48
Left Shift
The binary representation of x is shifted to the left by y
digits, the freed right-side digits are filled with zeros.
x = x << y;
Example:
char a='a',b='b';
Print("Before: a = ",a, " b = ",b);
//--- shift to the left
b=a<<1;
Print("After: a = ",a, " b = ",b);
// The result will be:
// Before: a = 97 b = 98
// After: a = 97 b = -62
Example:
char a='a',b='b';
//--- AND operation
char c=a&b;
Print("a = ",a," b = ",b);
Print("a & b = ",c);
// The result will be:
// a = 97 b = 98
// a & b = 96
Bitwise OR Operation
The bitwise OR operation of binary representations of x
and y. The value of the expression contains 1 in all digits
where x or y does not contain 0, and it contains 0 in all
other digits.
b = x | y;
Example:
char a='a',b='b';
//--- OR operation
char c=a|b;
Print("a = ",a," b = ",b);
Print("a | b = ",c);
// The result will be:
// a = 97 b = 98
// a | b = 99
Example:
char a='a', b='b';
//--- Excluding OR operation
char c=a^b;
Print("a = ",a," b = ",b);
Print("a ^ b = ",c);
// The result will be:
// a = 97 b = 98
// a ^ b = 3
Other operations
Indexing ( [] )
When addressing the i-th element of the array, the expression value is the
value of a variable with the serial number i.
Example:
array[i] = 3; // Assign the value of 3 to i-th element of the array.
Comma Operation ( , )
Expressions separated by commas are executed from left to right. All side
effects of the left expression calculation can appear before the right
expression is calculated. The result type and value coincide with those of the
right expression. The list of parameters to be passed (see above) can be
considered as an example.
Example:
for(i=0,j=99; i<100; i++,j--) Print(array[i][j]);
Dot Operator ( . )
For the direct access to the public members of structures and classes the dot
operation is used. Syntax:
Variable_name_of_structure_type.Member_name
Example:
struct SessionTime
{
string sessionName;
int startHour;
int startMinutes;
int endHour;
int endMinutes;
} st;
st.sessionName="Asian";
st.startHour=0;
st.startMinutes=0;
st.endHour=9;
st.endMinutes=0;
If there is no scope name, this is the explicit direction to use the global
scope. If there is no scope resolution operation, the function is sought in the
nearest scope. If there is no function in the local scope, the search is
conducted in the global scope.
The scope resolution operation is also used to define function-class member.
type Class_name::Function_name(parameters_description)
{
// function body
}
Use of several functions of the same name from different execution contexts
in a program may cause ambiguity. The priority order of function calls
without explicit scope specification is the following:
1. Class methods. If no function with the specified name is set in the class,
move to the next level.
2. MQL4 functions. If the language does not have such a function, move to
the next level.
3. User defined global functions. If no function with the specified name is
found, move to the next level.
4. Imported functions. If no function with the specified name is found, the
compiler returns an error.
To avoid the ambiguity of function calls, always explicitly specify the
function scope using the scope resolution operation.
Example:
#property script_show_inputs
#import "kernel32.dll"
int GetLastError(void);
#import
class CCheckContext
{
int m_id;
public:
CCheckContext() { m_id=1234; }
protected:
int GetLastError() { return(m_id); }
};
class CCheckContext2 : public CCheckContext
{
int m_id2;
public:
CCheckContext2() { m_id2=5678; }
void Print();
protected:
int GetLastError() { return(m_id2); }
};
void CCheckContext2::Print()
{
::Print("Terminal GetLastError",::GetLastError());
::Print("kernel32 GetLastError",kernel32::GetLastError());
::Print("parent GetLastError",CCheckContext::GetLastError());
::Print("our GetLastError",GetLastError());
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
CCheckContext2 test;
test.Print();
}
//+------------------------------------------------------------------+
Precedence Rules
Each group of operations in the table has the same
priority. The higher the priority of operations is, the
higher it is position of the group in the table. The
precedence rules determine the grouping of operations
and operands.
Attention: Precedence of operations in the MQL4
language corresponds to the priority adopted in C++.
Operation Desciption Execution
Order
() Function Call From left to
[] Referencing to an array right
. element
Referencing to a structure
element
! Logical negation Right to left
~ Bitwise negation (complement)
++ Sign changing
-- Increment by one
(type) Decrement by one
sizeof Typecasting
Determining size in bytes
* Multiplication From left to
/ Division right
% Module division
+ Addition From left to
Subtraction right
Operation Desciption Execution
Order
<< Left shift From left to
>> Right shift right
< Less than From left to
<= Less than or equal right
> Greater than
>= Greater than or equal
== Equal From left to
!= Not equal right
& Bitwise AND operation From left to
right
^ Bitwise exclusive OR From left to
right
| Bitwise OR operation From left to
right
&& Logical AND operation From left to
right
|| Logical OR operation From left to
right
?: Conditional Operator Right to left
Operation Desciption Execution
Order
= Assignment Right to left
*= Multiplication with assignment
/= Division with assignment
%= Module with assignment
+= Addition with assignment
-= Subtraction with assignment
<<= Left shift with assignment
>>= Right shift with assignment
&= Bitwise AND with assignment
^= Exclusive OR with assignment
|= Bitwise OR with assignment
, Comma From left to
right
Operators
Language operators describe some algorithmic operations that
must be executed to accomplish a task. The program body is a
sequence of such operators. Operators following one by one are
separated by semicolons.
Operator Description
Compound One or more operators of any type, enclosed in
operator {} curly braces {}
Expression Any expression that ends with a semicolon (;)
operator (;)
return operator Terminates the current function and returns
control to the calling program
if-else conditional Is used when it's necessary to make a choice
operator
?: conditional A simple analog of the if-else conditional
operator operator
switch selection Passes control to the operator, which corresponds
operator to the expression value
while loop Performs an operator until the expression
operator checked becomes false. The expression is
checked before each iteration
for loop operator Performs an operator until the expression
checked becomes false. The expression is
checked before each iteration
do-while loop Performs an operator until the expression
operator checked becomes false. The end condition is
checked, after each loop. The loop body is
always executed at least once.
Operator Description
break operator Terminates the execution of the nearest
attached external operator switch, while, do-
while or for
continue operator Passes control to the beginning of the nearest
external loop operator while, do-while or for
new operator Creates an object of the appropriate size and
returns a descriptor of the created object.
delete operator Deletes the object created by the new operator
See also
Initialization of Variables, Visibility Scope and Lifetime of
Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Operators / Compound Operator
Compound Operator
A compound operator (a block) consists of one or more
operators of any type, enclosed in braces {}. The closing
brace must not be followed by a semicolon (;).
Example:
if(x==0) {
Print("invalid position x = ",x);
return;
}
See also
Initialization of Variables, Visibility Scope and Lifetime
of Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Operators / Expression Operator
Expression Operator
Any expression followed by a semicolon (;) is the operator.
Here are some examples of expression operators.
Assignment Operator
Identifier = expression;
x=3; y=x=3;
bool equal=(x==y);
Empty Operator
Consists only of a semicolon (;) and is used to denote an
empty body of a control operator.
See also
Initialization of Variables, Visibility Scope and Lifetime
of Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Operators / Return Operator
Return Operator
The return operator terminates the current function
execution and returns control to the calling program. The
expression calculation result is returned to the calling
function. The expression can contain an assignment
operator.
Example:
int CalcSum(int x, int y) {
return(x+y);
}
See also
Initialization of Variables, Visibility Scope and Lifetime
of Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Operators / Ternary Operator ?:
Ternary Operator ?:
The general form of the ternary operator is as follows:
expression1 ? expression2 : expression3
For the first operand - "expression1" - any expression that results in a bool type value
can be used. If the result is true, then the operator set by the second operand, i.e.
"expression2" is executed.
If the first operand is false, the third operand - "expression3" is performed. The second
and third operands, i.e. "expression2" and "expression3" should return values of one type
and should not be of void type. The result of the conditional operator execution is the
result of expression2 or result of the expression3, depending on the result of
expression1.
//--- normalize difference between open and close prices for a day range double true_r
bool Expression1=true;
double Expression2=M_PI;
string Expression3="3.1415926";
void OnStart()
{
func(Expression2);
func(Expression3);
// Result:
// double argument: 3.141592653589793
// string argument: 3.1415926
// string argument: 3.141592653589793
// string argument: 3.1415926
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating and
Deleting Objects
MQL4 Reference / Language Basics / Operators / Switch Operator
Switch Operator
Compares the expression value with constants in all the
case variants and passes control to the operator that
corresponds to the expression value. Each variant of case
can be marked with an integer constant, a literal constant
or a constant expression. The constant expression can't
contain variables or function calls. Expression of the
switch operator must be of integer type.
switch(expression) {
case constant: operators
case constant: operators
...
default: operators
}
See also
Initialization of Variables, Visibility Scope and Lifetime
of Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Operators / Loop Operator while
See also
Initialization of Variables, Visibility Scope and Lifetime
of Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Operators / Loop Operator for
See also
Initialization of Variables, Visibility Scope and Lifetime
of Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Operators / Loop Operator do while
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables, Creating
and Deleting Objects
MQL4 Reference / Language Basics / Operators / Break Operator
Break Operator
The break operator terminates the execution of the nearest nested
outward switch, while, do-while or for operator. The control is passed to
the operator that follows the terminated one. One of the purposes of
this operator is to finish the looping execution when a certain value is
assigned to a variable.
Example:
//--- searching for the first zero element for(i=0;i<array_size;i++)
if(array[i]==0)
break;
See also
Initialization of Variables, Visibility Scope and Lifetime of Variables,
Creating and Deleting Objects
MQL4 Reference / Language Basics / Operators / Continue Operator
Continue Operator
The continue operator passes control to the beginning of
the nearest outward loop while, do-while or for operator,
the next iteration being called. The purpose of this
operator is opposite to that of break operator.
Example:
//--- Sum of all nonzero elements int func(int array[])
{
int array_size=ArraySize(array);
int sum=0;
for(int i=0;i<array_size; i++)
{
if(a[i]==0) continue;
sum+=a[i];
}
return(sum);
}
See also
Initialization of Variables, Visibility Scope and Lifetime of
Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Operators / Object Create Operator new
See also
Initialization of Variables, Visibility Scope and Lifetime
of Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Functions
Functions
Every task can be divided into subtasks, each of which can either be directly
represented in the form of a code, or divided into smaller sub-tasks. This method is
called stepwise refinement. Functions are used for writing the code of sub-tasks to
be solved. The code that describes what a function does is called function definition:
function_header {
instructions
}
All that is before the first brace is the header of the function definition, and what is
between braces is the body of the function definition. The function header includes a
description of the return value type, name (identifier) and formal parameters. The
number of parameters passed to the function is limited and cannot exceed 64.
The function can be called from other parts of the program as many times as
necessary. In fact, the return type, function identifier and parameter types
constitute the function prototype.
Function prototype is the function declaration, but not its definition. Due to the
explicit declaration of the return type and a list of argument types, the strict type
checking and implicit typecasting are possible during function calls. Very often
function declarations are used in classes to improve the code readability.
The function definition must exactly match its declaration. Each declared function
must be defined.
Example:
double // return value type
linfunc (double a, double b) // function name and parameter list
{
// composite operator
return (a + b); // return value
}
The return operator can return the value of an expression located in this operator. If
necessary, the expression value is converted to the function result type. What can be
returned: simple types, simple structures, object pointers. With the return operator
you can't return any arrays, class objects, variables of compound structure type.
A function that returns no value should be described as that of void type.
Example:
void errmesg(string s)
{
Print("error: "+s);
}
Parameters passed to the function can have default values, which are defined by
constants of that type.
Example:
int somefunc(double a,
double d=0.0001,
int n=5,
bool b=true,
string s="passed string")
{
Print("Required parameter a = ",a);
Print("Pass the following parameters: d = ",d," n = ",n," b = ",b," s = ",s);
return(0);
}
If any of parameters has a default value, all subsequent parameters must also have
default values.
Example of incorrect declaration:
int somefunc(double a,
double d=0.0001, // default value 0.0001 declared
int n, // default value is not specified !
bool b, // default value is not specified !
string s="passed string")
{
}
See also
Overload, Virtual Functions, Polymorphism
MQL4 Reference / Language Basics / Functions / Function Call
Function Call
If a name that has not been described before, appears in the expression and is followed
by the left parenthesis, it is contextually considered as the name of a function.
function_name (x1, x2,..., xn)
Arguments (formal parameters) are passed by value, i.e. each expression x1,..., xn is
calculated, and the value is passed to the function. The order of expressions calculation
and the order of values loading are not guaranteed. During the execution, the system
checks the number and type of arguments passed to the function. Such way of
addressing to the function is called a value call.
Function call is an expression, the value of which is the value returned by the function.
The function type described above must correspond with the type of the return value.
The function can be declared or described in any part of the program on the global
scope, i.e., outside other functions. The function cannot be declared or described inside
of another function.
Examples:
int start() {
double some_array[4]={0.3, 1.4, 2.5, 3.6};
double a=linfunc(some_array, 10.5, 8);
//...
}
double linfunc(double x[], double a, double b)
{
return (a*x[0] + b);
}
At calling of a function with default parameters, the list of parameters to be passed can
be limited, but not before the first default parameter.
Examples:
void somefunc(double init,
double sec=0.0001, //set default values
int level=10);
//...
somefunc(); // Wrong call. The first parameter must be presented
somefunc(3.14); // Correct call
somefunc(3.14,0.0002); // Correct call
somefunc(3.14,0.0002,10); // Correct call
When calling a function, one may not skip parameters, even those having default values:
somefunc(3.14, , 10); // Wrong call -> the second parameter was skipped.
Use of several functions of the same name from different execution contexts in a
program may cause ambiguity. To avoid the ambiguity of function calls, always explicitly
specify the function scope using scope resolution operation.
See also
Overload, Virtual Functions, Polymorphism
MQL4 Reference / Language Basics / Functions / Passing Parameters
Passing Parameters
There are two methods, by which the machine language can pass arguments to a
subprogram (function). The first method is to send a parameter by value. This method
copies the argument value into a formal function parameter. Therefore, any changes in
this parameter within the function have no influence on the corresponding call
argument.
//+------------------------------------------------------------------+ //| Passing par
//+------------------------------------------------------------------+
double FirstMethod(int i,int j)
{
double res;
//---
i*=2;
j/=2;
res=i+j;
//---
return(res);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int a=14,b=8;
Print("a and b before call:",a," ",b);
double d=FirstMethod(a,b);
Print("a and b after call:",a," ",b);
}
//--- Result of script execution
// a and b before call: 14 8
// a and b after call: 14 8
The second method is to pass by reference. In this case, reference to a parameter (not
its value) is passed to a function parameter. Inside the function, it is used to refer to the
actual parameter specified in the call. This means that the parameter changes will
affect the argument used to call the function.
//+------------------------------------------------------------------+
//| Passing parameters by reference |
//+------------------------------------------------------------------+
double SecondMethod(int &i,int &j)
{
double res;
//---
i*=2;
j/=2;
res=i+j;
//---
return(res);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int a=14,b=8;
Print("a and b before call:",a," ",b);
double d=SecondMethod(a,b);
Print("a and b after call:",a," ",b);
}
//+------------------------------------------------------------------+
//--- result of script execution
// a and b before call: 14 8
// a and b after call: 28 4
MQL4 uses both methods, with one exception: arrays, structure type variables and class
objects are always passed by reference. In order to avoid changes in actual parameters
(arguments passed at function call) use the access specifier const. When trying to
change the contents of a variable declared with the const specifier, the compiler will
generate an error.
Note
It should be noted that parameters are passed to a function in reversed order, i.e., first
the last parameter is calculated and passed, and then the last but one, etc. The last
calculated and passed parameter is the one that stands first after opening parenthesis.
Example:
void OnStart()
{
//---
int a[]={0,1,2};
int i=0;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void func(int par1,int par2,string comment)
{
Print(comment,": par1 = ",par1," par2 = ",par2);
}
In first call (see example above) the i variable is first used in strings concatenation:
"First call (i = "+string(i)+")"
Here its value doesn't change. Then the i variable is used in calculation of the a[i++]
array element, i.e. when array element with index i is accessed, the i variable is
incremented. And only after that the first parameter with changed value of i variable is
calculated.
In the second call the same value of i (calculated on the first phase of function calling) is
used when calculating all three parameters. Only after the first parameters is calculated
the i variable is changed again.
See also
Visibility Scope and Lifetime of Variables, Overload, Virtual Functions, Polymorphism
MQL4 Reference / Language Basics / Functions / Function Overloading
Function Overloading
Usually the function name tends to reflect its main purpose. As a rule, readable
programs contain various well selected identifiers. Sometimes different functions are
used for the same purposes. Let's consider, for example, a function that calculates the
average value of an array of double precision numbers and the same function, but
operating with an array of integers. Both are convenient to be called AverageFromArray:
//+------------------------------------------------------------------+ //| The calcula
//+------------------------------------------------------------------+
double AverageFromArray(const double & array[],int size)
{
if(size<=0) return 0.0;
double sum=0.0;
double aver;
//---
for(int i=0;i<size;i++)
{
sum+=array[i]; // Summation for the double
}
aver=sum/size; // Just divide the sum by the number
//---
Print("Calculation of the average for an array of double type");
return aver;
}
//+------------------------------------------------------------------+
//| The calculation of average for an array of int type |
//+------------------------------------------------------------------+
double AverageFromArray(const int & array[],int size)
{
if(size<=0) return 0.0;
double aver=0.0;
int sum=0;
//---
for(int i=0;i<size;i++)
{
sum+=array[i]; // Summation for the int
}
aver=(double)sum/size;// Give the amount of type double, and divide
//---
Print("Calculation of the average for an array of int type");
return aver;
}
Each function contains the message output via the Print() function;
Print("Calculation of the average for an array of int type");
The compiler selects a necessary function in accordance with the types of arguments and
their quantity. The rule, according to which the choice is made, is called the signature
matching algorithm. A signature is a list of types used in the function declaration.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int a[5]={1,2,3,4,5};
double b[5]={1.1,2.2,3.3,4.4,5.5};
double int_aver=AverageFromArray(a,5);
double double_aver=AverageFromArray(b,5);
Print("int_aver = ",int_aver," double_aver = ",double_aver);
}
//--- Result of the script
// Calculate the average for an array of int type
// Calculate the average for an array of double type
// int_aver= 3.00000000 double_aver= 3.30000000
Function overloading is a process of creating several functions with the same name, but
different parameters. This means that in overloaded variants of a function, the number
of arguments and/or their type must be different. A specific function variant is selected
based on the correspondence of the list of arguments when calling the function, to the
list of parameters in the function declaration.
When an overloaded function is called, the compiler must have an algorithm to select
the appropriate function. The algorithm that performs this choice depends on castings of
what types are present. The best correspondence must be unique. An overloaded
function must be the best match among all the other variants for at least one argument.
At the same time it must match for all other arguments not worse than other variants.
Below is a matching algorithm for each argument.
See also
Overload, Virtual Functions, Polymorphism
MQL4 Reference / Language Basics / Functions / Operation Overloading
Operation Overloading
For ease of code reading and writing, overloading of some operations is allowed.
Overloading operator is written using the keyword operator. The following operators can
be overloaded:
binary +,-,/,*,%,<<,>>,==,!=,<,>,<=,>=,=,+=,-=,/=,*=,%=,&=,|=,^=,
<<=,>>=,&&,||,&,|,^
unary +,-,++,--,!,~
assignment operator =
indexing operator []
Operation overloading allows the use of the operating notation (written in the form of
simple expressions) for complex objects - structures and classes. Writing expressions
using overloaded operations simplifies the view of the source code, because a more
complex implementation is hidden.
For example, consider complex numbers, which consist of real and imaginary parts. They
are widely used in mathematics. The MQL4 language has no data type to represent
complex numbers, but it is possible to create a new data type in the form of a structure
or class. Declare the complex structure and define four methods that implement four
arithmetic operations:
//+------------------------------------------------------------------+ //| A structure
//+------------------------------------------------------------------+
struct complex
{
double re; // Real part
double im; // Imaginary part
//--- Constructors
complex():re(0.0),im(0.0) { }
complex(const double r):re(r),im(0.0) { }
complex(const double r,const double i):re(r),im(i) { }
complex(const complex &o):re(o.re),im(o.im) { }
//--- Arithmetic operations
complex Add(const complex &l,const complex &r) const; // Addition
complex Sub(const complex &l,const complex &r) const; // Subtraction
complex Mul(const complex &l,const complex &r) const; // Multiplication
complex Div(const complex &l,const complex &r) const; // Division
};
Now, in our code we can declare variables representing complex numbers, and work with
them.
For example:
void OnStart()
{
//--- Declare and initialize variables of a complex type
complex a(2,4),b(-4,-2);
PrintFormat("a=%.2f+i*%.2f, b=%.2f+i*%.2f",a.re,a.im,b.re,b.im);
//--- Sum up two numbers
complex z;
z=a.Add(a,b);
PrintFormat("a+b=%.2f+i*%.2f",z.re,z.im);
//--- Multiply two numbers
z=a.Mul(a,b);
PrintFormat("a*b=%.2f+i*%.2f",z.re,z.im);
//--- Divide two numbers
z=a.Div(a,b);
PrintFormat("a/b=%.2f+i*%.2f",z.re,z.im);
//---
}
But it would be more convenient to use usual operators "+", "-", "*" and "/" for ordinary
arithmetic operations with complex numbers.
Keyword operator is used for defining a member function that performs type conversion.
Unary and binary operations for class object variables can be overloaded as non-static
member functions. They implicitly act on the class object.
Most binary operations can be overloaded like regular functions that take one or both
arguments as a class variable or a pointer to an object of this class. For our type
complex, overloading in the declaration will look like this:
//--- Operators
complex operator+(const complex &r) const { return(Add(this,r)); }
complex operator-(const complex &r) const { return(Sub(this,r)); }
complex operator*(const complex &r) const { return(Mul(this,r)); }
complex operator/(const complex &r) const { return(Div(this,r)); }
z=a*b;
PrintFormat("a*b=%.2f+i*%.2f",z.re,z.im);
//--- Divide two numbers
z=a/b;
PrintFormat("a/b=%.2f+i*%.2f",z.re,z.im);
//---
}
//+------------------------------------------------------------------+
//| A structure for operations with complex numbers |
//+------------------------------------------------------------------+
struct complex
{
double re; // Real part
double im; // Imaginary part
//--- Constructors
complex():re(0.0),im(0.0) { }
complex(const double r):re(r),im(0.0) { }
complex(const double r,const double i):re(r),im(i) { }
complex(const complex &o):re(o.re),im(o.im) { }
//--- Arithmetic operations
complex Add(const complex &l,const complex &r) const; // Addition
complex Sub(const complex &l,const complex &r) const; // Subtraction
complex Mul(const complex &l,const complex &r) const; // Multiplication
complex Div(const complex &l,const complex &r) const; // Division
//--- Binary operators
complex operator+(const complex &r) const { return(Add(this,r)); }
complex operator-(const complex &r) const { return(Sub(this,r)); }
complex operator*(const complex &r) const { return(Mul(this,r)); }
complex operator/(const complex &r) const { return(Div(this,r)); }
};
//+------------------------------------------------------------------+
//| Addition |
//+------------------------------------------------------------------+
complex complex::Add(const complex &l,const complex &r) const
{
complex res;
//---
res.re=l.re+r.re;
res.im=l.im+r.im;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Subtraction |
//+------------------------------------------------------------------+
complex complex::Sub(const complex &l,const complex &r) const
{
complex res;
//---
res.re=l.re-r.re;
res.im=l.im-r.im;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Multiplication |
//+------------------------------------------------------------------+
complex complex::Mul(const complex &l,const complex &r) const
{
complex res;
//---
res.re=l.re*r.re-l.im*r.im;
res.im=l.re*r.im+l.im*r.re;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Division |
//+------------------------------------------------------------------+
complex complex::Div(const complex &l,const complex &r) const
{
//--- Empty complex number
complex res(EMPTY_VALUE,EMPTY_VALUE);
//--- Check for zero
if(r.re==0 && r.im==0)
{
Print(__FUNCTION__+": number is zero");
return(res);
}
//--- Auxiliary variables
double e;
double f;
//--- Selecting calculation variant
if(MathAbs(r.im)<MathAbs(r.re))
{
e = r.im/r.re;
f = r.re+r.im*e;
res.re=(l.re+l.im*e)/f;
res.im=(l.im-l.re*e)/f;
}
else
{
e = r.re/r.im;
f = r.im+r.re*e;
res.re=(l.im+l.re*e)/f;
res.im=(-l.re+l.im*e)/f;
}
//--- Result
return res;
}
Most unary operations for classes can be overloaded as ordinary functions that accept a
single class object argument or a pointer to it. Add overloading of unary operations "-"
and "!".
//+------------------------------------------------------------------+
//| Structure for operations with complex numbers |
//+------------------------------------------------------------------+
struct complex
{
double re; // Real part
double im; // Imaginary part
...
//--- Unary operators
complex operator-() const; // Unary minus
bool operator!() const; // Negation
};
...
//+------------------------------------------------------------------+
//| Overloading the "unary minus" operator |
//+------------------------------------------------------------------+
complex complex::operator-() const
{
complex res;
//---
res.re=-re;
res.im=-im;
//--- Result
return res;
}
//+------------------------------------------------------------------+
//| Overloading the "logical negation" operator |
//+------------------------------------------------------------------+
bool complex::operator!() const
{
//--- Are the real and imaginary parts of the complex number equal to zero?
return (re!=0 && im!=0);
}
Now we can check the value of a complex number for zero and get a negative value:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Declare and initialize variables of type complex
complex a(2,4),b(-4,-2);
PrintFormat("a=%.2f+i*%.2f, b=%.2f+i*%.2f",a.re,a.im,b.re,b.im);
//--- Divide the two numbers
complex z=a/b;
PrintFormat("a/b=%.2f+i*%.2f",z.re,z.im);
//--- A complex number is equal to zero by default (in the default constructor re==0
complex zero;
Print("!zero=",!zero);
//--- Assign a negative value
zero=-z;
PrintFormat("z=%.2f+i*%.2f, zero=%.2f+i*%.2f",z.re,z.im, zero.re,zero.im);
PrintFormat("-zero=%.2f+i*%.2f",-zero.re,-zero.im);
//--- Check for zero once again
Print("!zero=",!zero);
//---
}
Note that we did not have to overload the assignment operator "=", as structures of
simple types can be directly copied one into each other. Thus, we can now write a code
for calculations involving complex numbers in the usual manner.
Overloading of the indexing operator allows to obtain the values of the arrays enclosed
in an object, in a simple and familiar way, and it also contributes to a better readability
of the source code. For example, we need to provide access to a symbol in the string at
the specified position. A string in MQL4 is a separate type string, which is not an array of
symbols, but with the help of an overloaded indexing operation we can provide a simple
and transparent work in the generated CString class:
//+------------------------------------------------------------------+
//| Class to access symbols in string as in array of symbols |
//+------------------------------------------------------------------+
class CString
{
string m_string;
public:
CString(string str=NULL):m_string(str) { }
ushort operator[] (int x) { return(StringGetCharacter(m_string,x)); }
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- An array for receiving symbols from a string
int x[]={ 19,4,18,19,27,14,15,4,17,0,19,14,17,27,26,28,27,5,14,
17,27,2,11,0,18,18,27,29,30,19,17,8,13,6 };
CString str("abcdefghijklmnopqrstuvwxyz[ ]CS");
string res;
//--- Make up a phrase using symbols from the str variable
for(int i=0,n=ArraySize(x);i<n;i++)
{
res+=ShortToString(str[x[i]]);
}
//--- Show the result
Print(res);
}
Another example of overloading of the indexing operation is operations with matrices.
The matrix represents a two-dimensional dynamic array, the array size is not defined in
advance. Therefore, you cannot declare an array of form array[][] without specifying the
size of the second dimension, and then pass this array as a parameter. A possible solution
is a special class CMatrix, which contains an array of CRow class objects.
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Operations of addition and multiplication of matrices
CMatrix A(3),B(3),C();
//--- Prepare an array for rows
double a1[3]={1,2,3}, a2[3]={2,3,1}, a3[3]={3,1,2};
double b1[3]={3,2,1}, b2[3]={1,3,2}, b3[3]={2,1,3};
//--- Fill the matrices
A[0]=a1; A[1]=a2; A[2]=a3;
B[0]=b1; B[1]=b2; B[2]=b3;
//--- Output the matrices in the Experts log
Print("---- Elements of matrix A");
Print(A.String());
Print("---- Elements of matrix B");
Print(B.String());
//--- Now we show how to get values in the style of dynamic arrays matrix[i][j]
Print("Output the values of matrix C elementwise");
//--- Go through the matrix rows - CRow objects - in a loop
for(int i=0;i<3;i++)
{
string com="| ";
//--- Form rows from the matrix for the value
for(int j=0;j<3;j++)
{
//--- Get the matrix element by the number of the row and column
double element=C[i][j];// [i] - Access to CRow in the array m_rows[] ,
// [j] - Overloaded operator of indexing in CRow
com=com+StringFormat("a(%d,%d)=%G ; ",i,j,element);
}
com+="|";
//--- Output the values of the row
Print(com);
}
}
//+------------------------------------------------------------------+
//| Class "Row" |
//+------------------------------------------------------------------+
class CRow
{
private:
double m_array[];
public:
//--- Constructors and a destructor
CRow(void) { ArrayResize(m_array,0); }
CRow(const CRow &r) { this=r; }
CRow(const double &array[]);
~CRow(void){};
//--- Number of elements in the row
int Size(void) const { return(ArraySize(m_array));}
//--- Returns a string with values
string String(void) const;
//--- Indexing operator
double operator[](int i) const { return(m_array[i]); }
//--- Assignment operators
void operator=(const double &array[]); // An array
void operator=(const CRow & r); // Another CRow object
double operator*(const CRow &o); // CRow object for multiplica
};
//+------------------------------------------------------------------+
//| Constructor for initializing a row with an array |
//+------------------------------------------------------------------+
void CRow::CRow(const double &array[])
{
int size=ArraySize(array);
//--- If the array is not empty
if(size>0)
{
ArrayResize(m_array,size);
//--- Fill with values
for(int i=0;i<size;i++)
m_array[i]=array[i];
}
//---
}
//+------------------------------------------------------------------+
//| Assignment operation for the array |
//+------------------------------------------------------------------+
void CRow::operator=(const double &array[])
{
int size=ArraySize(array);
if(size==0) return;
//--- Fill the array with values
ArrayResize(m_array,size);
for(int i=0;i<size;i++) m_array[i]=array[i];
//---
}
//+------------------------------------------------------------------+
//| Assignment operation for CRow |
//+------------------------------------------------------------------+
void CRow::operator=(const CRow &r)
{
int size=r.Size();
if(size==0) return;
//--- Fill the array with values
ArrayResize(m_array,size);
for(int i=0;i<size;i++) m_array[i]=r[i];
//---
}
//+------------------------------------------------------------------+
//| Operator of multiplication by another row |
//+------------------------------------------------------------------+
double CRow::operator*(const CRow &o)
{
double res=0;
//--- Verifications
int size=Size();
if(size!=o.Size() || size==0)
{
Print(__FUNCSIG__,": Failed to multiply two matrices, their sizes are different
return(res);
}
//--- Multiply arrays elementwise and add the products
for(int i=0;i<size;i++)
res+=m_array[i]*o[i];
//--- Result
return(res);
}
//+------------------------------------------------------------------+
//| Returns a formatted string representation |
//+------------------------------------------------------------------+
string CRow::String(void) const
{
string out="";
//--- If the size of the array is greater than zero
int size=ArraySize(m_array);
//--- We work only with a non-zero number of array elements
if(size>0)
{
out="{";
for(int i=0;i<size;i++)
{
//--- Collect the values to a string
out+=StringFormat(" %G;",m_array[i]);
}
out+=" }";
}
//--- Result
return(out);
}
//+------------------------------------------------------------------+
//| Class "Matrix" |
//+------------------------------------------------------------------+
class CMatrix
{
private:
CRow m_rows[];
public:
//--- Constructors and a destructor
CMatrix(void);
CMatrix(int rows) { ArrayResize(m_rows,rows); }
~CMatrix(void){};
//--- Get the matrix sizes
int Rows() const { return(ArraySize(m_rows)); }
int Cols() const { return(Rows()>0? m_rows[0].Size():0); }
//--- Returns the value of the column in the form of a CRow row
CRow GetColumnAsRow(const int col_index) const;
//--- Returns a string with the matrix values
string String(void) const;
//--- The indexing operator returns a string by its number
CRow *operator[](int i) const { return(GetPointer(m_rows[i])); }
//--- Addition operator
CMatrix operator+(const CMatrix &m);
//--- Multiplication operator
CMatrix operator*(const CMatrix &m);
//--- Assignment operator
CMatrix *operator=(const CMatrix &m);
};
//+------------------------------------------------------------------+
//| Default constructor, create and array of rows of zero size |
//+------------------------------------------------------------------+
CMatrix::CMatrix(void)
{
//--- The zero number of rows in the matrix
ArrayResize(m_rows,0);
//---
}
//+------------------------------------------------------------------+
//| Returns the column value in the form of CRow |
//+------------------------------------------------------------------+
CRow CMatrix::GetColumnAsRow(const int col_index) const
{
//--- A variable to get the values from the column
CRow row();
//--- The number of rows in the matrix
int rows=Rows();
//--- If the number of rows is greater than zero, execute the operation
if(rows>0)
{
//--- An array to receive the values of the column with index col_index
double array[];
ArrayResize(array,rows);
//--- Filling the array
for(int i=0;i<rows;i++)
{
//--- Check the number of the column for row i - it may exceed the boundarie
if(col_index>=this[i].Size())
{
Print(__FUNCSIG__,": Error! Column number ",col_index,"> row size ",i);
break; // row will be uninitialized object
}
array[i]=this[i][col_index];
}
//--- Create a CRow row based on the array values
row=array;
}
//--- Result
return(row);
}
//+------------------------------------------------------------------+
//| Addition of two matrices |
//+------------------------------------------------------------------+
CMatrix CMatrix::operator+(const CMatrix &m)
{
//--- The number of rows and columns in the passed matrix
int cols=m.Cols();
int rows=m.Rows();
//--- The matrix to receive the addition results
CMatrix res(rows);
//--- The sizes of the matrix must match
if(cols!=Cols() || rows!=Rows())
{
//--- Addition impossible
Print(__FUNCSIG__,": Failed to add two matrices, their sizes are different");
return(res);
}
//--- Auxiliary array
double arr[];
ArrayResize(arr,cols);
//--- Go through rows to add
for(int i=0;i<rows;i++)
{
//--- Write the results of addition of matrix strings in the array
for(int k=0;k<cols;k++)
{
arr[k]=this[i][k]+m[i][k];
}
//--- Place the array to the matrix row
res[i]=arr;
}
//--- return the result of addition of matrices
return(res);
}
//+------------------------------------------------------------------+
//| Multiplication of two matrices |
//+------------------------------------------------------------------+
CMatrix CMatrix::operator*(const CMatrix &m)
{
//--- Number of columns of the first matrix, number of rows passed in the matrix
int cols1=Cols();
int rows2=m.Rows();
int rows1=Rows();
int cols2=m.Cols();
//--- Matrix to receive the addition result
CMatrix res(rows1);
//--- Matrices should be coordinated
if(cols1!=rows2)
{
//--- Multiplication impossible
Print(__FUNCSIG__,": Failed to multiply two matrices, format is not compatible
"- number of columns in the first factor should be equal to the number of
return(res);
}
//--- Auxiliary array
double arr[];
ArrayResize(arr,cols1);
//--- Fill the rows in the multiplication matrix
for(int i=0;i<rows1;i++)// Go through rows
{
//--- Reset the receiving array
ArrayInitialize(arr,0);
//--- Go through elements in the row
for(int k=0;k<cols1;k++)
{
//--- Take values of column k of the matrix m in the for of CRow
CRow column=m.GetColumnAsRow(k);
//--- Multiply two rows and write the result of scalar multiplication of vec
arr[k]=this[i]*column;
}
//--- place array arr[] in the i-th row of the matrix
res[i]=arr;
}
//--- Return the product of two matrices
return(res);
}
//+------------------------------------------------------------------+
//| Assignment operation |
//+------------------------------------------------------------------+
CMatrix *CMatrix::operator=(const CMatrix &m)
{
//--- Find and set the number of rows
int rows=m.Rows();
ArrayResize(m_rows,rows);
//--- Fill our rows with the values of rows of the passed matrix
for(int i=0;i<rows;i++) this[i]=m[i];
//---
return(GetPointer(this));
}
//+------------------------------------------------------------------+
//| String representation of the matrix |
//+------------------------------------------------------------------+
string CMatrix::String(void) const
{
string out="";
int rows=Rows();
//--- Form string by string
for(int i=0;i<rows;i++)
{
out=out+this[i].String()+"\r\n";
}
//--- Result
return(out);
}
See also
Overloading, Arithmetic Operations, Function Overloading, Precedence Rules
MQL4 Reference / Language Basics / Functions / Description of External Functions
With the help of import, it is easy to describe functions that are called from external
DLL or compiled EX4 libraries. EX4 libraries are compiled ex4 files, which have the
library property. Only function described with the export modifier can be imported from
EX4 libraries.
Please keep in mind that DLL and EX4 libraries should have different names (regardless
of the directories they are located in) if they are imported together. All imported
functions have the scope resolution corresponding to the library's "file name".
Use of several functions of the same name from different execution contexts in a
program may cause ambiguity. To avoid the ambiguity of function calls, always explicitly
specify the function scope using the scope resolution operation.
Example:
#import "kernel32.dll"
int GetLastError();
#import "lib.ex4"
int GetLastError();
#import
class CFoo
{
public:
int GetLastError() { return(12345); }
void func()
{
Print(GetLastError()); // call of the class method
Print(::GetLastError()); // call of the MQL5 function
Print(kernel32::GetLastError()); // call of the DLL library function from kerne
Print(lib::GetLastError()); // call of the EX4 library function from lib.e
}
};
void OnStart()
{
CFoo foo;
foo.func();
}
See also
Overload, Virtual Functions, Polymorphism
MQL4 Reference / Language Basics / Functions / Exporting Functions
Exporting Functions
A function declared in a mql4 program with the export
postmodifier can be used in another mql4 program. Such a
function is called exportable, and it can be called from
other programs after compilation.
int Function() export {
}
For the OnStart() function, the int return type can be specified.
OnInit
The OnInit() function is the Init event handler. It must be of void or int type, with no
parameters:
void OnInit();
The OnInit() function of the void type always denotes successful initialization.
OnDeinit
The OnDeinit() function is called during deinitialization and is the Deinit event handler. It
must be declared as the void type and should have one parameter of the const int type,
which contains the code of deinitialization reason. If a different type is declared, the
compiler will generate a warning, but the function will not be called.
void OnDeinit(const int reason);
The Deinit event is generated for Expert Advisors and indicators in the following cases:
before reinitialization due to the change of a symbol or chart period, to which the
mql4 program is attached;
before reinitialization due to the change of input parameters;
before unloading the mql4 program.
OnTick
The NewTick event is generated for Expert Advisors only when a new tick for a symbol
is received, to the chart of which the Expert Advisor is attached. It's useless to define
the OnTick() function in a custom indicator or script, because the NewTick event is not
generated for them.
The Tick event is generated only for Expert Advisors, but this does not mean that Expert
Advisors required the OnTick() function, since not only NewTick events are generated for
Expert Advisors, but also events of Timer, BookEvent and ChartEvent are generated. It
must be declared as the void type, with no parameters:
void OnTick();
OnTimer
The OnTimer() function is called when the Timer event occurs, which is generated by the
system timer only for Expert Advisors and indicators - it can't be used in scripts. The
frequency of the event occurrence is set when subscribing to notifications about this
event to be received by the EventSetTimer() function.
You can unsubscribe from receiving timer events for a particular Expert Advisor using the
EventKillTimer() function. The function must be defined with the void type, with no
parameters:
void OnTimer();
The function is called right before the call of OnDeinit() and has the same type of the
return value - double. OnTester() can be used only in the testing of Expert Advisors. Its
main purpose is to calculate a certain value that is used as the Custom max criterion in
the genetic optimization of input parameters.
In the genetic optimization descending sorting is applied to results within one
generation. I.e. from the point of view of the optimization criterion, the best results are
those with largest values (for the Custom max optimization criterion values returned by
the OnTester function are taken into account). In such a sorting, the worst values are
positioned at the end and further thrown off and do not participate in the forming of the
next generation.
OnChartEvent
OnChartEvent() is the handler of a group of ChartEvent events:
CHARTEVENT_KEYDOWN event of a keystroke, when the chart window is focused;
CHARTEVENT_MOUSE_MOVE mouse move events and mouse click events (if
CHART_EVENT_MOUSE_MOVE=true is set for the chart);
CHARTEVENT_OBJECT_CREATE event of graphical object creation (if
CHART_EVENT_OBJECT_CREATE=true is set for the chart);
CHARTEVENT_OBJECT_CHANGE event of change of an object property via the
properties dialog;
CHARTEVENT_OBJECT_DELETE event of graphical object deletion (if
CHART_EVENT_OBJECT_DELETE=true is set for the chart);
CHARTEVENT_CLICK event of a mouse click on the chart;
CHARTEVENT_OBJECT_CLICK event of a mouse click in a graphical object belonging to
the chart;
CHARTEVENT_OBJECT_DRAG event of a graphical object move using the mouse;
CHARTEVENT_OBJECT_ENDEDIT event of the finished text editing in the entry box of
the LabelEdit graphical object;
CHARTEVENT_CHART_CHANGE event of chart changes;
CHARTEVENT_CUSTOM+n ID of the user event, where n is in the range from 0 to
65535.
CHARTEVENT_CUSTOM_LAST the last acceptable ID of a custom event
(CHARTEVENT_CUSTOM +65535).
The function can be called only in Expert Advisors and indicators. The function should be
of void type with 4 parameters:
void OnChartEvent(const int id, // Event ID const long& lpar
const double& dparam, // Parameter of type double event
const string& sparam // Parameter of type string events
);
For each type of event, the input parameters of the OnChartEvent() function have
definite values that are required for the processing of this event. The events and values
passed through these parameters are listed in the table below.
Event Value of the id parameter Value of the lparam Value
parameter dpara
Event of a keystroke CHARTEVENT_KEYDOWN code of a pressed Repea
key numb
the
repea
of the
down
Mouse events (if property CHARTEVENT_MOUSE_MOVE the X coordinate the Y
CHART_EVENT_MOUSE_MOVE=true is
set for the chart)
Parameters of open[], high[], low[] and close[] contain arrays with open prices, high and
low prices and close prices of the current time frame. The time[] parameter contains an
array with open time values, the spread[] parameter has an array containing the history
of spreads (if any spread is provided for the traded security). The parameters of
volume[] and tick_volume[] contain the history of trade and tick volume, respectively.
To determine the indexing direction of time[], open[], high[], low[], close[],
tick_volume[], volume[] and spread[], call ArrayGetAsSeries(). In order not to depend on
default values, you should unconditionally call the ArraySetAsSeries() function for those
arrays, which are expected to work with.
The first rates_total parameter contains the number of bars, available to the indicator
for calculation, and corresponds to the number of bars available in the chart.
We should note the connection between the return value of OnCalculate() and the
second input parameter prev_calculated. During the function call, the prev_calculated
parameter contains a value returned by OnCalculate() during previous call. This allows
for economical algorithms for calculating the custom indicator in order to avoid
repeated calculations for those bars that haven't changed since the previous run of this
function.
For this, it is usually enough to return the value of the rates_total parameter, which
contains the number of bars in the current function call. If since the last call of
OnCalculate() price data has changed (a deeper history downloaded or history blanks
filled), the value of the input parameter prev_calculated will be set to zero by the
terminal.
To understand it better, it would be useful to start the indicator, which code is attached
below.
Indicator Example:
#property indicator_chart_window
#property indicator_buffers 1
//---- plot Line
#property indicator_label1 "Line"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrDarkBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- indicator buffers
double LineBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,LineBuffer,INDICATOR_DATA);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime& time[],
const double& open[],
const double& high[],
const double& low[],
const double& close[],
const long& tick_volume[],
const long& volume[],
const int& spread[])
{
//--- Get the number of bars available for the current symbol and chart period
int bars=Bars(Symbol(),0);
Print("Bars = ",bars,", rates_total = ",rates_total,", prev_calculated = ",prev_c
Print("time[0] = ",time[0]," time[rates_total-1] = ",time[rates_total-1]);
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Running Programs, Client Terminal Events, Working with Events
MQL4 Reference / Language Basics / Variables
Variables
Declaring Variables
Variables must be declared before they are used. Unique names are used to
identify variables. To declare a variable, you must specify its type and a unique
name. Declaration of variable is not an operator.
Simple types are:
char, short, int, long, uchar, ushort, uint, ulong integers;
color integer representing the RGB-color;
datetime the date and time, an unsigned integer containing the number of
seconds since 0 hour January 1, 1970;
bool boolean values true and false;
double double-precision floating point number;
float single-precision floating point number;
string character strings.
Examples:
string szInfoBox; int nOrders;
double dSymbolPrice;
bool bLog;
datetime tBegin_Data = D'2004.01.01 00:00';
color cModify_Color = C'0x44,0xB9,0xE6';
You can't declare variables of the structure type until you declare the structure.
Arrays
Array is the indexed sequence of identical-type data:
int a[50]; // One-dimensional array of 50 integers.
double m[7][50]; // Two-dimensional array of seven arrays,
// each of them consisting of 50 numbers.
MyTime t[100]; // Array containing elements such as MyTime
Only an integer can be an array index. No more than four-dimensional arrays are
allowed. Numbering of array elements starts with 0. The last element of a one-
dimensional array has the number which is 1 less than the array size. This means
that call for the last element of an array consisting of 50 integers will appear as
a[49]. The same concerns multidimensional arrays: A dimension is indexed from 0
to the dimension size-1. The last element of a two-dimensional array from the
example will appear as m[6][49].
Static arrays can't be represented as timeseries, i.e., the ArraySetAsSeries()
function, which sets access to array elements from the end to beginning, can't be
applied to them. If you want to provide access to an array the same as in
timeseries, use the dynamic array object.
If there is an attempt to access out of the array range, the executing subsystem
will generate a critical error and the program will be stopped.
Access Specifiers
Access specifiers define how the compiler can access variables, members of
structures or classes.
The const specifier declares a variable as a constant, and does not allow to
change this variable during runtime. A single initialization of a variable is allowed
when declaring it.
Example:
int OnCalculate (const int rates_total, // size of input time series
const int prev_calculated, // bars handled in previous call
const datetime& time[], // Time
const double& open[], // Open
const double& high[], // High
const double& low[], // Low
const double& close[], // Close
const long& tick_volume[], // Tick Volume
const long& volume[], // Real Volume
const int& spread[] // Spread
);
Local Variables
A variable declared inside a function is local. The scope of
a local variable is limited to the function range inside
which it is declared. Local variable can be initialized by
outcome of any expression. Every call of the function
initializes a local variable. Local variables are stored in
memory area of the corresponding function.
Example:
int somefunc() {
int ret_code=0;
...
return(ret_code);
}
Stack
In every MQL4 program, a special memory area called
stack is allocated for storing local function variables that
are created automatically. One stack is allocated for all
functions. The default stack size is 256 kb, the stack size
can be managed using the #property stacksize compiler
directive.
Static local variables are stored in the same place where
other static and global variables are stored - in a special
memory area, which exists separately from the stack.
Dynamically created variables also use a memory area
separate from the stack.
With each function call, a place on the stack is allocated
for internal non-static variables. After exiting the function,
the memory is available for use again.
If from the first function the second one is called, then the
second function occupies the required size from the
remaining stack memory for its variables. Thus, when using
included functions, stack memory will be sequentially
occupied for each function. This may lead to a shortage of
memory during one of the function calls, such a situation is
called stack overflow.
Therefore, for large local data you should better use
dynamic memory - when entering a function, allocate the
memory, which is required for local needs, in the system
(new, ArrayResize()), and when exiting the function,
release the memory (delete, ArrayFree()).
See also
Data Types, Encapsulation and Extensibility of
Types,Initialization of Variables, Visibility Scope and
Lifetime of Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Variables / Formal Parameters
Formal Parameters
Parameters passed to the function are local. The scope is
the function block. Formal parameters must have names
differing from those of external variables and local
variables defined within one function. Some values can be
assigned to formal parameters in the function block. If a
formal parameter is declared with the const modifier, its
value can't be changed within the function.
Example:
void func(const int & x[], double y, bool z) {
if(y>0.0 && !z)
Print(x[0]);
...
}
Static Variables
The storage class of static defines a static variable. The static modifier is indicated
before the data type.
Example:
int somefunc() {
static int flag=10;
...
return(flag);
}
Global Variables
Global variables are created by placing their declarations
outside function descriptions. Global variables are defined
at the same level as functions, i.e., they are not local in
any block.
Example:
int GlobalFlag=10; // Global variable int OnStart()
{
...
}
Input Variables
The input storage class defines the external variable. The input modifier
is indicated before the data type. A variable with the input modifier can't
be changed inside mql4-programs, such variables can be accessed for
reading only. Values of input variables can be changed only by a user from
the program properties window. External variables are always
reinitialized immediately before the OnInit() is called.
Example:
//--- input parameters input int MA_Period=13;
input int MA_Shift=0;
input ENUM_MA_METHOD MA_Method=MODE_SMMA;
There is another way to set how your input parameter will look like in the
Inputs tab. For this, place a string comment after the description of an
input parameter in the same line. In this way you can make names of
input parameters more understandable for users.
Example:
//--- input parameters
input int InpMAPeriod=13; // Smoothing period
input int InpMAShift=0; // Line horizontal shift
input ENUM_MA_METHOD InpMAMethod=MODE_SMMA; // Smoothing method
Note: Arrays and variables of complex types can't act as input variables.
Note: The length of a string comment for Input variables cannot exceed
63 characters.
Passing Parameters When Calling Custom Indicators from
MQL4 Programs
Custom Indicators are called using the iCustom() function. After the name
of the custom indicator, parameters should go in a strict accordance with
the declaration of input variables of this custom indicator. If indicated
parameters are less than input variables declared in the called custom
indicator, the missing parameters are filled with values specified during
the declaration of variables.
If the custom indicator uses the OnCalculate function of the first type
(i.e., the indicator is calculated using the same array of data), then one
of ENUM_APPLIED_PRICE values or handle of another indicator should be
used as the last parameter when calling such a custom indicator. All
parameters corresponding to input variables must be clearly indicated.
Enumerations as input Parameters
Not only built-in enumerations provided in MQL4, but also user defined
variables can be used as input variables (input parameters for mql4
programs). For example, we can create the dayOfWeek enumeration,
describing days of the week, and use the input variable to specify a
particular day of the week, not as a number, but in a more common way.
Example:
#property script_show_inputs
//--- day of week
enum dayOfWeek
{
S=0, // Sunday
M=1, // Monday
T=2, // Tuesday
W=3, // Wednesday
Th=4, // Thursday
Fr=5, // Friday,
St=6, // Saturday
};
//--- input parameters
input dayOfWeek swapday=W;
Extern variables
The extern storage class defines the external variable. The extern modifier is
indicated before the data type.
//--- extern parameters extern int MA_Period=13;
extern int MA_Shift=0;
extern ENUM_MA_METHOD MA_Method=MODE_SMMA;
Strict compilation mode with the output of the input parameters window is set in
this script. Therefore, the values set in the string comments instead of ExtVar and
InpVar variable names are displayed in Variable field.
Note: Arrays and variables of complex types can't act as extern variables.
Note: The length of a string comment for extern variables cannot exceed 63
characters.
See also
Input Variables, Data Types, Encapsulation and Extensibility of Types, Initialization
of Variables, Visibility Scope and Lifetime of Variables, Creating and Deleting
Objects
MQL4 Reference / Language Basics / Variables / Initialization of Variables
Initialization of Variables
Any variable can be initialized during definition. If a variable is not initialized
explicitly, the value stored in this variable can be any. Implicit initialization is not
used.
Global and static variables can be initialized only by a constant of the
corresponding type or a constant expression. Local variables can be initialized by
any expression, not just a constant.
Initialization of global and static variables is performed only once. Initialization of
local variables is made every time you call the corresponding functions.
Examples:
int n = 1; string s = "hello";
double f[] = { 0.0, 0.236, 0.382, 0.5, 0.618, 1.0 };
int a[4][4] = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4 } };
//--- from tetris
int right[4]={WIDTH_IN_PIXELS+VERT_BORDER,WIDTH_IN_PIXELS+VERT_BORDER,
WIDTH_IN_PIXELS+VERT_BORDER,WIDTH_IN_PIXELS+VERT_BORDER};
//--- initialization of all fields of the structure with zero values
MqlTradeRequest request={0};
List of values of the array elements must be enclosed in curly brackets. Missed
initializing sequences are considered equal to 0. The initializing sequence must
have at least one value: this value is initialized to the first element of the
corresponding structure or array, missing elements are considered equal to zero.
If the size of the initialized array is not specified, it is determined by a compiler,
based on the size of the initialization sequence. Multi-dimensional arrays cannot
be initialized by a one-dimensional sequence (a sequence without additional curly
brackets), except for the case, when only one initializing element is specified
(zero, as a rule).
Arrays (including those announced at the local level) can be initialized only by
constants.
Examples:
struct str3
{
int low_part;
int high_part;
};
struct str10
{
str3 s3;
double d1[10];
int i3;
};
void OnStart()
{
str10 s10_1={{1,0},{1.0,2.1,3.2,4.4,5.3,6.1,7.8,8.7,9.2,10.0},100};
str10 s10_2={{1,0},{0},100};
str10 s10_3={{1,0},{1.0}};
//---
Print("1. s10_1.d1[5] = ",s10_1.d1[5]);
Print("2. s10_2.d1[5] = ",s10_2.d1[5]);
Print("3. s10_3.d1[5] = ",s10_3.d1[5]);
Print("4. s10_3.d1[0] = ",s10_3.d1[0]);
}
For structure type variable partial initialization is allowed, as well as for static
arrays (with an implicitly set size). You can initialize one or more first elements of
a structure or array, the other elements will be initialized with zeroes in this case.
See also
Data Types, Encapsulation and Extensibility of Types, Visibility Scope and
Lifetime of Variables, Creating and Deleting Objects
MQL4 Reference / Language Basics / Variables / Visibility Scope and Lifetime of Variables
for(i=limit;i<rates_total;i++)
{
sum=0;
for(int j=0; j<MA_Period; j++) sum+=(MA_Period-j)*price[i-j];
LineBuffer[i]=sum/weightsum;
}
//---
}
Pay attention to the variable i, declared in line
for(int i=begin; i<limit; i++)
{
int k=i-begin+1;
weightsum+=k;
firstValue+=k*price[i];
}
Its scope is only the for loop; outside of this loop there is another variable with the same
name, declared at the beginning of the function. In addition, the k variable is declared
in the loop body, its scope is the loop body.
Local variables can be declared with the access specifier static. In this case, the
compiler has a variable in the global pool of memory. Therefore, the lifetime of a static
variable is equal to the lifetime of the program. Here the scope of such a variable is
limited to the block in which it is declared.
See also
Data Types, Encapsulation and Extensibility of Types,Initialization of Variables, Creating
and Deleting Objects
MQL4 Reference / Language Basics / Variables / Creating and
Deleting Objects
See also
Data Types, Encapsulation and Extensibility of
Types,Initialization of Variables, Visibility Scope and
Lifetime of Variables
MQL4 Reference / Language Basics / Preprocessor
Preprocessor
Preprocessor is a special subsystem of the MQL4 compiler
that is intended for preparation of the program source
code immediately before the program is compiled.
Preprocessor allows enhancement of the source code
readability. The code can be structured by including of
specific files containing source codes of mql4-programs.
The possibility to assign mnemonic names to specific
constants contributes to enhancement of the code
readability.
Preprocessor also allows determining specific parameters
of mql4-programs:
Declare constants
Set program properties
Include files in program text
Import functions
Conditional compilation
If the # symbol is used as the first character in a line of
the program, this line is considered as a preprocessor
directive. A preprocessor directive ends with a line feed
character.
MQL4 Reference / Language Basics / Preprocessor / Macro substitution (#define)
The #define directive substitutes expression for all further found entries of identifier in
the source text. The identifier is replaced only if it is a separate token. The identifier is
not replaced if it is part of a comment, part of a string, or part of another longer
identifier.
The constant identifier is governed by the same rules as variable names. The value can
be of any type:
#define ABC 100
#define PI 3.14
#define COMPANY_NAME "MetaQuotes Software Corp."
...
void ShowCopyright()
{
Print("Copyright 2001-2013, ",COMPANY_NAME);
Print("https://www.metaquotes.net");
}
expression can consist of several tokens, such as keywords, constants, constant and non-
constant expressions. expression ends with the end of the line and can't be transferred
to the next line.
Example:
#define TWO 2
#define THREE 3
#define INCOMPLETE TWO+THREE
#define COMPLETE (TWO+THREE)
void OnStart()
{
Print("2 + 3*2 = ",INCOMPLETE*2);
Print("(2 + 3)*2 = ",COMPLETE*2);
}
// Result
// 2 + 3*2 = 8
// (2 + 3)*2 = 10
Parametric Form #define
With the parametric form, all the subsequent found entries of identifier will be replaced
by expression taking into account the actual parameters. For example:
// example with two parameters a and b
#define A 2+3
#define B 5-1
#define MUL(a, b) ((a)*(b))
double c=MUL(A,B);
Print("c=",c);
/*
expression double c=MUL(A,B);
is equivalent to double c=((2+3)*(5-1));
*/
// Result
// c=20
double c=MUL(A,B);
Print("c=",c);
/*
expression double c=MUL(A,B);
is equivalent to double c=2+3*5-1;
*/
// Result
// c=16
The #undef directive
The #undef directive cancels declaration of the macro substitution, defined before.
Example:
#define MACRO
void func1()
{
#ifdef MACRO
Print("MACRO is defined in ",__FUNCTION__);
#else
Print("MACRO is not defined in ",__FUNCTION__);
#endif
}
#undef MACRO
void func2()
{
#ifdef MACRO
Print("MACRO is defined in ",__FUNCTION__);
#else
Print("MACRO is not defined in ",__FUNCTION__);
#endif
}
void OnStart()
{
func1();
func2();
}
/* Result:
MACRO is defined in func1
MACRO is not defined in func2
*/
See also
Identifiers, Character Constants
MQL4 Reference / Language Basics / Preprocessor / Program Properties (#property)
The compiler will write declared values in the configuration of the module executed.
Constant Type Description
strict Compiler directive for strict compilation mode (see
Updated MQL4)
icon string Path to the file of an image that will be used as an icon of
the EX4 program. Path specification rules are the same as
for resources. The property must be specified in the main
module with the MQL4 source code. The icon file must be
in the ICO format.
link string Link to the company website
copyright string The company name
version string Program version, maximum 31 characters
description string Brief text description of a MQL4-program. Several
description can be present, each of them describes one
line of the text. The total length of all description can not
exceed 511 characters including line feed.
stacksize int MQL4 program stack size. The stack of sufficient size is
necessary when executing function recursive calls.
When launching a script or an Expert Advisor on the chart,
the stack of at least 8 MB is allocated. In case of
indicators, the stack size is always fixed and equal to 1
MB.
When a program is launched in the strategy tester, the
stack of 8 MB is always allocated for it.
library A library; no start function is assigned, functions with the
export modifier can be imported in other MQL4-programs
indicator_chart_window Show the indicator in the chart window
indicator_separate_window Show the indicator in a separate window
indicator_height int Fixed height of the indicator subwindow in pixels
(property INDICATOR_HEIGHT)
indicator_buffers int Number of buffers for indicator calculation
indicator_minimum double The bottom scaling limit for a separate indicator window
indicator_maximum double The top scaling limit for a separate indicator window
Constant Type Description
indicator_labelN string Sets a label for the N-th graphic series displayed in
DataWindow
indicator_colorN color The color for displaying line N, where N is the number of
graphic series; numbering starts from 1
indicator_widthN int Line thickness in graphic series, where N is the number of
graphic series; numbering starts from 1
indicator_styleN int Line style in graphic series, specified by the values of
ENUM_LINE_STYLE. N is the number of graphic series;
numbering starts from 1
indicator_typeN int Type of indicator drawing style. N is the number of
graphic series; numbering starts from 1
indicator_levelN double Horizontal level of N in a separate indicator window
indicator_levelcolor color Color of horizontal levels of the indicator
indicator_levelwidth int Thickness of horizontal levels of the indicator
indicator_levelstyle int Style of horizontal levels of the indicator
script_show_confirm Display a confirmation window before running the script
script_show_inputs Display a window with the properties before running the
script and disable this confirmation window
tester_file string File name from <terminal_data_folder>\MQL4\Files\ to be
sent to a virtual server
tester_indicator string Indicator file name from
<terminal_data_folder>\MQL4\Indicators\ to be sent to a
virtual server
tester_library string Library file name from
<terminal_data_folder>\MQL4\Libraries\ to be sent to a
virtual server
Examples:
#include <WinUser32.mqh>
#include "mylib.mqh"
Imported functions can have any names. Functions having the same names
but from different modules can be imported at the same time. Imported
functions can have names that coincide with the names of built-in functions.
Operation of scope resolution defines which of the functions should be
called.
The order of searching for a file specified after the #import keyword is
described in Call of Imported Functions.
Since the imported functions are outside the compiled module, the compiler
can not verify the validity of passed parameters. Therefore, to avoid run-
time errors, one must accurately describe the composition and order of
parameters passed to imported functions. Parameters passed to imported
functions (both from EX4, and from the DLL-module) can have default
values.
The following can't be used for parameters in imported functions:
pointers (*);
links to objects that contain dynamic arrays and/or pointers.
Classes, string arrays or complex objects that contain strings and/or dynamic
arrays of any types cannot be passed as a parameter to functions imported
from DLL.
Examples:
#import "user32.dll"
int MessageBoxW(uint hWnd,string lpText,string lpCaption,uint uType);
#import "stdlib.ex4"
string ErrorDescription(int error_code);
int RGB(int red_value,int green_value,int blue_value);
bool CompareDoubles(double number1,double number2);
string DoubleToStrMorePrecision(double number,int precision);
string IntegerToHexString(int integer_number);
#import "ExpertSample.dll"
int GetIntValue(int);
double GetDoubleValue(double);
string GetStringValue(string);
double GetArrayItemValue(double &arr[],int,int);
bool SetArrayItemValue(double &arr[],int,int,double);
double GetRatesItemValue(double &rates[][6],int,int,int);
#import
#ifndef identifier
// the code located here is compiled if identifier is not currently defined by #de
#endif
Any of the conditional compilation directives can be followed by any number of lines
possibly containing #else directive and ending with #endif. If the verified condition is
true, the lines between #else and #endif are ignored. If the verified condition is not
fulfilled, all lines between checking and #else directive (or #endif directive if the former
is absent) are ignored.
Example:
#ifndef TestMode
#define TestMode
#endif
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
#ifdef TestMode
Print("Test mode");
#else
Print("Normal mode");
#endif
}
Depending on the program type and compilation mode, the standard macros are defined
the following way:
__MQL4__ macro is defined when compiling *.mq4 file, __MQL5__ macro is defined
when compiling *.mq5 one.
_DEBUG macro is defined when compiling in debug mode.
_RELEASE macro is defined when compiling in release mode.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
#ifdef __MQL5__
#ifdef _DEBUG
Print("Hello from MQL5 compiler [DEBUG]");
#else
#ifdef _RELEASE
Print("Hello from MQL5 compiler [RELEASE]");
#endif
#endif
#else
#ifdef __MQL4__
#ifdef _DEBUG
Print("Hello from MQL4 compiler [DEBUG]");
#else
#ifdef _RELEASE
Print("Hello from MQL4 compiler [RELEASE]");
#endif
#endif
#endif
#endif
}
MQL4 Reference / Language Basics / Object-Oriented Programming
Object-Oriented Programming
Object-oriented programming (OOP) is programming
primarily focused on data, while data and behavior are
being inseparably linked. Data and behavior together
constitute a class, while objects are class instances.
The components of the object-oriented approach are:
Encapsulation and type extensibility
Inheritance
Polymorphism
Overloading
Virtual functions
OOP considers computation as modeling of behavior. The
modeled item is the object represented by computational
abstractions. Suppose we want to write a well known
game "Tetris". To do this, we must learn how to model the
appearance of random shapes composed of four squares
joined together by edges. Also we need to regulate the
falling speed of shapes, define operations of rotation and
shift of shapes. Moving of shapes on the screen is limited
by the well's boundaries, this requirement must also be
modeled. Besides that, filled rows of cubes must be
destroyed and achieved points must be counted.
Thus, this easy-to-understand game requires the creation
of several models - shape model, well model, shape
movement model and so on. All these models are
abstractions, represented by calculations in the computer.
To describe these models, the concept of Abstract Data
Type, ADT (or complex data type) is used. Strictly
speaking, the model of the "shapes" motion in the DOM is
not a data type, but it is a set of operations on the
"shape" data type, using the restrictions of the "well" data
type.
Objects are class variables. Object-oriented programming
allows you to easily create and use ADT. Object-oriented
programming uses the inheritance mechanism. The
benefit of inheritance is in the fact that it allows
obtaining derivative types from data types already
defined by a user.
For example, to create Tetris shapes, it's convenient to
create a base class Shape first. The other classes
representing all seven possible shape types can be derived
on its basis. Behavior of shapes is defined in the base
class, while implementation of behavior of each separate
shape is defined in derivative classes.
In OOP objects are responsible for their behavior. ADT
developer should include a code to describe any behavior
that would normally be expected from the corresponding
objects. The fact that the object itself is responsible for
its behavior, greatly simplifies the task of programming
for the user of this object.
If we want to draw a shape on the screen, we need to
know where the center will be and how to draw it. If a
separate shape knows how to draw itself, the programmer
should send a "draw" message when using such a shape.
The MQL4 Language is a C++ like, and it also has the
encapsulation mechanism for the implementation of ADT.
On the one hand encapsulation combines the internal
details of the implementation of a particular type, and on
the other hand it combines externally accessible functions
that can influence objects of this type. Implementation
details may be inaccessible for a program that uses this
type.
The concept of OOP has a set of related concepts,
including the following:
Simulation of actions from the real world
User-defined data types
Hiding the implementation details
Possibility of the code reuse through inheritance
Interpretation of function calls during execution
Some of these concepts are rather vague, some are
abstract, others are general.
MQL4 Reference / Language Basics / Object-Oriented Programming / Encapsulation and Extensibility of
Types
This approach offers several advantages. First, by function name we can understand
what it does - sets or gets the value of a class member. Secondly, perhaps in the
future we will need to change the type of the m_name variable in the CPerson class
or in any of its derivative classes.
In this case, we'll need just to change the implementation of functions SetName()
and GetName(), while objects of the CPerson class will be available for using in a
program without any code changes because the user will not even know that the
data type of m_name has changed.
Example:
struct Name
{
string first_name; // name
string last_name; // last name
};
class CPerson
{
protected:
Name m_name; // name
public:
void SetName(string n);
string GetName(){return(m_name.first_name+" "+m_name.last_name);}
private:
string GetFirstName(string full_name);
string GetLastName(string full_name);
};
void CPerson::SetName(string n)
{
m_name.first_name=GetFirstName(n);
m_name.last_name=GetLastName(n);
}
See also
Data Types
MQL4 Reference / Language Basics / Object-Oriented Programming / Inheritance
Inheritance
The characteristic feature of OOP is the encouragement of code reuse through
inheritance. A new class is made from the existing, which is called the base class. The
derived class uses the members of the base class, but can also modify and supplement
them.
Many types are variations of the existing types. It is often tedious to develop a new code
for each of them. In addition, the new code implies new errors. The derived class
inherits the description of the base class, thus any re-development and re-testing of
code is unnecessary. The inheritance relationships are hierarchical.
Hierarchy is a method that allows to copy the elements in all their diversity and
complexity. It introduces the objects classification. For example, the periodic table of
elements has gases. They possess to properties inherent to all periodic elements.
Inert gases constitute the next important subclass. The hierarchy is that the inert gas,
such as argon is a gas, and gas, in its turn, is part of the system. Such a hierarchy allows
to interpret behaviour of inert gases easily. We know that their atoms contain protons
and electrons, that is true for all other elements.
We know that they are in a gaseous state at room temperature, like all the gases. We
know that no gas from inert gas subclass enters usual chemical reaction with other
elements, and it is a property of all inert gases.
Consider an example of the inheritance of geometric shapes. To describe the whole
variety of simple shapes (circle, triangle, rectangle, square etc.), the best way is to
create a base class (ADT), which is the ancestor of all the derived classes.
Let's create a base class CShape, which contains just the most common members
describing the shape. These members describe properties that are characteristic of any
shape - the type of the shape and main anchor point coordinates.
Example:
//--- The base class Shape class CShape
{
protected:
int m_type; // Shape type
int m_xpos; // X - coordinate of the base point
int m_ypos; // Y - coordinate of the base point
public:
CShape(){m_type=0; m_xpos=0; m_ypos=0;} // constructor
void SetXPos(int x){m_xpos=x;} // set X
void SetYPos(int y){m_ypos=y;} // set Y
};
Next, create new classes derived from the base class, in which we will add necessary
fields, each specifying a certain class. For the Circle shape it is necessary to add a
member that contains the radius value. The Square shape is characterized by the side
value. Therefore, derived classes, inherited from the base class CShape will be declared
as follows:
//--- The derived class circle
class CCircle : public CShape // After a colon we define the base class
{ // from which inheritance is made
private:
int m_radius; // circle radius
public:
CCircle(){m_type=1;}// constructor, type 1
};
public:
CSquare(){m_type=2;} // constructor, type 2
};
It should be noted that while object is created the base class constructor is called first,
and then the constructor of the derived class is called. When an object is destroyed first
the destructor of the derived class is called, and then a base class destructor is called.
Thus, by declaring the most general members in the base class, we can add an additional
members in derived classes, which specify a particular class. Inheritance allows creating
powerful code libraries that can be reused many times.
The syntax for creating a derived class from an already existing one is as follows:
class class_name :
(public | protected | private) opt base_class_name
{
class members declaration
};
One of aspects of the derived class is the visibility (openness) of its members successors
(heirs). The public, protected and private keywords are used to indicate the extent, to
which members of the base class will be available for the derived one. The public
keyword after a colon in the header of a derived class indicates that the protected and
public members of the base class CShape should be inherited as protected and public
members of the derived class CCircle.
The private class members of the base class are not available for the derived class. The
public inheritance also means that derived classes (CCircle and CSquare) are CShapes.
That is, the Square (CSquare) is a shape (CShape), but the shape does not necessarily
have to be a square.
The derived class is a modification of the base class, it inherits the protected and public
members of the base class. The constructors and destructors of the base class cannot be
inherited. In addition to members of the base class, new members are added in a
derivative class.
The derived class may include the implementation of member functions, different from
the base class. It has nothing common with an overload, when the meaning of the same
function name may be different for different signatures.
In protected inheritance, public and protected members of base class become protected
members of derived class. In private inheritance, the public and protected members of
base class become private members of the derived class.
In protected and private inheritance, the relation that "the object of a derivative class is
object of a base class" is not true. The protected and private inheritance types are rare,
and each of them needs to be used carefully.
It should be understood that the type of inheritance (public, protected or private) does
not affect the ways of accessing the members of base classes in the hierarchy of
inheritance from a derived class. With any type of inheritance, only base class
members declared with public and protected access specifiers will be available out of
the derived classes. Let's consider it in the following example:
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//+------------------------------------------------------------------+
//| Example class with a few access types |
//+------------------------------------------------------------------+
class CBaseClass
{
private: //--- The private member is not available from derived classes
int m_member;
protected: //--- The protected method is available from the base class and
int Member(){return(m_member);}
public: //--- Class constructor is available to all members of classes
CBaseClass(){m_member=5;return;};
private: //--- A private method for assigning a value to m_member
void Member(int value) { m_member=value;};
};
//+------------------------------------------------------------------+
//| Derived class with errors |
//+------------------------------------------------------------------+
class CDerived: public CBaseClass // specification of public inheritance can be omitt
{
public:
void Func() // In the derived class, define a function with calls to base class me
{
//--- An attempt to modify a private member of the base class
m_member=0; // Error, the private member of the base class is not availa
Member(0); // Error, the private method of the base class is not availa
//--- Reading the member of the base class
Print(m_member); // Error, the private member of the base class is not availa
Print(Member()); // No error, protected method is available from the base cla
}
};
In the above example, CBaseClass has only a public method the constructor. Constructors
are called automatically when creating a class object. Therefore, the private member
m_member and the protected methods Member() cannot be called from the outside. But
in case of public inheritance, the Member() method of the base class will be available
from the derived classes.
In case of protected inheritance, all the members of the base class with public and
protected access become protected. It means that if public data members and methods
of the base class were accessible from the outside, with protected inheritance they are
available only from the classes of the derived class and its further derivatives.
//+------------------------------------------------------------------+
//| Example class with a few access types |
//+------------------------------------------------------------------+
class CBaseMathClass
{
private: //--- The private member is not available from derived classes
double m_Pi;
public: //--- Getting and setting a value for m_Pi
void SetPI(double v){m_Pi=v;return;};
double GetPI(){return m_Pi;};
public: // The class constructor is available to all members
CBaseMathClass() {SetPI(3.14); PrintFormat("%s",__FUNCTION__);}
};
//+------------------------------------------------------------------+
//| A derived class, in which m_Pi cannot be modified |
//+------------------------------------------------------------------+
class CProtectedChildClass: protected CBaseMathClass // Protected inheritance
{
private:
double m_radius;
public: //--- Public methods in the derived class
void SetRadius(double r){m_radius=r; return;};
double GetCircleLength(){return GetPI()*m_radius;};
};
//+------------------------------------------------------------------+
//| Script starting function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- When creating a derived class, the constructor of the base class will be called
CProtectedChildClass pt;
//--- Specify radius
pt.SetRadius(10);
PrintFormat("Length=%G",pt.GetCircleLength());
//--- If we uncomment the line below, we will get an error at the stage of compilatio
// pt.SetPI(3);
//--- Now declare a variable of the base class and try to set the Pi constant equal t
CBaseMathClass bc;
bc.SetPI(10);
//--- Here is the result
PrintFormat("bc.GetPI()=%G",bc.GetPI());
}
The example shows that methods SetPI() and GetPi() in the base class CBaseMathClass
are open and available for calling from any place of the program. But at the same time,
for CProtectedChildClass which is derived from it these methods can be called only from
the methods of the CProtectedChildClass class or its derived classes.
In case of private inheritance, all the members of the basic class with the public and
protected access become private, and calling them becomes impossible in further
inheritance.
MQL4 has no multiple inheritance.
See also
Structures and Classes
MQL4 Reference / Language Basics / Object-Oriented Programming / Polymorphism
Polymorphism
Polymorphism is an opportunity for different classes of objects, related through
inheritance, to respond in various ways when calling the same function element. It helps
to create a universal mechanism describing the behavior of not only the base class, but
also descendant classes.
Let's continue to develop a base class CShape, and define a member function GetArea(),
designed to calculate the area of a shape. In all the descendant classes, produced by
inheritance from the base class, we redefine this function in accordance with rules of
calculating the area of a particular shape.
For a square (class CSquare), the area is calculated through its sides, for a circle (class
CCircle), area is expressed through its radius etc. We can create an array to store
objects of CShape type, in which both objects of a base class and those of all descendant
classes can be stored. Further we can call the same function for each element of the
array.
Example:
//--- Base class class CShape
{
protected:
int m_type; // Shape type
int m_xpos; // X - coordinate of the base point
int m_ypos; // Y - coordinate of the base point
public:
void CShape(){m_type=0;}; // constructor, type=0
int GetType(){return(m_type);};// returns type of the shape
virtual
double GetArea(){return (0); }// returns area of the shape
};
Now, all of the derived classes have a member function getArea(), which returns a zero
value. The implementation of this function in each descendant will vary.
//--- The derived class Circle
class CCircle : public CShape // After a colon we define the base class
{ // from which inheritance is made
private:
double m_radius; // circle radius
public:
void CCircle(){m_type=1;}; // constructor, type=1
void SetRadius(double r){m_radius=r;};
virtual double GetArea(){return (3.14*m_radius*m_radius);}// circle area
};
public:
void CSquare(){m_type=2;}; // constructor, type=1
void SetSide(double s){m_square_side=s;};
virtual double GetArea(){return (m_square_side*m_square_side);}// square area
};
For calculating the area of the square and circle, we need the corresponding values of
m_radius and m_square_side, so we have added the functions SetRadius() and SetSide()
in the declaration of the corresponding class.
It is assumed that object of different types (CCircle and CSquare) derived from one base
type CShape are used in our program. Polymorphism allows creating an array of objects
of the base CShape class, but when declaring this array, these objects are yet unknown
and their type is undefined.
The decision on what type of object will be contained in each element of the array will
be taken directly during program execution. This involves the dynamic creation of
objects of the appropriate classes, and hence the necessity to use object pointers
instead of objects.
The new operator is used for dynamic creation of objects. Each such object must be
individually and explicitly deleted using the delete operator. Therefore we will declare
an array of pointers of CShape type, and create an object of a proper type for each
element (new Class_Name), as shown in the following script example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Declare an array of object pointers of the base type
CShape *shapes[5]; // An array of pointers to CShape object
//--- Create another CCircle object and write down its pointer in shapes[1]
circle=new CCircle();
shapes[1]=circle;
circle.SetRadius(5);
//--- Create a CSquare object and write down its pointer to shapes[3]
CSquare *square=new CSquare();
square.SetSide(5);
shapes[3]=square;
//--- Create a CSquare object and write down its pointer to shapes[4]
square=new CSquare();
square.SetSide(10);
shapes[4]=square;
Please note that when deleting an object using the delete operator, the type of its
pointer must be checked. Only objects with the POINTER_DYNAMIC pointer can be
deleted using delete. For pointers of other type, an error will be returned.
But besides the redefining of functions during inheritance, polymorphism also includes
the implementation of one and the same functions with different sets of parameters
within a class. This means that the class may have several functions with the same name
but with a different type and/or set of parameters. In this case, polymorphism is
implemented through the function overload.
MQL4 Reference / Language Basics / Object-Oriented Programming /
Overload
Overload
Within one class it is possible to define two or more
methods that use the same name, but have different
numbers of parameters. When this occurs, methods are
called overloaded and such a process is referred to as
method overloading.
Method overloading is one of ways of polymorphism
realization. Overloading of methods is performed
according to the same rules as the function overloading.
If the called function has no exact match, the compiler
searches for a suitable function on three levels
sequentially:
1. search within class methods.
2. search within the base class methods, consistently
from the nearest ancestor to the very first.
3. search among other functions.
If there is no exact correspondence at all levels, but
several suitable functions at different levels have been
found, the function found at the least level is used.
Within one level, there can't be more than one suitable
function.
See also
Function Overloading
MQL4 Reference / Language Basics / Object-Oriented Programming / Virtual Functions
Virtual Functions
The virtual keyword is the function specifier, which provides a mechanism to select
dynamically at runtime an appropriate function-member among the functions of basic
and derived classes. Structures cannot have virtual functions. It can be used to change
the declarations for function-members only.
The virtual function, like an ordinary function, must have an executable body. When
called, its semantic is the same as that of other functions.
A virtual function may be overridden in a derived class. The choice of what function
definition should be called for a virtual function is made dynamically (at runtime). A
typical case is when a base class contains a virtual function, and derived classes have
their own versions of this function.
The pointer to the base class can indicate either a base class object or the object of a
derived class. The choice of the member-function to call will be performed at runtime
and will depend on the type of the object, not the type of the pointer. If there is no
member of a derived type, the virtual function of the base class is used by default.
Destructors are always virtual, regardless of whether they are declared with the virtual
keyword or not.
Attention: it is not recommended to call virtual methods from constructors and
desctructors, because the result is undefined in this case.
Let's consider the use of virtual functions on the example of Tetris.mq5. The base class
CTetrisShape with the virtual function Draw is defined in the included file
TetisShape.mqh.
//+------------------------------------------------------------------+ class CTetrisSh
{
protected:
int m_type;
int m_xpos;
int m_ypos;
int m_xsize;
int m_ysize;
int m_prev_turn;
int m_turn;
int m_right_border;
public:
void CTetrisShape();
void SetRightBorder(int border) { m_right_border=border; }
void SetYPos(int ypos) { m_ypos=ypos; }
void SetXPos(int xpos) { m_xpos=xpos; }
int GetYPos() { return(m_ypos); }
int GetXPos() { return(m_xpos); }
int GetYSize() { return(m_ysize); }
int GetXSize() { return(m_xsize); }
int GetType() { return(m_type); }
void Left() { m_xpos-=SHAPE_SIZE; }
void Right() { m_xpos+=SHAPE_SIZE; }
void Rotate() { m_prev_turn=m_turn; if(++m_turn>3)
virtual void Draw() { return; }
virtual bool CheckDown(int& pad_array[]);
virtual bool CheckLeft(int& side_row[]);
virtual bool CheckRight(int& side_row[]);
};
Further, for each derived class, this function is implemented in accordance with
characteristics of a descendant class. For example, the first shape CTetrisShape1 has its
own implementation of the Draw() function:
class CTetrisShape1 : public CTetrisShape
{
public:
//--- shape drawing
virtual void Draw()
{
int i;
string name;
//---
if(m_turn==0 || m_turn==2)
{
//--- horizontal
for(i=0; i<4; i++)
{
name=SHAPE_NAME+(string)i;
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,m_xpos+i*SHAPE_SIZE);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,m_ypos);
}
}
else
{
//--- vertical
for(i=0; i<4; i++)
{
name=SHAPE_NAME+(string)i;
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,m_xpos);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,m_ypos+i*SHAPE_SIZE);
}
}
}
}
The Square shape is described by class CTetrisShape6 and has its own implementation of
the Draw() method:
class CTetrisShape6 : public CTetrisShape
{
public:
//--- Shape drawing
virtual void Draw()
{
int i;
string name;
//---
for(i=0; i<2; i++)
{
name=SHAPE_NAME+(string)i;
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,m_xpos+i*SHAPE_SIZE);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,m_ypos);
}
for(i=2; i<4; i++)
{
name=SHAPE_NAME+(string)i;
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,m_xpos+(i-2)*SHAPE_SIZE);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,m_ypos+SHAPE_SIZE);
}
}
};
Depending on the class, to which the created object belongs, it calls the virtual function
of this or that derived class.
void CTetrisField::NewShape()
{
//--- creating one of the 7 possible shapes randomly
int nshape=rand()%7;
switch(nshape)
{
case 0: m_shape=new CTetrisShape1; break;
case 1: m_shape=new CTetrisShape2; break;
case 2: m_shape=new CTetrisShape3; break;
case 3: m_shape=new CTetrisShape4; break;
case 4: m_shape=new CTetrisShape5; break;
case 5: m_shape=new CTetrisShape6; break;
case 6: m_shape=new CTetrisShape7; break;
}
//--- draw
m_shape.Draw();
//---
}
MQL4 Reference / Language Basics / Object-Oriented Programming / Static Members of a Class
where class_name is the name of the class, and variable is the name of the class
member.
As you see, to access the static member of a class, context resolution operator :: is
used. When you access a static member within class methods, the context operator is
optional.
Static member of a class has to be explicitly initialized with desired value. For this it
must be declared and initialized in global scope. The sequence of static members
initialization will correspond to the sequence of their declaration in global scope.
For example, we have a class CParser used for parsing the text, and we need to count
the total number of processed words and characters. We only need to declare the
necessary class members as static and initialize them at the global level. Then all
instances of the class will use common counters of words and characters.
//+------------------------------------------------------------------+ //| Class "Text
//+------------------------------------------------------------------+
class CParser
{
public:
static int s_words;
static int s_symbols;
//--- Constructor and destructor
CParser(void);
~CParser(void){};
};
...
//--- Initialization of static members of the Parser class at the global level
int CParser::s_words=0;
int CParser::s_symbols=0;
A static class member can be declared with the const keyword. Such static constants
must be initialized at the global level with the const keyword:
//+------------------------------------------------------------------+
//| Class "Stack" for storing processed data |
//+------------------------------------------------------------------+
class CStack
{
public:
CStack(void);
~CStack(void){};
...
private:
static const int s_max_length; // Maximum stack capacity
};
Pointer this
The keyword this denotes an implicitly declared pointer to itself to a specific instance of
the class, in the context of which the method is executed. It can be used only in non-
static methods of the class. Pointer this is an implicit non-static member of any class.
In static functions you can access only static members/methods of a class.
Static Methods
In MQL4 member functions of type static can be used. The static modifier must precede
the return type of a function in the declaration inside a class.
class CStack
{
public:
//--- Constructor and destructor
CStack(void){};
~CStack(void){};
//--- Maximum stack capacity
static int Capacity();
private:
int m_length; // The number of elements in the stack
static const int s_max_length; // Maximum stack capacity
};
//+------------------------------------------------------------------+
//| Returns the maximum number of elements to store in the stack |
//+------------------------------------------------------------------+
int CStack::Capacity(void)
{
return(s_max_length);
}
//--- Initialization of the static constant of the CStack class
const int CStack::s_max_length=1000;
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- declare CStack type variable
CStack stack;
//--- call the object's static method
Print("CStack.s_max_length=",stack.Capacity());
//--- it can also be called the following way, as the method is static and does not r
Print("CStack.s_max_length=",CStack::Capacity());
}
A method with the const modifier is called constant and cannot modify implicit members
of its class. Declaration of constant functions of a class and constant parameters is
called const-correctness control. Through this control you can be sure that the compiler
will ensure the consistency of values of objects and will return an error during
compilation if there is something wrong.
The const modifier is placed after the list of arguments inside a class declaration.
Definition outside a class should also include the const modifier:
//+------------------------------------------------------------------+
//| Class "Rectangle" |
//+------------------------------------------------------------------+
class CRectangle
{
private:
double m_width; // Width
double m_height; // Height
public:
//--- Constructors and destructor
CRectangle(void):m_width(0),m_height(0){};
CRectangle(const double w,const double h):m_width(w),m_height(h)
~CRectangle(void){};
//--- Calculating the area
double Square(void) const;
static double Square(const double w,const double h);// { return(w*h); }
};
//+------------------------------------------------------------------+
//| Returns the area of the "Rectangle" object |
//+------------------------------------------------------------------+
double CRectangle::Square(void) const
{
return(Square(m_width,m_height));
}
//+------------------------------------------------------------------+
//| Returns the product of two variables |
//+------------------------------------------------------------------+
static double CRectangle::Square(const double w,const double h)
{
return(w*h);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Create a rectangle rect with the sides equal to 5 and 6
CRectangle rect(5,6);
//--- Find the rectangle area using a constant method
PrintFormat("rect.Square()=%.2f",rect.Square());
//--- Find the product of numbers using the static method of class CRectangle
PrintFormat("CRectangle::Square(2.0,1.5)=%f",CRectangle::Square(2.0,1.5));
}
An additional argument in favor of using the constancy control is the fact that in this
case, the compiler generates a special optimization, for example, places a constant
object in read-only memory.
A static function cannot be determined with the const modifier, because this modifier
ensures the constancy of the instance members when calling this function. But, as
mentioned above, the static function cannot access non-static class members.
See also
Static Variables, Variables, References. Modifier & and Keyword this
MQL4 Reference / Language Basics / Object-Oriented Programming / Function Templates
Function Templates
Overloaded functions are commonly used to perform similar operations on
various data types. ArraySize() is a simple example of such function in
MQL4. It returns size of any type of array. In fact, this system function is
overloaded and the entire implementation of such an overload is hidden
from MQL4 application developers:
int ArraySize( void& array[] // checked array
);
ArraySize() function can be displayed the following way for MqlRates type
array for working with quotations in historical data format:
int ArraySize(
MqlRates& array[] // array filled with MqlRates type values
);
Thus, it is very convenient to use the same function for working with
different types. However, all preliminary work should be carried out the
necessary function should be overloaded for all data types it should
correctly work with.
There is a convenient solution. If similar operations should be executed for
each data type, it is possible to use function templates. In this case, a
programmer needs to write only one function template description. When
describing the template in such a way, we should specify only some formal
parameter instead of some definite data type the function should work
with. The compiler will automatically generate various functions for the
appropriate handling of each type based on the types of the arguments used
when calling the function.
Function template definition starts with the template keyword followed by
the list of formal parameters in angle brackets. Each formal parameter is
preceded by the typename keyword. Formal parameter types are built-in or
user-defined types. They are used:
to specify the types of function arguments,
to specify the types of function's return value,
to declare the variables inside the function definition
Number of template parameters cannot exceed eight. Each formal
parameter in the template definition should appear in the list of function
parameters at least once. Each name of the formal parameter should be
unique.
Below is an example of a function template for searching the highest value
in the array of any numeric type (integer and real numbers):
template<typename T>
T ArrayMax(T &arr[])
{
uint size=ArraySize(arr);
if(size==0) return(0);
T max=arr[0];
for(uint n=1;n<size;n++)
if(max<arr[n]) max=arr[n];
//---
return(max);
}
This template defines the function that finds the highest value in the
passed array and returns this value as a result. Keep in mind that the
ArrayMaximum() function built in MQL4 returns only the highest value index
that can be used to find the value itself. For example:
//--- create an array
double array[];
int size=50;
ArrayResize(array,size);
//--- fill with random values
for(int i=0;i<size;i++)
{
array[i]=MathRand();
}
we now can use only one line, in which the returned result has the same
type as the array passed into function:
//--- find the highest value
double max=ArrayMax(array);
In this case, the type of result returned by the ArrayMax() function will
automatically match the type of array.
Use the typename keyword to get the argument type as a string in order to
create general purpose methods of working with various data types. Let's
consider a specific example of the function that returns data type as a
string:
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void OnStart()
{
//---
CTrade trade;
double d_value=M_PI;
int i_value=INT_MAX;
Print("d_value: type=",GetTypeName(d_value), ", value=", d_value);
Print("i_value: type=",GetTypeName(i_value), ", value=", i_value);
Print("trade: type=",GetTypeName(trade));
//---
}
//+------------------------------------------------------------------+
//| Type is returned as a line |
//+------------------------------------------------------------------+
template<typename T>
string GetTypeName(const T &t)
{
//--- return the type as a line
return(typename(T));
//---
}
Function templates can also be used for class methods, for example:
class CFile
{
...
public:
...
template<typename T>
uint WriteStruct(T &data);
};
template<typename T>
uint CFile::WriteStruct(T &data)
{
...
return(FileWriteStruct(m_handle,data));
}
Function templates should not be declared with export, virtual and #import
keywords.
Template function overload
A template function overload may be necessary sometimes. For example,
we have a template function that writes the value of the second parameter
to the first one using typecasting. MQL5 does not allow typecasting string to
bool. We can do that ourselves let's create an overload of a template
function. For example:
//+------------------------------------------------------------------+
//| Template function |
//+------------------------------------------------------------------+
template<typename T1,typename T2>
string Assign(T1 &var1,T2 var2)
{
var1=(T1)var2;
return(__FUNCSIG__);
}
//+------------------------------------------------------------------+
//| Special overload for bool+string |
//+------------------------------------------------------------------+
string Assign(bool &var1,string var2)
{
var1=(StringCompare(var2,"true",false) || StringToInteger(var2)!=0);
return(__FUNCSIG__);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
int i;
bool b;
Print(Assign(i,"test"));
Print(Assign(b,"test"));
}
As a result of the code execution, we can see that the Assign() template
function has been used for the int+string pair, while the overloaded version
has already been used for the bool+string pair during the second call.
string Assign<int,string>(int&,string)
string Assign(bool&,string)
See also
Overload
MQL4 Reference / Language Basics / Object-Oriented Programming / Class Templates
Template advantages
Function templates are used when you need to perform similar operations on various
data types, for example, searching for a maximum element in the array. The main
advantage of applying the templates is that you do not have to code a separate overload
for each type. Instead of declaring multiple overloads of each type
double ArrayMax(double array[]) {
...
}
int ArrayMax(int array[])
{
...
}
uint ArrayMax(uint array[])
{
...
}
long ArrayMax(long array[])
{
...
}
datetime ArrayMax(datetime array[])
{
...
}
Here, the T formal parameter specifying a type of used data is replaced with an actually
applied type during compilation, i.e. the compiler automatically generates a separate
function for each type double, datetime, etc. MQL5 also allows you to develop class
templates using all the advantages of the approach.
Class templates
A class template is declared using the template keyword followed by angle brackets<>
enumerating the list of formal parameters with the typename keyword. This entry
informs the compiler that it deals with a generic class with the T formal parameter
defining a real variable type when implementing a class. For example, let's create a
vector class for storing an array with T type elements:
#define TOSTR(x) #x+" " // macro for displaying an object name
//+------------------------------------------------------------------+
//| Vector class for storing T-type elements |
//+------------------------------------------------------------------+
template <typename T>
class TArray
{
protected:
T m_array[];
public:
//--- constructor creates an array for 10 elements by default
void TArray(void){ArrayResize(m_array,10);}
//--- constructor for creating a vector with a specified array size
void TArray(int size){ArrayResize(m_array,size);}
//--- return a type and amount of data stored in the TArray type object
string Type(void){return(typename(m_array[0])+":"+(string)ArraySize(m_array));};
};
Next, let's apply different methods to create three TArray objects in the program for
working with various types
void OnStart()
{
TArray<double> double_array; // vector has a default size of 10
TArray<int> int_array(15); // vector has a size of 15
TArray<string> *string_array; // pointer to TArray<string> vector
//--- create a dynamic object
string_array=new TArray<string>(20);
//--- display an object name, data type and vector size in the Journal
PrintFormat("%s (%s)",TOSTR(double_array),double_array.Type());
PrintFormat("%s (%s)",TOSTR(int_array),int_array.Type());
PrintFormat("%s (%s)",TOSTR(string_array),string_array.Type());
//--- remove a dynamic object before completing the program
delete(string_array);
}
Now, we have 3 vectors with different data types: double, int and string.
Class templates are well suited for developing containers objects designed for
encapsulating other objects of any type. Container objects are collections already
containing objects of one certain type. Usually, working with stored data is instantly
built into the container.
For example, you can create a class template that does not allow accessing an element
outside the array, thus avoiding the "out of range" critical error.
//+------------------------------------------------------------------+
//| Class for a free access to an array element |
//+------------------------------------------------------------------+
template<typename T>
class TSafeArray
{
protected:
T m_array[];
public:
//--- default constructor
void TSafeArray(void){}
//--- constructor for creating the array of a specified size
void TSafeArray(int size){ArrayResize(m_array,size);}
//--- array size
int Size(void){return(ArraySize(m_array));}
//--- change the array size
int Resize(int size,int reserve){return(ArrayResize(m_array,size,res
//--- release the array
void Erase(void){ZeroMemory(m_array);}
//--- operator for accessing the array element by index
T operator[](int index);
//--- assignment operator for receiving all elements from the array at once
void operator=(const T &array[]); // T type array
};
//+------------------------------------------------------------------+
//| Receiving an element by index |
//+------------------------------------------------------------------+
template<typename T>
T TSafeArray::operator[](int index)
{
static T invalid_value;
//---
int max=ArraySize(m_array)-1;
if(index<0 || index>=ArraySize(m_array))
{
PrintFormat("%s index %d is not in range (0-%d)!",__FUNCTION__,index,max);
return(invalid_value);
}
//---
return(m_array[index]);
}
//+------------------------------------------------------------------+
//| Assigning for the array |
//+------------------------------------------------------------------+
template<typename T>
void TSafeArray::operator=(const T &array[])
{
int size=ArraySize(array);
ArrayResize(m_array,size);
//--- T type should support the copying operator
for(int i=0;i<size;i++)
m_array[i]=array[i];
//---
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
int copied,size=15;
MqlRates rates[];
//--- copy the array of quotes
if((copied=CopyRates(_Symbol,_Period,0,size,rates))!=size)
{
PrintFormat("CopyRates(%s,%s,0,%d) returned %d error code",
_Symbol,EnumToString(_Period),size,GetLastError());
return;
}
//--- create a container and insert the MqlRates value array to it
TSafeArray<MqlRates> safe_rates;
safe_rates=rates;
//--- index within the array
int index=3;
PrintFormat("Close[%d]=%G",index,safe_rates[index].close);
//--- index outside the array
index=size;
PrintFormat("Close[%d]=%G",index,safe_rates[index].close);
}
Please note that template declaration should also be used when describing methods
outside the class declaration:
template<typename T>
T TSafeArray::operator[](int index)
{
...
}
template<typename T>
void TSafeArray::operator=(const T &array[])
{
...
}
Class and function templates allow you to define multiple comma-separated formal
parameters, for example, Map collection for storing "key value" pairs:
template<typename Key, template Value>
class TMap
{
...
}
See also
Function templates, Overload
MQL4 Reference / Language Basics / Object-Oriented Programming / Abstract Classes
Here Sound() is a pure virtual function, because it is declared with the specifier of the
pure virtual function PURE (=0).
Pure virtual functions are only the virtual functions for which the PURE specifier is set:
(=NULL) or (=0). Example of abstract class declaration and use:
class CAnimal
{
public:
virtual void Sound()=NULL; // PURE method, should be overridden in the der
};
//--- Derived from an abstract class
class CCat : public CAnimal
{
public:
virtual void Sound() { Print("Myau"); } // PURE is overridden, CCat is not a
};
Restrictions on abstract classes
If the constructor for an abstract class calls a pure virtual function (either directly or
indirectly), the result is undefined.
//+------------------------------------------------------------------+
//| An abstract base class |
//+------------------------------------------------------------------+
class CAnimal
{
public:
//--- A pure virtual function
virtual void Sound(void)=NULL;
//--- Function
void CallSound(void) { Sound(); }
//--- Constructor
CAnimal()
{
//--- An explicit call of the virtual method
Sound();
//--- An implicit call (using a third function)
CallSound();
//--- A constructor and/or destructor always calls its own functions,
//--- even if they are virtual and overridden by a called function in a derived
//--- If the called function is pure virtual,
//--- its call will cause a critical runtime error: "pure virtual function call"
}
};
However, constructors and destructors for abstract classes can call other member
functions.
MQL4 Reference / Language Basics / Updated MQL4
Also the new function format can be used for virtual copying, when there is no actual
copying, and accessing the copied values you actually access the price data.
int ArrayCopyRates(
MqlRates& rates_array[], // MqlRates array, passed by reference
string symbol=NULL, // symbol
int timeframe=0 // timeframe
);
To provide compatibility with old MQL4 programs, the previous call format is also
preserved, but now it leads to actual copying of data into a double-type array.
int ArrayCopyRates(
void& dest_array[][], // destination array, passed by reference
string symbol=NULL, // symbol
int timeframe=0 // timeframe
);
This means that when the values in the time series change (new bars are added,
restructuring, the last bar's Close price is uodated), you must re-copy the required data
into the dest_array[][]. The receiver array will be automatically allocated for the
required number of copied bars, even if it was declared statically.
Changed RateInfo history data storage format. RateInfo structure was presented as
follows in the old version:
struct RateInfo
{
unsigned int ctm; // bar open date
double open; // Open price
double low; // Low price
double high; // High price
double close; // Close price
double vol; // volume
};
In the new format, RateInfo structure features fields for storing spread and trading
volume:
//--- Standard quote presentation in the new terminal version
struct RateInfo
{
INT64 ctm; // open date and time
double open; // Open price (absolute value)
double high; // Low price
double low; // High price
double close; // Close price
UINT64 vol; // tick volume
INT32 spread; // spread
UINT64 real; // trade volume
};
Thus, if MQL4 programs contain DLLs for passing/accepting price data, the
corresponding functions in the source codes should be rewritten and recompiled
considering format changes to ensure proper operation.
Old EX4 applications and DLLs based on old RateInfo format will not work in the new
terminal. Conversion to the new format is required.
In file operations, the number of simultaneously opened files can now reach 64 ones,
while there could be no more than 32 ones in the old MQL4. Until recently, the files
were always opened in FILE_SHARE_READ or FILE_SHARE_WRITE mode. Now, the
necessary opening mode should be specified explicitly.
For FileWrite(), FileWriteArray(), FileWriteDouble(), FileWriteInteger() and
FileWriteString() functions the type of returned value has been changed from int to
uint. The functions return the number of bytes, actually written or 0 in case of error
(in old version of MQL4 the negative number is returned in case of error).
Working with functions, scope of variables and memory release in local arrays has also
been changed. Since the number of changes is large enough, the new #property strict
property has been introduced to provide maximum compatibility with the previous
approach to developing MQL4 programs. When creating new MQL4 application using
MQL wizard, this property is always added to the template.
The string representation of datetime type depends on compilation mode:
datetime date=D'2014.03.05 15:46:58';
string str="mydate="+date;
//--- str="mydate=1394034418" - old compiler/new compiler without #property strict
//--- str="mydate=2014.03.05 15:46:58" - new compiler with #property strict
The table below contains the differences between MQL4, new MQL4 without using strict
and new MQL4 with specified strict compilation mode:
#property strict
When compiling libraries in the strict mode, the export modifier should be added for
each exported function, otherwise the function will not be accessible from outside.
The table of differences between compilers:
Old MQL4 compiler New MQL4 compiler New MQL4 with #property
strict
Old MQL4 compiler New MQL4 compiler New MQL4 with #property
strict
init(), start() and deinit() init(), start() and deinit() Ditto
entry points may have any have been remained intact for
parameters and any return compatibility,
type while new OnInit(), OnStart(),
OnCalculate(), OnTick(),
OnTimer(), OnChartEvent(),
OnTester() and OnDeinit()
should strictly correspond to
their signatures
The result of the return from The result of the return from If a non-zero value is returned
init() function is not analyzed init() and OnInit() functions is from OnInit(), the operation of
by the runtime subsystem not analyzed by the runtime an Expert Advisor or an
subsystem indicator is stopped, the
program is unloaded
Virtually any variable names Variable names cannot have Ditto
(except for the reserved special characters and points.
words) are possible, including The list of the reserved words
special characters and points has been expanded. Thus,
such widespread words as
short, long, const, etc. cannot
be used as names
Variable scope is from Ditto Variable scope is from
declaration (even in the declaration to the end of the
nested block) to the function block, in which the variable is
end declared
Implicit initialization of all Ditto Only global variables are
the variables (both global and initialized. In local variables,
local ones) by zero only strings are initialized
implicitly
Local arrays are not released Local arrays are released Local arrays are released when
when exiting the function when exiting the function exiting {} block
"Array out of range" does not Ditto, except for the arrays of "Array out of range" is a
cause a critical error structures and classes, for critical error causing the
which this error is critical one program to stop
No structures and classes Structures and classes are Ditto
present. Additional data types
are implemented
Strings are single-byte. Strings are unicode ones. Ditto
datetime is a 32-bit integer datetime is a 64-bit integer
Predefined Volume variable is Predefined Volume variable is
of double type of long type
Old MQL4 compiler New MQL4 compiler New MQL4 with #property
strict
ArrayCopyRates() performs ArrayCopyRates() performs Ditto
virtual copying to double[][6] virtual copying to MqlRates[]
array array. Copying to double[][6]
array has remained intact for
the sake of compatibility,
however, that copying is real,
not virtual.
The functions may not return Ditto Functions of any type should
values even if they have a return a value
type. To do this, return(0) is
automatically inserted by the
compiler in the function end
The number of The number of simultaneously Ditto
simultaneously opened files is opened files is 64
32
The files are always opened FILE_SHARE_READ and/or Ditto
in FILE_SHARE_READ, FILE_SHARE_WRITE should be
FILE_SHARE_WRITE mode ** specified explicitly
The names of extern The names of extern and String comments instead of
variables are displayed for input variables are displayed extern and input variable
scripts in the input for scripts in show_inputs names are displayed for scripts
parameters window mode in the input parameters in show_inputs mode in the
window input parameters window
* Please pay special attention to "Array out of range" error - many old custom indicators
will display this error in strict mode of the new compiler when launched on the chart.
It is recommended to find the cause and eliminate it.
** In the new MQL4 and MQL5, FILE_SHARE_READ and FILE_SHARE_WRITE flags are
responsible for the files shared use mode. There were no such files in the old MQL4.
Changes in File Structure
In the previous builds of MetaTrader 4 client terminal (509 and older), all MQL4
applications were stored in the following subdirectories of
<terminal_installation_folder>\experts\ root directory:
\experts - Expert Advisors (trading robots),
\experts\indicators - custom indicators,
\experts\scripts - scripts (MQL4 applications for a single run on the chart),
\include - source code MQH and MQ4 files implemented into other programs,
\libraries - libraries in the form of MQ4 source codes and EX4 executable files
compiled from them. They are used for the dynamic call of the functions contained
there by other MQL4 programs,
\files - special "file sandbox". MQL4 applications are allowed to execute file
operations only within this directory.
In the new MQL4 version, the file structure for storing the source codes has changed.
Now, all MQL4 applications should be located in the appropriate folders of
<data_folder>\MQL4\ directory:
\Experts - Expert Advisors (trading robots),
\Indicators - custom indicators,
\Scripts - scripts (MQL4 applications for a single run on the chart),
\Include - source code MQH and MQ4 files implemented into other programs,
\Libraries - libraries in the form of MQ4 source codes and EX4 executable files
compiled from them. They are used for the dynamic call of the functions contained
there by other MQL4 programs,
\Images - image files for using in resources,
\Files - special "file sandbox". MQL4 applications are allowed to execute file
operations only within this directory.
When updating MetaTrader 4 terminal from build 509 to the newer version, all MQ4,
MQH and EX4 files from standard root directories of the previous version are
automatically copied and relocated to the appropriate folders. Subfolders additionally
created by a user, as well as files contained there are not processed. They should be
relocated to the new place manually if necessary.
No files or folders are deleted during the update! All file copy operations including used file
paths are fixed in the terminal Journal during the update.
No automatic re-compilation of the old EX4 files to the new version is performed
during the update. Users are free to decide what source codes should be compiled to
the new EX4 version. All old EX4 will work in the new MetaTrader 4 terminal. EX4
libraries compiled by the new compiler can be called only from the EX4 programs that
have also been compiled in the new version.
In some cases, you may need to edit the path in #include for included files (if relative
paths have changed) in the source files. Please note that MetaEditor's root directory is
now <data_folder>\MQL4\. All programs should be located in the correct subdirectories.
You can find the data folder (<data_folder>) for each copy of MetaTrader 4 terminal on
your computer via the terminal menu or in MetaEditor: File - Open Data Folder.
MQL4 Reference / Constants, Enumerations and Structures
Chart Constants
Constants describing various properties of charts are divided into the
following groups:
Types of events events that occur when working with charts;
Chart timeframes standard built-in periods;
Properties of chart identifiers that are used as parameters of chart
functions;
Positioning constants - value of a parameter of the ChartNavigate()
function;
Displaying charts - setting the chart appearance.
What's new in MQL5
The new generation platform has two times more timeframes (21 vs
9). It also features new graphical objects and analytical tools. Object
anchors can be placed in any position between the chart bars up to a
minute. Moreover, when switching between timeframes, the accurate
positioning of the control points of the object is preserved.
You can set any chart properties directly from an MQL5 program. The
number of properties has been increased. CHART_SHOW and
CHART_IS_DOCKED are among the most notable ones. They allow
moving any chart beyond the terminal turning it into a full-fledged
separate trading panel. Disable the display of unnecessary areas on
the chart and place OBJ_CHART objects, indicators and an EA on it to
get your own trading control center with all the necessary technical
analysis tools.
The table shows the new properties allowing you to fully manage a
symbol chart.
Property
ID Description
Type
Property
ID Description
Type
Price chart drawing. If false,
drawing any price chart
attributes is disabled and all
chart border indents are
eliminated, including time and
price scales, quick navigation
bar, Calendar event labels,
trade labels, indicator and bar
CHART_SHOW tooltips, indicator subwindows, bool
volume histograms, etc.
Disabling the drawing is a
perfect solution for creating a
custom program interface using
the graphical resources.
The graphical objects are
always drawn regardless of the
CHART_SHOW property value.
Identifying "Chart"
(OBJ_CHART) object returns
CHART_IS_OBJECT bool r/o
true for a graphical object.
Returns false for a real chart
bool
Show chart on top of other
CHART_CONTEXT_MENU (default
charts
is 'true')
Enabling/disabling access to
the context menu using the
right click.
When bool
CHART_CROSSHAIR_TOOL CHART_CONTEXT_MENU=false, (default
only the chart context menu is is 'true')
disabled. The context menu of
objects on the chart remains
available.
Enabling/disabling access to
CHART_MOUSE_SCROLL the Crosshair tool using the bool
middle click.
Property
ID Description
Type
Scrolling the chart horizontally
using the left mouse button.
Vertical scrolling is also
available if the value of any
following properties is set to
bool
true: CHART_SCALEFIX,
CHART_EVENT_MOUSE_WHEEL (default
CHART_SCALEFIX_11 or
is 'true')
CHART_SCALE_PT_PER_BAR
When
CHART_MOUSE_SCROLL=false,
chart scrolling with the mouse
wheel is unavailable
Sending messages about mouse
wheel events
CHART_EVENT_MOUSE_MOVE bool
(CHARTEVENT_MOUSE_WHEEL)
to all mql5 programs on a chart
Send notifications of mouse
move and mouse click events
CHART_EVENT_OBJECT_CREATE bool
(CHARTEVENT_MOUSE_MOVE)
to all mql5 programs on a chart
Send a notification of an event
of new object creation
CHART_EVENT_OBJECT_DELETE bool
(CHARTEVENT_OBJECT_CREATE)
to all mql5-programs on a chart
Allow managing the chart using
a keyboard ("Home", "End",
"PageUp", "+", "-", "Up arrow",
etc.). Setting
CHART_KEYBOARD_CONTROL to
CHART_KEYBOARD_CONTROL bool
false disables chart scrolling
and scaling while leaving intact
the ability to receive the keys
pressing events in
OnChartEvent().
Display textual descriptions of
CHART_SHOW_OBJECT_DESCR objects (not available for all bool
objects)
Property
ID Description
Type
Showing the "One click trading"
CHART_SHOW_ONE_CLICK bool
panel on a chart
CHART_IS_MAXIMIZED Chart window is maximized bool
CHART_IS_MINIMIZED Chart window is minimized bool
The chart window is docked. If
set to false, the chart can be
CHART_IS_DOCKED bool
dragged outside the terminal
area
The left coordinate of the
CHART_FLOAT_LEFT undocked chart window int
relative to the virtual screen
The top coordinate of the
CHART_FLOAT_TOP undocked chart window int
relative to the virtual screen
The right coordinate of the
CHART_FLOAT_RIGHT undocked chart window int
relative to the virtual screen
The bottom coordinate of the
CHART_FLOAT_BOTTOM undocked chart window int
relative to the virtual screen
MQL4 Reference / Constants, Enumerations and Structures / Chart Constants / Types of Chart Events
For each type of event, the input parameters of the OnChartEvent() function have
definite values that are required for the processing of this event. The events and values
passed through this parameters are listed in the below table.
Event Value of the id parameter Value of the lparam Value
parameter dpara
Event of a keystroke CHARTEVENT_KEYDOWN code of a pressed Repea
key numb
the
repea
of the
down
Mouse events (if CHARTEVENT_MOUSE_MOVE the X coordinate the Y
CHART_EVENT_MOUSE_MOVE=true is
set for the chart)
Event Value of the id parameter Value of the lparam Value
parameter dpara
event of graphical object creation CHARTEVENT_OBJECT_CREATE
(if
CHART_EVENT_OBJECT_CREATE=true
is set for the chart)
Event of change of an object CHARTEVENT_OBJECT_CHANGE
property via the properties dialog
Example:
#define KEY_NUMPAD_5 12 #define KEY_LEFT 37
#define KEY_UP 38
#define KEY_RIGHT 39
#define KEY_DOWN 40
#define KEY_NUMLOCK_DOWN 98
#define KEY_NUMLOCK_LEFT 100
#define KEY_NUMLOCK_5 101
#define KEY_NUMLOCK_RIGHT 102
#define KEY_NUMLOCK_UP 104
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
Print("The Expert Advisor with name ",MQLInfoString(MQL_PROGRAM_NAME)," is running
//--- enable object create events
ChartSetInteger(ChartID(),CHART_EVENT_OBJECT_CREATE,true);
//--- enable object delete events
ChartSetInteger(ChartID(),CHART_EVENT_OBJECT_DELETE,true);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, // Event identifier
const long& lparam, // Event parameter of long type
const double& dparam, // Event parameter of double type
const string& sparam) // Event parameter of string type
{
//--- the left mouse button has been pressed on the chart
if(id==CHARTEVENT_CLICK)
{
Print("The coordinates of the mouse click on the chart are: x = ",lparam," y =
}
//--- the mouse has been clicked on the graphic object
if(id==CHARTEVENT_OBJECT_CLICK)
{
Print("The mouse has been clicked on the object with name '"+sparam+"'");
}
//--- the key has been pressed
if(id==CHARTEVENT_KEYDOWN)
{
switch(int(lparam))
{
case KEY_NUMLOCK_LEFT: Print("The KEY_NUMLOCK_LEFT has been pressed"); br
case KEY_LEFT: Print("The KEY_LEFT has been pressed"); br
case KEY_NUMLOCK_UP: Print("The KEY_NUMLOCK_UP has been pressed"); br
case KEY_UP: Print("The KEY_UP has been pressed"); br
case KEY_NUMLOCK_RIGHT: Print("The KEY_NUMLOCK_RIGHT has been pressed"); br
case KEY_RIGHT: Print("The KEY_RIGHT has been pressed"); br
case KEY_NUMLOCK_DOWN: Print("The KEY_NUMLOCK_DOWN has been pressed"); br
case KEY_DOWN: Print("The KEY_DOWN has been pressed"); br
case KEY_NUMPAD_5: Print("The KEY_NUMPAD_5 has been pressed"); br
case KEY_NUMLOCK_5: Print("The KEY_NUMLOCK_5 has been pressed"); br
default: Print("Some not listed key has been pressed");
}
ChartRedraw();
}
//--- the object has been deleted
if(id==CHARTEVENT_OBJECT_DELETE)
{
Print("The object with name ",sparam," has been deleted");
}
//--- the object has been created
if(id==CHARTEVENT_OBJECT_CREATE)
{
Print("The object with name ",sparam," has been created");
}
//--- the object has been moved or its anchor point coordinates has been changed
if(id==CHARTEVENT_OBJECT_DRAG)
{
Print("The anchor point coordinates of the object with name ",sparam," has been
}
//--- the text in the Edit of object has been changed
if(id==CHARTEVENT_OBJECT_ENDEDIT)
{
Print("The text in the Edit field of the object with name ",sparam," has been c
}
}
Example:
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- enable CHART_EVENT_MOUSE_MOVE messages
ChartSetInteger(0,CHART_EVENT_MOUSE_MOVE,1);
}
//+------------------------------------------------------------------+
//| MouseState |
//+------------------------------------------------------------------+
string MouseState(uint state)
{
string res;
res+="\nML: " +(((state& 1)== 1)?"DN":"UP"); // mouse left
res+="\nMR: " +(((state& 2)== 2)?"DN":"UP"); // mouse right
res+="\nMM: " +(((state&16)==16)?"DN":"UP"); // mouse middle
res+="\nMX: " +(((state&32)==32)?"DN":"UP"); // mouse first X key
res+="\nMY: " +(((state&64)==64)?"DN":"UP"); // mouse second X key
res+="\nSHIFT: "+(((state& 4)== 4)?"DN":"UP"); // shift key
res+="\nCTRL: " +(((state& 8)== 8)?"DN":"UP"); // control key
return(res);
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long &lparam,const double &dparam,const string &
{
if(id==CHARTEVENT_MOUSE_MOVE)
Comment("POINT: ",(int)lparam,",",(int)dparam,"\n",MouseState((uint)sparam));
}
See also
Event Handling Functions, Working with events
MQL4 Reference / Constants, Enumerations and Structures / Chart
Constants / Chart Timeframes
Chart Timeframes
All predefined timeframes of charts have unique
identifiers. The PERIOD_CURRENT identifier means the
current period of a chart, at which a mql4-program is
running.
ENUM_TIMEFRAMES
ID Value Description
PERIOD_CURRENT 0 Current timeframe
PERIOD_M1 1 1 minute
PERIOD_M5 5 5 minutes
PERIOD_M15 15 15 minutes
PERIOD_M30 30 30 minutes
PERIOD_H1 60 1 hour
PERIOD_H4 240 4 hours
PERIOD_D1 1440 1 day
PERIOD_W1 10080 1 week
PERIOD_MN1 43200 1 month
Chart Properties
Identifiers of ENUM_CHART_PROPERTY enumerations are used as parameters of
functions for working with charts. The abbreviation of r/o in the "Property Type"
column means that this property is read-only and cannot be changed. The w/o
abbreviation in the "Property Type" column means that this property is write-only and
it cannot be received. When accessing certain properties, it's necessary to specify an
additional parameter-modifier (modifier), which serves to indicate the number of
chart subwindows. 0 means the main window.
For functions ChartSetInteger() and ChartGetInteger()
ENUM_CHART_PROPERTY_INTEGER
ID Description Property Type
CHART_BRING_TO_TOP Show chart on top of other bool w/o
charts
CHART_MOUSE_SCROLL Scrolling the chart horizontally bool
using the left mouse button.
Vertical scrolling is also
available if the value of any
following properties is set to
true: CHART_SCALEFIX,
CHART_SCALEFIX_11 or
CHART_SCALE_PT_PER_BAR
CHART_EVENT_MOUSE_MOVE Send notifications of mouse bool
move and mouse click events
(CHARTEVENT_MOUSE_MOVE)
to all mql4 programs on a chart
CHART_EVENT_OBJECT_CREATE Send a notification of an event bool
of new object creation
(CHARTEVENT_OBJECT_CREATE)
to all mql4-programs on a chart
CHART_EVENT_OBJECT_DELETE Send a notification of an event bool
of object deletion
(CHARTEVENT_OBJECT_DELETE)
to all mql4-programs on a chart
CHART_MODE Chart type (candlesticks, bars enum ENUM_CHART_MODE
or line)
CHART_FOREGROUND Price chart in the foreground bool
CHART_SHIFT Mode of price chart indent from bool
the right border
CHART_AUTOSCROLL Mode of automatic moving to bool
the right border of the chart
ID Description Property Type
CHART_QUICK_NAVIGATION Allow the chart to intercept bool
Space and Enter key strokes to
activate the quick navigation
bar. The quick navigation bar
automatically appears at the
bottom of the chart after
double-clicking the mouse or
pressing Space/Enter. It allows
you to quickly change a symbol,
timeframe and first visible bar
date.
CHART_SCALE Scale int from 0 to 5
CHART_SCALEFIX Fixed scale mode bool
CHART_SCALEFIX_11 Scale 1:1 mode bool
CHART_SCALE_PT_PER_BAR Scale to be specified in points bool
per bar
CHART_SHOW_OHLC Show OHLC values in the upper bool
left corner
CHART_SHOW_BID_LINE Display Bid values as a bool
horizontal line in a chart
CHART_SHOW_ASK_LINE Display Ask values as a bool
horizontal line in a chart
CHART_SHOW_LAST_LINE Display Last values as a bool
horizontal line in a chart
CHART_SHOW_PERIOD_SEP Display vertical separators bool
between adjacent periods
CHART_SHOW_GRID Display grid in the chart bool
CHART_SHOW_VOLUMES Display volume in the chart enum
ENUM_CHART_VOLUME_MODE
CHART_SHOW_OBJECT_DESCR Display textual descriptions of bool
objects (not available for all
objects)
CHART_VISIBLE_BARS The number of bars on the int r/o
chart that can be displayed
CHART_WINDOWS_TOTAL The total number of chart int r/o
windows, including indicator
subwindows
CHART_WINDOW_IS_VISIBLE Visibility of subwindows bool r/o modifier -
subwindow number
CHART_WINDOW_HANDLE Chart window handle (HWND) int r/o
ID Description Property Type
CHART_WINDOW_YDISTANCE The distance between the int r/o modifier -
upper frame of the indicator subwindow number
subwindow and the upper
frame of the main chart
window, along the vertical Y
axis, in pixels. In case of a
mouse event, the cursor
coordinates are passed in terms
of the coordinates of the main
chart window, while the
coordinates of graphical
objects in an indicator
subwindow are set relative to
the upper left corner of the
subwindow.
The value is required for
converting the absolute
coordinates of the main chart
to the local coordinates of a
subwindow for correct work
with the graphical objects,
whose coordinates are set
relative to the upper left
corner of the subwindow
frame.
CHART_FIRST_VISIBLE_BAR Number of the first visible bar int r/o
in the chart. Indexing of bars is
the same as for timeseries.
CHART_WIDTH_IN_BARS Chart width in bars int r/o
CHART_WIDTH_IN_PIXELS Chart width in pixels int r/o
CHART_HEIGHT_IN_PIXELS Chart height in pixels int modifier - subwindow
number
CHART_COLOR_BACKGROUND Chart background color color
CHART_COLOR_FOREGROUND Color of axes, scales and OHLC color
line
CHART_COLOR_GRID Grid color color
CHART_COLOR_VOLUME Color of volumes and order color
opening levels
CHART_COLOR_CHART_UP Color for the up bar, shadows color
and body borders of bull
candlesticks
CHART_COLOR_CHART_DOWN Color for the down bar, color
shadows and body borders of
bear candlesticks
ID Description Property Type
CHART_COLOR_CHART_LINE Line chart color and color of color
"Doji" Japanese candlesticks
CHART_COLOR_CANDLE_BULL Body color of a bull candlestick color
CHART_COLOR_CANDLE_BEAR Body color of a bear color
candlestick
CHART_COLOR_BID Bid price level color color
CHART_COLOR_ASK Ask price level color color
CHART_COLOR_LAST Line color of the last executed color
deal price (Last)
CHART_COLOR_STOP_LEVEL Color of stop order levels (Stop color
Loss and Take Profit)
CHART_SHOW_TRADE_LEVELS Displaying trade levels in the bool
chart (levels of open orders,
Stop Loss, Take Profit and
pending orders)
CHART_DRAG_TRADE_LEVELS Permission to drag trading bool
levels on a chart with a mouse.
The drag mode is enabled by
default (true value)
CHART_SHOW_DATE_SCALE Showing the time scale on a bool
chart
CHART_SHOW_PRICE_SCALE Showing the price scale on a bool
chart
CHART_IS_OFFLINE Flag, indicating that chart bool r/o
opened in offline mode
Example:
int chartMode=ChartGetInteger(0,CHART_MODE); switch(chartMode)
{
case(CHART_BARS): Print("CHART_BARS"); break;
case(CHART_CANDLES): Print("CHART_CANDLES");break;
default:Print("CHART_LINE");
}
bool shifted=ChartGetInteger(0,CHART_SHIFT);
if(shifted) Print("CHART_SHIFT = true");
else Print("CHART_SHIFT = false");
bool autoscroll=ChartGetInteger(0,CHART_AUTOSCROLL);
if(autoscroll) Print("CHART_AUTOSCROLL = true");
else Print("CHART_AUTOSCROLL = false");
int chartHandle=ChartGetInteger(0,CHART_WINDOW_HANDLE);
Print("CHART_WINDOW_HANDLE = ",chartHandle);
int windows=ChartGetInteger(0,CHART_WINDOWS_TOTAL);
Print("CHART_WINDOWS_TOTAL = ",windows);
if(windows>1)
{
for(int i=0;i<windows;i++)
{
int height=ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,i);
double priceMin=ChartGetDouble(0,CHART_PRICE_MIN,i);
double priceMax=ChartGetDouble(0,CHART_PRICE_MAX,i);
Print(i+": CHART_HEIGHT_IN_PIXELS = ",height," pixels");
Print(i+": CHART_PRICE_MIN = ",priceMin);
Print(i+": CHART_PRICE_MAX = ",priceMax);
}
}
See also
Examples of Working with the Chart
MQL4 Reference / Constants, Enumerations and Structures / Chart Constants /
Positioning Constants
Positioning Constants
Three identifiers from the ENUM_CHART_POSITION list are the
possible values of the position parameter for the ChartNavigate()
function.
ENUM_CHART_POSITION
ID Description
CHART_BEGIN Chart beginning (the oldest prices)
CHART_CURRENT_POS Current position
CHART_END Chart end (the latest prices)
Example:
long handle=ChartOpen("EURUSD",PERIOD_H12); if(handle!=0)
{
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
ChartSetInteger(handle,CHART_SHIFT,true);
ChartSetInteger(handle,CHART_MODE,CHART_LINE);
ResetLastError();
bool res=ChartNavigate(handle,CHART_END,150);
if(!res) Print("Navigate failed. Error = ",GetLastError());
ChartRedraw();
}
MQL4 Reference / Constants, Enumerations and Structures / Chart Constants / Chart
Representation
Chart Representation
Price charts can be displayed in three ways:
as bars;
as candlesticks;
as a line.
The specific way of displaying the price chart is set by the function
ChartSetInteger(chart_handle,CHART_MODE, chart_mode), where
chart_mode is one of the values of the ENUM_CHART_MODE
enumeration.
ENUM_CHART_MODE
ID Description
CHART_BARS Display as a sequence of bars
CHART_CANDLES Display as Japanese candlesticks
CHART_LINE Display as a line drawn by Close prices
Example:
//--- Get the handle of the current chart long handle=ChartID();
if(handle>0) // If it succeeded, additionally customize
{
//--- Disable autoscroll
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
//--- Set the indent of the right border of the chart
ChartSetInteger(handle,CHART_SHIFT,true);
//--- Display as candlesticks
ChartSetInteger(handle,CHART_MODE,CHART_CANDLES);
//--- Scroll by 100 bars from the beginning of history
ChartNavigate(handle,CHART_CURRENT_POS,100);
//--- Set the tick volume display mode
ChartSetInteger(handle,CHART_SHOW_VOLUMES,CHART_VOLUME_TICK);
}
See also
ChartOpen, ChartID
MQL4 Reference / Constants, Enumerations and Structures / Chart Constants / Examples of Working with the
Chart
CHART_MOUSE_SCROLL is a property for scrolling the chart using left mouse button.
//+--------------------------------------------------------------------------+
//| The function defines if scrolling the chart using left mouse button is |
//| enabled. |
//+--------------------------------------------------------------------------+
bool ChartMouseScrollGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_MOUSE_SCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------+
//| The function enables/disables scrolling the chart using left mouse |
//| button. |
//+--------------------------------------------------------------------+
bool ChartMouseScrollSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_MOUSE_SCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_EVENT_MOUSE_MOVE is a property of sending messages concerning move
events and mouse clicks to mql4 applications (CHARTEVENT_MOUSE_MOVE).
//+------------------------------------------------------------------+
//| Check if messages concerning move events and mouse clicks |
//| are sent to all mql4 applications on the chart. |
//+------------------------------------------------------------------+
bool ChartEventMouseMoveGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_EVENT_MOUSE_MOVE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------------------+
//| The function enables/disables the mode of sending messages concerning move |
//| events and mouse clicks to mql4 applications on the |
//| chart. |
//+------------------------------------------------------------------------------+
bool ChartEventMouseMoveSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_EVENT_MOUSE_MOVE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_EVENT_OBJECT_CREATE is a property of sending messages concerning the
event of a graphic object creation to mql4 applications
(CHARTEVENT_OBJECT_CREATE).
//+---------------------------------------------------------------------+
//| Check if messages concerning the event of a graphic object creation |
//| are sent to all mql4 applications on the chart. |
//+---------------------------------------------------------------------+
bool ChartEventObjectCreateGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_EVENT_OBJECT_CREATE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| The function enables/disables the mode of sending messages concerning |
//| the event of a graphic object creation to all mql4 applications on the |
//| chart. |
//+--------------------------------------------------------------------------+
bool ChartEventObjectCreateSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_EVENT_OBJECT_CREATE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_EVENT_OBJECT_DELETE is a property of sending messages concerning the
event of a graphic object deletion to mql4 applications
(CHARTEVENT_OBJECT_DELETE).
//+---------------------------------------------------------------------+
//| Check if messages concerning the event of a graphic object deletion |
//| are sent to all mql4 applications on the chart. |
//+---------------------------------------------------------------------+
bool ChartEventObjectDeleteGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_EVENT_OBJECT_DELETE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| The function enables/disables the mode of sending messages concerning |
//| the event of a graphic object deletion to all mql4 applications on the |
//| chart. |
//+--------------------------------------------------------------------------+
bool ChartEventObjectDeleteSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_EVENT_OBJECT_DELETE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_MODE type of the chart (candlesticks, bars or line).
//+------------------------------------------------------------------+
//| Get chart display type (candlesticks, bars or |
//| line). |
//+------------------------------------------------------------------+
ENUM_CHART_MODE ChartModeGet(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=WRONG_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_MODE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((ENUM_CHART_MODE)result);
}
//+------------------------------------------------------------------+
//| Set chart display type (candlesticks, bars or |
//| line). |
//+------------------------------------------------------------------+
bool ChartModeSet(const long value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_MODE,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_FOREGROUND is a property of displaying a price chart in the foreground.
//+------------------------------------------------------------------+
//| The function defines if a price chart is displayed in the |
//| foreground. |
//+------------------------------------------------------------------+
bool ChartForegroundGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_FOREGROUND,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+---------------------------------------------------------------------------+
//| The function enables/disables the mode of displaying a price chart on the |
//| foreground. |
//+---------------------------------------------------------------------------+
bool ChartForegroundSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_FOREGROUND,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHIFT mode of shift of the price chart from the right border.
//+----------------------------------------------------------------------------------
//| The function defines if the mode of shift of the price chart from the right borde
//| is enabled.
//+----------------------------------------------------------------------------------
bool ChartShiftGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHIFT,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| The function enables/disables the mode of displaying a price chart with |
//| a shift from the right border. |
//+--------------------------------------------------------------------------+
bool ChartShiftSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHIFT,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_AUTOSCROLL the mode of automatic shift to the right border of the chart.
//+---------------------------------------------------------------------+
//| The function defines if the mode of the autoscroll |
//| of the chart to the right in case of new ticks' arrival is enabled. |
//+---------------------------------------------------------------------+
bool ChartAutoscrollGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_AUTOSCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function enables/disables the mode of the autoscroll |
//| of the chart to the right in case of new ticks' arrival. |
//+------------------------------------------------------------------+
bool ChartAutoscrollSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_AUTOSCROLL,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SCALE chart scale property.
//+------------------------------------------------------------------+
//| Get chart scale (from 0 to 5). |
//+------------------------------------------------------------------+
int ChartScaleGet(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SCALE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
//+------------------------------------------------------------------+
//| Set chart scale (from 0 to 5). |
//+------------------------------------------------------------------+
bool ChartScaleSet(const long value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SCALEFIX the mode of fixed chart scale.
//+------------------------------------------------------------------+
//| The function defines if the fixed scale mode is enabled. |
//+------------------------------------------------------------------+
bool ChartScaleFixGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SCALEFIX,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function enables/disables the fixed scale mode. |
//+------------------------------------------------------------------+
bool ChartScaleFixSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALEFIX,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SCALEFIX_11 1:1 chart scale mode.
//+------------------------------------------------------------------+
//| The function defines if "1:1" scale is enabled. |
//+------------------------------------------------------------------+
bool ChartScaleFix11Get(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SCALEFIX_11,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function enables/disables "1:1" scale mode |
//+------------------------------------------------------------------+
bool ChartScaleFix11Set(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALEFIX_11,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SCALE_PT_PER_BAR the mode of specifying the chart scale in points per bar.
//+------------------------------------------------------------------------------+
//| The function defines if the mode of specifying the chart scale in points per |
//| bar is enabled. |
//+------------------------------------------------------------------------------+
bool ChartScalePerBarGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SCALE_PT_PER_BAR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+----------------------------------------------------------------------------------
//| The function enables/disables the mode of specifying the chart scale in points pe
//| bar.
//+----------------------------------------------------------------------------------
bool ChartScalePerBarSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SCALE_PT_PER_BAR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_OHLC the property of displaying OHLC values in the upper left corner.
//+------------------------------------------------------------------+
//| The function defines if the mode of displaying OHLC values |
//| in the upper left corner is enabled. |
//+------------------------------------------------------------------+
bool ChartShowOHLCGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_OHLC,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| The function enables/disables the mode of displaying OHLC values in the |
//| upper left corner of the chart. |
//+--------------------------------------------------------------------------+
bool ChartShowOHLCSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_OHLC,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_BID_LINE the property of displaying Bid value as a horizontal line on
the chart.
//+-----------------------------------------------------------------------------+
//| The function defines if the mode of displaying Bid value line on the chart |
//| is enabled. |
//+-----------------------------------------------------------------------------+
bool ChartShowBidLineGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_BID_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------+
//| The function enables/disables the mode of displaying Bid line on a |
//| chart. |
//+--------------------------------------------------------------------+
bool ChartShowBidLineSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_BID_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_ASK_LINE the property of displaying Ask value as a horizontal line on
a chart.
//+-----------------------------------------------------------------------+
//| The function defines if the mode of displaying Ask value line on the |
//| chart. |
//+-----------------------------------------------------------------------+
bool ChartShowAskLineGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_ASK_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+-----------------------------------------------------------------------+
//| The function enables/disables the mode of displaying Ask line on the |
//| chart. |
//+-----------------------------------------------------------------------+
bool ChartShowAskLineSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_ASK_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_LAST_LINE the property of displaying Last value as a horizontal line
on a chart.
//+---------------------------------------------------------------------------------+
//| The function defines if the mode of displaying the line for the last performed |
//| deal's price is enabled. |
//+---------------------------------------------------------------------------------+
bool ChartShowLastLineGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_LAST_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+----------------------------------------------------------------------------------
//| The function enables/disables the mode of displaying the line for the last perfor
//| deal's price.
//+----------------------------------------------------------------------------------
bool ChartShowLastLineSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_LAST_LINE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_PERIOD_SEP the property of displaying vertical separators between
adjacent periods.
//+------------------------------------------------------------------+
//| The function defines if the mode of displaying vertical |
//| separators between adjacent periods is enabled. |
//+------------------------------------------------------------------+
bool ChartShowPeriodSeparatorGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_PERIOD_SEP,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function enables/disables the mode of displaying vertical |
//| separators between adjacent periods. |
//+------------------------------------------------------------------+
bool ChartShowPeriodSepapatorSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_PERIOD_SEP,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_GRID the property of displaying the chart grid.
//+------------------------------------------------------------------+
//| The function defines if the chart grid is displayed. |
//+------------------------------------------------------------------+
bool ChartShowGridGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_GRID,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function enables/disables the chart grid. |
//+------------------------------------------------------------------+
bool ChartShowGridSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_GRID,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_VOLUMES the property of displaying the volumes on a chart.
//+------------------------------------------------------------------------+
//| The function defines if the volumes are displayed on a chart (are not |
//| displayed, tick ones are displayed, actual ones are displayed). |
//+------------------------------------------------------------------------+
ENUM_CHART_VOLUME_MODE ChartShowVolumesGet(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=WRONG_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_VOLUMES,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((ENUM_CHART_VOLUME_MODE)result);
}
//+------------------------------------------------------------------+
//| The function sets the mode of displaying the volumes on a chart. |
//+------------------------------------------------------------------+
bool ChartShowVolumesSet(const long value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_VOLUMES,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_OBJECT_DESCR the property of graphical object pop-up descriptions.
//+-------------------------------------------------------------------+
//| The function defines if pop-up descriptions |
//| of graphical objects are displayed when hovering mouse over them. |
//+-------------------------------------------------------------------+
bool ChartShowObjectDescriptionGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_OBJECT_DESCR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------------+
//| The function enables/disables the mode of displaying pop-up descriptions |
//| of graphical objects when hovering mouse over them. |
//+--------------------------------------------------------------------------+
bool ChartShowObjectDescriptionSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_OBJECT_DESCR,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_VISIBLE_BARS defines the number of bars on a chart that are available for
display.
//+-----------------------------------------------------------------------+
//| The function receives the number of bars that are displayed (visible) |
//| in the chart window. |
//+-----------------------------------------------------------------------+
int ChartVisibleBars(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_VISIBLE_BARS,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
CHART_WINDOWS_TOTAL defines the total number of chart windows including
indicator subwindows.
//+--------------------------------------------------------------------------+
//| The function gets the total number of chart windows including indicator |
//| subwindows. |
//+--------------------------------------------------------------------------+
int ChartWindowsTotal(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOWS_TOTAL,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
CHART_WINDOW_IS_VISIBLE defines the subwindow's visibility.
//+------------------------------------------------------------------+
//| The function defines if the current chart window or subwindow |
//| is visible. |
//+------------------------------------------------------------------+
bool ChartWindowsIsVisible(bool &result,const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOW_IS_VISIBLE,sub_window,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
CHART_WINDOW_HANDLE returns the chart handle.
//+------------------------------------------------------------------+
//| The function gets the chart handle |
//+------------------------------------------------------------------+
int ChartWindowsHandle(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOW_HANDLE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
CHART_WINDOW_YDISTANCE defines the distance in pixels between the upper frame
of the indicator subwindow and the upper frame of the chart's main window.
//+------------------------------------------------------------------+
//| The function gets the distance in pixels between the upper frame |
//| of the subwindow and the upper frame of the chart's main window. |
//+------------------------------------------------------------------+
int ChartWindowsYDistance(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOW_YDISTANCE,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
CHART_FIRST_VISIBLE_BAR returns the number of the first visible bar on the chart
(bar indexing corresponds to the time series).
//+----------------------------------------------------------------------------+
//| The function receives the number of the first visible bar on the chart. |
//| Indexing is performed like in time series, last bars have smaller indices. |
//+----------------------------------------------------------------------------+
int ChartFirstVisibleBar(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WINDOW_YDISTANCE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
CHART_WIDTH_IN_BARS returns the chart width in bars.
//+------------------------------------------------------------------+
//| The function receives the chart width in bars. |
//+------------------------------------------------------------------+
int ChartWidthInBars(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WIDTH_IN_BARS,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
CHART_WIDTH_IN_PIXELS returns the chart width in pixels.
//+------------------------------------------------------------------+
//| The function receives the chart width in pixels. |
//+------------------------------------------------------------------+
int ChartWidthInPixels(const long chart_ID=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_WIDTH_IN_PIXELS,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
CHART_HEIGHT_IN_PIXELS chart height property in pixels.
//+------------------------------------------------------------------+
//| The function receives the chart height value in pixels. |
//+------------------------------------------------------------------+
int ChartHeightInPixelsGet(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the property value
long result=-1;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_HEIGHT_IN_PIXELS,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((int)result);
}
//+------------------------------------------------------------------+
//| The function sets the chart height value in pixels. |
//+------------------------------------------------------------------+
bool ChartHeightInPixelsSet(const int value,const long chart_ID=0,const int sub_windo
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_HEIGHT_IN_PIXELS,sub_window,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_BACKGROUND - chart background color.
//+------------------------------------------------------------------+
//| The function receives chart background color. |
//+------------------------------------------------------------------+
color ChartBackColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive chart background color
if(!ChartGetInteger(chart_ID,CHART_COLOR_BACKGROUND,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets chart background color. |
//+------------------------------------------------------------------+
bool ChartBackColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the chart background color
if(!ChartSetInteger(chart_ID,CHART_COLOR_BACKGROUND,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_FOREGROUND color of axes, scale and OHLC line.
//+------------------------------------------------------------------+
//| The function receives the color of axes, scale and OHLC line. |
//+------------------------------------------------------------------+
color ChartForeColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of axes, scale and OHLC line
if(!ChartGetInteger(chart_ID,CHART_COLOR_FOREGROUND,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets the color of axes, scale and OHLC line. |
//+------------------------------------------------------------------+
bool ChartForeColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of axes, scale and OHLC line
if(!ChartSetInteger(chart_ID,CHART_COLOR_FOREGROUND,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_GRID chart grid color.
//+------------------------------------------------------------------+
//| The function receives chart grid color. |
//+------------------------------------------------------------------+
color ChartGridColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive chart grid color
if(!ChartGetInteger(chart_ID,CHART_COLOR_GRID,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets chart grid color. |
//+------------------------------------------------------------------+
bool ChartGridColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set chart grid color
if(!ChartSetInteger(chart_ID,CHART_COLOR_GRID,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_VOLUME - color of volumes and order opening levels.
//+------------------------------------------------------------------+
//| The function receives color of volumes and market entry |
//| levels. |
//+------------------------------------------------------------------+
color ChartVolumeColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive color of volumes and market entry levels
if(!ChartGetInteger(chart_ID,CHART_COLOR_VOLUME,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets the color of volumes and market entry |
//| levels. |
//+------------------------------------------------------------------+
bool ChartVolumeColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set color of volumes and market entry levels
if(!ChartSetInteger(chart_ID,CHART_COLOR_VOLUME,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_CHART_UP color of up bar, its shadow and border of a bullish
candlestick's body.
//+------------------------------------------------------------------+
//| The function receives color of up bar, its shadow and |
//| border of a bullish candlestick's body. |
//+------------------------------------------------------------------+
color ChartUpColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of up bar, its shadow and border of bullish candlestick's bod
if(!ChartGetInteger(chart_ID,CHART_COLOR_CHART_UP,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets color of up bar, its shadow and |
//| border of a bullish candlestick's body. |
//+------------------------------------------------------------------+
bool ChartUpColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of up bar, its shadow and border of body of a bullish candlestick
if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_UP,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_CHART_DOWN color of down bar, its shadow and border of bearish
candlestick's body.
//+------------------------------------------------------------------+
//| The function receives color of up bar, its shadow and |
//| border of a bearish candlestick's body. |
//+------------------------------------------------------------------+
color ChartDownColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of down bar, its shadow and border of bearish candlestick's b
if(!ChartGetInteger(chart_ID,CHART_COLOR_CHART_DOWN,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets color of down bar, its shadow and |
//| border of a bearish candlestick's body. |
//+------------------------------------------------------------------+
bool ChartDownColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of down bar, its shadow and border of bearish candlestick's body
if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_DOWN,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_CHART_LINE color of the chart line and Doji candlesticks.
//+------------------------------------------------------------------------+
//| The function receives color of the chart line and Doji candlesticks. |
//+------------------------------------------------------------------------+
color ChartLineColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive color of the chart line and Doji candlesticks
if(!ChartGetInteger(chart_ID,CHART_COLOR_CHART_LINE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets the color of the chart line and Doji |
//| candlesticks. |
//+------------------------------------------------------------------+
bool ChartLineColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set color of the chart line and Doji candlesticks
if(!ChartSetInteger(chart_ID,CHART_COLOR_CHART_LINE,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_CANDLE_BULL color of bullish candlestick's body.
//+------------------------------------------------------------------+
//| The function receives color of bullish candlestick's body. |
//+------------------------------------------------------------------+
color ChartBullColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of bullish candlestick's body
if(!ChartGetInteger(chart_ID,CHART_COLOR_CANDLE_BULL,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets color of bullish candlestick's body. |
//+------------------------------------------------------------------+
bool ChartBullColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of bullish candlestick's body
if(!ChartSetInteger(chart_ID,CHART_COLOR_CANDLE_BULL,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_CANDLE_BEAR color of bearish candlestick's body.
//+------------------------------------------------------------------+
//| The function receives color of bearish candlestick's body. |
//+------------------------------------------------------------------+
color ChartBearColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of bearish candlestick's body
if(!ChartGetInteger(chart_ID,CHART_COLOR_CANDLE_BEAR,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets color of bearish candlestick's body. |
//+------------------------------------------------------------------+
bool ChartBearColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of bearish candlestick's body
if(!ChartSetInteger(chart_ID,CHART_COLOR_CANDLE_BEAR,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_BID Bid price line color.
//+------------------------------------------------------------------+
//| The function receives the color of Bid line. |
//+------------------------------------------------------------------+
color ChartBidColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of Bid price line
if(!ChartGetInteger(chart_ID,CHART_COLOR_BID,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets the color of Bid line. |
//+------------------------------------------------------------------+
bool ChartBidColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of Bid price line
if(!ChartSetInteger(chart_ID,CHART_COLOR_BID,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_ASK Ask price line color.
//+------------------------------------------------------------------+
//| The function receives the color of Ask line. |
//+------------------------------------------------------------------+
color ChartAskColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of Ask price line
if(!ChartGetInteger(chart_ID,CHART_COLOR_ASK,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets the color of Ask line. |
//+------------------------------------------------------------------+
bool ChartAskColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of Ask price line
if(!ChartSetInteger(chart_ID,CHART_COLOR_ASK,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_LAST color of the last performed deal's price line (Last).
//+----------------------------------------------------------------------+
//| The function receives color of the last performed deal's price line. |
//+----------------------------------------------------------------------+
color ChartLastColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive color of the last performed deal's price line (Last)
if(!ChartGetInteger(chart_ID,CHART_COLOR_LAST,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets color of the last performed deal's price |
//| line. |
//+------------------------------------------------------------------+
bool ChartLastColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set color of the last performed deal's price line (Last)
if(!ChartSetInteger(chart_ID,CHART_COLOR_LAST,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_COLOR_STOP_LEVEL stop order level color (Stop Loss and Take Profit).
//+--------------------------------------------------------------------+
//| The function receives colors of Stop Loss and Take Profit levels. |
//+--------------------------------------------------------------------+
color ChartStopLevelColorGet(const long chart_ID=0)
{
//--- prepare the variable to receive the color
long result=clrNONE;
//--- reset the error value
ResetLastError();
//--- receive the color of stop order levels (Stop Loss and Take Profit)
if(!ChartGetInteger(chart_ID,CHART_COLOR_STOP_LEVEL,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return((color)result);
}
//+------------------------------------------------------------------+
//| The function sets Stop Loss and Take Profit level colors. |
//+------------------------------------------------------------------+
bool ChartStopLevelColorSet(const color clr,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set the color of stop order levels (Stop Loss and Take Profit)
if(!ChartSetInteger(chart_ID,CHART_COLOR_STOP_LEVEL,clr))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_TRADE_LEVELS property of displaying trade levels on the chart (levels
of open orders, Stop Loss, Take Profit and pending orders).
//+---------------------------------------------------------------------+
//| The function defines if trading levels are displayed on the chart. |
//+---------------------------------------------------------------------+
bool ChartShowTradeLevelsGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function enables/disables trading levels display mode. |
//+------------------------------------------------------------------+
bool ChartShowTradeLevelsSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_DRAG_TRADE_LEVELS property of enabling the ability to drag trading levels
on a chart using mouse.
//+---------------------------------------------------------------------------+
//| The function defines if dragging trading levels on a chart using mouse |
//| is allowed. |
//+---------------------------------------------------------------------------+
bool ChartDragTradeLevelsGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_DRAG_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function enables/disables the mode of dragging trade levels |
//| on the chart using mouse. |
//+------------------------------------------------------------------+
bool ChartDragTradeLevelsSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_DRAG_TRADE_LEVELS,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_DATE_SCALE property of displaying the time scale on a chart.
//+--------------------------------------------------------------------+
//| The function defines if the time scale is displayed on the chart. |
//+--------------------------------------------------------------------+
bool ChartShowDateScaleGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_DATE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+-----------------------------------------------------------------------------+
//| The function enables/disables the mode of displaying the time scale on a |
//| chart. |
//+-----------------------------------------------------------------------------+
bool ChartShowDateScaleSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_DATE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHOW_PRICE_SCALE property of displaying the price scale on a chart.
//+--------------------------------------------------------------------+
//| The function defines if the price scale is displayed on the chart. |
//+--------------------------------------------------------------------+
bool ChartShowPriceScaleGet(bool &result,const long chart_ID=0)
{
//--- prepare the variable to get the property value
long value;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetInteger(chart_ID,CHART_SHOW_PRICE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- store the value of the chart property in memory
result=value;
//--- successful execution
return(true);
}
//+----------------------------------------------------------------------------+
//| The function enables/disables the mode of displaying the price scale on a |
//| chart. |
//+----------------------------------------------------------------------------+
bool ChartShowPriceScaleSet(const bool value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetInteger(chart_ID,CHART_SHOW_PRICE_SCALE,0,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_SHIFT_SIZE shift size of the zero bar from the right border in percentage
values.
//+---------------------------------------------------------------------------+
//| The function receives shift size of the zero bar from the right border |
//| of the chart in percentage values (from 10% up to 50%). |
//+---------------------------------------------------------------------------+
double ChartShiftSizeGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_SHIFT_SIZE,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+----------------------------------------------------------------------------------
//| The function sets the shift size of the zero bar from the right
//| border of the chart in percentage values (from 10% up to 50%). To enable the shif
//| mode, CHART_SHIFT property value should be set to
//| true.
//+----------------------------------------------------------------------------------
bool ChartShiftSizeSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_SHIFT_SIZE,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_IS_OFFLINE checks offline mode of the chart.
//+------------------------------------------------------------------+
//| The function checks offline mode of the chart |
//+------------------------------------------------------------------+
bool CheckChartOffline(const long chart_ID=0)
{
bool offline=ChartGetInteger(chart_ID,CHART_IS_OFFLINE);
return(offline);
}
CHART_FIXED_POSITION chart fixed position from the left border in percentage
value.
//+--------------------------------------------------------------------------+
//| The function receives the location of the chart fixed position from the |
//| left border in percentage value. |
//+--------------------------------------------------------------------------+
double ChartFixedPositionGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_FIXED_POSITION,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+---------------------------------------------------------------------+
//| The function sets the location of the chart fixed position from the |
//| left border in percentage value. To view the location of the |
//| chart fixed position, the value of |
//| CHART_AUTOSCROLL property should be set to false. |
//+---------------------------------------------------------------------+
bool ChartFixedPositionSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_FIXED_POSITION,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_FIXED_MAX property of the chart's fixed maximum.
//+------------------------------------------------------------------+
//| The function receives the value of chart's fixed maximum. |
//+------------------------------------------------------------------+
double ChartFixedMaxGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_FIXED_MAX,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+------------------------------------------------------------------+
//| The function sets the value of chart's fixed maximum. |
//| To change the value of the property, |
//| CHART_SCALEFIX property value should be preliminarily set to |
//| true. |
//+------------------------------------------------------------------+
bool ChartFixedMaxSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_FIXED_MAX,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_FIXED_MIN property of the chart's fixed minimum.
//+------------------------------------------------------------------+
//| The function receives the value of chart's fixed minimum. |
//+------------------------------------------------------------------+
double ChartFixedMinGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_FIXED_MIN,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+------------------------------------------------------------------+
//| The function sets the value of chart's fixed minimum. |
//| To change the value of the property, |
//| CHART_SCALEFIX property value should be preliminarily set to |
//| true. |
//+------------------------------------------------------------------+
bool ChartFixedMinSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_FIXED_MIN,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_POINTS_PER_BAR value of scale in points per bar.
//+---------------------------------------------------------------------------+
//| The function receives the value of the chart scale in points per bar. |
//+---------------------------------------------------------------------------+
double ChartPointsPerBarGet(const long chart_ID=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_POINTS_PER_BAR,0,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
//+----------------------------------------------------------------------+
//| The function sets the value of the chart scale in points per bar. |
//| To view the result of this property's value change, |
//| the value of |
//| CHART_SCALE_PT_PER_BAR property should be preliminarily set to true. |
//+----------------------------------------------------------------------+
bool ChartPointsPerBarSet(const double value,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetDouble(chart_ID,CHART_POINTS_PER_BAR,value))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
CHART_PRICE_MIN returns the value of the chart minimum.
//+---------------------------------------------------------------------------------+
//| The function receives the value of the chart minimum in the main window or a |
//| subwindow. |
//+---------------------------------------------------------------------------------+
double ChartPriceMin(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_PRICE_MIN,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
CHART_PRICE_MAX returns the value of the chart maximum.
//+--------------------------------------------------------------------------------+
//| The function receives the value of the chart maximum in the main window or a |
//| subwindow. |
//+--------------------------------------------------------------------------------+
double ChartPriceMax(const long chart_ID=0,const int sub_window=0)
{
//--- prepare the variable to get the result
double result=EMPTY_VALUE;
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetDouble(chart_ID,CHART_PRICE_MAX,sub_window,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
}
//--- return the value of the chart property
return(result);
}
CHART_COMMENT comment on the chart.
//+----------------------------------------------------------------------+
//| The function receives comment in the upper left corner of the chart. |
//+----------------------------------------------------------------------+
bool ChartCommentGet(string &result,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- receive the property value
if(!ChartGetString(chart_ID,CHART_COMMENT,result))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function sets comment in the upper left corner of the |
//| chart. |
//+------------------------------------------------------------------+
bool ChartCommentSet(const string str,const long chart_ID=0)
{
//--- reset the error value
ResetLastError();
//--- set property value
if(!ChartSetString(chart_ID,CHART_COMMENT,str))
{
//--- display the error message in Experts journal
Print(__FUNCTION__+", Error Code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
Panel for chart properties
//--- connect the library of control elements
#include <ChartObjects\ChartObjectsTxtControls.mqh>
//--- predefined constants
#define X_PROPERTY_NAME_1 10 // х coordinate of the property name in the first co
#define X_PROPERTY_VALUE_1 225 // х coordinate of the property value in the first c
#define X_PROPERTY_NAME_2 345 // х coordinate of the property name in the second a
#define X_PROPERTY_VALUE_2 550 // х coordinate of the property value in the second
#define X_BUTTON_1 285 // х coordinate of the button in the first column
#define X_BUTTON_2 700 // х coordinate of the button in the second column
#define Y_PROPERTY_1 30 // y coordinate of the beginning of the first and se
#define Y_PROPERTY_2 286 // y coordinate of the beginning of the third column
#define Y_DISTANCE 16 // y axial distance between the lines
#define LAST_PROPERTY_NUMBER 111 // number of the last graphical property
//--- input parameters
input color InpFirstColor=clrDodgerBlue; // Color of odd lines
input color InpSecondColor=clrGoldenrod; // Color of even lines
//--- variables and arrays
CChartObjectLabel ExtLabelsName[]; // labels for displaying property names
CChartObjectLabel ExtLabelsValue[]; // labels for displaying property values
CChartObjectButton ExtButtons[]; // buttons
int ExtNumbers[]; // property indices
string ExtNames[]; // property names
uchar ExtDataTypes[]; // property data types (integer, double, string)
uint ExtGroupTypes[]; // array that stores the data on belonging of pr
uchar ExtDrawTypes[]; // array that stores the data on the type of pro
double ExtMaxValue[]; // maximum property values that are possible whe
double ExtMinValue[]; // minimum property values that are possible whe
double ExtStep[]; // steps for changing properties
int ExtCount; // total number of all properties
color ExtColors[2]; // array of colors for displaying lines
string ExtComments[2]; // array of comments (for CHART_COMMENT property
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- display a comment on the chart
Comment("SomeComment");
//--- store colors in the array to be able to switch between them later
ExtColors[0]=InpFirstColor;
ExtColors[1]=InpSecondColor;
//--- store comments in the array to be able to switch between them later
ExtComments[0]="FirstComment";
ExtComments[1]="SecondComment";
//--- prepare and display the control panel for managing chart properties
if(!PrepareControls())
return(INIT_FAILED);
//--- successful execution
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Deinitialization function of the expert |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- remove the comment on the chart
Comment("");
}
//+------------------------------------------------------------------+
//| Handler of a chart event |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- check the event of clicking the chart object
if(id==CHARTEVENT_OBJECT_CLICK)
{
//--- divide the object name by separator
string obj_name[];
StringSplit(sparam,'_',obj_name);
//--- check if the object is a button
if(obj_name[0]=="Button")
{
//--- receive button index
int index=(int)StringToInteger(obj_name[1]);
//--- unpress the button
ExtButtons[index].State(false);
//--- set the new value of the property depending on its type
if(ExtDataTypes[index]=='I')
ChangeIntegerProperty(index);
if(ExtDataTypes[index]=='D')
ChangeDoubleProperty(index);
if(ExtDataTypes[index]=='S')
ChangeStringProperty(index);
}
}
//--- re-draw property values
RedrawProperties();
ChartRedraw();
}
//+------------------------------------------------------------------+
//| Change the integer property of the chart |
//+------------------------------------------------------------------+
void ChangeIntegerProperty(const int index)
{
//--- receive the current property value
long value=ChartGetInteger(0,(ENUM_CHART_PROPERTY_INTEGER)ExtNumbers[index]);
//--- define the following property value
switch(ExtDrawTypes[index])
{
case 'C':
value=GetNextColor((color)value);
break;
default:
value=(long)GetNextValue((double)value,index);
break;
}
//--- set the new property value
ChartSetInteger(0,(ENUM_CHART_PROPERTY_INTEGER)ExtNumbers[index],0,value);
}
//+------------------------------------------------------------------+
//| Change double property of the chart |
//+------------------------------------------------------------------+
void ChangeDoubleProperty(const int index)
{
//--- receive the current property value
double value=ChartGetDouble(0,(ENUM_CHART_PROPERTY_DOUBLE)ExtNumbers[index]);
//--- define the following property value
value=GetNextValue(value,index);
//--- set the new property value
ChartSetDouble(0,(ENUM_CHART_PROPERTY_DOUBLE)ExtNumbers[index],value);
}
//+------------------------------------------------------------------+
//| Change string property of the chart |
//+------------------------------------------------------------------+
void ChangeStringProperty(const int index)
{
//--- static variable for switching inside ExtComments array
static uint comment_index=1;
//--- change index for receiving another comment
comment_index=1-comment_index;
//--- set the new property value
ChartSetString(0,(ENUM_CHART_PROPERTY_STRING)ExtNumbers[index],ExtComments[comment
}
//+------------------------------------------------------------------+
//| Define the next property value |
//+------------------------------------------------------------------+
double GetNextValue(const double value,const int index)
{
if(value+ExtStep[index]<=ExtMaxValue[index])
return(value+ExtStep[index]);
else
return(ExtMinValue[index]);
}
//+------------------------------------------------------------------+
//| Receive the next color for color type property |
//+------------------------------------------------------------------+
color GetNextColor(const color clr)
{
//--- return the following color value
switch(clr)
{
case clrWhite: return(clrRed);
case clrRed: return(clrGreen);
case clrGreen: return(clrBlue);
case clrBlue: return(clrBlack);
default: return(clrWhite);
}
}
//+------------------------------------------------------------------+
//| Re-draw property values |
//+------------------------------------------------------------------+
void RedrawProperties(void)
{
//--- property value text
string text;
long value;
//--- loop of the number of properties
for(int i=0;i<ExtCount;i++)
{
text="";
switch(ExtDataTypes[i])
{
case 'I':
//--- receive the current property value
if(!ChartGetInteger(0,(ENUM_CHART_PROPERTY_INTEGER)ExtNumbers[i],0,value)
break;
//--- integer property text
switch(ExtDrawTypes[i])
{
//--- color property
case 'C':
text=(string)((color)value);
break;
//--- boolean property
case 'B':
text=(string)((bool)value);
break;
//--- ENUM_CHART_MODE enumeration property
case 'M':
text=EnumToString((ENUM_CHART_MODE)value);
break;
//--- ENUM_CHART_VOLUME_MODE enumeration property
case 'V':
text=EnumToString((ENUM_CHART_VOLUME_MODE)value);
break;
//--- int type number
default:
text=IntegerToString(value);
break;
}
break;
case 'D':
//--- double property text
text=DoubleToString(ChartGetDouble(0,(ENUM_CHART_PROPERTY_DOUBLE)ExtNumbe
break;
case 'S':
//--- string property text
text=ChartGetString(0,(ENUM_CHART_PROPERTY_STRING)ExtNumbers[i]);
break;
}
//--- display property value
ExtLabelsValue[i].Description(text);
}
}
//+------------------------------------------------------------------+
//| Create the panel for managing chart properties |
//+------------------------------------------------------------------+
bool PrepareControls(void)
{
//--- allocate memory for arrays with a reserve
MemoryAllocation(LAST_PROPERTY_NUMBER+1);
//--- variables
int i=0; // loop variable
int col_1=0; // number of properties in the first column
int col_2=0; // number of properties in the second column
int col_3=0; // number of properties in the third column
//--- current number of properties - 0
ExtCount=0;
//--- looking for properties in the loop
while(i<=LAST_PROPERTY_NUMBER)
{
//--- store the current number of the property
ExtNumbers[ExtCount]=i;
//--- increase the value of the loop variable
i++;
//--- check if there is a property with such a number
if(CheckNumber(ExtNumbers[ExtCount],ExtNames[ExtCount],ExtDataTypes[ExtCount],E
{
//--- create control elements for the property
switch(ExtGroupTypes[ExtCount])
{
case 1:
//--- create labels and a button for the property
if(!ShowProperty(ExtCount,0,X_PROPERTY_NAME_1,X_PROPERTY_VALUE_1,X_BUT
return(false);
//--- number of the elements in the first column has increased
col_1++;
break;
case 2:
//--- create labels and a button for the property
if(!ShowProperty(ExtCount,1,X_PROPERTY_NAME_2,X_PROPERTY_VALUE_2,X_BUT
return(false);
//--- number of the elements in the second column has increased
col_2++;
break;
case 3:
//--- create only labels for the property
if(!ShowProperty(ExtCount,2,X_PROPERTY_NAME_2,X_PROPERTY_VALUE_2,0,Y_P
return(false);
//--- number of the elements in the third column has increased
col_3++;
break;
}
//--- define maximum and minimum property value and step
GetMaxMinStep(ExtNumbers[ExtCount],ExtMaxValue[ExtCount],ExtMinValue[ExtCoun
//--- increase the number of properties
ExtCount++;
}
}
//--- free the memory not used by arrays
MemoryAllocation(ExtCount);
//--- re-draw property values
RedrawProperties();
ChartRedraw();
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Allocate memory for arrays |
//+------------------------------------------------------------------+
void MemoryAllocation(const int size)
{
ArrayResize(ExtLabelsName,size);
ArrayResize(ExtLabelsValue,size);
ArrayResize(ExtButtons,size);
ArrayResize(ExtNumbers,size);
ArrayResize(ExtNames,size);
ArrayResize(ExtDataTypes,size);
ArrayResize(ExtGroupTypes,size);
ArrayResize(ExtDrawTypes,size);
ArrayResize(ExtMaxValue,size);
ArrayResize(ExtMinValue,size);
ArrayResize(ExtStep,size);
}
//+------------------------------------------------------------------+
//| Check if the property index belongs to the one of |
//| ENUM_CHART_PROPERTIES enumerations |
//+------------------------------------------------------------------+
bool CheckNumber(const int ind,string &name,uchar &data_type,uint &group_type,uchar &
{
//--- check if the property is of integer type
ResetLastError();
name=EnumToString((ENUM_CHART_PROPERTY_INTEGER)ind);
if(_LastError==0)
{
data_type='I'; // property from ENUM_CHART_PROPERTY_INTEGE
GetTypes(ind,group_type,draw_type); // define property display parameters
return(true);
}
//--- check if the property is of double type
ResetLastError();
name=EnumToString((ENUM_CHART_PROPERTY_DOUBLE)ind);
if(_LastError==0)
{
data_type='D'; // property from ENUM_CHART_PROPERTY_DOUBLE
GetTypes(ind,group_type,draw_type); // define property display parameters
return(true);
}
//--- check if the property is of string type
ResetLastError();
name=EnumToString((ENUM_CHART_PROPERTY_STRING)ind);
if(_LastError==0)
{
data_type='S'; // property from ENUM_CHART_PROPERTY_STRING
GetTypes(ind,group_type,draw_type); // define property display parameters
return(true);
}
//--- property does not belong to any enumeration
return(false);
}
//+------------------------------------------------------------------+
//| Define the group the property should be stored in, |
//| as well as its display type |
//+------------------------------------------------------------------+
void GetTypes(const int property_number,uint &group_type,uchar &draw_type)
{
//--- check if the property belongs to the third group
//--- third group properties are displayed in the second column starting from CHART_B
if(CheckThirdGroup(property_number,group_type,draw_type))
return;
//--- check if the property belongs to the second group
//--- second group properties are displayed at the beginning of the second column
if(CheckSecondGroup(property_number,group_type,draw_type))
return;
//--- if you find yourself here, the property belongs to the first group (first colum
CheckFirstGroup(property_number,group_type,draw_type);
}
//+----------------------------------------------------------------------+
//| The function checks if the property belongs to the third group and |
//| defines its display type in case of a positive answer |
//+----------------------------------------------------------------------+
bool CheckThirdGroup(const int property_number,uint &group_type,uchar &draw_type)
{
//--- check if the property belongs to the third group
switch(property_number)
{
//--- boolean properties
case CHART_WINDOW_IS_VISIBLE:
draw_type='B';
break;
//--- integer properties
case CHART_VISIBLE_BARS:
case CHART_WINDOWS_TOTAL:
case CHART_WINDOW_HANDLE:
case CHART_WINDOW_YDISTANCE:
case CHART_FIRST_VISIBLE_BAR:
case CHART_WIDTH_IN_BARS:
case CHART_WIDTH_IN_PIXELS:
draw_type='I';
break;
//--- double properties
case CHART_PRICE_MIN:
case CHART_PRICE_MAX:
draw_type='D';
break;
//--- in fact, this property is a command of displaying the chart on top of
//--- there is no need to apply this panel, as the window will always be
//--- on top of other ones before we use it
case CHART_BRING_TO_TOP:
draw_type=' ';
break;
//--- property does not belong to the third group
default:
return(false);
}
//--- property belongs to the third group
group_type=3;
return(true);
}
//+----------------------------------------------------------------------+
//| The function checks if the property belongs to the second group and |
//| defines its display type in case of a positive answer |
//+----------------------------------------------------------------------+
bool CheckSecondGroup(const int property_number,uint &group_type,uchar &draw_type)
{
//--- check if the property belongs to the second group
switch(property_number)
{
//--- ENUM_CHART_MODE type property
case CHART_MODE:
draw_type='M';
break;
//--- ENUM_CHART_VOLUME_MODE type property
case CHART_SHOW_VOLUMES:
draw_type='V';
break;
//--- string property
case CHART_COMMENT:
draw_type='S';
break;
//--- color property
case CHART_COLOR_BACKGROUND:
case CHART_COLOR_FOREGROUND:
case CHART_COLOR_GRID:
case CHART_COLOR_VOLUME:
case CHART_COLOR_CHART_UP:
case CHART_COLOR_CHART_DOWN:
case CHART_COLOR_CHART_LINE:
case CHART_COLOR_CANDLE_BULL:
case CHART_COLOR_CANDLE_BEAR:
case CHART_COLOR_BID:
case CHART_COLOR_ASK:
case CHART_COLOR_LAST:
case CHART_COLOR_STOP_LEVEL:
draw_type='C';
break;
//--- property does not belong to the second group
default:
return(false);
}
//--- property belongs to the second group
group_type=2;
return(true);
}
//+-----------------------------------------------------------------------+
//| This function is called only if it is already known that |
//| the property does not belong to the second and third property groups |
//+-----------------------------------------------------------------------+
void CheckFirstGroup(const int property_number,uint &group_type,uchar &draw_type)
{
//--- the property belongs to the first group
group_type=1;
//--- define property display type
switch(property_number)
{
//--- integer properties
case CHART_SCALE:
case CHART_HEIGHT_IN_PIXELS:
draw_type='I';
return;
//--- double properties
case CHART_SHIFT_SIZE:
case CHART_FIXED_POSITION:
case CHART_FIXED_MAX:
case CHART_FIXED_MIN:
case CHART_POINTS_PER_BAR:
draw_type='D';
return;
//--- only boolean properties have remained
default:
draw_type='B';
return;
}
}
//+------------------------------------------------------------------+
//| Create a label and a button for the property |
//+------------------------------------------------------------------+
bool ShowProperty(const int ind,const int type,const int x1,const int x2,
const int xb,const int y,const bool btn)
{
//--- static array for switching inside ExtColors color array
static uint color_index[3]={1,1,1};
//--- change index for receiving another color
color_index[type]=1-color_index[type];
//--- display labels and a button (if btn=true) for the property
if(!LabelCreate(ExtLabelsName[ind],"name_"+(string)ind,ExtNames[ind],ExtColors[col
return(false);
if(!LabelCreate(ExtLabelsValue[ind],"value_"+(string)ind,"",ExtColors[color_index[
return(false);
if(btn && !ButtonCreate(ExtButtons[ind],(string)ind,xb,y+1))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create a label |
//+------------------------------------------------------------------+
bool LabelCreate(CChartObjectLabel &lbl,const string name,const string text,
const color clr,const int x,const int y)
{
if(!lbl.Create(0,"Label_"+name,0,x,y)) return(false);
if(!lbl.Description(text)) return(false);
if(!lbl.FontSize(10)) return(false);
if(!lbl.Color(clr)) return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create the button |
//+------------------------------------------------------------------+
bool ButtonCreate(CChartObjectButton &btn,const string name,
const int x,const int y)
{
if(!btn.Create(0,"Button_"+name,0,x,y,50,15)) return(false);
if(!btn.Description("Next")) return(false);
if(!btn.FontSize(10)) return(false);
if(!btn.Color(clrBlack)) return(false);
if(!btn.BackColor(clrWhite)) return(false);
if(!btn.BorderColor(clrBlack)) return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Define maximum and minimum property value and step |
//+------------------------------------------------------------------+
void GetMaxMinStep(const int property_number,double &max,double &min,double &step)
{
double value;
//--- set values depending on the property type
switch(property_number)
{
case CHART_SCALE:
max=5;
min=0;
step=1;
break;
case CHART_MODE:
case CHART_SHOW_VOLUMES:
max=2;
min=0;
step=1;
break;
case CHART_SHIFT_SIZE:
max=50;
min=10;
step=2.5;
break;
case CHART_FIXED_POSITION:
max=90;
min=0;
step=15;
break;
case CHART_POINTS_PER_BAR:
max=19;
min=1;
step=3;
break;
case CHART_FIXED_MAX:
value=ChartGetDouble(0,CHART_FIXED_MAX);
max=value*1.25;
min=value;
step=value/32;
break;
case CHART_FIXED_MIN:
value=ChartGetDouble(0,CHART_FIXED_MIN);
max=value;
min=value*0.75;
step=value/32;
break;
case CHART_HEIGHT_IN_PIXELS:
max=700;
min=520;
step=30;
break;
//--- default values
default:
max=1;
min=0;
step=1;
}
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants
Object Constants
There are 40 graphical objects that can be created and displayed
in the price chart. All constants for working with objects are
divided into 9 groups:
Object types Identifiers of graphical objects;
Object properties setting and getting properties of graphical
objects;
Methods of object binding constants of object positioning in the
chart;
Binding corner setting the corner relative to which an object is
positioned on chart;
Visibility of objects setting timeframes in which an object is
visible;
Gann objects trend constants for Gann fan and Gann grid;
Web colors constants of predefined web colors;
Wingdings codes of characters of the Wingdings font.
What's new in MQL5
Added new objects and analytical tools. The most notable of them
is the OBJ_CHART graphical object which is actually a full-fledged
chart. It allows creating an unlimited number of nested charts, set
all the necessary properties (color scheme, timeframe, symbol)
and even impose indicators on them.
Added new properties allowing you to manage a chart object
location and visibility more accurately.
ID Description Property Type
ID Description Property Type
Fill an object with
color (for
OBJ_RECTANGLE,
OBJ_TRIANGLE,
OBJ_ELLIPSE,
OBJ_CHANNEL,
OBJPROP_FILL bool
OBJ_STDDEVCHANNEL,
OBJ_REGRESSION)
OBJ_ELLIPSE,
OBJ_CHANNEL,
OBJ_STDDEVCHANNEL,
OBJ_REGRESSION)
OBJPROP_SELECTABLE Object availability bool
Time of object
OBJPROP_CREATETIME datetime r/o
creation
OBJPROP_RAY_LEFT Ray goes to the left bool
Location of the anchor
ENUM_ARROW_ANCHOR
OBJPROP_ANCHOR point of a graphical
ENUM_ANCHOR_POINT
object
Button state (pressed
OBJPROP_STATE bool
/ depressed))
ID of the "Chart"
object (OBJ_CHART).
It allows working with
the properties of this
OBJPROP_CHART_ID object like with a long r/o
normal chart using the
functions described in
Chart Operations, but
there some exceptions
Timeframe for the
OBJPROP_PERIOD ENUM_TIMEFRAMES
Chart object
Displaying the time
OBJPROP_DATE_SCALE scale for the Chart bool
object
ID Description Property Type
Displaying the price
OBJPROP_PRICE_SCALE scale for the Chart bool
object
The scale for the int value in the range
OBJPROP_CHART_SCALE
Chart object 0-5
MQL4 Reference / Constants, Enumerations and Structures / Objects
Constants / Object Types
Object Types
When a graphical object is created using the
ObjectCreate() function, it's necessary to specify the type
of object being created, which can be one of the values
of the ENUM_OBJECT enumeration. Object type identifiers
are used in ObjectCreate(), ObjectsDeleteAll() and
ObjectType() functions.
Further specifications of object properties are possible
using functions for working with graphical objects.
ENUM_OBJECT
ID Description
OBJ_VLINE Vertical Line
OBJ_HLINE Horizontal Line
OBJ_TREND Trend Line
OBJ_TRENDBYANGLE Trend Line By Angle
OBJ_CYCLES Cycle Lines
OBJ_CHANNEL Equidistant Channel
OBJ_STDDEVCHANNEL Standard Deviation Channel
OBJ_REGRESSION Linear Regression Channel
OBJ_PITCHFORK Andrews Pitchfork
OBJ_GANNLINE Gann Line
OBJ_GANNFAN Gann Fan
OBJ_GANNGRID Gann Grid
ID Description
OBJ_FIBO Fibonacci Retracement
OBJ_FIBOTIMES Fibonacci Time Zones
OBJ_FIBOFAN Fibonacci Fan
OBJ_FIBOARC Fibonacci Arcs
OBJ_FIBOCHANNEL Fibonacci Channel
OBJ_EXPANSION Fibonacci Expansion
OBJ_RECTANGLE Rectangle
OBJ_TRIANGLE Triangle
OBJ_ELLIPSE Ellipse
OBJ_ARROW_THUMB_UP Thumbs Up
OBJ_ARROW_THUMB_DOWN Thumbs Down
OBJ_ARROW_UP Arrow Up
OBJ_ARROW_DOWN Arrow Down
OBJ_ARROW_STOP Stop Sign
OBJ_ARROW_CHECK Check Sign
OBJ_ARROW_LEFT_PRICE Left Price Label
OBJ_ARROW_RIGHT_PRICE Right Price Label
OBJ_ARROW_BUY Buy Sign
OBJ_ARROW_SELL Sell Sign
OBJ_ARROW Arrow
OBJ_TEXT Text
OBJ_LABEL Label
OBJ_BUTTON Button
ID Description
OBJ_BITMAP Bitmap
OBJ_BITMAP_LABEL Bitmap Label
OBJ_EDIT Edit
OBJ_EVENT The "Event" object
corresponding to an event in
the economic calendar
OBJ_RECTANGLE_LABEL The "Rectangle label" object
for creating and designing
the custom graphical
interface.
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_VLINE
OBJ_VLINE
Vertical Line.
Example
The following script creates and moves the vertical line on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Vertical Line\" graphical object."
#property description "Anchor point date is set in percentage of"
#property description "the chart window width in bars."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="VLine"; // Line name
input int InpDate=25; // Event date, %
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style
input int InpWidth=1; // Line width
input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the vertical line |
//+------------------------------------------------------------------+
bool VLineCreate(const long chart_ID=0, // chart's ID
const string name="VLine", // line name
const int sub_window=0, // subwindow index
datetime time=0, // line time
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object lis
const long z_order=0) // priority for mouse click
{
//--- if the line time is not set, draw it via the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- create a vertical line
if(!ObjectCreate(chart_ID,name,OBJ_VLINE,sub_window,time,0))
{
Print(__FUNCTION__,
": failed to create a vertical line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the vertical line |
//+------------------------------------------------------------------+
bool VLineMove(const long chart_ID=0, // chart's ID
const string name="VLine", // line name
datetime time=0) // line time
{
//--- if line time is not set, move the line to the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the vertical line
if(!ObjectMove(chart_ID,name,0,time,0))
{
Print(__FUNCTION__,
": failed to move the vertical line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the vertical line |
//+------------------------------------------------------------------+
bool VLineDelete(const long chart_ID=0, // chart's ID
const string name="VLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete the vertical line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the vertical line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- array for storing the date values to be used
//--- for setting and changing line anchor point's coordinates
datetime date[];
//--- memory allocation
ArrayResize(date,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- define points for drawing the line
int d=InpDate*(bars-1)/100;
//--- create a vertical line
if(!VLineCreate(0,InpName,0,date[d],InpColor,InpStyle,InpWidth,InpBack,
InpSelection,InpHidden,InpZOrder))
return;
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line
//--- loop counter
int h_steps=bars/2;
//--- move the line
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!VLineMove(0,InpName,date[d]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.03 seconds of delay
Sleep(30);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
VLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_HLINE
OBJ_HLINE
Horizontal Line.
Example
The following script creates and moves the horizontal line on the chart. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Horizontal Line\" graphical object."
#property description "Anchor point price is set in percentage of the height of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="HLine"; // Line name
input int InpPrice=25; // Line price, %
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style
input int InpWidth=1; // Line width
input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the horizontal line |
//+------------------------------------------------------------------+
bool HLineCreate(const long chart_ID=0, // chart's ID
const string name="HLine", // line name
const int sub_window=0, // subwindow index
double price=0, // line price
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object lis
const long z_order=0) // priority for mouse click
{
//--- if the price is not set, set it at the current Bid price level
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- create a horizontal line
if(!ObjectCreate(chart_ID,name,OBJ_HLINE,sub_window,0,price))
{
Print(__FUNCTION__,
": failed to create a horizontal line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move horizontal line |
//+------------------------------------------------------------------+
bool HLineMove(const long chart_ID=0, // chart's ID
const string name="HLine", // line name
double price=0) // line price
{
//--- if the line price is not set, move it to the current Bid price level
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move a horizontal line
if(!ObjectMove(chart_ID,name,0,0,price))
{
Print(__FUNCTION__,
": failed to move the horizontal line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete a horizontal line |
//+------------------------------------------------------------------+
bool HLineDelete(const long chart_ID=0, // chart's ID
const string name="HLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete a horizontal line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a horizontal line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- price array size
int accuracy=1000;
//--- array for storing the price values to be used
//--- for setting and changing line anchor point's coordinates
double price[];
//--- memory allocation
ArrayResize(price,accuracy);
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int p=InpPrice*(accuracy-1)/100;
//--- create a horizontal line
if(!HLineCreate(0,InpName,0,price[p],InpColor,InpStyle,InpWidth,InpBack,
InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line
//--- loop counter
int v_steps=accuracy/2;
//--- move the line
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!HLineMove(0,InpName,price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete from the chart
HLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_TREND
OBJ_TREND
Trend Line.
Note
For Trend Line, it is possible to specify the mode of continuation of its display to the
right (OBJPROP_RAY_RIGHT property).
Example
The following script creates and moves the trend line on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Trend Line\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Trend"; // Line name
input int InpDate1=35; // 1 st point's date, %
input int InpPrice1=60; // 1 st point's price, %
input int InpDate2=65; // 2 nd point's date, %
input int InpPrice2=40; // 2 nd point's price, %
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style
input int InpWidth=1; // Line width
input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpRayRight=false; // Line's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create a trend line by the given coordinates |
//+------------------------------------------------------------------+
bool TrendCreate(const long chart_ID=0, // chart's ID
const string name="TrendLine", // line name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_right=false, // line's continuation to t
const bool hidden=true, // hidden in the object lis
const long z_order=0) // priority for mouse click
{
//--- set anchor points' coordinates if they are not set
ChangeTrendEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create a trend line by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_TREND,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create a trend line! Error code = ",GetLastError());
return(false);
}
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the line's display
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move trend line anchor point |
//+------------------------------------------------------------------+
bool TrendPointChange(const long chart_ID=0, // chart's ID
const string name="TrendLine", // line name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move trend line's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function deletes the trend line from the chart. |
//+------------------------------------------------------------------+
bool TrendDelete(const long chart_ID=0, // chart's ID
const string name="TrendLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete a trend line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a trend line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of trend line's anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeTrendEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the secon
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, it is equal to the first point's one
if(!price2)
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing line anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create a trend line
if(!TrendCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,InpStyl
InpWidth,InpBack,InpSelection,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line's anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!TrendPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- move the second anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2<accuracy-1)
p2+=1;
//--- move the point
if(!TrendPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- half a second of delay
Sleep(500);
//--- loop counter
int h_steps=bars/2;
//--- move both anchor points horizontally at the same time
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2>1)
d2-=1;
//--- shift the points
if(!TrendPointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!TrendPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.03 seconds of delay
Sleep(30);
}
//--- 1 second of delay
Sleep(1000);
//--- delete a trend line
TrendDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_TRENDBYANGLE
OBJ_TRENDBYANGLE
Trend Line By Angle.
Note
For Trend Line By Angle, it is possible to specify the mode of continuation of its display
to the right (OBJPROP_RAY_RIGHT property).
Both angle and the second anchor point's coordinates can be used to set the slope of
the line.
Example
The following script creates and moves the trend line on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Trend Line By Angle\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Trend"; // Line name
input int InpDate1=50; // 1 st point's date, %
input int InpPrice1=75; // 1 st point's price, %
input int InpAngle=0; // Line's slope angle
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Line style
input int InpWidth=1; // Line width
input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpRayRight=true; // Line's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create a trend line by angle |
//+------------------------------------------------------------------+
bool TrendByAngleCreate(const long chart_ID=0, // chart's ID
const string name="TrendLine", // line name
const int sub_window=0, // subwindow index
datetime time=0, // point time
double price=0, // point price
const double angle=45.0, // slope angle
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_right=true, // line's continuati
const bool hidden=true, // hidden in the obj
const long z_order=0) // priority for mous
{
//--- create the second point to facilitate dragging the trend line by mouse
datetime time2=0;
double price2=0;
//--- set anchor points' coordinates if they are not set
ChangeTrendEmptyPoints(time,price,time2,price2);
//--- reset the error value
ResetLastError();
//--- create a trend line using 2 points
if(!ObjectCreate(chart_ID,name,OBJ_TRENDBYANGLE,sub_window,time,price,time2,price2
{
Print(__FUNCTION__,
": failed to create a trend line! Error code = ",GetLastError());
return(false);
}
//--- change trend line's slope angle; when changing the angle, coordinates of the se
//--- point of the line are redefined automatically according to the angle's new valu
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the line by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the line's display
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change trend line anchor point's coordinates |
//+------------------------------------------------------------------+
bool TrendPointChange(const long chart_ID=0, // chart's ID
const string name="TrendLine", // line name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move trend line's anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change trend line's slope angle |
//+------------------------------------------------------------------+
bool TrendAngleChange(const long chart_ID=0, // chart's ID
const string name="TrendLine", // trend line name
const double angle=45) // trend line's slope angle
{
//--- reset the error value
ResetLastError();
//--- change trend line's slope angle
if(!ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle))
{
Print(__FUNCTION__,
": failed to change the line's slope angle! Error code = ",GetLastError()
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the trend line |
//+------------------------------------------------------------------+
bool TrendDelete(const long chart_ID=0, // chart's ID
const string name="TrendLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete a trend line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a trend line! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of trend line's anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeTrendEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- set coordinates of the second, auxiliary point
//--- the second point will be 9 bars left and have the same price
datetime second_point_time[10];
CopyTime(Symbol(),Period(),time1,10,second_point_time);
time2=second_point_time[0];
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing line anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the line
int d1=InpDate1*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create a trend line
if(!TrendByAngleCreate(0,InpName,0,date[d1],price[p1],InpAngle,InpColor,InpStyle,
InpWidth,InpBack,InpSelection,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move and rotate the line
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor point and change the line's slope angle
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!TrendPointChange(0,InpName,date[d1],price[p1]))
return;
if(!TrendAngleChange(0,InpName,18*(i+1)))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete from the chart
TrendDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_CYCLES
OBJ_CYCLES
Cycle Lines.
Note
The distance between the lines is set by time coordinates of two anchor points of the
object.
Example
The following script creates and moves cycle lines on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates cycle lines on the chart."
#property description "Anchor point coordinates are set in percentage"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Cycles"; // Object name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=45; // 1 st point's price, %
input int InpDate2=20; // 2 nd point's date, %
input int InpPrice2=55; // 2 nd point's price, %
input color InpColor=clrRed; // Color of cycle lines
input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Style of cycle lines
input int InpWidth=1; // Width of cycle lines
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create cycle lines |
//+------------------------------------------------------------------+
bool CyclesCreate(const long chart_ID=0, // chart's ID
const string name="Cycles", // object name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // color of cycle lines
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of cycle lines
const int width=1, // width of cycle lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object li
const long z_order=0) // priority for mouse clic
{
//--- set anchor points' coordinates if they are not set
ChangeCyclesEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create cycle lines by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_CYCLES,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create cycle lines! Error code = ",GetLastError());
return(false);
}
//--- set color of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set display style of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the lines by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool CyclesPointChange(const long chart_ID=0, // chart's ID
const string name="Cycles", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the cycle lines |
//+------------------------------------------------------------------+
bool CyclesDelete(const long chart_ID=0, // chart's ID
const string name="Cycles") // object name
{
//--- reset the error value
ResetLastError();
//--- delete cycle lines
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete cycle lines! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-----------------------------------------------------------------------+
//| Check the values of cycle lines' anchor points and set default values |
//| values for empty ones |
//+-----------------------------------------------------------------------+
void ChangeCyclesEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the secon
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, it is equal to the first point's one
if(!price2)
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of cycle lines' anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing cycle lines
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create a trend line
if(!CyclesCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int h_steps=bars/5;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!CyclesPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
h_steps=bars/4;
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1<bars-1)
d1+=1;
//--- move the point
if(!CyclesPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
CyclesDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_CHANNEL
OBJ_CHANNEL
Equidistant Channel
Note
For an equidistant channel, it is possible to specify the mode of its continuation to the
right (OBJPROP_RAY_RIGHT property). The mode of filling the channel with color can
also be set.
Example
The following script creates and moves an equidistant channel on the chart. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Equidistant Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Channel"; // Channel name
input int InpDate1=25; // 1 st point's date, %
input int InpPrice1=60; // 1 st point's price, %
input int InpDate2=65; // 2 nd point's date, %
input int InpPrice2=80; // 2 nd point's price, %
input int InpDate3=30; // 3 rd point's date, %
input int InpPrice3=40; // 3 rd point's date, %
input color InpColor=clrRed; // Channel color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Style of channel lines
input int InpWidth=1; // Channel line width
input bool InpBack=false; // Background channel
input bool InpFill=false; // Filling the channel with color
input bool InpSelection=true; // Highlight to move
input bool InpRayRight=false; // Channel's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create an equidistant channel by the given coordinates |
//+------------------------------------------------------------------+
bool ChannelCreate(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
const color clr=clrRed, // channel color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel lines
const int width=1, // width of channel lines
const bool fill=false, // filling the channel wi
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_right=false, // channel's continuation
const bool hidden=true, // hidden in the object l
const long z_order=0) // priority for mouse cli
{
//--- set anchor points' coordinates if they are not set
ChangeChannelEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_CHANNEL,sub_window,time1,price1,time2,price2,ti
{
Print(__FUNCTION__,
": failed to create an equidistant channel! Error code = ",GetLastError()
return(false);
}
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for movin
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the channel's disp
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the channel's anchor point |
//+------------------------------------------------------------------+
bool ChannelPointChange(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the channel |
//+------------------------------------------------------------------+
bool ChannelDelete(const long chart_ID=0, // chart's ID
const string name="Channel") // channel name
{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the channel! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Check the values of the channel's anchor points and set default values |
//| for empty ones |
//+-------------------------------------------------------------------------+
void ChangeChannelEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the second (right) point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 300 points higher than the secon
if(!price1)
price1=price2+300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the first point's one
if(!time3)
time3=time1;
//--- if the third point's price is not set, it is equal to the second point's one
if(!price3)
price3=price2;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create the equidistant channel
if(!ChannelCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],price
InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpRayRight,InpHidden,InpZOrder)
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the channel's anchor points
//--- loop counter
int h_steps=bars/6;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!ChannelPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1>1)
d1-=1;
//--- move the point
if(!ChannelPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/10;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3>1)
p3-=1;
//--- move the point
if(!ChannelPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
ChannelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_STDDEVCHANNEL
OBJ_STDDEVCHANNEL
Standard Deviation Channel.
Note
For Standard Deviation Channel, it is possible to specify the mode of continuation of its
display to the right (OBJPROP_RAY_RIGHT property). The mode of filling the channel
with color can also be set.
OBJPROP_DEVIATION property is used to change the value of the channel deviation.
Example
The following script creates and moves Standard Deviation Channel on the chart.
Special functions have been developed to create and change graphical object's
properties. You can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Standard Deviation Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="StdDevChannel"; // Channel name
input int InpDate1=10; // 1 st point's date, %
input int InpDate2=40; // 2 nd point's date, %
input double InpDeviation=1.0; // Deviation
input color InpColor=clrRed; // Channel color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of channel lines
input int InpWidth=1; // Width of channel lines
input bool InpFill=false; // Filling the channel with color
input bool InpBack=false; // Background channel
input bool InpSelection=true; // Highlight to move
input bool InpRayRight=false; // Channel's continuation to the rig
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create standard deviation channel by the given coordinates |
//+------------------------------------------------------------------+
bool StdDevChannelCreate(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
datetime time2=0, // second point tim
const double deviation=1.0, // deviation
const color clr=clrRed, // channel color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel
const int width=1, // width of channel
const bool fill=false, // filling the chan
const bool back=false, // in the backgroun
const bool selection=true, // highlight to mov
const bool ray_right=false, // channel's contin
const bool hidden=true, // hidden in the ob
const long z_order=0) // priority for mou
{
//--- set anchor points' coordinates if they are not set
ChangeChannelEmptyPoints(time1,time2);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_STDDEVCHANNEL,sub_window,time1,0,time2,0))
{
Print(__FUNCTION__,
": failed to create standard deviation channel! Error code = ",GetLastErr
return(false);
}
//--- set deviation value affecting the channel width
ObjectSetDouble(chart_ID,name,OBJPROP_DEVIATION,deviation);
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for movin
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the channel's disp
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the channel's anchor point |
//+------------------------------------------------------------------+
bool StdDevChannelPointChange(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const int point_index=0, // anchor point index
datetime time=0) // anchor point time coord
{
//--- if point time is not set, move the point to the current bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,0))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the channel's deviation |
//+------------------------------------------------------------------+
bool StdDevChannelDeviationChange(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const double deviation=1.0) // deviation
{
//--- reset the error value
ResetLastError();
//--- change trend line's slope angle
if(!ObjectSetDouble(chart_ID,name,OBJPROP_DEVIATION,deviation))
{
Print(__FUNCTION__,
": failed to change channel deviation! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the channel |
//+------------------------------------------------------------------+
bool StdDevChannelDelete(const long chart_ID=0, // chart's ID
const string name="Channel") // channel name
{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the channel! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Check the values of the channel's anchor points and set default values |
//| for empty ones |
//+-------------------------------------------------------------------------+
void ChangeChannelEmptyPoints(datetime &time1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
//--- create standard deviation channel
if(!StdDevChannelCreate(0,InpName,0,date[d1],date[d2],InpDeviation,InpColor,InpSty
InpWidth,InpFill,InpBack,InpSelection,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the channel horizontally to the right and expand it
//--- loop counter
int h_steps=bars/2;
//--- move the channel
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2<bars-1)
d2+=1;
//--- move the anchor points
if(!StdDevChannelPointChange(0,InpName,0,date[d1]))
return;
if(!StdDevChannelPointChange(0,InpName,1,date[d2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
double v_steps=InpDeviation*2;
//--- expand the channel
for(double i=InpDeviation;i<v_steps;i+=10.0/accuracy)
{
if(!StdDevChannelDeviationChange(0,InpName,i))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
StdDevChannelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_REGRESSION
OBJ_REGRESSION
Linear Regression Channel.
Note
For Linear Regression Channel, it is possible to specify the mode of continuation of its
display to the right (OBJPROP_RAY_RIGHT property). The mode of filling the channel
with color can also be set.
Example
The following script creates and moves Linear Regression Channel on the chart. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Linear Regression Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Regression"; // Channel name
input int InpDate1=10; // 1 st point's date, %
input int InpDate2=40; // 2 nd point's date, %
input color InpColor=clrRed; // Channel color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Style of channel lines
input int InpWidth=1; // Width of channel lines
input bool InpFill=false; // Filling the channel with color
input bool InpBack=false; // Background channel
input bool InpSelection=true; // Highlight to move
input bool InpRayRight=false; // Channel's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Linear Regression Channel by the given coordinates |
//+------------------------------------------------------------------+
bool RegressionCreate(const long chart_ID=0, // chart's ID
const string name="Regression", // channel name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
datetime time2=0, // second point time
const color clr=clrRed, // channel color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel li
const int width=1, // width of channel li
const bool fill=false, // filling the channel
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_right=false, // channel's continuat
const bool hidden=true, // hidden in the objec
const long z_order=0) // priority for mouse
{
//--- set anchor points' coordinates if they are not set
ChangeRegressionEmptyPoints(time1,time2);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_REGRESSION,sub_window,time1,0,time2,0))
{
Print(__FUNCTION__,
": failed to create linear regression channel! Error code = ",GetLastErro
return(false);
}
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for movin
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the channel's disp
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the channel's anchor point |
//+------------------------------------------------------------------+
bool RegressionPointChange(const long chart_ID=0, // chart's ID
const string name="Channel", // channel name
const int point_index=0, // anchor point index
datetime time=0) // anchor point time coordina
{
//--- if point time is not set, move the point to the current bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,0))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the channel |
//+------------------------------------------------------------------+
bool RegressionDelete(const long chart_ID=0, // chart's ID
const string name="Channel") // channel name
{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the channel! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+-------------------------------------------------------------------------+
//| Check the values of the channel's anchor points and set default values |
//| for empty ones |
//+-------------------------------------------------------------------------+
void ChangeRegressionEmptyPoints(datetime &time1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
//--- create linear regression channel
if(!RegressionCreate(0,InpName,0,date[d1],date[d2],InpColor,InpStyle,InpWidth,
InpFill,InpBack,InpSelection,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, the channel horizontally to the right
//--- loop counter
int h_steps=bars/2;
//--- move the channel
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2<bars-1)
d2+=1;
//--- move the anchor points
if(!RegressionPointChange(0,InpName,0,date[d1]))
return;
if(!RegressionPointChange(0,InpName,1,date[d2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
RegressionDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_PITCHFORK
OBJ_PITCHFORK
Andrews Pitchfork.
Note
For Andrews Pitchfork, it is possible to specify the mode of continuation of its display
to the right (OBJPROP_RAY_RIGHT property).
You can also specify the number of line-levels, their values and color.
Example
The following script creates and moves Andrews Pitchfork on the chart. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Andrews Pitchfork\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Pitchfork"; // Pitchfork name
input int InpDate1=14; // 1 st point's date, %
input int InpPrice1=40; // 1 st point's price, %
input int InpDate2=18; // 2 nd point's date, %
input int InpPrice2=50; // 2 nd point's price, %
input int InpDate3=18; // 3 rd point's date, %
input int InpPrice3=30; // 3 rd point's price, %
input color InpColor=clrRed; // Pitchfork color
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Style of pitchfork lines
input int InpWidth=1; // Width of pitchfork lines
input bool InpBack=false; // Background pitchfork
input bool InpSelection=true; // Highlight to move
input bool InpRayRight=false; // Pitchfork's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Andrews' Pitchfork by the given coordinates |
//+------------------------------------------------------------------+
bool PitchforkCreate(const long chart_ID=0, // chart's ID
const string name="Pitchfork", // pitchfork name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
const color clr=clrRed, // color of pitchfork l
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of pitchfork l
const int width=1, // width of pitchfork l
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_right=false, // pitchfork's continua
const bool hidden=true, // hidden in the object
const long z_order=0) // priority for mouse c
{
//--- set anchor points' coordinates if they are not set
ChangeChannelEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create Andrews' Pitchfork by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_PITCHFORK,sub_window,time1,price1,time2,price2,
{
Print(__FUNCTION__,
": failed to create \"Andrews' Pitchfork\"! Error code = ",GetLastError()
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the pitchfork for mov
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the pitchfork's di
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Andrews' Pitchfork anchor point |
//+------------------------------------------------------------------+
bool PitchforkPointChange(const long chart_ID=0, // chart's ID
const string name="Pitchfork", // channel name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordin
double price=0) // anchor point price coordi
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Andrews Pitchfork |
//+------------------------------------------------------------------+
bool PitchforkDelete(const long chart_ID=0, // chart's ID
const string name="Pitchfork") // channel name
{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Andrews' Pitchfork\"! Error code = ",GetLastError()
return(false);
}
//--- successful execution
return(true);
}
//+----------------------------------------------------------------------+
//| Check the values of Andrews' Pitchfork anchor points and set default |
//| values for empty ones |
//+----------------------------------------------------------------------+
void ChangeChannelEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the second (upper right) point's time is not set, it will be on the current
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 200 points below the second one
if(!price1)
price1=price2-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the second point's one
if(!time3)
time3=time2;
//--- if the third point's price is not set, move it 200 points lower than the first
if(!price3)
price3=price1-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Andrews' Pitchfork anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Andrews' Pitchfork
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create the pitchfork
if(!PitchforkCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],pri
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpRayRight,InpHidden,InpZOrder
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the pitchfork's anchor points
//--- loop counter
int v_steps=accuracy/10;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!PitchforkPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/8;
//--- move the third anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d3<bars-1)
d3+=1;
//--- move the point
if(!PitchforkPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/10;
//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2>1)
p2-=1;
//--- move the point
if(!PitchforkPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the pitchfork from the chart
PitchforkDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_GANNLINE
OBJ_GANNLINE
Gann Line.
Note
For Gann Line, it is possible to specify the mode of continuation of its display to the
right (OBJPROP_RAY_RIGHT property).
Both Gann angle with a scale and coordinates of the second anchor point can be used
to set the slope of the line.
Example
The following script creates and moves Gann Line on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Gann Line\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="GannLine"; // Line name
input int InpDate1=20; // 1 st point's date, %
input int InpPrice1=75; // 1 st point's price, %
input int InpDate2=80; // 2 nd point's date, %
input double InpAngle=0.0; // Gann Angle
input double InpScale=1.0; // Scale
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style
input int InpWidth=1; // Line width
input bool InpBack=false; // Background line
input bool InpSelection=true; // Highlight to move
input bool InpRayRight=true; // Line's continuation to the right
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Gann Line by the coordinates, angle and scale |
//+------------------------------------------------------------------+
bool GannLineCreate(const long chart_ID=0, // chart's ID
const string name="GannLine", // line name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
const double angle=1.0, // Gann angle
const double scale=1.0, // scale
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_right=true, // line's continuation t
const bool hidden=true, // hidden in the object
const long z_order=0) // priority for mouse cl
{
//--- set anchor points' coordinates if they are not set
ChangeGannLineEmptyPoints(time1,price1,time2);
//--- reset the error value
ResetLastError();
//--- create Gann Line by the given coordinates
//--- correct coordinate of the second anchor point is redefined
//--- automatically after Gann angle and/or the scale changes,
if(!ObjectCreate(chart_ID,name,OBJ_GANNLINE,sub_window,time1,price1,time2,0))
{
Print(__FUNCTION__,
": failed to create \"Gann Line\"! Error code = ",GetLastError());
return(false);
}
//--- change Gann angle
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- change the scale (number of pips per bar)
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- set line color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line display style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the lines for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the line's display
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Gann Line anchor point |
//+------------------------------------------------------------------+
bool GannLinePointChange(const long chart_ID=0, // chart's ID
const string name="GannLine", // line name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinat
double price=0) // anchor point price coordina
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the line's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann angle |
//+------------------------------------------------------------------+
bool GannLineAngleChange(const long chart_ID=0, // chart's ID
const string name="GannLine", // line name
const double angle=1.0) // Gann angle
{
//--- reset the error value
ResetLastError();
//--- change Gann angle
if(!ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle))
{
Print(__FUNCTION__,
": failed to change Gann angle! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Line's scale |
//+------------------------------------------------------------------+
bool GannLineScaleChange(const long chart_ID=0, // chart's ID
const string name="GannLine", // line name
const double scale=1.0) // scale
{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))
{
Print(__FUNCTION__,
": failed to change the scale! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes Gann Line from the chart |
//+------------------------------------------------------------------+
bool GannLineDelete(const long chart_ID=0, // chart's ID
const string name="GannLine") // line name
{
//--- reset the error value
ResetLastError();
//--- delete Gann line
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Gann Line\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Gann Line anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeGannLineEmptyPoints(datetime &time1,double &price1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing line anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Gann Line
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create Gann Line
if(!GannLineCreate(0,InpName,0,date[d1],price[p1],date[d2],InpAngle,InpScale,InpCo
InpStyle,InpWidth,InpBack,InpSelection,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the line's anchor point and change the angle
//--- loop counter
int v_steps=accuracy/2;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!GannLinePointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- half a second of delay
Sleep(500);
//--- define the current value of Gann angle (changed
//--- after moving the first anchor point)
double curr_angle;
if(!ObjectGetDouble(0,InpName,OBJPROP_ANGLE,0,curr_angle))
return;
//--- loop counter
v_steps=accuracy/8;
//--- change Gann angle
for(int i=0;i<v_steps;i++)
{
if(!GannLineAngleChange(0,InpName,curr_angle-0.05*i))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the line from the chart
GannLineDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_GANNFAN
OBJ_GANNFAN
Gann Fan.
Note
For Gann Fan, it is possible to specify trend type from ENUM_GANN_DIRECTION
enumeration. By adjusting the scale value (OBJPROP_SCALE), it is possible to change
slope angle of the fan lines.
Example
The following script creates and moves Gann Fan on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Gann Fan\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="GannFan"; // Fan name
input int InpDate1=15; // 1 st point's date, %
input int InpPrice1=25; // 1 st point's price, %
input int InpDate2=85; // 2 nd point's date, %
input double InpScale=2.0; // Scale
input bool InpDirection=false; // Trend direction
input color InpColor=clrRed; // Fan color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of fan lines
input int InpWidth=1; // Width of fan lines
input bool InpBack=false; // Background fan
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Gann Fan |
//+------------------------------------------------------------------+
bool GannFanCreate(const long chart_ID=0, // chart's ID
const string name="GannFan", // fan name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
const double scale=1.0, // scale
const bool direction=true, // trend direction
const color clr=clrRed, // fan color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of fan lines
const int width=1, // width of fan lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object l
const long z_order=0) // priority for mouse cli
{
//--- set anchor points' coordinates if they are not set
ChangeGannFanEmptyPoints(time1,price1,time2);
//--- reset the error value
ResetLastError();
//--- create Gann Fan by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_GANNFAN,sub_window,time1,price1,time2,0))
{
Print(__FUNCTION__,
": failed to create \"Gann Fan\"! Error code = ",GetLastError());
return(false);
}
//--- change the scale (number of pips per bar)
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- change Gann Fan's trend direction (true - descending, false - ascending)
ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction);
//--- set fan color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set display style of the fan lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the fan lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the fan for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Gann Fan anchor point |
//+------------------------------------------------------------------+
bool GannFanPointChange(const long chart_ID=0, // chart's ID
const string name="GannFan", // fan name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the fan's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Fan's scale |
//+------------------------------------------------------------------+
bool GannFanScaleChange(const long chart_ID=0, // chart's ID
const string name="GannFan", // fan name
const double scale=1.0) // scale
{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))
{
Print(__FUNCTION__,
": failed to change the scale! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Fan's trend direction |
//+------------------------------------------------------------------+
bool GannFanDirectionChange(const long chart_ID=0, // chart's ID
const string name="GannFan", // fan name
const bool direction=true) // trend direction
{
//--- reset the error value
ResetLastError();
//--- change Gann Fan's trend direction
if(!ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction))
{
Print(__FUNCTION__,
": failed to change trend direction! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes Gann Fan from the chart |
//+------------------------------------------------------------------+
bool GannFanDelete(const long chart_ID=0, // chart's ID
const string name="GannFan") // fan name
{
//--- reset the error value
ResetLastError();
//--- delete Gann Fan
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Gann Fan\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
// | Check the values of Gann Fan anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeGannFanEmptyPoints(datetime &time1,double &price1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of fan's anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Gann Fan
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create Gann Fan
if(!GannFanCreate(0,InpName,0,date[d1],price[p1],date[d2],InpScale,InpDirection,
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the fan's anchor point
//--- loop counter
int v_steps=accuracy/2;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
//--- move the point
if(!GannFanPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- change fan's trend direction to descending one
GannFanDirectionChange(0,InpName,true);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the fan from the chart
GannFanDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_GANNGRID
OBJ_GANNGRID
Gann Grid.
Note
For Gann Grid, it is possible to specify trend type from ENUM_GANN_DIRECTION. By
adjusting the scale value (OBJPROP_SCALE), it is possible to change slope angle of the
grid lines.
Example
The following script creates and moves Gann Grid on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Gann Grid\" graphical object."
#property description "Anchor point coordinates of the grid are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="GannGrid"; // Grid name
input int InpDate1=15; // 1 st point's date, %
input int InpPrice1=25; // 1 st point's price, %
input int InpDate2=35; // 2 nd point's date, %
input double InpScale=3.0; // Scale
input bool InpDirection=false; // Trend direction
input color InpColor=clrRed; // Grid color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of grid lines
input int InpWidth=1; // Width of fan lines
input bool InpBack=false; // Background grid
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Gann Grid |
//+------------------------------------------------------------------+
bool GannGridCreate(const long chart_ID=0, // chart's ID
const string name="GannGrid", // grid name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
const double scale=1.0, // scale
const bool direction=true, // trend direction
const color clr=clrRed, // grid color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of grid lines
const int width=1, // width of grid lines
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object
const long z_order=0) // priority for mouse cl
{
//--- set anchor points' coordinates if they are not set
ChangeGannGridEmptyPoints(time1,price1,time2);
//--- reset the error value
ResetLastError();
//--- create Gann Grid by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_GANNGRID,sub_window,time1,price1,time2,0))
{
Print(__FUNCTION__,
": failed to create \"Gann Grid\"! Error code = ",GetLastError());
return(false);
}
//--- change the scale (number of pips per bar)
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- change Gann Fan's trend direction (true - descending, false - ascending)
ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction);
//--- set grid color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set display style of the grid lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the grid lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the grid for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Gann Grid anchor point |
//+------------------------------------------------------------------+
bool GannGridPointChange(const long chart_ID=0, // chart's ID
const string name="GannGrid", // grid name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinat
double price=0) // anchor point price coordina
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the grid's anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Grid's scale |
//+------------------------------------------------------------------+
bool GannGridScaleChange(const long chart_ID=0, // chart's ID
const string name="GannGrid", // grids
const double scale=1.0) // scale
{
//--- reset the error value
ResetLastError();
//--- change the scale (number of pips per bar)
if(!ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale))
{
Print(__FUNCTION__,
": failed to change the scale! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Gann Grid's trend direction |
//+------------------------------------------------------------------+
bool GannGridDirectionChange(const long chart_ID=0, // chart's ID
const string name="GannGrid", // grid name
const bool direction=true) // trend direction
{
//--- reset the error value
ResetLastError();
//--- change Gann Grid's trend direction
if(!ObjectSetInteger(chart_ID,name,OBJPROP_DIRECTION,direction))
{
Print(__FUNCTION__,
": failed to change trend direction! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| The function removes Gann Fan from the chart |
//+------------------------------------------------------------------+
bool GannGridDelete(const long chart_ID=0, // chart's ID
const string name="GannGrid") // grid name
{
//--- reset the error value
ResetLastError();
//--- delete Gann Grid
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Gann Grid\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Gann Grid anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeGannGridEmptyPoints(datetime &time1,double &price1,datetime &time2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the first point's time is not set, it is located 9 bars left from the second
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing grid anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Gann Grid
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
//--- create Gann Grid
if(!GannGridCreate(0,InpName,0,date[d1],price[p1],date[d2],InpScale,InpDirection,
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the grid's anchor points
//--- loop counter
int v_steps=accuracy/4;
//--- move the first anchor point vertically
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
if(!GannGridPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/4;
//--- move the second anchor point horizontally
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
if(!GannGridPointChange(0,InpName,1,date[d2],0))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- change grid's trend direction to descending one
GannGridDirectionChange(0,InpName,true);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the grid from the chart
GannGridDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_FIBO
OBJ_FIBO
Fibonacci Retracement.
Note
For Fibonacci Retracement, it is possible to specify the mode of continuation of its
display to the right (OBJPROP_RAY_RIGHT property).
You can also specify the number of line-levels, their values and color.
Example
The following script creates and moves Fibonacci Retracement on the chart. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Fibonacci Retracement\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboLevels"; // Object name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=65; // 1 st point's price, %
input int InpDate2=90; // 2 nd point's date, %
input int InpPrice2=85; // 2 nd point's price, %
input color InpColor=clrRed; // Object color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style
input int InpWidth=1; // Line width
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpRayRight=false; // Object's continuation to the righ
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Retracement by the given coordinates |
//+------------------------------------------------------------------+
bool FiboLevelsCreate(const long chart_ID=0, // chart's ID
const string name="FiboLevels", // object name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // object color
const ENUM_LINE_STYLE style=STYLE_SOLID, // object line style
const int width=1, // object line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray_right=false, // object's continuati
const bool hidden=true, // hidden in the objec
const long z_order=0) // priority for mouse
{
//--- set anchor points' coordinates if they are not set
ChangeFiboLevelsEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- Create Fibonacci Retracement by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBO,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Retracement\"! Error code = ",GetLastErro
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for movin
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the object's displ
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboLevels") // object name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels,
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Retracement anchor point |
//+------------------------------------------------------------------+
bool FiboLevelsPointChange(const long chart_ID=0, // chart's ID
const string name="FiboLevels", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coord
double price=0) // anchor point price coor
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Retracement |
//+------------------------------------------------------------------+
bool FiboLevelsDelete(const long chart_ID=0, // chart's ID
const string name="FiboLevels") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Retracement\"! Error code = ",GetLastErro
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Retracement anchor points and set |
//| default values for empty ones |
//+------------------------------------------------------------------+
void ChangeFiboLevelsEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first point's time is not set, it is located 9 bars left from the second
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 200 points below the second one
if(!price1)
price1=price2-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Retracement anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Retracement
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboLevelsCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpRayRight,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy*2/5;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!FiboLevelsPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy*4/5;
//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2>1)
p2-=1;
//--- move the point
if(!FiboLevelsPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboLevelsDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_FIBOTIMES
OBJ_FIBOTIMES
Fibonacci Time Zones.
Note
For "Fibonacci Time Zones", it is possible to specify the number of line-levels, their
values and color.
Example
The following script creates and moves Fibonacci Time Zones on the chart. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Fibonacci Time Zones\" graphical object."
#property description "Anchor point coordinates are set in percentage of the size of"
#property description "the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboTimes"; // Object name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=45; // 1 st point's price, %
input int InpDate2=20; // 2 nd point's date, %
input int InpPrice2=55; // 2 nd point's price, %
input color InpColor=clrRed; // Object color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style
input int InpWidth=1; // Line width
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Time Zones by the given coordinates |
//+------------------------------------------------------------------+
bool FiboTimesCreate(const long chart_ID=0, // chart's ID
const string name="FiboTimes", // object name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // object color
const ENUM_LINE_STYLE style=STYLE_SOLID, // object line style
const int width=1, // object line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object
const long z_order=0) // priority for mouse c
{
//--- set anchor points' coordinates if they are not set
ChangeFiboTimesEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create Fibonacci Time Zones by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOTIMES,sub_window,time1,price1,time2,price2)
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Time Zones\"! Error code = ",GetLastError
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for movin
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboTimesLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboTimes") // object name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels,
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(values[i],1));
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Time Zones anchor point |
//+------------------------------------------------------------------+
bool FiboTimesPointChange(const long chart_ID=0, // chart's ID
const string name="FiboTimes", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordin
double price=0) // anchor point price coordi
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Time Zones |
//+------------------------------------------------------------------+
bool FiboTimesDelete(const long chart_ID=0, // chart's ID
const string name="FiboTimes") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Time Zones\"! Error code = ",GetLastError
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Time Zones and |
//| set default values for empty ones |
//+------------------------------------------------------------------+
void ChangeFiboTimesEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 2 bars left from the secon
if(!time2)
{
//--- array for receiving the open time of the last 3 bars
datetime temp[3];
CopyTime(Symbol(),Period(),time1,3,temp);
//--- set the first point 2 bars left from the second one
time2=temp[0];
}
//--- if the second point's price is not set, it is equal to the first point's one
if(!price2)
price2=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Time Zones anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Time Zones
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboTimesCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int h_steps=bars*2/5;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!FiboTimesPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
h_steps=bars*3/5;
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1<bars-1)
d1+=1;
//--- move the point
if(!FiboTimesPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboTimesDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_FIBOFAN
OBJ_FIBOFAN
Fibonacci Fan.
Note
For "Fibonacci Fan", it is possible to specify the number of line-levels, their values and
color.
Example
The following script creates and moves Fibonacci Fan on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Fibonacci Fan\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboFan"; // Fan name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=25; // 1 st point's price, %
input int InpDate2=30; // 2 nd point's date, %
input int InpPrice2=50; // 2 nd point's price, %
input color InpColor=clrRed; // Fan line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style
input int InpWidth=1; // Line width
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Fan by the given coordinates |
//+------------------------------------------------------------------+
bool FiboFanCreate(const long chart_ID=0, // chart's ID
const string name="FiboFan", // fan name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // fan line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // fan line style
const int width=1, // fan line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object l
const long z_order=0) // priority for mouse cli
{
//--- set anchor points' coordinates if they are not set
ChangeFiboFanEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create Fibonacci Fan by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOFAN,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Fan\"! Error code = ",GetLastError());
return(false);
}
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the fan for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboFanLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboFan") // fan name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels,
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Fan anchor point |
//+------------------------------------------------------------------+
bool FiboFanPointChange(const long chart_ID=0, // chart's ID
const string name="FiboFan", // fan name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibo name |
//+------------------------------------------------------------------+
bool FiboFanDelete(const long chart_ID=0, // chart's ID
const string name="FiboFan") // fan name
{
//--- reset the error value
ResetLastError();
//--- delete the fan
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Fan\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Fan anchor points and set |
//| default values for empty ones |
//+------------------------------------------------------------------+
void ChangeFiboFanEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first point's time is not set, it is located 9 bars left from the second
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 200 points below the second one
if(!price1)
price1=price2-200*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Fan anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Fan
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboFanCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the fan's anchor points
//--- loop counter
int v_steps=accuracy/2;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
//--- move the point
if(!FiboFanPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/4;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!FiboFanPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboFanDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_FIBOARC
OBJ_FIBOARC
Fibonacci Arcs.
Note
For "Fibonacci Arcs", it is possible to specify the display mode of the entire ellipse.
Curvature radius can be specified by changing the scale and coordinates of the anchor
points.
You can also specify the number of line-levels, their values and color.
Example
The following script creates and moves Fibonacci Arcs on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Fibonacci Arcs\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboArc"; // Object name
input int InpDate1=25; // 1 st point's date, %
input int InpPrice1=25; // 1 st point's price, %
input int InpDate2=35; // 2 nd point's date, %
input int InpPrice2=55; // 2 nd point's price, %
input double InpScale=3.0; // Scale
input bool InpFullEllipse=true; // Shape of the arcs
input color InpColor=clrRed; // Line color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Line style
input int InpWidth=1; // Line width
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Arcs by the given coordinates |
//+------------------------------------------------------------------+
bool FiboArcCreate(const long chart_ID=0, // chart's ID
const string name="FiboArc", // object name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const double scale=1.0, // scale
const bool full_ellipse=false, // shape of the arcs
const color clr=clrRed, // line color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style
const int width=1, // line width
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object
const long z_order=0) // priority for mouse cl
{
//--- set anchor points' coordinates if they are not set
ChangeFiboArcEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create Fibonacci Arcs by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOARC,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Arcs\"! Error code = ",GetLastError());
return(false);
}
//--- set the scale
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,scale);
//--- set display of the arcs as a full ellipse (true) or a half of it (false)
ObjectSetInteger(chart_ID,name,OBJPROP_ELLIPSE,full_ellipse);
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set line width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the arcs for moving
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboArcLevelsSet(int levels, // number of level lines
double &values[], // values of level lines
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboArc") // object name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels,
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Arcs anchor point |
//+------------------------------------------------------------------+
bool FiboArcPointChange(const long chart_ID=0, // chart's ID
const string name="FiboArc", // object name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Arcs |
//+------------------------------------------------------------------+
bool FiboArcDelete(const long chart_ID=0, // chart's ID
const string name="FiboArc") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Arcs\"! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Arcs anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeFiboArcEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the second point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first point's time is not set, it is located 9 bars left from the second
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 300 points below the second one
if(!price1)
price1=price2-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing the coordinates of Fibonacci Arcs anchor points
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Arcs
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an object
if(!FiboArcCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpScale,
InpFullEllipse,InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOr
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1<accuracy-1)
p1+=1;
//--- move the point
if(!FiboArcPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars/5;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2<bars-1)
d2+=1;
//--- move the point
if(!FiboArcPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboArcDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_FIBOCHANNEL
OBJ_FIBOCHANNEL
Fibonacci Channel.
Note
For Fibonacci Channel, it is possible to specify the mode of continuation of its display
to the chart (OBJPROP_RAY property).
You can also specify the number of line-levels, their values and color.
Example
The following script creates and moves Fibonacci Channel on the chart. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Fibonacci Channel\" graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboChannel"; // Channel name
input int InpDate1=20; // 1 st point's date, %
input int InpPrice1=10; // 1 st point's price, %
input int InpDate2=60; // 2 nd point's date, %
input int InpPrice2=30; // 2 nd point's price, %
input int InpDate3=20; // 3 rd point's date, %
input int InpPrice3=25; // 3 rd point's price, %
input color InpColor=clrRed; // Channel color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of channel lines
input int InpWidth=1; // Width of channel lines
input bool InpBack=false; // Background channel
input bool InpSelection=true; // Highlight to move
input bool InpRay=false; // Channel's continuation to the cha
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Channel by the given coordinates |
//+------------------------------------------------------------------+
bool FiboChannelCreate(const long chart_ID=0, // chart's ID
const string name="FiboChannel", // channel name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point pric
datetime time3=0, // third point time
double price3=0, // third point price
const color clr=clrRed, // channel color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of channel
const int width=1, // width of channel
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool ray=false, // channel's continu
const bool hidden=true, // hidden in the obj
const long z_order=0) // priority for mous
{
//--- set anchor points' coordinates if they are not set
ChangeFiboChannelEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create a channel by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_FIBOCHANNEL,sub_window,time1,price1,time2,price
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Channel\"! Error code = ",GetLastError())
return(false);
}
//--- set channel color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the channel lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for movin
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the channel's disp
ObjectSetInteger(chart_ID,name,OBJPROP_RAY,ray);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboChannelLevelsSet(int levels, // number of level line
double &values[], // values of level line
color &colors[], // color of level lines
ENUM_LINE_STYLE &styles[], // style of level lines
int &widths[], // width of level lines
const long chart_ID=0, // chart's ID
const string name="FiboChannel") // object name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels,
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,DoubleToString(100*values[i],
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Channel anchor point |
//+------------------------------------------------------------------+
bool FiboChannelPointChange(const long chart_ID=0, // chart's ID
const string name="FiboChannel", // channel name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coo
double price=0) // anchor point price co
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the channel |
//+------------------------------------------------------------------+
bool FiboChannelDelete(const long chart_ID=0, // chart's ID
const string name="FiboChannel") // channel name
{
//--- reset the error value
ResetLastError();
//--- delete the channel
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Channel\"! Error code = ",GetLastError())
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Channel anchor points and set |
//| default values for empty ones |
//+------------------------------------------------------------------+
void ChangeFiboChannelEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the second (right) point's time is not set, it will be on the current bar
if(!time2)
time2=TimeCurrent();
//--- if the second point's price is not set, it will have Bid value
if(!price2)
price2=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the
if(!time1)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time2,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, move it 300 points higher than the secon
if(!price1)
price1=price2+300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the first point's one
if(!time3)
time3=time1;
//--- if the third point's price is not set, it is equal to the second point's one
if(!price3)
price3=price2;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing channel anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the channel
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create Fibonacci Channel
if(!FiboChannelCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],p
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpRay,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the channel's anchor points
//--- loop counter
int h_steps=bars/10;
//--- move the first anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d1>1)
d1-=1;
//--- move the point
if(!FiboChannelPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/10;
//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2>1)
p2-=1;
//--- move the point
if(!FiboChannelPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/15;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3<accuracy-1)
p3+=1;
//--- move the point
if(!FiboChannelPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
FiboChannelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_EXPANSION
OBJ_EXPANSION
Fibonacci Expansion.
Note
For "Fibonacci Expansion", it is possible to specify the mode of continuation of its
display to the right (OBJPROP_RAY_RIGHT property).
You can also specify the number of line-levels, their values and color.
Example
The following script creates and moves Fibonacci Expansion on the chart. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Fibonacci Expansion\"graphical object."
#property description "Anchor point coordinates are set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="FiboExpansion"; // Object name
input int InpDate1=10; // 1 st point's date, %
input int InpPrice1=55; // 1 st point's price, %
input int InpDate2=30; // 2 nd point's date, %
input int InpPrice2=10; // 2 nd point's price, %
input int InpDate3=80; // 3 rd point's date, %
input int InpPrice3=75; // 3 rd point's price, %
input color InpColor=clrRed; // Object color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of lines
input int InpWidth=1; // Width of the lines
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpRayRight=false; // Object's continuation to the righ
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Fibonacci Extension by the given coordinates |
//+------------------------------------------------------------------+
bool FiboExpansionCreate(const long chart_ID=0, // chart's ID
const string name="FiboExpansion", // channel name
const int sub_window=0, // subwindow ind
datetime time1=0, // first point t
double price1=0, // first point p
datetime time2=0, // second point
double price2=0, // second point
datetime time3=0, // third point t
double price3=0, // third point p
const color clr=clrRed, // object color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of the
const int width=1, // width of the
const bool back=false, // in the backgr
const bool selection=true, // highlight to
const bool ray_right=false, // object's cont
const bool hidden=true, // hidden in the
const long z_order=0) // priority for
{
//--- set anchor points' coordinates if they are not set
ChangeFiboExpansionEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- Create Fibonacci Extension by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_EXPANSION,sub_window,time1,price1,time2,price2,
{
Print(__FUNCTION__,
": failed to create \"Fibonacci Extension\"! Error code = ",GetLastError(
return(false);
}
//--- set the object's color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the channel for movin
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- enable (true) or disable (false) the mode of continuation of the object's displ
ObjectSetInteger(chart_ID,name,OBJPROP_RAY_RIGHT,ray_right);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set number of levels and their parameters |
//+------------------------------------------------------------------+
bool FiboExpansionLevelsSet(int levels, // number of level
double &values[], // values of level
color &colors[], // color of level l
ENUM_LINE_STYLE &styles[], // style of level l
int &widths[], // width of level l
const long chart_ID=0, // chart's ID
const string name="FiboExpansion") // object name
{
//--- check array sizes
if(levels!=ArraySize(colors) || levels!=ArraySize(styles) ||
levels!=ArraySize(widths) || levels!=ArraySize(widths))
{
Print(__FUNCTION__,": array length does not correspond to the number of levels,
return(false);
}
//--- set the number of levels
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELS,levels);
//--- set the properties of levels in the loop
for(int i=0;i<levels;i++)
{
//--- level value
ObjectSetDouble(chart_ID,name,OBJPROP_LEVELVALUE,i,values[i]);
//--- level color
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELCOLOR,i,colors[i]);
//--- level style
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELSTYLE,i,styles[i]);
//--- level width
ObjectSetInteger(chart_ID,name,OBJPROP_LEVELWIDTH,i,widths[i]);
//--- level description
ObjectSetString(chart_ID,name,OBJPROP_LEVELTEXT,i,"FE "+DoubleToString(100*valu
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Fibonacci Expansion anchor point |
//+------------------------------------------------------------------+
bool FiboExpansionPointChange(const long chart_ID=0, // chart's ID
const string name="FiboExpansion", // object name
const int point_index=0, // anchor point inde
datetime time=0, // anchor point time
double price=0) // anchor point pric
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Fibonacci Expansion |
//+------------------------------------------------------------------+
bool FiboExpansionDelete(const long chart_ID=0, // chart's ID
const string name="FiboExpansion") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Fibonacci Expansion\"! Error code = ",GetLastError(
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of Fibonacci Expansion anchor points and set |
//| default values for empty ones |
//+------------------------------------------------------------------+
void ChangeFiboExpansionEmptyPoints(datetime &time1,double &price1,datetime &time2,
double &price2,datetime &time3,double &price3)
{
//--- if the third (right) point's time is not set, it will be on the current bar
if(!time3)
time3=TimeCurrent();
//--- if the third point's price is not set, it will have Bid value
if(!price3)
price3=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the first (left) point's time is not set, it is located 9 bars left from the
//--- array for receiving the open time of the last 10 bars
datetime temp[];
ArrayResize(temp,10);
if(!time1)
{
CopyTime(Symbol(),Period(),time3,10,temp);
//--- set the first point 9 bars left from the second one
time1=temp[0];
}
//--- if the first point's price is not set, it is equal to the third point's one
if(!price1)
price1=price3;
//--- if the second point's time is not set, it is located 7 bars left from the third
if(!time2)
time2=temp[2];
//--- if the second point's price is not set, move it 250 points lower than the first
if(!price2)
price2=price1-250*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing object anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing Fibonacci Expansion
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create Fibonacci Expansion
if(!FiboExpansionCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3]
InpColor,InpStyle,InpWidth,InpBack,InpSelection,InpRayRight,InpHidden,InpZOrder
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor points
//--- loop counter
int v_steps=accuracy/10;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!FiboExpansionPointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/2;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3>1)
p3-=1;
//--- move the point
if(!FiboExpansionPointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy*4/5;
//--- move the second anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p2<accuracy-1)
p2+=1;
//--- move the point
if(!FiboExpansionPointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the object from the chart
FiboExpansionDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_RECTANGLE
OBJ_RECTANGLE
Rectangle.
Example
The following script creates and moves the rectangle on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates rectangle on the chart."
#property description "Anchor point coordinates are set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Rectangle"; // Rectangle name
input int InpDate1=40; // 1 st point's date, %
input int InpPrice1=40; // 1 st point's price, %
input int InpDate2=60; // 2 nd point's date, %
input int InpPrice2=60; // 2 nd point's price, %
input color InpColor=clrRed; // Rectangle color
input ENUM_LINE_STYLE InpStyle=STYLE_DASH; // Style of rectangle lines
input int InpWidth=1; // Width of rectangle lines
input bool InpFill=true; // Filling the rectangle with color
input bool InpBack=false; // Background rectangle
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create rectangle by the given coordinates |
//+------------------------------------------------------------------+
bool RectangleCreate(const long chart_ID=0, // chart's ID
const string name="Rectangle", // rectangle name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
const color clr=clrRed, // rectangle color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of rectangle l
const int width=1, // width of rectangle l
const bool fill=false, // filling rectangle wi
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object
const long z_order=0) // priority for mouse c
{
//--- set anchor points' coordinates if they are not set
ChangeRectangleEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create a rectangle by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE,sub_window,time1,price1,time2,price2)
{
Print(__FUNCTION__,
": failed to create a rectangle! Error code = ",GetLastError());
return(false);
}
//--- set rectangle color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the style of rectangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of the rectangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- enable (true) or disable (false) the mode of filling the rectangle
ObjectSetInteger(chart_ID,name,OBJPROP_FILL,fill);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the rectangle for mov
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the rectangle anchor point |
//+------------------------------------------------------------------+
bool RectanglePointChange(const long chart_ID=0, // chart's ID
const string name="Rectangle", // rectangle name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordin
double price=0) // anchor point price coordi
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the rectangle |
//+------------------------------------------------------------------+
bool RectangleDelete(const long chart_ID=0, // chart's ID
const string name="Rectangle") // rectangle name
{
//--- reset the error value
ResetLastError();
//--- delete rectangle
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete rectangle! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of rectangle's anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeRectangleEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the secon
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, move it 300 points lower than the first
if(!price2)
price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing rectangle anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the rectangle
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create a rectangle
if(!RectangleCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpColor,
InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the rectangle's anchor points
//--- loop counter
int h_steps=bars/2;
//--- move the anchor points
for(int i=0;i<h_steps;i++)
{
//--- use the following values
if(d1<bars-1)
d1+=1;
if(d2>1)
d2-=1;
//--- shift the points
if(!RectanglePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!RectanglePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p1<accuracy-1)
p1+=1;
if(p2>1)
p2-=1;
//--- shift the points
if(!RectanglePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!RectanglePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the rectangle from the chart
RectangleDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_TRIANGLE
OBJ_TRIANGLE
Triangle.
Example
The following script creates and moves the triangle on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates triangle on the chart."
#property description "Anchor point coordinates are set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Triangle"; // Triangle name
input int InpDate1=25; // 1 st point's date, %
input int InpPrice1=50; // 1 st point's price, %
input int InpDate2=70; // 2 nd point's date, %
input int InpPrice2=70; // 2 nd point's price, %
input int InpDate3=65; // 3 rd point's date, %
input int InpPrice3=20; // 3 rd point's price, %
input color InpColor=clrRed; // Triangle color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of triangle lines
input int InpWidth=1; // Width of triangle lines
input bool InpFill=false; // Filling triangle with color
input bool InpBack=false; // Background triangle
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create triangle by the given coordinates |
//+------------------------------------------------------------------+
bool TriangleCreate(const long chart_ID=0, // chart's ID
const string name="Triangle", // triangle name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
datetime time3=0, // third point time
double price3=0, // third point price
const color clr=clrRed, // triangle color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of triangle lin
const int width=1, // width of triangle lin
const bool fill=false, // filling triangle with
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object
const long z_order=0) // priority for mouse cl
{
//--- set anchor points' coordinates if they are not set
ChangeTriangleEmptyPoints(time1,price1,time2,price2,time3,price3);
//--- reset the error value
ResetLastError();
//--- create triangle by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_TRIANGLE,sub_window,time1,price1,time2,price2,t
{
Print(__FUNCTION__,
": failed to create a triangle! Error code = ",GetLastError());
return(false);
}
//--- set triangle color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of triangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of triangle lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the triangle for movi
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the triangle anchor point |
//+------------------------------------------------------------------+
bool TrianglePointChange(const long chart_ID=0, // chart's ID
const string name="Triangle", // triangle name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinat
double price=0) // anchor point price coordina
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the triangle |
//+------------------------------------------------------------------+
bool TriangleDelete(const long chart_ID=0, // chart's ID
const string name="Triangle") // triangle name
{
//--- reset the error value
ResetLastError();
//--- delete the triangle
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the ellipse! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of triangle's anchor points and set default |
//| values for empty ones |
//+------------------------------------------------------------------+
void ChangeTriangleEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2,
datetime &time3,double &price3)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the secon
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, move it 300 points lower than the first
if(!price2)
price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
//--- if the third point's time is not set, it coincides with the second point's date
if(!time3)
time3=time2;
//--- if the third point's price is not set, it is equal to the first point's one
if(!price3)
price3=price1;
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100 ||
InpDate3<0 || InpDate3>100 || InpPrice3<0 || InpPrice3>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing triangle anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the triangle
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int d3=InpDate3*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
int p3=InpPrice3*(accuracy-1)/100;
//--- create a triangle
if(!TriangleCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],date[d3],pric
InpColor,InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the ellipse anchor points
//--- loop counter
int v_steps=accuracy*3/10;
//--- move the first anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p1>1)
p1-=1;
//--- move the point
if(!TrianglePointChange(0,InpName,0,date[d1],price[p1]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int h_steps=bars*9/20-1;
//--- move the second anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d2>1)
d2-=1;
//--- move the point
if(!TrianglePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
v_steps=accuracy/4;
//--- move the third anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p3<accuracy-1)
p3+=1;
//--- move the point
if(!TrianglePointChange(0,InpName,2,date[d3],price[p3]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete triangle from the chart
TriangleDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_ELLIPSE
OBJ_ELLIPSE
Ellipse.
Example
The following script creates and moves the ellipse on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates ellipse on the chart."
#property description "Anchor point coordinates are set"
#property description "in percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Ellipse"; // Ellipse name
input int InpDate1=30; // 1 st point's date, %
input int InpPrice1=20; // 1 st point's price, %
input int InpDate2=70; // 2 nd point's date, %
input int InpPrice2=80; // 2 nd point's price, %
input double InpEllipseScale=0.2; // Ellipse scale ratio
input color InpColor=clrRed; // Ellipse color
input ENUM_LINE_STYLE InpStyle=STYLE_DASHDOTDOT; // Style of ellipse lines
input int InpWidth=1; // Width of ellipse lines
input bool InpFill=false; // Filling ellipse with color
input bool InpBack=false; // Background ellipse
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create an ellipse by the given coordinates |
//+------------------------------------------------------------------+
bool EllipseCreate(const long chart_ID=0, // chart's ID
const string name="Ellipse", // ellipse name
const int sub_window=0, // subwindow index
datetime time1=0, // first point time
double price1=0, // first point price
datetime time2=0, // second point time
double price2=0, // second point price
double ellipse_scale=0, // ellipse scale ratio
const color clr=clrRed, // ellipse color
const ENUM_LINE_STYLE style=STYLE_SOLID, // style of ellipse lines
const int width=1, // width of ellipse lines
const bool fill=false, // filling ellipse with c
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the object l
const long z_order=0) // priority for mouse cli
{
//--- set anchor points' coordinates if they are not set
ChangeEllipseEmptyPoints(time1,price1,time2,price2);
//--- reset the error value
ResetLastError();
//--- create an ellipse by the given coordinates
if(!ObjectCreate(chart_ID,name,OBJ_ELLIPSE,sub_window,time1,price1,time2,price2))
{
Print(__FUNCTION__,
": failed to create an ellipse! Error code = ",GetLastError());
return(false);
}
//--- set ellipse scale ratio
ObjectSetDouble(chart_ID,name,OBJPROP_SCALE,InpEllipseScale);
//--- set an ellipse color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set style of ellipse lines
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set width of ellipse lines
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of highlighting the ellipse for movin
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the ellipse anchor point |
//+------------------------------------------------------------------+
bool EllipsePointChange(const long chart_ID=0, // chart's ID
const string name="Ellipse", // ellipse name
const int point_index=0, // anchor point index
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,point_index,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete ellipse |
//+------------------------------------------------------------------+
bool EllipseDelete(const long chart_ID=0, // chart's ID
const string name="Ellipse") // ellipse name
{
//--- reset the error value
ResetLastError();
//--- delete an ellipse
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete an ellipse! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check the values of ellipse anchor points and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeEllipseEmptyPoints(datetime &time1,double &price1,
datetime &time2,double &price2)
{
//--- if the first point's time is not set, it will be on the current bar
if(!time1)
time1=TimeCurrent();
//--- if the first point's price is not set, it will have Bid value
if(!price1)
price1=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- if the second point's time is not set, it is located 9 bars left from the secon
if(!time2)
{
//--- array for receiving the open time of the last 10 bars
datetime temp[10];
CopyTime(Symbol(),Period(),time1,10,temp);
//--- set the second point 9 bars left from the first one
time2=temp[0];
}
//--- if the second point's price is not set, move it 300 points lower than the first
if(!price2)
price2=price1-300*SymbolInfoDouble(Symbol(),SYMBOL_POINT);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate1<0 || InpDate1>100 || InpPrice1<0 || InpPrice1>100 ||
InpDate2<0 || InpDate2>100 || InpPrice2<0 || InpPrice2>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing ellipse anchor points' coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- set as series
ArraySetAsSeries(date,true);
ArraySetAsSeries(price,true);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the ellipse
int d1=InpDate1*(bars-1)/100;
int d2=InpDate2*(bars-1)/100;
int p1=InpPrice1*(accuracy-1)/100;
int p2=InpPrice2*(accuracy-1)/100;
//--- create an ellipse
if(!EllipseCreate(0,InpName,0,date[d1],price[p1],date[d2],price[p2],InpEllipseScal
InpColor,InpStyle,InpWidth,InpFill,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the ellipse anchor points
//--- loop counter
int v_steps=accuracy/5;
//--- move the first and second anchor points
for(int i=0;i<v_steps;i++)
{
//--- use the following values
if(p1<accuracy-1)
p1+=1;
if(p2>1)
p2-=1;
//--- shift the points
if(!EllipsePointChange(0,InpName,0,date[d1],price[p1]))
return;
if(!EllipsePointChange(0,InpName,1,date[d2],price[p2]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
//--- delay
Sleep(10);
}
//--- 1 second of delay
Sleep(1000);
//--- inital ellipse scale ratio
double ellipse_scale=InpEllipseScale;
//--- loop counter
v_steps=100;
//--- change ellipse scale ratio
for(int i=0;i<v_steps;i++)
{
ellipse_scale+=2.0/v_steps;
//--- set scale ratio
if(!ObjectSetDouble(0,InpName,OBJPROP_SCALE,ellipse_scale)) return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
//--- delay
Sleep(20);
}
//--- 1 second of delay
Sleep(1000);
//--- delete ellipse from the chart
EllipseDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_ARROW_THUMB_UP
OBJ_ARROW_THUMB_UP
Thumbs Up sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate
OBJPROP_WIDTH property value when writing a code in MetaEditor.
Example
The following script creates and moves Thumbs Up sign on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Thumbs Up\" sign."
#property description "Anchor point coordinate is set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ThumbUp"; // Sign name
input int InpDate=75; // Anchor point date in %
input int InpPrice=25; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type
input color InpColor=clrRed; // Sign color
input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style
input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Thumbs Up sign |
//+------------------------------------------------------------------+
bool ArrowThumbUpCreate(const long chart_ID=0, // chart's ID
const string name="ThumbUp", // sign name
const int sub_window=0, // subwindow in
datetime time=0, // anchor point
double price=0, // anchor point
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line
const int width=3, // sign size
const bool back=false, // in the backg
const bool selection=true, // highlight to
const bool hidden=true, // hidden in th
const long z_order=0) // priority for
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_THUMB_UP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Thumbs Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowThumbUpMove(const long chart_ID=0, // chart's ID
const string name="ThumbUp", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Thumbs Up sign anchor type |
//+------------------------------------------------------------------+
bool ArrowThumbUpAnchorChange(const long chart_ID=0, // chart's I
const string name="ThumbUp", // object na
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor ty
{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Thumbs Up sign |
//+------------------------------------------------------------------+
bool ArrowThumbUpDelete(const long chart_ID=0, // chart's ID
const string name="ThumbUp") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Thumbs Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Thumbs Up sign on the chart
if(!ArrowThumbUpCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars/4;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d>1)
d-=1;
//--- move the point
if(!ArrowThumbUpMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/4;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!ArrowThumbUpMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- change anchor point location relative to the sign
ArrowThumbUpAnchorChange(0,InpName,ANCHOR_BOTTOM);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowThumbUpDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_ARROW_THUMB_DOWN
OBJ_ARROW_THUMB_DOWN
Thumbs Down sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate
OBJPROP_WIDTH property value when writing a code in MetaEditor.
Example
The following script creates and moves Thumbs Down sign on the chart. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Thumbs Down\" sign."
#property description "Anchor point coordinate is set in percentage of"
#property description "the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ThumbDown"; // Sign name
input int InpDate=25; // Anchor point date in %
input int InpPrice=75; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_BOTTOM; // Anchor type
input color InpColor=clrRed; // Sign color
input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style
input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Thumbs Down sign |
//+------------------------------------------------------------------+
bool ArrowThumbDownCreate(const long chart_ID=0, // chart's ID
const string name="ThumbDown", // sign name
const int sub_window=0, // subwindow
datetime time=0, // anchor poi
double price=0, // anchor poi
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor typ
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border lin
const int width=3, // sign size
const bool back=false, // in the bac
const bool selection=true, // highlight
const bool hidden=true, // hidden in
const long z_order=0) // priority f
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_THUMB_DOWN,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Thumbs Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowThumbDownMove(const long chart_ID=0, // chart's ID
const string name="ThumbDown", // object name
datetime time=0, // anchor point time coordinat
double price=0) // anchor point price coordina
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Thumbs Down sign anchor type |
//+------------------------------------------------------------------+
bool ArrowThumbDownAnchorChange(const long chart_ID=0, // chart's
const string name="ThumbDown", // object
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor
{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Thumbs Down sign |
//+------------------------------------------------------------------+
bool ArrowThumbDownDelete(const long chart_ID=0, // chart's ID
const string name="ThumbDown") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Thumbs Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Thumbs Down sign on the chart
if(!ArrowThumbDownCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars/4;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowThumbDownMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- loop counter
int v_steps=accuracy/4;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p>1)
p-=1;
//--- move the point
if(!ArrowThumbDownMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- change anchor point location relative to the sign
ArrowThumbDownAnchorChange(0,InpName,ANCHOR_TOP);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowThumbDownDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_ARROW_UP
OBJ_ARROW_UP
Arrow Up sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate
OBJPROP_WIDTH property value when writing a code in MetaEditor.
Example
The following script creates and moves Arrow Up sign on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Arrow Up\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ArrowUp"; // Sign name
input int InpDate=25; // Anchor point date in %
input int InpPrice=25; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type
input color InpColor=clrRed; // Sign color
input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style
input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Array Up sign |
//+------------------------------------------------------------------+
bool ArrowUpCreate(const long chart_ID=0, // chart's ID
const string name="ArrowUp", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point pric
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=3, // sign size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the obj
const long z_order=0) // priority for mous
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_UP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Arrow Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowUpMove(const long chart_ID=0, // chart's ID
const string name="ArrowUp", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Arrow Down sign anchor type |
//+------------------------------------------------------------------+
bool ArrowUpAnchorChange(const long chart_ID=0, // chart's ID
const string name="ArrowUp", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type
{
//--- reset the error value
ResetLastError();
//--- change anchor point location
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Arrow Up sign |
//+------------------------------------------------------------------+
bool ArrowUpDelete(const long chart_ID=0, // chart's ID
const string name="ArrowUp") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Arrow Up\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Arrow Up sign on the chart
if(!ArrowUpCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!ArrowUpMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- change anchor point location relative to the sign
ArrowUpAnchorChange(0,InpName,ANCHOR_BOTTOM);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowUpDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_ARROW_DOWN
OBJ_ARROW_DOWN
Arrow Down sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate
OBJPROP_WIDTH property value when writing a code in MetaEditor.
Example
The following script creates and moves Arrow Down sign on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Array Down\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ArrowDown"; // Sign name
input int InpDate=75; // Anchor point date in %
input int InpPrice=75; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_BOTTOM; // Anchor type
input color InpColor=clrRed; // Sign color
input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style
input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Array Down sign |
//+------------------------------------------------------------------+
bool ArrowDownCreate(const long chart_ID=0, // chart's ID
const string name="ArrowDown", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point ti
double price=0, // anchor point pr
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line sty
const int width=3, // sign size
const bool back=false, // in the backgrou
const bool selection=true, // highlight to mo
const bool hidden=true, // hidden in the o
const long z_order=0) // priority for mo
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_DOWN,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Arrow Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowDownMove(const long chart_ID=0, // chart's ID
const string name="ArrowDown", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Arrow Down sign anchor type |
//+------------------------------------------------------------------+
bool ArrowDownAnchorChange(const long chart_ID=0, // chart's ID
const string name="ArrowDown", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type
{
//--- reset the error value
ResetLastError();
//--- change anchor point location
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Array Down sign |
//+------------------------------------------------------------------+
bool ArrowDownDelete(const long chart_ID=0, // chart's ID
const string name="ArrowDown") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Arrow Down\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Arrow Down sign on the chart
if(!ArrowDownCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int v_steps=accuracy/2;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p>1)
p-=1;
//--- move the point
if(!ArrowDownMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- change anchor point location relative to the sign
ArrowDownAnchorChange(0,InpName,ANCHOR_TOP);
//--- redraw the chart
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowDownDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_ARROW_STOP
OBJ_ARROW_STOP
Stop sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate
OBJPROP_WIDTH property value when writing a code in MetaEditor.
Example
The following script creates and moves Stop sign on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Stop\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ArrowStop"; // Sign name
input int InpDate=10; // Anchor point date in %
input int InpPrice=50; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_BOTTOM; // Anchor type
input color InpColor=clrRed; // Sign color
input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style
input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Stop sign |
//+------------------------------------------------------------------+
bool ArrowStopCreate(const long chart_ID=0, // chart's ID
const string name="ArrowStop", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point ti
double price=0, // anchor point pr
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line sty
const int width=3, // sign size
const bool back=false, // in the backgrou
const bool selection=true, // highlight to mo
const bool hidden=true, // hidden in the o
const long z_order=0) // priority for mo
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_STOP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Stop\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowStopMove(const long chart_ID=0, // chart's ID
const string name="ArrowStop", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Stop sign anchor type |
//+------------------------------------------------------------------+
bool ArrowStopAnchorChange(const long chart_ID=0, // chart's ID
const string name="ArrowStop", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor point
{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Stop sign |
//+------------------------------------------------------------------+
bool ArrowStopDelete(const long chart_ID=0, // chart's ID
const string name="ArrowStop") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Stop\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Stop sign on the chart
if(!ArrowStopCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowStopMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- change anchor point location relative to the sign
ArrowStopAnchorChange(0,InpName,ANCHOR_TOP);
//--- redraw the chart
ChartRedraw();
//--- loop counter
h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowStopMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowStopDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_ARROW_CHECK
OBJ_ARROW_CHECK
Check sign.
Note
Anchor point position relative to the sign can be selected from ENUM_ARROW_ANCHOR
enumeration.
Large signs (more than 5) can only be created by setting the appropriate
OBJPROP_WIDTH property value when writing a code in MetaEditor.
Example
The following script creates and moves Check sign on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Check\" sign."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="ArrowCheck"; // Sign name
input int InpDate=10; // Anchor point date in %
input int InpPrice=50; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type
input color InpColor=clrRed; // Sign color
input ENUM_LINE_STYLE InpStyle=STYLE_DOT; // Border line style
input int InpWidth=5; // Sign size
input bool InpBack=false; // Background sign
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Check sign |
//+------------------------------------------------------------------+
bool ArrowCheckCreate(const long chart_ID=0, // chart's ID
const string name="ArrowCheck", // sign name
const int sub_window=0, // subwindow inde
datetime time=0, // anchor point t
double price=0, // anchor point p
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor type
const color clr=clrRed, // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line st
const int width=3, // sign size
const bool back=false, // in the backgro
const bool selection=true, // highlight to m
const bool hidden=true, // hidden in the
const long z_order=0) // priority for m
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_CHECK,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Check\" sign! Error code = ",GetLastError());
return(false);
}
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the sign size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowCheckMove(const long chart_ID=0, // chart's ID
const string name="ArrowCheck", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Check anchor type |
//+------------------------------------------------------------------+
bool ArrowCheckAnchorChange(const long chart_ID=0, // chart's ID
const string name="ArrowCheck", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type
{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Check sign |
//+------------------------------------------------------------------+
bool ArrowCheckDelete(const long chart_ID=0, // chart's ID
const string name="ArrowCheck") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Check\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the sign
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create Check sign on the chart
if(!ArrowCheckCreate(0,InpName,0,date[d],price[p],InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point and change its position relative to the sign
//--- loop counter
int h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowCheckMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- change anchor point location relative to the sign
ArrowCheckAnchorChange(0,InpName,ANCHOR_BOTTOM);
//--- redraw the chart
ChartRedraw();
//--- loop counter
h_steps=bars*2/5;
//--- move the anchor point
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!ArrowCheckMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.025 seconds of delay
Sleep(25);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the sign from the chart
ArrowCheckDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_ARROW_LEFT_PRICE
OBJ_ARROW_LEFT_PRICE
Left Price Label
Example
The following script creates and moves left price label on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates the left price label on the chart."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="LeftPrice"; // Price label name
input int InpDate=100; // Anchor point date in %
input int InpPrice=10; // Anchor point price in %
input color InpColor=clrRed; // Price label color
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Border line style
input int InpWidth=2; // Price label size
input bool InpBack=false; // Background label
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the left price label |
//+------------------------------------------------------------------+
bool ArrowLeftPriceCreate(const long chart_ID=0, // chart's ID
const string name="LeftPrice", // price label nam
const int sub_window=0, // subwindow index
datetime time=0, // anchor point ti
double price=0, // anchor point pr
const color clr=clrRed, // price label col
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line sty
const int width=1, // price label siz
const bool back=false, // in the backgrou
const bool selection=true, // highlight to mo
const bool hidden=true, // hidden in the o
const long z_order=0) // priority for mo
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create a price label
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_LEFT_PRICE,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create the left price label! Error code = ",GetLastError());
return(false);
}
//--- set the label color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the label size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowLeftPriceMove(const long chart_ID=0, // chart's ID
const string name="LeftPrice", // label name
datetime time=0, // anchor point time coordinat
double price=0) // anchor point price coordina
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the left price label from the chart |
//+------------------------------------------------------------------+
bool ArrowLeftPriceDelete(const long chart_ID=0, // chart's ID
const string name="LeftPrice") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the left price label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing label anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the label
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create the left price label on the chart
if(!ArrowLeftPriceCreate(0,InpName,0,date[d],price[p],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point
//--- loop counter
int v_steps=accuracy*4/5;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p<accuracy-1)
p+=1;
//--- move the point
if(!ArrowLeftPriceMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the label from the chart
ArrowLeftPriceDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_ARROW_RIGHT_PRICE
OBJ_ARROW_RIGHT_PRICE
Right Price Label.
Example
The following script creates and moves right price label on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates the right price label on the chart."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="RightPrice"; // Price label name
input int InpDate=0; // Anchor point date in %
input int InpPrice=90; // Anchor point price in %
input color InpColor=clrRed; // Price label color
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Border line style
input int InpWidth=2; // Price label size
input bool InpBack=false; // Background label
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the right price label |
//+------------------------------------------------------------------+
bool ArrowRightPriceCreate(const long chart_ID=0, // chart's ID
const string name="RightPrice", // price label na
const int sub_window=0, // subwindow inde
datetime time=0, // anchor point t
double price=0, // anchor point p
const color clr=clrRed, // price label co
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line st
const int width=1, // price label si
const bool back=false, // in the backgro
const bool selection=true, // highlight to m
const bool hidden=true, // hidden in the
const long z_order=0) // priority for m
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create a price label
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_RIGHT_PRICE,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create the right price label! Error code = ",GetLastError())
return(false);
}
//--- set the label color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the label size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowRightPriceMove(const long chart_ID=0, // chart's ID
const string name="RightPrice", // label name
datetime time=0, // anchor point time coordin
double price=0) // anchor point price coordi
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the right price label from the chart |
//+------------------------------------------------------------------+
bool ArrowRightPriceDelete(const long chart_ID=0, // chart's ID
const string name="RightPrice") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the right price label! Error code = ",GetLastError())
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing label anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the label
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create the right price label on the chart
if(!ArrowRightPriceCreate(0,InpName,0,date[d],price[p],InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the anchor point
//--- loop counter
int v_steps=accuracy*4/5;
//--- move the anchor point
for(int i=0;i<v_steps;i++)
{
//--- use the following value
if(p>1)
p-=1;
//--- move the point
if(!ArrowRightPriceMove(0,InpName,date[d],price[p]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
}
//--- 1 second of delay
Sleep(1000);
//--- delete the label from the chart
ArrowRightPriceDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_ARROW_BUY
OBJ_ARROW_BUY
Buy sign.
Example
The following script creates and moves Buy sign on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Buy\" signs in the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input color InpColor=C'3,95,172'; // Color of signs
//+------------------------------------------------------------------+
//| Create Buy sign |
//+------------------------------------------------------------------+
bool ArrowBuyCreate(const long chart_ID=0, // chart's ID
const string name="ArrowBuy", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const color clr=C'3,95,172', // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style (when high
const int width=1, // line size (when highl
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object
const long z_order=0) // priority for mouse cl
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_BUY,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Buy\" sign! Error code = ",GetLastError());
return(false);
}
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set a line style (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a line size (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowBuyMove(const long chart_ID=0, // chart's ID
const string name="ArrowBuy", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Buy sign |
//+------------------------------------------------------------------+
bool ArrowBuyDelete(const long chart_ID=0, // chart's ID
const string name="ArrowBuy") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Buy\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double low[]; // array for storing Low prices of visible bars
double high[]; // array for storing High prices of visible bars
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(low,bars);
ArrayResize(high,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of Low prices
if(CopyLow(Symbol(),Period(),0,bars,low)==-1)
{
Print("Failed to copy the values of Low prices! Error code = ",GetLastError());
return;
}
//--- fill the array of High prices
if(CopyHigh(Symbol(),Period(),0,bars,high)==-1)
{
Print("Failed to copy the values of High prices! Error code = ",GetLastError())
return;
}
//--- create Buy signs in Low point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowBuyCreate(0,"ArrowBuy_"+(string)i,0,date[i],low[i],InpColor))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- move Buy signs to High point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowBuyMove(0,"ArrowBuy_"+(string)i,date[i],high[i]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- delete Buy signs
for(int i=0;i<bars;i++)
{
if(!ArrowBuyDelete(0,"ArrowBuy_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_ARROW_SELL
OBJ_ARROW_SELL
Sell sign.
Example
The following script creates and moves Sell sign on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Sell\" signs in the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input color InpColor=C'225,68,29'; // Color of signs
//+------------------------------------------------------------------+
//| Create Sell sign |
//+------------------------------------------------------------------+
bool ArrowSellCreate(const long chart_ID=0, // chart's ID
const string name="ArrowSell", // sign name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const color clr=C'225,68,29', // sign color
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style (when hig
const int width=1, // line size (when high
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object
const long z_order=0) // priority for mouse c
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create the sign
if(!ObjectCreate(chart_ID,name,OBJ_ARROW_SELL,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Sell\" sign! Error code = ",GetLastError());
return(false);
}
//--- set a sign color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set a line style (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a line size (when highlighted)
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the sign by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowSellMove(const long chart_ID=0, // chart's ID
const string name="ArrowSell", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Sell sign |
//+------------------------------------------------------------------+
bool ArrowSellDelete(const long chart_ID=0, // chart's ID
const string name="ArrowSell") // sign name
{
//--- reset the error value
ResetLastError();
//--- delete the sign
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Sell\" sign! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double low[]; // array for storing Low prices of visible bars
double high[]; // array for storing High prices of visible bars
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(low,bars);
ArrayResize(high,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of Low prices
if(CopyLow(Symbol(),Period(),0,bars,low)==-1)
{
Print("Failed to copy the values of Low prices! Error code = ",GetLastError());
return;
}
//--- fill the array of High prices
if(CopyHigh(Symbol(),Period(),0,bars,high)==-1)
{
Print("Failed to copy the values of High prices! Error code = ",GetLastError())
return;
}
//--- create Sell signs in High point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowSellCreate(0,"ArrowSell_"+(string)i,0,date[i],high[i],InpColor))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- move Sell signs to Low point for each visible bar
for(int i=0;i<bars;i++)
{
if(!ArrowSellMove(0,"ArrowSell_"+(string)i,date[i],low[i]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- delete Sell signs
for(int i=0;i<bars;i++)
{
if(!ArrowSellDelete(0,"ArrowSell_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_ARROW
OBJ_ARROW
Arrow object.
Note
Anchor point position relative to the object can be selected from
ENUM_ARROW_ANCHOR.
Large arrows (more than 5) can only be created by setting the appropriate
OBJPROP_WIDTH property value when writing a code in MetaEditor.
The necessary arrow type can be selected by setting one of the Wingdings font's symbol
codes.
Example
The following script creates Arrow object on the chart and changes its type. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates a random arrow in the chart window."
#property description "Anchor point coordinate is set in"
#property description "percentage of the chart window size."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Arrow"; // Arrow name
input int InpDate=50; // Anchor point date in %
input int InpPrice=50; // Anchor point price in %
input ENUM_ARROW_ANCHOR InpAnchor=ANCHOR_TOP; // Anchor type
input color InpColor=clrDodgerBlue; // Arrow color
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Border line style
input int InpWidth=10; // Arrow size
input bool InpBack=false; // Background arrow
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the arrow |
//+------------------------------------------------------------------+
bool ArrowCreate(const long chart_ID=0, // chart's ID
const string name="Arrow", // arrow name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const uchar arrow_code=252, // arrow code
const ENUM_ARROW_ANCHOR anchor=ANCHOR_BOTTOM, // anchor point positi
const color clr=clrRed, // arrow color
const ENUM_LINE_STYLE style=STYLE_SOLID, // border line style
const int width=3, // arrow size
const bool back=false, // in the background
const bool selection=true, // highlight to move
const bool hidden=true, // hidden in the objec
const long z_order=0) // priority for mouse
{
//--- set anchor point coordinates if they are not set
ChangeArrowEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create an arrow
if(!ObjectCreate(chart_ID,name,OBJ_ARROW,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create an arrow! Error code = ",GetLastError());
return(false);
}
//--- set the arrow code
ObjectSetInteger(chart_ID,name,OBJPROP_ARROWCODE,arrow_code);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set the arrow color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set the arrow's size
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the arrow by mouse
//--- when creating a graphical object using ObjectCreate function, the object cannot
//--- highlighted and moved by default. Inside this method, selection parameter
//--- is true by default making it possible to highlight and move the object
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool ArrowMove(const long chart_ID=0, // chart's ID
const string name="Arrow", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the arrow code |
//+------------------------------------------------------------------+
bool ArrowCodeChange(const long chart_ID=0, // chart's ID
const string name="Arrow", // object name
const uchar code=252) // arrow code
{
//--- reset the error value
ResetLastError();
//--- change the arrow code
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ARROWCODE,code))
{
Print(__FUNCTION__,
": failed to change the arrow code! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change anchor type |
//+------------------------------------------------------------------+
bool ArrowAnchorChange(const long chart_ID=0, // chart's ID
const string name="Arrow", // object name
const ENUM_ARROW_ANCHOR anchor=ANCHOR_TOP) // anchor type
{
//--- reset the error value
ResetLastError();
//--- change anchor type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor))
{
Print(__FUNCTION__,
": failed to change anchor type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete an arrow |
//+------------------------------------------------------------------+
bool ArrowDelete(const long chart_ID=0, // chart's ID
const string name="Arrow") // arrow name
{
//--- reset the error value
ResetLastError();
//--- delete an arrow
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete an arrow! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeArrowEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100 || InpPrice<0 || InpPrice>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- price array size
int accuracy=1000;
//--- arrays for storing the date and price values to be used
//--- for setting and changing sign anchor point coordinates
datetime date[];
double price[];
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(price,accuracy);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of prices
//--- find the highest and lowest values of the chart
double max_price=ChartGetDouble(0,CHART_PRICE_MAX);
double min_price=ChartGetDouble(0,CHART_PRICE_MIN);
//--- define a change step of a price and fill the array
double step=(max_price-min_price)/accuracy;
for(int i=0;i<accuracy;i++)
price[i]=min_price+i*step;
//--- define points for drawing the arrow
int d=InpDate*(bars-1)/100;
int p=InpPrice*(accuracy-1)/100;
//--- create an arrow on the chart
if(!ArrowCreate(0,InpName,0,date[d],price[p],32,InpAnchor,InpColor,
InpStyle,InpWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart
ChartRedraw();
//--- consider all cases of creating arrows in the loop
for(int i=33;i<256;i++)
{
if(!ArrowCodeChange(0,InpName,(uchar)i))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// half a second of delay
Sleep(500);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the arrow from the chart
ArrowDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_TEXT
OBJ_TEXT
Text object.
Note
Anchor point position relative to the text can be selected from ENUM_ANCHOR_POINT
enumeration. You can also change text slope angle using OBJPROP_ANGLE property.
Example
The following script creates several Text objects on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates \"Text\" graphical object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpFont="Arial"; // Font
input int InpFontSize=10; // Font size
input color InpColor=clrRed; // Color
input double InpAngle=90.0; // Slope angle in degrees
input ENUM_ANCHOR_POINT InpAnchor=ANCHOR_LEFT; // Anchor type
input bool InpBack=false; // Background object
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Creating Text object |
//+------------------------------------------------------------------+
bool TextCreate(const long chart_ID=0, // chart's ID
const string name="Text", // object name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point tim
double price=0, // anchor point pri
const string text="Text", // the text itself
const string font="Arial", // font
const int font_size=10, // font size
const color clr=clrRed, // color
const double angle=0.0, // text slope
const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type
const bool back=false, // in the backgroun
const bool selection=false, // highlight to mov
const bool hidden=true, // hidden in the ob
const long z_order=0) // priority for mou
{
//--- set anchor point coordinates if they are not set
ChangeTextEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create Text object
if(!ObjectCreate(chart_ID,name,OBJ_TEXT,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create \"Text\" object! Error code = ",GetLastError());
return(false);
}
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the slope angle of the text
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the object by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the anchor point |
//+------------------------------------------------------------------+
bool TextMove(const long chart_ID=0, // chart's ID
const string name="Text", // object name
datetime time=0, // anchor point time coordinate
double price=0) // anchor point price coordinate
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the object text |
//+------------------------------------------------------------------+
bool TextChange(const long chart_ID=0, // chart's ID
const string name="Text", // object name
const string text="Text") // text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Text object |
//+------------------------------------------------------------------+
bool TextDelete(const long chart_ID=0, // chart's ID
const string name="Text") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Text\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeTextEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double low[]; // array for storing Low prices of visible bars
double high[]; // array for storing High prices of visible bars
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(low,bars);
ArrayResize(high,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of Low prices
if(CopyLow(Symbol(),Period(),0,bars,low)==-1)
{
Print("Failed to copy the values of Low prices! Error code = ",GetLastError());
return;
}
//--- fill the array of High prices
if(CopyHigh(Symbol(),Period(),0,bars,high)==-1)
{
Print("Failed to copy the values of High prices! Error code = ",GetLastError())
return;
}
//--- define how often texts are to be displayed
int scale=(int)ChartGetInteger(0,CHART_SCALE);
//--- define the step
int step=1;
switch(scale)
{
case 0:
step=12;
break;
case 1:
step=6;
break;
case 2:
step=4;
break;
case 3:
step=2;
break;
}
//--- create texts for High and Low bars' values (with gaps)
for(int i=0;i<bars;i+=step)
{
//--- create the texts
if(!TextCreate(0,"TextHigh_"+(string)i,0,date[i],high[i],DoubleToString(high[i]
InpColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
if(!TextCreate(0,"TextLow_"+(string)i,0,date[i],low[i],DoubleToString(low[i],5)
InpColor,-InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- half a second of delay
Sleep(500);
//--- delete the texts
for(int i=0;i<bars;i+=step)
{
if(!TextDelete(0,"TextHigh_"+(string)i))
return;
if(!TextDelete(0,"TextLow_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_LABEL
OBJ_LABEL
Label object.
Note
For OBJ_LABEL, OBJ_BITMAP_LABEL and OBJ_RECTANGLE_LABEL, you can set the chart
corner, relative to which the object anchor point is positioned. The corner is set using
the OBJPROP_CORNER object property which can take one of the four values of
ENUM_BASE_CORNER:
ID Description
CORNER_LEFT_UPPER Anchor point coordinates are set relative to the upper left corner of
the chart
CORNER_LEFT_LOWER Anchor point coordinates are set relative to the lower left corner of
the chart
CORNER_RIGHT_LOWER Anchor point coordinates are set relative to the lower right corner of
the chart
CORNER_RIGHT_UPPER Anchor point coordinates are set relative to the upper right corner of
the chart
The position of the anchor points is set using the OBJPROP_ANCHOR property. It can be
one of the 9 values of ENUM_ANCHOR_POINT:
ID Description
ANCHOR_LEFT_UPPER Anchor point in the upper left corner
ANCHOR_LEFT Anchor point at the center of the left side
ANCHOR_LEFT_LOWER Anchor point in the lower left corner
ANCHOR_LOWER Anchor point at the center of the bottom side
ANCHOR_RIGHT_LOWER Anchor point in the lower right corner
ANCHOR_RIGHT Anchor point at the center of the right side
ID Description
ANCHOR_RIGHT_UPPER Anchor point in the upper right corner
ANCHOR_UPPER Anchor point at the center of the top side
ANCHOR_CENTER Anchor point at the center of the object
Example
The following script creates and moves Edit object on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates \"Label\" graphical object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Label"; // Label name
input int InpX=150; // X-axis distance
input int InpY=150; // Y-axis distance
input string InpFont="Arial"; // Font
input int InpFontSize=14; // Font size
input color InpColor=clrRed; // Color
input double InpAngle=0.0; // Slope angle in degrees
input ENUM_ANCHOR_POINT InpAnchor=ANCHOR_CENTER; // Anchor type
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create a text label |
//+------------------------------------------------------------------+
bool LabelCreate(const long chart_ID=0, // chart's ID
const string name="Label", // label name
const int sub_window=0, // subwindow index
const int x=0, // X coordinate
const int y=0, // Y coordinate
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner fo
const string text="Label", // text
const string font="Arial", // font
const int font_size=10, // font size
const color clr=clrRed, // color
const double angle=0.0, // text slope
const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor type
const bool back=false, // in the backgrou
const bool selection=false, // highlight to mo
const bool hidden=true, // hidden in the o
const long z_order=0) // priority for mo
{
//--- reset the error value
ResetLastError();
//--- create a text label
if(!ObjectCreate(chart_ID,name,OBJ_LABEL,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create text label! Error code = ",GetLastError());
return(false);
}
//--- set label coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the slope angle of the text
ObjectSetDouble(chart_ID,name,OBJPROP_ANGLE,angle);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the text label |
//+------------------------------------------------------------------+
bool LabelMove(const long chart_ID=0, // chart's ID
const string name="Label", // label name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the text label
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the label! Error code = ",GetLastError(
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the label! Error code = ",GetLastError(
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change corner of the chart for binding the label |
//+------------------------------------------------------------------+
bool LabelChangeCorner(const long chart_ID=0, // chart's ID
const string name="Label", // label name
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER) // chart corn
{
//--- reset the error value
ResetLastError();
//--- change anchor corner
if(!ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner))
{
Print(__FUNCTION__,
": failed to change the anchor corner! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the object text |
//+------------------------------------------------------------------+
bool LabelTextChange(const long chart_ID=0, // chart's ID
const string name="Label", // object name
const string text="Text") // text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete a text label |
//+------------------------------------------------------------------+
bool LabelDelete(const long chart_ID=0, // chart's ID
const string name="Label") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a text label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- store the label's coordinates in the local variables
int x=InpX;
int y=InpY;
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- check correctness of the input parameters
if(InpX<0 || InpX>x_distance-1 || InpY<0 || InpY>y_distance-1)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- prepare initial text for the label
string text;
text=StringConcatenate("Upper left corner: ",x,",",y);
//--- create a text label on the chart
if(!LabelCreate(0,InpName,0,InpX,InpY,CORNER_LEFT_UPPER,text,InpFont,InpFontSize,
InpColor,InpAngle,InpAnchor,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for half a second
ChartRedraw();
Sleep(500);
//--- move the label and change its text simultaneously
//--- number of iterations by axes
int h_steps=(int)(x_distance/2-InpX);
int v_steps=(int)(y_distance/2-InpY);
//--- move the label down
for(int i=0;i<v_steps;i++)
{
//--- change the coordinate
y+=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}
//--- half a second of delay
Sleep(500);
//--- move the label to the right
for(int i=0;i<h_steps;i++)
{
//--- change the coordinate
x+=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}
//--- half a second of delay
Sleep(500);
//--- move the label up
for(int i=0;i<v_steps;i++)
{
//--- change the coordinate
y-=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}
//--- half a second of delay
Sleep(500);
//--- move the label to the left
for(int i=0;i<h_steps;i++)
{
//--- change the coordinate
x-=2;
//--- move the label and change its text
MoveAndTextChange(x,y,"Upper left corner: ");
}
//--- half a second of delay
Sleep(500);
//--- now, move the point by changing the anchor corner
//--- move to the lower left corner
if(!LabelChangeCorner(0,InpName,CORNER_LEFT_LOWER))
return;
//--- change the label text
text=StringConcatenate("Lower left corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))
return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- move to the lower right corner
if(!LabelChangeCorner(0,InpName,CORNER_RIGHT_LOWER))
return;
//--- change the label text
text=StringConcatenate("Lower right corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))
return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- move to the upper right corner
if(!LabelChangeCorner(0,InpName,CORNER_RIGHT_UPPER))
return;
//--- change the label text
text=StringConcatenate("Upper right corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))
return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- move to the upper left corner
if(!LabelChangeCorner(0,InpName,CORNER_LEFT_UPPER))
return;
//--- change the label text
text=StringConcatenate("Upper left corner: ",x,",",y);
if(!LabelTextChange(0,InpName,text))
return;
//--- redraw the chart and wait for two seconds
ChartRedraw();
Sleep(2000);
//--- delete the label
LabelDelete(0,InpName);
//--- redraw the chart and wait for half a second
ChartRedraw();
Sleep(500);
//---
}
//+------------------------------------------------------------------+
//| The function moves the object and changes its text |
//+------------------------------------------------------------------+
bool MoveAndTextChange(const int x,const int y,string text)
{
//--- move the label
if(!LabelMove(0,InpName,x,y))
return(false);
//--- change the label text
text=StringConcatenate(text,x,",",y);
if(!LabelTextChange(0,InpName,text))
return(false);
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return(false);
//--- redraw the chart
ChartRedraw();
// 0.01 seconds of delay
Sleep(10);
//--- exit the function
return(true);
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_BUTTON
OBJ_BUTTON
Button object.
Note
Anchor point coordinates are set in pixels. You can select button anchoring corner from
ENUM_BASE_CORNER.
Example
The following script creates and moves Button object on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates the button on the chart."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Button"; // Button name
input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring
input string InpFont="Arial"; // Font
input int InpFontSize=14; // Font size
input color InpColor=clrBlack; // Text color
input color InpBackColor=C'236,233,216'; // Background color
input color InpBorderColor=clrNONE; // Border color
input bool InpState=false; // Pressed/Released
input bool InpBack=false; // Background object
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create the button |
//+------------------------------------------------------------------+
bool ButtonCreate(const long chart_ID=0, // chart's ID
const string name="Button", // button name
const int sub_window=0, // subwindow inde
const int x=0, // X coordinate
const int y=0, // Y coordinate
const int width=50, // button width
const int height=18, // button height
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner f
const string text="Button", // text
const string font="Arial", // font
const int font_size=10, // font size
const color clr=clrBlack, // text color
const color back_clr=C'236,233,216', // background col
const color border_clr=clrNONE, // border color
const bool state=false, // pressed/releas
const bool back=false, // in the backgro
const bool selection=false, // highlight to m
const bool hidden=true, // hidden in the
const long z_order=0) // priority for m
{
//--- reset the error value
ResetLastError();
//--- create the button
if(!ObjectCreate(chart_ID,name,OBJ_BUTTON,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create the button! Error code = ",GetLastError());
return(false);
}
//--- set button coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set button size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set text color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set background color
ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
//--- set border color
ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_COLOR,border_clr);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- set button state
ObjectSetInteger(chart_ID,name,OBJPROP_STATE,state);
//--- enable (true) or disable (false) the mode of moving the button by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move the button |
//+------------------------------------------------------------------+
bool ButtonMove(const long chart_ID=0, // chart's ID
const string name="Button", // button name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the button
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the button! Error code = ",GetLastError
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the button! Error code = ",GetLastError
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change button size |
//+------------------------------------------------------------------+
bool ButtonChangeSize(const long chart_ID=0, // chart's ID
const string name="Button", // button name
const int width=50, // button width
const int height=18) // button height
{
//--- reset the error value
ResetLastError();
//--- change the button size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the button width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the button height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change corner of the chart for binding the button |
//+------------------------------------------------------------------+
bool ButtonChangeCorner(const long chart_ID=0, // chart's I
const string name="Button", // button na
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER) // chart cor
{
//--- reset the error value
ResetLastError();
//--- change anchor corner
if(!ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner))
{
Print(__FUNCTION__,
": failed to change the anchor corner! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change button text |
//+------------------------------------------------------------------+
bool ButtonTextChange(const long chart_ID=0, // chart's ID
const string name="Button", // button name
const string text="Text") // text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the button |
//+------------------------------------------------------------------+
bool ButtonDelete(const long chart_ID=0, // chart's ID
const string name="Button") // button name
{
//--- reset the error value
ResetLastError();
//--- delete the button
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete the button! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define the step for changing the button size
int x_step=(int)x_distance/32;
int y_step=(int)y_distance/32;
//--- set the button coordinates and its size
int x=(int)x_distance/32;
int y=(int)y_distance/32;
int x_size=(int)x_distance*15/16;
int y_size=(int)y_distance*15/16;
//--- create the button
if(!ButtonCreate(0,InpName,0,x,y,x_size,y_size,InpCorner,"Press",InpFont,InpFontSi
InpColor,InpBackColor,InpBorderColor,InpState,InpBack,InpSelection,InpHidden,In
{
return;
}
//--- redraw the chart
ChartRedraw();
//--- reduce the button in the loop
int i=0;
while(i<13)
{
//--- half a second of delay
Sleep(500);
//--- switch the button to the pressed state
ObjectSetInteger(0,InpName,OBJPROP_STATE,true);
//--- redraw the chart and wait for 0.2 second
ChartRedraw();
Sleep(200);
//--- redefine coordinates and button size
x+=x_step;
y+=y_step;
x_size-=x_step*2;
y_size-=y_step*2;
//--- reduce the button
ButtonMove(0,InpName,x,y);
ButtonChangeSize(0,InpName,x_size,y_size);
//--- bring the button back to the released state
ObjectSetInteger(0,InpName,OBJPROP_STATE,false);
//--- redraw the chart
ChartRedraw();
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- increase the loop counter
i++;
}
//--- half a second of delay
Sleep(500);
//--- delete the button
ButtonDelete(0,InpName);
ChartRedraw();
//--- wait for 1 second
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_BITMAP
OBJ_BITMAP
Bitmap object.
Note
For Bitmap object, you can select visibility scope of an image.
Example
The following script creates several bitmaps on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates a bitmap in the chart window."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpFile="\\Images\\dollar.bmp"; // Bitmap file name
input int InpWidth=24; // Visibility scope X coordinat
input int InpHeight=24; // Visibility scope Y coordinat
input int InpXOffset=4; // Visibility scope shift by X
input int InpYOffset=4; // Visibility scope shift by Y
input color InpColor=clrRed; // Border color when highlighte
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Line style when highlighted
input int InpPointWidth=1; // Point size to move
input bool InpBack=false; // Background object
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create a bitmap in the chart window |
//+------------------------------------------------------------------+
bool BitmapCreate(const long chart_ID=0, // chart's ID
const string name="Bitmap", // bitmap name
const int sub_window=0, // subwindow index
datetime time=0, // anchor point time
double price=0, // anchor point price
const string file="", // bitmap file name
const int width=10, // visibility scope X coor
const int height=10, // visibility scope Y coor
const int x_offset=0, // visibility scope shift
const int y_offset=0, // visibility scope shift
const color clr=clrRed, // border color when highl
const ENUM_LINE_STYLE style=STYLE_SOLID, // line style when highlig
const int point_width=1, // move point size
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object li
const long z_order=0) // priority for mouse clic
{
//--- set anchor point coordinates if they are not set
ChangeBitmapEmptyPoint(time,price);
//--- reset the error value
ResetLastError();
//--- create a bitmap
if(!ObjectCreate(chart_ID,name,OBJ_BITMAP,sub_window,time,price))
{
Print(__FUNCTION__,
": failed to create a bitmap in the chart window! Error code = ",GetLastE
return(false);
}
//--- set the path to the image file
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,file))
{
Print(__FUNCTION__,
": failed to load the image! Error code = ",GetLastError());
return(false);
}
//--- set visibility scope for the image; if width or height values
//--- exceed the width and height (respectively) of a source image,
//--- it is not drawn; in the opposite case,
//--- only the part corresponding to these values is drawn
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the part of an image that is to be displayed in the visibility scope
//--- the default part is the upper left area of an image; the values allow
//--- performing a shift from this area displaying another part of the image
ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset);
ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset);
//--- set the border color when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a size of the anchor point for moving an object
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,point_width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set a new image for the bitmap |
//+------------------------------------------------------------------+
bool BitmapSetImage(const long chart_ID=0, // chart's ID
const string name="Bitmap", // bitmap name
const string file="") // path to the file
{
//--- reset the error value
ResetLastError();
//--- set the path to the image file
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,file))
{
Print(__FUNCTION__,
": failed to load the image! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move a bitmap in the chart window |
//+------------------------------------------------------------------+
bool BitmapMove(const long chart_ID=0, // chart's ID
const string name="Bitmap", // bitmap name
datetime time=0, // anchor point time
double price=0) // anchor point price
{
//--- if point position is not set, move it to the current bar having Bid price
if(!time)
time=TimeCurrent();
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
//--- reset the error value
ResetLastError();
//--- move the anchor point
if(!ObjectMove(chart_ID,name,0,time,price))
{
Print(__FUNCTION__,
": failed to move the anchor point! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change visibility scope (bitmap) size |
//+------------------------------------------------------------------+
bool BitmapChangeSize(const long chart_ID=0, // chart's ID
const string name="Bitmap", // bitmap name
const int width=0, // bitmap width
const int height=0) // bitmap height
{
//--- reset the error value
ResetLastError();
//--- change bitmap size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the bitmap width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the bitmap height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------+
//| Change coordinate of the upper left corner of the visibility scope |
//+--------------------------------------------------------------------+
bool BitmapMoveVisibleArea(const long chart_ID=0, // chart's ID
const string name="Bitmap", // bitmap name
const int x_offset=0, // visibility scope X coordina
const int y_offset=0) // visibility scope Y coordina
{
//--- reset the error value
ResetLastError();
//--- change the bitmap's visibility scope coordinates
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset))
{
Print(__FUNCTION__,
": failed to change X coordinate of the visibility scope! Error code = ",
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset))
{
Print(__FUNCTION__,
": failed to change Y coordinate of the visibility scope! Error code = ",
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete a bitmap |
//+------------------------------------------------------------------+
bool BitmapDelete(const long chart_ID=0, // chart's ID
const string name="Bitmap") // bitmap name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a bitmap! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Check anchor point values and set default values |
//| for empty ones |
//+------------------------------------------------------------------+
void ChangeBitmapEmptyPoint(datetime &time,double &price)
{
//--- if the point's time is not set, it will be on the current bar
if(!time)
time=TimeCurrent();
//--- if the point's price is not set, it will have Bid value
if(!price)
price=SymbolInfoDouble(Symbol(),SYMBOL_BID);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date[]; // array for storing dates of visible bars
double close[]; // array for storing Close prices
//--- bitmap file name
string file="\\Images\\dollar.bmp";
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- memory allocation
ArrayResize(date,bars);
ArrayResize(close,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- fill the array of Close prices
if(CopyClose(Symbol(),Period(),0,bars,close)==-1)
{
Print("Failed to copy the values of Close prices! Error code = ",GetLastError()
return;
}
//--- define how often the images should be displayed
int scale=(int)ChartGetInteger(0,CHART_SCALE);
//--- define the step
int step=1;
switch(scale)
{
case 0:
step=27;
break;
case 1:
step=14;
break;
case 2:
step=7;
break;
case 3:
step=4;
break;
case 4:
step=2;
break;
}
//--- create bitmaps for High and Low bars' values (with gaps)
for(int i=0;i<bars;i+=step)
{
//--- create the bitmaps
if(!BitmapCreate(0,"Bitmap_"+(string)i,0,date[i],close[i],InpFile,InpWidth,InpH
InpYOffset,InpColor,InpStyle,InpPointWidth,InpBack,InpSelection,InpHidden,In
{
return;
}
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- half a second of delay
Sleep(500);
//--- delete Sell signs
for(int i=0;i<bars;i+=step)
{
if(!BitmapDelete(0,"Bitmap_"+(string)i))
return;
if(!BitmapDelete(0,"Bitmap_"+(string)i))
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_BITMAP_LABEL
OBJ_BITMAP_LABEL
Bitmap Label object.
Note
For bitmap label, you can select visibility scope of an image.
For OBJ_LABEL, OBJ_BITMAP_LABEL and OBJ_RECTANGLE_LABEL, you can set the chart
corner, relative to which the object anchor point is positioned. The corner is set using
the OBJPROP_CORNER object property which can take one of the four values of
ENUM_BASE_CORNER:
ID Description
CORNER_LEFT_UPPER Anchor point coordinates are set relative to the upper left of the chart
CORNER_LEFT_LOWER Anchor point coordinates are set relative to the lower heft corner of
the chart
CORNER_RIGHT_LOWER Anchor point coordinates are set relative to the lower right corner of
the chart
CORNER_RIGHT_UPPER Anchor point coordinates are set relative to the upper right corner of
the chart
The position of the anchor points is set using the OBJPROP_ANCHOR property. It can be
one of the 9 values of ENUM_ANCHOR_POINT:
ID Description
ANCHOR_LEFT_UPPER Anchor point in the upper left corner
ANCHOR_LEFT Anchor point at the center of the left side
ANCHOR_LEFT_LOWER Anchor point in the lower left corner
ANCHOR_LOWER Anchor point at the center of the bottom side
ANCHOR_RIGHT_LOWER Anchor point in the lower right corner
ANCHOR_RIGHT Anchor point at the center of the right side
ID Description
ANCHOR_RIGHT_UPPER Anchor point in the upper right corner
ANCHOR_UPPER Anchor point at the center of the top side
ANCHOR_CENTER Anchor point at the center of the object
Example
The following script creates several bitmaps on the chart. Special functions have been
developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates \"Bitmap Label\" object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="BmpLabel"; // Label name
input string InpFileOn="\\Images\\dollar.bmp"; // File name for On mode
input string InpFileOff="\\Images\\euro.bmp"; // File name for Off mode
input bool InpState=false; // Label pressed/released
input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchori
input ENUM_ANCHOR_POINT InpAnchor=ANCHOR_CENTER; // Anchor type
input color InpColor=clrRed; // Border color when highli
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Line style when highligh
input int InpPointWidth=1; // Point size to move
input bool InpBack=false; // Background object
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object lis
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Bitmap Label object |
//+------------------------------------------------------------------+
bool BitmapLabelCreate(const long chart_ID=0, // chart's I
const string name="BmpLabel", // label nam
const int sub_window=0, // subwindow
const int x=0, // X coordin
const int y=0, // Y coordin
const string file_on="", // image in
const string file_off="", // image in
const int width=0, // visibilit
const int height=0, // visibilit
const int x_offset=10, // visibilit
const int y_offset=10, // visibilit
const bool state=false, // pressed/r
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart cor
const ENUM_ANCHOR_POINT anchor=ANCHOR_LEFT_UPPER, // anchor ty
const color clr=clrRed, // border co
const ENUM_LINE_STYLE style=STYLE_SOLID, // line styl
const int point_width=1, // move poin
const bool back=false, // in the ba
const bool selection=false, // highlight
const bool hidden=true, // hidden in
const long z_order=0) // priority
{
//--- reset the error value
ResetLastError();
//--- create a bitmap label
if(!ObjectCreate(chart_ID,name,OBJ_BITMAP_LABEL,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create \"Bitmap Label\" object! Error code = ",GetLastError(
return(false);
}
//--- set the images for On and Off modes
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,0,file_on))
{
Print(__FUNCTION__,
": failed to load the image for On mode! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,1,file_off))
{
Print(__FUNCTION__,
": failed to load the image for Off mode! Error code = ",GetLastError());
return(false);
}
//--- set label coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set visibility scope for the image; if width or height values
//--- exceed the width and height (respectively) of a source image,
//--- it is not drawn; in the opposite case,
//--- only the part corresponding to these values is drawn
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the part of an image that is to be displayed in the visibility scope
//--- the default part is the upper left area of an image; the values allow
//--- performing a shift from this area displaying another part of the image
ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset);
ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset);
//--- define the label's status (pressed or released)
ObjectSetInteger(chart_ID,name,OBJPROP_STATE,state);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set anchor type
ObjectSetInteger(chart_ID,name,OBJPROP_ANCHOR,anchor);
//--- set the border color when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set the border line style when object highlighting mode is enabled
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set a size of the anchor point for moving an object
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,point_width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Set a new image for Bitmap label object |
//+------------------------------------------------------------------+
bool BitmapLabelSetImage(const long chart_ID=0, // chart's ID
const string name="BmpLabel", // label name
const int on_off=0, // modifier (On or Off)
const string file="") // path to the file
{
//--- reset the error value
ResetLastError();
//--- set the path to the image file
if(!ObjectSetString(chart_ID,name,OBJPROP_BMPFILE,on_off,file))
{
Print(__FUNCTION__,
": failed to load the image! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Bitmap Label object |
//+------------------------------------------------------------------+
bool BitmapLabelMove(const long chart_ID=0, // chart's ID
const string name="BmpLabel", // label name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the object! Error code = ",GetLastError
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the object! Error code = ",GetLastError
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change visibility scope (object) size |
//+------------------------------------------------------------------+
bool BitmapLabelChangeSize(const long chart_ID=0, // chart's ID
const string name="BmpLabel", // label name
const int width=0, // label width
const int height=0) // label height
{
//--- reset the error value
ResetLastError();
//--- change the object size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the object width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the object height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+--------------------------------------------------------------------+
//| Change coordinate of the upper left corner of the visibility scope |
//+--------------------------------------------------------------------+
bool BitmapLabelMoveVisibleArea(const long chart_ID=0, // chart's ID
const string name="BmpLabel", // label name
const int x_offset=0, // visibility scope X c
const int y_offset=0) // visibility scope Y c
{
//--- reset the error value
ResetLastError();
//--- change the object's visibility scope coordinates
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XOFFSET,x_offset))
{
Print(__FUNCTION__,
": failed to change X coordinate of the visibility scope! Error code = ",
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YOFFSET,y_offset))
{
Print(__FUNCTION__,
": failed to change Y coordinate of the visibility scope! Error code = ",
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete "Bitmap label" object |
//+------------------------------------------------------------------+
bool BitmapLabelDelete(const long chart_ID=0, // chart's ID
const string name="BmpLabel") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Bitmap label\" object! Error code = ",GetLastError(
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define bitmap label coordinates
int x=(int)x_distance/2;
int y=(int)y_distance/2;
//--- set label size and visibility scope coordinates
int width=32;
int height=32;
int x_offset=0;
int y_offset=0;
//--- place bitmap label at the center of the window
if(!BitmapLabelCreate(0,InpName,0,x,y,InpFileOn,InpFileOff,width,height,x_offset,y
InpCorner,InpAnchor,InpColor,InpStyle,InpPointWidth,InpBack,InpSelection,InpHid
{
return;
}
//--- redraw the chart and wait one second
ChartRedraw();
Sleep(1000);
//--- change label's visibility scope size in the loop
for(int i=0;i<6;i++)
{
//--- change visibility scope size
width--;
height--;
if(!BitmapLabelChangeSize(0,InpName,width,height))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.3 seconds of delay
Sleep(300);
}
//--- 1 second of delay
Sleep(1000);
//--- change label's visibility scope coordinates in the loop
for(int i=0;i<2;i++)
{
//--- change visibility scope coordinates
x_offset++;
y_offset++;
if(!BitmapLabelMoveVisibleArea(0,InpName,x_offset,y_offset))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.3 seconds of delay
Sleep(300);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the label
BitmapLabelDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_EDIT
OBJ_EDIT
Edit object.
Note
Anchor point coordinates are set in pixels. You can select Edit anchoring corner from
ENUM_BASE_CORNER enumeration.
You can also select one of the text alignment types inside Edit from ENUM_ALIGN_MODE
enumeration.
Example
The following script creates and moves Edit object on the chart. Special functions have
been developed to create and change graphical object's properties. You can use these
functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates \"Edit\" object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Edit"; // Object name
input string InpText="Text"; // Object text
input string InpFont="Arial"; // Font
input int InpFontSize=14; // Font size
input ENUM_ALIGN_MODE InpAlign=ALIGN_CENTER; // Text alignment type
input bool InpReadOnly=false; // Ability to edit
input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring
input color InpColor=clrBlack; // Text color
input color InpBackColor=clrWhite; // Background color
input color InpBorderColor=clrBlack; // Border color
input bool InpBack=false; // Background object
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Edit object |
//+------------------------------------------------------------------+
bool EditCreate(const long chart_ID=0, // chart's ID
const string name="Edit", // object name
const int sub_window=0, // subwindow index
const int x=0, // X coordinate
const int y=0, // Y coordinate
const int width=50, // width
const int height=18, // height
const string text="Text", // text
const string font="Arial", // font
const int font_size=10, // font size
const ENUM_ALIGN_MODE align=ALIGN_CENTER, // alignment type
const bool read_only=false, // ability to edit
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner for
const color clr=clrBlack, // text color
const color back_clr=clrWhite, // background color
const color border_clr=clrNONE, // border color
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the obj
const long z_order=0) // priority for mous
{
//--- reset the error value
ResetLastError();
//--- create edit field
if(!ObjectCreate(chart_ID,name,OBJ_EDIT,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create \"Edit\" object! Error code = ",GetLastError());
return(false);
}
//--- set object coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set object size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set the text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set text font
ObjectSetString(chart_ID,name,OBJPROP_FONT,font);
//--- set font size
ObjectSetInteger(chart_ID,name,OBJPROP_FONTSIZE,font_size);
//--- set the type of text alignment in the object
ObjectSetInteger(chart_ID,name,OBJPROP_ALIGN,align);
//--- enable (true) or cancel (false) read-only mode
ObjectSetInteger(chart_ID,name,OBJPROP_READONLY,read_only);
//--- set the chart's corner, relative to which object coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set text color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set background color
ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
//--- set border color
ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_COLOR,border_clr);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Edit object |
//+------------------------------------------------------------------+
bool EditMove(const long chart_ID=0, // chart's ID
const string name="Edit", // object name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the object! Error code = ",GetLastError
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the object! Error code = ",GetLastError
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Resize Edit object |
//+------------------------------------------------------------------+
bool EditChangeSize(const long chart_ID=0, // chart's ID
const string name="Edit", // object name
const int width=0, // width
const int height=0) // height
{
//--- reset the error value
ResetLastError();
//--- change the object size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the object width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the object height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Edit object's text |
//+------------------------------------------------------------------+
bool EditTextChange(const long chart_ID=0, // chart's ID
const string name="Edit", // object name
const string text="Text") // text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Return Edit object text |
//+------------------------------------------------------------------+
bool EditTextGet(string &text, // text
const long chart_ID=0, // chart's ID
const string name="Edit") // object name
{
//--- reset the error value
ResetLastError();
//--- get object text
if(!ObjectGetString(chart_ID,name,OBJPROP_TEXT,0,text))
{
Print(__FUNCTION__,
": failed to get the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Edit object |
//+------------------------------------------------------------------+
bool EditDelete(const long chart_ID=0, // chart's ID
const string name="Edit") // object name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Edit\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define the step for changing the edit field
int x_step=(int)x_distance/64;
//--- set edit field coordinates and its size
int x=(int)x_distance/8;
int y=(int)y_distance/2;
int x_size=(int)x_distance/8;
int y_size=InpFontSize*2;
//--- store the text in the local variable
string text=InpText;
//--- create edit field
if(!EditCreate(0,InpName,0,x,y,x_size,y_size,InpText,InpFont,InpFontSize,InpAlign,
InpCorner,InpColor,InpBackColor,InpBorderColor,InpBack,InpSelection,InpHidden,I
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- stretch the edit field
while(x_size-x<x_distance*5/8)
{
//--- increase edit field's width
x_size+=x_step;
if(!EditChangeSize(0,InpName,x_size,y_size))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart and wait for 0.05 seconds
ChartRedraw();
Sleep(50);
}
//--- half a second of delay
Sleep(500);
//--- change the text
for(int i=0;i<20;i++)
{
//--- add "+" at the beginning and at the end
text="+"+text+"+";
if(!EditTextChange(0,InpName,text))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart and wait for 0.1 seconds
ChartRedraw();
Sleep(100);
}
//--- half a second of delay
Sleep(500);
//--- delete edit field
EditDelete(0,InpName);
ChartRedraw();
//--- wait for 1 second
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types / OBJ_EVENT
OBJ_EVENT
Event object.
Note
When hovering mouse over the event, its text appears.
Example
The following script creates and moves Event object on the chart. Special functions
have been developed to create and change graphical object's properties. You can use
these functions "as is" in your own applications.
#property strict //--- description
#property description "Script draws \"Event\" graphical object."
#property description "Anchor point date is set in percentage of"
#property description "the chart window width in bars."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="Event"; // Event name
input int InpDate=25; // Event date, %
input string InpText="Text"; // Event text
input color InpColor=clrRed; // Event color
input int InpWidth=1; // Point size when highlighted
input bool InpBack=false; // Background event
input bool InpSelection=false; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create Event object on the chart |
//+------------------------------------------------------------------+
bool EventCreate(const long chart_ID=0, // chart's ID
const string name="Event", // event name
const int sub_window=0, // subwindow index
const string text="Text", // event text
datetime time=0, // time
const color clr=clrRed, // color
const int width=1, // point width when highlight
const bool back=false, // in the background
const bool selection=false, // highlight to move
const bool hidden=true, // hidden in the object list
const long z_order=0) // priority for mouse click
{
//--- if time is not set, create the object on the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- create Event object
if(!ObjectCreate(chart_ID,name,OBJ_EVENT,sub_window,time,0))
{
Print(__FUNCTION__,
": failed to create \"Event\" object! Error code = ",GetLastError());
return(false);
}
//--- set event text
ObjectSetString(chart_ID,name,OBJPROP_TEXT,text);
//--- set color
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set anchor point width if the object is highlighted
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving event by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change Event object text |
//+------------------------------------------------------------------+
bool EventTextChange(const long chart_ID=0, // chart's ID
const string name="Event", // event name
const string text="Text") // text
{
//--- reset the error value
ResetLastError();
//--- change object text
if(!ObjectSetString(chart_ID,name,OBJPROP_TEXT,text))
{
Print(__FUNCTION__,
": failed to change the text! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move Event object |
//+------------------------------------------------------------------+
bool EventMove(const long chart_ID=0, // chart's ID
const string name="Event", // event name
datetime time=0) // time
{
//--- if time is not set, move event to the last bar
if(!time)
time=TimeCurrent();
//--- reset the error value
ResetLastError();
//--- move the object
if(!ObjectMove(chart_ID,name,0,time,0))
{
Print(__FUNCTION__,
": failed to move \"Event\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete Event object |
//+------------------------------------------------------------------+
bool EventDelete(const long chart_ID=0, // chart's ID
const string name="Event") // event name
{
//--- reset the error value
ResetLastError();
//--- delete the object
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete \"Event\" object! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- check correctness of the input parameters
if(InpDate<0 || InpDate>100)
{
Print("Error! Incorrect values of input parameters!");
return;
}
//--- number of visible bars in the chart window
int bars=(int)ChartGetInteger(0,CHART_VISIBLE_BARS);
//--- array for storing the date values to be used
//--- for setting and changing line anchor point's coordinates
datetime date[];
//--- memory allocation
ArrayResize(date,bars);
//--- fill the array of dates
ResetLastError();
if(CopyTime(Symbol(),Period(),0,bars,date)==-1)
{
Print("Failed to copy time values! Error code = ",GetLastError());
return;
}
//--- define the points to create an object
int d=InpDate*(bars-1)/100;
//--- create Event object
if(!EventCreate(0,InpName,0,InpText,date[d],InpColor,InpWidth,
InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- now, move the object
//--- loop counter
int h_steps=bars/2;
//--- move the object
for(int i=0;i<h_steps;i++)
{
//--- use the following value
if(d<bars-1)
d+=1;
//--- move the point
if(!EventMove(0,InpName,date[d]))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart
ChartRedraw();
// 0.05 seconds of delay
Sleep(50);
}
//--- 1 second of delay
Sleep(1000);
//--- delete the channel from the chart
EventDelete(0,InpName);
ChartRedraw();
//--- 1 second of delay
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Types /
OBJ_RECTANGLE_LABEL
OBJ_RECTANGLE_LABEL
Rectangle Label object.
Note
The function is used for creating and designing the graphical user interface. The frame
type for the rectangular label can be selected from the enumeration
ENUM_BORDER_TYPE.
For OBJ_LABEL, OBJ_BITMAP_LABEL and OBJ_RECTANGLE_LABEL, you can set the chart
corner, relative to which the object anchor point is positioned. The corner is set using
the OBJPROP_CORNER object property which can take one of the four values of
ENUM_BASE_CORNER:
ID Description
CORNER_LEFT_UPPER Anchor point coordinates are set relative to the upper left corner of
the chart
CORNER_LEFT_LOWER Anchor point coordinates are set relative to the lower left corner of
the chart
CORNER_RIGHT_LOWER Anchor point coordinates are set relative to the lower right corner of
the chart
CORNER_RIGHT_UPPER Anchor point coordinates are set relative to the upper right corner of
the chart
Example
The following script creates and moves Rectangle Label object on the chart. Special
functions have been developed to create and change graphical object's properties. You
can use these functions "as is" in your own applications.
#property strict //--- description
#property description "Script creates \"Rectangle Label\" graphical object."
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- input parameters of the script
input string InpName="RectLabel"; // Label name
input color InpBackColor=clrSkyBlue; // Background color
input ENUM_BORDER_TYPE InpBorder=BORDER_FLAT; // Border type
input ENUM_BASE_CORNER InpCorner=CORNER_LEFT_UPPER; // Chart corner for anchoring
input color InpColor=clrDarkBlue; // Flat border color (Flat)
input ENUM_LINE_STYLE InpStyle=STYLE_SOLID; // Flat border style (Flat)
input int InpLineWidth=3; // Flat border width (Flat)
input bool InpBack=false; // Background object
input bool InpSelection=true; // Highlight to move
input bool InpHidden=true; // Hidden in the object list
input long InpZOrder=0; // Priority for mouse click
//+------------------------------------------------------------------+
//| Create rectangle label |
//+------------------------------------------------------------------+
bool RectLabelCreate(const long chart_ID=0, // chart's ID
const string name="RectLabel", // label name
const int sub_window=0, // subwindow in
const int x=0, // X coordinate
const int y=0, // Y coordinate
const int width=50, // width
const int height=18, // height
const color back_clr=C'236,233,216', // background c
const ENUM_BORDER_TYPE border=BORDER_SUNKEN, // border type
const ENUM_BASE_CORNER corner=CORNER_LEFT_UPPER, // chart corner
const color clr=clrRed, // flat border
const ENUM_LINE_STYLE style=STYLE_SOLID, // flat border
const int line_width=1, // flat border
const bool back=false, // in the backg
const bool selection=false, // highlight to
const bool hidden=true, // hidden in th
const long z_order=0) // priority for
{
//--- reset the error value
ResetLastError();
//--- create a rectangle label
if(!ObjectCreate(chart_ID,name,OBJ_RECTANGLE_LABEL,sub_window,0,0))
{
Print(__FUNCTION__,
": failed to create a rectangle label! Error code = ",GetLastError());
return(false);
}
//--- set label coordinates
ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x);
ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y);
//--- set label size
ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width);
ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height);
//--- set background color
ObjectSetInteger(chart_ID,name,OBJPROP_BGCOLOR,back_clr);
//--- set border type
ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_TYPE,border);
//--- set the chart's corner, relative to which point coordinates are defined
ObjectSetInteger(chart_ID,name,OBJPROP_CORNER,corner);
//--- set flat border color (in Flat mode)
ObjectSetInteger(chart_ID,name,OBJPROP_COLOR,clr);
//--- set flat border line style
ObjectSetInteger(chart_ID,name,OBJPROP_STYLE,style);
//--- set flat border width
ObjectSetInteger(chart_ID,name,OBJPROP_WIDTH,line_width);
//--- display in the foreground (false) or background (true)
ObjectSetInteger(chart_ID,name,OBJPROP_BACK,back);
//--- enable (true) or disable (false) the mode of moving the label by mouse
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTABLE,selection);
ObjectSetInteger(chart_ID,name,OBJPROP_SELECTED,selection);
//--- hide (true) or display (false) graphical object name in the object list
ObjectSetInteger(chart_ID,name,OBJPROP_HIDDEN,hidden);
//--- set the priority for receiving the event of a mouse click in the chart
ObjectSetInteger(chart_ID,name,OBJPROP_ZORDER,z_order);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Move rectangle label |
//+------------------------------------------------------------------+
bool RectLabelMove(const long chart_ID=0, // chart's ID
const string name="RectLabel", // label name
const int x=0, // X coordinate
const int y=0) // Y coordinate
{
//--- reset the error value
ResetLastError();
//--- move the rectangle label
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XDISTANCE,x))
{
Print(__FUNCTION__,
": failed to move X coordinate of the label! Error code = ",GetLastError(
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YDISTANCE,y))
{
Print(__FUNCTION__,
": failed to move Y coordinate of the label! Error code = ",GetLastError(
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change the size of the rectangle label |
//+------------------------------------------------------------------+
bool RectLabelChangeSize(const long chart_ID=0, // chart's ID
const string name="RectLabel", // label name
const int width=50, // label width
const int height=18) // label height
{
//--- reset the error value
ResetLastError();
//--- change label size
if(!ObjectSetInteger(chart_ID,name,OBJPROP_XSIZE,width))
{
Print(__FUNCTION__,
": failed to change the label's width! Error code = ",GetLastError());
return(false);
}
if(!ObjectSetInteger(chart_ID,name,OBJPROP_YSIZE,height))
{
Print(__FUNCTION__,
": failed to change the label's height! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Change rectangle label border type |
//+------------------------------------------------------------------+
bool RectLabelChangeBorderType(const long chart_ID=0, // chart'
const string name="RectLabel", // label
const ENUM_BORDER_TYPE border=BORDER_SUNKEN) // border
{
//--- reset the error value
ResetLastError();
//--- change border type
if(!ObjectSetInteger(chart_ID,name,OBJPROP_BORDER_TYPE,border))
{
Print(__FUNCTION__,
": failed to change the border type! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Delete the rectangle label |
//+------------------------------------------------------------------+
bool RectLabelDelete(const long chart_ID=0, // chart's ID
const string name="RectLabel") // label name
{
//--- reset the error value
ResetLastError();
//--- delete the label
if(!ObjectDelete(chart_ID,name))
{
Print(__FUNCTION__,
": failed to delete a rectangle label! Error code = ",GetLastError());
return(false);
}
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- chart window size
long x_distance;
long y_distance;
//--- set window size
if(!ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0,x_distance))
{
Print("Failed to get the chart width! Error code = ",GetLastError());
return;
}
if(!ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0,y_distance))
{
Print("Failed to get the chart height! Error code = ",GetLastError());
return;
}
//--- define rectangle label coordinates
int x=(int)x_distance/4;
int y=(int)y_distance/4;
//--- set label size
int width=(int)x_distance/4;
int height=(int)y_distance/4;
//--- create a rectangle label
if(!RectLabelCreate(0,InpName,0,x,y,width,height,InpBackColor,InpBorder,InpCorner,
InpColor,InpStyle,InpLineWidth,InpBack,InpSelection,InpHidden,InpZOrder))
{
return;
}
//--- redraw the chart and wait one second
ChartRedraw();
Sleep(1000);
//--- change the size of the rectangle label
int steps=(int)MathMin(x_distance/4,y_distance/4);
for(int i=0;i<steps;i++)
{
//--- resize
width+=1;
height+=1;
if(!RectLabelChangeSize(0,InpName,width,height))
return;
//--- check if the script's operation has been forcefully disabled
if(IsStopped())
return;
//--- redraw the chart and wait for 0.01 seconds
ChartRedraw();
Sleep(10);
}
//--- 1 second of delay
Sleep(1000);
//--- change border type
if(!RectLabelChangeBorderType(0,InpName,BORDER_RAISED))
return;
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- change border type
if(!RectLabelChangeBorderType(0,InpName,BORDER_SUNKEN))
return;
//--- redraw the chart and wait for 1 second
ChartRedraw();
Sleep(1000);
//--- delete the label
RectLabelDelete(0,InpName);
ChartRedraw();
//--- wait for 1 second
Sleep(1000);
//---
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Object Properties
Object Properties
Graphical objects can have various properties depending on the object type. All objects
used in technical analysis are bound to the time and price coordinates: trendline,
channels, Fibonacci tools, etc. But there is a number of auxiliary objects intended to
improve the user interface that are bound to the always visible part of a chart (main
chart windows or indicator subwindows):
Object ID X/Y Width/Height Date/Price OBJPROP_CORNER O
Text OBJ_TEXT Yes
Label OBJ_LABEL Yes Yes (read only) Yes
Button OBJ_BUTTON Yes Yes Yes
Bitmap OBJ_BITMAP Yes (read only) Yes
Bitmap OBJ_BITMAP_LABEL Yes Yes (read only) Yes
Label
Edit OBJ_EDIT Yes Yes Yes
Rectangle OBJ_RECTANGLE_LABEL Yes Yes Yes
Label
For objects OBJ_BITMAP_LABEL and OBJ_BITMAP, a special mode of image display can be
set programmatically. In this mode, only part of an original image (at which a
rectangular visible area is applied) is displayed, while the rest of the image becomes
invisible. The size of this area should be set using the properties OBJPROP_XSIZE and
OBJPROP_YSIZE. The visible area can be "moved" only within the original image using the
properties OBJPROP_XOFFSET and OBJPROP_YOFFSET.
For the fixed-sized objects: OBJ_BUTTON, OBJ_RECTANGLE_LABEL and OBJ_EDIT,
properties OBJPROP_XDISTANCE and OBJPROP_YDISTANCE set the position of the top left
point of the object relative to the chart corner (OBJPROP_CORNER), from which the X
and Y coordinates will be counted in pixels.
For functions ObjectSetDouble() and ObjectGetDouble()
ENUM_OBJECT_PROPERTY_DOUBLE
Identifier Description Property Type
OBJPROP_PRICE Price coordinate double modifier=number of anchor
point
OBJPROP_LEVELVALUE Level value double modifier=level number
OBJPROP_SCALE Scale (properties of Gann objects, double
Fibonacci Arcs and Ellipse)
OBJPROP_ANGLE Angle. For the objects with no double
angle specified, created from a
program, the value is equal to
EMPTY_VALUE
OBJPROP_DEVIATION Deviation for the Standard double
Deviation Channel
For functions ObjectSetString() and ObjectGetString()
ENUM_OBJECT_PROPERTY_STRING
Identifier Description Property Type
OBJPROP_NAME Object name string
OBJPROP_TEXT Description of the object (the text string
contained in the object)
OBJPROP_TOOLTIP The text of a tooltip. If the string
property is not set, then the tooltip
generated automatically by the
terminal is shown. A tooltip can be
disabled by setting the "\n" (line
feed) value to it
OBJPROP_LEVELTEXT Level description string modifier=level number
OBJPROP_FONT Font string
OBJPROP_BMPFILE The name of BMP-file for Bitmap string modifier: 0-state ON, 1-state
Label. See also Resources OFF
OBJPROP_SYMBOL Symbol for the Chart object string
For the OBJ_RECTANGLE_LABEL object ("Rectangle label") one of the three design modes
can be set, to which the following values of ENUM_BORDER_TYPE correspond.
ENUM_BORDER_TYPE
Identifier Description
BORDER_FLAT Flat form
BORDER_RAISED Prominent form
BORDER_SUNKEN Concave form
For the OBJ_EDIT object ("Edit") and for the ChartScreenShot()function, you can specify
the horizontal alignment type using the values of the ENUM_ALIGN_MODE enumeration.
ENUM_ALIGN_MODE
Identifier Description
ALIGN_LEFT Left alignment
ALIGN_CENTER Centered (only for the Edit object)
ALIGN_RIGHT Right alignment
Example:
#define UP "\x0431" //+-----------------------------------------------------
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
string label_name="my_OBJ_LABEL_object";
if(ObjectFind(0,label_name)<0)
{
Print("Object ",label_name," not found. Error code = ",GetLastError());
//--- create Label object
ObjectCreate(0,label_name,OBJ_LABEL,0,0,0);
//--- set X coordinate
ObjectSetInteger(0,label_name,OBJPROP_XDISTANCE,200);
//--- set Y coordinate
ObjectSetInteger(0,label_name,OBJPROP_YDISTANCE,300);
//--- define text color
ObjectSetInteger(0,label_name,OBJPROP_COLOR,clrWhite);
//--- define text for object Label
ObjectSetString(0,label_name,OBJPROP_TEXT,UP);
//--- define font
ObjectSetString(0,label_name,OBJPROP_FONT,"Wingdings");
//--- define font size
ObjectSetInteger(0,label_name,OBJPROP_FONTSIZE,10);
//--- 45 degrees rotation clockwise
ObjectSetDouble(0,label_name,OBJPROP_ANGLE,-45);
//--- disable for mouse selecting
ObjectSetInteger(0,label_name,OBJPROP_SELECTABLE,false);
//--- draw it on the chart
ChartRedraw(0);
}
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Methods of Object Binding
Graphical objects Arrow (OBJ_ARROW) have only 2 ways of linking their coordinates.
Identifiers are listed in ENUM_ARROW_ANCHOR.
ENUM_ARROW_ANCHOR
ID Description
ANCHOR_TOP Anchor on the top side
ANCHOR_BOTTOM Anchor on the bottom side
Example:
#property strict
void OnStart()
{
//--- Auxiliary arrays
double Ups[],Downs[];
datetime Times[];
//--- Set the arrays as timeseries
ArraySetAsSeries(Ups,true);
ArraySetAsSeries(Downs,true);
ArraySetAsSeries(Times,true);
//--- Set Last error value to Zero
ResetLastError();
//--- Copy timeseries containing the opening bars of the last 1000 ones
int copied=CopyTime(NULL,0,0,1000,Times);
if(copied<=0)
{
Print("Unable to copy the Open Time of the last 1000 bars");
return;
}
//--- prepare the Ups[] and Downs[] arrays
ArrayResize(Ups,copied);
ArrayResize(Downs,copied);
//--- copy the values of iFractals indicator
for(int i=0;i<copied;i++)
{
Ups[i]=iFractals(NULL,0,MODE_UPPER,i);
Downs[i]=iFractals(NULL,0,MODE_LOWER,i);
}
//---
int upcounter=0,downcounter=0; // count there the number of arrows
bool created;// the result of attempts to create an object
for(int i=2;i<copied;i++)// Run through the values of the indicator iFractals
{
if(Ups[i]!=0)// Found the upper fractal
{
if(upcounter<10)// Create no more than 10 "Up" arrows
{
//--- Try to create an "Up" object
created=ObjectCreate(0,string(Times[i]),OBJ_ARROW_THUMB_UP,0,Times[i],Ups
if(created)// If set up - let's make tuning for it
{
//--- Point anchor is below in order not to cover bar
ObjectSetInteger(0,string(Times[i]),OBJPROP_ANCHOR,ANCHOR_BOTTOM);
//--- Final touch - painted
ObjectSetInteger(0,string(Times[i]),OBJPROP_COLOR,clrBlue);
upcounter++;
}
}
}
if(Downs[i]!=0)// Found a lower fractal
{
if(downcounter<10)// Create no more than 10 arrows "Down"
{
//--- Try to create an object "Down"
created=ObjectCreate(0,string(Times[i]),OBJ_ARROW_THUMB_DOWN,0,Times[i],D
if(created)// If set up - let's make tuning for it
{
//--- Point anchor is above in order not to cover bar
ObjectSetInteger(0,string(Times[i]),OBJPROP_ANCHOR,ANCHOR_TOP);
//--- Final touch - painted
ObjectSetInteger(0,string(Times[i]),OBJPROP_COLOR,clrRed);
downcounter++;
}
}
}
}
}
After the script execution the chart will look like in this figure.
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Chart Corner
Example:
void CreateLabel(long chart_id, string name,
int chart_corner,
int anchor_point,
string text_label,
int x_ord,
int y_ord)
{
//---
if(ObjectCreate(chart_id,name,OBJ_LABEL,0,0,0))
{
ObjectSetInteger(chart_id,name,OBJPROP_CORNER,chart_corner);
ObjectSetInteger(chart_id,name,OBJPROP_ANCHOR,anchor_point);
ObjectSetInteger(chart_id,name,OBJPROP_XDISTANCE,x_ord);
ObjectSetInteger(chart_id,name,OBJPROP_YDISTANCE,y_ord);
ObjectSetString(chart_id,name,OBJPROP_TEXT,text_label);
}
else
Print("Failed to create the object OBJ_LABEL ",name,", Error code = ", GetLastE
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int height=(int)ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
int width=(int)ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0);
string arrows[4]={"LEFT_UPPER","RIGHT_UPPER","RIGHT_LOWER","LEFT_LOWER"};
CreateLabel(0,arrows[0],CORNER_LEFT_UPPER,ANCHOR_LEFT_UPPER,arrows[0],50,50);
CreateLabel(0,arrows[1],CORNER_RIGHT_UPPER,ANCHOR_RIGHT_UPPER,arrows[1],50,50);
CreateLabel(0,arrows[2],CORNER_RIGHT_LOWER,ANCHOR_RIGHT_LOWER,arrows[2],50,50);
CreateLabel(0,arrows[3],CORNER_LEFT_LOWER,ANCHOR_LEFT_LOWER,arrows[3],50,50);
}
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Visibility of Objects
Visibility of Objects
The combination of object visibility flags determines chart timeframes, where the object
is visible. To set/get the value of the OBJPROP_TIMEFRAMES property, you can use the
ObjectSet()/ObjectGet or ObjectSetInteger()/ObjectGetInteger() functions.
ID Value Description
OBJ_NO_PERIODS, EMPTY -1 The object is not drawn in all timeframes
OBJ_PERIOD_M1 0x0001 The object is drawn in 1-minute chart
OBJ_PERIOD_M5 0x0002 The object is drawn in 5-minute chart
OBJ_PERIOD_M15 0x0004 The object is drawn in 15-minute chart
OBJ_PERIOD_M30 0x0008 The object is drawn in 30-minute chart
OBJ_PERIOD_H1 0x0010 The object is drawn in 1-hour chart
OBJ_PERIOD_H4 0x0020 The object is drawn in 4-hour chart
OBJ_PERIOD_D1 0x0040 The object is drawn in day charts
OBJ_PERIOD_W1 0x0080 The object is drawn in week charts
OBJ_PERIOD_MN1 0x0100 The object is drawn in month charts
OBJ_ALL_PERIODS 0x01ff The object is drawn in all timeframes
Visibility flags can be combined using the symbol "|", for example, the combination of
flags OBJ_PERIOD_M15|OBJ_PERIOD_H1 means that the object will be visible on the 15-
minute and hourly timeframes.
Example:
void OnStart() {
//---
string highlevel="PreviousDayHigh";
string lowlevel="PreviousDayLow";
double prevHigh; // The previous day High
double prevLow; // The previous day Low
double highs[],lows[]; // Arrays for High and Low
See also
PeriodSeconds, Period, Chart timeframes, Date and Time
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Gann Objects
Gann Objects
For Gann Fan (OBJ_GANNFAN) and Gann Grid (OBJ_GANNGRID) objects you can specify
two values of the ENUM_GANN_DIRECTION enumeration that sets the trend direction.
ENUM_GANN_DIRECTION
ID Description
GANN_UP_TREND Line corresponding to the uptrend line
GANN_DOWN_TREND Line corresponding to the downward trend
To set the scale of the main line as 1x1, use function ObjectSetDouble(chart_handle,
gann_object_name, OBJPROP_SCALE, scale), where:
chart_handle chart window where the object is located;
gann_object_name object name;
OBJPROP_SCALE identifier of the "Scale" property;
scale required scale in units of Pips/Bar.
Web Colors
The following color constants are defined for the color type:
clrBlack clrDarkGreen clrDarkSlateGray clrOlive clrGreen
clrMaroon clrIndigo clrMidnightBlue clrDarkBlue clrDarkOliveGreen
clrSeaGreen clrDarkGoldenrod clrDarkSlateBlue clrSienna clrMediumBlue
clrLightSeaGreen clrDarkViolet clrFireBrick clrMediumVioletRed clrMediumSeaGreen
clrGoldenrod clrMediumSpringGreen clrLawnGreen clrCadetBlue clrDarkOrchid
clrDarkOrange clrOrange clrGold clrYellow clrChartreuse
clrDeepSkyBlue clrBlue clrMagenta clrRed clrGray
clrLightSlateGray clrDeepPink clrMediumTurquoise clrDodgerBlue clrTurquoise
clrIndianRed clrMediumOrchid clrGreenYellow clrMediumAquamarine clrDarkSeaGreen
clrMediumPurple clrPaleVioletRed clrCoral clrCornflowerBlue clrDarkGray
clrDarkSalmon clrBurlyWood clrHotPink clrSalmon clrViolet
clrPlum clrKhaki clrLightGreen clrAquamarine clrSilver
clrPaleGreen clrThistle clrPowderBlue clrPaleGoldenrod clrPaleTurquoise
clrMoccasin clrLightPink clrGainsboro clrPeachPuff clrPink
clrLemonChiffon clrBeige clrAntiqueWhite clrPapayaWhip clrCornsilk
clrLavender clrMistyRose clrOldLace clrWhiteSmoke clrSeashell
clrLavenderBlush clrMintCream clrSnow clrWhite
Color can be set to an object using the ObjectSetInteger() function. For getting color
values there are similar functions ObjectGetInteger().
Example:
//---- indicator settings #property indicator_chart_window
#property indicator_buffers 3
#property indicator_type1 DRAW_LINE
#property indicator_type2 DRAW_LINE
#property indicator_type3 DRAW_LINE
#property indicator_color1 clrBlue
#property indicator_color2 clrRed
#property indicator_color3 clrLime
MQL4 Reference / Constants, Enumerations and Structures / Objects Constants / Wingdings
Wingdings
Characters of Wingdings used with the OBJ_ARROW object:
Arrow codes
Predefined Arrow codes enumeration. Arrows code constants. It can be one of the
following values:
ID Value Description
SYMBOL_THUMBSUP 67 Thumb up symbol
SYMBOL_THUMBSDOWN 68 Thumb down symbol
SYMBOL_ARROWUP 241 Arrow up symbol
SYMBOL_ARROWDOWN 242 Arrow down symbol
SYMBOL_STOPSIGN 251 Stop sign symbol
SYMBOL_CHECKSIGN 252 Check sign symbol
Special Arrow codes that exactly points to price and time. It can be one of the following
values:
ID Value Description
1 Upwards arrow with tip rightwards
2 Downwards arrow with tip rightwards
3 Left pointing triangle
4 Dash symbol
SYMBOL_LEFTPRICE 5 Left sided price label
SYMBOL_RIGHTPRICE 6 Right sided price label
Special Arrow codes cannot be used in custom indicators for lines with DRAW_ARROW
drawing style.
Example:
#property indicator_chart_window #property indicator_buffers 1
#property indicator_color1 Lime
//---- input parameters
extern double Step=0.02;
extern double Maximum=0.2;
//---- buffers
double SarBuffer[];
//----
int save_lastreverse;
bool save_dirlong;
double save_start;
double save_last_high;
double save_last_low;
double save_ep;
double save_sar;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
SetIndexStyle(0,DRAW_ARROW);
SetIndexArrow(0,159);
SetIndexBuffer(0,SarBuffer);
//----
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| SaveLastReverse |
//+------------------------------------------------------------------+
void SaveLastReverse(int last,int dir,double start_index,double low,double high,doubl
{
save_lastreverse=last;
save_dirlong=dir;
save_start=start_index;
save_last_low=low;
save_last_high=high;
save_ep=ep;
save_sar=sar;
}
//+------------------------------------------------------------------+
//| Parabolic Sell And Reverse system |
//+------------------------------------------------------------------+
int start()
{
static bool first=true;
bool dirlong;
double start_index,last_high,last_low;
double ep,sar,price_low,price_high,price;
int i;
int limit,cb;
//----
if(Bars<3) return(0);
int counted_bars=IndicatorCounted();
if(counted_bars < 0) return(-1);
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
if(counted_bars==0) limit-=2;
price=Low[i+1];
if(sar>price) sar=price;
price=Low[i+2];
if(sar>price) sar=price;
if(sar>price_low)
{
SaveLastReverse(i,true,start_index,price_low,last_high,ep,sar);
start_index=Step; dirlong=false; ep=price_low;
last_low=price_low;
SarBuffer[i]=last_high;
i--;
continue;
}
if(ep<price_high) { last_high=price_high; ep=price_high; }
}
else
{
if(ep>price_low && (start_index+Step)<=Maximum) start_index+=Step;
if(price_low<Low[i+1] && i==Bars-2) sar=SarBuffer[i+1];
price=High[i+1];
if(sar<price) sar=price;
price=High[i+2];
if(sar<price) sar=price;
if(sar<price_high)
{
SaveLastReverse(i,false,start_index,last_low,price_high,ep,sar);
start_index=Step; dirlong=true; ep=price_high;
last_high=price_high;
SarBuffer[i]=last_low;
i--;
continue;
}
if(ep>price_low) { last_low=price_low; ep=price_low; }
}
SarBuffer[i]=sar;
i--;
}
//---
for(cb=limit;cb>=0;cb--)
{
if(GreaterDoubles(SarBuffer[cb],0,Digits))
{
string object_name="price"+string(Time[cb]);
//--- first find object by name
if(ObjectFind(object_name)<0)
{
//--- if not found, create it
if(ObjectCreate(object_name,OBJ_ARROW,0,Time[cb],SarBuffer[cb]))
{
//--- set object properties
//--- arrow code
ObjectSet(object_name,OBJPROP_ARROWCODE,SYMBOL_LEFTPRICE);
//--- color
ObjectSet(object_name,OBJPROP_COLOR,DodgerBlue);
//--- price
ObjectSet(object_name,OBJPROP_PRICE1,SarBuffer[cb]);
//--- time
ObjectSet(object_name,OBJPROP_TIME1,Time[cb]);
}
}
else
{
//--- if the object exists, just modify its price coordinate
ObjectSet(object_name,OBJPROP_PRICE1,SarBuffer[cb]);
}
}
}
//----
return(0);
}
//+------------------------------------------------------------------+
//| GreaterDoubles |
//+------------------------------------------------------------------+
bool GreaterDoubles(double number1,double number2,int dig)
{
if(NormalizeDouble(number1-number2,dig)>0) return(true);
else return(false);
}
//+------------------------------------------------------------------+
MQL4 Reference / Constants, Enumerations and Structures /
Indicator Constants
Indicators Constants
There are many predefined technical indicators, which
can be used in programs written in the MQL4 language. In
addition, there is an opportunity to create custom
indicators using the iCustom() function. All constants
required for that are divided into 5 groups:
Price constants for selecting the type of price or
volume, on which an indicator is calculated;
Series Array Identifiers - for selecting a value type
from a timeseries;
Smoothing methods built-in smoothing methods used in
indicators;
Indicator lines identifiers of indicator buffers when
accessing indicator values;
Drawing styles for indicating one of 6 types of drawing
and setting the line drawing style;
Custom indicators properties are used in functions for
working with custom indicators;
What's new in MQL5
In the new terminal, the number of built-in technical
indicators has been increased from 30 to 38, while the
number of drawing styles of custom indicators has been
increased 3 times from 6 to 18. Now custom indicators are
able to use up to 512 indicator buffers. A separate color
on each bar can be specified for color styles.
Data Color
ID Description
buffers buffers
DRAW_NONE Not drawn 1 -
DRAW_LINE Line 1 -
DRAW_SECTION Section 1 -
Histogram
DRAW_HISTOGRAM from the 1 -
zero line
Histogram of
the two
DRAW_HISTOGRAM2 2 -
indicator
buffers
Drawing
DRAW_ARROW 1 -
arrows
Style Zigzag
allows
DRAW_ZIGZAG vertical 2 -
section on
the bar
Color fill
DRAW_FILLING between the 2 -
two levels
Display as a
DRAW_BARS sequence of 4 -
bars
Display as a
DRAW_CANDLES sequence of 4 -
candlesticks
Multicolored
DRAW_COLOR_LINE 1 1
line
Data Color
ID Description
buffers buffers
Multicolored
DRAW_COLOR_SECTION 1 1
section
Multicolored
histogram
DRAW_COLOR_HISTOGRAM 1 1
from the
zero line
Multicolored
histogram of
DRAW_COLOR_HISTOGRAM2 the two 2 1
indicator
buffers
Drawing
DRAW_COLOR_ARROW multicolored 1 1
arrows
Multicolored
DRAW_COLOR_ZIGZAG 2 1
ZigZag
Multicolored
DRAW_COLOR_BARS 4 1
bars
Multicolored
DRAW_COLOR_CANDLES 4 1
candlesticks
MQL4 Reference / Constants, Enumerations and Structures /
Indicator Constants / Price Constants
Price Constants
Calculations of technical indicators require price values
and/or values of volumes, on which calculations will be
performed. There are 7 predefined identifiers from the
ENUM_APPLIED_PRICE enumeration, used to specify the
desired price base for calculations.
ENUM_APPLIED_PRICE
ID Value Description
PRICE_CLOSE 0 Close price
PRICE_OPEN 1 Open price
PRICE_HIGH 2 The
maximum
price for the
period
PRICE_LOW 3 The
minimum
price for the
period
PRICE_MEDIAN 4 Median
price, (high
+ low)/2
PRICE_TYPICAL 5 Typical
price, (high
+ low +
close)/3
ID Value Description
PRICE_WEIGHTED 6 Weighted
close price,
(high + low +
close +
close)/4
MQL4 Reference / Constants, Enumerations and Structures /
Indicator Constants / Series Array Identifiers
MQL4 Reference / Constants, Enumerations and Structures /
Indicator Constants / Smoothing Methods
Smoothing Methods
Many technical indicators are based on various methods of
the price series smoothing. Some standard technical
indicators (iAlligator(), iEnvelopes(), iEnvelopesOnArray(),
iForce(), iGator(), iMA(), iMAOnArray(), iStdDev(),
iStdDevOnArray() and iStochastic() indicators) require
specification of the smoothing type as an input parameter.
For specifying the desired type of smoothing, identifiers
listed in the ENUM_MA_METHOD enumeration are used.
ENUM_MA_METHOD
ID Value Description
MODE_SMA 0 Simple averaging
MODE_EMA 1 Exponential averaging
MODE_SMMA 2 Smoothed averaging
MODE_LWMA 3 Linear-weighted averaging
MQL4 Reference / Constants, Enumerations and Structures /
Indicator Constants / Indicators Lines
Indicator Lines
Indicator line identifiers used in iMACD(), iRVI() and
iStochastic() indicators.
ID Value Description
MODE_MAIN 0 Base indicator line
MODE_SIGNAL 1 Signal line
Drawing Styles
Drawing shape styles for SetIndexStyle() function.
ID Value Description
DRAW_LINE 0 Drawing line
DRAW_SECTION 1 Drawing sections
DRAW_HISTOGRAM 2 Drawing histogram
DRAW_ARROW 3 Drawing arrows (symbols)
DRAW_ZIGZAG 4 Drawing sections between even
and odd indicator buffers, 2
buffers of values
DRAW_NONE 12 No drawing
ENUM_CUSTOMIND_PROPERTY_DOUBLE
ID Description Property type
INDICATOR_MINIMUM Minimum of the indicator window double
INDICATOR_MAXIMUM Maximum of the indicator window double
INDICATOR_LEVELVALUE Level value double modifier = level
number
ENUM_CUSTOMIND_PROPERTY_STRING
ID Description Property type
INDICATOR_SHORTNAME Short indicator name string
INDICATOR_LEVELTEXT Level description string modifier = level
number
Example:
#property description "Relative Strength Index" #property strict
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1 clrDodgerBlue
//--- input parameters
input int InpRSIPeriod=14; // RSI Period
//--- buffers
double ExtRSIBuffer[];
double ExtPosBuffer[];
double ExtNegBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit(void)
{
string short_name;
//--- 2 additional buffers are used for calculations.
IndicatorBuffers(3);
SetIndexBuffer(0,ExtRSIBuffer);
SetIndexBuffer(1,ExtPosBuffer);
SetIndexBuffer(2,ExtNegBuffer);
//--- set levels
IndicatorSetInteger(INDICATOR_LEVELS,2);
IndicatorSetDouble(INDICATOR_LEVELVALUE,0,30);
IndicatorSetDouble(INDICATOR_LEVELVALUE,1,70);
//--- set maximum and minimum for subwindow
IndicatorSetDouble(INDICATOR_MINIMUM,0);
IndicatorSetDouble(INDICATOR_MAXIMUM,100);
//--- indicator line
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,ExtRSIBuffer);
//--- name for DataWindow and indicator subwindow label
short_name="RSI("+string(InpRSIPeriod)+")";
IndicatorShortName(short_name);
SetIndexLabel(0,short_name);
//--- check for input
if(InpRSIPeriod<2)
{
Print("Incorrect value for input variable InpRSIPeriod = ",InpRSIPeriod);
return(INIT_FAILED);
}
//---
SetIndexDrawBegin(0,InpRSIPeriod);
//--- initialization done
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Relative Strength Index |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
int i,pos;
double diff;
//---
if(Bars<=InpRSIPeriod || InpRSIPeriod<2)
return(0);
//--- counting from 0 to rates_total
ArraySetAsSeries(ExtRSIBuffer,false);
ArraySetAsSeries(ExtPosBuffer,false);
ArraySetAsSeries(ExtNegBuffer,false);
ArraySetAsSeries(close,false);
//--- preliminary calculations
pos=prev_calculated-1;
if(pos<=InpRSIPeriod)
{
//--- first RSIPeriod values of the indicator are not calculated
ExtRSIBuffer[0]=0.0;
ExtPosBuffer[0]=0.0;
ExtNegBuffer[0]=0.0;
double sump=0.0;
double sumn=0.0;
for(i=1; i<=InpRSIPeriod; i++)
{
ExtRSIBuffer[i]=0.0;
ExtPosBuffer[i]=0.0;
ExtNegBuffer[i]=0.0;
diff=close[i]-close[i-1];
if(diff>0)
sump+=diff;
else
sumn-=diff;
}
//--- calculate first visible value
ExtPosBuffer[InpRSIPeriod]=sump/InpRSIPeriod;
ExtNegBuffer[InpRSIPeriod]=sumn/InpRSIPeriod;
if(ExtNegBuffer[InpRSIPeriod]!=0.0)
ExtRSIBuffer[InpRSIPeriod]=100.0-(100.0/(1.0+ExtPosBuffer[InpRSIPeriod]/ExtN
else
{
if(ExtPosBuffer[InpRSIPeriod]!=0.0)
ExtRSIBuffer[InpRSIPeriod]=100.0;
else
ExtRSIBuffer[InpRSIPeriod]=50.0;
}
//--- prepare the position value for main calculation
pos=InpRSIPeriod+1;
}
//--- the main loop of calculations
for(i=pos; i<rates_total && !IsStopped(); i++)
{
diff=close[i]-close[i-1];
ExtPosBuffer[i]=(ExtPosBuffer[i-1]*(InpRSIPeriod-1)+(diff>0.0?diff:0.0))/InpRSI
ExtNegBuffer[i]=(ExtNegBuffer[i-1]*(InpRSIPeriod-1)+(diff<0.0?-diff:0.0))/InpRS
if(ExtNegBuffer[i]!=0.0)
ExtRSIBuffer[i]=100.0-100.0/(1+ExtPosBuffer[i]/ExtNegBuffer[i]);
else
{
if(ExtPosBuffer[i]!=0.0)
ExtRSIBuffer[i]=100.0;
else
ExtRSIBuffer[i]=50.0;
}
}
//---
return(rates_total);
}
MQL4 Reference / Constants, Enumerations and Structures /
Environment State
Environment State
Constants describing the current runtime environment of
an mql4-program are divided into groups:
Client terminal properties information about the client
terminal;
Running MQL4 Program Properties mql4 program
properties, which help to control its execution;
Symbol properties obtaining information about a
symbol;
Account properties information about the current
account;
Testing Statistics results of Expert Advisor testing.
MQL4 Reference / Constants, Enumerations and Structures / Environment State / Client Terminal Properties
In the above example, the graphical resource looks the same on monitors with different
resolution characteristics. The size of control elements (buttons, dialog windows, etc.)
corresponds to personalization settings.
ENUM_TERMINAL_INFO_DOUBLE
Identifier Description Type
TERMINAL_COMMUNITY_BALANCE Balance in MQL5.community double
File operations can be performed only in two directories; corresponding paths can be
obtained using the request for TERMINAL_DATA_PATH and TERMINAL_COMMONDATA_PATH
properties.
ENUM_TERMINAL_INFO_STRING
Identifier Description Type
TERMINAL_LANGUAGE Language of the terminal string
TERMINAL_COMPANY Company name string
TERMINAL_NAME Terminal name string
TERMINAL_PATH Folder from which the terminal is started string
TERMINAL_DATA_PATH Folder in which terminal data are stored string
TERMINAL_COMMONDATA_PATH Common path for all of the terminals installed on a string
computer
As result of the script execution in the Experts Journal you will see a messages, like the
following:
MQL4 Reference / Constants, Enumerations and Structures / Environment State / Running MQL4 Program
Properties
For information about the type of the running program, values of ENUM_PROGRAM_TYPE
are used.
ENUM_PROGRAM_TYPE
Identifier Description
PROGRAM_SCRIPT Script
PROGRAM_EXPERT Expert
PROGRAM_INDICATOR Indicator
ENUM_LICENSE_TYPE
Identifier Description
LICENSE_FREE A free unlimited version
LICENSE_DEMO A trial version of a paid product from the Market. It works only in
the strategy tester
LICENSE_FULL A purchased licensed version allows at least 5 activations. The
number of activations is specified by seller. Seller may increase the
allowed number of activations
LICENSE_TIME A version with limited term liсense
Example:
ENUM_PROGRAM_TYPE mql_program=(ENUM_PROGRAM_TYPE)MQLInfoInteger(MQL_PROGRAM_TYPE);
{
case PROGRAM_SCRIPT:
{
Print(__FILE__+" is script");
break;
}
case PROGRAM_EXPERT:
{
Print(__FILE__+" is Expert Advisor");
break;
}
case PROGRAM_INDICATOR:
{
Print(__FILE__+" is custom indicator");
break;
}
default:Print("MQL4 program type value is ",mql_program);
}
MQL4 Reference / Constants, Enumerations and Structures / Environment State / Symbol Properties
Symbol Properties
Market information identifiers, used with MarketInfo() function. It can be any of the
following values:
ID Value Description
MODE_LOW 1 Low day price
MODE_HIGH 2 High day price
MODE_TIME 5 The last incoming tick time (last known server time)
MODE_BID 9 Last incoming bid price. For the current symbol, it is
stored in the predefined variable Bid
MODE_ASK 10 Last incoming ask price. For the current symbol, it is
stored in the predefined variable Ask
MODE_POINT 11 Point size in the quote currency. For the current
symbol, it is stored in the predefined variable Point
MODE_DIGITS 12 Count of digits after decimal point in the symbol
prices. For the current symbol, it is stored in the
predefined variable Digits
MODE_SPREAD 13 Spread value in points
MODE_STOPLEVEL 14 Stop level in points
A zero value of MODE_STOPLEVEL means either
absence of any restrictions on the minimal distance for
Stop Loss/Take Profit or the fact that a trade server
utilizes some external mechanisms for dynamic level
control, which cannot be translated in the client
terminal. In the second case, GetLastError() can return
error 130, because MODE_STOPLEVEL is actually
"floating" here.
MODE_LOTSIZE 15 Lot size in the base currency
MODE_TICKVALUE 16 Tick value in the deposit currency
MODE_TICKSIZE 17 Tick size in points
MODE_SWAPLONG 18 Swap of the buy order
MODE_SWAPSHORT 19 Swap of the sell order
MODE_STARTING 20 Market starting date (usually used for futures)
MODE_EXPIRATION 21 Market expiration date (usually used for futures)
MODE_TRADEALLOWED 22 Trade is allowed for the symbol
MODE_MINLOT 23 Minimum permitted amount of a lot
MODE_LOTSTEP 24 Step for changing lots
MODE_MAXLOT 25 Maximum permitted amount of a lot
ID Value Description
MODE_SWAPTYPE 26 Swap calculation method. 0 - in points; 1 - in the
symbol base currency; 2 - by interest; 3 - in the margin
currency
MODE_PROFITCALCMODE 27 Profit calculation mode. 0 - Forex; 1 - CFD; 2 - Futures
MODE_MARGINCALCMODE 28 Margin calculation mode. 0 - Forex; 1 - CFD; 2 -
Futures; 3 - CFD for indices
MODE_MARGININIT 29 Initial margin requirements for 1 lot
MODE_MARGINMAINTENANCE 30 Margin to maintain open orders calculated for 1 lot
MODE_MARGINHEDGED 31 Hedged margin calculated for 1 lot
MODE_MARGINREQUIRED 32 Free margin required to open 1 lot for buying
MODE_FREEZELEVEL 33 Order freeze level in points. If the execution price lies
within the range defined by the freeze level, the
order cannot be modified, cancelled or closed
MODE_CLOSEBY_ALLOWED 34 Allowed using OrderCloseBy() to close opposite orders
on a specified symbol
Example:
//+------------------------------------------------------------------+ //| The script
//+------------------------------------------------------------------+
void OnStart()
{
Print("Symbol=",Symbol());
Print("Low day price=",MarketInfo(Symbol(),MODE_LOW));
Print("High day price=",MarketInfo(Symbol(),MODE_HIGH));
Print("The last incoming tick time=",(MarketInfo(Symbol(),MODE_TIME)));
Print("Last incoming bid price=",MarketInfo(Symbol(),MODE_BID));
Print("Last incoming ask price=",MarketInfo(Symbol(),MODE_ASK));
Print("Point size in the quote currency=",MarketInfo(Symbol(),MODE_POINT));
Print("Digits after decimal point=",MarketInfo(Symbol(),MODE_DIGITS));
Print("Spread value in points=",MarketInfo(Symbol(),MODE_SPREAD));
Print("Stop level in points=",MarketInfo(Symbol(),MODE_STOPLEVEL));
Print("Lot size in the base currency=",MarketInfo(Symbol(),MODE_LOTSIZE));
Print("Tick value in the deposit currency=",MarketInfo(Symbol(),MODE_TICKVALUE));
Print("Tick size in points=",MarketInfo(Symbol(),MODE_TICKSIZE));
Print("Swap of the buy order=",MarketInfo(Symbol(),MODE_SWAPLONG));
Print("Swap of the sell order=",MarketInfo(Symbol(),MODE_SWAPSHORT));
Print("Market starting date (for futures)=",MarketInfo(Symbol(),MODE_STARTING));
Print("Market expiration date (for futures)=",MarketInfo(Symbol(),MODE_EXPIRATION)
Print("Trade is allowed for the symbol=",MarketInfo(Symbol(),MODE_TRADEALLOWED));
Print("Minimum permitted amount of a lot=",MarketInfo(Symbol(),MODE_MINLOT));
Print("Step for changing lots=",MarketInfo(Symbol(),MODE_LOTSTEP));
Print("Maximum permitted amount of a lot=",MarketInfo(Symbol(),MODE_MAXLOT));
Print("Swap calculation method=",MarketInfo(Symbol(),MODE_SWAPTYPE));
Print("Profit calculation mode=",MarketInfo(Symbol(),MODE_PROFITCALCMODE));
Print("Margin calculation mode=",MarketInfo(Symbol(),MODE_MARGINCALCMODE));
Print("Initial margin requirements for 1 lot=",MarketInfo(Symbol(),MODE_MARGININIT
Print("Margin to maintain open orders calculated for 1 lot=",MarketInfo(Symbol(),M
Print("Hedged margin calculated for 1 lot=",MarketInfo(Symbol(),MODE_MARGINHEDGED)
Print("Free margin required to open 1 lot for buying=",MarketInfo(Symbol(),MODE_MA
Print("Order freeze level in points=",MarketInfo(Symbol(),MODE_FREEZELEVEL));
}
There are several symbol trading modes. Information about trading modes of a certain
symbol is reflected in the values of enumeration ENUM_SYMBOL_TRADE_MODE.
ENUM_SYMBOL_TRADE_MODE
Identifier Description
SYMBOL_TRADE_MODE_DISABLED Trade is disabled for the symbol
Identifier Description
SYMBOL_TRADE_MODE_LONGONLY* Allowed only long positions
SYMBOL_TRADE_MODE_SHORTONLY* Allowed only short positions
SYMBOL_TRADE_MODE_CLOSEONLY Allowed only position close operations
SYMBOL_TRADE_MODE_FULL No trade restrictions
Possible deal execution modes for a certain symbol are defined in enumeration
ENUM_SYMBOL_TRADE_EXECUTION.
ENUM_SYMBOL_TRADE_EXECUTION
Identifier Description
SYMBOL_TRADE_EXECUTION_REQUEST Execution by request
SYMBOL_TRADE_EXECUTION_INSTANT Instant execution
SYMBOL_TRADE_EXECUTION_MARKET Market execution
SYMBOL_TRADE_EXECUTION_EXCHANGE* Exchange execution
*These values are not used in MQL4 (added for compatibility with MQL5).
Values of the ENUM_DAY_OF_WEEK enumeration are used for specifying days of week.
ENUM_DAY_OF_WEEK
Identifier Description
SUNDAY Sunday
MONDAY Monday
TUESDAY Tuesday
WEDNESDAY Wednesday
THURSDAY Thursday
FRIDAY Friday
SATURDAY Saturday
MQL4 Reference / Constants, Enumerations and Structures / Environment State / Account Properties
Account Properties
To obtain information about the current account there are several functions:
AccountInfoInteger(), AccountInfoDouble() and AccountInfoString(). The function
parameter values can accept values from the corresponding ENUM_ACCOUNT_INFO
enumerations.
For the function AccountInfoInteger()
ENUM_ACCOUNT_INFO_INTEGER
Identifier Description Type
ACCOUNT_LOGIN Account number long
ACCOUNT_TRADE_MODE Account trade mode ENUM_ACCOUNT_TRADE_MODE
ACCOUNT_LEVERAGE Account leverage long
ACCOUNT_LIMIT_ORDERS Maximum allowed number of int
open positions and active
pending orders (in total), 0
unlimited
ACCOUNT_MARGIN_SO_MODE Mode for setting the minimal ENUM_ACCOUNT_STOPOUT_MODE
allowed margin
ACCOUNT_TRADE_ALLOWED Allowed trade for the current bool
account
ACCOUNT_TRADE_EXPERT Allowed trade for an Expert bool
Advisor
There are several types of accounts that can be opened on a trade server. The type of
account on which an MQL4 program is running can be found out using the
ENUM_ACCOUNT_TRADE_MODE enumeration.
ENUM_ACCOUNT_TRADE_MODE
Identifier Description
ACCOUNT_TRADE_MODE_DEMO Demo account
ACCOUNT_TRADE_MODE_CONTEST Contest account
ACCOUNT_TRADE_MODE_REAL Real account
In case equity is not enough for maintaining open orders, the Stop Out situation, i.e.
forced closing occurs. The minimum margin level at which Stop Out occurs can be set in
percentage or in monetary terms. To find out the mode set for the account use the
ENUM_ACCOUNT_STOPOUT_MODE enumeration.
ENUM_ACCOUNT_STOPOUT_MODE
Identifier Description
ACCOUNT_STOPOUT_MODE_PERCENT Account stop out mode in percents
ACCOUNT_STOPOUT_MODE_MONEY Account stop out mode in money
Testing Statistics
After the testing is over, different parameters of the trading results
statistics are calculated. The values of the parameters can be obtained
using the TesterStatistics() function, by specifying the parameter ID from
the ENUM_STATISTICS enumeration.
Although two types of parameters (int and double) are used for
calculating statistics, the function returns all values in the double form.
All the statistic values of the double type are expressed in the deposit
currency by default, unless otherwise specified.
ENUM_STATISTICS
ID Description of a statistic parameter Type
STAT_INITIAL_DEPOSIT The value of the initial deposit double
STAT_PROFIT Net profit after testing, the sum of double
STAT_GROSS_PROFIT and
STAT_GROSS_LOSS (STAT_GROSS_LOSS is
always less than or equal to zero)
STAT_GROSS_PROFIT Total profit, the sum of all profitable double
(positive) trades. The value is greater
than or equal to zero
STAT_GROSS_LOSS Total loss, the sum of all negative double
trades. The value is less than or equal
to zero
STAT_MAX_PROFITTRADE Maximum profit the largest value of all double
profitable trades. The value is greater
than or equal to zero
STAT_MAX_LOSSTRADE Maximum loss the lowest value of all double
losing trades. The value is less than or
equal to zero
STAT_CONPROFITMAX Maximum profit in a series of profitable double
trades. The value is greater than or
equal to zero
STAT_CONPROFITMAX_TRADES The number of trades that have formed int
STAT_CONPROFITMAX (maximum profit
in a series of profitable trades)
ID Description of a statistic parameter Type
STAT_MAX_CONWINS The total profit of the longest series of double
profitable trades
STAT_MAX_CONPROFIT_TRADES The number of trades in the longest int
series of profitable trades
STAT_MAX_CONWINS
STAT_CONLOSSMAX Maximum loss in a series of losing double
trades. The value is less than or equal
to zero
STAT_CONLOSSMAX_TRADES The number of trades that have formed int
STAT_CONLOSSMAX (maximum loss in a
series of losing trades)
STAT_MAX_CONLOSSES The total loss of the longest series of double
losing trades
STAT_MAX_CONLOSS_TRADES The number of trades in the longest int
series of losing trades
STAT_MAX_CONLOSSES
STAT_BALANCEMIN Minimum balance value double
STAT_BALANCE_DD Maximum balance drawdown in double
monetary terms. In the process of
trading, a balance may have numerous
drawdowns; here the largest value is
taken
STAT_BALANCEDD_PERCENT Balance drawdown as a percentage that double
was recorded at the moment of the
maximum balance drawdown in
monetary terms (STAT_BALANCE_DD).
STAT_BALANCE_DDREL_PERCENT Maximum balance drawdown as a double
percentage. In the process of trading, a
balance may have numerous
drawdowns, for each of which the
relative drawdown value in percents is
calculated. The greatest value is
returned
STAT_BALANCE_DD_RELATIVE Balance drawdown in monetary terms double
that was recorded at the moment of the
maximum balance drawdown as a
percentage
(STAT_BALANCE_DDREL_PERCENT).
ID Description of a statistic parameter Type
STAT_EQUITYMIN Minimum equity value double
STAT_EQUITY_DD Maximum equity drawdown in monetary double
terms. In the process of trading,
numerous drawdowns may appear on
the equity; here the largest value is
taken
STAT_EQUITYDD_PERCENT Drawdown in percent that was recorded double
at the moment of the maximum equity
drawdown in monetary terms
(STAT_EQUITY_DD).
STAT_EQUITY_DDREL_PERCENT Maximum equity drawdown as a double
percentage. In the process of trading,
an equity may have numerous
drawdowns, for each of which the
relative drawdown value in percents is
calculated. The greatest value is
returned
STAT_EQUITY_DD_RELATIVE Equity drawdown in monetary terms double
that was recorded at the moment of the
maximum equity drawdown in percent
(STAT_EQUITY_DDREL_PERCENT).
STAT_EXPECTED_PAYOFF Expected payoff double
STAT_PROFIT_FACTOR Profit factor, equal to the ratio of double
STAT_GROSS_PROFIT/STAT_GROSS_LOSS.
If STAT_GROSS_LOSS=0, the profit factor
is equal to DBL_MAX
STAT_MIN_MARGINLEVEL Minimum value of the margin level double
STAT_CUSTOM_ONTESTER The value of the calculated custom double
optimization criterion returned by the
OnTester() function
STAT_TRADES The number of trades int
STAT_PROFIT_TRADES Profitable trades int
STAT_LOSS_TRADES Losing trades int
STAT_SHORT_TRADES Short trades int
STAT_LONG_TRADES Long trades int
STAT_PROFIT_SHORTTRADES Profitable short trades int
ID Description of a statistic parameter Type
STAT_PROFIT_LONGTRADES Profitable long trades int
STAT_PROFITTRADES_AVGCON Average length of a profitable series of int
trades
STAT_LOSSTRADES_AVGCON Average length of a losing series of int
trades
MQL4 Reference / Constants, Enumerations and Structures / Trade
Constants
Trade Constants
Various constants used for programming trading strategies
are divided into the following groups:
History Database Properties receiving general
information on a symbol;
Order Properties obtaining information about trade
orders;
Signal Properties - obtaining information about trade
signals;
What's new in MQL5
The new platform features the netting accounting system
allowing users to trade on exchange markets. In this
regard, MQL5 contains deals and positions providing data
on the current account status and performed trading
operations. The platform also features new properties
allowing you to form trading orders considering the
specification of new financial instruments, as well as get
data on deal's type and direction. The transaction time for
orders, positions and deals is now displayed to the nearest
millisecond. You can use not only the Magic Number, but
also position ID to analyze trading.
Trading itself in MQL5 can now also be arranged in a new
way based on the control of transactions using event
handling. You do not need to survey the state of pending
orders and open positions on your own anymore. The
OnTradeTransaction() handler receives all changes on a
trading account: activated orders, performed deals,
opened positions, etc. You only need to analyze data on a
received transaction and respond to it in accordance with
your trading system logic.
The functions for working with the Depth of Market are
meant for scalping and arbitration strategies. These
functions allow you to receive all changes in buy and sell
orders from the trade server continuously and without
delay. New constants help you analyze the flow of quotes
and performed deals by all selected instruments. The fast
MQL5 language and asynchronous operations allow you to
make trading decisions in real time with no delay.
MQL4 Reference / Constants, Enumerations and Structures / Trade
Constants / History Database Properties
Order Properties
Operation type for the OrderSend() function. It can be any
of the following values:
ID Value Description
OP_BUY 0 Buy operation
OP_SELL 1 Sell operation
OP_BUYLIMIT 2 Buy limit pending order
OP_SELLLIMIT 3 Sell limit pending order
OP_BUYSTOP 4 Buy stop pending order
OP_SELLSTOP 5 Sell stop pending order
MQL4 Reference / Constants, Enumerations and Structures / Trade
Constants / Signal Properties
Signal Properties
The following enumerations are used when working with
trading signals and signal copy settings.
Enumeration of double type properties of the trading
signal:
ENUM_SIGNAL_BASE_DOUBLE
ID Description
SIGNAL_BASE_BALANCE Account balance
SIGNAL_BASE_EQUITY Account equity
SIGNAL_BASE_GAIN Account gain
SIGNAL_BASE_MAX_DRAWDOWN Account maximum
drawdown
SIGNAL_BASE_PRICE Signal subscription price
SIGNAL_BASE_ROI Return on Investment
(%)
See also
Trade signals
MQL4 Reference / Constants, Enumerations and Structures / Named
Constants
Named Constants
All constants used in MQL4 can be divided into the
following groups:
Predefined macro substitutions values are substituted
during compilation;
Mathematical constants values of some mathematical
expressions;
Numerical type constants some of the simple type
restrictions;
Uninitialization reason codes description of
uninitialization reasons;
Checking Object Pointer enumeration of types of
pointers returned by the CheckPointer() function;
Other constants all other constants.
MQL4 Reference / Constants, Enumerations and Structures / Named Constants / Predefined Macro Substitutions
Example:
#property copyright "Copyright © 2009, MetaQuotes Software Corp." #property link
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- an example of information output at Expert Advisor initialization
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__);
//--- set the interval between the timer events
EventSetTimer(5);
//---
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- an example of information output at Expert Advisor deinitialization
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__);
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- information output at tick receipt
Print(" __MQLBUILD__ = ",__MQLBUILD__," __FILE__ = ",__FILE__);
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__);
test1(__FUNCTION__);
test2();
//---
}
//+------------------------------------------------------------------+
//| test1 |
//+------------------------------------------------------------------+
void test1(string par)
{
//--- information output inside the function
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__," par = ",par);
}
//+------------------------------------------------------------------+
//| test2 |
//+------------------------------------------------------------------+
void test2()
{
//--- information output inside the function
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__);
}
//+------------------------------------------------------------------+
//| OnTimer event handler |
//+------------------------------------------------------------------+
void OnTimer()
{
//---
Print(" __FUNCTION__ = ",__FUNCTION__," __LINE__ = ",__LINE__);
test1(__FUNCTION__);
}
//+------------------------------------------------------------------+
MQL4 Reference / Constants, Enumerations and Structures / Named Constants / Mathematical Constants
Mathematical Constants
Special constants containing values are reserved for some mathematical expressions.
These constants can be used in any place of the program instead of calculating their
values using mathematical functions.
Constant Description Value
M_E e 2.71828182845904523536
M_LOG2E log2(e) 1.44269504088896340736
M_LOG10E log10(e) 0.434294481903251827651
M_LN2 ln(2) 0.693147180559945309417
M_LN10 ln(10) 2.30258509299404568402
M_PI pi 3.14159265358979323846
M_PI_2 pi/2 1.57079632679489661923
M_PI_4 pi/4 0.785398163397448309616
M_1_PI 1/pi 0.318309886183790671538
M_2_PI 2/pi 0.636619772367581343076
M_2_SQRTPI 2/sqrt(pi) 1.12837916709551257390
M_SQRT2 sqrt(2) 1.41421356237309504880
M_SQRT1_2 1/sqrt(2) 0.707106781186547524401
Example:
//+------------------------------------------------------------------+ //| Script prog
//+------------------------------------------------------------------+
void OnStart()
{
//--- print the values of constants
Print("M_E = ",DoubleToString(M_E,16));
Print("M_LOG2E = ",DoubleToString(M_LOG2E,16));
Print("M_LOG10E = ",DoubleToString(M_LOG10E,16));
Print("M_LN2 = ",DoubleToString(M_LN2,16));
Print("M_LN10 = ",DoubleToString(M_LN10,16));
Print("M_PI = ",DoubleToString(M_PI,16));
Print("M_PI_2 = ",DoubleToString(M_PI_2,16));
Print("M_PI_4 = ",DoubleToString(M_PI_4,16));
Print("M_1_PI = ",DoubleToString(M_1_PI,16));
Print("M_2_PI = ",DoubleToString(M_2_PI,16));
Print("M_2_SQRTPI = ",DoubleToString(M_2_SQRTPI,16));
Print("M_SQRT2 = ",DoubleToString(M_SQRT2,16));
Print("M_SQRT1_2 = ",DoubleToString(M_SQRT1_2,16));
}
MQL4 Reference / Constants, Enumerations and Structures / Named
Constants / Numerical Type Constants
Example:
void OnStart() {
//--- print the constant values
printf("CHAR_MIN = %d",CHAR_MIN);
printf("CHAR_MAX = %d",CHAR_MAX);
printf("UCHAR_MAX = %d",UCHAR_MAX);
printf("SHORT_MIN = %d",SHORT_MIN);
printf("SHORT_MAX = %d",SHORT_MAX);
printf("USHORT_MAX = %d",USHORT_MAX);
printf("INT_MIN = %d",INT_MIN);
printf("INT_MAX = %d",INT_MAX);
printf("UINT_MAX = %u",UINT_MAX);
printf("LONG_MIN = %I64d",LONG_MIN);
printf("LONG_MAX = %I64d",LONG_MAX);
printf("ULONG_MAX = %I64u",ULONG_MAX);
printf("EMPTY_VALUE = %.16e",EMPTY_VALUE);
printf("DBL_MIN = %.16e",DBL_MIN);
printf("DBL_MAX = %.16e",DBL_MAX);
printf("DBL_EPSILON = %.16e",DBL_EPSILON);
printf("DBL_DIG = %d",DBL_DIG);
printf("DBL_MANT_DIG = %d",DBL_MANT_DIG);
printf("DBL_MAX_10_EXP = %d",DBL_MAX_10_EXP);
printf("DBL_MAX_EXP = %d",DBL_MAX_EXP);
printf("DBL_MIN_10_EXP = %d",DBL_MIN_10_EXP);
printf("DBL_MIN_EXP = %d",DBL_MIN_EXP);
printf("FLT_MIN = %.8e",FLT_MIN);
printf("FLT_MAX = %.8e",FLT_MAX);
printf("FLT_EPSILON = %.8e",FLT_EPSILON);
}
MQL4 Reference / Constants, Enumerations and Structures / Named Constants / Uninitialization Reason Codes
See also
Runtime errors, Object Delete Operator delete,
CheckPointer()
MQL4 Reference / Constants, Enumerations and Structures / Named Constants / Other constants
Other constants
Special constants are used to indicate parameters and variables states. It can be one
of the following values:
Constant Description Value
NULL Zero for any types. Also 0
indicates empty state of the
string
EMPTY Indicates empty state of the -1
parameter
EMPTY_VALUE Empty value in an indicator 2147483647 (0x7FFFFFFF)
buffer. Default custom
indicator empty value
CLR_NONE, clrNONE Absence of color. Indicates -1
empty state of colors
CHARTS_MAX The maximum possible 100
number of simultaneously
open charts in the terminal
INVALID_HANDLE Incorrect handle -1
IS_DEBUG_MODE Flag that a mql4-program non zero in debug mode,
operates in debug mode otherwise zero
IS_PROFILE_MODE Flag that a mql4-program non zero in profiling mode,
operates in profiling mode otherwise zero
WHOLE_ARRAY Used with array functions. 0
Indicates that all array
elements will be processed.
Means the number of items
remaining until the end of
the array, i.e., the entire
array will be processed
WRONG_VALUE The constant can be -1
implicitly cast to any
enumeration type
The NULL constant can be assigned to a variable of any simple type or to an object
structure or class pointer. The NULL assignment for a string variable means the full
deinitialization of this variable.
The EMPTY_VALUE constant usually corresponds to the values of indicators that are
not shown in the chart. For example, for built-in indicator Standard Deviation with a
period of 20, the line for the first 19 bars in the history are not shown in the chart.
The CLR_NONE constant is used to outline the absence of color, it means that the
graphical object or graphical series of an indicator will not be plotted. This constant
was not included into the Web-color constants list, but it can be applied everywhere
where the color arguments are required.
The INVALID_HANDLE constant can be used for checking file handles (see FileOpen()
and FileFindFirst()).
The WRONG_VALUE constant is intended for cases, when it is necessary to return
value of an enumeration, and this must be a wrong value. For example, when we
need to inform that a return value is a value from this enumeration. Let's consider as
an example some function CheckLineStyle(), which returns the line style for an
object, specified by its name. If at style check by ObjectGetInteger() the result is
true, a value from ENUM_LINE_STYLE is returned; otherwise WRONG_VALUE is
returned.
void OnStart() {
if(CheckLineStyle("MyChartObject")==WRONG_VALUE)
printf("Error line style getting.");
}
//+------------------------------------------------------------------+
//| returns the line style for an object specified by its name |
//+------------------------------------------------------------------+
ENUM_LINE_STYLE CheckLineStyle(string name)
{
long style;
//---
if(ObjectGetInteger(0,name,OBJPROP_STYLE,0,style))
return((ENUM_LINE_STYLE)style);
else
return(WRONG_VALUE);
}
The WHOLE_ARRAY constant is intended for functions that require specifying the
number of elements in processed arrays:
ArrayCopy();
ArrayMinimum();
ArrayMaximum();
FileReadArray();
FileWriteArray().
If you want to specify that all the array values from a specified position till the end
must be processed, you should specify just the WHOLE_ARRAY value.
IS_PROFILE_MODE constant allows changing a program operation for correct data
collection in the profiling mode. Profiling allows measuring the execution time of the
individual program fragments (usually comprising functions), as well as calculating
the number of such calls. Sleep() function calls can be disabled to determine the
execution time in the profiling mode, like in this example:
//--- Sleep can greatly affect (change) profiling result
if(!IS_PROFILE_MODE) Sleep(100); // disabling Sleep() call in the profiling mode
Crypt Methods
The ENUM_CRYPT_METHOD enumeration is used to specify the data transformation
method, used in CryptEncode() and CryptDecode() functions.
ENUM_CRYPT_METHOD
Constant Description
Constant Description
CRYPT_BASE64 BASE64
CRYPT_AES128 AES encryption with 128 bit key (16 bytes)
CRYPT_AES256 AES encryption with 256 bit key (32 bytes)
CRYPT_DES DES encryption with 56 bit key (7 bytes)
CRYPT_HASH_SHA1 SHA1 HASH calculation
CRYPT_HASH_SHA256 SHA256 HASH calculation
CRYPT_HASH_MD5 MD5 HASH calculation
CRYPT_ARCH_ZIP ZIP archives
See also
DebugBreak(), Executed MQL4 program properties, CryptEncode(), CryptDecode()
MQL4 Reference / Constants, Enumerations and Structures / Data
Structures
Data Structures
MQL4 Language offers 8 predefined structures:
MqlDateTime is intended for working with date and
time;
MqlRates is intended for manipulating the historical
data, it contains information about the price, volume
and spread;
MqlTick is designed for fast retrieval of the most
requested information about current prices.
What's new in MQL5
The fifth generation platform features the significantly
expanded trading functionality. It allows working with
ticks and the Depth of Market. Order and trade request
properties have been expanded as well. The platform has
the ability to handle trading events. The economic
calendar functions have also been added. The new data
storage structures are meant for passing and handling
these huge amounts of data:
MqlParam describes inputs when creating the
IndicatorCreate() function;
MqlRates provides info on historical data containing
price, volume and spread;
MqlBookInfo gets data from the Depth of Market
(quotes window);
MqlTick is designed for obtaining the most needed data
on the current prices in a timely manner;
MqlTradeRequest is used for sending trade requests;
MqlTradeCheckResult contains results of checking a
trade request before it was sent;
MqlTradeResult returns the trade server response to a
trade request;
MqlTradeTransaction provides a description of an
obtained transaction;
Economic calendar structures are used to obtain news
and relevant macro economic indices sent directly to
the platform.
MQL4 Reference / Constants, Enumerations and Structures / Data Structures / Structure of the Date Type
MqlDateTime
The date type structure contains eight fields of the int type:
struct MqlDateTime {
int year; // Year
int mon; // Month
int day; // Day
int hour; // Hour
int min; // Minutes
int sec; // Seconds
int day_of_week; // Day of week (0-Sunday, 1-Monday, ... ,6-Saturday)
int day_of_year; // Day number of the year (January 1st is assigned the number
};
Note
The day number of the year day_of_year for the leap year, since March, will differ from
a number of the corresponding day for a non-leap year.
Example:
void OnStart()
{
//---
datetime date1=D'2008.03.01';
datetime date2=D'2009.03.01';
MqlDateTime str1,str2;
TimeToStruct(date1,str1);
TimeToStruct(date2,str2);
printf("%02d.%02d.%4d, day of year = %d",str1.day,str1.mon,
str1.year,str1.day_of_year);
printf("%02d.%02d.%4d, day of year = %d",str2.day,str2.mon,
str2.year,str2.day_of_year);
}
/* Result:
01.03.2008, day of year = 60
01.03.2009, day of year = 59
*/
See also
TimeToStruct, Structures and Classes
MQL4 Reference / Constants, Enumerations and Structures / Data Structures /
History Data Structure
MqlRates
This structure stores information about the prices, volumes and
spread.
struct MqlRates {
datetime time; // Period start time
double open; // Open price
double high; // The highest price of the period
double low; // The lowest price of the period
double close; // Close price
long tick_volume; // Tick volume
int spread; // Spread
long real_volume; // Trade volume
};
Example:
void OnStart()
{
MqlRates rates[];
int copied=CopyRates(NULL,0,0,100,rates);
if(copied<=0)
Print("Error copying price data ",GetLastError());
else Print("Copied ",ArraySize(rates)," bars");
}
See also
CopyRates, Access to timeseries
MQL4 Reference / Constants, Enumerations and Structures / Data Structures / Structure
for Current Prices
The variable of the MqlTick type allows obtaining values of Ask, Bid, Last
and Volume within a single call of the SymbolInfoTick() function.
Example:
void OnTick()
{
MqlTick last_tick;
//---
if(SymbolInfoTick(Symbol(),last_tick))
{
Print(last_tick.time,": Bid = ",last_tick.bid,
" Ask = ",last_tick.ask," Volume = ",last_tick.volume);
}
else Print("SymbolInfoTick() failed, error = ",GetLastError());
//---
}
See also
Structures and Classes
MQL4 Reference / Constants, Enumerations and Structures / Codes of
Errors and Warnings
Code ID Description
0 ERR_NO_ERROR No error returned
1 ERR_NO_RESULT No error returned, but the result is unknown
2 ERR_COMMON_ERROR Common error
3 ERR_INVALID_TRADE_PARAMETERS Invalid trade parameters
4 ERR_SERVER_BUSY Trade server is busy
5 ERR_OLD_VERSION Old version of the client terminal
6 ERR_NO_CONNECTION No connection with trade server
7 ERR_NOT_ENOUGH_RIGHTS Not enough rights
8 ERR_TOO_FREQUENT_REQUESTS Too frequent requests
9 ERR_MALFUNCTIONAL_TRADE Malfunctional trade operation
64 ERR_ACCOUNT_DISABLED Account disabled
65 ERR_INVALID_ACCOUNT Invalid account
128 ERR_TRADE_TIMEOUT Trade timeout
129 ERR_INVALID_PRICE Invalid price
130 ERR_INVALID_STOPS Invalid stops
131 ERR_INVALID_TRADE_VOLUME Invalid trade volume
132 ERR_MARKET_CLOSED Market is closed
133 ERR_TRADE_DISABLED Trade is disabled
134 ERR_NOT_ENOUGH_MONEY Not enough money
135 ERR_PRICE_CHANGED Price changed
136 ERR_OFF_QUOTES Off quotes
137 ERR_BROKER_BUSY Broker is busy
138 ERR_REQUOTE Requote
Code ID Description
139 ERR_ORDER_LOCKED Order is locked
140 ERR_LONG_POSITIONS_ONLY_ALLOWED Buy orders only allowed
141 ERR_TOO_MANY_REQUESTS Too many requests
145 ERR_TRADE_MODIFY_DENIED Modification denied because order is too close to
market
146 ERR_TRADE_CONTEXT_BUSY Trade context is busy
147 ERR_TRADE_EXPIRATION_DENIED Expirations are denied by broker
148 ERR_TRADE_TOO_MANY_ORDERS The amount of open and pending orders has
reached the limit set by the broker
149 ERR_TRADE_HEDGE_PROHIBITED An attempt to open an order opposite to the
existing one when hedging is disabled
150 ERR_TRADE_PROHIBITED_BY_FIFO An attempt to close an order contravening the
FIFO rule
MQL4 Reference / Constants, Enumerations and Structures / Codes of
Errors and Warnings / Compiler Warnings
Compiler Warnings
Compiler warnings are shown for informational purposes
only and are not error messages.
Code Description
21 Incomplete record of a date in the datetime string
22 Wrong number in the datetime string for the date.
Requirements:
Year 1970 <= X <= 3000
Month 0 <X <= 12
Day 0 <X <= 31/30/28 (29 )....
23 Wrong number of datetime string for time.
Requirements:
Hour 0 <= X <24
Minute 0 <= X <60
24 Invalid color in RGB format: one of RGB components
is less than 0 or greater than 255
25 Unknown character of the escape sequences.
Known: \n \r \t \\ \" \' \X \x
26 Too large volume of local variables (> 512Kb) of the
function, reduce the number
29 Enumeration already defined (duplication) -
members will be added to the first definition
30 Overriding macro
31 The variable is declared but is not used anywhere
32 Constructor must be of void type
Code Description
33 Destructor must be of void type
34 Constant does not fit in the range of integers (X>
_UI64_MAX | | X <_I64_MIN) and will be converted to
the double type
35 Too long HEX - more than 16 significant characters
(senior nibbles are cut)
36 No nibbles in HEX string "0x"
37 No function - nothing to be performed
38 A non-initialized variable is used
41 Function has no body, and is not called
43 Possible loss of data at typecasting. Example: int x =
(double) z;
44 Loss of accuracy (of data) when converting a
constant. Example: int x = M_PI
45 Difference between the signs of operands in the
operations of comparison. Example: (char) c1>
(uchar) c2
46 Problems with function importing - declaration of
#import is required or import of functions is closed
47 Too large description - extra characters will not be
included in the executable file
48 The number of indicator buffers declared is less than
required
49 No color to plot a graphical series in the indicator
50 No graphical series to draw the indicator
51 'OnStart' handler function not found in the script
Code Description
52 'OnStart' handler function is defined with wrong
parameters
53 'OnStart' function can be defined only in a script
54 'OnInit' function is defined with wrong parameters
55 'OnInit' function is not used in scripts
56 'OnDeinit' function is defined with wrong parameters
57 'OnDeinit' function is not used in scripts
58 Two 'OnCalculate' functions are defined. OnCalculate
() at one price array will be used
59 Overfilling detected when calculating a complex
integer constant
60 Probably, the variable is not initialized.
61 This declaration makes it impossible to refer to the
local variable declared on the specified line
62 This declaration makes it impossible to refer to the
global variable declared on the specified line
63 Cannot be used for static allocated array
64 This variable declaration hides predefined variable
65 The value of the expression is always true/false
66 Using a variable or bool type expression in
mathematical operations is unsafe
67 The result of applying the unary minus operator to
an unsigned ulong type is undefined
68 The version specified in the #property version
property is unacceptable for the Market section; the
correct format of #property version id "XXX.YYY"
Code Description
69 Empty controlled statement found
70 Invalid function return type or incorrect parameters
during declaration of the event handler function
71 An implicit cast of structures to one type is required
72 This declaration makes direct access to the member
of a class declared in the specified string impossible.
Access will be possible only with the scope resolution
operation ::
73 Binary constant is too big, high-order digits will be
truncated
74 Parameter in the method of the inherited class has a
different const modifier, the derived function has
overloaded the parent function
75 Negative or too large shift value in shift bitwise
operation, execution result is undefined
76 Function must return a value
77 void function returns a value
78 Not all control paths return a value
79 Expressions are not allowed on a global scope
80 Check operator precedence for possible error; use
parentheses to clarify precedence
81 Two OnCalCulate() are defined. OHLC version will be
used
82 Struct has no members, size assigned to 1 byte
83 Return value of the function should be checked
Code Description
84 Resource indicator is compiled for debugging. That
slows down the performance. Please recompile the
indicator to increase performance
85 Too great character code in the string, must be in
the range 0 to 65535
86 Unrecognized character in the string
87 No indicator window property (setting the display in
the main window or a subwindow) is defined.
Property #property indicator_chart_window is
applied
88 Property ignored, it must be declared on the global
scope. The warning is not generated for the
following properties: copyright, link, version and
strict.
MQL4 Reference / Constants, Enumerations and Structures / Codes of
Errors and Warnings / Compilation Errors
Compilation Errors
MetaEdtior 5 shows error messages about the program
errors detected by the built-in compiler during
compilation. The list of these errors is given below in
table. To compile a source code into an executable one,
press F7. Programs that contain errors cannot be
compiled until the errors identified by the compiler are
eliminated.
Code Description
100 File reading error
101 Error of opening an *. EX4 for writing
103 Not enough free memory to complete compilation
104 Empty syntactic unit unrecognized by compiler
105 Incorrect file name in #include
106 Error accessing a file in #include (probably the file
does not exist)
108 Inappropriate name for #define
109 Unknown command of preprocessor (valid #include,
#define, #property, #import)
110 Symbol unknown to compiler
111 Function not implemented (description is present,
but no body)
112 Double quote (") omitted
Code Description
113 Opening angle bracket (<) or double quote (")
omitted
114 Single quote (') omitted
115 Closing angle bracket ">" omitted
116 Type not specified in declaration
117 No return operator or return is found not in all
branches of the implementation
118 Opening bracket of call parameters was expected
119 Error writing EX4
120 Invalid access to an array
121 The function is not of void type and the return
operator must return a value
122 Incorrect declaration of the destructor
123 Colon ":" is missing
124 Variable is already declared
125 Variable with such identifier already declared
126 Variable name is too long (> 250 characters)
127 Structure with such identifier already defined
128 Structure is not defined
129 Structure member with the same name already
defined
130 No such structure member
131 Breached pairing of brackets
132 Opening parenthesis "(" expected
Code Description
133 Unbalanced braces (no "}")
134 Difficult to compile (too much branching, internal
stack levels are overfilled)
135 Error of file opening for reading
136 Not enough memory to download the source file into
memory
137 Variable is expected
138 Reference cannot be initialized
140 Assignment expected (appears at declaration)
141 Opening brace "{" expected
142 Parameter can be a dynamic array only
143 Use of "void" type is unacceptable
144 No pair for ")" or "]", i.e. "(or" [ " is absent
145 No pair for "(or" [ ", i.e. ") "or"] " is absent
146 Incorrect array size
147 Too many parameters (> 64)
149 This token is not expected here
150 Invalid use of operation (invalid operands)
151 Expression of void type not allowed
152 Operator is expected
153 Misuse of break
154 Semicolon ";" expected
155 Comma "," expected
156 Must be a class type, not struct
Code Description
157 Expression is expected
158 "non HEX character" found in HEX or too long number
(number of digits> 511)
159 String-constant has more than 65534 characters
160 Function definition is unacceptable here
161 Unexpected end of program
162 Forward declaration is prohibited for structures
163 Function with this name is already defined and has
another return type
164 Function with this name is already defined and has a
different set of parameters
165 Function with this name is already defined and
implemented
166 Function overload for this call was not found
167 Function with a return value of void type cannot
return a value
168 Function is not defined
170 Value is expected
171 In case expression only integer constants are valid
172 The value of case in this switch is already used
173 Integer is expected
174 In #import expression file name is expected
175 Expressions are not allowed on global level
176 Omitted parenthesis ")" before ";"
177 To the left of equality sign a variable is expected
Code Description
178 The result of expression is not used
179 Declaring of variables is not allowed in case
180 Implicit conversion from a string to a number
181 Implicit conversion of a number to a string
182 Ambiguous call of an overloaded function (several
overloads fit)
183 Illegal else without proper if
184 Invalid case or default without a switch
185 Inappropriate use of ellipsis
186 The initializing sequence has more elements than the
initialized variable
187 A constant for case expected
188 A constant expression required
189 A constant variable cannot be changed
190 Closing bracket or a comma is expected (declaring
array member)
191 Enumerator identifier already defined
192 Enumeration cannot have access modifiers (const,
extern, static)
193 Enumeration member already declared with a
different value
194 There is a variable defined with the same name
195 There is a structure defined with the same name
196 Name of enumeration member expected
197 Integer expression expected
Code Description
198 Division by zero in constant expression
199 Wrong number of parameters in the function
200 Parameter by reference must be a variable
201 Variable of the same type to pass by reference
expected
202 A constant variable cannot be passed by a non-
constant reference
203 Requires a positive integer constant
204 Failed to access protected class member
205 Import already defined in another way
208 Executable file not created
209 'OnCalculate' entry point not found for the indicator
210 The continue operation can be used only inside a
loop
211 Error accessing private (closed) class member
213 Method of structure or class is not declared
214 Error accessing private (closed) class method
216 Copying of structures with objects is not allowed
218 Index out of array range
219 Array initialization in structure or class declaration
not allowed
220 Class constructor cannot have parameters
221 Class destructor can not have parameters
222 Class method or structure with the same name and
parameters have already been declared
Code Description
223 Operand expected
224 Class method or structure with the same name
exists, but with different parameters
(declaration!=implementation)
225 Imported function is not described
226 ZeroMemory() is not allowed for objects with
protected members or inheritance
227 Ambiguous call of the overloaded function (exact
match of parameters for several overloads)
228 Variable name expected
229 A reference cannot be declared in this place
230 Already used as the enumeration name
232 Class or structure expected
235 Cannot call 'delete' operator to delete the array
236 Operator ' while' expected
237 Operator 'delete' must have a pointer
238 There is 'default' for this 'switch' already
239 Syntax error
240 Escape-sequence can occur only in strings (starts
with '\')
241 Array required - square bracket '[' does not apply to
an array, or non arrays are passed as array
parameters
242 Can not be initialized through the initialization
sequence
243 Import is not defined
Code Description
244 Optimizer error on the syntactic tree
245 Declared too many structures (try to simplify the
program)
246 Conversion of the parameter is not allowed
247 Incorrect use of the 'delete' operator
248 It's not allowed to declare a pointer to a reference
249 It's not allowed to declare a reference to a reference
250 It's not allowed to declare a pointer to a pointer
251 Structure declaration in the list of parameter is not
allowed
252 Invalid operation of typecasting
253 A pointer can be declared only for a class or
structure
256 Undeclared identifier
257 Executable code optimizer error
258 Executable code generation error
260 Invalid expression for the 'switch' operator
261 Pool of string constants overfilled, simplify program
262 Cannot convert to enumeration
263 Do not use 'virtual' for data (members of a class or
structure)
264 Cannot call protected method of class
265 Overridden virtual functions return a different type
266 Class cannot be inherited from a structure
Code Description
267 Structure cannot be inherited from a class
268 Constructor cannot be virtual (virtual specifier is not
allowed)
269 Method of structure cannot be virtual
270 Function must have a body
271 Overloading of system functions (terminal functions)
is prohibited
272 Const specifier is invalid for functions that are not
members of a class or structure
274 Not allowed to change class members in constant
method
276 Inappropriate initialization sequence
277 Missed default value for the parameter (specific
declaration of default parameters)
278 Overriding the default parameter (different values in
declaration and implementation)
279 Not allowed to call non-constant method for a
constant object
280 An object is necessary for accessing members (a dot
for a non class/structure is set)
281 The name of an already declared structure cannot be
used in declaration
284 Unauthorized conversion (at closed inheritance)
285 Structures and arrays cannot be used as input
variables
286 Const specifier is not valid for
constructor/destructor
Code Description
287 Incorrect string expression for a datetime
288 Unknown property (#property)
289 Incorrect value of a property
290 Invalid index for a property in #property
291 Call parameter omitted - <func (x,)>
293 Object must be passed by reference
294 Array must be passed by reference
295 Function was declared as exportable
296 Function was not declared as exportable
297 It is prohibited to export imported function
298 Imported function cannot have this parameter
(prohibited to pass a pointer, class or structure
containing a dynamic array, pointer, class, etc.)
299 Must be a class
300 #import was not closed
302 Type mismatch
303 Extern variable is already initialized
304 No exported function or entry point found
305 Explicit constructor call is not allowed
306 Method was declared as constant
307 Method was not declared as constant
308 Incorrect size of the resource file
309 Incorrect resource name
310 Resource file opening error
Code Description
311 Resource file reading error
312 Unknown resource type
313 Incorrect path to the resource file
314 The specified resource name is already used
315 Argument expected for the function-like macro
316 Unexpected symbol in macro definition
317 Error in formal parameters of the macro
318 Invalid number of parameters for a macro
319 Too many parameters for a macro
320 Too complex, simplify the macro
321 Parameter for EnumToString() can be only an
enumeration
322 The resource name is too long
323 Unsupported image format (only BMP with 24 or 32
bit color depth is supported)
324 An array cannot be declared in operator
325 The function can be declared only in the global
scope
326 The declaration is not allowed for the current scope
327 Initialization of static variables with the values of
local variables is not allowed
328 Illegal declaration of an array of objects that do not
have a default constructor
329 Initialization list allowed only for constructors
330 No function definition after initialization list
Code Description
331 Initialization list is empty
332 Array initialization in a constructor is not allowed
333 Initializing members of a parent class in the
initialization list is not allowed
334 Expression of the integer type expected
335 Memory required for the array exceeds the maximum
value
336 Memory required for the structure exceeds the
maximum value
337 Memory required for the variables declared on the
global level exceeds the maximum value
338 Memory required for local variables exceeds the
maximum value
339 Constructor not defined
340 Invalid name of the icon file
341 Could not open the icon file at the specified path
342 The icon file is incorrect and is not of the ICO format
343 Reinitialization of a member in a class/structure
constructor using the initialization list
344 Initialization of static members in the constructor
initialization list is not allowed
345 Initialization of a non-static member of a
class/structure on a global level is not allowed
346 The name of the class/structure method matches the
name of an earlier declared member
Code Description
347 The name of the class/structure member matches
the name of an earlier declared method
348 Virtual function cannot be declared as static
349 The const modifier is not allowed for static functions
350 Constructor or destructor cannot be static
351 Non-static member/method of a class or a structure
cannot be accessed from a static function
352 An overload operation (+,-,[],++,-- etc.) is expected
after the operator keyword
353 Not all operations can be overloaded in MQL4
354 Definition does not match declaration
355 An invalid number of parameters is specified for the
operator
356 Event handling function not found
357 Method cannot be exported
358 A pointer to the constant object cannot be
normalized by a non-constant object
359 Class templates are not supported yet
360 Function template overload is not supported yet
361 Function template cannot be applied
362 Ambiguous parameter in function template (several
parameter types can be applied)
363 Unable to determine the parameter type, by which
the function template argument should be
normalized
Code Description
364 Incorrect number of parameters in the function
template
365 Function template cannot be virtual
366 Function templates cannot be exported
367 Function templates cannot be imported
368 Structures containing the objects are not allowed
369 String arrays and structures containing the objects
are not allowed
370 A static class/structure member must be explicitly
initialized
371 Compiler limitation: the string cannot contain more
than 65 535 characters
372 Inconsistent #ifdef/#endif
373 Object of class cannot be returned, copy constructor
not found
374 Non-static members and methods cannot be used
375 OnTesterInit() impossible to use without
OnTesterDeinit()
376 Redefinition of formal parameter '%s'
377 Macro __FUNCSIG__ and __FUNCTION__ cannot
appear outside of a function body
378 Invalid returned type. For example, this error will be
produced for functions imported from DLL that
return structure or pointer.
379 Template usage error
380 Not used
Code Description
381 Illegal syntax when declaring pure virtual function,
only "=NULL" or "=0" are allowed
382 Only virtual functions can be declared with the pure-
specifier ("=NULL" or "=0")
383 Abstract class cannot be instantiated
384 A pointer to a user-defined type should be applied as
a target type for dynamic casting using the
dynamic_cast operator
385 "Pointer to function" type is expected
386 Pointers to methods are not supported
387 Error cannot define the type of a pointer to function
388 Type cast is not available due to private inheritance
389 A variable with const modifier should be initialized
during declaration
MQL4 Reference / Constants, Enumerations and Structures / Codes of
Errors and Warnings / Runtime Errors
Runtime Errors
The GetLastError() function return last error code, stored in
_LastError predefined variable. This value can be reset using
the ResetLastError() function. Error code constants defined at
stderror.mqh file. To print text messages use
ErrorDescription() function defined at stdlib.mqh file.
For convenience, trade errors are additionally listed in the
Trade Server Return Codes section.
Runtime errors of mql4-program:
Code ID Description
0 ERR_NO_ERROR No error
returned
1 ERR_NO_RESULT No error
returned, but
the result is
unknown
2 ERR_COMMON_ERROR Common error
3 ERR_INVALID_TRADE_PARAMETERS Invalid trade
parameters
4 ERR_SERVER_BUSY Trade server is
busy
5 ERR_OLD_VERSION Old version of
the client
terminal
6 ERR_NO_CONNECTION No connection
with trade
server
Code ID Description
7 ERR_NOT_ENOUGH_RIGHTS Not enough
rights
8 ERR_TOO_FREQUENT_REQUESTS Too frequent
requests
9 ERR_MALFUNCTIONAL_TRADE Malfunctional
trade operation
64 ERR_ACCOUNT_DISABLED Account
disabled
65 ERR_INVALID_ACCOUNT Invalid account
128 ERR_TRADE_TIMEOUT Trade timeout
129 ERR_INVALID_PRICE Invalid price
130 ERR_INVALID_STOPS Invalid stops
131 ERR_INVALID_TRADE_VOLUME Invalid trade
volume
132 ERR_MARKET_CLOSED Market is closed
133 ERR_TRADE_DISABLED Trade is
disabled
134 ERR_NOT_ENOUGH_MONEY Not enough
money
135 ERR_PRICE_CHANGED Price changed
136 ERR_OFF_QUOTES Off quotes
137 ERR_BROKER_BUSY Broker is busy
138 ERR_REQUOTE Requote
139 ERR_ORDER_LOCKED Order is locked
140 ERR_LONG_POSITIONS_ONLY_ALLOWED Buy orders only
allowed
141 ERR_TOO_MANY_REQUESTS Too many
requests
Code ID Description
145 ERR_TRADE_MODIFY_DENIED Modification
denied because
order is too
close to market
146 ERR_TRADE_CONTEXT_BUSY Trade context is
busy
147 ERR_TRADE_EXPIRATION_DENIED Expirations are
denied by
broker
148 ERR_TRADE_TOO_MANY_ORDERS The amount of
open and
pending orders
has reached the
limit set by the
broker
149 ERR_TRADE_HEDGE_PROHIBITED An attempt to
open an order
opposite to the
existing one
when hedging is
disabled
150 ERR_TRADE_PROHIBITED_BY_FIFO An attempt to
close an order
contravening
the FIFO rule
4000 ERR_NO_MQLERROR No error
returned
4001 ERR_WRONG_FUNCTION_POINTER Wrong function
pointer
4002 ERR_ARRAY_INDEX_OUT_OF_RANGE Array index is
out of range
Code ID Description
4003 ERR_NO_MEMORY_FOR_CALL_STACK No memory for
function call
stack
4004 ERR_RECURSIVE_STACK_OVERFLOW Recursive stack
overflow
4005 ERR_NOT_ENOUGH_STACK_FOR_PARAM Not enough
stack for
parameter
4006 ERR_NO_MEMORY_FOR_PARAM_STRING No memory for
parameter
string
4007 ERR_NO_MEMORY_FOR_TEMP_STRING No memory for
temp string
4008 ERR_NOT_INITIALIZED_STRING Not initialized
string
4009 ERR_NOT_INITIALIZED_ARRAYSTRING Not initialized
string in array
4010 ERR_NO_MEMORY_FOR_ARRAYSTRING No memory for
array string
4011 ERR_TOO_LONG_STRING Too long string
4012 ERR_REMAINDER_FROM_ZERO_DIVIDE Remainder from
zero divide
4013 ERR_ZERO_DIVIDE Zero divide
4014 ERR_UNKNOWN_COMMAND Unknown
command
4015 ERR_WRONG_JUMP Wrong jump
(never
generated
error)
Code ID Description
4016 ERR_NOT_INITIALIZED_ARRAY Not initialized
array
4017 ERR_DLL_CALLS_NOT_ALLOWED DLL calls are
not allowed
4018 ERR_CANNOT_LOAD_LIBRARY Cannot load
library
4019 ERR_CANNOT_CALL_FUNCTION Cannot call
function
4020 ERR_EXTERNAL_CALLS_NOT_ALLOWED Expert function
calls are not
allowed
4021 ERR_NO_MEMORY_FOR_RETURNED_STR Not enough
memory for
temp string
returned from
function
4022 ERR_SYSTEM_BUSY System is busy
(never
generated
error)
4023 ERR_DLLFUNC_CRITICALERROR DLL-function
call critical
error
4024 ERR_INTERNAL_ERROR Internal error
4025 ERR_OUT_OF_MEMORY Out of memory
4026 ERR_INVALID_POINTER Invalid pointer
4027 ERR_FORMAT_TOO_MANY_FORMATTERS Too many
formatters in
the format
function
Code ID Description
4028 ERR_FORMAT_TOO_MANY_PARAMETERS Parameters
count exceeds
formatters
count
4029 ERR_ARRAY_INVALID Invalid array
4030 ERR_CHART_NOREPLY No reply from
chart
4050 ERR_INVALID_FUNCTION_PARAMSCNT Invalid function
parameters
count
4051 ERR_INVALID_FUNCTION_PARAMVALUE Invalid function
parameter
value
4052 ERR_STRING_FUNCTION_INTERNAL String function
internal error
4053 ERR_SOME_ARRAY_ERROR Some array
error
4054 ERR_INCORRECT_SERIESARRAY_USING Incorrect series
array using
4055 ERR_CUSTOM_INDICATOR_ERROR Custom
indicator error
4056 ERR_INCOMPATIBLE_ARRAYS Arrays are
incompatible
4057 ERR_GLOBAL_VARIABLES_PROCESSING Global
variables
processing
error
4058 ERR_GLOBAL_VARIABLE_NOT_FOUND Global variable
not found
Code ID Description
4059 ERR_FUNC_NOT_ALLOWED_IN_TESTING Function is not
allowed in
testing mode
4060 ERR_FUNCTION_NOT_CONFIRMED Function is not
allowed for call
4061 ERR_SEND_MAIL_ERROR Send mail error
4062 ERR_STRING_PARAMETER_EXPECTED String
parameter
expected
4063 ERR_INTEGER_PARAMETER_EXPECTED Integer
parameter
expected
4064 ERR_DOUBLE_PARAMETER_EXPECTED Double
parameter
expected
4065 ERR_ARRAY_AS_PARAMETER_EXPECTED Array as
parameter
expected
4066 ERR_HISTORY_WILL_UPDATED Requested
history data is
in updating
state
4067 ERR_TRADE_ERROR Internal trade
error
4068 ERR_RESOURCE_NOT_FOUND Resource not
found
4069 ERR_RESOURCE_NOT_SUPPORTED Resource not
supported
4070 ERR_RESOURCE_DUPLICATED Duplicate
resource
Code ID Description
4071 ERR_INDICATOR_CANNOT_INIT Custom
indicator
cannot
initialize
4072 ERR_INDICATOR_CANNOT_LOAD Cannot load
custom
indicator
4073 ERR_NO_HISTORY_DATA No history data
4074 ERR_NO_MEMORY_FOR_HISTORY No memory for
history data
4075 ERR_NO_MEMORY_FOR_INDICATOR Not enough
memory for
indicator
calculation
4099 ERR_END_OF_FILE End of file
4100 ERR_SOME_FILE_ERROR Some file error
4101 ERR_WRONG_FILE_NAME Wrong file
name
4102 ERR_TOO_MANY_OPENED_FILES Too many
opened files
4103 ERR_CANNOT_OPEN_FILE Cannot open
file
4104 ERR_INCOMPATIBLE_FILEACCESS Incompatible
access to a file
4105 ERR_NO_ORDER_SELECTED No order
selected
4106 ERR_UNKNOWN_SYMBOL Unknown
symbol
4107 ERR_INVALID_PRICE_PARAM Invalid price
4108 ERR_INVALID_TICKET Invalid ticket
Code ID Description
4109 ERR_TRADE_NOT_ALLOWED Trade is not
allowed. Enable
checkbox
"Allow live
trading" in the
Expert Advisor
properties
4110 ERR_LONGS_NOT_ALLOWED Longs are not
allowed. Check
the Expert
Advisor
properties
4111 ERR_SHORTS_NOT_ALLOWED Shorts are not
allowed. Check
the Expert
Advisor
properties
4112 ERR_TRADE_EXPERT_DISABLED_BY_SERVER Automated
trading by
Expert
Advisors/Scripts
disabled by
trade server
4200 ERR_OBJECT_ALREADY_EXISTS Object already
exists
4201 ERR_UNKNOWN_OBJECT_PROPERTY Unknown
object property
4202 ERR_OBJECT_DOES_NOT_EXIST Object does not
exist
4203 ERR_UNKNOWN_OBJECT_TYPE Unknown
object type
4204 ERR_NO_OBJECT_NAME No object name
Code ID Description
4205 ERR_OBJECT_COORDINATES_ERROR Object
coordinates
error
4206 ERR_NO_SPECIFIED_SUBWINDOW No specified
subwindow
4207 ERR_SOME_OBJECT_ERROR Graphical
object error
4210 ERR_CHART_PROP_INVALID Unknown chart
property
4211 ERR_CHART_NOT_FOUND Chart not found
4212 ERR_CHARTWINDOW_NOT_FOUND Chart
subwindow not
found
4213 ERR_CHARTINDICATOR_NOT_FOUND Chart indicator
not found
4220 ERR_SYMBOL_SELECT Symbol select
error
4250 ERR_NOTIFICATION_ERROR Notification
error
4251 ERR_NOTIFICATION_PARAMETER Notification
parameter
error
4252 ERR_NOTIFICATION_SETTINGS Notifications
disabled
4253 ERR_NOTIFICATION_TOO_FREQUENT Notification
send too
frequent
4260 ERR_FTP_NOSERVER FTP server is
not specified
Code ID Description
4261 ERR_FTP_NOLOGIN FTP login is not
specified
4262 ERR_FTP_CONNECT_FAILED FTP connection
failed
4263 ERR_FTP_CLOSED FTP connection
closed
4264 ERR_FTP_CHANGEDIR FTP path not
found on server
4265 ERR_FTP_FILE_ERROR File not found
in the
MQL4\Files
directory to
send on FTP
server
4266 ERR_FTP_ERROR Common error
during FTP data
transmission
5001 ERR_FILE_TOO_MANY_OPENED Too many
opened files
5002 ERR_FILE_WRONG_FILENAME Wrong file
name
5003 ERR_FILE_TOO_LONG_FILENAME Too long file
name
5004 ERR_FILE_CANNOT_OPEN Cannot open
file
5005 ERR_FILE_BUFFER_ALLOCATION_ERROR Text file buffer
allocation error
5006 ERR_FILE_CANNOT_DELETE Cannot delete
file
Code ID Description
5007 ERR_FILE_INVALID_HANDLE Invalid file
handle (file
closed or was
not opened)
5008 ERR_FILE_WRONG_HANDLE Wrong file
handle (handle
index is out of
handle table)
5009 ERR_FILE_NOT_TOWRITE File must be
opened with
FILE_WRITE flag
5010 ERR_FILE_NOT_TOREAD File must be
opened with
FILE_READ flag
5011 ERR_FILE_NOT_BIN File must be
opened with
FILE_BIN flag
5012 ERR_FILE_NOT_TXT File must be
opened with
FILE_TXT flag
5013 ERR_FILE_NOT_TXTORCSV File must be
opened with
FILE_TXT or
FILE_CSV flag
5014 ERR_FILE_NOT_CSV File must be
opened with
FILE_CSV flag
5015 ERR_FILE_READ_ERROR File read error
5016 ERR_FILE_WRITE_ERROR File write error
Code ID Description
5017 ERR_FILE_BIN_STRINGSIZE String size must
be specified for
binary file
5018 ERR_FILE_INCOMPATIBLE Incompatible
file (for string
arrays-TXT, for
others-BIN)
5019 ERR_FILE_IS_DIRECTORY File is directory
not file
5020 ERR_FILE_NOT_EXIST File does not
exist
5021 ERR_FILE_CANNOT_REWRITE File cannot be
rewritten
5022 ERR_FILE_WRONG_DIRECTORYNAME Wrong directory
name
5023 ERR_FILE_DIRECTORY_NOT_EXIST Directory does
not exist
5024 ERR_FILE_NOT_DIRECTORY Specified file is
not directory
5025 ERR_FILE_CANNOT_DELETE_DIRECTORY Cannot delete
directory
5026 ERR_FILE_CANNOT_CLEAN_DIRECTORY Cannot clean
directory
5027 ERR_FILE_ARRAYRESIZE_ERROR Array resize
error
5028 ERR_FILE_STRINGRESIZE_ERROR String resize
error
5029 ERR_FILE_STRUCT_WITH_OBJECTS Structure
contains strings
or dynamic
arrays
Code ID Description
5200 ERR_WEBREQUEST_INVALID_ADDRESS Invalid URL
5201 ERR_WEBREQUEST_CONNECT_FAILED Failed to
connect to
specified URL
5202 ERR_WEBREQUEST_TIMEOUT Timeout
exceeded
5203 ERR_WEBREQUEST_REQUEST_FAILED HTTP request
failed
User errors
65536 ERR_USER_ERROR_FIRST User defined
errors start
with this code
MQL4 Reference / Constants, Enumerations and Structures /
Input/Output Constants
There are some specific features of work when you specify read and
write flags:
If FILE_READ is specified, an attempt is made to open an existing
file. If a file does not exist, file opening fails, a new file is not
created.
FILE_READ|FILE_WRITE a new file is created if the file with the
specified name does not exist.
FILE_WRITE the file is created again with a zero size.
When opening a file, specification of FILE_WRITE and/or FILE_READ is
required.
Flags that define the type of reading of an open file possess priority.
The highest flag is FILE_CSV, then goes FILE_BIN, and FILE_TXT is of
lowest priority. Thus, if several flags are specified at the same time,
(FILE_TXT|FILE_CSV or FILE_TXT|FILE_BIN or FILE_BIN|FILE_CSV), the
flag with the highest priority will be used.
Flags that define the type of encoding also have priority. FILE_UNICODE
is of a higher priority than FILE_ANSI. So if you specify combination
FILE_UNICODE|FILE_ANSI, flag FILE_UNICODE will be used.
If neither FILE_UNICODE nor FILE_ANSI is indicated, FILE_UNICODE is
implied. If neither FILE_CSV, nor FILE_BIN, nor FILE_TXT is specified,
FILE_CSV is implied.
If a file is opened for reading as a text file (FILE_TXT or FILE_CSV), and
at the file beginning a special two-byte indication 0xff,0xfe is found,
the encoding flag will be FILE_UNICODE, even if FILE_ANSI is specified.
See also
File Functions
MQL4 Reference / Constants, Enumerations and Structures /
Input/Output Constants / File Properties
File Properties
The FileGetInteger() function is used for obtaining file
properties. The identifier of the required property from
the ENUM_FILE_PROPERTY_INTEGER enumeration is
passed to it during call.
ENUM_FILE_PROPERTY_INTEGER
ID ID description
FILE_EXISTS Check the existence
FILE_CREATE_DATE Date of creation
FILE_MODIFY_DATE Date of the last modification
FILE_ACCESS_DATE Date of the last access to the file
FILE_SIZE File size in bytes
FILE_POSITION Position of a pointer in the file
FILE_END Get the end of file sign
FILE_LINE_END Get the end of line sign
FILE_IS_COMMON The file is opened in a shared folder of all
terminals (see FILE_COMMON)
FILE_IS_TEXT The file is opened as a text file (see
FILE_TXT)
FILE_IS_BINARY The file is opened as a binary file (see
FILE_BIN)
FILE_IS_CSV The file is opened as CSV (see FILE_CSV)
FILE_IS_ANSI The file is opened as ANSI (see FILE_ANSI)
ID ID description
FILE_IS_READABLE The opened file is readable (see
FILE_READ)
FILE_IS_WRITABLE The opened file is writable (see
FILE_WRITE)
See also
FileIsEnding, FileIsLineEnding
MQL4 Reference / Constants, Enumerations and Structures /
Input/Output Constants / Use of a Codepage
See also
Client Terminal Properties
MQL4 Reference / Constants, Enumerations and Structures /
Input/Output Constants / MessageBox
The main flags of the MessageBox() function define
contents and behavior of the dialog window. This value
can be a combination of the following flag groups:
Constant Value Description
MB_OK 0x00000000 Message window
contains only one
button: OK. Default
MB_OKCANCEL 0x00000001 Message window
contains two buttons:
OK and Cancel
MB_ABORTRETRYIGNORE 0x00000002 Message window
contains three
buttons: Abort, Retry
and Ignore
MB_YESNOCANCEL 0x00000003 Message window
contains three
buttons: Yes, No and
Cancel
MB_YESNO 0x00000004 Message window
contains two buttons:
Yes and No
MB_RETRYCANCEL 0x00000005 Message window
contains two buttons:
Retry and Cancel
MB_CANCELTRYCONTINUE 0x00000006 Message window
contains three
buttons: Cancel, Try
Again, Continue
MQL4 Reference / MQL4 programs
MQL4 Programs
For the mql4-program to operate, it must be compiled
(Compile button or F7 key). Compilation should pass
without errors (some warnings are possible; they should
be analyzed). At this process, an executable file with the
same name and with EX4 extension must be created in the
corresponding directory, terminal_dir\MQL4\Experts,
terminal_dir\MQL4\indicators or
terminal_dir\MQL4\scripts. This file can be run.
Operating features of MQL4 programs are described in the
following sections:
Program running order of calling predefined event-
handlers.
Client terminal events description of events, which can
be processed in programs.
Call of imported functions description order, allowed
parameters, search details and call agreement for
imported functions.
Runtime errors getting information about runtime and
critical errors.
Expert Advisors, custom indicators and scripts are
attached to one of opened charts by Drag'n'Drop method
from the Navigator window.
For an expert Advisor to stop operating, it should be
removed from a chart. To do it select "Expert list" in chart
context menu, then select an Expert Advisor from list and
click "Remove" button. Operation of Expert Advisors is also
affected by the state of the "AutoTrading" button.
In order to stop a custom indicator, it should be removed
from a chart.
Custom indicators and Expert Advisors work until they are
explicitly removed from a chart; information about
attached Expert Advisors and Indicators is saved between
client terminal sessions.
Scripts are executed once and are deleted automatically
upon operation completion or change of the current chart
state, or upon client terminal shutdown. After the restart
of the client terminal scripts are not started, because the
information about them is not saved.
Maximum one Expert Advisor, one script and unlimited
number of indicators can operate in one chart.
What's new in MQL5
In MQL5, the entire program logic is based on handling
events. The event handling functions allow you to develop
trading algorithms, create user interfaces, as well as
collect and visualize optimization results. The number of
events has increased. The five most important ones are as
follows:
NewTick occurs when new quotes arrive and handled in
EAs by the OnTick() function
Calculate created only for indicators in case of any
change in price data and handled by the OnCalculate()
function
Trade generated upon completion of a trading
operation on a trade server and handled by the
OnTrade()
TradeTransaction sent by a trade server to the terminal
in case of changes on a trading account and handled by
the OnTradeTransaction() function
BookEvent reports Depth of Market changes and
handled by the OnBookEvent() function.
Developers of trading robots will appreciate the new
tester features described in the articles and
documentation. The most notable advantages are as
follows:
Automatic history download and synchronization of
bars on all timeframes all the history required for
testing is downloaded by the terminal automatically.
Using real ticks during a test now you can test your
trading on history as accurately as possible. Arrival of
ticks is emulated on all symbols.
Multi-currency testing allows users to develop
strategies trading on multiple symbols, while ticks and
bars are synchronized correctly on all symbols and the
trading environment is emulated accurately, including
spreads, margin requirements and profit calculation in
the required deposit currency.
The OnTimer() and Sleep() functions work in the tester
correctly and are available for debugging.
The multi-threaded tester uses all CPU cores allowing
you to perform optimization on thousands of agents
from MQL5 Cloud Network.
MQL4 Reference / MQL4 programs / Program Running
Program Running
Each script and each Expert Advisor runs in its own separate thread. All indicators work
in the graphic interface thread. processing of ticks and history synchronization are also
performed in graphic interface thread. Custom indicators work in the main interface
thread. If a custom indicator has been called with the iCustom() function, this indicator
works in the thread of the program that has called it. Library (imported) functions work
in the calling program thread, as well.
When running an Expert Advisor, make sure that it has an actual trading environment and
can access the history of the required symbol and period, and synchronize data between
the terminal and the server. For all these procedures, the terminal provides a start delay
of no more than 5 seconds, after which the Expert Advisor will be started with available
data. Therefore, in case there is no connection to the server, this may lead to a delay in
the start of an Expert Advisor.
The below table contains a brief summary of MQL4 programs:
Program Running Note
Script A separate thread, the number of threads for A looped script cannot break
scripts is equal to the number of scripts running of other programs
Expert Advisor A separate thread, the number of threads for A looped Expert Advisor
Expert Advisors is equal to the number of cannot break running of
Expert Advisors other programs
Indicator All indicators share the resources of graphic An infinite loop in one
interface thread of the terminal indicator will stop the work
of terminal
A client terminal sends new events to the corresponding open charts. Events can also be
generated by charts (chart events) or mql4-programs (custom events). Generation of
events of creation or deletion of graphical objects on a chart can be enabled or disabled
by setting CHART_EVENT_OBJECT_CREATE and CHART_EVENT_OBJECT_DELETE chart
properties. Each MQL4 program and each chart has its own queue of events, where all
new incoming events are added.
A program receives only events from the chart it runs on. All events are processed one
after another in the order they are received. If a queue already has a NewTick event, or
this event is currently being processed, then the new NewTick event is not placed in the
queue of the MQL4 program. Similarly, if ChartEvent is already enqueued, or this event is
being processed, no new event of this kind is enqueued. The timer events are handled
the same way if the Timer event is in the queue or being handled, the new timer event
is not enqueued.
Event queues have a limited but sufficient size, so that the queue overflow for well
written programs is unlikely. In case of queue overflow, new events are discarded
without queuing.
It is not recommended to use infinite loops to handle events. The exception to this rule
may be only scripts that process only a single Start event.
Libraries do not handle any events.
Functions prohibited in Indicators and Expert Advisors
Indicators, scripts and Expert Advisors are executable programs written in MQL4. They
are designed for different types of tasks. Therefore there are some restrictions on the
use of certain functions, depending on the type of program. The following functions are
prohibited in indicators:
OrderSend();
SendFTP();
Sleep();
ExpertRemove();
MessageBox().
All functions designed for indicators are prohibited in Expert Advisors and scripts:
SetIndexBuffer();
IndicatorSetDouble();
IndicatorSetInteger();
IndicatorSetString().
The library is not an independent program and is executed in the context of the MQL4
program that has called it: script, indicator or Expert Advisor. Accordingly, the above
restrictions apply to the called library.
Loading and Unloading of Indicators
Indicators are loaded in the following cases:
an indicator is attached to a chart;
terminal start (if the indicator was attached to the chart prior to the shutdown of the
terminal);
loading of a template (if the indicator attached to a chart is specified in the
template);
change of a profile (if the indicator is attached to one of the profile charts);
change of a symbol and/or timeframe of a chart, to which the indicator is attached;
after the successful recompilation of an indicator (if the indicator was attached to a
chart);
change of input parameters of the indicator.
Indicators are unloaded in the following cases:
when detaching an indicator from a chart;
terminal shutdown (if the indicator was attached to a chart);
loading of a template (if an indicator is attached to a chart);
closing of a chart, to which the indicator was attached;
change of a profile (if the indicator is attached to one of charts of the changed
profile);
change of a symbol and/or timeframe of a chart, to which the indicator is attached;
change of input parameters of the indicator.
class CTestClass
{
public:
CTestClass() { Print("CTestClass constructor"); }
~CTestClass() { Print("CTestClass destructor"); }
};
CTestClass global;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
Print("Initialization");
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Print("Deinitialization with reason",reason);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
}
//+------------------------------------------------------------------+
Loading and Unloading of Scripts
Scripts are loaded immediately after they are attached to a chart and unloaded
immediately after they complete their operation.
When a program is unloaded (deleted from a chart) the client terminal performs
deinitialization of global variables and deletes the events queue. In this case
deinitialization means reset of all the string-type variables, deallocation of dynamical
array objects and call of their destructors if they are available.
//+------------------------------------------------------------------+
//| TestScript.mq5 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
class CTestClass
{
public:
CTestClass() { Print("CTestClass constructor"); }
~CTestClass() { Print("CTestClass destructor"); }
};
CTestClass global;
//+------------------------------------------------------------------+
//| Script program initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
Print(__FUNCTION__);
}
//+------------------------------------------------------------------+
//| Script program deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
Print(__FUNCTION__," reason=",reason);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
Print(__FUNCTION__);
}
Input Parameters and Source Code Compilation
If a source code of a program launched on a chart is successfully recompiled, its previous
version is removed from the chart and the new compiled copy is executed instead.
If the set of the input parameters is not changed after the recompilation, the previously
specified parameter values are applied. Otherwise, the default values are used.
The set of mql4 program input parameters is considered to be changed when editing the
source code in the following cases:
the number of parameters has been changed;
the sequence order of parameters has been changed;
parameter names have been changed;
the type of one or more parameters has been changed.
Changing a default value of any of the parameters is not considered to be a change of
the input parameter set.
The set of the input parameters clearly identifies the program in the terminal's
execution system. If this set is unchanged, the new versions of the executable file are
considered to retain the entire logic and functionality of the program.
If the set of the input parameters is changed, the terminal considers the new executable
file as incompatible with the program that has been previously launched on the chart.
Thus, the new recompiled program is launched with the set of the input parameters
having default values.
In other cases (including the ones when a default value of any parameter is changed),
the previously specified parameters are applied after the recompilation.
The OnInit() predefined function is called after any compilation. Its purpose is to
correctly initialize all global and static variables of the program. The program's input
parameter values should be used correctly in OnInit() event handler.
See also
Client terminal events, Event handlers
MQL4 Reference / MQL4 programs / Trade Permission
Trade Permission
Trade Automation
MQL4 language provides a special group of trade functions designed for developing
automated trading systems. Programs developed for automated trading with no human
intervention are called Expert Advisors or trading robots. In order to create an Expert
Advisor in MetaEditor, launch MQL4 Wizard and select the option "Expert Advisor
(template)". It allows you to create a template with ready-made event handling
functions that should be supplemented with all necessary functionality by means of
programming.
Trading functions can work only in Expert Advisors and scripts. Trading is not allowed for
indicators.
Sample check:
if(!TerminalInfoInteger(TERMINAL_TRADE_ALLOWED))
Alert("Check if automated trading is allowed in the terminal settings!");
else
{
if(!MQLInfoInteger(MQL_TRADE_ALLOWED))
Alert("Automated trading is forbidden in the program settings for ",__FILE__
}
Resources
Using graphics and sound in MQL4 programs
Programs in MQL4 allow working with sound and graphic files:
PlaySound() plays a sound file;
ObjectCreate() allows creating user interfaces using graphical objects OBJ_BITMAP
and OBJ_BITMAP_LABEL.
PlaySound()
Example of call of the PlaySound() function:
//+------------------------------------------------------------------+ //| Calls stand
//+------------------------------------------------------------------+
void OrderSendWithAudio()
{
double price=Ask;
//--- place market order to buy 1 lot
int ticket=OrderSend(Symbol(),OP_BUY,1,price,3,0,0,"My order",16384,0,clrGreen)
if(ticket<0)
{
Print("OrderSend failed with error #",GetLastError());
//--- if error play sound from timeout.wav
PlaySound("timeout.wav");
}
else
{
Print("OrderSend placed successfully");
//--- if success, play sound from Ok.wav
PlaySound("Ok.wav");
}
}
The example shows how to play sounds from files 'Ok.wav' and 'timeout.wav', which are
included into the standard terminal package. These files are located in the folder
terminal_directory\Sounds. Here terminal_directory is a folder, from which the
MetaTrader 4 Client Terminal is started. The location of the terminal directory can be
found out from an mql4 program in the following way:
//--- Folder, in which terminal data are stored
string terminal_path=TerminalInfoString(TERMINAL_PATH);
You can use sound files not only from the folder terminal_directory\Sounds, but also
from any subfolder located in terminal_data_directory\MQL4. You can find out the
location of the terminal data directory from the terminal menu "File" -> "Open Data
Folder" or using program method:
//--- Folder, in which terminal data are stored
string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH);
For example, if the Demo.wav sound file is located in
terminal_data_directory\MQL4\Files, then call of PlaySound() should be written the
following way:
//--- play Demo.wav from the folder terminal_directory_data\MQL4\Files\
PlaySound("\\Files\\Demo.wav");
Please note that in the comment the path to the file is written using backslash "\", and in
the function "\\" is used.
When specifying the path, always use only the double backslash as a separator, because
a single backslash is a control symbol for the compiler when dealing with constant strings
and character constants in the program source code.
Call PlaySound() function with NULL parameter to stop playback:
//--- call of PlaySound() with NULL parameter stops playback
PlaySound(NULL);
ObjectCreate()
Example of an Expert Advisor, which creates a graphical label (OBJ_BITMAP_LABEL) using
the ObjectCreate() function.
string label_name="currency_label"; // name of the OBJ_BITMAP_LABEL object
string euro ="\\Images\\euro.bmp"; // path to the file terminal_data_director
string dollar ="\\Images\\dollar.bmp"; // path to the file terminal_data_director
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create a button OBJ_BITMAP_LABEL, if it hasn't been created yet
if(ObjectFind(0,label_name)<0)
{
//--- trying to create object OBJ_BITMAP_LABEL
bool created=ObjectCreate(0,label_name,OBJ_BITMAP_LABEL,0,0,0);
if(created)
{
//--- link the button to the left upper corner of the chart
ObjectSetInteger(0,label_name,OBJPROP_CORNER,CORNER_RIGHT_UPPER);
//--- now set up the object properties
ObjectSetInteger(0,label_name,OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,label_name,OBJPROP_YDISTANCE,50);
//--- reset the code of the last error to 0
ResetLastError();
//--- download a picture to indicate the "Pressed" state of the button
bool set=ObjectSetString(0,label_name,OBJPROP_BMPFILE,0,euro);
//--- test the result
if(!set)
{
PrintFormat("Failed to download image from file %s. Error code %d",euro,G
}
ResetLastError();
//--- download a picture to indicate the "Unpressed" state of the button
set=ObjectSetString(0,label_name,OBJPROP_BMPFILE,1,dollar);
if(!set)
{
PrintFormat("Failed to download image from file %s. Error code %d",dollar
}
//--- send a command for a chart to refresh so that the button appears immed
ChartRedraw(0);
}
else
{
//--- failed to create an object, notify
PrintFormat("Failed to create object OBJ_BITMAP_LABEL. Error code %d",GetLas
}
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- delete an object from a chart
ObjectDelete(0,label_name);
}
Creation and setup of the graphical object named currency_label are carried out in the
OnInit() function. The paths to the graphical files are set in global variables euro and
dollar, a double backlash is used for a separator:
string euro ="\\Images\\euro.bmp"; // path to the file terminal_dara_director
string dollar ="\\Images\\dollar.bmp"; // path to the file terminal_dara_director
The size of the button with a graphical interface is automatically adjusted to the size of
the picture. The image is changed by a left mouse button click on the
OBJ_BITMAP_LABEL object ("Disable selection" option must be checked in the
properties). The OBJ_BITMAP object is created the same way - it is used for creating the
background with a necessary image.
The value of the OBJPROP_BMPFILE property, which is responsible for the appearance of
the objects OBJ_BITMAP and OBJ_BITMAP_LABEL, can be changed dynamically. This
allows creating various interactive user interfaces for mql4 programs.
The #resource command tells the compiler that the resource at the specified path
path_to_resource_file should be included into the executable EX5 file. Thus all the
necessary images and sounds can be located directly in an EX4 file, so that there is no
need to transfer separately the files used in it, if you want to run the program on a
different terminal. Any EX4 file can contain resources, and any EX4 program can use
resources from another EX4 program.
The files in format BMP and WAV are automatically compressed before including them to
an EX4 file. This denotes that in addition to the creation of complete programs in MQL4,
using resources also allows to reduce the total size of necessary files when using graphics
and sounds, as compared to the usual way of MQL4 program writing.
The resource file size must not exceed 16 Mb.
Use of Resources
Resource name
After a resource is declared using the #resource directive, it can be used in any part of a
program. The name of the resource is its path without a backslash at the beginning of
the line, which sets the path to the resource. To use your own resource in the code, the
special sign "::" should be added before the resource name.
Examples:
//--- examples of resource specification and their names in comments
#resource "\\Images\\euro.bmp" // resource name - Images\euro.bmp
#resource "picture.bmp" // resource name - picture.bmp
#resource "Resource\\map.bmp" // resource name - Resource\map.bmp
#resource "\\Files\\Pictures\\good.bmp" // resource name - Files\Pictures\good.bmp
#resource "\\Files\\Demo.wav"; // resource name - Files\Demo.wav"
#resource "\\Sounds\\thrill.wav"; // resource name - Sounds\thrill.wav"
...
It should be noted that when setting images from a resource to the OBJ_BITMAP and
OBJ_BITMAP_LABEL objects, the value of the OBJPROP_BMPFILE property cannot be
modified manually. For example, for creating OBJ_BITMAP_LABEL we use resources
euro.bmp and dollar.bmp.
#resource "\\Images\\euro.bmp"; // euro.bmp is located in terminal_data_directory\
#resource "\\Images\\dollar.bmp"; // dollar.bmp is located in terminal_data_director
When viewing the properties of this object, we'll see that the properties BitMap File (On)
and BitMap File (Off) are dimmed and cannot be change manually:
Using the resources of other mql4 programs
There is another advantage of using resources in any MQL4 program, resources of
another EX4 file can be used. Thus the resources from one EX4 file can be used in many
other mql4 programs.
In order to use a resource name from another file, it should be specified as
<path_EX4_file_name>::<resource_name>. For example, suppose the
Draw_Triangles_Script.mq5 script contains a resource to an image in the file
triangle.bmp:
#resource "\\Files\\triangle.bmp"
Then its name, for using in the script itself, will look like "Files\triangle.bmp", and in
order to use it, "::" should be added to the resource name.
//--- using the resource in the script
ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"::Files\\triangle.bmp");
In order to use the same resource from another program, e.g. from an Expert Advisor, we
need to add to the resource name the path to the EX4 file relative to
terminal_data_directory\MQL4\ and the name of the script's EX4 file -
Draw_Triangles_Script.ex4. Suppose the script is located in the standard folder
terminal_data_directory\MQL4\Scripts\, then the call should be written the following
way:
//--- using a resource from a script in an EA
ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"\\Scripts\\Draw_Triangles_Script.
If the path to the executable file is not specified when calling the resource from another
EX4, the executable file is searched for in the same folder that contains the program
that calls the resource. This means that if an Expert Advisor calls a resource from
Draw_Triangles_Script.ex4 without specification of the path, like this:
//--- call script resource in an EA without specifying the path
ObjectSetString(0,my_bitmap_name,OBJPROP_BMPFILE,0,"Draw_Triangles_Script.ex4::Files\
See also
ResourceCreate(), ResourceSave(), PlaySound(), ObjectSetInteger(),
ChartApplyTemplate(), File Functions
MQL4 Reference / MQL4 programs / Call of Imported Functions
Passing Parameters
All parameters of simple types are passed by values unless
it is explicitly indicated that they are passed by
reference. When a string is passed, the address of the
buffer of the copied string is passed; if a string is passed
by reference, the address of the buffer of this string
without copying it is passed to the function imported from
DLL.
Structures that contain dynamic arrays, strings, classes,
other complex structures, as well as static or dynamic
arrays of the enumerated objects, can't be passed as a
parameter to an imported function.
When passing an array to DLL, the address of the
beginning of the data buffer is always passed (irrespective
of the AS_SERIES flag). A function inside a DLL knows
nothing about the AS_SERIES flag, the passed array is a
static array of an undefined length; an additional
parameter should be used for specifying the array size.
MQL4 Reference / MQL4 programs / Runtime Errors
Runtime Errors
The executing subsystem of the client terminal has an
opportunity to save the error code in case it occurs during
a MQL4 program run. There is a predefined variable
_LastError for each executable MQL4 program.
Before starting the OnInit function, the _LastError
variable is reset. In case an erroneous situation occurs
during calculations or in the process of internal function
calls, the _LastError variable accepts a corresponding
error code. The value stored in this variable can be
obtained using the GetLastError() function.
There are several critical errors in case of which a
program is terminated immediately:
division by zero
going beyond array boundary
using an incorrect object pointer
MQL4 Reference / MQL4 programs / Operation of Programs in the
Strategy Tester
Function Limitations in the Strategy Tester
There are operation limitations for some functions in the
client terminal's Strategy Tester. Calling that functions
leads to error 4059 (Function is not allowed in testing
mode).
The Sleep() Function
The Sleep() function does not cause any delays in the
Strategy Tester.
The Print() and PrintFormat() Functions
To increase performance, Print() and PrintFormat()
functions are not executed when optimizing the trading
robot's parameters. The exception is the use of these
functions inside the OnInit() handler. This allows you to
easily find the cause of errors when they occur.
The Alert(), MessageBox(), PlaySound(),
SendFTP, SendMail(), SendNotification(),
WebRequest() Functions
The Alert(), MessageBox(), PlaySound(), SendFTP(),
SendMail(), SendNotification() and WebRequest() functions
designed for interaction with the "outside world" are not
executed in the Strategy Tester.
The OrderSend(), OrderModify(),
OrderDelete(), OrderClose(), OrderCloseBy()
Functions
Trade operations are not performed on the symbols that
are different from the tested one.
Predefined variables cannot be defined in a library. A library uses such variables that are
defined in program from which this library is called.
Example:
//+------------------------------------------------------------------+ //| Script prog
//+------------------------------------------------------------------+
void OnStart()
{
Print("Symbol name of the current chart=",_Symbol);
Print("Timeframe of the current chart=",_Period);
Print("The latest known seller's price (ask price) for the current symbol=",Ask);
Print("The latest known buyer's price (bid price) of the current symbol=",Bid);
Print("Number of decimal places=",Digits);
Print("Number of decimal places=",_Digits);
Print("Size of the current symbol point in the quote currency=",_Point);
Print("Size of the current symbol point in the quote currency=",Point);
Print("Number of bars in the current chart=",Bars);
Print("Open price of the current bar of the current chart=",Open[0]);
Print("Close price of the current bar of the current chart=",Close[0]);
Print("High price of the current bar of the current chart=",High[0]);
Print("Low price of the current bar of the current chart=",Low[0]);
Print("Time of the current bar of the current chart=",Time[0]);
Print("Tick volume of the current bar of the current chart=",Volume[0]);
Print("Last error code=",_LastError);
Print("Random seed=",_RandomSeed);
Print("Stop flag=",_StopFlag);
Print("Uninitialization reason code=",_UninitReason);
}
MQL4 Reference / Predefined Variables / _Digits
int _Digits
The _Digits variable stores number of digits after a
decimal point, which defines the price accuracy of the
symbol of the current chart.
You may also use the Digits() function.
MQL4 Reference / Predefined Variables / _Point
double _Point
The _Point variable contains the point size of the current
symbol in the quote currency.
You may also use the Point() function.
MQL4 Reference / Predefined Variables / _LastError
int _LastError
The _LastError variable contains code of the last error,
that occurred during the mql4-program run. Its value can
be reset to zero by ResetLastError().
To obtain the code of the last error, you may also use the
GetLastError() function.
MQL4 Reference / Predefined Variables / _Period
int _Period
The _Period variable contains the value of the timeframe
of the current chart.
Also you may use the Period() function.
See also
PeriodSeconds(), Chart timeframes, Date and Time,
Visibility of objects
MQL4 Reference / Predefined Variables / _RandomSeed
_RandomSeed
Variable for storing the current state when generating
pseudo-random integers. _RandomSeed changes its value
when calling MathRand(). Use MathSrand() to set the
required initial condition.
x random number received by MathRand() function is
calculated in the following way at each call:
x=_RandomSeed*214013+2531011; _RandomSeed=x;
x=(x>>16)&0x7FFF;
See also
MathRand(), MathSrand(), Integer types
MQL4 Reference / Predefined Variables / _StopFlag
bool _StopFlag
The _StopFlag variable contains the flag of the mql4-
program stop. When the client terminal is trying to stop
the program, it sets the _StopFlag variable to true.
To check the state of the _StopFlag you may also use the
IsStopped() function.
MQL4 Reference / Predefined Variables / _Symbol
string _Symbol
The _Symbol variable contains the symbol name of the
current chart.
You may also use the Symbol() function.
MQL4 Reference / Predefined Variables / _UninitReason
int _UninitReason
The _UninitReason variable contains the code of the
program uninitialization reason.
Usually, this code is obtained by UninitializeReason()the
function.
MQL4 Reference / Predefined Variables / Ask
double Ask
The latest known seller's price (ask price) for the current symbol. The RefreshRates()
function must be used to update.
Example:
if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25) {
OrderSend(Symbol(),OP_BUY,Lots,Ask,3,NormalizeDouble(Bid-StopLoss*Point,Digits),
"My order #2",3,D'2005.10.10 12:30',Red);
return;
}
See also
MarketInfo()
MQL4 Reference / Predefined Variables / Bars
int Bars
Number of bars in the current chart.
Example:
int counter=1; for(int i=1; i<=Bars; i++)
{
Print(Close[i-1]);
}
See also
Function Bars, iBars
MQL4 Reference / Predefined Variables / Bid
double Bid
The latest known buyer's price (offer price, bid price) of the current symbol. The
RefreshRates() function must be used to update.
Example:
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75) {
OrderSend("EURUSD",OP_SELL,Lots,Bid,3,NormalizeDouble(Ask+StopLoss*Point,Digits)
"My order #2",3,D'2005.10.10 12:30',Red);
return(0);
}
See also
MarketInfo()
MQL4 Reference / Predefined Variables / Close
double Close[]
Series array that contains close prices for each bar of the current chart.
Series array elements are indexed in the reverse order, i.e., from the last one to the
first one. The current bar which is the last in the array is indexed as 0. The oldest bar,
the first in the chart, is indexed as Bars-1.
Example:
int handle = FileOpen("file.csv", FILE_CSV|FILE_WRITE, ";"); if(handle>0)
{
// table column headers recording
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// data recording
for(int i=0; i<Bars; i++)
FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]);
FileClose(handle);
}
See also
iClose()
MQL4 Reference / Predefined Variables / Digits
int Digits
Number of digits after decimal point for the current
symbol prices.
Example:
Print(DoubleToStr(Close[0], Digits));
See also
MarketInfo()
MQL4 Reference / Predefined Variables / High
double High[]
Series array that contains the highest prices of each bar of
the current chart.
Series array elements are indexed in the reverse order,
i.e., from the last one to the first one. The current bar
which is the last in the array is indexed as 0. The oldest
bar, the first in the chart, is indexed as Bars-1.
Example:
//---- maximums counting i=Bars-KPeriod;
if(counted_bars>KPeriod) i=Bars-counted_bars-1;
while(i>=0)
{
double max=-1000000;
k = i + KPeriod-1;
while(k>=i)
{
price=High[k];
if(max<price) max=price;
k--;
}
HighesBuffer[i]=max;
i--;
}
//----
See also
iHigh()
MQL4 Reference / Predefined Variables / Low
double Low[]
Series array that contains the lowest prices of each bar of
the current chart.
Series array elements are indexed in the reverse order,
i.e., from the last one to the first one. The current bar
which is the last in the array is indexed as 0. The oldest
bar, the first in the chart, is indexed as Bars-1.
Example:
//---- minima counting i=Bars-KPeriod;
if(counted_bars>KPeriod) i=Bars-counted_bars-1;
while(i>=0)
{
double min=1000000;
k = i + KPeriod-1;
while(k>=i)
{
price=Low[k];
if(min>price) min=price;
k--;
}
LowesBuffer[i]=min;
i--;
}
//----
See also
iLow()
MQL4 Reference / Predefined Variables / Open
double Open[]
Series array that contains open prices of each bar of the current chart.
Series array elements are indexed in the reverse order, i.e., from the
last one to the first one. The current bar which is the last in the array is
indexed as 0. The oldest bar, the first in the chart, is indexed as Bars-1.
Example:
i = Bars - counted_bars - 1; while(i>=0)
{
double high = High[i];
double low = Low[i];
double open = Open[i];
double close = Close[i];
AccumulationBuffer[i] = (close-low) - (high-close);
if(AccumulationBuffer[i] != 0)
{
double diff = high - low;
if(0==diff)
AccumulationBuffer[i] = 0;
else
{
AccumulationBuffer[i] /= diff;
AccumulationBuffer[i] *= Volume[i];
}
}
if(i<Bars-1) AccumulationBuffer[i] += AccumulationBuffer[i+1];
i--;
}
See also
iOpen()
MQL4 Reference / Predefined Variables / Point
double Point
The current symbol point value in the quote currency.
Example:
OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,NormalizeDouble(Ask+TakeProfit*Point,Digits)
See also
MarketInfo()
MQL4 Reference / Predefined Variables / Time
datetime Time[]
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 January,
1970.
Series array elements are indexed in the reverse order,
i.e., from the last one to the first one. The current bar
which is the last in the array is indexed as 0. The oldest
bar, the first in the chart, is indexed as Bars-1.
Example:
for(i=Bars-2; i>=0; i--) {
if(High[i+1] > LastHigh) LastHigh = High[i+1];
if(Low[i+1] < LastLow) LastLow = Low[i+1];
//----
if(TimeDay(Time[i]) != TimeDay(Time[i+1]))
{
P = (LastHigh + LastLow + Close[i+1])/3;
R1 = P*2 - LastLow;
S1 = P*2 - LastHigh;
R2 = P + LastHigh - LastLow;
S2 = P - (LastHigh - LastLow);
R3 = P*2 + LastHigh - LastLow*2;
S3 = P*2 - (LastHigh*2 - LastLow);
LastLow = Open[i];
LastHigh = Open[i];
}
//----
PBuffer[i] = P;
S1Buffer[i] = S1;
R1Buffer[i] = R1;
S2Buffer[i] = S2;
R2Buffer[i] = R2;
S3Buffer[i] = S3;
R3Buffer[i] = R3;
}
See also
iTime()
MQL4 Reference / Predefined Variables / Volume
long Volume[]
Series array that contains tick volumes of each bar of the
current chart.
Series array elements are indexed in the reverse order, i.e.,
from the last one to the first one. The current bar which is
the last in the array is indexed as 0. The oldest bar, the first
in the chart, is indexed as Bars-1.
Example:
if(i==0 && time0<i_time+periodseconds) {
d_volume += Volume[0];
if(Low[0]<d_low) d_low = Low[0];
if(High[0]>d_high) d_high = High[0];
d_close = Close[0];
}
last_fpos = FileTell(ExtHandle);
last_volume = Volume[i];
FileWriteInteger(ExtHandle, i_time, LONG_VALUE);
FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE);
See also
iVolume()
MQL4 Reference / Common Functions
Common Functions
General-purpose functions not included into any
specialized group are listed here.
Function Action
Alert Displays a message in a separate
window
CheckPointer Returns the type of the object pointer
Comment Outputs a comment in the left top
corner of the chart
CryptEncode Transforms the data from array with
the specified method
CryptDecode Performs the inverse transformation of
the data from array
DebugBreak Program breakpoint in debugging
ExpertRemove Stops Expert Advisor and unloads it
from the chart
GetPointer Returns the object pointer
GetTickCount Returns the number of milliseconds
that have elapsed since the system was
started
GetMicrosecondCount Returns the number of microseconds
that have elapsed since the start of
MQL4-program
MessageBox Creates, displays a message box and
manages it
Function Action
PeriodSeconds Returns the number of seconds in the
period
PlaySound Plays a sound file
Print Displays a message in the log
PrintFormat Formats and prints the sets of symbols
and values in a log file in accordance
with a preset format
ResetLastError Sets the value of a predetermined
variable _LastError to zero
ResourceCreate Creates an image resource based on a
data set
ResourceFree Deletes dynamically created resource
(freeing the memory allocated for it)
ResourceReadImage Reads data from the graphical resource
created by ResourceCreate() function
or saved in EX4 file during compilation
ResourceSave Saves a resource into the specified file
SendFTP Sends a file at the address specified in
the settings window of the "FTP" tab
SendMail Sends an email at the address specified
in the settings window of the "Email"
tab
SendNotification Sends push notifications to mobile
terminals, whose MetaQuotes ID are
specified in the "Notifications" tab
Sleep Suspends execution of the current
Expert Advisor or script within a
specified interval
Function Action
TerminalClose Commands the terminal to complete
operation
TesterStatistics It returns the value of a specified
statistic calculated based on testing
results
TranslateKey Returns a Unicode character by a
virtual key code
WebRequest Sends HTTP request to the specified
server
ZeroMemory Resets a variable passed to it by
reference. The variable can be of any
type, except for classes and structures
that have constructors.
What's new in MQL5
In MQL5, the SendFTP, SendMail and SendNotification
functions are moved to the new extended Network
functions section. Now programs can exchange data with
remote servers included in the list of allowed IP
addresses. This means that MQL5 EAs are able to establish
secure connections between processes using the TCP/IP
protocol without using third-party DLLs.
MQL4 Reference / Common Functions / Alert
Alert
Displays a message in a separate window.
void Alert( argument, // first value
... // other values
);
Parameters
argument
[in] Any values separated by commas. To split the
information output in several lines you can use the line
feed characters "\r\n". The number of parameters can
not exceed 64.
Return Value
No return value.
Note
Arrays can't be passed to the Alert() function. Arrays
should be output elementwise. Data of the double type
are output with 8 digits after the decimal point, data of
the float type are displayed with 5 digits after the
decimal point. To output the real numbers with a
different precision or in a scientific format, use the
DoubleToString() function.
Data of the bool type is output as "true" or "false"
strings. Dates are output as YYYY.MM.DD HH:MI:SS. To
display a date in another format use the TimeToString()
function. Data of the color type are output either as an
R,G,B string or as a color name, if the color is present in
a color set.
Alert() function does not work in the Strategy Tester.
See also
Comment(), Print()
MQL4 Reference / Common Functions / CheckPointer
CheckPointer
The function returns the type of the object pointer.
ENUM_POINTER_TYPE CheckPointer( object* anyobject // object pointer
);
Parameters
anyobject
[in] Object pointer.
Return value
Returns a value from the ENUM_POINTER_TYPE enumeration.
Note
An attempt to call an incorrect pointer results in the critical termination of a
program. That's why it's necessary to call the CheckPointer function before using a
pointer. A pointer can be incorrect in the following cases:
the pointer is equal to NULL;
the object has been deleted using the delete operator.
This function can be used for checking pointer validity. A non-zero value
warranties that the pointer can be used for accessing.
Example:
//+------------------------------------------------------------------+
//| Deletes list by deleting its elements |
//+------------------------------------------------------------------+
void CMyList::Destroy()
{
//--- service pointer for working in the loop
CItem* item;
//--- go through loop and try to delete dynamic pointers
while(CheckPointer(m_items)!=POINTER_INVALID)
{
item=m_items;
m_items=m_items.Next();
if(CheckPointer(item)==POINTER_DYNAMIC)
{
Print("Dynamyc object ",item.Identifier()," to be deleted");
delete (item);
}
else Print("Non-dynamic object ",item.Identifier()," cannot be deleted");
}
//---
}
See also
Object Pointers, Checking the Object Pointer, Object Delete Operator delete
MQL4 Reference / Common Functions / Comment
Comment
This function outputs a comment defined by a user in the top left corner of a chart.
void Comment( argument, // first value
... // next values
);
Parameters
...
[in] Any values, separated by commas. To delimit output information into several
lines, a line break symbol "\n" or "\r\n" is used. Number of parameters cannot exceed
64. Total length of the input comment (including invisible symbols) cannot exceed
2045 characters (excess symbols will be cut out during output).
Return Value
No return value.
Note
Arrays can't be passed to the Comment() function. Arrays must be entered element-by-
element.
Data of double type are output with the accuracy of up to 16 digits after a decimal
point, and can be output either in traditional or in scientific format, depending on
what notation will be more compact. Data of float type are output with 5 digits after a
decimal point. To output real numbers with another accuracy or in a predefined
format, use the DoubleToString() function.
Data of bool type are output as "true" or "false" strings. Dates are shown as YYYY.MM.DD
HH:MI:SS. To show dates in another format, use the TimeToString() function. Data of
color type are output either as R,G,B string or as a color name, if this color is present
in the color set.
Example:
void OnTick()
{
//---
double Ask,Bid;
int Spread;
Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Spread=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);
//--- Output values in three lines
Comment(StringFormat("Show prices\nAsk = %G\nBid = %G\nSpread = %d",Ask,Bid,Spread
}
See also
Alert(), Print()
MQL4 Reference / Common Functions / CryptEncode
CryptEncode
Transforms the data from array with the specified method.
int CryptEncode( ENUM_CRYPT_METHOD method, // method
const uchar& data[], // source array
const uchar& key[], // key
uchar& result[] // destination array
);
Parameters
method
[in] Data transformation method. Can be one of the values of ENUM_CRYPT_METHOD
enumeration.
data[]
[in] Source array.
key[]
[in] Key array.
result[]
[out] Destination array.
Returned value
Amount of bytes in the destination array or 0 in case of error. To obtain information
about the error call the GetLastError() function.
Example:
//+------------------------------------------------------------------+
//| ArrayToHex |
//+------------------------------------------------------------------+
string ArrayToHex(uchar &arr[],int count=-1)
{
string res="";
//--- check
if(count<0 || count>ArraySize(arr))
count=ArraySize(arr);
//--- transform to HEX string
for(int i=0; i<count; i++)
res+=StringFormat("%.2X",arr[i]);
//---
return(res);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string text="The quick brown fox jumps over the lazy dog";
string keystr="ABCDEFG";
uchar src[],dst[],key[];
//--- prepare key
StringToCharArray(keystr,key);
//--- copy text to source array src[]
StringToCharArray(text,src);
//--- print initial data
PrintFormat("Initial data: size=%d, string='%s'",ArraySize(src),CharArrayToString(
//--- encrypt src[] with DES 56-bit key in key[]
int res=CryptEncode(CRYPT_DES,src,key,dst);
//--- check error
if(res>0)
{
//--- print encrypted data
PrintFormat("Encoded data: size=%d %s",res,ArrayToHex(dst));
//--- decode dst[] to src[]
res=CryptDecode(CRYPT_DES,dst,key,src);
//--- check error
if(res>0)
{
//--- print decoded data
PrintFormat("Decoded data: size=%d, string='%s'",ArraySize(src),CharArrayToS
}
else
Print("Error in CryptDecode. Error code=",GetLastError());
}
else
Print("Error in CryptEncode. Error code=",GetLastError());
}
See also
Array Functions, CryptDecode()
MQL4 Reference / Common Functions / CryptDecode
CryptDecode
Performs the inverse transformation of the data from array,
tranformed by CryptEncode().
int CryptEncode( ENUM_CRYPT_METHOD method, // method
const uchar& data[], // source array
const uchar& key[], // key
uchar& result[] // destination array
);
Parameters
method
[in] Data transformation method. Can be one of the values of
ENUM_CRYPT_METHOD enumeration.
data[]
[in] Source array.
key[]
[in] Key array.
result[]
[out] Destination array.
Returned value
Amount of bytes in the destination array or 0 in case of error. To
obtain information about the error call the GetLastError() function.
See also
Array Functions, CryptEncode()
MQL4 Reference / Common Functions / DebugBreak
DebugBreak
It is a program breakpoint in debugging.
void DebugBreak();
Return Value
No return value.
Note
Execution of an MQL4 program is interrupted only if a
program is started in a debugging mode. The function
can be used for viewing values of variables and/or for
further step-by-step execution.
MQL4 Reference / Common Functions / ExpertRemove
ExpertRemove
The function stops an Expert Advisor and unloads it from a chart.
void ExpertRemove();
Returned value
No return value.
Note
The Expert Advisor is not stopped immediately as you call ExpertRemove(); just a flag
to stop the EA operation is set. That is, any next event won't be processed, OnDeinit()
will be called and the Expert Advisor will be unloaded and removed from the chart.
Example:
//+------------------------------------------------------------------+ //|
//| Copyright 2009, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
input int ticks_to_close=20;// number of ticks before EA unload
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Print(TimeCurrent(),": " ,__FUNCTION__," reason code = ",reason);
//--- "clear" comment
Comment("");
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
static int tick_counter=0;
//---
tick_counter++;
Comment("\nBefore unloading expert advisor ",__FILE__," left",
(ticks_to_close-tick_counter)," ticks");
//--- before
if(tick_counter>=ticks_to_close)
{
ExpertRemove();
Print(TimeCurrent(),": ",__FUNCTION__," expert advisor will be unloaded");
}
Print("tick_counter =",tick_counter);
//---
}
//+------------------------------------------------------------------+
See also
Programs running, Client terminal events
MQL4 Reference / Common Functions / GetPointer
GetPointer
The function returns the object pointer.
void* GetPointer( any_class anyobject // object of any class
);
Parameters
anyobject
[in] Object of any class.
Return Value
The function returns the object pointer.
Note
Only class objects have pointers. Instances of structures and simple-type variables can't
have pointers. The class object not created using the new() operator, but, e.g.,
automatically created in the array of objects, still has a pointer. But this pointer will be
of the automatic type POINTER_AUTOMATIC, therefore the delete() operator can't be
applied to it. Aside from that, the type pointer doesn't differ from dynamic pointers of
the POINTER_AUTOMATIC type.
Since variables of structure types and simple types do not have pointers, it's prohibited
to apply the GetPointer() function to them. It's also prohibited to pass the pointer as a
function argument. In all these cases the compiler will notify an error.
An attempt to call an incorrect pointer causes the critical termination of a program.
That's why the CheckPointer() function should be called prior to using a pointer. A
pointer can be incorrect in the following cases:
the pointer is equal to NULL;
the object has been deleted using the delete operator.
This function can be used to check the validity of a pointer. A non-zero value
guarantees, that the pointer can be used for accessing.
Example:
//+------------------------------------------------------------------+
//| Check_GetPointer.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//+------------------------------------------------------------------+
//| Class implementing the list element |
//+------------------------------------------------------------------+
class CItem
{
int m_id;
string m_comment;
CItem* m_next;
public:
CItem() { m_id=0; m_comment=NULL; m_next=NULL; }
~CItem() { Print("Destructor of ",m_id,
(CheckPointer(GetPointer(this))==POINTER_DYNAMIC
"dynamic":"non-dynamic"); }
void Initialize(int id,string comm) { m_id=id; m_comment=comm; }
void PrintMe() { Print(__FUNCTION__,":",m_id,m_comment); }
int Identifier() { return(m_id); }
CItem* Next() {return(m_next); }
void Next(CItem *item) { m_next=item; }
};
//+------------------------------------------------------------------+
//| Simplest class of the list |
//+------------------------------------------------------------------+
class CMyList
{
CItem* m_items;
public:
CMyList() { m_items=NULL; }
~CMyList() { Destroy(); }
bool InsertToBegin(CItem* item);
void Destroy();
};
//+------------------------------------------------------------------+
//| Inserts list element at the beginning |
//+------------------------------------------------------------------+
bool CMyList::InsertToBegin(CItem* item)
{
if(CheckPointer(item)==POINTER_INVALID) return(false);
//---
item.Next(m_items);
m_items=item;
//---
return(true);
}
//+------------------------------------------------------------------+
//| Deletes the list by deleting elements |
//+------------------------------------------------------------------+
void CMyList::Destroy()
{
//--- service pointer to work in a loop
CItem* item;
//--- go through the loop and try to delete dynamic pointers
while(CheckPointer(m_items)!=POINTER_INVALID)
{
item=m_items;
m_items=m_items.Next();
if(CheckPointer(item)==POINTER_DYNAMIC)
{
Print("Dynamyc object ",item.Identifier()," to be deleted");
delete (item);
}
else Print("Non-dynamic object ",item.Identifier()," cannot be deleted");
}
//---
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
CMyList list;
CItem items[10];
CItem* item;
//--- create and add into the list a dynamic object pointer
item=new CItem;
if(item!=NULL)
{
item.Initialize(100,"dynamic");
item.PrintMe();
list.InsertToBegin(item);
}
//--- add automatic pointers into the list
for(int i=0; i<10; i++)
{
items[i].Initialize(i,"automatic");
items[i].PrintMe();
item=GetPointer(items[i]);
if(CheckPointer(item)!=POINTER_INVALID)
list.InsertToBegin(item);
}
//--- add one more dynamic object pointer at the list beginning
item=new CItem;
if(item!=NULL)
{
item.Initialize(200,"dynamic");
item.PrintMe();
list.InsertToBegin(item);
}
//--- delete all the list elements
list.Destroy();
//--- all the list elements will be deleted after the script is over
//--- see the Experts tab in the terminal
}
See also
Object Pointers, Checking the Object Pointer, Object Delete Operator delete
MQL4 Reference / Common Functions / GetTickCount
GetTickCount
The GetTickCount() function returns the number of milliseconds that elapsed since the
system start.
uint GetTickCount();
Return Value
Value of uint type.
Note
Counter is limited by the restrictions of the system timer. Time is stored as an unsigned
integer, so it's overfilled every 49.7 days if a computer works uninterruptedly.
Example:
#define MAX_SIZE 40 //+---------------------------------------------------------------
//| Script for measuring computation time of 40 Fibonacci numbers |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Remember the initial value
uint start=GetTickCount();
//--- A variable for getting the next number in the Fibonacci series
long fib=0;
//--- In loop calculate the specified amount of numbers from Fibonacci series
for(int i=0;i<MAX_SIZE;i++) fib=TestFibo(i);
//--- Get the spent time in milliseconds
uint time=GetTickCount()-start;
//--- Output a message to the Experts journal
PrintFormat("Calculating %d first Fibonacci numbers took %d ms",MAX_SIZE,time);
//--- Script completed
return;
}
//+------------------------------------------------------------------+
//| Function for getting Fibonacci number by its serial number |
//+------------------------------------------------------------------+
long TestFibo(long n)
{
//--- The first member of the Fibonacci series
if(n<2) return(1);
//--- All other members are calculated by the following formula
return(TestFibo(n-2)+TestFibo(n-1));
}
See also
Date and Time
MQL4 Reference / Common Functions / GetMicrosecondCount
GetMicrosecondCount
The GetMicrosecondCount() function returns the number of microseconds that have
elapsed since the start of MQL program.
ulong GetMicrosecondCount();
Return Value
Value of ulong type.
Example:
//+------------------------------------------------------------------+ //| Test functi
//+------------------------------------------------------------------+
void Test()
{
int res_int=0;
double res_double=0;
//---
for(int i=0;i<10000;i++)
{
res_int+=i*i;
res_int++;
res_double+=i*i;
res_double++;
}
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
uint ui=0,ui_max=0,ui_min=INT_MAX;
ulong ul=0,ul_max=0,ul_min=INT_MAX;
//--- number of measurements
for(int count=0;count<1000;count++)
{
uint ui_res=0;
ulong ul_res=0;
//---
for(int n=0;n<2;n++)
{
//--- select measurement type
if(n==0) ui=GetTickCount();
else ul=GetMicrosecondCount();
//--- execute code
Test();
//--- add measurement result (depending on type)
if(n==0) ui_res+=GetTickCount()-ui;
else ul_res+=GetMicrosecondCount()-ul;
}
//--- calculate minimum and maximum time for both measurements
if(ui_min>ui_res) ui_min=ui_res;
if(ui_max<ui_res) ui_max=ui_res;
if(ul_min>ul_res) ul_min=ul_res;
if(ul_max<ul_res) ul_max=ul_res;
}
//---
Print("GetTickCount error(msec): ",ui_max-ui_min);
Print("GetMicrosecondCount error(msec): ",DoubleToString((ul_max-ul_min)/1000.0,2)
}
See also
Date and Time
MQL4 Reference / Common Functions / MessageBox
MessageBox
It creates and shows a message box and manages it. A message box
contains a message and header, any combination of predefined signs
and command buttons.
int MessageBox( string text, // message text
string caption=NULL, // box header
int flags=0 // defines set of buttons in the box
);
Parameters
text
[in] Text, containing message to output.
caption=NULL
[in] Optional text to be displayed in the box header. If the
parameter is empty, Expert Advisor name is shown in the box
header.
flags=0
[in] Optional flags defining appearance and behavior of a message
box. Flags can be a combination of a special group of flags.
Return Value
If the function is successfully performed, the returned value is one
of values of MessageBox() return codes.
Note
The function can't be called from custom indicators, because
indicators are executed in the interface thread and shouldn't slow it
down.
MessageBox() function does not work in the Strategy Tester.
MQL4 Reference / Common Functions / PeriodSeconds
PeriodSeconds
This function returns number of seconds in a period.
int PeriodSeconds( ENUM_TIMEFRAMES period=PERIOD_CURRENT // chart period
);
Parameters
period=PERIOD_CURRENT
[in] Value of a chart period from the enumeration ENUM_TIMEFRAMES. If the
parameter isn't specified, it returns the number of seconds of the current chart
period, at which the program runs.
Return Value
Number of seconds in a selected period.
See also
_Period, Chart timeframes, Date and Time, Visibility of objects
MQL4 Reference / Common Functions / PlaySound
PlaySound
It plays a sound file.
bool PlaySound( string filename // file name
);
Parameters
filename
[in] Path to a sound file. If filename=NULL, the
playback is stopped.
Return Value
true if the file is found, otherwise - false.
Note
The file must be located in terminal_directory\Sounds or
its sub-directory. Only WAV files are played.
Call of PlaySound() with NULL parameter stops playback.
PlaySound() function does not work in the Strategy
Tester.
See also
Resources
MQL4 Reference / Common Functions / Print
Print
It enters a message in the Expert Advisor log. Parameters can be of any type.
void Print( argument, // first value
... // next values
);
Parameters
...
[in] Any values separated by commas. The number of parameters cannot exceed 64.
Note
Arrays cannot be passed to the Print() function. Arrays must be input element-by-
element.
Data of double type are shown with the accuracy of up to 16 digits after a decimal
point, and can be output either in traditional or in scientific format, depending on
what entry will be more compact. Data of float type are output with 5 digits after a
decimal point. To output real numbers with another accuracy or in a predefined
format, use the PrintFormat() function.
Data of bool type are output as "true" or "false" lines. Dates are shown as YYYY.MM.DD
HH:MI:SS. To show data in another format, use TimeToString(). Data of color type are
returned either as R,G,B line or as a color name, if this color is present in the color set.
Print() function does not work during optimization in the Strategy Tester.
Example:
void OnStart()
{
//--- Output DBL_MAX using Print(), this is equivalent to PrintFormat(%%.16G,DBL_MAX)
Print("---- how DBL_MAX looks like -----");
Print("Print(DBL_MAX)=",DBL_MAX);
//--- Now output a DBL_MAX number using PrintFormat()
PrintFormat("PrintFormat(%%.16G,DBL_MAX)=%.16G",DBL_MAX);
//--- Output to the Experts journal
// Print(DBL_MAX)=1.797693134862316e+308
// PrintFormat(%.16G,DBL_MAX)=1.797693134862316E+308
//--- Show what can happen with arithmetic operations with real types
double a=7,b=200;
Print("---- Before arithmetic operations");
Print("a=",a," b=",b);
Print("Print(DoubleToString(b,16))=",DoubleToString(b,16));
//--- Divide a by b (7/200)
a=a/b;
//--- Now emulate restoring a value in the b variable
b=7.0/a; // It is expected that b=7.0/(7.0/200.0)=>7.0/7.0*200.0=200 - but it diff
//--- Output the newly calculated value of b
Print("----- After arithmetic operations");
Print("Print(b)=",b);
Print("Print(DoubleToString(b,16))=",DoubleToString(b,16));
//--- Output to the Experts journal
// Print(b)=200.0
// Print(DoubleToString(b,16))=199.9999999999999716 (see that b is no more equal to 2
See also
Alert(), Comment(), DoubleToString(), StringFormat()
MQL4 Reference / Common Functions / PrintFormat
PrintFormat
It formats and enters sets of symbols and values in the Expert Advisor log in accordance
with a preset format.
void PrintFormat( string format_string, // format string
... // values of simple types
);
Parameters
format_string
[in] A format string consists of simple symbols, and if the format string is followed by
arguments, it also contains format specifications.
...
[in] Any values of simple types separated by commas. Total number of parameters
can't exceed 64 including the format string.
Return Value
String.
Note
PrintFormat() function does not work during optimization in the Strategy Tester.
The number, order and type of parameters must exactly match the set of qualifiers,
otherwise the print result is undefined. Instead of PrintFormat() you can use printf().
If the format string is followed by parameters, this string must contain format
specifications that denote output format of these parameters. Specification of format
always starts with the percent sign (%).
A format string is read from left to right. When the first format specification is met (if
there is any), the value of the first parameter after the format string is transformed
and output according to the preset specification. The second format specification calls
transformation and output of the second parameter, and so on till the format string
end.
The format specification has the following form:
%[flags][width][.precision][{h | l | ll | I32 | I64}]type
Each field of the format specification is either a simple symbol, or a number denoting a
simple format option. The simplest format specification contains only the percent sign
(%) and a symbol defining the type of the output parameter (for example, %s). If you
need to output the percent sign in the format string, use the format specification %%.
flags
Flag Description Default Behavior
(minus) Left justification within the set width Right justification
Flag Description Default Behavior
+ (plus) Output of the + or - sign for values of sign types The sign is shown only if the
value is negative
0 (zero) Zeroes are added before an output value within the Nothing is added
preset width. If 0 flag is specified with an integer
format (i, u, x, X, o, d) and accuracy specification is
set (for example, %04.d), then 0 is ignored.
space A space is shown before an output value, if it is a Spaces aren't inserted
sign and positive value
# If used together with the format o, x or X, then Nothing is added
before the output value 0, 0x or 0X is added
respectively.
If used together with the format e, E, a or A, value Decimal point is shown only if
is always shown with a decimal point. there is a non-zero fractional
part.
If used together with the format g or G, flag defines Decimal point is shown only if
presence of a decimal point in the output value and there is a non-zero fractional
prevents the cutting off of leading zeroes. part. Leading zeroes are cut
Flag # is ignored when used together with formats c, off.
d, i, u, s.
width
A non-negative decimal number that sets the minimal number of output symbols of the
formatted value. If the number of output symbols is less than the specified width, the
corresponding number of spaces is added from the left or right depending on the
alignment (flag ). If there is flag zero (0), the corresponding number of zeroes is added
before the output value. If the number of output symbols is greater than the specified
width, the output value is never cut off.
If an asterisk (*) is specified as width, value of int type must be indicated in the
corresponding place of the list of passed parameters. It will be used for specifying
width of the output value.
precision
A non-negative decimal number that sets the output accuracy - number of digits after a
decimal point. As distinct from width specification, accuracy specification can cut off
the part of fractional type with or without rounding.
The use of accuracy specification is different for different format types.
Types Description Default Behavior
a, A Accuracy specification sets the number of digits Default accuracy 6.
after a decimal point.
c, C Not used
Types Description Default Behavior
d, i, u, Sets minimal number of output digits. If number of Default accuracy 1.
o, x, X digits in a corresponding parameter is less than this
accuracy, zeroes are added to the left of the output
value. The output value isn't cut off, if the number
of output digits is larger than the specified
accuracy.
e, E, f Sets number of output digits after a decimal point. Default accuracy 6. If set
The last digit is rounded off. accuracy is 0 or decimal part is
absent, the decimal point is not
shown.
g, G Sets maximal number of meaningful numbers. 6 meaningful numbers are
output.
s, S Sets number of output symbols of a string. If the The whole string is output.
string length exceeds the accuracy, the string is cut
off.
h | l | ll | I32 | I64
Specification of data sizes, passed as a parameter.
Parameter Used Prefix Joint Specifier of Type
Type
int l (lower case L) d, i, o, x, or X
uint l (lower case L) o, u, x, or X
long ll (two lower d, i, o, x, or X
case L)
short h d, i, o, x, or X
ushort h o, u, x, or X
int I32 d, i, o, x, or X
uint I32 o, u, x, or X
long I64 d, i, o, x, or X
ulong I64 o, u, x, or X
type
Type specifier is the only obligatory field for formatted output.
Symbol Type Output Format
c int Symbol of short type (Unicode)
C int Symbol of char type (ANSI)
d int Signed decimal integer
i int Signed decimal integer
o int Unsigned octal integer
u int Unsigned decimal integer
Symbol Type Output Format
x int Unsigned hexadecimal integer, using "abcdef"
X int Unsigned hexadecimal integer, using "ABCDEF"
e double A real value in the format [-] d.dddde[sign] ddd, where d - one decimal
digit, dddd - one or more decimal digits, ddd - a three-digit number that
determines the size of the exponent, sign - plus or minus
E double Similar to the format of e, except that the sign of exponent is output by
upper case letter (E instead of e)
f double A real value in the format [-] dddd.dddd, where dddd - one or more decimal
digits. Number of displayed digits before the decimal point depends on the
size of number value. Number of digits after the decimal point depends on
the required accuracy.
g double A real value output in f or e format depending on what output is more
compact.
G double A real value output in F or E format depending on what output is more
compact.
a double A real number in format [−]0xh.hhhh p±dd, where h.hhhh mantissa in the
form of hexadecimal digits, using "abcdef", dd - One or more digits of
exponent. Number of decimal places is determined by the accuracy
specification
A double A real number in format [−]0xh.hhhh P±dd, where h.hhhh mantissa in the
form of hexadecimal digits, using "ABCDEF", dd - One or more digits of
exponent. Number of decimal places is determined by the accuracy
specification
s string String output
Instead of PrintFormat() you can use printf().
Example:
void OnStart()
{
//--- trade server name
string server=AccountInfoString(ACCOUNT_SERVER);
//--- account number
int login=(int)AccountInfoInteger(ACCOUNT_LOGIN);
//--- long value output
long leverage=AccountInfoInteger(ACCOUNT_LEVERAGE);
PrintFormat("%s %d: leverage = 1:%I64d",
server,login,leverage);
//--- account currency
string currency=AccountInfoString(ACCOUNT_CURRENCY);
//--- double value output with 2 digits after the decimal point
double equity=AccountInfoDouble(ACCOUNT_EQUITY);
PrintFormat("%s %d: account equity = %.2f %s",
server,login,equity,currency);
//--- double value output with mandatory output of the +/- sign
double profit=AccountInfoDouble(ACCOUNT_PROFIT);
PrintFormat("%s %d: current result for open orders = %+.2f %s",
server,login,profit,currency);
//--- double value output with variable number of digits after the decimal point
double point_value=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
string format_string=StringFormat("%%s: point value = %%.%df",_Digits);
PrintFormat(format_string,_Symbol,point_value);
//--- int value output
int spread=(int)SymbolInfoInteger(_Symbol,SYMBOL_SPREAD);
PrintFormat("%s: current spread in points = %d ",
_Symbol,spread);
//--- double value output in the scientific (floating point) format with 17 meaningfu
PrintFormat("DBL_MAX = %.17e",DBL_MAX);
//--- double value output in the scientific (floating point) format with 17 meaningfu
PrintFormat("EMPTY_VALUE = %.17e",EMPTY_VALUE);
//--- output using PrintFormat() with default accuracy
PrintFormat("PrintFormat(EMPTY_VALUE) = %e",EMPTY_VALUE);
//--- simple output using Print()
Print("Print(EMPTY_VALUE) = ",EMPTY_VALUE);
/* execution result
MetaQuotes-Demo 4236774: leverage = 1:100
MetaQuotes-Demo 4236774: account equity = 9998.49 USD
MetaQuotes-Demo 4236774: current result for open orders = -1.51 USD
EURJPY: point value = 0.001
EURJPY: current spread in points = 15
DBL_MAX = 1.79769313486231570e+308
EMPTY_VALUE = 2.14748364700000000e+009
PrintFormat(EMPTY_VALUE) = 2.147484e+009
Print(EMPTY_VALUE) = 2147483647
*/
}
See also
StringFormat(), DoubleToString(), Real types (double, float)
MQL4 Reference / Common Functions / ResetLastError
ResetLastError
Sets the value of the predefined variable _LastError into
zero.
void ResetLastError();
Return Value
No return value.
Note
The GetLastError() function zero the _LastError
variable.
MQL4 Reference / Common Functions / ResourceCreate
ResourceCreate
Creates an image resource based on a data set. There are two variants of the function:
Creating a resource based on a file
bool ResourceCreate(
const string resource_name, // Resource name
const string path // A relative path to the file
);
Parameters
resource_name
[in] Resource name.
path
[in] Relative path to the file, containing the resource data. If the path is started from
"\" (written as "\\"), it is assumed that file path is relative to
terminal_data_folder\MQL4\, otherwise it is assumed that file is specified relative to
.EX4 program folder.
data[][]
[in] A one-dimensional or two-dimensional array for creating a complete image.
img_width
[in] The width of the rectangular image area in pixels to be placed in the resource in
the form of an image. It cannot be greater than the data_width value.
img_height
[in] The height of the rectangular image area in pixels to be placed in the resource in
the form of an image.
data_xoffset
[in] The horizontal rightward offset of the rectangular area of the image.
data_yoffset
[in] The vertical downward offset of the rectangular area of the image.
data_width
[in] Required only for one-dimensional arrays. It denotes the full width of the image
from the data set. If data_width=0, it is assumed to be equal to img_width. For two-
dimensional arrays the parameter is ignored and is assumed to be equal to the second
dimension of the data[] array.
color_format
[in] Color processing method, from a value from the ENUM_COLOR_FORMAT
enumeration.
Return Value
Returns true if successful, otherwise false. To get information about the error call the
GetLastError() function. The following errors may occur:
4015 ERR_RESOURCE_NAME_DUPLICATED (identical names of the dynamic and the
static resource)
4016 ERR_RESOURCE_NOT_FOUND (the resource is not found)
4017 ERR_RESOURCE_UNSUPPORTED_TYPE (this type of resource is not supported)
4018 ERR_RESOURCE_NAME_IS_TOO_LONG (the name of the resource is too long)
Note
If the second version of the function is called for creating the same resource with
different width, height and shift parameters, it does not create a new resource, but
simply updates the existing one.
The first version of the function is used for uploading images and sounds from files, and
the second version is used only for the dynamic creation of images.
Images must be in the BMP format with a color depth of 24 or 32 bits. Sounds can only
be in the WAV format. The size of the resource should not exceed 16 Mb.
ENUM_COLOR_FORMAT
Identifier Description
COLOR_FORMAT_XRGB_NOALPHA The component of the alpha channel is ignored
COLOR_FORMAT_ARGB_RAW Color components are not handled by the terminal (must be
correctly set by the user)
COLOR_FORMAT_ARGB_NORMALIZE Color components are handled by the terminal
See also
Resources, ObjectCreate(), ObjectSetString(), OBJPROP_BMPFILE
MQL4 Reference / Common Functions / ResourceFree
ResourceFree
The function deletes dynamically created resource (freeing the memory
allocated for it).
bool ResourceFree( const string resource_name // resource name
);
Parameters
resource_name
[in] Resource name should start with "::".
Returned value
True if successful, otherwise false. To get information about the error, call
the GetLastError() function.
Note
ResourceFree() allows mql4 application developers to manage memory
consumption when actively working with resources. Graphical objects
bound to the resource being deleted from the memory will be displayed
correctly after its deletion. However, newly created graphical objects
(OBJ_BITMAP and OBJ_BITMAP_LABEL) will not be able to use the deleted
resource.
The function deletes only dynamic resources created by the program.
See also
Resources, ObjectCreate(), PlaySound(), ObjectSetString(),
OBJPROP_BMPFILE
MQL4 Reference / Common Functions / ResourceReadImage
ResourceReadImage
The function reads data from the graphical resource created by ResourceCreate()
function or saved in EX4 file during compilation.
bool ResourceReadImage( const string resource_name, // graphical resour
uint& data[], // array for receiving data from the resour
uint& width, // for receiving the image width in the res
uint& height // for receiving the image height in the re
);
Parameters
resource_name
[in] Name of the graphical resource containing an image. To gain access to its own
resources, the name is used in brief form "::resourcename". If we download a resource
from a compiled EX4 file, the full name should be used with the path relative to MQL4
directory, file and resource names "path\\filename.ex4::resourcename".
data[][]
[in] One- or two-dimensional array for receiving data from the graphical resource.
img_width
[out] Graphical resource image width in pixels.
img_height
[out] Graphical resource image height in pixels.
Returned value
true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
Note
If data[] array is then to be used for creating a graphical resource,
COLOR_FORMAT_ARGB_NORMALIZE or COLOR_FORMAT_XRGB_NOALPHA color formats
should be used.
If data[] array is two-dimensional and its second dimension is less than X(width)
graphical resource size, ResourceReadImage() function returns false and reading is not
performed. But if the resource exists, actual image size is returned to width and height
parameters. This will allow making another attempt to receive data from the resource.
See also
Resource, ObjectCreate(), ObjectSetString(), OBJPROP_BMPFILE
MQL4 Reference / Common Functions / ResourceSave
ResourceSave
Saves a resource into the specified file.
bool ResourceSave( const string resource_name, // Resource name
const string file_name // File name
);
Parameters
resource_name
[in] The name of the resource, must start with "::".
file_name
[in] The name of the file relative to MQL4\Files.
Return Value
true in case of success, otherwise false. For the error information call
GetLastError().
Note
The function always overwrites a file and creates all the required
intermediate directories in the file name if necessary.
See also
Resources, ObjectCreate(), PlaySound(), ObjectSetString(),
OBJPROP_BMPFILE
MQL4 Reference / Common Functions / SetUserError
SetUserError
Sets the predefined variable _LastError into the value equal
to ERR_USER_ERROR_FIRST + user_error.
void SetUserError( ushort user_error // error number
);
Parameters
user_error
[in] Error number set by a user.
Return Value
No return value.
Note
After an error has been set using the
SetUserError(user_error) function, GetLastError() returns
value equal to ERR_USER_ERROR_FIRST + user_error.
Example:
void OnStart()
{
//--- set error number 65537=(ERR_USER_ERROR_FIRST +1)
SetUserError(1);
//--- get last error code
Print("GetLastError = ",GetLastError());
//--- Result
//--- GetLastError = 65537
}
MQL4 Reference / Common Functions / SendFTP
SendFTP
Sends a file at the address, specified in the setting window of the "FTP"
tab.
bool SendFTP( string filename, // file to be send by ftp
string ftp_path=NULL // ftp catalog
);
Parameters
filename
[in] Name of sent file.
ftp_path=NULL
[in] FTP catalog. If a directory is not specified, directory described in
settings is used.
Return Value
In case of failure returns 'false'.
Note
Sent file must be located in the folder terminal_directory\MQL4\files or
its subfolders. Sending isn't performed if FTP address and/or access
password are not specified in settings.
SendFTP() function does not work in the Strategy Tester.
What's new in MQL5
In MQL5, the SendFTP, SendMail and SendNotification functions are moved
to the new extended Network functions section. Now programs can
exchange data with remote servers included in the list of allowed IP
addresses. This means that MQL5 EAs are able to establish secure
connections between processes using the TCP/IP protocol without using
third-party DLLs.
MQL4 Reference / Common Functions / SendMail
SendMail
Sends an email at the address specified in the settings
window of the "Email" tab.
bool SendMail( string subject, // header
string some_text // email text
);
Parameters
subject
[in] Email header.
some_text
[in] Email body.
Return Value
true if an email is put into the send queue, otherwise -
false.
Note
Sending can be prohibited in settings, email address can
be omitted as well. For the error information call
GetLastError().
SendMail() function does not work in the Strategy Tester.
What's new in MQL5
In MQL5, the SendFTP, SendMail and SendNotification
functions are moved to the new extended Network
functions section. Now programs can exchange data with
remote servers included in the list of allowed IP
addresses. This means that MQL5 EAs are able to establish
secure connections between processes using the TCP/IP
protocol without using third-party DLLs.
MQL4 Reference / Common Functions / SendNotification
SendNotification
Sends push notifications to the mobile terminals, whose MetaQuotes IDs are
specified in the "Notifications" tab.
bool SendNotification( string text // Text of the notification
);
Parameters
text
[in] The text of the notification. The message length should not exceed 255
characters.
Return Value
true if a notification has been successfully sent from the terminal; in case of
failure returns false. When checking after a failed push of notification,
GetLastError () may return one of the following errors:
4250 ERR_NOTIFICATION_SEND_FAILED,
4251 ERR_NOTIFICATION_WRONG_PARAMETER,
4252 ERR_NOTIFICATION_WRONG_SETTINGS,
4253 ERR_NOTIFICATION_TOO_FREQUENT.
Note
Strict use restrictions are set for the SendNotification() function: no more than
2 calls per second and not more than 10 calls per minute. Monitoring the
frequency of use is dynamic. The function can be disabled in case of the
restriction violation.
SendNotification() function does not work in the Strategy Tester.
What's new in MQL5
In MQL5, the SendFTP, SendMail and SendNotification functions are moved to the
new extended Network functions section. Now programs can exchange data with
remote servers included in the list of allowed IP addresses. This means that
MQL5 EAs are able to establish secure connections between processes using the
TCP/IP protocol without using third-party DLLs.
MQL4 Reference / Common Functions / Sleep
Sleep
The function suspends execution of the current Expert
Advisor or script within a specified interval.
void Sleep( int milliseconds // interval
);
Parameters
milliseconds
[in] Delay interval in milliseconds.
Return Value
No return value.
Note
The Sleep() function can't be called for custom
indicators, because indicators are executed in the
interface thread and must not slow down it. The
function has the built-in check of EA halt flag every 0.1
seconds.
Sleep() function does not suspend execution of the
Expert Advisor in the Strategy Tester.
MQL4 Reference / Common Functions / TerminalClose
TerminalClose
The function commands the terminal to complete operation.
bool TerminalClose( int ret_code // closing code of the client terminal
);
Parameters
ret_code
[in] Return code, returned by the process of the client terminal at the operation
completion.
Return Value
The function returns true on success, otherwise - false.
Note
The TerminalClose() function does not stop the terminal immediately, it just
commands the terminal to complete its operation.
The code of an Expert Advisor that called TerminalClose() must have all
arrangements for the immediate completion (e.g. all previously opened files must
be closed in the normal mode). Call of this function must be followed by the return
operator.
The ret_code parameter allows indicating the necessary return code for analyzing
reasons of the program termination of the terminal operation when starting it from
the command prompt.
Example:
//--- input parameters
input int tiks_before=500; // number of ticks till termination
input int pips_to_go=15; // distance in pips
input int seconds_st=50; // number of seconds given to the Expert Advisor
//--- globals
datetime launch_time;
int tick_counter=0;
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
Print(__FUNCTION__," reason code = ",reason);
Comment("");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
static double first_bid=0.0;
MqlTick tick;
double distance;
//---
SymbolInfoTick(_Symbol,tick);
tick_counter++;
if(first_bid==0.0)
{
launch_time=tick.time;
first_bid=tick.bid;
Print("first_bid =",first_bid);
return;
}
//--- price distance in pips
distance=(tick.bid-first_bid)/_Point;
//--- show a notification to track the EA operation
string comm="From the moment of start:\r\n\x25CF elapsed seconds: "+
IntegerToString(tick.time-launch_time)+" ;"+
"\r\n\x25CF ticks received: "+(string)tick_counter+" ;"+
"\r\n\x25CF price went in points: "+StringFormat("%G",distance);
Comment(comm);
//--- section for checking condition to close the terminal
if(tick_counter>=tiks_before)
TerminalClose(0); // exit by tick counter
if(distance>pips_to_go)
TerminalClose(1); // go up by the number of pips equal to pips_to_go
if(distance<-pips_to_go)
TerminalClose(-1); // go down by the number of pips equal to pips_to_go
if(tick.time-launch_time>seconds_st)
TerminalClose(100); // termination by timeout
//---
}
See also
Program running, Execution errors, Reasons for deinitialization
MQL4 Reference / Common Functions / TesterStatistics
TesterStatistics
The function returns the value of the specified statistical parameter
calculated based on testing results.
double TesterStatistics( ENUM_STATISTICS statistic_id // ID
);
Parameters
statistic_id
[in] The ID of the statistical parameter from the ENUM_STATISTICS
enumeration.
Return Value
The value of the statistical parameter from testing results.
Note
The function can be called inside OnTester() or OnDeinit() in the
tester. In other cases the result is undefined.
MQL4 Reference / Common Functions / TranslateKey
TranslateKey
Returns a Unicode character by a virtual key code considering the current input language
and the status of control keys.
short TranslateKey( int key_code // key code for receiving a Unicode charact
);
Parameters
key_code
[in] Key code.
Return Value
Unicode character in case of a successful conversion. The function returns -1 in case of
an error.
Note
The function uses ToUnicodeEx to convert keys pressed by a user into Unicode
characters. An error may occur in case ToUnicodeEx is not triggered for example, when
trying to receive the SHIFT key character.
Example:
void OnChartEvent(const int id,const long& lparam,const double& dparam,const string&
{
if(id==CHARTEVENT_KEYDOWN)
{
short sym=TranslateKey((int)lparam);
//--- if the entered character is successfully converted to Unicode
if(sym>0)
Print(sym,"'",ShortToString(sym),"'");
else
Print("Error in TranslateKey for key=",lparam);
}
}
See also
Client terminal events, OnChartEvent
MQL4 Reference / Common Functions / WebRequest
WebRequest
The function sends an HTTP request to a specified server. The function has two versions:
1. Sending simple requests of type "key=value" using the header Content-Type:
application/x-www-form-urlencoded.
int WebRequest( const string method, // HTTP method
const string url, // URL
const string cookie, // cookie
const string referer, // referer
int timeout, // timeout
const char &data[], // the array of the HTTP message body
int data_size, // data[] array size in bytes
char &result[], // an array containing server response data
string &result_headers // headers of server response
);
2. Sending a request of any type specifying the custom set of headers for a more
flexible interaction with various Web services.
int WebRequest(
const string method, // HTTP method
const string url, // URL
const string headers, // headers
int timeout, // timeout
const char &data[], // the array of the HTTP message body
char &result[], // an array containing server response data
string &result_headers // headers of server response
);
Parameters
method
[in] HTTP method.
url
[in] URL.
headers
[in] Request headers of type "key: value", separated by a line break "\r\n".
cookie
[in] Cookie value.
referer
[in] Value of the Referer header of the HTTP request.
timeout
[in] Timeout in milliseconds.
data[]
[in] Data array of the HTTP message body.
data_size
[in] Size of the data[] array.
result[]
[out] An array containing server response data.
result_headers
[out] Server response headers.
Returned value
HTTP server response code or -1 for an error.
Note
To use the WebRequest() function, add the addresses of the required servers in the list
of allowed URLs in the "Expert Advisors" tab of the "Options" window. Server port is
automatically selected on the basis of the specified protocol - 80 for "http://" and 443
for "https://".
The WebRequest() function is synchronous, which means its breaks the program
execution and waits for the response from the requested server. Since the delays in
receiving a response can be large, the function is not available for calls from the
indicators, because indicators run in a common thread shared by all indicators and
charts on one symbol. Indicator performance delay on one of the charts of a symbol
may stop updating of all charts of the same symbol.
The function can be called only from Expert Advisors and scripts, as they run in their
own execution threads. If you try to call the function from an indicator, GetLastError()
will return error 4060 "Function is not allowed for call".
WebRequest() cannot be executed in the Strategy Tester.
An example of using the first version of the WebRequest () function:
void OnStart()
{
string cookie=NULL,headers;
char post[],result[];
int res;
//--- to enable access to the server, you should add URL "https://www.google.com/fina
//--- in the list of allowed URLs (Main Menu->Tools->Options, tab "Expert Advisors"):
string google_url="https://www.google.com/finance";
//--- Reset the last error code
ResetLastError();
//--- Loading a html page from Google Finance
int timeout=5000; //--- Timeout below 1000 (1 sec.) is not enough for slow Interne
res=WebRequest("GET",google_url,cookie,NULL,timeout,post,0,result,headers);
//--- Checking errors
if(res==-1)
{
Print("Error in WebRequest. Error code =",GetLastError());
//--- Perhaps the URL is not listed, display a message about the necessity to a
MessageBox("Add the address '"+google_url+"' in the list of allowed URLs on tab
}
else
{
//--- Load successfully
PrintFormat("The file has been successfully loaded, File size =%d bytes.",Array
//--- Save the data to a file
int filehandle=FileOpen("GoogleFinance.htm",FILE_WRITE|FILE_BIN);
//--- Checking errors
if(filehandle!=INVALID_HANDLE)
{
//--- Save the contents of the result[] array to a file
FileWriteArray(filehandle,result,0,ArraySize(result));
//--- Close the file
FileClose(filehandle);
}
else Print("Error in FileOpen. Error code=",GetLastError());
}
}
An example of using the second version of the WebRequest() function:
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
#property script_show_inputs
#property description "Sample script posting a user message "
#property description "on the wall on mql5.com"
MQL4 Reference / Common Functions / ZeroMemory
ZeroMemory
The function resets a variable passed to it by reference.
void ZeroMemory( void & variable // reset variable
);
Parameters
variable
[in] [out] Variable passed by reference, you want to reset
(initialize by zero values).
Return Value
No return value.
Note
If the function parameter is a string, the call will be
equivalent to indicating NULL as its value.
For simple types and their arrays, as well as for
structures/classes consisting of such types, this is a simple
reset.
For objects containing strings and dynamic arrays,
ZeroMemory() is called for each element.
For any arrays not protected by the const modifier, this is the
zeroing of all elements.
For arrays of complex objects, ZeroMemory() is called for
each element.
ZeroMemory() can't be applied to classes with protected
members or inheritance.
MQL4 Reference / Array Functions
What's new in MQL5
Added functions for quick insertion, deletion, copying and
expanding array elements. The new ArraySwap() function
swaps the contents of two dynamic arrays of the same
type, while the ArrayPrint() function allows you to easily
print an array of a simple type or a simple structure in the
journal.
For fast and easy visualization, use the Graphics library
containing the functions for fast drawing of five chart
types with auto scaling, color selection and line
smoothing.
MQL4 Reference / Array Functions / ArrayBsearch
ArrayBsearch
Searches for a specified value in a multidimensional numeric array sorted in the
ascending order. The search is performed in the first dimension taking into account the
AS_SERIES flag.
For searching in an array of double type
int ArrayBsearch( const double& array[], // array for search
double value, // what is searched for
int count=WHOLE_ARRAY, // count of elements to search for
int start=0, // starting position
int direction=MODE_ASCEND // search direction
);
Parameters
array[]
[in] Numeric array for search.
value
[in] Value for search.
count=WHOLE_ARRAY
[in] Count of elements to search for. By default, it searches in the whole array.
start=0
[in] Starting index to search for. By default, the search starts at the first element.
direction=MODE_ASCEND
[in] Search direction. It can be any of the following values:
MODE_ASCEND searching in forward direction,
MODE_DESCEND searching in backward direction.
Return Value
The function returns index of a found element. If the wanted value isn't found, the
function returns the index of an element nearest in value.
Note
Binary search processes only sorted arrays. To sort numeric arrays use the ArraySort()
function.
Example:
datetime daytimes[];
int shift=10,dayshift;
// All the Time[] series are sorted in descendant mode
ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1);
if(Time[shift]>=daytimes[0]) dayshift=0;
else
{
dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND);
if(Period()<PERIOD_D1) dayshift++;
}
Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar opened at ",
TimeToStr(daytimes[dayshift]));
MQL4 Reference / Array Functions / ArrayCopy
ArrayCopy
It copies an array into another one.
int ArrayCopy( void& dst_array[], // destination array
const void& src_array[], // source array
int dst_start=0, // index starting from which write into destinat
int src_start=0, // first index of a source array
int count=WHOLE_ARRAY // number of elements
);
Parameters
dst_array[]
[out] Destination array
src_array[]
[in] Source array
dst_start=0
[in] Starting index from the destination array. By default, start index is 0.
src_start=0
[in] Starting index for the source array. By default, start index is 0.
count=WHOLE_ARRAY
[in] Number of elements that should be copied. By default, the whole array is copied
(count=WHOLE_ARRAY).
Return Value
It returns the number of copied elements.
Note
If count<=0 or count>src_size-src_start, all the remaining array part is copied. Arrays
are copied from left to right. For series arrays, the starting position is correctly defined
adjusted for copying from left to right. If an array is copied to itself, the result is
undefined.
If arrays are of different types, during copying it tries to transform each element of a
source array into the type of the destination array. A string array can be copied into a
string array only. Array of classes and structures containing objects that require
initialization aren't copied. An array of structures can be copied into an array of the
same type only.
For static and dynamic arrays (except for class and structure members), the size of a
destination array is automatically increased to the amount of copied data (if the latter
exceeds the array size).
Example:
void OnStart()
{
//---
int src_data[10];
for (int i=0; i<ArraySize(src_data); i++) src_data[i]=i;
int dst_data[];
//--- copy data to dst_data[]
ArrayCopy(dst_data,src_data,0,0,WHOLE_ARRAY);
//--- print copied data[]
PrintFormat("Copied array size=%d",ArraySize(dst_data));
for (int i=0; i<ArraySize(dst_data); i++) PrintFormat("index=%d, value=%d",i,dst_d
}
MQL4 Reference / Array Functions / ArrayCompare
ArrayCompare
The function returns the result of comparing two arrays of the same type. It
can be used to compare arrays of simple types or custom structures without
complex objects, that is the custom structures that do not contain strings,
dynamic arrays, classes and other structures with complex objects.
int ArrayCompare( const void& array1[], // first array
const void& array2[], // second array
int start1=0, // initial offset in the first array
int start2=0, // initial offset in the second array
int count=WHOLE_ARRAY // number of elements for comparison
);
Parameters
array1[]
[in] First array.
array2[]
[in] Second array.
start1=0
[in] The element's initial index in the first array, from which comparison
starts. The default start index - 0.
start2=0
[in] The element's initial index in the second array, from which comparison
starts. The default start index - 0.
count=WHOLE_ARRAY
[in] Number of elements to be compared. All elements of both arrays
participate in comparison by default (count=WHOLE_ARRAY).
Returned value
-1, if array1[] less than array2[]
0, if array1[] equal to array2[]
1, if array1[] more than array2[]
-2, if an error occurs due to incompatibility of the types of compared
arrays or if start1, start2 or count values lead to falling outside the array.
Note
The function will not return 0 (the arrays will not be considered equal) if the
arrays differ in size and count=WHOLE_ARRAY for the case when one array is a
faithful subset of another one. In this case, the result of comparing the sizes
of that arrays will be returned: -1, if the size of array1[] is less than the size
of array2[] , otherwise 1.
MQL4 Reference / Array Functions / ArrayFree
ArrayFree
It frees up a buffer of any dynamic array and sets the size of the zero dimension to 0.
void ArrayFree( void& array[] // array
);
Parameters
array[]
[in] Dynamic array.
Return Value
No return value.
Note
The need for using ArrayFree() function may not appear too often considering that all
used memory is freed at once and main work with the arrays comprises the access to
the indicator buffers. The sizes of the buffers are automatically managed by the
terminal's executive subsystem.
In case it is necessary to manually manage the memory in complex dynamic
environment of the application, ArrayFree() function allows users to free the memory
occupied by the already unnecessary dynamic array explicitly and immediately.
Example:
#include <Controls\Dialog.mqh>
#include <Controls\Button.mqh>
#include <Controls\Label.mqh>
#include <Controls\ComboBox.mqh>
//--- predefined constants
#define X_START 0
#define Y_START 0
#define X_SIZE 280
#define Y_SIZE 300
//+------------------------------------------------------------------+
//| Dialog class for working with memory |
//+------------------------------------------------------------------+
class CMemoryControl : public CAppDialog
{
private:
//--- array size
int m_arr_size;
//--- arrays
char m_arr_char[];
int m_arr_int[];
float m_arr_float[];
double m_arr_double[];
long m_arr_long[];
//--- labels
CLabel m_lbl_memory_physical;
CLabel m_lbl_memory_total;
CLabel m_lbl_memory_available;
CLabel m_lbl_memory_used;
CLabel m_lbl_array_size;
CLabel m_lbl_array_type;
CLabel m_lbl_error;
CLabel m_lbl_change_type;
CLabel m_lbl_add_size;
//--- buttons
CButton m_button_add;
CButton m_button_free;
//--- combo boxes
CComboBox m_combo_box_step;
CComboBox m_combo_box_type;
//--- current value of the array type from the combo box
int m_combo_box_type_value;
public:
CMemoryControl(void);
~CMemoryControl(void);
//--- class object creation method
virtual bool Create(const long chart,const string name,const int subwin,const
//--- handler of chart events
virtual bool OnEvent(const int id,const long &lparam,const double &dparam,con
protected:
//--- create labels
bool CreateLabel(CLabel &lbl,const string name,const int x,const int
//--- create control elements
bool CreateButton(CButton &button,const string name,const int x,const
bool CreateComboBoxStep(void);
bool CreateComboBoxType(void);
//--- event handlers
void OnClickButtonAdd(void);
void OnClickButtonFree(void);
void OnChangeComboBoxType(void);
//--- methods for working with the current array
void CurrentArrayFree(void);
bool CurrentArrayAdd(void);
};
//+------------------------------------------------------------------+
//| Free memory of the current array |
//+------------------------------------------------------------------+
void CMemoryControl::CurrentArrayFree(void)
{
//--- reset array size
m_arr_size=0;
//--- free the array
if(m_combo_box_type_value==0)
ArrayFree(m_arr_char);
if(m_combo_box_type_value==1)
ArrayFree(m_arr_int);
if(m_combo_box_type_value==2)
ArrayFree(m_arr_float);
if(m_combo_box_type_value==3)
ArrayFree(m_arr_double);
if(m_combo_box_type_value==4)
ArrayFree(m_arr_long);
}
//+------------------------------------------------------------------+
//| Attempt to add memory for the current array |
//+------------------------------------------------------------------+
bool CMemoryControl::CurrentArrayAdd(void)
{
//--- exit if the size of the used memory exceeds the size of the physical memory
if(TerminalInfoInteger(TERMINAL_MEMORY_PHYSICAL)/TerminalInfoInteger(TERMINAL_MEMO
return(false);
//--- attempt to allocate memory according to the current type
if(m_combo_box_type_value==0 && ArrayResize(m_arr_char,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==1 && ArrayResize(m_arr_int,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==2 && ArrayResize(m_arr_float,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==3 && ArrayResize(m_arr_double,m_arr_size)==-1)
return(false);
if(m_combo_box_type_value==4 && ArrayResize(m_arr_long,m_arr_size)==-1)
return(false);
//--- memory allocated
return(true);
}
//+------------------------------------------------------------------+
//| Handling events |
//+------------------------------------------------------------------+
EVENT_MAP_BEGIN(CMemoryControl)
ON_EVENT(ON_CLICK,m_button_add,OnClickButtonAdd)
ON_EVENT(ON_CLICK,m_button_free,OnClickButtonFree)
ON_EVENT(ON_CHANGE,m_combo_box_type,OnChangeComboBoxType)
EVENT_MAP_END(CAppDialog)
//+------------------------------------------------------------------+
//| Constructor |
//+------------------------------------------------------------------+
CMemoryControl::CMemoryControl(void)
{
}
//+------------------------------------------------------------------+
//| Destructor |
//+------------------------------------------------------------------+
CMemoryControl::~CMemoryControl(void)
{
}
//+------------------------------------------------------------------+
//| Class object creation method |
//+------------------------------------------------------------------+
bool CMemoryControl::Create(const long chart,const string name,const int subwin,
const int x1,const int y1,const int x2,const int y2)
{
//--- create base class object
if(!CAppDialog::Create(chart,name,subwin,x1,y1,x2,y2))
return(false);
//--- prepare strings for labels
string str_physical="Memory physical = "+(string)TerminalInfoInteger(TERMINAL_MEMO
string str_total="Memory total = "+(string)TerminalInfoInteger(TERMINAL_MEMORY_TOT
string str_available="Memory available = "+(string)TerminalInfoInteger(TERMINAL_ME
string str_used="Memory used = "+(string)TerminalInfoInteger(TERMINAL_MEMORY_USED)
//--- create labels
if(!CreateLabel(m_lbl_memory_physical,"physical_label",X_START+10,Y_START+5,str_ph
return(false);
if(!CreateLabel(m_lbl_memory_total,"total_label",X_START+10,Y_START+30,str_total,1
return(false);
if(!CreateLabel(m_lbl_memory_available,"available_label",X_START+10,Y_START+55,str
return(false);
if(!CreateLabel(m_lbl_memory_used,"used_label",X_START+10,Y_START+80,str_used,12,c
return(false);
if(!CreateLabel(m_lbl_array_type,"type_label",X_START+10,Y_START+105,"Array type =
return(false);
if(!CreateLabel(m_lbl_array_size,"size_label",X_START+10,Y_START+130,"Array size =
return(false);
if(!CreateLabel(m_lbl_error,"error_label",X_START+10,Y_START+155,"",12,clrRed))
return(false);
if(!CreateLabel(m_lbl_change_type,"change_type_label",X_START+10,Y_START+185,"Chan
return(false);
if(!CreateLabel(m_lbl_add_size,"add_size_label",X_START+10,Y_START+210,"Add to arr
return(false);
//--- create control elements
if(!CreateButton(m_button_add,"add_button",X_START+15,Y_START+245,"Add",12,clrBlue
return(false);
if(!CreateButton(m_button_free,"free_button",X_START+75,Y_START+245,"Free",12,clrB
return(false);
if(!CreateComboBoxType())
return(false);
if(!CreateComboBoxStep())
return(false);
//--- initialize the variable
m_arr_size=0;
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create the button |
//+------------------------------------------------------------------+
bool CMemoryControl::CreateButton(CButton &button,const string name,const int x,
const int y,const string str,const int font_size,
const int clr)
{
//--- create the button
if(!button.Create(m_chart_id,name,m_subwin,x,y,x+50,y+20))
return(false);
//--- text
if(!button.Text(str))
return(false);
//--- font size
if(!button.FontSize(font_size))
return(false);
//--- label color
if(!button.Color(clr))
return(false);
//--- add the button to the control elements
if(!Add(button))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create a combo box for the array size |
//+------------------------------------------------------------------+
bool CMemoryControl::CreateComboBoxStep(void)
{
//--- create the combo box
if(!m_combo_box_step.Create(m_chart_id,"step_combobox",m_subwin,X_START+100,Y_STAR
return(false);
//--- add elements to the combo box
if(!m_combo_box_step.ItemAdd("100 000",100000))
return(false);
if(!m_combo_box_step.ItemAdd("1 000 000",1000000))
return(false);
if(!m_combo_box_step.ItemAdd("10 000 000",10000000))
return(false);
if(!m_combo_box_step.ItemAdd("100 000 000",100000000))
return(false);
//--- set the current combo box element
if(!m_combo_box_step.SelectByValue(1000000))
return(false);
//--- add the combo box to control elements
if(!Add(m_combo_box_step))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create a combo box for the array type |
//+------------------------------------------------------------------+
bool CMemoryControl::CreateComboBoxType(void)
{
//--- create the combo box
if(!m_combo_box_type.Create(m_chart_id,"type_combobox",m_subwin,X_START+100,Y_STAR
return(false);
//--- add elements to the combo box
if(!m_combo_box_type.ItemAdd("char",0))
return(false);
if(!m_combo_box_type.ItemAdd("int",1))
return(false);
if(!m_combo_box_type.ItemAdd("float",2))
return(false);
if(!m_combo_box_type.ItemAdd("double",3))
return(false);
if(!m_combo_box_type.ItemAdd("long",4))
return(false);
//--- set the current combo box element
if(!m_combo_box_type.SelectByValue(3))
return(false);
//--- store the current combo box element
m_combo_box_type_value=3;
//--- add the combo box to control elements
if(!Add(m_combo_box_type))
return(false);
//--- successful execution
return(true);
}
//+------------------------------------------------------------------+
//| Create a label |
//+------------------------------------------------------------------+
bool CMemoryControl::CreateLabel(CLabel &lbl,const string name,const int x,
const int y,const string str,const int font_size,
const int clr)
{
//--- create a label
if(!lbl.Create(m_chart_id,name,m_subwin,x,y,0,0))
return(false);
//--- text
if(!lbl.Text(str))
return(false);
//--- font size
if(!lbl.FontSize(font_size))
return(false);
//--- color
if(!lbl.Color(clr))
return(false);
//--- add the label to control elements
if(!Add(lbl))
return(false);
//--- succeed
return(true);
}
//+------------------------------------------------------------------+
//| Handler of clicking "Add" button event |
//+------------------------------------------------------------------+
void CMemoryControl::OnClickButtonAdd(void)
{
//--- increase the array size
m_arr_size+=(int)m_combo_box_step.Value();
//--- attempt to allocate memory for the current array
if(CurrentArrayAdd())
{
//--- memory allocated, display the current status on the screen
m_lbl_memory_available.Text("Memory available = "+(string)TerminalInfoInteger(T
m_lbl_memory_used.Text("Memory used = "+(string)TerminalInfoInteger(TERMINAL_ME
m_lbl_array_size.Text("Array size = "+IntegerToString(m_arr_size));
m_lbl_error.Text("");
}
else
{
//--- failed to allocate memory, display the error message
m_lbl_error.Text("Array is too large, error!");
//--- return the previous array size
m_arr_size-=(int)m_combo_box_step.Value();
}
}
//+------------------------------------------------------------------+
//| Handler of clicking "Free" button event |
//+------------------------------------------------------------------+
void CMemoryControl::OnClickButtonFree(void)
{
//--- free the memory of the current array
CurrentArrayFree();
//--- display the current status on the screen
m_lbl_memory_available.Text("Memory available = "+(string)TerminalInfoInteger(TERM
m_lbl_memory_used.Text("Memory used = "+(string)TerminalInfoInteger(TERMINAL_MEMOR
m_lbl_array_size.Text("Array size = 0");
m_lbl_error.Text("");
}
//+------------------------------------------------------------------+
//| Handler of the combo box change event |
//+------------------------------------------------------------------+
void CMemoryControl::OnChangeComboBoxType(void)
{
//--- check if the array's type has changed
if(m_combo_box_type.Value()!=m_combo_box_type_value)
{
//--- free the memory of the current array
OnClickButtonFree();
//--- work with another array type
m_combo_box_type_value=(int)m_combo_box_type.Value();
//--- display the new array type on the screen
if(m_combo_box_type_value==0)
m_lbl_array_type.Text("Array type = char");
if(m_combo_box_type_value==1)
m_lbl_array_type.Text("Array type = int");
if(m_combo_box_type_value==2)
m_lbl_array_type.Text("Array type = float");
if(m_combo_box_type_value==3)
m_lbl_array_type.Text("Array type = double");
if(m_combo_box_type_value==4)
m_lbl_array_type.Text("Array type = long");
}
}
//--- CMemoryControl class object
CMemoryControl ExtDialog;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- create the dialog
if(!ExtDialog.Create(0,"MemoryControl",0,X_START,Y_START,X_SIZE,Y_SIZE))
return(INIT_FAILED);
//--- launch
ExtDialog.Run();
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
ExtDialog.Destroy(reason);
}
//+------------------------------------------------------------------+
//| Expert chart event function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
ExtDialog.ChartEvent(id,lparam,dparam,sparam);
}
MQL4 Reference / Array Functions / ArrayGetAsSeries
ArrayGetAsSeries
It checks direction of an array index.
bool ArrayGetAsSeries( const void& array[] // array for checking
);
Parameters
array
[in] Checked array.
Return Value
Returns true, if the specified array has the AS_SERIES flag set, i.e. access to the array is
performed back to front as in timeseries. A timeseries differs from a usual array in that
the indexing of timeseries elements is performed from its end to beginning (from the
newest data to old).
Note
To check whether an array belongs to timeseries, use the ArrayIsSeries() function.
Arrays of price data passed as input parameters into the OnCalculate() function do not
obligatorily have the indexing direction the same as in timeseries. The necessary
indexing direction can be set using the ArraySetAsSeries() function.
Example:
#property description "Indicator calculates absolute values of the difference between
#property description "Open and Close or High and Low prices displaying them in a sep
#property description "as a histrogram."
//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 1
//--- input parameters
input bool InpAsSeries=true; // Indexing direction in the indicator buffer
input bool InpPrices=true; // Calculation prices (true - Open,Close; false - High,L
//--- indicator buffer
double ExtBuffer[];
//+------------------------------------------------------------------+
//| Calculating indicator values |
//+------------------------------------------------------------------+
void CandleSizeOnBuffer(const int rates_total,const int prev_calculated,
const double &first[],const double &second[],double &buffer[]
{
//--- start variable for calculation of bars
int start_index=prev_calculated;
//--- work at the last bar if the indicator values have already been calculated at th
if(prev_calculated>0)
start_index--;
//--- define indexing direction in arrays
bool as_series_first=ArrayGetAsSeries(first);
bool as_series_second=ArrayGetAsSeries(second);
bool as_series_buffer=ArrayGetAsSeries(buffer);
//--- replace indexing direction with direct one if necessary
if(as_series_first)
ArraySetAsSeries(first,false);
if(as_series_second)
ArraySetAsSeries(second,false);
if(as_series_buffer)
ArraySetAsSeries(buffer,false);
//--- calculate indicator values
for(int i=start_index;i<rates_total;i++)
buffer[i]=MathAbs(first[i]-second[i]);
}
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- bind indicator buffers
SetIndexBuffer(0,ExtBuffer);
//--- set indexing element in the indicator buffer
ArraySetAsSeries(ExtBuffer,InpAsSeries);
//--- check for what prices the indicator is calculated
if(InpPrices)
{
//--- Open and Close prices
IndicatorShortName("BodySize");
//--- set the indicator color
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3,clrOrange);
}
else
{
//--- High and Low prices
IndicatorShortName("ShadowSize");
//--- set the indicator color
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3,clrDodgerBlue);
}
//---
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- calculate the indicator according to the flag value
if(InpPrices)
CandleSizeOnBuffer(rates_total,prev_calculated,open,close,ExtBuffer);
else
CandleSizeOnBuffer(rates_total,prev_calculated,high,low,ExtBuffer);
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Access to timeseries, ArraySetAsSeries
MQL4 Reference / Array Functions / ArrayInitialize
ArrayInitialize
The function initializes a numeric array by a preset value.
For initialization of an array of char type
int ArrayInitialize( char array[], // initialized array
char value // value that will be set
);
ArrayFill
The function fills an array with the specified value.
void ArrayFill( void& array[], // array
int start, // starting index
int count, // number of elements to fill
void value // value
);
Parameters
array[]
[out] Array of simple type (char, uchar, short, ushort, int, uint,
long, ulong, bool, color, datetime, float, double).
start
[in] Starting index. In such a case, specified AS_SERIES flag is
ignored.
count
[in] Number of elements to fill.
value
[in] Value to fill the array with.
Returned value
No return value.
Note
When ArrayFill() function is called, normal indexation direction
(from left to right) is always implied. It means that the change of
the order of access to the array elements using ArraySetAsSeries()
function is ignored.
A multidimensional array is shown as one-dimensional when
processed by ArrayFill() function. For example, array[2][4] is
processed as array[8]. Therefore, you may specify the initial
element's index to be equal to 5 when working with this array.
Thus, the call of ArrayFill(array, 5, 2, 3.14) for array[2][4] fills
array[1][1] and array[1][2] elements with 3.14.
Example:
void OnStart()
{
//--- declare dynamic array
int a[];
//--- set size
ArrayResize(a,10);
//--- fill first 5 elements with 123
ArrayFill(a,0,5,123);
//--- fill next 5 elements with 456
ArrayFill(a,5,5,456);
//--- show values
for(int i=0;i<ArraySize(a);i++) printf("a[%d] = %d",i,a[i]);
}
MQL4 Reference / Array Functions / ArrayIsDynamic
ArrayIsDynamic
The function checks whether an array is dynamic.
bool ArrayIsDynamic( const void& array[] // checked array
);
Parameters
array[]
[in] Checked array.
Return Value
It returns true if the selected array is dynamic, otherwise it returns false.
Example:
#property description "This indicator does not calculate values. It makes a single at
#property description "apply the call of ArrayFree() function to three arrays: dynami
#property description "an indicator buffer. Results are shown in Experts journal."
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 1
//--- global variables
double ExtDynamic[]; // dynamic array
double ExtStatic[100]; // static array
bool ExtFlag=true; // flag
double ExtBuff[]; // indicator buffer
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- allocate memory for the array
ArrayResize(ExtDynamic,100);
//--- indicator buffers mapping
SetIndexBuffer(0,ExtBuff);
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- perform a single analysis
if(ExtFlag)
{
//--- attempt to free memory for arrays
//--- 1. Dynamic array
Print("+============================+");
Print("1. Check dynamic array:");
Print("Size before memory is freed = ",ArraySize(ExtDynamic));
Print("Is this a dynamic array = ",ArrayIsDynamic(ExtDynamic) ? "Yes" : "No");
//--- attempt to free array memory
ArrayFree(ExtDynamic);
Print("Size after memory is freed = ",ArraySize(ExtDynamic));
//--- 2. Static array
Print("2. Check static array:");
Print("Size before memory is freed = ",ArraySize(ExtStatic));
Print("Is this a dynamic array = ",ArrayIsDynamic(ExtStatic) ? "Yes" : "No");
//--- attempt to free array memory
ArrayFree(ExtStatic);
Print("Size after memory is freed = ",ArraySize(ExtStatic));
//--- 3. Indicator buffer
Print("3. Check indicator buffer:");
Print("Size before memory is freed = ",ArraySize(ExtBuff));
Print("Is this a dynamic array = ",ArrayIsDynamic(ExtBuff) ? "Yes" : "No");
//--- attempt to free array memory
ArrayFree(ExtBuff);
Print("Size after memory is freed = ",ArraySize(ExtBuff));
//--- change the flag value
ExtFlag=false;
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Access to timeseries and indicators
MQL4 Reference / Array Functions / ArrayIsSeries
ArrayIsSeries
The function checks whether an array is a timeseries.
bool ArrayIsSeries( const void& array[] // checked array
);
Parameters
array[]
[in] Checked array.
Return Value
It returns true, if a checked array is an array timeseries, otherwise it
returns false. Arrays passed as a parameter to the OnCalculate() function
must be checked for the order of accessing the array elements by
ArrayGetAsSeries().
Example:
#property indicator_chart_window
#property indicator_buffers 1
//---- plot Label1
#property indicator_label1 "Label1"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- indicator buffers
double Label1Buffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,Label1Buffer,INDICATOR_DATA);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
if(ArrayIsSeries(open))
Print("open[] is timeseries");
else
Print("open[] is not timeseries!!!");
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Access to timeseries and indicators
MQL4 Reference / Array Functions / ArrayMaximum
ArrayMaximum
The function searches a maximal element in a one-dimension numeric array.
int ArrayMaximum( const void& array[], // array for search
int count=WHOLE_ARRAY, // number of checked elements
int start=0 // index to start checking with
);
Parameters
array[]
[in] A numeric array, in which search is made.
count=WHOLE_ARRAY
[in] Number of elements for search. By default, searches in the entire array
(count=WHOLE_ARRAY).
start=0
[in] Index to start checking with.
Return Value
The function returns an index of a found element taking into account the array
serial. In case of failure it returns -1.
Example:
void OnStart()
{
//---
double num_array[15]={4,1,6,3,19,4,2,6,3,9,4,5,6,3,9};
int maxValueIdx=ArrayMaximum(num_array,WHOLE_ARRAY,0);
Print("Max value = ",num_array[maxValueIdx]," at index=",maxValueIdx);
}
See also
ArrayMinimum()
MQL4 Reference / Array Functions / ArrayMinimum
ArrayMinimum
The function searches a minimal element in a one-dimension numeric array.
int ArrayMinimum( const void& array[], // array for search
int count=WHOLE_ARRAY, // number of checked elements
int start=0 // index to start checking with
);
Parameters
array[]
[in] A numeric array, in which search is made.
count=WHOLE_ARRAY
[in] Number of elements for search. By default, searches in the entire array
(count=WHOLE_ARRAY).
start=0
[in] Index to start checking with.
Return Value
The function returns an index of a found element taking into account the array
serial. In case of failure it returns -1.
Example:
void OnStart()
{
//---
double num_array[15]={4,1,6,3,19,4,2,6,3,9,4,5,6,3,9};
int minValueIdx=ArrayMinimum(num_array,WHOLE_ARRAY,0);
Print("Min value = ",num_array[minValueIdx]," at index=",minValueIdx);
}
See also
ArrayMaximum()
MQL4 Reference / Array Functions / ArrayRange
ArrayRange
The function returns the number of elements in a selected array
dimension.
int ArrayRange( const void& array[], // array for check
int rank_index // index of dimension
);
Parameters
array[]
[in] Checked array.
rank_index
[in] Index of dimension.
Return Value
Number of elements in a selected array dimension.
Note
Since indexes start at zero, the number of the array dimensions is
one greater than the index of the last dimension.
Example:
void OnStart()
{
//--- create four-dimensional array
double array[][5][2][4];
//--- set the size of the zero dimension
ArrayResize(array,10,10);
//--- print dimensions
int temp;
for(int i=0;i<4;i++)
{
//--- receive the size of i dimension
temp=ArrayRange(array,i);
//--- print
PrintFormat("dim = %d, range = %d",i,temp);
}
//--- Result
// dim = 0, range = 10
// dim = 1, range = 5
// dim = 2, range = 2
// dim = 3, range = 4
}
MQL4 Reference / Array Functions / ArrayResize
ArrayResize
The function sets a new size for the first dimension
int ArrayResize( void& array[], // array passed by reference
int new_size, // new array size
int reserve_size=0 // reserve size value (excess)
);
Parameters
array[]
[out] Array for changing sizes.
new_size
[in] New size for the first dimension.
reserve_size=0
[in] Optional parameter. Distributed size to get reserve.
Return Value
If executed successfully, it returns count of all elements contained in the array after
resizing, otherwise, returns -1, and array is not resized.
Note
The function can be applied only to dynamic arrays. It should be noted that you cannot
change the size of dynamic arrays assigned as indicator buffers by the SetIndexBuffer()
function. For indicator buffers, all operations of resizing are performed by the runtime
subsystem of the terminal.
Total amount of elements in the array cannot exceed 2147483647.
With the frequent memory allocation, it is recommended to use a third parameter that
sets a reserve to reduce the number of physical memory allocations. All the subsequent
calls of ArrayResize do not lead to physical reallocation of memory, but only change the
size of the first array dimension within the reserved memory. It should be remembered
that the third parameter will be used only during physical memory allocation. For
example:
ArrayResize(arr,1000,1000);
for(int i=1;i<3000;i++)
ArrayResize(arr,i,1000);
In this case the memory will be reallocated twice, first before entering the 2000-
element loop (the array size will be set to 1000), and the second time with i equal to
2000. If we skip the third parameter, there will be 2000 physical reallocations of
memory, which will slow down the program.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Counters
ulong start=GetTickCount();
ulong now;
int count=0;
//--- An array for demonstration of a quick version
double arr[];
ArrayResize(arr,100000,100000);
//--- Check how fast the variant with memory reservation works
Print("--- Test Fast: ArrayResize(arr,100000,100000)");
for(int i=1;i<=300000;i++)
{
//--- Set a new array size specifying the reserve of 100,000 elements!
ArrayResize(arr,i,100000);
//--- When reaching a round number, show the array size and the time spent
if(ArraySize(arr)%100000==0)
{
now=GetTickCount();
count++;
PrintFormat("%d. ArraySize(arr)=%d Time=%d ms",count,ArraySize(arr),(now-sta
start=now;
}
}
//--- Now show, how slow the version without memory reservation is
double slow[];
ArrayResize(slow,100000,100000);
//---
count=0;
start=GetTickCount();
Print("---- Test Slow: ArrayResize(slow,100000)");
//---
for(int i=1;i<=300000;i++)
{
//--- Set a new array size, but without the additional reserve
ArrayResize(slow,i);
//--- When reaching a round number, show the array size and the time spent
if(ArraySize(slow)%100000==0)
{
now=GetTickCount();
count++;
PrintFormat("%d. ArraySize(slow)=%d Time=%d ms",count,ArraySize(slow),(now-s
start=now;
}
}
}
//--- A sample result of the script
/*
Test_ArrayResize (EURUSD,H1) --- Test Fast: ArrayResize(arr,100000,100000)
Test_ArrayResize (EURUSD,H1) 1. ArraySize(arr)=100000 Time=0 ms
Test_ArrayResize (EURUSD,H1) 2. ArraySize(arr)=200000 Time=0 ms
Test_ArrayResize (EURUSD,H1) 3. ArraySize(arr)=300000 Time=0 ms
Test_ArrayResize (EURUSD,H1) ---- Test Slow: ArrayResize(slow,100000)
Test_ArrayResize (EURUSD,H1) 1. ArraySize(slow)=100000 Time=0 ms
Test_ArrayResize (EURUSD,H1) 2. ArraySize(slow)=200000 Time=0 ms
Test_ArrayResize (EURUSD,H1) 3. ArraySize(slow)=300000 Time=228511 ms
*/
See also
ArrayInitialize
MQL4 Reference / Array Functions / ArraySetAsSeries
ArraySetAsSeries
The function sets the AS_SERIES flag to a selected object of a dynamic array,
and elements will be indexed like in timeseries.
bool ArraySetAsSeries( const void& array[], // array by reference
bool flag // true denotes reverse order of indexing
);
Parameters
array[]
[in][out] Numeric array to set.
flag
[in] Array indexing direction.
Return Value
The function returns true on success, otherwise - false.
Note
The AS_SERIES flag can't be set for multi-dimensional arrays or static arrays
(arrays, whose size in square brackets is preset already on the compilation
stage). Indexing in timeseries differs from a common array in that the
elements of timeseries are indexed from the end towards the beginning
(from the newest to oldest data).
Example: Indicator that shows bar number
#property indicator_chart_window
#property indicator_buffers 1
//--- indicator buffers
double NumerationBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,NumerationBuffer,INDICATOR_DATA);
//--- set buffer style
SetIndexStyle(0,DRAW_LINE,STYLE_SOLID,1,CLR_NONE);
//--- set indexing for the buffer like in timeseries
ArraySetAsSeries(NumerationBuffer,true);
//--- set accuracy of showing in DataWindow
IndicatorSetInteger(INDICATOR_DIGITS,0);
//--- how the name of the indicator arry is displayed in DataWindow
IndicatorShortName("Bar #");
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- we'll store the time of the current zero bar opening
static datetime currentBarTimeOpen=0;
//--- revert access to array time[] - do it like in timeseries
ArraySetAsSeries(time,true);
//--- If time of zero bar differs from the stored one
if(currentBarTimeOpen!=time[0])
{
//--- enumerate all bars from the current to the chart depth
for(int i=rates_total-1;i>=0;i--) NumerationBuffer[i]=i;
currentBarTimeOpen=time[0];
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Access to timeseries, ArrayGetAsSeries
MQL4 Reference / Array Functions / ArraySize
ArraySize
The function returns the number of elements of a selected array.
int ArraySize( const void& array[] // checked array
);
Parameters
array[]
[in] Array of any type.
Return Value
Value of int type.
Note
For a one-dimensional array, the value to be returned by the ArraySize is equal to that
of ArrayRange(array,0).
Example:
void OnStart()
{
//--- create arrays
double one_dim[];
double four_dim[][10][5][2];
//--- sizes
int one_dim_size=25;
int reserve=20;
int four_dim_size=5;
//--- auxiliary variable
int size;
//--- allocate memory without backup
ArrayResize(one_dim,one_dim_size);
ArrayResize(four_dim,four_dim_size);
//--- 1. one-dimensional array
Print("+==========================================================+");
Print("Array sizes:");
Print("1. One-dimensional array");
size=ArraySize(one_dim);
PrintFormat("Zero dimension size = %d, Array size = %d",one_dim_size,size);
//--- 2. multidimensional array
Print("2. Multidimensional array");
size=ArraySize(four_dim);
PrintFormat("Zero dimension size = %d, Array size = %d",four_dim_size,size);
//--- dimension sizes
int d_1=ArrayRange(four_dim,1);
int d_2=ArrayRange(four_dim,2);
int d_3=ArrayRange(four_dim,3);
Print("Check:");
Print("Zero dimension = Array size / (First dimension * Second dimension * Third d
PrintFormat("%d = %d / (%d * %d * %d)",size/(d_1*d_2*d_3),size,d_1,d_2,d_3);
//--- 3. one-dimensional array with memory backup
Print("3. One-dimensional array with memory backup");
//--- double the value
one_dim_size*=2;
//--- allocate memory with backup
ArrayResize(one_dim,one_dim_size,reserve);
//--- print out the size
size=ArraySize(one_dim);
PrintFormat("Size with backup = %d, Actual array size = %d",one_dim_size+reserve,s
}
MQL4 Reference / Array Functions / ArraySort
ArraySort
Sorts numeric arrays by first dimension. The AS_SERIES flag is taken into account
in sorting.
bool ArraySort( void& array[], // array for sorting
int count=WHOLE_ARRAY, // count
int start=0, // starting index
int direction=MODE_ASCEND // sort direction
);
Parameters
array[]
[in][out] Numeric array for sorting.
count=WHOLE_ARRAY
[in] Count of elements to sort. By default, it sorts the whole array.
start=0
[in] Starting index to sort. By default, the sort starts at the first element.
direction=MODE_ASCEND
[in] Sort direction. It can be any of the following values:
MODE_ASCEND sort in ascend direction,
MODE_DESCEND sort in descend direction.
Return Value
The function returns true on success, otherwise - false.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- example of sorting of one dimensional array
double num_array[5]={4,1,6,3,9};
//--- now array contains values 4,1,6,3,9
ArraySort(num_array);
//--- now array is sorted 1,3,4,6,9
ArraySort(num_array,WHOLE_ARRAY,0,MODE_DESCEND);
//--- now array is sorted 9,6,4,3,1
MQL4 Reference / Array Functions / ArrayCopyRates
ArrayCopyRates
Copies rates data to the array and returns the amount of bars copied. There are 2
variants of the function:
int ArrayCopyRates( MqlRates& rates_array[], // MqlRates array, passed by refer
string symbol=NULL, // symbol
int timeframe=0 // timeframe
);
Copies rates data to the RateInfo[][6] two-dimensional array of double type and returns
the amount of bars copied.
int ArrayCopyRates(
void& dest_array[][], // destination array, passed by reference
string symbol=NULL, // symbol
int timeframe=0 // timeframe
);
Parameters
rates_array[]
[out] Destination array of MqlRates type.
dest_array[]
[out] Two-dimensional destination array of double type.
symbol=NULL
[in] Symbol name.
timeframe=0
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
Returned value
The function returns copied bars amount, or -1 if failed.
If data (symbol name and/or timeframe differ from the current ones) are requested
from another chart, the situation is possible that the corresponding chart was not
opened in the client terminal and the necessary data must be requested from the
server. In this case, error ERR_HISTORY_WILL_UPDATED (4066 - the requested history
data are under updating) will be placed in the last_error variable, and one will has to
re-request (see example of ArrayCopySeries()).
Note
This rates array is normally used to pass data to a DLL function.
In the first variant of the function it performs the virtual data copying to the array of
MqlRates type. It means that if timeseries data has been updated, rates_array[] array
always will refer to the actual data.
In the second variant it performs the real data copying to dest_array[][] array. The
destination array will be resized to the size of the timeseries (even if the destination
array has been declared as static).
First dimension of RateInfo array contains bars amount, second dimension has 6
elements:
0 - time,
1 - open,
2 - low,
3 - high,
4 - close,
5 - volume.
Example:
#property copyright "Copyright © 2013, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
#property description "Expert Advisor displaying two cases of"
#property description "ArrayCopyRates() function call"
//--- destination array for physical copying of historical data
double double_array[][6];
//--- destination array for logical copying of historical data
MqlRates mqlrates_array[];
//--- first call flag
bool first_call;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- run this EA at chart with M1 timeframe
if(Period()!=PeriodSeconds(PERIOD_M1)/60)
{
Alert("The Expert Advisor must be attached to M1 chart!");
return(INIT_FAILED);
}
//--- first call
first_call=true;
//--- all ok
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- delete all comments
Comment("");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
if(first_call)
{
//--- copying physically double_array
ArrayCopyRates(double_array,NULL,0);
//--- virtual copying -> mqlrates_array will contain the reference on the data
ArrayCopyRates(mqlrates_array,NULL,0);
//--- cancel first call flag
first_call=false;
}
//--- at each tick print the values of the 0-th array element to see the differenc
Comment("The values of double_array[] are not changed (because of real data copyin
"0 - time: ",(datetime)double_array[0][0],"\n",
"1 - open: ",double_array[0][1],"\n"
"2 - low: ",double_array[0][2],"\n"
"3 - high: ",double_array[0][3],"\n"
"4 - close: ",double_array[0][4],"\n"
"5 - volume: ",DoubleToString(double_array[0][5],0),"\n\n",
"The values of mqlrates_array[] are changed (because of virtual data copyi
"0 - time: ",mqlrates_array[0].time,"\n",
"1 - open: ",mqlrates_array[0].open,"\n"
"2 - low: ",mqlrates_array[0].low,"\n"
"3 - high: ",mqlrates_array[0].high,"\n"
"4 - close: ",mqlrates_array[0].close,"\n"
"5 - volume: ",mqlrates_array[0].tick_volume);
}
MQL4 Reference / Array Functions / ArrayCopySeries
ArrayCopySeries
Copies a series array to another one and returns the count of the copied elements.
int ArrayCopySeries( void& array[], // destination array
int series_index, // series array identifier
string symbol=NULL, // symbol
int timeframe=0 // timeframe
);
Parameters
array[]
[out] Destination array of double type.
series_index
[in] Series array identifier. It can be any of the Series array identifier enumeration
values.
symbol
[in] Symbol name.
timeframe
[in] Timeframe. It can be any of Timeframe enumeration values. 0 means the current
chart timeframe.
Returned value
The function returns copied elements amount, or -1 if failed.
If data are copied from another chart with different symbol and/or timeframe, it is
possible that the necessary data will lack. In this case, error
ERR_HISTORY_WILL_UPDATED (4066 - requested history data under updating) will be
placed into the last_error variable, and there will be necessary to retry copying after a
certain period of time.
Note
There is no real memory allocation for data array and nothing is copied. When such an
array is accessed, the access is redirected. Excluded are arrays that are assigned as
indexed ones in custom indicators. In this case, data are really copied.
If series_index is MODE_TIME, the array to be passed to the function must be of the
datetime type.
Example:
datetime daytimes[];
int shift=10,dayshift,error;
//---- the Time[] array was sroted in the descending order
ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1);
error=GetLastError();
if(error==4066)
{
//---- make two more attempts to read
for(int i=0;i<2; i++)
{
Sleep(5000);
ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1);
//---- check the current daily bar time
datetime last_day=daytimes[0];
if(Year()==TimeYear(last_day) && Month()==TimeMonth(last_day) && Day()==TimeDay
}
}
if(Time[shift]>=daytimes[0]) dayshift=0;
else
{
dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND);
if(Period()<PERIOD_D1) dayshift++;
}
Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar opened at ", TimeT
MQL4 Reference / Array Functions / ArrayDimension
ArrayDimension
Returns the multidimensional array rank.
int ArrayDimension( void& array[] // array
);
Parameters
array[]
[in] Array for which the rank will be returned.
Returned value
Rank (dimension) of multidimensional array or -1 if error.
Example:
void OnStart()
{
int num_array[10][5];
int dim_size=ArrayDimension(num_array);// dim_size=2
Print("Dimension of num_array=",dim_size);
}
MQL4 Reference / Conversion Functions
Conversion Functions
This is a group of functions that provide conversion of
data from one format into another.
The NormalizeDouble() function must be specially noted
as it provides the necessary accuracy of the price
presentation. In trading operations, no unnormalized
prices may be used if their accuracy even a digit exceeds
that required by the trade server.
Function Action
CharToString Converting a symbol code into a one-
character string
DoubleToString Converting a numeric value to a text line
with a specified accuracy
EnumToString Converting an enumeration value of any
type to string
NormalizeDouble Rounding of a floating point number to a
specified accuracy
StringToDouble Converting a string containing a symbol
representation of number into number of
double type
StringToInteger Converting a string containing a symbol
representation of number into number of
int type
StringToTime Converting a string containing time or
date in "yyyy.mm.dd [hh:mi]" format into
datetime type
Function Action
TimeToString Converting a value containing time in
seconds elapsed since 01.01.1970 into a
string of "yyyy.mm.dd hh:mi" format
IntegerToString Converting int into a string of preset
length
ShortToString Converting symbol code (unicode) into
one-symbol string
ShortArrayToString Copying array part into a string
StringToShortArray Symbol-wise copying a string to a selected
part of array of ushort type
CharArrayToString Converting symbol code (ansi) into one-
symbol array
StringToCharArray Symbol-wise copying a string converted
from Unicode to ANSI, to a selected place
of array of uchar type
ColorToARGB Converting color type to uint type to
receive ARGB representation of the color.
ColorToString Converting color value into string as
"R,G,B"
StringToColor Converting "R,G,B" string or string with
color name into color type value
StringFormat Converting number into string according
to preset format
CharToStr Conversion of the symbol code into a one-
character string
DoubleToStr Returns text string with the specified
numerical value converted into a specified
precision format
Function Action
StrToDouble Converts string representation of number
to double type
StrToInteger Converts string containing the value
character representation into a value of
the integer type
StrToTime Converts string in the format "yyyy.mm.dd
hh:mi" to datetime type
TimeToStr Converts value of datetime type into a
string of "yyyy.mm.dd hh:mi" format
What's new in MQL5
Added the CharArrayToStruct and StructToCharArray
functions for converting the uchar array to the binary
sequence and vice versa. This simplifies the exchange of
byte data when working with a DLL.
See also
Use of a Codepage
MQL4 Reference / Conversion Functions / CharToString
CharToString
Converting a symbol code into a one-character string.
string CharToString( uchar char_code // numeric code of symbol
);
Parameters
char_code
[in] Code of ANSI symbol.
Return Value
String with a ANSI symbol.
MQL4 Reference / Conversion Functions / CharArrayToString
CharArrayToString
It copies and converts part of array of uchar type into a returned
string.
string CharArrayToString( uchar array[], // array
int start=0, // starting position in the array
int count=-1, // number of symbols
uint codepage=CP_ACP // code page
);
Parameters
array[]
[in] Array of uchar type.
start=0
[in] Position from which copying starts. by default 0 is used.
count=-1
[in] Number of array elements for copying. Defines the length of a
resulting string. Default value is -1, which means copying up to the
array end, or till terminal 0.
codepage=CP_ACP
[in] The value of the code page. There is a number of built-in
constants for the most used code pages.
Return Value
String.
See also
Use of a Codepage
MQL4 Reference / Conversion Functions / ColorToARGB
ColorToARGB
The function converts color type into uint type to get ARGB representation of the color.
ARGB color format is used to generate a graphical resource, text display, as well as for
CCanvas standard library class.
uint ColorToARGB( color clr, // converted color in color format
uchar alpha=255 // alpha channel managing color transparency
);
Parameters
clr
[in] Color value in color type variable.
alpha
[in] The value of the alpha channel used to receive the color in ARGB format. The
value may be set from 0 (a color of a foreground pixel does not change the display of
an underlying one) up to 255 (a color of an underlying pixel is completely replaced by
the foreground pixel's one). Color transparency in percentage terms is calculated as
(1-alpha/255)*100%. In other words, the lesser value of the alpha channel leads to
more transparent color.
Returned value
Presenting the color in ARGB format where Alfa, Red, Green, Blue (alpha channel, red,
green, blue) values are set in series in four uint type bytes.
Note
RGB is a basic and commonly used format for pixel color description on a screen in
computer graphics. Names of basic colors are used to set red, green and blue color
components. Each component is described by one byte specifying the color saturation
in the range of 0 to 255 (0x00 to 0XFF in hexadecimal format). Since the white color
contains all colors, it is described as 0xFFFFFF, that is, each one of three components is
presented by the maximum value of 0xFF.
However, some tasks require to specify the color transparency to describe the look of
an image in case it is covered by the color with some degree of transparency. The
concept of alpha channel is introduced for such cases. It is implemented as an
additional component of RGB format. ARGB format structure is shown below.
ARGB values are typically expressed using hexadecimal format with each pair of digits
representing the values of Alpha, Red, Green and Blue channels, respectively. For
example, 80FFFF00 color represents 50.2% opaque yellow. Initially, 0x80 sets 50.2%
alpha value, as it is 50.2% of 0xFF value. Then, the first FF pair defines the highest
value of the red component; the next FF pair is like the previous but for the green
component; the final 00 pair represents the lowest value the blue component can have
(absence of blue). Combination of green and red colors yields yellow one. If the alpha
channel is not used, the entry can be reduced down to 6 RRGGBB digits, this is why the
alpha channel values are stored in the top bits of uint integer type.
Depending on the context, hexadecimal digits can be written with '0x' or '#' prefix, for
example, 80FFFF00, 0x80FFFF00 or #80FFFF00.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set transparency
uchar alfa=0x55; // 0x55 means 55/255=21.6 % of transparency
//--- derive conversion to ARGB for clrBlue color
PrintFormat("0x%.8X - clrBlue",clrBlue);
PrintFormat("0x%.8X - clrBlue ARGB with alfa=0x55 (transparency 21.6%%)",ColorToAR
//--- derive conversion to ARGB for clrGreen color
PrintFormat("0x%.8X - clrGreen",clrGreen);
PrintFormat("0x%.8X - clrGreen ARGB with alfa=0x55 (transparency 21.6%%)",ColorToA
//--- derive conversion to ARGB for clrRed color
PrintFormat("0x%.8X - clrRed",clrRed);
PrintFormat("0x%.8X - clrRed ARGB with alfa=0x55 (transparency 21.6%%)",ColorToARG
}
See also
Resources, ResourceCreate(), TextOut(), color type, char, short, int and long types
MQL4 Reference / Conversion Functions / ColorToString
ColorToString
It converts color value into string of "R,G,B" form.
string ColorToString( color color_value, // color value
bool color_name // show color name or not
);
Parameters
color_value
[in] Color value in color type variable.
color_name
[in] Return color name if it is identical to one of predefined color
constants.
Return Value
String presentation of color as "R,G,B", where R, G and B are
decimal constants from 0 to 255 converted into a string. If the
color_name=true parameter is set, it will try to convert color
value into color name.
Example:
string clr=ColorToString(C'0,255,0'); // green color
Print(clr);
MQL4 Reference / Conversion Functions / DoubleToString
DoubleToString
Converting numeric value into text string.
string DoubleToString( double value, // number
int digits=8 // number of digits after decimal point
);
Parameters
value
[in] Value with a floating point.
digits
[in] Accuracy format. If the digits value is in the range between 0 and 16, a
string presentation of a number with the specified number of digits after the
point will be obtained. If the digits value is in the range between -1 and -16, a
string representation of a number in the scientific format with the specified
number of digits after the decimal point will be obtained. In all other cases the
string value will contain 8 digits after the decimal point.
Return Value
String containing a symbol representation of a number with the specified accuracy.
Example:
Print("DoubleToString(120.0 + M_PI) : ",DoubleToString(120.0+M_PI));
Print("DoubleToString(120.0 + M_PI,16) : ",DoubleToString(120.0+M_PI,16));
Print("DoubleToString(120.0 + M_PI,-16) : ",DoubleToString(120.0+M_PI,-16));
Print("DoubleToString(120.0 + M_PI,-1) : ",DoubleToString(120.0+M_PI,-1));
Print("DoubleToString(120.0 + M_PI,-20) : ",DoubleToString(120.0+M_PI,-20));
See also
NormalizeDouble, StringToDouble
MQL4 Reference / Conversion Functions / EnumToString
EnumToString
Converting an enumeration value of any type to a text form.
string EnumToString( any_enum value // any type enumeration value
);
Parameters
value
[in] Any type enumeration value.
Return Value
A string with a text representation of the enumeration. To get the error
message call the GetLastError() function.
Note
The function can set the following error values in the _LastError variable:
ERR_INTERNAL_ERROR error of the execution environment
ERR_NOT_ENOUGH_MEMORY not enough memory to complete the operation
ERR_INVALID_PARAMETER can't allow the name of the enumeration value
Example:
enum interval // enumeration of named constants
{
month=1, // one-month interval
two_months, // two months
quarter, // three months - a quarter
halfyear=6, // half a year
year=12, // a year - 12 months
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- set the time interval equal to one month
interval period=month;
Print(EnumToString(period)+"="+IntegerToString(period));
//--- set the time interval equal to one year (12 months)
period=year;
Print(EnumToString(period)+"="+IntegerToString(period));
// Result:
// month=1
// quarter=3
// year=12
// ORDER_TYPE_BUY=0
// ENUM_ORDER_TYPE::-1=-1
}
See also
Enumerations, Input variables
MQL4 Reference / Conversion Functions / IntegerToString
IntegerToString
This function converts value of integer type into a string of a specified
length and returns the obtained string.
string IntegerToString( long number, // number
int str_len=0, // length of result string
ushort fill_symbol=' ' // filler
);
Parameters
number
[in] Number for conversion.
str_len=0
[in] String length. If the resulting string length is larger than the
specified one, the string is not cut off. If it is smaller, filler symbols
will be added to the left.
fill_symbol=' '
[in] Filler symbol. By default it is a space.
Return Value
String.
MQL4 Reference / Conversion Functions / ShortToString
ShortToString
It converts the symbol code (unicode) into one-symbol string
and returns resulting string.
string ShortToString( ushort symbol_code // symbol
);
Parameters
symbol_code
[in] Symbol code. Instead of a symbol code you can use
literal string containing a symbol or a literal string with 2-
byte hexadecimal code corresponding to the symbol from the
Unicode table.
Return Value
String.
MQL4 Reference / Conversion Functions / ShortArrayToString
ShortArrayToString
It copies part of array into a returned string.
string ShortArrayToString( ushort array[], // array
int start=0, // starting position in the array
int count=-1 // number of symbols
);
Parameters
array[]
[in] Array of ushort type (analog of wchar_t type).
start=0
[in] Position, from which copying starts, Default - 0.
count=-1
[in] Number of array elements to copy. Defines the length of a
resulting string. Default value is -1, which means copying up to
the array end, or till terminal 0.
Return Value
String.
MQL4 Reference / Conversion Functions / TimeToString
TimeToString
Converting a value containing time in seconds elapsed since 01.01.1970 into a
string of "yyyy.mm.dd hh:mi" format.
string TimeToString( datetime value, // number
int mode=TIME_DATE|TIME_MINUTES // output format
);
Parameters
value
[in] Time in seconds from 00:00 1970/01/01.
mode=TIME_DATE|TIME_MINUTES
[in] Additional data input mode. Can be one or combined flag:
TIME_DATE gets result as "yyyy.mm.dd",
TIME_MINUTES gets result as "hh:mi",
TIME_SECONDS gets results as "hh:mi:ss".
Return Value
String.
MQL4 Reference / Conversion Functions / NormalizeDouble
NormalizeDouble
Rounding floating point number to a specified accuracy.
double NormalizeDouble( double value, // normalized number
int digits // number of digits after decimal point
);
Parameters
value
[in] Value with a floating point.
digits
[in] Accuracy format, number of digits after point (0-8).
Return Value
Value of double type with preset accuracy.
Note
Calculated values of StopLoss, TakeProfit, and values of open prices for pending orders
must be normalized with the accuracy, the value of which can be obtained by Digits().
Please note that when output to Journal using the Print() function, a normalized
number may contain a greater number of decimal places than you expect. For example,
for:
double a=76.671; // A normalized number with three decimal places
Print("Print(76.671)=",a); // Output as is
Print("DoubleToString(a,8)=",DoubleToString(a,8)); // Output with a preset accurac
Example:
double pi=M_PI;
Print("pi = ",DoubleToString(pi,16));
double pi_3=NormalizeDouble(M_PI,3);
Print("NormalizeDouble(pi,3) = ",DoubleToString(pi_3,16))
;
double pi_8=NormalizeDouble(M_PI,8);
Print("NormalizeDouble(pi,8) = ",DoubleToString(pi_8,16));
double pi_0=NormalizeDouble(M_PI,0);
Print("NormalizeDouble(pi,0) = ",DoubleToString(pi_0,16));
/*
Result:
pi= 3.1415926535897931
NormalizeDouble(pi,3)= 3.1419999999999999
NormalizeDouble(pi,8)= 3.1415926499999998
NormalizeDouble(pi,0)= 3.0000000000000000
*/
See also
DoubleToString, Real types (double, float), Reduction of types,
MQL4 Reference / Conversion Functions / StringToCharArray
StringToCharArray
Symbol-wise copies a string converted from Unicode to ANSI, to a selected
place of array of uchar type. It returns the number of copied elements.
int StringToCharArray( string text_string, // source string
uchar& array[], // array
int start=0, // starting position in the array
int count=-1, // number of symbols
uint codepage=CP_ACP // code page
);
Parameters
text_string
[in] String to copy.
array[]
[out] Array of uchar type.
start=0
[in] Position from which copying starts. Default - 0.
count=-1
[in] Number of array elements to copy. Defines length of a resulting
string. Default value is -1, which means copying up to the array end, or
till terminating '\0'. Terminating zero will also be copied to the recipient
array, in this case the size of a dynamic array can be increased if
necessary to the size of the string. If the size of the dynamic array
exceeds the length of the string, the size of the array will not be reduced.
codepage=CP_ACP
[in] The value of the code page. For the most-used code pages provide
appropriate constants.
Return Value
Number of copied elements.
Note
StringToCharArray() function includes terminating zero. To exclude it
specify the string length explicitely:
//--- example of copying of string str to array[]
StringToCharArray(str,array,0,StringLen(str));
See also
Use of a Codepage
MQL4 Reference / Conversion Functions / StringToColor
StringToColor
Converting "R,G,B" string or string with color name into color type value.
color StringToColor( string color_string // string representation of color
);
Parameters
color_string
[in] String representation of a color of "R,G,B" type or name of one of predefined
Web-colors.
Return Value
Color value.
Example:
color str_color=StringToColor("0,127,0");
Print(str_color);
Print((string)str_color);
//--- change color a little
str_color=StringToColor("0,128,0");
Print(str_color);
Print((string)str_color);
MQL4 Reference / Conversion Functions / StringToDouble
StringToDouble
The function converts string containing a symbol
representation of number into number of double type.
double StringToDouble( string value // string
);
Parameters
value
[in] String containing a symbol representation of a
number.
Return Value
Value of double type.
MQL4 Reference / Conversion Functions / StringToInteger
StringToInteger
The function converts string containing a symbol
representation of number into number of int (integer)
type.
long StringToInteger( string value // string
);
Parameters
value
[in] String containing a number.
Return Value
Value of long type.
MQL4 Reference / Conversion Functions / StringToShortArray
StringToShortArray
The function symbol-wise copies a string into a specified place of an
array of ushort type. It returns the number of copied elements.
int StringToShortArray( string text_string, // source string
ushort& array[], // array
int start=0, // starting position in the array
int count=-1 // number of symbols
);
Parameters
text_string
[in] String to copy
array[]
[out] Array of ushort type (analog of wchar_t type).
start=0
[in] Position, from which copying starts. Default - 0.
count=-1
[in] Number of array elements to copy. Defines length of a resulting
string. Default value is -1, which means copying up to the array end, or
till terminal 0.Terminal 0 will also be copied to the recipient array, in
this case the size of a dynamic array can be increased if necessary to
the size of the string. If the size of the dynamic array exceeds the
length of the string, the size of the array will not be reduced.
Return Value
Number of copied elements.
MQL4 Reference / Conversion Functions / StringToTime
StringToTime
The function converts a string containing time or date in
"yyyy.mm.dd [hh:mi]" format into datetime type.
datetime StringToTime( string value // date string
);
Parameters
value
[in] String in " yyyy.mm.dd hh:mi " format.
Return Value
Value of datetime type containing total number of seconds
that elapsed since 01.01.1970.
Note
If a string contains time with no date, the execution result is a
current date of a local PC with a specified time.
MQL4 Reference / Conversion Functions / StringFormat
StringFormat
The function formats obtained parameters and returns a string.
string StringFormat( string format, // string with format description
... ... // parameters
);
Parameters
format
[in] String containing method of formatting. Formatting rules are the same as for the
PrintFormat function.
...
[in] Parameters, separated by a comma.
Return Value
String.
Example:
void OnStart()
{
//--- string variables
string output_string;
string temp_string;
string format_string;
//--- prepare the specification header
temp_string=StringFormat("Contract specification for %s:\r\n",_Symbol);
StringAdd(output_string,temp_string);
//--- int value output
int digits=(int)SymbolInfoInteger(_Symbol,SYMBOL_DIGITS);
temp_string=StringFormat(" SYMBOL_DIGITS = %d (number of digits after the decima
digits);
StringAdd(output_string,temp_string);
//--- double value output with variable number of digits after the decimal point
double point_value=SymbolInfoDouble(_Symbol,SYMBOL_POINT);
format_string=StringFormat(" SYMBOL_POINT = %%.%df (point value)\r\n",
digits);
temp_string=StringFormat(format_string,point_value);
StringAdd(output_string,temp_string);
//--- int value output
int spread=(int)SymbolInfoInteger(_Symbol,SYMBOL_SPREAD);
temp_string=StringFormat(" SYMBOL_SPREAD = %d (current spread in points)\r\n",
spread);
StringAdd(output_string,temp_string);
//--- int value output
int min_stop=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_STOPS_LEVEL);
temp_string=StringFormat(" SYMBOL_TRADE_STOPS_LEVEL = %d (minimal indention in p
min_stop);
StringAdd(output_string,temp_string);
//--- double value output without the fractional part
double contract_size=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_CONTRACT_SIZE);
temp_string=StringFormat(" SYMBOL_TRADE_CONTRACT_SIZE = %.f (contract size)\r\n"
contract_size);
StringAdd(output_string,temp_string);
//--- double value output with default accuracy
double tick_size=SymbolInfoDouble(_Symbol,SYMBOL_TRADE_TICK_SIZE);
temp_string=StringFormat(" SYMBOL_TRADE_TICK_SIZE = %f (minimal price change)\r\
tick_size);
StringAdd(output_string,temp_string);
//--- determining the swap calculation mode
int swap_mode=(int)SymbolInfoInteger(_Symbol,SYMBOL_SWAP_MODE);
string str_swap_mode;
switch(swap_mode)
{
case 0: str_swap_mode="0 (in points)"; break;
case 1: str_swap_mode="1 (in symbol base currency)"; break;
case 2: str_swap_mode="2 (by interest)"; break;
case 3: str_swap_mode="3 (in margin currency)"; break;
}
//--- string value output
temp_string=StringFormat(" SYMBOL_SWAP_MODE = %s\r\n",
str_swap_mode);
StringAdd(output_string,temp_string);
//--- double value output with default accuracy
double swap_long=SymbolInfoDouble(_Symbol,SYMBOL_SWAP_LONG);
temp_string=StringFormat(" SYMBOL_SWAP_LONG = %f (buy order swap value)\r\n",
swap_long);
StringAdd(output_string,temp_string);
//--- double value output with default accuracy
double swap_short=SymbolInfoDouble(_Symbol,SYMBOL_SWAP_SHORT);
temp_string=StringFormat(" SYMBOL_SWAP_SHORT = %f (sell order swap value)\r\n",
swap_short);
StringAdd(output_string,temp_string);
//--- determining the trading mode
int trade_mode=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_MODE);
string str_trade_mode;
switch(trade_mode)
{
case SYMBOL_TRADE_MODE_DISABLED: str_trade_mode="SYMBOL_TRADE_MODE_DISABLED (tr
case SYMBOL_TRADE_MODE_LONGONLY: str_trade_mode="SYMBOL_TRADE_MODE_LONGONLY (on
case SYMBOL_TRADE_MODE_SHORTONLY: str_trade_mode="SYMBOL_TRADE_MODE_SHORTONLY (
case SYMBOL_TRADE_MODE_CLOSEONLY: str_trade_mode="SYMBOL_TRADE_MODE_CLOSEONLY (
case SYMBOL_TRADE_MODE_FULL: str_trade_mode="SYMBOL_TRADE_MODE_FULL (no trade r
}
//--- string value output
temp_string=StringFormat(" SYMBOL_TRADE_MODE = %s\r\n",
str_trade_mode);
StringAdd(output_string,temp_string);
//--- double value output in a compact format
double volume_min=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MIN);
temp_string=StringFormat(" SYMBOL_VOLUME_MIN = %g (minimal volume for a deal)\r\
StringAdd(output_string,temp_string);
//--- double value output in a compact format
double volume_step=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_STEP);
temp_string=StringFormat(" SYMBOL_VOLUME_STEP = %g (minimal volume change step)\
StringAdd(output_string,temp_string);
//--- double value output in a compact format
double volume_max=SymbolInfoDouble(_Symbol,SYMBOL_VOLUME_MAX);
temp_string=StringFormat(" SYMBOL_VOLUME_MAX = %g (maximal volume for a deal)\r\
StringAdd(output_string,temp_string);
//--- determining the contract price calculation mode
int calc_mode=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_CALC_MODE);
string str_calc_mode;
switch(calc_mode)
{
case 0:str_calc_mode="0 (Forex)";break;
case 1:str_calc_mode="1 (CFD)";break;
case 2:str_calc_mode="2 (futures)";break;
case 3:str_calc_mode="3 (CFD for indices)";break;
}
//--- string value output
temp_string=StringFormat(" SYMBOL_TRADE_CALC_MODE = %s\r\n",
str_calc_mode);
StringAdd(output_string,temp_string);
//--- double value output with 2 digits after the decimal point
double margin_initial=SymbolInfoDouble(_Symbol,SYMBOL_MARGIN_INITIAL);
temp_string=StringFormat(" SYMBOL_MARGIN_INITIAL = %.2f (initial margin)\r\n",
margin_initial);
StringAdd(output_string,temp_string);
//--- double value output with 2 digits after the decimal point
double margin_maintenance=SymbolInfoDouble(_Symbol,SYMBOL_MARGIN_MAINTENANCE);
temp_string=StringFormat(" SYMBOL_MARGIN_MAINTENANCE = %.2f (maintenance margin)
margin_maintenance);
StringAdd(output_string,temp_string);
//--- int value output
int freeze_level=(int)SymbolInfoInteger(_Symbol,SYMBOL_TRADE_FREEZE_LEVEL);
temp_string=StringFormat(" SYMBOL_TRADE_FREEZE_LEVEL = %d (order freeze level in
freeze_level);
StringAdd(output_string,temp_string);
Print(output_string);
Comment(output_string);
/* execution result
Contract specification for EURJPY:
SYMBOL_DIGITS = 3 (number of digits after the decimal point)
SYMBOL_POINT = 0.001 (point value)
SYMBOL_SPREAD = 23 (current spread in points)
SYMBOL_TRADE_STOPS_LEVEL = 100 (minimal indention in points for Stop orders)
SYMBOL_TRADE_CONTRACT_SIZE = 100000 (contract size)
SYMBOL_TRADE_TICK_SIZE = 0.001000 (minimal price change)
SYMBOL_SWAP_MODE = 0 (in points)
SYMBOL_SWAP_LONG = -1.600000 (buy order swap value)
SYMBOL_SWAP_SHORT = -1.100000 (sell order swap value)
SYMBOL_TRADE_MODE = SYMBOL_TRADE_MODE_FULL (no trade restrictions)
SYMBOL_VOLUME_MIN = 0.01 (minimal volume for a deal)
SYMBOL_VOLUME_STEP = 0.01 (minimal volume change step)
SYMBOL_VOLUME_MAX = 1000 (maximal volume for a deal)
SYMBOL_TRADE_CALC_MODE = 0 (Forex)
SYMBOL_MARGIN_INITIAL = 0.00 (initial margin)
SYMBOL_MARGIN_MAINTENANCE = 0.00 (maintenance margin)
SYMBOL_TRADE_FREEZE_LEVEL = 20 (order freeze level in points)
*/
}
See also
PrintFormat, DoubleToString,ColorToString, TimeToString
MQL4 Reference / Conversion Functions / CharToStr
CharToStr
Conversion of the symbol code into a one-character string.
string CharToStr( uchar char_code // ASCII-code
);
Parameters
char_code
[in] ASCII char code.
Returned value
Text string.
Example:
string str="WORL" + CharToStr(68); // 68 is code for 'D'
// the resulting string will be WORLD
See also
PrintFormat(), DoubleToString(), ColorToString(),
TimeToString()
MQL4 Reference / Conversion Functions / DoubleToStr
DoubleToStr
Returns text string with the specified numerical value
converted into a specified precision format.
string DoubleToStr( double value, // value
int digits // precision
);
Parameters
value
[in] Floating point value.
digits
[in] Precision format, number of digits after decimal
point (0-8).
Returned value
Text string.
Example:
string value=DoubleToStr(1.28473418, 5);
// the value is "1.28473"
See also
PrintFormat(), StrToDouble(), DoubleToString()
MQL4 Reference / Conversion Functions / StrToDouble
StrToDouble
Converts string representation of number to double type
(double-precision format with floating point).
double StrToDouble( string value // value
);
Parameters
value
[in] String containing the number character
representation format.
Returned value
Value of double type.
Example:
double var=StrToDouble("103.2812");
See also
PrintFormat(), DoubleToStr(), DoubleToString()
MQL4 Reference / Conversion Functions / StrToInteger
StrToInteger
Converts string containing the value character
representation into a value of the int (integer) type.
int StrToInteger( string value // string
);
Parameters
value
[in] String containing the integer character
representation format.
Returned value
Value of int type.
Example:
int var1=StrToInteger("1024");
See also
PrintFormat(), StringToInteger(), IntegerToString()
MQL4 Reference / Conversion Functions / StrToTime
StrToTime
Converts string in the format "yyyy.mm.dd hh:mi" to datetime type (the amount of
seconds that have passed since 1 Jan., 1970).
datetime StrToTime( string value // string
);
Parameters
value
[in] String having "yyyy.mm.dd hh:mi " format.
Returned value
Value of datetime type as a number of seconds, passed since 01.01.1970.
Example:
datetime var1,var2,var3;
var1=StrToTime("2003.8.12 17:35");
var2=StrToTime("17:35"); // returns the current date with the given time
var3=StrToTime("2003.8.12"); // returns the date with the midnight time of "00:00"
See also
PrintFormat(), TimeToStr(), TimeToString()
MQL4 Reference / Conversion Functions / TimeToStr
TimeToStr
Converts value containing time in seconds that has passed since January 1,
1970, into a string of "yyyy.mm.dd hh:mi" format.
string TimeToStr( datetime value, // value
int mode=TIME_DATE|TIME_MINUTES // format
);
Parameters
value
[in] Positive amount of seconds that have passed since 00:00, January 1,
1970.
mode=TIME_DATE|TIME_MINUTES
[in] Optional data output mode can be one or combination of:
TIME_DATE gets result as "yyyy.mm.dd",
TIME_MINUTES gets result as "hh:mi",
TIME_SECONDS gets result as "hh:mi:ss".
Returned value
String.
Example:
string var1=TimeToStr(TimeCurrent(),TIME_DATE|TIME_SECONDS);
See also
PrintFormat(), StrToTime(), StringToTime()
MQL4 Reference / Math Functions
Mathematical Functions
A set of mathematical and trigonometric functions.
Function Action
MathAbs Returns absolute value (modulus) of the
specified numeric value
MathArccos Returns the arc cosine of x in radians
MathArcsin Returns the arc sine of x in radians
MathArctan Returns the arc tangent of x in radians
MathCeil Returns integer numeric value closest
from above
MathCos Returns the cosine of a number
MathExp Returns exponent of a number
MathFloor Returns integer numeric value closest
from below
MathLog Returns natural logarithm
MathLog10 Returns the logarithm of a number by
base 10
MathMax Returns the maximal value of the two
numeric values
MathMin Returns the minimal value of the two
numeric values
MathMod Returns the real remainder after the
division of two numbers
MathPow Raises the base to the specified power
Function Action
MathRand Returns a pseudorandom value within the
range of 0 to 32767
MathRound Rounds of a value to the nearest integer
MathSin Returns the sine of a number
MathSqrt Returns a square root
MathSrand Sets the starting point for generating a
series of pseudorandom integers
MathTan Returns the tangent of a number
MathIsValidNumber Checks the correctness of a real number
What's new in MQL5
Added hyperbolic trigonometric functions and the
MathSwap function for changing the byte order in ushort,
uint and ulong integer types. The need for such a
transformation often arises when working with the
Network functions.
The Mathematics section contains the ready-made
libraries for working with random distributions, fuzzy logic
and neural networks. It also contains functions for solving
differential equations, clustering, statistical analysis and
optimization tasks.
MQL4 Reference / Math Functions / MathAbs
MathAbs
The function returns the absolute value (modulus) of the
specified numeric value.
double MathAbs( double value // numeric value
);
Parameters
value
[in] Numeric value.
Return Value
Value of double type more than or equal to zero.
Note
Instead the MathAbs() function you can use fabs().
MQL4 Reference / Math Functions / MathArccos
MathArccos
The function returns the arccosine of x within the range 0
to π in radians.
double MathArccos( double val // -1<val<1
);
Parameters
val
[in] The val value between -1 and 1, the arc cosine of
which is to be calculated.
Return Value
Arc cosine of a number in radians. If val is less than -1 or
more than 1, the function returns NaN (indeterminate
value).
Note
Instead of the MathArccos() function you can use acos().
See also
Real types (double, float)
MQL4 Reference / Math Functions / MathArcsin
MathArcsin
The function returns the arc sine of x within the range of
-π/2 to π/2 radians.
double MathArcsin( double val // -1<value<1
);
Parameters
val
[in] The val value between -1 and 1, the arc sine of
which is to be calculated.
Return Value
Arc sine of the val number in radians within the range of
-π/2 to π/2 radians. If val is less than -1 or more than 1,
the function returns NaN (indeterminate value).
Note
Instead of the MathArcsin() function you can use asin().
See also
Real types (double, float)
MQL4 Reference / Math Functions / MathArctan
MathArctan
The function returns the arc tangent of x. If x is equal to
0, the function returns 0.
double MathArctan( double value // tangent
);
Parameters
value
[in] A number representing a tangent.
Return Value
MathArctan returns a value within the range of -π/2 to
π/2 radians.
Note
Instead of the MathArctan() function you can use atan().
MQL4 Reference / Math Functions / MathCeil
MathCeil
The function returns integer numeric value closest from
above.
double MathCeil( double val // number
);
Parameters
val
[in] Numeric value.
Return Value
Numeric value representing the smallest integer that
exceeds or equals to val.
Note
Instead of the MathCeil() function you can use ceil().
MQL4 Reference / Math Functions / MathCos
MathCos
The function returns the cosine of an angle.
double MathCos( double value // number
);
Parameters
value
[in] Angle in radians.
Return Value
Value of double type within the range of -1 to 1.
Note
Instead of MathCos() you can use cos().
MQL4 Reference / Math Functions / MathExp
MathExp
The function returns the value of e raised to the power of d.
double MathExp( double value // power for the number e
);
Parameters
value
[in] A number specifying the power.
Return Value
A number of double type. In case of overflow the function returns
INF (infinity), in case of underflow MathExp returns 0.
Note
Instead of MathExp() you can use exp().
See also
Real types (double, float)
MQL4 Reference / Math Functions / MathFloor
MathFloor
The function returns integer numeric value closest from
below.
double MathFloor( double val // number
);
Parameters
val
[in] Numeric value.
Return Value
A numeric value representing the largest integer that is
less than or equal to val.
Note
Instead of MathFloor() you can use floor().
MQL4 Reference / Math Functions / MathLog
MathLog
The function returns a natural logarithm.
double MathLog( double val // value to take the logarithm
);
Parameters
val
[in] Value logarithm of which is to be found.
Return Value
The natural logarithm of val in case of success. If val is negative, the
function returns NaN (undetermined value). If val is equal to 0, the
function returns INF (infinity).
Note
Instead of MathLog() you can use log().
See also
Real types (double, float)
MQL4 Reference / Math Functions / MathLog10
MathLog
Returns the logarithm of a number by base 10.
double MathLog10( double val // number to take logarithm
);
Parameters
val
[in] Numeric value the common logarithm of which is to be
calculated.
Return Value
The common logarithm in case of success. If val is negative, the
function returns NaN (undetermined value). If val is equal to 0, the
function returns INF (infinity).
Note
Instead of MathLog10() you can use log10().
See also
Real types (double, float)
MQL4 Reference / Math Functions / MathMax
MathMax
The function returns the maximal value of two values.
double MathMax( double value1, // first value
double value2 // second value
);
Parameters
value1
[in] First numeric value.
value2
[in] Second numeric value.
Return Value
The largest of the two values.
Note
Instead of MathMax() you can use fmax(). Functions
fmax(), fmin(), MathMax(), MathMin() can work with
integer types without typecasting them to the type of
double.
If parameters of different types are passed into a
function, the parameter of the smaller type is
automatically cast to the larger type. The type of the
return value corresponds to the larger type.
If data of the same type are passed, no casting is
performed.
MQL4 Reference / Math Functions / MathMin
MathMin
The function returns the minimal value of two values.
double MathMin( double value1, // first value
double value2 // second value
);
Parameters
value1
[in] First numeric value.
value2
[in] Second numeric value.
Return Value
The smallest of the two values.
Note
Instead of MathMin() you can use fmin(). Functions
fmax(), fmin(), MathMax(), MathMin() can work with
integer types without typecasting them to the type of
double.
If parameters of different types are passed into a
function, the parameter of the smaller type is
automatically cast to the larger type. The type of the
return value corresponds to the larger type.
If data of the same type are passed, no casting is
performed.
MQL4 Reference / Math Functions / MathMod
MathMod
The function returns the real remainder of division of two
numbers.
double MathMod( double value, // dividend value
double value2 // divisor value
);
Parameters
value
[in] Dividend value.
value2
[in] Divisor value.
Return Value
The MathMod function calculates the real remainder f from
expression val/y so that val = i * y + f , where i is an
integer, f has the same sign as val, and the absolute value
of f is less than the absolute value of y.
Note
Instead of MathMod() you can use fmod().
MQL4 Reference / Math Functions / MathPow
MathPow
The function raises a base to a specified power.
double MathPow( double base, // base
double exponent // exponent value
);
Parameters
base
[in] Base.
exponent
[in] Exponent value.
Return Value
Value of base raised to the specified power.
Note
Instead of MathPow() you can use pow().
MQL4 Reference / Math Functions / MathRand
MathRand
Returns a pseudorandom integer within the range of 0 to
32767.
int MathRand();
Return Value
Integer value within the range of 0 to 32767.
Note
Before the first call of the function, it's necessary to call
MathSrand to set the generator of pseudorandom
numbers to the initial state.
Note
Instead of MathRand() you can use rand().
MQL4 Reference / Math Functions / MathRound
MathRound
The function returns a value rounded off to the nearest integer of
the specified numeric value.
double MathRound( double value // value to be rounded
);
Parameters
value
[in] Numeric value before rounding.
Return Value
Value rounded till to the nearest integer.
Note
Instead of MathRound() you can use round().
MQL4 Reference / Math Functions / MathSin
MathSin
Returns the sine of a specified angle.
double MathSin( double value // argument in radians
);
Parameters
value
[in] Angle in radians.
Return Value
Sine of an angle measured in radians. Returns value within the
range of -1 to 1.
Note
Instead of MathSin() you can use sin().
MQL4 Reference / Math Functions / MathSqrt
MathSqrt
Returns the square root of a number.
double MathSqrt( double value // positive number
);
Parameters
value
[in] Positive numeric value.
Return Value
Square root of value. If value is negative, MathSqrt returns
NaN (indeterminate value).
Note
Instead of MathSqrt() you can use sqrt().
See also
Real types (double, float)
MQL4 Reference / Math Functions / MathSrand
MathSrand
Sets the starting point for generating a series of pseudorandom integers.
void MathSrand( int seed // initializing number
);
Parameters
seed
[in] Starting number for the sequence of random numbers.
Return Value
No return value.
Note
The MathRand() function is used for generating a sequence of pseudorandom numbers.
Call of MathSrand() with a certain initializing number allows to always produces the
same sequence of pseudorandom numbers.
To ensure receipt of non-recurring sequence, use the call of
MathSrand(GetTickCount()), since the value of GetTickCount() increases from the
moment of the start of the operating system and is not repeated within 49 days, until
the built-in counter of milliseconds overflows. Use of MathSrand(TimeCurrent()) is not
suitable, because the TimeCurrent() function returns the time of the last tick, which
can be unchanged for a long time, for example at the weekend.
Initialization of the random number generator using MathSrand() for indicators and
Expert Advisors is better performed in the OnInit() handler; it saves you from the
following multiple restarts of the generator in OnTick() and OnCalculate().
Instead of the MathSrand() function you can use the srand() function.
Example:
#property description "The indicator shows the central limit theorem, which states:"
#property description "The sum of a sufficiently large number of weakly dependent ran
#property description "having approximately equal magnitude (none of the summands dom
#property description "or makes a determining contribution to the sum), has a distrib
#property indicator_separate_window
#property indicator_buffers 1
//--- Properties of the graphical construction
#property indicator_label1 "Label"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrRoyalBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 5
//--- An input variable
input int sample_number=10;
//--- An indicator buffer to for drawing the distribution
double LabelBuffer[];
//--- A counter of ticks
double ticks_counter;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- Binding an array and an indicator buffer
SetIndexBuffer(0,LabelBuffer,INDICATOR_DATA);
//--- turn the indicator buffer around from the present to the past
ArraySetAsSeries(LabelBuffer,true);
//--- Initialize the generator of random numbers
MathSrand(GetTickCount());
//--- Initialize the counter of ticks
ticks_counter=0;
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- For a zero counter reset the indicator buffer
if(ticks_counter==0) ArrayInitialize(LabelBuffer,0);
//--- Increase the counter
ticks_counter++;
//--- We should periodically reset the counter ticks, to revive the distribution
if(ticks_counter>100)
{
Print("We've reset the indicator values, let's start filling the cells once aga
ticks_counter=0;
}
//--- Get a sample of random values as the sum of three numbers from 0 to 7
for(int i=0;i<sample_number;i++)
{
//--- Calculation of the index of the cell, where the random number falls as th
int rand_index=0;
//--- Get three random numbers from 0 to 7
for(int k=0;k<3;k++)
{
//--- A remainder in the division by 7 will return a value from 0 to 6
rand_index+=MathRand()%7;
}
//--- Increase the value in the cell number rand_index by 1
LabelBuffer[rand_index]++;
}
//--- Exit the OnCalculate() handler
return(rates_total);
}
MQL4 Reference / Math Functions / MathTan
MathTan
The function returns a tangent of a number.
double MathTan( double rad // argument in radians
);
Parameters
rad
[in] Angle in radians.
Return Value
Tangent of rad. If rad is greater than or equal to 263, or less
than or equal to -263, a loss of significance in the result
occurs, in which case the function returns an indefinite
number.
Note
Instead of MathTan() you can use tan().
See also
Real types (double, float)
MQL4 Reference / Math Functions / MathIsValidNumber
MathIsValidNumber
It checks the correctness of a real number.
bool MathIsValidNumber( double number // number to check
);
Parameters
number
[in] Checked numeric value.
Return Value
It returns true, if the checked value is an acceptable real number. If the checked value
is a plus or minus infinity, or "not a number" (NaN), the function returns false.
Example:
double abnormal=MathArcsin(2.0);
if(!MathIsValidNumber(abnormal)) Print("Attention! MathArcsin(2.0) = ",abnormal);
See also
Real types (double, float)
MQL4 Reference / String Functions
String Functions
This is a group of functions intended for working with data
of the string type.
Function Action
StringAdd Adds a string to the end of another string
StringBufferLen Returns the size of buffer allocated for
the string
StringCompare Compares two strings and returns 1 if the
first string is greater than the second; 0 -
if the strings are equal; -1 (minus 1) - if
the first string is less than the second one
StringConcatenate Forms a string of parameters passed
StringFill Fills out a specified string by selected
symbols
StringFind Search for a substring in a string
StringGetCharacter Returns the value of a number located in
the specified string position
StringInit Initializes string by specified symbols and
provides the specified string length
StringLen Returns the number of symbols in a string
StringReplace Replaces all the found substrings of a
string by a set sequence of symbols
StringSetCharacter Returns a copy of a string with a changed
value of a symbol in a specified position
Function Action
StringSplit Gets substrings by a specified separator
from the specified string, returns the
number of substrings obtained
StringSubstr Extracts a substring from a text string
starting from a specified position
StringToLower Transforms all symbols of a selected
string to lowercase
StringToUpper Transforms all symbols of a selected
string into capitals
StringTrimLeft Cuts line feed characters, spaces and
tabs in the left part of the string
StringTrimRight Cuts line feed characters, spaces and
tabs in the right part of the string
StringGetChar Returns character (code) from the
specified position in the string
StringSetChar Returns the string copy with changed
character in the specified position
MQL4 Reference / String Functions / StringAdd
StringAdd
The function adds a substring to the end of a string.
bool StringAdd( string& string_var, // string, to which we add
string add_substring // string, which is added
);
Parameters
string_var
[in][out] String, to which another one is added.
add_substring
[in] String that is added to the end of a source string.
Return Value
In case of success returns true, otherwise false. In order to get an error code, the
GetLastError() function should be called.
Example:
void OnStart()
{
//---
long length=10000000;
string a="a",b="b",c;
//--- first method
uint starttime=GetTickCount(),finishtime;
long i;
for(i=0;i<length;i++)
{
c=a+b;
}
finishtime=GetTickCount();
Print("time for 'c = a + b' = ",(finishtime-starttime)," milliseconds, i = ",i);
See also
StringConcatenate()
MQL4 Reference / String Functions / StringBufferLen
StringBufferLen
The function returns the size of buffer allocated for the string.
int StringBufferLen( string string_var // string
)
Parameters
string_var
[in] String.
Return Value
The value 0 means that the string is constant and buffer size
can't be changed. -1 means that the string belongs to the
client terminal, and modification of the buffer contents can
have indeterminate results.
Note
Minimal buffer size is equal to 16.
Example:
void OnStart()
{
long length=1000;
string a="a",b="b";
//---
long i;
Print("before: StringBufferLen(a) = ",StringBufferLen(a),
" StringLen(a) = ",StringLen(a));
for(i=0;i<length;i++)
{
StringAdd(a,b);
}
Print("after: StringBufferLen(a) = ",StringBufferLen(a),
" StringLen(a) = ",StringLen(a));
}
See also
StringAdd(), StringInit(), StringLen(), StringFill()
MQL4 Reference / String Functions / StringCompare
StringCompare
The function compares two strings and returns the comparison result in form of an
integer.
int StringCompare( const string& string1, // the first string in
const string& string2, // the second string in the comparison
bool case_sensitive=true // case sensitivity mode selection for the
);
Parameters
string1
[in] The first string.
string2
[in] The second string.
case_sensitive=true
[in] Case sensitivity mode selection. If it is true, then "A">"a". If it is false, then
"A"="a". By default the value is equal to true.
Return Value
-1 (minus one), if string1<string2
0 (zero), if string1=string2
1 (one), if string1>string2
Note
The strings are compared symbol by symbol, the symbols are compared in the
alphabetic order in accordance with the current code page.
Example:
void OnStart()
{
//--- what is larger - apple or home?
string s1="Apple";
string s2="home";
See also
String Type, CharToString(), ShortToString(), StringToCharArray(), StringToShortArray(),
StringGetCharacter(), Use of a Codepage
MQL4 Reference / String Functions / StringConcatenate
StringConcatenate
The function returns the string formed by concatenation of parameters transformed into
string type.
string StringConcatenate( void argument1, // first parameter of any simple
void argument2, // second parameter of any simple type
... // next parameter of any simple type
);
Parameters
argumentN
[in] Any comma separated values. From 2 to 63 parameters of any simple type.
Return Value
Returns the string, formed by concatenation of parameters transformed into string
type. Parameters are transformed into strings according to the same rules as in Print()
and Comment().
Note
Parameters can be of any type. Number of parameters can't be less than 2 or more than
64.
Example:
string text;
text=StringConcatenate("Account free margin is ", AccountFreeMargin(), " Current ti
// text="Account free margin is " + AccountFreeMargin() + " Current time is " + Ti
Print(text);
See also
StringAdd()
MQL4 Reference / String Functions / StringFill
StringFill
It fills out a selected string by specified symbols.
bool StringFill( string& string_var, // string to fill
ushort character // symbol that will fill the string
);
Parameters
string_var
[in][out] String, that will be filled out by the selected symbol.
character
[in] Symbol, by which the string will be filled out.
Return Value
In case of success returns true, otherwise - false. To get the error code call
GetLastError().
Note
Filling out a string at place means that symbols are inserted directly to the
string without transitional operations of new string creation or copying. This
allows to save the operation time.
Example:
void OnStart()
{
string str;
StringInit(str,20,'_');
Print("str = ",str);
StringFill(str,0);
Print("str = ",str,": StringBufferLen(str) = ", StringBufferLen(str));
}
// Result
// str = ____________________
// str = : StringBufferLen(str) = 20
//
See also
StringBufferLen(), StringLen(), StringInit()
MQL4 Reference / String Functions / StringFind
StringFind
Search for a substring in a string.
int StringFind( string string_value, // string in which search is made
string match_substring, // what is searched
int start_pos=0 // from what position search starts
);
Parameters
string_value
[in] String, in which search is made.
match_substring
[in] Searched substring.
start_pos=0
[in] Position in the string from which search is started.
Return Value
Returns position number in a string, from which the searched substring starts, or -1,
if the substring is not found.
MQL4 Reference / String Functions / StringGetCharacter
StringGetCharacter
Returns value of a symbol, located in the specified position of a
string.
ushort StringGetCharacter( string string_value, // string
int pos // symbol position in the string
);
Parameters
string_value
[in] String.
pos
[in] Position of a symbol in the string. Can be from 0 to
StringLen(text) -1.
Return Value
Symbol code or 0 in case of an error. To get the error code call
GetLastError().
MQL4 Reference / String Functions / StringInit
StringInit
Initializes a string by specified symbols and provides the specified string size.
bool StringInit( string& string_var, // string to initialize
int new_len=0, // required string length after initialization
ushort character=0 // symbol, by which the string will be filled
);
Parameters
string_var
[in][out] String that should be initialized and deinitialized.
new_len=0
[in] String length after initialization. If length=0, it deinitializes the string, i.e.
the string buffer is cleared and the buffer address is zeroed.
character=0
[in] Symbol to fill the string.
Return Value
In case of success returns true, otherwise - false. To get the error code call
GetLastError().
Note
If character=0 and the length new_len>0, the buffer of the string of indicated
length will be distributed and filled by zeroes. The string length will be equal to
zero, because the whole buffer is filled out by string terminators.
Example:
void OnStart()
{
//---
string str;
StringInit(str,200,0);
Print("str = ",str,": StringBufferLen(str) = ",
StringBufferLen(str)," StringLen(str) = ",StringLen(str));
}
/* Result
str = : StringBufferLen(str) = 200 StringLen(str) = 0
*/
See also
StringBufferLen(), StringLen()
MQL4 Reference / String Functions / StringLen
StringLen
Returns the number of symbols in a string.
int StringLen( string string_value // string
);
Parameters
string_value
[in] String to calculate length.
Return Value
Number of symbols in a string without the ending zero.
MQL4 Reference / String Functions / StringReplace
StringReplace
It replaces all the found substrings of a string by a set sequence of symbols.
int StringReplace( string& str, // the string in which substr
const string find, // the searched substring
const string replacement // the substring that will be inserted to the fo
);
Parameters
str
[in][out] The string in which you are going to replace substrings.
find
[in] The desired substring to replace.
replacement
[in] The string that will be inserted instead of the found one.
Return Value
The function returns the number of replacements in case of success, otherwise -1. To
get an error code call the GetLastError() function.
Note
If the function has run successfully but no replacements have been made (the substring
to replace was not found), it returns 0.
The error can result from incorrect str or find parameters (empty or non-initialized
string, see StringInit() ). Besides, the error occurs if there is not enough memory to
complete the replacement.
Example:
string text="The quick brown fox jumped over the lazy dog.";
int replaced=StringReplace(text,"quick","slow");
replaced+=StringReplace(text,"brown","black");
replaced+=StringReplace(text,"fox","bear");
Print("Replaced: ", replaced,". Result=",text);
// Result
// Replaced: 3. Result=The slow black bear jumped over the lazy dog.
//
See also
StringSetCharacter(), StringSubstr()
MQL4 Reference / String Functions / StringSetCharacter
StringSetCharacter
Returns true is a symbol is successfully inserted to the passed string.
bool StringSetCharacter( string& string_var, // string
int pos, // position
ushort character // character
);
Parameters
string_var
[in][out] String.
pos
[in] Position of a character in a string. Can be from 0 to StringLen(text).
character
[in] Symbol code Unicode.
Return Value
In case of success returns true, otherwise - false.
Note
If pos is less than string length and the symbol code value = 0, the string is cut
off (but the buffer size, distributed for the string remains unchanged). The
string length becomes equal to pos.
If pos is equal to string length, the specified symbol is added at the string end,
and the length is enlarged by one.
Example:
void OnStart()
{
string str="0123456789";
Print("before: str = ",str,",StringBufferLen(str) = ",
StringBufferLen(str)," StringLen(str) = ",StringLen(str));
//--- add zero value in the middle
StringSetCharacter(str,6,0);
Print("after: str = ",str,",StringBufferLen(str) = ",
StringBufferLen(str)," StringLen(str) = ",StringLen(str));
//--- add symbol at the end
int size=StringLen(str);
StringSetCharacter(str,size,'+');
Print("addition: str = ",str,",StringBufferLen(str) = ",
StringBufferLen(str)," StringLen(str) = ",StringLen(str));
}
/* Result
before: str = 0123456789 ,StringBufferLen(str) = 0 StringLen(str) = 10
after: str = 012345 ,StringBufferLen(str) = 16 StringLen(str) = 6
addition: str = 012345+ ,StringBufferLen(str) = 16 StringLen(str) = 7
*/
See also
StringBufferLen(), StringLen(), StringFill(), StringInit()
MQL4 Reference / String Functions / StringSplit
StringSplit
Gets substrings by a specified separator from the specified string, returns the number of
substrings obtained.
int StringSplit( const string string_value, // A string to search in
const ushort separator, // A separator using which substrings will be s
string & result[] // An array passed by reference to get the foun
);
Parameters
string_value
[in] The string from which you need to get substrings. The string will not change.
pos
[in] The code of the separator character. To get the code, you can use the
StringGetCharacter() function.
result[]
[out] An array of strings where the obtained substrings are located.
Return Value
The number of substrings in the result[] array. If the separator is not found in the
passed string, only one source string will be placed in the array.
If string_value is empty or NULL, the function will return zero. In case of an error the
function returns -1. To get the error code, call the GetLastError() function.
Example:
string to_split="life_is_good"; // A string to split into substrings
string sep="_"; // A separator as a character
ushort u_sep; // The code of the separator character
string result[]; // An array to get strings
//--- Get the separator code
u_sep=StringGetCharacter(sep,0);
//--- Split the string to substrings
int k=StringSplit(to_split,u_sep,result);
//--- Show a comment
PrintFormat("Strings obtained: %d. Used separator '%s' with the code %d",k,sep,u_s
//--- Now output all obtained strings
if(k>0)
{
for(int i=0;i<k;i++)
{
PrintFormat("result[%d]=%s",i,result[i]);
}
}
See also
StringReplace(), StringSubstr(), StringConcatenate()
MQL4 Reference / String Functions / StringSubstr
StringSubstr
Extracts a substring from a text string starting from the
specified position.
string StringSubstr( string string_value, // string
int start_pos, // position to start with
int length=0 // length of extracted string
);
Parameters
string_value
[in] String to extract a substring from.
start_pos
[in] Initial position of a substring. Can be from 0 to
StringLen(text) -1.
length=0
[in] Length of an extracted substring. If the parameter value
is equal or less than 0 or parameter isn't set, the substring
will be extracted from the indicated position till the string
end.
Return Value
Copy of a extracted substring, if possible. Otherwise returns
an empty string.
MQL4 Reference / String Functions / StringToLower
StringToLower
Transforms all symbols of a selected string into lowercase.
bool StringToLower( string& string_var // string to process
);
Parameters
string_var
[in][out] String.
Return Value
In case of success returns true, otherwise - false. To get the error code
call GetLastError().
MQL4 Reference / String Functions / StringToUpper
StringToUpper
Transforms all symbols of a selected string into capitals.
bool StringToUpper( string& string_var // string to process
);
Parameters
string_var
[in][out] String.
Return Value
In case of success returns true, otherwise - false. To get the error code
call GetLastError().
MQL4 Reference / String Functions / StringTrimLeft
StringTrimLeft
The function cuts line feed characters, spaces and tabs in the left part
of the string till the first meaningful symbol. The string is modified at
place.
string StringTrimLeft( const string text // string to cut
);
Parameters
text
[in] String that will be cut from the left.
Return Value
A copy of the cut string if possible, otherwise an empty string.
Example:
string str1=" Hello world ";
string str2=StringTrimLeft(str1);
// after left trim str2 will be equal to "Hello World "
MQL4 Reference / String Functions / StringTrimRight
StringTrimRight
The function cuts line feed characters, spaces and tabs in the right part
of the string after the last meaningful symbol. The string is modified at
place.
string StringTrimRight( const string text // string to cut
);
Parameters
text
[in] String that will be cut from the right.
Return Value
A copy of the cut string if possible, otherwise an empty string.
Exampe:
string str1 = " Hello world ";
string str2=StringTrimRight(str1);
// after right trim str2 will be equal to " Hello World"
MQL4 Reference / String Functions / StringGetChar
StringGetChar
Returns character (code) from the specified position in the
string.
ushort StringGetChar( string string_value, // string
int pos // position
);
Parameters
string_value
[in] String.
pos
[in] Char position in the string. Can be from 0 to
StringLen(text) -1.
Returned value
Char code or 0 if error. To get information about error, call the
GetLastError() function.
Example:
int char_code=StringGetChar("abcdefgh", 2);
// char code of 'c' = 99
MQL4 Reference / String Functions / StringSetChar
StringSetChar
Returns the string copy with changed character in the specified
position.
string StringSetChar( string string_var, // string
int pos, // position
ushort value // char code
);
Parameters
string_var
[in] Source string.
pos
[in] The character position in the string. Can be from 0 to
StringLen(text).
value
[in] New char ASCII-code.
Returned value
The string copy with changed character in the specified position.
Note
If the value of pos parameter is less than string length and char
code = 0, the string will be truncated (to position, equal to pos).
If the value of pos parameter is equal to string lenth, the
specified symbol will be added to the end of the string and string
length will be increased by 1.
Example:
string str="abcdefgh";
string str1=StringSetChar(str, 3, 'D');
// str1 = "abcDefgh"
See also
StringBufferLen(), StringLen(), StringFill(), StringInit()
MQL4 Reference / Date and Time
What's new in MQL5
Added the MqlDateTime structure containing eight int type fields:
struct MqlDateTime {
int year; // year
int mon; // month
int day; // day
int hour; // hour
int min; // minutes
int sec; // seconds
int day_of_week; // day of week (0 - Sunday, 1 - Monday, ..., 6 - Saturday)
int day_of_year; // number of a day in a year (January 1 has number 0)
};
Thus, the new TimeToStruct() and StructToTime() functions allow you to receive and
pass data on days, hours, minutes and seconds within a single call.
MQL4 Reference / Date and Time / TimeCurrent
TimeCurrent
Returns the last known server time, time of the last quote receipt for one of the
symbols selected in the "Market Watch" window. In the OnTick() handler, this function
returns the time of the received handled tick. In other cases (for example, call in
handlers OnInit(), OnDeinit(), OnTimer() and so on) this is the time of the last quote
receipt for any symbol available in the "Market Watch" window, the time shown in the
title of this window. The time value is formed on a trade server and does not depend
on the time settings on your computer. There are 2 variants of the function.
Call without parameters
datetime TimeCurrent();
Parameters
dt_struct
[out] MqlDateTime structure type variable.
Return Value
Value of datetime type
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is
filled accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function,
which produces values in milliseconds.
During testing in the Strategy Tester, TimeCurrent() is simulated according to
historical data.
MQL4 Reference / Date and Time / TimeLocal
TimeLocal
Returns the local time of a computer, where the client terminal is running. There are 2
variants of the function.
Call without parameters
datetime TimeLocal();
Parameters
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
Value of datetime type
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is filled
accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function,
which produces values in milliseconds.
During testing in the Strategy Tester, TimeLocal() is always equal to TimeCurrent()
simulated server time.
MQL4 Reference / Date and Time / TimeGMT
TimeGMT
Returns the GMT, which is calculated taking into account the DST switch by the local
time on the computer where the client terminal is running. There are 2 variants of
the function.
Call without parameters
datetime TimeGMT();
Parameters
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
Value of datetime type
Note
If the MqlDateTime structure type variable has been passed as a parameter, it is
filled accordingly.
To arrange high-resolution counters and timers, use the GetTickCount() function,
which produces values in milliseconds.
During testing in the Strategy Tester, TimeGMT() is always equal to TimeCurrent()
simulated server time.
MQL4 Reference / Date and Time / TimeDaylightSavings
TimeDaylightSavings
Returns correction for daylight saving time in seconds, if
the switch to summer time has been made. It depends on
the time settings of your computer.
int TimeDaylightSavings();
Return Value
If switch to winter (standard) time has been made, it
returns 0.
MQL4 Reference / Date and Time / TimeGMTOffset
TimeGMTOffset
Returns the current difference between GMT time and the
local computer time in seconds, taking into account
switch to winter or summer time. Depends on the time
settings of your computer.
int TimeGMTOffset();
Return Value
The value of int type, representing the current
difference between GMT time and the local time of the
computer TimeLocal in seconds.
TimeGMTOffset() = TimeGMT() - TimeLocal()
MQL4 Reference / Date and Time / TimeToStruct
TimeToStruct
Converts a value of datetime type (number of seconds since 01.01.1970)
into a structure variable MqlDateTime.
void TimeToStruct( datetime dt, // date and time
MqlDateTime& dt_struct // structure for the adoption of values
);
Parameters
dt
[in] Date value to convert.
dt_struct
[out] Variable of structure type MqlDateTime.
Return Value
True if successful, otherwise false. To get information about the error, call
the GetLastError() function.
MQL4 Reference / Date and Time / StructToTime
StructToTime
Converts a structure variable MqlDateTime into a value of datetime type and returns the
resulting value.
datetime StructToTime( MqlDateTime$ dt_struct // structure of the date and t
);
Parameters
dt_struct
[in] Variable of structure type MqlDateTime.
Return Value
The value of datetime type containing the number of seconds since 01.01.1970.
MQL4 Reference / Date and Time / Day
Day
Returns the current day of the month, i.e., the day of
month of the last known server time.
int Day();
Returned value
Current day of the month.
Note
At the testing, the last known server time is modelled.
Example:
if(Day()<5) return(0);
MQL4 Reference / Date and Time / DayOfWeek
DayOfWeek
Returns the current zero-based day of the week (0-Sunday,1,2,3,4,5,6) of the last
known server time.
int DayOfWeek();
Returned value
Current zero-based day of the week (0-Sunday,1,2,3,4,5,6).
Note
At the testing, the last known server time is modelled.
Example:
// do not work on holidays. if(DayOfWeek()==0 || DayOfWeek()==6) return(0);
MQL4 Reference / Date and Time / DayOfYear
DayOfYear
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.
int DayOfYear();
Returned value
Current day of the year (1 means 1 January,..,365(6)
does 31 December).
Note
At the testing, the last known server time is modelled.
Example:
if(DayOfYear()==245) return(true);
MQL4 Reference / Date and Time / Hour
Hour
Returns the hour (0,1,2,..23) of the last known server
time by the moment of the program start.
int Hour();
Returned value
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 execution).
Note
At the testing, the last known server time is modelled.
Example:
bool is_siesta=false; if(Hour()>=12 && Hour()<17)
is_siesta=true;
MQL4 Reference / Date and Time / Minute
Minute
Returns the current minute (0,1,2,..59) of the last known
server time by the moment of the program start.
int Minute();
Returned value
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 the
program execution).
Note
At the testing, the last known server time is modelled.
Example:
if(Minute()<=15) return("first quarter");
MQL4 Reference / Date and Time / Month
Month
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.
int Month();
Returned value
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.
Note
At the testing, the last known server time is modelled.
Example:
if(Month()<=5) return("the first half year");
MQL4 Reference / Date and Time / Seconds
Seconds
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.
int Seconds();
Returned value
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 value will not change
within the time of the program execution).
Note
At the testing, the last known server time is modelled.
Example:
if(Seconds()<=15) return(0);
MQL4 Reference / Date and Time / TimeDay
TimeDay
Returns the day of month (1 - 31) of the specified date.
int TimeDay( datetime date // date and time
);
Parameters
date
[in] Datetime as number of seconds elapsed since midnight
(00:00:00), January 1, 1970.
Returned value
Day of month (1 - 31) of the specified date.
Example:
int day=TimeDay(D'2003.12.31');
// day is 31
MQL4 Reference / Date and Time / TimeDayOfWeek
TimeDayOfWeek
Returns the zero-based day of week (0 means Sunday,1,2,3,4,5,6) of the
specified date.
int TimeDayOfWeek( datetime date // date and time
);
Parameters
date
[in] Datetime as number of seconds elapsed since midnight (00:00:00),
January 1, 1970.
Returned value
The zero-based day of week (0 means Sunday,1,2,3,4,5,6) of the
specified date.
Example:
int weekday=TimeDayOfWeek(D'2004.11.2');
// day is 2 - Tuesday
MQL4 Reference / Date and Time / TimeDayOfYear
TimeDayOfYear
Returns the day of year of the specified date.
int TimeDayOfYear( datetime date // date and time
);
Parameters
date
[in] Datetime as number of seconds elapsed since midnight (00:00:00),
January 1, 1970.
Returned value
Day (1 means 1 January,..,365(6) does 31 December) of year of the
specified date.
Example:
int nday=TimeDayOfYear(TimeCurrent());
MQL4 Reference / Date and Time / TimeHour
TimeHour
Returns the hour of the specified time.
int TimeHour( datetime date // date and time
);
Parameters
date
[in] Datetime is the number of seconds elapsed since midnight
(00:00:00), January 1, 1970.
Returned value
Hour of the specified time.
Example:
int h=TimeHour(TimeCurrent());
MQL4 Reference / Date and Time / TimeMinute
TimeMinute
Returns the minute of the specified time.
int TimeMinute( datetime date // date and time
);
Parameters
date
[in] Datetime as number of seconds elapsed since midnight
(00:00:00), January 1, 1970.
Returned value
Minute (0-59) for the specified time.
Example:
int m=TimeMinute(TimeCurrent());
MQL4 Reference / Date and Time / TimeMonth
TimeMonth
Returns the month number of the specified time.
int TimeMonth( datetime date // date and time
);
Parameters
date
[in] Datetime as number of seconds elapsed since midnight
(00:00:00), January 1, 1970.
Returned value
Month number (1-January,2,3,4,5,6,7,8,9,10,11,12) of the specified
time.
Example:
int m=TimeMonth(TimeCurrent());
MQL4 Reference / Date and Time / TimeSeconds
TimeSeconds
Returns the amount of seconds elapsed from the beginning of the
minute of the specified time.
int TimeSeconds( datetime date // date and time
);
Parameters
date
[in] Datetime as number of seconds elapsed since midnight
(00:00:00), January 1, 1970.
Returned value
The amount of seconds elapsed from the beginning of the minute of
the specified time.
Example:
int m=TimeSeconds(TimeCurrent());
MQL4 Reference / Date and Time / TimeYear
TimeYear
Returns year of the specified date.
int TimeYear( datetime date // date and time
);
Parameters
date
[in] Datetime as number of seconds elapsed since midnight
(00:00:00), January 1, 1970.
Returned value
Year of the specified date. The returned value can be within the
range of 1970 to 3000.
Example:
int y=TimeYear(TimeCurrent());
MQL4 Reference / Date and Time / Year
Year
Returns the current year, i.e., the year of the last known server time.
int Year();
Returned value
Current year.
Note
At the testing, the last known server time is modelled.
Example:
// return if the date is within the range from 1 Jan. to 30 Apr., 2006. if(Year
return(0);
MQL4 Reference / Account Information
Account Information
Functions that return parameters of the current account.
Function Action
AccountInfoDouble Returns a value of double type of
the corresponding account property
AccountInfoInteger Returns a value of integer type
(bool, int or long) of the
corresponding account property
AccountInfoString Returns a value string type
corresponding account property
AccountBalance Returns balance value of the
current account
AccountCredit Returns credit value of the current
account
AccountCompany Returns the brokerage company
name where the current account
was registered
AccountCurrency Returns currency name of the
current account
AccountEquity Returns equity value of the current
account
AccountFreeMargin Returns free margin value of the
current account
Function Action
AccountFreeMarginCheck Returns free margin that remains
after the specified position has
been opened at the current price
on the current account
AccountFreeMarginMode Calculation mode of free margin
allowed to open orders on the
current account
AccountLeverage Returns leverage of the current
account
AccountMargin Returns margin value of the current
account
AccountName Returns the current account name
AccountNumber Returns the current account
number
AccountProfit Returns profit value of the current
account
AccountServer Returns the connected server name
AccountStopoutLevel Returns the value of the Stop Out
level
AccountStopoutMode Returns the calculation mode for
the Stop Out level
MQL4 Reference / Account Information / AccountInfoDouble
AccountInfoDouble
Returns the value of the corresponding account property.
double AccountInfoDouble( int property_id // identifier of the property
);
Parameters
property_id
[in] Identifier of the property. The value can be one of the values of
ENUM_ACCOUNT_INFO_DOUBLE.
Return Value
Value of double type.
Example:
void OnStart()
{
//--- show all the information available from the function AccountInfoDouble()
printf("ACCOUNT_BALANCE = %G",AccountInfoDouble(ACCOUNT_BALANCE));
printf("ACCOUNT_CREDIT = %G",AccountInfoDouble(ACCOUNT_CREDIT));
printf("ACCOUNT_PROFIT = %G",AccountInfoDouble(ACCOUNT_PROFIT));
printf("ACCOUNT_EQUITY = %G",AccountInfoDouble(ACCOUNT_EQUITY));
printf("ACCOUNT_MARGIN = %G",AccountInfoDouble(ACCOUNT_MARGIN));
printf("ACCOUNT_MARGIN_FREE = %G",AccountInfoDouble(ACCOUNT_FREEMARGIN));
printf("ACCOUNT_MARGIN_LEVEL = %G",AccountInfoDouble(ACCOUNT_MARGIN_LEVEL));
printf("ACCOUNT_MARGIN_SO_CALL = %G",AccountInfoDouble(ACCOUNT_MARGIN_SO_CALL));
printf("ACCOUNT_MARGIN_SO_SO = %G",AccountInfoDouble(ACCOUNT_MARGIN_SO_SO));
}
See also
SymbolInfoDouble, SymbolInfoString, SymbolInfoInteger, PrintFormat
MQL4 Reference / Account Information / AccountInfoInteger
AccountInfoInteger
Returns the value of the properties of the account.
long AccountInfoInteger( int property_id // Identifier of the property
);
Parameters
property_id
[in] Identifier of the property. The value can be one of the values of
ENUM_ACCOUNT_INFO_INTEGER.
Return Value
Value of long type.
Note
The property must be one of the bool, int or long types.
Example:
void OnStart()
{
//--- show all the information available from the function AccountInfoInteger()
printf("ACCOUNT_LOGIN = %d",AccountInfoInteger(ACCOUNT_LOGIN));
printf("ACCOUNT_LEVERAGE = %d",AccountInfoInteger(ACCOUNT_LEVERAGE));
bool thisAccountTradeAllowed=AccountInfoInteger(ACCOUNT_TRADE_ALLOWED);
bool EATradeAllowed=AccountInfoInteger(ACCOUNT_TRADE_EXPERT);
ENUM_ACCOUNT_TRADE_MODE tradeMode=(ENUM_ACCOUNT_TRADE_MODE)AccountInfoInteger(ACCO
ENUM_ACCOUNT_STOPOUT_MODE stopOutMode=(ENUM_ACCOUNT_STOPOUT_MODE)AccountInfoIntege
See also
Account Information
MQL4 Reference / Account Information / AccountInfoString
AccountInfoString
Returns the value of the corresponding account property.
string AccountInfoString( int property_id // Identifier of the property
);
Parameters
property_id
[in] Identifier of the property. The value can be one of the values of
ENUM_ACCOUNT_INFO_STRING.
Return Value
Value of string type.
Example:
void OnStart()
{
//--- Show all the information available from the function AccountInfoString()
Print("The name of the broker = ",AccountInfoString(ACCOUNT_COMPANY));
Print("Deposit currency = ",AccountInfoString(ACCOUNT_CURRENCY));
Print("Client name = ",AccountInfoString(ACCOUNT_NAME));
Print("The name of the trade server = ",AccountInfoString(ACCOUNT_SERVER));
}
See also
Account Information
MQL4 Reference / Account Information / AccountBalance
AccountBalance
Returns balance value of the current account.
double AccountBalance();
Returned value
Balance value of the current account (the amount of
money on the account).
Example:
Print("Account balance = ",AccountBalance());
MQL4 Reference / Account Information / AccountCredit
AccountCredit
Returns credit value of the current account.
double AccountCredit();
Returned value
Credit value of the current account.
Example:
Print("Account number ", AccountCredit());
MQL4 Reference / Account Information / AccountCompany
AccountCompany
Returns the brokerage company name where the current
account was registered.
string AccountCompany();
Returned value
The brokerage company name where the current account
was registered.
Example:
Print("Account company name ", AccountCompany());
MQL4 Reference / Account Information / AccountCurrency
AccountCurrency
Returns currency name of the current account.
string AccountCurrency();
Returned value
Currency name of the current account.
Example:
Print("Account currency is ", AccountCurrency());
MQL4 Reference / Account Information / AccountEquity
AccountEquity
Returns equity value of the current account.
double AccountEquity();
Returned value
Equity value of the current account. Equity calculation
depends on trading server settings.
Example:
Print("Account equity = ",AccountEquity());
MQL4 Reference / Account Information / AccountFreeMargin
AccountFreeMargin
Returns free margin value of the current account.
double AccountFreeMargin();
Returned value
Free margin value of the current account.
Example:
Print("Account free margin = ",AccountFreeMargin());
MQL4 Reference / Account Information / AccountFreeMarginCheck
AccountFreeMarginCheck
Returns free margin that remains after the specified order has been opened at the
current price on the current account.
double AccountFreeMarginCheck( string symbol, // symbol
int cmd, // trade operation
double volume // volume
);
Parameters
symbol
[in] Symbol for trading operation.
cmd
[in] Operation type. It can be either OP_BUY or OP_SELL.
volume
[in] Number of lots.
Returned value
Free margin that remains after the specified order has been opened at the current price
on the current account. If the free margin is insufficient, an error 134
(ERR_NOT_ENOUGH_MONEY) will be generated.
Example:
if(AccountFreeMarginCheck(Symbol(),OP_BUY,Lots)<=0 || GetLastError()==134) return;
MQL4 Reference / Account Information / AccountFreeMarginMode
AccountFreeMarginMode
Returns the calculation mode of free margin allowed to
open orders on the current account.
double AccountFreeMarginMode();
Returned value
Calculation mode of free margin allowed to opened orders
on the current account.
The calculation mode can take the following values: 0 -
floating profit/loss is not used for calculation;
1 - both floating profit and loss on opened orders on the
current account are used for free margin calculation;
2 - only profit value is used for calculation, the current
loss on opened orders is not considered;
3 - only loss value is used for calculation, the current
floating profit on opened orders is not considered.
Example:
if(AccountFreeMarginMode()==0)
Print("Floating Profit/Loss do not use.");
MQL4 Reference / Account Information / AccountLeverage
AccountLeverage
Returns leverage of the current account.
int AccountLeverage();
Returned value
Leverage of the current account.
Example:
Print("Account #",AccountNumber(), " leverage is ", AccountLeverage());
MQL4 Reference / Account Information / AccountMargin
AccountMargin
Returns margin value of the current account.
double AccountMargin();
Returned value
Margin value of the current account.
Example:
Print("Account margin ", AccountMargin());
MQL4 Reference / Account Information / AccountName
AccountName
Returns the current account name.
string AccountName();
Returned value
Name of the current account.
Example:
Print("Account name ", AccountName());
MQL4 Reference / Account Information / AccountNumber
AccountNumber
Returns the current account number.
int AccountNumber();
Returned value
The current account number.
Example:
Print("Account number ", AccountNumber());
MQL4 Reference / Account Information / AccountProfit
AccountProfit
Returns profit value of the current account.
double AccountProfit();
Returned value
Profit value of the current account.
Example:
Print("Account profit ", AccountProfit());
MQL4 Reference / Account Information / AccountServer
AccountServer
Returns the connected server name.
string AccountServer();
Returned value
Connected server name.
Example:
Print("Server name is ", AccountServer());
MQL4 Reference / Account Information / AccountStopoutLevel
AccountStopoutLevel
Returns the value of the Stop Out level.
int AccountStopoutLevel();
Returned value
The value of the Stop Out level.
Example:
Print("StopOut level = ", AccountStopoutLevel());
MQL4 Reference / Account Information / AccountStopoutMode
AccountStopoutMode
Returns the calculation mode for the Stop Out level.
int AccountStopoutMode();
Returned value
Returns the calculation mode for the Stop Out level.
Calculation mode can take the following values: 0 - calculation of
percentage ratio between margin and equity;
1 - comparison of the free margin level to the absolute value.
Example:
int level=AccountStopoutLevel();
if(AccountStopoutMode()==0)
Print("StopOut level = ", level, "%");
else
Print("StopOut level = ", level, " ", AccountCurrency());
MQL4 Reference / Checkup
State Checking
Functions that return parameters of the current state of
the client terminal
Function Action
GetLastError Returns the last error
IsStopped Returns true, if an mql4 program has
been commanded to stop its operation
UninitializeReason Returns the code of the reason for
deinitialization
MQLInfoInteger Returns an integer value of a
corresponding property of a running mql4
program
MQLInfoString Returns a string value of a corresponding
property of a running mql4 program
MQLSetInteger Sets the value of the MQL_CODEPAGE
property in an MQL4 program
environment
TerminalInfoInteger Returns an integer value of a
corresponding property of a running mql4
program
TerminalInfoDouble Returns a double value of a
corresponding property of a running mql4
program
TerminalInfoString Returns a string value of a corresponding
property of a running mql4 program
Function Action
Symbol Returns the name of a symbol of the
current chart
Period Returns the current chart timeframe
Digits Returns the number of decimal digits
determining the accuracy of the price
value of the current chart symbol
Point Returns the point size of the current
symbol in the quote currency
IsConnected Checks connection between client
terminal and server
IsDemo Checks if the Expert Advisor runs on a
demo account
IsDllsAllowed Checks if the DLL function call is allowed
for the Expert Advisor
IsExpertEnabled Checks if Expert Advisors are enabled for
running
IsLibrariesAllowed Checks if the Expert Advisor can call
library function
IsOptimization Checks if Expert Advisor runs in the
Strategy Tester optimization mode
IsTesting Checks if the Expert Advisor runs in the
testing mode
IsTradeAllowed Checks if the Expert Advisor is allowed to
trade and trading context is not busy
IsTradeContextBusy Returns the information about trade
context
IsVisualMode Checks if the Expert Advisor is tested in
visual mode
Function Action
TerminalCompany Returns the name of company owning the
client terminal
TerminalName Returns client terminal name
TerminalPath Returns the directory, from which the
client terminal was launched
MQL4 Reference / Checkup / GetLastError
GetLastError
Returns the contents of the
system variable _LastError.
int GetLastError();
Returned Value
Returns the value of the last error that occurred during
the execution of an mql4 program.
Note
After the function call, the contents of _LastError are
reset.
For convenience, trade errors are additionally listed in
the Trade Server Return Codes section.
MQL4 Reference / Checkup / IsStopped
IsStopped
Checks the forced shutdown of an mql4 program.
bool IsStopped();
Returned Value
Returns true, if the _StopFlag system variable contains a
value other than 0. A nonzero value is written into
_StopFlag, if a mql4 program has been commanded to
complete its operation. In this case, you must
immediately terminate the program, otherwise the
program will be completed forcibly from the outside
after 3 seconds.
MQL4 Reference / Checkup / UninitializeReason
UninitializeReason
Returns the code of a reason for deinitialization.
int UninitializeReason();
Returned Value
Returns the value of _UninitReason which is formed
before OnDeinit() is called. Value depends on the reasons
that led to deinitialization.
MQL4 Reference / Checkup / MQLInfoInteger
MQLInfoInteger
Returns the value of a corresponding property of a running mql4 program.
int MQLInfoInteger( int property_id // identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Can be one of values of the
ENUM_MQL_INFO_INTEGER enumeration.
Return Value
Value of int type.
MQL4 Reference / Checkup / MQLInfoString
MQLInfoString
Returns the value of a corresponding property of a running MQL4 program.
string MQLInfoString( int property_id // Identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Can be one of the ENUM_MQL_INFO_STRING
enumeration.
Return Value
Value of string type.
MQL4 Reference / Checkup / MQLSetInteger
MQLSetInteger
Sets the value of the MQL_CODEPAGE property in an MQL4 program environment.
void MQLSetInteger( int property_id // identifier of a property
int property_value // value to be set
);
Parameters
property_id
[in] Identifier of a property. Only MQL_CODEPAGE is supported, as other
properties cannot be changed.
property_value
[in] Value of property. Can be one of the Codepage constants.
Return Value
No return value
Note
The MQLSetInteger() function is intended to change current codepage in a
running MQL4 program. This can be useful when the client terminal sets the
default codepage that is different from the one used when the program was
compiled. For example, an MQL4 program was compiled on a computer with
Spanish locale, while it is running on a machine with Chinese locale.
When locales of machines the program was compiled and is running on are
different, you can get errors when printing messages or getting some values.
Such errors relate to the PrintFormat, Print, Comment, Alert, MessageBox,
SendFTP, SendMail, SendNotification, iCustom and other functions that use
object names, global variable names, etc. as their parameters.
To explicitly change a codepage to work with strings in a running program, you
need to call MQLSetInteger() with required codepage passed as its second
parameter. The function can be particularly useful for localization of messages
displayed to user.
See also
Use of a Codepage
MQL4 Reference / Checkup / TerminalInfoInteger
TerminalInfoInteger
Returns the value of a corresponding property of the mql4 program environment.
int TerminalInfoInteger( int property_id // identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Can be one of the values of the
ENUM_TERMINAL_INFO_INTEGER enumeration.
Return Value
Value of int type.
MQL4 Reference / Checkup / TerminalInfoDouble
TerminalInfoDouble
Returns the value of a corresponding property of the mql4 program environment.
double TerminalInfoDouble( int property_id // identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Can be one of the values of the
ENUM_TERMINAL_INFO_DOUBLE enumeration.
Return Value
Value of double type.
MQL4 Reference / Checkup / TerminalInfoString
TerminalInfoString
Returns the value of a corresponding property of the mql4 program environment.
The property must be of string type.
string TerminalInfoString( int property_id // identifier of a property
);
Parameters
property_id
[in] Identifier of a property. Can be one of the values of the
ENUM_TERMINAL_INFO_STRING enumeration.
Return Value
Value of string type.
MQL4 Reference / Checkup / Symbol
Symbol
Returns the name of a symbol of the current chart.
string Symbol();
Returned Value
Value of the _Symbol system variable, which stores the
name of the current chart symbol.
MQL4 Reference / Checkup / Period
Period
Returns the current chart timeframe.
int Period();
Returned Value
The contents of the _Period variable that contains the
value of the current chart timeframe.
See also
PeriodSeconds, Chart timeframes, Date and Time,
Visibility of objects
MQL4 Reference / Checkup / Digits
Digits
Returns the number of decimal digits determining the
accuracy of price of the current chart symbol.
int Digits();
Returned Value
The value of the _Digits variable which stores the
number of decimal digits determining the accuracy of
price of the current chart symbol.
MQL4 Reference / Checkup / Point
Point
Returns the point size of the current symbol in the quote
currency.
double Point();
Returned Value
The value of the _Point variable which stores the point
size of the current symbol in the quote currency.
MQL4 Reference / Checkup / IsConnected
IsConnected
Checks connection between client terminal and server.
bool IsConnected();
Returned value
It returns true if connection to the server was
successfully established, otherwise, it returns false.
Example:
if(!IsConnected()) {
Print("No connection!");
return(0);
}
// Expert body that needs the connection opened
// ...
MQL4 Reference / Checkup / IsDemo
IsDemo
Checks if the Expert Advisor runs on a demo account.
bool IsDemo();
Returned value
Returns true if the Expert Advisor runs on a demo account, otherwise returns false.
Example:
if(IsDemo()) Print("I work at a demo account"); else Print("I work at a real accou
MQL4 Reference / Checkup / IsDllsAllowed
IsDllsAllowed
Checks if the DLL function call is allowed for the Expert Advisor.
bool IsDllsAllowed();
Returned value
Returns true if the DLL function call is allowed for the Expert Advisor, otherwise returns
false.
Example:
#import "user32.dll" int MessageBoxA(int hWnd, string szText, string szCapt
...
...
if(IsDllsAllowed()==false)
{
Print("DLL call is not allowed. Experts cannot run.");
return(0);
}
// expert body that calls external DLL functions
MessageBoxA(0,"an message","Message",MB_OK);
See also
IsLibrariesAllowed(), IsTradeAllowed()
MQL4 Reference / Checkup / IsExpertEnabled
IsExpertEnabled
Checks if Expert Advisors are enabled for running.
bool IsExpertEnabled();
Returned value
Returns true if Expert Advisors are enabled for running,
otherwise returns false.
Example:
while(!IsStopped()) {
...
if(!IsExpertEnabled()) break;
}
MQL4 Reference / Checkup / IsLibrariesAllowed
IsLibrariesAllowed
Checks if the Expert Advisor can call library function.
bool IsLibrariesAllowed();
Returned value
Returns true if the Expert Advisor can call library
function, otherwise returns false.
Example:
#import "somelibrary.ex4" int somefunc();
...
...
if(IsLibrariesAllowed()==false)
{
Print("Library call is not allowed.");
return(0);
}
// expert body that calls external DLL functions
somefunc();
See also
IsDllSAllowed(), IsTradeAllowed()
MQL4 Reference / Checkup / IsOptimization
IsOptimization
Checks if Expert Advisor runs in the Strategy Tester
optimization mode.
bool IsOptimization();
Returned value
Returns true if Expert Advisor runs in the Strategy Tester
optimization mode, otherwise returns false.
Example:
if(IsOptimization()) return(0);
MQL4 Reference / Checkup / IsTesting
IsTesting
Checks if the Expert Advisor runs in the testing mode.
bool IsTesting();
Returned value
Returns true if the Expert Advisor runs in the testing
mode, otherwise returns false.
Example:
if(IsTesting()) Print("I am testing now");
MQL4 Reference / Checkup / IsTradeAllowed
IsTradeAllowed
Checks if the Expert Advisor is allowed to trade and trading
context is not busy.
bool IsTradeAllowed();
The second form of the function checks trade status for the
specified symbol in the specified time.
bool IsTradeAllowed( const string symbol // symbol
datetime tested_time // time
);
Parameters
symbol
[in] Symbol.
tested_time
[in] Time to check status.
Returned value
Returns true if the Expert Advisor is allowed to trade and
trading context is not busy, otherwise returns false.
Note:
OrderSend(), OrderClose(), OrderCloseBy(), OrderModify(),
OrderDelete() trading functions changing the state of a
trading account can be called only if trading by Expert
Advisors is allowed (the "Allow live trading" checkbox is
enabled in the Expert Advisor or script properties).
Example:
if(IsTradeAllowed()) Print("Trade allowed");
See also
IsDllsAllowed(), IsLibrariesAllowed(), IsTradeContextBusy()
MQL4 Reference / Checkup / IsTradeContextBusy
IsTradeContextBusy
Returns the information about trade context.
bool IsTradeContextBusy();
Returned value
Returns true if a thread for trading is occupied by another Expert Advisor,
otherwise returns false.
Example:
if(IsTradeContextBusy()) Print("Trade context is busy. Please wait");
MQL4 Reference / Checkup / IsVisualMode
IsVisualMode
Checks if the Expert Advisor is tested in visual mode.
bool IsVisualMode();
Returned value
Returns true if the Expert Advisor is tested with checked
"Visual Mode" button, otherwise returns false.
Example:
if(IsVisualMode()) Comment("Visual mode turned on");
MQL4 Reference / Checkup / TerminalCompany
TerminalCompany
Returns the name of company owning the client terminal.
string TerminalCompany();
Returned value
The name of company owning the client terminal.
Example:
Print("Company name is ",TerminalCompany());
See also
TerminalName(), TerminalPath()
MQL4 Reference / Checkup / TerminalName
TerminalName
Returns client terminal name.
string TerminalName();
Returned value
Client terminal name.
Example:
Print("Terminal name is ",TerminalName());
See also
TerminalCompany(), TerminalPath()
MQL4 Reference / Checkup / TerminalPath
TerminalPath
Returns the directory, from which the client terminal was
launched.
string TerminalPath();
Returned value
The directory, from which the client terminal was
launched.
Example:
Print("Working directory is ",TerminalPath());
See also
TerminalCompany(), TerminalName()
MQL4 Reference / Market Info
What's new in MQL5
Added the functions for working with the Depth of Market to
obtain exchange data. Visually, it is presented as a table of
Sell and Buy limit orders for traded assets. The format is the
same for currency pairs, stocks, metals and futures.
The Depth of Market featuring orders of market participants
is available in the trading platform. The Bid and Ask prices
are formed in the Market Depth based on the best orders.
These prices are shown in the Market Watch window.
Besides, the exchange provides prices and volumes of the
last executed deals (Last and Volume). The Last prices are
used for creating price charts and for displaying the Time &
Sales:
The new functions allow you to develop strategies based on
deals volume and order flow, create a custom Depth of
Market for manual trading and carry out automatic analysis
in real time.
Function Action
MarketBookAdd Open the Depth of Market for a specified
symbol and subscribe to receiving the Depth
of Market changes
MarketBookRelease Close the Depth of Market for a specified
symbol and unsubscribe from receiving the
Depth of Market changes
MarketBookGet Return the MqlBookInfo array of structures
containing data from the specified symbol's
Depth of Market
MQL4 Reference / Market Info / MarketInfo
MarketInfo
Returns various data about securities listed in the "Market Watch"
window.
double MarketInfo( string symbol, // symbol
int type // information type
);
Parameters
symbol
[in] Symbol name.
type
[in] Request identifier that defines the type of information to
be returned. Can be any of values of request identifiers.
Returned value
Returns various data about securities listed in the "Market
Watch" window. A part of information about the current
security is stored in predefined variables.
Example:
double vbid = MarketInfo("EURUSD",MODE_BID);
double vask = MarketInfo("EURUSD",MODE_ASK);
double vpoint = MarketInfo("EURUSD",MODE_POINT);
int vdigits = (int)MarketInfo("EURUSD",MODE_DIGITS);
int vspread = (int)MarketInfo("EURUSD",MODE_SPREAD);
See also
Symbol properties
MQL4 Reference / Market Info / SymbolsTotal
SymbolsTotal
Returns the number of available (selected in Market Watch or all) symbols.
int SymbolsTotal( bool selected // True - only symbols in MarketWatch
);
Parameters
selected
[in] Request mode. Can be true or false.
Return Value
If the 'selected' parameter is true, the function returns the number of symbols
selected in MarketWatch. If the value is false, it returns the total number of all
symbols.
MQL4 Reference / Market Info / SymbolName
SymbolName
Returns the name of a symbol.
string SymbolName( int pos, // number in the list
bool selected // true - only symbols in MarketWatch
);
Parameters
pos
[in] Order number of a symbol.
selected
[in] Request mode. If the value is true, the symbol is taken from
the list of symbols selected in MarketWatch. If the value is false,
the symbol is taken from the general list.
Return Value
Value of string type with the symbol name.
MQL4 Reference / Market Info / SymbolSelect
SymbolSelect
Selects a symbol in the Market Watch window or removes a
symbol from the window.
bool SymbolSelect( string name, // symbol name
bool select // add or remove
);
Parameters
name
[in] Symbol name.
select
[in] Switch. If the value is false, a symbol should be
removed from MarketWatch, otherwise a symbol should be
selected in this window. A symbol can't be removed if the
symbol chart is open, or there are open orders for this
symbol.
Return Value
In case of failure returns false.
Note
To get symbol data using functions for accessing timeseries
and indicators, make sure that the symbol exists in the
MarketWatch window. If the symbols is not available in
Market watch, enable it using the
SymbolSelect(symbol_name, true) function before you
request the data.
The symbol can be hidden from MarketWatch after 10
minutes since the last access to the symbol history, i.e.
since the call of functions like iOpen(), iHigh(), CopyTime()
etc. This is due to the fact that the terminal stores symbol
data for 10 minutes since the last access to them; after
that unused data are automatically deleted from the
terminal memory.
MQL4 Reference / Market Info / SymbolInfoDouble
SymbolInfoDouble
Returns the corresponding property of a specified symbol. There are 2 variants of the
function.
1. Immediately returns the property value.
double SymbolInfoDouble( string name, // symbol
ENUM_SYMBOL_INFO_DOUBLE prop_id // identifier of the property
);
Parameters
name
[in] Symbol name.
prop_id
[in] Identifier of a symbol property. The value can be one of the values of the
ENUM_SYMBOL_INFO_DOUBLE enumeration.
double_var
[out] Variable of double type receiving the value of the requested property.
Return Value
The value of double type. In case of execution failure, information about the error can
be obtained using GetLastError() function:
4106 symbol is not selected in "Market Watch" (not found in the list of available
ones),
4051 invalid identifier of a symbol property,
4024 internal error.
Note
It is recommended to use SymbolInfoTick() if the function is used for getting
information about the last tick. It may well be that not a single quote has appeared yet
since the terminal is connected to a trading account. In such a case, the requested
value will be indefinite.
In most cases, it is enough to use SymbolInfoTick() function allowing a user to receive
the values of Ask, Bid, Last, Volume and the time of the last tick's arrival during a
single call.
Example:
void OnTick()
{
//--- obtain spread from the symbol properties
bool spreadfloat=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD_FLOAT);
string comm=StringFormat("Spread %s = %I64d points\r\n",
spreadfloat?"floating":"fixed",
SymbolInfoInteger(Symbol(),SYMBOL_SPREAD));
//--- now let's calculate the spread by ourselves
double ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
double bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
double spread=ask-bid;
int spread_points=(int)MathRound(spread/SymbolInfoDouble(Symbol(),SYMBOL_POINT));
comm=comm+"Calculated spread = "+(string)spread_points+" points";
Comment(comm);
}
MQL4 Reference / Market Info / SymbolInfoInteger
SymbolInfoInteger
Returns the corresponding property of a specified symbol. There are 2 variants of the
function.
1. Immediately returns the property value.
long SymbolInfoInteger( string name, // symbol
ENUM_SYMBOL_INFO_INTEGER prop_id // identifier of a property
);
Parameters
name
[in] Symbol name.
prop_id
[in] Identifier of a symbol property. The value can be one of the values of the
ENUM_SYMBOL_INFO_INTEGER enumeration.
long_var
[out] Variable of the long type receiving the value of the requested property.
Return Value
The value of long type. In case of execution failure, information about the error can be
obtained using GetLastError() function:
4106 symbol is not selected in "Market Watch" (not found in the list of available
ones),
4051 invalid identifier of a symbol property,
4024 internal error.
Note
It is recommended to use SymbolInfoTick() if the function is used for getting
information about the last tick. It may well be that not a single quote has appeared yet
since the terminal is connected to a trading account. In such a case, the requested
value will be indefinite.
In most cases, it is enough to use SymbolInfoTick() function allowing a user to receive
the values of Ask, Bid, Last, Volume and the time of the last tick's arrival during a
single call.
Example:
void OnTick()
{
//--- obtain spread from the symbol properties
bool spreadfloat=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD_FLOAT);
string comm=StringFormat("Spread %s = %I64d points\r\n",
spreadfloat?"floating":"fixed",
SymbolInfoInteger(Symbol(),SYMBOL_SPREAD));
//--- now let's calculate the spread by ourselves
double ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
double bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
double spread=ask-bid;
int spread_points=(int)MathRound(spread/SymbolInfoDouble(Symbol(),SYMBOL_POINT));
comm=comm+"Calculated spread = "+(string)spread_points+" points";
Comment(comm);
}
MQL4 Reference / Market Info / SymbolInfoString
SymbolInfoString
Returns the corresponding property of a specified symbol. There are 2 variants of
the function.
1. Immediately returns the property value.
string SymbolInfoString( string name, // Symbol
ENUM_SYMBOL_INFO_STRING prop_id // Property identifier
);
Parameters
name
[in] Symbol name.
prop_id
[in] Identifier of a symbol property. The value can be one of the values of the
ENUM_SYMBOL_INFO_STRING enumeration.
string_var
[out] Variable of the string type receiving the value of the requested property.
Return Value
The value of string type. In case of execution failure, information about the
error can be obtained using GetLastError() function:
4106 symbol is not selected in "Market Watch" (not found in the list of
available ones),
4051 invalid identifier of a symbol property,
4024 internal error.
Note
It is recommended to use SymbolInfoTick() if the function is used for getting
information about the last tick. It may well be that not a single quote has
appeared yet since the terminal is connected to a trading account. In such a
case, the requested value will be indefinite.
In most cases, it is enough to use SymbolInfoTick() function allowing a user to
receive the values of Ask, Bid, Last, Volume and the time of the last tick's arrival
during a single call.
MQL4 Reference / Market Info / SymbolInfoTick
SymbolInfoTick
The function returns current prices of a specified symbol in a
variable of the MqlTick type.
bool SymbolInfoTick( string symbol, // symbol name
MqlTick& tick // reference to a structure
);
Parameters
symbol
[in] Symbol name.
tick
[out] Link to the structure of the MqlTick type, to which the
current prices and time of the last price update will be
placed.
Return Value
The function returns true if successful, otherwise returns false.
MQL4 Reference / Market Info / SymbolInfoSessionQuote
SymbolInfoSessionQuote
Allows receiving time of beginning and end of the specified quoting sessions for a
specified symbol and day of week.
bool SymbolInfoSessionQuote( string name, // symbol name
ENUM_DAY_OF_WEEK day_of_week, // day of the week
uint session_index, // session index
datetime& from, // time of the session beginning
datetime& to // time of the session end
);
Parameters
name
[in] Symbol name.
ENUM_DAY_OF_WEEK
[in] Day of the week, value of enumeration ENUM_DAY_OF_WEEK.
uint
[in] Ordinal number of a session, whose beginning and end time we want to receive.
Indexing of sessions starts with 0.
from
[out] Session beginning time in seconds from 00 hours 00 minutes, in the returned
value date should be ignored.
to
[out] Session end time in seconds from 00 hours 00 minutes, in the returned value
date should be ignored.
Return Value
If data for the specified session, symbol and day of the week are received, returns
true, otherwise returns false.
See also
Symbol Properties, TimeToStruct, Data Structures
MQL4 Reference / Market Info / SymbolInfoSessionTrade
SymbolInfoSessionTrade
Allows receiving time of beginning and end of the specified trading sessions for a
specified symbol and day of week.
bool SymbolInfoSessionTrade( string name, // symbol name
ENUM_DAY_OF_WEEK day_of_week, // day of the week
uint session_index, // session index
datetime& from, // session beginning time
datetime& to // session end time
);
Parameters
name
[in] Symbol name.
ENUM_DAY_OF_WEEK
[in] Day of the week, value of enumeration ENUM_DAY_OF_WEEK.
uint
[in] Ordinal number of a session, whose beginning and end time we want to receive.
Indexing of sessions starts with 0.
from
[out] Session beginning time in seconds from 00 hours 00 minutes, in the returned
value date should be ignored.
to
[out] Session end time in seconds from 00 hours 00 minutes, in the returned value
date should be ignored.
Return value
If data for the specified session, symbol and day of the week are received, returns
true, otherwise returns false.
See also
Symbol Properties, TimeToStruct, Data Structures
MQL4 Reference / Timeseries and Indicators Access
datetime ArrayNotSeries[];
ArraySetAsSeries(ArrayNotSeries,false);
ResetLastError();
copied=CopyTime(NULL,0,0,10,ArrayNotSeries);
if(copied<=0)
{
Print("The copy operation of the open time values for last 10 bars has failed")
return;
}
size=ArraySize(ArrayNotSeries);
for(int i=size-1;i>=0;i--)
{
Print("ArrayNotSeries["+i+"] =",ArrayNotSeries[i]);
}
As we see from the output, as the index of TimeAsSeries array increases, the time value
of the index decreases, i.e. we move from the present to the past. For the common
array ArrayNotSeries the result is different - as index grows, we move from past to
present.
See Also
ArrayIsDynamic(), ArrayGetAsSeries(), ArraySetAsSeries(), ArrayIsSeries()
MQL4 Reference / Timeseries and Indicators Access / Indexing Direction
in Arrays, Buffers and Timeseries
SeriesInfoInteger
Returns information about the state of historical data. There are 2 variants of function
calls.
Directly returns the property value.
long SeriesInfoInteger( string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
ENUM_SERIES_INFO_INTEGER prop_id // property identifier
);
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
prop_id
[in] Identifier of the requested property, value of the ENUM_SERIES_INFO_INTEGER
enumeration.
long_var
[out] Variable to which the value of the requested property is placed.
Return Value
In the first case, it returns value of the long type.
For the second case, it returns true, if the specified property is available and its value
has been placed into long_var variable, otherwise it returns false. For more details
about an error, call GetLastError().
Example:
void OnStart()
{
//---
Print("Total number of bars for the symbol-period at this moment = ",
SeriesInfoInteger(Symbol(),0,SERIES_BARS_COUNT));
Print("The first date in the history for the symbol-period on the server = ",
(datetime)SeriesInfoInteger(Symbol(),0,SERIES_SERVER_FIRSTDATE));
}
MQL4 Reference / Timeseries and Indicators Access / RefreshRates
RefreshRates
Refreshing of data in pre-defined variables and series arrays.
bool RefreshRates();
Parameters
None.
Returned value
True if the data updated, otherwise false.
Note
This function is used when Expert Advisor has been calculating for a long time and
needs data refreshing. Returns true if data are refreshed, otherwise returns false. The
only reason for data cannot be refreshed is that they are the current data of the client
terminal.
Expert Advisors and scripts operate with their own copy of history data. Data of the
current symbol are copied at the first launch of the expert or script. At each
subsequent launch of the expert (remember that script is executed only once and does
not depend on incoming ticks), the initial copy will be updated. One or more new ticks
can income while the Expert Advisor or script is operating, and data can become out of
date.
Example:
int ticket; while(true)
{
ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert comment",255,0,CLR_NONE)
if(ticket<=0)
{
int error=GetLastError();
//---- not enough money
if(error==134) break;
//---- 10 seconds wait
Sleep(10000);
//---- refresh price data
RefreshRates();
break;
}
else
{
OrderSelect(ticket,SELECT_BY_TICKET);
OrderPrint();
break;
}
}
MQL4 Reference / Timeseries and Indicators Access / CopyRates
CopyRates
Gets history data of MqlRates structure of a specified symbol-period in specified
quantity into the rates_array array. The elements ordering of the copied data is
from present to the past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic
array as a target array, because if the requested data count is less (or more) than
the length of the target array, function tries to reallocate the memory so that the
requested data fit entirely.
If you know the amount of data you need to copy, it should better be done to a
statically allocated buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or
as_series=false. Data will be copied so that the oldest element will be located at
the start of the physical memory allocated for the array. There are 3 variants of
function calls.
Call by the first position and the number of required elements
int CopyRates( string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
MqlRates rates_array[] // target array to copy
);
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_time
[in] Bar time for the first element to copy.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
rates_array[]
[out] Array of MqlRates type.
Return Value
Returns the number of copied elements or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server,
the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of
bars on the chart) is requested, the function will also return -1.
If requested timeseries are not yet built or they need to be downloaded from the
server, the function will immediately return -1.
When requesting data by the start date and the number of required elements,
only data whose date is less than (earlier) or equal to the date specified will be
returned. It means, the open time of any bar, for which value is returned
(volume, spread, value on the indicator buffer, prices Open, High, Low, Close or
open time Time) is always less or equal to the specified one.
When requesting data in a specified range of dates, only data from this interval
will be returned. The interval is set and counted up to seconds. It means, the
open time of any bar, for which value is returned (volume, spread, value on the
indicator buffer, prices Open, High, Low, Close or open time Time) is always
within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week
timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the
function will return 0, because the open time on a week timeframe is always
Sunday, but one week bar does not fall into the specified interval.
If you need to return value corresponding to the current uncompleted bar, you
can use the first form of call specifying start_pos=0 and count=1.
Example:
void OnStart()
{
//---
MqlRates rates[];
ArraySetAsSeries(rates,true);
int copied=CopyRates(Symbol(),0,0,100,rates);
if(copied>0)
{
Print("Bars copied: "+copied);
string format="open = %G, high = %G, low = %G, close = %G, volume = %d";
string out;
int size=fmin(copied,10);
for(int i=0;i<size;i++)
{
out=i+":"+TimeToString(rates[i].time);
out=out+" "+StringFormat(format,
rates[i].open,
rates[i].high,
rates[i].low,
rates[i].close,
rates[i].tick_volume);
Print(out);
}
}
else Print("Failed to get history data for the symbol ",Symbol());
}
See also
Structures and Classes, TimeToString, StringFormat
MQL4 Reference / Timeseries and Indicators Access / CopyTime
CopyTime
The function gets to time_array history data of bar opening time for the
specified symbol-period pair in the specified quantity. It should be noted
that elements ordering is from present to past, i.e., starting position of 0
means the current bar.
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] Bar time corresponding to the last element to copy.
time_array[]
[out] Array of datetime type.
Return Value
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the
server, the function returns -1. If data outside TERMINAL_MAXBARS
(maximal number of bars on the chart) is requested, the function will also
return -1.
If requested timeseries are not yet built or they need to be downloaded
from the server, the function will immediately return -1.
When requesting data by the start date and the number of required
elements, only data whose date is less than (earlier) or equal to the date
specified will be returned. It means, the open time of any bar, for which
value is returned (volume, spread, value on the indicator buffer, prices
Open, High, Low, Close or open time Time) is always less or equal to the
specified one.
When requesting data in a specified range of dates, only data from this
interval will be returned. The interval is set and counted up to seconds. It
means, the open time of any bar, for which value is returned (volume,
spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week
timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday
the function will return 0, because the open time on a week timeframe is
always Sunday, but one week bar does not fall into the specified interval.
If you need to return value corresponding to the current uncompleted bar,
you can use the first form of call specifying start_pos=0 and count=1.
See a detailed example of requesting history data in section Methods of
Object Binding. The script available in that section shows how to get the
values of indicator iFractals on the last 1000 bars and how to display the last
10 up and 10 down fractals on the chart. A similar technique can be used for
all indicators that have missing data and that are usually drawn using the
following styles:
DRAW_SECTION,
DRAW_ARROW,
DRAW_ZIGZAG,
DRAW_COLOR_SECTION,
DRAW_COLOR_ARROW,
DRAW_COLOR_ZIGZAG.
MQL4 Reference / Timeseries and Indicators Access / CopyOpen
CopyOpen
The function gets into open_array the history data of bar open prices for the
selected symbol-period pair in the specified quantity. It should be noted that
elements ordering is from present to past, i.e., starting position of 0 means
the current bar.
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] The start time for the last element to copy.
open_array[]
[out] Array of double type.
Return Value
Returns the number of element in the array or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the
server, the function returns -1. If data outside TERMINAL_MAXBARS
(maximal number of bars on the chart) is requested, the function will also
return -1.
If requested timeseries are not yet built or they need to be downloaded
from the server, the function will immediately return -1.
When requesting data by the start date and the number of required
elements, only data whose date is less than (earlier) or equal to the date
specified will be returned. It means, the open time of any bar, for which
value is returned (volume, spread, value on the indicator buffer, prices
Open, High, Low, Close or open time Time) is always less or equal to the
specified one.
When requesting data in a specified range of dates, only data from this
interval will be returned. The interval is set and counted up to seconds. It
means, the open time of any bar, for which value is returned (volume,
spread, value on the indicator buffer, prices Open, High, Low, Close or open
time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week
timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday
the function will return 0, because the open time on a week timeframe is
always Sunday, but one week bar does not fall into the specified interval.
If you need to return value corresponding to the current uncompleted bar,
you can use the first form of call specifying start_pos=0 and count=1.
MQL4 Reference / Timeseries and Indicators Access / CopyHigh
CopyHigh
The function gets into high_array the history data of highest bar prices for the
selected symbol-period pair in the specified quantity. It should be noted that
elements ordering is from present to past, i.e., starting position of 0 means the
current bar.
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
high_array[]
[out] Array of double type.
Return Value
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server,
the function returns -1. If data outside TERMINAL_MAXBARS (maximal number of
bars on the chart) is requested, the function will also return -1.
If requested timeseries are not yet built or they need to be downloaded from the
server, the function will immediately return -1.
When requesting data by the start date and the number of required elements,
only data whose date is less than (earlier) or equal to the date specified will be
returned. It means, the open time of any bar, for which value is returned
(volume, spread, value on the indicator buffer, prices Open, High, Low, Close or
open time Time) is always less or equal to the specified one.
When requesting data in a specified range of dates, only data from this interval
will be returned. The interval is set and counted up to seconds. It means, the
open time of any bar, for which value is returned (volume, spread, value on the
indicator buffer, prices Open, High, Low, Close or open time Time) is always
within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week
timeframe specifying start_time=Last_Tuesday and stop_time=Last_Friday the
function will return 0, because the open time on a week timeframe is always
Sunday, but one week bar does not fall into the specified interval.
If you need to return value corresponding to the current uncompleted bar, you
can use the first form of call specifying start_pos=0 and count=1.
Example:
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property description "An example for output of the High[i] and Low[i]"
#property description "for a random chosen bars"
double High[],Low[];
//+------------------------------------------------------------------+
//| Get Low for specified bar index |
//+------------------------------------------------------------------+
double iLow(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double low=0;
ArraySetAsSeries(Low,true);
int copied=CopyLow(symbol,timeframe,0,Bars(symbol,timeframe),Low);
if(copied>0 && index<copied) low=Low[index];
return(low);
}
//+------------------------------------------------------------------+
//| Get the High for specified bar index |
//+------------------------------------------------------------------+
double iHigh(string symbol,ENUM_TIMEFRAMES timeframe,int index)
{
double high=0;
ArraySetAsSeries(High,true);
int copied=CopyHigh(symbol,timeframe,0,Bars(symbol,timeframe),High);
if(copied>0 && index<copied) high=High[index];
return(high);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- on every tick we output the High and Low values for the bar with index,
//--- that is equal to the second, on which tick arrived
datetime t=TimeCurrent();
int sec=t%60;
printf("High[%d] = %G Low[%d] = %G",
sec,iHigh(Symbol(),0,sec),
sec,iLow(Symbol(),0,sec));
}
MQL4 Reference / Timeseries and Indicators Access / CopyLow
CopyLow
The function gets into low_array the history data of minimal bar
prices for the selected symbol-period pair in the specified quantity.
It should be noted that elements ordering is from present to past,
i.e., starting position of 0 means the current bar.
Parameters
symbol_name
[in] Symbol.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] Bar time, corresponding to the first element to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
low_array[]
[out] Array of double type.
Return Value
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data
on the server, the function returns -1. If data outside
TERMINAL_MAXBARS (maximal number of bars on the chart) is
requested, the function will also return -1.
If requested timeseries are not yet built or they need to be
downloaded from the server, the function will immediately return
-1.
When requesting data by the start date and the number of required
elements, only data whose date is less than (earlier) or equal to the
date specified will be returned. It means, the open time of any bar,
for which value is returned (volume, spread, value on the indicator
buffer, prices Open, High, Low, Close or open time Time) is always
less or equal to the specified one.
When requesting data in a specified range of dates, only data from
this interval will be returned. The interval is set and counted up to
seconds. It means, the open time of any bar, for which value is
returned (volume, spread, value on the indicator buffer, prices
Open, High, Low, Close or open time Time) is always within the
requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on
a week timeframe specifying start_time=Last_Tuesday and
stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does
not fall into the specified interval.
If you need to return value corresponding to the current
uncompleted bar, you can use the first form of call specifying
start_pos=0 and count=1.
See also
CopyHigh
MQL4 Reference / Timeseries and Indicators Access / CopyClose
CopyClose
The function gets into close_array the history data of bar close prices for
the selected symbol-period pair in the specified quantity. It should be
noted that elements ordering is from present to past, i.e., starting
position of 0 means the current bar.
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
close_array[]
[out] Array of double type.
Return Value
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on
the server, the function returns -1. If data outside TERMINAL_MAXBARS
(maximal number of bars on the chart) is requested, the function will
also return -1.
If requested timeseries are not yet built or they need to be downloaded
from the server, the function will immediately return -1.
When requesting data by the start date and the number of required
elements, only data whose date is less than (earlier) or equal to the
date specified will be returned. It means, the open time of any bar, for
which value is returned (volume, spread, value on the indicator buffer,
prices Open, High, Low, Close or open time Time) is always less or equal
to the specified one.
When requesting data in a specified range of dates, only data from this
interval will be returned. The interval is set and counted up to seconds.
It means, the open time of any bar, for which value is returned (volume,
spread, value on the indicator buffer, prices Open, High, Low, Close or
open time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a
week timeframe specifying start_time=Last_Tuesday and
stop_time=Last_Friday the function will return 0, because the open
time on a week timeframe is always Sunday, but one week bar does not
fall into the specified interval.
If you need to return value corresponding to the current uncompleted
bar, you can use the first form of call specifying start_pos=0 and
count=1.
MQL4 Reference / Timeseries and Indicators Access / CopyTickVolume
CopyTickVolume
The function gets into volume_array the history data of tick volumes for the selected
symbol-period pair in the specified quantity. It should be noted that elements ordering is
from present to past, i.e., starting position of 0 means the current bar.
When copying the yet unknown amount of data, it is recommended to use dynamic array
as a target array, because if the requested data count is less (or more) than the length of
the target array, function tries to reallocate the memory so that the requested data fit
entirely.
If you know the amount of data you need to copy, it should better be done to a statically
allocated buffer, in order to prevent the allocation of excessive memory.
No matter what is the property of the target array - as_series=true or as_series=false.
Data will be copied so that the oldest element will be located at the start of the physical
memory allocated for the array. There are 3 variants of function calls.
Call by the first position and the number of required elements
int CopyTickVolume( string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe, // period
int start_pos, // start position
int count, // data count to copy
long volume_array[] // target array for tick volumes
);
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_pos
[in] The start position for the first element to copy.
count
[in] Data count to copy.
start_time
[in] The start time for the first element to copy.
stop_time
[in] Bar time, corresponding to the last element to copy.
volume_array[]
[out] Array of long type.
Return Value
Returns the copied data count or -1 in case of an error.
Note
If the whole interval of requested data is out of the available data on the server, the
function returns -1. If data outside TERMINAL_MAXBARS (maximal number of bars on
the chart) is requested, the function will also return -1.
If requested timeseries are not yet built or they need to be downloaded from the
server, the function will immediately return -1.
When requesting data by the start date and the number of required elements, only
data whose date is less than (earlier) or equal to the date specified will be returned. It
means, the open time of any bar, for which value is returned (volume, spread, value on
the indicator buffer, prices Open, High, Low, Close or open time Time) is always less or
equal to the specified one.
When requesting data in a specified range of dates, only data from this interval will be
returned. The interval is set and counted up to seconds. It means, the open time of any
bar, for which value is returned (volume, spread, value on the indicator buffer, prices
Open, High, Low, Close or open time Time) is always within the requested interval.
Thus, if the current day is Saturday, at the attempt to copy data on a week timeframe
specifying start_time=Last_Tuesday and stop_time=Last_Friday the function will return
0, because the open time on a week timeframe is always Sunday, but one week bar
does not fall into the specified interval.
If you need to return value corresponding to the current uncompleted bar, you can use
the first form of call specifying start_pos=0 and count=1.
Example:
#property strict
#property indicator_separate_window
#property indicator_buffers 1
//---- plot TickVolume
#property indicator_label1 "TickVolume"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 C'143,188,139'
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int bars=3000;
//--- indicator buffers
double TickVolumeBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- indicator buffers mapping
SetIndexBuffer(0,TickVolumeBuffer,INDICATOR_DATA);
IndicatorSetInteger(INDICATOR_DIGITS,0);
//---
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
if(prev_calculated==0)
{
long timeseries[];
ArraySetAsSeries(timeseries,true);
int copied=CopyTickVolume(Symbol(),0,0,bars,timeseries);
for(int i=rates_total-copied-1;i>copied-1;i--) TickVolumeBuffer[i]=0.0;
for(int i=0;i<copied;i++) TickVolumeBuffer[i]=(double)timeseries[i];
Print("We have received the following number of TickVolume values: "+(string)co
}
else
{
long timeseries[];
int copied=CopyTickVolume(Symbol(),0,0,1,timeseries);
TickVolumeBuffer[0]=(double)timeseries[0];
}
//--- return value of prev_calculated for next call
return(rates_total);
}
MQL4 Reference / Timeseries and Indicators Access / Bars
Bars
Returns the number of bars count in the history for a specified
symbol and period. There are 2 variants of functions calls.
Request all of the history bars
int Bars( string symbol_name, // symbol name
ENUM_TIMEFRAMES timeframe // period
);
Parameters
symbol_name
[in] Symbol name.
timeframe
[in] Period.
start_time
[in] Bar time corresponding to the first element.
stop_time
[in] Bar time corresponding to the last element.
Return Value
If the start_time and stop_time parameters are defined, the
function returns the number of bars in the specified time
interval, otherwise it returns the total number of bars.
Note
If data for the timeseries with specified parameters are not
formed in the terminal by the time of the Bars() function call, or
data of the timeseries are not synchronized with a trade server
by the moment of the function call, the function returns a zero
value.
See also
Predefined variable Bars, iBars
MQL4 Reference / Timeseries and Indicators Access / iBars
iBars
Returns the number of bars on the specified chart.
int iBars( string symbol, // symbol
int timeframe // timeframe
);
Parameters
symbol
[in] Symbol the data of which should be used to calculate indicator.
NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration
values. 0 means the current chart timeframe.
Returned value
The number of bars on the specified chart.
Note
For the current chart, the information about the amount of bars is in the
Bars predefined variable.
Example:
Print("Bar count on the 'EURUSD,H1' is ",iBars("EURUSD",PERIOD_H1));
MQL4 Reference / Timeseries and Indicators Access / iBarShift
iBarShift
Search for a bar by its time. The function returns the index of the bar which
covers the specified time.
int iBarShift( string symbol, // symbol
int timeframe, // timeframe
datetime time, // time
bool exact=false // mode
);
Parameters
symbol
[in] Symbol name. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0
means the current chart timeframe.
time
[in] Time value for searching.
exact=false
[in] Return mode when the bar is not found (false - iBarShift returns the
nearest, true - iBarShift returns -1).
Returned value
Index of the bar which covers the specified time. If there is no bar for the
specified time (history "gap"), the function will return -1 or the nearest bar
index (depending on exact parameter).
Example:
datetime some_time=D'2004.03.21 12:00';
int shift=iBarShift("EURUSD",PERIOD_M1,some_time);
Print("index of the bar for the time ",TimeToStr(some_time)," is ",shift);
MQL4 Reference / Timeseries and Indicators Access / iClose
iClose
Returns Close price value for the bar of specified symbol with timeframe and shift.
double iClose( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
Parameters
symbol
[in] Symbol name. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Close price value for the bar of specified symbol with timeframe and shift. If local
history is empty (not loaded), function returns 0. To check errors, one has to call the
GetLastError() function.
Note
For the current chart, the information about close prices is in the Close[] predefined
array.
Example:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,0),", ", iOpen("USDCH
iHigh("USDCHF",PERIOD_H1,0),", ", iLow("USDCHF
iClose("USDCHF",PERIOD_H1,0),", ", iVolume("USD
MQL4 Reference / Timeseries and Indicators Access / iHigh
iHigh
Returns High price value for the bar of specified symbol with timeframe and shift.
double iHigh( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
Parameters
symbol
[in] Symbol name. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
High value for the bar of specified symbol with timeframe and shift. If local history is
empty (not loaded), function returns 0. To check errors, one has to call the
GetLastError() function.
Note
For the current chart, the information about high prices is in the High[] predefined
array.
Example:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,0),", ", iOpen("USDCH
iHigh("USDCHF",PERIOD_H1,0),", ", iLow("USDCHF
iClose("USDCHF",PERIOD_H1,0),", ", iVolume("USD
MQL4 Reference / Timeseries and Indicators Access / iHighest
iHighest
Returns the shift of the maximum value over a specific number of bars
depending on type.
int iHighest( string symbol, // symbol
int timeframe, // timeframe
int type, // timeseries
int count, // cont
int start // start
);
Parameters
symbol
[in] Symbol the data of which should be used for search. NULL means the
current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0
means the current chart timeframe.
type
[in] Series array identifier. It can be any of the Series array identifier
enumeration values.
count=WHOLE_ARRAY
[in] Number of bars (in direction from the start bar to the back one) on which
the search is carried out.
start=0
[in] Shift showing the bar, relative to the current bar, that the data should be
taken from.
Returned value
The shift of the maximum value over a specific number of bars or -1 if error. To
check errors, one has to call the GetLastError() function.
Example:
double val;
//--- calculating the highest value on the 20 consecutive bars in the range
//--- from the 4th to the 23rd index inclusive on the current chart
int val_index=iHighest(NULL,0,MODE_HIGH,20,4);
if(val_index!=-1) val=High[val_index];
else PrintFormat("Error in call iHighest. Error code=%d",GetLastError());
MQL4 Reference / Timeseries and Indicators Access / iLow
iLow
Returns Low price value for the bar of indicated symbol with timeframe and shift.
double iLow( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
Parameters
symbol
[in] Symbol name. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Low price value for the bar of specified symbol with timeframe and shift. If local
history is empty (not loaded), function returns 0. To check errors, one has to call the
GetLastError() function.
Note
For the current chart, the information about low prices is in the Low[] predefined
array.
Example:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,0),", ", iOpen("USDCH
iHigh("USDCHF",PERIOD_H1,0),", ", iLow("USDCHF
iClose("USDCHF",PERIOD_H1,0),", ", iVolume("USD
MQL4 Reference / Timeseries and Indicators Access / iLowest
iLowest
Returns the shift of the lowest value over a specific number of bars depending
on type.
int iLowest( string symbol, // symbol
int timeframe, // timeframe
int type, // timeseries id
int count, // count
int start // starting index
);
Parameters
symbol
[in] Symbol name. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0
means the current chart timeframe.
type
[in] Series array identifier. It can be any of the Series array identifier
enumeration values.
count=WHOLE_ARRAY
[in] Number of bars (in direction from the start bar to the back one) on
which the search is carried out.
start=0
[in] Shift showing the bar, relative to the current bar, that the data should
be taken from.
Returned value
The shift of the lowest value over a specific number of bars or -1 if error. To
check errors, one has to call the GetLastError() function.
Example:
double val;
//--- calculating the lowest value on the 10 consequtive bars in the range
//--- from the 10th to the 19th index inclusive on the current chart
int val_index=iLowest(NULL,0,MODE_LOW,10,10);
if(val_index!=-1) val=Low[val_index];
else PrintFormat("Error in iLowest. Error code=%d",GetLastError());
MQL4 Reference / Timeseries and Indicators Access / iOpen
iOpen
Returns Open price value for the bar of specified symbol with timeframe and shift.
double iOpen( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
Parameters
symbol
[in] Symbol name. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Open price value for the bar of specified symbol with timeframe and shift or 0 if error.
To check errors, one has to call the GetLastError() function.
Note
For the current chart, the information about open prices is in the Open[] predefined
array.
Example:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,0),", ", iOpen("USDCH
iHigh("USDCHF",PERIOD_H1,0),", ", iLow("USDCHF
iClose("USDCHF",PERIOD_H1,0),", ", iVolume("USD
MQL4 Reference / Timeseries and Indicators Access / iTime
iTime
Returns Time value for the bar of specified symbol with timeframe and shift.
datetime iTime( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
Parameters
symbol
[in] Symbol name. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Time value for the bar of specified symbol with timeframe and shift. If local history is
empty (not loaded), function returns 0. To check errors, one has to call the
GetLastError() function.
Note
For the current chart, the information about open bar times is in the Time[] predefined
array.
Example:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,0),", ", iOpen("USDCH
iHigh("USDCHF",PERIOD_H1,0),", ", iLow("USDCHF
iClose("USDCHF",PERIOD_H1,0),", ", iVolume("USD
MQL4 Reference / Timeseries and Indicators Access / iVolume
iVolume
Returns Tick Volume value for the bar of specified symbol with timeframe and shift.
long iVolume( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
Parameters
symbol
[in] Symbol name. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Tick volume value for the bar of specified symbol with timeframe and shift. If local
history is empty (not loaded), function returns 0. To check errors, one has to call the
GetLastError() function.
Note
For the current chart, the information about bars tick volumes is in the Volume[]
predefined array.
Example:
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,0),", ", iOpen("USDCH
iHigh("USDCHF",PERIOD_H1,0),", ", iLow("USDCHF
iClose("USDCHF",PERIOD_H1,0),", ", iVolume("USD
MQL4 Reference / Chart Operations
Chart Operations
These are functions for working with charts. All chart
operations are allowed in Expert Advisors and scripts only.
The functions defining the chart properties are actually
used for sending change commands to the chart. If these
functions are executed successfully, the command is
included in the common queue of the chart events. The
changes are implemented to the chart when handling the
queue of the chart events.
Thus, do not expect an immediate visual update of the
chart after calling these functions. Generally, the chart is
updated automatically by the terminal following the
change events - a new quote arrival, resizing the chart
window, etc. Use ChartRedraw() function to forcefully
update the chart.
Function Action
ChartApplyTemplate Applies a specific template from a
specified file to the chart
ChartSaveTemplate Saves current chart settings in a
template with a specified name
ChartWindowFind Returns the number of a subwindow
where an indicator is drawn
ChartTimePriceToXY Converts the coordinates of a chart
from the time/price representation
to the X and Y coordinates
Function Action
ChartXYToTimePrice Converts the X and Y coordinates on
a chart to the time and price values
ChartOpen Opens a new chart with the
specified symbol and period
ChartFirst Returns the ID of the first chart of
the client terminal
ChartNext Returns the chart ID of the chart
next to the specified one
ChartClose Closes the specified chart
ChartSymbol Returns the symbol name of the
specified chart
ChartPeriod Returns the period value of the
specified chart
ChartRedraw Calls a forced redrawing of a
specified chart
ChartSetDouble Sets the double value for a
corresponding property of the
specified chart
ChartSetInteger Sets the integer value (datetime,
int, color, bool or char) for a
corresponding property of the
specified chart
ChartSetString Sets the string value for a
corresponding property of the
specified chart
ChartGetDouble Returns the double value property of
the specified chart
Function Action
ChartGetInteger Returns the integer value property
of the specified chart
ChartGetString Returns the string value property of
the specified chart
ChartNavigate Performs shift of the specified chart
by the specified number of bars
relative to the specified position in
the chart
ChartID Returns the ID of the current chart
ChartIndicatorDelete Removes an indicator with a
specified name from the specified
chart window
ChartIndicatorName Returns the short name of the
indicator by the number in the
indicators list on the specified chart
window
ChartIndicatorsTotal Returns the number of all indicators
applied to the specified chart
window.
ChartWindowOnDropped Returns the number (index) of the
chart subwindow the Expert Advisor
or script has been dropped to
ChartPriceOnDropped Returns the price coordinate of the
chart point the Expert Advisor or
script has been dropped to
ChartTimeOnDropped Returns the time coordinate of the
chart point the Expert Advisor or
script has been dropped to
Function Action
ChartXOnDropped Returns the X coordinate of the
chart point the Expert Advisor or
script has been dropped to
ChartYOnDropped Returns the Y coordinate of the
chart point the Expert Advisor or
script has been dropped to
ChartSetSymbolPeriod Changes the symbol value and a
period of the specified chart
ChartScreenShot Provides a screenshot of the chart of
its current state in a gif format
Period Returns timeframe of the current
chart
Symbol Returns a text string with the name
of the current financial instrument
WindowBarsPerChart Returns the amount of bars visible
on the chart
WindowExpertName Returns the name of the executed
Expert Advisor, script, custom
indicator, or library
WindowFind Returns the window index containing
this specified indicator
WindowFirstVisibleBar Returns index of the first visible bar
in the current chart window
WindowHandle Returns the system handle of the
chart window
WindowIsVisible Returns the visibility flag of the
chart subwindow
Function Action
WindowOnDropped Returns the window index where
Expert Advisor, custom indicator or
script was dropped
WindowPriceMax Returns the maximal value of the
vertical scale of the specified
subwindow of the current chart
WindowPriceMin Returns the minimal value of the
vertical scale of the specified
subwindow of the current chart
WindowPriceOnDropped Returns the price of the chart point
where Expert Advisor or script was
dropped
WindowRedraw Redraws the current chart forcedly
WindowScreenShot Saves current chart screen shot as a
GIF, PNG or BMP file depending on
specified extension
WindowTimeOnDropped Returns the time of the chart point
where Expert Advisor or script was
dropped
WindowsTotal Returns total number of indicator
windows on the chart
WindowXOnDropped Returns the value at X axis in pixels
for the chart window client area
point at which the Expert Advisor or
script was dropped
WindowYOnDropped Returns the value at Y axis in pixels
for the chart window client area
point at which the Expert Advisor or
script was dropped
MQL4 Reference / Chart Operations / ChartApplyTemplate
ChartApplyTemplate
Applies a specific template from a specified file to the chart. The command is added to
chart message queue and executed only after all previous commands have been
processed.
bool ChartApplyTemplate( long chart_id, // Chart ID
const string filename // Template file name
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
filename
[in] The name of the file containing the template.
Return Value
Returns true if the command has been added to chart queue, otherwise false. To get
error details use the GetLastError() function.
Note
The Expert Advisor will be unloaded and will not be able to continue operating in case
of successful loading of a new template to the chart it is attached to.
Live Trading and DLL Imports
Users can allow or forbid the following actions for an mql4 program launched on a
chart:
1. Performing trade operations (live trading),
2. DLL imports.
The terminal allows saving the configured chart as a template with all indicators and
Expert Advisors launched on it. Thus, it is possible to quickly apply template settings to
all other charts. When saving the template, permissions of the launched programs (live
trading and DLL imports) are also saved. When applying the template to the chart,
these permissions may be limited due to security reasons:
Live trading and DLL imports permissions cannot be extended for the Expert Advisors
launched by applying the template using ChartApplyTemplate() function.
For example:
//--- search for a template in terminal_data_directory\MQL4\
ChartApplyTemplate(0,"\\first_template.tpl"))
Templates are not resources, they cannot be included into an executable EX4 file.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- example of applying template, located in \MQL4\Files
if(FileIsExist("my_template.tpl"))
{
Print("The file my_template.tpl found in \Files'");
//--- apply template
if(ChartApplyTemplate(0,"\\Files\\my_template.tpl"))
{
Print("The template 'my_template.tpl' applied successfully");
}
else
Print("Failed to apply 'my_template.tpl', error code ",GetLastError());
}
else
{
Print("File 'my_template.tpl' not found in "
+TerminalInfoString(TERMINAL_PATH)+"\\MQL4\\Files");
}
}
See also
Resources
MQL4 Reference / Chart Operations / ChartSaveTemplate
ChartSaveTemplate
Saves current chart settings in a template with a specified name. The command is added
to chart message queue and executed only after all previous commands have been
processed.
bool ChartSaveTemplate( long chart_id, // Chart ID
const string filename // Filename to save the template
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
filename
[in] The filename to save the template. The ".tpl" extension will be added to the
filename automatically; there is no need to specify it. The template is saved in
data_folder\templates\ and can be used for manual application in the terminal. If a
template with the same filename already exists, the contents of this file will be
overwritten.
Return Value
Returns true if the command has been added to chart queue, otherwise false. To get
error details use the GetLastError() function.
Note
Using templates, you can save chart settings with all applied indicators and graphical
objects, to then apply it to another chart.
Example:
//+------------------------------------------------------------------+
//| Test_ChartSaveTemplate.mq4 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property script_show_inputs
//--- input parameters
input string symbol="GBPUSD"; // The symbol of a new chart
input ENUM_TIMEFRAMES period=PERIOD_H3; // The timeframe of a new chart
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- First attach indicators to the chart
int handle;
//--- Prepare the indicator for use
if(!PrepareZigzag(NULL,0,handle)) return; // Failed, so exit
//--- Attach the indicator to the current chart, but in a separate window.
if(!ChartIndicatorAdd(0,1,handle))
{
PrintFormat("Failed to attach to chart %s/%s an indicator with the handle=%d. E
_Symbol,
EnumToString(_Period),
handle,
GetLastError());
//--- Terminate the program operation
return;
}
//--- Refresh the chart to see the indicator
ChartRedraw();
//--- Find the last two last fractures of the zigzag
double two_values[];
datetime two_times[];
if(!GetLastTwoFractures(two_values,two_times,handle))
{
PrintFormat("Failed to find two last fractures in the Zigzag!");
//--- Terminate the program operation
return;
}
//--- Now attach a standard deviation channel
string channel="StdDeviation Channel";
if(!ObjectCreate(0,channel,OBJ_STDDEVCHANNEL,0,two_times[1],0))
{
PrintFormat("Failed to create object %s. Error code %d",
EnumToString(OBJ_STDDEVCHANNEL),GetLastError());
return;
}
else
{
//--- The channel has been created, define the second point
ObjectSetInteger(0,channel,OBJPROP_TIME,1,two_times[0]);
//--- Set a tooltip text for the channel
ObjectSetString(0,channel,OBJPROP_TOOLTIP,"Demo from MQL4 Help");
//--- Refresh the chart
ChartRedraw();
}
//--- Save the result in a template
ChartSaveTemplate(0,"StdDevChannelOnZigzag");
//--- Open a new chart and apply a saved template to it
long new_chart=ChartOpen(symbol,period);
//--- Enable tooltips for graphical objects
ChartSetInteger(new_chart,CHART_SHOW_OBJECT_DESCR,true);
if(new_chart!=0)
{
//--- Apply the saved template to a chart
ChartApplyTemplate(new_chart,"StdDevChannelOnZigzag");
}
Sleep(10000);
}
//+------------------------------------------------------------------+
//| Creates a zigzag handle and ensures readiness of its data |
//+------------------------------------------------------------------+
bool PrepareZigzag(string sym,ENUM_TIMEFRAMES tf,int &h)
{
ResetLastError();
//--- The Zigzag indicator must be located in terminal_data_folder\MQL4\Examples
h=iCustom(sym,tf,"Examples\\Zigzag");
if(h==INVALID_HANDLE)
{
PrintFormat("%s: Failed to create the handle of the Zigzag indicator. Error cod
__FUNCTION__,GetLastError());
return false;
}
//--- When creating an indicator handle, it requires time to calculate values
int k=0; // The number of attempts to wait for the indicator calculation
//--- Wait for the calculation in a loop, pausing to 50 milliseconds if the calculati
while(BarsCalculated(h)<=0)
{
k++;
//--- Show the number of attempts
PrintFormat("%s: k=%d",__FUNCTION__,k);
//--- Wait 50 milliseconds to wait until the indicator is calculated
Sleep(50);
//--- If more than 100 attempt, then something is wrong
if(k>100)
{
//--- Report a problem
PrintFormat("Failed to calculate the indicator for %d attempts!");
//--- Terminate the program operation
return false;
}
}
//--- Everything is ready, the indicator is created and values are calculated
return true;
}
//+------------------------------------------------------------------+
//| Searches for the last 2 zigzag fractures and places to arrays |
//+------------------------------------------------------------------+
bool GetLastTwoFractures(double &get_values[],datetime &get_times[],int handle)
{
double values[]; // An array for the values of the zigzag
datetime times[]; // An array to get time
int size=100; // Size of the array
ResetLastError();
//--- Copy the last 100 values of the indicator
int copied=CopyBuffer(handle,0,0,size,values);
//--- Check the number of values copied
if(copied<100)
{
PrintFormat("%s: Failed to copy %d values of the indicator with the handle=%d.
__FUNCTION__,size,handle,GetLastError());
return false;
}
//--- Define the order of access to the array as in a timeseries
ArraySetAsSeries(values,true);
//--- Write here the numbers of bars, in which fractures were found
int positions[];
//--- Set array sizes
ArrayResize(get_values,3); ArrayResize(get_times,3); ArrayResize(positions,3);
//--- Counters
int i=0,k=0;
//--- Start to search for fractures
while(i<100)
{
double v=values[i];
//--- We are not interested in empty values
if(v!=0.0)
{
//--- Remember the bar number
positions[k]=i;
//--- Remember the value of a zigzag on the fracture
get_values[k]=values[i];
PrintFormat("%s: Zigzag[%d]=%G",__FUNCTION__,i,values[i]);
//--- Increase the counter
k++;
//--- If two fractures found, break the loop
if(k>2) break;
}
i++;
}
//--- Define the order of access to the arrays as in a timeseries
ArraySetAsSeries(times,true); ArraySetAsSeries(get_times,true);
if(CopyTime(_Symbol,_Period,0,size,times)<=0)
{
PrintFormat("%s: Failed to copy %d values from CopyTime(). Error code %d",
__FUNCTION__,size,GetLastError());
return false;
}
//--- Open the bar open time, on which the last 2 fractures occurred
get_times[0]=times[positions[1]];// The last but one value will be written as the
get_times[1]=times[positions[2]];// The value third from the end will be the secon
PrintFormat("%s: first=%s, second=%s",__FUNCTION__,TimeToString(get_times[1]),Tim
//--- Successful
return true;
}
See also
ChartApplyTemplate(), Resources
MQL4 Reference / Chart Operations / ChartWindowFind
ChartWindowFind
The function returns the number of a subwindow where an indicator is drawn. There are
2 variants of the function.
1. The function searches in the indicated chart for the subwindow with the specified
"short name" of the indicator (the short name is displayed in the left top part of the
subwindow), and it returns the subwindow number in case of success.
int ChartWindowFind( long chart_id, // chart identifier
string indicator_shortname // short indicator name, see INDICATOR_SHORTNA
);
2. The function must be called from a custom indicator. It returns the number of the
subwindow where the indicator is working.
int ChartWindowFind();
Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
indicator_shortname
[in] Short name of the indicator.
Return Value
Subwindow number in case of success. In case of failure the function returns -1.
Note
If the second variant of the function (without parameters) is called from a script or
Expert Advisor, the function returns -1.
Don't mix up the short name of an indicator and a file name, which is specified when an
indicator is created using iCustom() function. If the indicator's short name is not set
explicitly, then the name of the file containing the source code of the indicator, is
specified in it during compilation.
It is important to correctly form the short name of an indicator, which is recorded in
the INDICATOR_SHORTNAME property using the IndicatorSetString() function. It is
recommended that the short name contains values of the indicator's input parameters,
because the indicator deleted from a chart in the ChartIndicatorDelete() function is
identified by its short name.
Example:
#property script_show_inputs
//--- input parameters
input string shortname="MACD(12,26,9)";
//+------------------------------------------------------------------+
//| Returns number of the chart window with this indicator |
//+------------------------------------------------------------------+
int GetIndicatorSubWindowNumber(long chartID=0,string short_name="")
{
int window=-1;
//---
if((ENUM_PROGRAM_TYPE)MQLInfoInteger(MQL_PROGRAM_TYPE)==PROGRAM_INDICATOR)
{
//--- the function is called from the indicator, name is not required
window=ChartWindowFind();
}
else
{
//--- the function is called from an Expert Advisor or script
window=ChartWindowFind(0,short_name);
if(window==-1) Print(__FUNCTION__+"(): Error = ",GetLastError());
}
//---
return(window);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//---
int window=GetIndicatorSubWindowNumber(0,shortname);
if(window!=-1)
Print("Indicator "+shortname+" is in the window #"+(string)window);
else
Print("Indicator "+shortname+" is not found. window = "+(string)window);
}
See also
ObjectCreate(), ObjectFind()
MQL4 Reference / Chart Operations / ChartTimePriceToXY
ChartTimePriceToXY
Converts the coordinates of a chart from the time/price representation to the X and
Y coordinates.
bool ChartTimePriceToXY( long chart_id, // Chart ID
int sub_window, // The number of the subwindow
datetime time, // Time on the chart
double price, // Price on the chart
int& x, // The X coordinate for the time on the chart
int& y // The Y coordinates for the price on the chart
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
sub_window
[in] The number of the chart subwindow. 0 means the main chart window.
time
[in] The time value on the chart, for which the value in pixels along the X axis
will be received.
price
[in] The price value on the chart, for which the value in pixels along the Y axis
will be received.
x
[out] The variable, into which the conversion of time to X will be received. The
origin is in the upper left corner of the main chart window.
y
[out] The variable, into which the conversion of price to Y will be received. The
origin is in the upper left corner of the main chart window.
Return Value
Returns true if successful, otherwise false. To get information about the error, call
the GetLastError() function.
See also
ChartXYToTimePrice()
MQL4 Reference / Chart Operations / ChartXYToTimePrice
ChartXYToTimePrice
Converts the X and Y coordinates on a chart to the time and price values.
bool ChartXYToTimePrice( long chart_id, // Chart ID
int x, // The X coordinate on the chart
int y, // The Y coordinate on the chart
int& sub_window, // The number of the subwindow
datetime& time, // Time on the chart
double& price // Price on the chart
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
x
[in] The X coordinate. The origin is in the upper left corner of the main chart window.
y
[in] The Y coordinate. The origin is in the upper left corner of the main chart window.
sub_window
[out] The variable, into which the chart subwindow number will be written. 0 means
the main chart window.
time
[out] The time value on the chart, for which the value in pixels along the X axis will
be received.
price
[out] The price value on the chart, for which the value in pixels along the Y axis will
be received.
Return Value
Returns true if successful, otherwise false. To get information about the error, call the
GetLastError() function.
Example:
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- Show the event parameters on the chart
Comment(__FUNCTION__,": id=",id," lparam=",lparam," dparam=",dparam," sparam=",spa
//--- If this is an event of a mouse click on the chart
if(id==CHARTEVENT_CLICK)
{
//--- Prepare variables
int x =(int)lparam;
int y =(int)dparam;
datetime dt =0;
double price =0;
int window=0;
//--- Convert the X and Y coordinates in terms of date/time
if(ChartXYToTimePrice(0,x,y,window,dt,price))
{
PrintFormat("Window=%d X=%d Y=%d => Time=%s Price=%G",window,x,y,TimeToS
//--- Perform reverse conversion: (X,Y) => (Time,Price)
if(ChartTimePriceToXY(0,window,dt,price,x,y))
PrintFormat("Time=%s Price=%G => X=%d Y=%d",TimeToString(dt),price,x,
else
Print("ChartTimePriceToXY return error code: ",GetLastError());
//--- delete lines
ObjectDelete(0,"V Line");
ObjectDelete(0,"H Line");
//--- create horizontal and vertical lines of the crosshair
ObjectCreate(0,"H Line",OBJ_HLINE,window,dt,price);
ObjectCreate(0,"V Line",OBJ_VLINE,window,dt,price);
ChartRedraw(0);
}
else
Print("ChartXYToTimePrice return error code: ",GetLastError());
Print("+--------------------------------------------------------------+");
}
}
See also
ChartTimePriceToXY()
MQL4 Reference / Chart Operations / ChartOpen
ChartOpen
Opens a new chart with the specified symbol and period. The
command is added to chart message queue and executed only
after all previous commands have been processed.
long ChartOpen( string symbol, // Symbol name
ENUM_TIMEFRAMES period // Period
);
Parameters
symbol
[in] Chart symbol. NULL means the symbol of the current chart
(the Expert Advisor is attached to).
period
[in] Chart period (timeframe). Can be one of the
ENUM_TIMEFRAMES values. 0 means the current chart period.
Return Value
If successful, it returns the opened chart ID. Otherwise returns 0.
To get error details use the GetLastError() function.
Note
The maximum possible number of simultaneously open charts in
the terminal can't exceed the CHARTS_MAX value.
MQL4 Reference / Chart Operations / ChartFirst
ChartFirst
Returns the ID of the first chart of the client terminal.
long ChartFirst();
Return Value
Chart ID.
MQL4 Reference / Chart Operations / ChartNext
ChartNext
Returns the chart ID of the chart next to the specified one.
long ChartNext( long chart_id // Chart ID
);
Parameters
chart_id
[in] Chart ID. 0 does not mean the current chart. 0 means "return the first chart ID".
Return Value
Chart ID. If this is the end of the chart list, it returns -1.
Example:
//--- variables for chart ID
long currChart,prevChart=ChartFirst();
int i=0,limit=100;
Print("ChartFirst =",ChartSymbol(prevChart)," ID =",prevChart);
while(i<limit)// We have certainly not more than 100 open charts
{
currChart=ChartNext(prevChart); // Get the new chart ID by using the previous c
if(currChart<0) break; // Have reached the end of the chart list
Print(i,ChartSymbol(currChart)," ID =",currChart);
prevChart=currChart;// let's save the current chart ID for the ChartNext()
i++;// Do not forget to increase the counter
}
MQL4 Reference / Chart Operations / ChartClose
ChartClose
Closes the specified chart.
bool ChartClose( long chart_id=0 // Chart ID
);
Parameters
chart_id=0
[in] Chart ID. 0 means the current chart.
Return Value
If successful, returns true, otherwise false.
MQL4 Reference / Chart Operations / ChartSymbol
ChartSymbol
Returns the symbol name for the specified chart.
string ChartSymbol( long chart_id=0 // Chart ID
);
Parameters
chart_id=0
[in] Chart ID. 0 means the current chart.
Return Value
If chart does not exist, the result will be an empty string.
See also
ChartSetSymbolPeriod()
MQL4 Reference / Chart Operations / ChartPeriod
ChartPeriod
Returns the timeframe period of specified chart.
ENUM_TIMEFRAMES ChartPeriod( long chart_id=0 // Chart ID
);
Parameters
chart_id=0
[in] Chart ID. 0 means the current chart.
Return Value
The function returns one of the ENUM_TIMEFRAMES values. If chart
does not exist, it returns 0.
MQL4 Reference / Chart Operations / ChartRedraw
ChartRedraw
This function calls a forced redrawing of a specified chart.
void ChartRedraw( long chart_id=0 // Chart ID
);
Parameters
chart_id=0
[in] Chart ID. 0 means the current chart.
Note
Usually it is used after changing the object properties.
When the ChartRedraw() function is called from an
indicator, the chart is redrawn only after the calculation
of the OnCalculate() function is over, because indicators
are executed in the common terminal thread.
See also
Objects functions
MQL4 Reference / Chart Operations / ChartSetDouble
ChartSetDouble
Sets a value for a corresponding property of the specified
chart. Chart property should be of a double type. The
command is added to chart message queue and executed only
after all previous commands have been processed.
bool ChartSetDouble( long chart_id, // Chart ID
int prop_id, // Property ID
double value // Value
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. Can be one of the
ENUM_CHART_PROPERTY_DOUBLE values (except the read-
only properties).
value
[in] Property value.
Return Value
Returns true if the command has been added to chart
queue, otherwise false. To get error details use the
GetLastError() function.
MQL4 Reference / Chart Operations / ChartSetInteger
ChartSetInteger
Sets a value for a corresponding property of the specified
chart. Chart property must be
datetime, int, color, bool or char. The command is added to
chart message queue and executed only after all previous
commands have been processed.
bool ChartSetInteger( long chart_id, // Chart ID
int prop_id, // Property ID
long value // Value
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. It can be one of the
ENUM_CHART_PROPERTY_INTEGER value (except the read-
only properties).
sub_window
[in] Chart subwindow.
value
[in] Property value.
Return Value
Returns true if the command has been added to chart
queue, otherwise false. To get error details use the
GetLastError() function.
MQL4 Reference / Chart Operations / ChartSetString
ChartSetString
Sets a value for a corresponding property of the specified chart. Chart property must be
of the string type. The command is added to chart message queue and executed only
after all previous commands have been processed.
bool ChartSetString( long chart_id, // Chart ID
int prop_id, // Property ID
string str_value // Value
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. Its value can be one of the ENUM_CHART_PROPERTY_STRING
values (except the read-only properties).
str_value
[in] Property value string. String length cannot exceed 2045 characters (extra
characters will be truncated).
Return Value
Returns true if the command has been added to chart queue, otherwise false. To get
error details use the GetLastError() function.
Note
ChartSetString can be used for a comment output on the chart instead of the Comment
function.
Example:
void OnTick()
{
//---
double Ask,Bid;
int Spread;
Ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
Bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
Spread=SymbolInfoInteger(Symbol(),SYMBOL_SPREAD);
string comment=StringFormat("Printing prices:\nAsk = %G\nBid = %G\nSpread = %d",
Ask,Bid,Spread);
ChartSetString(0,CHART_COMMENT,comment);
}
See also
Comment, ChartGetString
MQL4 Reference / Chart Operations / ChartGetDouble
ChartGetDouble
Returns the value of a corresponding property of the specified chart.
Chart property must be of double type. There are 2 variants of the
function calls.
1. Returns the property value directly.
double ChartGetDouble( long chart_id, // Chart ID
int prop_id, // Property ID
int sub_window=0 // subwindow number, if necessary
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. This value can be one of the
ENUM_CHART_PROPERTY_DOUBLE values.
sub_window
[in] Number of the chart subwindow. For the first case, the default
value is 0 (main chart window). The most of the properties do not
require a subwindow number.
double_var
[out] Target variable of double type for the requested property.
Return Value
The value of double type.
For the second call case it returns true if the specified property is
available and its value has been placed into double_var variable,
otherwise returns false. To get an additional information about the
error, it is necessary to call the function GetLastError().
Example:
void OnStart()
{
double priceMin=ChartGetDouble(0,CHART_PRICE_MIN,0);
double priceMax=ChartGetDouble(0,CHART_PRICE_MAX,0);
Print("CHART_PRICE_MIN =",priceMin);
Print("CHART_PRICE_MAX =",priceMax);
}
MQL4 Reference / Chart Operations / ChartGetInteger
ChartGetInteger
Returns the value of a corresponding property of the specified
chart. Chart property must be of datetime, int or bool type. There
are 2 variants of the function calls.
1. Returns the property value directly.
long ChartGetInteger( long chart_id, // Chart ID
int prop_id, // Property ID
int sub_window=0 // subwindow number, if necessary
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. This value can be one of the
ENUM_CHART_PROPERTY_INTEGER values.
sub_window
[in] Number of the chart subwindow. For the first case, the
default value is 0 (main chart window). The most of the
properties do not require a subwindow number.
long_var
[out] Target variable of long type for the requested property.
Return Value
The value of long type.
For the second call case it returns true if specified property is
available and its value has been stored into long_var variable,
otherwise returns false. To get additional information about the
error, it is necessary to call the function GetLastError().
Example:
void OnStart()
{
int height=ChartGetInteger(0,CHART_HEIGHT_IN_PIXELS,0);
int width=ChartGetInteger(0,CHART_WIDTH_IN_PIXELS,0);
Print("CHART_HEIGHT_IN_PIXELS =",height,"pixels");
Print("CHART_WIDTH_IN_PIXELS =",width,"pixels");
}
MQL4 Reference / Chart Operations / ChartGetString
ChartGetString
Returns the value of a corresponding property of the specified chart. Chart
property must be of string type. There are 2 variants of the function call.
1. Returns the property value directly.
string ChartGetString( long chart_id, // Chart ID
int prop_id // Property ID
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
prop_id
[in] Chart property ID. This value can be one of the
ENUM_CHART_PROPERTY_STRING values.
string_var
[out] Target variable of string type for the requested property.
Return Value
The value of string type.
For the second call case it returns true if the specified property is available
and its value has been stored into string_var variable, otherwise returns
false. To get additional information about the error, it is necessary to call
the function GetLastError().
Note
ChartGetString can be used for reading comments plotted on the chart using
the Comment or ChartSetString functions.
Example:
void OnStart()
{
ChartSetString(0,CHART_COMMENT,"Test comment.\nSecond line.\nThird!");
ChartRedraw();
Sleep(1000);
string comm=ChartGetString(0,CHART_COMMENT);
Print(comm);
}
See also
Comment, ChartSetString
MQL4 Reference / Chart Operations / ChartNavigate
ChartNavigate
Performs shift of the specified chart by the specified number of bars relative to the
specified position in the chart. The command is added to chart message queue and
executed only after all previous commands have been processed.
bool ChartNavigate( long chart_id, // Chart ID
int position, // Position
int shift=0 // Shift value
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
position
[in] Chart position to perform a shift. Can be one of the ENUM_CHART_POSITION
values.
shift=0
[in] Number of bars to shift the chart. Positive value means the right shift (to the end
of chart), negative value means the left shift (to the beginning of chart). The zero
shift can be used to navigate to the beginning or end of chart.
Return Value
Returns true if successful, otherwise returns false.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get handle of the current chart
long handle=ChartID();
string comm="";
if(handle>0) // if successful, additionally set up the chart
{
//--- disable auto scroll
ChartSetInteger(handle,CHART_AUTOSCROLL,false);
//--- set a shift from the right chart border
ChartSetInteger(handle,CHART_SHIFT,true);
//--- draw candlesticks
ChartSetInteger(handle,CHART_MODE,CHART_CANDLES);
//--- set the display mode for tick volumes
ChartSetInteger(handle,CHART_SHOW_VOLUMES,CHART_VOLUME_TICK);
MQL4 Reference / Chart Operations / ChartID
ChartID
Returns the ID of the current chart.
long ChartID();
Return Value
Value of long type.
MQL4 Reference / Chart Operations / ChartIndicatorDelete
ChartIndicatorDelete
Removes an indicator with a specified name from the specified chart window. The
command is added to chart message queue and executed only after all previous
commands have been processed.
bool ChartIndicatorDelete( long chart_id, // chart id
int sub_window, // number of the subwindow
const string indicator_shortname // short name of the indicator
);
Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.
const indicator_shortname
[in] The short name of the indicator which is set in the INDICATOR_SHORTNAME
property with the IndicatorSetString() function. To get the short name of an indicator
use the ChartIndicatorName() function.
Return Value
Returns true if the command has been added to chart queue, otherwise false. To get
error details use the GetLastError() function.
Note
If two indicators with identical short names exist in the chart subwindow, the first one
in a row will be deleted.
If other indicators on this chart are based on the values of the indicator that is being
deleted, such indicators will also be deleted.
If the short name of an indicator is not set explicitly, then the name of the file
containing the source code of the indicator will be specified during compilation.
The indicator's short name should be formed correctly. It will be written to the
INDICATOR_SHORTNAME property using the IndicatorSetString() function. It is
recommended that the short name should contain values of all the input parameters of
the indicator, because the indicator to be deleted from the chart by the
ChartIndicatorDelete() function is identified by the short name.
Example of deleting an indicator after initialization has failed:
//+------------------------------------------------------------------+
//| Demo_ChartIndicatorDelete.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 1
//--- plot Histogram
#property indicator_label1 "Histogram"
#property indicator_type1 DRAW_HISTOGRAM
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
//--- input parameters
input int first_param=1;
input int second_param=2;
input int third_param=3;
input bool wrong_init=true;
//--- indicator buffers
double HistogramBuffer[];
string shortname;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
int res=INIT_SUCCEEDED;
//--- Link the HistogramBuffer array to the indicator buffer
SetIndexBuffer(0,HistogramBuffer,INDICATOR_DATA);
//--- Construct a short indicator name based on input parameters
shortname=StringFormat("Demo_ChartIndicatorDelete(%d,%d,%d)",
first_param,second_param,third_param);
IndicatorSetString(INDICATOR_SHORTNAME,shortname);
//--- If forced completion of an indicator is set, return a non-zero value
if(wrong_init) res=INIT_FAILED;
return(res);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//--- Starting position for working in a loop
int start=prev_calculated-1;
if(start<0) start=0;
//--- Fill in the indicator buffer with values
for(int i=start;i<rates_total;i++)
{
HistogramBuffer[i]=close[i];
}
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Handler of the Deinit event |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
PrintFormat("%s: Deinitialization reason code=%d",__FUNCTION__,reason);
if(reason==REASON_INITFAILED)
{
PrintFormat("An indicator with a short name %s (file %s) deletes itself from th
int window=ChartWindowFind();
bool res=ChartIndicatorDelete(0,window,shortname);
//--- Analyse the result of call of ChartIndicatorDelete()
if(!res)
{
PrintFormat("Failed to delete indicator %s from window #%d. Error code %d",
shortname,window,GetLastError());
}
}
}
See also
ChartIndicatorName(), ChartIndicatorsTotal(), IndicatorSetString()
MQL4 Reference / Chart Operations / ChartIndicatorName
ChartIndicatorName
Returns the short name of the indicator by the number in the indicators list on the
specified chart window.
string ChartIndicatorName( long chart_id, // chart id
int sub_window, // number of the subwindow
int index // index of the indicator in the list of indicators added to
);
Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart subwindow.
index
[in] the index of the indicator in the list of indicators. The numeration of indicators
start with zero, i.e. the first indicator in the list has the 0 index. To obtain the number
of indicators in the list use the ChartIndicatorsTotal() function.
Return Value
The short name of the indicator which is set in the INDICATOR_SHORTNAME property
with the IndicatorSetString() function. To get error details use the GetLastError()
function.
Note
If the short name of an indicator is not set explicitly, then the name of the file
containing the source code of the indicator will be specified during compilation.
The indicator's short name should be formed correctly. It will be written to the
INDICATOR_SHORTNAME property using the IndicatorSetString() function. It is
recommended that the short name should contain values of all the input parameters of
the indicator, because the indicator to be deleted from the chart by the
ChartIndicatorDelete() function is identified by the short name.
See also
ChartIndicatorDelete(), ChartIndicatorsTotal(), IndicatorSetString()
MQL4 Reference / Chart Operations / ChartIndicatorsTotal
ChartIndicatorsTotal
Returns the number of all indicators applied to the specified chart
window.
int ChartIndicatorsTotal( long chart_id, // chart id
int sub_window // number of the subwindow
);
Parameters
chart_id
[in] Chart ID. 0 denotes the current chart.
sub_window
[in] Number of the chart subwindow. 0 denotes the main chart
subwindow.
Return Value
The number of indicators in the specified chart window. To get
error details use the GetLastError() function.
Note
The function allows going searching through all the indicators
attached to the chart. The number of all the windows of the
chart can be obtained from the CHART_WINDOWS_TOTAL
property using the ChartGetInteger() function.
See also
ChartIndicatorDelete(), ChartIndicatorsTotal(),
IndicatorSetString()
MQL4 Reference / Chart Operations / ChartWindowOnDropped
ChartWindowOnDropped
Returns the number (index) of the chart subwindow the Expert Advisor or script has been
dropped to. 0 means the main chart window.
int ChartWindowOnDropped();
Return Value
Value of int type.
Example:
int myWindow=ChartWindowOnDropped(); int windowsTotal=ChartGetInteger(0,CHART_WI
Print("Script is running on the window #"+myWindow+
". Total windows on the chart "+ChartSymbol()+":",windowsTotal);
See also
ChartPriceOnDropped(), ChartTimeOnDropped(), ChartXOnDropped(),
ChartYOnDropped()
MQL4 Reference / Chart Operations / ChartPriceOnDropped
ChartPriceOnDropped
Returns the price coordinate corresponding to the chart point the Expert
Advisor or script has been dropped to.
double ChartPriceOnDropped();
Return Value
Value of double type.
Example:
double p=ChartPriceOnDropped(); Print("ChartPriceOnDropped() = ",p);
See also
ChartXOnDropped(), ChartYOnDropped()
MQL4 Reference / Chart Operations / ChartTimeOnDropped
ChartTimeOnDropped
Returns the time coordinate corresponding to the chart point the Expert Advisor
or script has been dropped to.
datetime ChartTimeOnDropped();
Return Value
Value of datetime type.
Example:
datetime t=ChartTimeOnDropped(); Print("Script was dropped on the "+t);
See also
ChartXOnDropped(), ChartYOnDropped()
MQL4 Reference / Chart Operations / ChartXOnDropped
ChartXOnDropped
Returns the X coordinate of the chart point the Expert
Advisor or script has been dropped to.
int ChartXOnDropped();
Return Value
The X coordinate value.
Note
X axis direction from left to right.
Example:
int X=ChartXOnDropped(); int Y=ChartYOnDropped();
Print("(X,Y) = ("+X+","+Y+")");
See also
ChartWindowOnDropped(), ChartPriceOnDropped(),
ChartTimeOnDropped()
MQL4 Reference / Chart Operations / ChartYOnDropped
ChartYOnDropped
Returns the Y coordinateof the chart point the Expert
Advisor or script has been dropped to.
int ChartYOnDropped();
Return Value
The Y coordinate value.
Note
Y axis direction from top to bottom.
See also
ChartWindowOnDropped(), ChartPriceOnDropped(),
ChartTimeOnDropped()
MQL4 Reference / Chart Operations / ChartSetSymbolPeriod
ChartSetSymbolPeriod
Changes the symbol and period of the specified chart. The function is
asynchronous, i.e. it sends the command and does not wait for its execution
completion. The command is added to chart message queue and executed
only after all previous commands have been processed.
bool ChartSetSymbolPeriod( long chart_id, // Chart ID
string symbol, // Symbol name
ENUM_TIMEFRAMES period // Period
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
symbol
[in] Chart symbol. NULL value means the current chart symbol (Expert
Advisor is attached to)
period
[in] Chart period (timeframe). Can be one of the ENUM_TIMEFRAMES
values. 0 means the current chart period.
Return Value
Returns true if the command has been added to chart queue, otherwise
false. To get error details use the GetLastError() function.
Note
The symbol/period change leads to the re-initialization of the Expert
Advisor, attached to a chart. Re-initialization is not performed on offline
charts, they're only refreshed (the same as when clicking Refresh in the
terminal).
See also
ChartSymbol(), ChartPeriod()
MQL4 Reference / Chart Operations / ChartScreenShot
ChartScreenShot
Saves current chart screen shot as a GIF, PNG or BMP file depending on specified
extension. The command is added to chart message queue and executed only after all
previous commands have been processed.
bool ChartScreenShot( long chart_id, // Chart ID
string filename, // Symbol name
int width, // Width
int height, // Height
ENUM_ALIGN_MODE align_mode=ALIGN_RIGHT // Alignment type
);
Parameters
chart_id
[in] Chart ID. 0 means the current chart.
filename
[in] Screenshot file name. Cannot exceed 63 characters. Screenshot files are placed in
the \Files directory.
width
[in] Screenshot width in pixels.
height
[in] Screenshot height in pixels.
align_mode=ALIGN_RIGHT
[in] Output mode of a narrow screenshot. A value of the ENUM_ALIGN_MODE
enumeration. ALIGN_RIGHT means align to the right margin (the output from the end).
ALIGN_LEFT means Left justify.
Return Value
Returns true if the command has been added to chart queue, otherwise false. To get
error details use the GetLastError() function.
Note
If you need to take a screenshot from a chart from a certain position, first it's necessary
to position the graph using the ChartNavigate() function. If the horizontal size of the
screenshot is smaller than the chart window, either the right part of the chart window,
or its left part is output, depending on the align_mode settings.
Example:
#property description "The Expert Advisor demonstrates how to create a series of scre
#property description "chart using the ChartScreenShot() function. For convenience, t
#property description "shown on the chart. The height and width of images is defined
//---
#define WIDTH 800 // Image width to call ChartScreenShot()
#define HEIGHT 600 // Image height to call ChartScreenShot()
//--- input parameters
input int pictures=5; // The number of images in the series
int mode=-1; // -1 denotes a shift to the right edge of the chart, 1
int bars_shift=300;// The number of bars when scrolling the chart using Ch
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
void OnInit()
{
//--- Disable chart autoscroll
ChartSetInteger(0,CHART_AUTOSCROLL,false);
//--- Set the shift of the right edge of the chart
ChartSetInteger(0,CHART_SHIFT,true);
//--- Show a candlestick chart
ChartSetInteger(0,CHART_MODE,CHART_CANDLES);
//---
Print("Preparation of the Expert Advisor is completed");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- Show the name of the function, call time and event identifier
Print(__FUNCTION__,TimeCurrent()," id=",id," mode=",mode);
//--- Handle the CHARTEVENT_CLICK event ("A mouse click on the chart")
if(id==CHARTEVENT_CLICK)
{
//--- Initial shift from the chart edge
int pos=0;
//--- Operation with the left chart edge
if(mode>0)
{
//--- Scroll the chart to the left edge
ChartNavigate(0,CHART_BEGIN,pos);
for(int i=0;i<pictures;i++)
{
//--- Prepare a text to show on the chart and a file name
string name="ChartScreenShot"+"CHART_BEGIN"+string(pos)+".gif";
//--- Show the name on the chart as a comment
Comment(name);
//--- Save the chart screenshot in a file in the terminal_directory\MQL4\
if(ChartScreenShot(0,name,WIDTH,HEIGHT,ALIGN_LEFT))
Print("We've saved the screenshot ",name);
//---
pos+=bars_shift;
//--- Give the user time to look at the new part of the chart
Sleep(3000);
//--- Scroll the chart from the current position bars_shift bars to the r
ChartNavigate(0,CHART_CURRENT_POS,bars_shift);
}
//--- Change the mode to the opposite
mode*=-1;
}
else // Operation with the right chart edge
{
//--- Scroll the chart to the right edge
ChartNavigate(0,CHART_END,pos);
for(int i=0;i<pictures;i++)
{
//--- Prepare a text to show on the chart and a file name
string name="ChartScreenShot"+"CHART_END"+string(pos)+".gif";
//--- Show the name on the chart as a comment
Comment(name);
//--- Save the chart screenshot in a file in the terminal_directory\MQL4\
if(ChartScreenShot(0,name,WIDTH,HEIGHT,ALIGN_RIGHT))
Print("We've saved the screenshot ",name);
//---
pos+=bars_shift;
//--- Give the user time to look at the new part of the chart
Sleep(3000);
//--- Scroll the chart from the current position bars_shift bars to the r
ChartNavigate(0,CHART_CURRENT_POS,-bars_shift);
}
//--- Change the mode to the opposite
mode*=-1;
}
} // End of CHARTEVENT_CLICK event handling
//--- End of the OnChartEvent() handler
}
See also
ChartNavigate(), Resources
MQL4 Reference / Chart Operations / Period
Period
Returns timeframe of the current chart.
int Period();
Parameters
None.
Returned value
Period (timeframe) of the current chart (in minutes).
Example:
Print("Period ", Period());
MQL4 Reference / Chart Operations / Symbol
Symbol
Returns a text string with the name of the current financial instrument.
string Symbol();
Parameters
None.
Returned value
A text string with the name of the current financial instrument.
Example:
int total=OrdersTotal(); for(int pos=0;pos<total;pos++)
{
// check selection result because the order may be closed or deleted at this ti
if(OrderSelect(pos, SELECT_BY_POS)==false) continue;
if(OrderType()>OP_SELL || OrderSymbol()!=Symbol()) continue;
// performs some processing...
}
MQL4 Reference / Chart Operations / WindowBarsPerChart
WindowBarsPerChart
Returns the amount of bars visible on the chart.
int WindowBarsPerChart();
Parameters
None.
Returned value
The amount of bars visible on the chart.
Example:
// work with visible bars. int bars_count=WindowBarsPerChart();
int bar=WindowFirstVisibleBar();
for(int i=0; i<bars_count; i++,bar--)
{
// ...
}
MQL4 Reference / Chart Operations / WindowExpertName
WindowExpertName
Returns the name of the executed Expert Advisor, script, custom
indicator, or library.
string WindowExpertName();
Parameters
None.
Returned value
The name of the executed Expert Advisor, script, custom indicator, or
library, depending on the MQL4 program, from which this function
has been called.
Example:
string name=WindowExpertName(); GlobalVariablesDeleteAll(name);
MQL4 Reference / Chart Operations / WindowFind
WindowFind
Returns the window index containing this specified
indicator.
int WindowFind( string name // name
);
Parameters
name
[in] Indicator short name.
Returned value
If indicator with name was found, the function returns
the window index containing this specified indicator,
otherwise it returns -1.
Note
WindowFind() returns -1 if custom indicator searches
itself when init() function works.
Example:
int win_idx=WindowFind("MACD(12,26,9)");
MQL4 Reference / Chart Operations / WindowFirstVisibleBar
WindowFirstVisibleBar
Returns index of the first visible bar in the current chart window.
int WindowFirstVisibleBar();
Parameters
None.
Returned value
Index of the first visible bar number in the current chart window.
Note
It must be taken into consideration that price bars are numbered in the
reverse order, from the last to the first one. The current bar, the latest
in the price array, is indexed as 0. The oldest bar is indexed as Bars-1. If
the first visible bar number is 2 or more bars less than the amount of
visible bars in the chart, it means that the chart window has not been
fully filled out and there is a space to the left.
Example:
// work with visible bars. int bars_count=WindowBarsPerChart();
int bar=WindowFirstVisibleBar();
for(int i=0; i<bars_count; i++,bar--)
{
// ...
}
MQL4 Reference / Chart Operations / WindowHandle
WindowHandle
Returns the system handle of the chart window.
int WindowHandle( string symbol, // symbol
int timeframe // timeframe
);
Parameters
symbol
[in] Symbol.
timeframe
[in] Timeframe. It can be any of Timeframe enumeration values. 0 means the current
chart timeframe.
Returned value
Returns the system handle of the chart window. If the chart of symbol and timeframe
has not been opened by the moment of function calling, 0 will be returned.
Example:
int win_handle=WindowHandle("USDX",PERIOD_H1);
if(win_handle!=0)
Print("Window with USDX,H1 detected. Rates array will be copied immediately.");
MQL4 Reference / Chart Operations / WindowIsVisible
WindowIsVisible
Returns the visibility flag of the chart subwindow.
int WindowIsVisible( int index // subwindow
);
Parameters
index
[in] Subwindow index.
Returned value
Returns true if the chart subwindow is visible, otherwise
returns false. The chart subwindow can be hidden due to
the visibility properties of the indicator placed in it.
Example:
int maywin=WindowFind("MyMACD");
if(maywin>-1 && WindowIsVisible(maywin)==true)
Print("window of MyMACD is visible");
else
Print("window of MyMACD not found or is not visible");
MQL4 Reference / Chart Operations / WindowOnDropped
WindowOnDropped
Returns the window index where Expert Advisor, custom indicator or script was
dropped.
int WindowOnDropped();
Parameters
None.
Returned value
The window index where Expert Advisor, custom indicator or script was
dropped. This value is valid if the Expert Advisor, custom indicator or script was
dropped by mouse.
Note
For custom indicators being initialized (call from the init() function), this index
is not defined.
The returned index is the number of window (0-chart main menu, subwindows
of indicators are numbered starting from 1) where the custom indicator is
working. A custom indicator can create its own new subwindow during its work,
and the number of this subwindow will differ from that of the window where
the indicator was really dropped in.
Example:
if(WindowOnDropped()!=0) {
Print("Indicator 'MyIndicator' must be applied to main chart window!");
return(false);
}
See also
WindowXOnDropped(), WindowYOnDropped()
MQL4 Reference / Chart Operations / WindowPriceMax
WindowPriceMax
Returns the maximal value of the vertical scale of the specified
subwindow of the current chart.
int WindowPriceMax( int index=0 // subwindow
);
Parameters
index=0
[in] Chart subwindow index (0 - main chart window).
Returned value
The maximal value of the vertical scale of the specified subwindow of
the current chart (0-main chart window, the indicators' subwindows are
numbered starting from 1). If the subwindow index has not been
specified, the maximal value of the price scale of the main chart
window is returned.
Example:
double top=WindowPriceMax();
double bottom=WindowPriceMin();
datetime left=Time[WindowFirstVisibleBar()];
int right_bound=WindowFirstVisibleBar()-WindowBarsPerChart();
if(right_bound<0) right_bound=0;
datetime right=Time[right_bound]+Period()*60;
//----
ObjectCreate("Padding_rect",OBJ_RECTANGLE,0,left,top,right,bottom);
ObjectSet("Padding_rect",OBJPROP_BACK,true);
ObjectSet("Padding_rect",OBJPROP_COLOR,Blue);
WindowRedraw();
See also
WindowPriceMin(), WindowFirstVisibleBar(), WindowBarsPerChart()
MQL4 Reference / Chart Operations / WindowPriceMin
WindowPriceMin
Returns the minimal value of the vertical scale of the specified
subwindow of the current chart.
int WindowPriceMin( int index=0 // subwindow
);
Parameters
index=0
[in] Chart subwindow index (0 - main chart window).
Returned value
The minimal value of the vertical scale of the specified subwindow of
the current chart (0-main chart window, the indicators' subwindows are
numbered starting from 1). If the subwindow index has not been
specified, the minimal value of the price scale of the main chart window
is returned.
Example:
double top=WindowPriceMax();
double bottom=WindowPriceMin();
datetime left=Time[WindowFirstVisibleBar()];
int right_bound=WindowFirstVisibleBar()-WindowBarsPerChart();
if(right_bound<0) right_bound=0;
datetime right=Time[right_bound]+Period()*60;
//----
ObjectCreate("Padding_rect",OBJ_RECTANGLE,0,left,top,right,bottom);
ObjectSet("Padding_rect",OBJPROP_BACK,true);
ObjectSet("Padding_rect",OBJPROP_COLOR,Blue);
WindowRedraw();
See also
WindowPriceMax(), WindowFirstVisibleBar(), WindowBarsPerChart()
MQL4 Reference / Chart Operations / WindowPriceOnDropped
WindowPriceOnDropped
Returns the price of the chart point where Expert Advisor or script was dropped.
double WindowPriceOnDropped();
Parameters
None.
Returned value
The price of the chart point where Expert Advisor or script was dropped. This value is
only valid if the expert or script was dropped by mouse.
Note
For custom indicators this value is undefined.
Example:
double drop_price=WindowPriceOnDropped(); datetime drop_time=WindowTimeOnDropped
//---- may be undefined (zero)
if(drop_time>0)
{
ObjectCreate("Dropped price line", OBJ_HLINE, 0, drop_price);
ObjectCreate("Dropped time line", OBJ_VLINE, 0, drop_time);
}
See also
WindowTimeOnDropped(), WindowYOnDropped(), WindowOnDropped()
MQL4 Reference / Chart Operations / WindowRedraw
WindowRedraw
Redraws the current chart forcedly.
void WindowRedraw();
Parameters
None.
Returned value
None.
Note
Redraws the current chart forcedly. It is normally used after the objects properties
have been changed.
Example:
//---- set new properties for some objects ObjectMove(object_name1, 0, Time[index
ObjectSet(object_name1, OBJPROP_ANGLE, angle*2);
ObjectSet(object_name1, OBJPROP_FONTSIZE, fontsize);
ObjectSet(line_name, OBJPROP_TIME2, time2);
ObjectSet(line_name, OBJPROP_ANGLE, line_angle);
//---- now redraw all
WindowRedraw();
MQL4 Reference / Chart Operations / WindowScreenShot
WindowScreenShot
Saves current chart screen shot as a GIF file.
bool WindowScreenShot( string filename, // file name
int size_x, // width
int size_y, // height
int start_bar=-1, // first visible bar
int chart_scale=-1, // scale
int chart_mode=-1 // mode
);
Parameters
filename
[in] Screen shot file name. Screenshot is saved to \Files folder.
size_x
[in] Screen shot width in pixels.
size_y
[in] Screen shot height in pixels.
start_bar=-1
[in] Index of the first visible bar in the screen shot. If 0 value is set, the current first
visible bar will be shot. If no value or negative value has been set, the end-of-chart
screen shot will be produced, indent being taken into consideration.
chart_scale=-1
[in] Horizontal chart scale for screen shot. Can be in the range from 0 to 5. If no value
or negative value has been set, the current chart scale will be used.
chart_mode=-1
[in] Chart displaying mode. It can take the following values: CHART_BAR (0 is a
sequence of bars), CHART_CANDLE (1 is a sequence of candlesticks), CHART_LINE (2 is
a close prices line). If no value or negative value has been set, the chart will be shown
in its current mode.
Returned value
Returns true if succeed, otherwise false. To get the error code, one has to use the
GetLastError() function.
Note
The screen shot is saved in the terminal_dir\experts\files (terminal_dir\tester\files in
case of testing) directory or its subdirectories.
Example:
int lasterror=0;
//---- tester has closed one or more trades
if(IsTesting() && ExtTradesCounter<TradesTotal())
{
//---- make WindowScreenShot for further checking
if(!WindowScreenShot("shots\\tester"+ExtShotsCounter+".gif",640,480))
lasterror=GetLastError();
else ExtShotsCounter++;
ExtTradesCounter=TradesTotal();
}
MQL4 Reference / Chart Operations / WindowTimeOnDropped
WindowTimeOnDropped
Returns the time of the chart point where Expert Advisor or script was dropped.
datetime WindowTimeOnDropped();
Parameters
None.
Returned value
The time value of the chart point where expert or script was dropped. This value is
only valid if the expert or script was dropped by mouse.
Notwe
For custom indicators this value is undefined.
Example:
double drop_price=WindowPriceOnDropped(); datetime drop_time=WindowTimeOnDropped
//---- may be undefined (zero)
if(drop_time>0)
{
ObjectCreate("Dropped price line", OBJ_HLINE, 0, drop_price);
ObjectCreate("Dropped time line", OBJ_VLINE, 0, drop_time);
}
See also
WindowPriceOnDropped(), WindowYOnDropped(), WindowOnDropped()
MQL4 Reference / Chart Operations / WindowsTotal
WindowsTotal
Returns total number of indicator windows on the chart.
int WindowsTotal();
Parameters
None.
Returned value
Total number of indicator windows on the chart
(including main chart).
Example:
Print("Total windows = ", WindowsTotal());
MQL4 Reference / Chart Operations / WindowXOnDropped
WindowXOnDropped
Returns the value at X axis in pixels for the chart window client area point at which
the Expert Advisor or script was dropped.
int WindowXOnDropped();
Parameters
None.
Returned value
The value at X axis in pixels for the chart window client area point at which the
expert or script was dropped. The value will be true only if the expert or script were
moved with the mouse ("Drag'n'Drop") technique.
Example:
Print("Expert dropped at point x=",WindowXOnDropped()," y=",WindowYOnDropped());
See also
WindowYOnDropped(), WindowTimeOnDropped(), WindowOnDropped()
MQL4 Reference / Chart Operations / WindowYOnDropped
WindowYOnDropped
Returns the value at Y axis in pixels for the chart window client area point at which the
Expert Advisor or script was dropped.
int WindowYOnDropped();
Parameters
None.
Returned value
Returns the value at Y axis in pixels for the chart window client area point at which the
Expert Advisor or script was dropped. The value will be true only if the expert or script
were moved with the mouse ("Drag'n'Drop") technique.
Example:
Print"Expert was attached to the window in the point x=",WindowXOnDropped()," y=",W
See also
WindowYOnDropped(), WindowPriceOnDropped(), WindowOnDropped()
MQL4 Reference / Trade Functions
Trade Functions
This is the group of functions intended for managing
trading activities.
Trading functions can be used in Expert Advisors and
scripts. OrderSend(), OrderClose(), OrderCloseBy(),
OrderModify(), OrderDelete() trading functions changing
the state of a trading account can be called only if trading
by Expert Advisors is allowed (the "Allow live trading"
checkbox is enabled in the Expert Advisor or script
properties).
Trading can be allowed or prohibited depending on various
factors described in the Trade Permission section.
Function Action
OrderClose Closes opened order
OrderCloseBy Closes an opened order by another
opposite opened order
OrderClosePrice Returns close price of the currently
selected order
OrderCloseTime Returns close time of the currently
selected order
OrderComment Returns comment of the currently
selected order
OrderCommission Returns calculated commission of the
currently selected order
OrderDelete Deletes previously opened pending order
Function Action
OrderExpiration Returns expiration date of the selected
pending order
OrderLots Returns amount of lots of the selected
order
OrderMagicNumber Returns an identifying (magic) number of
the currently selected order
OrderModify Modification of characteristics of the
previously opened or pending orders
OrderOpenPrice Returns open price of the currently
selected order
OrderOpenTime Returns open time of the currently
selected order
OrderPrint Prints information about the selected
order in the log
OrderProfit Returns profit of the currently selected
order
OrderSelect The function selects an order for further
processing
OrderSend The main function used to open an order
or place a pending order
OrdersHistoryTotal Returns the number of closed orders in
the account history loaded into the
terminal
OrderStopLoss Returns stop loss value of the currently
selected order
OrdersTotal Returns the number of market and
pending orders
Function Action
OrderSwap Returns swap value of the currently
selected order
OrderSymbol Returns symbol name of the currently
selected order
OrderTakeProfit Returns take profit value of the currently
selected order
OrderTicket Returns ticket number of the currently
selected order
OrderType Returns order operation type of the
currently selected order
What's new in MQL5
Added the functions for working with orders, deals and
positions to conduct trading operations. An order is a
request to buy or sell. The order execution leads to a deal
resulting in opening, modifying or closing a position.
If you develop trading robots, pay attention to the new
OrderSendAsync function intended for asynchronous
trading operations. This function is executed in less than 1
millisecond (it does not wait till the trade server responds
to a sent request) and returns control immediately. Low
network costs, high Depth of Market refresh rates and
asynchronous order sending accelerate trading operations
dozens of times. For intraday systems, the speed of
trading operations can be a key factor.
MQL4 Reference / Trade Functions / OrderClose
OrderClose
Closes opened order.
bool OrderClose( int ticket, // ticket
double lots, // volume
double price, // close price
int slippage, // slippage
color arrow_color // color
);
Parameters
ticket
[in] Unique number of the order ticket.
lots
[in] Number of lots.
price
[in] Closing price.
slippage
[in] Value of the maximum price slippage in points.
arrow_color
[in] Color of the closing arrow on the chart. If the
parameter is missing or has CLR_NONE value closing
arrow will not be drawn on the chart.
Returned value
Returns true if successful, otherwise false. To get
additional error information, one has to call the
GetLastError() function.
Example:
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)
{
OrderClose(order_id,1,Ask,3,Red);
return(0);
}
MQL4 Reference / Trade Functions / OrderCloseBy
OrderCloseBy
Closes an opened order by another opposite opened order.
bool OrderCloseBy( int ticket, // ticket to close
int opposite, // opposite ticket
color arrow_color // color
);
Parameters
ticket
[in] Unique number of the order ticket.
opposite
[in] Unique number of the opposite order ticket.
arrow_color
[in] Color of the closing arrow on the chart. If the parameter is
missing or has CLR_NONE value closing arrow will not be drawn on
the chart.
Returned value
Returns true if successful, otherwise false. To get additional error
information, one has to call the GetLastError() function.
Example:
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)
{
OrderCloseBy(order_id,opposite_id);
return(0);
}
MQL4 Reference / Trade Functions / OrderClosePrice
OrderClosePrice
Returns close price of the currently selected order.
double OrderClosePrice();
Returned value
The close price of currently selected order.
Note
The order must be previously selected by the OrderSelect()
function.
Example:
if(OrderSelect(10,SELECT_BY_POS,MODE_HISTORY)==true) {
datetime ctm=OrderOpenTime();
if(ctm>0) Print("Open time for the order 10 ", ctm);
ctm=OrderCloseTime();
if(ctm>0) Print("Close time for the order 10 ", ctm);
}
else
Print("OrderSelect failed error code is",GetLastError());
MQL4 Reference / Trade Functions / OrderCloseTime
OrderCloseTime
Returns close time of the currently selected order.
datetime OrderCloseTime();
Returned value
Close time for the currently selected order. If order close time
is not 0, then the order selected and has been closed and
retrieved from the account history. Open and pending orders
close time is equal to 0.
Note
The order must be previously selected by the OrderSelect()
function.
Example:
if(OrderSelect(10,SELECT_BY_POS,MODE_HISTORY)==true) {
datetime ctm=OrderOpenTime();
if(ctm>0) Print("Open time for the order 10 ", ctm);
ctm=OrderCloseTime();
if(ctm>0) Print("Close time for the order 10 ", ctm);
}
else
Print("OrderSelect failed error code is",GetLastError());
MQL4 Reference / Trade Functions / OrderComment
OrderComment
Returns comment of the currently selected order.
string OrderComment();
Returned value
Comment of the currently selected order.
Note
The order must be previously selected by the OrderSelect()
function.
Example:
string comment; if(OrderSelect(10,SELECT_BY_TICKET)==false)
{
Print("OrderSelect failed error code is",GetLastError());
return(0);
}
comment = OrderComment();
// ...
MQL4 Reference / Trade Functions / OrderCommission
OrderCommission
Returns calculated commission of the currently selected order.
double OrderCommission();
Returned value
The calculated commission of the currently selected order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(10,SELECT_BY_POS)==true) Print("Commission for the order 10 ",Ord
else
Print("OrderSelect failed error code is",GetLastError());
MQL4 Reference / Trade Functions / OrderDelete
OrderDelete
Deletes previously opened pending order.
bool OrderDelete( int ticket, // ticket
color arrow_color // color
);
Parameters
ticket
[in] Unique number of the order ticket.
arrow_color
[in] Color of the arrow on the chart. If the parameter is
missing or has CLR_NONE value arrow will not be drawn
on the chart.
Returned value
If the function succeeds, it returns true, otherwise false.
To get the detailed error information, call the
GetLastError() function.
Example:
if(Ask>var1)
{
OrderDelete(order_ticket);
return(0);
}
MQL4 Reference / Trade Functions / OrderExpiration
OrderExpiration
Returns expiration date of the selected pending order.
datetime OrderExpiration();
Returned value
Expiration date of the selected pending order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(10, SELECT_BY_TICKET)==true) Print("Order expiration for the orde
else
Print("OrderSelect returned error of ",GetLastError());
MQL4 Reference / Trade Functions / OrderLots
OrderLots
Returns amount of lots of the selected order.
double OrderLots();
Returned value
Amount of lots (trade volume) of the selected order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(10,SELECT_BY_POS)==true) Print("lots for the order 10 ",OrderLots
else
Print("OrderSelect returned error of ",GetLastError());
MQL4 Reference / Trade Functions / OrderMagicNumber
OrderMagicNumber
Returns an identifying (magic) number of the currently selected order.
int OrderMagicNumber();
Returned value
The identifying (magic) number of the currently selected order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(10,SELECT_BY_POS)==true) Print("Magic number for the order 10 ",
else
Print("OrderSelect returned error of ",GetLastError());
MQL4 Reference / Trade Functions / OrderModify
OrderModify
Modification of characteristics of the previously opened or pending orders.
bool OrderModify( int ticket, // ticket
double price, // price
double stoploss, // stop loss
double takeprofit, // take profit
datetime expiration, // expiration
color arrow_color // color
);
Parameters
ticket
[in] Unique number of the order ticket.
price
[in] New open price of the pending order.
stoploss
[in] New StopLoss level.
takeprofit
[in] New TakeProfit level.
expiration
[in] Pending order expiration time.
arrow_color
[in] Arrow color for StopLoss/TakeProfit modifications in the chart. If the parameter is
missing or has CLR_NONE value, the arrows will not be shown in the chart.
Returned value
If the function succeeds, it returns true, otherwise false. To get the detailed error
information, call the GetLastError() function.
Note
Open price and expiration time can be changed only for pending orders. If unchanged
values are passed as the function parameters, the error 1 (ERR_NO_RESULT) will be
generated.
Pending order expiration time can be disabled in some trade servers. In this case, when
a non-zero value is specified in the expiration parameter, the error 147
(ERR_TRADE_EXPIRATION_DENIED) will be generated.
Example:
void OnStart()
{
int TrailingStop=50;
//--- modifies Stop Loss price for buy order №12345
if(TrailingStop>0)
{
OrderSelect(12345,SELECT_BY_TICKET);
if(Bid-OrderOpenPrice()>Point*TrailingStop)
{
if(OrderStopLoss()<Bid-Point*TrailingStop)
{
bool res=OrderModify(OrderTicket(),OrderOpenPrice(),NormalizeDouble(Bid-P
if(!res)
Print("Error in OrderModify. Error code=",GetLastError());
else
Print("Order modified successfully.");
}
}
}
}
MQL4 Reference / Trade Functions / OrderOpenPrice
OrderOpenPrice
Returns open price of the currently selected order.
double OrderOpenPrice();
Returned value
Open price of the currently selected order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(10, SELECT_BY_POS)==true) Print("open price for the order 10 ",Or
else
Print("OrderSelect returned the error of ",GetLastError());
MQL4 Reference / Trade Functions / OrderOpenTime
OrderOpenTime
Returns open time of the currently selected order.
datetime OrderOpenTime();
Returned value
Open time of the currently selected order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(10, SELECT_BY_POS)==true) Print("open time for the order 10 ",Ord
else
Print("OrderSelect returned error of ",GetLastError());
MQL4 Reference / Trade Functions / OrderPrint
OrderPrint
Prints information about the selected order in the log.
void OrderPrint();
Parameters
Prints information about the selected order in the log in the
following format:
#ticket number; open time; trade operation; amount of lots;
symbol; open price; Stop Loss; Take Profit; close time; close
price; commission; swap; profit; comment; magic number;
pending order expiration date.
Note
The order must be previously selected by the OrderSelect()
function.
Example:
if(OrderSelect(10, SELECT_BY_TICKET)==true) OrderPrint();
else
Print("OrderSelect failed error code is",GetLastError());
MQL4 Reference / Trade Functions / OrderProfit
OrderProfit
Returns profit of the currently selected order.
double OrderProfit();
Returned value
The net profit value (without swaps or commissions) for the selected order. For open
orders, it is the current unrealized profit. For closed orders, it is the fixed profit.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(10, SELECT_BY_POS)==true) Print("Profit for the order 10 ",OrderP
else
Print("OrderSelect returned the error of ",GetLastError());
MQL4 Reference / Trade Functions / OrderSelect
OrderSelect
The function selects an order for further processing.
bool OrderSelect( int index, // index or order ticket
int select, // flag
int pool=MODE_TRADES // mode
);
Parameters
ticket
[in] Order index or order ticket depending on the second parameter.
select
[in] Selecting flags. It can be any of the following values:
SELECT_BY_POS - index in the order pool,
SELECT_BY_TICKET - index is order ticket.
pool=MODE_TRADES
[in] Optional order pool index. Used when the selected parameter is
SELECT_BY_POS. It can be any of the following values:
MODE_TRADES (default)- order selected from trading pool(opened and
pending orders),
MODE_HISTORY - order selected from history pool (closed and canceled
order).
Returned value
It returns true if the function succeeds, otherwise falses. To get the error
information, one has to call the GetLastError() function.
Note
The pool parameter is ignored if the order is selected by the ticket
number. The ticket number is a unique order identifier.
To find out from what list the order has been selected, its close time must
be analyzed. If the order close time equals to 0, the order is open or
pending and taken from the terminal open orders list.
One can distinguish an opened order from a pending order by the order
type. If the order close time does not equal to 0, the order is a closed
order or a deleted pending order and was selected from the terminal
history. They also differ from each other by their order types.
The OrderSelect() function copies order data into program environment
and all further calls of OrderClosePrice(), OrderCloseTime(),
OrderComment(), OrderCommission(), OrderExpiration(), OrderLots(),
OrderMagicNumber(), OrderOpenPrice(), OrderOpenTime(), OrderPrint(),
OrderProfit(), OrderStopLoss(), OrderSwap(), OrderSymbol(),
OrderTakeProfit(), OrderTicket(), OrderType() functions return the data,
copied earlier. It means that in some cases the order details (open price,
SL/TP levels or expiration date) may change and the data become non-
actual. It is strongly recommended to call the OrderSelect() function
before request the order data.
Consecutive selection of orders using the SELECT_BY_POS parameter
returns information in the sequence in which it was received from the
trading server. Sorting of the resulting list of orders cannot be guaranteed.
Example:
if(OrderSelect(12470, SELECT_BY_TICKET)==true)
{
Print("order #12470 open price is ", OrderOpenPrice());
Print("order #12470 close price is ", OrderClosePrice());
}
else
Print("OrderSelect returned the error of ",GetLastError());
See also
Order properties, OrderClosePrice(), OrderCloseTime(), OrderComment(),
OrderCommission(), OrderExpiration(), OrderLots(), OrderMagicNumber(),
OrderOpenPrice(), OrderOpenTime(), OrderPrint(), OrderProfit(),
OrderStopLoss(), OrderSwap(), OrderSymbol(), OrderTakeProfit(),
OrderTicket(), OrderType()
MQL4 Reference / Trade Functions / OrderSend
OrderSend
The main function used to open market or place a pending order.
int OrderSend( string symbol, // symbol
int cmd, // operation
double volume, // volume
double price, // price
int slippage, // slippage
double stoploss, // stop loss
double takeprofit, // take profit
string comment=NULL, // comment
int magic=0, // magic number
datetime expiration=0, // pending order expiration
color arrow_color=clrNONE // color
);
Parameters
symbol
[in] Symbol for trading.
cmd
[in] Operation type. It can be any of the Trade operation enumeration.
volume
[in] Number of lots.
price
[in] Order price.
slippage
[in] Maximum price slippage for buy or sell orders.
stoploss
[in] Stop loss level.
takeprofit
[in] Take profit level.
comment=NULL
[in] Order comment text. Last part of the comment may be changed by server.
magic=0
[in] Order magic number. May be used as user defined identifier.
expiration=0
[in] Order expiration time (for pending orders only).
arrow_color=clrNONE
[in] Color of the opening arrow on the chart. If parameter is missing or has CLR_NONE
value opening arrow is not drawn on the chart.
Returned value
Returns number of the ticket assigned to the order by the trade server or -1 if it fails.
To get additional error information, one has to call the GetLastError() function.
Note
At opening of a market order (OP_SELL or OP_BUY), only the latest prices of Bid (for
selling) or Ask (for buying) can be used as open price. If operation is performed with a
security differing from the current one, the MarketInfo() function must be used with
MODE_BID or MODE_ASK parameter for the latest quotes for this security to be
obtained.
Calculated or unnormalized price cannot be applied. If there has not been the
requested open price in the price thread or it has not been normalized according to the
amount of digits after decimal point, the error 129 (ERR_INVALID_PRICE) will be
generated. If the requested open price is fully out of date, the error 138
(ERR_REQUOTE) will be generated independently on the slippage parameter. If the
requested price is out of date, but present in the thread, the order will be opened at
the current price and only if the current price lies within the range of price+-slippage.
StopLoss and TakeProfit levels cannot be too close to the market. The minimal distance
of stop levels in points can be obtained using the MarketInfo() function with
MODE_STOPLEVEL parameter. In the case of erroneous or unnormalized stop levels, the
error 130 (ERR_INVALID_STOPS) will be generated. A zero value of MODE_STOPLEVEL
means either absence of any restrictions on the minimal distance for Stop Loss/Take
Profit or the fact that a trade server utilizes some external mechanisms for dynamic
level control, which cannot be translated in the client terminal. In the second case,
GetLastError() can return error 130, because MODE_STOPLEVEL is actually "floating"
here.
At placing of a pending order, the open price cannot be too close to the market. The
minimal distance of the pending price from the current market one in points can be
obtained using the MarketInfo() function with the MODE_STOPLEVEL parameter. In case
of false open price of a pending order, the error 130 (ERR_INVALID_STOPS) will be
generated.
Applying of pending order expiration time can be disabled in some trade servers. In this
case, when a non-zero value is specified in the expiration parameter, the error 147
(ERR_TRADE_EXPIRATION_DENIED) will be generated.
On some trade servers, the total amount of open and pending orders can be limited. If
this limit has been exceeded, no new order will be opened (or no pending order will be
placed) and trade server will return error 148 (ERR_TRADE_TOO_MANY_ORDERS).
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- get minimum stop level
double minstoplevel=MarketInfo(Symbol(),MODE_STOPLEVEL);
Print("Minimum Stop Level=",minstoplevel," points");
double price=Ask;
//--- calculated SL and TP prices must be normalized
double stoploss=NormalizeDouble(Bid-minstoplevel*Point,Digits);
double takeprofit=NormalizeDouble(Bid+minstoplevel*Point,Digits);
//--- place market order to buy 1 lot
int ticket=OrderSend(Symbol(),OP_BUY,1,price,3,stoploss,takeprofit,"My order",1638
if(ticket<0)
{
Print("OrderSend failed with error #",GetLastError());
}
else
Print("OrderSend placed successfully");
//---
}
MQL4 Reference / Trade Functions / OrdersHistoryTotal
OrdersHistoryTotal
Returns the number of closed orders in the account history loaded into the
terminal.
int OrdersHistoryTotal();
Returned value
The number of closed orders in the account history loaded into the terminal. The
history list size depends on the current settings of the "Account history" tab of
the terminal.
Example:
// retrieving info from trade history int i,hstTotal=OrdersHistoryTotal();
for(i=0;i<hstTotal;i++)
{
//---- check selection result
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
{
Print("Access to history failed with error (",GetLastError(),")");
break;
}
// some work with order
}
MQL4 Reference / Trade Functions / OrderStopLoss
OrderStopLoss
Returns stop loss value of the currently selected order.
double OrderStopLoss();
Returned value
Stop loss value of the currently selected order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(ticket,SELECT_BY_POS)==true) Print("Stop loss value for the order
else
Print("OrderSelect failed error code is",GetLastError());
MQL4 Reference / Trade Functions / OrdersTotal
OrdersTotal
Returns the number of market and pending orders.
int OrdersTotal();
Returned value
Total amount of market and pending orders.
Example:
int handle=FileOpen("OrdersReport.csv",FILE_WRITE|FILE_CSV,"\t"); if(handle<0) ret
// write header
FileWrite(handle,"#","open price","open time","symbol","lots");
int total=OrdersTotal();
// write open orders
for(int pos=0;pos<total;pos++)
{
if(OrderSelect(pos,SELECT_BY_POS)==false) continue;
FileWrite(handle,OrderTicket(),OrderOpenPrice(),OrderOpenTime(),OrderSymbol(),Or
}
FileClose(handle);
MQL4 Reference / Trade Functions / OrderSwap
OrderSwap
Returns swap value of the currently selected order.
double OrderSwap();
Returned value
Swap value of the currently selected order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(order_id, SELECT_BY_TICKET)==true) Print("Swap for the order #",
else
Print("OrderSelect failed error code is",GetLastError());
MQL4 Reference / Trade Functions / OrderSymbol
OrderSymbol
Returns symbol name of the currently selected order.
string OrderSymbol();
Returned value
The symbol name of the currently selected order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(12, SELECT_BY_POS)==true) Print("symbol of order #", OrderTicket
else
Print("OrderSelect failed error code is",GetLastError());
MQL4 Reference / Trade Functions / OrderTakeProfit
OrderTakeProfit
Returns take profit value of the currently selected order.
double OrderTakeProfit();
Returned value
Take profit value of the currently selected order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(12, SELECT_BY_POS)==true) Print("Order #",OrderTicket()," profit
else
Print("OrderSelect() returns error - ",GetLastError());
MQL4 Reference / Trade Functions / OrderTicket
OrderTicket
Returns ticket number of the currently selected order.
int OrderTicket();
Returned value
Ticket number of the currently selected order.
Note
The order must be previously selected by the OrderSelect() function.
Example:
if(OrderSelect(12, SELECT_BY_POS)==true) order=OrderTicket();
else
Print("OrderSelect failed error code is",GetLastError());
MQL4 Reference / Trade Functions / OrderType
OrderType
Returns order operation type of the currently selected order.
int OrderType();
Returned value
Order operation type of the currently selected order. It can be
any of the following values:
OP_BUY - buy order, OP_SELL - sell order,
OP_BUYLIMIT - buy limit pending order,
OP_BUYSTOP - buy stop pending order,
OP_SELLLIMIT - sell limit pending order,
OP_SELLSTOP - sell stop pending order.
Note
The order must be previously selected by the OrderSelect()
function.
Example:
int order_type;
if(OrderSelect(12, SELECT_BY_POS)==true)
{
order_type=OrderType();
// ...
}
else
Print("OrderSelect() returned error - ",GetLastError());
MQL4 Reference / Trade Signals
Trade Signals
This is the group of functions intended for managing trade
signals. The functions allow:
get information about trade signals, available for
copying,
get and set the signal copy settings,
subscribe and unsubscribe to the signal copying using
MQL4 language functions.
Function Action
SignalBaseGetDouble Returns the value of double type
property for selected signal
SignalBaseGetInteger Returns the value of integer type
property for selected signal
SignalBaseGetString Returns the value of string type
property for selected signal
SignalBaseSelect Selects a signal from signals, available
in terminal for further working with it
SignalBaseTotal Returns the total amount of signals,
available in terminal
SignalInfoGetDouble Returns the value of double type
property of signal copy settings
SignalInfoGetInteger Returns the value of integer type
property of signal copy settings
SignalInfoGetString Returns the value of string type
property of signal copy settings
Function Action
SignalInfoSetDouble Sets the value of double type property
of signal copy settings
SignalInfoSetInteger Sets the value of integer type property
of signal copy settings
SignalSubscribe Subscribes to the trading signal
SignalUnsubscribe Cancels subscription
MQL4 Reference / Trade Signals / SignalBaseGetDouble
SignalBaseGetDouble
Returns the value of double type property for selected signal.
double SignalBaseGetDouble( ENUM_SIGNAL_BASE_DOUBLE property_id // propert
);
Parameters
property_id
[in] Signal property identifier. The value can be one of the values of the
ENUM_SIGNAL_BASE_DOUBLE enumeration.
Returned value
The value of double type property of the selected signal.
MQL4 Reference / Trade Signals / SignalBaseGetInteger
SignalBaseGetInteger
Returns the value of integer type property for selected signal.
long SignalBaseGetInteger( ENUM_SIGNAL_BASE_INTEGER property_id // propert
);
Parameters
property_id
[in] Signal property identifier. The value can be one of the values of the
ENUM_SIGNAL_BASE_INTEGER enumeration.
Returned value
The value of integer type property of the selected signal.
MQL4 Reference / Trade Signals / SignalBaseGetString
SignalBaseGetString
Returns the value of string type property for selected signal.
string SignalBaseGetString( ENUM_SIGNAL_BASE_STRING property_id // propert
);
Parameters
property_id
[in] Signal property identifier. The value can be one of the values of the
ENUM_SIGNAL_BASE_STRING enumeration.
Returned value
The value of string type property of the selected signal.
MQL4 Reference / Trade Signals / SignalBaseSelect
SignalBaseSelect
Selects a signal from signals, available in terminal for further working with it.
bool SignalBaseSelect( int index // signal index
);
Parameters
index
[in] Signal index in base of trading signals.
Returned value
Returns true if successful, otherwise returns false. To read more about the error call
GetLastError().
Example:
void OnStart()
{
//--- get total amount of signals in the terminal
int total=SignalBaseTotal();
//--- process all signals
for(int i=0;i<total;i++)
{
//--- select the signal by index
if(SignalBaseSelect(i))
{
//--- get signal properties
long id =SignalBaseGetInteger(SIGNAL_BASE_ID); // signal id
long pips =SignalBaseGetInteger(SIGNAL_BASE_PIPS); // profit in pi
long subscr=SignalBaseGetInteger(SIGNAL_BASE_SUBSCRIBERS); // number of su
string name =SignalBaseGetString(SIGNAL_BASE_NAME); // signal name
double price =SignalBaseGetDouble(SIGNAL_BASE_PRICE); // signal price
string curr =SignalBaseGetString(SIGNAL_BASE_CURRENCY); // signal curre
//--- print all profitable free signals with subscribers
if(price==0.0 && pips>0 && subscr>0)
PrintFormat("id=%d, name=\"%s\", currency=%s, pips=%d, subscribers=%d",id
}
else PrintFormat("Error in call of SignalBaseSelect. Error code=%d",GetLastErro
}
}
MQL4 Reference / Trade Signals / SignalBaseTotal
SignalBaseTotal
Returns the total amount of signals, available in terminal.
int SignalBaseTotal();
Returned value
The total amount of signals, available in terminal.
MQL4 Reference / Trade Signals / SignalInfoGetDouble
SignalInfoGetDouble
Returns the value of double type property of signal copy settings.
double SignalInfoGetDouble( ENUM_SIGNAL_INFO_DOUBLE property_id // propert
);
Parameters
property_id
[in] Signal copy settings property identifier. The value can be one of the values of the
ENUM_SIGNAL_INFO_DOUBLE enumeration.
Returned value
The value of double type property of signal copy settings.
MQL4 Reference / Trade Signals / SignalInfoGetInteger
SignalInfoGetInteger
Returns the value of integer type property of signal copy settings.
long SignalInfoGetInteger( ENUM_SIGNAL_INFO_INTEGER property_id // propert
);
Parameters
property_id
[in] Signal copy settings property identifier. The value can be one of the values of the
ENUM_SIGNAL_INFO_INTEGER enumeration.
Returned value
The value of integer type property of signal copy settings.
MQL4 Reference / Trade Signals / SignalInfoGetString
SignalInfoGetString
Returns the value of string type property of signal copy settings.
string SignalInfoGetString( ENUM_SIGNAL_INFO_STRING property_id // propert
);
Parameters
property_id
[in] Signal copy settings property identifier. The value can be one of the values of the
ENUM_SIGNAL_INFO_STRING enumeration.
Returned value
The value of string type property of signal copy settings.
MQL4 Reference / Trade Signals / SignalInfoSetDouble
SignalInfoSetDouble
Sets the value of double type property of signal copy settings.
bool SignalInfoSetDouble( ENUM_SIGNAL_INFO_DOUBLE property_id, // propert
double value // new value
);
Parameters
property_id
[in] Signal copy settings property identifier. The value can be one of the values of the
ENUM_SIGNAL_INFO_DOUBLE enumeration.
value
[in] The value of signal copy settings property.
Returned value
Returns true if property has been changed, otherwise returns false. To read more about
the error call GetLastError().
MQL4 Reference / Trade Signals / SignalInfoSetInteger
SignalInfoSetInteger
Sets the value of integer type property of signal copy settings.
bool SignalInfoSetInteger( ENUM_SIGNAL_INFO_INTEGER property_id, // proper
long value // new value
);
Parameters
property_id
[in] Signal copy settings property identifier. The value can be one of the values of the
ENUM_SIGNAL_INFO_INTEGER enumeration.
value
[in] The value of signal copy settings property.
Returned value
Returns true if property has been changed, otherwise returns false. To read more about
the error call GetLastError().
MQL4 Reference / Trade Signals / SignalSubscribe
SignalSubscribe
Subscribes to the trading signal.
bool SignalSubscribe( long signal_id // signal id
);
Parameters
signal_id
[in] Signal identifier.
Returned value
Returns true if subscription was successful, otherwise returns
false. To read more about the error call GetLastError().
MQL4 Reference / Trade Signals / SignalUnsubscribe
SignalUnsubscribe
Cancels subscription.
bool SignalUnsubscribe();
Returned value
Returns true if subscription has been canceled
successfully, otherwise returns false. To read more about
the error call GetLastError().
MQL4 Reference / Global Variables of the Terminal
GlobalVariableCheck
Checks the existence of a global variable with the specified name
bool GlobalVariableCheck( string name // Global variable name
);
Parameters
name
[in] Global variable name.
Return Value
Returns true, if the global variable exists, otherwise returns false.
Global variables exist in the client terminal during 4 weeks since their last
use, then they are automatically deleted.
See also
GlobalVariableTime()
MQL4 Reference / Global Variables of the Terminal / GlobalVariableTime
GlobalVariableTime
Returns the time when the global variable was last accessed.
datetime GlobalVariableTime( string name // name
);
Parameters
name
[in] Name of the global variable.
Return Value
The function returns time of last accessing the specified
global variable. Addressing a variable for its value, for
example using the GlobalVariableGet() and
GlobalVariableCheck() functions, also modifies the time of
last access. In order to obtain error details, call the
GetLastError() function.
Note
Global variables exist in the client terminal during 4 weeks
since they were called last. After that they are
automatically deleted.
See also
GlobalVariableCheck()
MQL4 Reference / Global Variables of the Terminal / GlobalVariableDel
GlobalVariableDel
Deletes a global variable from the client terminal.
bool GlobalVariableDel( string name // Global variable name
);
Parameters
name
[in] Global variable name.
Return Value
If successful, the function returns true, otherwise it returns false. To
obtain an information about the error it is necessary to call the function
GetLastError().
Note
Global variables exist in the client terminal during 4 weeks since their
last use, then they are automatically deleted.
MQL4 Reference / Global Variables of the Terminal / GlobalVariableGet
GlobalVariableGet
Returns the value of an existing global variable of the client terminal. There are 2
variants of the function.
1. Immediately returns the value of the global variable.
double GlobalVariableGet( string name // Global variable name
);
2. Returns true or false depending on the success of the function run. If successful, the
global variable of the client terminal is placed in a variable passed by reference in the
second parameter.
bool GlobalVariableGet(
string name, // Global variable name
double& double_var // This variable will contain the value of the global v
);
Parameters
name
[in] Global variable name.
double_var
[out] Target variable of the double type, which accepts the value stored in a the
global variable of the client terminal.
Return Value
The value of the existing global variable or 0 in case of an error. For more details about
the error, call GetLastError().
Note
Global variables exist in the client terminal during 4 weeks since their last use, then
they are automatically deleted.
MQL4 Reference / Global Variables of the Terminal / GlobalVariableName
GlobalVariableName
Returns the name of a global variable by its ordinal number.
string GlobalVariableName( int index // Global variable number in the list o
);
Parameters
index
[in] Sequence number in the list of global variables. It should be greater than or equal
to 0 and less than GlobalVariablesTotal().
Return Value
Global variable name by its ordinal number in the list of global variables. For more
details about the error, call GetLastError().
Note
Global variables exist in the client terminal during 4 weeks since their last use, then
they are automatically deleted.
MQL4 Reference / Global Variables of the Terminal / GlobalVariableSet
GlobalVariableSet
Sets a new value for a global variable. If the variable does not exist, the
system creates a new global variable.
datetime GlobalVariableSet( string name, // Global variable name
double value // Value to set
);
Parameters
name
[in] Global variable name.
value
[in] The new numerical value.
Return Value
If successful, the function returns the last modification time, otherwise 0.
For more details about the error, call GetLastError().
Note
A global variable name should not exceed 63 characters. Characters not
belonging to the current code page are not allowed (characters that cannot
be converted from Unicode to ANSI are replaced with '?'). If programs are to
be distributed among users with different code pages, we strongly
recommend using Latin characters in global variable names.
Global variables exist in the client terminal during 4 weeks since their last
use, then they are automatically deleted.
MQL4 Reference / Global Variables of the Terminal /
GlobalVariablesFlush
GlobalVariablesFlush
Forcibly saves contents of all global variables to a disk.
void GlobalVariablesFlush();
Return Value
No return value.
Note
The terminal writes all the global variables when the
work is over, but data can be lost at a sudden computer
operation failure. This function allows independently
controlling the process of saving global variables in case
of contingency.
MQL4 Reference / Global Variables of the Terminal / GlobalVariableTemp
GlobalVariableTemp
The function attempts to create a temporary global variable. If the
variable doesn't exist, the system creates a new temporary global
variable.
bool GlobalVariableTemp( string name // Global variable name
);
Parameters
name
[in] The name of a temporary global variable.
Return Value
If successful, the function returns true, otherwise - false. To get details
about the error, you should call the GetLastError() function.
Note
Temporary global variables exist only while the client terminal is
running; after the terminal shutdown they are automatically deleted.
Note that during the execution of GlobalVariablesFlush() temporary
global variables are not written to a disk.
After a temporary global variable has been created, it can be accessed
and modified the same as global variable of the client terminal.
MQL4 Reference / Global Variables of the Terminal / GlobalVariableSetOnCondition
GlobalVariableSetOnCondition
Sets the new value of the existing global variable if the current value equals to the third
parameter check_value. If there is no global variable, the function will generate an error
ERR_GLOBALVARIABLE_NOT_FOUND (4501) and return false.
bool GlobalVariableSetOnCondition( string name, // Global variable nam
double value, // New value for variable if condition is true
double check_value // Check value condition
);
Parameters
name
[in] The name of a global variable.
value
[in] New value.
check_value
[in] The value to check the current value of the global variable.
Return Value
If successful, the function returns true, otherwise it returns false. For details about the
error call GetLastError(). If the current value of the global variable is different from
check_value, the function returns false.
Note
Function provides atomic access to the global variable, so it can be used for providing
of a mutex at interaction of several Expert Advisors working simultaneously within one
client terminal.
MQL4 Reference / Global Variables of the Terminal / GlobalVariablesDeleteAll
GlobalVariablesDeleteAll
Deletes global variables of the client terminal.
int GlobalVariablesDeleteAll( string prefix_name=NULL, // All global varia
datetime limit_data=0 // All global variables that were changed before
);
Parameters
prefix_name=NULL
[in] Name prefix global variables to remove. If you specify a prefix NULL or empty
string, then all variables that meet the data criterion will be deleted.
limit_data=0
[in] Optional parameter. Date to select global variables by the time of their last
modification. The function removes global variables, which were changed before this
date. If the parameter is zero, then all variables that meet the first criterion (prefix)
are deleted.
Return Value
The number of deleted variables.
Note
If both options are equal to zero (prefix_name = NULL and limit_data = 0), then
function deletes all global variables of the terminal. If both parameters are specified,
then it deletes global variables corresponding to both parameters.
Global variables exist in the client terminal during 4 weeks since their last use, then
they are automatically deleted.
MQL4 Reference / Global Variables of the Terminal /
GlobalVariablesTotal
GlobalVariablesTotal
Returns the total number of global variables of the client
terminal.
int GlobalVariablesTotal();
Return Value
Number of global variables.
Note
Global variables exist in the client terminal during 4
weeks since their last use, then they are automatically
deleted. Call of a global variable is not only setting a
new value, but also reading the value of the global
variable.
MQL4 Reference / File Functions
File Functions
This is a group of functions for working with files.
For security reasons, work with files is strictly controlled in the MQL4 language. Files
with which file operations are conducted using MQL4 means cannot be outside the file
sandbox.
There are two directories (with subdirectories) in which working files can be located:
terminal_data_folder\MQL4\Files\ (in the terminal menu select to view "File" - "Open
the data directory");
the common folder for all the terminals installed on a computer - usually located in
the directory C:\Documents and Settings\All Users\Application
Data\MetaQuotes\Terminal\Common\Files.
There is a program method to obtain names of these catalogs using the
TerminalInfoString() function, using the ENUM_TERMINAL_INFO_STRING enumeration:
//--- Folder that stores the terminal data string terminal_data_path=TerminalInfoSt
//--- Common folder for all client terminals
string common_data_path=TerminalInfoString(TERMINAL_COMMONDATA_PATH);
If the file is opened for writing using FileOpen(), all subfolders specified in the path will
be created if there are no such ones.
MQL4 Reference / File Functions / FileFindFirst
FileFindFirst
The function starts the search of files or subdirectories in a directory in accordance with
the specified filter.
long FileFindFirst( const string file_filter, // String - search filter
string& returned_filename, // Name of the file or subdirectory found
int common_flag=0 // Defines the search
);
Parameters
file_filter
[in] Search filter. A subdirectory (or sequence of nested subdirectories) relative to the
\Files directory, in which files should be searched for, can be specified in the filter.
returned_filename
[out] The returned parameter, where, in case of success, the name of the first found
file or subdirectory is placed. Only the file name is returned (including the extension),
the directories and subdirectories are not included no matter if they are specified or
not in the search filter.
common_flag
[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then
the file is located in a shared folder for all client terminals \Terminal\Common\Files.
Otherwise, the file is located in a local folder.
Return Value
Returns handle of the object searched, which should be used for further sorting of files
and subdirectories by the FileFindNext() function, or INVALID_HANDLE when there is no
file and subdirectory corresponding to the filter (in the particular case - when the
directory is empty). After searching, the handle must be closed using the
FileFindClose() function.
Note
For security reasons, work with files is strictly controlled in the MQL4 language. Files
with which file operations are conducted using MQL4 means, cannot be outside the file
sandbox.
Example:
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- filter
input string InpFilter="Dir1\\*";
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string file_name;
string int_dir="";
int i=1,pos=0,last_pos=-1;
//--- search for the last backslash
while(!IsStopped())
{
pos=StringFind(InpFilter,"\\",pos+1);
if(pos>=0)
last_pos=pos;
else
break;
}
//--- the filter contains the folder name
if(last_pos>=0)
int_dir=StringSubstr(InpFilter,0,last_pos+1);
//--- get the search handle in the root of the local folder
long search_handle=FileFindFirst(InpFilter,file_name);
//--- check if the FileFindFirst() is executed successfully
if(search_handle!=INVALID_HANDLE)
{
//--- in a loop, check if the passed strings are the names of files or director
do
{
ResetLastError();
//--- if it's a file, the function returns true, and if it's a directory, it
FileIsExist(int_dir+file_name);
PrintFormat("%d : %s name = %s",i,GetLastError()==ERR_FILE_IS_DIRECTORY ? "D
i++;
}
while(FileFindNext(search_handle,file_name));
//--- close the search handle
FileFindClose(search_handle);
}
else
Print("Files not found!");
}
See also
FileFindNext(), FileFindClose()
MQL4 Reference / File Functions / FileFindNext
FileFindNext
The function continues the search started by FileFindFirst().
bool FileFindNext( long search_handle, // Search handle
string& returned_filename // Name of the file or subdirectory found
);
Parameters
search_handle
[in] Search handle, retrieved by FileFindFirst().
returned_filename
[out] The name of the next file or subdirectory found. Only the file name is returned
(including the extension), the directories and subdirectories are not included no
matter if they are specified or not in the search filter.
Return Value
If successful returns true, otherwise false.
Example:
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- filter
input string InpFilter="*";
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string file_name;
int i=1;
//--- receive search handle in local folder's root
long search_handle=FileFindFirst(InpFilter,file_name);
//--- check if FileFindFirst() function executed successfully
if(search_handle!=INVALID_HANDLE)
{
//--- check if the passed strings are file or directory names in the loop
do
{
ResetLastError();
//--- if this is a file, the function will return true, if it is a directory
FileIsExist(file_name);
PrintFormat("%d : %s name = %s",i,GetLastError()==ERR_FILE_IS_DIRECTORY ? "D
i++;
}
while(FileFindNext(search_handle,file_name));
//--- close search handle
FileFindClose(search_handle);
}
else
Print("Files not found!");
}
See also
FileFindFirst(), FileFindClose()
MQL4 Reference / File Functions / FileFindClose
FileFindClose
The function closes the search handle.
void FileFindClose( long search_handle // Search handle
);
Parameters
search_handle
[in] Search handle, retrieved by FileFindFirst().
Return Value
No value returned.
Note
Function must be called to free up system resources.
Example:
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- filter
input string InpFilter="*";
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string file_name;
int i=1;
//--- receive search handle in local folder's root
long search_handle=FileFindFirst(InpFilter,file_name);
//--- check if FileFindFirst() function executed successfully
if(search_handle!=INVALID_HANDLE)
{
//--- check if the passed strings are file or directory names in the loop
do
{
ResetLastError();
//--- if this is a file, the function will return true, if it is a directory
FileIsExist(file_name);
PrintFormat("%d : %s name = %s",i,GetLastError()==5018 ? "Directory" : "File
i++;
}
while(FileFindNext(search_handle,file_name));
//--- close search handle
FileFindClose(search_handle);
}
else
Print("Files not found!");
}
See also
FileFindFirst(), FileFindNext()
MQL4 Reference / File Functions / FileIsExist
FileIsExist
Checks the existence of a file.
bool FileIsExist( const string file_name, // File name
int common_flag=0 // Search area
);
Parameters
file_name
[in] The name of the file being checked
common_flag=0
[in] Flag determining the location of the file. If common_flag = FILE_COMMON,
then the file is located in a shared folder for all client terminals
\Terminal\Common\Files. Otherwise, the file is located in a local folder.
Return Value
Returns true, if the specified file exists.
Note
Checked file can turn out to be a subdirectory. In this case, FileIsExist() function
will return false, while error 5019 will be logged in _LastError variable - "This is a
directory, not a file" (see example for FileFindFirst() function).
For security reasons, work with files is strictly controlled in the MQL4 language.
Files with which file operations are conducted using MQL4 means, cannot be outside
the file sandbox.
If common_flag = FILE_COMMON, then the function looks for the file in a shared
folder for all client terminals \Terminal\Common\Files, otherwise the function looks
for a file in a local folder (MQL4\Files or MQL4\Tester\Files in the case of testing).
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- date for old files
input datetime InpFilesDate=D'2013.01.01 00:00';
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string file_name; // variable for storing file names
string filter="*.txt"; // filter for searching the files
datetime create_date; // file creation date
string files[]; // list of file names
int def_size=25; // array size by default
int size=0; // number of files
//--- allocate memory for the array
ArrayResize(files,def_size);
//--- receive the search handle in the local folder's root
long search_handle=FileFindFirst(filter,file_name);
//--- check if FileFindFirst() executed successfully
if(search_handle!=INVALID_HANDLE)
{
//--- searching files in the loop
do
{
files[size]=file_name;
//--- increase the array size
size++;
if(size==def_size)
{
def_size+=25;
ArrayResize(files,def_size);
}
//--- reset the error value
ResetLastError();
//--- receive the file creation date
create_date=(datetime)FileGetInteger(file_name,FILE_CREATE_DATE,false);
//--- check if the file is old
if(create_date<InpFilesDate)
{
PrintFormat("%s file deleted!",file_name);
//--- delete the old file
FileDelete(file_name);
}
}
while(FileFindNext(search_handle,file_name));
//--- close the search handle
FileFindClose(search_handle);
}
else
{
Print("Files not found!");
return;
}
//--- check what files have remained
PrintFormat("Results:");
for(int i=0;i<size;i++)
{
if(FileIsExist(files[i]))
PrintFormat("%s file exists!",files[i]);
else
PrintFormat("%s file deleted!",files[i]);
}
}
See also
FileFindFirst()
MQL4 Reference / File Functions / FileOpen
FileOpen
The function opens the file with the specified name and flag.
int FileOpen( string file_name, // File name
int open_flags, // Combination of flags
short delimiter=';', // Delimiter
uint codepage=CP_ACP // Code page
);
Parameters
file_name
[in] The name of the file can contain subfolders. If the file is opened for writing,
these subfolders will be created if there are no such ones.
open_flags
[in] combination of flags determining the operation mode for the file. The flags are
defined as follows:
FILE_READ file is opened for reading
FILE_WRITE file is opened for writing
FILE_BIN binary read-write mode (no conversion from a string and to a string)
FILE_CSV file of csv type (all recorded items are converted to the strings of unicode or
ansi type, and are separated by a delimiter)
FILE_TXT a simple text file (the same as csv, but the delimiter is not taken into
account)
FILE_ANSI lines of ANSI type (single-byte symbols)
FILE_UNICODE lines of UNICODE type (double-byte characters)
FILE_SHARE_READ shared reading from several programs
FILE_SHARE_WRITE shared writing from several programs
FILE_COMMON location of the file in a shared folder for all client terminals
\Terminal\Common\Files
delimiter=';'
[in] value to be used as a separator in txt or csv-file. If the csv-file delimiter is not
specified, the default delimiter is ";". If the txt-file delimiter is not specified, then no
separator is used. If the separator is clearly set to 0, then no separator is used.
codepage=CP_ACP
[in] Optional parameter. The value of the code page. For the most-used code pages
provide appropriate constants.
Return Value
If a file has been opened successfully, the function returns the file handle, which is
then used to access the file data. In case of failure returns INVALID_HANDLE.
Note
For security reasons, work with files is strictly controlled in the MQL4 language. Files
with which file operations are conducted using MQL4 means, cannot be outside the file
sandbox.
The file is opened in the folder of the client terminal in the subfolder MQL4\files (or
Tester\Files in case of testing). If FILE_COMMON is specified among flags, the file is
opened in a shared folder for all MetaTrader 4 client terminals.
"Named pipes" can be opened according to the following rules:
Pipe name is a string, which should have the following look:
"\\servername\pipe\pipename", where servername - server name in the network,
while pipename is a pipe name. If the pipes are used on the same computer, the
server name can be omitted but a point should be inserted instead of it:
"\\.\pipe\pipename". A client trying to connect the pipe should know its name.
FileFlush() and FileSeek() should be called to the beginning of a file between
sequential operations of reading from the pipe and writing to it.
A special symbol '\' is used in shown strings. Therefore, '\' should be doubled when
writing a name in MQL4 application. It means that the above example should have the
following look in the code: "\\\\servername\\pipe\\pipename".
More information about working with named pipes can be found in the article
"Communicating With MetaTrader 5 Using Named Pipes Without Using DLLs".
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- incorrect file opening method
string terminal_data_path=TerminalInfoString(TERMINAL_DATA_PATH);
string filename=terminal_data_path+"\\MQL4\\Files\\"+"fractals.csv";
int filehandle=FileOpen(filename,FILE_WRITE|FILE_CSV);
if(filehandle<0)
{
Print("Failed to open the file by the absolute path ");
Print("Error code ",GetLastError());
}
//--- correct way of working in the "file sandbox"
ResetLastError();
filehandle=FileOpen("fractals.csv",FILE_WRITE|FILE_CSV);
if(filehandle!=INVALID_HANDLE)
{
FileWrite(filehandle,TimeCurrent(),Symbol(), EnumToString(ENUM_TIMEFRAMES(_Peri
FileClose(filehandle);
Print("FileOpen OK");
}
else Print("Operation FileOpen failed, error ",GetLastError());
//--- another example with the creation of an enclosed directory in MQL4\Files\
string subfolder="Research";
filehandle=FileOpen(subfolder+"\\fractals.txt",FILE_WRITE|FILE_CSV);
if(filehandle!=INVALID_HANDLE)
{
FileWrite(filehandle,TimeCurrent(),Symbol(), EnumToString(ENUM_TIMEFRAMES(_Peri
FileClose(filehandle);
Print("The file most be created in the folder "+terminal_data_path+"\\"+subfold
}
else Print("File open failed, error ",GetLastError());
}
See also
Use of a Codepage, FileFindFirst(), FolderCreate(), File opening flags
MQL4 Reference / File Functions / FileClose
FileClose
Close the file previously opened by FileOpen().
void FileClose( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
No value returned.
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="file.txt"; // file name
input string InpDirectoryName="Data"; // directory name
input int InpEncodingType=FILE_ANSI; // ANSI=32 or UNICODE=64
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- print the path to the file we are going to use
PrintFormat("Working %s\\Files\\ folder",TerminalInfoString(TERMINAL_DATA_PATH));
//--- reset the error value
ResetLastError();
//--- open the file for reading (if the file does not exist, the error will occur)
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_TXT|InpE
if(file_handle!=INVALID_HANDLE)
{
//--- print the file contents
while(!FileIsEnding(file_handle))
Print(FileReadString(file_handle));
//--- close the file
FileClose(file_handle);
}
else
PrintFormat("Error, code = %d",GetLastError());
}
See also
FileOpen()
MQL4 Reference / File Functions / FileCopy
FileCopy
The function copies the original file from a local or shared folder to another file.
bool FileCopy( const string src_file_name, // Name of a source file
int common_flag, // Location
const string dst_file_name, // Name of the destination file
int mode_flags // Access mode
);
Parameters
src_file_name
[in] File name to copy.
common_flag
[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then
the file is located in a shared folder for all client terminals \Terminal\Common\Files.
Otherwise, the file is located in a local folder (for example, common_flag=0).
dst_file_name
[in] Result file name.
mode_flags
[in] Access flags. The parameter can contain only 2 flags: FILE_REWRITE and/or
FILE_COMMON - other flags are ignored. If the file already exists, and the
FILE_REWRITE flag hasn't been specified, then the file will not be rewritten, and the
function will return false.
Return Value
In case of failure the function returns false.
Note
For security reasons, work with files is strictly controlled in the MQL4 language. Files
with which file operations are conducted using MQL4 means, cannot be outside the file
sandbox.
If the new file already exists, the copy will be made depending on the availability of
the FILE_REWRITE flag in the mode_flags parameter.
Example:
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpSrc="source.txt"; // source
input string InpDst="destination.txt"; // copy
input int InpEncodingType=FILE_ANSI; // ANSI=32 or UNICODE=64
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- display the source contents (it must exist)
if(!FileDisplay(InpSrc))
return;
//--- check if the copy file already exists (may not be created)
if(!FileDisplay(InpDst))
{
//--- the copy file does not exist, copying without FILE_REWRITE flag (correct
if(FileCopy(InpSrc,0,InpDst,0))
Print("File is copied!");
else
Print("File is not copied!");
}
else
{
//--- the copy file already exists, try to copy without FILE_REWRITE flag (inco
if(FileCopy(InpSrc,0,InpDst,0))
Print("File is copied!");
else
Print("File is not copied!");
//--- InpDst file's contents remains the same
FileDisplay(InpDst);
//--- copy once more with FILE_REWRITE flag (correct copying if the file exists
if(FileCopy(InpSrc,0,InpDst,FILE_REWRITE))
Print("File is copied!");
else
Print("File is not copied!");
}
//--- receive InpSrc file copy
FileDisplay(InpDst);
}
//+------------------------------------------------------------------+
//| Read the file contents |
//+------------------------------------------------------------------+
bool FileDisplay(const string file_name)
{
//--- reset the error value
ResetLastError();
//--- open the file
int file_handle=FileOpen(file_name,FILE_READ|FILE_TXT|InpEncodingType);
if(file_handle!=INVALID_HANDLE)
{
//--- display the file contents in the loop
Print("+---------------------+");
PrintFormat("File name = %s",file_name);
while(!FileIsEnding(file_handle))
Print(FileReadString(file_handle));
Print("+---------------------+");
//--- close the file
FileClose(file_handle);
return(true);
}
//--- failed to open the file
PrintFormat("%s is not opened, error = %d",file_name,GetLastError());
return(false);
}
MQL4 Reference / File Functions / FileDelete
FileDelete
Deletes the specified file in a local folder of the client terminal.
bool FileDelete( const string file_name, // File name to delete
int common_flag=0 // Location of the file to delete
);
Parameters
file_name
[in] File name.
common_flag=0
[in] Flag determining the file location. If common_flag = FILE_COMMON, then the
file is located in a shared folder for all client terminals \Terminal\Common\Files.
Otherwise, the file is located in a local folder.
Return Value
In case of failure the function returns false.
Note
For security reasons, work with files is strictly controlled in the MQL4 language.
Files with which file operations are conducted using MQL4 means, cannot be outside
the file sandbox.
Deletes the specified file from a local folder of the client terminal (MQL4\Files or
MQL4\Tester\Files in case of testing). If common_flag = FILE_COMMON, then the
function removes the file from the shared folder for all client terminals.
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- date for old files
input datetime InpFilesDate=D'2013.01.01 00:00';
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string file_name; // variable for storing file names
string filter="*.txt"; // filter for searching the files
datetime create_date; // file creation date
string files[]; // list of file names
int def_size=25; // array size by default
int size=0; // number of files
//--- allocate memory for the array
ArrayResize(files,def_size);
//--- receive the search handle in the local folder's root
long search_handle=FileFindFirst(filter,file_name);
//--- check if FileFindFirst() executed successfully
if(search_handle!=INVALID_HANDLE)
{
//--- searching files in the loop
do
{
files[size]=file_name;
//--- increase the array size
size++;
if(size==def_size)
{
def_size+=25;
ArrayResize(files,def_size);
}
//--- reset the error value
ResetLastError();
//--- receive the file creation date
create_date=(datetime)FileGetInteger(file_name,FILE_CREATE_DATE,false);
//--- check if the file is old
if(create_date<InpFilesDate)
{
PrintFormat("%s file deleted!",file_name);
//--- delete the old file
FileDelete(file_name);
}
}
while(FileFindNext(search_handle,file_name));
//--- close the search handle
FileFindClose(search_handle);
}
else
{
Print("Files not found!");
return;
}
//--- check what files have remained
PrintFormat("Results:");
for(int i=0;i<size;i++)
{
if(FileIsExist(files[i]))
PrintFormat("%s file exists!",files[i]);
else
PrintFormat("%s file deleted!",files[i]);
}
}
MQL4 Reference / File Functions / FileMove
FileMove
Moves a file from a local or shared folder to another folder.
bool FileMove( const string src_file_name, // File name for the move operation
int common_flag, // Location
const string dst_file_name, // Name of the destination file
int mode_flags // Access mode
);
Parameters
src_file_name
[in] File name to move/rename.
common_flag
[in] Flag determining the location of the file. If common_flag = FILE_COMMON, then
the file is located in a shared folder for all client terminals \Terminal\Common\Files.
Otherwise, the file is located in a local folder (common_flag=0).
dst_file_name
[in] File name after operation
mode_flags
[in] Access flags. The parameter can contain only 2 flags: FILE_REWRITE and/or
FILE_COMMON - other flags are ignored. If the file already exists and the
FILE_REWRITE flag isn't specified, the file will not be rewritten, and the function will
return false.
Return Value
In case of failure the function returns false.
Note
For security reasons, work with files is strictly controlled in the MQL4 language. Files
with which file operations are conducted using MQL4 means, cannot be outside the file
sandbox.
If the new file already exists, the copy will be made depending on the availability of
the FILE_REWRITE flag in the mode_flags parameter.
Example:
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpSrcName="data.txt";
input string InpDstName="newdata.txt";
input string InpSrcDirectory="SomeFolder";
input string InpDstDirectory="OtherFolder";
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string local=TerminalInfoString(TERMINAL_DATA_PATH);
string common=TerminalInfoString(TERMINAL_COMMONDATA_PATH);
//--- get file paths
string src_path=InpSrcDirectory+"//"+InpSrcName;
string dst_path=InpDstDirectory+"//"+InpDstName;
//--- check if the source file exists (if not - exit)
if(FileIsExist(src_path))
PrintFormat("%s file exists in the %s\\Files\\%s folder",InpSrcName,local,InpSr
else
{
PrintFormat("Error, %s source file not found",InpSrcName);
return;
}
//--- check if the result file already exists
if(FileIsExist(dst_path,FILE_COMMON))
{
PrintFormat("%s file exists in the %s\\Files\\%s folder",InpDstName,common,InpD
//--- file exists, moving should be performed with FILE_REWRITE flag
ResetLastError();
if(FileMove(src_path,0,dst_path,FILE_COMMON|FILE_REWRITE))
PrintFormat("%s file moved",InpSrcName);
else
PrintFormat("Error! Code = %d",GetLastError());
}
else
{
PrintFormat("%s file does not exist in the %s\\Files\\%s folder",InpDstName,com
//--- the file does not exist, moving should be performed without FILE_REWRITE
ResetLastError();
if(FileMove(src_path,0,dst_path,FILE_COMMON))
PrintFormat("%s file moved",InpSrcName);
else
PrintFormat("Error! Code = %d",GetLastError());
}
//--- the file is moved; let's check it out
if(FileIsExist(dst_path,FILE_COMMON) && !FileIsExist(src_path,0))
Print("Success!");
else
Print("Error!");
}
See also
FileIsExist()
MQL4 Reference / File Functions / FileFlush
FileFlush
Writes to a disk all data remaining in the input/output file buffer.
void FileFlush( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
No value returned.
Note
When writing to a file, the data may be actually found there only after some time. To
save the data in the file instantly, use FileFlush() function. If the function is not used,
part of the data that has not been stored in the disk yet, will be forcibly written there
only when the file is closed using FileClose() function.
The function should be used when written data is of a certain value. It should be kept
in mind that frequent function call may affect the program operation speed.
Function FileFlush () must be called between the operations of reading from a file and
writing to it.
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- file name for writing
input string InpFileName="example.csv"; // file name
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- reset error value
ResetLastError();
//--- open the file
int file_handle=FileOpen(InpFileName,FILE_READ|FILE_WRITE|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
//--- write data to the file
for(int i=0;i<1000;i++)
{
//--- call write function
FileWrite(file_handle,TimeCurrent(),SymbolInfoDouble(Symbol(),SYMBOL_BID),Sy
//--- save data on the disk at each 128th iteration
if((i & 127)==127)
{
//--- now, data will be located in the file and will not be lost in case
FileFlush(file_handle);
PrintFormat("i = %d, OK",i);
}
//--- 0.01 second pause
Sleep(10);
}
//--- close the file
FileClose(file_handle);
}
else
PrintFormat("Error, code = %d",GetLastError());
}
See also
FileClose()
MQL4 Reference / File Functions / FileGetInteger
FileGetInteger
Gets an integer property of a file. There are two variants of the function.
1. Get a property by the handle of a file.
long FileGetInteger( int file_handle, // File handle
ENUM_FILE_PROPERTY_INTEGER property_id // Property ID
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
file_name
[in] File name.
property_id
[in] File property ID. The value can be one of the values of the
ENUM_FILE_PROPERTY_INTEGER enumeration. If the second variant of the function is
used, you can receive only the values of the following properties: FILE_EXISTS,
FILE_CREATE_DATE, FILE_MODIFY_DATE, FILE_ACCESS_DATE and FILE_SIZE.
common_folder=false
[in] Points to the file location. If the parameter is false, terminal data folder is
viewed. Otherwise it is assumed that the file is in the shared folder of all terminals
\Terminal\Common\Files (FILE_COMMON).
Return Value
The value of the property. In case of an error, -1 is returned. To get an error code use
the GetLastError() function.
If a folder is specified when getting properties by the name, the function will have
error 5018 (ERR_MQL_FILE_IS_DIRECTORY) in any case, though the return value will be
correct.
Note
The function always changes the error code. In case of successful completion the error
code is reset to NULL.
Example:
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="data.csv";
input string InpDirectoryName="SomeFolder";
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string path=InpDirectoryName+"//"+InpFileName;
long l=0;
//--- open the file
ResetLastError();
int handle=FileOpen(path,FILE_READ|FILE_CSV);
if(handle!=INVALID_HANDLE)
{
//--- print all information about the file
Print(InpFileName," file info:");
FileInfo(handle,FILE_EXISTS,l,"bool");
FileInfo(handle,FILE_CREATE_DATE,l,"date");
FileInfo(handle,FILE_MODIFY_DATE,l,"date");
FileInfo(handle,FILE_ACCESS_DATE,l,"date");
FileInfo(handle,FILE_SIZE,l,"other");
FileInfo(handle,FILE_POSITION,l,"other");
FileInfo(handle,FILE_END,l,"bool");
FileInfo(handle,FILE_IS_COMMON,l,"bool");
FileInfo(handle,FILE_IS_TEXT,l,"bool");
FileInfo(handle,FILE_IS_BINARY,l,"bool");
FileInfo(handle,FILE_IS_CSV,l,"bool");
FileInfo(handle,FILE_IS_ANSI,l,"bool");
FileInfo(handle,FILE_IS_READABLE,l,"bool");
FileInfo(handle,FILE_IS_WRITABLE,l,"bool");
//--- close the file
FileClose(handle);
}
else
PrintFormat("%s file is not opened, ErrorCode = %d",InpFileName,GetLastError())
}
//+------------------------------------------------------------------+
//| Display the value of the file property |
//+------------------------------------------------------------------+
void FileInfo(const int handle,const ENUM_FILE_PROPERTY_INTEGER id,
long l,const string type)
{
//--- receive the property value
ResetLastError();
if((l=FileGetInteger(handle,id))!=-1)
{
//--- the value received, display it in the correct format
if(!StringCompare(type,"bool"))
Print(EnumToString(id)," = ",l ? "true" : "false");
if(!StringCompare(type,"date"))
Print(EnumToString(id)," = ",(datetime)l);
if(!StringCompare(type,"other"))
Print(EnumToString(id)," = ",l);
}
else
Print("Error, Code = ",GetLastError());
}
See also
File Operations, File Properties
MQL4 Reference / File Functions / FileIsEnding
FileIsEnding
Defines the end of a file in the process of reading.
bool FileIsEnding( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
The function returns true if the file end has been reached in the process of reading or
moving of the file pointer.
Note
To define the end of the file, the function tries to read the next string from it. If the
string does not exist, the function returns true, otherwise it returns false.
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="file.txt"; // file name
input string InpDirectoryName="Data"; // directory name
input int InpEncodingType=FILE_ANSI; // ANSI=32 or UNICODE=64
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- print the path to the file we are going to use
PrintFormat("Working %s\\Files\\ folder",TerminalInfoString(TERMINAL_DATA_PATH));
//--- reset the error value
ResetLastError();
//--- open the file for reading (if the file does not exist, the error will occur)
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_TXT|InpE
if(file_handle!=INVALID_HANDLE)
{
//--- print the file contents
while(!FileIsEnding(file_handle))
Print(FileReadString(file_handle));
//--- close the file
FileClose(file_handle);
}
else
PrintFormat("Error, code = %d",GetLastError());
}
MQL4 Reference / File Functions / FileIsLineEnding
FileIsLineEnding
Defines the line end in a text file in the process of reading.
bool FileIsLineEnding( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
Returns true if in the process of reading txt or csv-file reached the end of the line (the
characters CR-LF).
Example (the file obtained during the execution of an example for FileWriteString()
function is used here)
//+------------------------------------------------------------------+
//| Demo_FileIsLineEnding.mq5 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- parameters for data reading
input string InpFileName="RSI.csv"; // file name
input string InpDirectoryName="Data"; // directory name
//--- overbought variables
int ovb_size=0;
datetime ovb_time[];
//--- oversold variables
int ovs_size=0;
datetime ovs_time[];
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_CSV|FILE
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
double value;
//--- read data from file
while(!FileIsEnding(file_handle))
{
//--- read the first value in the string
value=FileReadNumber(file_handle);
//--- read to different arrays according to the function result
if(value>=70)
ReadData(file_handle,ovb_time,ovb_size);
else
ReadData(file_handle,ovs_time,ovs_size);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is read, %s file is closed",InpFileName);
//--- print data
PrintFormat("Overbought=%d",ovb_size);
for(int i=0; i<ovb_size; i++) Print(i," time=",TimeToString(ovb_time[i]));
PrintFormat("Oversold=%d",ovs_size);
for(int i=0; i<ovs_size; i++) Print(i," time=",TimeToString(ovs_time[i]));
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
return;
}
//---
}
//+------------------------------------------------------------------+
//| Read the file's string data |
//+------------------------------------------------------------------+
void ReadData(const int file_handle,datetime &arr[],int &size)
{
bool flag=false;
string str="";
//--- read till the end of the string or of the file is reached
while(!FileIsLineEnding(file_handle) && !FileIsEnding(file_handle))
{
//--- shift the position by reading the number
if(flag)
FileReadNumber(file_handle);
size++;
//--- increase the array size if necessary
if(size>ArraySize(arr)) ArrayResize(arr,size,100);
//--- read date
arr[size-1]=FileReadDatetime(file_handle);
//--- add to string
str+=" "+TimeToString(arr[size-1]);
//--- slip past the first iteration
flag=true;
}
Print(str);
}
See also
FileWriteString()
MQL4 Reference / File Functions / FileReadArray
FileReadArray
Reads from a file of BIN type arrays of any type except string (may be an array of
structures, not containing strings, and dynamic arrays).
uint FileReadArray( int file_handle, // File handle
void& array[], // Array to record
int start=0, // start array position to write
int count=WHOLE_ARRAY // count to read
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
array[]
[out] An array where the data will be loaded.
start=0
[in] Start position to read from the array.
count=WHOLE_ARRAY
[in] Number of elements to read. By default, reads the entire array
(count=WHOLE_ARRAY).
Return Value
Number of elements read or 0 in case of error. To obtain information about the
error, call the GetLastError() function. By default the count=WHOLE_ARRAY
elements will be read.
Note
String array can be read only from the file of TXT type. If necessary, the function
tries to increase the size of the array.
Example (the file obtained after execution of the example for FileWriteArray()
function is used here)
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="data.bin";
input string InpDirectoryName="SomeFolder";
//+------------------------------------------------------------------+
//| Structure for storing price data |
//+------------------------------------------------------------------+
struct prices
{
datetime date; // date
double bid; // bid price
double ask; // ask price
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- structure array
prices arr[];
//--- file path
string path=InpDirectoryName+"//"+InpFileName;
//--- open the file
ResetLastError();
int file_handle=FileOpen(path,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
//--- read all data from the file to the array
FileReadArray(file_handle,arr);
//--- receive the array size
int size=ArraySize(arr);
//--- print data from the array
for(int i=0;i<size;i++)
Print("Date = ",arr[i].date," Bid = ",arr[i].bid," Ask = ",arr[i].ask);
Print("Total data = ",size);
//--- close the file
FileClose(file_handle);
}
else
Print("File open failed, error ",GetLastError());
}
See also
Variables, FileWriteArray()
MQL4 Reference / File Functions / FileReadBool
FileReadBool
Reads from the file of CSV type string from the current position to a delimiter (or till the
end of the text line) and converts the read string to a bool type value.
bool FileReadBool( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
Line read may be set to "true", "false" or the symbolic representation of integers "0" or
"1". A nonzero value is converted to a logical true. The function returns the converted
value.
Example (the file obtained after executing the example for FileWrite() function is used
here)
//+------------------------------------------------------------------+
//| Demo_FileReadBool.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 2
//---- plot Label1
#property indicator_label1 "UpSignal"
#property indicator_type1 DRAW_ARROW
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 4
//---- plot Label2
#property indicator_label2 "DownSignal"
#property indicator_type2 DRAW_ARROW
#property indicator_color2 clrRed
#property indicator_style2 STYLE_SOLID
#property indicator_width2 4
//--- parameters for data reading
input string InpFileName="MACD.csv"; // file name
input string InpDirectoryName="Data"; // directory name
//--- global variables
int ind=0; // index
double upbuff[]; // indicator buffers of up arrows
double downbuff[]; // indicator buffer of down arrows
bool sign_buff[]; // signal array (true - buy, false - sell)
datetime time_buff[]; // array of signals' arrival time
int size=0; // size of signal arrays
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is open for reading",InpFileName);
//--- first, read the number of signals
size=(int)FileReadNumber(file_handle);
//--- allocate memory for the arrays
ArrayResize(sign_buff,size);
ArrayResize(time_buff,size);
//--- read data from the file
for(int i=0;i<size;i++)
{
//--- signal time
time_buff[i]=FileReadDatetime(file_handle);
//--- signal value
sign_buff[i]=FileReadBool(file_handle);
}
//--- close the file
FileClose(file_handle);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
return(INIT_FAILED);
}
//--- binding the arrays
SetIndexBuffer(0,upbuff,INDICATOR_DATA);
SetIndexBuffer(1,downbuff,INDICATOR_DATA);
//--- set the symbol code for drawing in PLOT_ARROW
PlotIndexSetInteger(0,PLOT_ARROW,241);
PlotIndexSetInteger(1,PLOT_ARROW,242);
//---- set the indicator values that will not be seen on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
ArraySetAsSeries(time,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(high,false);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
upbuff[i]=0;
downbuff[i]=0;
//--- check if any data is still present
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if dates coincide, use the value from the file
if(time[i]==time_buff[j])
{
//--- draw the arrow according to the signal
if(sign_buff[j])
upbuff[i]=high[i];
else
downbuff[i]=low[i];
//--- increase the counter
ind=j+1;
break;
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Type bool, FileWrite()
MQL4 Reference / File Functions / FileReadDatetime
FileReadDatetime
Reads from the file of CSV type a string of one of the formats: "YYYY.MM.DD HH:MI:SS",
"YYYY.MM.DD" or "HH:MI:SS" - and converts it into a value of datetime type.
datetime FileReadDatetime( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
The value of datetime type.
Example (the file obtained after executing the example for FileWrite() function is used
here)
//+------------------------------------------------------------------+
//| Demo_FileReadDateTime.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property indicator_chart_window
#property indicator_buffers 2
//---- plot Label1
#property indicator_label1 "UpSignal"
#property indicator_type1 DRAW_ARROW
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 4
//---- plot Label2
#property indicator_label2 "DownSignal"
#property indicator_type2 DRAW_ARROW
#property indicator_color2 clrRed
#property indicator_style2 STYLE_SOLID
#property indicator_width2 4
//--- parameters for data reading
input string InpFileName="MACD.csv"; // file name
input string InpDirectoryName="Data"; // directory name
//--- global variables
int ind=0; // index
double upbuff[]; // indicator buffers of up arrows
double downbuff[]; // indicator buffer of down arrows
bool sign_buff[]; // signal array (true - buy, false - sell)
datetime time_buff[]; // array of signals' arrival time
int size=0; // size of signal arrays
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_CSV);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is open for reading",InpFileName);
//--- first, read the number of signals
size=(int)FileReadNumber(file_handle);
//--- allocate memory for the arrays
ArrayResize(sign_buff,size);
ArrayResize(time_buff,size);
//--- read data from the file
for(int i=0;i<size;i++)
{
//--- signal time
time_buff[i]=FileReadDatetime(file_handle);
//--- signal value
sign_buff[i]=FileReadBool(file_handle);
}
//--- close the file
FileClose(file_handle);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
return(INIT_FAILED);
}
//--- binding the arrays
SetIndexBuffer(0,upbuff,INDICATOR_DATA);
SetIndexBuffer(1,downbuff,INDICATOR_DATA);
//--- set the symbol code for drawing in PLOT_ARROW
PlotIndexSetInteger(0,PLOT_ARROW,241);
PlotIndexSetInteger(1,PLOT_ARROW,242);
//---- set the indicator values that will not be seen on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
PlotIndexSetDouble(1,PLOT_EMPTY_VALUE,0);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
ArraySetAsSeries(time,false);
ArraySetAsSeries(low,false);
ArraySetAsSeries(high,false);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
upbuff[i]=0;
downbuff[i]=0;
//--- check if any data is still present
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if dates coincide, use the value from the file
if(time[i]==time_buff[j])
{
//--- draw the arrow according to the signal
if(sign_buff[j])
upbuff[i]=high[i];
else
downbuff[i]=low[i];
//--- increase the counter
ind=j+1;
break;
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Type datetime, StringToTime(), TimeToString(), FileWrite()
MQL4 Reference / File Functions / FileReadDouble
FileReadDouble
Reads a double-precision floating point number (double) from the current position of the
binary file.
double FileReadDouble( int file_handle, // File handle
int size=DOUBLE_VALUE // Size
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
size=DOUBLE_VALUE
Number of bytes (up to 8 inclusive), that should be read. The corresponding constants
are provided: DOUBLE_VALUE = 8, FLOAT_VALUE = 4, so the function can read the
whole value of double or float type.
Return Value
The value of double type.
Note
For more details about the error, call GetLastError().
Example (the file obtained after executing the example for FileWriteDouble() function is
used here)
//+------------------------------------------------------------------+
//| Demo_FileReadDouble.mq4 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
#property indicator_chart_window
#property indicator_buffers 1
//---- plot Label1
#property indicator_label1 "MA"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrGreen
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
#property indicator_separate_window
//--- data reading parameters
input string InpFileName="MA.bin"; // File name
input string InpDirectoryName="Data"; // Folder name
//--- global variables
int ind=0;
int size=0;
double ma_buff[];
datetime time_buff[];
//--- indicator buffer
double buff[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- first, read the amount of data in the file
size=(int)FileReadDouble(file_handle,DOUBLE_VALUE);
//--- allocate memory for the arrays
ArrayResize(ma_buff,size);
ArrayResize(time_buff,size);
//--- read data from the file
for(int i=0;i<size;i++)
{
time_buff[i]=(datetime)FileReadDouble(file_handle,DOUBLE_VALUE);
ma_buff[i]=FileReadDouble(file_handle,DOUBLE_VALUE);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
return(INIT_FAILED);
}
//--- bind the array to the indicator buffer with index 0
SetIndexBuffer(0,buff,INDICATOR_DATA);
//---- set the indicator values that will not be visible on the chart
SetIndexEmptyValue(0,0.0);
//--- set indexing as timeseries
ArraySetAsSeries(time_buff,true);
ArraySetAsSeries(ma_buff,true);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
ArraySetAsSeries(time,true);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
buff[i]=0;
for(int j=0;j<size;j++)
{
//--- if the dates coincide, the value from the file is used
if(time[i]==time_buff[j])
{
buff[i]=ma_buff[j];
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Real types (double, float), StringToDouble(), DoubleToString(), FileWriteDouble()
MQL4 Reference / File Functions / FileReadFloat
FileReadFloat
Reads the single-precision floating point number (float) from the current position of the
binary file.
float FileReadFloat( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
The value of float type.
Note
For more details about the error, call GetLastError().
Example (the file obtained after executing the example for FileWriteFloat() function is
used here)
//+------------------------------------------------------------------+
//| Demo_FileReadFloat.mq4 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//--- parameters for data reading
input string InpFileName="Close.bin"; // file name
input string InpDirectoryName="Data"; // directory name
//--- global variables
int size=0;
double close_buff[];
datetime time_buff[];
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- read data from the file
while(!FileIsEnding(file_handle))
{
size++;
//--- check size
if(size>ArraySize(time_buff)) ArrayResize(time_buff,size,100);
if(size>ArraySize(close_buff)) ArrayResize(close_buff,size,100);
//--- read time and price values
time_buff[size-1]=(datetime)FileReadDouble(file_handle);
close_buff[size-1]=(double)FileReadFloat(file_handle);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is read, %s file is closed",InpFileName);
//--- check arrays
if(ArraySize(time_buff)==ArraySize(close_buff))
{
//--- print data
PrintFormat("Read data:%d",ArraySize(time_buff));
for(int i=0; i<ArraySize(time_buff); i++) PrintFormat("%d, time=%s, close pr
}
else
Print("Error in data.");
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
return;
}
}
See also
Real types (double, float), FileReadDouble(), FileWriteFloat()
MQL4 Reference / File Functions / FileReadInteger
FileReadInteger
The function reads int, short or char value from the current position of the file pointer
depending on the length specified in bytes.
int FileReadInteger( int file_handle, // File handle
int size=INT_VALUE // Size of an integer in bytes
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
size=INT_VALUE
[in] Number of bytes (up to 4 inclusive) that should be read. The corresponding
constants are provided: CHAR_VALUE = 1, SHORT_VALUE = 2 and INT_VALUE
(LONG_VALUE) = 4, so the function can read the whole value of char, short, int or long
type.
Return Value
A value of the int type. The result of this function must be explicitly cast to a target
type, i.e. to the type of data that you need to read. Since a value of the int type is
returned, it can be easily converted to any integer value. The file pointer is shifted by
the number of bytes read.
Note
When reading less than 4 bytes, the received result is always positive. If one or two
bytes are read, the sign of the number can be determined by explicit casting to type
char (1 byte) or short (2 bytes). Getting the sign for a three-byte number is not trivial,
since there is no corresponding underlying type.
Example (the file obtained after executing the example for FileWriteInteger() function is
used here)
//+------------------------------------------------------------------+
//| Demo_FileReadInteger.mq4 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
#property indicator_chart_window
#property indicator_buffers 1
//---- plot Label1
#property indicator_label1 "Trends"
#property indicator_type1 DRAW_SECTION
#property indicator_color1 clrRed
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
//--- parameters for data reading
input string InpFileName="Trend.bin"; // File name
input string InpDirectoryName="Data"; // Folder name
//--- global variables
int ind=0;
int size=0;
datetime time_buff[];
//--- indicator buffers
double buff[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
int def_size=100;
//--- allocate memory for the array
ArrayResize(time_buff,def_size);
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- additional variables
int arr_size;
uchar arr[];
//--- read data from the file
while(!FileIsEnding(file_handle))
{
//--- find out how many bytes are used for writing the time
arr_size=FileReadInteger(file_handle,INT_VALUE);
ArrayResize(arr,arr_size);
for(int i=0;i<arr_size;i++)
arr[i]=(char)FileReadInteger(file_handle,CHAR_VALUE);
//--- store the time value
time_buff[size]=StringToTime(CharArrayToString(arr));
size++;
//--- increase the sizes of the arrays if they are filled
if(size==def_size)
{
def_size+=100;
ArrayResize(time_buff,def_size);
}
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is read, %s file is closed",InpFileName);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
return(INIT_FAILED);
}
//--- bind the array to the indicator buffer
SetIndexBuffer(0,buff,INDICATOR_DATA);
//---- set the indicator values that will not be visible on the chart
SetIndexEmptyValue(0,0.0);
//--- set indexing as timeseries
ArraySetAsSeries(time_buff,true);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
ArraySetAsSeries(time,true);
ArraySetAsSeries(close,true);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
buff[i]=0;
for(int j=0;j<size;j++)
{
//--- if dates coincide, set as close price
if(time[i]==time_buff[j])
{
//--- set as close price
buff[i]=close[i];
}
}
}
//---
return(rates_total);
}
See also
IntegerToString(), StringToInteger(), Integer types, FileWriteInteger()
MQL4 Reference / File Functions / FileReadLong
FileReadLong
The function reads an integer of long type (8 bytes) from the current position of the
binary file.
long FileReadLong( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
The value of long type.
Example (the file obtained during the execution of an example for FileWriteLong()
function is used here)
//+------------------------------------------------------------------+
//| Demo_FileReadLong.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property indicator_buffers 1
//---- plot Label1
#property indicator_label1 "Volume"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrYellow
#property indicator_style1 STYLE_SOLID
#property indicator_width1 2
#property indicator_separate_window
//--- parameters for data reading
input string InpFileName="Volume.bin"; // file name
input string InpDirectoryName="Data"; // directory name
//--- global variables
int ind=0;
int size=0;
long volume_buff[];
datetime time_buff[];
//--- indicator buffers
double buff[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN);
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is open for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- first, read the amount of data in the file
size=(int)FileReadLong(file_handle);
//--- allocate memory for the arrays
ArrayResize(volume_buff,size);
ArrayResize(time_buff,size);
//--- read data from the file
for(int i=0;i<size;i++)
{
time_buff[i]=(datetime)FileReadLong(file_handle);
volume_buff[i]=FileReadLong(file_handle);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is read, %s file is closed",InpFileName);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
return(INIT_FAILED);
}
//--- bind the array to the indicator buffer with 0 index
SetIndexBuffer(0,buff,INDICATOR_DATA);
//---- set the indicator values that will be visible on the chart
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
ArraySetAsSeries(time,false);
//--- the loop for the bars that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
buff[i]=0;
//--- check if any data is still present
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if dates coincide, the value from the file is used
if(time[i]==time_buff[j])
{
buff[i]=(double)volume_buff[j];
ind=j+1;
break;
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Integer types, FileReadInteger(), FileWriteLong()
MQL4 Reference / File Functions / FileReadNumber
FileReadNumber
The function reads from the CSV file a string from the current
position till a separator (or till the end of a text string) and
converts the read string to a value of double type.
double FileReadNumber( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
The value of double type.
Example script in FileIsLineEnding().
See also
FileWriteString()
MQL4 Reference / File Functions / FileReadString
FileReadString
The function reads a string from the current position of a file pointer in a file.
string FileReadString( int file_handle, // File handle
int length=0 // Length of the string
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
length=0
[in] Number of characters to read.
Return Value
Line read (string).
Note
When reading from a bin-file. the length of a string to read must be specified. When
reading from a txt-file the string length is not required, and the string will be read from
the current position to the line feed character "\r\n". When reading from a csv-file, the
string length isn't required also, the string will be read from the current position till the
nearest delimiter or till the text string end character.
If the file is opened with FILE_ANSI flag, then the line read is converted to Unicode.
Example (the file obtained after executing the example for FileWriteInteger() function is
used here)
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for data reading
input string InpFileName="Trend.bin"; // file name
input string InpDirectoryName="Data"; // directory name
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN|FILE
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- additional variables
int str_size;
string str;
//--- read data from the file
while(!FileIsEnding(file_handle))
{
//--- find out how many symbols are used for writing the time
str_size=FileReadInteger(file_handle,INT_VALUE);
//--- read the string
str=FileReadString(file_handle,str_size);
//--- print the string
PrintFormat(str);
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is read, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
}
See also
String Type, Conversion Functions, FileWriteInteger()
MQL4 Reference / File Functions / FileReadStruct
FileReadStruct
The function reads contents into a structure passed as a parameter from a binary-file,
starting with the current position of the file pointer.
uint FileReadStruct( int file_handle, // file handle
const void& struct_object, // target structure to which the contents are rea
int size=-1 // structure size in bytes
);
Parameters
file_handle
[in] File descriptor of an open bin-file.
struct_object
[out] The object of this structure. The structure should not contain strings, dynamic
arrays or virtual functions.
size=-1
[in] Number of bytes that should be read. If size is not specified or the indicated
value is greater than the size of the structure, the exact size of the specified structure
is used.
Return Value
If successful the function returns the number of bytes read or 0 in case of error. If
successful, the number of bytes read corresponds to the size of the structure. To obtain
information about the error call the GetLastError() function. File pointer is moved by
the same number of bytes.
Example (the file obtained after using the example for FileWriteStruct() function is used
here)
//+------------------------------------------------------------------+
//| Demo_FileReadStruct.mq4 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property indicator_separate_window
#property indicator_buffers 4
//---- plot Label1
#property indicator_label1 "Open"
#property indicator_type1 DRAW_LINE
#property indicator_color1 clrBlue
#property indicator_style1 STYLE_SOLID
#property indicator_width1 1
#property indicator_label1 "High"
#property indicator_type2 DRAW_LINE
#property indicator_color2 clrGreen
#property indicator_style2 STYLE_SOLID
#property indicator_width2 1
#property indicator_label1 "Low"
#property indicator_type3 DRAW_LINE
#property indicator_color3 clrOrange
#property indicator_style3 STYLE_SOLID
#property indicator_width3 1
#property indicator_label1 "Close"
#property indicator_type4 DRAW_LINE
#property indicator_color4 clrRed
#property indicator_style4 STYLE_SOLID
#property indicator_width4 1
#property indicator_separate_window
//--- parameters for receiving data
input string InpFileName="EURUSD.txt"; // file name
input string InpDirectoryName="Data"; // directory name
//+------------------------------------------------------------------+
//| Structure for storing candlestick data |
//+------------------------------------------------------------------+
struct candlesticks
{
double open; // open price
double close; // close price
double high; // high price
double low; // low price
datetime date; // date
};
//--- indicator buffers
double open_buff[];
double close_buff[];
double high_buff[];
double low_buff[];
//--- global variables
candlesticks cand_buff[];
int size=0;
int ind=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
int default_size=100;
ArrayResize(cand_buff,default_size);
//--- open the file
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_BIN|FILE
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_COMMONDATA_PAT
//--- read data from the file
while(!FileIsEnding(file_handle))
{
//--- write data to the array
uint bytesread=FileReadStruct(file_handle,cand_buff[size]);
//--- check data read
if (bytesread!=sizeof(candlesticks))
{
PrintFormat("Error reading data. Error code=%d",GetLastError());
//--- close the file
FileClose(file_handle);
return(INIT_FAILED);
}
else
{
size++;
//--- check if the array is overflown
if(size==default_size)
{
//--- increase the array size
default_size+=100;
ArrayResize(cand_buff,default_size);
}
}
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is read, %s file is closed",InpFileName);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
return(INIT_FAILED);
}
//--- indicator buffers mapping
SetIndexBuffer(0,open_buff,INDICATOR_DATA);
SetIndexBuffer(1,high_buff,INDICATOR_DATA);
SetIndexBuffer(2,low_buff,INDICATOR_DATA);
SetIndexBuffer(3,close_buff,INDICATOR_DATA);
//--- empty value
PlotIndexSetDouble(0,PLOT_EMPTY_VALUE,0);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
ArraySetAsSeries(time,false);
//--- the loop for the candlesticks that have not been handled yet
for(int i=prev_calculated;i<rates_total;i++)
{
//--- 0 by default
open_buff[i]=0;
close_buff[i]=0;
high_buff[i]=0;
low_buff[i]=0;
//--- check if any data is still present
if(ind<size)
{
for(int j=ind;j<size;j++)
{
//--- if dates coincide, the value from the file is used
if(time[i]==cand_buff[j].date)
{
open_buff[i]=cand_buff[j].open;
close_buff[i]=cand_buff[j].close;
high_buff[i]=cand_buff[j].high;
low_buff[i]=cand_buff[j].low;
//--- increase the counter
ind=j+1;
break;
}
}
}
}
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Structures and classes, FileWriteStruct()
MQL4 Reference / File Functions / FileSeek
FileSeek
The function moves the position of the file pointer by a specified number of bytes
relative to the specified position.
bool FileSeek( int file_handle, // File handle
long offset, // In bytes
ENUM_FILE_POSITION origin // Position for reference
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
offset
[in] The shift in bytes (may take a negative value).
origin
[in] The starting point for the displacement. Can be one of values of
ENUM_FILE_POSITION.
Return Value
If successful the function returns true, otherwise false. To obtain information about the
error call the GetLastError() function.
Note
If the execution of the FileSeek() function results in a negative shift (going beyond the
"level boundary" of the file), the file pointer will be set to the file beginning.
If a position is set beyond the "right boundary" of the file (larger than the file size), the
next writing to the file will be performed not from the end of the file, but from the
position set. In this case indefinite values will be written for the previous file end and
the position set.
Example:
//+------------------------------------------------------------------+
//| Demo_FileSeek.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="file.txt"; // file name
input string InpDirectoryName="Data"; // directory name
input int InpEncodingType=FILE_ANSI; // ANSI=32 or UNICODE=64
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- specify the value of the variable for generating random numbers
_RandomSeed=GetTickCount();
//--- variables for positions of the strings' start points
ulong pos[];
int size;
//--- reset the error value
ResetLastError();
//--- open the file
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_TXT|InpE
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
//--- receive start position for each string in the file
GetStringPositions(file_handle,pos);
//--- define the number of strings in the file
size=ArraySize(pos);
if(!size)
{
//--- stop if the file does not have strings
PrintFormat("%s file is empty!",InpFileName);
FileClose(file_handle);
return;
}
//--- make a random selection of a string number
int ind=MathRand()%size;
//--- shift position to the starting point of the string
if(FileSeek(file_handle,pos[ind],SEEK_SET)==true)
{
//--- read and print the string with ind number
PrintFormat("String text with %d number: \"%s\"",ind,FileReadString(file_han
}
//--- close the file
FileClose(file_handle);
PrintFormat("%s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
}
//+-------------------------------------------------------------------------------+
//| The function defines starting points for each of the strings in the file and |
//| places them in arr array |
//+-------------------------------------------------------------------------------+
void GetStringPositions(const int handle,ulong &arr[])
{
//--- default array size
int def_size=127;
//--- allocate memory for the array
ArrayResize(arr,def_size);
//--- string counter
int i=0;
//--- if this is not the file's end, then there is at least one string
if(!FileIsEnding(handle))
{
arr[i]=FileTell(handle);
i++;
}
else
return; // the file is empty, exit
//--- define the shift in bytes depending on encoding
int shift;
if(FileGetInteger(handle,FILE_IS_ANSI))
shift=1;
else
shift=2;
//--- go through the strings in the loop
while(1)
{
//--- read the string
FileReadString(handle);
//--- check for the file end
if(!FileIsEnding(handle))
{
//--- store the next string's position
arr[i]=FileTell(handle)+shift;
i++;
//--- increase the size of the array if it is overflown
if(i==def_size)
{
def_size+=def_size+1;
ArrayResize(arr,def_size);
}
}
else
break; // end of the file, exit
}
//--- define the actual size of the array
ArrayResize(arr,i);
}
MQL4 Reference / File Functions / FileSize
FileSize
The function returns the file size in bytes.
ulong FileSize( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
The value of type int.
Note
To obtain information about the error call GetLastError() function.
Example:
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input ulong InpThresholdSize=20; // file threshold size in kilobytes
input string InpBigFolderName="big"; // folder for large files
input string InpSmallFolderName="small"; // folder for small files
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string file_name; // variable for storing file names
string filter="*.csv"; // filter for searching the files
ulong file_size=0; // file size in bytes
int size=0; // number of files
//--- print the path to the file we are going to work with
PrintFormat("Working in %s\\Files\\ folder",TerminalInfoString(TERMINAL_COMMONDATA
//--- receive the search handle in common folder's root of all terminals
long search_handle=FileFindFirst(filter,file_name,FILE_COMMON);
//--- check if FileFindFirst() has been executed successfully
if(search_handle!=INVALID_HANDLE)
{
//--- move files in the loop according to their size
do
{
//--- open the file
ResetLastError();
int file_handle=FileOpen(file_name,FILE_READ|FILE_CSV|FILE_COMMON);
if(file_handle!=INVALID_HANDLE)
{
//--- receive the file size
file_size=FileSize(file_handle);
//--- close the file
FileClose(file_handle);
}
else
{
PrintFormat("Failed to open %s file, Error code = %d",file_name,GetLastEr
continue;
}
//--- print the file size
PrintFormat("Size of %s file is equal to %d bytes",file_name,file_size);
//--- define the path for moving the file
string path;
if(file_size>InpThresholdSize*1024)
path=InpBigFolderName+"//"+file_name;
else
path=InpSmallFolderName+"//"+file_name;
//--- move the file
ResetLastError();
if(FileMove(file_name,FILE_COMMON,path,FILE_REWRITE|FILE_COMMON))
PrintFormat("%s file is moved",file_name);
else
PrintFormat("Error, code = %d",GetLastError());
}
while(FileFindNext(search_handle,file_name));
//--- close the search handle
FileFindClose(search_handle);
}
else
Print("Files not found!");
}
MQL4 Reference / File Functions / FileTell
FileTell
The file returns the current position of the file pointer of an open file.
ulong FileTell( int file_handle // File handle
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
Return Value
Current position of the file descriptor in bytes from the beginning of the file.
Note
To obtain information about the error call GetLastError().
Example:
//+------------------------------------------------------------------+
//| Demo_FileTell.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- display the window of input parameters when launching the script
#property script_show_inputs
//--- input parameters
input string InpFileName="file.txt"; // file name
input string InpDirectoryName="Data"; // directory name
input int InpEncodingType=FILE_ANSI; // ANSI=32 or UNICODE=64
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- specify the value of the variable for generating random numbers
_RandomSeed=GetTickCount();
//--- variables for positions of the strings' start points
ulong pos[];
int size;
//--- reset the error value
ResetLastError();
//--- open the file
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_TXT|InpE
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for reading",InpFileName);
//--- receive start position for each string in the file
GetStringPositions(file_handle,pos);
//--- define the number of strings in the file
size=ArraySize(pos);
if(!size)
{
//--- stop if the file does not have strings
PrintFormat("%s file is empty!",InpFileName);
FileClose(file_handle);
return;
}
//--- make a random selection of a string number
int ind=MathRand()%size;
//--- shift position to the starting point of the string
FileSeek(file_handle,pos[ind],SEEK_SET);
//--- read and print the string with ind number
PrintFormat("String text with %d number: \"%s\"",ind,FileReadString(file_handle
//--- close the file
FileClose(file_handle);
PrintFormat("%s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
}
//+-------------------------------------------------------------------------------+
//| The function defines starting points for each of the strings in the file and |
//| places them in arr array |
//+-------------------------------------------------------------------------------+
void GetStringPositions(const int handle,ulong &arr[])
{
//--- default array size
int def_size=127;
//--- allocate memory for the array
ArrayResize(arr,def_size);
//--- string counter
int i=0;
//--- if this is not the file's end, then there is at least one string
if(!FileIsEnding(handle))
{
arr[i]=FileTell(handle);
i++;
}
else
return; // the file is empty, exit
//--- define the shift in bytes depending on encoding
int shift;
if(FileGetInteger(handle,FILE_IS_ANSI))
shift=1;
else
shift=2;
//--- go through the strings in the loop
while(1)
{
//--- read the string
FileReadString(handle);
//--- check for the file end
if(!FileIsEnding(handle))
{
//--- store the next string's position
arr[i]=FileTell(handle)+shift;
i++;
//--- increase the size of the array if it is overflown
if(i==def_size)
{
def_size+=def_size+1;
ArrayResize(arr,def_size);
}
}
else
break; // end of the file, exit
}
//--- define the actual size of the array
ArrayResize(arr,i);
}
MQL4 Reference / File Functions / FileWrite
FileWrite
The function is intended for writing of data into a CSV file, delimiter being inserted
automatically unless it is equal to 0. After writing into the file, the line end character
"\r\n" will be added.
uint FileWrite( int file_handle, // File handle
... // List of recorded parameters
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
...
[in] The list of parameters separated by commas, to write to the file. The number of
written parameters can be up to 63.
Return Value
Number of bytes written or 0 in case of error. To obtain information about the error call
the GetLastError() function.
Note
Numbers will be converted into a text at output (see the Print() function). Data of the
double type are output with the accuracy of 16 digits after the decimal point, and the
data can be displayed either in traditional or in scientific format - depending on which
format will be the most compact. The data of the float type are shown with 5 digits
after the decimal point. To output real numbers with different precision or in a clearly
specified format, use DoubleToString().
Numbers of the bool type are displayed as "true" or "false" strings. Numbers of the
datetime type are displayed as "YYYY.MM.DD HH:MI:SS".
Example:
//+------------------------------------------------------------------+
//| Demo_FileWrite.mq4 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string InpSymbolName="EURUSD"; // Сurrency pair
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // Time frame
input int InpFastEMAPeriod=12; // Fast EMA period
input int InpSlowEMAPeriod=26; // Slow EMA period
input int InpSignalPeriod=9; // Difference averaging period
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Price type
//--- parameters for writing data to file
input string InpFileName="MACD.csv"; // File name
input string InpDirectoryName="Data"; // Folder name
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
bool sign_buff[]; // signal array (true - buy, false - sell)
datetime time_buff[]; // array of signals' appear time
int sign_size=0; // signal array size
double macd_buff[]; // array of indicator values
datetime date_buff[]; // array of indicator dates
int macd_size=0; // size of indicator arrays
//--- set indexing as time series
ArraySetAsSeries(sign_buff,true);
ArraySetAsSeries(time_buff,true);
ArraySetAsSeries(macd_buff,true);
ArraySetAsSeries(date_buff,true);
//--- reset last error code
ResetLastError();
//--- copying the time from last 1000 bars
int copied=CopyTime(NULL,0,0,1000,date_buff);
if(copied<=0)
{
PrintFormat("Failed to copy time values. Error code = %d",GetLastError());
return;
}
//--- prepare macd_buff array
ArrayResize(macd_buff,copied);
//--- copy the values of main line of the iMACD indicator
for(int i=0;i<copied;i++)
{
macd_buff[i]=iMACD(InpSymbolName,InpSymbolPeriod,InpFastEMAPeriod,InpSlowEMAPer
}
//--- get size
macd_size=ArraySize(macd_buff);
//--- analyze the data and save the indicator signals to the arrays
ArrayResize(sign_buff,macd_size-1);
ArrayResize(time_buff,macd_size-1);
for(int i=1;i<macd_size;i++)
{
//--- buy signal
if(macd_buff[i-1]<0 && macd_buff[i]>=0)
{
sign_buff[sign_size]=true;
time_buff[sign_size]=date_buff[i];
sign_size++;
}
//--- sell signal
if(macd_buff[i-1]>0 && macd_buff[i]<=0)
{
sign_buff[sign_size]=false;
time_buff[sign_size]=date_buff[i];
sign_size++;
}
}
//--- open the file for writing the indicator values (if the file is absent, it will
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FI
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- first, write the number of signals
FileWrite(file_handle,sign_size);
//--- write the time and values of signals to the file
for(int i=0;i<sign_size;i++)
FileWrite(file_handle,time_buff[i],sign_buff[i]);
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
}
See also
Comment(), Print(), StringFormat()
MQL4 Reference / File Functions / FileWriteArray
FileWriteArray
The function writes arrays of any type except for string to a BIN file (can be an array of
structures not containing strings or dynamic arrays).
uint FileWriteArray( int file_handle, // File handle
const void& array[], // Array
int start=0, // Start index in the array
int count=WHOLE_ARRAY // Number of elements
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
array[]
[out] Array for recording.
start=0
[in] Initial index in the array (number of the first recorded element).
count=WHOLE_ARRAY
[in] Number of items to write (WHOLE_ARRAY means all items starting with the
number start until the end of the array).
Return Value
Number of elements written or 0 in case of error. To obtain information about the error
call the GetLastError() function.
Note
String array can be written in a TXT file. In this case, strings are automatically ended
by the line end characters "\r\n". Depending on the file type ANSI or UNICODE, strings
are either converted to ansi-encoding or not.
Example:
//+------------------------------------------------------------------+
//| Demo_FileWriteArray.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- input parameters
input string InpFileName="data.bin";
input string InpDirectoryName="SomeFolder";
//+------------------------------------------------------------------+
//| Structure for storing price data |
//+------------------------------------------------------------------+
struct prices
{
datetime date; // date
double bid; // bid price
double ask; // ask price
};
//--- global variables
int count=0;
int size=20;
string path=InpDirectoryName+"//"+InpFileName;
prices arr[];
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- allocate memory for the array
ArrayResize(arr,size);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- write the remaining count strings if count<n
WriteData(count);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//--- save data to array
arr[count].date=TimeCurrent();
arr[count].bid=SymbolInfoDouble(Symbol(),SYMBOL_BID);
arr[count].ask=SymbolInfoDouble(Symbol(),SYMBOL_ASK);
//--- show current data
Print("Date = ",arr[count].date," Bid = ",arr[count].bid," Ask = ",arr[count].ask)
//--- increase the counter
count++;
//--- if the array is filled, write data to the file and zero it out
if(count==size)
{
WriteData(size);
count=0;
}
}
//+------------------------------------------------------------------+
//| Write n elements of the array to file |
//+------------------------------------------------------------------+
void WriteData(const int n)
{
//--- open the file
ResetLastError();
int handle=FileOpen(path,FILE_READ|FILE_WRITE|FILE_BIN);
if(handle!=INVALID_HANDLE)
{
//--- write array data to the end of the file
FileSeek(handle,0,SEEK_END);
FileWriteArray(handle,arr,0,n);
//--- close the file
FileClose(handle);
}
else
Print("Failed to open the file, error ",GetLastError());
}
See also
Variables, FileSeek()
MQL4 Reference / File Functions / FileWriteDouble
FileWriteDouble
The function writes the value of a double parameter to a file, starting from the current
position of the file pointer.
uint FileWriteDouble( int file_handle, // File handle
double value // Value to write
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
value
[in] The value of double type.
Return Value
If successful the function returns the number of bytes written or 0 in case of error. If
successful, the number of bytes written corresponds to the data type size
(sizeof(double)=8). To obtain information about the error call the GetLastError()
function. The file pointer is shifted by the same number of bytes.
Example:
//+------------------------------------------------------------------+
//| Demo_FileWriteDouble.mq4 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string InpSymbolName="EURUSD"; // Currency pair
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // Time frame
input int InpMAPeriod=10; // Smoothing period
input int InpMAShift=0; // Indicator shift
input ENUM_MA_METHOD InpMAMethod=MODE_SMA; // Smoothing type
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // price type
//--- parameters for writing data to the file
input string InpFileName="MA.bin"; // File name
input string InpDirectoryName="Data"; // Folder name
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date_finish=TimeCurrent();
double ma_buff[];
datetime time_buff[];
int size;
//--- set indexing as timeseries
ArraySetAsSeries(ma_buff,true);
ArraySetAsSeries(time_buff,true);
//--- reset last erro
ResetLastError();
//--- copying the time from last 1000 bars
int copied=CopyTime(NULL,0,0,1000,time_buff);
if(copied<=0)
{
PrintFormat("Failed to copy time values. Error code = %d",GetLastError());
return;
}
//--- prepare ma_buff[] array
ArrayResize(ma_buff,copied);
//--- copy the values of iMA indicator
for(int i=0;i<copied;i++)
{
ma_buff[i]=iMA(InpSymbolName,InpSymbolPeriod,InpMAPeriod,InpMAShift,InpMAMethod
}
//---
PrintFormat("The values starting from %s to %s will be written to file.",TimeToStr
//--- get size
size=ArraySize(ma_buff);
//--- open the file for writing the indicator values (if the file is absent, it will
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FI
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- first, write the size of data sample
uint byteswritten=FileWriteDouble(file_handle,(double)size,DOUBLE_VALUE);
//--- check the number of bytes written
if(byteswritten!=sizeof(double))
{
PrintFormat("Error in FileWriteDouble. Error code=%d",GetLastError());
//--- close the file
FileClose(file_handle);
return;
}
//--- write the indicator time and value to the file
for(int i=0;i<size;i++)
{
byteswritten=FileWriteDouble(file_handle,(double)time_buff[i],DOUBLE_VALUE);
//--- check the number of bytes written
if(byteswritten!=sizeof(double))
{
PrintFormat("Error in FileWriteDouble. Error code=%d",GetLastError());
//--- close the file
FileClose(file_handle);
return;
}
byteswritten=FileWriteDouble(file_handle,ma_buff[i],DOUBLE_VALUE);
//--- check number of bytes written
if(byteswritten!=sizeof(double))
{
PrintFormat("Error in FileWriteDouble. Error code=%d",GetLastError());
//--- close the file
FileClose(file_handle);
return;
}
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
}
See also
Real types (double, float)
MQL4 Reference / File Functions / FileWriteFloat
FileWriteFloat
The function writes the value of the float parameter to a bin-file, starting from the
current position of the file pointer.
uint FileWriteFloat( int file_handle, // File handle
float value // Value to be written
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
value
[in] The value of float type.
Return Value
If successful the function returns the number of bytes written or 0 in case of error. If
successful, the number of bytes written corresponds to the data type size
(sizeof(float)=4). To obtain information about the error call the GetLastError() function.
The file pointer is shifted by the same number of bytes.
Example:
//+------------------------------------------------------------------+
//| Demo_FileWriteFloat.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string InpSymbolName="EURUSD"; // currency pair
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_M15; // time frame
input datetime InpDateStart=D'2013.01.01 00:00'; // data copying start date
//--- parameters for writing data to the file
input string InpFileName="Close.bin"; // file name
input string InpDirectoryName="Data"; // directory name
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date_finish=TimeCurrent();
double close_buff[];
datetime time_buff[];
int size;
//--- reset the error value
ResetLastError();
//--- copy the close price for each bar
if(CopyClose(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,close_buff)==-
{
PrintFormat("Failed to copy close price values. Error code = %d",GetLastError()
return;
}
//--- copy the time for each bar
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat("Failed to copy the time values. Error code = %d",GetLastError());
return;
}
//--- receive the buffer size
size=ArraySize(close_buff);
//--- open the file for writing the values (if the file is absent, it will be created
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FI
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is open for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- write close prices' time and values to the file
for(int i=0;i<size;i++)
{
uint byteswritten=FileWriteDouble(file_handle,(double)time_buff[i]);
//--- check the number of bytes written
if(byteswritten!=sizeof(double))
{
PrintFormat("Error in FileWriteDouble. Error code=%d",GetLastError());
//--- close the file
FileClose(file_handle);
return;
}
byteswritten=FileWriteFloat(file_handle,(float)close_buff[i]);
//--- check the number of bytes written
if(byteswritten!=sizeof(float))
{
PrintFormat("Error in FileWriteDouble. Error code=%d",GetLastError());
//--- close the file
FileClose(file_handle);
return;
}
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
}
See also
Real types (double, float), FileWriteDouble()
MQL4 Reference / File Functions / FileWriteInteger
FileWriteInteger
The function writes the value of the int parameter to a bin-file, starting from the
current position of the file pointer.
uint FileWriteInteger( int file_handle, // File handle
int value, // Value to be written
int size=INT_VALUE // Size in bytes
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
value
[in] Integer value.
size=INT_VALUE
[in] Number of bytes (up to 4 inclusive), that should be written. The corresponding
constants are provided: CHAR_VALUE=1, SHORT_VALUE=2 and INT_VALUE=4, so the
function can write the integer value of char, uchar, short, ushort, int, or uint type.
Return Value
If successful the function returns the number of bytes written or 0 in case of error. If
successful, the number of bytes written corresponds to the data type size. To obtain
information about the error call the GetLastError() function. The file pointer is shifted
by the same number of bytes.
Example:
//+------------------------------------------------------------------+
//| Demo_FileWriteInteger.mq4 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string InpSymbolName="EURUSD"; // Currency pair
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // Time frame
//--- parameters for writing data to the file
input string InpFileName="Trend.bin"; // File name
input string InpDirectoryName="Data"; // Folder name
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
double close_buff[];
datetime time_buff[];
int size;
//--- set indexing as timeseries
ArraySetAsSeries(close_buff,true);
ArraySetAsSeries(time_buff,true);
//--- reset the error value
ResetLastError();
//--- copy the close price for each bar
if(CopyClose(InpSymbolName,InpSymbolPeriod,0,1000,close_buff)==-1)
{
PrintFormat("Failed to copy the values of close prices. Error code = %d",GetLas
return;
}
//--- copy the time for each bar
if(CopyTime(InpSymbolName,InpSymbolPeriod,0,1000,time_buff)==-1)
{
PrintFormat("Failed to copy time values. Error code = %d",GetLastError());
return;
}
//--- get the buffer size
size=ArraySize(close_buff);
//--- open the file for writing the values (if the file is absent, it will be created
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FI
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//---
uint byteswritten;// number of bytes written
int up_down=0; // trend flag
int arr_size; // arr array size
uchar arr[]; // uchar type array
//--- write time values to the file
for(int i=0;i<size-1;i++)
{
//--- compare close prices of the current and next bars
if(close_buff[i]<=close_buff[i+1])
{
if(up_down!=1)
{
//--- write date value to the file using FileWriteInteger
StringToCharArray(TimeToString(time_buff[i]),arr);
arr_size=ArraySize(arr);
//--- first, write the number of chars in the array
byteswritten=FileWriteInteger(file_handle,arr_size,INT_VALUE);
//--- checking the number of bytes written
if(byteswritten!=sizeof(int))
{
PrintFormat("Error in FileWriteInteger. Error code=%d",GetLastError
//--- close the file
FileClose(file_handle);
return;
}
//--- write the chars
for(int j=0;j<arr_size;j++)
{
byteswritten=FileWriteInteger(file_handle,arr[j],CHAR_VALUE);
//--- checking the number of bytes written
if(byteswritten!=sizeof(char))
{
PrintFormat("Error in FileWriteInteger. Error code=%d",GetLastEr
//--- close the file
FileClose(file_handle);
return;
}
}
//--- change the trend flag
up_down=1;
}
}
else
{
if(up_down!=-1)
{
//--- write the date value to the file using FileWriteInteger
StringToCharArray(TimeToString(time_buff[i]),arr);
arr_size=ArraySize(arr);
//--- first, write the number of chars in the array
byteswritten=FileWriteInteger(file_handle,arr_size,INT_VALUE);
//--- checking the number of bytes written
if(byteswritten!=sizeof(int))
{
PrintFormat("Error in FileWriteInteger. Error code=%d",GetLastError
//--- close the file
FileClose(file_handle);
return;
}
//--- write chars
for(int j=0;j<arr_size;j++)
{
byteswritten=FileWriteInteger(file_handle,arr[j],CHAR_VALUE);
//--- checking the number of bytes written
if(byteswritten!=sizeof(char))
{
PrintFormat("Error in FileWriteInteger. Error code=%d",GetLastEr
//--- close the file
FileClose(file_handle);
return;
}
}
//--- change the trend flag
up_down=-1;
}
}
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Data is written, %s file is closed",InpFileName,GetLastError());
}
See also
IntegerToString(), StringToInteger(), Integer types
MQL4 Reference / File Functions / FileWriteLong
FileWriteLong
The function writes the value of the long-type parameter to a bin-file, starting from the
current position of the file pointer.
uint FileWriteLong( int file_handle, // File handle
long value // Value to be written
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
value
[in] Value of type long.
Return Value
If successful the function returns the number of bytes written or 0 in case of error. If
successful, the number of bytes written corresponds to the data type size
(sizeof(long)=8). To obtain information about the error call the GetLastError() function.
The file pointer is shifted by the same number of bytes.
Example:
//+------------------------------------------------------------------+
//| Demo_FileWriteLong.mq5 |
//| Copyright 2013, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2013, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string InpSymbolName="EURUSD"; // currency pair
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // time frame
input datetime InpDateStart=D'2013.01.01 00:00'; // data copying start date
//--- parameters for writing data to the file
input string InpFileName="Volume.bin"; // file name
input string InpDirectoryName="Data"; // directory name
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date_finish=TimeCurrent();
long volume_buff[];
datetime time_buff[];
int size;
//--- reset the error value
ResetLastError();
//--- copy tick volumes for each bar
if(CopyTickVolume(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,volume_bu
{
PrintFormat("Failed to copy values of the tick volume. Error code = %d",GetLast
return;
}
//--- copy the time for each bar
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat("Failed to copy time values. Error code = %d",GetLastError());
return;
}
//--- receive the buffer size
size=ArraySize(volume_buff);
//--- open the file for writing the indicator values (if the file is absent, it will
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FI
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- first, write the data sample size
uint byteswritten=FileWriteLong(file_handle,(long)size);
//--- check the number of bytes written
if(byteswritten!=sizeof(long))
{
PrintFormat("Error in FileWriteLong. Error code=%d",GetLastError());
//--- close the file
FileClose(file_handle);
return;
}
//--- write time and volume values to file
for(int i=0;i<size;i++)
{
byteswritten=FileWriteLong(file_handle,(long)time_buff[i]);
//--- check the number of bytes written
if(byteswritten!=sizeof(long))
{
PrintFormat("Error in FileWriteLong. Error code=%d",GetLastError());
//--- close the file
FileClose(file_handle);
return;
}
byteswritten=FileWriteLong(file_handle,volume_buff[i]);
//--- check the number of bytes written
if(byteswritten!=sizeof(long))
{
PrintFormat("Error in FileWriteLong. Error code=%d",GetLastError());
//--- close the file
FileClose(file_handle);
return;
}
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
}
See also
Integer types, FileWriteInteger()
MQL4 Reference / File Functions / FileWriteString
FileWriteString
The function writes the value of a string-type parameter into a BIN, CSV or TXT file
starting from the current position of the file pointer. When writing to a CSV or TXT file:
if there is a symbol in the string '\n' (LF) without previous character '\r' (CR), then before
'\n' the missing '\r' is added.
uint FileWriteString( int file_handle, // File handle
const string text_string, // string to write
int length=0 // number of symbols
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
text_string
[in] String.
length=0
[in] The number of characters that you want to write. This option is needed for writing
a string into a BIN file. If the size is not specified, then the entire string without the
trailer 0 is written. If you specify a size smaller than the length of the string, then a
part of the string without the trailer 0 is written. If you specify a size greater than the
length of the string, the string is filled by the appropriate number of zeros. For files of
CSV and TXT type, this parameter is ignored and the string is written entirely.
Return Value
If successful the function returns the number of bytes written or 0 in case of error. To
obtain information about the error call the GetLastError() function. The file pointer is
shifted by the same number of bytes.
Note
Note that when writing to a file opened by the FILE_UNICODE flag (or without a flag
FILE_ANSI), then the number of bytes written will be twice as large as the number of
string characters written. When recording to a file opened with the FILE_ANSI flag, the
number of bytes written will coincide with the number of string characters written.
Example:
//+------------------------------------------------------------------+
//| Demo_FileWriteString.mq4 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
#property strict
//--- show the window of input parameters when launching the script
#property script_show_inputs
//--- parameters for receiving data from the terminal
input string InpSymbolName="EURUSD"; // Currency pair
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // Time frame
input int InpMAPeriod=14; // MA period
input ENUM_APPLIED_PRICE InpAppliedPrice=PRICE_CLOSE; // Price type
//--- parameters for writing data to the file
input string InpFileName="RSI.csv"; // File name
input string InpDirectoryName="Data"; // Folder name
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
double rsi_buff[]; // array of indicator values
datetime date_buff[]; // array of the indicator dates
int rsi_size=0; // size of the indicator arrays
//--- set indexing as timeseries
ArraySetAsSeries(rsi_buff,true);
ArraySetAsSeries(date_buff,true);
//--- reset last error code
ResetLastError();
//--- copying the time from last 1000 bars
int copied=CopyTime(NULL,0,0,1000,date_buff);
if(copied<=0)
{
PrintFormat("Failed to copy time values. Error code = %d",GetLastError());
return;
}
//--- prepare rsi_buff array
ArrayResize(rsi_buff,copied);
//--- copy the values of RSI indicator
for(int i=0;i<copied;i++)
{
rsi_buff[i]=iRSI(InpSymbolName,InpSymbolPeriod,InpMAPeriod,InpAppliedPrice,i);
}
//--- get size
rsi_size=ArraySize(rsi_buff);
//--- open the file for writing the indicator values (if the file is absent, it will
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FI
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is available for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_DATA_PATH));
//--- prepare additional variables
string str="";
bool is_formed=false;
//--- write dates of forming overbought and oversold areas
for(int i=0;i<rsi_size;i++)
{
//--- check the indicator values
if(rsi_buff[i]>=70 || rsi_buff[i]<=30)
{
//--- if the value is the first one in this area
if(!is_formed)
{
//--- add the value and the date
str=(string)rsi_buff[i]+"\t"+(string)date_buff[i];
is_formed=true;
}
else
str+="\t"+(string)rsi_buff[i]+"\t"+(string)date_buff[i];
//--- move to the next loop iteration
continue;
}
//--- check the flag
if(is_formed)
{
//--- the string is formed, write it to the file
FileWriteString(file_handle,str+"\r\n");
is_formed=false;
}
}
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
}
See also
String Type, StringFormat()
MQL4 Reference / File Functions / FileWriteStruct
FileWriteStruct
The function writes into a bin-file contents of a structure passed as a parameter, starting
from the current position of the file pointer.
uint FileWriteStruct( int file_handle, // File handle
const void& struct_object, // link to an object
int size=-1 // size to be written in bytes
);
Parameters
file_handle
[in] File descriptor returned by FileOpen().
struct_object
[in] Reference to the object of this structure. The structure should not contain strings,
dynamic arrays or virtual functions.
size=-1
[in] Number of bytes that you want to record. If size is not specified or the specified
number of bytes is greater than the size of the structure, the entire structure is
written.
Return Value
If successful the function returns the number of bytes written or 0 in case of error. If
successful, the number of bytes written corresponds to the size of the structure.To
obtain information about the error call the GetLastError() function. The file pointer is
shifted by the same number of bytes.
Example:
//+------------------------------------------------------------------+
//| Demo_FileWriteStruct.mq4 |
//| Copyright 2014, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2014, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- show the window of input parameters when launching the script
#property script_show_inputs
#property strict
//--- parameters for receiving data from the terminal
input string InpSymbolName="EURUSD"; // currency pair
input ENUM_TIMEFRAMES InpSymbolPeriod=PERIOD_H1; // time frame
input datetime InpDateStart=D'2013.01.01 00:00'; // data copying start date
//--- parameters for writing data to the file
input string InpFileName="EURUSD.txt"; // file name
input string InpDirectoryName="Data"; // directory name
//+------------------------------------------------------------------+
//| Structure for storing candlestick data |
//+------------------------------------------------------------------+
struct candlesticks
{
double open; // open price
double close; // close price
double high; // high price
double low; // low price
datetime date; // date
};
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
datetime date_finish=TimeCurrent();
int size;
datetime time_buff[];
double open_buff[];
double close_buff[];
double high_buff[];
double low_buff[];
candlesticks cand_buff[];
//--- reset the error value
ResetLastError();
//--- receive the time of the arrival of the bars from the range
if(CopyTime(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,time_buff)==-1)
{
PrintFormat("Failed to copy time values. Error code = %d",GetLastError());
return;
}
//--- receive high prices of the bars from the range
if(CopyHigh(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,high_buff)==-1)
{
PrintFormat("Failed to copy values of high prices. Error code = %d",GetLastErro
return;
}
//--- receive low prices of the bars from the range
if(CopyLow(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,low_buff)==-1)
{
PrintFormat("Failed to copy values of low prices. Error code = %d",GetLastError
return;
}
//--- receive open prices of the bars from the range
if(CopyOpen(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,open_buff)==-1)
{
PrintFormat("Failed to copy values of open prices. Error code = %d",GetLastErro
return;
}
//--- receive close prices of the bars from the range
if(CopyClose(InpSymbolName,InpSymbolPeriod,InpDateStart,date_finish,close_buff)==-
{
PrintFormat("Failed to copy values of close prices. Error code = %d",GetLastErr
return;
}
//--- define dimension of the arrays
size=ArraySize(time_buff);
//--- save all data in the structure array
ArrayResize(cand_buff,size);
for(int i=0;i<size;i++)
{
cand_buff[i].open=open_buff[i];
cand_buff[i].close=close_buff[i];
cand_buff[i].high=high_buff[i];
cand_buff[i].low=low_buff[i];
cand_buff[i].date=time_buff[i];
}
//--- open the file for writing the structure array to the file (if the file is absen
ResetLastError();
int file_handle=FileOpen(InpDirectoryName+"//"+InpFileName,FILE_READ|FILE_WRITE|FI
if(file_handle!=INVALID_HANDLE)
{
PrintFormat("%s file is open for writing",InpFileName);
PrintFormat("File path: %s\\Files\\",TerminalInfoString(TERMINAL_COMMONDATA_PAT
//--- prepare the counter of the number of bytes
uint counter=0;
//--- write array values in the loop
for(int i=0;i<size;i++)
{
uint byteswritten=FileWriteStruct(file_handle,cand_buff[i]);
//--- check the number of bytes written
if(byteswritten!=sizeof(candlesticks))
{
PrintFormat("Error read data. Error code=%d",GetLastError());
//--- close the file
FileClose(file_handle);
return;
}
else
counter+=byteswritten;
}
PrintFormat("%d bytes of information is written to %s file",InpFileName,counter
PrintFormat("Total number of bytes: %d * %d * %d = %d, %s",size,5,8,size*5*8,si
//--- close the file
FileClose(file_handle);
PrintFormat("Data is written, %s file is closed",InpFileName);
}
else
PrintFormat("Failed to open %s file, Error code = %d",InpFileName,GetLastError(
}
See also
Structures and classes
MQL4 Reference / File Functions / FolderCreate
FolderCreate
The function creates a folder in the Files directory (depending on the value of
common_flag).
bool FolderCreate( string folder_name, // String with the name of the new f
int common_flag=0 // Scope
);
Parameters
folder_name
[in] The name of the directory you want to create. Contains the full path to the folder.
common_flag=0
[in] Flag determining the location of the directory. If common_flag=FILE_COMMON,
then the directory is in the shared folder for all client terminals
\Terminal\Common\Files. Otherwise, the directory is in a local folder (MQL4\Files or
MQL4\Tester\Files in case of testing).
Return Value
Returns true if successful, otherwise - false.
Note
For security reasons, work with files is strictly controlled in the MQL4 language. Files
with which file operations are conducted using MQL4 means, cannot be outside the file
sandbox.
Example:
//+------------------------------------------------------------------+
//| Demo_FolderCreate.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- description
#property description "The script shows FolderCreate() application sample."
#property description "The external parameter defines the directory for creating fold
#property description "The folder structure is created after executing the script"
//--- display window of the input parameters during the script's launch
#property script_show_inputs
//--- the input parameter defines the folder, in which the script works
input bool common_folder=false; // common folder for all terminals
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- folder to be created in MQL5\Files
string root_folder="Folder_A";
if(CreateFolder(root_folder,common_folder))
{
//--- create the Child_Folder_B1 sub-folder in it
string folder_B1="Child_Folder_B1";
string path=root_folder+"\\"+folder_B1; // create the folder name cons
if(CreateFolder(path,common_folder))
{
//--- create 3 more sub-directories in this folder
string folder_C11="Child_Folder_C11";
string child_path=root_folder+"\\"+folder_C11;// create the folder name cons
CreateFolder(child_path,common_folder);
//--- second sub-directory
string folder_C12="Child_Folder_C12";
child_path=root_folder+"\\"+folder_C12;
CreateFolder(child_path,common_folder);
See also
FileOpen(), FolderClean(), FileCopy()
MQL4 Reference / File Functions / FolderDelete
FolderDelete
The function removes the specified directory. If the folder is not empty, then it can't be
removed.
bool FolderDelete( string folder_name, // String with the name of the folde
int common_flag=0 // Scope
);
Parameters
folder_name
[in] The name of the directory you want to delete. Contains the full path to the folder.
common_flag=0
[in] Flag determining the location of the directory. If common_flag=FILE_COMMON,
then the directory is in the shared folder for all client terminals
\Terminal\Common\Files. Otherwise, the directory is in a local folder (MQL4\Files or
MQL4\Tester\Files in the case of testing).
Return Value
Returns true if successful, otherwise false.
Note
For security reasons, work with files is strictly controlled in the MQL4 language. Files
with which file operations are conducted using MQL4 means, cannot be outside the file
sandbox.
If the directory contains at least one file and/or subdirectory, then this directory can't
be deleted, it must be cleared first. FolderClean() is used to clear a folder of all its
files or subfolders.
Example:
//+------------------------------------------------------------------+
//| Demo_FolderDelete.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- Description
#property description "The script shows a sample use of FolderDelete()."
#property description "First two folders are created; one of them is empty, the secon
#property description "When trying to delete a non-empty folder, an error is returned
//--- Show the dialog of input parameters when starting the script
#property script_show_inputs
//--- Input parameters
input string firstFolder="empty"; // An empty folder
input string secondFolder="nonempty";// The folder, in which one file will be creat
string filename="delete_me.txt"; // The name of the file that will be created i
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- Write the file handle here
int handle;
//--- Find out in what folder we are working
string working_folder=TerminalInfoString(TERMINAL_DATA_PATH)+"\\MQL4\\Files";
//--- A debug message
PrintFormat("working_folder=%s",working_folder);
//--- Trying to create an empty folder relative to path MQL4\Files
if(FolderCreate(firstFolder,0)) // 0 means that we are working in the local folder
{
//--- Enter the full path to the created folder
PrintFormat("Folder %s has been created",working_folder+"\\"+firstFolder);
//--- Reset the error code
ResetLastError();
}
else
PrintFormat("Failed to create folder %s. Error code %d",working_folder+"\\"+fir
ResetLastError();
//--- Delete the folder that contains a file
if(FolderDelete(secondFolder))
PrintFormat("Folder %s has been successfully deleted", secondFolder);
else
//--- The following message should appear since the folder contains a file
PrintFormat("Failed to delete folder %s. Error code=%d", secondFolder, GetLa
}
else
Print("Deletion canceled");
//---
}
See also
FileOpen(), FolderClean(), FileMove()
MQL4 Reference / File Functions / FolderClean
FolderClean
The function deletes all files in a specified folder.
bool FolderClean( string folder_name, // String with the name of the delete
int common_flag=0 // Scope
);
Parameters
folder_name
[in] The name of the directory where you want to delete all files. Contains the full
path to the folder.
common_flag=0
[in] Flag determining the location of the directory. If common_flag = FILE_COMMON,
then the directory is in the shared folder for all client terminals
\Terminal\Common\Files. Otherwise, the directory is in a local folder(MQL4\files or
MQL4\tester\files in case of testing).
Return Value
Returns true if successful, otherwise false.
Note
For security reasons, work with files is strictly controlled in the MQL4 language. Files
with which file operations are conducted using MQL4 means, cannot be outside the file
sandbox.
This function should be used with caution, since all the files and all subdirectories are
deleted irretrievably.
Example:
//+------------------------------------------------------------------+
//| Demo_FolderClean.mq5 |
//| Copyright 2011, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "Copyright 2011, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
//--- Description
#property description "The script shows a sample use of FolderClean()."
#property description "First, files are created in the specified folder using the Fil
#property description "Then, before the files are deleted, a warning is shown using M
//--- Show the dialog of input parameters when starting the script
#property script_show_inputs
//--- Input parameters
input string foldername="demo_folder"; // Create a folder in MQL4/Files/
input int files=5; // The number of files to create and delete
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
string name="testfile";
//--- First open or create files in the terminal data folder
for(int N=0;N<files;N++)
{
//--- The name of the file in the foem of 'demo_folder\testfileN.txt'
string filemane=StringFormat("%s\\%s%d.txt",foldername,name,N);
//--- Open a file with the flag for writing, in this case the 'demo_folder' wil
int handle=FileOpen(filemane,FILE_WRITE);
//--- Find out if the FileOpen() function was successful
if(handle==INVALID_HANDLE)
{
PrintFormat("Failed to create file %s. Error code",filemane,GetLastError());
ResetLastError();
}
else
{
PrintFormat("File %s has been successfully opened",filemane);
//--- The opened file is not needed any more, so close it
FileClose(handle);
}
}
See also
FileFindFirst(), FileFindNext(), FileFindClose()
MQL4 Reference / File Functions / FileOpenHistory
FileOpenHistory
Opens file in the current history directory (terminal_directory\history\server_name) or in
its subfolders.
int FileOpenHistory( int filename, // file name
int mode, // open mode
int delimiter=';' // delimiter
);
Parameters
filename
[in] File name.
mode
[in] File open mode. Can be one or combination of values: FILE_BIN, FILE_CSV,
FILE_READ, FILE_WRITE, FILE_SHARE_READ, FILE_SHARE_WRITE.
delimiter=';'
[in] Delimiter for csv files. By default, the ';' symbol will be passed.
Returned value
Returns the file handle for the opened file. If the function fails, the returned value is
-1. To get the detailed error information, call the GetLastError() function.
Note
Client terminal can connect to servers of different brokerage companies. History data
(HST files) for each brokerage company are stored in the corresponding subfolder of the
terminal_directory\history folder. The function can be useful to form own history data
for a non-standard symbol and/or period. The file formed in the history folder can be
opened offline, not data pumping is needed to chart it.
In the new MQL4, FILE_SHARE_WRITE and FILE_SHARE_READ flags should explicitly be
specified for shared use when opening files. If the flags are absent, the file is opened in
exclusive mode and cannot be opened by anyone else till it is closed by the user who
opened it (see "Offline Charts in the New MQL4").
Example:
int handle=FileOpenHistory("USDX240.HST",FILE_BIN|FILE_WRITE|FILE_SHARE_WRITE|FILE_
if(handle<1)
{
Print("Cannot open file USDX240.HST");
return(false);
}
// work with file
// ...
FileClose(handle);
MQL4 Reference / Custom Indicators
Custom Indicators
This is the group functions used in the creation of custom
indicators. These functions can't be used when writing
Expert Advisors and Scripts.
Function Action
HideTestIndicators The function sets a flag hiding indicators
called by the Expert Advisor
IndicatorSetDouble Sets the value of an indicator property of
the double type
IndicatorSetInteger Sets the value of an indicator property of
the int type
IndicatorSetString Sets the value of an indicator property of
the string type
SetIndexBuffer Binds the specified indicator buffer with
one-dimensional dynamic array of the
double type
IndicatorBuffers Allocates memory for buffers used for
custom indicator calculations
IndicatorCounted Returns the amount of bars not changed
after the indicator had been launched last
IndicatorDigits Sets precision format to visualize indicator
values
IndicatorShortName Sets the "short" name of a custom indicator
to be shown in the DataWindow and in the
chart subwindow
SetIndexArrow Sets an arrow symbol for indicators line of
the DRAW_ARROW type
Function Action
SetIndexDrawBegin Sets the bar number from which the
drawing of the given indicator line must
start
SetIndexEmptyValue Sets drawing line empty value
SetIndexLabel Sets drawing line description for showing in
the DataWindow and in the tooltip
SetIndexShift Sets offset for the drawing line
SetIndexStyle Sets the new type, style, width and color
for a given indicator line
SetLevelStyle Sets a new style, width and color of
horizontal levels of indicator to be output
in a separate window
SetLevelValue Sets a value for a given horizontal level of
the indicator to be output in a separate
window
HideTestIndicators
The function sets a flag hiding indicators called by the
Expert Advisor.
void HideTestIndicators( bool hide // flag
);
Parameters
hide
[in] Hiding flag.
Returned value
None.
Note
After the Expert Advisor has been tested and the
appropriate chart opened, the flagged indicators will not
be drawn in the testing chart. Every indicator called will
first be flagged with the current hiding flag. It must be
noted that only those indicators can be drawn in the
testing chart that are directly called from the expert
under test.
Example:
HideTestIndicators(true);
MaCurrent=iMA(NULL,0,56,0,MODE_EMA,PRICE_CLOSE,0);
MaPrevious=iMA(NULL,0,56,0,MODE_EMA,PRICE_CLOSE,1);
HideTestIndicators(false);
MQL4 Reference / Custom Indicators / IndicatorSetDouble
IndicatorSetDouble
The function sets the value of the corresponding indicator property.
Indicator property must be of the double type. There are two variants of
the function.
Call with specifying the property identifier.
bool IndicatorSetDouble( int prop_id, // identifier
double prop_value // value to be set
);
Parameters
prop_id
[in] Identifier of the indicator property. The value can be one of the
values of the ENUM_CUSTOMIND_PROPERTY_DOUBLE enumeration.
prop_modifier
[in] Modifier of the specified property. Only level properties require a
modifier. Numbering of levels starts from 0. It means that in order to set
property for the second level you need to specify 1 (1 less than when
using compiler directive).
prop_value
[in] Value of property.
Return Value
In case of successful execution, returns true, otherwise - false.
Note
Numbering of properties (modifiers) starts from 1 (one) when using the
#property directive, while the function uses numbering from 0 (zero). In
case the level number is set incorrectly, indicator display can differ from
the intended one.
For example, the first level value for the indicator in a separate
subwindow can be set in two ways:
property indicator_level1 50 - the value of 1 is used for specifying the
level number,
IndicatorSetDouble(INDICATOR_LEVELVALUE, 0, 50) - 0 is used for
specifying the first level.
Example: indicator that turns upside down the values of levels on which the
horizontal lines are placed.
#property indicator_separate_window
//--- set the maximum and minimum values for the indicator window
#property indicator_minimum 0
#property indicator_maximum 100
//--- display two horizontal levels in a separate indicator window
#property indicator_level1 25
#property indicator_level2 75
//--- set thickness of horizontal levels
#property indicator_levelwidth 1
//--- set style of horizontal levels
#property indicator_levelstyle STYLE_DOT
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- two levels
IndicatorSetInteger(INDICATOR_LEVELS,2);
//--- set descriptions of horizontal levels
IndicatorSetString(INDICATOR_LEVELTEXT,0,"First Level (index 0)");
IndicatorSetString(INDICATOR_LEVELTEXT,1,"Second Level (index 1)");
//--- set the short name for indicator
IndicatorSetString(INDICATOR_SHORTNAME,"IndicatorSetDouble() Demo");
//--- set clrBlue color for all levels
IndicatorSetInteger(INDICATOR_LEVELCOLOR,0,clrBlue);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int tick_counter=0;
static double level1=25,level2=75;
static int delta=1;
//--- calculate ticks
tick_counter+=delta;
//--- check ranges
if(tick_counter<0) delta=5;
if(tick_counter>25) delta=-5;
//--- calculate new values
level1+=delta;
level2-=delta;
//--- set new values for levels
IndicatorSetDouble(INDICATOR_LEVELVALUE,0,level1);
IndicatorSetDouble(INDICATOR_LEVELVALUE,1,level2);
//--- return value of prev_calculated for next call
return(rates_total);
}
See also
Drawing Styles
MQL4 Reference / Custom Indicators / IndicatorSetInteger
IndicatorSetInteger
The function sets the value of the corresponding indicator property. Indicator property
must be of the int or color type. There are two variants of the function.
Call with specifying the property identifier.
bool IndicatorSetInteger( int prop_id, // identifier
int prop_value // value to be set
);
Parameters
prop_id
[in] Identifier of the indicator property. The value can be one of the values of the
ENUM_CUSTOMIND_PROPERTY_INTEGER enumeration.
prop_modifier
[in] Modifier of the specified property. Only level properties require a modifier.
prop_value
[in] Value of property.
Return Value
In case of successful execution, returns true, otherwise - false.
Note
Numbering of properties (modifiers) starts from 1 (one) when using the #property
directive, while the function uses numbering from 0 (zero). In case the level number is
set incorrectly, indicator display can differ from the intended one.
For example, in order to set thickness of the first horizontal line use zeroth index:
IndicatorSetInteger(INDICATOR_LEVELWIDTH, 0, 5) - index 0 is used to set thickness
of the first level.
Example: indicator that turns upside down the values of levels on which the horizontal
lines are placed.
#property indicator_separate_window
//--- set the maximum and minimum values for the indicator window
#property indicator_minimum 0
#property indicator_maximum 100
//--- display three horizontal levels in a separate indicator window
#property indicator_level1 20
#property indicator_level2 50
#property indicator_level3 80
//--- set thickness of horizontal levels
#property indicator_levelwidth 5
//--- set color of horizontal levels
#property indicator_levelcolor clrAliceBlue
//--- set style of horizontal levels
#property indicator_levelstyle STYLE_DOT
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- set descriptions of horizontal levels
IndicatorSetString(INDICATOR_LEVELTEXT,0,"First Level (index 0)");
IndicatorSetString(INDICATOR_LEVELTEXT,1,"Second Level (index 1)");
IndicatorSetString(INDICATOR_LEVELTEXT,2,"Third Level (index 2)");
//--- set the short name for indicator
IndicatorSetString(INDICATOR_SHORTNAME,"IndicatorSetInteger() Demo");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
static int tick_counter=0;
//--- calculate ticks
tick_counter++;
//--- and calculate colors of horizontal levels depending on the tick counter
ChangeLevelsColor(tick_counter,3,6,10); // three last parameters are switching the
//--- modify style of horizontal levels
ChangeLevelStyle(tick_counter);
//--- get width as the remainder of integer division of the ticks number by 5
int width=tick_counter%5;
//--- iterate over all horizontal levels and set thickness
IndicatorSetInteger(INDICATOR_LEVELWIDTH,0,width+1);
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| Set color of horizontal line in the separate indicator window |
//+------------------------------------------------------------------+
void ChangeLevelsColor(int tick_number,// dividend, number to get the remainder of di
int f_trigger, // first divisor of color switching
int s_trigger, // second divisor of color switching
int t_trigger) // third divisor of color switching
{
static color colors[3]={clrRed,clrBlue,clrGreen};
//--- index of color from the colors[] array
int index=-1;
//--- calculate the number of color from the colors[] array to paint horizontal line
if(tick_number%f_trigger==0)
index=0; // if tick_number divides by f_trigger without the remainder
if(tick_number%s_trigger==0)
index=1; // if tick_number divides by s_trigger without the remainder
if(tick_number%t_trigger==0)
index=2; // if tick_number divides by t_trigger without the remainder
//--- if color is defined, set it
if(index!=-1)
IndicatorSetInteger(INDICATOR_LEVELCOLOR,0,colors[index]);
//---
}
//+------------------------------------------------------------------+
//| Set style of horizontal line in the separate indicator window |
//+------------------------------------------------------------------+
void ChangeLevelStyle(int tick_number) // number to get the remainder of division
{
//--- array to store styles
static ENUM_LINE_STYLE styles[5]=
{STYLE_SOLID,STYLE_DASH,STYLE_DOT,STYLE_DASHDOT,STYLE_DASHDOTDOT};
//--- index of style from the styles[] array
int index=-1;
//--- calculate the number from the styles[] array to set style of horizontal line
if(tick_number%50==0)
index=5; // if tick_number divides by 50 without the remainder, then style is
if(tick_number%40==0)
index=4; // ... STYLE_DASHDOT
if(tick_number%30==0)
index=3; // ... STYLE_DOT
if(tick_number%20==0)
index=2; // ... STYLE_DASH
if(tick_number%10==0)
index=1; // ... STYLE_SOLID
//--- if style is defined, set it
if(index!=-1)
IndicatorSetInteger(INDICATOR_LEVELSTYLE,0,styles[index]);
}
See also
Custom Indicator Properties, Program Properties (#property), Drawing Styles
MQL4 Reference / Custom Indicators / IndicatorSetString
IndicatorSetString
The function sets the value of the corresponding indicator property.
Indicator property must be of the string type. There are two variants of the
function.
Call with specifying the property identifier.
bool IndicatorSetString( int prop_id, // identifier
string prop_value // value to be set
);
Parameters
prop_id
[in] Identifier of the indicator property. The value can be one of the
values of the ENUM_CUSTOMIND_PROPERTY_STRING enumeration.
prop_modifier
[in] Modifier of the specified property. Only level properties require a
modifier.
prop_value
[in] Value of property.
Return Value
In case of successful execution, returns true, otherwise - false.
Note
Numbering of properties (modifiers) starts from 1 (one) when using the
#property directive, while the function uses numbering from 0 (zero). In
case the level number is set incorrectly, indicator display can differ from
the intended one.
For example, in order to set description of the first horizontal line use
zeroth index:
IndicatorSetString(INDICATOR_LEVELTEXT, 0, "First Level") - index 0 is
used to set text description of the first level.
Example: indicator that sets text labels to the indicator horizontal lines.
#property indicator_separate_window
#property indicator_minimum 0
#property indicator_maximum 100
//--- display three horizontal levels in a separate indicator window
#property indicator_level1 30
#property indicator_level2 50
#property indicator_level3 70
//--- set color of horizontal levels
#property indicator_levelcolor clrRed
//--- set style of horizontal levels
#property indicator_levelstyle STYLE_SOLID
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- set descriptions of horizontal levels
IndicatorSetString(INDICATOR_LEVELTEXT,0,"First Level (index 0)");
IndicatorSetString(INDICATOR_LEVELTEXT,1,"Second Level (index 1)");
IndicatorSetString(INDICATOR_LEVELTEXT,2,"Third Level (index 2)");
//--- set the short name for indicator
IndicatorSetString(INDICATOR_SHORTNAME,"IndicatorSetString() Demo");
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
//---
See also
Custom Indicator Properties, Program Properties (#property)
MQL4 Reference / Custom Indicators / SetIndexBuffer
SetIndexBuffer
The function binds a specified indicator buffer with one-dimensional dynamic
array of the double type. There are two variants of the function.
bool SetIndexBuffer( int index, // buffer index
double buffer[], // array
ENUM_INDEXBUFFER_TYPE data_type // what will be stored
);
Parameters
index
[in] Number of the indicator buffer. The numbering starts with 0. The number
must be less than the value declared in #property indicator_buffers.
buffer[]
[in] An array declared in the custom indicator program.
Return Value
If successful, returns true, otherwise - false.
Note
After binding, the dynamic array buffer[] will be indexed as in common arrays,
even if the indexing of timeseries is pre-installed for the bound array. If you want
to change the order of access to elements of the indicator array, use the
ArraySetAsSeries() function after binding the array using the SetIndexBuffer()
function. Please note that you can't change the size for dynamic arrays set as
indicator buffers by the function SetIndexBuffer(). For indicator buffers, all
operations of size changes are performed by the executing sub-system of the
terminal.
Example:
double ExtBufferSilver[];
int init()
{
SetIndexBuffer(0, ExtBufferSilver); // buffer of the first line
// ...
}
See also
Custom Indicator Properties, Access to timeseries and indicators
MQL4 Reference / Custom Indicators / IndicatorBuffers
IndicatorBuffers
Allocates memory for buffers used for custom indicator calculations.
bool IndicatorBuffers( int count // buffers
);
Parameters
count
[in] Amount of buffers to be allocated. Should be within the range between
indicator_buffers and 512 buffers.
Returned value
true, if the amount of buffers has been changed successfully, otherwise false.
Note
The amount of buffers cannot exceed 512 and be less than the value set in
#property indicator_buffers. If a custom indicator requires additional buffers
for counting, IndicatorBuffers() function should be used for specifying the total
amount of buffers.
Example:
//+------------------------------------------------------------------+
//| Bulls.mq4 |
//| Copyright 2005-2013, MetaQuotes Software Corp. |
//| https://www.mql4.com |
//+------------------------------------------------------------------+
#property copyright "2005-2013, MetaQuotes Software Corp."
#property link "https://www.mql4.com"
#property description "Bulls Power"
#property strict
//--- indicator settings
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//--- input parameter
input int InpBullsPeriod=13;
//--- buffers
double ExtBullsBuffer[];
double ExtTempBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit(void)
{
string short_name;
//--- 1 additional buffer used for counting.
IndicatorBuffers(2);
IndicatorDigits(Digits);
//--- drawing style
SetIndexStyle(0,DRAW_HISTOGRAM);
SetIndexBuffer(0,ExtBullsBuffer);
SetIndexBuffer(1,ExtTempBuffer);
//--- name for DataWindow and indicator subwindow label
short_name="Bulls("+IntegerToString(InpBullsPeriod)+")";
IndicatorShortName(short_name);
SetIndexLabel(0,short_name);
}
//+------------------------------------------------------------------+
//| Bulls Power |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
int limit=rates_total-prev_calculated;
//---
if(rates_total<=InpBullsPeriod)
return(0);
//---
if(prev_calculated>0)
limit++;
for(int i=0; i<limit; i++)
{
ExtTempBuffer[i]=iMA(NULL,0,InpBullsPeriod,0,MODE_EMA,PRICE_CLOSE,i);
ExtBullsBuffer[i]=high[i]-ExtTempBuffer[i];
}
//---
return(rates_total);
}
See also
Custom Indicator Properties, Access to timeseries and indicators
MQL4 Reference / Custom Indicators / IndicatorCounted
IndicatorCounted
The function returns the amount of bars not changed after the indicator had
been launched last.
int IndicatorCounted();
Returned value
The amount of bars not changed after the indicator had been launched last.
Note
The most calculated bars do not need any recalculation. In most cases, same
count of index values do not need for recalculation. The function is used to
optimize calculating.
Example:
int start() {
int limit;
int counted_bars=IndicatorCounted();
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- the last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- main loop
for(int i=0; i<limit; i++)
{
//---- ma_shift set to 0 because SetIndexShift called abowe
ExtBlueBuffer[i]=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtRedBuffer[i]=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtLimeBuffer[i]=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
}
//---- done
return(0);
}
See also
Custom Indicator Properties, Access to timeseries and indicators
MQL4 Reference / Custom Indicators / IndicatorDigits
IndicatorDigits
Sets precision format (the count of digits after decimal point) to visualize
indicator values.
void IndicatorDigits( int digits // digits
);
Parameters
digits
[in] Precision format, the count of digits after decimal point.
Returned value
None.
Note
The symbol price preicision is used by default, the indicator being
attached to this symbol chart.
Example:
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- setting of drawing parameters
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(Digits+2);
//---- 3 allocated buffers of an indicator
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//---- "short name" for DataWindow and indicator subwindow
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}
See also
Custom Indicator Properties
MQL4 Reference / Custom Indicators / IndicatorShortName
IndicatorShortName
Sets the "short" name of a custom indicator to be shown in the
DataWindow and in the chart subwindow.
void IndicatorShortName( string name // name
);
Parameters
name
[in] New short name.
Returned value
None.
Example:
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}
See also
Custom Indicator Properties
MQL4 Reference / Custom Indicators / SetIndexArrow
SetIndexArrow
Sets an arrow symbol for indicators line of the DRAW_ARROW
type.
void SetIndexArrow( int index, // line index
int code // code
);
Parameters
index
[in] Line index. Must lie between 0 and 7.
code
[in] Symbol code from Wingdings font or predefined arrow
constant.
Returned value
None.
Note
Arrow codes out of range 33 to 255 cannot be used.
Example:
int init()
{
//---- 2 allocated indicator buffers
SetIndexBuffer(0,ExtUppperBuffer);
SetIndexBuffer(1,ExtLowerBuffer);
//---- drawing parameters setting
SetIndexStyle(0,DRAW_ARROW);
SetIndexArrow(0,217);
SetIndexStyle(1,DRAW_ARROW);
SetIndexArrow(1,218);
//---- displaying in the DataWindow
SetIndexLabel(0,"Fractal Up");
SetIndexLabel(1,"Fractal Down");
//---- initialization done
return(0);
}
See also
Custom Indicator Properties
MQL4 Reference / Custom Indicators / SetIndexDrawBegin
SetIndexDrawBegin
Sets the bar number (from the data beginning) from which the drawing of the
given indicator line must start.
void SetIndexDrawBegin( int index, // line index
int begin // position
);
Parameters
index
[in] Line index. Must lie between 0 and 7.
begin
[in] First drawing bar position number.
Returned value
None.
Note
The indicators are drawn from left to right. The indicator array values that are
to the left of the given bar will not be shown in the chart or in the DataWindow.
0 will be set as default, and all data will be drawn.
Example:
//+------------------------------------------------------------------+
//| Alligator.mq4 |
//| Copyright 2005-2013, MetaQuotes Software Corp. |
//| https://www.mql4.com |
//+------------------------------------------------------------------+
#property copyright "2005-2013, MetaQuotes Software Corp."
#property link "https://www.mql4.com"
#property description "Bill Williams' Alligator"
#property strict
//--- indicator settings
#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1 Blue
#property indicator_color2 Red
#property indicator_color3 Lime
//--- input parameters
input int InpJawsPeriod=13; // Jaws Period
input int InpJawsShift=8; // Jaws Shift
input int InpTeethPeriod=8; // Teeth Period
input int InpTeethShift=5; // Teeth Shift
input int InpLipsPeriod=5; // Lips Period
input int InpLipsShift=3; // Lips Shift
//--- indicator buffers
double ExtBlueBuffer[];
double ExtRedBuffer[];
double ExtLimeBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
void OnInit(void)
{
IndicatorDigits(Digits);
//--- line shifts when drawing
SetIndexShift(0,InpJawsShift);
SetIndexShift(1,InpTeethShift);
SetIndexShift(2,InpLipsShift);
//--- first positions skipped when drawing
SetIndexDrawBegin(0,InpJawsShift+InpJawsPeriod);
SetIndexDrawBegin(1,InpTeethShift+InpTeethPeriod);
SetIndexDrawBegin(2,InpLipsShift+InpLipsPeriod);
//--- 3 indicator buffers mapping
SetIndexBuffer(0,ExtBlueBuffer);
SetIndexBuffer(1,ExtRedBuffer);
SetIndexBuffer(2,ExtLimeBuffer);
//--- drawing settings
SetIndexStyle(0,DRAW_LINE);
SetIndexStyle(1,DRAW_LINE);
SetIndexStyle(2,DRAW_LINE);
//--- index labels
SetIndexLabel(0,"Gator Jaws");
SetIndexLabel(1,"Gator Teeth");
SetIndexLabel(2,"Gator Lips");
}
//+------------------------------------------------------------------+
//| Bill Williams' Alligator |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
int limit=rates_total-prev_calculated;
//--- main loop
for(int i=0; i<limit; i++)
{
//--- ma_shift set to 0 because SetIndexShift called abowe
ExtBlueBuffer[i]=iMA(NULL,0,InpJawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtRedBuffer[i]=iMA(NULL,0,InpTeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtLimeBuffer[i]=iMA(NULL,0,InpLipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
}
//--- done
return(rates_total);
}
See also
Custom Indicator Properties
MQL4 Reference / Custom Indicators / SetIndexEmptyValue
SetIndexEmptyValue
Sets drawing line empty value.
void SetIndexEmptyValue( int index, // line index
double value // new "empty value"
);
Parameters
index
[in] Line index. Must lie between 0 and 7.
value
[in] New "empty" value.
Returned value
None.
Note
Empty values are not drawn or shown in the DataWindow. By
default, empty value is EMPTY_VALUE.
Example:
int init()
{
//---- 2 allocated indicator buffers
SetIndexBuffer(0,ExtUppperBuffer);
SetIndexBuffer(1,ExtLowerBuffer);
//---- drawing parameters setting
SetIndexStyle(0,DRAW_ARROW);
SetIndexArrow(0,217);
SetIndexStyle(1,DRAW_ARROW);
SetIndexArrow(1,218);
//---- 0 value will not be displayed
SetIndexEmptyValue(0,0.0);
SetIndexEmptyValue(1,0.0);
//---- displaying in DataWindow
SetIndexLabel(0,"Fractal Up");
SetIndexLabel(1,"Fractal Down");
//---- initialization done
return(0);
}
See also
Custom Indicator Properties
MQL4 Reference / Custom Indicators / SetIndexLabel
SetIndexLabel
Sets drawing line description for showing in the DataWindow and in the
tooltip.
void SetIndexLabel( int index, // line index
string text // text
);
Parameters
index
[in] Line index. Must lie between 0 and 7.
text
[in] Label text. NULL means that index value is not shown in the
DataWindow.
Returned value
None.
Example:
//+------------------------------------------------------------------+
//| Ichimoku Kinko Hyo initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,Tenkan_Buffer);
SetIndexDrawBegin(0,Tenkan-1);
SetIndexLabel(0,"Tenkan Sen");
//----
SetIndexStyle(1,DRAW_LINE);
SetIndexBuffer(1,Kijun_Buffer);
SetIndexDrawBegin(1,Kijun-1);
SetIndexLabel(1,"Kijun Sen");
//----
a_begin=Kijun; if(a_begin<Tenkan) a_begin=Tenkan;
SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_DOT);
SetIndexBuffer(2,SpanA_Buffer);
SetIndexDrawBegin(2,Kijun+a_begin-1);
SetIndexShift(2,Kijun);
//---- Up Kumo bounding line does not show in the DataWindow
SetIndexLabel(2,NULL);
SetIndexStyle(5,DRAW_LINE,STYLE_DOT);
SetIndexBuffer(5,SpanA2_Buffer);
SetIndexDrawBegin(5,Kijun+a_begin-1);
SetIndexShift(5,Kijun);
SetIndexLabel(5,"Senkou Span A");
//----
SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_DOT);
SetIndexBuffer(3,SpanB_Buffer);
SetIndexDrawBegin(3,Kijun+Senkou-1);
SetIndexShift(3,Kijun);
//---- Down Kumo bounding line does not show in the DataWindow
SetIndexLabel(3,NULL);
//----
SetIndexStyle(6,DRAW_LINE,STYLE_DOT);
SetIndexBuffer(6,SpanB2_Buffer);
SetIndexDrawBegin(6,Kijun+Senkou-1);
SetIndexShift(6,Kijun);
SetIndexLabel(6,"Senkou Span B");
//----
SetIndexStyle(4,DRAW_LINE);
SetIndexBuffer(4,Chinkou_Buffer);
SetIndexShift(4,-Kijun);
SetIndexLabel(4,"Chikou Span");
//----
return(0);
}
See also
Custom Indicator Properties
MQL4 Reference / Custom Indicators / SetIndexShift
SetIndexShift
Sets offset for the drawing line.
void SetIndexShift( int index, // line index
int shift // shift
);
Parameters
index
[in] Line index. Must lie between 0 and 7.
shift
[in] Shift value in bars.
Returned value
None.
Note
For positive values, the line drawing will be shifted to the right,
otherwise it will be shifted to the left. I.e., the value calculated on the
current bar will be drawn shifted relatively to the current bar.
Example:
//+------------------------------------------------------------------+
//| Alligator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- line shifts when drawing
SetIndexShift(0,JawsShift);
SetIndexShift(1,TeethShift);
SetIndexShift(2,LipsShift);
//---- first positions skipped when drawing
SetIndexDrawBegin(0,JawsShift+JawsPeriod);
SetIndexDrawBegin(1,TeethShift+TeethPeriod);
SetIndexDrawBegin(2,LipsShift+LipsPeriod);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ExtBlueBuffer);
SetIndexBuffer(1,ExtRedBuffer);
SetIndexBuffer(2,ExtLimeBuffer);
//---- drawing settings
SetIndexStyle(0,DRAW_LINE);
SetIndexStyle(1,DRAW_LINE);
SetIndexStyle(2,DRAW_LINE);
//---- index labels
SetIndexLabel(0,"Gator Jaws");
SetIndexLabel(1,"Gator Teeth");
SetIndexLabel(2,"Gator Lips");
//---- initialization done
return(0);
}
See also
Custom Indicator Properties
MQL4 Reference / Custom Indicators / SetIndexStyle
SetIndexStyle
Sets the new type, style, width and color for a given indicator
line.
void SetIndexStyle( int index, // line index
int type, // line type
int style=EMPTY, // line style
int width=EMPTY, // line width
color clr=clrNONE // line color
);
Parameters
index
[in] Line index. Must lie between 0 and 7.
type
[in] Shape style. Can be one of Drawing shape styles listed.
style=EMPTY
[in] Drawing style. It is used for one-pixel thick lines. It
can be one of the Drawing shape styles listed. EMPTY value
means that the style will not be changed.
width=EMPTY
[in] Line width. Valid values are: 1,2,3,4,5. EMPTY value
means that width will not be changed.
clr=clrNONE
[in] Line color. Absence of this parameter means that the
color will not be changed.
Returned value
None.
Example:
SetIndexStyle(3,DRAW_LINE,EMPTY,2,clrRed);
See also
Custom Indicator Properties
MQL4 Reference / Custom Indicators / SetLevelStyle
SetLevelStyle
The function sets a new style, width and color of horizontal levels of
indicator to be output in a separate window.
void SetLevelStyle( int draw_style, // drawing style
int line_width, // line width
color clr // color
);
Parameters
draw_style
[in] Drawing style. Can be one of the Drawing shape styles listed.
EMPTY value means that the style will not be changed.
line_width
[in] Line width. Valid values are 1,2,3,4,5. EMPTY value indicates
that the width will not be changed.
clr
[in] Line color. Empty value CLR_NONE means that the color will
not be changed.
Returned value
None.
Example:
//--- show levels as thick red lines
SetLevelStyle(STYLE_SOLID,2,clrRed);
See also
Custom Indicator Properties
MQL4 Reference / Custom Indicators / SetLevelValue
SetLevelValue
The function sets a value for a given horizontal level of
the indicator to be output in a separate window.
void SetLevelValue( int level, // level
double value // value
);
Parameters
level
[in] Level index (0-31).
value
[in] Value for the given indicator level.
Returned value
None.
Example:
SetLevelValue(1,3.14);
See also
Custom Indicator Properties
MQL4 Reference / Object Functions
Object Functions
This is the group of functions intended for working with
graphic objects relating to any specified chart. When
working with objects on the current chart, a direct access is
used, i.e. the existence of the specified object is pre-
checked during the function call, and the error code is
immediately returned in case of failure. When a function is
used for the objects of a chart other than the current one,
an asynchronous function call is used, during which no pre-
checks are performed and the function is added to the
queue of that chart as is.
Functions that set the properties of graphical objects, as
well as the ObjectCreate() and ObjectMove() operations are
actually used for sending commands to a chart. If these
functions are executed successfully, the command is added
to the queue of chart events. Visual changes in the
properties of graphical objects are implemented upon
handling of chart events from the queue.
That is why you should do not expect an immediate visual
update of graphical objects after calling these functions.
Generally, graphical objects on a chart are updated
automatically by the terminal based on update events, such
as a new quote arrival, chart window resizing, etc. Use the
ChartRedraw() command to force the update of graphical
objects.
Function Action
ObjectCreate Creates an object of the specified
type in a specified chart
Function Action
ObjectName Returns the name of an object by its
index in the objects list
ObjectDelete Removes the object having the
specified name
ObjectsDeleteAll Removes all objects of the specified
type from the specified chart
subwindow
ObjectFind Searches for an object having the
specified name
ObjectGetTimeByValue Returns the time value for the
specified object price value
ObjectGetValueByTime Returns the price value of an object
for the specified time
ObjectMove Changes the coordinates of the
specified object anchor point
ObjectsTotal Returns the number of objects of the
specified type
ObjectGetDouble Returns the double value of the
corresponding object property
ObjectGetInteger Returns the integer value of the
corresponding object property
ObjectGetString Returns the string value of the
corresponding object property
ObjectSetDouble Sets the value of the corresponding
object property
ObjectSetInteger Sets the value of the corresponding
object property
ObjectSetString Sets the value of the corresponding
object property
Function Action
TextSetFont Sets the font for displaying the text
using drawing methods (Arial 20 used
by default)
TextOut Transfers the text to the custom array
(buffer) designed for creation of a
graphical resource
TextGetSize Returns the string's width and height
at the current font settings
ObjectDescription Returns the object description
ObjectGet Returns the value of the specified
object property
ObjectGetFiboDescription Returns the level description of a
Fibonacci object
ObjectGetShiftByValue Calculates and returns bar index for
the given price
ObjectGetValueByShift Calculates and returns the price value
for the specified bar
ObjectSet Changes the value of the specified
object property
ObjectSetFiboDescription Sets a new description to a level of a
Fibonacci object
ObjectSetText Changes the object description
ObjectType Returns the object type
ObjectCreate
The function creates an object with the specified name, type, and the initial coordinates
in the specified chart subwindow of the specified chart. There are two variants of the
function:
bool ObjectCreate( long chart_id, // chart ID
string object_name, // object name
ENUM_OBJECT object_type, // object type
int sub_window, // window index
datetime time1, // time of the first anchor point
double price1, // price of the first anchor point
...
datetime timeN=0, // time of the N-th anchor point
double priceN=0 // price of the N-th anchor point
);
The function creates an object with the specified name, type, and the initial coordinates
in the specified chart subwindow:
bool ObjectCreate(
string object_name, // object name
ENUM_OBJECT object_type, // object type
int sub_window, // window index
datetime time1, // time of the first anchor point
double price1, // price of the first anchor point
datetime time2=0, // time of the second anchor point
double price2=0, // price of the second anchor point
datetime time3=0, // time of the third anchor point
double price3=0 // price of the third anchor point
);
Parameters
chart_id
[in] Chart identifier.
object_name
[in] Name of the object. The name must be unique within a chart, including its
subwindows.
object_type
[in] Object type. The value can be one of the values of the ENUM_OBJECT
enumeration.
sub_window
[in] Number of the chart subwindow. 0 means the main chart window. The specified
subwindow must exist (window index must be greater or equal to 0 and less than
WindowsTotal()), otherwise the function returns false.
time1
[in] The time coordinate of the first anchor point.
price1
[in] The price coordinate of the first anchor point.
time2=0
[in] The time coordinate of the second anchor point.
price2=0
[in] The price coordinate of the second anchor point.
time3=0
[in] The time coordinate of the third anchor point.
price3=0
[in] The price coordinate of the third anchor point.
timeN=0
[in] The time coordinate of the N-th anchor point.
priceN=0
[in] The price coordinate of the N-th anchor point.
Return Value
When the function is used on the current chart, the chart is accessed directly (a usual
behavior in MQL4), and the return of true means a successful creation of an object;
otherwise false is returned. In this case, you should call GetLastError() for further
information about the error.
To create objects on a different size, an asynchronous function call is used, and
ObjectCreate() only returns the result of command adding to the chart queue. In this
case true means that the object creation command has been successfully enqueued,
while the command execution result is unknown. To check the command execution
result, you can use the ObjectFind function or any other function that request object
properties, such as ObjectGetXXX. However, you should keep in mind that such
functions are added to the end of the queue of that chart, and they wait for the
execution result (due to the synchronous call), and can therefore be time consuming.
Note
An object name should not exceed 63 characters. Characters not belonging to the
current code page are not allowed (characters that cannot be converted from Unicode
to ANSI are replaced with '?'). If programs are to be distributed among users with
different code pages, we strongly recommend using Latin characters in object names.
Objects of the OBJ_LABEL type ignore the coordinates. Use the ObjectSet() function to
set up the OBJPROP_XDISTANCE and OBJPROP_YDISTANCE properties. The chart sub-
windows (if there are sub-windows with indicators in the chart) are numbered starting
from 1. The chart main window always exists and has the 0 index. Coordinates must be
passed in pairs: time and price. For example, the OBJ_VLINE object needs only time,
but price (any value) must be passed, as well.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
int start()
{
int i;
string obj_name="label_object";
long current_chart_id=ChartID();
//--- creating label object (it does not have time/price coordinates)
if(!ObjectCreate(current_chart_id,obj_name,OBJ_LABEL,0,0,0))
{
Print("Error: can't create label! code #",GetLastError());
return(0);
}
//--- set color to Red
ObjectSetInteger(current_chart_id,obj_name,OBJPROP_COLOR,clrRed);
//--- move object down and change its text
for(i=0; i<200; i++)
{
//--- set text property
ObjectSetString(current_chart_id,obj_name,OBJPROP_TEXT,StringFormat("Simple Lab
//--- set distance property
ObjectSet(obj_name,OBJPROP_YDISTANCE,i);
//--- forced chart redraw
ChartRedraw(current_chart_id);
Sleep(10);
}
//--- set color to Blue
ObjectSetInteger(current_chart_id,obj_name,OBJPROP_COLOR,clrBlue);
//--- move object up and change its text
for(i=200; i>0; i--)
{
//--- set text property
ObjectSetString(current_chart_id,obj_name,OBJPROP_TEXT,StringFormat("Simple Lab
//--- set distance property
ObjectSet(obj_name,OBJPROP_YDISTANCE,i);
//--- forced chart redraw
ChartRedraw(current_chart_id);
Sleep(10);
}
//--- delete object
ObjectDelete(obj_name);
return(0);
}
See also
Object types
MQL4 Reference / Object Functions / ObjectName
ObjectName
The function returns the name of the corresponding object by its index in the objects
list.
string ObjectName( int object_index // object index
);
Parameters
object_index
[in] Object index. This value must be greater or equal to 0 and less than
ObjectsTotal().
Return Value
Name of the object is returned in case of success. To get the detailed error
information, one has to call the GetLastError() function.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
int i;
long current_chart_id=ChartID();
//--- creates several objects of label type
for(i=0; i<300; i+=10)
{
string obj_name="label_object"+IntegerToString(i);
//--- creating label object (it does not have time/price coordinates)
if(ObjectCreate(obj_name,OBJ_LABEL,0,0,0))
{
PrintFormat("Object %s created.",obj_name);
//--- set random color
ObjectSetInteger(current_chart_id,obj_name,OBJPROP_COLOR,MathRand());
//--- set text property
ObjectSetString(current_chart_id,obj_name,OBJPROP_TEXT,StringFormat("Simple
//--- set distance property
ObjectSet(obj_name,OBJPROP_XDISTANCE,i);
ObjectSet(obj_name,OBJPROP_YDISTANCE,i);
//--- forced chart redraw
ChartRedraw(current_chart_id);
Sleep(10);
}
else
{
Print("Error: can't create label! code #",GetLastError());
}
}
//--- sleep to see the objects created
Sleep(3000);
//--- show all objects
int obj_total=ObjectsTotal();
PrintFormat("Total %d objects",obj_total);
string name;
for(i=0;i<obj_total;i++)
{
name=ObjectName(i);
PrintFormat("%d object: Object name - %s",i,name);
}
//--- delete all objects
ObjectsDeleteAll();
}
MQL4 Reference / Object Functions / ObjectDelete
ObjectDelete
The function removes the object with the specified name at the specified chart. There
are two variants of the function:
bool ObjectDelete( long chart_id, // chart ID
string object_name // object name
);
Parameters
chart_id
[in] Chart identifier.
object_name
[in] Name of object to be deleted.
Return Value
Returns true if the removal was successful, otherwise returns false. To read more about
the error call GetLastError().
Note
When the function is used with no chart ID specified, the function is supposed to be
working with the current chart to which it has a direct access. In this case, the return
value means the function execution result.
If the ID of a chart other than the current one is specified, the return value only
informs whether the command has been added to the queue of that chart. In this case
an asynchronous call is used, which means that the function does not wait for the
execution of the command that has been added to the queue of another chart. Instead,
it immediately returns control.
To check the result of command execution on a chart other than the current one, you
can use a function that checks the specified object property. However, you should keep
in mind that such functions are added to the end of the queue of that chart and wait
for the execution result, and can therefore be time consuming. This feature should be
taken into account when working with a large number of objects on a chart.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
int start()
{
int i;
long current_chart_id=ChartID();
//--- creates several objects of label type
for(i=0; i<300; i+=10)
{
string obj_name="label_object"+IntegerToString(i);
//--- creating label object (it does not have time/price coordinates)
if(ObjectCreate(obj_name,OBJ_LABEL,0,0,0))
{
PrintFormat("Object %s created.",obj_name);
//--- set random color
ObjectSetInteger(current_chart_id,obj_name,OBJPROP_COLOR,MathRand());
//--- set text property
ObjectSetString(current_chart_id,obj_name,OBJPROP_TEXT,StringFormat("Simple
//--- set distance property
ObjectSet(obj_name,OBJPROP_XDISTANCE,i);
ObjectSet(obj_name,OBJPROP_YDISTANCE,i);
//-- forced chart redraw
ChartRedraw(current_chart_id);
Sleep(10);
}
else
{
Print("Error: can't create label! code #",GetLastError());
return(0);
}
}
//--- sleep to see the objects created
Sleep(3000);
//--- delete all objects
int obj_total=ObjectsTotal();
PrintFormat("Total %d objects",obj_total);
for(i=obj_total-1;i>=0;i--)
{
string name=ObjectName(i);
PrintFormat("object %d: %s",i,name);
ObjectDelete(name);
}
return(0);
}
MQL4 Reference / Object Functions / ObjectsDeleteAll
ObjectsDeleteAll
Removes all objects from the specified chart, specified chart subwindow, of the
specified type.
int ObjectsDeleteAll( long chart_id, // chart ID
int sub_window=EMPTY, // window index
int object_type=EMPTY // object type
);
Removes all objects of the specified type from the specified chart subwindow.
int ObjectsDeleteAll(
int sub_window=EMPTY, // window index
int object_type=EMPTY // object type
);
Removes all objects of the specified type using prefix in object names.
int ObjectsDeleteAll(
long chart_id, // chart ID
const string prefix, // prefix in object name
int sub_window=EMPTY, // window index
int object_type=EMPTY // object type
);
Parameters
chart_id
[in] Chart identifier.
prefix
[in] Prefix in object names. All objects whose names start with this set of characters
will be removed from chart. You can specify prefix as 'name' or 'name*' both variants
will work the same. If an empty string is specified as the prefix, objects with all
possible names will be removed.
sub_window=EMPTY
[in] Number of the chart window. Must be greater or equal to -1 (-1 mean all
subwindows, 0 means the main chart window) and less than WindowsTotal().
object_type=EMPTY
[in] Type of the object. The value can be one of the values of the ENUM_OBJECT
enumeration. EMPTY (-1) means all types.
Return Value
Returns the number of deleted objects. To read more about the error call
GetLastError().
Note
Indexing of chart subwindows (if a chart has subwindows with indicators) starts with 1.
The index of the main chart window is always equal to 0. If a window has no index, or
its index is -1, objects will be deleted from the entire chart. If the value of the type
parameter is -1 or this parameter is not available, all objects from the specified
subwindow will be deleted.
When the function is used with no chart ID specified, the function is supposed to be
working with the current chart to which it has a direct access. In this case, the return
value means the function execution result.
If the ID of a chart other than the current one is specified, the return value only
informs whether the command has been added to the queue of that chart. In this case
an asynchronous call is used, which means that the function does not wait for the
execution of the command that has been added to the queue of another chart. Instead,
it immediately returns control.
To check the result of command execution on a chart other than the current one, you
can use a function that checks the specified object property. However, you should keep
in mind that such functions are added to the end of the queue of that chart and wait
for the execution result, and can therefore be time consuming. This feature should be
taken into account when working with a large number of objects on a chart.
Example:
ObjectsDeleteAll(2, OBJ_HLINE); // delete all horizontal lines from the 2nd subwind
ObjectsDeleteAll(2); // delete all objects from the 2nd subwindow
ObjectsDeleteAll(); // delete all objects from chart.
MQL4 Reference / Object Functions / ObjectFind
ObjectFind
The function searches for an object having the specified
name. There are two variants of the function:
int ObjectFind( long chart_id, // chart ID
string object_name // object name
);
Parameters
chart_id
[in] Chart identifier.
object_name
[in] The name of the object to find.
Return Value
If successful the function returns the number of the
subwindow (0 means the main window of the chart), in
which the object is found. If the object is not found, the
function returns a negative number. To read more about
the error call GetLastError().
Note
The chart sub-windows (if there are sub-windows with
indicators in the chart) are numbered starting from 1.
The chart main window always exists and has the 0
index.
When the function is used with no chart ID specified, the
function is supposed to be working with the current
chart to which it has a direct access.
If a chart ID is specified in the function call, a
synchronous call will be used to search for an object on
a chart different from the current one. The synchronous
call means that the function waits for the execution of
all commands that have been enqueued for this chart
prior to its call, that is why this function can be time
consuming. This feature should be taken into account
when working with a large number of objects on a chart.
Example:
if(ObjectFind(0,"line_object2")!=win_idx) return(0);
MQL4 Reference / Object Functions / ObjectGetTimeByValue
ObjectGetTimeByValue
The function returns the time value for the specified price value of the
specified object.
datetime ObjectGetTimeByValue( long chart_id, // chart ID
string object_name, // object name
double value, // price
int line_id=0 // line identifier
);
Parameters
chart_id
[in] Chart identifier.
object_name
[in] Name of the object.
value
[in] Price value.
line_id=0
[in] Line identifier.
Return Value
The time value for the specified price value of the specified object.
Note
When this function is used on the current chart, this chart is accessed
directly, while in order to receive the properties of an object on a
different chart, a synchronous call is used. The synchronous call means
that the function waits for the execution of all commands that have
been enqueued for this chart prior to its call, that is why this function
can be time consuming. This feature should be taken into account when
working with a large number of objects on a chart.
An object can have several values in one price coordinate, therefore it is
necessary to specify the line number. This function applies only to the
following objects:
Trendline (OBJ_TREND)
Trendline by angle (OBJ_TRENDBYANGLE)
Gann line (OBJ_GANNLINE)
Equidistant channel (OBJ_CHANNEL) - 2 lines
Linear regression channel (OBJ_REGRESSION) - 3 lines
Standard deviation channel (OBJ_STDDEVCHANNEL) - 3 lines
See also
Object Types
MQL4 Reference / Object Functions / ObjectGetValueByTime
ObjectGetValueByTime
The function returns the price value for the specified time value of the
specified object.
double ObjectGetValueByTime( long chart_id, // chart ID
string object_name, // object name
datetime time, // time
int line_id=0 // line ID
);
Parameters
chart_id
[in] Chart identifier.
object_name
[in] Name of the object.
time
[in] Time value.
line_id=0
[in] Line identifier.
Return Value
The price value for the specified time value of the specified object.
Note
When this function is used on the current chart, this chart is accessed
directly, while in order to receive the properties of an object on a
different chart, a synchronous call is used. The synchronous call means
that the function waits for the execution of all commands that have
been enqueued for this chart prior to its call, that is why this function
can be time consuming. This feature should be taken into account when
working with a large number of objects on a chart.
An object can have several values in one price coordinate, therefore it is
necessary to specify the line number. This function applies only to the
following objects:
Trendline (OBJ_TREND)
Trendline by angle (OBJ_TRENDBYANGLE)
Gann line (OBJ_GANNLINE)
Equidistant channel (OBJ_CHANNEL) - 2 lines
Linear regression channel (OBJ_REGRESSION) - 3 lines
Standard deviation channel (OBJ_STDDEVCHANNEL) - 3 lines
See also
Object Types
MQL4 Reference / Object Functions / ObjectMove
ObjectMove
The function changes coordinates of the specified anchor point of the
object at the specified chart. There are two variants of the function:
bool ObjectMove( string object_name, // object name
int point_index, // anchor point number
datetime time, // Time
double price // Price
);
Parameters
object_name
[in] Name of the object.
point_index
[in] Index of the anchor point. The number of anchor points depends on
the type of object.
time
[in] Time coordinate of the selected anchor point.
price
[in] Price coordinate of the selected anchor point.
Return Value
If successful, returns true, in case of failure returns false. To read more
about the error call GetLastError().
Note
The function moves an object coordinate in the chart. Objects can have
from one to three coordinates depending on their types. The object
coordinates are numbered starting from 0.
When the function is used with no chart ID specified, the function is
supposed to be working with the current chart to which it has a direct
access. In this case, the return value means the function execution
result.
If the ID of a chart other than the current one is specified, the return
value only informs whether the command has been added to the queue of
that chart. In this case an asynchronous call is used, which means that
the function does not wait for the execution of the command that has
been added to the queue of another chart. Instead, it immediately
returns control.
To check the result of command execution on a chart other than the
current one, you can use a function that checks the specified object
property. However, you should keep in mind that such functions are
added to the end of the queue of that chart and wait for the execution
result, and can therefore be time consuming. This feature should be
taken into account when working with a large number of objects on a
chart.
Example:
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
int start()
{
string obj_name="trend_line";
long current_chart_id=ChartID();
//---
datetime t1=Time[0];
double p1=Close[0];
//---
datetime t2=Time[1];
double p2=Close[1];
//--- creating trend line object
if(!ObjectCreate(obj_name,OBJ_TREND,0,t1,p1,t2,p2))
{
Print("Error: can't create trend line! code #",GetLastError());
return(0);
}
//--- set color to Red
ObjectSetInteger(current_chart_id,obj_name,OBJPROP_COLOR,clrRed);
//--- moving of the trend line
for(int i=1; i<200; i++)
{
t2=Time[i];
p2=Close[i];
//--- move the 2nd anchor point of the trend line
ObjectMove(obj_name,1,t2,p2);
//--- forced chart redraw
ChartRedraw(current_chart_id);
Sleep(100);
}
//--- sleep to see the object
Sleep(3000);
//--- delete object
ObjectDelete(obj_name);
return(0);
}
MQL4 Reference / Object Functions / ObjectsTotal
ObjectsTotal
The function returns the number of objects of the specified type in
the specified chart. There are two variants of the function:
int ObjectsTotal( long chart_id, // chart identifier
int sub_window=-1, // window index
int type=-1 // object type
);
Parameters
chart_id
[in] Chart identifier.
sub_window=-1
[in] Number of the chart subwindow. 0 means the main chart
window, -1 means all the subwindows of the chart, including the
main window.
type=-1
[in] Type of the object. The value can be one of the values of the
ENUM_OBJECT enumeration. EMPTY(-1) means all types.
Return Value
The number of objects.
Note
When this function is used on the current chart, this chart is
accessed directly, while in order to receive the properties of an
object on a different chart, a synchronous call is used. The
synchronous call means that the function waits for the execution of
the command added to the chart queue. If the queue already
contains other commands, the result will only be obtained after
their execution.
Example:
int obj_total=ObjectsTotal();
string name;
for(int i=0;i<obj_total;i++)
{
name = ObjectName(i);
Print(i," object - ",name);
}
MQL4 Reference / Object Functions / ObjectGetDouble
ObjectGetDouble
The function returns the value of the corresponding object property. The
object property must be of the double type. There are 2 variants of the
function.
1. Immediately returns the property value.
double ObjectGetDouble( long chart_id, // chart identifier
string object_name, // object name
int prop_id, // property identifier
int prop_modifier=0 // property modifier, if required
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
object_name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_DOUBLE enumeration.
prop_modifier
[in] Modifier of the specified property. For the first variant, the default
modifier value is equal to 0. Most properties do not require a modifier. It
denotes the number of the level in Fibonacci tools and in the graphical
object Andrew's pitchfork. The numeration of levels starts from zero.
double_var
[out] Variable of the double type that received the value of the requested
property.
Return Value
Value of the double type for the first calling variant.
For the second variant the function returns true, if this property is
maintained and the value has been placed into the double_var variable,
otherwise returns false. To read more about the error call GetLastError().
Note
When this function is used on the current chart, this chart is accessed
directly, while in order to receive the properties of an object on a different
chart, a synchronous call is used. The synchronous call means that the
function waits for the execution of all commands that have been enqueued
for this chart prior to its call, that is why this function can be time
consuming. This feature should be taken into account when working with a
large number of objects on a chart.
MQL4 Reference / Object Functions / ObjectGetInteger
ObjectGetInteger
The function returns the value of the corresponding object property. The
object property must be of the datetime, int, color, bool or char type. There
are 2 variants of the function.
1. Immediately returns the property value.
long ObjectGetInteger( long chart_id, // chart identifier
string object_name, // object name
int prop_id, // property identifier
int prop_modifier=0 // property modifier, if required
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
object_name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_INTEGER enumeration.
prop_modifier
[in] Modifier of the specified property. For the first variant, the default
modifier value is equal to 0. Most properties do not require a modifier. It
denotes the number of the level in Fibonacci tools and in the graphical
object Andrew's pitchfork. The numeration of levels starts from zero.
long_var
[out] Variable of the long type that receives the value of the requested
property.
Return Value
The long value for the first calling variant.
For the second variant the function returns true, if this property is
maintained and the value has been placed into the long_var variable,
otherwise returns false. To read more about the error call GetLastError().
Note
When this function is used on the current chart, this chart is accessed
directly, while in order to receive the properties of an object on a different
chart, a synchronous call is used. The synchronous call means that the
function waits for the execution of all commands that have been enqueued
for this chart prior to its call, that is why this function can be time
consuming. This feature should be taken into account when working with a
large number of objects on a chart.
MQL4 Reference / Object Functions / ObjectGetString
ObjectGetString
The function returns the value of the corresponding object property. The
object property must be of the string type. There are 2 variants of the
function.
1. Immediately returns the property value.
string ObjectGetString( long chart_id, // chart identifier
string object_name, // object name
int prop_id, // property identifier
int prop_modifier=0 // property modifier, if required
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
object_name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_STRING enumeration.
prop_modifier
[in] Modifier of the specified property. For the first variant, the default
modifier value is equal to 0. Most properties do not require a modifier. It
denotes the number of the level in Fibonacci tools and in the graphical
object Andrew's pitchfork. The numeration of levels starts from zero.
string_var
[out] Variable of the string type that receives the value of the requested
properties.
Return Value
String value for the first version of the call.
For the second version of the call returns true, if this property is maintained
and the value has been placed into the string_var variable, otherwise returns
false. To read more about the error call GetLastError().
Note
When this function is used on the current chart, this chart is accessed
directly, while in order to receive the properties of an object on a different
chart, a synchronous call is used. The synchronous call means that the
function waits for the execution of all commands that have been enqueued
for this chart prior to its call, that is why this function can be time
consuming. This feature should be taken into account when working with a
large number of objects on a chart.
MQL4 Reference / Object Functions / ObjectSetDouble
ObjectSetDouble
The function sets the value of the corresponding object property. The object property
must be of the double type. There are 2 variants of the function.
Setting property value, without modifier.
bool ObjectSetDouble( long chart_id, // chart identifier
string object_name, // object name
int prop_id, // property
double prop_value // value
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
object_name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_DOUBLE enumeration.
prop_modifier
[in] Modifier of the specified property. It denotes the number of the level in Fibonacci
tools and in the graphical object Andrew's pitchfork. The numeration of levels starts
from zero.
prop_value
[in] The value of the property.
Return Value
The function returns true only if the command to change properties of a graphical
object has been sent to a chart successfully. Otherwise it returns false. To read more
about the error call GetLastError().
Note
When this function is used on the current chart, this chart is accessed directly and the
result is returned immediately. In order to set object properties on a different chart, an
asynchronous call is used. The asynchronous call means that the function does not wait
for the execution of the command that has been added to the queue of another chart.
Instead, it immediately returns control.
To check the result of command execution on a chart other than the current one, you
can use a function that checks the specified object property. However, you should keep
in mind that such functions are added to the end of the queue of that chart and wait
for the execution result, and can therefore be time consuming. This feature should be
taken into account when working with a large number of objects on a chart.
Example of creating a Fibonacci object and adding a new level in it
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- auxiliary arrays
double high[],low[],price1,price2;
datetime time[],time1,time2;
//--- Copy the open prices - 100 latest bars are enough
int copied=CopyHigh(Symbol(),0,0,100,high);
if(copied<=0)
{
Print("Failed to copy the values of the High price series");
return;
}
//--- Copy the close price - 100 latest bars are enough
copied=CopyLow(Symbol(),0,0,100,low);
if(copied<=0)
{
Print("Failed to copy the values of the Low price series");
return;
}
//--- Copy the open time for the last 100 bars
copied=CopyTime(Symbol(),0,0,100,time);
if(copied<=0)
{
Print("Failed to copy the values of the price series of Time");
return;
}
//--- Organize access to the copied data as to timeseries - backwards
ArraySetAsSeries(high,true);
ArraySetAsSeries(low,true);
ArraySetAsSeries(time,true);
See also
Object Types, Object Properties
MQL4 Reference / Object Functions / ObjectSetInteger
ObjectSetInteger
The function sets the value of the corresponding object property. The object property
must be of the datetime, int, color, bool or char type. There are 2 variants of the
function.
Setting property value, without modifier:
bool ObjectSetInteger( long chart_id, // chart identifier
string object_name, // object name
int prop_id, // property
long prop_value // value
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
object_name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_INTEGER enumeration.
prop_modifier
[in] Modifier of the specified property. It denotes the number of the level in
Fibonacci tools and in the graphical object Andrew's pitchfork. The numeration of
levels starts from zero.
prop_value
[in] The value of the property.
Return Value
The function returns true only if the command to change properties of a graphical
object has been sent to a chart successfully. Otherwise it returns false. To read more
about the error call GetLastError().
Note
When this function is used on the current chart, this chart is accessed directly and the
result is returned immediately. In order to set object properties on a different chart, an
asynchronous call is used. The asynchronous call means that the function does not wait
for the execution of the command that has been added to the queue of another chart.
Instead, it immediately returns control.
To check the result of command execution on a chart other than the current one, you
can use a function that checks the specified object property. However, you should keep
in mind that such functions are added to the end of the queue of that chart and wait
for the execution result, and can therefore be time consuming. This feature should be
taken into account when working with a large number of objects on a chart.
An example of how to create a table of Web colors
//+------------------------------------------------------------------+
//| Table of Web Colors|
//| Copyright 2011, MetaQuotes Software Corp |
//| https://www.metaquotes.net |
//+------------------------------------------------------------------+
#define X_SIZE 140 // width of an edit object
#define Y_SIZE 33 // height of an edit object
//+------------------------------------------------------------------+
//| Array of web colors |
//+------------------------------------------------------------------+
color ExtClr[140]=
{
clrAliceBlue,clrAntiqueWhite,clrAqua,clrAquamarine,clrAzure,clrBeige,clrBisque,clr
clrBlue,clrBlueViolet,clrBrown,clrBurlyWood,clrCadetBlue,clrChartreuse,clrChocolat
clrCornsilk,clrCrimson,clrCyan,clrDarkBlue,clrDarkCyan,clrDarkGoldenrod,clrDarkGra
clrDarkMagenta,clrDarkOliveGreen,clrDarkOrange,clrDarkOrchid,clrDarkRed,clrDarkSal
clrDarkSlateBlue,clrDarkSlateGray,clrDarkTurquoise,clrDarkViolet,clrDeepPink,clrDe
clrDodgerBlue,clrFireBrick,clrFloralWhite,clrForestGreen,clrFuchsia,clrGainsboro,c
clrGoldenrod,clrGray,clrGreen,clrGreenYellow,clrHoneydew,clrHotPink,clrIndianRed,c
clrLavender,clrLavenderBlush,clrLawnGreen,clrLemonChiffon,clrLightBlue,clrLightCor
clrLightGoldenrod,clrLightGreen,clrLightGray,clrLightPink,clrLightSalmon,clrLightS
clrLightSlateGray,clrLightSteelBlue,clrLightYellow,clrLime,clrLimeGreen,clrLinen,c
clrMediumAquamarine,clrMediumBlue,clrMediumOrchid,clrMediumPurple,clrMediumSeaGree
clrMediumSpringGreen,clrMediumTurquoise,clrMediumVioletRed,clrMidnightBlue,clrMint
clrNavajoWhite,clrNavy,clrOldLace,clrOlive,clrOliveDrab,clrOrange,clrOrangeRed,clr
clrPaleGreen,clrPaleTurquoise,clrPaleVioletRed,clrPapayaWhip,clrPeachPuff,clrPeru,
clrPurple,clrRed,clrRosyBrown,clrRoyalBlue,clrSaddleBrown,clrSalmon,clrSandyBrown,
clrSienna,clrSilver,clrSkyBlue,clrSlateBlue,clrSlateGray,clrSnow,clrSpringGreen,cl
clrThistle,clrTomato,clrTurquoise,clrViolet,clrWheat,clrWhite,clrWhiteSmoke,clrYel
};
//+------------------------------------------------------------------+
//| Creating and initializing an edit object |
//+------------------------------------------------------------------+
void CreateColorBox(int x,int y,color c)
{
//--- generate a name for a new edit object
string name="ColorBox_"+(string)x+"_"+(string)y;
//--- create a new edit object
if(!ObjectCreate(0,name,OBJ_EDIT,0,0,0))
{
Print("Cannot create: '",name,"'");
return;
}
//--- set coordinates, width and height
ObjectSetInteger(0,name,OBJPROP_XDISTANCE,x*X_SIZE);
ObjectSetInteger(0,name,OBJPROP_YDISTANCE,y*Y_SIZE);
ObjectSetInteger(0,name,OBJPROP_XSIZE,X_SIZE);
ObjectSetInteger(0,name,OBJPROP_YSIZE,Y_SIZE);
//--- set text color
if(clrBlack==c) ObjectSetInteger(0,name,OBJPROP_COLOR,clrWhite);
else ObjectSetInteger(0,name,OBJPROP_COLOR,clrBlack);
//--- set background color
ObjectSetInteger(0,name,OBJPROP_BGCOLOR,c);
//--- set text
ObjectSetString(0,name,OBJPROP_TEXT,(string)c);
}
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- create 7x20 table of colored edit objects
for(uint i=0;i<140;i++)
CreateColorBox(i%7,i/7,ExtClr[i]);
}
See also
Object Types, Object Properties
MQL4 Reference / Object Functions / ObjectSetString
ObjectSetString
The function sets the value of the corresponding object property. The
object property must be of the string type. There are 2 variants of the
function.
Setting property value, without modifier:
bool ObjectSetString( long chart_id, // chart identifier
string object_name, // object name
int prop_id, // property
string prop_value // value
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
object_name
[in] Name of the object.
prop_id
[in] ID of the object property. The value can be one of the values of the
ENUM_OBJECT_PROPERTY_STRING enumeration.
prop_modifier
[in] Modifier of the specified property. It denotes the number of the
level in Fibonacci tools and in the graphical object Andrew's pitchfork.
The numeration of levels starts from zero.
prop_value
[in] The value of the property.
Return Value
The function returns true only if the command to change properties of a
graphical object has been sent to a chart successfully. Otherwise it
returns false. To read more about the error call GetLastError().
Note
When this function is used on the current chart, this chart is accessed
directly and the result is returned immediately. In order to set object
properties on a different chart, an asynchronous call is used. The
asynchronous call means that the function does not wait for the execution
of the command that has been added to the queue of another chart.
Instead, it immediately returns control.
To check the result of command execution on a chart other than the
current one, you can use a function that checks the specified object
property. However, you should keep in mind that such functions are added
to the end of the queue of that chart and wait for the execution result,
and can therefore be time consuming. This feature should be taken into
account when working with a large number of objects on a chart.
MQL4 Reference / Object Functions / TextSetFont
TextSetFont
The function sets the font for displaying the text using drawing methods and returns the
result of that operation. Arial font with the size -120 (12 pt) is used by default.
bool TextSetFont( const string name, // font name or path to font file
int size, // font size
uint flags=0, // combination of flags
int orientation=0 // text slope angle
);
Parameters
name
[in] Font name in the system or the name of the resource containing the font or the
path to font file on the disk.
size
[in] The font size that can be set using positive and negative values. In case of
positive values, the size of a displayed text does not depend on the operating system's
font size settings. In case of negative values, the value is set in tenths of a point and
the text size depends on the operating system settings ("standard scale" or "large
scale"). See the Note below for more information about the differences between the
modes.
flags=0
[in] Combination of flags describing font style.
orientation=0
[in] Text's horizontal inclination to X axis, the unit of measurement is 0.1 degrees. It
means that orientation=450 stands for inclination equal to 45
degrees.
Returned value
Returns true if the current font is successfully installed, otherwise false. Possible code
errors:
ERR_INVALID_PARAMETER(4003) - name presents NULL or "" (empty string),
ERR_INTERNAL_ERROR(4001) - operating system error (for example, an attempt to
create a non-existent font).
Note
If "::" is used in font name, the font is downloaded from EX4 resource. If name font
name is specified with an extension, the font is downloaded from the file, if the path
starts from "\" or "/", the file is searched relative to MQL4 directory. Otherwise, it is
searched relative to the path of EX4 file which called TextSetFont() function.
The font size is set using positive or negative values. This fact defines the dependence
of the text size from the operating system settings (size scale).
If the size is specified by a positive number, this size is transformed into physical
measurement units of a device (pixels) when changing a logical font into a physical
one, and this size corresponds to the height of the symbol glyphs picked from the
available fonts. This case is not recommended when the texts displayed by TextOut()
function and the ones displayed by OBJ_LABEL ("Label") graphical object are to be
used together on the chart.
If the size is specified by a negative number, this number is supposed to be set in
tenths of a logical point (-350 is equal to 35 logical points) and is divided by 10. An
obtained value is then transformed into physical measurement units of a device
(pixels) and corresponds to the absolute value of the height of a symbol picked from
the available fonts. Multiply the font size specified in the object properties by -10 to
make the size of a text on the screen similar to the one in OBJ_LABEL object.
The flags can be used as the combination of style flags with one of the flags specifying
the font width. Flag names are shown below.
Flags for specifying font style
Flag Description
FONT_ITALIC Italic
FONT_UNDERLINE Underline
FONT_STRIKEOUT Strikeout
Flags for specifying font width
Flag
FW_DONTCARE
FW_THIN
FW_EXTRALIGHT
FW_ULTRALIGHT
FW_LIGHT
FW_NORMAL
FW_REGULAR
FW_MEDIUM
FW_SEMIBOLD
FW_DEMIBOLD
FW_BOLD
FW_EXTRABOLD
FW_ULTRABOLD
FW_HEAVY
FW_BLACK
See also
Resources, ResourceCreate(), ResourceSave(), TextOut()
MQL4 Reference / Object Functions / TextOut
TextOut
The function displays a text in a custom array (buffer) and returns the result of that
operation. The array is designed to create the graphical resource.
bool TextOut( const string text, // displayed text
int x, // X coordinate
int y, // Y coordinate
uint anchor, // anchor type
uint &data[], // output buffer
uint width, // buffer width in pixels
uint height, // buffer height in pixels
uint color, // text color
ENUM_COLOR_FORMAT color_format // color format for output
);
Parameters
text
[in] Displayed text that will be written to the buffer. Only one-lined text is displayed.
x
[in] X coordinate of the anchor point of the displayed text.
y
[in] Y coordinate of the anchor point of the displayed text.
anchor
[in] The value out of the 9 pre-defined methods of the displayed text's anchor point
location. The value is set by a combination of two flags flags of horizontal and vertical
text align. Flag names are listed in the Note below.
data[]
[in] Buffer, in which text is displayed. The buffer is used to create the graphical
resource.
width
[in] Buffer width in pixels.
height
[in] Buffer height in pixels.
color
[in] Text color.
color_format
[in] Color format is set by ENUM_COLOR_FORMAT enumeration value.
Returned value
Returns true if successful, otherwise false.
Note
Anchor point specified by anchor is a combination of two flags of horizontal and
vertical text align. Horizontal text align flags:
TA_LEFT anchor point on the left side of the bounding box
TA_CENTER horizontal anchor point is located at the center of the bounding box
TA_RIGHT anchor point on the right side of the bounding box
Vertical text align flags:
TA_TOP anchor point at the upper side of the bounding box
TA_VCENTER vertical anchor point is located at the center of the bounding box
TA_BOTTOM anchor point at the lower side of the bounding box
Possible combinations of flags and specified anchor points are shown in the image.
Example:
#property strict
//--- width and height of the canvas (used for drawing)
#define IMG_WIDTH 200
#define IMG_HEIGHT 200
//--- display the parameter window before launching the script
#property script_show_inputs
//--- enable to set color format
input ENUM_COLOR_FORMAT clr_format=COLOR_FORMAT_XRGB_NOALPHA;
//--- drawing array (buffer)
uint ExtImg[IMG_WIDTH*IMG_HEIGHT];
//+------------------------------------------------------------------+
//| Script program start function |
//+------------------------------------------------------------------+
void OnStart()
{
//--- create OBJ_BITMAP_LABEL object for drawing
ObjectCreate(0,"CLOCK",OBJ_BITMAP_LABEL,0,0,0);
//--- specify the name of the graphical resource for writing in CLOCK object
ObjectSetString(0,"CLOCK",OBJPROP_BMPFILE,"::IMG");
//--- rotate clock hands in an infinite loop, till the script is stopped
while(!IsStopped())
{
//--- clear the clock drawing buffer array
ArrayFill(ExtImg,0,IMG_WIDTH*IMG_HEIGHT,0);
//--- set the font for drawing digits for the clock-face
TextSetFont("Arial",-200,FW_EXTRABOLD,0);
//--- draw the clock-face
for(int i=1;i<=12;i++)
{
//--- receive the size of the current hour on the clock-face
TextGetSize(string(i),w,h);
//--- calculate the coordinates of the current hour on the clock-face
a=-((i*300)%3600*M_PI)/1800.0;
x=IMG_WIDTH/2-int(sin(a)*80+0.5+w/2);
y=IMG_HEIGHT/2-int(cos(a)*80+0.5+h/2);
//--- output the hour on the clock-face to ExtImg[] buffer
TextOut(string(i),x,y,TA_LEFT|TA_TOP,ExtImg,IMG_WIDTH,IMG_HEIGHT,0xFFFFFFFF,
}
//--- now, specify the font for drawing the minute hand
TextSetFont("Arial",-200,FW_EXTRABOLD,-int(nm%3600));
//--- receive the size of the minute hand
TextGetSize("----->",w,h);
//--- calculate the coordinates of the minute hand on the clock-face
a=-(nm%3600*M_PI)/1800.0;
x=IMG_WIDTH/2-int(sin(a)*h/2+0.5);
y=IMG_HEIGHT/2-int(cos(a)*h/2+0.5);
//--- output of the minute hand to the clock-face in ExtImg[]buffer
TextOut("----->",x,y,TA_LEFT|TA_TOP,ExtImg,IMG_WIDTH,IMG_HEIGHT,0xFFFFFFFF,clr_
//--- now, set the font for drawing the minute hand
TextSetFont("Arial",-200,FW_EXTRABOLD,-int(nh/12%3600));
TextGetSize("==>",w,h);
//--- calculate the coordinates of the hour hand on the clock-face
a=-(nh/12%3600*M_PI)/1800.0;
x=IMG_WIDTH/2-int(sin(a)*h/2+0.5);
y=IMG_HEIGHT/2-int(cos(a)*h/2+0.5);
//--- output of the hour hand on the clock-face to ExtImg[] buffer
TextOut("==>",x,y,TA_LEFT|TA_TOP,ExtImg,IMG_WIDTH,IMG_HEIGHT,0xFFFFFFFF,clr_for
See also
Resources, ResourceCreate(), ResourceSave(), TextGetSize(), TextSetFont()
MQL4 Reference / Object Functions / TextGetSize
TextGetSize
The function returns the line width and height at the current
font settings.
bool TextGetSize( const string text, // text string
uint& width, // buffer width in pixels
uint& height // buffer height in pixels
);
Parameters
text
[in] String, for which length and width should be obtained.
width
[out] Input parameter for receiving width.
height
[out] Input parameter for receiving height.
Returned value
Returns true if successful, otherwise false. Possible code
errors:
ERR_INTERNAL_ERROR(4001) - operating system error.
See also
Resources, ResourceCreate(), ResourceSave(), TextSetFont(),
TextOut()
MQL4 Reference / Object Functions / ObjectDescription
ObjectDescription
Returns the object description.
string ObjectDescription( string object_name // object name
);
Parameters
object_name
[in] Object name.
Returned value
Object description. For objects of OBJ_TEXT and OBJ_LABEL types, the text drawn by
these objects will be returned. To get the detailed error information, one has to call
the GetLastError() function.
Example:
// writing the chart objects list to the file
int handle, total;
string obj_name,fname;
// file name
fname="objlist_"+Symbol();
handle=FileOpen(fname,FILE_CSV|FILE_WRITE);
if(handle!=false)
{
total=ObjectsTotal();
for(int i=-;i<total;i++)
{
obj_name=ObjectName(i);
FileWrite(handle,"Object "+obj_name+" description= "+ObjectDescription(obj_na
}
FileClose(handle);
}
See also
ObjectSetText()
MQL4 Reference / Object Functions / ObjectGet
ObjectGet
Returns the value of the specified object property.
double ObjectGet( string object_name, // object name
int index // object property
);
Parameters
object_name
[in] Object name.
index
[in] Object property index. It can be any of the Object
properties enumeration values.
Return Value
The value of the specified object property. To check errors,
one has to call the GetLastError() function.
Note
When this function is used on the current chart, this chart is
accessed directly, while in order to receive the properties of
an object on a different chart, a synchronous call is used. The
synchronous call means that the function waits for the
execution of all commands that have been enqueued for this
chart prior to its call, that is why this function can be time
consuming. This feature should be taken into account when
working with a large number of objects on a chart.
Example:
color oldColor=ObjectGet("hline12", OBJPROP_COLOR);
See also
ObjectSet()
MQL4 Reference / Object Functions / ObjectGetFiboDescription
ObjectGetFiboDescription
Returns the level description of a Fibonacci object.
string ObjectGetFiboDescription( string object_name, // object name
int index // level index
);
Parameters
object_name
[in] Fibonacci object name.
index
[in] Index of the Fibonacci level (0-31).
Return Value
The level description of a Fibonacci object. To get the detailed error
information, one has to call the GetLastError() function.
Note
The amount of Fibonacci levels depends on the object type. The maximum
amount of Fibonacci levels is 32.
When this function is used on the current chart, this chart is accessed directly,
while in order to receive the properties of an object on a different chart, a
synchronous call is used. The synchronous call means that the function waits
for the execution of all commands that have been enqueued for this chart
prior to its call, that is why this function can be time consuming. This feature
should be taken into account when working with a large number of objects on
a chart.
Example:
#include <stdlib.mqh>
...
string text;
for(int i=0;i<32;i++)
{
text=ObjectGetFiboDescription(MyObjectName,i);
//---- check if your object has less than 32 levels
if(GetLastError()!=ERR_NO_ERROR) break;
Print(MyObjectName," level index: ",i," description: ",text);
}
See also
ObjectSetFiboDescription()
MQL4 Reference / Object Functions / ObjectGetShiftByValue
ObjectGetShiftByValue
The function calculates and returns bar index (shift related to the
current bar) for the given price.
int ObjectGetShiftByValue( string object_name, // object name
double value // price
);
Parameters
object_name
[in] Object name.
value
[in] Price value.
Returned value
The function calculates and returns bar index (shift related to the
current bar) for the given price. The bar index is calculated by the first
and second coordinates using a linear equation. Applied to trendlines
and similar objects. To get the detailed error information, one has to
call the GetLastError() function.
Note
When this function is used on the current chart, this chart is accessed
directly, while in order to receive the properties of an object on a
different chart, a synchronous call is used. The synchronous call means
that the function waits for the execution of all commands that have
been enqueued for this chart prior to its call, that is why this function
can be time consuming. This feature should be taken into account when
working with a large number of objects on a chart.
Example:
int shift=ObjectGetShiftByValue("MyTrendLine#123", 1.34);
See also
ObjectGetValueByShift()
MQL4 Reference / Object Functions / ObjectGetValueByShift
ObjectGetValueByShift
The function calculates and returns the price value for the specified bar
(shift related to the current bar).
double ObjectGetValueByShift( string object_name, // object name
int shift // bar index
);
Parameters
object_name
[in] Object name.
shift
[in] Bar index.
Returned value
The function calculates and returns the price value for the specified bar
(shift related to the current bar). The price value is calculated by the first
and second coordinates using a linear equation. Applied to trendlines and
similar objects. To get the detailed error information, one has to call the
GetLastError() function.
Note
When this function is used on the current chart, this chart is accessed
directly, while in order to receive the properties of an object on a
different chart, a synchronous call is used. The synchronous call means
that the function waits for the execution of all commands that have been
enqueued for this chart prior to its call, therefor this function can be time
consuming. This feature should be taken into account when working with a
large number of objects on a chart.
Example:
double price=ObjectGetValueByShift("MyTrendLine#123", 11);
See also
ObjectGetShiftByValue()
MQL4 Reference / Object Functions / ObjectSet
ObjectSet
Changes the value of the specified object property.
bool ObjectSet( string object_name, // object name
int index, // property index
double value // value
);
Parameters
object_name
[in] Object name.
index
[in] Object property index. It can be any of object properties enumeration values.
value
[in] New value of the given property.
Returned value
If the function succeeds, the returned value will be true, otherwise it returns false. To
get the detailed error information, one has to call the GetLastError() function.
Example:
// moving the first coord to the last bar time
ObjectSet("MyTrend", OBJPROP_TIME1, Time[0]);
// setting the second fibo level
ObjectSet("MyFibo", OBJPROP_FIRSTLEVEL+1, 1.234);
// setting object visibility. object will be shown only on 15 minute and 1 hour cha
ObjectSet("MyObject", OBJPROP_TIMEFRAMES, OBJ_PERIOD_M15 | OBJ_PERIOD_H1);
See also
ObjectGet()
MQL4 Reference / Object Functions / ObjectSetFiboDescription
ObjectSetFiboDescription
The function sets a new description to a level of a Fibonacci object.
bool ObjectSetFiboDescription( string object_name, // object name
int index, // level index
string text // new description
);
Parameters
object_name
[in] Object name.
index
[in] Index of the Fibonacci level (0-31).
text
[in] New description of the level.
Returned value
The function returns true if successful, otherwise false. To get the detailed
error information, one has to call the GetLastError() function.
Note
The amount of Fibonacci levels depends on the object type. The maximum
amount of Fibonacci levels is 32.
Example:
ObjectSetFiboDescription("MyFiboObject",2,"Second line");
See also
ObjectGetFiboDescription()
MQL4 Reference / Object Functions / ObjectSetText
ObjectSetText
The function changes the object description.
bool ObjectSetText( string object_name, // object name
string text, // description
int font_size=0, // font size
string font_name=NULL, // font name
color text_color=clrNONE // text color
);
Parameters
object_name
[in] Object name.
text
[in] A text describing the object.
font_size=0
[in] Font size in points.
font_name=NULL
[in] Font name.
text_color=clrNONE
[in] Font color.
Returned value
Changes the object description. If the function succeeds, the returned
value will be true, otherwise false. To get the detailed error information,
one has to call the GetLastError() function.
Note
For objects of OBJ_TEXT and OBJ_LABEL, this description is shown as a text
line in the chart. Parameters of font_size, font_name and text_color are
used for objects of OBJ_TEXT and OBJ_LABEL only. For objects of other
types, these parameters are ignored.
Example:
ObjectSetText("text_object","Hello world!",10,"Times New Roman",Green);
See also
ObjectDescription()
MQL4 Reference / Object Functions / ObjectType
ObjectType
The function returns the object type value.
int ObjectType( string object_name // object name
);
Parameters
object_name
[in] Object name.
Returned value
The function returns the object type value. To get the
detailed error information, one has to call the
GetLastError() function.
Example:
if(ObjectType("line_object2")!=OBJ_HLINE) return(0);
See also
Object types
MQL4 Reference / Technical Indicators
What's new in MQL5
In MQL5, the number of built-in technical indicators has
been increased from 30 to 38. The indicators are
generated and managed using handles to avoid
unnecessary copies and reduce memory consumption. For
the same purpose, new functions for working with
indicators and timeseries are presented they allow
receiving indicator values in entire arrays rather than by a
single value.
New functions have been added for working with
indicators. Among them are ChartIndicatorAdd() and
IndicatorRelease() ones for dynamic adding and removal
of indicators when creating complex technical analysis
tools.
Function Action
ChartIndicatorAdd Add an indicator with the specified handle
into a specified chart window
IndicatorRelease Delete an indicator handle and release its
calculation part if unused
MQL4 Reference / Technical Indicators / iAC
iAC
Calculates the Bill Williams' Accelerator/Decelerator
oscillator and returns its value.
double iAC( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator
will be calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart
timeframe.
shift
[in] Index of the value taken from the indicator buffer
(shift relative to the current bar the given amount of
periods ago).
Returned value
Numerical value of the Bill Williams'
Accelerator/Decelerator oscillator.
Example:
double result=iAC(NULL,0,1);
MQL4 Reference / Technical Indicators / iAD
iAD
Calculates the Accumulation/Distribution indicator and
returns its value.
double iAD( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator
will be calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart
timeframe.
shift
[in] Index of the value taken from the indicator buffer
(shift relative to the current bar the given amount of
periods ago).
Returned value
Numerical value of the Accumulation/Distribution
indicator.
Example:
double result=iAD(NULL, 0, 1);
MQL4 Reference / Technical Indicators / iADX
iADX
Calculates the Average Directional Movement Index indicator and returns its value.
double iADX( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
int applied_price, // applied price
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL means
the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
period
[in] Averaging period for calculation.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE enumeration values.
mode
[in] Indicator line index. It can be any of the Indicators line identifiers enumeration
value. (0 - MODE_MAIN, 1 - MODE_PLUSDI, 2 - MODE_MINUSDI).
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Numerical value of the Average Directional Movement Index indicator.
Example:
if(iADX(NULL,0,14,PRICE_HIGH,MODE_MAIN,0)>iADX(NULL,0,14,PRICE_HIGH,MODE_PLUSDI,0))
MQL4 Reference / Technical Indicators / iAlligator
iAlligator
Calculates the Alligator indicator and returns its value.
double iAlligator( string symbol, // symbol
int timeframe, // timeframe
int jaw_period, // Jaw line averaging period
int jaw_shift, // Jaw line shift
int teeth_period, // Teeth line averaging period
int teeth_shift, // Teeth line shift
int lips_period, // Lips line averaging period
int lips_shift, // Lips line shift
int ma_method, // averaging method
int applied_price, // applied price
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL means
the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
jaw_period
[in] Blue line averaging period (Alligator's Jaw).
jaw_shift
[in] Blue line shift relative to the chart.
teeth_period
[in] Red line averaging period (Alligator's Teeth).
teeth_shift
[in] Red line shift relative to the chart.
lips_period
[in] Green line averaging period (Alligator's Lips).
lips_shift
[in] Green line shift relative to the chart.
ma_method
[in] MA method. It can be any of Moving Average methods. It can be any of
ENUM_MA_METHOD enumeration values.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE enumeration values.
mode
[in] Data source, identifier of the indicator line. It can be any of the following values:
MODE_GATORJAW - Gator Jaw (blue) balance line,
MODE_GATORTEETH - Gator Teeth (red) balance line,
MODE_GATORLIPS - Gator Lips (green) balance line.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Numerical value of the Alligator indicator.
Example:
double jaw_val=iAlligator(NULL,0,13,8,8,5,5,3,MODE_SMMA,PRICE_MEDIAN,MODE_GATORJAW,
MQL4 Reference / Technical Indicators / iAO
iAO
Calculates the Awesome oscillator and returns its value.
double iAO( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator
will be calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart
timeframe.
shift
[in] Index of the value taken from the indicator buffer
(shift relative to the current bar the given amount of
periods ago).
Returned value
Numerical value of the Awesome oscillator indicator.
Example:
double val=iAO(NULL,0,2);
MQL4 Reference / Technical Indicators / iATR
iATR
Calculates the Average True Range indicator and returns
its value.
double iATR( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator
will be calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart
timeframe.
period
[in] Averaging period.
shift
[in] Index of the value taken from the indicator buffer
(shift relative to the current bar the given amount of
periods ago).
Returned value
Numerical value of the Average True Range indicator.
Example:
if(iATR(NULL,0,12,0)>iATR(NULL,0,20,0)) return(0);
MQL4 Reference / Technical Indicators / iBearsPower
iBearsPower
Calculates the Bears Power indicator and returns its value.
double iBearsPower( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
int applied_price, // applied price
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be
calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration
values. 0 means the current chart timeframe.
period
[in] Averaging period.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE
enumeration values.
shift
[in] Index of the value taken from the indicator buffer (shift
relative to the current bar the given amount of periods ago).
Returned value
Numerical value of the Bears Power indicator.
Example:
double val=iBearsPower(NULL,0,13,PRICE_CLOSE,0);
MQL4 Reference / Technical Indicators / iBands
iBands
Calculates the Bollinger Bands® indicator and returns its value.
double iBands( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
double deviation, // standard deviations
int bands_shift, // bands shift
int applied_price, // applied price
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be
calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration
values. 0 means the current chart timeframe.
period
[in] Averaging period to calculate the main line.
deviation
[in] Number of standard deviations from the main line.
bands_shift
[in] The indicator shift relative to the chart.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE
enumeration values.
mode
[in] Indicator line index. It can be any of the Indicators line
identifiers enumeration value (0 - MODE_MAIN, 1 - MODE_UPPER, 2 -
MODE_LOWER).
shift
[in] Index of the value taken from the indicator buffer (shift
relative to the current bar the given amount of periods ago).
Returned value
Numerical value of the Bollinger Bands® indicator.
Example:
if(iBands(NULL,0,20,2,0,PRICE_LOW,MODE_LOWER,0)>Low[0]) return(0);
MQL4 Reference / Technical Indicators / iBandsOnArray
iBandsOnArray
Calculates the Bollinger Bands® indicator on data, stored in array, and returns
its value.
double iBandsOnArray( double array[], // array with data
int total, // number of elements
int period, // averaging period
double deviation, // deviation
int bands_shift, // bands shift
int mode, // line index
int shift // shift
);
Parameters
array[]
[in] Array with data.
total
[in] The number of items to be counted. 0 means the whole array.
period
[in] Averaging period to calculate the main line.
deviation
[in] Number of standard deviations from the main line.
bands_shift
[in] The indicator shift relative to the chart.
mode
[in] Indicator line index. It can be any of the Indicators line identifiers
enumeration value (0 - MODE_MAIN, 1 - MODE_UPPER, 2 - MODE_LOWER).
shift
[in] Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Returned value
Numerical value of the Bollinger Bands® indicator, calculated on data, stored
in array[].
Note
Unlike iBands(...), the iBandsOnArray() function does not take data by symbol
name, timeframe, the applied price. The price data must be previously
prepared. The indicator is calculated from left to right. To access to the array
elements as to a series array (i.e., from right to left), one has to use the
ArraySetAsSeries() function.
Example:
if(iBandsOnArray(ExtBuffer,total,2,0,0,MODE_LOWER,0)>Low[0]) return(0);
MQL4 Reference / Technical Indicators / iBullsPower
iBullsPower
Calculates the Bulls Power indicator and returns its value.
double iBullsPower( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
int applied_price, // applied price
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be
calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration
values. 0 means the current chart timeframe.
period
[in] Averaging period for calculation.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE
enumeration values.
shift
[in] Index of the value taken from the indicator buffer (shift
relative to the current bar the given amount of periods ago).
Returned value
Numerical value of the Bulls Power indicator.
Example:
double val=iBullsPower(NULL,0,13,PRICE_CLOSE,0);
MQL4 Reference / Technical Indicators / iCCI
iCCI
Calculates the Commodity Channel Index indicator and returns its value.
double iCCI( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
int applied_price, // applied price
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL means
the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
period
[in] Averaging period for calculation.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE enumeration values.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Numerical value of the Commodity Channel Index indicator.
Example:
if(iCCI(Symbol(),0,12,PRICE_TYPICAL,0)>iCCI(Symbol(),0,20,PRICE_TYPICAL,0)) return(
MQL4 Reference / Technical Indicators / iCCIOnArray
iCCIOnArray
Calculates the Commodity Channel Index indicator on data, stored in array, and returns
its value.
double iCCIOnArray( double array[], // array with data
int total, // number of elements
int period, // averaging period
int shift // shift
);
Parameters
array[]
[in] Array with data.
total
[in] The number of items to be counted. 0 means the whole array.
period
[in] Averaging period for calculation.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Numerical value of the Commodity Channel Index indicator, calculated on data, stored
in array[].
Note
Unlike iCCI(...), the iCCIOnArray() function does not take data by symbol name,
timeframe, the applied price. The price data must be previously prepared. The
indicator is calculated from left to right. To access to the array elements as to a series
array (i.e., from right to left), one has to use the ArraySetAsSeries() function.
Example:
if(iCCIOnArray(ExtBuffer,total,12,0)>iCCIOnArray(ExtBuffer,total,20,0)) return(1);
MQL4 Reference / Technical Indicators / iCustom
iCustom
Calculates the specified custom indicator and returns its value.
double iCustom( string symbol, // symbol
int timeframe, // timeframe
string name, // path/name of the custom indicator compiled progr
... // custom indicator input parameters (if necessary)
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL means
the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
name
[in] Custom indicator compiled program name, relative to the root indicators
directory (MQL4/Indicators/). If the indicator is located in subdirectory, for example,
in MQL4/Indicators/Examples, its name must be specified as
"Examples\\indicator_name" (double backslash "\\"must be specified as separator
instead of a single one).
...
[in] Custom indicator input-parameters, separated by commas.
The passed parameters and their order must correspond with the declaration order
and the type of extern variables of the custom indicator. If the values of input
parameters is not specified, the default values will be used.
mode
[in] Line index. Can be from 0 to 7 and must correspond with the index, specified in
call of the SetIndexBuffer() function.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Numerical value of the specified custom indicator. The custom indicator must be
compiled (*.EX4 file) and be in the terminal_directory\MQL4\Indicators\ directory.
Example:
double val=iCustom(NULL,0,"SampleInd",13,1,0);
MQL4 Reference / Technical Indicators / iDeMarker
iDeMarker
Calculates the DeMarker indicator and returns its value.
double iDeMarker( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will
be calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart
timeframe.
period
[in] Averaging period for calculation.
shift
[in] Index of the value taken from the indicator buffer
(shift relative to the current bar the given amount of
periods ago).
Returned value
Numerical value of the DeMarker indicator.
Example:
double val=iDeMarker(NULL,0,13,1);
MQL4 Reference / Technical Indicators / iEnvelopes
iEnvelopes
Calculates the Envelopes indicator and returns its value.
double iEnvelopes( string symbol, // symbol
int timeframe, // timeframe
int ma_period, // MA averaging period
int ma_method, // MA averaging method
int ma_shift, // moving average shift
int applied_price, // applied price
double deviation, // deviation (in percents)
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL
means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0
means the current chart timeframe.
ma_period
[in] Averaging period for calculation of the main line.
ma_method
[in] Moving Average method. It can be any of ENUM_MA_METHOD enumeration
values.
ma_shift
[in] MA shift. Indicator line offset relate to the chart by timeframe.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE enumeration values.
deviation
[in] Percent deviation from the main line.
mode
[in] Indicator line index. It can be any of Indicators line identifiers
enumeration value (0 - MODE_MAIN, 1 - MODE_UPPER, 2 - MODE_LOWER).
shift
[in] Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Returned value
Numerical value of the Envelopes indicator.
Example:
double val=iEnvelopes(NULL,0,13,MODE_SMA,10,PRICE_CLOSE,0.2,MODE_UPPER,0);
MQL4 Reference / Technical Indicators / iEnvelopesOnArray
iEnvelopesOnArray
Calculates the Envelopes indicator on data, stored in array, and returns its value.
double iEnvelopesOnArray( double array[], // array with data
int total, // number of elemements
int ma_period, // MA averaging period
int ma_method, // MA averaging method
int ma_shift, // MA shift
double deviation, // deviation (in percents)
int mode, // line index
int shift // shift
);
Parameters
array[]
[in] Array with data.
total
[in] The number of items to be counted. 0 means the whole array.
ma_period
[in] Averaging period for calculation of the main line.
ma_method
[in] Moving Average method. It can be any of ENUM_MA_METHOD enumeration
values.
ma_shift
[in] MA shift. Indicator line offset relate to the chart by timeframe.
deviation
[in] Percent deviation from the main line.
mode
[in] Indicator line index. It can be any of Indicators line identifiers enumeration
value (0 - MODE_MAIN, 1 - MODE_UPPER, 2 - MODE_LOWER).
shift
[in] Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Returned value
Numerical value of the Envelopes indicator, calculated on data, stored in array[].
Note
Unlike iEnvelopes(...), the iEnvelopesOnArray() function does not take data by
symbol name, timeframe, the applied price. The price data must be previously
prepared. The indicator is calculated from left to right. To access to the array
elements as to a series array (i.e., from right to left), one has to use the
ArraySetAsSeries() function.
Example:
double val=iEnvelopesOnArray(ExtBuffer,10,13,MODE_SMA,0,0.2,MODE_UPPER,0);
MQL4 Reference / Technical Indicators / iForce
iForce
Calculates the Force Index indicator and returns its value.
double iForce( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
int ma_method, // averaging method
int applied_price, // applied price
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be
calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart timeframe.
period
[in] Averaging period for calculation.
ma_method
[in] Moving Average method. It can be any of
ENUM_MA_METHOD enumeration values.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE
enumeration values.
shift
[in] Index of the value taken from the indicator buffer (shift
relative to the current bar the given amount of periods ago).
Returned value
Numerical value of the Force Index indicator.
Example:
double val=iForce(NULL,0,13,MODE_SMA,PRICE_CLOSE,0);
MQL4 Reference / Technical Indicators / iFractals
iFractals
Calculates the Fractals indicator and returns its value.
double iFractals( string symbol, // symbol
int timeframe, // timeframe
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be
calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart timeframe.
mode
[in] Indicator line index. It can be any of the Indicators line
identifiers enumeration value.
shift
[in] Index of the value taken from the indicator buffer (shift
relative to the current bar the given amount of periods ago).
Returned value
Numerical value of the Fractals indicator.
Example:
double val=iFractals(NULL,0,MODE_UPPER,3);
MQL4 Reference / Technical Indicators / iGator
iGator
Calculates the Gator oscillator and returns its value.
double iGator( string symbol, // symbol
int timeframe, // timeframe
int jaw_period, // Jaw line period
int jaw_shift, // Jaw line shift
int teeth_period, // Teeth line period
int teeth_shift, // Teeth line shift
int lips_period, // Lips line period
int lips_shift, // Lips line shift
int ma_method, // MA averaging method
int applied_price, // applied price
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL
means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0
means the current chart timeframe.
jaw_period
[in] Blue line averaging period (Alligator's Jaw).
jaw_shift
[in] Blue line shift relative to the chart.
teeth_period
[in] Red line averaging period (Alligator's Teeth).
teeth_shift
[in] Red line shift relative to the chart.
lips_period
[in] Green line averaging period (Alligator's Lips).
lips_shift
[in] Green line shift relative to the chart.
ma_method
[in] MA method. It can be any of Moving Average method enumeration value.
applied_price
[in] Applied price. It can be any of Applied price enumeration values.
mode
[in] Indicator line index. It can be any of Indicators line identifiers enumeration
value.
MODE_UPPER - upper histogram,
MODE_LOWER - lower histogram.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Returned value
Numerical value of the Gator oscillator.
Note
The oscillator displays the difference between the Alligator red and blue lines
(the upper histogram) and that between red and green lines (the lower
histogram).
Example:
double diff=iGator(NULL,0,13,8,8,5,5,3,MODE_SMMA,PRICE_MEDIAN,MODE_UPPER,1);
MQL4 Reference / Technical Indicators / iIchimoku
iIchimoku
Calculates the Ichimoku Kinko Hyo indicator and returns its value.
double iIchimoku( string symbol, // symbol
int timeframe, // timeframe
int tenkan_sen, // period of Tenkan-sen line
int kijun_sen, // period of Kijun-sen line
int senkou_span_b, // period of Senkou Span B line
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be
calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration
values. 0 means the current chart timeframe.
tenkan_sen
[in] Tenkan Sen averaging period.
kijun_sen
[in] Kijun Sen averaging period.
senkou_span_b
[in] Senkou SpanB averaging period.
mode
[in] Source of data. It can be one of the Ichimoku Kinko Hyo mode
enumeration (1 - MODE_TENKANSEN, 2 - MODE_KIJUNSEN, 3 -
MODE_SENKOUSPANA, 4 - MODE_SENKOUSPANB, 5 -
MODE_CHIKOUSPAN).
shift
[in] Index of the value taken from the indicator buffer (shift
relative to the current bar the given amount of periods ago).
Returned value
Numerical value of the Ichimoku Kinko Hyo indicator.
Example:
double tenkan_sen=iIchimoku(NULL,0,9,26,52,MODE_TENKANSEN,1);
MQL4 Reference / Technical Indicators / iBWMFI
iBWMFI
Calculates the Market Facilitation Index indicator and
returns its value.
double iBWMFI( string symbol, // symbol
int timeframe, // timeframe
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator
will be calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart
timeframe.
shift
[in] Index of the value taken from the indicator buffer
(shift relative to the current bar the given amount of
periods ago).
Returned value
Numerical value of the Market Facilitation Index
indicator.
Example:
double val=iBWMFI(NULL,10,0);
MQL4 Reference / Technical Indicators / iMomentum
iMomentum
Calculates the Momentum indicator and returns its value.
double iMomentum( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
int applied_price, // applied price
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL means
the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
period
[in] Averaging period (amount of bars) for calculation of price changes.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE enumeration values.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Numerical value of the Momentum indicator.
Example:
if(iMomentum(NULL,0,12,PRICE_CLOSE,0)>iMomentum(NULL,0,20,PRICE_CLOSE,0)) return(0)
MQL4 Reference / Technical Indicators / iMomentumOnArray
iMomentumOnArray
Calculates the Momentum indicator on data, stored in array, and returns its value.
double iMomentumOnArray( double array[], // array with data
int total, // number of elements
int period, // averaging period
int shift // shift
);
Parameters
array[]
[in] Array with data.
total
[in] The number of items to be counted. 0 means the whole array.
period
[in] Averaging period (amount of bars) for calculation of price changes.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Numerical value of the Momentum indicator, calculated on data, stored in array[].
Note
Unlike iMomentum(...), the iMomentumOnArray() function does not take data by
symbol name, timeframe, the applied price. The price data must be previously
prepared. The indicator is calculated from left to right. To access to the array elements
as to a series array (i.e., from right to left), one has to use the ArraySetAsSeries()
function.
Example:
if(iMomentumOnArray(mybuffer,100,12,0)>iMomentumOnArray(mybuffer,100,20,0)) return(
MQL4 Reference / Technical Indicators / iMFI
iMFI
Calculates the Money Flow Index indicator and returns its
value.
double iMFI( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator
will be calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart
timeframe.
period
[in] Period (amount of bars) for calculation of the
indicator.
shift
[in] Index of the value taken from the indicator buffer
(shift relative to the current bar the given amount of
periods ago).
Returned value
Numerical value of the Money Flow Index indicator.
Example:
if(iMFI(NULL,0,14,0)>iMFI(NULL,0,14,1)) return(0);
MQL4 Reference / Technical Indicators / iMA
iMA
Calculates the Moving Average indicator and returns its value.
double iMA( string symbol, // symbol
int timeframe, // timeframe
int ma_period, // MA averaging period
int ma_shift, // MA shift
int ma_method, // averaging method
int applied_price, // applied price
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be
calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration
values. 0 means the current chart timeframe.
ma_period
[in] Averaging period for calculation.
ma_shift
[in] MA shift. Indicators line offset relate to the chart by timeframe.
ma_method
[in] Moving Average method. It can be any of ENUM_MA_METHOD
enumeration values.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE
enumeration values.
shift
[in] Index of the value taken from the indicator buffer (shift relative
to the current bar the given amount of periods ago).
Returned value
Numerical value of the Moving Average indicator.
Example:
AlligatorJawsBuffer[i]=iMA(NULL,0,13,8,MODE_SMMA,PRICE_MEDIAN,i);
MQL4 Reference / Technical Indicators / iMAOnArray
iMAOnArray
Calculates the Moving Average indicator on data, stored in array, and returns
its value.
double iMAOnArray( double array[], // array with data
int total, // number of elements
int ma_period, // MA averaging period
int ma_shift, // MA shift
int ma_method, // MA averaging method
int shift // shift
);
Parameters
array[]
[in] Array with data.
total
[in] The number of items to be counted. 0 means the whole array.
ma_period
[in] Averaging period for calculation.
ma_shift
[in] MA shift. Indicators line offset relate to the chart by timeframe.
ma_method
[in] Moving Average method. It can be any of ENUM_MA_METHOD
enumeration values.
shift
[in] Index of the value taken from the indicator buffer (shift relative to
the current bar the given amount of periods ago).
Returned value
Numerical value of the Moving Average indicator, calculated on data,
stored in array[].
Note
Unlike iMA(...), the iMAOnArray() function does not take data by symbol
name, timeframe, the applied price. The price data must be previously
prepared. The indicator is calculated from left to right. To access to the
array elements as to a series array (i.e., from right to left), one has to use
the ArraySetAsSeries() function.
Example:
double macurrent=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,0);
double macurrentslow=iMAOnArray(ExtBuffer,0,10,0,MODE_LWMA,0);
double maprev=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,1);
double maprevslow=iMAOnArray(ExtBuffer,0,10,0,MODE_LWMA,1);
//----
if(maprev<maprevslow && macurrent>=macurrentslow)
Alert("crossing up");
MQL4 Reference / Technical Indicators / iOsMA
iOsMA
Calculates the Moving Average of Oscillator indicator and returns its value.
double iOsMA( string symbol, // symbol
int timeframe, // timeframe
int fast_ema_period, // Fast EMA period
int slow_ema_period, // Slow EMA period
int signal_period, // Signal line period
int applied_price, // applied price
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL means
the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
fast_ema_period
[in] Fast EMA averaging period.
slow_ema_period
[in] Slow EMA averaging period.
signal_period
[in] Signal line averaging period.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE enumeration values.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Numerical value of the Moving Average of Oscillator.
Example:
if(iOsMA(NULL,0,12,26,9,PRICE_OPEN,1)>iOsMA(NULL,0,12,26,9,PRICE_OPEN,0)) return(0)
MQL4 Reference / Technical Indicators / iMACD
iMACD
Calculates the Moving Averages Convergence/Divergence indicator and returns its value.
double iMACD( string symbol, // symbol
int timeframe, // timeframe
int fast_ema_period, // Fast EMA period
int slow_ema_period, // Slow EMA period
int signal_period, // Signal line period
int applied_price, // applied price
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL means
the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
fast_ema_period
[in] Fast EMA averaging period.
slow_ema_period
[in] Slow EMA averaging period.
signal_period
[in] Signal line averaging period.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE enumeration values.
mode
[in] Indicator line index. It can be one of the Indicators line identifiers enumeration
values (0-MODE_MAIN, 1-MODE_SIGNAL).
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Numerical value of the Moving Average of Oscillator indicator.
Note
In some systems it is called MACD Histogram and plotted as two lines. In MetaTrader 4
client terminal MACD is plotted as histogram.
Example:
if(iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0)>iMACD(NULL,0,12,26,9,PRICE_CLOSE,M
MQL4 Reference / Technical Indicators / iOBV
iOBV
Calculates the On Balance Volume indicator and returns its
value.
double iOBV( string symbol, // symbol
int timeframe, // timeframe
int applied_price, // applied price
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will
be calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart
timeframe.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE
enumeration values.
shift
[in] Index of the value taken from the indicator buffer
(shift relative to the current bar the given amount of
periods ago).
Returned value
Numerical value of the On Balance Volume indicator.
Example:
double val=iOBV(NULL,0,PRICE_CLOSE,1);
MQL4 Reference / Technical Indicators / iSAR
iSAR
Calculates the Parabolic Stop and Reverse system indicator and returns its value.
double iSAR( string symbol, // symbol
int timeframe, // timeframe
double step, // price increment step - acceleration factor
double maximum, // maximum value of step
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL
means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means
the current chart timeframe.
step
[in] The step of price increment, usually 0.02.
maximum
[in] The maximum step, usually 0.2.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Returned value
Numerical value of the Parabolic Stop and Reverse system indicator.
Example:
if(iSAR(NULL,0,0.02,0.2,0)>Close[0]) return(0);
MQL4 Reference / Technical Indicators / iRSI
iRSI
Calculates the Relative Strength Index indicator and returns its value.
double iRSI( string symbol, // symbol
int timeframe, // timeframe
int period, // period
int applied_price, // applied price
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL
means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0
means the current chart timeframe.
period
[in] Averaging period for calculation.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE enumeration values.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Returned value
Numerical value of the Relative Strength Index indicator.
Example:
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>iRSI(NULL,0,14,PRICE_CLOSE,1)) return(0);
MQL4 Reference / Technical Indicators / iRSIOnArray
iRSIOnArray
Calculates the Relative Strength Index indicator on data, stored in array, and
returns its value.
double iRSIOnArray( double array[], // array with data
int total, // number of elements
int period, // averaging period
int shift // shift
);
Parameters
array[]
[in] Array with data.
total
[in] The number of items to be counted. 0 means the whole array.
period
[in] Averaging period for calculation.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Returned value
Numerical value of the Relative Strength Index indicator, calculated on data,
stored in array[].
Note
Unlike iRSI(...), the iRSIOnArray() does not take data by symbol name, timeframe,
the applied price. The price data must be previously prepared. The indicator is
calculated from left to right. To access to the array elements as to a series array
(i.e., from right to left), one has to use the ArraySetAsSeries() function.
Example:
if(iRSIOnArray(ExtBuffer,1000,14,0)>iRSI(NULL,0,14,PRICE_CLOSE,1)) return(0);
MQL4 Reference / Technical Indicators / iRVI
iRVI
Calculates the Relative Vigor Index indicator and returns its
value.
double iRVI( string symbol, // symbol
int timeframe, // timeframe
int period, // averaging period
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will
be calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart
timeframe.
period
[in] Averaging period for calculation.
mode
[in] Indicator line index. It can be any of Indicators line
identifiers enumeration value.
shift
[in] Index of the value taken from the indicator buffer
(shift relative to the current bar the given amount of
periods ago).
Returned value
Numerical value of the Relative Vigor Index indicator.
Example:
double val=iRVI(NULL,0,10,MODE_MAIN,0);
MQL4 Reference / Technical Indicators / iStdDev
iStdDev
Calculates the Standard Deviation indicator and returns its
value.
double iStdDev( string symbol, // symbol
int timeframe, // timeframe
int ma_period, // MA averaging period
int ma_shift, // MA shift
int ma_method, // MA averaging method
int applied_price, // applied price
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be
calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart timeframe.
ma_period
[in] Moving Average period.
ma_shift
[in] Moving Average shift.
ma_method
[in] Moving Average method. It can be any of
ENUM_MA_METHOD enumeration values.
applied_price
[in] Applied price. It can be any of ENUM_APPLIED_PRICE
enumeration values.
shift
[in] Index of the value taken from the indicator buffer (shift
relative to the current bar the given amount of periods ago).
Returned value
Numerical value of the Standard Deviation indicator.
Example:
double val=iStdDev(NULL,0,10,0,MODE_EMA,PRICE_CLOSE,0);
MQL4 Reference / Technical Indicators / iStdDevOnArray
iStdDevOnArray
Calculates the Standard Deviation indicator on data, stored in array, and returns
its value.
double iStdDevOnArray( double array[], // array with data
int total, // number of elements
int ma_period, // MA averaging period
int ma_shift, // MA shift
int ma_method, // MA averaging method
int shift // shift
);
Parameters
array[]
[in] Array with data.
total
[in] The number of items to be counted. 0 means the whole array.
ma_period
[in] Moving Average period.
ma_shift
[in] Moving Average shift.
ma_method
[in] Moving Average method. It can be any of ENUM_MA_METHOD enumeration
values.
shift
[in] Index of the value taken from the indicator buffer (shift relative to the
current bar the given amount of periods ago).
Returned value
Numerical value of the Standard Deviation indicator, calculated on data, stored
in array[].
Note
Unlike iStdDev(...), the iStdDevOnArray() does not take data by symbol name,
timeframe, the applied price. The price data must be previously prepared. The
indicator is calculated from left to right. To access to the array elements as to
a series array (i.e., from right to left), one has to use the ArraySetAsSeries()
function.
Example:
double val=iStdDevOnArray(ExtBuffer,100,10,0,MODE_EMA,0);
MQL4 Reference / Technical Indicators / iStochastic
iStochastic
Calculates the Stochastic Oscillator and returns its value.
double iStochastic( string symbol, // symbol
int timeframe, // timeframe
int Kperiod, // K line period
int Dperiod, // D line period
int slowing, // slowing
int method, // averaging method
int price_field, // price (Low/High or Close/Close)
int mode, // line index
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will be calculated. NULL means
the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES enumeration values. 0 means the
current chart timeframe.
Kperiod
[in] Period of the %K line.
Dperiod
[in] Period of the %D line.
slowing
[in] Slowing value.
method
[in] Moving Average method. It can be any of ENUM_MA_METHOD enumeration values.
price_field
[in] Price field parameter. Can be one of this values: 0 - Low/High or 1 - Close/Close.
mode
[in] Indicator line index. It can be any of the Indicators line identifiers enumeration
value (0 - MODE_MAIN, 1 - MODE_SIGNAL).
shift
[in] Index of the value taken from the indicator buffer (shift relative to the current
bar the given amount of periods ago).
Returned value
Numerical value of the Stochastic Oscillator.
Example:
if(iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,0)>iStochastic(NULL,0,5,3,3,MODE_S
MQL4 Reference / Technical Indicators / iWPR
iWPR
Calculates the Larry Williams' Percent Range and returns its
value.
double iWPR( string symbol, // symbol
int timeframe, // timeframe
int period, // period
int shift // shift
);
Parameters
symbol
[in] Symbol name on the data of which the indicator will
be calculated. NULL means the current symbol.
timeframe
[in] Timeframe. It can be any of ENUM_TIMEFRAMES
enumeration values. 0 means the current chart
timeframe.
period
[in] Averaging period for calculation.
shift
[in] Index of the value taken from the indicator buffer
(shift relative to the current bar the given amount of
periods ago).
Returned value
Numerical value of the Larry Williams' Percent Range
indicator.
Example:
if(iWPR(NULL,0,14,0)>iWPR(NULL,0,14,1)) return(0);
MQL4 Reference / Working with Events
Event Functions
This group contains functions for working with custom
events and timer events. Besides this group, there are
special functions for handling predefined events.
Function Action
EventSetMillisecondTimer Launches event generator of the
high-resolution timer with a period
less than 1 second for the current
chart
EventSetTimer Starts the timer event generator
with the specified periodicity for
the current chart
EventKillTimer Stops the generation of events by
the timer in the current chart
EventChartCustom Generates a custom event for the
specified chart
See also
Types of Chart Events
MQL4 Reference / Working with Events / EventSetMillisecondTimer
EventSetMillisecondTimer
The function indicates to the client terminal that timer events should be generated at
intervals less than one second for this Expert Advisor or indicator.
bool EventSetMillisecondTimer( int milliseconds // number of milliseconds
);
Parameters
milliseconds
[in] Number of milliseconds defining the frequency of timer events.
Returned value
In case of successful execution, returns true, otherwise - false. To receive an error
code, GetLastError() function should be called.
Note
This feature is designed for the cases when high-resolution timer is required. In other
words, timer events should be received more frequently than once per second. If a
conventional timer with the period of several seconds is enough for you, use
EventSetTimer().
Usually, this function should be called from OnInit() function or in class constructor. To
handle events coming from the timer, an Expert Advisor or an indicator should have
OnTimer() function.
Each Expert Advisor and each indicator work with its own timer receiving events solely
from this timer. During mql4 application shutdown, the timer is forcibly destroyed in
case it has been created but has not been disabled by EventKillTimer() function.
Only one timer can be launched for each program. Each mql4 application and chart
have their own queue of events where all newly arrived events are placed. If the
queue already contains Timer event or this event is in the processing stage, then the
new Timer event is not added to mql4 application queue.
MQL4 Reference / Working with Events / EventSetTimer
EventSetTimer
The function indicates to the client terminal, that for this
indicator or Expert Advisor, events from the timer must be
generated with the specified periodicity.
bool EventSetTimer( int seconds // number of seconds
);
Parameters
seconds
[in] Number of seconds that determine the frequency of the
timer event occurrence.
Return Value
In case of success returns true, otherwise false. In order to get
an error code, the GetLastError() function should be called.
Note
Normally, this function must be called from the OnInit() function
or from a class constructor. In order to handle events coming
from the timer, the Expert Advisor must have the OnTimer()
function.
Every Expert Advisor, as well as every indicator works with its
own timer and receives events only from it. As soon as a mql4
program stops operating, the timer is destroyed forcibly if it was
created but hasn't been disabled by the EventKillTimer()
function.
For each program no more than one timer can be run. Each mql4
program and each chart has its own queue of events, in which
all the newly received events are placed. If the Timer event is
present in the queue or is being processed, the new Timer event
will not be placed in the queue of the mql4 program.
MQL4 Reference / Working with Events / EventKillTimer
EventKillTimer
Specifies the client terminal that is necessary to stop the
generation of events from Timer.
void EventKillTimer();
Return Value
No return value.
Note
Typically, this function must be called from a function
OnDeinit(), if the EventSetTimer() function has been
called from OnInit(). This function can also be called
form the class destructor, if the EventSetTimer()
function has been called in the constructor of this class.
Every Expert Advisor, as well as every indicator works
with its own timer and receives events only from it. As
soon as a mql4 program stops operating, the timer is
destroyed forcibly if it was created but hasn't been
disabled by the EventKillTimer() function.
MQL4 Reference / Working with Events / EventChartCustom
EventChartCustom
The function generates a custom event for the specified chart.
bool EventChartCustom( long chart_id, // identifier of the event rec
ushort custom_event_id, // event identifier
long lparam, // parameter of type long
double dparam, // parameter of type double
string sparam // string parameter of the event
);
Parameters
chart_id
[in] Chart identifier. 0 means the current chart.
custom_event_id
[in] ID of the user events. This identifier is automatically added to the value
CHARTEVENT_CUSTOM and converted to the integer type.
lparam
[in] Event parameter of the long type passed to the OnChartEvent function.
dparam
[in] Event parameter of the double type passed to the OnChartEvent function.
sparam
[in] Event parameter of the string type passed to the OnChartEvent function. If the
string is longer than 63 characters, it is truncated.
Return Value
Returns true if a custom event has been successfully placed in the events queue of the
chart that receives the events. In case of failure, it returns false. Use GetLastError() to
get an error code.
Note
An Expert Advisor or indicator attached to the specified chart handles the event using
the function OnChartEvent(int event_id, long& lparam, double& dparam, string&
sparam).
For each type of event, the input parameters of the OnChartEvent() function have
definite values that are required for the processing of this event. The events and values
passed through this parameters are listed in the below table.
Event Value of the id parameter Value of the lparam Value
parameter dpara
Event of a keystroke CHARTEVENT_KEYDOWN code of a pressed Repea
key numb
the
repea
of the
down
Event Value of the id parameter Value of the lparam Value
parameter dpara
Mouse event (if property CHARTEVENT_MOUSE_MOVE the X coordinate the Y
CHART_EVENT_MOUSE_MOVE=true is
set for the chart)
Example:
//+------------------------------------------------------------------+
//| ButtonClickExpert.mq5 |
//| Copyright 2009, MetaQuotes Software Corp. |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "2009, MetaQuotes Software Corp."
#property link "https://www.mql5.com"
#property version "1.00"
string buttonID="Button";
string labelID="Info";
int broadcastEventID=5000;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Create a button to send custom events
ObjectCreate(0,buttonID,OBJ_BUTTON,0,100,100);
ObjectSetInteger(0,buttonID,OBJPROP_COLOR,clrWhite);
ObjectSetInteger(0,buttonID,OBJPROP_BGCOLOR,clrGray);
ObjectSetInteger(0,buttonID,OBJPROP_XDISTANCE,100);
ObjectSetInteger(0,buttonID,OBJPROP_YDISTANCE,100);
ObjectSetInteger(0,buttonID,OBJPROP_XSIZE,200);
ObjectSetInteger(0,buttonID,OBJPROP_YSIZE,50);
ObjectSetString(0,buttonID,OBJPROP_FONT,"Arial");
ObjectSetString(0,buttonID,OBJPROP_TEXT,"Button");
ObjectSetInteger(0,buttonID,OBJPROP_FONTSIZE,10);
ObjectSetInteger(0,buttonID,OBJPROP_SELECTABLE,0);
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
ObjectDelete(0,buttonID);
ObjectDelete(0,labelID);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
}
//+------------------------------------------------------------------+
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
//--- Check the event by pressing a mouse button
if(id==CHARTEVENT_OBJECT_CLICK)
{
string clickedChartObject=sparam;
//--- If you click on the object with the name buttonID
if(clickedChartObject==buttonID)
{
//--- State of the button - pressed or not
bool selected=ObjectGetInteger(0,buttonID,OBJPROP_STATE);
//--- log a debug message
Print("Button pressed = ",selected);
int customEventID; // Number of the custom event to send
string message; // Message to be sent in the event
//--- If the button is pressed
if(selected)
{
message="Button pressed";
customEventID=CHARTEVENT_CUSTOM+1;
}
else // Button is not pressed
{
message="Button in not pressed";
customEventID=CHARTEVENT_CUSTOM+999;
}
//--- Send a custom event "our" chart
EventChartCustom(0,customEventID-CHARTEVENT_CUSTOM,0,0,message);
///--- Send a message to all open charts
BroadcastEvent(ChartID(),0,"Broadcast Message");
//--- Debug message
Print("Sent an event with ID = ",customEventID);
}
ChartRedraw();// Forced redraw all chart objects
}
See also
Events of the client terminal, Event handler functions
MQL4 Reference / Obsolete functions
Obsolete functions
In further development of MQL4, some functions were
renamed and moved from one group to another in order
to systematize them better.
The old function names are not highlighted or linked to
the MetaEditor key names dictionary. The old function
names can be used since the compiler will accept them in
a proper way. However, we strongly recommend to use
the new names.
Old name New Name
BarsPerWindow WindowBarsPerChart
ClientTerminalName TerminalName
CurTime TimeCurrent
CompanyName TerminalCompany
FirstVisibleBar WindowFirstVisibleBar
Highest iHighest
HistoryTotal OrdersHistoryTotal
LocalTime TimeLocal
Lowest iLowest
ObjectsRedraw WindowRedraw
PriceOnDropped WindowPriceOnDropped
ScreenShot WindowScreenShot
ServerAddress AccountServer
Old name New Name
TimeOnDropped WindowTimeOnDropped
MQL4 Reference / List of MQL4 Functions