Date post: | 02-Jun-2018 |
Category: |
Documents |
Upload: | lacramioara-georgescu |
View: | 236 times |
Download: | 2 times |
of 18
8/10/2019 2. Simple Expert Advisor - MQ4
1/18
Simple Expert Advisor
This section dwells on the principles of creating a simple trading Expert Advisor.
Problem 29. Create a trading Expert Advisor.
Preliminary Arguments
Before starting to program a trading Expert Advisor, it is necessar to define general
principles of a f!t!re program. There are no strict program creating r!les. "owever, once
having created a program, a programmer !s!all contin!es to improve it. To be able to easil!nderstand the program in f!t!re, it m!st be created in accordance with a well#tho!ght and
eas#to#!nderstand scheme $it is especiall important if a program will be f!rther improved b
another programmer%. The most convenient program is the one that consists of f!nctional
bloc&s, each of which is responsible for its part of calc!lations. To create an algorithm of a
trading Expert Advisor, let's anal(e what an operating program sho!ld do.
)ne of the most important data in the formation of trade orders is the information abo!t
orders that alread exist in a client terminal. *ome of trading strategies allow onl one
!nidirectional order. +enerall, if a trading strateg allows, several orders can be open in a
terminal at the same time, tho!gh their n!mber sho!ld be reasonabl limited. hen !sing an
strateg, trade decisions sho!ld be made ta&ing into acco!nt the c!rrent sit!ation. Before a
trade decision is made in a program, it is necessar to &now what trading orders have alread
been opened or placed. -irst of all a program m!st contain a bloc& of orders acco!nting which
is among the first to be exec!ted.
!ring an EA exec!tion trading decisions sho!ld be made, the implementation of which leads
to the exec!tion of trade operations. Code part responsible for trade orders formation is better
written in a separate bloc&. An Expert Advisor can form a trade re/!est to open a new pending
or mar&et order, close or modif an of existing orders or perform no actions at all. An EA
m!st also calc!late order prices depending on a !ser's desire.
Trade decisions sho!ld be made in a program on the bases of trade criteria. The s!ccess of the
whole program depends on the correctness of detecting trade criteria in the program. hen
calc!lating trade criteria a program can $and m!st% ta&e into acco!nt all information that can
be !sef!l. -or example, an Expert Advisor can anal(e combination of technical indicator
val!es, time of important news releases, c!rrent time, val!es of some price levels, etc. -or
convenience, the program part responsible for the calc!lation of trading criteria sho!ld be
written in a separate bloc&.
A trading Expert Advisor m!st necessaril contain error processing bloc&. Anal(ing errors
that ma occ!r in the exec!tion of trade operation allows, on the one side, to repeat a trade
re/!est and, on the other hand, to inform a !ser abo!t a possible conflict sit!ation.
8/10/2019 2. Simple Expert Advisor - MQ4
2/18
Structure of a Simple Expert Advisor
Below is a str!ct!ral scheme of a simple Expert Advisor constr!cted on the basis of several
f!nctional bloc&s, in each bloc& a certain detached part of calc!lations.
-ig. 019. *tr!ct!ral scheme of a simple Expert Advisor.
)n the following EA development stage there is no program code et. At the same time the
algorithm of a program is to a great extent formed. "ow the EA b!ilt on the bases of the
offered scheme will operate can be easil !nderstood simpl loo&ing on the scheme and
orienting !pon bloc& names and relations arras $control passing% between them.
After program start control is passed to the bloc& of preliminar processing. n this bloc&some general parameters can be anal(ed. -or example, if there are not eno!gh bars in a
8/10/2019 2. Simple Expert Advisor - MQ4
3/18
window $bars necessar for calc!lating parameters of technical indicators%, an EA will not be
able to operate ade/!atel. n s!ch a case an EA m!st terminate operation preliminaril
informing a !ser abo!t it and reporting abo!t the reason of termination. f there are no
contraindicatons of a general character, control is passed to order acco!nting bloc&.
n the bloc& of acco!nting orders the n!mber and /!alit of orders existing in a client terminalfor a sec!rit $to the window of which the EA is attached% is detected. n this bloc& orders of
other sec!rities m!st be eliminated. f a programmed trading strateg re/!ires !sing onl
mar&et orders $and does not !se pending orders% the fact of presence of pending orders m!st
be detected. f a strateg admits onl one mar&et order and there are act!all several orders,
this fact sho!ld also be &nown. The tas& of the order acco!nting bloc& $in this scheme% is in
defining whether the c!rrent trading sit!ation corresponds with an expected one, i.e. that in
which the EA can ade/!atel operate. f the sit!ation corresponds, control m!st be passed to
the next bloc& to contin!e the EA's operation3 if not, the EA's operation m!st be terminated
and this fact m!st be reported to a !ser.
f there are no orders in the terminal or the n!mber and /!alit of existing orders correspondsto what was expected, control is passed to the bloc& of defining trading criteria. n this bloc&
all criteria necessar for ma&ing trade decisions are calc!lated, namel criteria for opening,
closing and modifing orders. -!rther control is passed to the bloc& of closing orders.
t is eas to !nderstand wh in the offered scheme the bloc& of closing orders is exec!ted
earlier than the bloc& of opening orders. t is alwas more reasonable to process first existing
orders $close or modif% and onl after that to open new orders. +enerall, it is correct to be
g!ided b the desire to have as little orders as possible. !ring the exec!tion of this bloc& all
orders, for which the closing criterion has been activated, m!st be closed.
After all necessar orders has been closed, control is passed to a bloc& of new orders si(e
calc!lation. There are a lot of algorithms for calc!lating an order vol!me. The simplest of
them is !sing a constant, fixed lot si(e. t is convenient to !se this algorithm in a program for
testing strategies. 4ore pop!lar method of defining an order si(e is setting the n!mber of lots
depending on the amo!nt of free margin, for example 51#617 of it. f free margin is not
eno!gh, the program terminates its operation having informed a !ser abo!t the reason.
After the n!mber of lots for opening new orders is defined, control is passed to order opening
bloc&. f an of criteria calc!lated earlier points to the necessit of opening an order of a
certain tpe, a trade re/!est to open an order is formed in this bloc&.
There is also error anal(ing bloc& in an Expert Advisor. f an trade operation failed, control
$onl in this case% is passed to the error processing bloc&. f an error ret!rned b a server or
client terminal is not cr!cial, one more attempt is made to perform a trade operation. f a
cr!cial error is ret!rned $for example, an acco!nt is bloc&ed%, an EA m!st terminate its
operation. 8emember, in 4:6 there is no possibilit of program terminating an EA's
operation in a sec!rit window $as distinct from scripts, see *pecial -!nctions%. hat can be
done in a program wa is the termination of start$%. At a new start of the f!nction start$% on a
new tic& the val!e of a certain variable#flag prohibiting trading $in this case enabled as a
res!lt of a critical error% can be anal(ed and control can be passed for the termination of the
special f!nction operation3 th!s formation of new trade re/!est is not permitted. n the offered
scheme the flag val!e is anal(ed in the bloc& of preliminar processing.
http://book.mql4.com/programm/specialhttp://book.mql4.com/programm/special8/10/2019 2. Simple Expert Advisor - MQ4
4/18
Trading Strategy
4ar&et prices are constantl moving. 4ar&et state at an moment of time can be conditionall
characteri(ed either as a trend # strong !nidirectional price change $rise or fall%, or as a flat #
lateral price movement with wea& deviations from a certain average. These mar&et
characteristics are conditional, beca!se there are no clear criteria, according to which trend or
flat can be identified. -or example, long lateral movements with strong deviations that can be
traced neither to a flat nor to a trend. +enerall it is ass!med that the mar&et is mainl in the
state of lateral movement and trends !s!all ta&e place 0;#217 of time.
-ig. 001. -lat and trend in the mar&et.
All trading strategies also can be conventionall divided into two main gro!ps. The first gro!p
contains flat#oriented strategies. The main idea of s!ch strategies is that after an evident
deviation price m!st ret!rn to the previo!s position, that's wh orders are opened in the
direction contrar to the last price movement. The second gro!p strategies are trend strategies,
when orders are opened in the same direction as the salt price movement. There are more
complicated $combined% strategies. *!ch strategies ta&e into acco!nt man different factors
that characteri(e mar&et3 as a res!lt trading can be exec!ted both on flat and trend. t is nothard to implement trading according to this or that strateg technicall # 4:6 contains all
necessar means for it. The main wor& in the creation of once own strateg consists in the
search of trading criteria.
Trading Criteria
n this example we will tr to constr!ct a trend Expert Advisor, i.e. the one that will open
orders in the price movement direction. *o, we need to find among vario!s technical
indicators those that detect a trend beginning. )ne of the simplest methods of searching
trading criteria is based on the analsis of the combination of 4As with different averaging
8/10/2019 2. Simple Expert Advisor - MQ4
5/18
periods. -ig. 000 and -ig. 002 show the position of two different 4A $with periods of
averaging 00 and 50% on different mar&et parts. Averages with small averaging period $red
lines% are closer to a price chart, twist and movable. 4oving averages with larger period of
averaging $bl!e line% are more inert, have larger lag and are sit!ated farther from mar&et
prices. :et's pa attention to places where 4As with different averaging periods cross and tr
to decide, whether the fact of 4A crossing can be !sed as a reading criterion.
-ig. 000. Crossing of 4A$00% and 4A$50% when price movement direction changes.
n -ig. 000 we see a mar&et part where opening orders in the direction of price movement at
4A crossing is
after that the mar&et price contin!es growing for some time. -!rther reverse 4A crossing
indicates the price movement direction change. f we open a B! order at point A and close it
at B, we will get profit proportional to difference of A and B prices.
8/10/2019 2. Simple Expert Advisor - MQ4
6/18
-ig. 002. Crossing of 4A$00% and 4A$50% when price movement direction changes.
At the same time there are other moments in the mar&et when 4A cross, b!t this does not lead
to f!rther considerable price rise or fall $-ig. 002%. )rders opened at 4A crossing at s!ch
moments will lead to losses. f *ell is opened at A and closed at B, s!ch trading will bring
losses. The same can be said abo!t a B! order opened at B and closed at C.
The s!ccess of the whole strateg implemented on the basis of 4A crossing depends on the
n!mber of parts that can be characteri(ed as trend and flat. n flat often 4A crossing is a
reg!lar event that interferes with an trend strateg. =!mero!s false signals as a r!le lead to
losses. That is wh this sign # crossing of 4As with different averaging period # can be !sedfor b!ilding trading strategies onl in combination with other signs proving a trend. n this
example $for constr!cting a simple Expert Advisor% we will have to ref!se !sing this sign.
e will !se another sign. Anal(ing vis!all the character of price changes in the mar&et, we
can see that a long one#direction price rise or fall often appears as a res!lt of a short strong
movement. n other words, if within a short period a strong movement happened, we ma
expect its contin!ation in a medi!m#term period.
8/10/2019 2. Simple Expert Advisor - MQ4
7/18
-ig. 005. *trong price movement can lead to a trend development.
-ig. 005 shows the mar&et period when a strong movement res!lted in the contin!ation of the
price change in the same direction. As the >a strong movement> we ma !se the difference of
4As with different averaging periods. The stronger the movement, the larger is the lag of 4A
with larger averaging period from 4A with a small period of averaging. 4oreover, even
strong discontin!o!s price movements with f!rther ret!rn do not res!lt in a large difference
between 4As, i.e. n!mero!s false signals do not appear. -or example, price
points with f!rther ret!rn $in the center in -ig. 005% entailed increase of difference between
4As onl b 21 points. At the same time a reall strong movement $which is not !s!all
accompanied b a considerable correction% in point A res!lted in the difference increase !p to2; # 51 points.
f B! order is opened when a certain val!e of difference between 4As is reached, for
example in A, most probabl the order will be profitable when a price reaches a preset *top
order val!e. :et's !se this val!e as a trading criterion in o!r Expert Advisor.
Number of Orders
n this example we anal(e an Expert Advisor that admits presence of onl one mar&et order,
pending orders are not provided. *!ch an approach is
example, b!t can be !sed as the basis for an strateg.
Pending orders are !s!all !sed when a developer has /!ite a reliable criterion for forecasting
the f!t!re price change with high probabilit. f there is no s!ch criterion, no need to !se
pending orders.
The sit!ation when several opposite orders for one sec!rit are open also cannot be
considered reasonable. t was written earlier that from economical point of view opposite
orders are considered to be senseless, especiall if the order prices are e/!al $see Closing and
http://book.mql4.com/trading/orderclosehttp://book.mql4.com/trading/orderclose8/10/2019 2. Simple Expert Advisor - MQ4
8/18
eleting )rders%. n s!ch a case we sho!ld close one order b another one and wait for a
signal to open one mar&et order in a certain direction.
Relation of Trading Criteria
-rom this position it becomes clear what relations are possible between trading criteria. -ig.
006 shows three variants of correlation of trading criteria, when each criterion is important
$valid%. Actions $opening and closing mar&et orders% ta&e place cloc&wise on the following
pict!res.
-ig. 006. )rder opening and closing criteria correlation $a and b # correct, c # incorrect%.
The most pop!lar variant of a correctl formed trading criteria is the variant a. After being
opened a mar&et order B! is held !pon till the moment when criterion re/!iring its closing
triggers. After that a pa!se occ!rs when no orders are opened. -!rther a mar&et order *ell can
be opened. Conditions for closing a *ell order $in accordance with correctl formed criteria%
occ!r earlier, than conditions for opening a B! order. "owever, a B! order can be opened
once again, if a trading criterion re/!ires this. B!t according to this variant a mar&et order
cannot be opened if there is an open mar&et order in the contrar direction.
*imilar criteria correlation is in the variant b. The difference is that a criterion for opening anmar&et order is at the same time a criterion for closing the opposite order. This variant li&e the
variant adoes not allow several orders opened in the terminal at the same time on one
sec!rit.
The variant of criteria correlation is incorrect. According to this variant opening of a mar&et
order is allowed when contrar orders are not closed et, which is senseless. There can be rare
cases when this variant is partiall
acceptable for compensating losses occ!rring at small corrections after strong price
movements. n s!ch cases an opposite order can be opened of the same or smaller val!e than
the alread existing one and then closed when the correction is over. *!ch a tactic allows not
to interfere with the >main> order opened in the trend direction.
http://book.mql4.com/trading/orderclosehttp://book.mql4.com/trading/orderclose8/10/2019 2. Simple Expert Advisor - MQ4
9/18
n general case several one#direction orders are also possible. This ma be
earlier opened order is protected b a *top order and the criterion pointing at the price
development in the same direction triggered once again. "owever, when creating s!ch a
strateg, a developer m!st be f!ll aware that in case of a sharp price movement change the
placed stop orders ma be !nexec!ted b some bro&ers at the first price to!ch. And the loss
will be proportionate to the total val!e of one#directional mar&et orders.
n o!r example we !se variant bof trading criteria correlation. All opened mar&et orders are
closed either b a stop order or after a criterion of opening an order in opposite direction
triggers $here criterion of closing B! coincides with that of opening *ell and vice versa%.
Size of Opened Orders
n an trading strateg order si(es sho!ld be reasonabl limited. n a simple case a fixed ordersi(e is !sed in an Expert Advisor. Before EA operation start, a !ser can set an si(e of f!t!re
orders and leave it !nchanged for some time. -!rther if balance changes, a !ser can set !p a
new val!e of lot n!mbers of opened orders.
A too small order si(e provides more confidence in operation at the !npredictable mar&et
change, b!t the profit in case of s!ccess will be not so large. f the order si(e is too large, large
profit can be ac/!ired, b!t s!ch an EA will be too ris&. ?s!all the si(e of opened orders is
set !p so, that margin re/!irements do not exceed 2#5;7 percent of the balance or free margin
$if a strateg allows onl one opened order, balance and free margin at the moment before the
order opening will be e/!al%.
n this example both variants are implemented. A !ser ma choose either to indicate directl
val!es of orders or set the val!e in percentage from the free margin.
Programming etails
A simple trend Expert Advisortradingexpert.m/6constr!cted on the basis of previo!s
arg!ments can loo& li&e this@
//--------------------------------------------------------------------// tradingexpert.mq4// The code should be used for educational purpose only.//--------------------------------------------------------------------#property copyright "Copyright oo! $$%"#property lin! "http&//'uto(raf.dp.ua"//--------------------------------------------------------------- ) -- // *umeric +alues for ,)extern double toposs 0$$1 // for an opened orderextern double Ta!e2rofit 031 // 56 for an opened orderextern int 2eriod7,'7)0))1 // 2eriod of ,' )extern int 2eriod7,'703)1 // 2eriod of ,'
extern double 8ast+or 09.$1 // :istance bet;een ,'sextern double ots 0$.)1 // trictly set amount of lotsextern double 2rots 0$.$%1 // 2ercent of free margin
http://book.mql4.com/c/book/mq4/experts/tradingexpert.mq4http://book.mql4.com/c/book/mq4/experts/tradingexpert.mq4http://book.mql4.com/c/book/mq4/experts/tradingexpert.mq48/10/2019 2. Simple Expert Advisor - MQ4
10/18
bool 0$0)?
Tic!et1 // Arder number double ,'7)7t // Current ,'7) +alue ,'77t // Current ,'7 +alue
ot // 'mount of lots in a selected order ts // 'mount of lots in an opened order ,in7ot // ,inimal amount of lots tep // tep of lot siBe change ree // Current free margin Ane7ot // 2rice of one lot
2rice // 2rice of a selected order // of a selected order T21 // T2 DE a selected order bool 'ns 0false // er+er response after closing Cls70false // Criterion for closing uy Cls70false // Criterion for closing ell Apn70false // Criterion for opening uy Apn70false1 // Criterion for opening ell//--------------------------------------------------------------- 3 -- // 2reliminary processing if>ars F 2eriod7,'7? // *ot enough bars @ 'lert>"*ot enough bars in the ;indo;. =' doesnGt ;or!."?1 return1 // =xit start>? H if>"e+eral mar!et orders. =' doesnGt ;or!."?1 return1 // =xit start>?
H Tic!et0ArderTic!et>?1 // *umber of selected order
8/10/2019 2. Simple Expert Advisor - MQ4
11/18
Tip 0ArderType>?1 // Type of selected order 2rice 0ArderApen2rice>?1 // 2rice of selected order 0Ardertoposs>?1 // of selected order T2 0ArderTa!e2rofit>?1 // T2 of selected order ot 0Arderots>?1 // 'mount of lots H
H//--------------------------------------------------------------- -- // Trading criteria ,'7)7t0i,'>*N$2eriod7,'7)$,A:=7*N$2eriod7,'7$,A:=7,'7)7t I ,'77t J 8ast+orQ2oint? // Lf difference bet;een @ // ..,' ) and is large Apn70true1 // Criterion for openinguy Cls70true1 // Criterion for closingell H
if >,'7)7t I ,'77t - 8ast+orQ2oint? // Lf difference bet;een @ // ..,' ) and is large Apn70true1 // Criterion for openingell Cls70true1 // Criterion for closinguy H//--------------------------------------------------------------- R -- // Closing orders ;hile>true? // oop of closing orders @ if >Tip00$ SS Cls700true? // Arder uy is opened.. @ // and there is criterionto close 'lert>"'ttempt to close uy "Tic!et". Tic!etot's!?1 // Closing ell if >'ns00true? // uccess &? @ 'lert >"Closed order ell "Tic!et?1 brea!1 // =xit closing loop H if >un7=rror>(etast=rror>??00)? // 2rocessing errors continue1 // 8etrying
return1 // =xit start>? H
8/10/2019 2. Simple Expert Advisor - MQ4
12/18
brea!1 // =xit ;hile H//--------------------------------------------------------------- % -- // Arder +alue 8efresh8ates>?1 // 8efresh rates ,in7ot0,ar!etLnfo>ymb,A:=7,L*AT?1 // ,inimal number of lots
ree 0'ccountree,argin>?1 // ree margin Ane7ot0,ar!etLnfo>ymb,A:=7,'8(L*8=NL8=:?1// 2rice of ) lot tep 0,ar!etLnfo>ymb,A:=7ATT=2?1 // tep is changed
if >ots F $? // Lf lots are set ts 0ots1 // ;or! ;ith them else // U of free margin ts0,athloor>reeQ2rots/Ane7ot/tep?Qtep1// or opening
if>ts I ,in7ot? ts0,in7ot1 // *ot less than minimal if >tsQAne7ot I ree? // ot larger than freemargin @
'lert>" *ot enough money for " ts" lots"?1 return1 // =xit start>? H//--------------------------------------------------------------- 9 -- // Apening orders ;hile>true? // Arders closing loop @ if >Total00$ SS Apn700true? // *o ne; orders J @ // criterion for openinguy 8efresh8ates>?1 // 8efresh rates 0id - *e;7top>toposs?Q2oint1 // Calculating of opened T20id J *e;7top>Ta!e2rofit?Q2oint1 // Calculating T2 of opened 'lert>"'ttempt to open uy. "Apened order ell "Tic!et?1 return1 // =xit start>? H if >un7=rror>(etast=rror>??00)? // 2rocessing errors continue1 // 8etrying return1 // =xit start>?
H brea!1 // =xit ;hile
8/10/2019 2. Simple Expert Advisor - MQ4
13/18
H//--------------------------------------------------------------- -- return1 // =xit start>? H//-------------------------------------------------------------- )$ --int un7=rror>int =rror? // unction of processing
errors @ s;itch>=rror? @ // *ot crucialerrors
case 4& 'lert>"Trade ser+er is busy. Trying once again.."?1 leep>3$$$?1 // imple solution return>)?1 // =xit the function case )3&'lert>"2rice changed. Trying once again.."?1 8efresh8ates>?1 // 8efresh rates return>)?1 // =xit the function case )3R&'lert>"*o prices. "Trading forbidden."?1 return>$?1 // =xit the function case )34&'lert>"*ot enough money to execute operation."?1 return>$?1 // =xit the function default& 'lert>"=rror occurred& "=rror?1 // Ather +ariants
return>$?1 // =xit the function H H//-------------------------------------------------------------- )) --int *e;7top>int 2arametr? // Chec!ing stop le+els @ int ,in7:ist0,ar!etLnfo>ymb,A:=7TA2=V=?1// ,inimal distance if >2arametr I ,in7:ist? // Lf less than allo;ed @ 2arametr0,in7:ist1 // ett allo;ed 'lert>"Lncreased distance of stop le+el."?1 H return>2arametr?1 // 8eturning +alue H//-------------------------------------------------------------- ) --
escribing !ariables
8/10/2019 2. Simple Expert Advisor - MQ4
14/18
)ne more criterion in program estimation is its readabilit. A program is considered to be
correctl written, if it can be easil read b other programmers, that's wh all main program
parts and main moments characteri(ing the strateg m!st be commented. This is also wh it is
recommended to declare and comment all variables at the beginning of the program.
n the bloc& 0#2 external and global variables are described.
According to r!les, external and global variables m!st be opened before their first !sage $see
Tpes of ariables%, that's wh the are declared in the program head part. All local variables
of the f!nction start$% are gathered and described in the !pper f!nction part $bloc& 2#5%
immediatel after the f!nction header. 8!les of declaring local variables do not re/!ire it, b!t
also do not prohibit. f a programmer faces diffic!lties in !nderstanding the meaning of a
variable when reading the program, he can refer to the !pper program part and find o!t the
meaning and tpe of an variable. t is ver convenient in programming practice.
"loc# of preliminary processing
n this example the preprocessing consists of two parts $bloc& 5#6%. The program terminates
operation if there are not eno!gh bars in a sec!rit window3 in s!ch a case it is impossible to
detect correctl $in bloc& ;#% val!es of moving averages necessar for calc!lating criteria.
Besides here the val!e of the variable or& is anal(ed. n the normal EA operation the
variable val!e is alwas 'tr!e' $it is set once d!ring initiali(ation%. f a critical error occ!rs in
the program operation, 'false' is assigned to this variable and start$% finishes its operation. This
val!e will not change in f!t!re, that is wh the following code is not exec!ted. n s!ch a case
the program operation m!st be stopped and the reason for the critical error m!st be detected$if needed, a dealing center m!st be contacted%. After the sit!ation is solved, the program can
be started once again, i.e. the EA can be attached to a sec!rit window.
Accounting orders
The described Expert Advisor allows wor&ing onl with one mar&et order. The tas& of the
orders acco!nting bloc& $bloc& 6#;% is to define characteristics of an opened order, if there is
one. n the loop going thro!gh orders 'for' all existing mar&et and pending orders are chec&ed,namel from the first $int i0% to the last one $iDlt3)rdersTotal$%%. n each ccle iteration the
next order is selected b the f!nction )rder*elect$%. The selection is made from a so!rce of
opened and pending orders $*E:ECTBFP)*%.
if >Arderelect>i-)==CT7K72A?00true? // Lf there is the next one
f the selection is exec!ted s!ccessf!ll $i.e. there is one more order in the terminal%, f!rther
this order and the sit!ation m!st be anal(ed@ whether the order is opened for the sec!rit, at
which the EA operates, whether the order is mar&et or pending3 it also m!st be ta&en into
acco!nt when co!nting orders. n the line@
if >Arderymbol>?M0ymb?continue1 // 'nother security
http://book.mql4.com/variables/typeshttp://book.mql4.com/variables/types8/10/2019 2. Simple Expert Advisor - MQ4
15/18
all orders opened for another sec!rit are eliminated. )perator 'contin!e' stops the iteration
and characteristics of s!ch an order are not processed. B!t if the order is opened for the
sec!rit, to the window of which the EA is attached, it is f!rther anal(ed.
f )rderTpe$% ret!rns val!e more than 0 $seeTpes of Trades%, the selected order is a
pending one. B!t in this Expert Advisor managing pending orders is not provided. t meansthe exec!tion of start$% m!st be terminated, beca!se a conflict sit!ation occ!rred. n s!ch a
case after a message abo!t the operation termination start$% exec!tion is stopped b the
operator 'ret!rn'.
f the last chec& showed that the anal(ed order is a mar&et order, the total n!mber of orders
for a sec!rit is calc!lated and anal(ed. -or the first of s!ch orders all necessar
characteristics are defined. f in the next iteration the order co!nter $variable Total% finds the
second mar&et order, the sit!ation is also considered to be conflict, beca!se the EA cannot
manage more than one mar&et order. n s!ch a case start$% exec!tion is stopped after showing
a corresponding message.
As a res!lt of the order acco!nting bloc& exec!tion $if all chec&s were s!ccessf!l% the variable
Total preserves its (ero val!e if there are no mar&et orders, or gets the val!e 0 if there is a
mar&et order for o!r sec!rit. n the latter case some variables set in correspondence with the
order characteristics $n!mber, tpe, opening price, stop levels and order val!e% also get their
val!es.
Calculating Trading Criteria
n the anal(ed example definition of trading criteria $bloc& ;#% is calc!lated on the bases of
difference between 4oving Averages with different periods of averaging. According to
accepted criteria a chart is b!ll#directed if the c!rrent val!e of the 4A with smaller period is
larger than the val!e of 4A with larger period, and the difference between the val!es is larger
than a certain val!e. n a bear movement 4A with smaller period is lower than 4A with
larger period and the difference is also larger than a certain critical val!e.
At the bloc& beginning val!es of 4As with averaging periods Period4A0 and
Period4A2 are calc!lated. The fact of significance of an trading criterion is expressed via
the val!e of a corresponding variable. ariables )pnB and )pn* denote the criterion
triggering for opening B! and *ell orders, variables ClsG and Cls* # for closing. -orexample, if a criterion for opening B! has not triggered, the val!e of )pnB remains 'false'
$set at the variable initiali(ation%3 if it has triggered, )pnB gets the val!e 'tr!e'. n this case
the criterion for closing *ell coincides with that for opening B!, criterion for opening *ell
coincides with that for closing B!.
Trading criteria accepted in this example are !sed for ed!cational p!rpose onl
and m!st not be considered as a g!ideline when trading on a real acco!nt.
Closing Orders
http://book.mql4.com/appendix/tradinghttp://book.mql4.com/appendix/tradinghttp://book.mql4.com/appendix/trading8/10/2019 2. Simple Expert Advisor - MQ4
16/18
t was written earlier that this Expert Advisor is intended for operation onl with one mar&et
order opened for a sec!rit, to which window the EA is attached. To the moment when control
in the program is passed to the order closing bloc& it is &nown for s!re that at the c!rrent
moment there are either no orders for the sec!rit, or there is onl one mar&et order. That's
wh the code in orders closing bloc& is written so that onl one order can be closed
s!ccessf!ll.
This bloc& is based on the infinite loop 'while', the bod of which consists of two analogo!s
parts@ one for closing a B! order, another for closing a *ell order. 'hile' is !sed here for the
p!rpose that in case of a trade operation fail!re it co!ld be repeated once again.
n the header of the first operator 'if' condition for closing a B! order is calc!lated $*ell
orders are closed in the analogo!s wa%. f the tpe of an earlier opened order corresponds to
B! $see Tpes of Trades% and the sign for closing B! is relevant, control is passed to the
bod of 'if' operator where a re/!est to close is formed. As an order closing price in the
f!nction )rderClose$% the val!e of a two#sided /!ote corresponding to the order tpe is
indicated $see 8e/!irements and :imitations in 4a&ing Trades%. f a trade operation isexec!ted s!ccessf!ll, after a message abo!t the order closing is shown the c!rrent 'while'
iteration is stopped and the exec!tion of the order closing bloc& is over. B!t if the operation
fails, the !ser#defined f!nction for processing errors -!nError$% is called $bloc& 01#00%.
Processing Errors
As a passed parameter in -!nError$% the last error code calc!lated b +et:astError$% is !sed.
epending on the error code -!nError$% ret!rns 0 if the error is not critical and the operationcan be repeated, and 1 if the error is critical. Critical errors are divided into two tpes # those,
after which a program exec!tion can be contin!ed $for example, a common error% and those,
after which exec!tion of an trade operations m!st be stopped $for example, bloc&ed
acco!nt%.
if after an !ns!ccessf!l trade operation the !ser#defined f!nction ret!rns 0, the c!rrent 'while'
iteration is terminated and d!ring the next iteration another attempt is made to exec!te the
operation # to close the order. f the f!nction ret!rns 1, the c!rrent start$% exec!tion is stopped.
)n the next tic& start$% will be started b the client terminal again and if HIJK conditions for
order closing are preserved, another attempt to close the order will be made.
f d!ring error processing it is fo!nd o!t that f!rther program exec!tion is senseless $for
example the program operates on an old client terminal version% d!ring the next start the
exec!tion of the special f!nction start$% will be terminated in the bloc& of preliminar
processing when anal(ing the val!e of the variable or&.
Calculating Amount of $ots for Ne% Orders
Amo!nt of lots can be calc!lated in accordance with a !ser's settings following one of the twovariants. The first variant is a certain constant val!e set !p b a !ser. According to the second
http://book.mql4.com/appendix/tradinghttp://book.mql4.com/appendix/limitshttp://book.mql4.com/appendix/tradinghttp://book.mql4.com/appendix/limits8/10/2019 2. Simple Expert Advisor - MQ4
17/18
variant the amo!nt of lots is calc!lated on the basis of a s!m e/!al to a certain percentage $set
b a !ser% of a free margin.
At the beginning of the bloc& of defining the amo!nt of lots for new orders $bloc& L#M%
necessar val!es of some variables are calc!lated # minimal allowed amo!nt of lots and step
of lot change set !p b a bro&er, free margin and price of one lot for the sec!rit.
n this example the following is provided. f a !ser has set !p a certain non#(ero val!e of the
external variable :ts, for example 1.;, it is accepted as the amo!nt of lots :ts when a trade
re/!est to open an order is formed. f 1 is assigned to :ts, the n!mber of lots :ts is defined on
the basis of the variable Prots $percentage%, free margin and conditions set !p b a bro&er.
After :ts is calc!lated, a chec& is cond!cted. f this val!e is lower than the minimal allowed
val!e, the minimal allowed val!e is accepted. b!t if free margin is not eno!gh, after a
corresponding message the start$% exec!tion is terminated.
Opening Orders
The bloc& of opening orders $bloc& M#9% li&e the blo&e of opening orders is an infinite loop
'while'. n the header of the first operator 'if' conditions for opening a B! order are
calc!lated@ if there are no orders for the sec!rit $variable Total is e/!al to 1% and the sign for
opening a B! order is relevant $)pnB is tr!e %, control is passed to 'if' operator bod for
opening an order. n s!ch a case after rates are refreshed prices for stop levels are calc!lated.
al!es of stop levels are initiall set b a !ser in external variables *top:oss and Ta&eProfit.n a general case a !ser can set val!es for this parameters smaller that a bro&er allows.
Besides a bro&er ma change the minimal allowed distance at an moment $it is an often case
at strong mar&et movements, for example, before important news release%. That's wh before
each order opening stop levels m!st be calc!late ta&ing into acco!nt val!es set b! a !ser and
the minimal allowed val!e set !p b a bro&er.
-or calc!lating stop levels the !ser#defined f!nction =ew*top$% is !sed3 as a passed
parameter the stop level val!e set b a !ser is !sed. n =ew*top$% first the c!rrent minimal
allowed distance is calc!lated. f the val!e set b a !ser corresponds to a bro&er's
re/!irements, this val!e is ret!rned. f it is smaller than the allowed val!e, the val!e allowed
b a bro&er is !sed. Prices of stop re/!ests are calc!lated from the corresponding two#sided/!ote $see 8e/!irements and :imitations in 4a&ing Trades%.
A trade re/!est to open an order is formed !sing the f!nction )rder*end$%. -or the calc!lation
of order opening price and prices of stop re/!ests the two#sided /!ote val!es corresponding to
the order tpe are !sed. f a trade operation was s!ccessf!l $i.e. a server ret!rned the n!mber
of an opened order% after a message abo!t a s!ccessf!l order opening is shown. start$%
exec!tion is finished. f an order was not opened and the client terminal ret!rned an error, the
error is processed according to the algorithm described earlier.
Some Code Peculiarities
http://book.mql4.com/appendix/limitshttp://book.mql4.com/appendix/limits8/10/2019 2. Simple Expert Advisor - MQ4
18/18
The anal(ed Expert Advisor code is oriented to the implementation of a certain strateg.
=ote, some program lines contain variables and calc!lations that wo!ld be changed, if the
strateg were changed.
-or example, according to the accepted strateg the Expert Advisor is developed to wor& onl
with one order. This allowed to !se the variable Tic&et both for the identification of a closing
order n!mber $in bloc& of closing #L% and for the identification of a s!ccess of a trade
operation exec!tion when opening an order $in the bloc& of opening M#9%. n this case s!ch a
sol!tion is acceptable. "owever, if we ta&e the anal(ed code as the basis for the
implementation of another strateg $for example allow opposite orders% we will have to
introd!ce one or several variables to be able to recogni(e n!mbers of opened orders and
identif the s!ccess of trade operations.
n f!rther strateg modifications we will have to change come program lines containing part
of logics contained in the so!rce strateg. =amel in the order acco!nting bloc& we will nothave to terminate the program operation if there are several open orders for a sec!rit.
Besides, conditions for opening and closing orders will alslo change. This will entail the code
changing in bloc&s of opening and closing orders.
)n the basis of this analsis we can easil concl!de that the described simple Expert Advisor
is not perfect. n a general case, for the implementation of order acco!nting one sho!ld !se a
!niversal f!nction based on !sing data arras and not containing logics of a certain strateg.
The same can be said abo!t the bloc&s of opening and closing orders. A more complete
program m!st contain a main analtical f!nction, all other !ser#defined f!nctions m!st be
s!bordinate to it. This analtical f!nction m!st contain a program code, in which all
conditions for the implementation of an strateg are anal(ed3 all s!bordinate f!nctions m!st
perform limited actions. The f!nction of acco!nting orders m!st onl acco!nt orders,
f!nctions of opening and closing orders m!st onl open and close orders, and the analtical
f!nction m!st >thin&> and manage all other f!nctions, i.e. call them when needed.