expert advisor programming
TRANSCRIPT
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 1/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 2/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 3/212
Expert AdvisorProgrammingCreating Automated Trading Systems
in MQL for MetaTrader 4
Andrew R. oung
Edgehill Publishing
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 4/212
SECOND PRINTING
Copyright © 2010 !ndre" R# $oung# !ll rights reser%ed#
Published by Edgehill Publishing N&sh%ille TN#
Dis'l&i(er o) *&rr&nty+ *hile "e h&%e stri%ed to ensure th&t the (&teri&l in this boo, is &''ur&te the
publisher be&rs no responsibility )or the &''ur&'y or 'o(pleteness o) this boo, &nd spe'i)i'&lly
dis'l&i(s &ll i(plied "&rr&nties o) o) (er'h&nt&bility or )itness )or & p&rti'ul&r purpose# Neither the
&uthor nor publisher sh&ll be li&ble )or &ny loss o) pro)it or &ny other non-'o((er'i&l or 'o((er'i&l
d&(&ges in'luding but not li(ited to 'onse.uenti&l in'ident&l spe'i&l or other d&(&ges#
/et&Tr&der / /3/ &nd /e4pert &d%isor/ &re tr&de(&r,s o) et&uotes So)t"&re Corp#
This boo, &nd it5s publisher is not in &ny "&y endorsed by or &))ili&ted "ith et&uotes So)t"&re
Corp#
6or (ore in)or(&tion on this boo, in'luding upd&tes ne"s &nd ne" editions ple&se %isit our "eb
site &t http+77"""#e4pert&d%isorboo,#'o(7#
IS8N+ 9:;-0-9;2<=9-0-1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 5/212
Ta!"e of Contents
#ntrodu$tion % !bout This 8oo, 2
! Note !bout 3 = 2
Con%entions >sed In This 8oo, ?
An #ntrodu$tion to MQL 4Introdu'tion to et&Editor
8&si' Con'epts :
3&yout o) &n 6ile 1
&rder P"a$ement '(8id !s, @ Spre&d 20
Order Types 20
The Order Pl&'e(ent Pro'ess 21
OrderSendAB 22
C&l'ul&ting Stop 3oss @ T&,e Pro)it 2=
Retrie%ing Order In)or(&tion ?2
Closing Orders ?
! Si(ple E4pert !d%isor ?<
Advan$ed &rder P"a$ement 4'Order odi)i'&tion 2
eri)ying Stops &nd Pending Order Pri'es =
C&l'ul&ting 3ot Sie 9
Other Consider&tions =2
Putting It !ll Together =:
)or*ing wit+ ,un$tions -4 !dd Stop 3oss &nd T&,e Pro)it :?
>sing In'lude 6iles :
>sing 3ibr&ries :
! Si(ple E4pert !d%isor A"ith 6un'tionsB :=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 6/212
&rder Management (The Order 3oop ;0
Order Counting ;2
Tr&iling Stops ;:
>pd&ting the E4pert !d%isor 92
&rder Conditions and #ndi$ators /4Pri'e D&t& 9
Indi'&tors 9=
Indi'&tor Const&nts 102
E%&lu&ting Tr&de Conditions 10?
Co(p&ring Indi'&tor &lues !'ross 8&rs 10;
)or*ing wit+ Time and 0ate %%'
D&teti(e &ri&bles 112D&te &nd Ti(e 6un'tions 11
Cre&ting ! Si(ple Ti(er 11=
E4e'ute On 8&r Open 11:
Tips and Tri$*s %''Es'&pe Ch&r&'ters 122
>sing Ch&rt Co((ents 122
Che', Settings 12?
De(o or !''ount 3i(it&tions 12
ess&ge8o4AB 12=
E(&il !lerts 12:
Retry on Error 12;
>sing Order Co((ents !s &n Identi)ier 1?1
&rgin Che', 1?2
Spre&d Che', 1?2
ultiple Orders 1??
Glob&l &ri&bles 1?<
Che', Order Pro)it 1?:
&rting&le 1?;
Debugging $our E4pert !d%isor 11
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 7/212
Custom #ndi$ators and S$ripts %4-8u))ers 1<
Cre&ting ! Custo( Indi'&tor 1<
S'ripts 1=2
Appendix A %14Si(ple E4pert !d%isor 1=
Si(ple E4pert !d%isor "ith Pending Orders 1=<
Appendix 2 %-( !d%&n'ed E4pert !d%isor 1<0
!d%&n'ed E4pert !d%isor "ith Pending Orders 1<<
Appendix C %3'E4pert !d%isor "ith 6un'tions 1:2
E4pert !d%isor "ith 6un'tions Pending Orders 1:=
Appendix 0 %(In'lude 6ile 1;0
Appendix E %/Custo( Indi'&tor 19;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 8/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 9/212
Introduction
#ntrodu$tion
The )oreign e4'h&nge (&r,et h&s r&pidly be'o(e one o) the (ost popul&r (&r,ets to tr&de in re'ent
ye&rs# 8e'&use o) its round-the-'lo', hours high le%er&ge &nd lo" (&rgin re.uire(ents thous&ndso) ordin&ry people h&%e be'o(e &'ti%e tr&ders#
et&Tr&der A'o((only &bbre%i&ted &s TB h&s be'o(e one o) the (ost popul&r tr&ding pl&t)or(s
)or )ore4# De%eloped by et&uotes So)t"&re Corpor&tion et&Tr&der is o))ered by hundreds o)
)ore4 bro,ers "orld"ide in'luding big n&(es su'h &s G!IN C&pit&l 6FC !lp&ri &nd Interb&n, 6F#
et&Tr&der5s popul&rity ste(s )ro( the )&'t th&t it5s )ree bro,er supported &nd in'ludes (&ny use)ul
te'hni'&l &n&lysis tools# 8ut prob&bly the biggest re&son )or et&Tr&der5s su''ess is the po"er)ul
3 progr&((ing l&ngu&ge#
3 h&s (&de it possible )or tr&ders to progr&( their o"n 'usto( indi'&tors &nd &uto(&ted tr&ding
str&tegies "ithout p&ying & di(e )or so)t"&re# Si(il&r tr&ding p&',&ges )or e.uities &nd )utures '&n
'ost o%er 1000# ! "orld"ide 'o((unity o) tr&ders &nd progr&((ers h&s de%eloped o))ering
hundreds o) )ree &nd 'o((er'i&l e4pert &d%isors &nd indi'&tors &s "ell &s progr&((ing ser%i'es &nd
&d%i'e#
The si(il&rity o) 3 to l&ngu&ges su'h &s C (&,es it rel&ti%ely e&sy )or e4perien'ed progr&((ers to
pi', up &nd the l&ngu&ge itsel) is "ell do'u(ented# 8ut le&rning ho" to e))e'ti%ely progr&( tr&ding
str&tegies in 3 is & pro'ess o) tri&l &nd error#
3 is & rel&ti%ely lo" le%el l&ngu&ge &nd &s su'h it is ne'ess&ry )or the progr&((er to 're&te
'usto( pro'edures to h&ndle (&ny 'o((on tr&ding )un'tions# Coding so(ething &s si(ple &s &
tr&iling stop )or e4&(ple '&n be d&unting )or the ne" 3 progr&((er#
There &re (&ny )&'tors th&t (ust be t&,en into 'onsider&tion "hen progr&((ing & robust &uto(&ted
tr&ding str&tegy &nd et&Tr&der itsel) h&s (&ny idiosyn'r&sies th&t the progr&((er needs to be
&"&re o)# It '&n t&,e doens o) hours o) troubleshooting &nd pr&'ti'e to le&rn the te'hni.ues
ne'ess&ry to progr&( e4pert &d%isors#
This boo, hopes to shorten the le&rning 'ur%e )or ne" e4pert &d%isor progr&((ers# Here I "illpresent (&ny o) the tips &nd tri',s I5%e le&rned in the hundreds o) hours I5%e spent 'oding e4pert
&d%isors o%er the l&st )e" ye&rs#
1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 10/212
EXPERT ADVISOR PROGRAMMING
A!out T+is 2oo*
8y the ti(e you )inish this boo, you should possess the ,no"ledge ne'ess&ry to 're&te your o"n
robust &uto(&ted tr&ding str&tegies in 3 in'luding 'o((on tr&ding )e&tures su'h &s tr&iling
stops (oney (&n&ge(ent &nd (u'h (ore# $ou "ill &lso le&rn ho" to 'onstru't & si(ple indi'&tor
using built-in indi'&tor )un'tions#
This boo, &ssu(es th&t the re&der is ,no"ledge&ble &bout )ore4 tr&ding &nd te'hni'&l &n&lysis in
gener&l# The re&der should &lre&dy be pro)i'ient in using e4pert &d%isors &nd indi'&tors in
et&Tr&der# *hile no prior progr&((ing ,no"ledge is &ssu(ed the re&der "ill bene)it )ro( h&%ing
so(e b&si' progr&((ing s,ills &nd )&(ili&rity "ith 'on'epts su'h &s %&ri&bles 'ontrol stru'tures
)un'tions &nd (odern progr&((ing l&ngu&ge synt&4#
*e "ill be di%ing right into 'oding solutions to spe'i)i' proble(s# E%ery &tte(pt is (&de to e4pl&in
ne" 'on'epts &s they &re introdu'ed ho"e%er this boo, is not intended &s & l&ngu&ge re)eren'e#
The 3 re)eren'e &t http://docs.mql4.com does &n e4'ellent ob &t th&t# The 3 re)eren'e is
&lso built into the et&Editor IDE th&t 'o(es "ith et&Tr&der#
*hile "e "ill &tte(pt to tou'h on e%erything th&t is ne'ess&ry &nd rele%&nt to e4pert &d%isor
de%elop(ent "e "ill not be &ble to 'o%er e%ery ele(ent o) the 3 l&ngu&ge# There &re (&ny
spe'i&lied )un'tions in 3 th&t &re not gener&lly used in e4pert &d%isor progr&(ing# In p&rti'ul&r
"e "ill not be dis'ussing &rr&y )un'tions )ile (&nipul&tion obe'ts "indo"s &nd (ost string or
'on%ersion )un'tions#
The o))i'i&l 3 "ebsite &t http://www.mql4.com h&s & )ree boo, on 3 progr&((ing th&t (&y
ser%e &s & use)ul &nd 'o(ple(ent&ry resour'e# There &re (&ny in)or(&ti%e &rti'les th&t 'o%er b&si'
&nd &d%&n'ed progr&((ing 'on'epts in 3 & 'ode libr&ry "ith &ddition&l indi'&tors &nd e4&(ples
&nd & )oru( "here you '&n &s, )or help "ith your progr&((ing .uestions#
The 'ode e4&(ples &nd te'hni.ues I te&'h in this boo, &re "h&t h&s "or,ed )or (e# I try to ,eep
things &s si(ple &s possible "ithout s&'ri)i'ing )un'tion&lity# Th&t s&id there is &l"&ys (ore th&n
one "&y to &''o(plish so(ething &nd this is espe'i&lly true in progr&((ing# There &re e.u&lly %&lid
(ethods o) &'hie%ing the s&(e result &nd it is possible you (&y dis'o%er & better "&y o) doing
so(ething#
&ny o) the sour'e 'ode e4&(ples in this boo, &s "ell &s the )ull &ppendi4es &re &%&il&ble )or
do"nlo&d &t the boo,5s o))i'i&l "ebsite http://www.expertadvisorbook.com/ # This "&y you '&n
s&%e yoursel) the ti(e o) typing in &ll o) the e4&(ples yoursel)# 6eel )ree to (odi)y the sour'e 'ode
)or your o"n needs#
2
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 11/212
Introduction
A ote A!out MQL 1
!s o) this "riting the ne4t %ersion o) the et&Tr&der pl&t)or( is in open bet& testing# There "ill be
so(e signi)i'&nt 'h&nges to the ne"est %ersion o) 3# et&uotes h&s reported th&t et&Tr&der =
"ill not be b&',"&rd 'o(p&tible "ith et&Tr&der progr&(s# Thus &ny progr&(s "ritten in 3
"ill need to be re"ritten or upd&ted )or 3 =#
This boo, de&ls "ith et&Tr&der &s it is the %ersion I h&%e been progr&((ing in )or the l&st )e"
ye&rs &nd is 'urrently the %ersion th&t is being used by 6ore4 bro,ers# Sin'e the rele&se o)
et&Tr&der in 200= 6ore4 tr&ding h&s e4ploded in popul&rity# et&Tr&der h&s be'o(e the (ost
popul&r )ore4 tr&ding pl&t)or( &nd there h&%e been thous&nds o) tr&ding str&tegies &nd indi'&tors
"ritten in 3 #
I predi't the (igr&tion to et&Tr&der = "ill be & gr&du&l one# 8ro,ers "ill 'ontinue to support
et&Tr&der )or so(e ti(e so the progr&(s you "rite in 3 "ill not be'o(e obsolete
i((edi&tely# The 'on'epts in this boo, "ill re(&in the s&(e <hough so(e o) the )un'tions &nd
synt&4 "ill 'h&nge# The 'h&llenge "ill be to le&rn the ne" 3 = )e&tures &nd in'orpor&te it into your
e4isting 'ode#
! se'ond edition o) this boo, "ill be rele&sed so(eti(e &)ter the )in&l rele&se o) et&Tr&der =# 6or
those "ho h&%e pur'h&sed this boo, the upd&ted sour'e 'ode &nd &n 3 to 3= guide "ill be
&%&il&ble &t our "ebsite http://www.expertadvisorbook.com/ #
Conventions 5sed #n T+is 2oo*
3 l&ngu&ge ele(ents sour'e 'ode e4&(ples &nd )ile &nd >R3 lo'&tions "ill be displ&yed in &
fixed-width font# ! l&rger bold )ont "ill be used )or inline te4t# 8lo',s o) sour'e 'ode "ill be
indented# !ny bold te4t &ppe&ring in &n indented sour'e 'ode blo', indi'&tes 'ode th&t h&s been
upd&ted or 'h&nged )ro( & pre%ious e4&(ple#
Source code block
Updated source code
*ords in italics indi'&te & ne" 'on'ept th&t is being introdu'ed or de)ined# Re)eren'es to se'tions
&nd topi's in the 3 Re)eren'e "ill be displ&yed in it&li's# Re)eren'es to ele(ents o) the et&Tr&der inter)&'e in'luding "indo"s di&logs buttons or (enu ite(s "ill &lso be displ&yed in it&li's#
?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 12/212
EXPERT ADVISOR PROGRAMMING
C+apter % An #ntrodu$tion to MQL
#ntrodu$tion to MetaEditor
)+at is an Expert Advisor6
!n expert advisor is &n &uto(&ted tr&ding progr&( "ritten in 3# E4pert &d%isors A'o((only
&bbre%i&ted &s E!B '&n pl&'e (odi)y &nd 'lose orders &''ording to & tr&ding syste( &lgorith(# E!5s
gener&lly use indi'&tors to gener&te tr&ding sign&ls# These indi'&tors '&n be the ones th&t 'o(e "ith
et&Tr&der or they '&n be 'usto( indi'&tors#
!n indicator is & te'hni'&l &n&lysis tool th&t '&l'ul&tes pri'e d&t& to gi%e &n interpret&tion o) (&r,et
&'ti%ity# !n indi'&tor dr&"s lines or obe'ts on the 'h&rt# Indi'&tors '&nnot pl&'e (odi)y or 'lose
orders# E4&(ples o) indi'&tors in'lude the (o%ing &%er&ge &nd sto'h&sti's#
! script is & si(pli)ied e4pert &d%isor th&t per)or(s & single t&s, su'h &s pl&'ing & pending order or
'losing &ll orders on & 'h&rt# ! )e" use)ul s'ripts &re in'luded "ith et&Tr&der#
,i"e ,ormats
6iles "ith the .mq4 e4tension &re source code )iles# These &re the )iles "e edit in et&Editor# *hen
&n .mq4 )ile is 'o(piled &n .ex4 )ile is produ'ed#
6iles "ith the .ex4 e4tension &re executable )iles# These &re the )iles "e run in et&Tr&der# These
)iles '&nnot be opened in et&Editor# I) you only h&%e the .ex4 )ile )or &n E! or indi'&tor the i'on
ne4t to the )ile n&(e in et&Tr&der5s Navigator "indo" "ill be gr&yed out#
6iles "ith the .mqh e4tension &re in'lude )iles# These )iles 'ont&in user-'re&ted )un'tions th&t &re
re)eren'ed in &n .mq4 )ile# During 'o(pil&tion the 'o(piler /in'ludes/ the 'ontents o) the .mqh )ile in
the .ex4 )ile# *e5ll le&rn (ore &bout in'lude )iles l&ter#
The .mqt e4tension is used )or te(pl&te )iles# *hile these )iles '&n be opened in et&Tr&der the )ile
type is not &sso'i&ted "ith the progr&( in *indo"s# Te(pl&tes &re used to 're&te ne" )iles using the
E4pert !d%isor *i&rd in et&Editor#
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 13/212
An Introduction to MQL
$ou '&n 're&te your o"n te(pl&tes i) you "ish but "e "ill not be 'o%ering te(pl&te 're&tion in this
boo,# The et&Tr&der do'u(ent&tion "ill tell you &ll you need to ,no" &bout 're&ting te(pl&tes#
Indi'&tors e4pert &d%isors libr&ries &nd s'ripts &ll sh&re the .mq4 e4tension# The only "&y to tell
the( &p&rt is either by their s&%e lo'&tion or by opening the )ile &nd e4&(ining the(# 8y the ti(e
you )inish this boo, you should be &ble to identi)y the di))eren'e bet"een progr&( types ust byloo,ing &t the sour'e 'ode#
,i"e Lo$ations
!ll et&Editor )iles &re stored inside the experts folder # The \experts )older is 'ont&ined in the
et&Tr&der inst&ll&tion dire'tory "hi'h is in C:\ro!ram "iles\# I) your bro,er is Interb&n, 6F )or
e4&(ple the T inst&ll&tion )older "ould be C:\ro!ram "iles\#nterbank "$ %rader 4\#
The \experts )older 'ont&ins the sour'e 'ode &nd e4e'ut&ble )iles )or the e4pert &d%isors# >sing the
&bo%e e4&(ple the \experts )older "ould be lo'&ted &t C:\ro!ram "iles\#nterbank "$ %rader
4\experts\#
There &re nu(erous )olders inside the \experts )older th&t 'ont&in other types o) sour'e 'ode &nd
e4e'ut&ble )iles# Here5s & list o) the s&%e lo'&tions )or &ll )ile types+
• \experts\indicators Sour'e 'ode &nd e4e'ut&ble )iles )or your indi'&tors &re stored
here#
• \experts\include Sour'e 'ode in'lude )iles "ith the .mqh e4tension &re stored here#
• \experts\libraries 6un'tion libr&ries &nd D33s &re stored here#
• \experts\scripts Sour'e 'ode &nd e4e'ut&ble )iles )or s'ripts &re stored here#
• \experts\templates Te(pl&tes )or sour'e 'ode )iles &re stored here#
There &re & )e" other )olders inside the e4perts )older th&t you5ll "&nt to be &"&re o) too+
• \experts\lo!s !'ti%ity logs )or your e4pert &d%isors &re stored here# These "ill be use)ul
)or debugging your e4pert &d%isors#
• \experts\presets E4pert &d%isor settings th&t &re s&%ed or lo&ded )ro( et&Tr&der5s
Properties di&log &re stored here#
• \experts\files !ny )iles used )or input or output (ust be stored here#
=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 14/212
EXPERT ADVISOR PROGRAMMING
MetaEditor
et&Editor is &n Integr&ted De%elop(ent En%iron(ent AIDEB )or 3 th&t 'o(es p&',&ged "ith
et&Tr&der# It in'ludes use)ul re)eren'e se&r'h &nd &uto-'o(plete tools th&t (&,es 'oding in 3 &
lot e&sier#
The Editor "indo" &llo"s you to h&%e (ultiple )iles open &t on'e# $ou '&n (ini(ie (&4i(ie &nd
t&b bet"een se%er&l open "indo"s# The Navigator "indo" o))ers use)ul )ile-bro"sing &nd re)eren'e
)e&tures# The Toolbox "indo" displ&ys help 'ontents 'o(pil&tion errors )ile se&r'h results &nd
online &''ess to &rti'les &nd )iles &t 3#'o(#
One o) the (ost use)ul editing )e&tures is the !ssist&nt# Si(ply type the )irst )e" 'h&r&'ters o) &n
3 )un'tion oper&tor or other l&ngu&ge ele(ent &nd & drop-do"n list "ill &ppe&r# Press Enter to
&''ept the highlighted suggestion &nd &uto-'o(plete the phr&se#
,ig. %.% The et&Editor inter)&'e# Clo',"ise )ro( top le)t+ Editor "indo" N&%ig&tor "indo" &nd Toolbo4 "indo"#
<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 15/212
An Introduction to MQL
The Files t&b in the N&%ig&tor "indo" is & si(ple )ile bro"ser th&t &llo"s you to open &nd edit &ny o)
the 3 )iles in your \experts )older# The Dictionary t&b )e&tures & built-in 3 re)eren'e "hile the
earc! t&b is & se&r'h )e&ture )or the 3 re)eren'e#
The built-in 3 re)eren'e &nd the 'onte4t-sensiti%e
help "ill s&%e you & lot o) ti(e "hen 'oding# I) youneed help re(e(bering the synt&4 o) & p&rti'ul&r
l&ngu&ge ele(ent sele't or pl&'e the te4t 'ursor on
the ele(ent in the editor "indo"# Press 61 on your
,eybo&rd &nd the help topi' "ill &ppe&r in the
Toolbo4 "indo"#
The toolb&r in et&Editor )e&tures the st&nd&rd
'o(ple(ent o) )ile &nd editing )un'tions# The
N&%ig&tor &nd Toolbo4 "indo"s '&n be sho"n or
hidden using their respe'ti%e buttons on the toolb&r#
The "o#pile button 'o(piles the 'urrent )ile in the editor# I) there &re
&ny 'o(pil&tion errors they "ill be sho"n in the Toolbo4 "indo"# The
Ter#inal button opens the tr&ding ter(in&l )or testing#
2asi$ Con$epts
*e5re going to re%ie" so(e b&si' progr&((ing 'on'epts th&t "ill (&,e the rest o) this boo, e&sier
to underst&nd )or ne" progr&((ers# I) you5re &n e4perien'ed progr&((er )eel )ree to s,ip &he&d to
the ne4t se'tion Layout of an MQL File$
Syntax
I) you5re )&(ili&r "ith progr&((ing in l&ngu&ges su'h &s CJJ PHP or one o) the (&ny l&ngu&ges
"hose synt&4 is deri%ed )ro( C you5ll be %ery 'o()ort&ble progr&((ing in 3# I) your pre%ious
progr&((ing e4perien'e is in & l&ngu&ge su'h &s isu&l 8&si' then you (&y need to (&,e & )e"
&dust(ents#
In 3 e%ery st&te(ent is ter(in&ted "ith & se(i'olon# This is '&lled &n expression# !n e4pression
'&n sp&n (ultiple lines but there (ust be & se(i'olon &t the end#
double LastHigh = High[1];
string MultiLine = StringConcatenate("This is a multiline statement! "
"#or clarit$ %e %ill indent multi&le lines in this book"';
:
,ig. %.' et&Editor5s !ssist&nt
&uto 'o(plete )e&ture#
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 16/212
EXPERT ADVISOR PROGRAMMING
I) you5re ne" to progr&(ing or &''usto(ed to progr&((ing in & l&ngu&ge th&t does not ter(in&te
e4pressions "ith & se(i'olon you5ll need to (&,e sure you5re pl&'ing the se(i'olon &t the end o)
e%ery st&te(ent# Not ter(in&ting lines "ith & se(i'olon is & 'o((on ne"bie (ist&,e#
There &re & )e" e4'eptions to this+ Co(pound oper&tors do not need & se(i-'olon# ! co#pound
operator is & blo', o) 'ode th&t 'ont&ins (ultiple e4pressions "ithin br&'es &'# E4&(ples o)'o(pound oper&tors in'lude 'ontrol oper&tors Aif switchB 'y'le oper&tors Afor whileB &nd
)un'tion de'l&r&tions#
i(Com&ound == true'
)
*rint("This is a com&ound e+&ression"';
,
Note th&t there is no se(i'olon &)ter the initi&l if oper&tor nor is there & se(i'olon &)ter the 'losing
br&'e# There is & se(i'olon &)ter the rint() )un'tion ho"e%er# There '&n be one or (ultiple
e4pressions inside the br&'es# E&'h (ust end "ith & se(i'olon#
Comments
Co((ents &re use)ul )or do'u(enting your 'ode &s "ell &s )or te(por&rily re(o%ing 'ode "hile
testing &nd debugging# $ou '&n 'o((ent out & single line "ith t"o )or"&rd sl&shes+
-- This is a comment
! (ulti-line 'o((ent begins "ith /* &nd ends "ith */# ! (ulti-line 'o((ent '&n sp&n &ny nu(bero) lines &nd e%erything bet"een /* &nd */ is 'o((ented out#
-. This is a comment block
/0er$thing here is commented out .-
#dentifiers
Identi)iers &re n&(es gi%en to %&ri&bles &nd 'usto( )un'tions# !n identi)ier '&n be &ny 'o(bin&tion
o) nu(bers letters &nd the unders'ore 'h&r&'ter AKB# Identi)iers '&n be up to ?1 'h&r&'ters in
length#
$ou5ll "&nt your identi)iers to be des'ripti%e o) their )un'tion but be sure your identi)ier doesn5t
(&t'h &n 3 l&ngu&ge ele(ent A&lso '&lled & reserved %ord B# Here5s &n e4&(ple o) & %&ri&ble
identi)ier &nd & 'usto( )un'tion identi)ier# The identi)ier is in it&li's+
;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 17/212
An Introduction to MQL
double StopLoss;
int Order_Count('
Identi)iers in 3 &re case&sensitive# This (e&ns th&t +top,oss &nd stoploss &re di))erent
%&ri&blesL This is ¬her 'o((on ne"bie (ist&,e so 'he', those identi)ier n&(esL
7aria!"es
! variable is the b&si' stor&ge unit o) &ny progr&((ing l&ngu&ge# &ri&bles hold d&t& ne'ess&ry )or
our progr&( to )un'tion su'h &s pri'es settings &nd indi'&tor %&lues#
&ri&bles (ust be de'l&red be)ore they &re used# To de'l&re & %&ri&ble you spe'i)y it5s data type &n
identi)ier &nd option&lly & de)&ult %&lue# I) you de'l&re & %&ri&ble (ore th&n on'e or not &t &ll you5ll
get & 'o(pil&tion error#
The data type spe'i)ies the type o) in)or(&tion the %&ri&ble holds "hether it be & nu(ber & te4t
string & d&te or & 'olor# Here &re the d&t& types in 3+
• int ! integer A"hole nu(berB su'h &s 0 ? or -=# !ny nu(ber &ssigned to &n integer
%&ri&ble is rounded up to the ne4t "hole nu(ber#
• double ! )r&'tion&l nu(ber su'h &s 1#=:<= 0#0? or -2#?:<# >se these )or pri'e d&t& or in
(&the(&ti'&l e4pressions in%ol%ing di%ision#
• strin! ! te4t string su'h &s %he quick brown fox umped over the la0 do!#
Strings (ust be surrounded by double .uotes#
• boolean ! true 7false %&lue# C&n &lso be represented &s 1 AtrueB or 0 A)&lseB# >se these
&nyti(e you need to e%&lu&te &n bin&ry or on7o)) 'ondition#
• datetime ! ti(e &nd d&te %&lue su'h &s 1223.2.2 22:22. Intern&lly & d&teti(e
%&ri&ble is represented &s the nu(ber o) se'onds p&ssed sin'e M&nu&ry 1 19:0#
• color ! 'onst&nt representing & 'olor su'h &s 5ed or 6ark+late7lue# These &re gener&lly
used )or 'h&nging indi'&tor or obe't 'olors#
Here5s &n e4&(ple o) & %&ri&ble de'l&r&tion# This is &n integer %&ri&ble "ith the identi)ier
809ariable &nd & de)&ult %&lue o) 1#
int M$ariable = 1;
9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 18/212
EXPERT ADVISOR PROGRAMMING
On'e & %&ri&ble h&s been de'l&red you '&n 'h&nge its %&lue by &ssigning & ne" %&lue to it# Here5s &n
e4&(ple "here "e &ssign the nu(ber = to 809ariable+
M$ariable = 2;
$ou '&n &lso &ssign the %&lue o) one %&ri&ble to ¬her %&ri&ble+
int 3ourariable = 4;
M$ariable = 3ourariable;
-- M$ariable is 4
The &ssigned %&ri&ble should be o) the s&(e d&t& type# I) & double is &ssigned to &n integer %&ri&ble
)or e4&(ple the double "ill be rounded to the ne&rest "hole nu(ber# This (&y le&d to &n
undesir&ble result#
Constants
Must li,e its n&(e suggests & constant is & d&t& %&lue th&t ne%er 'h&nges# 6or e4&(ple the nu(ber
is &n integer 'onst&nt the letter 5;5 is & 'h&r&'ter 'onst&nt &nd 1223.2.2 is & d&teti(e 'onst&nt
)or M&nu&ry 1 2009#
3 h&s & "ide %&riety o) st&nd&rd 'onst&nts )or things li,e pri'e d&t& 'h&rt periods 'olors &nd
tr&de oper&tions# 6or e4&(ple <5#=6>? is & 'onst&nt )or the H1 'h&rt ti(e )r&(e =>7U@ re)ers to
& buy (&r,et order &nd 5ed is & 'olor 'onst&nt )or the 'olor red#
$ou '&n e%en 're&te your o"n 'onst&nts using the Adefine prepro'essor dire'ti%e# *e5ll get to th&t
shortly# $ou '&n le&rn (ore &bout 35s st&nd&rd 'onst&nts in the tandard "onstants se'tion o) the
3 Re)eren'e#
,un$tions
6un'tions &re the building blo',s o) (odern progr&((ing l&ngu&ges# ! )un'tion is & blo', o) 'ode
th&t is designed to '&rry out & 'ert&in t&s, su'h &s pl&'ing &n order or '&l'ul&ting & stop loss# 3
h&s doens o) built-in )un'tions )or e%erything )ro( te'hni'&l indi'&tors to order pl&'e(ent#
6un'tions &re designed to be reused o%er &nd o%er &g&in# 3e&rning ho" to 're&te )un'tions )or
'o((on tr&ding t&s,s is essenti&l to produ'ti%e progr&((ing# *e "ill "or, on 're&ting reus&ble
)un'tions )or (&ny o) the t&s,s th&t "e "ill le&rn in this boo,#
10
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 19/212
An Introduction to MQL
3et5s st&rt "ith & si(ple )un'tion '&lled ipoint() th&t '&l'ul&tes the nu(ber o) de'i(&l points in
the 'urrent p&ir &nd &uto(&ti'&lly &dusts )or ? &nd = digit bro,ers so th&t the result is &l"&ys e.u&l
to one pip# 6or $en p&irs A2 or ? digitsB the )un'tion returns 0#01# 6or &ll other p&irs A &nd = digitsB
the )un'tion returns 0#0001# Here5s ho" "e "ould '&ll the )un'tion )ro( 'ode+
double 5se*oint;5se*oint = *i&*oint(';
*e de'l&re & %&ri&ble o) type double n&(ed Useoint# Then "e '&ll the ipoint() )un'tion &nd
&ssign the result to Useoint# No" "e '&n use the %&lue stored in Useoint to '&l'ul&te & stop loss
)or e4&(ple#
Here is the 'ode )or the ipoint() )un'tion+
double *i&*oint('
)i(6igits == 4 77 6igits == 8' double 5se*oint = 9!91;
else i(6igits == : 77 6igits == 2' 5se*oint = 9!9991;
return(5se*oint';
,
The )irst line is our )un'tion de'l&r&tion# 3i,e %&ri&bles )un'tion de'l&r&tions h&%e & d&t& type &nd &n
identi)ier# 6un'tions use the s&(e d&t& types &s %&ri&bles do# The d&t& type is dependent on the type
o) d&t& the )un'tion returns# Sin'e this )un'tion returns & )r&'tion&l nu(ber "e use the double d&t&
type#
The body o) the )un'tion is 'ont&ined "ithin the br&',ets # *e h&%e &n if-else st&te(ent th&t
e%&lu&tes the nu(ber o) digits &)ter the de'i(&l pl&'e &nd &ssigns the &ppropri&te %&lue to the
Useoint %&ri&ble# 6ollo"ing th&t "e h&%e the return oper&tor "hi'h returns the %&lue o)
Useoint to the '&lling )un'tion#
There is & spe'i&l d&t& type )or )un'tions th&t do not return & %&lue# The void d&t& type is used )or
)un'tions th&t '&rry out & spe'i)i' t&s, but do not need to return & %&lue to the '&lling )un'tion# 9oid
)un'tions do not re.uire & return oper&tor in the body o) the )un'tion#
3et5s 'onsider & si(ple )un'tion )or pl&'ing & buy order# This )un'tion h&s argu#ents th&t need to be
p&ssed to the )un'tion# This )un'tion "ill pl&'e & buy (&r,et order on the 'urrent sy(bol "ith the
spe'i)ied lot sie stop loss &nd t&,e pro)it#
11
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 20/212
EXPERT ADVISOR PROGRAMMING
int &en<u$rder(double LotSize double StopLoss double TakeProfit'
)
int Ticket = rderSend(S$mbol('*<53LotSi>e?skSto&LossTake*roit';
return(Ticket';
,
This )un'tion h&s three &rgu(ents ,ot+ie +top,oss &nd %akerofit# !rgu(ents &re %&ri&bles
th&t &re used only "ithin the )un'tion# Their %&lue is &ssigned by the '&lling )un'tion# Here5s ho" "e
"ould '&ll this )un'tion in 'ode using 'onst&nts+
&en<u$rder(4 1!2229 1!@929';
This "ill pl&'e & buy order o) 2 lots "ith & stop loss o) 1#===0 &nd & t&,e pro)it o) 1#<0=0# Here5s
¬her e4&(ple using %&ri&bles# *e5ll &ssu(e th&t the %&ri&bles Use,ot+ie 7u0+top,oss &nd
7u0%akerofit h&%e the &ppropri&te %&lues &ssigned+
int AetTicket = &en<u$rder(5seLotSi>e<u$Sto&Loss<u$Take*roit';
In this e4&(ple "e &re &ssigning the return %&lue o) =pen7u0=rder() to the %&ri&ble Bet%icket
"hi'h the ti',et nu(ber o) the order "e ust pl&'ed# !ssigning the output o) & )un'tion to & %&ri&ble
is option&l# In this '&se it is only ne'ess&ry i) you pl&n to do )urther pro'essing using the ti',et
nu(ber o) the pl&'ed order#
!rgu(ents '&n h&%e default values "hi'h (e&ns th&t i) & p&r&(eter is not e4pli'itly p&ssed to the
)un'tion the &rgu(ent "ill t&,e the de)&ult %&lue# De)&ult %&lue &rgu(ents "ill &l"&ys be &t the end
o) the &rgu(ent list# Here is &n e4&(ple o) & )un'tion "ith se%er&l de)&ult %&lues+
int 6eaultal#unc(int Ticket double Price int Number = 9 string Comment = B5LL'
This )un'tion h&s t"o &rgu(ents "ith de)&ult %&lues umber &nd Comment "ith de)&ult %&lues o) 2
&nd U,, respe'ti%ely# I) "e "&nt to use the de)&ult %&lues )or both umber &nd Comment "e si(ply
o(it those &rgu(ents "hen '&lling the )un'tion+
6eaultal#unc(TicketBum5se*rice';
Note th&t "e only spe'i)ied the )irst t"o &rgu(ents# umber &nd Comment use the de)&ult %&lues o) 2
&nd U,,# I) "e "&nt to spe'i)y & %&lue )or umber but not )or Comment "e si(ply o(it the l&st
&rgu(ent+
12
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 21/212
An Introduction to MQL
6eaultal#unc(TicketBum5se*rice5seBumber';
!g&in Comment uses the de)&ult %&lue o) U,,# 8ut i) "e "&nt to spe'i)y & %&lue )or Comment
reg&rdless o) "hether or not "e "&nt to use the de)&ult %&lue )or umber "e h&%e to spe'i)y & %&lue
)or umber &s "ell+
6eaultal#unc(TicketBum5se*rice9"Comment String"';
In this e4&(ple "e used 0 &s the %&lue )or umber "hi'h is the s&(e &s the de)&ult %&lue &nd &
string 'onst&nt &s the %&lue )or Comment# Re(e(ber th&t "hen you5re de&ling "ith (ultiple
&rgu(ents th&t h&%e de)&ult %&lues you '&n only o(it &rgu(ents i) you "&nt to use the de)&ult
%&lues )or &ll o) the re(&ining &rgu(entsL
7aria!"e S$ope
The scope o) & %&ri&ble deter(ines "hi'h )un'tions it is &%&il&ble to &nd ho" long it st&ys in
(e(ory# In 3 s'ope '&n be local or global # ! lo'&l %&ri&ble '&n &lso be static #
! local %&ri&ble is one th&t is de'l&red inside & )un'tion# 3o'&l %&ri&bles &re only &%&il&ble inside the
)un'tion it is de'l&red in# The %&ri&ble is initi&lied e%ery ti(e the )un'tion runs# On'e the )un'tion
e4its the %&ri&ble &nd its d&t& &re 'le&red )ro( (e(ory#
!n e4'eption to this "ould be & static lo'&l %&ri&ble# St&ti' %&ri&bles re(&in in (e(ory e%en &)ter the
)un'tion e4its# *hen the )un'tion is run &g&in the %&ri&ble is not reiniti&lied but inste&d ret&ins it5s
pre%ious %&lue#
! st&ti' %&ri&ble is de'l&red by typing static in )ront o) the %&ri&ble de'l&r&tion# Here5s &n e4&(ple
o) & st&ti' %&ri&ble de'l&r&tion+
static int M$Staticar;
I) & st&ti' %&ri&ble needs to be (&de &%&il&ble to (ore th&n one )un'tion use & glob&l %&ri&ble
inste&d# In this '&se you do not need to de'l&re the %&ri&ble &s st&ti'#
! global %&ri&ble is one th&t is &%&il&ble to &ll )un'tions inside & progr&(# !s long &s the progr&( is
running the %&lue o) the glob&l %&ri&ble is (&int&ined# Glob&l %&ri&bles &re de'l&red outside o) &
)un'tion gener&lly &t the top o) the sour'e 'ode )ile#
1?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 22/212
EXPERT ADVISOR PROGRAMMING
There is no spe'i&l (ethod )or initi&liing & glob&l %&ri&ble# The synt&4 is identi'&l to th&t o) & lo'&l
%&ri&ble#
Layout of an MQ4 ,i"e
Creating a ew Expert Advisor
The Expert Advisor 'i(ard in et&Editor is the .ui',est "&y to get st&rted in 're&ting &n e4pert
&d%isor# $ou '&n st&rt the "i&rd by sele'ting Ne% )ro( the File (enu by pressing the Ne% button
on the toolb&r or by pressing "trl)N on your ,eybo&rd#
The di&log presents you "ith se%er&l options# $ou '&n 're&te indi'&tors s'ripts libr&ries &nd in'lude
)iles using the "i&rd# $ou '&n &lso 'hoose & te(pl&te )or gener&ting & )ile# The resulting )ile "ill be
s&%ed to the &ppropri&te dire'tory depending on its type# &,e sure E4pert !d%isor is 'hosen &nd
press Ne4t #
,ig. %.8 E4pert !d%isor *i&rd gener&l properties#
1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 23/212
An Introduction to MQL
$ou "ill be pro(pted )or & Na#e Aut!or &nd Lin* &s "ell &s so(e option&l p&r&(eters# The N&(e
)ield "ill be the )ile n&(e o) your progr&(# The E! "ill be s&%ed to the \experts )older under th&t
)ile n&(e#
The 'ontents o) the !uthor )ield "ill &ppe&r ne4t to the E! n&(e in the Str&tegy Tester &nd &s &
tooltip "hen you (ouse o%er the E! n&(e in the N&%ig&tor "indo"# The 3in, )ield is & >R3 to your"ebsite but it "ill not &ppe&r &ny"here outside the sour'e 'ode )ile#
$ou '&n &lso enter your tr&de p&r&(eters here# 6or no" &dd & p&r&(eter or t"o but don5t bother
&dusting the(# It5s best to si(ply &dd these (&nu&lly to the sour'e 'ode l&ter# Press the Finis!
button &nd &n e4pert &d%isor te(pl&te "ill open "ith your in)or(&tion &lre&dy &dded#
The de)&ult e4pert &d%isor te(pl&te is r&ther (ini(&l but it 'ont&ins the b&si' stru'ture o) &n e4pert
&d%isor# 3et5s identi)y the l&yout o) &n 3 )ile using the e4pert &d%isor te(pl&te &s our guide#
Prepro$essor 0ire$tives
The )irst thing to &ppe&r in &ny 3 )ile &re the prepro'essor dire'ti%es# These &re pre)&'ed by & A#
The de)&ult e4pert &d%isor te(pl&te h&s t"o+ Apropert0 cop0ri!ht "hi'h is the !uthor n&(e you
entered in the E4pert !d%isor *i&rd &nd Apropert0 link "hi'h is the 3in, you entered in the
"i&rd#
There &re other Apropert0 dire'ti%es but &l(ost &ll o) the( &re rel&ted to indi'&tors &nd s'ripts#
The only Apropert0 dire'ti%e you should in'lude in your e4pert &d%isor is Apropert0 cop0ri!ht
"hi'h identi)ies the E! &s your 're&tion#
! se'ond type o) prepro'essor dire'ti%e you "ill li,ely use is the Ainclude dire'ti%e# !s (entioned
e&rlier &n in'lude )ile 'onsists o) )un'tions &nd sour'e 'ode th&t "ill be in'luded in your proe't "hen
it is 'o(piled# The synt&4 )or the in'lude dire'ti%e is+
include Dfilename!mEhF
The )ile stdlib.mqh in our e4&(ple on p&ge 19 is & st&nd&rd in'lude )ile th&t 'o(es "ith
et&Tr&der# It in'ludes se%er&l (is'ell&neous )un'tions th&t progr&((ers (&y )ind use)ul# 3i,e &ll
in'lude )iles it is lo'&ted in the \experts\include )older#
The Adefine dire'ti%e is used )or de'l&ring 'onst&nts )or use in our progr&(# 6or e4&(ple inste&d o)
typing out & long te4t string e%ery ti(e you need to use it you '&n de)ine & 'onst&nt &nd type th&t
inste&d+
1=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 24/212
EXPERT ADVISOR PROGRAMMING
deine M3CBST?BT GThis is a constant
In this e4&(ple "e '&n use the 'onst&nt identi)ier 8@C=+%;% in pl&'e o) the te4t string in our
'ode# The 'on%ention )or 'onst&nt identi)iers is to use &ll '&pit&l letters# !lthough it is not &bsolutely
ne'ess&ry )or 'onsisten'y5s s&,e you should de)ine &ll identi)iers )or 'onst&nts using '&ps#
So(eti(es & )un'tion you5ll need to use is &lre&dy 'o(piled in ¬her )ile su'h &s ¬her e4pert
&d%isor & libr&ry )ile A.ex4B or & *indo"s D33 )ile A.dllB# $ou '&n i(port )un'tions dire'tly into &
proe't using Aimport dire'ti%es#
3ibr&ries &re si(il&r to in'lude )iles but inste&d o) in'luding the sour'e 'ode in our proe't "e "ill
e4e'ute the other )ile &nd '&ll the )un'tion )ro( it# *e5ll t&l, &bout using libr&ries l&ter in the boo,#
I(port dire'ti%es &re usu&lly pl&'ed in in'lude )iles espe'i&lly i) there &re (&ny )un'tions to i(port#
8ut i) you ust need to i(port one or t"o )un'tions &nd &n in'lude )ile )or the( doesn5t &lre&dye4ists then go &he&d &nd i(port the( dire'tly into your proe't#
6or det&iled e4&(ples o) the Aimport dire'ti%e see the 3 Re)eren'e p&ge I#porting of Functions
&nd loo, &t the in'lude )iles in the \experts\include )older# Here is the synt&4 )or the Aimport
dire'ti%e+
im&ort "librar$!e+:"
double M$Im&orted#unction(';
im&ort
In this e4&(ple the libr&ry )ile "e &re i(porting the )un'tionAsB )ro( is librar0.ex4# *e &re
i(porting & single )un'tion o) type double '&lled 80#mported"unction() # The )un'tion identi)ier
(ust (&t'h the )un'tion n&(e in the sour'e libr&ry )ile# Note the se(i'olon &t the end o) the )un'tion
de'l&r&tion#
Parameters and Externa" 7aria!"es
The ne4t se'tion in our e4pert &d%isor sour'e 'ode )ile &re the e4tern&l %&ri&bles# These &re the
&dust&ble p&r&(eters )or our tr&ding syste(# This in'ludes your tr&de settings Astop loss t&,e pro)it
lot sieB &nd indi'&tor settings# *hen you open the Expert Properties di&log )or &n e4pert &d%isoryou &re %ie"ing the e4tern&l %&ri&bles )or th&t progr&(#
*e spe'i)y &n e4tern&l %&ri&ble by &dding extern in )ront o) the %&ri&ble# This spe'i)ies th&t the
%&ri&ble "ill &ppe&r in the E4pert Properties di&log &nd "ill be %ie"&ble &nd &dust&ble by the user#
1<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 25/212
An Introduction to MQL
e+tern double Sto&Loss = 29;
8e sure th&t the identi)ier )or your e4tern&l %&ri&ble is des'ripti%e o) "h&t it &'tu&lly does# A/Stop3oss/
is better th&n /stop/ or /S3/ )or e4&(pleB# $ou h&%e ?1 'h&r&'ters to des'ribe your %&ri&ble so (&,e
the (ost o) it# The de)&ult %&lue )or your %&ri&ble "ill &lso be the de)&ult )or th&t p&r&(eter so'hoose & logi'&l de)&ult %&lue#
9"o!a" 7aria!"es
*e de'l&re &ny glob&l %&ri&bles &t the top o) our sour'e 'ode )ile gener&lly &)ter the e4tern&l
%&ri&bles# The lo'&tion does not (&tter &s long &s both the glob&l &nd e4tern&l %&ri&bles &re pl&'ed
outside o) &nd be)ore &ny )un'tions#
! glob&l %&ri&ble is one th&t is &%&il&ble to &ny )un'tion in the progr&(# !s long &s the progr&( is
running the glob&l %&ri&ble &nd it5s %&lue st&ys in (e(ory &nd '&n be re)eren'ed &nd 'h&nged by&ny )un'tion in the progr&(#
Te'hni'&lly e4tern&l %&ri&bles &re glob&l &s "ell but the glob&l %&ri&bles "e5re dis'ussing in this
se'tion &re intern&l "hi'h (e&ns they &re not %ie"&ble or 'h&nge&ble by the user#
Spe$ia" ,un$tions
3 h&s ? built-in )un'tions to 'ontrol progr&( e4e'ution+ init() deinit() &nd start()# The
init() )un'tion is 'o(prised o) 'ode th&t is run on'e "hen the E! is )irst st&rted# The init()
)un'tion is option&l &nd '&n be le)t out i) you5re not using it#
The deinit() )un'tion 'onsists o) 'ode th&t is run on'e "hen the E! is stopped# This )un'tion is
&lso option&l &nd it5s unli,ely you "ill need to use it in &n e4pert &d%isor#
The start() )un'tion 'ont&ins the (&in progr&( 'ode &nd is re.uired in your E!# E%ery ti(e the
st&rt )un'tion is run your tr&ding 'onditions &re 'he',ed &nd orders &re pl&'ed or 'losed depending
on ho" those 'onditions &re e%&lu&ted#
The start() )un'tion is run on e%ery ti',# ! ti', is & pri'e (o%e(ent or 'h&nge in the 8id or !s,
pri'e )or & 'urren'y p&ir# During &'ti%e (&r,ets there (&y be se%er&l ti',s per se'ond# During slo"
(&r,ets (inutes '&n p&ss by "ithout & ti',#
1:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 26/212
EXPERT ADVISOR PROGRAMMING
&t+er ,un$tions
!ny other )un'tions th&t your E! (&y use should be de'l&red &)ter the start() )un'tion# These
)un'tions "ill be '&lled )ro( the start() init() or deinit() )un'tions or )ro( other )un'tions
th&t &re '&lled )ro( the (&in progr&(# *e5ll 'o%er 'usto( )un'tions l&ter in the boo,#
1;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 27/212
An Introduction to MQL
-- *re&rocessor 6irecti0es
&ro&ert$ co&$right "?ndre% 3oung"
&ro&ert$ link "htt&J--%%%!e+&ertad0isorbook!com"
include Dstdlib!mEhF
deine M3CBST?BT "This is a constant"
-- /+ternal *arameters
e+tern int *arameter1 = 1;
e+tern double *arameter4 = 9!91;
-- Alobal ariables
int Alobalariable1;
-- Init unction
int init('
)
-- Startu& code
return(9';
,
-- 6einit unction
int deinit('
)
-- Shutdo%n code
return(9';
,
-- Start unction
int start('
)
-- Main code
return(9';
,
-- Custom unctions
int M$Custom#unction('
)
-- Custom code
return(9';
,
,ig %.4 S&(ple e4pert &d%isor l&yout
19
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 28/212
EXPERT ADVISOR PROGRAMMING
C+apter '&rder P"a$ement
2id: As* ; Spread
!s & 6ore4 tr&der you5re prob&bly &lre&dy )&(ili&r "ith the 8id &nd !s, pri'es# 8ut you (ight not be
&"&re o) their role in order pl&'e(ent# It is %ery i(port&nt to use the 'orre't pri'e "hen opening or
'losing orders#
The +id pri'e is "h&t you see on the et&Tr&der 'h&rts# It is usu&lly "h&t "e thin, o) "hen "e thin,
o) the /'urrent pri'e#/ The As* pri'e is gener&lly ust & )e" pips &bo%e the 8id pri'e# The di))eren'e
bet"een the 8id &nd the !s, is the the spread "hi'h is the bro,er5s 'o((ission )or pl&'ing the
order#
The !s, pri'e is "here "e open buy orders &nd 'lose sell orders# The 8id pri'e is "here "e open sell
orders &nd 'lose buy orders# $ou5ll need to indi'&te the 'orre't pri'e "hen opening & (&r,et order
or "hen 'losing &n order &t (&r,et so re(e(ber the di))eren'e bet"een the t"o#
&rder Types
There &re three types o) orders th&t '&n be pl&'ed in et&Tr&der+ (&r,et stop &nd li(it orders#
&r,et orders &re the (ost 'o((on# ! (&r,et order opens & position i((edi&tely &t the pre%&iling
8id or !s, pri'e#
*hen pl&'ing & (&r,et order in 3 "e (ust spe'i)y &n opening pri'e Agener&lly the l&test 8id or
!s, .uoteB# I) the spe'i)ied opening pri'e is outd&ted due to & )&st (o%ing (&r,et or & del&y in
progr&( e4e'ution the ter(in&l "ill &tte(pt to pl&'e the order &t the 'urrent (&r,et pri'e pro%ided
it is "ithin the (&4i(u( slippage#
I) you pl&'e & (&r,et order using the Ne% ,rder di&log in et&Tr&der you5ll see & setting &t the
botto( l&beled /En&ble (&4i(u( de%i&tion )ro( .uoted pri'e#/ *hen this is 'he',ed you '&n then
spe'i)y the (&4i(u( de%i&tion in pips# This is the (&4i(u( slipp&ge#
I) the 'urrent pri'e )&lls outside o) our spe'i)ied opening pri'e plus or (inus the slipp&ge & re.uote
error "ill o''ur &nd the order "ill not be pl&'ed# $ou (&y h&%e noti'ed this "hen &tte(pting to pl&'e
& (&r,et order during & )&st (o%ing (&r,et# Note th&t ECN7STP bro,ers do not use & slipp&ge
setting &nd "ill &l"&ys open (&r,et orders &t the 'urrent pri'e#
20
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 29/212
,rder Place#ent
! stop order is & type o) pending order# Pending orders &re & re.uest to open & (&r,et order &t &
'ert&in pri'e# ! buy stop order is pl&'ed &bo%e the 'urrent pri'e "hile & sell stop order is pl&'ed
belo" the 'urrent pri'e# The e4pe't&tion is th&t the pri'e "ill e%entu&lly rise or )&ll to th&t le%el &nd
'ontinue in th&t dire'tion resulting in & pro)it#
! li#it order is the opposite o) & stop order# ! buy li#it order is pl&'ed belo" the 'urrent pri'e "hile& sell li#it order is pl&'ed &bo%e the 'urrent pri'e# The e4pe't&tion is th&t the pri'e "ill rise or )&ll to
th&t le%el triggering the order &nd then re%ersing# 3i(it orders &re not used %ery o)ten in &uto(&ted
tr&ding#
!n expiration ti(e '&n be set )or pending orders# I) the order is not )illed by the e4pir&tion ti(e the
order is &uto(&ti'&lly deleted# Not &ll bro,ers support tr&de e4pir&tion#
T+e &rder P"a$ement Pro$ess
The pro'ess o) pl&'ing &n order in 3 in%ol%es se%er&l steps# *e (ust deter(ine the )ollo"ing
be)ore pl&'ing the order+
• The type o) order to be pl&'ed buy or sell stop (&r,et or li(it#
• The 'urren'y p&ir to tr&de gener&lly the 'h&rt th&t the E! is &tt&'hed to#
• The lot sie# This '&n either be & )i4ed lot sie or one th&t is '&l'ul&ted using & (oney
(&n&ge(ent routine#
• The order opening pri'e# 6or (&r,et orders this "ill be the 'urrent 8id or !s, pri'e# 6or
pending orders the opening pri'e (ust be & (ini(u( dist&n'e )ro( the 'urrent pri'e &ndshould be &bo%e or belo" the 'urrent pri'e &s re.uired by the order type#
• The stop loss pri'e# The stop loss '&n be & predeter(ined pri'e &n indi'&tor %&lue & )i4ed
nu(ber o) pips )ro( the order opening pri'e or it '&n be dyn&(i'&lly '&l'ul&ted using & ris,
(&n&ge(ent routine# The stop loss '&n be pl&'ed "ith the order or it '&n be &dded to the
order &)ter"&rd#
• The t&,e pro)it pri'e# This is gener&lly & )i4ed nu(ber o) pips )ro( the order opening pri'e
<hough it '&n be '&l'ul&ted using other (ethods &s "ell# The t&,e pro)it '&n be pl&'ed "ith
the order or it '&n be &dded to the order &)ter"&rd#
• Order identi)iers su'h &s &n order 'o((ent or & /(&gi' nu(ber/ th&t identi)ies &n order &s
being pl&'ed by & spe'i)i' e4pert &d%isor#
• !n option&l e4pir&tion pri'e )or pending orders i) the bro,er supports it#
21
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 30/212
EXPERT ADVISOR PROGRAMMING
&rderSend<=
The =rder+end() )un'tion is used to pl&'e orders in 3# The synt&4 is &s )ollo"s+
int rderSend(string Symbol int Type double Lots double Priceint Slippage double StopLoss double TakeProfit string Comment = B5LL
int MagicNumber = 9 datetime Expiration = 9 color rro! = CLKBB/';
• Sym!o" ! string representing the 'urren'y p&ir to tr&de )or e4&(ple B7U+6# The
+0mbol() )un'tion is used )or the 'urrent 'h&rt5s 'urren'y p&ir#
• Type The type o) order to pl&'e+ buy or sell (&r,et stop or li(it# This is &n integer %&lue
represented by the )ollo"ing 'onst&nts+
◦ =>7U@ 8uy (&r,et order Ainteger %&lue 0B#
◦ =>+<,, Sell (&r,et order Ainteger %&lue 1B#
◦ =>7U@+%= 8uy stop order Ainteger %&lue 2B#
◦ =>+<,,+%= Sell stop order Ainteger %&lue ?B#
◦ =>7U@,#8#% 8uy li(it order Ainteger %&lue B#
◦ =>+<,,,#8#% Sell li(it order Ainteger %&lue =B#
• Lots The nu(ber o) lots to tr&de# $ou '&n spe'i)y (ini lots A0#1B or (i'ro lots A0#01B i) your
bro,er supports it#
• Pri$e The pri'e &t "hi'h to open the order# 6or & buy (&r,et order this "ill be the ;sk#
6or & sell (&r,et order this "ill be the 7id# 6or pending orders this "ill be &ny %&lid pri'e
th&t is &bo%e or belo" the 'urrent pri'e#
• S"ippage The (&4i(u( slipp&ge in points# >se & su))i'iently l&rge setting "hen &uto
tr&ding# 8ro,ers th&t do not use slipp&ge "ill ignore this p&r&(eter#
• StopLoss The stop loss pri'e# 6or & buy order the stop loss pri'e is belo" the order
opening pri'e &nd )or & sell order &bo%e# I) set to 0 no stop loss "ill be used#
• Ta*eProfit The t&,e pro)it pri'e# 6or & buy order the t&,e pro)it is &bo%e the order
opening pri'e &nd )or & sell order belo"# I) set to 0 no t&,e pro)it "ill be used#
• Comment !n option&l string th&t "ill ser%e &s &n order 'o((ent# Co((ents &re sho"n
under the Trade t&b in the Ter#inal "indo"# Order 'o((ents '&n &lso be used &s &n order
identi)ier#
22
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 31/212
,rder Place#ent
• Magi$um!er !n option&l integer %&lue th&t "ill identi)y the order &s being pl&'ed by &
spe'i)i' e4pert &d%isor# It is highly re'o((ended th&t you use this#
• Expiration !n option&l e4pir&tion ti(e )or pending orders# Not &ll bro,ers &''ept tr&de
e4pir&tion ti(es )or these bro,ers &n error "ill result i) &n e4pir&tion ti(e is spe'i)ied#
• Arrow !n option&l 'olor )or the &rro" th&t "ill be dr&"n on the 'h&rt indi'&ting theopening pri'e &nd ti(e# I) no 'olor is spe'i)ied the &rro" "ill not be dr&"n#
The =rder+end() )un'tion returns the ti',et nu(ber o) the order th&t "&s ust pl&'ed# I) no order
"&s pl&'ed due to &n error 'ondition the return %&lue "ill be -#
*e '&n s&%e the order ti',et to & glob&l or st&ti' %&ri&ble )or l&ter use# I) the order "&s not pl&'ed
due to &n error 'ondition "e '&n &n&lye the error &nd t&,e &ppropri&te &'tion b&sed on the
returned error 'ode#
P"a$ing A Mar*et &rder
Here5s &n e4&(ple o) & buy (&r,et order# *e5ll &ssu(e th&t the %&ri&bles ,ot+ie +lippa!e
7u0+top,oss 7u0%akerofit &nd 8a!icumber h&%e &lre&dy been '&l'ul&ted or &ssigned &nd &re
%&lid#
rderSend(S$mbol('*<53LotSi>e?skSli&&age<u$Sto&Loss<u$Take*roit
"<u$ rder"MagicBumber9Areen';
The +0mbol() )un'tion returns the 'urrent 'h&rt sy(bol# *e "ill be pl&'ing orders on the 'urrent
'h&rt p&ir 99Q o) the ti(e# =>7U@ indi'&tes th&t this is & buy (&r,et order# ;sk is & prede)ined%&ri&ble in 3 th&t stores the (ost re'ent !s, .uote# ARe(e(ber th&t buy orders open &t the !s,
pri'eLB
The +lippa!e is set using &n e4tern&l %&ri&ble# The slipp&ge p&r&(eter is &n integer indi'&ting the
nu(ber o) points to &llo" )or pri'e slipp&ge# I) your bro,er uses digit .uotes A2 )or $en p&irsB 1
point "ould be e.u&l to 1 pip# I) your bro,er o))ers ? &nd = digit .uotes ho"e%er then 1 point "ould
be 0#1 pips# In this '&se you5d need to &dd &n &ddition&l ero to the end o) your +lippa!e setting#
*e5%e &dded the generi' 'o((ent 7u0 =rder to this order# Sin'e there is no e4pir&tion )or (&r,et
orders the E4pir&tion p&r&(eter is 0# 6in&lly "e spe'i)y the 'olor 'onst&nt Breen to dr&" & green
&rro" on the 'h&rt#
Here is &n e4&(ple o) & sell (&r,et order using the s&(e p&r&(eters &s &bo%e+
2?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 32/212
EXPERT ADVISOR PROGRAMMING
rderSend(S$mbol('=>+<,,LotSi>e7idSli&&ageSellSto&LossSellTake*roit
+ell =rderMagicBumber95ed';
*e use =>+<,, &s the order type to spe'i)y & sell (&r,et order# *e use 7id &s the order opening
pri'e to re)le't the )&'t th&t sell orders open &t the 8id pri'e# +ell =rder is our order 'o((ent
&nd "e use 5ed &s the &rro" 'olor to di))erenti&te )ro( buy orders#
P"a$ing a Pending Stop &rder
The di))eren'e bet"een pending orders &nd (&r,et orders is th&t the order opening pri'e "ill be
so(ething other th&n the 'urrent (&r,et pri'e# The stop loss &nd t&,e pro)it %&lues (ust be
'&l'ul&ted rel&ti%e to the pending order opening pri'e#
In these e4&(ples "e "ill use the %&ri&ble endin!rice )or our pending order pri'e# It '&n be
'&l'ul&ted b&sed on our tr&ding &lgorith( or it '&n be set &s &n e4tern&l p&r&(eter#
6or & buy stop order endin!rice (ust be gre&ter th&n the 'urrent !s, pri'e# *e5ll &ssu(e th&t
7u0+top,oss &nd 7u0%akerofit h&%e been 'orre'tly '&l'ul&ted rel&ti%e to endin!rice# Here5s
&n e4&(ple o) & buy stop order pl&'e(ent+
rderSend(S$mbol('=>7U@+%=LotSi>eendin!riceSli&&age<u$Sto&Loss
<u$Take*roit7u0 +top =rderMagicBumber9Areen';
Note th&t "e use =>7U@+%= to indi'&te & buy stop order &nd endin!rice )or our order opening
pri'e# No e4pir&tion ti(e h&s been indi'&ted )or this order#
6or & sell stop order endin!rice (ust be less th&n the 'urrent 8id pri'e# In this e4&(ple "e5ll
&dd &n order e4pir&tion ti(e using the %&ri&ble <xpiration# The e4pir&tion ti(e (ust be gre&ter
th&n the 'urrent ser%er ti(e# Here5s &n e4&(ple o) & sell stop order pl&'e(ent+
rderSend(S$mbol('=>+<,,+%=LotSi>e*ending*riceSli&&ageSellSto&Loss
SellTake*roit+ell +top =rderMagicBumber<xpirationKed';
P"a$ing a Pending Limit &rder
3i(it orders &re si(il&r to stop orders e4'ept th&t the pending order pri'e is re%ersed rel&ti%e to the
'urrent pri'e &nd the order type# 6or buy li(it orders the pending order pri'e (ust be less th&n the
'urrent 8id pri'e# Here5s &n e4&(ple o) & buy li(it order+
2
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 33/212
,rder Place#ent
rderSend(S$mbol('=>7U@,#8#%LotSi>e*ending*riceSli&&age<u$Sto&Loss
<u$Take*roit7u0 ,imit =rderMagicBumber9Areen';
Note th&t "e used =>7U@,#8#% to indi'&te & buy li(it order# Other"ise our p&r&(eters &re identi'&l
to those )or stop orders#
6or & sell li(it order the pending order pri'e (ust be gre&ter th&n the 'urrent !s, pri'e# Here5s &n
e4&(ple o) & sell li(it order+
rderSend(S$mbol('=>+<,,,#8#%LotSi>e*ending*riceSli&&ageSellSto&Loss
SellTake*roit+ell ,imit =rderMagicBumber/+&irationKed';
Ca"$u"ating Stop Loss ; Ta*e Profit
There &re se%er&l "&ys o) '&l'ul&ting stop loss &nd t&,e pro)it pri'es# The (ost 'o((on (ethod is tospe'i)y the nu(ber o) pips &"&y )ro( the order opening pri'e to pl&'e your stop# 6or e4&(ple i) "e
h&%e & stop loss setting o) =0 pips th&t (e&ns th&t the stop loss pri'e "ill be =0 pips &"&y )ro( our
order opening pri'e#
*e '&n &lso use &n indi'&tor %&lue &n e4tern&l p&r&(eter or so(e other type o) pri'e '&l'ul&tion# !ll
"e "ill need to do then is %eri)y th&t the stop loss or t&,e pro)it pri'e is %&lid#
Ca"$u"ating in Pips
6or this the (ost 'o((on (ethod o) '&l'ul&ting stops "e "ill use &n e4tern&l %&ri&ble in "hi'h the
user spe'i)ies the nu(ber o) pips )or the stop loss &nd t&,e pro)it# *e then '&l'ul&te the stops
rel&ti%e to the order opening pri'e#
6or buy (&r,et orders the opening pri'e "ill be the ;sk &nd )or sell (&r,et orders the opening
pri'e "ill be the 7id# 6or pending stop &nd li(it orders "e &ssign & & %&lid opening pri'e th&t is
so(ething other th&n the 'urrent (&r,et pri'e# *e "ill &ssign the &ppropri&te pri'e to the %&ri&ble
=penrice#
Here &re the e4tern&l %&ri&bles "e5ll use )or our stop loss &nd t&,e pro)it settings+
e+tern int Sto&Loss = 29;
e+tern int Take*roit = 199;
2=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 34/212
EXPERT ADVISOR PROGRAMMING
In this e4&(ple "e5%e entered & stop loss o) =0 pips &nd & t&,e pro)it o) 100 pips# $ou5%e li,ely seen
settings si(il&r to these in the E!s you5%e used#
To '&l'ul&te our stop loss "e need to &dd or subtr&'t =0 pips )ro( our order opening pri'e# 6irst "e
need to 'on%ert the integer %&lue o) =0 to the )r&'tion&l %&lue "e5ll use to &dd or subtr&'t )ro( the
opening pri'e# 6or $en p&irs =0 pips is e.u&l to 0#=0# 6or &ll other p&irs it5s 0#00=0#
To 'on%ert &n integer to the &ppropri&te )r&'tion&l %&lue "e need to (ultiply our e4tern&l +top,oss
%&ri&ble by the Point #
Point
oint is & prede)ined %&ri&ble in 3 th&t returns the s(&llest pri'e unit o) & 'urren'y depending on
the nu(ber o) de'i(&l pl&'es# 6or & de'i(&l pl&'e 'urren'y p&ir the point is 0#0001# 6or & $en p&ir
it5s 0#01#
3et5s '&l'ul&te the stop loss )or & buy (&r,et order# *e5ll &ssign the 'urrent !s, pri'e to =penrice
&nd use th&t &s our order opening pri'e# *e5ll 'he', to see i) our +top,oss setting is gre&ter th&n
ero# I) so "e5ll (ultiply the +top,oss by the oint# Then "e5ll subtr&'t th&t )ro( =penrice# The
result "ill be stored in the %&ri&ble 7u0+top,oss#
double &en*rice = ?sk;
i(Sto&Loss F 9' double <u$Sto&Loss = &en*rice (Sto&Loss . *oint';
-- 1!:@99 (29 . 9!9991' = 1!:229
I) +top,oss is not gre&ter th&n ero then 7u0+top,oss is initi&lied "ith & %&lue o) 0 &nd no stop
loss "ill be pl&'ed "ith the order# !ssu(ing th&t oint is e.u&l to 0#0001 i) the order opening pri'e
is 1#<00 &nd our stop loss is =0 pips then the stop loss pri'e )or the buy order "ill be 1#<00 -
A0#00=0B 1#==0#
Re'ently (&ny bro,ers h&%e been (o%ing to"&rds )r&'tion&l pip pri'e .uotes "ith ? de'i(&l pl&'es
)or $en p&irs &nd = de'i(&l pl&'es )or &ll other p&irs# I) our bro,er uses )r&'tion&l pip .uotes then in
our e4&(ple &bo%e oint "ould be e.u&l to 0#00001#
I) "e use & point %&lue o) 0#00001 in our stop loss '&l'ul&tion e4&(ple &bo%e the stop loss "ould be'&l'ul&ted &s = pips )ro( the opening pri'e inste&d o) =0 pips# This poses & proble(# To get the
'orre't %&lue "e "ould h&%e to &dd &n e4tr& ero to our stop loss setting i$e$ +top,oss =00#
Inste&d o) re.uiring the user to &dd &n &ddition&l ero to their stop loss &nd t&,e pro)it settings e%ery
ti(e they tr&de on & )r&'tion pip bro,er "e5ll 're&te & )un'tion th&t "ill &l"&ys return 0#01 or 0#0001
2<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 35/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 36/212
EXPERT ADVISOR PROGRAMMING
This )un'tion "ill &uto(&ti'&lly set the slipp&ge p&r&(eter to the nu(ber o) pips spe'i)ied by the
e4tern&l +lippa!e p&r&(eter+
int AetSli&&age(string Currenc$ int Sli&&age*i&s'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == :' double CalcSli&&age = Sli&&age*i&s;
else i(Calc6igits == 8 77 Calc6igits == 2' CalcSli&&age = Sli&&age*i&s . 19;
return(CalcSli&&age';
,
*e p&ss the 'urren'y sy(bol &nd the e4tern&l slipp&ge p&r&(eter &s &rgu(ents# I) the 'urren'y uses
2 or digit .uotes "e use the un'h&nged +lippa!eips &rgu(ent &s our slipp&ge setting# I) the
'urren'y uses ? or = digit .uotes "e (ultiply +lippa!eips by 10# Here is ho" "e use this )un'tion
in =rder+end()+
-- /+ternal &arameterse+tern int Sli&&age = 2;
-- rder &lacement
rderSend(S$mbol('*<53LotSi>e?skBet+lippa!e(+0mbol()D+lippa!e)<u$Sto&Loss
<u$Take*roit"<u$ rder"MagicBumber9Areen';
The slipp&ge in this e4&(ple "ill be = pips &nd the slipp&ge p&r&(eter "ill be &uto(&ti'&lly &dusted
b&sed on the nu(ber o) digits in the 'urren'y .uote#
S"ippage and Point as 9"o!a" 7aria!"es
The dis&d%&nt&ge o) using & )un'tion to return the point or slipp&ge %&lue is the e4tr& typing re.uired
)or the )un'tion &rgu(ents# *e5ll 're&te glob&l %&ri&bles th&t "ill hold the &ppropri&te point &nd
slipp&ge %&lues )or our 'urren'y p&ir &nd "e5ll use those &nyti(e "e need to re)eren'e those %&lues#
Sin'e these %&lues "ill ne%er 'h&nge during progr&( e4e'ution "e5ll '&l'ul&te these %&lues in the
init() )un'tion# *e5ll &ssu(e th&t the e4tern&l integer %&ri&ble +lippa!e is &lre&dy present+
-- Alobal 0ariables
double 5se*oint;
int 5seSli&&age;
int init('
)
5se*oint = *i&*oint(S$mbol('';
5seSli&&age = AetSli&&age(S$mbol('Sli&&age';
,
2;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 37/212
,rder Place#ent
6ro( no" on "e5ll use Useoint &nd Use+lippa!e to re)er to these %&lues# The &bo%e 'ode
&ssu(es th&t your E! is pl&'ing orders on one 'urren'y only# This "ill be the '&se 9;Q o) the ti(e
but i) you5re 're&ting &n e4pert &d%isor th&t pl&'es orders on (ultiple 'urren'ies Aor on & 'urren'y
other th&n the 'urrent 'h&rtB you5ll need to use the ipoint() &nd Bet+lippa!e() )un'tions e%ery
ti(e you need to '&l'ul&te these %&lues#
Mar*et#nfo<=
*e used the 8arket#nfo() )un'tion &bo%e to retrie%e the Point %&lue &nd the nu(ber o) digits in the
'urren'y .uote# The 8arket#nfo() )un'tion h&s (&ny uses &nd you "ill be using it to retrie%e
ne'ess&ry pri'e in)or(&tion in your progr&(s# Here is the synt&4 )or the 8arket#nfo() )un'tion+
double MarketIno(string Symbol int "e#uestType';
The +0mbol &rgu(ent is si(ply the 'urren'y sy(bol th&t you "&nt to retrie%ing the in)or(&tion )or#
6or the 'urrent 'h&rt sy(bol the +0mbol() )un'tion '&n be used# 6or other sy(bols you5ll need to
spe'i)y the 'urren'y sy(bol su'h &s <U5E@#
5equest%0pe is &n integer 'onst&nt representing the in)or(&tion th&t you &re re.uesting )ro( the
)un'tion# Here5s & list o) the (ost use)ul 8arket#nfo() 'onst&nts# ! 'o(plete list '&n be )ound in the
3 Re)eren'e under tandard "onstants - Mar*etInfo#
• 8=6<>=#% The point %&lue# 6or e4&(ple 0#01 or 0#00001#
• 8=6<>6#B#%+ The nu(ber o) de'i(&l pl&'es in the pri'e# *ill be 2 or ? )or $en p&irs &nd
or = )or &ll other p&irs#
• 8=6<>+5<;6 The 'urrent spre&d# 6or e4&(ple ? pips Aor ?0 )or & )r&'tion&l pip bro,erB#
• 8=6<>+%=,<9<, The stop le%el# 6or e4&(ple ? pips Aor ?0 )or & )r&'tion&l pip bro,erB#
These re.uest identi)iers &re gener&lly used "hen 'he',ing pri'e in)or(&tion on ¬her 'urren'y or
&ny"here "here the sy(bol (&y be &nything other th&n the 'urrent 'h&rt sy(bol+
• 8=6<>7#6 The 'urrent bid pri'e o) the sele'ted sy(bol#
• 8=6<>;+F The 'urrent &s, pri'e o) the sele'ted sy(bol#
• 8=6<>,=G The lo" o) the 'urrent b&r o) the sele'ted sy(bol#
• 8=6<>?#B? The high o) the 'urrent b&r o) the sele'ted sy(bol#
29
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 38/212
EXPERT ADVISOR PROGRAMMING
Ca"$u"ating t+e Stop Loss
No" th&t "e5%e deter(ined the proper point %&lue it5s ti(e to '&l'ul&te our stop loss# 6or buy orders
the stop loss "ill be belo" the order opening pri'e &nd )or sell orders the stop loss "ill be &bo%e the
order opening pri'e#
Here5s our buy order stop loss '&l'ul&tion )ro( e&rlier "ith the Useoint %&ri&ble &dded# Note th&t
"e5%e &ssigned the ;sk pri'e to the =penrice %&ri&ble+
double &en*rice = ?sk;
i(Sto&Loss F 9' double <u$Sto&Loss = &en*rice (Sto&Loss . Useoint';
!nd here5s the '&l'ul&tion )or & sell order# Note th&t "e5%e &ssigned the 7id pri'e to =penrice &nd
th&t "e &re si(ply &dding inste&d o) subtr&'ting+
double &en*rice = <id;
i(Sto&Loss F 9' double SellSto&Loss = &en*rice H (Sto&Loss . Useoint';
6or pending orders the stop loss "ill be '&l'ul&ted rel&ti%e to the pending order pri'e# In this '&se
use the %&ri&ble =penrice to store the pending order pri'e inste&d o) the 'urrent (&r,et pri'e# The
logi' "ill be identi'&l to the e4&(ples &bo%e#
Ca"$u"ating t+e Ta*e Profit
C&l'ul&ting the t&,e pro)it pri'e is si(il&r to '&l'ul&ting the stop loss e4'ept "e5ll be re%ersing
&ddition &nd subtr&'tion# 6or & buy order the t&,e pro)it pri'e "ill be &bo%e the order opening pri'e
&nd )or & sell order the t&,e pro)it pri'e "ill be belo" the order opening pri'e# *e5ll &ssu(e th&t the
&ppropri&te pri'e h&s been &ssigned to =penrice+
i(Take*roit F 9' double <u$Take*roit = &en*rice N (Take*roit . Useoint';
i(Take*roit F 9' double SellTake*roit = &en*rice (Take*roit . Useoint';
A"ternate Stop Loss Met+ods
There &re other "&ys o) deter(ining stop loss &nd t&,e pro)it pri'es# 6or e4&(ple & re'ent high or
lo" or &n indi'&tor %&lue 'ould be used to deter(ine & stop loss# 3et5s de(onstr&te ho" "e 'ould
'&l'ul&te these#
?0
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 39/212
,rder Place#ent
3et5s s&y "e5re using & tr&ding syste( th&t pl&'es the stop loss 2 pips belo" the lo" o) the 'urrent
b&r# *e use the prede)ined pri'e &rr&y ,owIJ to retrie%e the lo" o) & b&r# ,owI2J is the lo" o) the
'urrent b&r ,owIJ is the lo" o) the pre%ious b&r &nd so on#
On'e "e5%e deter(ined the lo" o) the 'urrent b&r "e (ultiply 2 by Useoint to get & de'i(&l %&lue
&nd subtr&'t th&t )ro( our lo"+
double <u$Sto&Loss = Lo%[9] (4 . Useoint';
So i) the lo" o) the b&r is 1#:<0 the stop loss "ill be pl&'ed &t 1#:=;#
8ut (&ybe you "&nt to pl&'e your stop loss &t the lo"est lo" o) the l&st 4 nu(ber o) b&rs# There5s &
)un'tion built into et&Tr&der ust )or th&t# i,owest() returns the shi)t %&lue indi'&ting the b&r "ith
the lo"est %&lue in & spe'i)ied ti(e r&nge# *e '&n use high lo" open or 'lose %&lues#
Here5s &n e4&(ple o) ho" "e "ould use i,owest() to )ind the lo"est lo" o) the l&st 10 b&rs+
int Count<ars = 19;
int Lo%estShit = iLo%est(B5LL9M6/LOCount<ars9';
double <u$Sto&Loss = Lo%[Lo%estShit];
The )irst p&r&(eter o) i,owest() is the 'urren'y sy(bol U,, (e&ns th&t "e5re using the 'urrent
sy(bol# &ny )un'tions in 3 use the string 'onst&nt U,, to re)er to the 'urrent 'h&rt sy(bol# The
se'ond p&r&(eter is the 'h&rt period 2 re)ers to the 'urrent 'h&rt )r&(e#
8=6<>,=G is &n integer 'onst&nt th&t spe'i)ies the lo" pri'e series &rr&y# In other "ords "e5re
loo,ing )or the lo"est lo" o) the l&st Count7ars# I) "e "&nted to )ind the lo"est 'lose )or e4&(ple
"e "ould use 8=6<>C,=+<# $ou '&n )ind &ll o) the series &rr&y 'onst&nts in the 3 Re)eren'e under
tandard "onstants - eries Arrays#
Count7ars is the nu(ber o) b&rs "e "&nt to se&r'h in this '&se 10# 6in&lly the l&st p&r&(eter is our
st&rting lo'&tion# 0 is the 'urrent b&r# To st&rt &t & pre%ious b&r 'ount b&',"&rd )ro( the 'urrent b&r
the pre%ious b&r is 1 the b&r be)ore th&t is 2 et'#
The output o) the i,owest() )un'tion is &n integer indi'&ting the b&',"&rd shi)t o) the b&r "ith the
lo"est %&lue in the pri'e series# In the e4&(ple &bo%e i) i,owest() returns & < th&t (e&ns th&t the
lo"est lo" is < b&rs b&',# *e store th&t %&lue in the %&ri&ble ,owest+hift# To )ind the &'tu&l pri'e
"e si(ply retrie%e the pri'e %&lue o) ,owI,owest+hiftJ or in other "ords ,owIKJ#
?1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 40/212
EXPERT ADVISOR PROGRAMMING
I) you "&nted to '&l'ul&te & stop loss )or & sell order using this (ethod the i?i!hest() )un'tion
"or,s the s&(e "&y# Re)eren'ing the e4&(ple &bo%e you "ould use 8=6<>?#B? )or your series &rr&y
p&r&(eter#
Here5s &n e4&(ple using &n indi'&tor# 3et5s s&y "e h&%e & (o%ing &%er&ge &nd "e "&nt to use the
(o%ing &%er&ge line &s our stop loss# *e5ll use the %&ri&ble 8; to represent the (o%ing &%er&ge %&lue)or the 'urrent b&r# !ll you need to do is &ssign the 'urrent (o%ing &%er&ge %&lue to the stop loss+
double <u$Sto&Loss = M?;
I) the (o%ing &%er&ge line is 'urrently &t 1#<;9 then th&t "ill be our stop loss#
These &re si(ply the (ost 'o((on (ethods o) deter(ining & stop loss or t&,e pro)it pri'e# Other
(ethods '&n be de%eloped using your ,no"ledge o) te'hni'&l &n&lysis or your i(&gin&tion#
Retrieving &rder #nformation
On'e "e5%e su''ess)ully pl&'ed &n order "e5ll need to retrie%e so(e in)or(&tion &bout the order i)
"e "&nt to (odi)y or 'lose it# *e do this using the =rder+elect() )un'tion# To use =rder+elect()
"e '&n either use the ti',et nu(ber o) the order or "e '&n loop through the pool o) open orders &nd
sele't e&'h o) the( in order#
On'e "e5%e sele'ted &n order using =rder+elect() "e '&n use & %&riety o) order in)or(&tion
)un'tions to return in)or(&tion &bout the order in'luding the 'urrent stop loss t&,e pro)it order
opening pri'e 'losing pri'e &nd (ore#
&rderSe"e$t<=
Here is the synt&4 )or the =rder+electAB )un'tion+
bool rderSelect(int $ndex int Select int Pool = M6/TK?6/S'
• #ndex This is either the ti',et nu(ber o) the order th&t "e "&nt to sele't or the position
in the order pool# The +elect p&r&(eter "ill indi'&te "hi'h o) these "e &re using#
• Se"e$t ! 'onst&nt indi'&ting "hether the #ndex p&r&(eter is & ti',et nu(ber or &n order
pool position+
◦ +<,<C%>7@>%#CF<% The %&lue o) the #ndex p&r&(eter is &n order ti',et nu(ber#
◦ +<,<C%>7@>=+ The %&lue o) the #ndex p&r&(eter is &n order pool position#
?2
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 41/212
,rder Place#ent
• Poo" !n option&l 'onst&nt indi'&ting the order pool+ pending7open orders or 'losed orders#
◦ 8=6<>%5;6<+ 8y de)&ult "e &re e4&(ining the pool o) 'urrently opened orders#
◦ 8=6<>?#+%=5@ E4&(ines the 'losed order pool Athe order historyB#
I) the =rder+elect() )un'tion lo'&tes the order su''ess)ully the return %&lue "ill be trueother"ise the return %&lue "ill be false#
Here5s &n e4&(ple o) the =rder+electAB )un'tion using &n order ti',et nu(ber# The %icket %&ri&ble
should 'ont&in & %&lid order ti',et+
rderSelect(TicketS/L/CT<3TICP/T';
!)ter the =rder+electAB )un'tion h&s been '&lled "e '&n use &ny o) the order in)or(&tion )un'tions
to retrie%e in)or(&tion &bout th&t order# ! 'o(plete listing o) )un'tions th&t '&n be used "ith
=rder+electAB '&n be )ound in the 3 Re)eren'e under Trading Functions# Here5s & list o) the (ost'o((only used order in)or(&tion )un'tions+
• =rder+0mbol() The sy(bol o) the instru(ent th&t the sele'ted order "&s pl&'ed on.
• =rder%0pe() - The order type o) the sele'ted order+ buy or sell (&r,et stop or li(it# The
return %&lue is &n integer 'orresponding to the order type 'onst&nts on p&ge 22#
• =rder=penrice() The opening pri'e o) the sele'ted order#
• =rder,ots() The lot sie o) the sele'ted order#
• =rder+top,oss() The stop loss pri'e o) the sele'ted order#
• =rder%akerofit() The t&,e pro)it pri'e o) the sele'ted order#
• =rder%icket() The ti',et nu(ber o) the sele'ted order# Gener&lly used "hen 'y'ling
through the order pool "ith the +<,<C%>7@>=+ p&r&(eter#
• =rder8a!icumber() The (&gi' nu(ber o) the sele'ted order# *hen 'y'ling through
orders you5ll need to use this to identi)y orders pl&'ed by your E!#
• =rderComment() The 'o((ent th&t "&s pl&'ed "ith the order# This '&n be used &s &
se'ond&ry order identi)ier#
• =rderCloserice() The 'losing pri'e o) the sele'ted order# The order (ust &lre&dy be
'losed Ai$e$ present in the order history poolB#
• =rder=pen%ime() The opening ti(e o) the sele'ted order#
• =rderClose%ime() The 'losing ti(e o) the sele'ted order#
??
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 42/212
EXPERT ADVISOR PROGRAMMING
• =rderrofit() Returns the pro)it Ain the deposit 'urren'yB )or the sele'ted order#
*e5ll need to use =rder+elect() be)ore 'losing or (odi)ying &n order# 3et5s illustr&te ho" "e use
=rder+elect() to 'lose &n order#
C"osing &rders
*hen "e 'lose & (&r,et order "e &re e4iting the tr&de &t the 'urrent (&r,et pri'e# 6or buy orders
"e 'lose &t the 8id pri'e &nd )or sell orders "e 'lose &t the !s,# 6or pending orders "e si(ply
delete the order )ro( the tr&de pool#
&rderC"ose<=
*e 'lose (&r,et orders using the =rderClose() )un'tion# Here is the synt&4+
bool rderClose(int Ticket double Lots double Price int Slippage color rro! ';
• Ti$*et The ti',et nu(ber o) the (&r,et order to 'lose#
• Lots The nu(ber o) lots to 'lose# ost bro,ers &llo" p&rti&l 'loses#
• Pri$e The pre)erred pri'e &t "hi'h to 'lose the tr&de# 6or buy orders this "ill be the
'urrent 8id pri'e &nd )or sell orders the 'urrent !s, pri'e#
• S"ippage The &llo"ed slipp&ge )ro( the 'losing pri'e in pips#
• Co"or ! 'olor 'onst&nt )or the 'losing &rro"# I) no 'olor is indi'&ted no &rro" "ill be
dr&"n#
$ou '&n 'lose p&rt o) & tr&de by spe'i)ying & p&rti&l lot sie# 6or e4&(ple i) you h&%e & tr&de open
"ith & lot sie o) 2#00 &nd you "&nt to 'lose h&l) o) the tr&de then spe'i)y 1 lot )or the ,ots
&rgu(ent# Note th&t not &ll bro,ers support p&rti&l 'loses#
It is re'o((ended th&t i) you need to 'lose & position in se%er&l p&rts you should pl&'e (ultiple
orders inste&d o) doing p&rti&l 'loses# >sing the e4&(ple &bo%e you "ould pl&'e t"o orders o) 1#00
lot e&'h then si(ply 'lose one o) the orders "hen you "&nt to 'lose out h&l) o) the position# In this
boo, "e "ill &l"&ys be 'losing out the )ull order#
The )ollo"ing e4&(ple 'loses & buy (&r,et order+
rderSelect(CloseTicketS/L/CT<3TICP/T';
?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 43/212
,rder Place#ent
i(rderCloseTime(' == 9 QQ rderT$&e(' == *<53'
)
double CloseLots = rderLots(';
double Close*rice = <id;
bool Closed = rderClose(CloseTicketCloseLotsClose*rice5seSli&&ageKed';
,
The Close%icket %&ri&ble is the ti',et nu(ber o) the order "e "ish to 'lose# The =rder+elect()
)un'tion sele'ts the order &nd &llo"s us to retrie%e the order in)or(&tion# *e use
=rderClose%ime() to 'he', the order 'losing ti(e to see i) the order h&s &lre&dy been 'losed# I)
=rderClose%ime() returns 0 then "e ,no" the order h&s not been 'losed yet#
*e &lso need to 'he', the order type sin'e the order type deter(ines the 'losing pri'e )or the order#
The =rder%0pe() )un'tion returns &n integer indi'&ting the order type# I) it5s & buy (&r,et order
indi'&ted by =>7U@ "e5ll 'ontinue 'losing the order#
Ne4t "e retrie%e the order lot sie using =rder,ots() &nd store th&t %&lue in Close,ots# *e
&ssign the 'urrent 7id pri'e to Closerice# Then "e '&ll the =rderClose() )un'tion to 'lose out
our order#
*e spe'i)y our Slipp&ge setting "ith Use+lippa!e &nd indi'&te & 5ed &rro" to be printed on the
'h&rt# ! boole&n return %&lue is stored in the %&ri&ble Closed# I) the order h&s been 'losed
su''ess)ully the %&lue o) Closed "ill be true other"ise false#
To 'lose & sell (&r,et order &ll you need to do is 'h&nge the order type to =>+<,, &nd &ssign the
'urrent ;sk pri'e to Closerice+
i(rderCloseTime(' == 9 QQ rderT$&e(' == =>+<,,'
)
double CloseLots = rderLots(';
double Close*rice = ;sk;
bool Closed = rderClose(CloseTicketCloseLotsClose*rice5seSli&&ageKed';
,
&rder0e"ete<=There is & sep&r&te )un'tion )or 'losing pending orders# =rder6elete() h&s t"o &rgu(ents the
ti',et nu(ber &nd the &rro" 'olor# No 'losing pri'e lot sie or slipp&ge is re.uired# Here is the 'ode
to 'lose & pending buy stop order+
?=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 44/212
EXPERT ADVISOR PROGRAMMING
rderSelect(CloseTicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9 QQ rderT$&e(' == =>7U@+%='
)
bool 6eleted L =rder6elete(Close%icketD5ed)M
,
!s "e did "ith the =rderClose() )un'tion &bo%e "e need to 'he', the order type to be sure it is &
pending order# The pending order type 'onst&nts &re =>7U@+%= =>+<,,+%= =>7U@,#8#% &nd
=>+<,,,#8#%# To 'lose other types o) pending orders si(ply 'h&nge the order type#
I) the order h&s been )illed then it is no" & (&r,et order &nd (ust be 'losed using =rderClose()
inste&d#
A Simp"e Expert Advisor
3et5s see ho" the 'ode "e5%e dis'ussed so )&r "ould "or, in &n e4pert &d%isor# This is & si(ple
(o%ing &%er&ge 'ross syste(# ! buy order is opened "hen the 10 period (o%ing &%er&ge is gre&ter
th&n the 20 period (o%ing &%er&ge# *hen the 10 period (o%ing &%er&ge is less th&n the 20 period
(o%ing &%er&ge & sell order is opened#
This E! "ill <ern&te bet"een opening buy &nd sell orders# Orders "ill be 'losed "hen &n order is
opened in the opposite dire'tion or by stop loss or t&,e pro)it# *e "ill use the glob&l %&ri&bles
7u0%icket &nd +ell%icket to store the l&st order ti',et# *hen & ne" order is opened the l&st
order ti',et is 'le&red# This pre%ents (ultiple 'onse'uti%e orders )ro( opening#
&ro&ert$ co&$right "?ndre% 3oung"
-- /+ternal 0ariables
e+tern double LotSi>e = 9!1;
e+tern double Sto&Loss = 29;
e+tern double Take*roit = 199;
e+tern int Sli&&age = 2;
e+tern int MagicBumber = 148;
e+tern int #astM?*eriod = 19;
e+tern int Slo%M?*eriod = 49;
-- Alobal 0ariables
int <u$Ticket;
int SellTicket;
?<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 45/212
,rder Place#ent
double 5se*oint;
int 5seSli&&age;
-- Init unction
int init('
)
5se*oint = *i&*oint(S$mbol(''; 5seSli&&age = AetSli&&age(S$mbol('Sli&&age';
,
-- Start unction
int start('
)
-- Mo0ing a0erages
double #astM? = iM?(B5LL9#astM?*eriod9999';
double Slo%M? = iM?(B5LL9Slo%M?*eriod9999';
-- <u$ order
i(#astM? F Slo%M? QQ <u$Ticket == 9'
)
rderSelect(SellTicketS/L/CT<3TICP/T';
-- Close order
i(rderCloseTime(' == 9 QQ SellTicket F 9'
)
double CloseLots = rderLots(';
double Close*rice = ?sk;
bool Closed = rderClose(SellTicketCloseLotsClose*rice5seSli&&ageKed';
,
double &en*rice = ?sk;
-- Calculate sto& loss and take &roit
i(Sto&Loss F 9' double <u$Sto&Loss = &en*rice (Sto&Loss . 5se*oint';
i(Take*roit F 9' double <u$Take*roit = &en*rice N (Take*roit . 5se*oint';
-- &en bu$ order
<u$Ticket = rderSend(S$mbol('*<53LotSi>e&en*rice5seSli&&age
<u$Sto&Loss<u$Take*roit"<u$ rder"MagicBumber9Areen';
SellTicket = 9;
,
-- Sell rder
i(#astM? D Slo%M? QQ SellTicket == 9'
)
rderSelect(<u$TicketS/L/CT<3TICP/T';
?:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 46/212
EXPERT ADVISOR PROGRAMMING
i(rderCloseTime(' == 9 QQ <u$Ticket F 9'
)
CloseLots = rderLots(';
Close*rice = <id;
Closed = rderClose(<u$TicketCloseLotsClose*rice5seSli&&ageKed';
,
&en*rice = <id;
i(Sto&Loss F 9' double SellSto&Loss = &en*rice N (Sto&Loss . 5se*oint';
i(Take*roit F 9' double SellTake*roit = &en*rice (Take*roit . 5se*oint';
SellTicket = rderSend(S$mbol('*S/LLLotSi>e&en*rice5seSli&&age
SellSto&LossSellTake*roit"Sell rder"MagicBumber9Ked';
<u$Ticket = 9;
,
return(9';
,
-- *i& *oint #unction
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == 8' double Calc*oint = 9!91;
else i(Calc6igits == : 77 Calc6igits == 2' Calc*oint = 9!9991;
return(Calc*oint';
,
-- Aet Sli&&age #unction
int AetSli&&age(string Currenc$ int Sli&&age*i&s'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == :' double CalcSli&&age = Sli&&age*i&s;
else i(Calc6igits == 8 77 Calc6igits == 2' CalcSli&&age = Sli&&age*i&s . 19;
return(CalcSli&&age';
,
*e st&rt "ith our Apropert0 cop0ri!ht prepro'essor dire'ti%e th&t identi)ies the 'ode &s belonging
to us# The e4tern&l %&ri&bles &re ne4t &nd should be sel)-e4pl&n&tory# *e de'l&re 7u0%icket &nd+ell%icket &s glob&l %&ri&bles this "&y the order ti',et is stored bet"een progr&( e4e'utions# *e
'ould &lso h&%e de'l&red the( &s static %&ri&bles "ithin the start() )un'tion#
*e &dd Useoint &nd Use+lippa!e &s glob&l %&ri&bles "e5ll '&l'ul&te the %&lue o) these ne4t# Our
init() )un'tion is run )irst# *e '&ll the ipoint() &nd Bet+lippa!e() )un'tions Ade'l&red &t the
?;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 47/212
,rder Place#ent
botto( o) the )ileB &nd &ssign the return %&lues to our glob&l %&ri&bles# *e5ll use these "hen
re)eren'ing point or slipp&ge %&lues in the rest o) our e4pert &d%isor#
Ne4t is the start() )un'tion our (&in progr&( e4e'ution# *e5%e le)t out deinit() sin'e "e h&%e
no use )or it here# The i8;() )un'tion '&l'ul&tes the (o%ing &%er&ge The "ast8; %&ri&ble holds our
10 period (o%ing &%er&ge "hi'h is set using the "ast8;eriod %&ri&ble# The +low8; %&ri&ble is our20 period (o%ing &%er&ge set using +low8;eriod. E%erything else is set to de)&ult A& no shi)t
si(ple (o%ing &%er&ge '&l'ul&ted on the 'lose pri'eB#
*e use the if oper&tor to de)ine our order opening 'onditions# I) the 'urrent 10 period (o%ing
&%er&ge Athe "ast8;B is gre&ter th&n the 20 period (o%ing &%er&ge Athe +low8;B &nd i) 7u0%icket
is e.u&l to 0 "e "ill open & buy order#
8e)ore "e open the buy order "e "ill 'lose the 'urrent sell order i) it e4ists# *e use =rder+elect()
to retrie%e the 'urrent +ell%icket# I) the order 'lose ti(e is 0 Aindi'&ting th&t the order h&s not yet
been 'losedB &nd the +ell%icket is gre&ter th&n 0 Aindi'&ting th&t the +ell%icket is li,ely %&lidB"e "ill go &he&d &nd 'lose the sell order# *e retrie%e the lot sie o) the sell order &nd the 'urrent
;sk pri'e "hi'h "ill be the 'losing pri'e )or the sell order# Then "e 'lose the sell order using
=rderClose()#
Ne4t "e &ssign the 'urrent ;sk pri'e to the =penrice %&ri&ble this "ill be the opening pri'e o)
our buy order# *e '&l'ul&te our stop loss &nd t&,e pro)it rel&ti%e to the opening pri'e 'he',ing )irst
to (&,e sure th&t "e h&%e spe'i)ied & +top,oss or %akerofit %&lue in the settings# Then "e pl&'e
the order using the =rder+end() )un'tion &nd store the order ti',et in 7u0%icket# 3&stly "e 'le&r
the %&lue o) +ell%icket &llo"ing the pl&'e(ent o) ¬her sell order "hen the order 'ondition
be'o(es %&lid#
The sell order blo', )ollo"s the s&(e logi' &s the buy order blo',# *e 'lose the buy order )irst &nd
use the 7id &s the =penrice &nd the buy order Closerice# The stop loss &nd t&,e pro)it
'&l'ul&tions &re re%ersed#
The start() )un'tion ends "ith & return oper&tor# Our 'usto( ipoint() &nd Bet+lippa!e()
)un'tions &re de)ined &t the end &)ter the start() )un'tion# *e "ill in'lude these )un'tions in e%ery
e4&(ple in this boo,#
5sing Pending &rders
3et5s (odi)y our E! to use pending orders# *e5ll use stop orders in this e4&(ple# *hen the )&st
(o%ing &%er&ge is gre&ter th&n the slo" (o%ing &%er&ge "e "ill pl&'e & buy stop order 10 pips
?9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 48/212
EXPERT ADVISOR PROGRAMMING
&bo%e the 'urrent high# *hen the opposite is true "e5ll pl&'e & sell stop order 10 pips belo" the
'urrent lo"# 3et5s de'l&re &n e4tern&l %&ri&ble to &dust this setting '&lled endin!ips#
e+tern int *ending*i&s = 19;
*e5re &dding the =rder6elete() )un'tion to our buy &nd sell order blo', to 'lose &ny un)illed
pending orders# *e need to 'he', the order type o) the order indi'&ted by +ell%icket to ensure
th&t "e &re using the 'orre't )un'tion to 'lose the order#
rderSelect(SellTicketS/L/CT<3TICP/T';
-- Close rder
i(rderCloseTime(' == 9 QQ SellTicket F 9 NN =rder%0pe() LL =>+<,,'
)
double CloseLots = rderLots(';
double Close*rice = ?sk;
bool Closed = rderClose(SellTicketCloseLotsClose*rice5seSli&&ageKed';
i(Closed == true' SellTicket = 9;
,
-- 6elete rder
else i(rderCloseTime(' == 9 QQ SellTicket F 9 NN =rder%0pe() LL =>+<,,+%=)
&
bool 6eleted L =rder6elete(+ell%icketD5ed)M
if(6eleted LL true) +ell%icket L 2M
'
*e use =rder%0pe() to 'he', "hether the sele'ted sell order is & (&r,et order or & stop order# I)it5s & (&r,et order "e 'lose it using =rderClose()# I) it5s & pending order "e 'lose it using
=rder6elete()#
Here5s our pending order pri'e '&l'ul&tion# *e si(ply 'on%ert endin!ips to & )r&'tion&l %&lue "ith
Useoint &nd &dd it to the 'urrent Close pri'e# *e5ll store this %&lue in the endin!rice %&ri&ble#
Ne4t "e '&l'ul&te the stop loss &nd t&,e pro)it rel&ti%e to our pending order pri'e# 6in&lly "e pl&'e
our pending order using =rder+end() storing the tr&de result in the %&ri&ble 7u0%icket+
double endin!rice L CloseI2J H (endin!ips * Useoint)M
i(Sto&Loss F 9' double <u$Sto&Loss = endin!rice (Sto&Loss . 5se*oint';
i(Take*roit F 9' double <u$Take*roit = endin!rice N (Take*roit . 5se*oint';
7u0%icket = rderSend(S$mbol('=>7U@+%=LotSi>eendin!rice5seSli&&age
<u$Sto&Loss<u$Take*roit"<u$ Sto& rder"MagicBumber9Areen';
0
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 49/212
,rder Place#ent
SellTicket = 9;
The 'ode belo" sho"s the 'h&nges )or the sell stop order blo',+
rderSelect(7u0%icketS/L/CT<3TICP/T';
-- Close rder
i(rderCloseTime(' == 9 QQ <u$Ticket F 9 QQ rderT$&e(' == =>7U@'
)
CloseLots = rderLots(';
Close*rice = 7id;
Closed = rderClose(7u0%icketCloseLotsClose*rice5seSli&&ageKed';
i(Closed == true' 7u0%icket = 9;
,
-- 6elete rder
else i(rderCloseTime(' == 9 QQ <u$Ticket F 9 QQ rderT$&e(' == =>7U@+%='
)Closed = rder6elete(7u0%icketKed';
i(Closed == true' 7u0%icket = 9;
,
*ending*rice = Close[9] - (*ending*i&s . 5se*oint';
double +ell+top,oss = *ending*rice H (Sto&Loss . 5se*oint';
double +ell%akerofit = *ending*rice - (Take*roit . 5se*oint';
+ell%icket = rderSend(S$mbol('=>+<,,+%=LotSi>e*ending*rice5seSli&&age
SellSto&LossSellTake*roit"Sell Sto& rder"MagicBumber9Ked';
<u$Ticket = 9;
The 'o(plete 'ode )or both o) these e4pert &d%isors is in !ppendi4 !#
1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 50/212
EXPERT ADVISOR PROGRAMMING
C+apter 8 Advan$ed &rder P"a$ement
EC Compati!i"ity
!s the order pl&'e(ent e4&(ples in the l&st 'h&pter sho" the de)&ult (ethod o) pl&'ing & stop loss
&nd t&,e pro)it "ith & (&r,et order is to pl&'e the( using the =rder+end() )un'tion# *hile this
"or,s "ell )or (ost bro,ers the ne"er ECN7STP bro,ers th&t use et&Tr&der don5t support this
beh&%ior#
In this '&se "e5ll need to pl&'e the stop loss &nd t&,e pro)it &)ter the order h&s been pl&'ed using
the =rder8odif0() )un'tion# This only &pplies to (&r,et orders )or pending orders you '&n still
pl&'e the stop loss &nd t&,e pro)it "ith the =rder+end() )un'tion#
&rder Modifi$ation
!)ter pl&'ing &n order you '&n (odi)y the t&,e pro)it stop loss pending order pri'e or e4pir&tion
ti(e using the =rder8odif0() )un'tion# To use =rder8odif0() "e5ll need the ti',et nu(ber o) the
order th&t "e "ish to (odi)y# Here is the synt&4 )or the =rder8odif0() )un'tion+
bool rderModi$(int Ticket double Price double StopLoss double TakeProfit
datetime Expiration color rro! = CLKBB/'
• Ti$*et The ti',et nu(ber o) the order to (odi)y#
• Pri$e The ne" pending order pri'e#
• StopLoss The ne" stop loss pri'e#
• Ta*eProfit The ne" t&,e pro)it pri'e#
• Expiration The ne" e4pir&tion ti(e )or pending orders#
• Arrow ! option&l 'olor )or the &rro" to indi'&te & (odi)ied order# I) not indi'&ted no
&rro" "ill be displ&yed#
I) the order (odi)i'&tion is su''ess)ul =rder8odif0() "ill return & boole&n %&lue o) true# I) the
order (odi)i'&tion )&iled the return %&lue "ill be false#
2
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 51/212
Advanced ,rder Place#ent
*hen (odi)ying orders "e (ust be sure th&t the %&lues "e &re p&ssing to the )un'tion &re %&lid# 6or
e4&(ple the order (ust still be open "e '&nnot (odi)y & 'losed order# *hen (odi)ying pending
orders "ith the rice p&r&(eter the order (ust not h&%e &lre&dy been )illed i$e$ hit its order pri'e#
The (odi)ied order pri'e &lso (ust not be too 'lose to the 'urrent 8id or !s, pri'e# *e should &lso
'he', to (&,e sure th&t the stop loss &nd t&,e pro)it &re %&lid# *e '&n do this using the pri'e%eri)i'&tion routines th&t "e "ill 'o%er l&ter in this 'h&pter#
I) "e &re not (odi)ying & p&rti'ul&r p&r&(eter "e (ust p&ss the origin&l %&lue to the
=rder8odif0() )un'tion# 6or e4&(ple i) "e &re (odi)ying only the stop loss )or & pending order
then "e (ust retrie%e the 'urrent order pri'e &nd t&,e pro)it using =rder+elect() &nd p&ss those
%&lues to the =rder8odif0() )un'tion#
I) you &tte(pt to (odi)y &n order "ithout spe'i)ying &ny 'h&nged %&lues you5ll get &n error 1+ /no
result/# $ou should %eri)y "hy your 'ode is p&ssing un'h&nged %&lues to the )un'tion but other"ise
this error is h&r(less &nd '&n be s&)ely ignored#
Adding Stop Loss and Ta*e Profit to an Existing &rder
6irst "e need to %eri)y th&t the order h&s been pl&'ed 'orre'tly# *e do this by e4&(ining the return
%&lue o) the =rder+end() )un'tion "hi'h is the ti',et nu(ber o) the order th&t "&s ust pl&'ed# I)
the order "&s not pl&'ed due to &n error 'ondition the ti',et nu(ber "ill be e.u&l to -#
Ne4t "e use the =rder+elect() )un'tion to retrie%e the in)or(&tion )or the order th&t "&s ust
pl&'ed# *e "ill use the =rder=penrice() =rder%akerofit() =rder+top,oss() &nd option&lly
the =rder<xpiration() )un'tions "hen p&ssing un'h&nged %&lues to the =rder8odif0() )un'tion#
6in&lly "e5ll use =rder8odif0() to &dd the stop loss &nd t&,e pro)it to the order#
Here5s &n e4&(ple "here "e set the stop loss &nd t&,e pro)it )or & buy order using the
=rder8odif0() )un'tion# *e5%e (o%ed the stop loss &nd t&,e pro)it '&l'ul&tion &)ter the
=rder+end() )un'tion so th&t it is '&l'ul&ted be)ore "e (odi)y the order+
int <u$Ticket = rderSend(S$mbol('*<53LotSi>e?sk5seSli&&age22
"<u$ rder"MagicBumber9Areen';
if(7u0%icket O 2)&
=rder+elect(7u0%icketD+<,<C%>7@>%#CF<%)M
double =penrice L =rder=penrice()M
if(+top,oss O 2) double 7u0+top,oss L =penrice P (+top,oss * Useoint)M
if(%akerofit O 2) double 7u0%akerofit L =penrice H (%akerofit * Useoint)M
?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 52/212
EXPERT ADVISOR PROGRAMMING
if(7u0+top,oss O 2 QQ 7u0%akerofit O 2)
&
bool %icket8od L =rder8odif0(7u0%icketD=rder=penrice()D7u0+top,ossD
7u0%akerofitD2)M
'
'
The =rder+end() )un'tion is identi'&l to our e&rlier e4&(ple e4'ept th&t "e use & %&lue o) 0 )or the
stop loss &nd t&,e pro)it p&r&(eters# ! %&lue o) ero (e&ns th&t there is no stop loss or t&,e pro)it
being pl&'ed "ith the order# The 7u0%icket %&ri&ble stores the ti',et nu(ber o) the order#
*e use &n if st&te(ent to 'he', th&t the 7u0%icket nu(ber is %&lid i$e$ gre&ter th&n ero# I) so
"e '&ll the =rder+elect() )un'tion using our 7u0%icket nu(ber# *e retrie%e the opening pri'e )or
the order using =rder=penrice() &nd &ssign th&t to the =penrice %&ri&ble#
Ne4t "e '&l'ul&te the stop loss &nd t&,e pro)it rel&ti%e to the opening pri'e o) the order "e ust
pl&'ed# *e 'he', )irst to see i) the +top,oss &nd %akerofit e4tern&l %&ri&bles &re gre&ter th&nero# I) so "e '&l'ul&te the ne" stop loss &nd7or t&,e pro)it pri'e#
6in&lly "e '&ll the =rder8odif0() )un'tion to &dd our stop loss &nd t&,e pro)it to the order# *e
'he', )irst to (&,e sure th&t the 7u0+top,oss or 7u0%akerofit %&ri&bles &re so(ething other th&n
ero# I) "e &tte(pt to (odi)y the order "ith un'h&nged %&lues "e5ll get &n error 'ode 1 )ro( the
=rder8odif0() )un'tion#
The )irst p&r&(eter )or =rder8odif0() is our 7u0%icket nu(ber# *e 'ould &lso use =rder%icket()
&s "ell# The se'ond p&r&(eter is the ne" order pri'e# Sin'e "e &re not (odi)ying the order pri'e "e
use the =rder=penrice() )un'tion to indi'&te th&t the order pri'e is un'h&nged#
Re(e(ber th&t "e '&n only (odi)y order pri'es )or pending orders# I) "e &re (odi)ying & (&r,et
order "e '&n p&ss &ny %&lue )or the rice p&r&(eter sin'e you '&nnot 'h&nge the order pri'e o) &
(&r,et order# 8ut "e '&nnot &ssu(e th&t "e "ill &l"&ys be (odi)ying (&r,et orders so "e "ill
&l"&ys use =rder=penrice()#
The 7u0+top,oss &nd 7u0%akerofit %&ri&bles p&ss the 'h&nged stop loss &nd t&,e pro)it %&lues to
the =rder8odif0() )un'tion# I) you pl&n on using order e4pir&tion ti(es )or your pending orders
you '&n use =rder<xpiration() &s the un'h&nged E4pir&tion p&r&(eter# Other"ise ust use 0#
!lthough this (ethod &dds & )e" e4tr& steps "e re'o((ended th&t you use this (ethod o) pl&'ing
stop losses &nd t&,e pro)its )or (&r,et orders in your e4pert &d%isors to ensure th&t they &re
'o(p&tible "ith &ll bro,ers# This (ethod &lso h&s the &d%&nt&ge o) &llo"ing us to pl&'e &''ur&te stop
loss &nd t&,e pro)it pri'es "ithout the e))e'ts o) slipp&ge#
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 53/212
Advanced ,rder Place#ent
Modifying a Pending &rder Pri$e
=rder8odif0() '&n &lso be used to (odi)y the order pri'e o) & pending order# I) the pending order
pri'e h&s &lre&dy been hit &nd the order h&s been )illed it is no longer & pending order &nd the pri'e
'&nnot be 'h&nged#
*e5ll use the %&ri&ble ewendin!rice to represent our 'h&nged order pri'e# *e5ll &ssu(e the pri'e
h&s &lre&dy been '&l'ul&ted &nd is %&lid# Here5s ho" "e (odi)y & pending order pri'e+
rderSelect(TicketS/L/CT<3TICP/T';
i(Be%*ending*rice R= rder&en*rice(''
)
bool TicketMod = rderModi$(Ticketewendin!rice=rder+top,oss()
=rder%akerofit()9';
,
!s &l"&ys "e retrie%e the order in)or(&tion using =rder+elect()# This "&y "e '&n p&ss the
un'h&nged stop loss &nd t&,e pro)it pri'es to the =rder8odif0() )un'tion# 8e)ore (odi)ying the
order "e5ll 'he', to (&,e sure th&t our ne" pending order pri'e is not the s&(e &s the 'urrent
pending order pri'e#
6or =rder8odif0() "e spe'i)y our order ti',et the ne" order pri'e stored in ewendin!rice
&nd the un'h&nged stop loss &nd t&,e pro)it %&lues represented by =rder+top,oss() &nd
=rder%akerofit()# *e5re not using &n e4pir&tion ti(e )or this order so "e use 0 )or the e4pir&tion
p&r&(eter#
7erifying Stops and Pending &rder Pri$es
Stop loss t&,e pro)it &nd pending order pri'es (ust be & (ini(u( dist&n'e &"&y )ro( the 8id &nd
!s, pri'es# I) & stop or pending order pri'e is too 'lose to the 'urrent pri'e &n error "ill result &nd
the order "ill not be pl&'ed# This is one o) the (ost 'o((on tr&ding errors &nd it '&n e&sily be
pre%ented i) the tr&der is '&re)ul to set their stops &nd pending orders & su))i'ient dist&n'e )ro( the
pri'e#
8ut during periods o) r&pid pri'e (o%e(ent %&lid stop loss pri'es '&n be (&de in%&lid by "idening
spre&ds# Di))erent bro,ers h&%e %&rying stop le%els so & stop loss th&t is %&lid on one bro,er (&y be
too 'lose )or ¬her# So(e tr&ding syste(s "ill set stops &nd pending order pri'es b&sed on
indi'&tor %&lues highs or lo"s or so(e other (ethod o) '&l'ul&tion "here & (ini(u( dist&n'e is not
gu&r&nteed#
=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 54/212
EXPERT ADVISOR PROGRAMMING
6or these re&sons it is &l"&ys ne'ess&ry to %eri)y th&t & stop loss t&,e pro)it or pending order pri'e
is %&lid &nd not too 'lose to the 'urrent (&r,et pri'e# *e %eri)y this by 'he',ing the 'urren'y5s stop
level$
Stop Leve"s
The stop le%el is the nu(ber o) pips &"&y )ro( the 'urrent 8id or !s, pri'e th&t &ll stops &nd pending
orders (ust be pl&'ed# 6or (ost bro,ers the stop le%el is &ppro4i(&tely ?- pips# ECN bro,ers
gener&lly h&%e %ery tight stop le%els "hile other bro,ers su'h &s !lp&ri h&%e "ider stop le%els A&t
le&st ; pipsB#
6igure ?#1 illustr&tes the stop le%els in rel&tion to the pri'es# Thin, o)
the pri'e &s not being ust & single %&lue Asu'h &s the 8idB but
r&ther & thi', line the "idth o) the spre&d#
On either side o) th&t pri'e line &re bound&ries indi'&ted by the stople%els# !ll stop loss t&,e pro)it &nd pending orders (ust be pl&'ed
outside o) these bound&ries#
The 8arket#nfo() )un'tion "ith the 8=6<>+%=,<9<, p&r&(eter is
used to retrie%e the stop le%el )or & 'urren'y sy(bol# The stop le%el
is e4pressed &s & "hole nu(ber &nd "ill need to be 'on%erted to &
)r&'tion&l %&lue using oint#
6or & digit 'urren'y "ith & stop le%el o) ? pips the 8arket#nfo() )un'tion "ith 8=6<>+%=,<9<,
"ill return & ?# 6or & = digit 'urren'y "ith & stop le%el o) ? pips 8arket#nfo() "ill return ?0 due to
the e4tr& de'i(&l pl&'e# Here5s the 'ode )or retrie%ing the stop le%el &nd 'on%erting it to & de'i(&l
%&lue+
double Sto&Le0el = MarketIno(S$mbol('M6/ST*L//L' . *oint;
Note th&t "e use the prede)ined oint %&ri&ble inste&d o) the ipoint() )un'tion "e 're&ted
e&rlier# This is be'&use "e need to (ultiply the stop le%el by the &'tu&l point %&lue# 6or & digit
'urren'y the oint "ill be 0#0001 &nd )or & = digit 'urren'y the oint "ill be 0#00001# I) the stop
le%el is ? pips &s de(onstr&ted &bo%e then the )r&'tion&l %&lue "ill be 0#000?#
No" th&t "e5%e )igured out ho" to )ind the stop le%el "e need to '&l'ul&te the (ini(u( &nd
(&4i(u( %&lues )or our stop loss t&,e pro)it &nd pending order pri'es# *e do this by &dding or
subtr&'ting the stop le%el )ro( our 'urrent 8id &nd !s, pri'es#
<
pread
Ask
Bid
Stop Level
Stop Level
,ig. 8.% Stop le%els
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 55/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 56/212
EXPERT ADVISOR PROGRAMMING
double MinSto& = 2 . 5se*oint;
i(<u$Sto&Loss F Lo%erSto&Le0el' <u$Sto&Loss = Lo%erSto&Le0el MinSto&;
i(<u$Take*roit D 5&&erSto&Le0el' <u$Take*roit = 5&&erSto&Le0el N MinSto&;
The %&ri&ble 8in+top &dds or subtr&'ts = pips )ro( the stop le%el to ensure th&t our %&lid&ted pri'esdo not be'o(e in%&lid due to slipp&ge# $ou '&n &dust this %&lue to en)or'e & su))i'ient (ini(u(
stop7pro)it le%el or e%en use &n e4tern&l %&ri&ble to &dust this &(ount#
The se'ond line 'o(p&res our stop loss to our ,ower+top,evel# I) the stop loss is gre&ter th&n our
lo"er stop le%el "e ,no" th&t the stop loss is in%&lid# In th&t '&se "e &dust the stop loss to be ust
& )e" pips belo" our stop le%el# The third line does the s&(e )or our t&,e pro)it#
To 'he', the stop loss &nd t&,e pro)it )or & sell order "e si(ply re%erse the '&l'ul&tions+
i(SellTake*roit F Lo%erSto&Le0el' SellTake*roit = Lo%erSto&Le0el MinSto&;
i(SellSto&Loss D 5&&erSto&Le0el' SellSto&Loss = 5&&erSto&Le0el N MinSto&;
Inste&d o) &uto(&ti'&lly &dusting &n in%&lid pri'e you 'ould &lso displ&y &n error (ess&ge &nd h<
progr&( e4e'ution# This "&y the user "ould be re.uired to re&dust their stop loss or t&,e pro)it
setting be)ore 'ontinuing# Here5s &n e4&(ple o) ho" to do this+
i(<u$Sto&Loss F Lo%erSto&Le0el'
)
?lert("The sto& loss setting is too smallR"';
return(9';
,
I) the '&l'ul&ted stop loss is &bo%e the stop le%el &nd thus too 'lose to the pri'e the ;lert()
)un'tion "ill displ&y & pop-up (ess&ge to the user# The return oper&tor e4its the 'urrent )un'tion
&nd &ssures th&t the order "ill not be pl&'ed#
In this boo, "e "ill be &uto(&ti'&lly &dusting in%&lid pri'es "ith the &ssu(ption th&t is is better to
pl&'e & 'orre'ted order th&n to not pl&'e one &t &ll# It (&y be use)ul to do'u(ent "hen this h&ppens
by printing & (ess&ge to the log+
i(<u$Sto&Loss F Lo%erSto&Le0el'
)
<u$Sto&Loss = Lo%erSto&Le0el MinSto&;
*rint("Sto& loss is in0alid and has been automaticall$ adusted"';
,
;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 57/212
Advanced ,rder Place#ent
7erifying Pending &rder Pri$es
Here5s ho" "e %eri)y the pending order pri'e )or & buy stop or sell li(it order# The endin!rice
%&ri&ble stores our pending order pri'e+
i(*ending*rice D 5&&erSto&Le0el' *ending*rice = 5&&erSto&Le0el N MinSto&;
Noti'e th&t the logi' here is identi'&l to the 'ode &bo%e th&t 'he',s our buy t&,e pro)it &nd sell stop
loss pri'es# !nd here5s the 'ode to 'he', the pending order pri'e )or & sell stop or buy li(it order+
i(*ending*rice F 5&&erSto&Le0el' *ending*rice = 5&&erSto&Le0el MinSto&;
Ca"$u"ating Lot Si>e
!side )ro( 'hoosing suit&ble stop loss &nd t&,e pro)it le%els using &n &ppropri&te lot sie is one o)the best ris, (&n&ge(ent tools you h&%e# Spe'i)ying & lot sie '&n be &s si(ple &s de'l&ring &n
e4tern&l %&ri&ble &nd using & )i4ed lot sie )or e%ery order# In this se'tion "e5ll e4plore & (ore
sophisti'&ted (ethod th&t '&l'ul&tes the lot sie b&sed on the (&4i(u( &(ount you5re "illing to lose
per tr&de#
O%er-le%er&ging is one o) the big ,illers o) )ore4 tr&ders# >sing lot sies th&t &re too l&rge in rel&tion
to your e.uity '&n "ipe out your &''ount ust &s e&sily &s it '&n produ'e big g&ins# It is
re'o((ended th&t you use no (ore th&n 2-?Q o) your e.uity per tr&de# 8y this "e (e&n th&t the
(&4i(u( &(ount you '&n lose per tr&de "ill be no (ore th&t 2-?Q o) your &''ount#
Money Management
To '&l'ul&te the lot sie using this (ethod "e need to spe'i)y & per'ent&ge o) e.uity to use &nd the
stop loss in pips# *e5ll use the e4tern&l %&ri&ble <quit0ercent to set the per'ent&ge o) e.uity to
use# *e5ll &ssu(e & stop loss o) =0 pips is used#
e+tern double /Euit$*ercent = 4;
e+tern double Sto&Loss = 29;
6irst "e need to '&l'ul&te the &(ount o) e.uity spe'i)ied by <quit0ercent# I) "e h&%e & b&l&n'e
o) 10000 &nd "e &re using 2Q o) our e.uity then the '&l'ul&tion is &s )ollo"s+
double Kisk?mount = ?ccount/Euit$(' . (/Euit$*ercent - 199';
9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 58/212
EXPERT ADVISOR PROGRAMMING
;ccount<quit0() is &n 3 )un'tion th&t returns the 'urrent &''ount e.uity# *e di%ide
<quit0ercent by 100 to gi%e us & )r&'tion&l %&lue A0#02B# Then "e (ultiply th&t by
;ccount<quit0() to '&l'ul&te the &(ount o) e.uity to use# 2Q o) 10000 is 200 &nd this "ill be
stored in the %&ri&ble 5isk;mount#
Ne4t "e h&%e to )ind the tic* value# This is the pro)it per pip i) "e "ere tr&ding one lot o) the desired'urren'y# 6or e4&(ple i) "e &re tr&ding 1 lot o) E>R>SD on & st&nd&rd &''ount A100, lotsB the pro)it
per pip "ould be 10# On & (ini &''ount A10, lotsB the pro)it per pip "ould be 1#
*e '&n use the 8arket#nfo() )un'tion "ith the 8=6<>%#CF9;,U< p&r&(eter to return the pro)it per
pip )or the spe'i)ied 'urren'y# The ti', %&lue (ust be in pips so i) "e &re tr&ding on & )r&'tion&l pip
bro,er A? or = de'i(&l pl&'esB "e (ust (ultiply the ti', %&lue by 10#
double Tickalue = MarketIno(S$mbol('M6/TICP?L5/';
i(*oint == 9!991 77 *oint == 9!99991' Tickalue .= 19;
!ssu(ing "e &re tr&ding & st&nd&rd &''ount the ti', %&lue )or E>R>SD "ill be 10# This "ill be stored
in the %ick9alue %&ri&ble# I) this is & )r&'tion&l pip bro,er then %ick9alue "ill be 1# *e "ill need to
(ultiply this by 10 to (&,e it e.ui%&lent to one pip# I) the oint %&ri&ble indi'&tes th&t the 'urren'y
is ? or = de'i(&l pl&'es then %ick9alue "ill be (ultiplied by 10 to (&,e it e.u&l to & 2 or de'i(&l
pl&'e %&lue#
The ne4t step is to '&l'ul&te our lot sie# 6irst "e di%ide the 5isk;mount by the +top,oss setting#
This "ill gi%e us our pro)it per ti', )or this order# 200 di%ided by our stop loss o) =0 "ill gi%e us #
No" &ll "e h&%e to do is di%ide th&t by %ick9alue to get the lot sie+
double CalcLots = (Kisk?mount - Sto&Loss' - Tickalue;
Our '&l'ul&ted lot sie on & st&nd&rd &''ount "ill be 0# lots# On & (ini &''ount the '&l'ul&ted lot
sie "ill be lots# This %&lue is stored in the Calc,ots %&ri&ble#
I) you &re using proper (oney (&n&ge(ent the per'ent&ge o) e.uity you &re using "ill be )&irly
'onsistent# A1-2Q )or 'onser%&ti%e ris, up to =Q )or higher ris,B# $our stop loss on the other h&nd
"ill %&ry b&sed on your ti(e )r&(e &nd your tr&ding syste(# The lot sie "ill %&ry "idely depending
on your stop loss#
! tight stop loss "ill gener&te & l&rger lot sie "hi'h pro%ides & lot o) upside bene)it i) your order hits
its t&,e pro)it# On the other h&nd i) you5re using & l&rge stop loss your lot sie "ill be )&irly s(&ll#
This (ethod "ill bene)it best )ro( using )&irly tight stops &nd7or l&rge t&,e pro)it %&lues#
=0
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 59/212
Advanced ,rder Place#ent
I) you (ust use & l&rge stop loss or none &t &ll & )i4ed lot sie "ould prob&bly be (ore bene)i'i&l#
*e need to be &ble to 'hoose bet"een '&l'ul&ting the lot sie or using & )i4ed lot sie# 3et5s use &n
e4tern&l boole&n %&ri&ble '&lled 60namic,ot+ie to turn our lot sie '&l'ul&tion on &nd o))+
-- /+ternal 0ariables
e+tern bool 6$namicLotSi>e = true;e+tern double /Euit$*ercent = 4;
e+tern double #i+edLotSi>e = 9!1;
-- Start unction
i(6$namicLotSi>e == true'
)
double Kisk?mount = ?ccount/Euit$(' . (/Euit$*ercent - 199';
double Tickalue = MarketIno(S$mbol('M6/TICP?L5/';
i(6igits == 8 77 6igits == 2' Tickalue .= 19;
double CalcLots = (Kisk?mount - Sto&Loss' - Tickalue;
double LotSi>e = CalcLots;
,else LotSi>e = #i+edLotSi>e;
I) 60namic,ot+ie is set to true "e "ill '&l'ul&te the lot sie b&sed on the stop loss &nd &ssign th&t
%&lue to the ,ot+ie %&ri&ble# I) 60namic,ot+ie is )&lse "e si(ply &ssign the %&lue o)
"ixed,ot+ie to ,ot+ie# The ,ot+ie %&ri&ble "ill be p&ssed to the =rder+end() )un'tion &s the
lot sie )or the order#
7erifying Lot Si>e
Must li,e the stop loss t&,e pro)it &nd pending order pri'es the lot sie should &lso be %eri)ied to(&,e sure it is &''ept&ble to your bro,er# This (e&ns th&t your lot sie should not be too l&rge or too
s(&ll &nd it should not be spe'i)ied in (i'ro lots A0#01B i) your bro,er doesn5t support those# $ou
should &lso nor(&lie your lot sie to the &ppropri&te de'i(&l pl&'e#
3et5s 'he', the (ini(u( &nd (&4i(u( lot sie )irst# The 8arket#nfo() )un'tion using the
8=6<>8#,=% &nd 8=6<>8;$,=% p&r&(eters "ill be used to 'o(p&re the 'urrent lot sie to the
(ini(u( &nd (&4i(u( lot sie# I) the lot sie is not %&lid it "ill &uto(&ti'&lly be resied to the
(ini(u( or (&4i(u(#
i(LotSi>e D MarketIno(S$mbol('M6/MIBLT''
)
LotSi>e = MarketIno(S$mbol('M6/MIBLT';
,
=1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 60/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 61/212
Advanced ,rder Place#ent
Here5s ho" "e 'he', the tr&ding e4e'ution thre&d using #s%radeContext7us0()+
%hile(IsTradeConte+t<us$('' Slee&(19';
int Ticket = rderSend(S$mbol('*<53LotSi>e?sk5seSli&&age22
"<u$ rder"MagicBumber9Areen';
*e use & while loop to e%&lu&te #s%radeContext7us0() # I) the )un'tion returns true indi'&ting th&t
the tr&de e4e'ution thre&d is o''upied the e4pert &d%isor "ill +leep )or 10 (illise'onds# The while
loop "ill 'ontinue to e4e'ute &s long &s #s%radeContext7us0() returns true# On'e the tr&de thre&d
is )reed up tr&ding "ill 'o((en'e#
I) the e4pert &d%isor &tte(pts to tr&de "hile the tr&de e4e'ution thre&d is o''upied &n error 1: +
/tr&de 'onte4t busy/ "ill result# !lthough this (ethod is )&irly reli&ble &t &%oiding the /tr&de 'onte4t
busy/ error it is not )oolproo) espe'i&lly "hen (ultiple e4pert &d%isors &re &tte(pting to tr&de &t the
s&(e ti(e# 3&ter in the boo, "e "ill e4plore "&ys to retry tr&de oper&tions &)ter 'ert&in error
'onditions#
Refres+ing Predefined 7aria!"es
The %&lues o) prede)ined %&ri&bles su'h &s 7id &nd ;sk &re set "hen the e4pert &d%isor begins its
e4e'ution# The &(ount o) ti(e re.uired to e4e'ute our e4pert &d%isor 'ode is %ery short &nd '&n be
(e&sured in (illise'onds# 8ut "hen you )igure in del&ys )or tr&de ser%er response &nd the )&'t th&t
pri'es '&n 'h&nge %ery r&pidly it5s %ery i(port&nt th&t you &l"&ys use the (ost 'urrent pri'es#
The 5efresh5ates() )un'tion upd&tes the 'ontents o) prede)ined %&ri&bles "ith the l&test pri'es)ro( the ser%er# It is re'o((ended th&t you '&ll this )un'tion e%ery ti(e you use the 7id or ;sk
%&ri&bles espe'i&lly &)ter & prior tr&de e4e'ution#
Note th&t i) you retrie%e the pri'e using the 8arket#nfo() )un'tion it is not ne'ess&ry to use
5efresh5ates()# *e 'o%ered 8arket#nfo() on p&ge 29# *hen "e get to the 'h&pter on 're&ting
)un'tions "e "ill use 8arket#nfo() to retrie%e pri'es inste&d o) using prede)ined %&ri&bles#
Ho"e%er you (&y still "&nt to use 7id &nd ;sk in your start() )un'tion to re)eren'e the 'urrent
'h&rt pri'es#
Error ?and"ing
*hen pl&'ing (odi)ying or 'losing orders errors '&n o''ur due to in%&lid tr&de p&r&(eters
re.uotes or ser%er issues# *e5%e done our best to (&,e sure th&t the tr&de p&r&(eters "e use &re
%&lid &nd h&%e been 'he',ed to pre%ent 'o((on pre%ent&ble errors# 8ut "hen errors do o''ur "e
need to &lert the user o) the error &nd log &ny rele%&nt in)or(&tion )or troubleshooting#
=?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 62/212
EXPERT ADVISOR PROGRAMMING
*e 'he', )or possible errors by e4&(ining the output o) )un'tions su'h &s =rder+end()
=rder8odif0() &nd =rderClose()# I) the )un'tion did not 'o(plete su''ess)ully the )un'tion "ill
return - )or =rder+end() or false )or =rder8odif0() &nd =rderClose()#
In this se'tion "e "ill 're&te &n error h&ndling routine )or the =rder+end() )un'tion# I) the return
%&lue o) =rder+end() is -1 "e "ill run &n error h&ndling routine to displ&y &n &lert to the user &ndprint rele%&nt tr&de p&r&(eter &nd pri'e in)or(&tion to the log#
6irst "e (ust )irst retrie%e the error 'ode# This is done using the Bet,ast<rror() )un'tion# *e
need to store the return %&lue o) Bet,ast<rror() in & %&ri&ble be'&use on'e Bet,ast<rror() h&s
been '&lled the error 'ode "ill be 'le&red &nd the ne4t '&ll o) Bet,ast<rror() "ill return 0# *e5ll
de'l&re & glob&l %&ri&ble '&lled <rrorCode &nd use it to store the %&lue o) Bet,ast<rror()#
Ne4t "e5ll need to get so(e des'ripti%e in)or(&tion on the error# The in'lude )ile stdlib.mqh
'ont&ins & )un'tion '&lled <rror6escription() # This )un'tion returns & string "ith & des'ription o)
the error# It5s &'tu&lly not %ery des'ripti%e but it5s better th&n nothing# *e5ll need to &dd &nAinclude st&te(ent )or stdlib.mqh &t the top o) our )ile#
Then "e5ll print &n &lert to the user5s s'reen using the built-in ;lert() )un'tion# This in)or(&tion "ill
&lso be printed to the log# The &lert "ill in'lude the error 'ode the error des'ription &nd & short
des'ription o) the oper&tion "e ust &tte(pted to '&rry out# This "&y you5ll ,no" e4&'tly "hi'h
se'tion in your progr&( gener&ted the error#
6in&lly "e "ill print rele%&nt pri'e in)or(&tion to the log using the rint() )un'tion# !long "ith the
'urrent 8id @ !s, pri'es "e "ill in'lude tr&de p&r&(eters su'h &s the lot sie &nd the order pri'e#
-- *re&rocessor section
include Dstdlib!mEhF
-- Alobal 0ariable
int /rrorCode;
-- rder &lacement
int Ticket = rderSend(S$mbol('*<53ST*LotSi>e*ending*rice5seSli&&age99
"<u$ Sto& rder"MagicBumber9Areen';
i(Ticket == 1'
)/rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("&en <u$ Sto& rder /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 63/212
Advanced ,rder Place#ent
string /rrLog = StringConcatenate("<idJ "<id" ?skJ "?sk" *riceJ "
*ending*rice" LotsJ "LotSi>e';
*rint(/rrLog';
,
!t the top "e in'lude the stdlib.mqh )ile# *e &dd the <rrorCode glob&l %&ri&ble to store our error
'ode# The =rder+end() pl&'es & buy stop order# I) the )un'tion is not su''ess)ul our error h&ndling
'ode is run#
6irst "e store the %&lue o) Bet,ast<rror() in <rrorCode# Then "e '&ll the <rror6escription()
)un'tion using <rrorCode &s the &rgu(ent# Ne4t "e use the +trin!Concatenate() )un'tion to
're&te our &lert (ess&ge "hi'h is stored in the string %&ri&ble <rr;lert#
+trin!Concatenate() is &n 3 )un'tion th&t &llo"s you to 're&te 'o(ple4 strings using %&ri&bles
&nd 'onst&nts# E&'h string ele(ent to be oined Aor /'on'&ten&ted/B together is sep&r&ted by &
'o((&# Try typing the e4&(ples &bo%e into et&Editor to %ie" it "ith synt&4 highlighting#
$ou '&n &lso 'on'&ten&te strings by 'o(bining the( "ith & plus sign AJB# >sing
+trin!Concatenate() is 'le&rer &nd (ore e))i'ient but i) you "&nt to si(ply 'on'&ten&te & short
string use the plus sign to 'o(bine string 'onst&nts &nd %&ri&bles+
string *lusCat = "The current ?sk &rice is "N?sk;
-- Sam&le out&utJ The current ?sk &rice is 1!:849
The ;lert() )un'tion displ&ys & pop-up on the user5s des,top 'ont&ining the 'ontents o) the
<rr;lert %&ri&ble# 6igure ?#2 displ&ys the output o) the ;lert() )un'tion#
*e 'onstru't ¬her string "ith our pri'e &nd tr&de p&r&(eters &nd store it in the <rr,o! %&ri&ble
"hi'h "e p&ss to the rint() )un'tion# rint() prints the 'ontents o) the )un'tion &rgu(ent to the
e4perts log# The e4perts log '&n be %ie"ed )ro( the Experts t&b inside the Ter#inal "indo" or )ro(
the .ournal t&b in the Tester "indo" i) you5re using the Str&tegy Tester#
==
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 64/212
EXPERT ADVISOR PROGRAMMING
,ig. 8.' !lert (ess&ge
Here &re the log 'ontents# The )irst line is the output )ro( the ;lert() )un'tion# The se'ond line is
the output o) the rint() )un'tion# Noti'e the error /in%&lid tr&de %olu(e/ &nd the )&'t th&t the lot
sie reported in the log is 0# In this '&se the proble( is th&t the lot sie is in%&lid#
1@J:UJ2: *roit <uster /5K5S6H1J ?lertJ &en <u$ Sto& rder /rror 181J
in0alid trade 0olume
1@J:UJ2: *roit <uster /5K5S6H1J <idJ 1!29:@ ?skJ 1!29:V LotsJ 9
$ou '&n 're&te si(il&r error h&ndling routines )or other )un'tions &s "ell espe'i&lly )or the
=rder8odif0() &nd =rderClose() )un'tions# $ou '&n &lso 're&te (ore sophisti'&ted error h&ndlingroutines th&t pro%ide 'usto( error (ess&ges b&sed on the error 'ode or per)or( other &'tions#
6or e4&(ple i) you re'ei%e error 1?0+ /in%&lid stops/ you 'ould displ&y & (ess&ge su'h &s /The stop
loss or t&,e pro)it pri'e is in%&lid#/ Here5s &n e4&(ple o) ho" you '&n do this+
/rrorCode = AetLast/rror(';
string /rr6esc;
i(/rrorCode == 14W' /rr6esc = "rder o&ening &rice is in0alidR";
i(/rrorCode == 189' /rr6esc = "Sto& loss or take &roit is in0alidR";
i(/rrorCode == 181' /rr6esc = "Lot si>e is in0alidR";
string /rr?lert = StringConcatenate("&en <u$ rder /rror "/rrorCode"J "/rr6esc';
?lert(/rr?lert';
=<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 65/212
Advanced ,rder Place#ent
Putting #t A"" Toget+er
*e5re going to &dd &ll o) the )e&tures "e5%e 'o%ered in this se'tion to the si(ple e4pert &d%isor "e
're&ted on p&ge ?<# *e5ll be &dding order (odi)i'&tion stop le%el %eri)i'&tion tr&de 'onte4t
'he',ing prede)ined %&ri&ble re)reshing &nd lot sie %eri)i'&tion to our E!# Here is our )ile st&rting &t
the beginning+
&ro&ert$ co&$right "?ndre% 3oung"
Ainclude Rstdlib.mqhO
-- /+ternal 0ariables
extern bool 60namic,ot+ie L trueM
extern double <quit0ercent L 1M
extern double "ixed,ot+ie L 2.M
e+tern double Sto&Loss = 29;
e+tern double Take*roit = 199;
e+tern int Sli&&age = 2;
e+tern int MagicBumber = 148;
e+tern int #astM?*eriod = 19;
e+tern int Slo%M?*eriod = 49;
-- Alobal 0ariables
int <u$Ticket;
int SellTicket;
double 5se*oint;
int 5seSli&&age;
int <rrorCodeM
*e5%e &dded the Ainclude st&te(ent )or the stdlib.mqh )ile th&t 'ont&ins the
<rror6escription() )un'tion )or our error h&ndling routines# *e5%e &dded three e4tern&l %&ri&bles
)or the lot siing &nd & glob&l %&ri&ble )or the error 'ode#
The )ollo"ing 'ode goes &t the beginning o) the start() )un'tion+
-- Mo0ing a0erages
double #astM? = iM?(B5LL9#astM?*eriod9999';
double Slo%M? = iM?(B5LL9Slo%M?*eriod9999';
=:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 66/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 67/212
Advanced ,rder Place#ent
// <rror handlin!
if(Closed LL false)
&
<rrorCode L Bet,ast<rror()M
strin! <rr6esc L <rror6escription(<rrorCode)M
strin! <rr;lert L +trin!Concatenate(Close +ell =rder - <rror D<rrorCodeD: D<rr6esc)M
;lert(<rr;lert)M
strin! <rr,o! L +trin!Concatenate(;sk: D;skD ,ots: D,ot+ieD
%icket: D+ell%icket)M
rint(<rr,o!)M
'
,
-- &en bu$ order
while(#s%radeContext7us0()) +leep(2)M
5efresh5ates()M
<u$Ticket = rderSend(S$mbol('*<53LotSi>e?sk5seSli&&age99
"<u$ rder"MagicBumber9Areen';
// <rror handlin!
if(7u0%icket LL -)
&
<rrorCode L Bet,ast<rror()M
<rr6esc L <rror6escription(<rrorCode)M
<rr;lert L +trin!Concatenate(=pen 7u0 =rder - <rror D
<rrorCodeD: D<rr6esc)M
;lert(<rr;lert)M
<rr,o! L +trin!Concatenate(;sk: D;skD ,ots: D,ot+ie)M
rint(<rr,o!)M
'
// =rder modification
else
&
=rder+elect(7u0%icketD+<,<C%>7@>%#CF<%)M
double =penrice L =rder=penrice()M
// Calculate stop level
double +top,evel L 8arket#nfo(+0mbol()D8=6<>+%=,<9<,) * ointM
5efresh5ates()M
double Upper+top,evel L ;sk H +top,evelM
double ,ower+top,evel L 7id - +top,evelM
double 8in+top L * UseointM
=9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 68/212
EXPERT ADVISOR PROGRAMMING
// Calculate stop loss and take profit
if(+top,oss O 2) double 7u0+top,oss L =penrice - (+top,oss * Useoint)M
if(%akerofit O 2) double 7u0%akerofit L =penrice H (%akerofit * Useoint)M
// 9erif0 stop loss and take profit
if(7u0+top,oss O 2 NN 7u0+top,oss O ,ower+top,evel)
& 7u0+top,oss L ,ower+top,evel - 8in+topM
'
if(7u0%akerofit O 2 NN 7u0%akerofit R Upper+top,evel)
&
7u0%akerofit L Upper+top,evel H 8in+topM
'
// 8odif0 order
if(#s%radeContext7us0()) +leep(2)M
if(7u0+top,oss O 2 QQ 7u0%akerofit O 2)
&
bool %icket8od L =rder8odif0(7u0%icketD=penriceD7u0+top,ossD
7u0%akerofitD2)M
// <rror handlin!
if(%icket8od LL false)
&
<rrorCode L Bet,ast<rror()M
<rr6esc L <rror6escription(<rrorCode)M
<rr;lert L +trin!Concatenate(8odif0 7u0 =rder - <rror D
<rrorCodeD: D<rr6esc)M
;lert(<rr;lert)M
<rr,o! L +trin!Concatenate(;sk: D;skD 7id: D7idD %icket: D
7u0%icketD +top: D7u0+top,ossD rofit: D7u0%akerofit)M
rint(<rr,o!)M
'
'
'
SellTicket = 9;
,
The re(&inder o) our 'ode 'ont&ins the sell (&r,et order pl&'e(ent blo', &s "ell &s the
ipoint() &nd Bet+lippa!e() )un'tions# $ou '&n %ie" the )ull 'ode )or this e4pert &d%isor in !ppendi4 8#
Note th&t "e5%e &dded the #s%radeContext7us0() )un'tion prior to e%ery tr&de oper&tion# *e "&nt
to (&,e sure th&t the tr&de thre&d is )ree be)ore &tte(pting to tr&de# *e use the 5efresh5ates()
<0
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 69/212
Advanced ,rder Place#ent
)un'tion be)ore e&'h re)eren'e o) the 7id or ;sk %&ri&bles to ensure th&t "e &re &l"&ys using the
l&test pri'es#
*e begin by sele'ting the pre%ious sell order ti',et &nd 'losing it using =rderClose()# I) the
)un'tion )&ils the error h&ndling blo', is run# Ne4t "e open the buy (&r,et order using
=rder+end()# I) the )un'tion )&ils it5s error h&ndling blo', is run# Other"ise "e 'ontinue to theorder (odi)i'&tion blo',#
*e sele't the order th&t "&s ust pl&'ed using =rder+elect() &nd &ssign the order5s opening pri'e
to the =penrice %&ri&ble# *e then '&l'ul&te the stop le%el &nd the upper &nd lo"er stop le%el
pri'es# Ne4t "e '&l'ul&te our stop loss &nd t&,e pro)it pri'es %eri)y those &nd )in&lly "e (odi)y the
order using =rder8odif0()# ! )in&l error h&ndling blo', de&ls "ith errors )ro( the order
(odi)i'&tion#
Here5s ho" "e (odi)y the 'ode )or & pending buy stop order+
-- Close order
rderSelect(SellTicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9 QQ SellTicket F 9 NN =rder%0pe() LL =>+<,,'
)
double CloseLots = rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
KereshKates(';
double Close*rice = ?sk;
bool Closed = rderClose(SellTicketCloseLotsClose*rice5seSli&&ageKed';
-- /rror handling
i(Closed == alse'
)
/rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close Sell rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("?skJ "?sk" LotsJ "LotSi>e" TicketJ "SellTicket';
*rint(/rrLog';
,
,
<1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 70/212
EXPERT ADVISOR PROGRAMMING
// 6elete order
else if(=rderClose%ime() LL 2 NN +ell%icket O 2 NN =rder%0pe() LL =>+<,,+%=)
&
bool 6eleted L =rder6elete(+ell%icketD5ed)M
if(6eleted LL true) +ell%icket L 2M
// <rror handlin! if(6eleted LL false)
&
<rrorCode L Bet,ast<rror()M
<rr6esc L <rror6escription(<rrorCode)M
<rr;lert L +trin!Concatenate(6elete +ell +top =rder - <rror D<rrorCodeD
: D<rr6esc)M
;lert(<rr;lert)M
<rr,o! L +trin!Concatenate(;sk: D;skD %icket: D+ell%icket)M
rint(<rr,o!)M
'
'
*e5%e &dded the 'ode to delete pending orders using =rder6elete() &)ter the =rderClose()
)un'tion# The order type o) the pre%ious sell order deter(ines "hi'h )un'tion is used to 'lose the
order#
The (&in di))eren'e bet"een the )ollo"ing 'ode &nd the (&r,et order 'ode is th&t "e do not h&%e &n
order (odi)i'&tion blo',# It is not ne'ess&ry to pl&'e the stop loss &nd t&,e pro)it sep&r&tely )or
pending orders# There)ore "e "ill '&l'ul&te the stop loss &nd t&,e pro)it be)ore pl&'ing the order "ith
=rder+end()#
// Calculate stop level
double +top,evel L 8arket#nfo(+0mbol()D8=6<>+%=,<9<,) * ointM
5efresh5ates()M
double Upper+top,evel L ;sk H +top,evelM
double 8in+top L * UseointM
// Calculate pendin! price
double endin!rice L ?i!hI2J H (endin!ips * Useoint)M
if(endin!rice R Upper+top,evel) endin!rice L Upper+top,evel H 8in+topM
// Calculate stop loss and take profit
if(+top,oss O 2) double 7u0+top,oss L endin!rice - (+top,oss * Useoint)Mif(%akerofit O 2) double 7u0%akerofit L endin!rice H (%akerofit * Useoint)M
// 9erif0 stop loss and take profit
Upper+top,evel L endin!rice H +top,evelM
double ,ower+top,evel L endin!rice P +top,evelM
<2
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 71/212
Advanced ,rder Place#ent
if(7u0+top,oss O 2 NN 7u0+top,oss O ,ower+top,evel)
&
7u0+top,oss L ,ower+top,evel - 8in+topM
'
if(7u0%akerofit O 2 NN 7u0%akerofit R Upper+top,evel)
& 7u0%akerofit L Upper+top,evel H 8in+topM
'
-- *lace &ending order
i(IsTradeConte+t<us$('' Slee&(19';
<u$Ticket = rderSend(S$mbol('=>7U@+%=LotSi>eendin!rice5seSli&&age
<u$Sto&Loss<u$Take*roit"<u$ Sto& rder"MagicBumber9Areen';
-- /rror handling
i(<u$Ticket == 1'
)
/rrorCode = AetLast/rror(';
/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("&en 7u0 +top rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("?skJ "?sk" LotsJ "LotSi>e rice: Dendin!rice
" Sto&J "<u$Sto&Loss" *roitJ "<u$Take*roit';
*rint(/rrLog';
,
SellTicket = 9;
6irst "e '&l'ul&te the upper stop le%el# *e then '&l'ul&te &nd %eri)y our pending order pri'e "hi'h
is stored in endin!rice# *e then re'&l'ul&te Upper+top,evel &nd '&l'ul&te the ,ower+top,evel
so th&t they &re rel&ti%e to the pending order pri'e# Note th&t "e do not need to use the !s, or 8id
pri'es or )igure in the spre&d "hen %eri)ying the stop loss &nd t&,e pro)it pri'es#
6in&lly "e pl&'e our pending order using =rder+end() pl&'ing the stop loss &nd t&,e pro)it &long
"ith it# *e h&%e the st&nd&rd error h&ndling )un'tion to de&l "ith order pl&'e(ent errors#
Despite &ll the e4tr& 'ode these e4pert &d%isors &re using the s&(e str&tegy &s the one &t the end o)'h&pter 2# This 'ode si(ply h&s e4tr& )e&tures )or '&l'ul&ting &nd %eri)ying lot sie stop le%els stop
loss t&,e pro)it &nd pending order pri'es# *e5%e &lso &dded tr&de 'onte4t 'he',s &nd error h&ndling
'ode# In the ne4t 'h&pter "e5ll le&rn ho" to 're&te )un'tions so "e '&n reuse &nd si(pli)y this 'ode#
<?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 72/212
EXPERT ADVISOR PROGRAMMING
C+apter 4)or*ing wit+ ,un$tions
*e5re going to 'on%ert the 'ode th&t "e5%e dis'ussed in the pre%ious 'h&pters into reus&ble
)un'tions# This "ill s&%e us & lot o) "or, &s "e '&n )o'us on the det&ils o) our tr&ding syste( inste&d
o) the (e'h&ni's o) tr&ding#
The ide& behind 're&ting )un'tions is to 're&te & blo', o) 'ode th&t '&rries out & %ery spe'i)i' t&s,#
The 'ode should be )le4ible enough to be reused in & %&riety o) tr&ding situ&tions# !ny e4tern&l
%&ri&bles or '&l'ul&tions "ill need to be p&ssed to the )un'tion# *e '&n5t &ssu(e th&t &ny ne'ess&ry
%&lues "ill be &%&il&ble to our )un'tion other"ise sin'e the )un'tion (&y reside in &n e4tern&l in'lude
)ile or libr&ry#
6or 'onsisten'y "e "ill ,eep the s&(e n&(es )or &ny e4tern&l %&ri&bles th&t "e h&%e used so )&r#
*e5ll pre)&'e these %&ri&bles "ith /ar!/ to indi'&te th&t they &re )un'tion &rgu(ents#
Lot Si>ing ,un$tion
3et5s st&rt "ith our lot sie '&l'ul&tion &s de)ined on p&ge =1+
double CalcLotSi>e(bool arg6$namicLotSi>e double arg/Euit$*ercent double argSto&Loss
double arg#i+edLotSi>e'
)
i(arg6$namicLotSi>e == true'
)
double Kisk?mount = ?ccount/Euit$(' . (arg/Euit$*ercent - 199';
double Tickalue = MarketIno(S$mbol('M6/TICP?L5/';
i(*oint == 9!991 77 *oint == 9!99991' Tickalue .= 19;
double LotSi>e = (Kisk?mount - argSto&Loss' - Tickalue;
,
else LotSi>e = arg#i+edLotSi>e;
return(LotSi>e';
,
The )irst line is our )un'tion de'l&r&tion# *e '&ll this )un'tion Calc,ot+ie()# Co(p&re this to the
'ode on p&ge =1# Noti'e th&t 60namic,ot+ie <quit0ercent +top,oss &nd "ixed,ot+ie &re
&ll )un'tion &rgu(ents no"# The e4tern&l %&ri&bles "ith these n&(es still e4ist in our progr&( "e
"ill ust p&ss the( to the )un'tion &s &rgu(ents no"#
<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 73/212
'or*ing %it! Functions
The &rgu(ents to our )un'tion &re highlighted in bold# Other th&n the )&'t th&t "e5re using
&rgu(ents no" the 'ode is identi'&l to the lot sie '&l'ul&tion 'ode )ro( e&rlier# *e5%e &dded &
return st&te(ent &t the end o) the )un'tion this "ill return the %&lue o) ,ot+ie to our '&lling
)un'tion#
The )un'tion itsel) "ill be pl&'ed so(e"here in our progr&( )ile outside o) the start() &nd init())un'tions or it "ill be lo'&ted in &n e4tern&l in'lude )ile# In the l&tter '&se &n Ainclude st&te(ent &t
the top o) the progr&( "ould in'lude the )ile )or use in our progr&(#
Here5s ho" "e "ould use this )un'tion in 'ode# 6irst let5s list the e4tern&l %&ri&bles "e5ll use )or our
lot sie settings+
e+tern bool 6$namicLotSi>e = true;
e+tern double /Euit$*ercent = 4;
e+tern double #i+edLotSi>e = 9!1;
e+tern double Sto&Loss = 29;
!nd here5s ho" "e '&ll the )un'tion# This line o) 'ode "ould be lo'&ted inside the start() )un'tion+
double LotSi>e = CalcLotSi>e(6$namicSto&Loss/Euit$*ercentSto&Loss#i+edLotSi>e';
Our e4tern&l %&ri&bles &re p&ssed to the )un'tion &s &rgu(ents# The )un'tion "ill '&l'ul&te our lot
sie &nd the %&lue "ill be s&%ed in the %&ri&ble ,ot+ie# Note th&t this %&ri&ble is di))erent )ro( the
,ot+ie %&ri&ble th&t is inside the Calc,ot+ie() )un'tion# 8oth %&ri&bles &re lo'&l to their
)un'tions so e%en though they h&%e the s&(e n&(e they &re not the s&(e %&ri&ble#
Lot 7erifi$ation ,un$tion
3et5s 'ontinue "ith the lot %eri)i'&tion 'ode )ro( p&ge =1# This "ill be & sep&r&te )un'tion in '&se
you de'ide to use &n <ern&te (ethod o) '&l'ul&ting lot sie# Reg&rdless o) the (ethod o)
deter(ining lot sie you5ll "&nt to %eri)y it be)ore using p&ssing it to &n order pl&'e(ent )un'tion+
double eri$LotSi>e(double argLotSize'
)
i(ar!,ot+ie D MarketIno(S$mbol('M6/MIBLT''
)
argLotSi>e = MarketIno(S$mbol('M6/MIBLT';
,
else i(argLotSi>e F MarketIno(S$mbol('M6/M?LT''
)
argLotSi>e = MarketIno(S$mbol('M6/M?LT';
,
<=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 74/212
EXPERT ADVISOR PROGRAMMING
i(MarketIno(S$mbol('M6/LTST/*' == 9!1'
)
argLotSi>e = Bormali>e6ouble(argLotSi>e1';
,
else argLotSi>e = Bormali>e6ouble(argLotSi>e4';
return(ar!,ot+ie)M ,
6or this )un'tion "e5ll p&ss the %&ri&ble "ith the lot sie "e '&l'ul&ted using Calc,ot+ie() &s the
&rgu(ent# The &rgu(ent %&ri&ble ar!,ot+ie is then pro'essed &nd returned b&', to the '&lling
)un'tion#
&rder P"a$ement ,un$tion
No" it5s ti(e to &sse(ble our buy (&r,et order pl&'e(ent )un'tion# There "ill be & )e" di))eren'es
bet"een our order pl&'e(ent )un'tion &nd the 'ode "e re%ie"ed e&rlier# 6or one "e "ill not be
'losing orders in our order pl&'e(ent )un'tions# *e "ill h&ndle the 'losing o) orders sep&r&tely# *e5ll
're&te & )un'tion to 'lose orders in the ne4t 'h&pter#
*e "ill &lso be '&l'ul&ting &nd (odi)ying our stop loss &nd t&,e pro)it pri'es outside o) the order
pl&'e(ent )un'tion# 8e'&use there &re (ultiple "&ys o) '&l'ul&ting stops "e need to ,eep our order
pl&'e(ent )un'tion &s )le4ible &s possible &nd not tie it to & predeter(ined (ethod o) '&l'ul&ting
stops# The order (odi)i'&tion 'ode h&s been (o%ed to & sep&r&te )un'tion#
*e5ll pl&'e our buy order &t the 'urrent (&r,et pri'e using =rder+end() &nd i) the order "&s not
pl&'ed "e5ll run the error h&ndling 'ode )ro( p&ge =# In &ny '&se "e5ll return the ti',et nu(ber to
the '&lling )un'tion or - i) the order "&s not pl&'ed#
*e &re spe'i)ying the order sy(bol using the ar!+0mbol &rgu(ent inste&d o) si(ply using the
'urrent 'h&rt sy(bol# This "&y i) you de'ide to pl&'e &n order on ¬her sy(bol you '&n do so
e&sily# Inste&d o) using the prede)ined 7id &nd ;sk %&ri&bles "e5ll need to use the 8arket#nfo()
)un'tion "ith the 8=6<>;+F &nd 8=6<>7#6 p&r&(eters to retrie%e the 8id &nd !s, pri'e )or th&t
p&rti'ul&r sy(bol#
*e h&%e &lso spe'i)ied & de)&ult %&lue )or the order 'o((ent# The &rgu(ent ar!Comment h&s &
de)&ult %&lue 7u0 =rder# I) no %&lue is spe'i)ied )or this &rgu(ent then the de)&ult is used# *e5ll
&ssu(e th&t the lot sie &nd slipp&ge h&%e been '&l'ul&ted &nd %eri)ied prior to '&lling this )un'tion+
<<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 75/212
'or*ing %it! Functions
int &en<u$rder(string argSymbol double argLotSize double argSlippage
double argMagicNumber string argComment = "<u$ rder"'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
-- *lace <u$ rder
int Ticket = rderSend(ar!+0mbol*<53ar!,ot+ie8arket#nfo(ar!+0mbolD8=6<>;+F)ar!+lippa!e99ar!Commentar!8a!icumber9Areen';
-- /rror Handling
i(Ticket == 1'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("&en <u$ rder /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "8arket#nfo(ar!+0mbolD8=6<>7#6)
" ?skJ "8arket#nfo(ar!+0mbolD8=6<>;+F)" LotsJ "ar!,ot+ie';
*rint(/rrLog';
,
return(Ticket';
,
In the =rder+end() )un'tion note th&t "e5%e used the 8arket#nfo() )un'tion "ith the 8=6<>;+F
p&r&(eter in pl&'e o) the prede)ined ;sk %&ri&ble# This "ill retrie%e the 'urrent !s, pri'e )or the
'urren'y sy(bol indi'&ted by ar!+0mbol#
I) the tr&de "&s not pl&'ed su''ess)ully the error h&ndling routine "ill be run# Other"ise the order
ti',et "ill be returned to the '&lling )un'tion or - i) the order "&s not pl&'ed# The 'o(plete order
pl&'e(ent )un'tion )or sell (&r,et orders is in !ppendi4 D#
Pending &rder P"a$ement
To pl&'e pending orders "e5ll need to p&ss p&r&(eters )or the pending order pri'e &s "ell &s the
order e4pir&tion ti(e# The ar!endin!rice &nd ar!<xpiration &rgu(ents "ill be &dded to the
)un'tion#
*e5ll &ssu(e th&t the pending order pri'e &s "ell &s the stop loss &nd t&,e pro)it h&%e been
'&l'ul&ted &nd %eri)ied prior to '&lling this )un'tion# The pending order pl&'e(ent )un'tions "ill pl&'e
the stop loss &nd t&,e pro)it "ith the pending order so no sep&r&te order (odi)i'&tion )un'tion is
re.uired#
<:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 76/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 77/212
'or*ing %it! Functions
&rder C"osing ,un$tion
3&stly let5s 're&te & )un'tion )or 'losing & single order# *e5ll use the order 'losing blo', )ro( the 'ode
on p&ge =;# In the ne4t 'h&pter "e5ll e4&(ine "&ys o) 'losing (ultiple orders o) the s&(e type
"hi'h is & si(pler (ethod o) 'losing orders# 8ut in '&se you need to 'lose ust one order this
)un'tion "ill do the tri',+
bool Close<u$rder(string argSymbol int argCloseTicket double argSlippage'
)
rderSelect(argCloseTicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9'
)
double CloseLots = rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
double Close*rice = 8arket#nfo(ar!+0mbolD8=6<>;+F);
bool Closed = rderClose(ar!Close%icketCloseLotsClose*ricear!+lippa!eKed';
i(Closed == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close <u$ rder /rrorJ "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("TicketJ "ar!Close%icket" ?skJ "MarketIno(argS$mbolM6/?SP'';
*rint(/rrLog';
,
,
return(Closed';
,
6or the Closerice %&ri&ble "e use 8arket#nfo() to retrie%e the 'urrent !s, pri'e )or the 'urren'y
indi'&ted by ar!+0mbol# *e use the )un'tion &rgu(ents ar!Close%icket &nd ar!+lippa!e )or the
'losing order ti',et &nd the slipp&ge respe'ti%ely# I) the order "&s not 'losed su''ess)ully "e runthe error h&ndling blo', "hi'h prints the ti',et nu(ber &nd 'urrent !s, pri'e to the log#
The 'ode to 'lose & sell order "ill be identi'&l e4'ept th&t you5d use the 8id pri'e )or the
Closerice %&ri&ble# $ou '&n %ie" the sell (&r,et 'lose )un'tion in !ppendi4 D#
<9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 78/212
EXPERT ADVISOR PROGRAMMING
Pending &rder C"ose ,un$tion
Here5s & )un'tion to 'lose & single pending order# This "ill "or, on &ll pending order types buy &nd
sell#
bool Close*endingrder(string argSymbol int argCloseTicket double argSlippage'
)
rderSelect(argCloseTicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9'
)
%hile(IsTradeConte+t<us$('' Slee&(19'M
bool 6eleted = rder6elete(argCloseTicketKed';
i(6eleted == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close *ending rder /rrorJ "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("TicketJ "argCloseTicket
" <idJ "MarketIno(argS$mbolM6/<I6'
" ?skJ "MarketIno(argS$mbolM6/?SP'';
*rint(/rrLog';
,
,
return(6eleted';
,
Stop Loss ; Ta*e Profit Ca"$u"ation ,un$tions
*e5re going to 're&te & )e" short )un'tions )or '&l'ul&ting stop loss &nd t&,e pro)it &s dis'ussed on
p&ges 2=-?0# *e "ill p&ss our e4tern&l %&ri&bles indi'&ting the stop loss or t&,e pro)it in pips to our
)un'tion &s "ell &s the order opening pri'e# The return %&lue o) our )un'tion "ill be the &'tu&l stop
loss or t&,e pro)it pri'e#
Here5s the )un'tion to '&l'ul&te & buy stop loss in pips+
double Calc<u$Sto&Loss(string argSymbol int argStopLoss double argOpenPrice'
)
i(argSto&Loss == 9' return(9';
double <u$Sto&Loss = arg&en*rice (argSto&Loss . *i&*oint(argS$mbol'';
return(<u$Sto&Loss';
,
:0
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 79/212
'or*ing %it! Functions
6irst "e5ll 'he', to see i) & %&lid stop loss le%el h&s been p&ssed &long "ith the )un'tion# I) the
ar!+top,oss &rgu(ent is 0 then "e return & %&lue o) 0 to the '&lling )un'tion indi'&ting th&t no
stop loss "&s spe'i)ied#
Ne4t "e '&l'ul&te the stop loss by subtr&'ting the stop loss in pips )ro( the order opening pri'e# *e
(ultiply ar!+top,oss by ipoint() to '&l'ul&te the )r&'tion&l %&lue &nd subtr&'t th&t )ro(ar!=penrice# *e "ill use either the 8id or !s, pri'e A)or (&r,et ordersB or the intended pending
order pri'e#
Note th&t "e do not 'he', the stop le%el or other"ise %eri)y th&t the stop loss is %&lid# *e "ill use
¬her set o) )un'tions to %eri)y or &dust the stop loss pri'e &s ne'ess&ry# $ou 'ould o) 'ourse
e&sily (odi)y this )un'tion to %eri)y the stop loss pri'e displ&y &n error (ess&ge or &uto(&ti'&lly
&dust the pri'e#
Here is the )un'tion to '&l'ul&te & buy t&,e pro)it in pips+
double Calc<u$Take*roit(string argSymbol int argTakeProfit double argOpenPrice'
)
i(argTake*roit == 9' return(9';
double <u$Take*roit = &en*rice N (argTake*roit . *i&*oint(argS$mbol'';
return(<u$Take*roit';
,
The )un'tions )or '&l'ul&ting stop loss &nd t&,e pro)it )or sell orders &re listed in !ppendi4 D# Note
th&t the )un'tion )or '&l'ul&ting sell stop loss is ne&rly identi'&l to the one &bo%e )or '&l'ul&ting the
buy t&,e pro)it &nd li,e"ise )or buy stop loss &nd sell t&,e pro)it#
Stop Leve" 7erifi$ation
*e5re going to 're&te t"o sets o) )un'tions to '&l'ul&te &nd %eri)y stop le%els# The )irst "ill si(ply
'&l'ul&te the stop le%el &bo%e or belo" & spe'i)ied pri'e &nd return & boole&n %&lue indi'&ting
"hether the indi'&ted pri'e is inside or outside the stop le%el# ! se'ond set o) )un'tions "ill
&uto(&ti'&lly &dust & pri'e so th&t it is outside the stop le%el plus or (inus & spe'i)ied nu(ber o)
pips#
The )ollo"ing )un'tion %eri)ies "hether & pri'e is &bo%e the upper stop le%el Athe order opening pri'e
plus the stop le%elB# I) so the )un'tion returns true other"ise )&lse+
:1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 80/212
EXPERT ADVISOR PROGRAMMING
bool eri$5&&erSto&Le0el(string argSymbol double arg%erifyPrice
double argOpenPrice = 9'
)
double Sto&Le0el = MarketIno(argS$mbolM6/ST*L//L' . *oint;
i(arg&en*rice == 9' double &en*rice = MarketIno(argS$mbolM6/?SP';
else &en*rice = arg&en*rice;
double 5&&erSto&Le0el = &en*rice N Sto&Le0el;
i(argeri$*rice F 5&&erSto&Le0el' bool Sto&eri$ = true;
else Sto&eri$ = alse;
return(Sto&eri$';
,
*e p&ss the 'urren'y sy(bol the pri'e to %eri)y &nd the order opening pri'e Aoption&lB &s
&rgu(ents# 8y de)&ult the stop le%el is '&l'ul&ted rel&ti%e to the !s, pri'e# I) ar!=penrice is
spe'i)ied the stop le%el "ill be '&l'ul&ted rel&ti%e to th&t pri'e inste&d# A>se this "hen %eri)ying stoploss &nd t&,e pro)it pri'es )or pending ordersB#
The )un'tion "ill 'he', to see "hether ar!9erif0rice is gre&ter th&n the Upper+top,evel# I) it is
the return %&lue "ill be true# Other"ise )&lse# $ou '&n use this )un'tion to 'he', )or & %&lid stop loss
t&,e pro)it or pending order pri'e "ithout (odi)ying the origin&l pri'e# Here5s &n e4&(ple "here "e
'he', & stop loss pri'e &nd sho" &n error (ess&ge i) the pri'e is not %&lid+
bool eriied = eri$5&&erSto&Le0el(S$mbol('SellSto&Loss';
i(eriied == alse' ?lert("Sell sto& loss is in0alidR"';
The 'ode to 'he', the stop le%el belo" the 'urrent or pending pri'e is in !ppendi4 D# Our se'ond set
o) )un'tions is si(il&r e4'ept th&t they "ill &uto(&ti'&lly &dust the in%&lid stop loss t&,e pro)it or
pending order pri'e to & %&lid one+
double ?dust?bo0eSto&Le0el(string argSymbol double argd&ustPrice int argddPips = 9
double argOpenPrice = 9'
)
double Sto&Le0el = MarketIno(argS$mbolM6/ST*L//L' . *oint;
i(arg&en*rice == 9' double &en*rice = MarketIno(argS$mbolM6/?SP';else &en*rice = arg&en*rice;
double 5&&erSto&Le0el = &en*rice N Sto&Le0el;
:2
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 81/212
'or*ing %it! Functions
i(arg?dust*rice D= 5&&erSto&Le0el'
)
double ?dusted*rice = 5&&erSto&Le0el N (arg?dd*i&s . *i&*oint(argS$mbol'';
,
else ?dusted*rice = arg?dust*rice;
return(?dusted*rice';,
The &rgu(ent ar!;dustrice is the pri'e "e "ill %eri)y &nd &dust i) it5s in%&lid# *e5%e &dded &
ne" option&l p&r&(eter ar!;ddips# This "ill &dd the spe'i)ied nu(ber o) pips to the stop le%el
pri'e "hen &dusting &n in%&lid pri'e#
!s be)ore "e '&l'ul&te the stop le%el rel&ti%e to either the !s, pri'e or the ar!=penrice
p&r&(eter# I) the ar!;dustrice p&r&(eter is inside the stop le%el Ai#e# not %&lidB the pri'e "ill be
&dusted so th&t it is outside the stop le%el by the nu(ber o) pips spe'i)ied by ar!;ddips#
I) the pri'e spe'i)ied by ar!;dustrice is %&lid th&t pri'e "ill be p&ssed b&', to the '&lling
)un'tion# In &ny '&se the return %&lue is the one you "ill "&nt to use )or your t&,e pro)it stop loss
or pending order pri'e# *e "ill be using these )un'tions in this boo, to %eri)y stop le%els &nd &dust
our pri'es &''ordingly# The )un'tions to '&l'ul&te &nd %eri)y the lo"er stop le%el '&n be )ound in
!ppendi4 D#
Add Stop Loss and Ta*e Profit
In ,eeping "ith our ide& to ,eep )un'tions )o'used on si(ple &nd dis'rete t&s,s "e5%e (o%ed our
order (odi)i'&tion to & sep&r&te )un'tion# This )un'tion "ill &dd or (odi)y the stop loss &nd t&,e
pro)it on the spe'i)ied order# *e5ll &ssu(e the stop loss &nd t&,e pro)it pri'es h&%e &lre&dy been
'&l'ul&ted &nd %eri)ied+
bool ?ddSto&*roit(int argTicket double argStopLoss double argTakeProfit'
)
if(ar!+top,oss LL 2 NN ar!%akerofit LL 2) return(false)M
rderSelect(ar!%icketS/L/CT<3TICP/T';
double &en*rice = rder&en*rice(';
%hile(IsTradeConte+t<us$('' Slee&(19';
-- Modi$ rder
bool TicketMod = rderModi$(ar!%icketrder&en*rice('ar!+top,ossar!%akerofit9';
:?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 82/212
EXPERT ADVISOR PROGRAMMING
-- /rror Handling
i(TicketMod == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate(";dd +top/rofit /rror "/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "8arket#nfo(=rder+0mbol()D8=6<>7#6)
" ?skJ "8arket#nfo(=rder+0mbol()D8=6<>;+F)" TicketJ "ar!%icket
" Sto&J "ar!+top,oss" *roitJ "ar!%akerofit';
*rint(/rrLog';
,
return(TicketMod';
,
*e 'he', )irst to see i) either & stop loss or & t&,e pro)it pri'e h&s been supplied# I) not "e "ill e4it
the )un'tion# Other"ise "e "ill (odi)y the order using the stop loss &nd t&,e pro)it th&t "&s p&ssed
to the )un'tion# The error h&ndling )un'tion "ill run i) the order (odi)i'&tion "&s not su''ess)ul# This
)un'tion "ill "or, on &ll order types#
5sing #n$"ude ,i"es
To ,eep our )un'tions org&nied )or e&sy in'lusion in our sour'e 'ode )iles "e5ll pl&'e the )un'tions
into &n in'lude )ile# !n in'lude )ile '&n 'onsist o) )un'tion de'l&r&tions i(ported )un'tions &nd &ny
glob&l or e4tern&l %&ri&bles th&t you "ish to in'lude in &n e4pert &d%isor#
In'lude )iles re.uire no spe'i&l synt&4# $ou de'l&re the )un'tions &nd %&ri&bles in the in'lude )ile ust
&s you "ould in &ny sour'e 'ode )ile# In'lude )iles should not h&%e &n init() start() or deinit()
)un'tion# The )ile (ust h&%e &n .mqh e4tension &nd be lo'&ted in the \experts\include )older#
!ll o) the )un'tions "e 're&te in this boo, "ill be pl&'ed in &n in'lude )ile n&(ed
#nclude<xample.mqh # The 'ontents o) this )ile &re listed in !ppendi4 D#
5sing Li!raries ! libr&ry is & 'o(piled 'olle'tion o) )un'tions# *here&s &n in'lude )ile is & sour'e 'ode )ile "hose
'ontents &re /in'luded/ in the e4e'ut&ble )ile & libr&ry is & sep&r&te e4e'ut&ble th&t 'ont&ins the
i(ported )un'tions# There)ore you (ust h&%e both your e4pert &d%isor e4e'ut&ble &nd the libr&ry
e4e'ut&ble to run your E!#
:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 83/212
'or*ing %it! Functions
3ibr&ries &re stored in the \experts\libraries )older# The sour'e 'ode )iles h&%e &n .mq4
e4tension &nd the e4e'ut&bles h&%e &n .ex4 e4tension# 3ibr&ries do not h&%e & start() init() or
deinit() )un'tion# To de'l&re & )ile &s & libr&ry you (ust pl&'e the Apropert0 librar0
prepro'essor dire'ti%e &t the beginning o) the )ile#
The &d%&nt&ge o) libr&ries is th&t they &re 'o(piled so i) you need to distribute & )un'tion libr&ryyou '&n do so "ithout e4posing your intelle'tu&l property &s you "ould i) you distributed &n in'lude
)ile# $ou '&n &lso (&,e bug )i4es to & libr&ry "ithout h&%ing to re'o(pile your e4pert &d%isors &s
long &s you do not (&,e &ny 'h&nges to the )un'tion de'l&r&tions su'h &s &dding &nd re(o%ing
&rgu(ents or )un'tions#
There &re & )e" dis&d%&nt&ges to libr&ries &s "ell# Sin'e they &re &lre&dy 'o(piled it is not possible
)or the 'o(piler to 'he', i) the p&r&(eters &re 'orre't# $ou '&nnot spe'i)y & de)&ult %&lue )or &
p&r&(eter in & libr&ry )un'tion "hi'h (e&ns you "ill need to spe'i)y & %&lue )or e%ery &rgu(ent in &
)un'tion '&ll# $ou '&nnot use e4tern&l %&ri&bles in & libr&ry or 're&te glob&lly s'oped %&ri&bles th&t
your e4pert &d%isor '&n &''ess#
$ou5ll need to use the Aimport dire'ti%e to i(port libr&ry )un'tions into your e4pert &d%isor# I) the
libr&ry 'ont&ins nu(erous )un'tions it (&y be best to 're&te &n in'lude )ile "ith the Aimport
st&te(ents# This in're&ses the nu(ber o) )iles you5ll need to "or, "ith# >nless you h&%e & %ery good
re&son to use libr&ries it is suggested th&t you sti', "ith in'lude )iles )or storing your )un'tions#
$ou '&n &lso i(port )un'tions )ro( *indo"s D33s using Aimport dire'ti%es# The GinUserS1.mqh
in'lude )ile in \experts\includes h&s nu(erous e4&(ples th&t &re used )or the 8essa!e7ox()
)un'tion# A*e5ll dis'uss the 8essa!e7ox() )un'tion in 'h&pter ;B# >sing D33 )un'tions is &n &d%&n'ed
us&ge th&t "e "ill not 'o%er here# There &re &rti'les on the 3 "ebsite on using D33s )or those"ho &re interested#
A Simp"e Expert Advisor <wit+ ,un$tions=
Here is our e4pert &d%isor sour'e 'ode &s it &ppe&rs in the sour'e 'ode )ile# *e5ll &ssu(e th&t the
)un'tions "e5%e 're&ted in this 'h&pter &re de'l&red in the in'lude )ile #nclude<xample.mqh the
'ontents o) "hi'h &re listed in !ppendi4 D#
-- *re&rocessor
Ainclude R#nclude<xample.mqhO
-- /+ternal ariables
e+tern bool 6$namicLotSi>e = true;
e+tern double /Euit$*ercent = 4;
e+tern double #i+edLotSi>e = 9!1;
:=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 84/212
EXPERT ADVISOR PROGRAMMING
e+tern double Sto&Loss = 29;
e+tern double Take*roit = 199;
e+tern int Sli&&age = 2;
e+tern int MagicBumber = 148;
e+tern int #astM?*eriod = 19;e+tern int Slo%M?*eriod = 49;
-- Alobal ariables
int <u$Ticket;
int SellTicket;
double 5se*oint;
int 5seSli&&age;
-- Init unction
int init('
)
5se*oint = *i&*oint(S$mbol('';
5seSli&&age = AetSli&&age(S$mbol('Sli&&age';
,
-- Start #unction
int start('
)
-- Mo0ing ?0erage
double #astM? = iM?(B5LL9#astM?*eriod9999';
double Slo%M? = iM?(B5LL9Slo%M?*eriod9999';
-- Calculate Lot Si>e
double LotSi>e = CalcLotSi>e(6$namicLotSi>e/Euit$*ercentSto&Loss#i+edLotSi>e';
LotSi>e = eri$LotSi>e(LotSi>e';
-- <u$ rder
i(#astM? F Slo%M? QQ <u$Ticket == 9'
)
i(SellTicket F 9' int Closed = CloseSellrder(S$mbol('SellTicket5seSli&&age';
SellTicket = 9;
<u$Ticket = &en<u$rder(S$mbol('LotSi>e5seSli&&ageMagicBumber';
i(<u$Ticket F 9 QQ (Sto&Loss F 9 77 Take*roit F 9''
)
rderSelect(<u$TicketS/L/CT<3TICP/T';
double &en*rice = rder&en*rice(';
:<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 85/212
'or*ing %it! Functions
double <u$Sto&Loss = Calc<u$Sto&Loss(S$mbol('Sto&Loss&en*rice';
i(<u$Sto&Loss F 9'
)
<u$Sto&Loss = ?dust<elo%Sto&Le0el(S$mbol('<u$Sto&Loss2';
,
double <u$Take*roit = Calc<u$Take*roit(S$mbol('Take*roit&en*rice'; i(<u$Take*roit F 9'
)
<u$Take*roit = ?dust?bo0eSto&Le0el(S$mbol('<u$Take*roit2';
,
?ddSto&*roit(<u$Ticket<u$Sto&Loss<u$Take*roit';
,
,
-- Sell rder
i(#astM? D Slo%M? QQ SellTicket == 9'
)
i(<u$Ticket F 9' Closed = Close<u$rder(S$mbol('<u$TicketSli&&age';
<u$Ticket = 9;
SellTicket = &enSellrder(S$mbol('LotSi>e5seSli&&ageMagicBumber';
i(SellTicket F 9 QQ (Sto&Loss F 9 77 Take*roit F 9''
)
rderSelect(SellTicketS/L/CT<3TICP/T';
&en*rice = rder&en*rice(';
double SellSto&Loss = CalcSellSto&Loss(S$mbol('Sto&Loss&en*rice';
i(SellSto&Loss F 9'
)
SellSto&Loss = ?dust?bo0eSto&Le0el(S$mbol('SellSto&Loss2';
,
double SellTake*roit = CalcSellTake*roit(S$mbol('Take*roit&en*rice';
i(SellTake*roit F 9'
)
SellTake*roit = ?dust<elo%Sto&Le0el(S$mbol('SellTake*roit2';
,
?ddSto&*roit(SellTicketSellSto&LossSellTake*roit';
,
,
return(9';
,
::
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 86/212
EXPERT ADVISOR PROGRAMMING
*e begin by in'luding the )ile th&t h&s our )un'tions in it in this '&se #nclude<xample.mqh# The
%&ri&ble de'l&r&tions &nd the 'ontents o) the init() )un'tion &re the s&(e &s be)ore# !t the
beginning o) the start() )un'tion "e use Calc,ot+ie() &nd 9erif0,ot+ie() to to '&l'ul&te
&nd %eri)y our lot sie#
In our buy &nd sell order blo',s "e use Close7u0=rder() &nd Close+ell=rder() to 'lose theopposite order# Our ne" orders &re opened using =pen7u0=rder() or =pen+ell=rder()# 8e)ore
'&l'ul&ting the stop loss &nd t&,e pro)it "e 'he', th&t the order "&s opened &nd th&t & +top,oss or
%akerofit h&s been spe'i)ied#
*e retrie%ing the opening pri'e o) the order using =rder+elect() &nd =rder=penrice()# *e then
'&l'ul&te our stop loss using Calc7u0+top,oss() or Calc+ell+top,oss() &nd our t&,e pro)it using
Calc7u0%akerofit() or Calc+ell%akerofit() #
*e 'he', to see i) the stop loss or t&,e pro)it is gre&ter th&n 0 &nd use the )un'tions
;dust;bove+top,evel() &nd ;dust7elow+top,evel() to %eri)y our stop loss &nd t&,e pro)itpri'es# 6in&lly "e p&ss those pri'es to the ;dd=rderrofit() )un'tion "hi'h &dds the stop loss &nd
t&,e pro)it to the order#
The E! &bo%e does e4&'tly the s&(e thing &s the 'ode st&rting on p&ge =1 but is (u'h e&sier to
re&d# 8y bre&,ing the 'ode into )un'tions "e h&%e de-'luttered our sour'e 'ode &nd (&de our E!
e&sier to (&n&ge# *e "ill &dd & )e" (ore )e&tures to this e4pert &d%isor be)ore the end o) the boo,#
$ou '&n %ie" the 'o(plete 'ode in !ppendi4 C#
The initi&l "or, in 're&ting these )un'tions "ill t&,e so(e ti(e but it "ill s&%e you ti(e in the long
run &s you "ill (ore e&sily be &ble to prototype tr&ding ide&s &nd turn out "or,ing e4pert &d%isorsin & short &(ount o) ti(e#
:;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 87/212
'or*ing %it! Functions
:9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 88/212
EXPERT ADVISOR PROGRAMMING
C+apter 1&rder Management
$ou5%e &lre&dy been introdu'ed to the =rder+elect() )un'tion in 'h&pter 2# In this se'tion "e "ill
use the =rder+elect() )un'tion &long "ith the 'y'le oper&tors for &nd while to loop through the
order pool &nd retrie%e order in)or(&tion# This (ethod "ill be used to 'lose (ultiple orders &dd
tr&iling stops 'ount the nu(ber o) open orders &nd (ore#
T+e &rder Loop
T+e for &perator
The for oper&tor is used to loop through & blo', o) 'ode & predeter(ined nu(ber o) ti(es# *e
de'l&re &n integer %&ri&ble to use &s & 'ounter &nd &ssign it & st&rting %&lue# *e indi'&te the
'ondition "hi'h i) true "ill '&use the loop to run# *e &lso indi'&te &n e4pression by "hi'h to
in're(ent the 'ounter %&ri&ble#
Here is &n e4&(ple o) & for loop+
or(int Counter = 1; Counter D= 8; CounterNN'
)
-- Code to loo&
,
The )irst e4pression int Counter L initi&lies our Counter %&ri&ble "ith & %&lue o) 1# The se'ond
e4pression Counter RL S is the 'ondition "hi'h i) true "ill e4e'ute the 'ode inside the br&'es# I)
)&lse the loop is ended &nd e4e'ution 'ontinues &)ter the end br&'e A'B#
The third e4pression CounterHH (e&ns /in're(ent the %&lue o) Counter by one#/ The e4pression
Counter-- "ould de're(ent the %&lue by one &nd CounterH1 "ould in're(ent by t"o# E%ery ti(e
the loop 'o(pletes the 'ounter %&ri&ble is in're(ented or de're(ented# On the ne4t iter&tion o) the
loop the se'ond &rgu(ent in this '&se CounterRL S is re-e%&lu&ted# Note th&t there is no
se(i'olon &)ter the third e4pression#
The &bo%e e4&(ple "ill e4e'ute the loop three ti(es# !)ter e&'h iter&tion the 'ounter is in're(ented
by one &nd &)ter the third iter&tion the loop "ill ter(in&te#
;0
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 89/212
,rder Manage#ent
T+e while &perator
The while oper&tor is & si(pler (ethod o) looping in 3# The for loop is best i) you ,no" e4&'tly
ho" (&ny ti(es you pl&n on e4e'uting the loop# I) you5re unsure o) the nu(ber o) iter&tions
ho"e%er then the while loop "ould be (ore &ppropri&te#
Here5s &n e4&(ple o) & while loop+
%hile(Something == true'
)
-- Loo& code
,
This liter&l e4&(ple uses & boole&n %&ri&ble '&lled +omethin!# I) +omethin! is e.u&l to true the
loop "ill e4e'ute# O) 'ourse i) the %&lue o) +omethin! ne%er 'h&nges the loop "ill run endlessly#
Thus it is ne'ess&ry th&t there be & 'ondition to 'h&nge the %&lue o) +omethin! &t so(e pointduring the loop# On'e this 'ondition is true +omethin! is 'h&nged to false &nd the loop "ill stop
e4e'uting#
$ou 'ould &lso in're(ent & %&ri&ble ust li,e you "ould using the for oper&tor+
int Counter = 1;
%hile(Counter D= 8'
)
CounterNN;
,
This 'ode "ill e4e'ute e4&'tly li,e the for loop &bo%eL
T+e &rder Loop
Here is the 'ode "e "ill use to loop through the pool o) open orders+
or(Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
-- /0aluate condition,
*e "ill set the %&lue o) Counter to 0 &nd iter&te the loop &s long &s Counter is less th&n or e.u&l to
the %&lue o) =rders%otal() (inus one# Counter "ill be in're(ented by 1 &)ter e&'h iter&tion o) the
loop#
;1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 90/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 91/212
,rder Manage#ent
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol'
)
rderCountNN;
,
,
return(rderCount';
,
*e5%e n&(ed our order 'ounting )un'tion %otal=rderCount()# It "ill return &n integer %&lue
indi'&ting ho" (&ny orders &re 'urrently opened on the spe'i)ied 'h&rt sy(bol (&t'hing the (&gi'
nu(ber th&t "e5%e p&ssed &s & )un'tion &rgu(ent#
*e st&rt by de'l&ring the =rderCount %&ri&ble# Sin'e "e h&%e not indi'&ted &n initi&l %&lue
=rderCount "ill be initi&lied &s 0# $ou5ll re'ognie the for oper&tor &nd the =rder+elect()
)un'tion )ro( the pre%ious se'tion#
Sin'e the order pool 'ont&ins &ll open orders in'luding those pl&'ed by other E!s it is ne'ess&ry )or
us to identi)y "hi'h orders "ere pl&'ed by our E!# *e 'he', the =rder+0mbol() o) the sele'ted
order )irst &nd (&,e sure th&t it (&t'hes the ar!+0mbol &rgu(ent# The "e 'he', the (&gi' nu(ber
on the order#
I) =rder8a!icumber() (&t'hes the ar!8a!icumber &rgu(ent "e '&n be )&irly sure th&t this
order "&s pl&'ed by this E!# !s long &s the user is not running t"o E!5s on the s&(e 'urren'y
sy(bol "ith the s&(e (&gi' nu(ber "e '&n be 'ert&in th&t this order "&s pl&'ed by this E!# *hen
running (ultiple e4pert &d%isors on the s&(e instru(ent t&,e '&re to ensure th&t you5re using &
uni.ue (&gi' nu(ber on e&'h E!#
I) the order (&t'hes both our (&gi' nu(ber &nd our 'h&rt sy(bol the %&lue o) =rderCount "ill be
in're(ented by one# !)ter "e h&%e looped through &ll o) the orders in the order pool "e return the
%&lue o) =rderCount to the '&lling )un'tion#
Here5s &n e4&(ple o) ho" "e "ould use this in 'ode+
i(TotalrderCount(S$mbol('MagicBumber' F 9 QQ Closerders == true'
)
-- Close all orders
,
I) there &re orders opened by this E! &nd the %&lue o) Close=rders is true A"e5ll &ssu(e this "&s
set so(e"here else in the progr&(B then the 'ode inside the br&'es "ill run "hi'h "ill 'lose &ll
open orders#
;?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 92/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 93/212
,rder Manage#ent
bool Closed = rderClose(CloseTicketCloseLotsClose*riceargSli&&ageKed';
-- /rror Handling
i(Closed == alse'
)
/rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close ?ll <u$ rders /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "
MarketIno(argS$mbolM6/<I6'" TicketJ "CloseTicket
" *riceJ "Close*rice';
*rint(/rrLog';
,
else Counter;
,
,
,
Note th&t "e &re using void &s the )un'tion d&t& type# *e5%e deter(ined th&t there is no use)ul d&t&
to return )ro( this )un'tion so "e &re not re.uiring & return oper&tor in the )un'tion#
$ou5ll re'ognie the for loop &nd the =rder+elect() )un'tion )ro( our order loop 'ode# *e "ill loop
through the order pool &nd e4&(ine e&'h order to see i) "e need to 'lose it# I) the 'urrent order is &
buy (&r,et order &s indi'&ted by =>7U@ &nd i) it (&t'hes our 'h&rt sy(bol &nd (&gi' nu(ber
&rgu(ents "e5ll pro'eed to 'lose the order#
*e '&ll the =rder%icket() )un'tion to retrie%e the ti',et nu(ber )or the 'urrent order# 6ro( here
our 'ode is identi'&l to the buy (&r,et 'lose 'ode in pre%ious 'h&pters# Note the %ery l&st st&te(ent+
Counter--# I) the order "&s 'losed properly the Counter %&ri&ble "ill be de're(ented by one#
*e e4pl&ined e&rlier th&t "hen &n order is 'losed &ll o) the orders behind it h&%e their inde4es
de're(ented by one# I) "e did not de're(ent the 'ounter %&ri&ble &)ter 'losing &n order subse.uent
orders "ould be s,ipped#
There5s & %ery good re&son "hy "e loop through the orders )ro( oldest to ne"est+ The N6!
regul&tions th&t "ent into e))e't in su((er 2009 )or >S bro,ers re.uires th&t (ultiple orders pl&'ed
on the s&(e 'urren'y sy(bol be 'losed in the order th&t they "ere pl&'ed# This is '&lled the 6I6O
A)irst in )irst outB rule# 3ooping through the orders )ro( oldest to ne"est ensures th&t "e 'o(ply
"ith the 6I6O rule "hen 'losing orders#
;=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 94/212
EXPERT ADVISOR PROGRAMMING
To 'lose sell (&r,et orders using the &bo%e 'ode si(ply 'h&nge the order type to =>+<,, &nd the
Closerice to the sy(bol5s !s, pri'e# The sell order 'lose )un'tion '&n be %ie"ed in !ppendi4 D#
3et5s e4&(ine the 'ode to 'lose (ultiple pending orders# This e4&(ple "ill 'lose &ll buy stop orders#
The di))eren'e bet"een this 'ode &nd the 'ode to 'lose buy (&r,et orders &bo%e is th&t "e spe'i)y
=>7U@+%= &s our order type &nd "e use =rder6elete() to 'lose the orders#
0oid Close?ll<u$Sto&rders(string argS$mbol int argMagicBumber int argSli&&age'
)
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *<53ST*'
)
-- 6elete rder
int CloseTicket = rderTicket(';
%hile(IsTradeConte+t<us$('' Slee&(19';
bool Closed = rder6elete(CloseTicketKed';
-- /rror Handling
i(Closed == alse'
)
/rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close ?ll <u$ Sto& rders"
" /rror "/rrorCode"J "/rr6esc';?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "
MarketIno(argS$mbolM6/<I6'" ?skJ "
MarketIno(argS$mbolM6/?SP'" TicketJ "CloseTicket';
*rint(/rrLog';
,
else Counter;
,
,
,
This 'ode "ill "or, )or &ll types o) pending orders si(ply 'h&nge the order type 'o(p&rison to the
type o) order you "ish to 'lose# The order 'losing )un'tions )or &ll pending orders '&n be %ie"ed in
!ppendi4 D#
;<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 95/212
,rder Manage#ent
Trai"ing Stops
*e '&n &lso use our order loop to (odi)y (ultiple orders# ! 'o((on e4&(ple o) this is the tr&iling
stop# ! tr&iling stop (o%es the stop loss up or do"n "ith the order pri'e &s the order g&ins in pro)it#
This /lo',s in/ pro)it &nd pro%ides e4'ellent loss prote'tion#
The tr&iling stop is e4pressed &s & (&4i(u( nu(ber o) pips# 6or e4&(ple i) your tr&iling stop is =0
pips the stop loss "ill ne%er be (ore th&n =0 pips &"&y )ro( your pri'e# I) the pri'e re%erses &nd
the pro)it de'lines the stop loss "ill st&y "here it is# The stop only (o%es in the dire'tion o) pro)it
ne%er in re%erse#
*hen (odi)ying & tr&iling stop "e (ust 'he', to see i) the dist&n'e in pips bet"een the 'urrent
pri'e &nd the 'urrent stop loss is gre&ter th&t the tr&iling stop# I) so the stop loss "ill be (odi)ied so
th&t the dist&n'e )ro( the 'urrent pri'e in pips is e.u&l to the nu(ber o) pips in the tr&iling stop
setting#
The tr&iling stop is '&l'ul&ted rel&ti%e to the 'losing pri'e "hi'h is the 8id )or buy orders &nd the
!s, )or sell orders# Note th&t this is the opposite o) the opening pri'e# 3et5s e4&(ine the 'ode )or
(odi)ying & tr&iling stop# 6irst "e de'l&re the e4tern&l %&ri&ble )or our tr&iling stop setting+
e+tern double TrailingSto& = 29;
This 'ode 'he',s &ll buy (&r,et orders &nd (odi)ies the stop loss &s ne'ess&ry+
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN')
rderSelect(CounterS/L/CT<3*S';
double Ma+Sto&Loss = MarketIno(S$mbol('M6/<I6'
(TrailingSto& . *i&*oint(S$mbol(''';
Ma+Sto&Loss = Bormali>e6ouble(Ma+Sto&LossMarketIno(rderS$mbol('M6/6IAITS'';
double CurrentSto& = Bormali>e6ouble(rderSto&Loss('
MarketIno(rderS$mbol('M6/6IAITS'';
-- Modi$ Sto&
i(rderMagicBumber(' == MagicBumber QQ rderS$mbol(' == S$mbol('QQ rderT$&e(' == *<53 QQ CurrentSto& D Ma+Sto&Loss'
)
bool Trailed = rderModi$(rderTicket('rder&en*rice('Ma+Sto&Loss
rderTake*roit('9';
;:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 96/212
EXPERT ADVISOR PROGRAMMING
-- /rror Handling
i(Trailed == alse'
)
/rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("<u$ Trailing Sto& /rror "
/rrorCode"J "/rr6esc';?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "MarketIno(S$mbol('M6/<I6'
" TicketJ "CloseTicket" Sto&J "rderSto&Loss('" TrailJ "
Ma+Sto&Loss';
*rint(/rrLog';
,
,
,
!)ter sele'ting the order )ro( the pool "ith =rder+elect() "e deter(ine the (&4i(u( stop loss
dist&n'e by subtr&'ting our tr&iling stop setting (ultiplied by ipoint() )ro( the 'urrent 8id
pri'e# This is stored in the %&ri&ble 8ax+top,oss#
*e use the 3 )un'tion ormalie6ouble() to round the 8ax+top,oss %&ri&ble to the 'orre't
nu(ber o) digits &)ter the de'i(&l point# Pri'es in et&Tr&der '&n be .uoted up to eight de'i(&l
pl&'es# 8y using ormalie6ouble() "e round th&t do"n to or = digits A2-? digits )or MP$ p&irsB#
Ne4t "e retrie%e the stop loss o) the 'urrently sele'ted order &nd round it using
ormalie6ouble() ust to be sure# *e &ssign this %&lue to the %&ri&ble Current+top#
Then "e 'he', to see i) the 'urrent order needs to be (odi)ied# I) (&gi' nu(ber sy(bol &nd order
type (&t'h &nd the 'urrent stop loss ACurrent+topB is less th&n 8ax+top,oss then "e (odi)y the
order5s stop loss# *e p&ss the 8ax+top,oss %&ri&ble &s our ne" stop loss to the =rder8odif0()
)un'tion#
I) the =rder8odif0() )un'tion "&s not su''ess)ul the error h&ndling routine "ill run &nd the
'urrent pri'e in)or(&tion ti',et nu(ber 'urrent stop loss &nd (odi)ied stop loss "ill be printed to
the log#
The tr&iling stop 'onditions )or sell orders &re di))erent &nd need to be &ddressed sep&r&tely# Here&re the 'onditions to (odi)y & sell order+
-- Modi$ Sto&
i(rderMagicBumber(' == MagicBumber QQ rderS$mbol(' == S$mbol('
QQ =rder%0pe() LL =>+<,, QQ (Current+top O 8ax+top,oss QQ Current+top LL 2)'
;;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 97/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 98/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 99/212
,rder Manage#ent
Here is the e4tern&l %&ri&ble )or our bre&, e%en pro)it setting# The (ini(u( pro)it is spe'i)ied in pips#
e+tern double <reak/0en*roit = 42;
This 'ode "ill (odi)y the stop loss on &ll buy (&r,et orders to bre&, e%en on'e the order pro)it in
pips is e.u&l to or gre&ter th&n 7reak<venrofit# *e "ill not be 're&ting & )un'tion )or this but you
'&n do so i) you )eel it "ould be use)ul#
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
KereshKates(';
double *i&s*roit = <id rder&en*rice(';
double Min*roit = <reak/0en*roit . *i&*oint(rderS$mbol(''';
i(rderMagicBumber(' == MagicBumber QQ rderS$mbol(' == S$mbol('
QQ rderT$&e(' == *<53 QQ *i&s*roit F= Min*roit
QQ rder&en*rice(' R= rderSto&Loss(''
)
bool <reak/0en = rderModi$(rderTicket('rder&en*rice('
rder&en*rice('rderTake*roit('9';
i(<reak/0en == alse'
)
/rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("<u$ <reak /0en /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "<id" ?skJ "?sk
" TicketJ "CloseTicket" Sto&J "rderSto&Loss('" <reakJ "
Min*roit';
*rint(/rrLog';
,
,
,
*e subtr&'t the order opening pri'e )ro( the 'urrent 8id pri'e to '&l'ul&te the 'urrent pro)it in pips
&nd store this in ipsrofit# *e '&l'ul&te the (ini(u( pro)it in pips &nd store th&t in 8inrofit#I) ipsrofit is gre&ter th&n or e.u&l to 8inrofit then "e "ill (odi)y the stop loss to be e.u&l
to the order opening pri'e#
*e &lso 'he', to (&,e sure th&t the stop loss is not &lre&dy set &t the bre&, e%en pri'e# I)
=rder=penrice() is not e.u&l to =rder+top,oss() then "e '&n pro'eed#
91
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 100/212
EXPERT ADVISOR PROGRAMMING
5pdating t+e Expert Advisor
3et5s (odi)y the start() )un'tion o) our (o%ing &%er&ge 'ross e4pert &d%isor to re)le't the ne"
)un'tions "e h&%e 're&ted# 6irst "e "ill 'he', to see i) there &re &ny buy orders open be)ore "e
open (ore# Inste&d o) 'losing & single sell order "e "ill si(ply use the )un'tion to 'lose &ll sell
orders# This (ethod does not re.uire us to use &n order ti',et#
-- <u$ rder
i(#astM? F Slo%M? QQ <u$Ticket == 9 QQ 7u08arketCount(+0mbol()D8a!icumber) LL 2'
)
if(+ell8arketCount(+0mbol()D8a!icumber) O 2)
&
Close;ll+ell=rders(+0mbol()D8a!icumberD+lippa!e)M
'
SellTicket = 9;
<u$Ticket = &en<u$rder(S$mbol('LotSi>e5seSli&&ageMagicBumber';,
*e used the )un'tion 7u08arketCount() th&t "e de)ined on p&ge ; to return the nu(ber o) buy
orders 'urrently open# *e "ill ,eep the 7u0%icket 'he', in so th&t only <ern&ting buy7sell orders
&re opened#
The )un'tion Close;ll+ell=rders() 'loses &ny sell orders th&t &re open# *e 'he',
+ell8arketCount() )irst to see i) there &re &ny sell orders to 'lose# This )un'tion does not re.uire
&n order ti',et unli,e the Close+ell=rder() )un'tion in 'h&pter # It is re'o((ended you use this
(ethod )or 'losing out opposite orders in your E! &s it is (ore robust#
The rest o) the buy order pl&'e(ent 'ode is the s&(e &s be)ore# The 'orresponding sell order
pl&'e(ent 'ode is belo"+
-- Sell rder
i(#astM? D Slo%M? QQ SellTicket == 9 QQ +ell8arketCount(+0mbol()D8a!icumber) LL 2'
)
if(7u08arketCount(+0mbol()D8a!icumber) O 2)
&
Close;ll7u0=rders(+0mbol()D8a!icumberD+lippa!e)M
'
<u$Ticket = 9;
SellTicket = &enSellrder(S$mbol('LotSi>e5seSli&&ageMagicBumber';
,
92
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 101/212
,rder Manage#ent
Ne4t let5s &dd the tr&iling stop )un'tions to our order# *e5ll per)or( the tr&iling stop routine &)ter our
order pl&'e(ent# !s &bo%e "e "ill 'he', )or open buy or sell orders be)ore '&lling the tr&iling stop
)un'tion# 3et5s &dd the )ollo"ing e4tern&l %&ri&bles to our E!+
e+tern int TrailingSto& = 29;
e+tern int Minimum*roit = 29;
This is the 'ode to 'he', &nd (odi)y the tr&iling stops# Note th&t "e 'he', to see i) there is &n entry
)or the %railin!+top setting# I) it5s set to 0 it is e))e'ti%ely dis&bled+
i(<u$MarketCount(S$mbol('MagicBumber' F 9 QQ TrailingSto& F 9'
)
<u$TrailingSto&(S$mbol('TrailingSto&Minimum*roitMagicBumber';
,
i(SellMarketCount(S$mbol('MagicBumber' F 9 QQ TrailingSto& F 9'
)SellTrailingSto&(S$mbol('TrailingSto&Minimum*roitMagicBumber';
,
$ou '&n %ie" these 'h&nges in 'onte4t in !ppendi4 C#
9?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 102/212
EXPERT ADVISOR PROGRAMMING
C+apter -&rder Conditions and #ndi$ators
*e5%e spent the l&st )e" 'h&pters 're&ting )un'tions th&t '&rry out the order (e'h&ni's th&t &re
'o((on to e%ery e4pert &d%isor# These )un'tions &re (e&nt to be used in & %&riety o) tr&ding
situ&tions &nd should be &s reus&ble &nd )le4ible &s possible# This &llo"s us to 'on'entr&te on 'oding
the uni.ue tr&ding 'onditions )or our tr&ding syste(#
This is "here (ost o) your "or, is going to be )o'used getting the e4pert &d%isor to tr&de your
syste( &s &''ur&tely &s possible# *e5ll need to identi)y the e4&'t 'onditions )or opening &nd 'losing
orders &s "ell &s deter(ining stop loss &nd t&,e pro)it pri'es# !l(ost e%ery tr&ding syste( uses pri'e
&nd7or indi'&tor d&t&# 3et5s e4&(ine the "&ys "e '&n &''ess &nd use this in)or(&tion in our e4pert
&d%isors#
Pri$e 0ata
!long "ith the 'urrent 8id or !s, pri'e A"hi'h "e5%e &lre&dy 'o%ered in pre%ious 'h&ptersB you (&y
need to use b&r pri'e d&t& n&(ely the !ig! lo% open or close o) & p&rti'ul&r b&r# 6or the 'urrent
'h&rt you '&n use the prede)ined series &rr&ys ?i!hIJ ,owIJ =penIJ &nd CloseIJ#
!n &rr&y is & %&ri&ble th&t holds (ultiple %&lues# $ou 'y'le through the %&lues by 'h&nging the inde4
"hi'h is 'ont&ined in the s.u&re br&',ets# 6or e4&(ple =penI2J is the open pri'e o) the 'urrent b&r#
0 is the inde4 &nd by 'h&nging it "e '&n get the open pri'e o) other b&rs# The b&r pre%ious to the'urrent b&r "ould h&%e &n inde4 o) 1 &nd so on# *e "ill )re.uently be using either the 'urrent b&r or
the pre%ious b&r5s pri'e %&lues#
I) you need & high lo" open or 'lose %&lue )or & sy(bol other th&n the 'urrent 'h&rt or i) you need
pri'e d&t& )or & period other th&n the 'urrent 'h&rt period you '&n use the )un'tions i?i!h()
i,ow() i=pen() &nd iClose()# Here5s the synt&4 o) these )un'tions using iClose() &s our
e4&(ple+
double iClose(string Symbol int Period int S'ift'
• Sym!o" The sy(bol o) the 'urren'y p&ir to use#
• Period The period o) the 'h&rt to use in (inutes#
• S+ift The b&',"&rd shi)t rel&ti%e to the 'urrent b&r#
9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 103/212
,rder "onditions and Indicators
3et5s use iClose() to get & 'lose pri'e )or & di))erent 'h&rt period# 6or e4&(ple "e5re using & 1 hour
'h&rt but "e "&nt to 'he', the 'lose pri'e o) the pre%ious b&r on the hour 'h&rt+
double H:Close = iClose(B5LL*/KI6H:1';
U,, re)ers to the 'urrent 'h&rt sy(bol# <5#=6>?4 is &n integer 'onst&nt th&t re)ers to the H 'h&rt
period# is our shi)t "hi'h is the b&r pre%ious to the 'urrent b&r# 3et5s use ¬her e4&(ple th&t
returns the 'lose o) the 'urrent b&r on ¬her 'h&rt+
double A<*Close = iClose(A<*5S699';
B7U+6 is the sy(bol th&t "e5re using# *e5%e spe'i)ied 2 &s our period so the 'h&rt period "e5re
'he',ing on B7U+6 "ill be the s&(e &s our 'urrent 'h&rt# The shi)t is 2 "hi'h is the 'urrent b&r#
$ou '&n use & loop oper&tor su'h &s for or while to in're(ent the +hift p&r&(eter &nd 'y'le
through the 'h&rt history# This for loop retrie%es the 'lose pri'e )or e&'h o) the l&st ten b&rs &nd
prints it to the log+
or(int Count = 9; Count D= W; CountNN'
)
double CloseShit = iClose(B5LL9Count';
*rint(CountN" "NCloseShit';
,
#ndi$ators
The (&ority o) tr&ding syste(s use indi'&tors to deter(ine tr&ding sign&ls# et&Tr&der in'ludes o%er
20 'o((on indi'&tors in'luding (o%ing &%er&ge !CD RSI &nd sto'h&sti's# 3 h&s built-in
)un'tions )or the sto', indi'&tors# $ou '&n &lso use 'usto( indi'&tors in your e4pert &d%isor#
Trend #ndi$ators
3et5s t&,e & loo, &t the indi'&tor "e5%e been using throughout this boo,+ the (o%ing &%er&ge# The
(o%ing &%er&ge is & trend indi'&tor# It sho"s "hether the pri'e h&s (o%ed up or do"n o%er the
indi'&tor period# The (o%ing &%er&ge 'onsists o) & single line dr&"n on the 'h&rt th&t sho"s the
&%er&ge pri'e o%er the l&st x nu(ber o) b&rs#
Here is the synt&4 )or the (o%ing &%er&ge )un'tion+
9=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 104/212
EXPERT ADVISOR PROGRAMMING
double iM?(string Symbol int Timeframe int MPeriod int MS'ift int MMet'od
int MPrice int S'ift'
• Sym!o" The sy(bol o) the 'h&rt to &pply the (o%ing &%er&ge to#
•
Timeframe The ti(e period o) the 'h&rt to &pply the (o%ing &%er&ge to#
E%ery indi'&tor )un'tion in 3 st&rts o)) "ith these t"o p&r&(eters# !)ter this &re the indi'&tor-
spe'i)i' p&r&(eters# These 'orrespond to the 'ontents o) the P&r&(eters t&b in the Indicator
properties#
• MAPeriod The loo,-b&', period o) the (o%ing &%er&ge#
!l(ost e%ery indi'&tor h&s &t le&st one period p&r&(eter# ost indi'&tors &re '&l'ul&ted using & pri'e
series t&,en )ro( the pre%ious b&rs# 6or e4&(ple & period setting o) 10 "ould (e&n th&t the
indi'&tor uses pri'e d&t& )ro( the l&st ten b&rs to '&l'ul&te the indi'&tor %&lue#
• MAS+ift The )or"&rd shi)t o) the (o%ing &%er&ge line in b&rs# This is di))erent th&n the
+hift p&r&(eter belo"#
• MAMet+od The '&l'ul&tion (ethod o) the (o%ing &%er&ge# Choi'es in'lude si(ple
e4ponenti&l s(oothed or line&r "eighted#
!ny indi'&tor th&t uses & (o%ing &%er&ge (&y gi%e you the option to 'hoose the ! '&l'ul&tion
(ethod# *e5ll t&l, &bout (o%ing &%er&ge (ethods l&ter in the 'h&pter#
• MAPri$e The pri'e &rr&y to use "hen '&l'ul&ting the (o%ing &%er&ge#
This '&n be the 'lose open high lo" or so(e type o) &%er&ge su'h &s (edi&n typi'&l or "eighted
pri'es# *e5ll dis'uss &pplied pri'e 'onst&nts l&ter in the 'h&pter#
• S+ift The b&',"&rd shi)t o) the b&r to return the '&l'ul&tion )or#
The +hift p&r&(eter is the )in&l p&r&(eter in &ny indi'&tor )un'tion# This is the inde4 o) the b&r to
return the indi'&tor %&lue )or# ! %&lue o) 0 returns the indi'&tor %&lue )or the 'urrent b&r# ! %&lue o) ?
"ill return the indi'&tor %&lue )ro( ? b&rs &go#
The (o%ing &%er&ge &nd si(il&r indi'&tors &re dr&"n dire'tly on the 'h&rt# $ou '&n 're&te tr&de
'onditions b&sed on the rel&tionship bet"een indi'&tors &nd pri'e# Our (o%ing &%er&ge 'ross is &n
e4&(ple o) & pri'e rel&tionship bet"een t"o indi'&tors# *hen one indi'&tor5s pri'e is gre&ter th&n the
other & buy or sell sign&l is gener&ted#
9<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 105/212
,rder "onditions and Indicators
$ou 'ould &lso gener&te tr&de sign&ls "hen the 'urrent pri'e p&sses &bo%e or belo" &n indi'&tor line#
6or e4&(ple the 8ollinger 8&nds indi'&tor '&n be used to gener&te tr&ding sign&ls b&sed on the
lo'&tion o) the pri'e in 'o(p&rison to the upper &nd lo"er b&nds#
&s$i""ators
The other (&or type o) indi'&tor is &n oscillator # Os'ill&tors &re dr&"n in & sep&r&te "indo" &nd &s
their n&(e suggests they os'ill&te bet"een high &nd lo" pri'e e4tre(es# Os'ill&tors &re either
'entered &round & neutr&l &4is Agener&lly 0B or they &re bound by &n upper or lo"er e4tre(e Asu'h
&s 0 &nd 100B# E4&(ples o) os'ill&tors in'lude (o(entu( sto'h&sti's &nd RSI#
Os'ill&tors indi'&te overboug!t &nd oversold le%els# *hile they '&n be used &s &n indi'&tor o) trend
they &re gener&lly used to lo'&te &re&s o) pending re%ers&l# These &re used to produ'e counter&trend
tr&ding sign&ls#
3et5s loo, &t & popul&r os'ill&tor the stoc!astic # Sto'h&sti's 'onsists o) t"o lines the sto'h&sti' lineA&lso '&lled the Q lineB &nd the sign&l line Athe QD lineB# The sto'h&sti' os'ill&tes bet"een 0 &nd
100# *hen the sto'h&sti' is &bo%e :0 it is s&id to be o%erbought &nd pending & possible re%ers&l# I)
it is belo" ?0 it is s&id to be o%ersold#
Here is the synt&4 )or the sto'h&sti' indi'&tor+
double iStochastic(string Symbol int Timeframe int PPeriod int (period int Slo!ing
int MMet'od int Price)ield int Mode int S'ift*
*e5re &lre&dy )&(ili&r "ith the )irst t"o p&r&(eters +0mbol &nd %imeframe# 3et5s e4&(ine the
indi'&tor-spe'i)i' p&r&(eters+
• @Period The period )or the Q line#
• 0Period The period )or the QD line#
• S"owing The slo"ing %&lue )or the sto'h&sti'# ! lo"er %&lue indi'&tes & )&st sto'h&sti'
"hile & higher %&lue indi'&tes & slo"er one#
• MAMet+od The QD line h&s & (o%ing &%er&ge (ethod &pplied to it# This is the s&(e
setting &s )or the (o%ing &%er&ge# *e5ll re%ie" the (o%ing &%er&ge (ethods shortly#
• Pri$e,ie"d Deter(ines the pri'e d&t& used )or the Q line# This is either /0 Lo%12ig! or 30
"lose1"lose# ! %&lue o) 1 (&,es it (ore li,ely th&t the sto'h&sti' "ill tr&de &t it5s e4tre(es#
• Mode Deter(ines the sto'h&sti' line to '&l'ul&te 30 45 line or 60 4D line$
9:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 106/212
EXPERT ADVISOR PROGRAMMING
3et5s t&,e & (o(ent to t&l, &bout the 8ode p&r&(eter# So(e indi'&tors dr&" (ultiple lines on the
'h&rt# The sto'h&sti' h&s t"o# *e "ill need to '&ll the i+tochastic() )un'tion )or both the Q &nd
QD lines &s sho"n belo"+
double PLine = iStochastic(B5LL9P*eriod6*eriodSlo%ingM?Method*rice99';
double 6Line = iStochastic(B5LL9P*eriod6*eriodSlo%ingM?Method*rice19';
Note th&t the 8ode p&r&(eter is 0 )or the Q line &nd 1 )or the QD line# The 3 Re)eren'e topi'
tandard "onstants - Indicator lines lists the %&lid integer 'onst&nts )or the %&rious indi'&tors th&t
use the 8ode p&r&(eter#
$ou '&n gener&te tr&de sign&ls b&sed on the rel&tionship bet"een the indi'&tor lines &nd 'ert&in
indi'&tor le%els su'h &s the o%erbought &nd o%ersold le%els o) :0 &nd ?0 respe'ti%ely# $ou '&n &lso
e%&lu&te tr&de sign&ls b&sed on the indi'&tor lines5 rel&tionship to e&'h other# 6or e4&(ple you (&y
"&nt to open & buy order only "hen the Q line is &bo%e the QD line# Here &re so(e e4&(ple
'onditions+
i(PLine D U9' -- <u$ i stochastic is not o0erbought
i(PLine F 6Line' -- <u$ i XP is greater than X6
The built-in indi'&tor )un'tions &re in the 3 Re)eren'e under Tec!nical indicators# I) you5d li,e
(ore in)or(&tion on &n indi'&tor5s us&ge or (ethod o) '&l'ul&tion 'onsult the te'hni'&l &n&lysis
se'tion o) the 3 "ebsite &t http://ta.mql4.com/ #
Custom #ndi$ators
Hundreds o) 'usto( indi'&tors )or et&Tr&der &re &%&il&ble online# I) you de'ide to use & 'usto(
indi'&tor in your e4pert &d%isor & little leg"or, "ill h&%e to be done# It is best i) you h&%e the .mq4
sour'e 'ode )ile "hen using & 'usto( indi'&tor# *hile it is possible to use & 'usto( indi'&tor "ithout
it h&%ing the sour'e 'ode "ill (&,e it e&sier to )igure out the bu))er inde4es )or the 8ode p&r&(eter#
3 h&s & built-in )un'tion )or h&ndling 'usto( indi'&tors iCustom()# Here is the synt&4+
double iCustom(string Symbol int Timeframe string $ndicatorName $ndicator Parameters,
int Mode int S'ift';
$ou5re &lre&dy )&(ili&r "ith +0mbol %imeframe 8ode &nd +hift )ro( e&rlier in the 'h&pter# 3et5s
st&rt "ith #ndicatorame# This is the n&(e o) the indi'&tor )ile e4&'tly &s it &ppe&rs in the "usto#
Indicators list in the Navigator "indo"# 6or e4&(ple /Slope Dire'tion 3ine/ or /superKsign&l/#
9;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 107/212
,rder "onditions and Indicators
#ndicator arameters is "here "e insert the p&r&(eters )or the 'usto( indi'&tor# The Inputs t&b
in the "usto# Indicator Properties "indo" "ill sho" the p&r&(eters )or the 'usto( indi'&tor# The
i'ons to the le)t o) e&'h p&r&(eter "ill indi'&te the d&t& type# I) you don5t h&%e the .mq4 )ile )or &n
indi'&tor you5ll h&%e to deter(ine the indi'&tor p&r&(eters )ro( this di&log#
,ig -.% The 'usto( indi'&tor input di&log
! e&sier "&y o) )inding the p&r&(eters is to 'he', the extern %&ri&bles &t the beginning o) the
indi'&tor sour'e 'ode )ile# !ll indi'&tor p&r&(eters their d&t& types &nd de)&ult %&lues "ill be listed
here $ou '&n si(ply 'opy &nd p&ste this 'ode to the e4tern&l %&ri&bles se'tion o) your e4pert
&d%isor#
E&'h &nd e%ery e4tern&l %&ri&ble in & 'usto( indi'&tor (ust h&%e & 'ounterp&rt p&r&(eter in the
iCustom() )un'tion &nd they (ust be in the order th&t they &ppe&r in the indi'&tor# $ou '&n use &
'onst&nt )or p&r&(eters th&t do not need to be 'h&nged Asu'h &s in)or(&tion&l strings or non-
essenti&l settingsB#
Here5s &n e4&(ple+ The popul&r 'usto( indi'&tor Slope Dire'tion 3ine h&s these e4tern&l %&ri&bles
listed in the sour'e 'ode# *e5ll 're&te e4tern&l %&ri&bles )or these settings in our e4pert &d%isor+
-- in&ut &arameterse+tern int &eriod=V9;
e+tern int method=8; -- M6/SM?
e+tern int &rice=9; -- *KIC/CLS/
99
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 108/212
EXPERT ADVISOR PROGRAMMING
*e5ll use the identi)iers +lopeeriod +lope8ethod &nd +loperice )or the e4tern&l %&ri&bles in our
e4pert &d%isor#
-- /+ternal 0ariables
e+tern int Slo&e*eriod = V9;
e+tern int Slo&eMethod = 8;
e+tern int Slo&e*rice = 9;
Here is ho" the iCustom() )un'tion "ill loo, )or this p&rti'ul&r indi'&tor &long "ith the e4tern&l
%&ri&bles+
iCustom(B5LL9"Slo&e 6irection Line"Slo&e*eriodSlo&eMethodSlo&e*rice99';
U,, indi'&tes th&t "e &re using the 'urrent 'h&rt sy(bol &nd 2 is the 'urrent 'h&rt period# +lope
6irection ,ine is the n&(e o) the indi'&tor )ile# +lopeeriod +lope8ethod &nd +loperice
&re the three indi'&tor p&r&(eters# *e &re using the de)&ult 8ode inde4 o) 2 &nd the +hift is the'urrent b&r#
!lthough the Slope Dire'tion 3ine indi'&tor is dr&"n &s & single line it is &'tu&lly 'o(posed o) t"o
di))erent bu))ers# Depending on "hether the indi'&tor pri'e is (o%ing up or do"n the 'olor A&nd the
bu))erB 'h&nge#
I) you &tt&'h the indi'&tor to & 'h&rt &nd %ie" the Data
'indo% in et&Tr&der you5ll see t"o %&lues )or the Slope
Dire'tion 3ine# The )irst %&lue displ&ys & pri'e "hen the
indi'&tor %&lue is in're&sing# The line is blue by de)&ult# These'ond %&lue displ&ys & pri'e "hen the indi'&tor %&lue is
de're&sing# This line is red by de)&ult#
*e need to deter(ine the 8ode inde4 )or both o) these
lines# The e&siest "&y to do this is to loo, &t the sour'e
'ode# In the init() )un'tion you "ill see se%er&l lines o)
'ode th&t &re used to de'l&re &nd set the properties )or the
indi'&tor bu))ers+
SetInde+<uer(9 5&trend';
SetInde+<uer(1 6ntrend';
SetInde+<uer(4 /+tMa&<uer';
!!!
SetInde+St$le(96K?OLIB/ST3L/SLI64';
SetInde+St$le(16K?OLIB/ST3L/SLI64';
100
,ig -.' D&t& *indo"
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 109/212
,rder "onditions and Indicators
The )irst +et#ndex7uffer() )un'tion sets &n indi'&tor bu))er "ith &n inde4 o) 0 &nd uses the &rr&y
Uptrend# *e '&n guess )ro( the &rr&y n&(e th&t this &pplies to to the blue indi'&tor line# The
se'ond )un'tion does li,e"ise )or )or the &rr&y 6n%rend# Note the +et#ndex+t0le() )un'tions &t the
botto( th&t sets bu))ers 0 &nd 1 to dr&" & solid line#
The third bu))er "ith the inde4 o) 2 &nd the &rr&y <xt8ap7uffer is used )or '&l'ul&tion only# *e '&nthere)ore 'on'lude th&t 0 &nd 1 &re the bu))er inde4es th&t 'ont&in our indi'&tor pri'e in)or(&tion#
8&sed on the &rr&y identi)iers 0 is the uptrend line &nd 1 is the do"ntrend# Here is ho" "e de'l&re
our indi'&tors+
double Slo&e5& = iCustom(B5LL9"Slo&e 6irection Line"Slo&e*eriodSlo&eMethod
Slo&e*rice91';
double Slo&e6o%n = iCustom(B5LL9"Slo&e 6irection Line"Slo&e*eriodSlo&eMethod
Slo&e*rice11';
Note th&t the 8ode p&r&(eter the ne4t to l&st one h&s been set to the &ppropri&te indi'&tor
bu))er inde4 2 )or +lopeUp &nd )or +lope6own# The +hift p&r&(eter the %ery l&st one h&s
been set to "hi'h 'he',s the 'losing %&lue o) the l&st b&r#
It5s & good ide& to double 'he', th&t you5re using the 'orre't 8ode p&r&(eters# !dd & rint()
)un'tion to your e4pert &d%isor &nd run & b&', test in the Str&tegy Tester using /Open pri'es only/ &s
the testing (odel# &,e sure the +hift p&r&(eter is set to 1 in the iCustom() )un'tion#
*rint("Slo&e 5&J "NSlo&e5&N" Slo&e 6o%nJ "NSlo&e6o%nN" TimeJ "NTimeToStr(Time[1]'';
The rint() )un'tion prints the %&lue o) our indi'&tor bu))ers to the log &long "ith the ti(e &nd
d&te o) the pre%ious b&r# $ou '&n %ie" the log under the .ournal t&b in the Str&tegy Tester "indo"#
Here is the output o) the rint() )un'tion in the log+
Slo&e 5&J 41:U:V8@:U!99999999 Slo&e 6o%nJ 1!29:V8W99 TimeJ 499W!11!4@ 1@J99
The %&lue )or +lopeUp 21:;?<: is & %ery l&rge integer th&t represents the <8%@>9;,U< st&te o)
& 'usto( indi'&tor# $ou '&n &'tu&lly use this &s & tr&ding 'ondition# +lope6own returns the indi'&tor
%&lue o) the pre%ious b&r# %ime indi'&tes the b&r th&t "e "&nt to )ind on the 'h&rt#
Cli', the ,pen "!art button in the Str&tegy Tester "indo" to open & 'h&rt "ith your indi'&tor
&lre&dy &pplied# 6ind the b&r indi'&ted in the log by %ime &nd (&,e sure the indi'&tor %&lues in the
D&t& *indo" (&t'h those printed in the log# I) not &dust the 8ode p&r&(eter in the iCustom()
)un'tion until you )ind the 'orre't bu))er#
101
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 110/212
EXPERT ADVISOR PROGRAMMING
Here5s ho" "e "ould use the Slope Dire'tion 3ine indi'&tor in our e4pert &d%isor# I) the slope is
trending up"&rd +lopeUp "ill return & pri'e %&lue "hile +lope6own "ill return <8%@>9;,U< or
21:;?<:# The opposite &pplies "hen the slope is trending do"n"&rd#
i(Slo&e5& R= /M*T3?L5/ QQ Slo&e6o%n == /M*T3?L5/' -- <u$
i(Slo&e5& == /M*T3?L5/ QQ Slo&e6o%n R= /M*T3?L5/' -- Sell
These 'onditions si(ply 'he', to see "hi'h line is e.u&l to <8%@>9;,U< &nd "hi'h line is not#
#ndi$ator Constants
Time ,rames
&ny )un'tions in 3 in'luding indi'&tor &nd pri'e )un'tions &''ept & ti(e )r&(e p&r&(eter# !s
indi'&ted be)ore i) "e use & %imeframe p&r&(eter o) 0 the 'urrent 'h&rt ti(e )r&(e "ill be used# I)
"e "ish to use & di))erent ti(e )r&(e "e "ill need to spe'i)y the ti(e )r&(e in (inutes# 6or
e4&(ple = is = H1 is <0 &nd H is 20# *e '&n &lso use 'onst&nts to indi'&te the ti(e )r&(e+
• PER#&0M% 1 (inute#
• PER#&0M1 = (inute#
• PER#&0M%1 1= (inute#
• PER#&0M8( ?0 (inute#
• PER#&0?% 1 hour A<0 (inutesB#
• PER#&0?4 hour A20 (inutesB#
• PER#&00% D&ily A10 (inutesB#
App"ied Pri$e
The &pplied pri'e indi'&tor p&r&(eter indi'&tes the pri'e series to use "hen '&l'ul&ting the indi'&tor
%&lue# $ou "ill gener&lly use the 'lose to '&l'ul&te indi'&tor %&lues <hough you (&y "ish to use
other %&lues &s "ell# Here is the list o) pri'e series &nd their &sso'i&ted 'onst&nts &long "ith the
integer %&lue+
• PR#CECL&SE 0+ Close pri'e#
• PR#CE&PE 1+ Open pri'e#
• PR#CE?#9? 2+ High pri'e#
102
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 111/212
,rder "onditions and Indicators
• PR#CEL&) ?+ 3o" pri'e#
• PR#CEME0#A + edi&n pri'e 72ig!)Lo%816 #
• PR#CETP#CAL =+ Typi'&l pri'e 72ig!)Lo%)"lose819#
• PR#CE)E#9?TE0 <+ *eighted pri'e 72ig!)Lo%)"lose)"lose81:#
Moving Average Met+ods
Indi'&tors th&t use & (o%ing &%er&ge &s p&rt o) their '&l'ul&tion (&y h&%e & p&r&(eter to &dust the
(o%ing &%er&ge '&l'ul&tion (ethod# The (o%ing &%er&ge line "ill be dr&"n di))erently depending on
the '&l'ul&tion (ethod# Here &re the (o%ing &%er&ge (ethod 'onst&nts "ith their 'orresponding
integer %&lues+
• M&0ESMA 0+ Si(ple (o%ing &%er&ge# C&l'ul&tes the (e&n o) the pri'e d&t&#
•
M&0EEMA 1+ E4ponenti&l (o%ing &%er&ge# Gi%es (ore "eight to re'ent pri'e d&t& &nde4ponenti&lly less "eight to older pri'e d&t&# ! %ery popul&r (o%ing &%er&ge#
• M&0ESMMA 2+ S(oothed (o%ing &%er&ge# ! si(ple (o%ing &%er&ge '&l'ul&ted "ith &
s(oothing e.u&tion# Cre&tes & s(ooth but less responsi%e line#
• M&0EL)MA ?+ 3ine&r "eighted (o%ing &%er&ge# Si(il&r to the e4ponenti&l (o%ing
&%er&ge but gi%es in're&sed "eight to the (ost 'urrent pri'e#
Eva"uating Trade Conditions
*e use the 'ondition&l oper&tors if &nd else to e%&lu&te our tr&ding 'onditions# $ou5%e &lre&dy seenthese used in this boo, but )or you ne" progr&((ers & .ui', re%ie" is in order#
The if oper&tor e%&lu&tes & true or )&lse 'ondition# I) the 'ondition is true the 'ode i((edi&tely
&)ter the if st&te(ent is e4e'uted# I) the 'ondition is )&lse it "ill s,ip &he&d to the 'ode )ollo"ing
the i) blo',+
i(<u$Condition == true'
)
&en<u$rder(!!!';
,
I) there is only one st&te(ent )ollo"ing the if oper&tor it '&n be "ritten li,e this+
i(<u$Condition == true' &en<u$rder(!!!';
10?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 112/212
EXPERT ADVISOR PROGRAMMING
ultiple st&te(ents (ust be en'losed in br&'es#
The else oper&tor e%&lu&tes &n <ern&te 'ondition pro%ided th&t the pre%ious if st&te(entAsB &re
)&lse# $ou '&n 'o(bine else &nd if to 're&te &n <ern&te 'ondition th&t "ill only be e4e'uted i) it5s
true#
6or e4&(ple this 'ode e%&lu&tes three 'onditions in order# I) one o) the( is true only th&t blo', o)
'ode "ill be e4e'uted# I) none o) the( &re true none o) the( "ill be e4e'uted+
i(Condition1 == true' -- /+ecute condition 1
else i(Condition4 == true' -- /+ecute condition 4
else i(Condition8 == true' -- /+ecute condition 8
The else oper&tor '&n be used by itsel) &t the end o) &n if-else se.uen'e to indi'&te & 'ondition
th&t "ill be e4e'uted by de)&ult i) &ll o) the other i) oper&tors &re )&lse# !s &bo%e only one o) the
'onditions "ill be e4e'uted+
i(Condition1 == true' -- /+ecute condition 1
else i(Condition4 == true' -- /+ecute condition 4
else
)
-- /+ecute condition 8 i 1 and 4 are alse
,
I) you h&%e (ultiple if oper&tors "ithout &ny else oper&tors e&'h one "ill be e4e'uted i) it is true
it doesn5t (&tter "hether the subse.uent if st&te(ent is true or )&lse+
i(Condition1 == true' -- /+ecute condition 1
i(Condition4 == true' -- /+ecute condition 4
Re"ation &perations
*e begin e%&lu&ting true &nd )&lse 'onditions by 'o(p&ring %&lues using gre&ter th&n less th&n
e.u&l to not e.u&l to &nd so on# Here5s & list o) rel&tion oper&tions+
• LL EBua" To I) x LL 0 the 'ondition is true#
• O 9reater T+an I) x O 0 the 'ondition is true#
• R Less T+an I) x R 0 the 'ondition is true#
• OL 9reater T+an or EBua" To I) x OL 0 the 'ondition is true#
10
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 113/212
,rder "onditions and Indicators
• RL Less T+an or EBua" To i) x RL 0 the 'ondition is true#
• TL ot EBua" To I) x TL 0 the 'ondition is true#
Note th&t the e.u&l to oper&tor ALLB is not the s&(e &s the &ssign(ent oper&tor ALBL The &ssign(ent
oper&tor is used "hen &ssigning & %&lue to & %&ri&ble# The e.u&l to oper&tor is used to e%&lu&te &
true7)&lse 'ondition# This is & 'o((on synt&4 error &nd one you should "&t'h out )or#
$ou '&n 'o(p&re &ny t"o %&lues &s long &s they &re o) the s&(e d&t& type# $ou '&n 'o(p&re &
boole&n %&lue to the 'onst&nts true or false# $ou '&n 'o(p&re & string integer or double %&ri&ble
to &n &ppropri&te 'onst&nt %&lue or to ¬her %&ri&ble o) the s&(e type#
2oo"ean &perations
*e use the boole&n oper&tors !ND ANNB &nd OR AQQB to 'o(bine rel&tion oper&tions# The !ND
oper&tor e%&lu&tes "hether &ll 'onditions &re true# I) so the entire st&te(ent is true# I) &ny o) the'onditions &re )&lse the entire st&te(ent is )&lse#
i(<ooleanar1 == true QQ Indicator1 F Indicator4'
)
-- &en order
,
I) 7oolean9ar is e.u&l to true &nd #ndicator is gre&ter th&n #ndicator1 the st&te(ent
e%&lu&tes to true &nd the 'ode bet"een the br&'es is run# I) either o) these 'onditions &re )&lse the
entire st&te(ent e%&lu&tes to false &nd the 'ode in the br&'es is not run# There '&n be &ny nu(ber
o) 'onditions 'o(bined together "ith the NN oper&tor &nd they (ust &ll e%&lu&te to true#
The OR oper&tor e%&lu&tes "hether &ny one o) the 'onditions &re true# I) &t le&st one 'ondition is
true the entire st&te(ent e%&lu&tes to true# I) &ll o) the 'onditions &re )&lse the st&te(ent
e%&lu&tes to false#
i(<ooleanar1 == true 77 Indicator1 F Indicator4'
I) either 7oolean9ar is e.u&l to true or #ndicator is gre&ter th&n #ndicator1 the st&te(ent is
e%&lu&ted to true# I) both o) these 'onditions &re )&lse the st&te(ent e%&lu&tes to false#
$ou '&n 'o(bine !ND &nd OR oper&tions to 're&te (ore 'o(ple4 tr&ding 'onditions# *hen doing so
use p&rentheses to est&blish the order o) oper&tions#
10=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 114/212
EXPERT ADVISOR PROGRAMMING
i((<ooleanar1 == true QQ Indicator1 F Indicator4' 77 <ooleanar1 == alse'
The st&te(ent (7oolean9ar LL true NN #ndicator O #ndicator1) is e%&lu&ted )irst# I) both
o) these 'onditions &re true the st&te(ent e%&lu&tes to true &nd "e &re le)t "ith &n OR oper&tion+
i(true 77 <ooleanar1 == alse'
This st&te(ent &uto(&ti'&lly e%&lu&tes to true sin'e one o) the 'onditions is &lre&dy true# 8ut "h&t i)
(7oolean9ar LL true NN #ndicator O #ndicator1) e%&lu&tes to )&lse
i(alse 77 <ooleanar1 == alse'
I) the 'ondition 7oolean9ar LL false e%&lu&tes to true then the entire st&te(ent is true# AIn
other "ords i) 7oolean9ar is set to false th&t 'ondition e%&lu&tes to true#B Other"ise the
st&te(ent is )&lse#
It5s possible to 're&te 'o(ple4 boole&n oper&tions using !ND OR &nd p&rentheses to 'ontrol the
order o) oper&tions# 8e sure to "&t'h the lo'&tions o) your p&rentheses &s one "rong p&renthesis
'&n '&use the st&te(ent to e%&lu&te di))erently &nd & (issing p&renthesis 'ould le&d to so(e tedious
debugging#
Turning An #ndi$ator &n and &ff
$ou '&n use the !ND7OR e4&(ple in the pre%ious se'tion to turn &n indi'&tor on &nd o))# 3et5s s&yyour E! uses (ultiple indi'&tors &nd you5d li,e to be &ble to s"it'h indi'&tors on &nd o))# Here5s ho"
"e do it# 6irst let5s de'l&re &n e4tern&l boole&n %&ri&ble to use &s the on7o)) s"it'h# *e5ll use the
sto'h&sti' indi'&tor in this e4&(ple+
e+tern bool 5seStochastic = true;
*e de)ine t"o sets o) 'onditions )or our indi'&tor &n /on/ st&te &nd &n /o))/ st&te# The on st&te
'onsists o) the on7o)) %&ri&ble being set to true &long "ith the order opening 'ondition# The o)) st&te
si(ply 'onsists o) the on7o)) %&ri&ble being set to )&lse#
i((5seStochastic == true QQ Pline F 6line' 77 5seStochastic == alse'
)
-- <u$ order
,
10<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 115/212
,rder "onditions and Indicators
The st&te(ent (Use+tochastic LL true NN Fline O 6line) is our /on/ st&te# I) the
Use+tochastic e4tern&l %&ri&ble is set to true &nd the tr&ding 'ondition Fline O 6line e%&lu&tes
to true then the sto'h&sti' order 'ondition "ill be true#
Use+tochastic LL false is our /o))/ st&te# I) the Use+tochastic e4tern&l %&ri&ble is set to )&lse
then (Use+tochastic LL true NN Fline O 6line) e%&lu&tes to )&lse "hile Use+tochastic LLfalse e%&lu&tes to true#
Sin'e the on &nd o)) st&tes &re lin,ed by &n OR oper&tor only one o) the( h&s to be true to (&,e
the "hole st&te(ent true# So &s long &s either &#B the indi'&tor is on &nd the order pl&'e(ent
'ondition is %&lid or b#B the indi'&tor is o)) the entire st&te(ent "ill be true &nd &ny re(&ining
order 'onditions '&n be e%&lu&ted#
3et5s &dd & se'ond tr&de 'ondition to our sto'h&sti' 'ondition the (o%ing &%er&ge 'ross+
i(((5seStochastic == true QQ Pline F 6line' 77 5seStochastic == alse)NN "ast8; O +low8;'
In this e4&(ple "e5%e &dded the (o%ing &%er&ge 'ross 'ondition "ast8; O +low8;# Note th&t "e
&dded ¬her set o) p&rentheses &round the sto'h&sti' 'ondition sin'e the entire st&te(ent in the
p&rentheses needs to be e%&lu&ted )irst#
6irst "e e%&lu&te the st&te(ent inside the inner(ost set o) p&rentheses+ (Use+tochastic LL true
NN Fline O 6line)# I) the Use+tochastic p&r&(eter is set to true &nd Fline O 6line e%&lu&tes
to true the )irst p&rt o) the st&te(ent is true#
i((true 77 5seStochastic == alse' QQ #astM? F Slo%M?'
The 'ondition Use+tochastic LL false e%&lu&tes to false# *e &re le)t "ith &n OR oper&tion &nd
sin'e one o) the 'onditions is &lre&dy true the entire sto'h&sti' 'ondition e%&lu&tes to true+
i((true 77 alse' QQ #astM? F Slo%M?'
i(true QQ #astM? F Slo%M?'
I) "ast8; O +low8; e%&lu&tes to true the entire tr&ding 'ondition is true &nd the order is pl&'ed#
I) it is )&lse the st&te(ent e%&lu&tes to false &nd the order is not pl&'ed#
No" "h&t h&ppens i) the sto'h&sti' tr&ding 'ondition is )&lse I) Use+tochastic is set to true &nd
Fline O 6line e%&lu&tes to )&lse the entire 'ondition be'o(es )&lse+
10:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 116/212
EXPERT ADVISOR PROGRAMMING
i((alse 77 5seStochastic == alse' QQ #astM? F Slo%M?'
i((alse 77 alse' QQ #astM? F Slo%M?'
i(alse QQ #astM? F Slo%M?'
Reg&rdless o) ho" "ast8; O +low8; e%&lu&tes the entire tr&de 'ondition is )&lse#
No" lets s&y th&t Use+tochastic is set to )&lse# In this '&se the st&te(ent (Use+tochastic LL
true NN Fline O 6line) e%&lu&tes to )&lse+
i((alse 77 5seStochastic == alse' QQ #astM? F Slo%M?'
Sin'e the st&te(ent Use+tochastic LL false is true the sto'h&sti' 'ondition e%&lu&tes to true#
i((alse 77 true' QQ #astM? F Slo%M?'
i(true QQ #astM? F Slo%M?'
*hi'h (e&ns th&t i) "ast8; O +low8; &lso e%&lu&tes to true the order "ill be pl&'ed# In this '&se
the sto'h&sti' 'ondition "&sn5t e%en 'onsidered &side )ro( e%&lu&ting the on7o)) st&te o) the
indi'&tor#
Comparing #ndi$ator 7a"ues A$ross 2ars
So(eti(es you "ill need to 'o(p&re the indi'&tor %&lue o) the 'urrent or (ost re'ently 'losed b&r to
the indi'&tor %&lue o) & pre%ious b&r# 6or e4&(ple let5s s&y you "&nt to ,no" "hether & (o%ing
&%er&ge is going up or do"n# To do this "e 'o(p&re the indi'&tor re&ding o) the 'urrent b&r to th&t
o) the pre%ious b&r#
*e use the +hift p&r&(eter o) &n indi'&tor )un'tion to deter(ine "hi'h b&r to return the indi'&tor
%&lue )or# The +hift p&r&(eter is &l"&ys the l&st p&r&(eter in &n indi'&tor )un'tion# The 'urrent b&r
h&s & shi)t o) 0 the pre%ious b&r h&s & shi)t o) 1 &nd so on# The (o%ing &%er&ge )un'tions belo"
"ill return & (o%ing &%er&ge %&lue )or the 'urrent &nd the pre%ious b&r+
double 8; = iM?(B5LL9M?*eriod9M?MethodM?*rice2';
double ,ast8; = iM?(B5LL9M?*eriod9M?MethodM?*rice';
10;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 117/212
,rder "onditions and Indicators
In this e4&(ple 8; is the %&ri&ble th&t holds the 'urrent b&r5s indi'&tor %&lue "hile ,ast8; holds the
pre%ious b&r5s indi'&tor %&lue# Note th&t the +hift p&r&(eter is 0 )or the 'urrent b&r &nd 1 )or the
pre%ious b&r#
Here is the 'ode to deter(ine "hether & (o%ing &%er&ge line is (o%ing up or do"n+
i(M? F LastM?'
)
-- M? is going u&
,
else i(M? D LastM?'
)
-- M? is going do%n
,
I) the indi'&tor %&lue o) the 'urrent b&r A8;B is gre&ter th&n the %&lue o) the pre%ious b&r A,ast8;B
"e '&n 'on'lude th&t the indi'&tor is (o%ing up# The re%erse is true "hen the 'urrent b&r5s indi'&tor
%&lue is less th&n the pre%ious b&r5s indi'&tor %&lue#
8y 'o(p&ring the indi'&tor %&lue o) & pre%ious b&r to the 'urrent one "e '&n deter(ine "hether the
indi'&tor h&s re'ently 'rossed &bo%e or belo" & 'ert&in %&lue su'h the o%erbought7o%ersold le%els o)
&n os'ill&tor or ¬her indi'&tor line#
6or e4&(ple let5s s&y your tr&ding syste( gi%es & tr&de sign&l "hen the sto'h&sti' p&sses &bo%e ?0
or belo" :0# Here is the 'ode to 'he', )or th&t+
double Stoch = iStochastic(B5LL9P*eriod6*eriodSlo%ingM?Method*rice92';
double LastStoch = iStochastic(B5LL9P*eriod6*eriodSlo%ingM?Method*rice9';
i(Stoch F 89 QQ LastStoch D 89'
)
-- &en bu$ order
,
i(Stoch D U9 QQ LastStoch F U9'
)
-- &en sell order
,
+toch is the indi'&tor %&lue o) the 'urrent b&r "hile ,ast+toch is the indi'&tor %&lue o) the pre%ious
b&r# I) +toch is gre&ter th&n ?0 &nd ,ast+toch is less th&n ?0 "e '&n 'on'lude th&t the indi'&tor
'rossed &bo%e the o%ersold le%el "ithin the l&st b&r# 8y re%ersing the 'o(p&rison oper&tors "e '&n
'he', )or & re'ent 'ross belo" & 'onst&nt %&lue su'h &s the o%erbought le%el o) :0#
109
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 118/212
EXPERT ADVISOR PROGRAMMING
Here5s ¬her e4&(ple using (o%ing &%er&ges# *e5ll 're&te & 'ondition to open &n order only "hen
the "ast8; &nd the +low8; h&%e 'rossed "ithin the l&st b&r+
double #astM? = iM?(B5LL9#astM?*eriod9999';
double Slo%M? = iM?(B5LL9Slo%M?*eriod9999';
double ,ast"ast8; L i8;(U,,D2D"ast8;eriodD2D2D2D)M
double ,ast+low8; L i8;(U,,D2D+low8;eriodD2D2D2D)M
i(#astM? F Slo%M? NN ,ast"ast8; RL ,ast+low8;
QQ <u$MarketCount(S$mbol('MagicBumber' == 9'
)
-- &en bu$ order
,
i(#astM? D Slo%M? NN ,ast"ast8; OL ,ast+low8;
QQ SellMarketCount(S$mbol('MagicBumber' == 9'
)
-- &en sell order
,
In this e4&(ple "e5re 'o(p&ring the rel&tionship o) t"o indi'&tors to e&'h other# ,ast"ast8; &nd
,ast+low8; return the (o%ing &%er&ge %&lues )or the pre%ious b&r# I) ,ast"ast8; is less th&n Aor
e.u&l toB ,ast+low8; &nd "ast8; is 'urrently gre&ter th&n +low8; then "e ,no" th&t the )&st
(o%ing &%er&ge line h&s 'rossed &bo%e the slo" (o%ing &%er&ge line "ithin the l&st b&r#
This pro%ides & reli&ble tr&ding sign&l sin'e "e '&n li(it our order pl&'e(ent to right &)ter the 'ross
o''urs# $ou '&n 'h&nge the +hift %&lue )or the ,ast"ast8; &nd ,ast+low8; )un'tions i) you "&nt
to in're&se the nu(ber o) b&rs to loo, b&', "hen )inding &n indi'&tor 'ross#
*e5%e &dded the ,ast"ast8; &nd ,ast+low8; 'o(p&rison to our buy &nd sell order 'onditions in
our e4pert &d%isor# *e '&n no" re(o%e the 7u0%icket &nd +ell%icket 'he', sin'e this (ethod is
(ore reli&ble th&t 'he',ing & stored order ti',et nu(ber# *e &lso don5t h&%e to "orry &bout orders
being pl&'ed "ell &)ter the 'ross h&s o''urred# See the e4pert &d%isor 'ode in !ppendi4 C to %ie" &ll
o) the 'h&nges#
110
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 119/212
,rder "onditions and Indicators
111
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 120/212
EXPERT ADVISOR PROGRAMMING
C+apter 3)or*ing wit+ Time and 0ate
0atetime 7aria!"es
Intern&lly the datetime %&ri&ble is represented &s the nu(ber o) se'onds el&psed sin'e M&nu&ry 1
19:0# 6or e4&(ple Mune 1= 2009 &t 0+00 A(idnightB "ould be 12=02000# The &d%&nt&ge o)
d&teti(e )or(&t is th&t it (&,es p&st &nd )uture ti(e 'o(p&risons &nd (&the(&ti'&l (&nipul&tions
%ery e&sy#
6or e4&(ple i) you "&nted to 'he', "hether one d&te 'o(es be)ore or &)ter ¬her d&te you
"ould do & si(ple rel&tion&l oper&tion# 3et5s s&y th&t +tart6ate is Mune 1= 2009 &t 1+00 &nd
<nd6ate is Mune 1< 2009 &t =+00#
i(Start6ate D /nd6ate' -- Kesult is true
i(Start6ate F /nd6ate' -- Kesult is alse
!nother &d%&nt&ge is th&t you '&n &dd or subtr&'t ti(e )ro( & p&rti'ul&r d&te si(ply by &dding or
subtr&'ting the &ppropri&te nu(ber o) se'onds# I) you "&nt to &dd 2 hours to +tart6ate si(ply
&dd the nu(ber o) se'onds in & d&y+
datetime ?dd6a$ = Start6ate N V@:99;
I) you5re pl&nning to do & lot o) (&the(&ti'&l (&nipul&tion "ith d&teti(e %&ri&bles it (ight be &
good ide& to de'l&re so(e integer 'onst&nts to represent 'ert&in units o) ti(e+
deine S/CH1 8@99 -- Seconds in an hour
deine S/C61 V@:99 -- Seconds in a da$
The dis&d%&nt&ge o) datetime )or(&t is th&t it is not %ery re&d&ble# $ou '&n5t loo, &t & %&lue su'h &s
12=02000 &nd &uto(&ti'&lly tell th&t it represents Mune 1= 2009 &t 0+00# 6or this "e use
'on%ersion )un'tions to 'on%ert d&teti(e to &nd )ro( & (ore re&d&ble )or(#
0atetime Constants
! d&teti(e 'onst&nt is & d&te &nd ti(e presented in the )ollo"ing string )or(&t+ 0000.mm.dd hh:mm#
6or e4&(ple Mune 1= 2009 &t 0+00 "ould be 1223.2K. 22:22# There &re other &''ept&ble
112
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 121/212
'or*ing %it! Ti#e and Date
)or(&ts )or d&teti(e 'onst&nts+ the 3 Re)eren'e topi' +asics - Data Types - Dateti#e constants
h&s (ore in)or(&tion# *e5ll use the )or(&t presented &bo%e sin'e it is the only one th&t '&n be
e&sily 'on%erted#
To 'on%ert & d&teti(e %&ri&ble to & string 'onst&nt use the )un'tion %ime%o+tr()# Here is the
synt&4+
string TimeToStr(datetime Time int Output = TIM/6?T/7TIM/MIB5T/S';
• Time ! d&teti(e %&ri&ble e4pressed &s the nu(ber o) se'onds el&psed sin'e M&nu&ry 1
19:0#
• &utput !n option&l p&r&(eter th&t outputs the 'onst&nt &s d&te only hour &nd (inute
only hour (inute &nd se'onds or &ny 'o(bin&tion o) d&te &nd ti(e# &lid input %&lues &re +
◦ %#8<>6;%< Outputs the d&te )or e4&(ple 1223.2K.
◦ %#8<>8#U%<+ Outputs hour &nd (inute )or e4&(ple 2:S2
◦ %#8<>+<C=6+ Outputs hour (inute &nd se'onds )or e4&(ple 2:S2:4
To output the string 'onst&nt in the de)&ult 0000.mm.dd hh:mm )or(&t le&%e =utput bl&n,# I) you
only "&nt the d&te or the hour &nd (inute Aor se'ondsB use the &ppropri&te &rgu(ent# In this
e4&(ple "e5ll &ssu(e th&t +tart%ime is e.u&l to 1223.2K. 2:S2:4.
TimeToStr(StartTimeTIM/6?T/' -- Keturns "499W!9@!12"
TimeToStr(StartTimeTIM/S/CB6S' -- Keturns "92J89J:2"
TimeToStr(StartTimeTIM/MIB5T/S' -- Keturns "92J89"
TimeToStr(StartTimeTIM/6?T/7TIM/S/CB6S' -- Keturns "499W!9@!12 92J89J:2"
TimeToStr(StartTime' -- Keturns "499W!9@!12 92J89"
*e '&n 'onstru't & d&teti(e 'onst&nt using string 'on'&ten&tion &nd 'on%ert it to & d&teti(e
%&ri&ble using the )un'tion +tr%o%ime()# The synt&4 is identi'&l to %ime%o+tr() &bo%e but "ithout
the =utput p&r&(eter# The string 'onst&nt (ust be in the )or(&t 0000.mm.dd hh:mm to be 'on%erted
'orre'tly#
Here5s &n e4&(ple o) ho" "e '&n &sse(ble & d&teti(e 'onst&nt using integers 'on%ert those
integers to string )or(&t &nd 'on%ert the string to & d&teti(e %&ri&ble# 6irst "e5ll de'l&re so(e
e4tern&l %&ri&bles to set & ti(e &nd d&te+
e+tern int 5seMonth = @;
e+tern int 5se6a$ = 12;
e+tern int 5seHour = 2;
e+tern int 5seMinute = 89;
11?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 122/212
EXPERT ADVISOR PROGRAMMING
Ne4t "e 're&te the string 'onst&nt using the +trin!Concatenate() )un'tion &nd )in&lly 'on%ert the
string to datetime )or(&t using +tr%o%ime()#
string 6ateConstant = StringConcatenate(3ear('"!"5seMonth"!"5se6a$" "
5seHour"J"5seMinute'; -- 6ateConstant is "499W!@!12 92J89"
datetime StartTime = StrToTime(6ateConstant'; -- StartTime is "14:29:8V99"
Note th&t in the +trin!Concatenate() )un'tion "e use @ear() to return the 'urrent ye&r inste&d o)
using &n e4tern&l %&ri&ble# $ou '&n use )un'tions li,e 8onth() 6a0() &nd so on to insert 'urrent
ti(e %&lues# *e5ll 'o%er these in the ne4t se'tion#
0ate and Time ,un$tions
There &re t"o )un'tions th&t return the 'urrent ti(e+ %imeCurrent() returns the 'urrent ser%er ti(e
"hile %ime,ocal() returns your lo'&l 'o(puter ti(e# $ou '&n use "hi'he%er you pre)er# $ou (&y"&nt to 're&te & boole&n e4tern&l %&ri&ble to 'hoose bet"een the t"o+
e+tern bool 5seLocalTime = true;
Here is the 'ode to &ssign either the 'urrent lo'&l ti(e or the 'urrent ser%er ti(e to & %&ri&ble n&(ed
Current%ime#
i(5seLocalTime == true' datetime CurrentTime = TimeLocal('; -- Local time
else CurrentTime = TimeCurrent('; -- Ser0er time
So(eti(es you (&y ust need to retrie%e & p&rt o) the 'urrent ti(e su'h &s the hour or d&y# Here is
the list o) the (ost use)ul )un'tions you '&n use to return 'urrent ti(e %&lues# !ll o) these )un'tions
use the ser%er ti(e not your lo'&l 'o(puter ti(e# The return %&lue is o) type integer+
• @ear() The 'urrent )our-digit ye&r )or e4&(ple 2009#
• 8onth() The 'urrent (onth o) the ye&r )ro( 1 to 12#
• 6a0() The 'urrent d&y o) the (onth )ro( 1 to ?1#
•6a0=fGeek() !n integer representing the 'urrent d&y o) the "ee,# Sund&y is 0 ond&y is1 6rid&y is = &nd so on#
• ?our() The 'urrent hour in 2 hour ti(e )ro( 0 to 2?# 6or e4&(ple ?&( is ? &nd ?p( is
1=#
• 8inute() The 'urrent (inute )ro( 0 to =9#
11
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 123/212
'or*ing %it! Ti#e and Date
$ou '&n &lso retrie%e these %&lues )ro( &ny d&teti(e %&ri&ble using & di))erent set o) )un'tions#
These )un'tions re.uire & d&teti(e %&ri&ble &s the only p&r&(eter but other"ise "or, ust li,e the
)un'tions &bo%e# I) you "&nt to retrie%e & ti(e %&lue )ro( %ime,ocal() use the output o) the
%ime,ocal() )un'tion &s the &rgu(ent )or the )un'tions belo"+
•
%ime@ear() The )our-digit ye&r o) the spe'i)ied d&teti(e %&lue#
• %ime8onth() The (onth o) the spe'i)ied d&teti(e %&lue )ro( 1 to 12#
• %ime6a0() The d&y o) the (onth o) the spe'i)ied d&teti(e %&lue )ro( 1 to ?1#
• %ime6a0=fGeek() !n integer representing the d&y o) the "ee, o) the spe'i)ied d&teti(e
%&lue# Sund&y is 0 ond&y is 1 6rid&y is = &nd so on#
• %ime?our() The hour o) the spe'i)ied d&teti(e %&lue in 2 hour ti(e )ro( 0 to 2?#
• %ime8inute() The (inute o) the spe'i)ied d&teti(e %&lue )ro( 0 to =9#
Here &re & )e" e4&(ples o) the us&ge o) these )un'tions# 3et5s &ssu(e th&t %ime,ocal() is e.u&l to1223.2K. 2:S2.
datetime CurrentTime = TimeLocal(';
int AetMonth = TimeMonth(CurrentTime'; -- Keturns @
int AetHour = TimeHour(CurrentTime'; -- Keturns 2
int AetOeekda$ = Time6a$Oeek(CurrentTime'; -- Keturns 1 or Monda$
Creating A Simp"e Timer
One %ery h&ndy thing "e '&n do "ith ti(e &nd d&te in 3 is to &dd & ti(er to our e4pert &d%isor#
So(e tr&ders li,e to li(it their tr&ding to the (ost &'ti%e hours o) the d&y su'h &s the 3ondon @ Ne"
$or, sessions# Others (&y "ish to &%oid tr&ding during %ol&tile (&r,et e%ents su'h &s ne"s reports
&nd N6P#
To 'onstru't & ti(er "e need to spe'i)y & st&rt ti(e &nd &n end ti(e# *e "ill use e4tern&l integer
%&ri&bles to input the ti(e p&r&(eters# *e "ill 're&te & d&teti(e 'onst&nt string &nd 'on%ert th&t to
& d&teti(e %&ri&ble# *e "ill then 'o(p&re our st&rt &nd end ti(es to the 'urrent ti(e# I) the 'urrent
ti(e is gre&ter th&n the st&rt ti(e but less th&n the end ti(e tr&ding "ill be &llo"ed#
Here &re the e4tern&l %&ri&bles "e5re going to use# *e5ll set & %&ri&ble to turn the ti(er on &nd o)) &s
"ell &s to sele't the 'urrent ti(e Aser%er or lo'&lB# *e h&%e (onth d&y hour &nd (inute settings )or
both the st&rt &nd end ti(es+
11=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 124/212
EXPERT ADVISOR PROGRAMMING
e+tern bool 5seTimer = true;
e+tern bool 5seLocalTime = alse;
e+tern int StartMonth = @;
e+tern int Start6a$ = 12;
e+tern int StartHour = U;
e+tern int StartMinute = 9;
e+tern int /ndMonth = @;
e+tern int /nd6a$ = 12;
e+tern int /ndHour = 4;
e+tern int /ndMinute = 89;
!nd here is the 'ode )or 'he',ing "hether to &llo" tr&ding or not# The %&ri&ble %rade;llowed
deter(ines "hether to open ne" tr&des# I) Use%imer is set to )&lse %rade;llowed is &uto(&ti'&lly
set to true# Other"ise "e e%&lu&te our st&rt &nd end ti(es in rel&tion to the 'urrent ti(e to see i) "e
"ill &llo" tr&ding or not#
i(5seTimer == true'
)
-- Con0ert start time
string StartConstant = StringConcatenate(3ear('"!"StartMonth"!"Start6a$" "
StartHour"J"StartMinute';
datetime StartTime = StrToTime(StartConstant';
i(StartMonth == 14 QQ Start6a$ == 81 QQ /ndMonth == 1' int /nd3ear = 3ear(' N 1;
else /nd3ear = 3ear(';
-- Con0ert end timestring /ndConstant = StringConcatenate(/nd3ear"!"/ndMonth"!"/nd6a$" "
/ndHour"J"/ndMinute';
datetime /ndTime = StrToTime(/ndConstant';
-- Choose local or ser0er time
i(5seLocalTime == true' datetime CurrentTime = TimeLocal(';
else CurrentTime = TimeCurrent(';
-- Check or trade condition
i(StartTime D= CurrentTime QQ /ndTime F CurrentTime'
)
bool Trade?llo%ed = true;,
else Trade?llo%ed = alse;
,
else Trade?llo%ed = true;
11<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 125/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 126/212
EXPERT ADVISOR PROGRAMMING
)ro( 1 d&t&# The tr&des th&t o''ur in li%e tr&ding "ill not ne'ess&rily 'orrespond to tr&de (&de in
the Str&tegy Tester#
8ut by pl&'ing our tr&des on the 'lose on the b&r &nd using /Open pri'es only/ &s the testing (odel
"e '&n get testing results th&t (ore &''ur&tely re)le't re&l-ti(e tr&des# The dis&d%&nt&ge o) tr&ding
on'e per b&r is th&t tr&des (&y be e4e'uted l&te espe'i&lly i) there is & lot o) pri'e (o%e(ent o%erthe 'ourse o) the b&r# It5s b&si'&lly & tr&de-o)) bet"een responsi%eness &nd reli&bility#
To 'he', the tr&de 'onditions on'e per b&r "e (ust e4&(ine the ti(e st&(p o) the 'urrent b&r# *e
"ill s&%e this ti(e st&(p to & glob&l %&ri&ble# >pon e&'h e4e'ution o) the e4pert &d%isor "e "ill
'o(p&re the s&%ed ti(e st&(p to the 'urrent ti(e st&(p# On'e the ti(e st&(p o) the 'urrent b&r
'h&nges indi'&ting th&t & ne" b&r h&s opened "e "ill then 'he', the tr&ding 'onditions#
*e (ust &lso &dust the shi)t p&r&(eter o) our indi'&tor )un'tions pri'e )un'tions &nd &rr&ys to
return the %&lue o) the pre%ious b&r# I) &n indi'&tor )un'tion or pri'e &rr&y is set to 'he', the 'urrent
b&r "e "ill shi)t the b&r inde4 by 1 to 'he', the pre%ious b&r inste&d# !ll indi'&tors &nd pri'e &rr&ys(ust h&%e their shi)t p&r&(eters in're(ented by 1#
Te'hni'&lly "e &re 'he',ing tr&ding 'onditions on the )irst ti', o) & ne" b&r "hile e4&(ining the
'losing %&lue o) the pre%ious b&r# *e do not 'he', the 'urrently opened b&r "hen e4e'uting on'e per
b&r#
Here is the 'ode to 'he', )or the opening o) & ne" b&r# 6irst "e de'l&re &n e4tern&l %&ri&ble n&(ed
Check=nceer7ar to turn this )e&ture on &nd o))# Then "e de'l&re & datetime glob&l %&ri&ble to
store the ti(e st&(p o) the 'urrent b&r this "ill be Current%ime+tamp#
In the init() )un'tion "e "ill &ssign the ti(e st&(p o) the 'urrent b&r to Current%ime+tamp# This
"ill del&y the tr&de 'ondition 'he', until the opening o) the ne4t b&r+
-- /+ternal 0ariables
e+tern bool Checknce*er<ar = true;
-- Alobal 0ariables
datetime CurrentTimeStam&;
-- Init unction
int init('
)
CurrentTimeStam& = Time[9];
,
11;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 127/212
'or*ing %it! Ti#e and Date
Here is the 'ode th&t goes &t the beginning o) our start() )un'tion ust &)ter the ti(er# The integer
%&ri&ble 7ar+hift "ill deter(ine "hether to set the +hift %&lue o) our indi'&tor &nd pri'e )un'tions
to the 'urrent b&r or the pre%ious b&r# The boole&n %&ri&ble ew7ar "ill deter(ine "hether "e "ill
'he', our tr&de 'onditions+
i(Checknce*er<ar == true')
int <arShit = 1;
i(CurrentTimeStam& R= Time[9]'
)
CurrentTimeStam& = Time[9];
bool Be%<ar = true;
,
else Be%<ar = alse;
,
else
)
Be%<ar = true;
<arShit = 9;,
I) Check=nceer7ar is set to true "e "ill )irst set 7ar+hift to 1# This "ill set the +hift p&r&(eter
o) &ll indi'&tor &nd pri'e )un'tions7&rr&ys to the pre%ious b&r#
Ne4t "e 'o(p&re the %&lue o) Current%ime+tamp %&ri&ble to %imeI2J "hi'h is the ti(e st&(p o)
the 'urrent b&r# I) the t"o %&lues do not (&t'h "e "ill &ssign the %&lue o) %imeI2J to
Current%ime+tamp &nd set ew7ar to true# The tr&ding 'onditions "ill be 'he',ed shortly there&)ter#
On subse.uent runs Current%ime+tamp &nd %imeI2J "ill (&t'h "hi'h (e&ns th&t ew7ar "ill beset to )&lse# The tr&de 'onditions "ill not be 'he',ed until & ne" b&r opens# On'e & ne" b&r opens
%imeI2J "ill be & di))erent %&lue th&n Current%ime+tamp &nd ew7ar "ill be set to true on'e &g&in#
I) Check=nceer7ar is set to false ew7ar "ill &uto(&ti'&lly be set to true &nd 7ar+hift "ill be
set to 2# This "ill 'he', the tr&ding 'onditions on e%ery ti', &s be)ore#
The 7ar+hift %&ri&ble "ill need to be &ssigned to the +hift p&r&(eter o) &ny indi'&tor )un'tions
pri'e )un'tions or &rr&ys th&t re)eren'e the (ost re'ent b&r# Here &re so(e e4&(ples o) ho" this
"ould be &pplied+
double #astM? = iM?(B5LL9#astM?*eriod9997ar+hift';
i(Close[7ar+hift] F &en[7ar+hift]'
double 5seLo% = iLo%(B5LL97ar+hift';
119
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 128/212
EXPERT ADVISOR PROGRAMMING
$ou should re'ognie these e4&(ples )ro( be)ore# Inste&d o) 'he',ing the 'urrent b&r "e "ill 'he',
the b&r th&t ust 'losed i$e$ the pre%ious b&r# I) you need to re)eren'e & b&r pre%ious to the l&st
'losed b&r si(ply &dd the 'urrent shi)t p&r&(eter to 7ar+hift+
double Last#astM? = iM?(B5LL9#astM?*eriod9997ar+hiftH';
I) you don5t &nti'ip&te e%er needing to run your e4pert &d%isor on'e per b&r you "on5t need to &dd
this 'ode# 8ut )or (&ny indi'&tor-b&sed tr&ding syste(s this '&n (&,e your tr&ding &nd b&', testing
results (ore reli&ble#
To 'ontrol the e4e'ution o) tr&des "e need to 'he', the %&lue o) ew7ar be)ore the order pl&'e(ent
routines# *e '&n do this using the if blo', "e pl&'ed e&rlier )or the ti(er+
-- <egin trade block
i(Trade?llo%ed == true NN ew7ar LL true'
)-- <u$ rder
i(#astM? F Slo%M? QQ <u$Ticket == 9 QQ <u$rderCount(S$mbol('MagicBumber' == 9'
)
-- <u$ order code omitted or bre0it$
,
-- Sell rder
i(#astM? D Slo%M? QQ SellTicket == 9 QQ SellrderCount(S$mbol('MagicBumber' == 9'
)
-- Sell order code omitted or bre0it$
,
, -- /nd trade block
120
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 129/212
'or*ing %it! Ti#e and Date
121
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 130/212
EXPERT ADVISOR PROGRAMMING
C+apter Tips and Tri$*s
In this 'h&pter "e "ill 'o%er &ddition&l )e&tures th&t (&y be use)ul in your e4pert &d%isors#
Es$ape C+ara$ters
I) you "&nt to &dd .uotes or & b&',sl&sh 'h&r&'ter to & string 'onst&nt you5ll need to escape the
'h&r&'ter using & b&',sl&sh AUB# 6or e4&(ple i) you need to insert & double .uote the es'&pe
'h&r&'ter "ill be \# 6or & single .uote the es'&pe 'h&r&'ter is \# 6or & b&',sl&sh use t"o
b&',sl&shes &s the es'&pe 'h&r&'ter+ \\
string /scYuotes = "This string has Z"esca&ed double EuotesZ"";
-- ut&utJ This string has "esca&ed double Euotes"
string /scYuote = "This string has Zesca&ed single EuotesZ";
-- ut&utJ This string has esca&ed single Euotes
string /scSlash = "This string has an esca&ed backslash ZZ";
-- ut&utJ This string has an esca&ed backslash Z
I) you need & string to sp&n (ultiple lines use the es'&pe 'h&r&'ter \n to &dd & ne"line+
string Be%Line = "This string has Zn a ne%line";-- ut&utJ This string has
a ne%line
5sing C+art Comments
$ou '&n print te4t in the top le)t h&nd 'orner o) the 'h&rt using the Comment() )un'tion# This '&n be
used to print st&tus in)or(&tion indi'&tor settings or &ny other in)or(&tion you (&y )ind use)ul#
One (ethod )or displ&ying 'h&rt 'o((ents is to de'l&re se%er&l string %&ri&bles &nd 'on'&ten&te
the( together "ith ne"line 'h&r&'ters# One string '&n be used to displ&y settings ¬her to displ&yin)or(&tion (ess&ges or order st&tus et'# The 'on'&ten&ted string "ill be p&ssed to the Comment()
)un'tion# Pl&'e the Comment() )un'tion &t the end o) the start() )un'tion to upd&te the 'h&rt
'o((ent+
122
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 131/212
Tips and Tric*s
string SettingsComment = "#astM?*eriodJ "N#astM?*eriodN" Slo%M?*eriodJ "NSlo%M?*eriod;
string StatusComment = "<u$ order &laced";
Comment(SettingsCommentN"Zn"NStatusComment';
*e de'l&re &nd set the %&lues o) the +ettin!sComment&nd +tatusComment strings inside the start()
)un'tion# !t the end o) the st&rt )un'tion "e '&ll the
Comment() )un'tion &nd use it to print our 'o((ents to
the 'h&rt# *e use & ne"line 'h&r&'ter A\nB to sep&r&te
the 'o((ents into t"o lines#
C+e$* Settings
There &re se%er&l e4pert &d%isor properties th&t (ust be en&bled be)ore the e4pert &d%isor (&y be&llo"ed to tr&de# These settings &re lo'&ted under the "o##on t&b in the Expert Properties di&log#
The setting Allo% live trading (ust be en&bled be)ore tr&ding '&n 'o((en'e# I) it is not en&bled &
)ro"ning )&'e "ill &ppe&r in the top right h&nd 'orner o) the 'h&rt ne4t to the e4pert &d%isor n&(e#
$ou '&n 'he', )or this 'ondition in your E! by using the #s%rade;llowed() )un'tion# I) it returns
)&lse the setting Allo% live trading is dis&bled#
I) you5d li,e to displ&y & (ess&ge to the user indi'&ting th&t this setting should be &'ti%&ted you '&n
do &s )ollo"s+
i(IsTrade?llo%ed(' == alse' ?lert("/nable the setting Z?llo% li0e tradingZ in the
/+&ert *ro&ertiesR"';
I) your e4pert &d%isor uses &n e4tern&l .ex4 libr&ry the setting Allo% i#port of external experts (ust
be en&bled in the E4pert Properties# $ou '&n 'he', )or this using the #s,ibraries;llowed()
)un'tion+
i(IsLibraries?llo%ed(' == alse' ?lert("/nable the setting Z?llo% im&ort o e+ternal
e+&ertsZ in the /+&ert *ro&ertiesR"';
The s&(e thing '&n be done )or D33s using the #s6lls;llowed() )un'tion+
i(Is6lls?llo%ed(' == alse' ?lert("/nable the setting Z?llo% 6LL im&ortsZ in the
/+&ert *ro&ertiesR"';
12?
,ig .%+ Ch&rt 'o((ent using & ne"line 'h&r&'ter
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 132/212
EXPERT ADVISOR PROGRAMMING
,ig. .' Co((on t&b o) E4pert !d%isor Properties di&log#
$ou '&n %ie" &ll o) the ter(in&l 'he',up )un'tions in the 3 Re)eren'e under "!ec*up#
0emo or A$$ount Limitations
$ou (&y de'ide &t so(e point to sell your pro)it&ble e4pert &d%isor to other tr&ders# $ou (&y &lso
"&nt to pro%ide & de(o %ersion )or potenti&l buyers to test# To pre%ent your E! )ro( being )reely
distributed or tr&ded by un&uthoried persons you5ll "&nt to in'orpor&te so(e ,ind o) &''ountli(it&tions th&t li(it the us&ge o) the E! to &uthoried buyers# $ou (&y e%en "&nt to li(it us&ge to &
p&rti'ul&r bro,er#
To li(it us&ge to & de(o &''ount use the #s6emo() )un'tion to 'he', "hether the 'urrently &'ti%e
&''ount is & de(o &''ount# I) the 'urrent &''ount is not & de(o &''ount "e "ill displ&y &n &lert &nd
h< the e4e'ution o) the E!#
i(Is6emo(' == alse'
)
?lert("This /? onl$ or use on a demo accountR"';return(9';
,
12
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 133/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 134/212
EXPERT ADVISOR PROGRAMMING
-- *re&rocessor directi0es
include DOin5ser84!mEhF
-- start(' unction
int 3esBo<o+ = Message<o+("*lace a Trade\""Trade Conirmation"
M<3/SB7M<ICBY5/STIB';
i(3esBo<o+ == I63/S'
)
-- *lace rder
,
The )l&g 87>@<+= spe'i)ies th&t "e "ill be using $es7No
buttons in our (ess&ge bo4 "hile the 87>#C=VU<+%#=
)l&g pl&'es the .uestion (&r, i'on in the di&log bo4# The
integer %&ri&ble @eso7ox holds the return %&lue o) the
8essa!e7ox() )un'tions "hi'h "ill indi'&te "hi'h
button "&s pressed#
I) the $es button "&s pressed the %&lue o) @eso7ox
"ill be #6@<+ &nd &n order "ill be pl&'ed# I) the No
button "&s pressed the return )l&g "ill be #6=# $ou '&n
use the return %&lue o) 8essa!e7ox() &s input to
deter(ine & 'ourse o) &'tion su'h &s pl&'ing &n order#
*h&t )ollo"s is & p&rti&l list o) )l&gs to use in your (ess&ge bo4es# 6or & 'o(plete list ple&se see the
3 Re)eren'e topi' tandard "onstants - Message+ox #
2utton ,"ags
These )l&gs spe'i)y "hi'h buttons &ppe&r in your (ess&ge bo4#
• M2&@CACEL O &nd C&n'el buttons#
• M2ES& $es &nd No buttons#
• M2ES&CACEL $es No &nd C&n'el buttons#
12<
,ig. .8 Popup di&log 're&ted using the
ess&ge8o4AB )un'tion
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 135/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 136/212
EXPERT ADVISOR PROGRAMMING
,ig. ;# The E(&il settings under Tools Options #
Here5s &n e4&(ple o) +end8ail() us&ge+
string /mailSubect = "<u$ order &laced";
string /mail<od$ = "<u$ order "NTicketN" &laced on "NS$mbol('N" at "N?sk;
-- Sam&le out&utJ "<u$ order 142V: &laced on /5K65S6 at 1!:2::"
SendMail(/mailSubect/mail<od$';
Retry on Error
Throughout this boo, "e5%e tried to %eri)y order p&r&(eters be)ore &tte(pting to pl&'e &n order so
&s to &%oid 'o((on error (ess&ges due to in'orre't settings or pri'es# Ho"e%er errors (&y still
o''ur due to re.uotes tr&de 'onte4t busy or ser%er issues# These errors '&n5t &l"&ys be &%oided but
"e '&n &tte(pt to pl&'e the order &g&in "hen this h&ppens#
To retry &n order on &n error "e "ill pl&'e the =rder+end() )un'tion inside & while loop# I)
=rder+end() does not return & ti',et nu(ber "e "ill retry the order &g&in+
12;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 137/212
Tips and Tric*s
int Ticket = 9;
%hile(Ticket D= 9'
)
Ticket = rderSend(S$mbol('*<53LotSi>e&en*rice5seSli&&age
<u$Sto&Loss<u$Take*roit';
,
*e de'l&re the %&ri&ble )or the ti',et nu(ber )irst in this '&se %icket# !s long &s %icket is not
gre&ter th&n 0 the while loop "ith the =rder+end() )un'tion "ill e4e'ute o%er &nd o%er# There5s
one proble( "ith this loop though# In '&se o) & 'oding error or so(e other un'orre'ted tr&ding error
the loop "ill iter&te inde)initely &nd your e4pert &d%isor "ill h&ng# *e '&n &lle%i&te this by &dding &
(&4i(u( nu(ber o) retries+
int 5etries L 2M
int 8ax5etries L M
int Ticket = 9;%hile(Ticket D= 9'
)
Ticket = rderSend(S$mbol('*<53LotSi>e&en*rice5seSli&&age<u$Sto&Loss
<u$Take*roit';
if(5etries RL 8ax5etries) 5etriesHHM
else breakM
,
*e de'l&re & %&ri&ble to use &s & retry 'ounter A5etriesB &nd & (&4i(u( retry setting
A8ax5etriesB# !s long &s "e h&%e not e4'eeded 8ax5etries the 5etries %&ri&ble is in're(ented
&nd the loop iter&tes &g&in# !s soon &s 8ax5etries is re&'hed the break oper&tor ends the loop# !)ter this you '&n &lert the user o) the error 'ondition &s ne'ess&ry#
I) you "&nt to (&,e the retry loop dependent on & p&rti'ul&r error 'ondition "e '&n 'he', the error
'ode &g&inst & list &nd return & %&lue o) true i) there is & (&t'h# This )un'tion 'ont&ins so(e 'o((on
error 'odes th&t indi'&te & 'ondition "here & tr&de 'ould be su''ess)ully retried+
bool /rrorCheck(int /rrorCode'
)
s%itch(/rrorCode'
)
case 14VJ -- Trade timeoutreturn(true';
case 18@J -- Euotes
return(true';
129
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 138/212
EXPERT ADVISOR PROGRAMMING
case 18VJ -- KeEuotes
return(true';
case 1:@J -- Trade conte+t bus$
return(true';
deaultJreturn(alse';
,
,
This )un'tion uses the switch oper&tor# *e &re loo,ing )or & case l&bel "hose %&lue (&t'hes the
e4pression &ssigned to the s"it'h oper&tor Ain this e4&(ple <rrorCodeB# I) & (&t'hing case is
)ound the 'ode &)ter case is e4e'uted# I) no case l&bel (&t'hes then the 'ode &)ter the default
l&bel is e4e'uted#
*hen & case (&t'h is )ound the switch blo', (ust be e4ited "ith & break or return oper&tor# Inthis e4&(ple "e &re using the return oper&tor to return & true7)&lse %&lue b&', to the '&lling
)un'tion# The switch oper&tor '&n be use)ul )or e%&lu&ting & (&t'h )or &n integer 'onst&nt but its
utility is r&ther li(ited#
Here is ho" "e use <rrorCheck() to 'ondition&lly retry &n order pl&'e(ent+
int Ketries;
int Ma+Ketries = 2;
int Ticket;
%hile(Ticket D= 9')
Ticket = rderSend(S$mbol('*<53LotSi>e&en*rice5seSli&&age<u$Sto&Loss
<u$Take*roit';
if(%icket LL -) int <rrCode L Bet,ast<rror()M
i(Ketries D= Ma+Ketries NN <rrorCheck(<rrCode) LL true' KetriesNN;
else break;
,
I) the %icket returns - indi'&ting th&t &n error h&s o''urred "e retrie%e the error 'ode using
Bet,ast<rror()# *e p&ss the error 'ode to our <rrorCheck() )un'tion &bo%e# I) the error 'ode
(&t'hes &ny o) the errors in the error 'he', )un'tion <rrorCheck() "ill return true &nd the
=rder+end() )un'tion "ill be retried up to = ti(es#
1?0
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 139/212
Tips and Tric*s
5sing &rder Comments As an #dentifier
*e5%e been using the /(&gi' nu(ber/ &s &n order identi)ier th&t uni.uely identi)ies orders &s being
pl&'ed by & p&rti'ul&r e4pert &d%isor# I) your e4pert &d%isor pl&'es (ultiple orders &t one ti(e &nd
you "&nt to be &ble to h&ndle e&'h o) those orders di))erently you '&n use the order 'o((ent &s &n
option&l identi)ier#
6or e4&(ple lets s&y your e4pert &d%isor "ill pl&'e t"o types o) orders# $ou "&nt to be &ble to
(odi)y or 'lose these orders sep&r&tely# $ou5ll "&nt to use t"o =rder+end() )un'tions &nd pl&'e &
di))erent order 'o((ent "ith e&'h one# Then "hen sele'ting orders using the order loop in 'h&pter
= you5ll use =rderComment() &s one o) the 'onditions )or lo'&ting orders to (odi)y or 'lose#
strin! =rderComment L "irst orderM
strin! =rderComment1 L +econd orderM
-- rder &lacementint Ticket1 = rderSend(S$mbol('*<53LotSi>e&en*rice5seSli&&age<u$Sto&Loss
<u$Take*roit=rderCommentMagicBumber9Areen';
int Ticket4 = rderSend(S$mbol('*<53LotSi>e&en*rice5seSli&&age<u$Sto&Loss
<u$Take*roit=rderComment1MagicBumber9Areen';
-- rder modiication
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == MagicBumber QQ rderS$mbol(' == S$mbol('
NN =rderComment() LL =rderComment')
-- Modi$ irst order
,
else i(rderMagicBumber(' == MagicBumber QQ rderS$mbol(' == S$mbol('
NN =rderComment() LL =rderComment1'
)
-- Modi$ second order
,
,
*e de'l&re t"o string %&ri&bles to use &s order 'o((ents# The =rder+end() )un'tions pl&'e t"oorders e&'h "ith & di))erent order 'o((ent# The e4&(ple order (odi)i'&tion loop th&t )ollo"s uses
the =rderComment() )un'tion &s & 'ondition "hen sele'ting orders to (odi)y#
$ou '&n use the =rderComment() 'he', to 'lose orders independently o) other orders use di))erent
tr&iling stop settings or "h&te%er your tr&ding syste( de(&nds#
1?1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 140/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 141/212
Tips and Tric*s
The 'ode "ill be %ery si(il&r to the pre%ious se'tion "here "e &dded the (ini(u( (&rgin 'he',# *e
"ill in'lude the 'ode )ro( the pre%ious se'tion to sho" ho" these %&rious 'he',s "or, together+
-- /+ternal 0ariables
extern int 8aximum+pread L M
e+tern int Minimum/Euit$ = V999;
i(?ccount/Euit$(' F Minimum/Euit$ NN 8arket#nfo(+0mbol()D8=6<>+5<;6) R 8aximum+pread'
)
-- *lace order
,
else
)
i(?ccount/Euit$(' D= Minimum/Euit$' ?lert("Current eEuit$ is less than minimum
eEuit$R rder not &laced!"';
if(8arket#nfo(+0mbol()D8=6<>+5<;6) O 8aximum+pread) ;lert(Current spread is
!reater than maximum spreadT =rder not placed.)M
,
Note th&t "e per)or( both the (ini(u( e.uity 'he', &nd the spre&d 'he', be)ore pl&'ing the order#
I) &n one o) the 'onditions &re )&lse "e go to the else blo', &nd 'he', to see "hi'h o) the
'onditions '&used the order to not be pl&'ed# *e "ill displ&y one or (ore &lerts depending on "hi'h
'ondition is true#
Mu"tip"e &rders
$ou (&y "ish to pl&'e (ultiple orders per position "ith di))erent stop loss &nd t&,e pro)it le%els &s"ell &s lot sies# There &re se%er&l "&ys to &''o(plish this# One "&y is to si(ply use & di))erent
=rder+end() st&te(ent )or e&'h order you "&nt to pl&'e# This is &ssu(ing th&t you pl&n on pl&'ing
the s&(e nu(ber o) orders e%ery ti(e#
!nother "&y is to use & for loop to pl&'e the orders# This "&y you '&n &dust the nu(ber o) orders
to pl&'e &t one ti(e# $ou '&n pre-lo&d your stop loss &nd t&,e pro)it pri'es into &rr&ys &nd in're(ent
through the &rr&ys in the for loop#
3et5s st&rt by de)ining e4tern&l %&ri&bles )or three stop loss &nd t&,e pro)it le%els# !ny &ddition&l
orders &bo%e three "ill not h&%e & stop loss or t&,e pro)it pl&'ed# *e5ll &lso &dd &n e4tern&l %&ri&bleto &dust the nu(ber o) orders to pl&'e#
e+tern int Sto&Loss1 = 49;
e+tern int Sto&Loss4 = :9;
e+tern int Sto&Loss8 = @9;
1??
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 142/212
EXPERT ADVISOR PROGRAMMING
e+tern int Take*roit1 = :9;
e+tern int Take*roit4 = V9;
e+tern int Take*roit8 = 149;
e+tern int Ma+rders = 8;
Ne4t "e "ill de'l&re our &rr&ys '&l'ul&te our stop loss &nd t&,e pro)it &nd lo&d our '&l'ul&ted pri'es
into the &rr&y+
double <u$Take*roit[8];
double <u$Sto&Loss[8];
<u$Take*roit[9] = Calc<u$Take*roit(S$mbol('Take*roit1?sk';
<u$Take*roit[1] = Calc<u$Take*roit(S$mbol('Take*roit4?sk';
<u$Take*roit[4] = Calc<u$Take*roit(S$mbol('Take*roit8?sk';
<u$Sto&Loss[9] = Calc<u$Sto&Loss(S$mbol('Sto&Loss1?sk';
<u$Sto&Loss[1] = Calc<u$Sto&Loss(S$mbol('Sto&Loss4?sk';<u$Sto&Loss[4] = Calc<u$Sto&Loss(S$mbol('Sto&Loss8?sk';
*e st&rt by de'l&ring the &rr&ys to hold the stop loss &nd t&,e pro)it pri'es 7u0%akerofit &nd
7u0+top,oss# The nu(ber o) &rr&y ele(ents (ust be indi'&ted "hen de'l&ring the &rr&y# !rr&y
inde4es st&rt &t ero so by de'l&ring &n &rr&y di(ension sie o) ? our st&rting inde4 is 0 &nd our
l&rgest inde4 is 2#
Ne4t "e '&l'ul&te the stop loss &nd t&,e pro)it pri'es using the )un'tions "e de)ined in 'h&pter
Calc7u0+top,oss() &nd Calc7u0%akerofit() # *e &ssign the '&l'ul&ted stop loss or t&,e pro)it
%&lue to the &ppropri&te &rr&y ele(ent# Note th&t the )irst &rr&y inde4 is 0 &nd the third &rr&y inde4 is
2#
Here is the for loop )or pl&'ing the orders+
or(int Count = 9; Count D= 8ax=rders - ; CountNN'
)
int rdInt = Count N 1;
rderSend(S$mbol('*<53LotSi>e?sk5seSli&&age7u0+top,ossICountJ
7u0%akerofitICountJ7u0 =rder H=rd#ntMagicBumber9Areen';
,
The Count %&ri&ble st&rts &t 0 to 'orrespond "ith our )irst &rr&y ele(ent# The nu(ber o) ti(es to
loop Ai#e# the nu(ber o) orders to pl&'eB is deter(ined by 8ax=rders - # 6or e&'h iter&tion o) the
loop "e in're(ent the stop loss &nd t&,e pro)it &rr&ys by one#
1?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 143/212
Tips and Tric*s
*e use the =rd#nt %&ri&ble to in're(ent the order 'ount in the order 'o((ent# The )irst order
'o((ent "ill be /8uy Order 1/ the ne4t "ill be /8uy Order 2/ &nd so on# The =rder+end() )un'tion
pl&'es the order "ith the &ppropri&te stop loss &nd t&,e pro)it %&lue using the Count %&ri&ble to
sele't the rele%&nt &rr&y ele(ent#
This is ust one "&y o) h&ndling (ultiple orders <hough it is prob&bly the (ost e))i'ient# The (&indr&"b&', to this &ppro&'h is th&t "e '&n only '&l'ul&te stop loss &nd t&,e pro)it pri'es )or & li(ited
nu(ber o) orders# !ltern&tely "e 'ould s'&le the t&,e pro)it &nd stop loss %&lues by & spe'i)ied
&(ount &nd pl&'e & potenti&lly unli(ited nu(ber o) orders+
e+tern int Sto&LossStart = 49;
e+tern int Sto&LossIncr = 49;
e+tern int Take*roitStart = :9;
e+tern int Take*roitIncr = :9;
e+tern int Ma+rders = 2;
In the &bo%e e4&(ple the stop loss )or our )irst order "ill be 20 pips# *e "ill in're(ent the stop loss
by 20 pips )or e&'h &ddition&l order# S&(e )or the t&,e pro)it e4'ept "e "ill st&rt &t 0 &nd
in're(ent by 0# Inste&d o) using &rr&ys "e "ill '&l'ul&te the stop loss &nd t&,e pro)it in the for
loop+
or(int Count = 9; Count D= Ma+rders 1; CountNN'
)
int rdInt = Count N 1;
int Use+top,oss L +top,oss+tart H (+top,oss#ncr * Count)Mint Use%akerofit L %akerofit+tart H (%akerofit#ncr * Count)M
double <u$Sto&Loss = Calc<u$Sto&Loss(S$mbol('5seSto&Loss?sk';
double <u$Take*roit = Calc<u$Take*roit(S$mbol('5seTake*roit?sk';
rderSend(S$mbol('*<53LotSi>e?sk5seSli&&age7u0+top,oss
7u0%akerofit"<u$ rder "NrdIntMagicBumber9Areen';
,
*e deter(ine the t&,e pro)it &nd stop loss le%el in pips by (ultiplying the +top,oss#ncr or
%akerofit#ncr %&ri&ble by the Count &nd &dding th&t to the +top,oss+tart or %akerofit+tart
%&lue# 6or the )irst order the stop loss or t&,e pro)it le%el "ill be e.u&l to +top,oss+tart or
%akerofit+tart#
Ne4t "e '&l'ul&te the stop loss &nd t&,e pro)it pri'e )or the order using our )un'tions )ro( 'h&pter #
6in&lly "e pl&'e the order using =rder+end()# The loop "ill 'ontinue until the nu(ber o) orders
1?=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 144/212
EXPERT ADVISOR PROGRAMMING
spe'i)ied by 8ax=rders &re pl&'ed# This (ethod &llo"s us to spe'i)y &s (&ny orders &s "e "&nt
using the 8ax=rders %&ri&ble gu&r&nteeing th&t e%ery order "e pl&'e "ill h&%e & stop loss &nd &
t&,e pro)it#
9"o!a" 7aria!"es
In this boo, "e5%e been re)erring to %&ri&bles "ith & glob&l s'ope &s /glob&l %&ri&bles#/ et&Tr&der
h&s & set o) )un'tions )or setting %&ri&bles &t the ter(in&l le%el "hi'h (e&ns th&t these %&ri&bles &re
&%&il&ble to e%ery e4pert &d%isor th&t is 'urrently running &ssu(ing th&t "e ,no" the n&(e o) the
%&ri&ble to st&rt "ith#
The 3 do'u(ent&tion re)ers to these &s /glob&l %&ri&bles/ <hough & (ore &ppropri&te n&(e
(ight be /ter(in&l %&ri&bles#/ *e use the glob&l %&ri&ble )un'tions in the 3 Re)eren'e under
<lobal variables to "or, "ith these types o) %&ri&bles# The 'urrent list o) glob&l %&ri&bles in the
ter(in&l '&n be %ie"ed by sele'ting <lobal =ariables )ro( the Tools (enu or by pressing 6? on the
,eybo&rd#
One "&y to use these %&ri&bles is to store 'ert&in glob&lly s'oped or st&ti' %&ri&bles to the ter(in&l
so th&t i) &n e4pert &d%isor is shut do"n "e '&n pi', up "here "e le)t o))# Not &ll e4pert &d%isors
re.uire this but (ore 'o(ple4 e4pert &d%isors "ill (&int&in & 'ert&in st&te th&t i) interrupted "ill
thro" o)) the e4pert &d%isor5s oper&tion#
The best "&y to pre%ent this is to &%oid 're&ting e4pert &d%isors th&t re.uire su'h & le%el o)
'o(ple4ity# 8ut i) it '&n5t be &%oided then using glob&l %&ri&ble )un'tions to store the 'urrent st&te to
the ter(in&l (&y be help)ul in '&se o) &''ident&l shutdo"n# Note th&t this (ethod is not )oolproo)
but it is li,ely the best (ethod to &'hie%e this#
To de'l&re & glob&l Ater(in&lB %&ri&ble use the Blobal9ariable+et() )un'tion# The )irst &rgu(ent is
& string indi'&ting the n&(e o) the glob&l %&ri&ble &nd the se'ond &rgu(ent is & %&lue o) type double
to &ssign to it#
AlobalariableSet(AlobalariableBame6oublealue';
To ,eep your %&ri&ble n&(es uni.ue you (&y "ish to 're&te & glob&l %&ri&ble pre)i4# De'l&re &
glob&lly s'oped %&ri&ble in your e4pert &d%isor &nd set the %&lue in the init() )un'tion using the'urrent sy(bol period e4pert &d%isor n&(e &nd (&gi' nu(ber to 're&te & uni.ue %&ri&ble pre)i4#
1?<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 145/212
Tips and Tric*s
-- Alobal 0ariables
string Alobalariable*rei+;
int init('
)
Alobalariable*rei+ = S$mbol('N*eriod('N""N"*roit<uster"N""NMagicBumberN"";
,
*e use the 'urrent sy(bol &nd period &long "ith &n identi)ier )or the E! &nd the 8a!icumber
e4tern&l %&ri&ble# No" "hen "e set & glob&l %&ri&ble using Blobal9ariable+et() "e use the
pre)i4 th&t "e de)ined &bo%e &long "ith the &'tu&l %&ri&ble n&(e+
AlobalariableSet(Alobalariable*rei+NCounterCounter';
So i) "e5re tr&ding on E>R>SD on the 1= ti(e)r&(e "ith &n E! n&(ed /Pro)it8uster/ using 11 &s
our (&gi' nu(ber &nd Counter &s our %&ri&ble n&(e the n&(e o) our glob&l %&ri&ble "ill be<U5U+6>rofit7uster>>Counter # $ou '&n use &ny 'on%ention you "ish )or n&(ing your glob&l
%&ri&bles but in'luding the &bo%e in)or(&tion is strongly re'o((ended#
To retrie%e the %&lue o) & glob&l %&ri&ble use the )un'tion Blobal9ariableBet() "ith the %&ri&ble
n&(e &s the &rgu(ent+
Counter = AlobalariableAet(Alobalariable*rei+NCounter';
To delete & glob&l %&ri&ble use the )un'tion Blobal9ariable6el() "ith the %&ri&ble n&(e &s the
&rgu(ent# To delete &ll glob&l %&ri&bles pl&'ed by your E! use the )un'tionBlobal9ariable6elete;ll() "ith your pre)i4 &s the &rgu(ent#
Alobalariable6el(Alobalariable*rei+NCounter';
Alobalariable6elete?ll(Alobalariable*rei+';
6or (ore in)or(&tion on glob&l %&ri&ble )un'tions see the <lobal variables topi' in the 3
Re)eren'e#
C+e$* &rder ProfitSo(eti(es it (&y be use)ul to 'he', the 'urrent pro)it on &n order or to 'he', the tot&l pro)it on &n
order th&t h&s &lre&dy 'losed# There &re t"o "&ys to 'he', pro)it# To get the pro)it in the deposit
'urren'y use the =rderrofit() )un'tion# $ou (ust )irst sele't the order using =rder+elect()#
1?:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 146/212
EXPERT ADVISOR PROGRAMMING
rderSelect(TicketS/L/CT<3TICP/T';
double Aet*roit = rder*roit(Ticket';
The result o) the =rderrofit() )un'tion should be identi'&l to the tot&l pro)it or loss th&t is listed in
the order history )or the sele'ted order#
To retrie%e the pro)it or loss in pips you "ill need to '&l'ul&te the di))eren'e bet"een the order
opening pri'e &nd the order 'losing pri'e# $ou "ill &lso need to use the =rder+elect() )un'tion to
retrie%e the open &nd 'lose pri'es#
rderSelect(TicketS/L/CT<3TICP/T';
i(rderT$&e(' == *<53' double Aet*roit = rderClose*rice(' rder&en*rice(';
else i(rderT$&e(' == *S/LL' Aet*roit = rder&en*rice(' rderClose*rice(';
Aet*roit -= *i&*oint(S$mbol('';
6or buy orders "e '&l'ul&te the pro)it by subtr&'ting the opening pri'e )ro( the 'losing pri'e# 6or
sell orders "e do the opposite# !)ter "e5%e '&l'ul&ted the di))eren'e "e '&n 'on%ert the pro)it or
loss to & "hole nu(ber by di%iding it by the point using our ipoint() )un'tion#
6or e4&(ple i) our buy order opening pri'e is 1#<=0 &nd our 'losing pri'e is 1#:00 the di))eren'e
bet"een =rderCloserice() &nd =rder=penrice() is 0#00=0# *hen "e di%ide th&t by our
ipoint() )un'tion the result is =0# So )or this order "e (&,e =0 pips in pro)it# I) the order 'losing
pri'e "&s 1#<00 inste&d then "e5d h&%e & loss o) -=0 pips#
Martinga"e
&rting&le is & betting syste( 'o((only used in roulette &nd bl&',&', "here the bet sie is
doubled &)ter e&'h 'onse'uti%e loss# The theory is th&t one "inning bet "ill bring the b&l&n'e b&', to
bre&, e%en# The do"nside to &rting&le is th&t you need & lot o) '&pit&l to "ithst&nd the dr&"do"ns#
6or e4&(ple i) your st&rting lot sie is 0#1 lots &)ter 'onse'uti%e losses your lot sie "ill be 1#< lots
1< ti(es your origin&l lot sie# !)ter : 'onse'uti%e losses your lot sie "ill be 12#; lots 12; ti(es
your origin&l lot sieL ! long losing stre&, "ill "ipe out your &''ount be)ore you5ll be &ble to bring
your &''ount b&', to bre&, e%en#
Ne%ertheless you (&y "ish to in'orpor&te & syste( o) in're&sing lot sies on 'onse'uti%e "ins or
losses &nd it5s possible to do so "ithout "iping out your &''ount# The e&siest (ethod is to put & '&p
on the nu(ber o) ti(es to in're&se the lot sie# ! sound tr&ding syste( should not h&%e (ore th&n ?
1?;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 147/212
Tips and Tric*s
or (&4i(u( 'onse'uti%e losses# $ou '&n deter(ine this by e4&(ining the (&4i(u( 'onse'uti%e
loss 'ount under the >eport t&b in the Str&tegy Tester "indo"#
!nother (ethod is to in're&se your lot sie by & s(&ller (ultiplier# The 'l&ssi' &rting&le str&tegy
doubles the lot sie &)ter e&'h 'onse'uti%e loss# $ou (&y "ish to use & (ultiplier s(&ller th&n 2#
There is &lso the &nti-&rting&le str&tegy "here you in're&se the lot sie &)ter e&'h 'onse'uti%e "in#
3et5s e4&(ine & routine "here "e '&l'ul&te the nu(ber o) 'onse'uti%e "ins or losses &nd in're&se
the lot sie &''ordingly# ! &rting&le str&tegy "or,s best "hen you5re pl&'ing one order &t & ti(e so
"e "ill &ssu(e th&t e%ery position 'onsists o) & single tr&de#
The user "ill be &ble to 'hoose bet"een & &rting&le AlossesB or &nti-&rting&le A"insB str&tegy# !
setting to li(it the (&4i(u( nu(ber o) 'onse'uti%e lot in're&ses "ill be in'luded &nd the lot
(ultiplier "ill be &dust&ble#
6irst let5s '&l'ul&te the nu(ber o) 'onse'uti%e "ins or losses# *e "ill need to loop through the orderhistory pool b&',"&rd st&rting )ro( the (ost re'ently 'losed order# *e "ill in're(ent & 'ounter )or
e&'h "in or loss# !s long &s & p&ttern o) 'onse'uti%e "ins or losses is (&int&ined "e "ill 'ontinue to
loop# !s soon &s the p&ttern is bro,en A& "in is lo'&ted &)ter one or (ore losses or %i'e %ers&B the
loop "ill e4it#
int OinCount;
int LossCount;
or(int Count = =rders?istor0%otal()-M M Count--'
)
rderSelect(CountS/L/CT<3*SM6/HISTK3'; i(rderS$mbol(' == S$mbol(' QQ rderMagicBumber(' == MagicBumber'
)
i(rder*roit(' F 9 QQ LossCount == 9' OinCountNN;
else i(rder*roit(' D 9 QQ OinCount == 9' LossCountNN;
else break;
,
,
*e st&rt by de'l&ring the %&ri&bles )or our "in &nd loss 'ounters# In the for oper&tor noti'e th&t "e
use =rders?istor0%otal() to est&blish our initi&l st&rting position# =rders?istor0%otal() returns
the nu(ber o) orders in the history pool# *e subtr&'t 1 to deter(ine the inde4 position )or the (ostre'ent order "hi'h is stored in the Count %&ri&ble#
Noti'e th&t "e h&%e o(itted the se'ond e4pression in the for loop the one th&t deter(ines the
'ondition to stop looping# The se(i'olon (ust re(&in )or &ny o(itted e4pressions# *e "ill de're(ent
the Count %&ri&ble on e&'h iter&tion o) the loop#
1?9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 148/212
EXPERT ADVISOR PROGRAMMING
*e use 8=6<>?#+%=5@ &s the third &rgu(ent in the =rder+elect() )un'tion to indi'&te th&t "e &re
looping through the 'losed order history pool# 8y de)&ult =rder+elect() uses the open order pool
so "e (ust spe'i)y 8=6<>?#+%=5@ "hen 'he',ing the 'losed order pool#
*e 'he', to (&,e sure th&t the 'urrently sele'ted order (&t'hes our 'h&rt sy(bol &nd our (&gi'
nu(ber# Then "e e4&(ine the order pro)it using the =rderrofit() )un'tion# I) the return %&lueindi'&tes & pro)it Ai$e$ is gre&ter th&n eroB then "e in're(ent the GinCount %&ri&ble# I) it5s & loss
"e in're(ent ,ossCount#
Sin'e "e &re loo,ing )or 'onse'uti%e "ins or losses "e need to ter(in&te the loop on'e &n
<ern&ting 'ondition is )ound# To do this "e 'he', the GinCount or ,ossCount %&ri&ble "hen
'he',ing the order pro)it# 6or e4&(ple i) "e h&%e 2 'onse'uti%e losses (e&ning th&t ,ossCount L
1 &nd our ne4t order is & "in then both o) our if st&te(ents "ill be )&lse &nd 'ontrol "ill p&ss to
the break oper&tor "hi'h ends the loop#
The &d%&nt&ge o) this (ethod is th&t it5s robust &nd "ill not )&il i) the e4pert &d%isor is &''ident&llyshut do"n# The E! "ill pi', up right "here it le)t o))# O) 'ourse this (e&ns th&t "hen you )irst st&rt
the E! it "ill use &ny pre%ious "in7loss stre&, "hen deter(ining the lot sie# 8ut &s you '&n see the
&d%&nt&ges out"eigh the dis&d%&nt&ges#
Either the GinCount or the ,ossCount %&ri&ble "ill 'ont&in the nu(ber o) 'onse'uti%e "ins or losses#
I) "e "&nt to do & &rting&le str&tegy "e use ,ossCount to deter(ine the )&'tor by "hi'h to
in're&se the lot sie# I) "e5re doing &n &nti-&rting&le "e use GinCount inste&d#
*e5ll use &n e4tern&l integer %&ri&ble '&lled 8artin!ale%0pe to deter(ine this# I) 8artin!ale%0pe
is set to 0 "e5ll use the &rting&le str&tegy# I) it5s set to 1 "e5ll use the &nti-&rting&le str&tegy# *e"ill &lso de'l&re e4tern&l %&ri&bles )or our (ultiplier A,ot8ultiplierB the (&4i(u( nu(ber o)
ti(es to in're&se the lot sie A8ax8artin!aleB &nd our st&rting lot sie A7ase,ot+ieB#
-- /+ternal 0ariables
e+tern int MartingaleT$&e = 9; -- 9J Martingale 1J ?ntiMartingale
e+tern int LotMulti&lier = 4;
e+tern int Ma+Martingale = :;
e+tern double <aseLotSi>e = 9!1;
-- Lot si>e calculationi(MartingaleT$&e == 9' int Consecuti0eCount = LossCount;
else i(MartingaleT$&e = 1' Consecuti0eCount = OinCount;
i(Consecuti0eCount F Ma+Martingale' Consecuti0eCount = Ma+Martingale;
double LotSi>e = <aseLotSi>e . Math*o%(LotMulti&lierConsecuti0eCount';
10
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 149/212
Tips and Tric*s
*e set the %&lue o) ConsecutiveCount to either GinCount or ,ossCount depending on the
8artin!ale%0pe setting# *e5ll 'o(p&re th&t to our 8ax8artin!ale setting# I) our 'onse'uti%e order
'ount is gre&ter th&n 8ax8artin!ale "e "ill resie it to be e.u&l to 8ax8artin!ale# A$ou 'ould
&lso resie it to the de)&ult lot sie i) you pre)er#B The lot sie "ill re(&in &t this sie until & "in or loss
bre&,s our 'onse'uti%e order stre&,#
The lot sie is deter(ined by (ultiplying our 7ase,ot+ie by the ,ot8ultiplier "hi'h is
e4ponenti&lly in're&sed by ConsecutiveCount# The 8athow() )un'tion r&ises & nu(ber to the
spe'i)ied po"er# The )irst &rgu(ent is the b&se &nd the se'ond &rgu(ent is the e4ponent# 6or
e4&(ple i) our st&rting lot sie is 0#1 the lot (ultiplier is 2 &nd "e h&%e )our 'onse'uti%e orders the
e.u&tion is 2. * 14 L .K#
8y &dusting the ,ot8ultiplier &nd using both &rting&le &nd &nti-&rting&le str&tegies this "ill
gi%e you enough options to e4peri(ent "ith using e4ponenti&l lot siing# $ou '&n e&sily (odi)y the
'ode &bo%e to use other %&ri&tions# 6or e4&(ple you 'ould s'&le lot sies in re%erse )ro( l&rgest to
s(&llest# Or you 'ould use &n e4tern&l 'ounter in pl&'e o) ConsecutiveCount#
0e!ugging our Expert Advisor
>nli,e (ost progr&((ing IDEs et&Editor doesn5t support bre&,points or &ny other ,ind o) (odern
debugging te'hni.ues# $ou5ll need to use rint() st&te(ents &nd logs to debug your e4pert
&d%isors#
$ou5%e &lre&dy been introdu'ed to the rint() )un'tion# In su((&ry &ny string &rgu(ent p&ssed to
the )un'tion "ill be printed to the log# 8y printing the 'ontents o) %&ri&bles &nd )un'tions to the log
you '&n e4&(ine the output o) your 'ode &nd )i4 &ny errors#
$ou5ll "&nt to use the Str&tegy Tester to run & tr&ding si(ul&tion &nd e4&(ine the log output# The
Str&tegy Tester log is displ&yed under the .ournal t&b in the Str&tegy Tester "indo"# There is & li(it
to the &(ount o) in)or(&tion th&t is listed in the Mourn&l t&b so you (&y "&nt to %ie" the &'tu&l log#
The Str&tegy Tester logs &re stored in the \tester\lo!s )older# Right 'li', &ny"here in the Mourn&l
"indo" &nd sele't ,pen )ro( the pop-up (enu# ! *indo"s E4plorer "indo" "ill open displ&ying
the 'ontents o) the log )older# The )ile n&(es &re in the )or(&t 0000mmdd.lo! "here 0000 is the
)our digit ye&r mm is the t"o digit (onth &nd dd is the t"o digit d&te# $ou '&n %ie" the logs in
Notep&d or &ny te4t editor#
3et5s illustr&te &n e4&(ple o) ho" you '&n use the log to lo'&te & progr&((ing proble(# The 'ode
belo" h&s &n error in it &nd it is not per)or(ing &s "e e4pe'ted# To be &ble to di&gnose the proble(
11
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 150/212
EXPERT ADVISOR PROGRAMMING
"e need to 'he', the input or output o) the )un'tion# 3et5s 're&te & rint() st&te(ent &nd print the
'ontents o) &ll rele%&nt %&ri&bles to the log#
*e5ll run the E! in the Str&tegy Tester using ,pen prices only &s our testing (odel# &,e sure you5re
testing the E! o%er & long enough ti(e period so th&t it "ill pl&'e enough tr&des )or us to &n&lye# I)
you need to 'he', pri'es on the 'h&rt hit the ,pen "!art button to open & 'h&rt sho"ing thesi(ul&ted tr&des#
Ne4t "e5ll go to the Mourn&l t&b &nd 'he', )or the in)or(&tion "e need# I) "e need to %ie" the log in
it5s entirety or i) there &re tr&des th&t &re not sho"ing in the Mourn&l t&b "e '&n right-'li', &nd
'hoose Open )ro( the pop-up (enu &nd open the log )ile dire'tly#
This 'ode is gi%ing us error 1?0+ /in%&lid stops/ e%ery ti(e "e pl&'e & buy order# *e ,no" th&t error
1?0 (e&ns th&t either the stop loss or the t&,e pro)it is in'orre't# C&n you identi)y the error
i(Close[9] F M? QQ <u$Ticket == 9')
double &en*rice = ?sk;
double <u$Sto&Loss = &en*rice N (Sto&Loss . 5se*oint';
double <u$Take*roit = &en*rice N (Take*roit . 5se*oint';
<u$Ticket = rderSend(S$mbol('*<53LotSi>e&en*rice5seSli&&age
<u$Sto&Loss<u$Take*roit"<u$ rder"MagicBumber9Areen';
SellTicket = 9;
,
*e "ill use the rint() )un'tion to %eri)y the p&r&(eters th&t &re being p&ssed to the =rder+end()
)un'tion# *e5ll )o'us on the order opening pri'e the stop loss &nd the t&,e pro)it#
*rint("*riceJ"N&en*riceN" Sto&J"N<u$Sto&LossN" *roitJ"N<u$Take*roit';
Here is the output "hen "e run the E! in the str&tegy tester# ! stop loss &nd t&,e pro)it o) =0 pips is
&ssu(ed+
11J24J14 499W!11!94 94J99 /+am&le /5K5S6H1J rderSend error 189
11J24J14 499W!11!94 94J99 /+am&le /5K5S6H1J *riceJ1!:U8:9999 Sto&J1!:UV:9999*roitJ1!:UV:9999
*e ,no" th&t the stop loss (ust be belo" the opening pri'e )or & buy order# Here it is &bo%e the
pri'e# In )&'t it5s the s&(e pri'e &s the t&,e pro)it# ! .ui', loo, &t our 'ode &nd "e re&lie th&t "e
&''ident&lly inserted & plus sign in the buy stop loss e.u&tion# Here is the 'orre't 'ode+
12
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 151/212
Tips and Tric*s
double <u$Sto&Loss = &en*rice (Sto&Loss . 5se*oint';
I) you &re re'ei%ing &n error (ess&ge "hen &tte(pting to pl&'e 'lose or (odi)y &n order )o'us your
e))orts on the issue indi'&ted by the error (ess&ge# Here &re & 'ouple o) the (ost 'o((on error
(ess&ges '&use by progr&((ing errors+
• Error %'/D #nva"id Pri$e The opening pri'e is in%&lid# 6or (&r,et orders (&,e sure the
'urrent 8id or !s, pri'e is being p&ssed &''ording to the order type# 6or pending orders
(&,e sure the pri'e is &bo%e or belo" the 'urrent pri'e &s re.uired by the order type# !lso
'he', to see th&t the pending order pri'e is not too 'lose to the 'urrent pri'e A i#e# inside the
stop le%elB#
• Error %8(D #nva"id Stops Either the stop loss or t&,e pro)it pri'e is in'orre't# Che', to
see th&t the stop loss &nd t&,e pro)it pri'es &re pl&'ed &bo%e or belo" the 'urrent pri'e
depending on "hether the order type is buy or sell# !lso 'he', to see th&t the stop loss or
t&,e pro)it pri'e is not too 'lose to the 'urrent pri'e A i#e# inside the stop le%elB#
• Error %8%D #nva"id Trade 7o"ume The lot sie is in'orre't# &,e sure th&t the lot sie
does not e4'eed the bro,er (ini(u( or (&4i(u( &nd th&t the lot sie is nor(&lied to the
'orre't step %&lue A0#1 or 0#01 on (ost bro,ersB#
Des'riptions o) &ll error (ess&ges '&n be )ound in the 3 Re)eren'e under tandard "onstants -
Error "odes# I) you need &ddition&l &ssist&n'e "ith &n error th&t you &re re'ei%ing 'he', the )oru(s
&t 3#'o(#
Trou!"es+ooting #ntermittent Trading Errors*hile (ost serious bugs '&n be )ound si(ply by b&', testing others "ill o''ur only during re&l-ti(e
tr&ding# Errors o) logi' '&n result in tr&des not being pl&'ed 'orre'tly &nd these bugs '&n t&,e so(e
e))ort to lo'&te# I) there &re tr&des being pl&'ed in'orre'tly during de(o or li%e tr&ding "e need &s
(u'h in)or(&tion &s ne'ess&ry to troubleshoot the proble(#
*e5re going to &dd &n option&l )e&ture to log tr&de &nd st&tus in)or(&tion in re&l-ti(e so th&t "e
h&%e & re'ord o) it "hen troubleshooting tr&des# *e5ll be using rint() st&te(ents &s pre%iously
but "e5ll be logging indi'&tor %&lues pri'es &ny in)or(&tion th&t "ill be help)ul in debugging# *e5ll
&lso &dd &n e4tern&l %&ri&ble to turn logging on &nd o))#
-- /+ternal 0ariables
e+tern bool 6ebug = true;
1?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 152/212
EXPERT ADVISOR PROGRAMMING
-- *lace near the end o the start(' unction
i(6ebug == true' *rint(StringConcatenate("<idJ"<id" ?skJ"?sk" M?J"M?
" <u$TicketJ"<u$Ticket" SellTicketJ"SellTicket'';
The &bo%e 'ode "ill log pri'e &nd indi'&tor in)or(&tion &s "ell &s the 'ontents o) the 7u0%icket &nd
+ell%icket %&ri&bles# I) there &re &ny .uestions &bout ho" & tr&de "&s opened or "hy & tr&de "&s
not opened the log &t th&t p&rti'ul&r (o(ent "ill sho" the st&tus o) &ll rele%&nt tr&de 'onditions#
$ou '&n turn logging on &nd o)) "ith the 6ebu! e4tern&l %&ri&ble#
The debug rint() st&te(ent should be pl&'ed ne&r the end o) the start() )un'tion &)ter &ll
tr&ding )un'tions# I) you &re using & ti(er &nd7or &n e4e'ute &t b&r open )e&ture pl&'e the debug
rint() st&te(ent inside the ti(er blo', so th&t it "ill only run "hen ne'ess&ry# Other"ise the
debug line "ill print to the log on e%ery ti', "hi'h '&n result in & l&rge log )ile#
,ixing Compi"ation Errors*hen you 'o(pile your e4pert &d%isor the 'o(piler "ill 'he', )or 'orre't synt&4 &nd ensure th&t &ll
'usto( )un'tions &nd %&ri&bles h&%e been properly de'l&red# I) you5%e le)t so(ething out the
'o(piler "ill stop &nd &ny 'o(pil&tion errors "ill &ppe&r in the Errors t&b in the Toolbox "indo"#
*hen 'on)ronted "ith & long list o) 'o(pil&tion errors &l"&ys st&rt "ith the )irst one# Double-'li',
the error in the list &nd the editor "ill u(p dire'tly to the line "ith the error# Corre't the error &nd
re'o(pile# So(eti(es & si(ple synt&4 error "ill result in se%er&l unrel&ted errors <hough only the
)irst one "&s %&lid#
Here is & list o) 'o((on 'o(pil&tion errors &nd their solutions+
• 7aria!"e not defined $ou )orgot to de'l&re & %&ri&ble "ith & d&t& type# I) it is & glob&l or
e4tern&l %&ri&ble de'l&re it &t the top o) the )ile# I) it is & lo'&l %&ri&ble )ind the )irst
o''urren'e &nd pl&'e the d&t& type de'l&r&tion in )ront o) it# Other"ise 'he', the spelling or
the '&se Aupper7lo"erB o) the %&ri&ble n&(e#
• 7aria!"e a"ready defined $ou de'l&red the s&(e %&ri&ble t"i'e# Re(o%e the d&t& type
de'l&r&tion )ro( &ll dupli'&te %&ri&ble de'l&r&tions#
• ,un$tion is not defined I) the )un'tion in .uestion is in &n in'lude or libr&ry )ile be sure
th&t the Ainclude or Aimport dire'ti%e is pl&'ed &t the top o) the )ile &nd is 'orre't#
Other"ise 'he', the spelling or the '&se o) the )un'tion n&(e &nd be sure th&t it e4ists
either in the 'urrent )ile or in the rele%&nt in'lude or libr&ry )iles#
1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 153/212
Tips and Tric*s
• #""ega" assignment used This is usu&lly in re)eren'e to &n e.u&l sign AB# Re(e(ber
th&t & single e.u&l sign is )or %&ri&ble &ssign(ent &nd t"o e.u&l signs AB is & 'o(p&rison
oper&tor# Corre't the &ssign(ent oper&tor to the &ppropri&te 'o(p&rison oper&tor#
• Assignment expe$ted This is usu&lly in re)eren'e to the /e.u&l to/ 'o(p&rison oper&tor
AB# $ou used t"o e.u&l signs inste&d o) one in & %&ri&ble &ssign(ent# Corre't the oper&tor
to & single e.u&l sign#
• 5n!a"an$ed rig+t parent+esis These usu&lly o''ur in &n if st&te(ent "hen using
nested p&rentheses# Go to the line indi'&ted by the )irst error &nd insert & le)t p&renthesis in
the &ppropri&te pl&'e#
• 5n!a"an$ed "eft parent+esis This is & tri',y one# The error usu&lly points to the end o)
progr&( line# 8&si'&lly you )orgot & right p&renthesis so(e"here# Double 'he', the 'ode you
re'ently edited &nd loo, )or & (issing right p&renthesis# $ou (&y h&%e to 'o((ent out lines
o) 'ode to lo'&te the proble(#
• )rong parameters $ount $ou h&%e too )e" or too (&ny &rgu(ents in & )un'tion#Double 'he', the )un'tion synt&4 in the 3 Re)eren'e &nd 'orre't the &rgu(ents#
• Semi$o"on expe$ted $ou prob&bly )orgot to put & se(i'olon &t the end o) & line# Pl&'e &
se(i'olon &t the end o) the pre%ious line# Note th&t & (issing se(i-'olon (&y '&use &ny o)
the &bo%e errors &s "ell so be sure to pl&'e those se(i'olonsL
1=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 154/212
EXPERT ADVISOR PROGRAMMING
C+apter /Custom #ndi$ators and S$ripts
No boo, on 3 "ould be 'o(plete "ithout 'o%ering 'usto( indi'&tors &nd s'ripts# The built-in
indi'&tors in et&Tr&der &re r&ther li(ited but )ortun&tely 3 &llo"s progr&((ers to 're&te their
o"n indi'&tors# I) you5re loo,ing )or & popul&r indi'&tor th&t is not in'luded in T 'h&n'es &re
so(eone h&s &lre&dy 're&ted one#
This 'h&pter "ill be & b&si' o%er%ie" o) 'usto( indi'&tor 're&tion# ost indi'&tors use 'o(ple4
(&the(&ti'&l )or(ul&s &nd &s su'h &re the do(&in o) (ore e4perien'ed progr&((ers# Ho"e%er &n
indi'&tor need not be 'o(ple4# *e5ll 're&te & 'usto( indi'&tor in this 'h&pter th&t uses only & )e"
lines o) 'ode#
2uffers
8u))ers &re &rr&ys th&t store indi'&tor %&lues &nd '&l'ul&tions# ! 'usto( indi'&tor '&n h&%e up to ;
bu))ers# 8u))ers use inde4es ust li,e &rr&ys do &nd r&nge )ro( 0 to :# *hen you '&ll & 'usto(
indi'&tor in &n e4pert &d%isor using the iCustom() )un'tion the ne4t-to-l&st p&r&(eter in the
)un'tion is the indi'&tor bu))er#
To )ind the &ppropri&te bu))er )or &n indi'&tor line you usu&lly 'he', the sour'e 'ode i) &%&il&ble# I)
the sour'e 'ode is 'le&rly )or(&tted "ith des'ripti%e %&ri&ble n&(es you should be &ble to identi)y
the &ppropri&te bu))er .uite e&sily# *e "ill &ddress the proper n&(ing o) indi'&tor bu))ers in this'h&pter#
Creating A Custom #ndi$ator
3et5s build & 'usto( indi'&tor using t"o built-in et&Tr&der indi'&tors to '&l'ul&te our lines# *e5re
going to build & (odi)ied 8ollinger 8&nds indi'&tor# The 8ollinger 8&nds 'onsist o) ? lines & 'enter
line "hi'h is & si(ple (o%ing &%er&ge &long "ith &n upper &nd lo"er line "hose %&lue is deter(ined
by the st&nd&rd de%i&tion#
*e '&n 're&te our o"n 8ollinger 8&nds indi'&tor using the o%ing !%er&ge &nd the St&nd&rd
De%i&tion indi'&tors# *e5d li,e to 're&te &n indi'&tor th&t uses &n e4ponenti&l (o%ing &%er&ge to
'&l'ul&te the lines &s opposed to & si(ple (o%ing &%er&ge#
1<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 155/212
"usto# Indicators and cripts
*e st&rt by using the "i&rd to 're&te our indi'&tor )ile# Sele't Ne% )ro( the 6ile (enu or the toolb&r
to open the "i&rd &nd 're&te & 'usto( indi'&tor# 6ill out the indi'&tor n&(e &nd &dd p&r&(eters i)
you "ish# On the )in&l p&ge "e &dded three indi'&tor lines o) the s&(e 'olor# Here is the result o)
the "i&rd# *e5%e le)t out the start() )un'tion )or no"+
--NN--7 /M? <ollinger!mE: 7
--7 ?ndre% 3oung 7
--7 htt&J--%%%!eas$e+&ertore+!com 7
--NN
&ro&ert$ co&$right "?ndre% 3oung"
&ro&ert$ link "htt&J--%%%!eas$e+&ertore+!com"
Apropert0 indicator>chart>window
Apropert0 indicator>buffers S
Apropert0 indicator>color 6eep+k07lue
Apropert0 indicator>color1 6eep+k07lue
Apropert0 indicator>colorS 6eep+k07lue
-- buersdouble <xt8ap7ufferIJM
double <xt8ap7uffer1IJM
double <xt8ap7ufferSIJM
--NN
--7 Custom indicator initiali>ation unction 7
--NN
int init('
)
-- indicators
+et#ndex+t0le(2D65;G>,#<)M
+et#ndex7uffer(2D<xt8ap7uffer)M
+et#ndex+t0le(D65;G>,#<)M
+et#ndex7uffer(D<xt8ap7uffer1)M +et#ndex+t0le(1D65;G>,#<)M
+et#ndex7uffer(1D<xt8ap7ufferS)M
--
return(9';
,
3et5s turn our &ttention to the ele(ents listed in bold# The Apropert0 de'l&r&tions set the p&r&(eters
)or our indi'&tor bu))ers# The indicator>chart>window property dr&"s our indi'&tor in the (&in
'h&rt "indo"# I) "e "ere 're&ting &n os'ill&tor &nd "&nted to dr&" the indi'&tor in & sep&r&te
"indo" "e5d use the indicator>separate>window property inste&d#
The indicator>buffers property set the nu(ber o) bu))ers )or our indi'&tor# In this '&se "e &re
using three bu))ers# The indicator>color properties set the 'olor o) &ll three lines to 6eep+k07lue#
1:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 156/212
EXPERT ADVISOR PROGRAMMING
Ne4t &re the de'l&r&tions )or our bu))er &rr&ys# *e h&%e three bu))ers n&(ed <xt8ap7uffer(1-3)#
*e "ill 'h&nge these &rr&y identi)iers to so(ething (ore des'ripti%e shortly#
The init() )un'tion is "here "e set the properties )or our indi'&tor bu))ers# +et#ndex7uffer()
binds & bu))er &rr&y to & bu))er inde4# The bu))er inde4 is "h&t "e re)er to "hen "e set the
properties )or &n indi'&tor line &nd &lso "hen "e '&ll &n indi'&tor line )ro( &n E! using theiCustom() )un'tion# The )irst p&r&(eter is &n integer )ro( 0 to : &nd the se'ond p&r&(eter is the
n&(e o) the bu))er &rr&y#
0rawing Properties
The +et#ndex+t0le() )un'tion sets the type o) line to dr&" &long "ith the properties o) th&t line#
E%ery indi'&tor line "ill h&%e & 'orresponding +et#ndex+t0le() )un'tion# Here is the synt&4+
0oid SetInde+St$le(int -uffer$ndex int LineType int LineStyle = /M*T3
int Line.idt' = /M*T3 color LineColor = CLKBB/'
• 2uffer#ndex The inde4 o) the bu))er )ro( 0 to :#
• LineType Sets the type o) line to dr&"# 65;G>,#< dr&"s & single line 65;G>?#+%=B5;8
dr&"s & %erti'&l histogr&( Asee the Os! or !"eso(e Os'ill&tor indi'&tors )or e4&(plesB
65;G>;55=G dr&"s & sy(bol &nd 65;G>=< dr&"s no line#
• LineSty"e !n option&l p&r&(eter indi'&ting the dr&"ing style# >sed (&inly )or lines o) type
65;G>,#<# 8y de)&ult & solid line is dr&"n A+%@,<>+=,#6B# $ou '&n &lso dr&" d&shed
A+%@,<>6;+?B &nd dotted A+%@,<>6=%B lines#
• Line)idt+ !n option&l p&r&(eter indi'&ting the "idth o) the line in pi4els# The de)&ult
%&lue is 1#
• LineCo"or !n option&l p&r&(eter indi'&ting the 'olor o) the line# I) you use the "i&rd the
'olor is set using Apropert0 de'l&r&tions but you '&n set the 'olor here &s "ell#
I) you &re using 65;G>;55=G &s the ,ine%0pe the +et;rrow() )un'tion &llo"s you to set the
*ingdings )ont sy(bol to dr&" on the 'h&rt# The )irst p&r&(eter is the bu))er inde4 &nd the se'ond
is &n integer 'onst&nt representing the sy(bol to dr&"# The sy(bols '&n be )ound in the 3
Re)eren'e under tandard "onstants - Arro% "odes#
$ou (&y "&nt to &dd & des'ription )or the indi'&tor lines th&t "ill be displ&yed in the tooltip or in the
d&t& "indo"# To do this use the +et#ndex,abel() )un'tion# The )irst p&r&(eter is the bu))er inde4
&nd the se'ond p&r&(eter is & te4t des'ription# *e5ll &dd these to our indi'&tor shortly#
1;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 157/212
"usto# Indicators and cripts
I) your indi'&tor is dr&"n in & sep&r&te "indo" Asu'h &s &n os'ill&torB &nd you5d li,e to &dd le%els to
indi'&te o%erbought or o%ersold le%els Asu'h &s in the Sto'h&sti' or RSI indi'&torsB or the ero le%el
Asu'h &s in the CCI indi'&torB you '&n use the +et,evel+t0le() &nd +et,evel9alue() )un'tions#
See the 3 Re)eren'e under "usto# Indicators )or (ore in)or(&tion#
$ou (&y &lso "&nt to spe'i)y & short indi'&tor n&(e to be displ&yed in the top le)t 'orner o) theindi'&tor "indo"# >se the #ndicator+hortame() )un'tion to set this %&lue# The only p&r&(eter is &
te4t string th&t "ill &ppe&r in the top le)t 'orner o) the indi'&tor "indo" &s "ell &s in the d&t&
"indo"#
5sing 0es$riptive 2uffer ames
Here is our upd&ted indi'&tor 'ode# Note th&t "e5%e ren&(ed the bu))er &rr&ys to be (ore des'ripti%e
&s to their &'tu&l )un'tion# *e5%e 'h&nged the se'ond p&r&(eter o) the +et#ndex7uffer() )un'tions
to re)le't the ne" bu))er n&(es# *e5%e &lso &dded +et#ndex,abel() )or e&'h line to displ&y
des'ripti%e n&(es in the D&t& *indo"#
-- buers
double <8;IJM
double Upper7andIJM
double ,ower7andIJM
--NN
--7 Custom indicator initiali>ation unction 7
--NN
int init('
)
-- indicators
SetInde+St$le(96K?OLIB/'; SetInde+<uer(9<8;';
+et#ndex,abel(2D<8;)M
SetInde+St$le(16K?OLIB/';
SetInde+<uer(1Upper7and';
+et#ndex,abel(DUpper7and)M
SetInde+St$le(46K?OLIB/';
SetInde+<uer(4,ower7and';
+et#ndex,abel(1D,ower7and)M
--
return(9';
,
*e5%e ren&(ed our bu))er &rr&ys )ro( the de)&ult n&(es A<xt8ap7ufferB to (ore des'ripti%e ones#
<8;IJ "ill be our bu))er )or the 'enter line &nd Upper7andIJ &nd ,ower7andIJ "ill be the upper
&nd lo"er b&nds respe'ti%ely#
19
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 158/212
EXPERT ADVISOR PROGRAMMING
The +et#ndex7uffer() )un'tions bind the bu))er inde4es to our bu))er &rr&ys# <8; is 0 Upper7and is
1 &nd ,ower7and is 2# Note th&t the br&'es &re le)t out o) the &rr&y identi)ier n&(e )or the se'ond
+et#ndex7uffer() p&r&(eter#
The +et#ndex,abel() )un'tions set & des'ripti%e n&(e )or e&'h o) the indi'&tor bu))ers# In this '&se
the line n&(es &re the s&(e &s our identi)ier n&(es# These "ill &ppe&r on the (ouse tooltip &s "ell&s in the D&t& *indo"# I) ¬her progr&((er de'ides to use this indi'&tor in &n e4pert &d%isor the
)or(&tting &bo%e "ill (&,e it 'le&r e4&'tly "hi'h indi'&tor bu))er inde4 they should use )or e&'h line#
T+e #ndi$ator start<= ,un$tion
The "i&rd inserts ust one e4pression in the start() )un'tion+
int countedbars = IndicatorCounted(';
#ndicatorCounted() returns the nu(ber o) b&rs on the 'h&rt th&t the indi'&tor h&s &lre&dy
'&l'ul&ted# *hen the E! is )irst st&rted this %&lue "ill be 0# The indi'&tor "ill be '&l'ul&ted )or e%ery
b&r on the 'h&rt# On subse.uent b&rs "e "ill 'he', the #ndicatorCounted() )un'tion to see ho"
(&ny b&rs h&%e &lre&dy been '&l'ul&ted so "e5ll ,no" e4&'tly ho" (&ny ne" b&rs "e5ll need to
'&l'ul&te#
Our indi'&tor '&l'ul&tions "ill o''ur inside & for loop# The st&rting point "ill be the )irst un'&l'ul&ted
b&r &nd the end point "ill be the 'urrent b&r# *e5ll 'o(p&re the %&lue o) #ndicatorCounted() to
the prede)ined 7ars %&ri&ble "hi'h returns the nu(ber o) b&rs on the 'urrent 'h&rt# This "ill
deter(ine our st&rting point# Here is the 'ode )or the for loop+
int countedbars = IndicatorCounted(';
i(countedbars F 9' countedbars;
int Calculate<ars = <ars countedbars;
or(int Count = Calculate<ars; Count F= 9; Count'
)
-- Indicator calculations
,
The )irst if st&te(ent "ill de're(ent the %&lue o) counted>bars by 1 "hen '&l'ul&ting ne" b&rs#
*e "ill &l"&ys be '&l'ul&ting &t le&st the t"o pre%ious b&rs# This is due to & 'ondition "here the )in&l
ti', o) & b&r (&y not be '&l'ul&ted in so(e '&ses# Ne4t "e deter(ine the nu(ber o) b&rs to
'&l'ul&te by subtr&'ting counted>bars )ro( the prede)ined 7ars %&ri&ble# This is stored in the
%&ri&ble Calculate7ars#
1=0
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 159/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 160/212
EXPERT ADVISOR PROGRAMMING
-- start(' unction
or(int Count = Calculate<ars; Count F= 9; Count'
)
/M?[Count] = iM?(B5LL9<ands*eriod7ands+hiftD7ands8ethodD7andsriceCount';
double Std6e0 = iStd6e0(B5LL9<ands*eriod7ands+hiftD7ands8ethodD7andsriceCount';
5&&er<and[Count] = /M?[Count] N (+td6ev * 6eviations);
Lo%er<and[Count] = /M?[Count] (+td6ev * 6eviations);
,
*e5%e &dded e4tern&l %&ri&bles to &dust the re(&ining p&r&(eters )or the i8;() &nd i+td6ev()
)un'tions# *e &lso &dded & p&r&(eter to &dust the nu(ber o) st&nd&rd de%i&tions# To '&l'ul&te this
"e si(ply (ultiply +td6ev by 6eviations# No" "e h&%e & )ully &dust&ble 8ollinger 8&nds indi'&tor
th&t is (ore )le4ible th&n the st&nd&rd et&Tr&der indi'&tor# The )ull 'ode is listed in !ppendi4 E#
$ou '&n do (ore "ith 'usto( indi'&tors th&n ust re'&l'ul&te built-in indi'&tors# Depending on yourle%el o) (&the(&ti'&l ,no"ledge you '&n 'ode indi'&tors th&t &ren5t in'luded "ith et&Tr&der or
e%en 're&te your o"n# $ou '&n &lso dr&" &nd (&nipul&te obe'ts &s "ell# I) you5d li,e to le&rn (ore
&bout 'usto( indi'&tor 're&tion see the 3 Re)eren'e topi's "usto# indicators? ,b@ect functions
&nd Mat! Trig #
S$ripts
! s'ript is &n 3 progr&( th&t runs only on'e "hen it is )irst &tt&'hed to & 'h&rt# S'ripts '&n be
used to &uto(&te & series o) tr&ding &'tions su'h &s 'losing &ll orders on the 'h&rt or sending &
pending order# So(e s'ripts su'h &s the period>converter s'ript th&t ships "ith et&Tr&der '&nredr&" the 'h&rt b&sed on & 'usto( ti(e period#
! s'ript sour'e 'ode )ile should h&%e either the show>confirm or show>inputs property dire'ti%e#
The show>confirm property pro(pts the user to 'on)ir( the oper&tion o) the s'ript "hile
show>inputs displ&ys the s'ript properties di&log#
&ro&ert$ sho%conirm -- sho%s conirm dialog
&ro&ert$ sho%in&uts -- sho%s &ro&erties dialog
I) your s'ript h&s p&r&(eters th&t need to be &dusted use the show>inputs property# Other"ise
use show>confirm#
1=2
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 161/212
"usto# Indicators and cripts
Must li,e e4pert &d%isors &nd indi'&tors s'ripts use the init() deinit() &nd start() )un'tions#
Re(e(ber th&t e&'h )un'tion "ill only be run on'e init() &nd start() "hen the s'ript is st&rted
&nd deinit() "hen it is re(o%ed# $ou '&n h&%e one s'ript &tt&'hed to & 'h&rt &t & ti(e#
et&Tr&der 'o(es "ith se%er&l s&(ple s'ripts# !ll s'ripts &re s&%ed in the \experts\scripts
dire'tory#
1=?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 162/212
EXPERT ADVISOR PROGRAMMING
Appendix A
Simp"e Expert Advisor
This is the si(ple e4pert &d%isor )ro( 'h&pter 2#
&ro&ert$ co&$right "?ndre% 3oung"
-- /+ternal 0ariables
e+tern double LotSi>e = 9!1;
e+tern double Sto&Loss = 29;
e+tern double Take*roit = 199;
e+tern int Sli&&age = 2;
e+tern int MagicBumber = 148;
e+tern int #astM?*eriod = 19;
e+tern int Slo%M?*eriod = 49;
-- Alobal 0ariables
int <u$Ticket;
int SellTicket;
double 5se*oint;
int 5seSli&&age;
-- Init unction
int init('
)
5se*oint = *i&*oint(S$mbol('';
5seSli&&age = AetSli&&age(S$mbol('Sli&&age';
,
-- Start unction
int start('
)
-- Mo0ing a0eragesdouble #astM? = iM?(B5LL9#astM?*eriod9999';
double Slo%M? = iM?(B5LL9Slo%M?*eriod9999';
1=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 163/212
Appendix A
-- <u$ order
i(#astM? F Slo%M? QQ <u$Ticket == 9'
)
rderSelect(SellTicketS/L/CT<3TICP/T';
-- Close order
i(rderCloseTime(' == 9 QQ SellTicket F 9')
double CloseLots = rderLots(';
double Close*rice = ?sk;
bool Closed = rderClose(SellTicketCloseLotsClose*rice5seSli&&ageKed';
,
double &en*rice = ?sk;
-- Calculate sto& loss and take &roit
i(Sto&Loss F 9' double <u$Sto&Loss = &en*rice (Sto&Loss . 5se*oint';
i(Take*roit F 9' double <u$Take*roit = &en*rice N (Take*roit . 5se*oint';
-- &en bu$ order
<u$Ticket = rderSend(S$mbol('*<53LotSi>e&en*rice5seSli&&age
<u$Sto&Loss<u$Take*roit"<u$ rder"MagicBumber9Areen';
SellTicket = 9;
,
-- Sell rder
i(#astM? D Slo%M? QQ SellTicket == 9'
)
rderSelect(<u$TicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9 QQ <u$Ticket F 9'
)
CloseLots = rderLots(';
Close*rice = <id;
Closed = rderClose(<u$TicketCloseLotsClose*rice5seSli&&ageKed';
,
&en*rice = <id;
i(Sto&Loss F 9' double SellSto&Loss = &en*rice N (Sto&Loss . 5se*oint';
i(Take*roit F 9' double SellTake*roit = &en*rice (Take*roit . 5se*oint';
SellTicket = rderSend(S$mbol('*S/LLLotSi>e&en*rice5seSli&&age
SellSto&LossSellTake*roit"Sell rder"MagicBumber9Ked';
<u$Ticket = 9;
,
1==
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 164/212
EXPERT ADVISOR PROGRAMMING
return(9';
,
-- *i& *oint #unction
double *i&*oint(string Currenc$'
)int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == 8' double Calc*oint = 9!91;
else i(Calc6igits == : 77 Calc6igits == 2' Calc*oint = 9!9991;
return(Calc*oint';
,
-- Aet Sli&&age #unction
int AetSli&&age(string Currenc$ int Sli&&age*i&s'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == :' double CalcSli&&age = Sli&&age*i&s;
else i(Calc6igits == 8 77 Calc6igits == 2' CalcSli&&age = Sli&&age*i&s . 19;
return(CalcSli&&age';
,
Simp"e Expert Advisor wit+ Pending &rders
Here is the si(ple e4pert &d%isor using pending stop orders+
&ro&ert$ co&$right "?ndre% 3oung"
-- /+ternal 0ariables
e+tern double LotSi>e = 9!1;
e+tern double Sto&Loss = 29;
e+tern double Take*roit = 199;
e+tern int *ending*i&s = 19;
e+tern int Sli&&age = 2;
e+tern int MagicBumber = 148;
e+tern int #astM?*eriod = 19;
e+tern int Slo%M?*eriod = 49;
-- Alobal 0ariables
int <u$Ticket;
int SellTicket;
double 5se*oint;
int 5seSli&&age;
1=<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 165/212
Appendix A
-- Init unction
int init('
)
5se*oint = *i&*oint(S$mbol('';
5seSli&&age = AetSli&&age(S$mbol('Sli&&age';
,
-- Start unction
int start('
)
-- Mo0ing a0erages
double #astM? = iM?(B5LL9#astM?*eriod9999';
double Slo%M? = iM?(B5LL9Slo%M?*eriod9999';
-- <u$ order
i(#astM? F Slo%M? QQ <u$Ticket == 9'
)
rderSelect(SellTicketS/L/CT<3TICP/T';
-- Close order
i(rderCloseTime(' == 9 QQ SellTicket F 9 QQ rderT$&e(' == *S/LL'
)
double CloseLots = rderLots(';
double Close*rice = ?sk;
bool Closed = rderClose(SellTicketCloseLotsClose*rice5seSli&&ageKed';
,
-- 6elete rder
else i(rderCloseTime(' == 9 QQ SellTicket F 9 QQ rderT$&e(' == *S/LLST*'
)
bool 6eleted = rder6elete(SellTicketKed';
,
double *ending*rice = High[9] N (*ending*i&s . 5se*oint';
-- Calculate sto& loss and take &roit
i(Sto&Loss F 9' double <u$Sto&Loss = *ending*rice (Sto&Loss . 5se*oint';
i(Take*roit F 9' double <u$Take*roit = *ending*rice N
(Take*roit . 5se*oint';
-- &en bu$ order
<u$Ticket = rderSend(S$mbol('*<53ST*LotSi>e*ending*rice5seSli&&age
<u$Sto&Loss<u$Take*roit"<u$ Sto& rder"MagicBumber9Areen';
SellTicket = 9;
,
1=:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 166/212
EXPERT ADVISOR PROGRAMMING
-- Sell rder
i(#astM? D Slo%M? QQ SellTicket == 9'
)
rderSelect(<u$TicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9 QQ <u$Ticket F 9 QQ rderT$&e(' == *<53'
)CloseLots = rderLots(';
Close*rice = <id;
Closed = rderClose(<u$TicketCloseLotsClose*rice5seSli&&ageKed';
,
else i(rderCloseTime(' == 9 QQ SellTicket F 9 QQ rderT$&e(' == *<53ST*'
)
6eleted = rder6elete(SellTicketKed';
,
*ending*rice = Lo%[9] (*ending*i&s . 5se*oint';
i(Sto&Loss F 9' double SellSto&Loss = *ending*rice N (Sto&Loss . 5se*oint';
i(Take*roit F 9' double SellTake*roit = *ending*rice
(Take*roit . 5se*oint';
SellTicket = rderSend(S$mbol('*S/LLST*LotSi>e*ending*rice5seSli&&age
SellSto&LossSellTake*roit"Sell Sto& rder"MagicBumber9Ked';
<u$Ticket = 9;
,
return(9';
,
-- *i& *oint #unction
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == 8' double Calc*oint = 9!91;
else i(Calc6igits == : 77 Calc6igits == 2' Calc*oint = 9!9991;
return(Calc*oint';
,
-- Aet Sli&&age #unction
int AetSli&&age(string Currenc$ int Sli&&age*i&s'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == :' double CalcSli&&age = Sli&&age*i&s;
else i(Calc6igits == 8 77 Calc6igits == 2' CalcSli&&age = Sli&&age*i&s . 19;
return(CalcSli&&age';
,
1=;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 167/212
Appendix A
1=9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 168/212
EXPERT ADVISOR PROGRAMMING
Appendix 2
Advan$ed Expert Advisor
This is the e4pert &d%isor "ith &d%&n'ed )e&tures )ro( 'h&pter ?#
&ro&ert$ co&$right "?ndre% 3oung"
include Dstdlib!mEhF
-- /+ternal 0ariables
e+tern bool 6$namicLotSi>e = true;
e+tern double /Euit$*ercent = 4;
e+tern double #i+edLotSi>e = 9!1;
e+tern double Sto&Loss = 29;
e+tern double Take*roit = 199;
e+tern int Sli&&age = 2;
e+tern int MagicBumber = 148;
e+tern int #astM?*eriod = 19;
e+tern int Slo%M?*eriod = 49;
-- Alobal 0ariables
int <u$Ticket;
int SellTicket;
double 5se*oint;
int 5seSli&&age;
int /rrorCode;
-- Init unction
int init('
)
5se*oint = *i&*oint(S$mbol('';
5seSli&&age = AetSli&&age(S$mbol('Sli&&age';
,
-- Start unctionint start('
)
-- Mo0ing a0erages
double #astM? = iM?(B5LL9#astM?*eriod9991';
double Slo%M? = iM?(B5LL9Slo%M?*eriod9991';
1<0
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 169/212
Appendix +
-- Lot si>e calculation
i(6$namicLotSi>e == true'
)
double Kisk?mount = ?ccount/Euit$(' . (/Euit$*ercent - 199';
double Tickalue = MarketIno(S$mbol('M6/TICP?L5/';
i(*oint == 9!991 77 *oint == 9!99991' Tickalue .= 19;
double CalcLots = (Kisk?mount - Sto&Loss' - Tickalue;
double LotSi>e = CalcLots;,
else LotSi>e = #i+edLotSi>e;
-- Lot si>e 0eriication
i(LotSi>e D MarketIno(S$mbol('M6/MIBLT''
)
LotSi>e = MarketIno(S$mbol('M6/MIBLT';
,
else i(LotSi>e F MarketIno(S$mbol('M6/M?LT''
)
LotSi>e = MarketIno(S$mbol('M6/M?LT';
,
i(MarketIno(S$mbol('M6/LTST/*' == 9!1'
)
LotSi>e = Bormali>e6ouble(LotSi>e1';
,
else LotSi>e = Bormali>e6ouble(LotSi>e4';
-- <u$ rder
i(#astM? F Slo%M? QQ <u$Ticket == 9'
)
-- Close rder
rderSelect(SellTicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9 QQ SellTicket F 9'
)
double CloseLots = rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
KereshKates(';
double Close*rice = ?sk;
bool Closed = rderClose(SellTicketCloseLotsClose*rice5seSli&&ageKed';
-- /rror handling
i(Closed == alse'
)
/rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
1<1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 170/212
EXPERT ADVISOR PROGRAMMING
string /rr?lert = StringConcatenate("Close Sell rder /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("?skJ "?sk" LotsJ "LotSi>e
" TicketJ "SellTicket';
*rint(/rrLog';
,
,
-- &en bu$ order
%hile(IsTradeConte+t<us$('' Slee&(19';
KereshKates(';
<u$Ticket = rderSend(S$mbol('*<53LotSi>e?sk5seSli&&age99
"<u$ rder"MagicBumber9Areen';
-- /rror handling
i(<u$Ticket == 1'
)
/rrorCode = AetLast/rror(';
/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("&en <u$ rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("?skJ "?sk" LotsJ "LotSi>e';
*rint(/rrLog';
,
-- rder modiication
else
)
rderSelect(<u$TicketS/L/CT<3TICP/T';
double &en*rice = rder&en*rice(';
-- Calculate sto& le0el
double Sto&Le0el = MarketIno(S$mbol('M6/ST*L//L' . *oint;
KereshKates(';
double 5&&erSto&Le0el = ?sk N Sto&Le0el;
double Lo%erSto&Le0el = <id Sto&Le0el;
double MinSto& = 2 . 5se*oint;
-- Calculate sto& loss and take &roit
i(Sto&Loss F 9' double <u$Sto&Loss = &en*rice (Sto&Loss . 5se*oint';
i(Take*roit F 9' double <u$Take*roit = &en*rice N
(Take*roit . 5se*oint';
1<2
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 171/212
Appendix +
-- eri$ sto& loss and take &roit
i(<u$Sto&Loss F 9 QQ <u$Sto&Loss F Lo%erSto&Le0el'
)
<u$Sto&Loss = Lo%erSto&Le0el MinSto&;
,
i(<u$Take*roit F 9 QQ <u$Take*roit D 5&&erSto&Le0el')
<u$Take*roit = 5&&erSto&Le0el N MinSto&;
,
-- Modi$ order
i(IsTradeConte+t<us$('' Slee&(19';
i(<u$Sto&Loss F 9 77 <u$Take*roit F 9'
)
bool TicketMod = rderModi$(<u$Ticket&en*rice<u$Sto&Loss
<u$Take*roit9';
-- /rror handling
i(TicketMod == alse'
)
/rrorCode = AetLast/rror(';
/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("Modi$ <u$ rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("?skJ "?sk" <idJ "<id" TicketJ "
<u$Ticket" Sto&J "<u$Sto&Loss" *roitJ "<u$Take*roit';
*rint(/rrLog';
,
,
,
SellTicket = 9;
,
-- Sell rder
i(#astM? D Slo%M? QQ SellTicket == 9'
)
rderSelect(<u$TicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9 QQ <u$Ticket F 9'
)
CloseLots = rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
KereshKates(';
1<?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 172/212
EXPERT ADVISOR PROGRAMMING
Close*rice = <id;
Closed = rderClose(<u$TicketCloseLotsClose*rice5seSli&&ageKed';
-- /rror handling
i(Closed == alse'
)
/rrorCode = AetLast/rror(';/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("Close <u$ rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("<idJ "<id" LotsJ "LotSi>e" TicketJ "
<u$Ticket';
*rint(/rrLog';
,
,
%hile(IsTradeConte+t<us$('' Slee&(19';
KereshKates(';
SellTicket = rderSend(S$mbol('*S/LLLotSi>e<id5seSli&&age99
"Sell rder" MagicBumber9Ked';
-- /rror handling
i(SellTicket == 1'
)
/rrorCode = AetLast/rror(';
/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("&en Sell rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("<idJ "<id" LotsJ "LotSi>e';
*rint(/rrLog';
,
else
)
rderSelect(SellTicketS/L/CT<3TICP/T';
&en*rice = rder&en*rice(';
Sto&Le0el = MarketIno(S$mbol('M6/ST*L//L' . *oint;
KereshKates(';
5&&erSto&Le0el = ?sk N Sto&Le0el;
Lo%erSto&Le0el = <id Sto&Le0el;
MinSto& = 2 . 5se*oint;
i(Sto&Loss F 9' double SellSto&Loss = &en*rice N (Sto&Loss . 5se*oint';
1<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 173/212
Appendix +
i(Take*roit F 9' double SellTake*roit = &en*rice
(Take*roit . 5se*oint';
i(SellSto&Loss F 9 QQ SellSto&Loss D 5&&erSto&Le0el'
)
SellSto&Loss = 5&&erSto&Le0el N MinSto&;
,
i(SellTake*roit F 9 QQ SellTake*roit F Lo%erSto&Le0el')
SellTake*roit = Lo%erSto&Le0el MinSto&;
,
i(IsTradeConte+t<us$('' Slee&(19';
i(SellSto&Loss F 9 77 SellTake*roit F 9'
)
TicketMod = rderModi$(SellTicket&en*riceSellSto&Loss
SellTake*roit9';
-- /rror handling
i(TicketMod == alse'
)
/rrorCode = AetLast/rror(';
/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("Modi$ Sell rder /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("?skJ "?sk" <idJ "<id" TicketJ "
SellTicket" Sto&J "SellSto&Loss" *roitJ "SellTake*roit';
*rint(/rrLog';
,
,
,
<u$Ticket = 9;
,
return(9';
,
-- *i& *oint #unction
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == 8' double Calc*oint = 9!91;
else i(Calc6igits == : 77 Calc6igits == 2' Calc*oint = 9!9991;
return(Calc*oint';
,
1<=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 174/212
EXPERT ADVISOR PROGRAMMING
-- Aet Sli&&age #unction
int AetSli&&age(string Currenc$ int Sli&&age*i&s'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == :' double CalcSli&&age = Sli&&age*i&s;
else i(Calc6igits == 8 77 Calc6igits == 2' CalcSli&&age = Sli&&age*i&s . 19;
return(CalcSli&&age';
,
Advan$ed Expert Advisor wit+ Pending &rders
Here is the &d%&n'ed e4pert &d%isor using pending stop orders+
include Dstdlib!mEhF
-- /+ternal ariables
e+tern int *ending*i&s = 49;
e+tern double LotSi>e = 9!1;e+tern double Sto&Loss = 29;
e+tern double Take*roit = 199;
e+tern int Sli&&age = 2;
e+tern int MagicBumber = 148;
e+tern int #astM?*eriod = 19;
e+tern int Slo%M?*eriod = 49;
-- Alobal ariables
int <u$Ticket;
int SellTicket;
double 5se*oint;
int 5seSli&&age;int /rrorCode;
-- Init unction
int init('
)
5se*oint = *i&*oint(S$mbol('';
5seSli&&age = AetSli&&age(S$mbol('Sli&&age';
,
-- Start #unction
int start(')
-- Mo0ing ?0erage
double #astM? = iM?(B5LL9#astM?*eriod9999';
double Slo%M? = iM?(B5LL9Slo%M?*eriod9999';
1<<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 175/212
Appendix +
-- <u$ rder
i(#astM? F Slo%M? QQ <u$Ticket == 9'
)
-- Close order
rderSelect(SellTicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9 QQ SellTicket F 9 QQ rderT$&e(' == *S/LL'
)double CloseLots = rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
KereshKates(';
double Close*rice = ?sk;
bool Closed = rderClose(SellTicketCloseLotsClose*rice5seSli&&ageKed';
-- /rror handling
i(Closed == alse'
)
/rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close Sell rder /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("?skJ "?sk" LotsJ "LotSi>e
" TicketJ "SellTicket';
*rint(/rrLog';
,
,
-- 6elete order
else i(rderCloseTime(' == 9 QQ SellTicket F 9 QQ rderT$&e(' == *S/LLST*'
)
bool 6eleted = rder6elete(SellTicketKed';
i(6eleted == true' SellTicket = 9;
-- /rror handling
i(6eleted == alse'
)
/rrorCode = AetLast/rror(';
/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("6elete Sell Sto& rder /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("?skJ "?sk" TicketJ "SellTicket';
*rint(/rrLog';
,
,
1<:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 176/212
EXPERT ADVISOR PROGRAMMING
-- Calculate sto& le0el
double Sto&Le0el = MarketIno(S$mbol('M6/ST*L//L' . *oint;
KereshKates(';
double 5&&erSto&Le0el = ?sk N Sto&Le0el;
double MinSto& = 2 . 5se*oint;
-- Calculate &ending &rice
double *ending*rice = High[9] N (*ending*i&s . 5se*oint';i(*ending*rice D 5&&erSto&Le0el' *ending*rice = 5&&erSto&Le0el N MinSto&;
-- Calculate sto& loss and take &roit
i(Sto&Loss F 9' double <u$Sto&Loss = *ending*rice (Sto&Loss . 5se*oint';
i(Take*roit F 9' double <u$Take*roit = *ending*rice N
(Take*roit . 5se*oint';
-- eri$ sto& loss and take &roit
5&&erSto&Le0el = *ending*rice N Sto&Le0el;
double Lo%erSto&Le0el = *ending*rice Sto&Le0el;
i(<u$Sto&Loss F 9 QQ <u$Sto&Loss F Lo%erSto&Le0el'
)
<u$Sto&Loss = Lo%erSto&Le0el MinSto&;
,
i(<u$Take*roit F 9 QQ <u$Take*roit D 5&&erSto&Le0el'
)
<u$Take*roit = 5&&erSto&Le0el N MinSto&;
,
-- *lace &ending order
i(IsTradeConte+t<us$('' Slee&(19';
<u$Ticket = rderSend(S$mbol('*<53ST*LotSi>e*ending*rice5seSli&&age
<u$Sto&Loss<u$Take*roit"<u$ Sto& rder"MagicBumber9Areen';
-- /rror handling
i(<u$Ticket == 1'
)
/rrorCode = AetLast/rror(';
/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("&en <u$ Sto& rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("?skJ "?sk" LotsJ "LotSi>e" *riceJ "
*ending*rice" Sto&J "<u$Sto&Loss" *roitJ "<u$Take*roit';
*rint(/rrLog';
,
SellTicket = 9;
,
1<;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 177/212
Appendix +
-- Sell rder
i(#astM? D Slo%M? QQ SellTicket == 9'
)
rderSelect(<u$TicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9 QQ <u$Ticket F 9 QQ rderT$&e(' == *<53'
)
CloseLots = rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
KereshKates(';
Close*rice = <id;
Closed = rderClose(<u$TicketCloseLotsClose*rice5seSli&&ageKed';
i(Closed == alse'
)
/rrorCode = AetLast/rror(';
/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("Close <u$ rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("<idJ "<id" LotsJ "LotSi>e" TicketJ "
<u$Ticket';
*rint(/rrLog';
,
,
else i(rderCloseTime(' == 9 QQ <u$Ticket F 9 QQ rderT$&e(' == *<53ST*'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
Closed = rder6elete(<u$TicketKed';
i(6eleted == alse'
)
/rrorCode = AetLast/rror(';
/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("6elete <u$ Sto& rder /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("<idJ "<id" TicketJ "<u$Ticket';
*rint(/rrLog';
,
,
Sto&Le0el = MarketIno(S$mbol('M6/ST*L//L' . *oint;
KereshKates(';
Lo%erSto&Le0el = <id Sto&Le0el;
1<9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 178/212
EXPERT ADVISOR PROGRAMMING
MinSto& = 2 . 5se*oint;
*ending*rice = Lo%[9] (*ending*i&s . 5se*oint';
i(*ending*rice F Lo%erSto&Le0el' *ending*rice = Lo%erSto&Le0el MinSto&;
i(Sto&Loss F 9' double SellSto&Loss = *ending*rice N (Sto&Loss . 5se*oint';
i(Take*roit F 9' double SellTake*roit = *ending*rice
(Take*roit . 5se*oint';
5&&erSto&Le0el = *ending*rice N Sto&Le0el;
Lo%erSto&Le0el = *ending*rice Sto&Le0el;
i(SellSto&Loss F 9 QQ SellSto&Loss D 5&&erSto&Le0el'
)
SellSto&Loss = 5&&erSto&Le0el N MinSto&;
,
i(SellTake*roit F 9 QQ SellTake*roit F Lo%erSto&Le0el'
)
SellTake*roit = Lo%erSto&Le0el MinSto&;
,
i(IsTradeConte+t<us$('' Slee&(19';
SellTicket = rderSend(S$mbol('*S/LLST*LotSi>e*ending*rice5seSli&&age
SellSto&LossSellTake*roit"Sell Sto& rder"MagicBumber9Ked';
i(SellTicket == 1'
)
/rrorCode = AetLast/rror(';
/rr6esc = /rror6escri&tion(/rrorCode';
/rr?lert = StringConcatenate("&en Sell Sto& rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
/rrLog = StringConcatenate("<idJ "<id" LotsJ "LotSi>e" *riceJ "
*ending*rice" Sto&J "SellSto&Loss" *roitJ "SellTake*roit';
*rint(/rrLog';
,
<u$Ticket = 9;
,
return(9';
,
1:0
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 179/212
Appendix +
-- *i& *oint #unction
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == 8' double Calc*oint = 9!91;
else i(Calc6igits == : 77 Calc6igits == 2' Calc*oint = 9!9991;
return(Calc*oint';
,
-- Aet Sli&&age #unction
int AetSli&&age(string Currenc$ int Sli&&age*i&s'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == :' double CalcSli&&age = Sli&&age*i&s;
else i(Calc6igits == 8 77 Calc6igits == 2' CalcSli&&age = Sli&&age*i&s . 19;
return(CalcSli&&age';
,
1:1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 180/212
EXPERT ADVISOR PROGRAMMING
Appendix C
Expert Advisor wit+ ,un$tions
This is the e4pert &d%isor using the )un'tions introdu'ed in 'h&pter # *e5%e &dded the /'lose &ll
orders/ )un'tions &nd tr&iling stop )un'tion )ro( 'h&pter = &nd the /e4e'ute on'e per b&r/ )e&tures
)ro( 'h&pter :#
The )un'tions &re de)ined in #nclude<xample.mqh the 'ontents o) "hi'h &re listed in !ppendi4 D#
-- *re&rocessor
&ro&ert$ co&$right "?ndre% 3oung"
include DInclude/+am&le!mEhF
-- /+ternal 0ariables
e+tern bool 6$namicLotSi>e = true;
e+tern double /Euit$*ercent = 4;
e+tern double #i+edLotSi>e = 9!1;
e+tern double Sto&Loss = 29;
e+tern double Take*roit = 199;
e+tern int TrailingSto& = 29;
e+tern int Minimum*roit = 29;
e+tern int Sli&&age = 2;e+tern int MagicBumber = 148;
e+tern int #astM?*eriod = 19;
e+tern int Slo%M?*eriod = 49;
e+tern bool Checknce*er<ar = true;
-- Alobal 0ariables
int <u$Ticket;
int SellTicket;
double 5se*oint;int 5seSli&&age;
datetime CurrentTimeStam&;
1:2
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 181/212
Appendix "
-- Init unction
int init('
)
5se*oint = *i&*oint(S$mbol('';
5seSli&&age = AetSli&&age(S$mbol('Sli&&age';
,
-- Start unction
int start('
)
-- /+ecute on bar o&en
i(Checknce*er<ar == true'
)
int <arShit = 1;
i(CurrentTimeStam& R= Time[9]'
)
CurrentTimeStam& = Time[9];
bool Be%<ar = true;
,
else Be%<ar = alse;
,
else
)
Be%<ar = true;
<arShit = 9;
,
-- Mo0ing a0erages
double #astM? = iM?(B5LL9#astM?*eriod999<arShit';
double Slo%M? = iM?(B5LL9Slo%M?*eriod999<arShit';
double Last#astM? = iM?(B5LL9#astM?*eriod999<arShitN1';
double LastSlo%M? = iM?(B5LL9Slo%M?*eriod999<arShitN1';
-- Calculate lot si>e
double LotSi>e = CalcLotSi>e(6$namicLotSi>e/Euit$*ercentSto&Loss#i+edLotSi>e';
LotSi>e = eri$LotSi>e(LotSi>e';
-- <egin trade block
i(Be%<ar == true'
)
-- <u$ order
i(#astM? F Slo%M? QQ Last#astM? D= LastSlo%M? QQ
<u$MarketCount(S$mbol('MagicBumber' == 9'
)
1:?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 182/212
EXPERT ADVISOR PROGRAMMING
-- Close sell orders
i(SellMarketCount(S$mbol('MagicBumber' F 9'
)
Close?llSellrders(S$mbol('MagicBumberSli&&age';
,
-- &en bu$ order
<u$Ticket = &en<u$rder(S$mbol('LotSi>e5seSli&&ageMagicBumber';
-- rder modiication
i(<u$Ticket F 9 QQ (Sto&Loss F 9 77 Take*roit F 9''
)
rderSelect(<u$TicketS/L/CT<3TICP/T';
double &en*rice = rder&en*rice(';
-- Calculate and 0eri$ sto& loss and take &roit
double <u$Sto&Loss = Calc<u$Sto&Loss(S$mbol('Sto&Loss&en*rice';
i(<u$Sto&Loss F 9' <u$Sto&Loss = ?dust<elo%Sto&Le0el(S$mbol('
<u$Sto&Loss2';
double <u$Take*roit = Calc<u$Take*roit(S$mbol('Take*roit
&en*rice';
i(<u$Take*roit F 9' <u$Take*roit = ?dust?bo0eSto&Le0el(S$mbol('
<u$Take*roit2';
-- ?dd sto& loss and take &roit
?ddSto&*roit(<u$Ticket<u$Sto&Loss<u$Take*roit';
,
,
-- Sell rder
i(#astM? D Slo%M? QQ Last#astM? F= LastSlo%M?
QQ SellMarketCount(S$mbol('MagicBumber' == 9'
)
i(<u$MarketCount(S$mbol('MagicBumber' F 9'
)
Close?ll<u$rders(S$mbol('MagicBumberSli&&age';
,
SellTicket = &enSellrder(S$mbol('LotSi>e5seSli&&ageMagicBumber';
i(SellTicket F 9 QQ (Sto&Loss F 9 77 Take*roit F 9''
)
rderSelect(SellTicketS/L/CT<3TICP/T';
&en*rice = rder&en*rice(';
double SellSto&Loss = CalcSellSto&Loss(S$mbol('Sto&Loss&en*rice';
i(SellSto&Loss F 9' SellSto&Loss = ?dust?bo0eSto&Le0el(S$mbol('
SellSto&Loss2';
double SellTake*roit = CalcSellTake*roit(S$mbol('Take*roit
&en*rice';
1:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 183/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 184/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 185/212
Appendix "
-- Calculate lot si>e
double LotSi>e = CalcLotSi>e(6$namicLotSi>e/Euit$*ercentSto&Loss#i+edLotSi>e';
LotSi>e = eri$LotSi>e(LotSi>e';
-- <egin trade block
i(Be%<ar == true'
)
-- <u$ order
i(#astM? F Slo%M? QQ <u$Ticket == 9 QQ <u$MarketCount(S$mbol('MagicBumber'
== 9 QQ <u$Sto&Count(S$mbol('MagicBumber' == 9'
)
-- Close sell order
i(SellMarketCount(S$mbol('MagicBumber' F 9'
)
Close?llSellrders(S$mbol('MagicBumberSli&&age';
,
-- 6elete sell sto& order
i(SellSto&Count(S$mbol('MagicBumber' F 9'
)
Close?llSellSto&rders(S$mbol('MagicBumber';
,
SellTicket = 9;
double *ending*rice = High[<arShit] N (*ending*i&s . 5se*oint';
*ending*rice = ?dust?bo0eSto&Le0el(S$mbol('*ending*rice2';
double <u$Sto&Loss = Calc<u$Sto&Loss(S$mbol('Sto&Loss*ending*rice';
i(<u$Sto&Loss F 9' <u$Sto&Loss = ?dust<elo%Sto&Le0el(S$mbol('<u$Sto&Loss
2*ending*rice';
double <u$Take*roit = Calc<u$Take*roit(S$mbol('Take*roit*ending*rice';
i(<u$Take*roit F 9' <u$Take*roit = ?dust?bo0eSto&Le0el(S$mbol('
<u$Take*roit2*ending*rice';
<u$Ticket = &en<u$Sto&rder(S$mbol('LotSi>e*ending*rice<u$Sto&Loss
<u$Take*roit5seSli&&ageMagicBumber';
,
-- Sell rder
i(#astM? D Slo%M? QQ SellTicket == 9
QQ SellMarketCount(S$mbol('MagicBumber' == 9
QQ SellSto&Count(S$mbol('MagicBumber' == 9'
)
i(<u$MarketCount(S$mbol('MagicBumber' F 9'
)
Close?ll<u$rders(S$mbol('MagicBumberSli&&age';
,
1::
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 186/212
EXPERT ADVISOR PROGRAMMING
i(<u$Sto&Count(S$mbol('MagicBumber' F 9'
)
Close?ll<u$Sto&rders(S$mbol('MagicBumber';
,
<u$Ticket = 9;
*ending*rice = Lo%[<arShit] (*ending*i&s . 5se*oint';*ending*rice = ?dust<elo%Sto&Le0el(S$mbol('*ending*rice2';
double SellSto&Loss = CalcSellSto&Loss(S$mbol('Sto&Loss*ending*rice';
i(SellSto&Loss F 9' SellSto&Loss = ?dust?bo0eSto&Le0el(S$mbol('
SellSto&Loss2*ending*rice';
double SellTake*roit = CalcSellTake*roit(S$mbol('Take*roit
*ending*rice';
i(SellTake*roit F 9' ?dust<elo%Sto&Le0el(S$mbol('
SellTake*roit2*ending*rice';
SellTicket = &enSellSto&rder(S$mbol('LotSi>e*ending*riceSellSto&Loss
SellTake*roit5seSli&&ageMagicBumber';
,
, -- /nd trade block
-- ?dust trailing sto&s
i(<u$MarketCount(S$mbol('MagicBumber' F 9 QQ TrailingSto& F 9'
)
<u$TrailingSto&(S$mbol('TrailingSto&Minimum*roitMagicBumber';
,
i(SellMarketCount(S$mbol('MagicBumber' F 9 QQ TrailingSto& F 9'
)
SellTrailingSto&(S$mbol('TrailingSto&Minimum*roitMagicBumber';
,
return(9';
,
1:;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 187/212
Appendix "
1:9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 188/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 189/212
Appendix D
int &en<u$rder(string argS$mbol double argLotSi>e double argSli&&age
double argMagicBumber string argComment = "<u$ rder"'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
-- *lace <u$ rder
int Ticket = rderSend(argS$mbol*<53argLotSi>eMarketIno(argS$mbolM6/?SP'
argSli&&age99argCommentargMagicBumber9Areen';
-- /rror Handling
i(Ticket == 1'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("&en <u$ rder /rror "/rrorCode"J "
/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "MarketIno(argS$mbolM6/<I6'
" ?skJ "MarketIno(argS$mbolM6/?SP'" LotsJ "argLotSi>e';
*rint(/rrLog';
,
return(Ticket';
,
int &enSellrder(string argS$mbol double argLotSi>e double argSli&&age
double argMagicBumber string argComment = "Sell rder"'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
-- *lace Sell rder
int Ticket = rderSend(argS$mbol*S/LLargLotSi>eMarketIno(argS$mbolM6/<I6'
argSli&&age99argCommentargMagicBumber9Ked';
-- /rror Handling
i(Ticket == 1'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("&en Sell rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "MarketIno(argS$mbolM6/<I6'
" ?skJ "MarketIno(argS$mbolM6/?SP'" LotsJ "argLotSi>e';
*rint(/rrLog';
,
return(Ticket';
,
1;1
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 190/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 191/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 192/212
EXPERT ADVISOR PROGRAMMING
string /rr?lert = StringConcatenate("&en Sell Sto& rder /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("?skJ "MarketIno(argS$mbolM6/?SP'
" LotsJ "argLotSi>e" *riceJ "arg*ending*rice" Sto&J "argSto&Loss
" *roitJ "argTake*roit" /+&irationJ "TimeToStr(arg/+&iration'';
*rint(/rrLog';,
return(Ticket';
,
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == 8' double Calc*oint = 9!91;
else i(Calc6igits == : 77 Calc6igits == 2' Calc*oint = 9!9991;
return(Calc*oint';
,
int AetSli&&age(string Currenc$ int Sli&&age*i&s'
)
int Calc6igits = MarketIno(Currenc$M6/6IAITS';
i(Calc6igits == 4 77 Calc6igits == :' double CalcSli&&age = Sli&&age*i&s;
else i(Calc6igits == 8 77 Calc6igits == 2' CalcSli&&age = Sli&&age*i&s . 19;
return(CalcSli&&age';
,
bool Close<u$rder(string argS$mbol int argCloseTicket double argSli&&age'
)
rderSelect(argCloseTicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9'
)
double CloseLots = rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
double Close*rice = MarketIno(argS$mbolM6/<I6';
bool Closed = rderClose(argCloseTicketCloseLotsClose*riceargSli&&ageAreen';
i(Closed == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close <u$ rder /rrorJ "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
1;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 193/212
Appendix D
string /rrLog = StringConcatenate("TicketJ "argCloseTicket" <idJ "
MarketIno(argS$mbolM6/<I6'';
*rint(/rrLog';
,
,
return(Closed';
,
bool CloseSellrder(string argS$mbol int argCloseTicket double argSli&&age'
)
rderSelect(argCloseTicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9'
)
double CloseLots = rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
double Close*rice = MarketIno(argS$mbolM6/?SP';
bool Closed = rderClose(argCloseTicketCloseLotsClose*riceargSli&&ageKed';
i(Closed == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close Sell rder /rrorJ "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("TicketJ "argCloseTicket
" ?skJ "MarketIno(argS$mbolM6/?SP'';
*rint(/rrLog';
,
,
return(Closed';
,
bool Close*endingrder(string argS$mbol int argCloseTicket'
)
rderSelect(argCloseTicketS/L/CT<3TICP/T';
i(rderCloseTime(' == 9'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
bool 6eleted = rder6elete(argCloseTicketKed';
i(6eleted == alse'
)
int /rrorCode = AetLast/rror(';
1;=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 194/212
EXPERT ADVISOR PROGRAMMING
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close *ending rder /rrorJ "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("TicketJ "argCloseTicket" <idJ "
MarketIno(argS$mbolM6/<I6'" ?skJ "MarketIno(argS$mbolM6/?SP'';*rint(/rrLog';
,
,
return(6eleted';
,
double Calc<u$Sto&Loss(string argS$mbol int argSto&Loss double arg&en*rice'
)
i(argSto&Loss == 9' return(9';
double <u$Sto&Loss = arg&en*rice (argSto&Loss . *i&*oint(argS$mbol'';
return(<u$Sto&Loss';
,
double CalcSellSto&Loss(string argS$mbol int argSto&Loss double arg&en*rice'
)
i(argSto&Loss == 9' return(9';
double SellSto&Loss = arg&en*rice N (argSto&Loss . *i&*oint(argS$mbol'';
return(SellSto&Loss';
,
double Calc<u$Take*roit(string argS$mbol int argTake*roit double arg&en*rice'
)
i(argTake*roit == 9' return(9';
double <u$Take*roit = arg&en*rice N (argTake*roit . *i&*oint(argS$mbol'';
return(<u$Take*roit';
,
double CalcSellTake*roit(string argS$mbol int argTake*roit double arg&en*rice'
)
i(argTake*roit == 9' return(9';
double SellTake*roit = arg&en*rice (argTake*roit . *i&*oint(argS$mbol'';
return(SellTake*roit';
,
1;<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 195/212
Appendix D
bool eri$5&&erSto&Le0el(string argS$mbol double argeri$*rice
double arg&en*rice = 9'
)
double Sto&Le0el = MarketIno(argS$mbolM6/ST*L//L' . *oint;
i(arg&en*rice == 9' double &en*rice = MarketIno(argS$mbolM6/?SP';
else &en*rice = arg&en*rice;
double 5&&erSto&Le0el = &en*rice N Sto&Le0el;
i(argeri$*rice F 5&&erSto&Le0el' bool Sto&eri$ = true;
else Sto&eri$ = alse;
return(Sto&eri$';
,
bool eri$Lo%erSto&Le0el(string argS$mbol double argeri$*rice
double arg&en*rice = 9'
)
double Sto&Le0el = MarketIno(argS$mbolM6/ST*L//L' . *oint;
i(arg&en*rice == 9' double &en*rice = MarketIno(argS$mbolM6/<I6';
else &en*rice = arg&en*rice;
double Lo%erSto&Le0el = &en*rice Sto&Le0el;
i(argeri$*rice D Lo%erSto&Le0el' bool Sto&eri$ = true;
else Sto&eri$ = alse;
return(Sto&eri$';
,
double ?dust?bo0eSto&Le0el(string argS$mbol double arg?dust*rice int arg?dd*i&s = 9
double arg&en*rice = 9'
)
double Sto&Le0el = MarketIno(argS$mbolM6/ST*L//L' . *oint;
i(arg&en*rice == 9' double &en*rice = MarketIno(argS$mbolM6/?SP';
else &en*rice = arg&en*rice;
double 5&&erSto&Le0el = &en*rice N Sto&Le0el;
i(arg?dust*rice D= 5&&erSto&Le0el' double ?dusted*rice = 5&&erSto&Le0el N
(arg?dd*i&s . *i&*oint(argS$mbol'';
else ?dusted*rice = arg?dust*rice;
return(?dusted*rice';
,
1;:
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 196/212
EXPERT ADVISOR PROGRAMMING
double ?dust<elo%Sto&Le0el(string argS$mbol double arg?dust*rice int arg?dd*i&s = 9
double arg&en*rice = 9'
)
double Sto&Le0el = MarketIno(argS$mbolM6/ST*L//L' . *oint;
i(arg&en*rice == 9' double &en*rice = MarketIno(argS$mbolM6/<I6';
else &en*rice = arg&en*rice;
double Lo%erSto&Le0el = &en*rice Sto&Le0el;
i(arg?dust*rice F= Lo%erSto&Le0el' double ?dusted*rice = Lo%erSto&Le0el
(arg?dd*i&s . *i&*oint(argS$mbol'';
else ?dusted*rice = arg?dust*rice;
return(?dusted*rice';
,
bool ?ddSto&*roit(int argTicket double argSto&Loss double argTake*roit'
)
rderSelect(argTicketS/L/CT<3TICP/T';
double &en*rice = rder&en*rice(';
%hile(IsTradeConte+t<us$('' Slee&(19';
-- Modi$ rder
bool TicketMod = rderModi$(argTicketrder&en*rice('argSto&LossargTake*roit9';
-- /rror Handling
i(TicketMod == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("?dd Sto&-*roit /rror "/rrorCode
"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "MarketIno(rderS$mbol('M6/<I6'
" ?skJ "MarketIno(rderS$mbol('M6/?SP'" TicketJ "argTicket" Sto&J "
argSto&Loss" *roitJ "argTake*roit';
*rint(/rrLog';
,
return(TicketMod';
,
1;;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 197/212
Appendix D
int TotalrderCount(string argS$mbol int argMagicBumber'
)
int rderCount;
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol'
)rderCountNN;
,
,
return(rderCount';
,
int <u$MarketCount(string argS$mbol int argMagicBumber'
)
int rderCount;
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *<53'
)
rderCountNN;
,
,
return(rderCount';
,
int SellMarketCount(string argS$mbol int argMagicBumber'
)
int rderCount;
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *S/LL'
)
rderCountNN;
,
,
return(rderCount';
,
1;9
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 198/212
EXPERT ADVISOR PROGRAMMING
int <u$Sto&Count(string argS$mbol int argMagicBumber'
)
int rderCount;
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *<53ST*')
rderCountNN;
,
,
return(rderCount';
,
int SellSto&Count(string argS$mbol int argMagicBumber'
)
int rderCount;
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *S/LLST*'
)
rderCountNN;
,
,
return(rderCount';
,
int <u$LimitCount(string argS$mbol int argMagicBumber'
)
int rderCount;
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *<53LIMIT'
)
rderCountNN;
,
,
return(rderCount';
,
190
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 199/212
Appendix D
int SellLimitCount(string argS$mbol int argMagicBumber'
)
int rderCount;
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *S/LLLIMIT')
rderCountNN;
,
,
return(rderCount';
,
0oid Close?ll<u$rders(string argS$mbol int argMagicBumber int argSli&&age'
)
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *<53'
)
-- Close rder
int CloseTicket = rderTicket(';
double CloseLots = rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
double Close*rice = MarketIno(argS$mbolM6/<I6';
bool Closed = rderClose(CloseTicketCloseLotsClose*riceargSli&&ageKed';
-- /rror Handling
i(Closed == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close ?ll <u$ rders /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "
MarketIno(argS$mbolM6/<I6'" TicketJ "CloseTicket" *riceJ "
Close*rice';
*rint(/rrLog';
,
else Counter;
,
,
,
191
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 200/212
EXPERT ADVISOR PROGRAMMING
0oid Close?llSellrders(string argS$mbol int argMagicBumber int argSli&&age'
)
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *S/LL')
-- Close rder
int CloseTicket = rderTicket(';
double CloseLots = rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
double Close*rice = MarketIno(argS$mbolM6/?SP';
bool Closed = rderClose(CloseTicketCloseLotsClose*riceargSli&&ageKed';
-- /rror Handling
i(Closed == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close ?ll Sell rders /rror "
/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("?skJ "
MarketIno(argS$mbolM6/?SP'" TicketJ "CloseTicket" *riceJ "
Close*rice';
*rint(/rrLog';
,
else Counter;
,
,
,
0oid Close?ll<u$Sto&rders(string argS$mbol int argMagicBumber'
)
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *<53ST*'
)
-- 6elete rder
int CloseTicket = rderTicket(';
192
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 201/212
Appendix D
%hile(IsTradeConte+t<us$('' Slee&(19';
bool Closed = rder6elete(CloseTicketKed';
-- /rror Handling
i(Closed == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close ?ll <u$ Sto& rders "
"/rror"/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "
MarketIno(argS$mbolM6/<I6'" ?skJ "
MarketIno(argS$mbolM6/?SP'" TicketJ "CloseTicket';
*rint(/rrLog';
,
else Counter;
,
,
,
0oid Close?llSellSto&rders(string argS$mbol int argMagicBumber'
)
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *S/LLST*'
)
-- 6elete rder
int CloseTicket = rderTicket(';
%hile(IsTradeConte+t<us$('' Slee&(19';
bool Closed = rder6elete(CloseTicketKed';
-- /rror Handling
i(Closed == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close ?ll Sell Sto& rders "
"/rror "/rrorCode"J "/rr6esc';
?lert(/rr?lert';
19?
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 202/212
EXPERT ADVISOR PROGRAMMING
string /rrLog = StringConcatenate("<idJ "
MarketIno(argS$mbolM6/<I6'" ?skJ "
MarketIno(argS$mbolM6/?SP'" TicketJ "CloseTicket';
*rint(/rrLog';
,
else Counter;
,
,,
0oid Close?ll<u$Limitrders(string argS$mbol int argMagicBumber'
)
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *<53LIMIT'
)
-- 6elete rder
int CloseTicket = rderTicket(';
%hile(IsTradeConte+t<us$('' Slee&(19';
bool Closed = rder6elete(CloseTicketKed';
-- /rror Handling
i(Closed == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close ?ll <u$ Limit rders "
"/rror "/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "
MarketIno(argS$mbolM6/<I6'" ?skJ "
MarketIno(argS$mbolM6/?SP'" TicketJ "CloseTicket';
*rint(/rrLog';
,
else Counter;
,
,
,
19
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 203/212
Appendix D
0oid Close?llSellLimitrders(string argS$mbol int argMagicBumber'
)
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *S/LLLIMIT')
-- 6elete rder
int CloseTicket = rderTicket(';
%hile(IsTradeConte+t<us$('' Slee&(19';
bool Closed = rder6elete(CloseTicketKed';
-- /rror Handling
i(Closed == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Close ?ll Sell Limit rders "
"/rror "/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "
MarketIno(argS$mbolM6/<I6'" ?skJ "
MarketIno(argS$mbolM6/?SP'" TicketJ "CloseTicket';
*rint(/rrLog';
,
else Counter;
,
,
,
0oid <u$TrailingSto&(string argS$mbol int argTrailingSto& int argMin*roit
int argMagicBumber'
)
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
-- Calculate Ma+ Sto& and Min *roit
double Ma+Sto&Loss = MarketIno(argS$mbolM6/<I6'
(argTrailingSto& . *i&*oint(argS$mbol'';
Ma+Sto&Loss = Bormali>e6ouble(Ma+Sto&Loss
MarketIno(rderS$mbol('M6/6IAITS'';
double CurrentSto& = Bormali>e6ouble(rderSto&Loss('
MarketIno(rderS$mbol('M6/6IAITS'';
19=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 204/212
EXPERT ADVISOR PROGRAMMING
double *i&s*roit = MarketIno(argS$mbolM6/<I6' rder&en*rice(';
double Min*roit = argMin*roit . *i&*oint(argS$mbol';
-- Modi$ Sto&
i(rderMagicBumber(' == argMagicBumber QQ rderS$mbol(' == argS$mbol
QQ rderT$&e(' == *<53 QQ CurrentSto& D Ma+Sto&Loss
QQ *i&s*roit F= Min*roit')
bool Trailed = rderModi$(rderTicket('rder&en*rice('Ma+Sto&Loss
rderTake*roit('9';
-- /rror Handling
i(Trailed == alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("<u$ Trailing Sto& /rror "
"/rrorCode"J "/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ "
MarketIno(argS$mbolM6/<I6'" TicketJ "rderTicket('" Sto&J "
rderSto&Loss('" TrailJ "Ma+Sto&Loss';
*rint(/rrLog';
,
,
,
,
0oid SellTrailingSto&(string argS$mbol int argTrailingSto& int argMin*roit
int argMagicBumber'
)
or(int Counter = 9; Counter D= rdersTotal('1; CounterNN'
)
rderSelect(CounterS/L/CT<3*S';
-- Calculate Ma+ Sto& and Min *roit
double Ma+Sto&Loss = MarketIno(argS$mbolM6/?SP' N
(argTrailingSto& . *i&*oint(argS$mbol'';
Ma+Sto&Loss = Bormali>e6ouble(Ma+Sto&Loss
MarketIno(rderS$mbol('M6/6IAITS'';
double CurrentSto& = Bormali>e6ouble(rderSto&Loss('
MarketIno(rderS$mbol('M6/6IAITS'';
double *i&s*roit = rder&en*rice(' MarketIno(argS$mbolM6/?SP';
double Min*roit = argMin*roit . *i&*oint(argS$mbol';
19<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 205/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 206/212
EXPERT ADVISOR PROGRAMMING
Appendix E
Custom #ndi$ator
Here is the 'ode )or the 'usto( indi'&tor )ro( 'h&pter 9+
&ro&ert$ co&$right "?ndre% 3oung"
&ro&ert$ indicatorchart%indo%
&ro&ert$ indicatorbuers 8
&ro&ert$ indicatorcolor1 6ee&Sk$<lue
&ro&ert$ indicatorcolor4 6ee&Sk$<lue
&ro&ert$ indicatorcolor8 6ee&Sk$<lue
-- /+ternal 0ariables
e+tern int <ands*eriod = 49;
e+tern int <andsShit = 9;
e+tern int <andsMethod = 1;
e+tern int <ands*rice = 9;
e+tern int 6e0iations = 1;
-- <uers
double /M?[];
double 5&&er<and[];
double Lo%er<and[];
-- Init
int init('
)
SetInde+St$le(96K?OLIB/';
SetInde+<uer(9/M?';
SetInde+Label(9"/M?"';
SetInde+St$le(16K?OLIB/';
SetInde+<uer(15&&er<and';
SetInde+Label(1"5&&er<and"';
SetInde+St$le(46K?OLIB/';SetInde+<uer(4Lo%er<and';
SetInde+Label(4"Lo%er<and"';
return(9';
,
19;
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 207/212
Appendix E
-- Start
int start('
)
int countedbars = IndicatorCounted(';
int Calculate<ars = <ars countedbars;
or(int Count = Calculate<ars; Count F= 9; Count')
/M?[Count] = iM?(B5LL9<ands*eriod<andsShit<andsMethod<ands*riceCount';
double Std6e0 = iStd6e0(B5LL9<ands*eriod<andsShit<andsMethod<ands*rice
Count';
5&&er<and[Count] = /M?[Count] N (Std6e0 . 6e0iations';
Lo%er<and[Count] = /M?[Count] (Std6e0 . 6e0iations';
,
return(9';
,
199
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 208/212
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 209/212
#ndex
A
;ccount7roker() ################################### 12=
;ccount<quit0() ############################# =0 1?2
;ccountame() ####################################### 12=
;ccountumber() ################################### 12=
;lert() ################################################### =
!pplied pri'e 'onst&nts ############################ 102
!rr&ys ##################################################### 1?
;sk ########################################################### 20
2
7ars ####################################################### 1=0
7id ########################################################### 20
boolean d&t& type ###################################### 9
8oole&n oper&tors ################################### 10=
8re&, e%en stop ######################################## 90
break oper&tor ######################################## 1?0
8u))ers #################################################### 1<
C
case oper&tor ######################################### 1?0
CloseIJ ################################################### 9color d&t& type ########################################## 9
Comment() ############################################## 122
Co((ents ################################################## ;
Co(pil&tion errors ################################### 1
Co(pound oper&tors ################################### ;
Const&nts ################################################# 10
Custo( indi'&tors ###################################### 9;
0
D&t& types ################################################## 9D&t& "indo" ########################################### 100
D&teti(e 'onst&nts ################################## 112
datetime d&t& type #################################### 9
datetime %&ri&bles ################################## 112
6a0() ##################################################### 11
6a0=fGeek() ########################################## 11
Debugging ############################################## 11default oper&tor #################################### 1?0
De)&ult %&lues ########################################### 12
deinit() ################################################## 1:
D33s ######################################################### :=
double d&t& type ######################################## 9
E
ECN7STP ############################################# 20 2
else oper&tor ######################################### 10
<8%@>9;,U< ########################################## 102Error 'odes ############################################# 1?
Error h&ndling ########################################### =?
<rror6escription() ############################### =
Es'&pe 'h&r&'ters #################################### 122
E4pert !d%isor *i&rd ################################ 1
E4pir&tion ################################################# 21
extern %&ri&bles ####################################### 1<
,
6I6O ######################################################### ;=6ile )or(&ts #################################################
6ile lo'&tions ############################################### =
for oper&tor ############################################# ;0
6un'tion &rgu(ents ################################### 12
6un'tions ################################################## 10
9
Bet,ast<rror() ####################################### =
Glob&l %&ri&bles ####################################### 1?<
Glob&lly s'oped %&ri&ble ####################### 1? 1:Blobal9ariable6el() ############################ 1?:
Blobal9ariable6elete;ll() ################# 1?:
Blobal9ariableBet() ############################ 1?:
Blobal9ariable+et() ############################ 1?<
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 210/212
?
?i!hIJ ##################################################### 9
?our() ################################################### 11
#
iClose() ################################################## 9
iCustom() ################################################ 9;
Identi)iers ################################################### ;
if oper&tor ############################################# 10?
i?i!h() ################################################### 9
i?i!hest() ############################################### ?2
i,ow() ##################################################### 9
i,owest() ################################################ ?1
i8;() ####################################################### 9<
In'lude )iles ############################################## :
indicator>buffers ############################### 1:
indicator>chart>window ###################### 1:
indicator>color ################################### 1:
indicator>separate>window ################# 1:
#ndicatorCounted() ############################## 1=0
Indi'&tors ################################################# 9=
#ndicator+hortame() ########################## 19
init() ##################################################### 1:
int d&t& type ############################################## 9
i=pen() ################################################### 9
#s6emo() ################################################ 12
#s6lls;llowed() ################################### 12?
#s,ibraries;llowed() ########################## 12?
i+td6ev() ############################################## 1=1
i+tochastic() ######################################### 9;
#s%rade;llowed() ################################# 12?
#s%radeContext7us0() ############################ =2
L
3ibr&ries #################################################### :
3i(it order ################################################ 21
3o'&l %&ri&ble ############################################ 1?
3ogs ####################################################### 11
3ot sie ##################################################### 9
3ot step %&lue ########################################### =2
,owIJ ####################################################### 9
M
&gi' nu(ber ########################################### 2?
&r,et order ############################################# 20
8arket#nfo() ########################################## 29&rting&le ############################################### 1?;
8athow() ############################################## 11
&4i(u( lot sie ####################################### =1
8essa!e7ox() ######################################## 12=
et&Editor ################################################## <
ini(u( lot sie ####################################### =1
8inute() ################################################ 11
8ode p&r&(eter ######################################### 9;
8onth() ################################################# 11
o%ing &%er&ge (ethods ######################### 10?
N&%ig&tor "indo" ####################################### <
Ne"line 'h&r&'ter #################################### 122
ormalie6ouble() ################################# =2
U,, ######################################################### ?1
&
=penIJ ##################################################### 9
Order type 'onst&nts ################################# 22=rderClose() ########################################## ?
=rderCloserice() ########################## ?? 1?;
=rderClose%ime() ############################# ?? ?=
=rderComment() ############################### ?? 1?1
=rder6elete() ######################################### ?=
=rder,ots() ############################################ ??
=rder8a!icumber() ############################### ??
=rder8odif0() ######################################### 2
=rder=penrice() ############################ ?? 1?;
=rder=pen%ime() ##################################### ??=rderrofit() ################################# ? 1?:
=rder+elect() ######################################### ?2
=rder+end() ############################################ 22
=rders?istor0%otal() ########################## 1?9
=rder+top,oss() ##################################### ??
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 211/212
=rders%otal() ######################################### ;2
=rder+0mbol() ######################################### ??
=rder%akerofit() ################################# ??
=rder%icket() ######################################### ??
=rder%0pe() ############################################ ??
Os'ill&tors ################################################# 9:
P
Pending orders ########################################## 21
oint ####################################################### 2<
Prepro'essor ############################################# 1=
Pri'e series &rr&ys ##################################### 9
rint() ################################################### =
R
5efresh5ates() ####################################### =?Rel&tion oper&tors ################################### 10
return oper&tor ######################################## 11
S
S'ripts #################################################### 1=2
Se(i'olon &s e4pression ter(in&tor ############## :
+end8ail() ############################################ 12:
+et;rrow() ############################################ 1;
+et#ndex7uffer() ########################## 101 1;
+et#ndex,abel() ################################### 1;+et#ndex+t0le() ############################ 101 1;
+et,evel+t0le() ################################### 19
+et,evel9alue() ################################### 19
+hift p&r&(eter ####################################### 9<
show>confirm ######################################## 1=2
show>inputs ########################################## 1=2
+leep() ################################################### =?
Slipp&ge ############################################## 20 2;
Spre&d ############################################## 20 1?2
start() ################################################### 1:static %&ri&ble ######################################### 1?
stdlib.mqh in'lude )ile ####################### 1= =
Stop le%els ################################################ <
Stop loss ################################################### ?0
Stop orders ############################################### 21
Stop out le%el ########################################## 1?2
strin! d&t& type ######################################## 9
+trin!Concatenate() ############################## ==
+tr%o%ime() ########################################## 11?
switch oper&tor ###################################### 1?0
+0mbol() ################################################## 2?
T
T&,e pro)it ################################################ ?0
Te(pl&tes ###################################################
Ti', %&lue ################################################# =0
Ti(e )r&(e 'onst&nts ############################## 102
%imeIJ ################################################### 119
%imeCurrent() ####################################### 11
%ime6a0() ############################################## 11=
%ime6a0=fGeek() ################################### 11=%ime?our() ############################################ 11=
%ime,ocal() ########################################## 11
%ime8inute() ######################################## 11=
%ime8onth() ########################################## 11=
%ime%o+tr() ########################################## 11?
%ime@ear() ############################################ 11=
Toolbo4 "indo" ########################################## <
Tr&iling stops ############################################# ;:
7
&ri&ble &ssign(ent ################################### 10
&ri&ble s'ope ########################################### 1?
&ri&bles ##################################################### 9
void d&t& type #################################### 11 ;=
)
while oper&tor ######################################### ;1
@ear() ################################################### 11
F
Adefine dire'ti%e ###################################### 1=
Aimport dire'ti%e ###################################### 1<
Ainclude dire'ti%e #################################### 1=
8/18/2019 Expert Advisor Programming
http://slidepdf.com/reader/full/expert-advisor-programming 212/212
Apropert0 cop0ri!ht ############################## 1=
Apropert0 dire'ti%es ################################# 1=
Apropert0 librar0 ################################# :=
Apropert0 link ####################################### 1=