You are on page 1of 212

Expert Advisor

Programming
Creating Automated Trading Systems
in MQL for MetaTrader 4
Andrew R. oung
Edgehill Publishing
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#
/0et&Tr&der 1/ /023/ &nd /e4pert &d%isor/ &re tr&de(&r,s o) 0et&2uotes So)t"&re Corp#
This boo, &nd it5s publisher is not in &ny "&y endorsed by or &))ili&ted "ith 0et&2uotes 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<1=9-0-1
Ta!"e of Contents
#ntrodu$tion %
!bout This 8oo, 2
! Note !bout 023 = 2
Con%entions >sed In This 8oo, ?
An #ntrodu$tion to MQL 4
Introdu'tion to 0et&Editor 1
8&si' Con'epts :
3&yout o) &n 021 6ile 11
&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 ?1
! Si(ple E4pert !d%isor ?<
Advan$ed &rder P"a$ement 4'
Order 0odi)i'&tion 12
Ceri)ying Stops &nd Pending Order Pri'es 1=
C&l'ul&ting 3ot SiDe 19
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 :1
>sing 3ibr&ries :1
! Si(ple E4pert !d%isor A"ith 6un'tionsB :=
&rder Management .(
The Order 3oop ;0
Order Counting ;2
Tr&iling Stops ;:
>pd&ting the E4pert !d%isor 92
&rder Conditions and #ndi$ators /4
Pri'e D&t& 91
Indi'&tors 9=
Indi'&tor Const&nts 102
E%&lu&ting Tr&de Conditions 10?
Co(p&ring Indi'&tor C&lues !'ross 8&rs 10;
)or*ing wit+ Time and 0ate %%'
D&teti(e C&ri&bles 112
D&te &nd Ti(e 6un'tions 111
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 121
0ess&ge8o4AB 12=
E(&il !lerts 12:
Retry on Error 12;
>sing Order Co((ents !s &n Identi)ier 1?1
0&rgin Che', 1?2
Spre&d Che', 1?2
0ultiple Orders 1??
Glob&l C&ri&bles 1?<
Che', Order Pro)it 1?:
0&rting&le 1?;
Debugging $our E4pert !d%isor 111
Custom #ndi$ators and S$ripts %4-
8u))ers 11<
Cre&ting ! Custo( Indi'&tor 11<
S'ripts 1=2
Appendix A %14
Si(ple E4pert !d%isor 1=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 E Pending Orders 1:=
Appendix 0 %.(
In'lude 6ile 1;0
Appendix E %/.
Custo( Indi'&tor 19;
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&nds
o) ordin&ry people h&%e be'o(e &'ti%e tr&ders#
0et&Tr&der 1 A'o((only &bbre%i&ted &s 0T1B h&s be'o(e one o) the (ost popul&r tr&ding pl&t)or(s
)or )ore4# De%eloped by 0et&2uotes So)t"&re Corpor&tion 0et&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 6FC0 !lp&ri &nd Interb&n, 6F#
0et&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 0et&Tr&der5s su''ess is the po"er)ul
023 progr&((ing l&ngu&ge#
023 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 G1000# ! "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) 023 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 023 is & pro'ess o) tri&l &nd error#
023 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" 023 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 0et&Tr&der itsel) h&s (&ny idiosyn'r&sies th&t the progr&((er needs to be
&"&re o)# It '&n t&,e doDens 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 "ill
present (&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
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 023 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
0et&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 023 re)eren'e &t http://docs.mql4.com does &n e4'ellent Iob &t th&t# The 023 re)eren'e is
&lso built into the 0et&Editor IDE th&t 'o(es "ith 0et&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 023 l&ngu&ge# There &re (&ny
spe'i&liDed )un'tions in 023 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 obIe'ts "indo"s &nd (ost string or
'on%ersion )un'tions#
The o))i'i&l 0231 "ebsite &t http://www.mql4.com h&s & )ree boo, on 023 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 023 & '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#
0&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
Introduction
A 4ote A!out MQL 1
!s o) this "riting the ne4t %ersion o) the 0et&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) 023# 0et&2uotes h&s reported th&t 0et&Tr&der =
"ill not be b&',"&rd 'o(p&tible "ith 0et&Tr&der 1 progr&(s# Thus &ny progr&(s "ritten in 023 1
"ill need to be re"ritten or upd&ted )or 023 =#
This boo, de&ls "ith 0et&Tr&der 1 &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)
0et&Tr&der 1 in 200= 6ore4 tr&ding h&s e4ploded in popul&rity# 0et&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 023 1#
I predi't the (igr&tion to 0et&Tr&der = "ill be & gr&du&l one# 8ro,ers "ill 'ontinue to support
0et&Tr&der 1 )or so(e ti(e so the progr&(s you "rite in 023 1 "ill not be'o(e obsolete
i((edi&tely# The 'on'epts in this boo, "ill re(&in the s&(e &lthough so(e o) the )un'tions &nd
synt&4 "ill 'h&nge# The 'h&llenge "ill be to le&rn the ne" 023 = )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) 0et&Tr&der =# 6or
those "ho h&%e pur'h&sed this boo, the upd&ted sour'e 'ode &nd &n 0231 to 023= guide "ill be
&%&il&ble &t our "ebsite http://www.expertadvisorbook.com/#
Conventions 5sed #n T+is 2oo*
023 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 023 Re)eren'e "ill be displ&yed in it&li's# Re)eren'es to ele(ents o) the 0et&Tr&der
1 inter)&'e in'luding "indo"s di&logs buttons or (enu ite(s "ill &lso be displ&yed in it&li's#
?
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 023# 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
0et&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 obIe'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 0et&Tr&der#
,i"e ,ormats
6iles "ith the .mq4 e4tension &re source code )iles# These &re the )iles "e edit in 0et&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 0et&Tr&der# These
)iles '&nnot be opened in 0et&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 0et&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 0et&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 *iD&rd in 0et&Editor#
1
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 0et&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 Iust by
loo,ing &t the sour'e 'ode#
,i"e Lo$ations
!ll 0et&Editor )iles &re stored inside the experts folder# The \experts )older is 'ont&ined in the
0et&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 0T1 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 E Sour'e 'ode &nd e4e'ut&ble )iles )or your indi'&tors &re stored
here#
\experts\include E Sour'e 'ode in'lude )iles "ith the .mqh e4tension &re stored here#
\experts\libraries E 6un'tion libr&ries &nd D33s &re stored here#
\experts\scripts E Sour'e 'ode &nd e4e'ut&ble )iles )or s'ripts &re stored here#
\experts\templates E 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 E !'ti%ity logs )or your e4pert &d%isors &re stored here# These "ill be use)ul
)or debugging your e4pert &d%isors#
\experts\presets E E4pert &d%isor settings th&t &re s&%ed or lo&ded )ro( 0et&Tr&der5s
Properties di&log &re stored here#
\experts\files E !ny )iles used )or input or output (ust be stored here#
=
EXPERT ADVISOR PROGRAMMING
MetaEditor
0et&Editor is &n Integr&ted De%elop(ent En%iron(ent AIDEB )or 023 th&t 'o(es p&',&ged "ith
0et&Tr&der# It in'ludes use)ul re)eren'e se&r'h &nd &uto-'o(plete tools th&t (&,es 'oding in 023 &
lot e&sier#
The Editor "indo" &llo"s you to h&%e (ultiple )iles open &t on'e# $ou '&n (ini(iDe (&4i(iDe &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 0231#'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
023 )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. %.% E The 0et&Editor inter)&'e# Clo',"ise )ro( top le)t+ Editor "indo" N&%ig&tor "indo" &nd Toolbo4 "indo"#
<
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 023 )iles in your \experts )older# The Dictionary t&b )e&tures & built-in 023 re)eren'e "hile the
earc! t&b is & se&r'h )e&ture )or the 023 re)eren'e#
The built-in 023 re)eren'e &nd the 'onte4t-sensiti%e
help "ill s&%e you & lot o) ti(e "hen 'oding# I) you
need 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 0et&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 023# I) your pre%ious
progr&((ing e4perien'e is in & l&ngu&ge su'h &s Cisu&l 8&si' then you (&y need to (&,e & )e"
&dIust(ents#
In 023 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. %.' E 0et&Editor5s !ssist&nt
&uto 'o(plete )e&ture#
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(ber
o) 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 023 l&ngu&ge ele(ent A&lso '&lled & reserved %ordB# Here5s &n e4&(ple o) & %&ri&ble
identi)ier &nd & 'usto( )un'tion identi)ier# The identi)ier is in it&li's+
;
An Introduction to MQL
double StopLoss;
int Order_Count('
Identi)iers in 023 &re case&sensitive# This (e&ns th&t +top,oss &nd stoploss &re di))erent
%&ri&blesL This is &nother '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# C&ri&bles hold d&t& ne'ess&ry )or
our progr&( to )un'tion su'h &s pri'es settings &nd indi'&tor %&lues#
C&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 023+
int E ! 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 E ! )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! E ! te4t string su'h &s -%he quick brown fox .umped over the la/0 do!-#
Strings (ust be surrounded by double .uotes#
boolean E ! true7false %&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 E ! ti(e &nd d&te %&lue su'h &s 1223.24.24 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 E ! 'onst&nt representing & 'olor su'h &s 5ed or 6ark+late7lue# These &re gener&lly
used )or 'h&nging indi'&tor or obIe'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$1ariable = 1;
9
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$1ariable = 2;
$ou '&n &lso &ssign the %&lue o) one %&ri&ble to &nother %&ri&ble+
int 3our1ariable = 4;
M$1ariable = 3our1ariable;
-- M$1ariable 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.24.24 is & d&teti(e 'onst&nt
)or M&nu&ry 1 2009#
023 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>?4 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 0235s st&nd&rd 'onst&nts in the tandard "onstants se'tion o) the
023 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# 023
h&s doDens 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
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 &dIusts )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 A1 &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 NO# *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 siDe stop loss &nd t&,e pro)it#
11
EXPERT ADVISOR PROGRAMMING
int ;&en<u$;rder(double LotSize" double StopLoss" double TakeProfit'
)
int Ticket = ;rderSend(S$mbol('";*=<53"LotSi>e"?sk"Sto&Loss"Take*ro(it';
return(Ticket';
,
This )un'tion h&s three &rgu(ents ,ot+i/e +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
&nother e4&(ple using %&ri&bles# *e5ll &ssu(e th&t the %&ri&bles Use,ot+i/e 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*ro(it';
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 Iust 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 6e(ault1al#unc(int Ticket" double Price" int Number = 9" string Comment = B5LL'
This )un'tion h&s t"o &rgu(ents "ith de)&ult %&lues Cumber &nd Comment "ith de)&ult %&lues o) 2
&nd CU,, respe'ti%ely# I) "e "&nt to use the de)&ult %&lues )or both Cumber &nd Comment "e si(ply
o(it those &rgu(ents "hen '&lling the )un'tion+
6e(ault1al#unc(TicketBum"5se*rice';
Note th&t "e only spe'i)ied the )irst t"o &rgu(ents# Cumber &nd Comment use the de)&ult %&lues o) 2
&nd CU,,# I) "e "&nt to spe'i)y & %&lue )or Cumber but not )or Comment "e si(ply o(it the l&st
&rgu(ent+
12
An Introduction to MQL
6e(ault1al#unc(TicketBum"5se*rice"5seBumber';
!g&in Comment uses the de)&ult %&lue o) CU,,# 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 Cumber "e h&%e to spe'i)y & %&lue
)or Cumber &s "ell+
6e(ault1al#unc(TicketBum"5se*rice"9""Comment String"';
In this e4&(ple "e used 0 &s the %&lue )or Cumber "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 023 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&liDed 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&liDed 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$Static1ar;
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?
EXPERT ADVISOR PROGRAMMING
There is no spe'i&l (ethod )or initi&liDing & 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 4ew Expert Advisor
The Expert Advisor 'i(ard in 0et&Editor is the .ui',est "&y to get st&rted in 're&ting &n e4pert
&d%isor# $ou '&n st&rt the "iD&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 "iD&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# 0&,e sure E4pert !d%isor is 'hosen &nd
press Ne4t#
,ig. %.8 E E4pert !d%isor *iD&rd gener&l properties#
11
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
&dIusting 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 023 )ile using the e4pert &d%isor te(pl&te &s our guide#
Prepro$essor 0ire$tives
The )irst thing to &ppe&r in &ny 023 )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 *iD&rd &nd Apropert0 link "hi'h is the 3in, you entered in the
"iD&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 proIe't "hen
it is 'o(piled# The synt&4 )or the in'lude dire'ti%e is+
Cinclude 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
0et&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=
EXPERT ADVISOR PROGRAMMING
Cde(ine M3C;BST?BT GThis is a constantH
In this e4&(ple "e '&n use the 'onst&nt identi)ier 8@C=C+%;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 &nother )ile su'h &s &nother e4pert
&d%isor & libr&ry )ile A.ex4B or & *indo"s D33 )ile A.dllB# $ou '&n i(port )un'tions dire'tly into &
proIe'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 proIe'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 Iust need to i(port one or t"o )un'tions &nd &n in'lude )ile )or the( doesn5t &lre&dy
e4ists then go &he&d &nd i(port the( dire'tly into your proIe't#
6or det&iled e4&(ples o) the Aimport dire'ti%e see the 023 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+
Cim&ort "librar$!e+:"
double M$Im&orted#unction(';
Cim&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
&dIust&ble p&r&(eters )or our tr&ding syste(# This in'ludes your tr&de settings Astop loss t&,e pro)it
lot siDeB &nd indi'&tor settings# *hen you open the Expert Properties di&log )or &n e4pert &d%isor
you &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 &dIust&ble by the user#
1<
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
023 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:
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;
An Introduction to MQL
-- *re&rocessor 6irecti0es
C&ro&ert$ co&$right "?ndre% 3oung"
C&ro&ert$ link "htt&J--%%%!e+&ertad0isorbook!com"
Cinclude Dstdlib!mEhF
Cde(ine M3C;BST?BT "This is a constant"
-- /+ternal *arameters
e+tern int *arameter1 = 1;
e+tern double *arameter4 = 9!91;
-- Alobal 1ariables
int Alobal1ariable1;
-- 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 E S&(ple e4pert &d%isor l&yout
19
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 0et&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 Iust & )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 0et&Tr&der+ (&r,et stop &nd li(it orders#
0&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 023 "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 0et&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
,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 023 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 E buy or sellP stop (&r,et or li(it#
The 'urren'y p&ir to tr&de E gener&lly the 'h&rt th&t the E! is &tt&'hed to#
The lot siDe# This '&n either be & )i4ed lot siDe 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 &nd
should 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
&lthough 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
EXPERT ADVISOR PROGRAMMING
&rderSend<=
The =rder+end() )un'tion is used to pl&'e orders in 023# The synt&4 is &s )ollo"s+
int ;rderSend(string Symbol" int Type" double Lots" double Price"
int Slippage" double StopLoss" double TakeProfit" string Comment = B5LL"
int MagicNumber = 9" datetime Expiration = 9" color rro! = CLK=B;B/';
Sym!o" E ! 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 E The type o) order to pl&'e+ buy or sellP (&r,et stop or li(it# This is &n integer %&lue
represented by the )ollo"ing 'onst&nts+
=>7U@ E 8uy (&r,et order Ainteger %&lue 0B#
=>+<,, E Sell (&r,et order Ainteger %&lue 1B#
=>7U@+%= E 8uy stop order Ainteger %&lue 2B#
=>+<,,+%= E Sell stop order Ainteger %&lue ?B#
=>7U@,#8#% E 8uy li(it order Ainteger %&lue 1B#
=>+<,,,#8#% E Sell li(it order Ainteger %&lue =B#
Lots E 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 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 E 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 E 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 E 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 E !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
,rder Place#ent
Magi$4um!er E !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 E !n option&l e4pir&tion ti(e )or pending orders# Not &ll bro,ers &''ept tr&de
e4pir&tion ti(es E )or these bro,ers &n error "ill result i) &n e4pir&tion ti(e is spe'i)ied#
Arrow E !n option&l 'olor )or the &rro" th&t "ill be dr&"n on the 'h&rt indi'&ting the
opening 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 Iust pl&'ed# I) no order
"&s pl&'ed due to &n error 'ondition the return %&lue "ill be -4#
*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&lyDe 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+i/e +lippa!e
7u0+top,oss 7u0%akerofit &nd 8a!icCumber h&%e &lre&dy been '&l'ul&ted or &ssigned &nd &re
%&lid#
;rderSend(S$mbol('";*=<53"LotSi>e"?sk"Sli&&age"<u$Sto&Loss"<u$Take*ro(it"
"<u$ ;rder""MagicBumber"9"Areen';
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 023 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 1 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 Dero 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?
EXPERT ADVISOR PROGRAMMING
;rderSend(S$mbol('"=>+<,,"LotSi>e"7id"Sli&&age"SellSto&Loss"SellTake*ro(it"
-+ell =rder-"MagicBumber"9"5ed';
*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>e"endin!rice"Sli&&age"<u$Sto&Loss"
<u$Take*ro(it"-7u0 +top =rder-"MagicBumber"9"Areen';
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*rice"Sli&&age"SellSto&Loss"
SellTake*ro(it"-+ell +top =rder-"MagicBumber"<xpiration"Ked';
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+
21
,rder Place#ent
;rderSend(S$mbol('"=>7U@,#8#%"LotSi>e"*ending*rice"Sli&&age"<u$Sto&Loss"
<u$Take*ro(it"-7u0 ,imit =rder-"MagicBumber"9"Areen';
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*rice"Sli&&age"SellSto&Loss"
SellTake*ro(it"-+ell ,imit =rder-"MagicBumber"/+&iration"Ked';
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 to
spe'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*ro(it = 199;
2=
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 023 th&t returns the s(&llest pri'e unit o) & 'urren'y depending on
the nu(ber o) de'i(&l pl&'es# 6or & 1 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
Dero# 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 L (Sto&Loss . *oint';
-- 1!:@99 (29 . 9!9991' = 1!:229
I) +top,oss is not gre&ter th&n Dero then 7u0+top,oss is initi&liDed "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#1<00 &nd our stop loss is =0 pips then the stop loss pri'e )or the buy order "ill be 1#1<00 -
A0#00=0B R 1#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& Dero to our stop loss setting E i$e$ +top,oss R =00#
Inste&d o) re.uiring the user to &dd &n &ddition&l Dero 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<
,rder Place#ent
reg&rdless o) "hether or not the bro,er uses )r&'tion&l pips# *e5ll '&ll this )un'tion ipoint
be'&use it "ill &l"&ys return the point %&lue th&t is e.u&l to one pip#
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIn(o(Currenc$"M;6/=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';
,
The string &rgu(ent Currenc0 is the sy(bol o) the 'urren'y p&ir th&t "e "&nt to retrie%e the point
)or# The 8arket#nfo() )un'tion "ith the 8=6<>6#B#%+ p&r&(eter returns the nu(ber o) de'i(&l
pl&'es AdigitsB )or th&t p&ir# The if-else st&te(ent &ssigns the &ppropri&te point %&lue to the
Calcoint %&ri&ble depending on the nu(ber o) digits#
Here5s &n e4&(ple o) the us&ge o) this )un'tion# $ou "ill be using the 'urrent 'h&rt p&ir the %&st
(&Iority o) the ti(e so "e "ill p&ss the +0mbol() )un'tion &s the &rgu(ent# This "ill return the
point )or the 'urrent 'h&rt#
double 5se*oint = *i&*oint(S$mbol('';
Here5s & set o) e4&(ples using spe'i)i' p&irs+
double 5se*oint = *i&*oint(/5K5S6';
-- Kesult is 9!9991
double 5se*oint = *i&*oint(5S6M*3';
-- Kesult is 9!91
*e "ill be using this )un'tion to )ind the single pip point %&lue )or the re(&inder o) this boo,# !s
"e5%e de(onstr&ted the oint %&ri&ble "on5t "or, 'orre'tly on )r&'tion&l pip bro,ers "hen
'&l'ul&ting the %&lue o) & single pip# $ou '&n ne%er &ssu(e th&t the E! "ill only be used on & 2 &nd 1
digit bro,er so it is ne'ess&ry to &uto(&ti'&lly deter(ine the point %&lue o) & single pip using
ipoint()#
S"ippage and Point
3et5s digress )or & (inute &nd 're&te & )un'tion to resiDe the slipp&ge p&r&(eter properly# !s
(entioned e&rlier in this 'h&pter on & bro,er "ith )r&'tion&l pip .uotes the slipp&ge p&r&(eter )or
the =rder+end() )un'tion "ill need to be in're&sed by & )&'tor o) 10 to get the 'orre't slipp&ge
%&lue#
2:
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 = MarketIn(o(Currenc$"M;6/=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 1 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 &arameters
e+tern int Sli&&age = 2;
-- ;rder &lacement
;rderSend(S$mbol('";*=<53"LotSi>e"?sk"Bet+lippa!e(+0mbol()D+lippa!e)"<u$Sto&Loss"
<u$Take*ro(it""<u$ ;rder""MagicBumber"9"Areen';
The slipp&ge in this e4&(ple "ill be = pips &nd the slipp&ge p&r&(eter "ill be &uto(&ti'&lly &dIusted
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;
,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 MarketIn(o(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
023 Re)eren'e under tandard "onstants - Mar*etInfo#
8=6<>=#C% E The point %&lue# 6or e4&(ple 0#01 or 0#00001#
8=6<>6#B#%+ E The nu(ber o) de'i(&l pl&'es in the pri'e# *ill be 2 or ? )or $en p&irs &nd 1
or = )or &ll other p&irs#
8=6<>+5<;6 E The 'urrent spre&d# 6or e4&(ple ? pips Aor ?0 )or & )r&'tion&l pip bro,erB#
8=6<>+%=,<9<, E 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 &nother '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 E The 'urrent bid pri'e o) the sele'ted sy(bol#
8=6<>;+F E The 'urrent &s, pri'e o) the sele'ted sy(bol#
8=6<>,=G E The lo" o) the 'urrent b&r o) the sele'ted sy(bol#
8=6<>?#B? E The high o) the 'urrent b&r o) the sele'ted sy(bol#
29
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 L (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*ro(it F 9' double <u$Take*ro(it = ;&en*rice N (Take*ro(it . Useoint';
i((Take*ro(it F 9' double SellTake*ro(it = ;&en*rice (Take*ro(it . 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
,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 ,owI4J 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] L (4 . Useoint';
So i) the lo" o) the b&r is 1#1:<0 the stop loss "ill be pl&'ed &t 1#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 0et&Tr&der Iust )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%estShi(t = iLo%est(B5LL"9"M;6/=L;O"Count<ars"9';
double <u$Sto&Loss = Lo%[Lo%estShi(t];
The )irst p&r&(eter o) i,owest() is the 'urren'y sy(bol E CU,, (e&ns th&t "e5re using the 'urrent
sy(bol# 0&ny )un'tions in 023 use the string 'onst&nt CU,, to re)er to the 'urrent 'h&rt sy(bol# The
se'ond p&r&(eter is the 'h&rt period E 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 023 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
E 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
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#<;91 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 = M;6/=TK?6/S'
#ndex E 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 E ! 'onst&nt indi'&ting "hether the #ndex p&r&(eter is & ti',et nu(ber or &n order
pool position+
+<,<C%>7@>%#CF<% E The %&lue o) the #ndex p&r&(eter is &n order ti',et nu(ber#
+<,<C%>7@>=+ E The %&lue o) the #ndex p&r&(eter is &n order pool position#
?2
,rder Place#ent
Poo" E !n option&l 'onst&nt indi'&ting the order pool+ pending7open orders or 'losed orders#
8=6<>%5;6<+ E 8y de)&ult "e &re e4&(ining the pool o) 'urrently opened orders#
8=6<>?#+%=5@ E 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 true
other"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(Ticket"S/L/CT=<3=TICP/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 023 Re)eren'e under Trading Functions# Here5s & list o) the (ost
'o((only used order in)or(&tion )un'tions+
=rder+0mbol() L 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 sellP (&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() E The opening pri'e o) the sele'ted order#
=rder,ots() E The lot siDe o) the sele'ted order#
=rder+top,oss() E The stop loss pri'e o) the sele'ted order#
=rder%akerofit() E The t&,e pro)it pri'e o) the sele'ted order#
=rder%icket() E 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!icCumber() E 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() E The 'o((ent th&t "&s pl&'ed "ith the order# This '&n be used &s &
se'ond&ry order identi)ier#
=rderCloserice() E 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() E The opening ti(e o) the sele'ted order#
=rderClose%ime() E The 'losing ti(e o) the sele'ted order#
??
EXPERT ADVISOR PROGRAMMING
=rderrofit() E 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 E The ti',et nu(ber o) the (&r,et order to 'lose#
Lots E The nu(ber o) lots to 'lose# 0ost bro,ers &llo" p&rti&l 'loses#
Pri$e 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 E The &llo"ed slipp&ge )ro( the 'losing pri'e in pips#
Co"or E ! '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 siDe# 6or e4&(ple i) you h&%e & tr&de open
"ith & lot siDe 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(CloseTicket"S/L/CT=<3=TICP/T';
?1
,rder Place#ent
i((;rderCloseTime(' == 9 QQ ;rderT$&e(' == ;*=<53'
)
double CloseLots = ;rderLots(';
double Close*rice = <id;
bool Closed = ;rderClose(CloseTicket"CloseLots"Close*rice"5seSli&&age"Ked';
,
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 siDe 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(CloseTicket"CloseLots"Close*rice"5seSli&&age"Ked';
,
&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 siDe or slipp&ge is re.uired# Here is the 'ode
to 'lose & pending buy stop order+
?=
EXPERT ADVISOR PROGRAMMING
;rderSelect(CloseTicket"S/L/CT=<3=TICP/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 &ltern&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#
C&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*ro(it = 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;
?<
,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?(B5LL"9"#astM?*eriod"9"9"9"9';
double Slo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"9';
-- <u$ order
i((#astM? F Slo%M? QQ <u$Ticket == 9'
)
;rderSelect(SellTicket"S/L/CT=<3=TICP/T';
-- Close order
i((;rderCloseTime(' == 9 QQ SellTicket F 9'
)
double CloseLots = ;rderLots(';
double Close*rice = ?sk;
bool Closed = ;rderClose(SellTicket"CloseLots"Close*rice"5seSli&&age"Ked';
,
double ;&en*rice = ?sk;
-- Calculate sto& loss and take &ro(it
i((Sto&Loss F 9' double <u$Sto&Loss = ;&en*rice (Sto&Loss . 5se*oint';
i((Take*ro(it F 9' double <u$Take*ro(it = ;&en*rice N (Take*ro(it . 5se*oint';
-- ;&en bu$ order
<u$Ticket = ;rderSend(S$mbol('";*=<53"LotSi>e";&en*rice"5seSli&&age"
<u$Sto&Loss"<u$Take*ro(it""<u$ ;rder""MagicBumber"9"Areen';
SellTicket = 9;
,
-- Sell ;rder
i((#astM? D Slo%M? QQ SellTicket == 9'
)
;rderSelect(<u$Ticket"S/L/CT=<3=TICP/T';
?:
EXPERT ADVISOR PROGRAMMING
i((;rderCloseTime(' == 9 QQ <u$Ticket F 9'
)
CloseLots = ;rderLots(';
Close*rice = <id;
Closed = ;rderClose(<u$Ticket"CloseLots"Close*rice"5seSli&&age"Ked';
,
;&en*rice = <id;
i((Sto&Loss F 9' double SellSto&Loss = ;&en*rice N (Sto&Loss . 5se*oint';
i((Take*ro(it F 9' double SellTake*ro(it = ;&en*rice (Take*ro(it . 5se*oint';
SellTicket = ;rderSend(S$mbol('";*=S/LL"LotSi>e";&en*rice"5seSli&&age"
SellSto&Loss"SellTake*ro(it""Sell ;rder""MagicBumber"9"Ked';
<u$Ticket = 9;
,
return(9';
,
-- *i& *oint #unction
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIn(o(Currenc$"M;6/=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 = MarketIn(o(Currenc$"M;6/=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 E 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 E "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
?;
,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 our
20 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 siDe 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 E 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) &nother 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
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 &dIust 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(SellTicket"S/L/CT=<3=TICP/T';
-- Close ;rder
i((;rderCloseTime(' == 9 QQ SellTicket F 9 NN =rder%0pe() LL =>+<,,'
)
double CloseLots = ;rderLots(';
double Close*rice = ?sk;
bool Closed = ;rderClose(SellTicket"CloseLots"Close*rice"5seSli&&age"Ked';
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*ro(it F 9' double <u$Take*ro(it = endin!rice N (Take*ro(it . 5se*oint';
7u0%icket = ;rderSend(S$mbol('"=>7U@+%="LotSi>e"endin!rice"5seSli&&age"
<u$Sto&Loss"<u$Take*ro(it""<u$ Sto& ;rder""MagicBumber"9"Areen';
10
,rder Place#ent
SellTicket = 9;
The 'ode belo" sho"s the 'h&nges )or the sell stop order blo',+
;rderSelect(7u0%icket"S/L/CT=<3=TICP/T';
-- Close ;rder
i((;rderCloseTime(' == 9 QQ <u$Ticket F 9 QQ ;rderT$&e(' == =>7U@'
)
CloseLots = ;rderLots(';
Close*rice = 7id;
Closed = ;rderClose(7u0%icket"CloseLots"Close*rice"5seSli&&age"Ked';
i((Closed == true' 7u0%icket = 9;
,
-- 6elete ;rder
else i((;rderCloseTime(' == 9 QQ <u$Ticket F 9 QQ ;rderT$&e(' == =>7U@+%='
)
Closed = ;rder6elete(7u0%icket"Ked';
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*ro(it . 5se*oint';
+ell%icket = ;rderSend(S$mbol('"=>+<,,+%="LotSi>e"*ending*rice"5seSli&&age"
SellSto&Loss"SellTake*ro(it""Sell Sto& ;rder""MagicBumber"9"Ked';
<u$Ticket = 9;
The 'o(plete 'ode )or both o) these e4pert &d%isors is in !ppendi4 !#
11
EXPERT ADVISOR PROGRAMMING
C+apter 8
Advan$ed &rder P"a$ement
EC4 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 0et&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 E )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! = CLK=B;B/'
Ti$*et E The ti',et nu(ber o) the order to (odi)y#
Pri$e E The ne" pending order pri'e#
StopLoss E The ne" stop loss pri'e#
Ta*eProfit E The ne" t&,e pro)it pri'e#
Expiration E The ne" e4pir&tion ti(e )or pending orders#
Arrow E ! 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#
12
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 "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 E 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 Iust 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 -4#
Ne4t "e use the =rder+elect() )un'tion to retrie%e the in)or(&tion )or the order th&t "&s Iust
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('";*=<53"LotSi>e"?sk"5seSli&&age"2"2"
"<u$ ;rder""MagicBumber"9"Areen';
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
1?
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) Dero (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 E i$e$ gre&ter th&n Dero# 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 Iust
pl&'ed# *e 'he', )irst to see i) the +top,oss &nd %akerofit e4tern&l %&ri&bles &re gre&ter th&n
Dero# 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
Dero# 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 Iust 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#
11
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 Cewendin!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(Ticket"S/L/CT=<3=TICP/T';
i((Be%*ending*rice R= ;rder;&en*rice(''
)
bool TicketMod = ;rderModi($(Ticket"Cewendin!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 Cewendin!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 &nother# 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#
1=
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 ?-1 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 Iust & 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 stop
le%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 & 1 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 = MarketIn(o(S$mbol('"M;6/=ST;*L/1/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 & 1 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#
1<
pread
Ask
Bid
Stop Level
Stop Level
,ig. 8.% E Stop le%els
Advanced ,rder Place#ent
This 'ode "ill '&l'ul&te the (ini(u( &llo"ed pri'e )or & buy t&,e pro)it sell stop loss buy stop order
or sell li(it order# *e5ll use the +top,evel %&lue "e '&l'ul&ted &bo%e#
double 5&&erSto&Le0el = ?sk N Sto&Le0el;
I) our ;sk pri'e is 1#1<=0 &nd the +top,evel is 0#000? pips &s '&l'ul&ted &bo%e then the (ini(u(
stop le%el pri'e "ill be 1#1<=?# I) "e &re pl&'ing & buy t&,e pro)it "ith this order then it (ust be
&bo%e this pri'e# *e5ll '&ll this the Upper+top,evel sin'e it is &bo%e the pri'e#
This 'ode "ill '&l'ul&te the (&4i(u( &llo"ed pri'e )or & sell t&,e pro)it buy stop loss sell stop order
or sell li(it order# Note th&t "e &re si(ply using the 7id inste&d o) the ;sk &nd subtr&'ting inste&d
o) &dding#
double Lo%erSto&Le0el = <id Sto&Le0el;
*e5ll '&ll this the ,ower+top,evel sin'e it is belo" the pri'e# 8e)ore pl&'ing &n order use the
Upper+top,evel &nd ,ower+top,evel %&lues &bo%e to %eri)y your stop loss t&,e pro)it &nd pending
order pri'es# Seep in (ind th&t pri'es '&n 'h&nge r&pidly &nd you5ll "&nt your &'tu&l stops pro)its
&nd pending orders to be "ell outside these le%els#
7erifying Stop Loss and Ta*e Profit Pri$es
The (ini(u( t&,e pro)it in pips "ill be e.u&l to the order opening pri'e plus or (inus the stop le%el#
I) the stop le%el is ? pips &nd the order opening pri'e is 1#1=00 the t&,e pro)it pri'e )or & buy order
"ill need to be &bo%e 1#1=0?#
The (ini(u( stop loss in pips )or & (&r,et order ho"e%er "ill in'lude the 'urrent spre&d so the
(ini(u( stop loss "ill be l&rger th&n the (ini(u( t&,e pro)it# 6or e4&(ple i) the stop le%el is ?
pips the spre&d is 2 pips &nd the order opening pri'e is 1#1=00 the stop loss )or & buy (&r,et order
"ill need to be belo" 1#119=#
This doesn5t &pply )or pending orders so "hen %eri)ying & stop loss )or & pending order it5s not
ne'ess&ry to )igure in the spre&d# So i) you5re pl&'ing & pending order &t 1#1=00 &nd the stop le%el is
? pips then the stop loss '&n be pl&'ed &ny"here belo" 1#119:#
Here5s &n e4&(ple "here "e 'he', the stop loss &nd t&,e pro)it )or & buy order to (&,e sure the
pri'es &re %&lid# I) the stop loss or t&,e pro)it pri'e is not %&lid "e "ill &uto(&ti'&lly &dIust it so th&t
it is se%er&l pips outside o) the stop le%el#
1:
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*ro(it D 5&&erSto&Le0el' <u$Take*ro(it = 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'es
do not be'o(e in%&lid due to slipp&ge# $ou '&n &dIust 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 &dIust 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 &dIust the stop loss to be Iust
& )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*ro(it F Lo%erSto&Le0el' SellTake*ro(it = Lo%erSto&Le0el MinSto&;
i((SellSto&Loss D 5&&erSto&Le0el' SellSto&Loss = 5&&erSto&Le0el N MinSto&;
Inste&d o) &uto(&ti'&lly &dIusting &n in%&lid pri'e you 'ould &lso displ&y &n error (ess&ge &nd h&lt
progr&( e4e'ution# This "&y the user "ould be re.uired to re&dIust 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 &dIusting 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$ adSusted"';
,
1;
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 L 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 siDe is one o)
the best ris, (&n&ge(ent tools you h&%e# Spe'i)ying & lot siDe '&n be &s si(ple &s de'l&ring &n
e4tern&l %&ri&ble &nd using & )i4ed lot siDe )or e%ery order# In this se'tion "e5ll e4plore & (ore
sophisti'&ted (ethod th&t '&l'ul&tes the lot siDe 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 siDes th&t &re too l&rge in rel&tion
to your e.uity '&n "ipe out your &''ount Iust &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 siDe 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) G10000 &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';
19
EXPERT ADVISOR PROGRAMMING
;ccount<quit0() is &n 023 )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) G10000 is G200 &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 G10# On & (ini &''ount A10, lotsB the pro)it per pip "ould be G1#
*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 Tick1alue = MarketIn(o(S$mbol('"M;6/=TICP1?L5/';
i((*oint == 9!991 77 *oint == 9!99991' Tick1alue .= 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 1 de'i(&l
pl&'e %&lue#
The ne4t step is to '&l'ul&te our lot siDe# 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# G200 di%ided by our stop loss o) =0 "ill gi%e us G1#
No" &ll "e h&%e to do is di%ide th&t by %ick9alue to get the lot siDe+
double CalcLots = (Kisk?mount - Sto&Loss' - Tick1alue;
Our '&l'ul&ted lot siDe on & st&nd&rd &''ount "ill be 0#1 lots# On & (ini &''ount the '&l'ul&ted lot
siDe "ill be 1 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 siDe "ill %&ry "idely depending
on your stop loss#
! tight stop loss "ill gener&te & l&rger lot siDe "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 siDe "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
Advanced ,rder Place#ent
I) you (ust use & l&rge stop loss or none &t &ll & )i4ed lot siDe "ould prob&bly be (ore bene)i'i&l#
*e need to be &ble to 'hoose bet"een '&l'ul&ting the lot siDe or using & )i4ed lot siDe# 3et5s use &n
e4tern&l boole&n %&ri&ble '&lled 60namic,ot+i/e to turn our lot siDe '&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 Tick1alue = MarketIn(o(S$mbol('"M;6/=TICP1?L5/';
i((6igits == 8 77 6igits == 2' Tick1alue .= 19;
double CalcLots = (Kisk?mount - Sto&Loss' - Tick1alue;
double LotSi>e = CalcLots;
,
else LotSi>e = #i+edLotSi>e;
I) 60namic,ot+i/e is set to true "e "ill '&l'ul&te the lot siDe b&sed on the stop loss &nd &ssign th&t
%&lue to the ,ot+i/e %&ri&ble# I) 60namic,ot+i/e is )&lse "e si(ply &ssign the %&lue o)
"ixed,ot+i/e to ,ot+i/e# The ,ot+i/e %&ri&ble "ill be p&ssed to the =rder+end() )un'tion &s the
lot siDe )or the order#
7erifying Lot Si>e
Must li,e the stop loss t&,e pro)it &nd pending order pri'es the lot siDe should &lso be %eri)ied to
(&,e sure it is &''ept&ble to your bro,er# This (e&ns th&t your lot siDe 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(&liDe your lot siDe to the &ppropri&te de'i(&l pl&'e#
3et5s 'he', the (ini(u( &nd (&4i(u( lot siDe )irst# The 8arket#nfo() )un'tion using the
8=6<>8#C,=% &nd 8=6<>8;$,=% p&r&(eters "ill be used to 'o(p&re the 'urrent lot siDe to the
(ini(u( &nd (&4i(u( lot siDe# I) the lot siDe is not %&lid it "ill &uto(&ti'&lly be resiDed to the
(ini(u( or (&4i(u(#
i((LotSi>e D MarketIn(o(S$mbol('"M;6/=MIBL;T''
)
LotSi>e = MarketIn(o(S$mbol('"M;6/=MIBL;T';
,
=1
EXPERT ADVISOR PROGRAMMING
else i((LotSi>e F MarketIn(o(S$mbol('"M;6/=M?TL;T''
)
LotSi>e = MarketIn(o(S$mbol('"M;6/=M?TL;T';
,
*e si(ply 'o(p&re the %&lue o) ,ot+i/e our '&l'ul&ted or )i4ed lot siDe )ro( &bo%e to the (ini(u(
&nd (&4i(u( lot siDe# I) ,ot+i/e is less th&n the (ini(u( lot siDe or gre&ter th&n the (&4i(u( lot
siDe it "ill be &ssigned the &ppropri&te (ini(u( or (&4i(u( %&lue#
Ne4t "e need to 'o(p&re our lot siDe to the step %&lue# The step %&lue indi'&tes "hether the bro,er
&llo"s (i'ro lots A0#01B or (ini lots A0#1B# I) you &tte(pt to use & (i'ro lot siDe on & bro,er th&t only
&llo"s (ini lots you "ill get &n error &nd the tr&de "ill not be pl&'ed# Here5s the 'ode to 'he', the
step %&lue+
i((MarketIn(o(S$mbol('"M;6/=L;TST/*' == 9!1'
)
LotSi>e = Bormali>e6ouble(LotSi>e"1';
,
else LotSi>e = Bormali>e6ouble(LotSi>e"4';
The Cormali/e6ouble() )un'tion rounds the %&lue o) ,ot+i/e to the nu(ber o) digits spe'i)ied in
the se'ond &rgu(ent# In the )irst line i) the step siDe is 0#1 indi'&ting the the bro,er only uses (ini
lots ,ot+i/e "ill be rounded to one de'i(&l pl&'e# Other"ise ,ot+i/e "ill be rounded to 2 de'i(&l
pl&'es#
I) in the )uture you h&ppen to 'o(e &'ross & bro,er th&t &llo"s lot siDes up to three de'i(&l pl&'es
then you 'ould e&sily (odi)y the &bo%e 'ode to 'he', th&t &s "ell# 8ut &t (o(ent %irtu&lly e%ery
0et&Tr&der bro,er uses either one or t"o de'i(&l pl&'es )or lot siDing#
&t+er Considerations
Trade Context
0et&Tr&der h&s & single tr&de e4e'ution thre&d )or e4pert &d%isors# This (e&ns th&t only one e4pert
&d%isor '&n tr&de &t &ny one ti(e reg&rdless o) ho" (&ny e4pert &d%isors &re running in the
ter(in&l# 8e)ore 'o((en'ing "ith &ny tr&de oper&tions "e (ust 'he', to see "hether the tr&de
e4e'ution thre&d is 'urrently being used#
The )un'tion #s%radeContext7us0() "ill return true i) the tr&de e4e'ution thre&d is o''upied
other"ise )&lse# *e "ill '&ll this )un'tion Iust be)ore '&lling &ny tr&ding )un'tions in'luding
=rder+end() =rderClose() =rder6elete() or =rder8odif0()#
=2
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('";*=<53"LotSi>e"?sk"5seSli&&age"2"2"
"<u$ ;rder""MagicBumber"9"Areen';
*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 11: +
/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#
=?
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 -4 )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 &nd
print 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 &n
Ainclude 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 Iust &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 siDe &nd the order pri'e#
-- *re&rocessor section
Cinclude Dstdlib!mEhF
-- Alobal 0ariable
int /rrorCode;
-- ;rder &lacement
int Ticket = ;rderSend(S$mbol('";*=<53ST;*"LotSi>e"*ending*rice"5seSli&&age"9"9"
"<u$ Sto& ;rder""MagicBumber"9"Areen';
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';
=1
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 023 )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 Ioined Aor /'on'&ten&ted/B together is sep&r&ted by &
'o((&# Try typing the e4&(ples &bo%e into 0et&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 &nother 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#
==
EXPERT ADVISOR PROGRAMMING
,ig. 8.' E !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
siDe reported in the log is 0# In this '&se the proble( is th&t the lot siDe is in%&lid#
1@J:UJ2: *ro(it <uster /5K5S6"H1J ?lertJ ;&en <u$ Sto& ;rder /rror 181J
in0alid trade 0olume
1@J:UJ2: *ro(it <uster /5K5S6"H1J <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&ndling
routines 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 &ro(it 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';
=<
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 siDe %eri)i'&tion to our E!# Here is our )ile st&rting &t
the beginning+
C&ro&ert$ co&$right "?ndre% 3oung"
Ainclude Rstdlib.mqhO
-- /+ternal 0ariables
extern bool 60namic,ot+i/e L trueM
extern double <quit0ercent L 1M
extern double "ixed,ot+i/e L 2.4M
e+tern double Sto&Loss = 29;
e+tern double Take*ro(it = 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 siDing &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?(B5LL"9"#astM?*eriod"9"9"9"9';
double Slo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"9';
=:
EXPERT ADVISOR PROGRAMMING
// ,ot si/e calculation
if(60namic,ot+i/e LL true)
&
double 5isk;mount L ;ccount<quit0() * (<quit0ercent / 422)M
double %ick9alue L 8arket#nfo(+0mbol()D8=6<>%#CF9;,U<)M
if(oint LL 2.224 QQ oint LL 2.22224) %ick9alue *L 42M
double Calc,ots L (5isk;mount / +top,oss) / %ick9alueM
double ,ot+i/e L Calc,otsM
'
else ,ot+i/e L "ixed,ot+i/eM
// ,ot si/e verification
if(,ot+i/e R 8arket#nfo(+0mbol()D8=6<>8#C,=%))
&
,ot+i/e L 8arket#nfo(+0mbol()D8=6<>8#C,=%)M
'
else if(,ot+i/e O 8arket#nfo(+0mbol()D8=6<>8;$,=%))
&
,ot+i/e L 8arket#nfo(+0mbol()D8=6<>8;$,=%)M
'
if(8arket#nfo(+0mbol()D8=6<>,=%+%<) LL 2.4)
&
,ot+i/e L Cormali/e6ouble(,ot+i/eD4)M
'
else ,ot+i/e L Cormali/e6ouble(,ot+i/eD1)M
The lot siDe '&l'ul&tion &nd %eri)i'&tion 'ode )ro( p&ge =1 is &dded to the beginning o) our st&rt
)un'tion# Sin'e our stop loss le%el is ,no"n be)oreh&nd this is & good & pl&'e &s &ny to put it# The
re(&ining 'ode is our (odi)ied buy (&r,et order routine+
-- <u$ ;rder
i((#astM? F Slo%M? QQ <u$Ticket == 9'
)
-- Close ;rder
;rderSelect(SellTicket"S/L/CT=<3=TICP/T';

i((;rderCloseTime(' == 9 QQ SellTicket F 9'
)
double CloseLots = ;rderLots(';

while(#s%radeContext7us0()) +leep(42)M
5efresh5ates()M
double Close*rice = ?sk;
bool Closed = ;rderClose(SellTicket"CloseLots"Close*rice"5seSli&&age"Ked';
=;
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+i/eD
- %icket: -D+ell%icket)M
rint(<rr,o!)M
'
,
-- ;&en bu$ order
while(#s%radeContext7us0()) +leep(42)M
5efresh5ates()M
<u$Ticket = ;rderSend(S$mbol('";*=<53"LotSi>e"?sk"5seSli&&age"9"9"
"<u$ ;rder""MagicBumber"9"Areen';
// <rror handlin!
if(7u0%icket LL -4)
&
<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+i/e)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
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(42)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
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 the
order (odi)i'&tion blo',#
*e sele't the order th&t "&s Iust 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(SellTicket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9 QQ SellTicket F 9 NN =rder%0pe() LL =>+<,,'
)
double CloseLots = ;rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
Ke(reshKates(';
double Close*rice = ?sk;
bool Closed = ;rderClose(SellTicket"CloseLots"Close*rice"5seSli&&age"Ked';
-- /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
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)M
if(%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
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>e"endin!rice"5seSli&&age"
<u$Sto&Loss"<u$Take*ro(it""<u$ Sto& ;rder""MagicBumber"9"Areen';
-- /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"" *ro(itJ ""<u$Take*ro(it';
*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 siDe 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#
<?
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 siDe '&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 Tick1alue = MarketIn(o(S$mbol('"M;6/=TICP1?L5/';
i((*oint == 9!991 77 *oint == 9!99991' Tick1alue .= 19;
double LotSi>e = (Kisk?mount - argSto&Loss' - Tick1alue;
,
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+i/e()# Co(p&re this to the
'ode on p&ge =1# Noti'e th&t 60namic,ot+i/e <quit0ercent +top,oss &nd "ixed,ot+i/e &re
&ll )un'tion &rgu(ents no"# The e4tern&l %&ri&bles "ith these n&(es still e4ist in our progr&( "e
"ill Iust p&ss the( to the )un'tion &s &rgu(ents no"#
<1
'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 siDe '&l'ul&tion 'ode )ro( e&rlier# *e5%e &dded &
return st&te(ent &t the end o) the )un'tion E this "ill return the %&lue o) ,ot+i/e 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 siDe 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$*ercent"Sto&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
siDe &nd the %&lue "ill be s&%ed in the %&ri&ble ,ot+i/e# Note th&t this %&ri&ble is di))erent )ro( the
,ot+i/e %&ri&ble th&t is inside the Calc,ot+i/e() )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 &ltern&te (ethod o) '&l'ul&ting lot siDe# Reg&rdless o) the (ethod o)
deter(ining lot siDe you5ll "&nt to %eri)y it be)ore using p&ssing it to &n order pl&'e(ent )un'tion+
double 1eri($LotSi>e(double argLotSize'
)
i((ar!,ot+i/e D MarketIn(o(S$mbol('"M;6/=MIBL;T''
)
argLotSi>e = MarketIn(o(S$mbol('"M;6/=MIBL;T';
,
else i((argLotSi>e F MarketIn(o(S$mbol('"M;6/=M?TL;T''
)
argLotSi>e = MarketIn(o(S$mbol('"M;6/=M?TL;T';
,

<=
EXPERT ADVISOR PROGRAMMING

i((MarketIn(o(S$mbol('"M;6/=L;TST/*' == 9!1'
)
argLotSi>e = Bormali>e6ouble(argLotSi>e"1';
,
else argLotSi>e = Bormali>e6ouble(argLotSi>e"4';

return(ar!,ot+i/e)M
,

6or this )un'tion "e5ll p&ss the %&ri&ble "ith the lot siDe "e '&l'ul&ted using Calc,ot+i/e() &s the
&rgu(ent# The &rgu(ent %&ri&ble ar!,ot+i/e 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 =1# In &ny '&se "e5ll return the ti',et nu(ber to
the '&lling )un'tion or -4 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 &nother 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 siDe &nd slipp&ge h&%e been '&l'ul&ted &nd %eri)ied prior to '&lling this )un'tion+
<<
'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";*=<53"ar!,ot+i/e"8arket#nfo(ar!+0mbolD8=6<>;+F)"
ar!+lippa!e"9"9"ar!Comment"ar!8a!icCumber"9"Areen';
-- /rror Handling
i((Ticket == 1'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate(";&en <u$ ;rder L /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+i/e';
*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 -4 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#
<:
EXPERT ADVISOR PROGRAMMING
Here5s the 'ode to pl&'e & pending buy stop order+
int ;&en<u$Sto&;rder(string argSymbol" double argLotSize" double argPendingPrice"
double argStopLoss" double argTakeProfit" double argSlippage" double argMagicNumber"
datetime argExpiration = 9" string argComment = "<u$ Sto& ;rder"'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
-- *lace <u$ Sto& ;rder
int Ticket = ;rderSend(argS$mbol";*=<53ST;*"argLotSi>e"ar!endin!rice"
argSli&&age"ar!+top,oss"ar!%akerofit"argComment"argMagicBumber"
ar!<xpiration"Areen';
-- /rror Handling
i((Ticket == 1'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate(";&en <u$ Sto& ;rder /rror ""/rrorCode"
"J ""/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("?skJ ""MarketIn(o(argS$mbol"M;6/=?SP'"
" LotsJ ""argLotSi>e"- rice: -Dar!endin!riceD- +top: -Dar!+top,ossD
- rofit: -Dar!%akerofitD- <xpiration: -D%ime%o+tr(ar!<xpiration)';
*rint(/rrLog';
,
return(Ticket';
,
Note th&t "e5%e spe'i)ied & de)&ult %&lue o) 0 )or ar!<xpiration# I) you &re not using & pending
order e4pir&tion ti(e &nd you "ish to use the de)&ult order 'o((ent you '&n si(ply o(it the
&rgu(ents )or ar!<xpiration &nd ar!Comment "hen '&lling the )un'tion# The )ollo"ing e4&(ple "ill
pl&'e & buy stop order "ith no e4pir&tion ti(e &nd the de)&ult order 'o((ent /8uy Stop Order/+
int Ticket = ;&en<u$Sto&;rder(S$mbol('"LotSi>e"*ending*rice"Sto&Loss"Take*ro(it"
5seSli&&age"MagicBumber';
*e5%e &dded the pending pri'e to the log in our error h&ndling )un'tion &s "ell &s the e4pir&tion
ti(e i) one is spe'i)ied# The %ime%o+tr() )un'tion 'on%erts & d&teti(e %&ri&ble to & re&d&ble string
)or(&t#
The )un'tions to open sell stop buy li(it &nd sell li(it orders &re identi'&l to this one# The only
di))eren'e is th&t the order type p&r&(eter )or the =rder+end() )un'tion is 'h&nged &''ordingly# $ou
'&n %ie" &ll o) the pending order pl&'e(ent )un'tions in !ppendi4 D#
<;
'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 Iust one order this
)un'tion "ill do the tri',+
bool Close<u$;rder(string argSymbol" int argCloseTicket" double argSlippage'
)
;rderSelect(argCloseTicket"S/L/CT=<3=TICP/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%icket"CloseLots"Close*rice"ar!+lippa!e"Ked';
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 ""
MarketIn(o(argS$mbol"M;6/=?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 run
the 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
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*ending;rder(string argSymbol" int argCloseTicket" double argSlippage'
)
;rderSelect(argCloseTicket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9'
)
%hile(IsTradeConte+t<us$('' Slee&(19'M
bool 6eleted = ;rder6elete(argCloseTicket"Ked';
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 ""MarketIn(o(argS$mbol"M;6/=<I6'"
" ?skJ ""MarketIn(o(argS$mbol"M;6/=?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
'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
&nother set o) )un'tions to %eri)y or &dIust 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
&dIust the pri'e#
Here is the )un'tion to '&l'ul&te & buy t&,e pro)it in pips+
double Calc<u$Take*ro(it(string argSymbol" int argTakeProfit" double argOpenPrice'
)
i((argTake*ro(it == 9' return(9';
double <u$Take*ro(it = ;&en*rice N (argTake*ro(it . *i&*oint(argS$mbol'';
return(<u$Take*ro(it';
,
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 &dIust & 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
EXPERT ADVISOR PROGRAMMING
bool 1eri($5&&erSto&Le0el(string argSymbol" double arg%erifyPrice"
double argOpenPrice = 9'
)
double Sto&Le0el = MarketIn(o(argS$mbol"M;6/=ST;*L/1/L' . *oint;

i((arg;&en*rice == 9' double ;&en*rice = MarketIn(o(argS$mbol"M;6/=?SP';
else ;&en*rice = arg;&en*rice;
double 5&&erSto&Le0el = ;&en*rice N Sto&Le0el;
i((arg1eri($*rice F 5&&erSto&Le0el' bool Sto&1eri($ = true;
else Sto&1eri($ = (alse;

return(Sto&1eri($';
,
*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 stop
loss &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 1eri(ied = 1eri($5&&erSto&Le0el(S$mbol('"SellSto&Loss';
i((1eri(ied == (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 &dIust the in%&lid stop loss t&,e pro)it or
pending order pri'e to & %&lid one+
double ?dSust?bo0eSto&Le0el(string argSymbol" double argd&ustPrice" int argddPips = 9"
double argOpenPrice = 9'
)
double Sto&Le0el = MarketIn(o(argS$mbol"M;6/=ST;*L/1/L' . *oint;

i((arg;&en*rice == 9' double ;&en*rice = MarketIn(o(argS$mbol"M;6/=?SP';
else ;&en*rice = arg;&en*rice;

double 5&&erSto&Le0el = ;&en*rice N Sto&Le0el;
:2
'or*ing %it! Functions
i((arg?dSust*rice D= 5&&erSto&Le0el'
)
double ?dSusted*rice = 5&&erSto&Le0el N (arg?dd*i&s . *i&*oint(argS$mbol'';
,
else ?dSusted*rice = arg?dSust*rice;
return(?dSusted*rice';
,
The &rgu(ent ar!;d.ustrice is the pri'e "e "ill %eri)y &nd &dIust 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 &dIusting &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!;d.ustrice p&r&(eter is inside the stop le%el Ai#e# not %&lidB the pri'e "ill be
&dIusted 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!;d.ustrice 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 &dIust
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&*ro(it(int argTicket" double argStopLoss" double argTakeProfit'
)
if(ar!+top,oss LL 2 NN ar!%akerofit LL 2) return(false)M
;rderSelect(ar!%icket"S/L/CT=<3=TICP/T';
double ;&en*rice = ;rder;&en*rice(';
%hile(IsTradeConte+t<us$('' Slee&(19';
-- Modi($ ;rder
bool TicketMod = ;rderModi($(ar!%icket";rder;&en*rice('"ar!+top,oss"ar!%akerofit"9';
:?
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"" *ro(itJ ""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&niDed )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 Iust
&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!#
:1
'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&ry
you '&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 E &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 0231 "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 1ariables
e+tern bool 6$namicLotSi>e = true;
e+tern double /Euit$*ercent = 4;
e+tern double #i+edLotSi>e = 9!1;
:=
EXPERT ADVISOR PROGRAMMING
e+tern double Sto&Loss = 29;
e+tern double Take*ro(it = 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 1ariables
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?(B5LL"9"#astM?*eriod"9"9"9"9';
double Slo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"9';
-- Calculate Lot Si>e
double LotSi>e = CalcLotSi>e(6$namicLotSi>e"/Euit$*ercent"Sto&Loss"#i+edLotSi>e';
LotSi>e = 1eri($LotSi>e(LotSi>e';
-- <u$ ;rder
i((#astM? F Slo%M? QQ <u$Ticket == 9'
)
i((SellTicket F 9' int Closed = CloseSell;rder(S$mbol('"SellTicket"5seSli&&age';
SellTicket = 9;
<u$Ticket = ;&en<u$;rder(S$mbol('"LotSi>e"5seSli&&age"MagicBumber';
i((<u$Ticket F 9 QQ (Sto&Loss F 9 77 Take*ro(it F 9''
)
;rderSelect(<u$Ticket"S/L/CT=<3=TICP/T';
double ;&en*rice = ;rder;&en*rice(';
:<
'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 = ?dSust<elo%Sto&Le0el(S$mbol('"<u$Sto&Loss"2';
,

double <u$Take*ro(it = Calc<u$Take*ro(it(S$mbol('"Take*ro(it";&en*rice';
i((<u$Take*ro(it F 9'
)
<u$Take*ro(it = ?dSust?bo0eSto&Le0el(S$mbol('"<u$Take*ro(it"2';
,
?ddSto&*ro(it(<u$Ticket"<u$Sto&Loss"<u$Take*ro(it';
,
,
-- Sell ;rder
i((#astM? D Slo%M? QQ SellTicket == 9'
)
i((<u$Ticket F 9' Closed = Close<u$;rder(S$mbol('"<u$Ticket"Sli&&age';
<u$Ticket = 9;
SellTicket = ;&enSell;rder(S$mbol('"LotSi>e"5seSli&&age"MagicBumber';
i((SellTicket F 9 QQ (Sto&Loss F 9 77 Take*ro(it F 9''
)
;rderSelect(SellTicket"S/L/CT=<3=TICP/T';
;&en*rice = ;rder;&en*rice(';

double SellSto&Loss = CalcSellSto&Loss(S$mbol('"Sto&Loss";&en*rice';
i((SellSto&Loss F 9'
)
SellSto&Loss = ?dSust?bo0eSto&Le0el(S$mbol('"SellSto&Loss"2';
,

double SellTake*ro(it = CalcSellTake*ro(it(S$mbol('"Take*ro(it";&en*rice';
i((SellTake*ro(it F 9'
)
SellTake*ro(it = ?dSust<elo%Sto&Le0el(S$mbol('"SellTake*ro(it"2';
,
?ddSto&*ro(it(SellTicket"SellSto&Loss"SellTake*ro(it';
,
,
return(9';
,
::
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+i/e() &nd 9erif0,ot+i/e() to to '&l'ul&te
&nd %eri)y our lot siDe#
In our buy &nd sell order blo',s "e use Close7u0=rder() &nd Close+ell=rder() to 'lose the
opposite 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
;d.ust;bove+top,evel() &nd ;d.ust7elow+top,evel() to %eri)y our stop loss &nd t&,e pro)it
pri'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%isors
in & short &(ount o) ti(e#
:;
'or*ing %it! Functions
:9
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 4 initi&liDes 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
,rder Manage#ent
T+e while &perator
The while oper&tor is & si(pler (ethod o) looping in 023# 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 point
during 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 Iust 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(Counter"S/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
EXPERT ADVISOR PROGRAMMING
=rders%otal() is & )un'tion th&t returns the nu(ber o) 'urrently opened orders# *hy &re "e
subtr&'ting 1 )ro( the %&lue o) =rders%otal()T 3et5s e4pl&in ho" the order pool "or,s+
The order pool 'ont&ins &ll orders th&t &re 'urrently open in our ter(in&l in'luding (&nu&lly pl&'ed
orders &s "ell &s orders pl&'ed by e4pert &d%isors# The order inde4es &re nu(bered st&rting )ro(
Dero# I) there is one order open its inde4 is 0# *hen & se'ond order is opened its inde4 is 1# I) &
third order is opened its inde4 "ill be 2 &nd so on# Inde4 0 is the oldest order &nd inde4 2 is the
ne"est#
=rders%otal() "ill return the nu(ber o) 'urrently opened orders# In the &bo%e e4&(ple "e h&%e
three orders open# 8ut be'&use our order inde4 st&rts &t 0 "e "&nt our 'ounter %&ri&ble to only
'ount to 2# The %&lue o) Counter (ust 'orrespond "ith our order inde4 nu(bers so th&t is "hy "e
(ust subtr&'t 1 )ro( =rders%otal()#
*hen &n order in the open order pool is 'losed &ny ne"er orders in the pool "ill h&%e their order
inde4es de're(ented# 6or e4&(ple i) the order "ith inde4 0 is 'losed then the order "ith inde4 1
be'o(es inde4 0 &nd order inde4 2 be'o(es inde4 1# This is i(port&nt "hen "e 'lose orders &nd
"e5ll 'o%er this in (ore det&il soon#
8&', to our order loop+ The =rder+elect() st&te(ent uses our Counter %&ri&ble &s the order
position inde4# !s e4pl&ined &bo%e "e "ill in're(ent our "&y through the order pool )ro( the oldest
order to the ne"est# The +<,<C%>7@>=+ p&r&(eter indi'&tes th&t "e &re sele'ting the order by its
position in the order pool &s opposed to its ti',et nu(ber#
6or the )irst iter&tion o) this loop Counter "ill be e.u&l to 0 &nd "e "ill sele't the oldest order )ro(
the order pool using =rder+elect()# *e '&n then e4&(ine the order in)or(&tion using )un'tions
su'h &s =rder%icket() or =rder+top,oss() &nd (odi)y or 'lose the order &s ne'ess&ry#
&rder Counting
It is o)ten %ery use)ul to )ind out ho" (&ny orders our E! h&s open &nd o) "h&t type# *e "ill 're&te
se%er&l order 'ounting )un'tions to 'ount the 'urrent nu(ber o) open orders b&sed on the order
type# The )ollo"ing )un'tion "ill 'ount the tot&l nu(ber o) open orders+
int Total;rderCount(string argSymbol" int argMagicNumber'
)
int ;rderCount;
(or(Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/L/CT=<3=*;S';
;2
,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&liDed &s 0# $ou5ll re'ogniDe 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!icCumber() (&t'hes the ar!8a!icCumber &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((Total;rderCount(S$mbol('"MagicBumber' F 9 QQ Close;rders == 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#
;?
EXPERT ADVISOR PROGRAMMING
3et5s (odi)y our order 'ounting routine to 'ount only buy (&r,et orders+
int <u$MarketCount(string argSymbol" int argMagicNumber'
)
int ;rderCount;
(or(Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/L/CT=<3=*;S';
i((;rderMagicBumber(' == argMagicBumber QQ ;rderS$mbol(' == argS$mbol
NN =rder%0pe() LL =>7U@'
)
;rderCountNN;
,
,
return(;rderCount';
,
The 'ode is identi'&l to be)ore e4'ept th&t "e5%e &dded the =rder%0pe() )un'tion to 'he', the order
type o) the 'urrently sele'ted order# =>7U@ is the 'onst&nt th&t indi'&tes & buy (&r,et order# To
'ount other types o) orders si(ply repl&'e =>7U@ "ith the &ppropri&te order type 'onst&nt &nd
ren&(e the )un'tion to re)le't the order type#
It is suggested th&t you 're&te &n order 'ounting )un'tion )or e%ery order type# $ou '&n %ie" the
'ode )or &ll o) the order 'ounting )un'tions in !ppendi4 D#
C"osing Mu"tip"e &rders
0ore o)ten th&t not "e5ll need to 'lose (ultiple orders o) the s&(e type# *e5ll 'o(bine our order
loop "ith our order 'losing routines to 'lose (ultiple orders &t on'e# This )un'tion "ill 'lose &ll buy
(&r,et orders pl&'ed by our e4pert &d%isor+
0oid Close?ll<u$;rders(string argSymbol" int argMagicNumber" int argSlippage'
)
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/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 = MarketIn(o(argS$mbol"M;6/=<I6';
;1
,rder Manage#ent
bool Closed = ;rderClose(CloseTicket"CloseLots"Close*rice"argSli&&age"Ked';
-- /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 ""
MarketIn(o(argS$mbol"M;6/=<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'ogniDe 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#
;=
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(Counter"S/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(CloseTicket"Ked';
-- /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 ""
MarketIn(o(argS$mbol"M;6/=<I6'" " ?skJ ""
MarketIn(o(argS$mbol"M;6/=?SP'"" TicketJ ""CloseTicket';
*rint(/rrLog';
,
else Counter;
,
,
,
This 'ode "ill "or, )or &ll types o) pending orders E 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#
;<
,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 E
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(Counter"S/L/CT=<3=*;S';
double Ma+Sto&Loss = MarketIn(o(S$mbol('"M;6/=<I6'
(TrailingSto& . *i&*oint(S$mbol(''';
Ma+Sto&Loss = Bormali>e6ouble(Ma+Sto&Loss"MarketIn(o(;rderS$mbol('"M;6/=6IAITS'';
double CurrentSto& = Bormali>e6ouble(;rderSto&Loss('"
MarketIn(o(;rderS$mbol('"M;6/=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*ro(it('"9';
;:
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 "MarketIn(o(S$mbol('"M;6/=<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 023 )un'tion Cormali/e6ouble() 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 0et&Tr&der '&n be .uoted up to eight de'i(&l
pl&'es# 8y using Cormali/e6ouble() "e round th&t do"n to 1 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
Cormali/e6ouble() Iust 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)'
;;
,rder Manage#ent
Note the 'ondition (Current+top O 8ax+top,oss QQ Current+top LL 2)# I) there is no stop loss
pl&'ed "ith the order then the 'ondition Current+top O 8ax+top,oss "ill ne%er be true be'&use
8ax+top,oss "ill ne%er be less th&n Dero# Thus "e &dd &n OR 'ondition Current+top LL 2#
I) the 'urrent order5s stop loss is 0 Ano stop lossB then &s long &s the re(&ining 'onditions &re true
the tr&iling stop "ill be pl&'ed#
Minimum Profit
3et5s enh&n'e our tr&iling stop by &dding & (ini(u( pro)it le%el# In the &bo%e e4&(ple the tr&iling
stop "ill ,i', in right &"&y# I) you set &n initi&l stop loss o) 100 pips &nd your tr&iling stop is =0 pips
the stop loss "ould be set to =0 pips i((edi&tely in%&lid&ting your initi&l 100 pip stop loss#
!dding & (ini(u( pro)it le%el "ill &llo" you to set &n initi&l stop loss "hile del&ying the tr&iling stop
until & spe'i)ied &(ount o) pro)it is re&'hed# In this e4&(ple let5s &ssu(e &n initi&l stop loss o) 100
pips is set "hen the order is pl&'ed# *e5re using & tr&iling stop o) =0 pips "ith & (ini(u( pro)it
le%el o) =0 pips# *hen the pro)it )or the order re&'hes =0 pips the stop loss "ill be &dIusted to bre&,
e%en#
3et5s &dd &n e4tern&l %&ri&ble )or our (ini(u( pro)it setting+
e+tern int TrailingSto& = 29;
extern int 8inimumrofit L :2M
The )ollo"ing )un'tion (odi)ies the stop loss )or &ll buy (&r,et orders 'he',ing the (ini(u( pro)it
be)ore doing so+
0oid <u$TrailingSto&(string argSymbol" int argTrailingStop" int argMinProfit"
int argMagicNumber'
)
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/L/CT=<3=*;S';
-- Calculate Ma+ Sto& and Min *ro(it
double Ma+Sto&Loss = MarketIn(o(argS$mbol"M;6/=<I6'
(TrailingSto& . *i&*oint(argS$mbol'';
Ma+Sto&Loss = Bormali>e6ouble(Ma+Sto&Loss"
MarketIn(o(;rderS$mbol('"M;6/=6IAITS'';
double CurrentSto& = Bormali>e6ouble(;rderSto&Loss('"
MarketIn(o(;rderS$mbol('"M;6/=6IAITS'';
;9
EXPERT ADVISOR PROGRAMMING
double ipsrofit L 8arket#nfo(ar!+0mbolD8=6<>7#6) - =rder=penrice()M
double 8inrofit L 8inimumrofit * ipoint(ar!+0mbol))M
-- Modi($ Sto&
i((;rderMagicBumber(' == argMagicBumber QQ ;rderS$mbol(' == argS$mbol
QQ ;rderT$&e(' == ;*=<53 QQ CurrentSto& D Ma+Sto&Loss
QQ ipsrofit OL 8inrofit'
)
bool Trailed = ;rderModi($(;rderTicket('";rder;&en*rice('"Ma+Sto&Loss"
;rderTake*ro(it('"9';
-- /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 ""
MarketIn(o(argS$mbol"M;6/=<I6'" " TicketJ ""CloseTicket"
" Sto&J "";rderSto&Loss('"" TrailJ ""Ma+Sto&Loss';
*rint(/rrLog';
,
,
,
,
*e '&l'ul&te the 'urrent order pro)it in pips by subtr&'ting =rder=penrice() )ro( the 'urrent 8id
pri'e &nd storing th&t in the %&ri&ble ipsrofit# *e 'o(p&re th&t to our (ini(u( pro)it setting
"hi'h is (ultiplied by ipoint() &nd stored in the %&ri&ble 8inrofit#
I) the 'urrent pro)it in pips AipsrofitB is gre&ter th&n or e.u&l to our (ini(u( pro)it
A8inrofitB &nd &ll o) the other 'onditions &re true the stop "ill be (odi)ied#
The tr&iling stop "ith the (ini(u( pro)it setting is (u'h (ore )le4ible so you5ll prob&bly "&nt to use
this )un'tion in your e4pert &d%isor# See !ppendi4 D )or the 'o(plete sell tr&iling stop 'ode#
2rea* Even Stop
$ou '&n &lso use this (ethod to &pply & bre&, e%en stop &dIust(ent to your orders# ! bre&, e%en
stop &dIusts the stop loss to be e.u&l to the order opening pri'e &)ter & 'ert&in le%el o) pro)it h&s
been re&'hed# The bre&, e%en stop is independent )ro( your initi&l stop loss &nd tr&iling stop
)un'tions#
90
,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*ro(it = 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(Counter"S/L/CT=<3=*;S';
Ke(reshKates(';
double *i&s*ro(it = <id L ;rder;&en*rice(';
double Min*ro(it = <reak/0en*ro(it . *i&*oint(;rderS$mbol(''';
i((;rderMagicBumber(' == MagicBumber QQ ;rderS$mbol(' == S$mbol('
QQ ;rderT$&e(' == ;*=<53 QQ *i&s*ro(it F= Min*ro(it
QQ ;rder;&en*rice(' R= ;rderSto&Loss(''
)
bool <reak/0en = ;rderModi($(;rderTicket('";rder;&en*rice('"
;rder;&en*rice('";rderTake*ro(it('"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*ro(it';
*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
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!icCumber) LL 2'
)
if(+ell8arketCount(+0mbol()D8a!icCumber) O 2)
&
Close;ll+ell=rders(+0mbol()D8a!icCumberD+lippa!e)M
'
SellTicket = 9;
<u$Ticket = ;&en<u$;rder(S$mbol('"LotSi>e"5seSli&&age"MagicBumber';
,
*e used the )un'tion 7u08arketCount() th&t "e de)ined on p&ge ;1 to return the nu(ber o) buy
orders 'urrently open# *e "ill ,eep the 7u0%icket 'he', in so th&t only &ltern&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 1# 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!icCumber) LL 2'
)
if(7u08arketCount(+0mbol()D8a!icCumber) O 2)
&
Close;ll7u0=rders(+0mbol()D8a!icCumberD+lippa!e)M
'
<u$Ticket = 9;
SellTicket = ;&enSell;rder(S$mbol('"LotSi>e"5seSli&&age"MagicBumber';
,
92
,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*ro(it = 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*ro(it"MagicBumber';
,
i((SellMarketCount(S$mbol('"MagicBumber' F 9 QQ TrailingSto& F 9'
)
SellTrailingSto&(S$mbol('"TrailingSto&"Minimum*ro(it"MagicBumber';
,
$ou '&n %ie" these 'h&nges in 'onte4t in !ppendi4 C#
9?
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 E 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" E The sy(bol o) the 'urren'y p&ir to use#
Period E The period o) the 'h&rt to use in (inutes#
S+ift E The b&',"&rd shi)t rel&ti%e to the 'urrent b&r#
91
,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 1 hour 'h&rt+
double H:Close = iClose(B5LL"*/KI;6=H:"1';
CU,, re)ers to the 'urrent 'h&rt sy(bol# <5#=6>?4 is &n integer 'onst&nt th&t re)ers to the H1 'h&rt
period# 4 is our shi)t "hi'h is the b&r pre%ious to the 'urrent b&r# 3et5s use &nother e4&(ple th&t
returns the 'lose o) the 'urrent b&r on &nother 'h&rt+
double A<*Close = iClose(A<*5S6"9"9';
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 CloseShi(t = iClose(B5LL"9"Count';
*rint(CountN" "NCloseShi(t';
,
#ndi$ators
The (&Iority o) tr&ding syste(s use indi'&tors to deter(ine tr&ding sign&ls# 0et&Tr&der in'ludes o%er
20 'o((on indi'&tors in'luding (o%ing &%er&ge 0!CD RSI &nd sto'h&sti's# 023 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=
EXPERT ADVISOR PROGRAMMING
double iM?(string Symbol" int Timeframe" int MPeriod" int MS'ift" int MMet'od"
int MPrice" int S'ift'
Sym!o" E The sy(bol o) the 'h&rt to &pply the (o%ing &%er&ge to#
Timeframe E The ti(e period o) the 'h&rt to &pply the (o%ing &%er&ge to#
E%ery indi'&tor )un'tion in 023 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 E 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# 0ost 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 E 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 E 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 0! '&l'ul&tion
(ethod# *e5ll t&l, &bout (o%ing &%er&ge (ethods l&ter in the 'h&pter#
MAPri$e 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&geP 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 E 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<
,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 (&Ior 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' line
A&lso '&lled the QS 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 E The period )or the QS line#
0Period E The period )or the QD line#
S"owing E 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 E 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 E Deter(ines the pri'e d&t& used )or the QS 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 E Deter(ines the sto'h&sti' line to '&l'ul&te E 30 45 line or 60 4D line$
9:
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 QS &nd
QD lines &s sho"n belo"+
double PLine = iStochastic(B5LL"9"P*eriod"6*eriod"Slo%ing"M?Method"*rice"9"9';
double 6Line = iStochastic(B5LL"9"P*eriod"6*eriod"Slo%ing"M?Method"*rice"1"9';
Note th&t the 8ode p&r&(eter is 0 )or the QS line &nd 1 )or the QD line# The 023 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 QS 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 023 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 023 "ebsite &t http://ta.mql4.com/#
Custom #ndi$ators
Hundreds o) 'usto( indi'&tors )or 0et&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#
023 h&s & built-in )un'tion )or h&ndling 'usto( indi'&tors E 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 #ndicatorCame# 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;
,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 -.% E 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 &arameters
e+tern int &eriod=V9;
e+tern int method=8; -- M;6/=SM?
e+tern int &rice=9; -- *KIC/=CL;S/
99
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(B5LL"9""Slo&e 6irection Line""Slo&e*eriod"Slo&eMethod"Slo&e*rice"9"9';
CU,, 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 0et&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# The
se'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+<u((er(9" 5&trend';
SetInde+<u((er(1" 6ntrend';
SetInde+<u((er(4" /+tMa&<u((er';
!!!
SetInde+St$le(9"6K?O=LIB/"ST3L/=S;LI6"4';
SetInde+St$le(1"6K?O=LIB/"ST3L/=S;LI6"4';
100
,ig -.' E D&t& *indo"
,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 '&n
there)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(B5LL"9""Slo&e 6irection Line""Slo&e*eriod"Slo&eMethod"
Slo&e*rice"9"1';
double Slo&e6o%n = iCustom(B5LL"9""Slo&e 6irection Line""Slo&e*eriod"Slo&eMethod"
Slo&e*rice"1"1';
Note th&t the 8ode p&r&(eter E the ne4t to l&st one E h&s been set to the &ppropri&te indi'&tor
bu))er inde4 E 2 )or +lopeUp &nd 4 )or +lope6own# The +hift p&r&(eter E the %ery l&st one E h&s
been set to 4 "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# 0&,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 211:1;?<1: 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 &dIust the 8ode p&r&(eter in the iCustom()
)un'tion until you )ind the 'orre't bu))er#
101
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
211:1;?<1:# The opposite &pplies "hen the slope is trending do"n"&rd#
i((Slo&e5& R= /M*T3=1?L5/ QQ Slo&e6o%n == /M*T3=1?L5/' -- <u$
i((Slo&e5& == /M*T3=1?L5/ QQ Slo&e6o%n R= /M*T3=1?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
0&ny )un'tions in 023 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 0= is = H1 is <0 &nd H1 is 210# *e '&n &lso use 'onst&nts to indi'&te the ti(e )r&(e+
PER#&0AM% E 1 (inute#
PER#&0AM1 E = (inute#
PER#&0AM%1 E 1= (inute#
PER#&0AM8( E ?0 (inute#
PER#&0A?% E 1 hour A<0 (inutesB#
PER#&0A?4 E 1 hour A210 (inutesB#
PER#&0A0% E D&ily A1110 (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 &lthough 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#CEACL&SE E 0+ Close pri'e#
PR#CEA&PE4 E 1+ Open pri'e#
PR#CEA?#9? E 2+ High pri'e#
102
,rder "onditions and Indicators
PR#CEAL&) E ?+ 3o" pri'e#
PR#CEAME0#A4 E 1+ 0edi&n pri'e 72ig!)Lo%816#
PR#CEATP#CAL E =+ Typi'&l pri'e 72ig!)Lo%)"lose819#
PR#CEA)E#9?TE0 E <+ *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 &dIust 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&0EASMA E 0+ Si(ple (o%ing &%er&ge# C&l'ul&tes the (e&n o) the pri'e d&t&#
M&0EAEMA E 1+ E4ponenti&l (o%ing &%er&ge# Gi%es (ore "eight to re'ent pri'e d&t& &nd
e4ponenti&lly less "eight to older pri'e d&t&# ! %ery popul&r (o%ing &%er&ge#
M&0EASMMA E 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&0EAL)MA E ?+ 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 seen
these 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?
EXPERT ADVISOR PROGRAMMING
0ultiple st&te(ents (ust be en'losed in br&'es#
The else oper&tor e%&lu&tes &n &ltern&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 &ltern&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 E
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 E I) x LL 0 the 'ondition is true#
O 9reater T+an E I) x O 0 the 'ondition is true#
R Less T+an E I) x R 0 the 'ondition is true#
OL 9reater T+an or EBua" To E I) x OL 0 the 'ondition is true#
101
,rder "onditions and Indicators
RL Less T+an or EBua" To E i) x RL 0 the 'ondition is true#
TL 4ot EBua" To E 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 &nother %&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((<oolean1ar1 == true QQ Indicator1 F Indicator4'
)
-- ;&en order
,
I) 7oolean9ar4 is e.u&l to true &nd #ndicator4 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((<oolean1ar1 == true 77 Indicator1 F Indicator4'
I) either 7oolean9ar4 is e.u&l to true or #ndicator4 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=
EXPERT ADVISOR PROGRAMMING
i(((<oolean1ar1 == true QQ Indicator1 F Indicator4' 77 <oolean1ar1 == (alse'
The st&te(ent (7oolean9ar4 LL true NN #ndicator4 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 <oolean1ar1 == (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)
(7oolean9ar4 LL true NN #ndicator4 O #ndicator1) e%&lu&tes to )&lseT
i(((alse 77 <oolean1ar1 == (alse'
I) the 'ondition 7oolean9ar4 LL false e%&lu&tes to true then the entire st&te(ent is true# AIn
other "ords i) 7oolean9ar4 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&y
your 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 E &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<
,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 LL
false 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 %&lidP or b#B the indi'&tor is o))P 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 E 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 &nother 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 )&lseT I) Use+tochastic is set to true &nd
Fline O 6line e%&lu&tes to )&lse the entire 'ondition be'o(es )&lse+
10:
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?(B5LL"9"M?*eriod"9"M?Method"M?*rice"2';
double ,ast8; = iM?(B5LL"9"M?*eriod"9"M?Method"M?*rice"4';
10;
,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 &nother 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(B5LL"9"P*eriod"6*eriod"Slo%ing"M?Method"*rice"9"2';
double LastStoch = iStochastic(B5LL"9"P*eriod"6*eriod"Slo%ing"M?Method"*rice"9"4';
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
EXPERT ADVISOR PROGRAMMING
Here5s &nother 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?(B5LL"9"#astM?*eriod"9"9"9"9';
double Slo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"9';
double ,ast"ast8; L i8;(CU,,D2D"ast8;eriodD2D2D2D4)M
double ,ast+low8; L i8;(CU,,D2D+low8;eriodD2D2D2D4)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
,rder "onditions and Indicators
111
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 121=021000# 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 &nother d&te you
"ould do & si(ple rel&tion&l oper&tion# 3et5s s&y th&t +tart6ate is Mune 1= 2009 &t 11+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 21 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+
Cde(ine S/C=H1 8@99 -- Seconds in an hour
Cde(ine S/C=61 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
121=021000 &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.4: 22:22# There &re other &''ept&ble
112
'or*ing %it! Ti#e and Date
)or(&ts )or d&teti(e 'onst&nts+ the 023 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 E ! d&teti(e %&ri&ble e4pressed &s the nu(ber o) se'onds el&psed sin'e M&nu&ry 1
19:0#
&utput E !n option&l p&r&(eter th&t outputs the 'onst&nt &s d&te only hour &nd (inute
onlyP hour (inute &nd se'ondsP or &ny 'o(bin&tion o) d&te &nd ti(e# C&lid input %&lues &re +
%#8<>6;%< E Outputs the d&te )or e4&(ple 1223.2K.4:
%#8<>8#CU%<+ E Outputs hour &nd (inute )or e4&(ple 2::S2
%#8<>+<C=C6+ E 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.4: 2::S2:4:.
TimeToStr(StartTime"TIM/=6?T/' -- Keturns "499W!9@!12"
TimeToStr(StartTime"TIM/=S/C;B6S' -- Keturns "92J89J:2"
TimeToStr(StartTime"TIM/=MIB5T/S' -- Keturns "92J89"
TimeToStr(StartTime"TIM/=6?T/7TIM/=S/C;B6S' -- 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?
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 Iust 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 E not your lo'&l 'o(puter ti(e# The return %&lue is o) type integer+
@ear() E The 'urrent )our-digit ye&r )or e4&(ple 2009#
8onth() E The 'urrent (onth o) the ye&r )ro( 1 to 12#
6a0() E The 'urrent d&y o) the (onth )ro( 1 to ?1#
6a0=fGeek() E !n integer representing the 'urrent d&y o) the "ee,# Sund&y is 0 0ond&y is
1 6rid&y is = &nd so on#
?our() E The 'urrent hour in 21 hour ti(e )ro( 0 to 2?# 6or e4&(ple ?&( is ? &nd ?p( is
1=#
8inute() E The 'urrent (inute )ro( 0 to =9#
111
'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, Iust 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() E The )our-digit ye&r o) the spe'i)ied d&teti(e %&lue#
%ime8onth() E The (onth o) the spe'i)ied d&teti(e %&lue )ro( 1 to 12#
%ime6a0() E The d&y o) the (onth o) the spe'i)ied d&teti(e %&lue )ro( 1 to ?1#
%ime6a0=fGeek() E !n integer representing the d&y o) the "ee, o) the spe'i)ied d&teti(e
%&lue# Sund&y is 0 0ond&y is 1 6rid&y is = &nd so on#
%ime?our() E The hour o) the spe'i)ied d&teti(e %&lue in 21 hour ti(e )ro( 0 to 2?#
%ime8inute() E 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 to
1223.2K.4: 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 023 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=
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 time
string /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<
'or*ing %it! Ti#e and Date
*e st&rt by 'on%erting our st&rt ti(e to & d&teti(e %&ri&ble +tart%ime# The st&te(ent
if(+tart8onth LL 41 NN +tart6a0 LL S4 NN <nd8onth LL 4) 'he',s to see i) the st&rt d&te is
the l&st d&y o) the ye&r &nd i) the end d&y is &)ter the )irst o) the ne4t ye&r# I) so it &uto(&ti'&lly
in're(ents the end ye&r by 1# Other"ise "e use the 'urrent ye&r )or <nd@ear#
Ne4t "e 'on%ert the end ti(e to the d&teti(e %&ri&ble <nd%ime &nd 'hoose "hi'h Current%ime "e
"&nt to use ser%er or lo'&l# The )in&l if blo', 'he',s to see i) the 'urrent ti(e is bet"een the st&rt
&nd end ti(es# I) so %rade;llowed is set to true#
No" "e need to &dd the 'ode to 'ontrol tr&de e4e'ution# The e&siest "&y to do this is to &dd &n if
blo', &round our order opening routines+
// 7e!in trade block
if(%rade;llowed 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 Sell;rderCount(S$mbol('"MagicBumber' == 9'
)
-- Sell order code omitted (or bre0it$
,
' // <nd trade block
There &re (&ny (ore "&ys to 're&te ti(ers E )or e4&(ple you 'ould use the d&y o) the "ee,
inste&d o) the (onth &nd d&y or set tr&de ti(es rel&ti%e to the 'urrent d&y# *e5ll le&%e it to you the
re&der to 're&te & ti(er th&t is &ppropri&te )or your needs#
Exe$ute &n 2ar &pen
8y de)&ult e4pert &d%isors run in re&l-ti(e on e%ery ti',# 8ut in so(e '&ses it (&y be better to
'he', tr&ding 'onditions only on'e per b&r# 8y "&iting )or the 'urrent b&r to 'lose "e '&n be sure
th&t the 'ondition h&s o''urred &nd th&t the sign&l is %&lid# In 'o(p&rison by e4e'uting tr&des in
re&l-ti(e "e (&y be (ore sus'eptible to )&lse sign&ls#
Tr&ding on'e per b&r &lso (e&ns th&t the results in the Str&tegy Tester "ill be (ore &''ur&te &nd
rele%&nt# Due to the inherent li(it&tions o) 0et&Tr&der5s Str&tegy Tester using /E%ery ti',/ &s the
testing (odel "ill produ'e unreli&ble b&', testing results due to the )&'t th&t ti',s &re o)ten (odeled
11:
EXPERT ADVISOR PROGRAMMING
)ro( 01 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%er
the '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 &dIust 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 E 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 Check;nce*er<ar = true;
-- Alobal 0ariables
datetime CurrentTimeStam&;
-- Init (unction
int init('
)
CurrentTimeStam& = Time[9];
,
11;
'or*ing %it! Ti#e and Date
Here is the 'ode th&t goes &t the beginning o) our start() )un'tion Iust &)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 Cew7ar "ill deter(ine "hether "e "ill
'he', our tr&de 'onditions+
i((Check;nce*er<ar == true'
)
int <arShi(t = 1;
i((CurrentTimeStam& R= Time[9]'
)
CurrentTimeStam& = Time[9];
bool Be%<ar = true;
,
else Be%<ar = (alse;
,
else
)
Be%<ar = true;
<arShi(t = 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 Cew7ar 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 Cew7ar "ill be
set 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 Cew7ar "ill be set to true on'e &g&in#
I) Check=nceer7ar is set to false Cew7ar "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?(B5LL"9"#astM?*eriod"9"9"9"7ar+hift';
i((Close[7ar+hift] F ;&en[7ar+hift]'
double 5seLo% = iLo%(B5LL"9"7ar+hift';
119
EXPERT ADVISOR PROGRAMMING
$ou should re'ogniDe these e4&(ples )ro( be)ore# Inste&d o) 'he',ing the 'urrent b&r "e "ill 'he',
the b&r th&t Iust '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?(B5LL"9"#astM?*eriod"9"9"9"7ar+hiftH4';
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) Cew7ar 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 Cew7ar 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 Sell;rderCount(S$mbol('"MagicBumber' == 9'
)
-- Sell order code omitted (or bre0it$
,
, -- /nd trade block
120
'or*ing %it! Ti#e and Date
121
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 \U# 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 Z[esca&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 &nother to displ&y
in)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
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
EXPERT ADVISOR PROGRAMMING
,ig. ..' E 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 023 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&uthoriDed persons you5ll "&nt to in'orpor&te so(e ,ind o) &''ount
li(it&tions th&t li(it the us&ge o) the E! to &uthoriDed 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&lt the e4e'ution o) the E!#
i((Is6emo(' == (alse'
)
?lert("This /? onl$ (or use on a demo accountR"';
return(9';
,
121
Tips and Tric*s
$ou '&n use the &''ount )un'tions ;ccountCame() ;ccountCumber() &nd ;ccount7roker() to
'he', the &''ount n&(e nu(ber &nd bro,er respe'ti%ely# 3i(iting us&ge by &''ount nu(ber is &
'o((on &nd e&sy to i(ple(ent (ethod o) prote'tion+
int Customer?ccount = 148:2@;
i((?ccountBumber(' R= Customer?ccount'
)
?lert("?ccount number does not matchR"';
return(9';
,
$ou '&n use ;ccountCame() or ;ccount7roker() in & si(il&r (&nner# 6or ;ccount7roker() you5ll
)irst need to use & rint() st&te(ent to retrie%e the 'orre't return %&lue )ro( the bro,er# This %&lue
"ill be printed in the e4perts log#
I) you do de'ide to sell &n E! 'o((er'i&lly be &"&re th&t 023 )iles &re notoriously e&sy to
de'o(pile# There &re %&rious (ethods you '&n use to (&,e it (ore di))i'ult )or h&',ers to 'r&', your
E! su'h &s pl&'ing )un'tions in e4tern&l libr&ries or D33s# 8ut ulti(&tely there is little prote'tion
&g&inst & deter(ined 'r&',er#
Message2ox<=
So )&r in this boo, "e5%e been using the built-in ;lert() )un'tion to displ&y error (ess&ges# 8ut
"h&t i) you "&nt to 'usto(iDe your &lert di&logs or re.uest input )ro( the userT The 8essa!e7ox()
)un'tion "ill &llo" you to 're&te & 'usto( pop-up di&log using *indo"s !PI )un'tions#
To use the 8essa!e7ox() )un'tion "e (ust )irst Ainclude the GinUserS1.mqh )ile th&t is inst&lled
"ith 0et&Tr&der# This )ile i(ports )un'tions )ro( the *indo"s userS1.dll )ile &nd de)ines 'onst&nts
ne'ess&ry )or the 8essa!e7ox() )un'tion to "or,# Here is the synt&4 )or the 8essa!e7ox() )un'tion+
int Message<o+(string Text" string Title" int )lags';
To use the 8essa!e7ox() )un'tion "e (ust de)ine the %ext to &ppe&r in the pop-up di&log &long
"ith & %itle th&t &ppe&rs in the title b&r# *e "ill &lso need to spe'i)y "la!s th&t indi'&te "hi'h
buttons &nd i'ons should &ppe&r in our pop-up# I) no )l&gs &re spe'i)ied &n OS button "ill be the
de)&ult# 6l&gs (ust be sep&r&ted by the pipe AVB 'h&r&'ter#
Here5s &n e4&(ple o) & (ess&ge bo4 "ith $es7No buttons &nd & .uestion (&r, i'on+
12=
EXPERT ADVISOR PROGRAMMING
-- *re&rocessor directi0es
Cinclude DOin5ser84!mEhF
-- start(' (unction
int 3esBo<o+ = Message<o+("*lace a Trade\"""Trade Con(irmation""
M<=3/SB;7M<=IC;BY5/STI;B';
i((3esBo<o+ == I63/S'
)
-- *lace ;rder
,
The )l&g 87>@<+C= spe'i)ies th&t "e "ill be using $es7No
buttons in our (ess&ge bo4 "hile the 87>#C=CVU<+%#=C
)l&g pl&'es the .uestion (&r, i'on in the di&log bo4# The
integer %&ri&ble @esCo7ox 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) @esCo7ox
"ill be #6@<+ &nd &n order "ill be pl&'ed# I) the No
button "&s pressed the return )l&g "ill be #6C=# $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
023 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#
M2A&@CA4CEL E OS &nd C&n'el buttons#
M2AES4& E $es &nd No buttons#
M2AES4&CA4CEL E $es No &nd C&n'el buttons#
12<
,ig. ..8 E Popup di&log 're&ted using the
0ess&ge8o4AB )un'tion
Tips and Tric*s
#$on ,"ags
These )l&gs spe'i)y i'ons th&t &ppe&r ne4t to the te4t in the (ess&ge bo4#
M2A#C&4ST&P E ! stop sign i'on#
M2A#C&4Q5EST#&4 E ! .uestion (&r, i'on#
M2A#C&4ECCLAMAT#&4 E !n e4'l&(&tion point i'on#
M2A#C&4#4,&RMAT#&4 E !n in)or(&tion i'on#
Return ,"ags
These )l&gs &re the return %&lue o) the 8essa!e7ox() )un'tion &nd indi'&te "hi'h button "&s
pressed#
#0&@ E The OS button "&s pressed#
#0CA4CEL E The C&n'el button "&s pressed#
#0ES E The $es button "&s pressed
#04& E The No button "&s pressed#
Emai" A"erts
$our e4pert &d%isor '&n &lert you by e(&il &bout pl&'ed tr&des potenti&l tr&de setups &nd (ore# The
)un'tion +end8ail() "ill send &n e(&il "ith the subIe't &nd body o) your 'hoi'e to the e(&il
&ddress th&t is listed in the Tools - ,ptions di&log under the E#ail t&b#
In the E(&il t&b you (ust )irst spe'i)y the S0TP (&il ser%er "ith port nu(ber E )or e4&(ple+
#ail$yourdo#ain$co#06; && &long "ith & usern&(e &nd p&ss"ord i) re.uired# Che', "ith your ISP or
hosting pro%ider )or this in)or(&tion#
$ou '&n use &ny e(&il &ddress in the Fro# )ield# The To )ield is the e(&il &ddress to send (ess&ges
to# 8e sure to 'he', the Enable setting &t the top to en&ble the sending o) (ess&ges#
The +end8ail() )un'tion h&s t"o &rgu(ents+ the )irst is the subIe't line o) the e(&il &nd the
se'ond is the 'ontents o) the e(&il itsel)# $ou '&n use ne"lines es'&ped 'h&r&'ters %&ri&bles &nd
'onst&nts "ithin the body o) your e(&il#
12:
EXPERT ADVISOR PROGRAMMING
,ig. ;#1 E The E(&il settings under Tools E Options#
Here5s &n e4&(ple o) +end8ail() us&ge+
string /mailSubSect = "<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(/mailSubSect"/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;
Tips and Tric*s
int Ticket = 9;
%hile(Ticket D= 9'
)
Ticket = ;rderSend(S$mbol('";*=<53"LotSi>e";&en*rice"5seSli&&age"
<u$Sto&Loss"<u$Take*ro(it';
,
*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('";*=<53"LotSi>e";&en*rice"5seSli&&age"<u$Sto&Loss"
<u$Take*ro(it';
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 timeout
return(true';
case 18@J -- ;(( Euotes
return(true';
129
EXPERT ADVISOR PROGRAMMING
case 18VJ -- KeEuotes
return(true';
case 1:@J -- Trade conte+t bus$
return(true';
de(aultJ
return((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# In
this 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('";*=<53"LotSi>e";&en*rice"5seSli&&age"<u$Sto&Loss"
<u$Take*ro(it';
if(%icket LL -4) int <rrCode L Bet,ast<rror()M
i((Ketries D= Ma+Ketries NN <rrorCheck(<rrCode) LL true' KetriesNN;
else break;
,
I) the %icket returns -4 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
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! =rderComment4 L -"irst order-M
strin! =rderComment1 L -+econd order-M
-- ;rder &lacement
int Ticket1 = ;rderSend(S$mbol('";*=<53"LotSi>e";&en*rice"5seSli&&age"<u$Sto&Loss"
<u$Take*ro(it"=rderComment4"MagicBumber"9"Areen';
int Ticket4 = ;rderSend(S$mbol('";*=<53"LotSi>e";&en*rice"5seSli&&age"<u$Sto&Loss"
<u$Take*ro(it"=rderComment1"MagicBumber"9"Areen';
-- ;rder modi(ication
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/L/CT=<3=*;S';
i((;rderMagicBumber(' == MagicBumber QQ ;rderS$mbol(' == S$mbol('
NN =rderComment() LL =rderComment4'
)
-- 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"o
orders 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
EXPERT ADVISOR PROGRAMMING
Margin C+e$*
0et&Tr&der 'o(es "ith )un'tions th&t &llo" you to 'he', the 'urrent free #argin or stop out level
be)ore pl&'ing &n order# The stop out le%el is the per'ent&ge or &(ount o) )ree (&rgin belo" "hi'h
you "ill not be &ble to pl&'e orders# 0&nu&lly 'he',ing the )ree (&rgin or stop out le%el be)ore
pl&'ing &n order is not re&lly ne'ess&ry ho"e%er &s &n error "ill o''ur i) you try to pl&'e &n order
"ith too little (&rgin#
! (ore use)ul ide& "ould be to deter(ine your o"n stop out le%el &nd h&lt tr&ding i) the 'urrent
e.uity goes belo" th&t le%el# 3et5s st&rt by de'l&ring &n e4tern&l %&ri&ble '&lled 8inimum<quit0
"hi'h is the (ini(u( &(ount o) e.uity re.uired in our &''ount be)ore "e '&n pl&'e &n order#
*e5ll 'o(p&re 8inimum<quit0 to our 'urrent &''ount e.uity# I) the 'urrent e.uity is less th&n our
(ini(u( e.uity the order "ill not be pl&'ed &nd &n &lert (ess&ge "ill in)or( the user o) the
'ondition# 3et5s &ssu(e "e h&%e &n &''ount b&l&n'e o) G10000# I) "e lose (ore th&n 20Q o) th&t
e.uity "e do not "&nt to pl&'e the order# Here is the 'ode to 'he', the (ini(u( e.uity+
-- /+ternal 0ariables
e+tern int Minimum/Euit$ = V999;
-- ;rder &lacement
i((?ccount/Euit$(' F Minimum/Euit$'
)
-- *lace order
,
else i((?ccount/Euit$(' D= Minimum/Euit$'
)
?lert("Current eEuit$ is less than minimum eEuit$R ;rder not &laced!"';
,
The e4tern&l %&ri&ble 8inimum<quit0 is pl&'ed &t the beginning o) the )ile# The rest o) the 'ode
'o(es be)ore &nd &)ter the order pl&'e(ent )un'tion# I) the 'urrent e.uity &s indi'&ted by
;ccount<quit0() is gre&ter th&n 8inimum<quit0 the order "ill be pl&'ed# Other"ise the order "ill
not be pl&'ed &nd &n &lert (ess&ge "ill be displ&yed#
Spread C+e$*
$ou (&y "ish to &%oid pl&'ing tr&des during periods "here the spre&d h&s "idened )&r beyond
nor(&l# *e '&n set & (&4i(u( spre&d &nd 'he', the 'urrent spre&d be)ore tr&ding# *e5ll de'l&re &n
e4tern&l %&ri&ble '&lled 8aximum+pread &nd use 8arket#nfo() to 'he', the 'urrent spre&d#
1?2
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 siDes# 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 &dIust 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&ble
to &dIust 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??
EXPERT ADVISOR PROGRAMMING
e+tern int Take*ro(it1 = :9;
e+tern int Take*ro(it4 = V9;
e+tern int Take*ro(it8 = 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*ro(it[8];
double <u$Sto&Loss[8];
<u$Take*ro(it[9] = Calc<u$Take*ro(it(S$mbol('"Take*ro(it1"?sk';
<u$Take*ro(it[1] = Calc<u$Take*ro(it(S$mbol('"Take*ro(it4"?sk';
<u$Take*ro(it[4] = Calc<u$Take*ro(it(S$mbol('"Take*ro(it8"?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 Dero so by de'l&ring &n &rr&y di(ension siDe 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 1 E
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 - 4; CountNN'
)
int ;rdInt = Count N 1;
;rderSend(S$mbol('";*=<53"LotSi>e"?sk"5seSli&&age"7u0+top,ossICountJ"
7u0%akerofitICountJ"-7u0 =rder -H=rd#nt"MagicBumber"9"Areen';
,
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 - 4# 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?1
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 Iust one "&y o) h&ndling (ultiple orders &lthough it is prob&bly the (ost e))i'ient# The (&in
dr&"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*ro(itStart = :9;
e+tern int Take*ro(itIncr = :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 10 &nd
in're(ent by 10# 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)M
int 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*ro(it = Calc<u$Take*ro(it(S$mbol('"5seTake*ro(it"?sk';
;rderSend(S$mbol('";*=<53"LotSi>e"?sk"5seSli&&age"7u0+top,oss"
7u0%akerofit""<u$ ;rder "N;rdInt"MagicBumber"9"Areen';
,
*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 1#
6in&lly "e pl&'e the order using =rder+end()# The loop "ill 'ontinue until the nu(ber o) orders
1?=
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#/ 0et&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 023 do'u(ent&tion re)ers to these &s /glob&l %&ri&bles/ &lthough & (ore &ppropri&te n&(e
(ight be /ter(in&l %&ri&bles#/ *e use the glob&l %&ri&ble )un'tions in the 023 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#
Alobal1ariableSet(Alobal1ariableBame"6ouble1alue';
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?<
Tips and Tric*s
-- Alobal 0ariables
string Alobal1ariable*re(i+;
int init('
)
Alobal1ariable*re(i+ = S$mbol('N*eriod('N"="N"*ro(it<uster"N"="NMagicBumberN"=";
,
*e use the 'urrent sy(bol &nd period &long "ith &n identi)ier )or the E! &nd the 8a!icCumber
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+
Alobal1ariableSet(Alobal1ariable*re(i+NCounter"Counter';
So i) "e5re tr&ding on E>R>SD on the 01= 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+64:>rofit7uster>44>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 = Alobal1ariableAet(Alobal1ariable*re(i+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'tion
Blobal9ariable6elete;ll() "ith your pre)i4 &s the &rgu(ent#
Alobal1ariable6el(Alobal1ariable*re(i+NCounter';
Alobal1ariable6elete?ll(Alobal1ariable*re(i+';
6or (ore in)or(&tion on glob&l %&ri&ble )un'tions see the <lobal variables topi' in the 023
Re)eren'e#
C+e$* &rder Profit
So(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?:
EXPERT ADVISOR PROGRAMMING
;rderSelect(Ticket"S/L/CT=<3=TICP/T';
double Aet*ro(it = ;rder*ro(it(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(Ticket"S/L/CT=<3=TICP/T';
i((;rderT$&e(' == ;*=<53' double Aet*ro(it = ;rderClose*rice(' ;rder;&en*rice(';
else i((;rderT$&e(' == ;*=S/LL' Aet*ro(it = ;rder;&en*rice(' ;rderClose*rice(';
Aet*ro(it -= *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#1<=0 &nd our 'losing pri'e is 1#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#1<00 inste&d then "e5d h&%e & loss o) -=0 pips#
Martinga"e
0&rting&le is & betting syste( 'o((only used in roulette &nd bl&',I&', "here the bet siDe 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 0&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 siDe is 0#1 lots &)ter 1 'onse'uti%e losses your lot siDe "ill be 1#< lots
E 1< ti(es your origin&l lot siDe# !)ter : 'onse'uti%e losses your lot siDe "ill be 12#; lots E 12; ti(es
your origin&l lot siDeL ! 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 siDes 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 siDe# ! sound tr&ding syste( should not h&%e (ore th&n ?
1?;
Tips and Tric*s
or 1 (&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 siDe by & s(&ller (ultiplier# The 'l&ssi' 0&rting&le str&tegy
doubles the lot siDe &)ter e&'h 'onse'uti%e loss# $ou (&y "ish to use & (ultiplier s(&ller th&n 2#
There is &lso the &nti-0&rting&le str&tegy "here you in're&se the lot siDe &)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 siDe &''ordingly# ! 0&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 & 0&rting&le AlossesB or &nti-0&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 &dIust&ble#
6irst let5s '&l'ul&te the nu(ber o) 'onse'uti%e "ins or losses# *e "ill need to loop through the order
history 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()-4M M Count--'
)
;rderSelect(Count"S/L/CT=<3=*;S"M;6/=HIST;K3';
i((;rderS$mbol(' == S$mbol(' QQ ;rderMagicBumber(' == MagicBumber'
)
i((;rder*ro(it(' F 9 QQ LossCount == 9' OinCountNN;
else i((;rder*ro(it(' 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 (ost
re'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 E 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
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 %&lue
indi'&tes & pro)it Ai$e$ is gre&ter th&n DeroB 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
&ltern&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 (e&ning th&t ,ossCount L
1 E &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&lly
shut 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 siDe# 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 & 0&rting&le str&tegy "e use ,ossCount to deter(ine the )&'tor by "hi'h to
in're&se the lot siDe# I) "e5re doing &n &nti-0&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 0&rting&le str&tegy# I) it5s set to 1 "e5ll use the &nti-0&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 siDe A8ax8artin!aleB &nd our st&rting lot siDe A7ase,ot+i/eB#
-- /+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 calculation
i((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&lier"Consecuti0eCount';
110
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 resiDe it to be e.u&l to 8ax8artin!ale# A$ou 'ould
&lso resiDe it to the de)&ult lot siDe i) you pre)er#B The lot siDe "ill re(&in &t this siDe until & "in or loss
bre&,s our 'onse'uti%e order stre&,#
The lot siDe is deter(ined by (ultiplying our 7ase,ot+i/e 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 siDe is 0#1 the lot (ultiplier is 2 &nd "e h&%e )our 'onse'uti%e orders the
e.u&tion is 2.4 * 1
4
L 4.K#
8y &dIusting the ,ot8ultiplier &nd using both 0&rting&le &nd &nti-0&rting&le str&tegies this "ill
gi%e you enough options to e4peri(ent "ith using e4ponenti&l lot siDing# $ou '&n e&sily (odi)y the
'ode &bo%e to use other %&ri&tions# 6or e4&(ple you 'ould s'&le lot siDes 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 0et&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(
111
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# 0&,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&lyDe# I)
you need to 'he', pri'es on the 'h&rt hit the ,pen "!art button to open & 'h&rt sho"ing the
si(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 errorT
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*ro(it = ;&en*rice N (Take*ro(it . 5se*oint';
<u$Ticket = ;rderSend(S$mbol('";*=<53"LotSi>e";&en*rice"5seSli&&age"
<u$Sto&Loss"<u$Take*ro(it""<u$ ;rder""MagicBumber"9"Areen';
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" *ro(itJ"N<u$Take*ro(it';
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 /5K5S6"H1J ;rderSend error 189
11J24J14 499W!11!94 94J99 /+am&le /5K5S6"H1J *riceJ1!:U8:9999 Sto&J1!:UV:9999
*ro(itJ1!: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&liDe th&t "e
&''ident&lly inserted & plus sign in the buy stop loss e.u&tion# Here is the 'orre't 'ode+
112
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 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 Ai#e# inside the
stop le%elB#
Error %8(D #nva"id Stops E 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 Ai#e# inside the stop le%elB#
Error %8%D #nva"id Trade 7o"ume E The lot siDe is in'orre't# 0&,e sure th&t the lot siDe
does not e4'eed the bro,er (ini(u( or (&4i(u( &nd th&t the lot siDe is nor(&liDed 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 023 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 0231#'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 E &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;
11?
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 Iu(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 &lthough only the
)irst one "&s %&lid#
Here is & list o) 'o((on 'o(pil&tion errors &nd their solutions+
7aria!"e not defined E $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 E $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 E 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#
111
Tips and Tric*s
#""ega" assignment used E This is usu&lly in re)eren'e to &n e.u&l sign ARB# Re(e(ber
th&t & single e.u&l sign is )or %&ri&ble &ssign(ent &nd t"o e.u&l signs ARRB 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 E This is usu&lly in re)eren'e to the /e.u&l to/ 'o(p&rison oper&tor
ARRB# $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 E 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 E 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 E $ou h&%e too )e" or too (&ny &rgu(ents in & )un'tion#
Double 'he', the )un'tion synt&4 in the 023 Re)eren'e &nd 'orre't the &rgu(ents#
Semi$o"on expe$ted E $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
11=
EXPERT ADVISOR PROGRAMMING
C+apter /
Custom #ndi$ators and S$ripts
No boo, on 023 "ould be 'o(plete "ithout 'o%ering 'usto( indi'&tors &nd s'ripts# The built-in
indi'&tors in 0et&Tr&der &re r&ther li(ited but )ortun&tely 023 &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 0T1 '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# 0ost 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 Iust 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 0et&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 E & '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 0o%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#
11<
"usto# Indicators and cripts
*e st&rt by using the "iD&rd to 're&te our indi'&tor )ile# Sele't Ne% )ro( the 6ile (enu or the toolb&r
to open the "iD&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 "iD&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+&ert(ore+!com 7
--NN
C&ro&ert$ co&$right "?ndre% 3oung"
C&ro&ert$ link "htt&J--%%%!eas$e+&ert(ore+!com"
Apropert0 indicator>chart>window
Apropert0 indicator>buffers S
Apropert0 indicator>color4 6eep+k07lue
Apropert0 indicator>color1 6eep+k07lue
Apropert0 indicator>colorS 6eep+k07lue
-- bu((ers
double <xt8ap7uffer4IJM
double <xt8ap7uffer1IJM
double <xt8ap7ufferSIJM
--NN
--7 Custom indicator initiali>ation (unction 7
--NN
int init('
)
-- indicators
+et#ndex+t0le(2D65;G>,#C<)M
+et#ndex7uffer(2D<xt8ap7uffer4)M
+et#ndex+t0le(4D65;G>,#C<)M
+et#ndex7uffer(4D<xt8ap7uffer1)M
+et#ndex+t0le(1D65;G>,#C<)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#
11:
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 the
iCustom() )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 = CLK=B;B/'
2uffer#ndex E The inde4 o) the bu))er )ro( 0 to :#
LineType E Sets the type o) line to dr&"# 65;G>,#C< dr&"s & single line 65;G>?#+%=B5;8
dr&"s & %erti'&l histogr&( Asee the Os0! or !"eso(e Os'ill&tor indi'&tors )or e4&(plesB
65;G>;55=G dr&"s & sy(bol &nd 65;G>C=C< dr&"s no line#
LineSty"e E !n option&l p&r&(eter indi'&ting the dr&"ing style# >sed (&inly )or lines o) type
65;G>,#C<# 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+ E !n option&l p&r&(eter indi'&ting the "idth o) the line in pi4els# The de)&ult
%&lue is 1#
LineCo"or E !n option&l p&r&(eter indi'&ting the 'olor o) the line# I) you use the "iD&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 023
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#
11;
"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 Dero le%el
Asu'h &s in the CCI indi'&torB you '&n use the +et,evel+t0le() &nd +et,evel9alue() )un'tions#
See the 023 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) the
indi'&tor "indo"# >se the #ndicator+hortCame() )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 4ames
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"#
-- bu((ers
double <8;IJM
double Upper7andIJM
double ,ower7andIJM
--NN
--7 Custom indicator initiali>ation (unction 7
--NN
int init('
)
-- indicators
SetInde+St$le(9"6K?O=LIB/';
SetInde+<u((er(9"<8;';
+et#ndex,abel(2D-<8;-)M
SetInde+St$le(1"6K?O=LIB/';
SetInde+<u((er(1"Upper7and';
+et#ndex,abel(4D-Upper7and-)M
SetInde+St$le(4"6K?O=LIB/';
SetInde+<u((er(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#
119
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) &nother 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 "iD&rd inserts Iust one e4pression in the start() )un'tion+
int counted=bars = 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 counted=bars = IndicatorCounted(';
i((counted=bars F 9' counted=bars;

int Calculate<ars = <ars counted=bars;

(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
"usto# Indicators and cripts
In our for loop the in're(enting %&ri&ble Count is set to the %&lue o) Calculate7ars the 'ondition
)or ter(in&tion is "hen Count is less th&n 0 &nd the Count %&ri&ble is de're(ented on e&'h
iter&tion# This "ill '&l'ul&te e&'h b&r on the 'h&rt )ro( le)t to right#
Here is the 'ode to '&l'ul&te our 8ollinger 8&nds# *e5ll de'l&re the e4tern&l %&ri&ble 7andseriod &t
the beginning o) the )ile# The for loop is the one "e 're&ted &bo%e+
-- /+ternal &arameters
extern int 7andseriod L 12M
-- start(' (unction
(or(int Count = Calculate<ars; Count F= 9; Count'
)
<8;ICountJ L i8;(CU,,D2D7andseriodD2D8=6<><8;D2DCount)M

double +td6ev L i+td6ev(CU,,D2D7andseriodD2D8=6<><8;D2DCount)M

Upper7andICountJ L <8;ICountJ H +td6evM
,ower7andICountJ L <8;ICountJ - +td6evM
,
6irst "e '&ll the built-in 0o%ing !%er&ge indi'&tor using the i8;() )un'tion &nd &ssign the return
%&lue to <8;ICountJ# Note th&t the &rr&y inde4 &nd the +hift p&r&(eter )or the (o%ing &%er&ge
indi'&tor both use the 'urrent Count %&lue#
Ne4t "e '&ll the St&nd&rd De%i&tion indi'&tor using i+td6ev()# To '&l'ul&te the upper b&nd &ll "e
need to do is &dd the st&nd&rd de%i&tion to the (o%ing &%er&ge line# This is stored in the bu))er &rr&y
Upper7andIJ# To '&l'ul&te ,ower7andIJ "e subtr&'t the st&nd&rd de%i&tion )ro( the (o%ing
&%er&ge#
3et5s e4tend our indi'&tor & bit (ore by gi%ing it & )ull r&nge o) settings# *e5ll &dd settings to &dIust
the )or"&rd shi)t (o%ing &%er&ge (ethod &nd &pplied pri'e p&r&(eters &s "ell &s & st&nd&rd
de%i&tion &dIust(ent+
-- /+ternal &arameters
e+tern int <ands*eriod = 49;
extern int 7ands+hift L 2M
extern int 7ands8ethod L 4M
extern int 7andsrice L 2M
extern int 6eviations L 4M
1=1
EXPERT ADVISOR PROGRAMMING
-- start(' (unction
(or(int Count = Calculate<ars; Count F= 9; Count'
)
/M?[Count] = iM?(B5LL"9"<ands*eriod"7ands+hiftD7ands8ethodD7andsrice"Count';

double Std6e0 = iStd6e0(B5LL"9"<ands*eriod"7ands+hiftD7ands8ethodD7andsrice"Count';

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 &dIust the re(&ining p&r&(eters )or the i8;() &nd i+td6ev()
)un'tions# *e &lso &dded & p&r&(eter to &dIust 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 &dIust&ble 8ollinger 8&nds indi'&tor
th&t is (ore )le4ible th&n the st&nd&rd 0et&Tr&der indi'&tor# The )ull 'ode is listed in !ppendi4 E#
$ou '&n do (ore "ith 'usto( indi'&tors th&n Iust re'&l'ul&te built-in indi'&tors# Depending on your
le%el o) (&the(&ti'&l ,no"ledge you '&n 'ode indi'&tors th&t &ren5t in'luded "ith 0et&Tr&der or
e%en 're&te your o"n# $ou '&n &lso dr&" &nd (&nipul&te obIe'ts &s "ell# I) you5d li,e to le&rn (ore
&bout 'usto( indi'&tor 're&tion see the 023 Re)eren'e topi's "usto# indicators? ,b@ect functions
&nd Mat! A Trig#
S$ripts
! s'ript is &n 023 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 0et&Tr&der '&n
redr&" 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#
C&ro&ert$ sho%=con(irm -- sho%s con(irm dialog
C&ro&ert$ sho%=in&uts -- sho%s &ro&erties dialog
I) your s'ript h&s p&r&(eters th&t need to be &dIusted use the show>inputs property# Other"ise
use show>confirm#
1=2
"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 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#
0et&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=?
EXPERT ADVISOR PROGRAMMING
Appendix A
Simp"e Expert Advisor
This is the si(ple e4pert &d%isor )ro( 'h&pter 2#
C&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*ro(it = 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 a0erages
double #astM? = iM?(B5LL"9"#astM?*eriod"9"9"9"9';
double Slo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"9';
1=1
Appendix A
-- <u$ order
i((#astM? F Slo%M? QQ <u$Ticket == 9'
)
;rderSelect(SellTicket"S/L/CT=<3=TICP/T';
-- Close order
i((;rderCloseTime(' == 9 QQ SellTicket F 9'
)
double CloseLots = ;rderLots(';
double Close*rice = ?sk;
bool Closed = ;rderClose(SellTicket"CloseLots"Close*rice"5seSli&&age"Ked';
,
double ;&en*rice = ?sk;
-- Calculate sto& loss and take &ro(it
i((Sto&Loss F 9' double <u$Sto&Loss = ;&en*rice (Sto&Loss . 5se*oint';
i((Take*ro(it F 9' double <u$Take*ro(it = ;&en*rice N (Take*ro(it . 5se*oint';
-- ;&en bu$ order
<u$Ticket = ;rderSend(S$mbol('";*=<53"LotSi>e";&en*rice"5seSli&&age"
<u$Sto&Loss"<u$Take*ro(it""<u$ ;rder""MagicBumber"9"Areen';
SellTicket = 9;
,
-- Sell ;rder
i((#astM? D Slo%M? QQ SellTicket == 9'
)
;rderSelect(<u$Ticket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9 QQ <u$Ticket F 9'
)
CloseLots = ;rderLots(';
Close*rice = <id;
Closed = ;rderClose(<u$Ticket"CloseLots"Close*rice"5seSli&&age"Ked';
,
;&en*rice = <id;
i((Sto&Loss F 9' double SellSto&Loss = ;&en*rice N (Sto&Loss . 5se*oint';
i((Take*ro(it F 9' double SellTake*ro(it = ;&en*rice (Take*ro(it . 5se*oint';
SellTicket = ;rderSend(S$mbol('";*=S/LL"LotSi>e";&en*rice"5seSli&&age"
SellSto&Loss"SellTake*ro(it""Sell ;rder""MagicBumber"9"Ked';
<u$Ticket = 9;
,
1==
EXPERT ADVISOR PROGRAMMING
return(9';
,
-- *i& *oint #unction
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIn(o(Currenc$"M;6/=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 = MarketIn(o(Currenc$"M;6/=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+
C&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*ro(it = 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=<
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?(B5LL"9"#astM?*eriod"9"9"9"9';
double Slo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"9';
-- <u$ order
i((#astM? F Slo%M? QQ <u$Ticket == 9'
)
;rderSelect(SellTicket"S/L/CT=<3=TICP/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(SellTicket"CloseLots"Close*rice"5seSli&&age"Ked';
,
-- 6elete ;rder
else i((;rderCloseTime(' == 9 QQ SellTicket F 9 QQ ;rderT$&e(' == ;*=S/LLST;*'
)
bool 6eleted = ;rder6elete(SellTicket"Ked';
,
double *ending*rice = High[9] N (*ending*i&s . 5se*oint';
-- Calculate sto& loss and take &ro(it
i((Sto&Loss F 9' double <u$Sto&Loss = *ending*rice (Sto&Loss . 5se*oint';
i((Take*ro(it F 9' double <u$Take*ro(it = *ending*rice N
(Take*ro(it . 5se*oint';
-- ;&en bu$ order
<u$Ticket = ;rderSend(S$mbol('";*=<53ST;*"LotSi>e"*ending*rice"5seSli&&age"
<u$Sto&Loss"<u$Take*ro(it""<u$ Sto& ;rder""MagicBumber"9"Areen';
SellTicket = 9;
,
1=:
EXPERT ADVISOR PROGRAMMING
-- Sell ;rder
i((#astM? D Slo%M? QQ SellTicket == 9'
)
;rderSelect(<u$Ticket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9 QQ <u$Ticket F 9 QQ ;rderT$&e(' == ;*=<53'
)
CloseLots = ;rderLots(';
Close*rice = <id;
Closed = ;rderClose(<u$Ticket"CloseLots"Close*rice"5seSli&&age"Ked';
,
else i((;rderCloseTime(' == 9 QQ SellTicket F 9 QQ ;rderT$&e(' == ;*=<53ST;*'
)
6eleted = ;rder6elete(SellTicket"Ked';
,
*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*ro(it F 9' double SellTake*ro(it = *ending*rice
(Take*ro(it . 5se*oint';
SellTicket = ;rderSend(S$mbol('";*=S/LLST;*"LotSi>e"*ending*rice"5seSli&&age"
SellSto&Loss"SellTake*ro(it""Sell Sto& ;rder""MagicBumber"9"Ked';
<u$Ticket = 9;
,
return(9';
,
-- *i& *oint #unction
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIn(o(Currenc$"M;6/=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 = MarketIn(o(Currenc$"M;6/=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=;
Appendix A
1=9
EXPERT ADVISOR PROGRAMMING
Appendix 2
Advan$ed Expert Advisor
This is the e4pert &d%isor "ith &d%&n'ed )e&tures )ro( 'h&pter ?#
C&ro&ert$ co&$right "?ndre% 3oung"
Cinclude 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*ro(it = 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 (unction
int start('
)
-- Mo0ing a0erages
double #astM? = iM?(B5LL"9"#astM?*eriod"9"9"9"1';
double Slo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"1';
1<0
Appendix +
-- Lot si>e calculation
i((6$namicLotSi>e == true'
)
double Kisk?mount = ?ccount/Euit$(' . (/Euit$*ercent - 199';
double Tick1alue = MarketIn(o(S$mbol('"M;6/=TICP1?L5/';
i((*oint == 9!991 77 *oint == 9!99991' Tick1alue .= 19;
double CalcLots = (Kisk?mount - Sto&Loss' - Tick1alue;
double LotSi>e = CalcLots;
,
else LotSi>e = #i+edLotSi>e;
-- Lot si>e 0eri(ication
i((LotSi>e D MarketIn(o(S$mbol('"M;6/=MIBL;T''
)
LotSi>e = MarketIn(o(S$mbol('"M;6/=MIBL;T';
,
else i((LotSi>e F MarketIn(o(S$mbol('"M;6/=M?TL;T''
)
LotSi>e = MarketIn(o(S$mbol('"M;6/=M?TL;T';
,
i((MarketIn(o(S$mbol('"M;6/=L;TST/*' == 9!1'
)
LotSi>e = Bormali>e6ouble(LotSi>e"1';
,
else LotSi>e = Bormali>e6ouble(LotSi>e"4';
-- <u$ ;rder
i((#astM? F Slo%M? QQ <u$Ticket == 9'
)
-- Close ;rder
;rderSelect(SellTicket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9 QQ SellTicket F 9'
)
double CloseLots = ;rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
Ke(reshKates(';
double Close*rice = ?sk;
bool Closed = ;rderClose(SellTicket"CloseLots"Close*rice"5seSli&&age"Ked';
-- /rror handling
i((Closed == (alse'
)
/rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
1<1
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';
Ke(reshKates(';
<u$Ticket = ;rderSend(S$mbol('";*=<53"LotSi>e"?sk"5seSli&&age"9"9"
"<u$ ;rder""MagicBumber"9"Areen';
-- /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 modi(ication
else
)
;rderSelect(<u$Ticket"S/L/CT=<3=TICP/T';
double ;&en*rice = ;rder;&en*rice(';
-- Calculate sto& le0el
double Sto&Le0el = MarketIn(o(S$mbol('"M;6/=ST;*L/1/L' . *oint;
Ke(reshKates(';
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 &ro(it
i((Sto&Loss F 9' double <u$Sto&Loss = ;&en*rice (Sto&Loss . 5se*oint';
i((Take*ro(it F 9' double <u$Take*ro(it = ;&en*rice N
(Take*ro(it . 5se*oint';
1<2
Appendix +
-- 1eri($ sto& loss and take &ro(it
i((<u$Sto&Loss F 9 QQ <u$Sto&Loss F Lo%erSto&Le0el'
)
<u$Sto&Loss = Lo%erSto&Le0el MinSto&;
,
i((<u$Take*ro(it F 9 QQ <u$Take*ro(it D 5&&erSto&Le0el'
)
<u$Take*ro(it = 5&&erSto&Le0el N MinSto&;
,
-- Modi($ order
i((IsTradeConte+t<us$('' Slee&(19';
i((<u$Sto&Loss F 9 77 <u$Take*ro(it F 9'
)
bool TicketMod = ;rderModi($(<u$Ticket";&en*rice"<u$Sto&Loss"
<u$Take*ro(it"9';
-- /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"" *ro(itJ ""<u$Take*ro(it';
*rint(/rrLog';
,
,
,
SellTicket = 9;
,
-- Sell ;rder
i((#astM? D Slo%M? QQ SellTicket == 9'
)
;rderSelect(<u$Ticket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9 QQ <u$Ticket F 9'
)
CloseLots = ;rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
Ke(reshKates(';
1<?
EXPERT ADVISOR PROGRAMMING
Close*rice = <id;
Closed = ;rderClose(<u$Ticket"CloseLots"Close*rice"5seSli&&age"Ked';
-- /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';
Ke(reshKates(';
SellTicket = ;rderSend(S$mbol('";*=S/LL"LotSi>e"<id"5seSli&&age"9"9"
"Sell ;rder"" MagicBumber"9"Ked';
-- /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(SellTicket"S/L/CT=<3=TICP/T';
;&en*rice = ;rder;&en*rice(';
Sto&Le0el = MarketIn(o(S$mbol('"M;6/=ST;*L/1/L' . *oint;
Ke(reshKates(';
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<1
Appendix +
i((Take*ro(it F 9' double SellTake*ro(it = ;&en*rice
(Take*ro(it . 5se*oint';
i((SellSto&Loss F 9 QQ SellSto&Loss D 5&&erSto&Le0el'
)
SellSto&Loss = 5&&erSto&Le0el N MinSto&;
,
i((SellTake*ro(it F 9 QQ SellTake*ro(it F Lo%erSto&Le0el'
)
SellTake*ro(it = Lo%erSto&Le0el MinSto&;
,
i((IsTradeConte+t<us$('' Slee&(19';
i((SellSto&Loss F 9 77 SellTake*ro(it F 9'
)
TicketMod = ;rderModi($(SellTicket";&en*rice"SellSto&Loss"
SellTake*ro(it"9';
-- /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"" *ro(itJ ""SellTake*ro(it';
*rint(/rrLog';
,
,
,
<u$Ticket = 9;
,
return(9';
,
-- *i& *oint #unction
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIn(o(Currenc$"M;6/=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<=
EXPERT ADVISOR PROGRAMMING
-- Aet Sli&&age #unction
int AetSli&&age(string Currenc$" int Sli&&age*i&s'
)
int Calc6igits = MarketIn(o(Currenc$"M;6/=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+
Cinclude Dstdlib!mEhF
-- /+ternal 1ariables
e+tern int *ending*i&s = 49;
e+tern double LotSi>e = 9!1;
e+tern double Sto&Loss = 29;
e+tern double Take*ro(it = 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 1ariables
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?(B5LL"9"#astM?*eriod"9"9"9"9';
double Slo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"9';
1<<
Appendix +
-- <u$ ;rder
i((#astM? F Slo%M? QQ <u$Ticket == 9'
)
-- Close order
;rderSelect(SellTicket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9 QQ SellTicket F 9 QQ ;rderT$&e(' == ;*=S/LL'
)
double CloseLots = ;rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
Ke(reshKates(';
double Close*rice = ?sk;
bool Closed = ;rderClose(SellTicket"CloseLots"Close*rice"5seSli&&age"Ked';
-- /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(SellTicket"Ked';
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<:
EXPERT ADVISOR PROGRAMMING
-- Calculate sto& le0el
double Sto&Le0el = MarketIn(o(S$mbol('"M;6/=ST;*L/1/L' . *oint;
Ke(reshKates(';
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 &ro(it
i((Sto&Loss F 9' double <u$Sto&Loss = *ending*rice (Sto&Loss . 5se*oint';
i((Take*ro(it F 9' double <u$Take*ro(it = *ending*rice N
(Take*ro(it . 5se*oint';
-- 1eri($ sto& loss and take &ro(it
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*ro(it F 9 QQ <u$Take*ro(it D 5&&erSto&Le0el'
)
<u$Take*ro(it = 5&&erSto&Le0el N MinSto&;
,
-- *lace &ending order
i((IsTradeConte+t<us$('' Slee&(19';
<u$Ticket = ;rderSend(S$mbol('";*=<53ST;*"LotSi>e"*ending*rice"5seSli&&age"
<u$Sto&Loss"<u$Take*ro(it""<u$ Sto& ;rder""MagicBumber"9"Areen';
-- /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"" *ro(itJ ""<u$Take*ro(it';
*rint(/rrLog';
,
SellTicket = 9;
,
1<;
Appendix +
-- Sell ;rder
i((#astM? D Slo%M? QQ SellTicket == 9'
)
;rderSelect(<u$Ticket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9 QQ <u$Ticket F 9 QQ ;rderT$&e(' == ;*=<53'
)
CloseLots = ;rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
Ke(reshKates(';
Close*rice = <id;
Closed = ;rderClose(<u$Ticket"CloseLots"Close*rice"5seSli&&age"Ked';
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$Ticket"Ked';
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 = MarketIn(o(S$mbol('"M;6/=ST;*L/1/L' . *oint;
Ke(reshKates(';
Lo%erSto&Le0el = <id Sto&Le0el;
1<9
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*ro(it F 9' double SellTake*ro(it = *ending*rice
(Take*ro(it . 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*ro(it F 9 QQ SellTake*ro(it F Lo%erSto&Le0el'
)
SellTake*ro(it = Lo%erSto&Le0el MinSto&;
,
i((IsTradeConte+t<us$('' Slee&(19';
SellTicket = ;rderSend(S$mbol('";*=S/LLST;*"LotSi>e"*ending*rice"5seSli&&age"
SellSto&Loss"SellTake*ro(it""Sell Sto& ;rder""MagicBumber"9"Ked';
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"" *ro(itJ ""SellTake*ro(it';
*rint(/rrLog';
,
<u$Ticket = 9;
,
return(9';
,
1:0
Appendix +
-- *i& *oint #unction
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIn(o(Currenc$"M;6/=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 = MarketIn(o(Currenc$"M;6/=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
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 1# *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
C&ro&ert$ co&$right "?ndre% 3oung"
Cinclude 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*ro(it = 199;
e+tern int TrailingSto& = 29;
e+tern int Minimum*ro(it = 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 Check;nce*er<ar = true;
-- Alobal 0ariables
int <u$Ticket;
int SellTicket;
double 5se*oint;
int 5seSli&&age;
datetime CurrentTimeStam&;
1:2
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((Check;nce*er<ar == true'
)
int <arShi(t = 1;
i((CurrentTimeStam& R= Time[9]'
)
CurrentTimeStam& = Time[9];
bool Be%<ar = true;
,
else Be%<ar = (alse;
,
else
)
Be%<ar = true;
<arShi(t = 9;
,
-- Mo0ing a0erages
double #astM? = iM?(B5LL"9"#astM?*eriod"9"9"9"<arShi(t';
double Slo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"<arShi(t';
double Last#astM? = iM?(B5LL"9"#astM?*eriod"9"9"9"<arShi(tN1';
double LastSlo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"<arShi(tN1';
-- Calculate lot si>e
double LotSi>e = CalcLotSi>e(6$namicLotSi>e"/Euit$*ercent"Sto&Loss"#i+edLotSi>e';
LotSi>e = 1eri($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:?
EXPERT ADVISOR PROGRAMMING
-- Close sell orders
i((SellMarketCount(S$mbol('"MagicBumber' F 9'
)
Close?llSell;rders(S$mbol('"MagicBumber"Sli&&age';
,
-- ;&en bu$ order
<u$Ticket = ;&en<u$;rder(S$mbol('"LotSi>e"5seSli&&age"MagicBumber';
-- ;rder modi(ication
i((<u$Ticket F 9 QQ (Sto&Loss F 9 77 Take*ro(it F 9''
)
;rderSelect(<u$Ticket"S/L/CT=<3=TICP/T';
double ;&en*rice = ;rder;&en*rice(';
-- Calculate and 0eri($ sto& loss and take &ro(it
double <u$Sto&Loss = Calc<u$Sto&Loss(S$mbol('"Sto&Loss";&en*rice';
i((<u$Sto&Loss F 9' <u$Sto&Loss = ?dSust<elo%Sto&Le0el(S$mbol('"
<u$Sto&Loss"2';
double <u$Take*ro(it = Calc<u$Take*ro(it(S$mbol('"Take*ro(it"
;&en*rice';
i((<u$Take*ro(it F 9' <u$Take*ro(it = ?dSust?bo0eSto&Le0el(S$mbol('"
<u$Take*ro(it"2';
-- ?dd sto& loss and take &ro(it
?ddSto&*ro(it(<u$Ticket"<u$Sto&Loss"<u$Take*ro(it';
,
,
-- 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('"MagicBumber"Sli&&age';
,
SellTicket = ;&enSell;rder(S$mbol('"LotSi>e"5seSli&&age"MagicBumber';
i((SellTicket F 9 QQ (Sto&Loss F 9 77 Take*ro(it F 9''
)
;rderSelect(SellTicket"S/L/CT=<3=TICP/T';
;&en*rice = ;rder;&en*rice(';
double SellSto&Loss = CalcSellSto&Loss(S$mbol('"Sto&Loss";&en*rice';
i((SellSto&Loss F 9' SellSto&Loss = ?dSust?bo0eSto&Le0el(S$mbol('"
SellSto&Loss"2';
double SellTake*ro(it = CalcSellTake*ro(it(S$mbol('"Take*ro(it"
;&en*rice';
1:1
Appendix "
i((SellTake*ro(it F 9' SellTake*ro(it = ?dSust<elo%Sto&Le0el(S$mbol('"
SellTake*ro(it"2';
?ddSto&*ro(it(SellTicket"SellSto&Loss"SellTake*ro(it';
,
,
, -- /nd trade block
-- ?dSust trailing sto&s
i((<u$MarketCount(S$mbol('"MagicBumber' F 9 QQ TrailingSto& F 9'
)
<u$TrailingSto&(S$mbol('"TrailingSto&"Minimum*ro(it"MagicBumber';
,
i((SellMarketCount(S$mbol('"MagicBumber' F 9 QQ TrailingSto& F 9'
)
SellTrailingSto&(S$mbol('"TrailingSto&"Minimum*ro(it"MagicBumber';
,
return(9';
,
Expert Advisor wit+ ,un$tions E Pending &rders
This is the e4pert &d%isor "ith )un'tions using pending stop orders+
-- *re&rocessor
C&ro&ert$ co&$right "?ndre% 3oung"
Cinclude 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*ro(it = 199;
e+tern int TrailingSto& = 29;
e+tern int Minimum*ro(it = 29;
e+tern int *ending*i&s = 1;
e+tern int Sli&&age = 2;
e+tern int MagicBumber = 148;
1:=
EXPERT ADVISOR PROGRAMMING
e+tern int #astM?*eriod = 19;
e+tern int Slo%M?*eriod = 49;
e+tern bool Check;nce*er<ar = true;
-- Alobal 1ariables
int <u$Ticket;
int SellTicket;
double 5se*oint;
int 5seSli&&age;
datetime CurrentTimeStam&;
-- Init (unction
int init('
)
5se*oint = *i&*oint(S$mbol('';
5seSli&&age = AetSli&&age(S$mbol('"Sli&&age';
CurrentTimeStam& = Time[9];
,
-- Start #unction
int start('
)
-- /+ecute on bar o&en
i((Check;nce*er<ar == true'
)
int <arShi(t = 1;
i((CurrentTimeStam& R= Time[9]'
)
CurrentTimeStam& = Time[9];
bool Be%<ar = true;
,
else Be%<ar = (alse;
,
else
)
Be%<ar = true;
<arShi(t = 9;
,
-- Mo0ing a0erages
double #astM? = iM?(B5LL"9"#astM?*eriod"9"9"9"<arShi(t';
double Slo%M? = iM?(B5LL"9"Slo%M?*eriod"9"9"9"<arShi(t';
1:<
Appendix "
-- Calculate lot si>e
double LotSi>e = CalcLotSi>e(6$namicLotSi>e"/Euit$*ercent"Sto&Loss"#i+edLotSi>e';
LotSi>e = 1eri($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?llSell;rders(S$mbol('"MagicBumber"Sli&&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[<arShi(t] N (*ending*i&s . 5se*oint';
*ending*rice = ?dSust?bo0eSto&Le0el(S$mbol('"*ending*rice"2';
double <u$Sto&Loss = Calc<u$Sto&Loss(S$mbol('"Sto&Loss"*ending*rice';
i((<u$Sto&Loss F 9' <u$Sto&Loss = ?dSust<elo%Sto&Le0el(S$mbol('"<u$Sto&Loss"
2"*ending*rice';
double <u$Take*ro(it = Calc<u$Take*ro(it(S$mbol('"Take*ro(it"*ending*rice';
i((<u$Take*ro(it F 9' <u$Take*ro(it = ?dSust?bo0eSto&Le0el(S$mbol('"
<u$Take*ro(it"2"*ending*rice';
<u$Ticket = ;&en<u$Sto&;rder(S$mbol('"LotSi>e"*ending*rice"<u$Sto&Loss"
<u$Take*ro(it"5seSli&&age"MagicBumber';
,
-- 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('"MagicBumber"Sli&&age';
,
1::
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%[<arShi(t] (*ending*i&s . 5se*oint';
*ending*rice = ?dSust<elo%Sto&Le0el(S$mbol('"*ending*rice"2';
double SellSto&Loss = CalcSellSto&Loss(S$mbol('"Sto&Loss"*ending*rice';
i((SellSto&Loss F 9' SellSto&Loss = ?dSust?bo0eSto&Le0el(S$mbol('"
SellSto&Loss"2"*ending*rice';
double SellTake*ro(it = CalcSellTake*ro(it(S$mbol('"Take*ro(it"
*ending*rice';
i((SellTake*ro(it F 9' ?dSust<elo%Sto&Le0el(S$mbol('"
SellTake*ro(it"2"*ending*rice';
SellTicket = ;&enSellSto&;rder(S$mbol('"LotSi>e"*ending*rice"SellSto&Loss"
SellTake*ro(it"5seSli&&age"MagicBumber';
,
, -- /nd trade block
-- ?dSust trailing sto&s
i((<u$MarketCount(S$mbol('"MagicBumber' F 9 QQ TrailingSto& F 9'
)
<u$TrailingSto&(S$mbol('"TrailingSto&"Minimum*ro(it"MagicBumber';
,
i((SellMarketCount(S$mbol('"MagicBumber' F 9 QQ TrailingSto& F 9'
)
SellTrailingSto&(S$mbol('"TrailingSto&"Minimum*ro(it"MagicBumber';
,
return(9';
,
1:;
Appendix "
1:9
EXPERT ADVISOR PROGRAMMING
Appendix 0
#n$"ude ,i"e
This is the in'lude )ile "ith the )un'tions used in the e4pert &d%isor in !ppendi4 C#
C&ro&ert$ co&$right "?ndre% 3oung"
Cinclude Dstdlib!mEhF
double CalcLotSi>e(bool arg6$namicLotSi>e" double arg/Euit$*ercent"double argSto&Loss"
double arg#i+edLotSi>e'
)
i((arg6$namicLotSi>e == true QQ argSto&Loss F 9'
)
double Kisk?mount = ?ccount/Euit$(' . (arg/Euit$*ercent - 199';
double Tick1alue = MarketIn(o(S$mbol('"M;6/=TICP1?L5/';
i((*oint == 9!991 77 *oint == 9!99991' Tick1alue .= 19;
double LotSi>e = (Kisk?mount - argSto&Loss' - Tick1alue;
,
else LotSi>e = arg#i+edLotSi>e;
return(LotSi>e';
,
double 1eri($LotSi>e(double argLotSi>e'
)
i((argLotSi>e D MarketIn(o(S$mbol('"M;6/=MIBL;T''
)
argLotSi>e = MarketIn(o(S$mbol('"M;6/=MIBL;T';
,
else i((argLotSi>e F MarketIn(o(S$mbol('"M;6/=M?TL;T''
)
argLotSi>e = MarketIn(o(S$mbol('"M;6/=M?TL;T';
,
i((MarketIn(o(S$mbol('"M;6/=L;TST/*' == 9!1'
)
argLotSi>e = Bormali>e6ouble(argLotSi>e"1';
,
else argLotSi>e = Bormali>e6ouble(argLotSi>e"4';
return(argLotSi>e';
,
1;0
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";*=<53"argLotSi>e"MarketIn(o(argS$mbol"M;6/=?SP'"
argSli&&age"9"9"argComment"argMagicBumber"9"Areen';
-- /rror Handling
i((Ticket == 1'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate(";&en <u$ ;rder L /rror ""/rrorCode""J ""
/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ ""MarketIn(o(argS$mbol"M;6/=<I6'"
" ?skJ ""MarketIn(o(argS$mbol"M;6/=?SP'"" LotsJ ""argLotSi>e';
*rint(/rrLog';
,
return(Ticket';
,
int ;&enSell;rder(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/LL"argLotSi>e"MarketIn(o(argS$mbol"M;6/=<I6'"
argSli&&age"9"9"argComment"argMagicBumber"9"Ked';
-- /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 ""MarketIn(o(argS$mbol"M;6/=<I6'"
" ?skJ ""MarketIn(o(argS$mbol"M;6/=?SP'"" LotsJ ""argLotSi>e';
*rint(/rrLog';
,
return(Ticket';
,
1;1
EXPERT ADVISOR PROGRAMMING
int ;&en<u$Sto&;rder(string argS$mbol" double argLotSi>e" double arg*ending*rice"
double argSto&Loss" double argTake*ro(it" double argSli&&age" double argMagicBumber"
datetime arg/+&iration = 9" string argComment = "<u$ Sto& ;rder"'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
-- *lace <u$ Sto& ;rder
int Ticket = ;rderSend(argS$mbol";*=<53ST;*"argLotSi>e"arg*ending*rice"argSli&&age"
argSto&Loss"argTake*ro(it"argComment"argMagicBumber"arg/+&iration"Areen';
-- /rror Handling
i((Ticket == 1'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate(";&en <u$ Sto& ;rder /rror ""/rrorCode"
"J ""/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("?skJ ""MarketIn(o(argS$mbol"M;6/=?SP'"
" LotsJ ""argLotSi>e"" *riceJ ""arg*ending*rice"" Sto&J ""argSto&Loss"
" *ro(itJ ""argTake*ro(it"" /+&irationJ ""TimeToStr(arg/+&iration'';
*rint(/rrLog';
,
return(Ticket';
,
int ;&enSellSto&;rder(string argS$mbol" double argLotSi>e" double arg*ending*rice"
double argSto&Loss" double argTake*ro(it" double argSli&&age" double argMagicBumber"
datetime arg/+&iration = 9" string argComment = "Sell Sto& ;rder"'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
-- *lace Sell Sto& ;rder
int Ticket = ;rderSend(argS$mbol";*=S/LLST;*"argLotSi>e"arg*ending*rice"argSli&&age"
argSto&Loss"argTake*ro(it"argComment"argMagicBumber"arg/+&iration"Ked';
-- /rror Handling
i((Ticket == 1'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate(";&en Sell Sto& ;rder /rror ""/rrorCode"
"J ""/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ ""MarketIn(o(argS$mbol"M;6/=<I6'"
" LotsJ ""argLotSi>e"" *riceJ ""arg*ending*rice"" Sto&J ""argSto&Loss"
" *ro(itJ ""argTake*ro(it"" /+&irationJ ""TimeToStr(arg/+&iration'';
1;2
Appendix D
*rint(/rrLog';
,
return(Ticket';
,
int ;&en<u$Limit;rder(string argS$mbol" double argLotSi>e" double arg*ending*rice"
double argSto&Loss" double argTake*ro(it" double argSli&&age" double argMagicBumber"
datetime arg/+&iration" string argComment = "<u$ Limit ;rder"'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
-- *lace <u$ Limit ;rder
int Ticket = ;rderSend(argS$mbol";*=<53LIMIT"argLotSi>e"arg*ending*rice"argSli&&age"
argSto&Loss"argTake*ro(it"argComment"argMagicBumber"arg/+&iration"Areen';
-- /rror Handling
i((Ticket == 1'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate(";&en <u$ Limit ;rder /rror ""/rrorCode"
"J ""/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ ""MarketIn(o(argS$mbol"M;6/=<I6'"
" LotsJ ""argLotSi>e"" *riceJ ""arg*ending*rice"" Sto&J ""argSto&Loss"
" *ro(itJ ""argTake*ro(it"" /+&irationJ ""TimeToStr(arg/+&iration'';
*rint(/rrLog';
,
return(Ticket';
,
int ;&enSellLimit;rder(string argS$mbol" double argLotSi>e" double arg*ending*rice"
double argSto&Loss" double argTake*ro(it" double argSli&&age" double argMagicBumber"
datetime arg/+&iration" string argComment = "Sell Limit ;rder"'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
-- *lace Sell Limit ;rder
int Ticket = ;rderSend(argS$mbol";*=S/LLLIMIT"argLotSi>e"arg*ending*rice"argSli&&age"
argSto&Loss"argTake*ro(it"argComment"argMagicBumber"arg/+&iration"Ked';
-- /rror Handling
i((Ticket == 1'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
1;?
EXPERT ADVISOR PROGRAMMING
string /rr?lert = StringConcatenate(";&en Sell Sto& ;rder /rror ""/rrorCode"
"J ""/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("?skJ ""MarketIn(o(argS$mbol"M;6/=?SP'"
" LotsJ ""argLotSi>e"" *riceJ ""arg*ending*rice"" Sto&J ""argSto&Loss"
" *ro(itJ ""argTake*ro(it"" /+&irationJ ""TimeToStr(arg/+&iration'';
*rint(/rrLog';
,
return(Ticket';
,
double *i&*oint(string Currenc$'
)
int Calc6igits = MarketIn(o(Currenc$"M;6/=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 = MarketIn(o(Currenc$"M;6/=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(argCloseTicket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9'
)
double CloseLots = ;rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
double Close*rice = MarketIn(o(argS$mbol"M;6/=<I6';
bool Closed = ;rderClose(argCloseTicket"CloseLots"Close*rice"argSli&&age"Areen';
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;1
Appendix D
string /rrLog = StringConcatenate("TicketJ ""argCloseTicket"" <idJ ""
MarketIn(o(argS$mbol"M;6/=<I6'';
*rint(/rrLog';
,
,
return(Closed';
,
bool CloseSell;rder(string argS$mbol" int argCloseTicket" double argSli&&age'
)
;rderSelect(argCloseTicket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9'
)
double CloseLots = ;rderLots(';
%hile(IsTradeConte+t<us$('' Slee&(19';
double Close*rice = MarketIn(o(argS$mbol"M;6/=?SP';
bool Closed = ;rderClose(argCloseTicket"CloseLots"Close*rice"argSli&&age"Ked';
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 ""MarketIn(o(argS$mbol"M;6/=?SP'';
*rint(/rrLog';
,
,
return(Closed';
,
bool Close*ending;rder(string argS$mbol" int argCloseTicket'
)
;rderSelect(argCloseTicket"S/L/CT=<3=TICP/T';
i((;rderCloseTime(' == 9'
)
%hile(IsTradeConte+t<us$('' Slee&(19';
bool 6eleted = ;rder6elete(argCloseTicket"Ked';
i((6eleted == (alse'
)
int /rrorCode = AetLast/rror(';
1;=
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 ""
MarketIn(o(argS$mbol"M;6/=<I6'"" ?skJ ""MarketIn(o(argS$mbol"M;6/=?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*ro(it(string argS$mbol" int argTake*ro(it" double arg;&en*rice'
)
i((argTake*ro(it == 9' return(9';
double <u$Take*ro(it = arg;&en*rice N (argTake*ro(it . *i&*oint(argS$mbol'';
return(<u$Take*ro(it';
,
double CalcSellTake*ro(it(string argS$mbol" int argTake*ro(it" double arg;&en*rice'
)
i((argTake*ro(it == 9' return(9';
double SellTake*ro(it = arg;&en*rice (argTake*ro(it . *i&*oint(argS$mbol'';
return(SellTake*ro(it';
,
1;<
Appendix D
bool 1eri($5&&erSto&Le0el(string argS$mbol" double arg1eri($*rice"
double arg;&en*rice = 9'
)
double Sto&Le0el = MarketIn(o(argS$mbol"M;6/=ST;*L/1/L' . *oint;
i((arg;&en*rice == 9' double ;&en*rice = MarketIn(o(argS$mbol"M;6/=?SP';
else ;&en*rice = arg;&en*rice;
double 5&&erSto&Le0el = ;&en*rice N Sto&Le0el;
i((arg1eri($*rice F 5&&erSto&Le0el' bool Sto&1eri($ = true;
else Sto&1eri($ = (alse;
return(Sto&1eri($';
,
bool 1eri($Lo%erSto&Le0el(string argS$mbol" double arg1eri($*rice"
double arg;&en*rice = 9'
)
double Sto&Le0el = MarketIn(o(argS$mbol"M;6/=ST;*L/1/L' . *oint;
i((arg;&en*rice == 9' double ;&en*rice = MarketIn(o(argS$mbol"M;6/=<I6';
else ;&en*rice = arg;&en*rice;
double Lo%erSto&Le0el = ;&en*rice Sto&Le0el;
i((arg1eri($*rice D Lo%erSto&Le0el' bool Sto&1eri($ = true;
else Sto&1eri($ = (alse;
return(Sto&1eri($';
,
double ?dSust?bo0eSto&Le0el(string argS$mbol" double arg?dSust*rice" int arg?dd*i&s = 9"
double arg;&en*rice = 9'
)
double Sto&Le0el = MarketIn(o(argS$mbol"M;6/=ST;*L/1/L' . *oint;
i((arg;&en*rice == 9' double ;&en*rice = MarketIn(o(argS$mbol"M;6/=?SP';
else ;&en*rice = arg;&en*rice;
double 5&&erSto&Le0el = ;&en*rice N Sto&Le0el;
i((arg?dSust*rice D= 5&&erSto&Le0el' double ?dSusted*rice = 5&&erSto&Le0el N
(arg?dd*i&s . *i&*oint(argS$mbol'';
else ?dSusted*rice = arg?dSust*rice;
return(?dSusted*rice';
,
1;:
EXPERT ADVISOR PROGRAMMING
double ?dSust<elo%Sto&Le0el(string argS$mbol" double arg?dSust*rice" int arg?dd*i&s = 9"
double arg;&en*rice = 9'
)
double Sto&Le0el = MarketIn(o(argS$mbol"M;6/=ST;*L/1/L' . *oint;
i((arg;&en*rice == 9' double ;&en*rice = MarketIn(o(argS$mbol"M;6/=<I6';
else ;&en*rice = arg;&en*rice;
double Lo%erSto&Le0el = ;&en*rice Sto&Le0el;
i((arg?dSust*rice F= Lo%erSto&Le0el' double ?dSusted*rice = Lo%erSto&Le0el
(arg?dd*i&s . *i&*oint(argS$mbol'';
else ?dSusted*rice = arg?dSust*rice;
return(?dSusted*rice';
,
bool ?ddSto&*ro(it(int argTicket" double argSto&Loss" double argTake*ro(it'
)
;rderSelect(argTicket"S/L/CT=<3=TICP/T';
double ;&en*rice = ;rder;&en*rice(';
%hile(IsTradeConte+t<us$('' Slee&(19';
-- Modi($ ;rder
bool TicketMod = ;rderModi($(argTicket";rder;&en*rice('"argSto&Loss"argTake*ro(it"9';
-- /rror Handling
i((TicketMod == (alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("?dd Sto&-*ro(it /rror ""/rrorCode"
"J ""/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ ""MarketIn(o(;rderS$mbol('"M;6/=<I6'"
" ?skJ ""MarketIn(o(;rderS$mbol('"M;6/=?SP'"" TicketJ ""argTicket"" Sto&J ""
argSto&Loss"" *ro(itJ ""argTake*ro(it';
*rint(/rrLog';
,
return(TicketMod';
,
1;;
Appendix D
int Total;rderCount(string argS$mbol" int argMagicBumber'
)
int ;rderCount;
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/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(Counter"S/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(Counter"S/L/CT=<3=*;S';
i((;rderMagicBumber(' == argMagicBumber QQ ;rderS$mbol(' == argS$mbol
QQ ;rderT$&e(' == ;*=S/LL'
)
;rderCountNN;
,
,
return(;rderCount';
,
1;9
EXPERT ADVISOR PROGRAMMING
int <u$Sto&Count(string argS$mbol" int argMagicBumber'
)
int ;rderCount;
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/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(Counter"S/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(Counter"S/L/CT=<3=*;S';
i((;rderMagicBumber(' == argMagicBumber QQ ;rderS$mbol(' == argS$mbol
QQ ;rderT$&e(' == ;*=<53LIMIT'
)
;rderCountNN;
,
,
return(;rderCount';
,
190
Appendix D
int SellLimitCount(string argS$mbol" int argMagicBumber'
)
int ;rderCount;
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/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(Counter"S/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 = MarketIn(o(argS$mbol"M;6/=<I6';
bool Closed = ;rderClose(CloseTicket"CloseLots"Close*rice"argSli&&age"Ked';
-- /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 ""
MarketIn(o(argS$mbol"M;6/=<I6'" " TicketJ ""CloseTicket"" *riceJ ""
Close*rice';
*rint(/rrLog';
,
else Counter;
,
,
,
191
EXPERT ADVISOR PROGRAMMING
0oid Close?llSell;rders(string argS$mbol" int argMagicBumber" int argSli&&age'
)
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/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 = MarketIn(o(argS$mbol"M;6/=?SP';
bool Closed = ;rderClose(CloseTicket"CloseLots"Close*rice"argSli&&age"Ked';
-- /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 ""
MarketIn(o(argS$mbol"M;6/=?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(Counter"S/L/CT=<3=*;S';
i((;rderMagicBumber(' == argMagicBumber QQ ;rderS$mbol(' == argS$mbol
QQ ;rderT$&e(' == ;*=<53ST;*'
)
-- 6elete ;rder
int CloseTicket = ;rderTicket(';
192
Appendix D
%hile(IsTradeConte+t<us$('' Slee&(19';
bool Closed = ;rder6elete(CloseTicket"Ked';
-- /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 ""
MarketIn(o(argS$mbol"M;6/=<I6'" " ?skJ ""
MarketIn(o(argS$mbol"M;6/=?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(Counter"S/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(CloseTicket"Ked';
-- /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?
EXPERT ADVISOR PROGRAMMING
string /rrLog = StringConcatenate("<idJ ""
MarketIn(o(argS$mbol"M;6/=<I6'" " ?skJ ""
MarketIn(o(argS$mbol"M;6/=?SP'"" TicketJ ""CloseTicket';
*rint(/rrLog';
,
else Counter;
,
,
,
0oid Close?ll<u$Limit;rders(string argS$mbol" int argMagicBumber'
)
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/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(CloseTicket"Ked';
-- /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 ""
MarketIn(o(argS$mbol"M;6/=<I6'" " ?skJ ""
MarketIn(o(argS$mbol"M;6/=?SP'"" TicketJ ""CloseTicket';
*rint(/rrLog';
,
else Counter;
,
,
,
191
Appendix D
0oid Close?llSellLimit;rders(string argS$mbol" int argMagicBumber'
)
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/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(CloseTicket"Ked';
-- /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 ""
MarketIn(o(argS$mbol"M;6/=<I6'" " ?skJ ""
MarketIn(o(argS$mbol"M;6/=?SP'"" TicketJ ""CloseTicket';
*rint(/rrLog';
,
else Counter;
,
,
,
0oid <u$TrailingSto&(string argS$mbol" int argTrailingSto&" int argMin*ro(it"
int argMagicBumber'
)
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/L/CT=<3=*;S';
-- Calculate Ma+ Sto& and Min *ro(it
double Ma+Sto&Loss = MarketIn(o(argS$mbol"M;6/=<I6'
(argTrailingSto& . *i&*oint(argS$mbol'';
Ma+Sto&Loss = Bormali>e6ouble(Ma+Sto&Loss"
MarketIn(o(;rderS$mbol('"M;6/=6IAITS'';
double CurrentSto& = Bormali>e6ouble(;rderSto&Loss('"
MarketIn(o(;rderS$mbol('"M;6/=6IAITS'';
19=
EXPERT ADVISOR PROGRAMMING
double *i&s*ro(it = MarketIn(o(argS$mbol"M;6/=<I6' ;rder;&en*rice(';
double Min*ro(it = argMin*ro(it . *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*ro(it F= Min*ro(it'
)
bool Trailed = ;rderModi($(;rderTicket('";rder;&en*rice('"Ma+Sto&Loss"
;rderTake*ro(it('"9';
-- /rror Handling
i((Trailed == (alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("<u$ Trailing Sto& L /rror ""
""/rrorCode""J ""/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("<idJ ""
MarketIn(o(argS$mbol"M;6/=<I6'" " TicketJ "";rderTicket('"" Sto&J ""
;rderSto&Loss('"" TrailJ ""Ma+Sto&Loss';
*rint(/rrLog';
,
,
,
,
0oid SellTrailingSto&(string argS$mbol" int argTrailingSto&" int argMin*ro(it"
int argMagicBumber'
)
(or(int Counter = 9; Counter D= ;rdersTotal('1; CounterNN'
)
;rderSelect(Counter"S/L/CT=<3=*;S';
-- Calculate Ma+ Sto& and Min *ro(it
double Ma+Sto&Loss = MarketIn(o(argS$mbol"M;6/=?SP' N
(argTrailingSto& . *i&*oint(argS$mbol'';
Ma+Sto&Loss = Bormali>e6ouble(Ma+Sto&Loss"
MarketIn(o(;rderS$mbol('"M;6/=6IAITS'';
double CurrentSto& = Bormali>e6ouble(;rderSto&Loss('"
MarketIn(o(;rderS$mbol('"M;6/=6IAITS'';
double *i&s*ro(it = ;rder;&en*rice(' MarketIn(o(argS$mbol"M;6/=?SP';
double Min*ro(it = argMin*ro(it . *i&*oint(argS$mbol';
19<
Appendix D
-- Modi($ Sto&
i((;rderMagicBumber(' == argMagicBumber QQ ;rderS$mbol(' == argS$mbol
QQ ;rderT$&e(' == ;*=S/LL QQ (CurrentSto& F Ma+Sto&Loss 77 CurrentSto& == 9'
QQ *i&s*ro(it F= Min*ro(it'
)
bool Trailed = ;rderModi($(;rderTicket('";rder;&en*rice('"Ma+Sto&Loss"
;rderTake*ro(it('"9';
-- /rror Handling
i((Trailed == (alse'
)
int /rrorCode = AetLast/rror(';
string /rr6esc = /rror6escri&tion(/rrorCode';
string /rr?lert = StringConcatenate("Sell Trailing Sto& /rror ""
/rrorCode""J ""/rr6esc';
?lert(/rr?lert';
string /rrLog = StringConcatenate("?skJ ""
MarketIn(o(argS$mbol"M;6/=?SP'" " TicketJ "";rderTicket('"" Sto&J ""
;rderSto&Loss('"" TrailJ ""Ma+Sto&Loss';
*rint(/rrLog';
,
,
,
,
19:
EXPERT ADVISOR PROGRAMMING
Appendix E
Custom #ndi$ator
Here is the 'ode )or the 'usto( indi'&tor )ro( 'h&pter 9+
C&ro&ert$ co&$right "?ndre% 3oung"
C&ro&ert$ indicator=chart=%indo%
C&ro&ert$ indicator=bu((ers 8
C&ro&ert$ indicator=color1 6ee&Sk$<lue
C&ro&ert$ indicator=color4 6ee&Sk$<lue
C&ro&ert$ indicator=color8 6ee&Sk$<lue
-- /+ternal 0ariables
e+tern int <ands*eriod = 49;
e+tern int <andsShi(t = 9;
e+tern int <andsMethod = 1;
e+tern int <ands*rice = 9;
e+tern int 6e0iations = 1;
-- <u((ers
double /M?[];
double 5&&er<and[];
double Lo%er<and[];
-- Init
int init('
)
SetInde+St$le(9"6K?O=LIB/';
SetInde+<u((er(9"/M?';
SetInde+Label(9""/M?"';
SetInde+St$le(1"6K?O=LIB/';
SetInde+<u((er(1"5&&er<and';
SetInde+Label(1""5&&er<and"';
SetInde+St$le(4"6K?O=LIB/';
SetInde+<u((er(4"Lo%er<and';
SetInde+Label(4""Lo%er<and"';
return(9';
,
19;
Appendix E
-- Start
int start('
)
int counted=bars = IndicatorCounted(';
int Calculate<ars = <ars counted=bars;
(or(int Count = Calculate<ars; Count F= 9; Count'
)
/M?[Count] = iM?(B5LL"9"<ands*eriod"<andsShi(t"<andsMethod"<ands*rice"Count';
double Std6e0 = iStd6e0(B5LL"9"<ands*eriod"<andsShi(t"<andsMethod"<ands*rice"
Count';
5&&er<and[Count] = /M?[Count] N (Std6e0 . 6e0iations';
Lo%er<and[Count] = /M?[Count] (Std6e0 . 6e0iations';
,
return(9';
,
199
#ndex
A
;ccount7roker() ################################### 12=
;ccount<quit0() ############################# =0 1?2
;ccountCame() ####################################### 12=
;ccountCumber() ################################### 12=
;lert() ################################################### =1
!pplied pri'e 'onst&nts ############################ 102
!rr&ys ##################################################### 1?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 #################################################### 11<
C
case oper&tor ######################################### 1?0
CloseIJ ################################################### 91
color d&t& type ########################################## 9
Comment() ############################################## 122
Co((ents ################################################## ;
Co(pil&tion errors ################################### 111
Co(pound oper&tors ################################### ;
Const&nts ################################################# 10
Custo( indi'&tors ###################################### 9;
0
D&t& types ################################################## 9
D&t& "indo" ########################################### 100
D&teti(e 'onst&nts ################################## 112
datetime d&t& type #################################### 9
datetime %&ri&bles ################################## 112
6a0() ##################################################### 111
6a0=fGeek() ########################################## 111
Debugging ############################################## 111
default oper&tor #################################### 1?0
De)&ult %&lues ########################################### 12
deinit() ################################################## 1:
D33s ######################################################### :=
double d&t& type ######################################## 9
E
ECN7STP ############################################# 20 12
else oper&tor ######################################### 101
<8%@>9;,U< ########################################## 102
Error 'odes ############################################# 11?
Error h&ndling ########################################### =?
<rror6escription() ############################### =1
Es'&pe 'h&r&'ters #################################### 122
E4pert !d%isor *iD&rd ################################ 11
E4pir&tion ################################################# 21
extern %&ri&bles ####################################### 1<
,
6I6O ######################################################### ;=
6ile )or(&ts ################################################# 1
6ile lo'&tions ############################################### =
for oper&tor ############################################# ;0
6un'tion &rgu(ents ################################### 12
6un'tions ################################################## 10
9
Bet,ast<rror() ####################################### =1
Glob&l %&ri&bles ####################################### 1?<
Glob&lly s'oped %&ri&ble ####################### 1? 1:
Blobal9ariable6el() ############################ 1?:
Blobal9ariable6elete;ll() ################# 1?:
Blobal9ariableBet() ############################ 1?:
Blobal9ariable+et() ############################ 1?<
?
?i!hIJ ##################################################### 91
?our() ################################################### 111
#
iClose() ################################################## 91
iCustom() ################################################ 9;
Identi)iers ################################################### ;
if oper&tor ############################################# 10?
i?i!h() ################################################### 91
i?i!hest() ############################################### ?2
i,ow() ##################################################### 91
i,owest() ################################################ ?1
i8;() ####################################################### 9<
In'lude )iles ############################################## :1
indicator>buffers ############################### 11:
indicator>chart>window ###################### 11:
indicator>color ################################### 11:
indicator>separate>window ################# 11:
#ndicatorCounted() ############################## 1=0
Indi'&tors ################################################# 9=
#ndicator+hortCame() ########################## 119
init() ##################################################### 1:
int d&t& type ############################################## 9
i=pen() ################################################### 91
#s6emo() ################################################ 121
#s6lls;llowed() ################################### 12?
#s,ibraries;llowed() ########################## 12?
i+td6ev() ############################################## 1=1
i+tochastic() ######################################### 9;
#s%rade;llowed() ################################# 12?
#s%radeContext7us0() ############################ =2
L
3ibr&ries #################################################### :1
3i(it order ################################################ 21
3o'&l %&ri&ble ############################################ 1?
3ogs ####################################################### 111
3ot siDe ##################################################### 19
3ot step %&lue ########################################### =2
,owIJ ####################################################### 91
M
0&gi' nu(ber ########################################### 2?
0&r,et order ############################################# 20
8arket#nfo() ########################################## 29
0&rting&le ############################################### 1?;
8athow() ############################################## 111
0&4i(u( lot siDe ####################################### =1
8essa!e7ox() ######################################## 12=
0et&Editor ################################################## <
0ini(u( lot siDe ####################################### =1
8inute() ################################################ 111
8ode p&r&(eter ######################################### 9;
8onth() ################################################# 111
0o%ing &%er&ge (ethods ######################### 10?
4
N&%ig&tor "indo" ####################################### <
Ne"line 'h&r&'ter #################################### 122
Cormali/e6ouble() ################################# =2
CU,, ######################################################### ?1
&
=penIJ ##################################################### 91
Order type 'onst&nts ################################# 22
=rderClose() ########################################## ?1
=rderCloserice() ########################## ?? 1?;
=rderClose%ime() ############################# ?? ?=
=rderComment() ############################### ?? 1?1
=rder6elete() ######################################### ?=
=rder,ots() ############################################ ??
=rder8a!icCumber() ############################### ??
=rder8odif0() ######################################### 12
=rder=penrice() ############################ ?? 1?;
=rder=pen%ime() ##################################### ??
=rderrofit() ################################# ?1 1?:
=rder+elect() ######################################### ?2
=rder+end() ############################################ 22
=rders?istor0%otal() ########################## 1?9
=rder+top,oss() ##################################### ??
=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 ##################################### 91
rint() ################################################### =1
R
5efresh5ates() ####################################### =?
Rel&tion oper&tors ################################### 101
return oper&tor ######################################## 11
S
S'ripts #################################################### 1=2
Se(i'olon &s e4pression ter(in&tor ############## :
+end8ail() ############################################ 12:
+et;rrow() ############################################ 11;
+et#ndex7uffer() ########################## 101 11;
+et#ndex,abel() ################################### 11;
+et#ndex+t0le() ############################ 101 11;
+et,evel+t0le() ################################### 119
+et,evel9alue() ################################### 119
+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= =1
Stop le%els ################################################ 1<
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 ################################################### 1
Ti', %&lue ################################################# =0
Ti(e )r&(e 'onst&nts ############################## 102
%imeIJ ################################################### 119
%imeCurrent() ####################################### 111
%ime6a0() ############################################## 11=
%ime6a0=fGeek() ################################### 11=
%ime?our() ############################################ 11=
%ime,ocal() ########################################## 111
%ime8inute() ######################################## 11=
%ime8onth() ########################################## 11=
%ime%o+tr() ########################################## 11?
%ime@ear() ############################################ 11=
Toolbo4 "indo" ########################################## <
Tr&iling stops ############################################# ;:
7
C&ri&ble &ssign(ent ################################### 10
C&ri&ble s'ope ########################################### 1?
C&ri&bles ##################################################### 9
void d&t& type #################################### 11 ;=
)
while oper&tor ######################################### ;1

@ear() ################################################### 111


F
Adefine dire'ti%e ###################################### 1=
Aimport dire'ti%e ###################################### 1<
Ainclude dire'ti%e #################################### 1=
Apropert0 cop0ri!ht ############################## 1=
Apropert0 dire'ti%es ################################# 1=
Apropert0 librar0 ################################# :=
Apropert0 link ####################################### 1=

You might also like