Sei sulla pagina 1di 263

MQL4 COURSE

By Coders’ g u ru
w w w . f orex -t sd. c om

-1-
WELCOME
--------------------

Welcome to the MQL4 course.


I n thi s seri es, I w i ll try to stri p the my sti q ue a n d con f usi on f rom MQL4 b y g i v i n g y ou
comp rehen si v e tutori a ls w i th a stra i g ht f orw a rd ex a mp le.

I n thi s seri es of lesson s, I w i ll show y ou how to use the MQL4 f or b ui ld i n g y our ow n


E x p ert Ad v i sors, C ustom I n d i ca tors a n d S cri p ts.

I f y ou a re p rog ra mmi n g i n C (or i ts sup erset C + + ) then y ou k n ow a lot of MQL4 b ef ore


ev en I sta rt my lesson s, i f y ou d i d n ’ t w ri te i n a n y p rog ra mmi n g la n g ua g e b ef ore, n o
p rob lem, I ’ ll g ui d e y ou to un d ersta n d the con cep t of p rog ra mmi n g i n g en era l a s w ell.

S o, let’ s sta rt f rom the b eg i n n i n g .

MQL4? What, Why an d Whe r e ?

MQL4 sta n d s f or Meta Quotes La n g ua g e 4.


Meta Quotes i s the comp a n y w ho b ui lt the Meta Tra d er Tra d i n g P la tf orm.
An d to ma k e i t stron g er tha n the other tra d i n g p la tf orms the comp a n y ex ten d ed i t b y a
b ui lt-i n p rog ra mmi n g la n g ua g e tha t en a b les the user (y ou) to w ri te hi s ow n tra d i n g
stra teg i es.

The la n g ua g e en a b les y ou to crea te on e of the f ollow i n g :

1- E x p ert Ad v i sors.
2- C ustom I n d i ca tors.
3- S cri p ts.

• E x p ert Ad v i sor i s a p rog ra m w hi ch ca n a utoma te tra d i n g d ea ls f or y ou. F or


ex a mp le i t ca n a utoma te y our ma rk et ord ers, stop s ord ers a utoma ti ca lly ,
ca n cels/ rep la ces ord ers a n d ta k es y our p rof i t.

• C ustom I n d i ca tor i s a p rog ra m w hi ch en a b les y ou to use the f un cti on s of the


techn i ca l i n d i ca tors a n d i t ca n n ot a utoma te y our d ea ls.
• S cri p t i s a p rog ra m d esi g n ed f or si n g le f un cti on ex ecuti on .
U n li k e the Ad v i sor, scri p ts a re b ei n g held on ly on ce (on d ema n d ) , a n d n ot b y
ti ck s. An d of course ha s n o access to indicator functions.

These w ere “W ha t” MQL4 i s? “W hy ” to use MQL4?


N ow , “W here” d o I w ri te MQL4?

To w ri te y our MQL4 cod e a n d a s a n y thi n g else i n w orld , y ou ca n choose on e of tw o


w a y s, the ha rd w a y a n d the ea sy w a y .

1- T h e h a r d w a y
The ha rd w a y i s usi n g y our f a v ori te tex t ed i tor a n d the comma n d p romp t to comp i le y our
p rog ra m.
N otep a d i s n ot b a d choi ce, b ut d o n ot f org et tw o thi n g s:
1- To sa v e the f i le y ou ha v e crea ted i n p la i n tex t f orma t.
2- To sa v e the f i le a s .mp 4 (tha t’ s to b e ea sy to reop en i t w i th Meta ed i tor) , b ut y ou
ca n sa v e i t a s a n y ex ten si on y ou p ref er.

Af ter sa v i n g y our p rog ra m there i s a n ex tra step to ma k e y our cod e comes out to the li g ht.
It’s the Compiling step.
C omp i li n g mea n s to con v ert the huma n rea d a b le scri p t tha t y ou ha v e j ust w rote to the
ma chi n e la n g ua g e tha t y our comp uter un d ersta n d s.

Meta Tra d er ha s b een shi p p ed w i th i ts ow n comp i ler (the p rog ra m w hi ch w i ll con v ert
y our scri p t to the ma chi n e la n g ua g e) ca lled Me t a La n g .e x e .

Meta la n g .ex e i s a con sole p rog ra m w hi ch ta k es 2 p a ra meters a n d outp ut a n .ex 4 f i le (the


f i le w hi ch Meta tra d er un d ersta n d s) .
The f i rst p a ra meter i s “op ti on s” p a ra meter a n d the on ly op ti on a v a i la b le i s –q q ui t
The secon d p a ra meter i s the f ull p a th to y our .mq l f i le.

The sy n ta x w i ll b e i n thi s f orma t.


m e ta la n g [ o p t io n s … ] f ile n a m e

E x a mp le
1- F i n d y our meta la n g .ex e p a th, i t w i ll b e the sa me p a th of Meta Tra d er (here my
p a th i s D :\P rog ra m F i les\Meta Tra d er 4)
2- C rea te a b a tch f i le a n d n a me i t comp i le.b a t (or a n y n a me y ou p ref er) .
3- W ri te these li n es i n to the b a t f i le then sa v e i t.
cd D : \P r ogr a m F iles\M eta T r a d er 4
meta la ng -q " D : \P r ogr a m F iles\M eta T r a d er 4 \my _ f ir st_ mq l4 _ scr ipt. mq 4 "
(D on ’ t f org et to cha n g e the p a th to y ou Meta Tra d er i n sta lled p a th)
4- R un the b a tch f i le a n d i f y ou a re luck y p erson li k e me y ou w i ll g et a screen li k e
thi s.
F i g u r e 1 Metalang compiler

As y ou see y ou w i ll g et the outp ut f i le “my _ f i rst_ mq l4_ scri p t.ex 4”

2-T h e e a s y w a y
Meta tra d er ha s b een shi p p ed w i th a g ood I D E (i n teg ra ted d ev elop men t ed i tor) ca lled
Meta E d i tor w hi ch ha s these f ea tures:

1- A tex t ed i tor ha s the f ea ture of hi g hli g hti n g d i f f eren t con structi on s of MQL4
la n g ua g e w hi le y ou a re w ri ti n g / rea d i n g cod e.

2- E a sy to comp i le y our p rog ra m, j ust cli ck F 5 a n d the Meta E d i tor w i ll ma k e a ll the


ha rd w ork f or y ou a n d p rod uces the “ex 4” f i le.
B esi d es i t’ s ea sy to see w ha t the w ron g i n y our p rog ra m i s (i n the E rror Ta b – see
f i g ure 2) .

3- B ui lt-i n a d i cti on a ry b ook w hi ch y ou ca n a ccess b y hi g hli g ht the k ey w ord y ou


w a n t to k n ow f urther a b out i t then p ress F 1.
F i g u r e 2 MetaE d itor 4

I n the comi n g lesson s w e w i ll k n ow more a b out Meta E d i tor.

Tod a y I j ust ca me to sa y hello, tomorrow w e w i ll sta rt the rea l w ork s.


Tomorrow w e w i ll stud y the S y n ta x of MQL4?

I w elcome v ery much the q uesti on s a n d the sug g esti on s.

S ee y ou
C o d e r s’ G u r u
19 -10 -20 0 5
MQL4 COURSE
By Coders’ g u ru
w w w . f orex -t sd. c om

-2-
SYNTAX
--------------------

I hope you enjoyed the “W el c om e” l esson w hi c h tr i ed to a nsw er the v er y b a si c


q uesti ons; what MQ L 4 i s, why MQ L 4 a nd whe r e ( to w r i te) MQ L 4?

Al w a ys the b i g g est a nd the m ost i m por ta nt q uesti on( s) a r e ho w, a nd the enti r e c om i ng


l essons a r e the a nsw er .

N ow , I w a nt you to em pty your m i nd f r om a ny c onf usi on a nd r ea d c a r ef ul l y the nex t f ew


c onc epts.

W e a r e ta l k i ng toda y a b out the S YN T AX r ul es of MQ L 4.


And a s I tol d you b ef or e, If you are programming in C ( or it s superset C + + ) t h en you
k now a l ot of M Q L 4 b efore ev en I st art my l essons.
T ha t’ s b ec a use the synta x of MQ L 4 i s v er y l i k e of the synta x of C .

T he di c ti ona r y m ea ns of the w or d S YN T AX of a pr og r a m m i ng l a ng ua g e i s:
“T h e set of al l ow ed reserv ed w ord s and t h eir paramet ers and t h e c orrec t w ord ord er in
t h e ex pression is c al l ed t h e synt ax of l anguage”. “Wikipedia”

S o, w hen w e a r e studyi ng the synta x of the l a ng ua g e w e a r e studyi ng i ts g r a m m a r a nd


w r i ti ng r ul es w hi c h c onsi st of :
• F or m a t
• C om m ents
• Identi f i er s
• R eser v ed w or ds

L et’ s sl i c e the c a k e.
1- F o r m a t :
W hen you w r i te your c ode, you c a n f r eel y use a ny set of spa c es, ta b s a nd em pty l i nes
you w a nt to sepa r a te your c ode a nd your l i ne of c ode to m a k e them r ea da b l e a nd eyes
pl ea si ng .

F or ex a m pl e a l l of these l i nes a r e v a l i d i n MQ L 4:

doub l e Ma c dC ur r ent, Ma c dP r ev i ous, S i g na l C ur r ent;

doub l e
Ma c dC ur r ent,
Ma c dP r ev i ous,
S i g na l C ur r ent;

doub l e Ma c dC ur r ent, Ma c dP r ev i ous, S i g na l C ur r ent;

B ut, a s you see, the f i r st l i ne i s m or e r ea da b l e a nd ea sy to under sta nd.

And a s ev er ythi ng i n the w or l d ther e a r e ex c epti ons to the r ul e:

1- You c a n’ t use new l i ne i n the “C ontr ol l i ng c om pi l a ti on”


You w i l l k now m or e a b out “C ontr ol l i ng c om pi l a ti on” i n nex t l esson b ut just
r em em b er thi s i s a n ex c epti on.

F or ex a m pl e the nex t l i ne of c ode i s i nv a l i d a nd the MQ L 4 c om pi l er w i l l c om pl a i n:

# pr oper ty
c opyr i g ht " C opyr i g ht © 20 0 4, Meta Q uotes S of tw a r e C or p."

T hi s i s the v a l i d “C ontr ol l i ng c om pi l a ti on”:

# pr oper ty c opyr i g ht " C opyr i g ht © 20 0 4, Meta Q uotes S of tw a r e C or p."

2- You c a n’ t use new l i ne or spa c e i n the m i ddl e of C onsta nt v a l ues, Identi f i er s or


Keyw or ds.

F or ex a m pl e thi s l i ne i s v a l i d:

ex ter n i nt MA_P er i od= 13;


“ex t ren” and “int ” h ere are Keyw ord s , “M A _ P eriod ” is an Id ent ifier and “1 3 ” is a
C onst ant v al ue..
Y ou w il l k now more in t h e nex t l essons.

F or ex a m pl e the nex t l i nes a r e i nv a l i ds:

ex ter n i nt MA_P er i od= 1


3;

ex ter n i nt MA_P er i od= 1 3;

N ot ic e t h e t ab b et w een 1 and 3 .

ex
ter n i nt MA_P er i od= 13;

2- C o m m e n t s :
T o m a k e the pr og r a m m i ng w or l d ea si er , a ny pr og r a m m i ng l a ng ua g e ha s i ts styl e of
w r i ti ng c om m ents.
You use C om m ents to w r i te l i nes i n your c ode w hi c h the c om pi l er w i l l i g nor e then
b ut i t c l ea r s your c ode a nd m a k es i t under sta nda b l e.
Assum e tha t you w r i te a pr og r a m i n the sum m er a nd i n the w i nter you w a nt to r ea d i t.
W i thout c om m ents -ev en you a r e the c ode’ s c r ea tor - you c a n’ t under sta nd a l l these
puz z l ed l i nes.

MQ L 4 ( & C / C + + ) uses tw o k i nds of c om m ents styl es:

1- S i ng l e l i ne c om m ents

T he S i ng l e l i ne c om m ent sta r ts w i th “/ / ” a nd ends w i th the new l i ne.


F or ex a m pl e:

/ / T hi s i s a c om m ent
ex ter n i nt MA_P er i od= 13;

ex ter n i nt MA_P er i od= 13; / / T hi s i s a nother c om m ent


2- Mul ti -l i ne c om m ents

T he m ul ti -l i ne c om m ent sta r t w i th “/ * ” a nd ends w i th “* / ”.


And you c a n c om m ent m or e tha n l i ne or m or e b y putti ng “/ * ” a t the sta r t of the f i r st
l i ne, a nd “* / ” a t the end of the l a st l i ne.
F or ex a m pl e:

/ * thi s
is
m ul ti
l i ne
c om m ent* /

You c a n a l so nest si ng l e l i ne c om m ent i nsi de m ul ti l i nes c om m ent l i k e tha t:

/ * thi s
is
m ul ti / / a nother c om m ent nested her e.
l i ne
c om m ent* /

T hi s i s a v a l i d c om m ent too:

ex ter n i nt / * H E L L O ! I’ m a c om m ent* / MA_P er i od= 13;

B ut thi s i s i nv a l i d c om m ent:

ex ter n i nt / / test MA_P er i od= 13;

3- I d e n t i f i e r s :
An i denti f i er i s the na m e you c hoose to your v a r i a b l es, c onsta nts a nd f unc ti ons.

F or ex a m pl e MA_P er i od her e i s a n i denti f i er :

ex ter n i nt MA_P er i od= 13;


T her e a r e f ew r ul es a nd r estr i c ti ons f or c hoosi ng those na m es:

1- T he l eng th of the Identi f i er m ust not ex c eed 3 1 c ha r a c ter s.

2- T he Identi f i er m ust b eg i n w i th a l etter ( c a pi ta l or sm a l l ) or the under l i ni ng sym b ol


_.
S o, i t c a n’ t b e sta r ted w i th a num b er or a nother sym b ol ex c ept the under l i ni ng
sym b ol .

3- You c a n’ t use a ny r eser v ed w or ds a s a n Identi f i er .


You w i l l see the l i st of the r eser v ed w or ds too soon.

4- T he i denti f i er s’ na m es a r e c a se sensi ti v e.
S o, M A _ P E R I O D not the sa m e a s m a_ p e r i o d or M A _ P e r i o d

L et’ s ta k e som e ex a m pl es:

Nam e 1 V a lid
_ Nam e 1 V a lid
1 Nam e Inv a l i d ( don’ t sta r t w i th num b er )
~ Nam e 1 Inv a l i d ( you c a n onl y use under l i ne sym b ol )
N~ am e 1 Inv a l i d ( you c a n onl y use under l i ne sym b ol )
i_ lo v e
_ m y _ c o u n tr y _ an d _ m y _ c o u n tr y _ l o v e s _ al l _ the _ wo r l d
Inv a l i d ( you c a n’ t ex c eed the 31 c ha r a c ter s l eng th)
C o lo r V a lid
c o lo r Inv a l i d ( you c a n’ t use r ev er sed w or d, a nd c o l o r i s one of them )

4- R e s e r v e d w o r d s :

T her e a r e “w or ds” w hi c h the l a ng ua g e uses them f or spec i f i c a c ti ons.


S o, they a r e r eser v ed to the l a ng ua g e usa g e a nd you c a n’ t use them a s a n i denti f i er
na m e or f or a ny other pur pose.

T hi s i s the l i st of the r eser v ed w or ds ( from t h e M Q L 4 guid e):

Data types M em o r y c l asses O per ato r s O th er


bool e x te rn br e a k f a ls e
c olor s t a t ic c a s e tru e
d a t e t im e c on t i n u e
d ou ble d e f a u lt
in t e ls e
s t r in g f or
v oi d if
re tu rn
s wi t c h
wh i le

F or ex a m pl e the nex t l i nes of c ode a r e i nv a l i d:

ex ter n i nt d ateti m e = 13;


i nt e x te r n = 20 ;
doub l e c o n ti n u e = 0 ;

I hope you enjoyed the l esson.


T he nex t l esson w i l l b e a b out the “D ata T y p e s ”.
S o, B e R ea dy, the r ea l ha r d w or k i s c om i ng !

I w el c om e v er y m uc h the q uesti ons a nd the sug g esti ons.

S ee you
C o d e r s’ G u r u
20 -10 -20 0 5
MQL4 COURSE
By Coders’ g u ru
w w w . f orex -t sd. c om

-3-
DATA TYPES
--------------------

Welcome to my thi rd lesson i n my M Q L 4 cou rse.

I hop e y ou enj oy ed the “ SY N T A X ” lesson, w hi ch tri ed to g i ve y ou the a nsw ers f or:


• W ha t f orma t y ou ca n u se to w ri te M Q L 4 cod e?
• H ow to ma k e the w orld better by commenti ng y ou r cod e?
• W ha t the Id enti f i ers a re, a nd w ha t a re the ru les of choosi ng them?
• W ha t a re the M Q L 4 R eserved w ord s?

If y ou d i d n’ t rea d the “ SY N T A X ” lesson p lea se d ow nloa d i t f rom here:


http :/ / f orex -tsd .com/ a tta chment.p hp ? a tta chmenti d = 39 9
A nd y ou ca n d ow nloa d the “ W elcome” lesson f rom here:
http :/ / f orex -tsd .com/ a tta chment.p hp ? a tta chmenti d = 37 2
Don’t f or g e t to l og i n f i r s t.

N ow , let’ s enjoy the D A T A T Y P E S.

W h a t ’ s t h e D a t a t yp e m ea n?

A ny p rog ra mmi ng la ng u a g e ha s a set of na mes of the memory rep resenta ti on of the d a ta .


F or ex a mp le i f the memory hold s nu mbers betw een -214 7 4 8 36 4 8 to 214 7 4 8 36 4 7 , the
most of the p rog ra mmi ng la ng u a g es w i ll na me thi s d a ta a s “ I nt eg er ” d a ta ty p e.

V a r i a b l es ?

V a ri a bles a re the na mes tha t ref er to secti ons of memory i nto w hi ch d a ta ca n be stored .

T o help y ou thi nk of thi s a s a p i ctu re, i ma g i ne tha t memory i s a seri es of d i f f erent si z e


box es. T he box si z e i s memory stora g e a rea req u i red i n by tes.

• In ord er to u se a box to store d a ta , the box mu st be g i ven a na me; thi s p rocess i s


k now n a s d ec l a r a t i on.
• In the d ecla ra ti on p rocess y ou u se a w ord tell the comp u ter w ha t’ s the k i nd a nd
si z e of the box y ou w a nt to u se, thi s w ord k now n a s k eyw or d .
• It help s i f y ou g i ve a box a mea ni ng f u l na me tha t rela tes to the ty p e of
i nf orma ti on w hi ch ma k e i t ea si er to f i nd the d a ta , thi s na me i s the v a r i a b l e
c ons t a nt .
• D a ta i s p la ced i nto a box by a s s i g ni ng the d a ta to the box .
• W hen w e set the va lu e of the box y ou ha ve crea ted i n the sa me li ne y ou d ecla red
the va ri a ble; thi s p rocess i s k now n a s i ni t i a l i z a t i on.

W hen w e crea te a va ri a ble w e a re telli ng the comp u ter tha t w e w a nt hi m to a ssi g n a


sp eci f i ed memory leng th (i n by tes) to ou r va ri a ble, si nce stori ng a si mp le nu mber, a letter
or a la rg e nu mber i s not g oi ng to occu p y the sa me sp a ce i n memory , so the comp u ter w i ll
a sk u s w ha t’ s the k i nd of d a ta a nd how mu ch the leng th of the d a ta ? T ha t i s the D a ta ty p e
f or.

F or ex a mp le i f w e sa i d thi s li ne of cod e to the comp u ter:

i nt M y V a ra i ble= 0 ;

T ha t’ s mea n w e a re a sk i ng the comp u ter to set a block of 4 by tes leng th to ou r va ri a ble


na med “ M y V a ra i a ble” .

In the p revi ou s ex a mp le w e ha ve u sed :


i nt  Key w ord
i nt  Integ er d a ta ty p e.
i nt  D ecla ra ti on
M yV a r a i b l e  V a ri a ble’ s consta nt.
= 0  Ini ti a li z a ti on

W e w i ll k now more a bou t va ri a bles i n a comi ng lesson.

In M Q L 4 , these a re the k i nd s of D a ta ty p es:

• Integ er (i nt)
• B oolea n (bool)
• C ha ra cter (cha r)
• Stri ng (stri ng )
• F loa ti ng -p oi nt nu mber (d ou ble)
• C olor (color)
• D a teti me (d a teti me)

1- I n t e g e r

A n i nteg er, i s a nu mber tha t ca n sta rt w i th a + or a - si g n a nd i s ma d e of d i g i ts. A nd


i ts ra ng e va lu e i s betw een -214 7 4 8 36 4 8 to 214 7 4 8 36 4 7 .
M Q L 4 p resents the i nteg er i n d eci ma l or hex a d eci ma l f orma t.
F or ex a mp le the nex t nu mbers a re Integ ers:

12, 3, 2134 , 0 , -230


0 x 0 A , 0 x 12, 0 X 12, 0 x 2f , 0 x A 3, 0 X a 3, 0 X 7 C 7

W e u se the k ey w ord i nt to crea te a n i nteg er va ri a ble.

F or ex a mp le:

i nt i ntInteg er = 0 ;
i nt i ntA notherIntg er = -10 0 ;
i nt i ntH ex Intg er= 0 x 12;

De c i m a l a nd H e x a d e c i m a l :

De c i m a l nota ti on i s th e w r i ti ng of nu m b e r s i n th e b a s e of 1 0, a nd u s e s d i g i ts ( 0, 1 , 2 ,
3 , 4 , 5 , 6 , 7 , 8 a nd 9 ) to r e p r e s e nt nu m b e r s . T h e s e d i g i ts a r e f r e q u e ntl y u s e d w i th a
d e c im a l p oi nt w h i c h i nd i c a te s th e s ta r t of a f r a c ti ona l p a r t, a nd w i th one of th e s i g n
s y m b ol s + ( p l u s ) or − ( m i nu s ) to i nd i c a te s i g n.

H e x a d e c i m a l i s a nu m e r a l s y s te m w i th a b a s e of 1 6 u s u a l l y w r i tte n u s i ng th e s y m b ol s
0–9 a nd A –F or a –f .
F or e x a m p l e , th e d e c i m a l nu m e r a l 7 9 c a n b e w r i tte n a s 4 F i n h e x a d e c i m a l .

2- B o o l e a n

B oolea n va ri a ble i s a d a ta ty p e w hi ch ca n hold only tw o va lu es, tru e a nd f a lse (or


thei r nu meri c rep resenta ti on, 0 a nd 1). A nd i t occu p i es 1 bi t of the memory .
In M Q L 4 , f a lse,F A L SE ,F a lse,tru e,T R U E a nd T ru e a re eq u a ls.

B ool e a n na m e d l i k e th i s i n th e h onor of th e g r e a t m a th e m a ti c i a n B ool e G e or g e .

W e u se the k ey w ord b ool to crea te a boolea n va ri a ble.

F or ex a mp le:

bool I = tru e;
bool bF la g = 1;
bool bB ool= F A L SE ;
3- Ch a r a c t e r
M Q L 4 na m e s th i s Da ta ty p e “ L i te r a l ” .
A cha ra cter i s one of 256 d ef i ned a lp ha beti c, nu meri c, a nd sp eci a l k ey elements
d ef i ned i n the A SC II (A meri ca n Sta nd a rd C od e f or Inf orma ti on Intercha ng e) set.
C ha ra cters ha ve i nteg er va lu es corresp ond i ng to loca ti on i n the A SC II set.
Y ou w ri te the cha ra cter consta nt by u si ng si ng le q u otes (') su rrou nd i ng the cha ra cter.

F or ex a mp le:

'a ' , '$ ' , 'Z '

W e u se the k ey w ord i nt to crea te a cha ra cter va ri a ble.

F or ex a mp le:

i nt chrA = 'A ';


i nt chrB = '$ ';

Some cha ra cters ca lled Sp eci a l C ha ra cters ca n’ t p resent d i rectly i nsi d e the si ng le
q u otes beca u se they ha ve a reserved mea ni ng s i n M Q L 4 la ng u a g e.
H ere w e u se somethi ng ca lled E s c a p e S eq u enc e to p resent those sp eci a l cha ra cters,
A nd tha t by p ref i x i ng the cha ra cter w i th the ba ck sla sh cha ra cter (\).

F or ex a mp le:

i nt chrA = '\\'; / / sla sh cha ra cter


i nt chrB = '\n'; / / new li ne

T hi s i s the li st of E sca p e Seq u ence cha ra cters u sed i n M Q L 4 .

ca rri a g e retu rn \r
new li ne \n
hori z onta l ta b \t
reverse sla sh \\
si ng le q u ote \'
d ou ble q u ote \"
hex a d eci ma l A SC II-cod e \x hh
ASCI I t a b l e
Char Dec Oct Hex | Char Dec Oct Hex | Char Dec Oct Hex | Char Dec Oct Hex
-------------------------------------------------------------------------------------
(nul) 0 0000 0x00 | (sp) 32 0040 0x20 | @ 64 0100 0x40 | ` 96 0140 0x60
(soh) 1 0001 0x01 | ! 33 0041 0x21 | A 65 0101 0x41 | a 97 0141 0x61
(stx) 2 0002 0x02 | " 34 0042 0x22 | B 66 0102 0x42 | b 98 0142 0x62
(etx) 3 0003 0x03 | # 35 0043 0x23 | C 67 0103 0x43 | c 99 0143 0x63
(eot) 4 0004 0x04 | $ 36 0044 0x24 | D 68 0104 0x44 | d 100 0144 0x64
(enq) 5 0005 0x05 | % 37 0045 0x25 | E 69 0105 0x45 | e 101 0145 0x65
(ack) 6 0006 0x06 | & 38 0046 0x26 | F 70 0106 0x46 | f 102 0146 0x66
(bel) 7 0007 0x07 | ' 39 0047 0x27 | G 71 0107 0x47 | g 103 0147 0x67
(bs) 8 0010 0x08 | ( 40 0050 0x28 | H 72 0110 0x48 | h 104 0150 0x68
(ht) 9 0011 0x09 | ) 41 0051 0x29 | I 73 0111 0x49 | i 105 0151 0x69
(nl) 10 0012 0x0a | * 42 0052 0x2a | J 74 0112 0x4a | j 106 0152 0x6a
(vt) 11 0013 0x0b | + 43 0053 0x2b | K 75 0113 0x4b | k 107 0153 0x6b
(np) 12 0014 0x0c | , 44 0054 0x2c | L 76 0114 0x4c | l 108 0154 0x6c
(cr) 13 0015 0x0d | - 45 0055 0x2d | M 77 0115 0x4d | m 109 0155 0x6d
(so) 14 0016 0x0e | . 46 0056 0x2e | N 78 0116 0x4e | n 110 0156 0x6e
(si) 15 0017 0x0f | / 47 0057 0x2f | O 79 0117 0x4f | o 111 0157 0x6f
(dle) 16 0020 0x10 | 0 48 0060 0x30 | P 80 0120 0x50 | p 112 0160 0x70
(dc1) 17 0021 0x11 | 1 49 0061 0x31 | Q 81 0121 0x51 | q 113 0161 0x71
(dc2) 18 0022 0x12 | 2 50 0062 0x32 | R 82 0122 0x52 | r 114 0162 0x72
(dc3) 19 0023 0x13 | 3 51 0063 0x33 | S 83 0123 0x53 | s 115 0163 0x73
(dc4) 20 0024 0x14 | 4 52 0064 0x34 | T 84 0124 0x54 | t 116 0164 0x74
(nak) 21 0025 0x15 | 5 53 0065 0x35 | U 85 0125 0x55 | u 117 0165 0x75
(syn) 22 0026 0x16 | 6 54 0066 0x36 | V 86 0126 0x56 | v 118 0166 0x76
(etb) 23 0027 0x17 | 7 55 0067 0x37 | W 87 0127 0x57 | w 119 0167 0x77
(can) 24 0030 0x18 | 8 56 0070 0x38 | X 88 0130 0x58 | x 120 0170 0x78
(em) 25 0031 0x19 | 9 57 0071 0x39 | Y 89 0131 0x59 | y 121 0171 0x79
(sub) 26 0032 0x1a | : 58 0072 0x3a | Z 90 0132 0x5a | z 122 0172 0x7a
(esc) 27 0033 0x1b | ; 59 0073 0x3b | [ 91 0133 0x5b | { 123 0173 0x7b
(fs) 28 0034 0x1c | < 60 0074 0x3c | \ 92 0134 0x5c | | 124 0174 0x7c
(gs) 29 0035 0x1d | = 61 0075 0x3d | ] 93 0135 0x5d | } 125 0175 0x7d
(rs) 30 0036 0x1e | > 62 0076 0x3e | ^ 94 0136 0x5e | ~ 126 0176 0x7e
(us) 31 0037 0x1f | ? 63 0077 0x3f | _ 95 0137 0x5f | (del) 127 0177 0x7f

4- St r i n g
T he stri ng d a ta ty p e i s a n a rra y of cha ra cters enclosed i n d ou ble q u ote (").

T he a rra y of cha ra cters i s a n a rra y w hi ch hold s one cha ra cter a f ter a nother, sta rti ng a t
i nd ex 0 . A f ter the la st cha ra cter of d a ta , a N U L L cha ra cter i s p la ced i n the nex t a rra y
loca ti on. It d oes not ma tter i f there a re u nu sed a rra y loca ti ons a f ter tha t.

A N U L L cha ra cter i s a sp eci a l cha ra cter (rep resented by the A SC II cod e 0 ) u sed to
ma rk the end of thi s ty p e of stri ng .

See f i g u re 1 f or a si mp le rep resenta ti on of the stri ng consta nt “ hello” i n the cha ra cters
a rra y .
F i g u r e 1 – Ch a r a c t e r s a r r a y

M Q L 4 li mi ts the si z e of the stri ng va ri a ble to 255 cha ra cters a nd a ny cha ra cter a bove
255 cha ra cters w i ll g enera te thi s error: (too l ong s tr i ng ( 2 5 5 c h a r a c te r s m a x i m u m ) ).

Y ou ca n u se a ny sp eci a l cha ra cter -menti oned a bove- i n y ou r stri ng consta nt by


p ref i x i ng i t w i th the ba ck sla sh (\).

W e u se the k ey w ord s t r i ng to crea te a stri ng va ri a ble.

F or ex a mp le:

stri ng str1 = "H ello w orld 1, w i th y ou cod ers g u ru ” ;


stri ng str2 = "C op y ri g ht © 20 0 5, \"F orex -tsd f oru m\"."; / / N oti ce the u se of (") cha ra cter.
stri ng str3 = "1234 56 7 8 9 0 ";

5- F l o a t i n g -p o i n t n u m b e r ( d o u b l e )
F loa ti ng p oi nt nu mber i s the R ea l N u mber (tha t i s, a nu mber tha t ca n conta i n a
f ra cti ona l p a rt besi d e the i nteg er p a rt sep a ra ted w i th (.) d ot).E x : 3.0 ,-115.5, 15 a nd
0 .0 0 0 1.

A nd i ts ra ng e va lu e i s betw een 2.2e-30 8 to 1.8 e30 8 .

W e u se the k ey w ord d ou b l e to crea te a f loa ti ng -p oi nt va ri a ble.

F or ex a mp le:

d ou ble d blN u mber1 = 10 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ;


d ou ble d blN u mber3 = 1/ 4 ;
d ou ble d blN u mber3 = 5.7 5;
6- Co l o r
C olor d a ta ty p e i s a sp eci a l M Q L 4 d a ta ty p e, w hi ch hold s a color a p p ea rs on the
M eta T ra d er cha rt w hen y ou crea te y ou r ow n E x p ert A d vi sor or C u stom Ind i ctor a nd
the u ser ca n cha ng e i t f rom the p rop erty ta b of y ou r E x p ert A d vi sor or C u stom
Ind i ctor.

Y ou ca n set the C olor va ri a ble consta nt i n three w a y s:

1- B y t h e c ol or na m e: F or the w ell k now colors (ca lled W eb C olors Set) y ou ca n


a ssi g n the na me of the color to the color va ri a ble, see the li st of the W eb C olors Set.

2- B y C h a r a c t er r ep r es ent a t i on (M Q L 4 na med i t thi s na me): In thi s method y ou u se


the k ey w ord (C ) f ollow ed by tw o si g na l q u ota ti ons ('). B etw een the tw o si g na l
q u ota ti ons y ou set the va lu e of the red , g reen a nd blu e (k now a s R G B va lu e of the
color). T hese va lu es ha ve to be betw een: 0 to 255. A nd y ou ca n w ri te these va lu es i n
d eci ma l or hex a d eci ma l f orma t.

3- B y t h e i nt eg er v a l u e: E very color i n the W eb C olors Set ha s i ts i nteg er va lu e


w hi ch y ou ca n w ri te i t i n d eci ma l or hex a d eci ma l f orma t. A nd y ou ca n a ssi g n the
Integ er va lu e of the color to the color va ri a ble. T he hex a d eci ma l color f orma t look s
li k e thi s: 0 x B B G G R R w here B B i s the blu e va lu e, G G i s g reen va lu e a nd R R i s the
red va lu e.

F or ex a mp le:

/ / sy mbol consta nts


C '128 ,128 ,128 ' / / g ra y
C '0 x 0 0 ,0 x 0 0 ,0 x F F ' / / blu e
/ / na med color
R ed
Y ellow
B la ck
/ / i nteg er-va lu ed rep resenta ti on
0 x F F F F F F / / w hi te
16 7 7 7 215 / / w hi te
0 x 0 0 8 0 0 0 / / g reen
327 6 8 / / g reen

W e u se the k ey w ord c ol or to crea te a color va ri a ble.

F or ex a mp le:

color clr1= R ed ;
color clr1= C '128 ,128 ,128 ' ;
color clr1= 327 6 8 ;

W e b Co l o r s Se t
Black D ar kG r e e n D ar kS lat e G r ay O li v e G re e n T e al N av y P u r p le
M ar o o n I n d ig o M i d n i g h t Blu e D ar kBlu e D ar kO li v e G r e e n S ad d le Br o w n F o re s tG re e n O li v e D r ab
S e aG r e e n D ar kG o ld e n r o d D ar kS lat e Blu e S ie n n a M e d i u m Blu e Br o w n D ar kT u r q u o i s e D i m G r ay
L i g h t S e aG r e e n D ar kV i o le t F i r e Br i ck M e d i u m V i o le t R e d M e d i u m S e aG r e e n C h o co lat e C r im s o n S t e e lBlu e
G o ld e n r o d M e d iu m S p r in g G r e e n L aw n G r e e n C ad e t Blu e D ar kO r ch i d Y e llo w G r e e n L im e G r e e n O r an g e R e d
D ar kO r an g e O r an g e G o ld Y e llo w C h ar t r e u s e L im e S p r in g G r e e n A q u a
D e e p S ky Blu e Blu e M ag e n t a R e d G r ay S lat e G r ay P e r u Blu e V i o le t
L i g h t S lat e G r ay D e e p P in k M e d iu m T u r q u o is e D o d g e r Blu e T u r q u o is e R o y alBlu e S lat e Blu e D ar kK h aki
I n d i an R e d M e d i u m O r ch i d G r e e n Y e llo w M e d i u m A q u am ar i n e D ar kS e aG r e e n T o m at o R o s y Br o w n O r ch i d
M e d i u m P u r p le P ale V i o le t R e d C o r al C o r n f lo w e r Blu e D ar kG r ay S an d y Br o w n M e d i u m S lat e Blu e T an
D ar kS alm o n Bu r ly W o o d H o t P in k S alm o n V i o le t L i g h t C o r al S ky Blu e L i g h t S alm o n
P lu m K h aki L ig h t G r e e n A q u am ar i n e S i lv e r L i g h t S ky Blu e L i g h t S t e e lBlu e L i g h t Blu e
P ale G r e e n T h i s t le P o w d e r Blu e P ale G o ld e n r o d P ale T u r q u o i s e L ig h t G r e y W h e at N av aj o W h i t e
M o ccas i n L ig h t P in k G ai n s b o r o P e ach P u f f P in k Bi s q u e L i g h t G o ld e n R o d Blan ch e d A lm o n d
L e m o n C h if f o n Be i g e A n t iq u e W h it e P ap ay aW h i p C o r n s i lk L i g h t Y e llo w L i g h t C y an L in e n
L av e n d e r M is t y R o s e O ld L ace W h i t e S m o ke S e as h e ll Iv o r y H o n e y d e w A li ce Blu e
L av e n d e r Blu s h M i n t C r e am S n o w W h it e

7- Da t e t i m e

D a teti me d a ta ty p e i s a sp eci a l M Q L 4 d a ta ty p e, w hi ch hold s a d a te a nd ti me d a ta .


Y ou set the D a teti me va ri a ble by u si ng the k ey w ord (D ) f ollow ed by tw o si g na l
q u ota ti ons ('). B etw een the tw o si g na l q u ota ti ons y ou w ri te a cha ra cter li ne consi sti ng
of 6 p a rts f or va lu e of y ea r, month, d a te, hou r, mi nu tes, a nd second s. D a teti me
consta nt ca n va ry f rom J a n 1, 19 7 0 to D ec 31, 20 37 .

F or ex a mp le:

D '20 0 4 .0 1.0 1 0 0 :0 0 ' / / N ew Y ea r


D '19 8 0 .0 7 .19 12:30 :27 '
D '19 .0 7 .19 8 0 12:30 :27 '
D '19 .0 7 .19 8 0 12' / / eq u a l to D '19 8 0 .0 7 .19 12:0 0 :0 0 '
D '0 1.0 1.20 0 4 ' / / eq u a l to D '0 1.0 1.20 0 4 0 0 :0 0 :0 0 '

W e u se the k ey w ord d a t et i m e to crea te a d a teti me va ri a ble.


F or ex a mp le:

d a teti me d tM y B i rthD a y = D '19 7 2.10 .19 12:0 0 :0 0 ';


d a teti me d t1= D '20 0 5.10 .22 0 4 :30 :0 0 ';

I hop e y ou enj oy ed the lesson.

T he nex t lesson w i ll be a bou t the “ O p era ti ons & E x p ressi ons” .

I w elcome very mu ch the q u esti ons a nd the su g g esti ons.

See y ou
C od er s ’ G u r u
22-10 -20 0 5
MQL4 COURSE
By Coders’ g u ru
w w w . f orex -t sd. c om

-4-
Operations & Expressions
--------------------

Welcome to the f ou r th lesson i n my cou r se a b ou t M Q L4.


T he p r ev i ou s lesson “ D a ta T y p es” p r esen ted a lot of n ew con cep ts; I hop e y ou u n d er sta n d
i t, a n d a b ov e a ll y ou enjoyed i t.

Y ou ca n d ow n loa d the p r ev i ou s lesson f r om her e:


http ://f or ex -tsd .com/a tta chmen t.p hp ? a tta chmen ti d =399
http ://f or ex -tsd .com/a tta chmen t.p hp ? a tta chmen ti d =37 2
http ://f or ex -tsd .com/a tta chmen t.p hp ? a tta chmen ti d =469
Don’t forget to login first.

N ow , let’ s en j oy the O p er a ti on s & E x p r essi on s.

W h a t ’ s t h e m ea ni ng of Op er a t i ons & Exp r essi ons?

Y ou kn ow the op er a ti on s v er y w ell. I f I told y ou tha t ( + ,-,*, /) a r e the b a si c a r i thmeti ca l


op er a tor s, y ou w i ll r ememb er v er y f a st w ha t’ s the op er a tor mea n s.

I hea r y ou sa y i n g “ O K , I kn ow the op er a ti on s; cou ld y ou tell me w ha t’ s the mea n i n g of


the ex p r essi on ? ”
I dent i f i er s ( d o y ou r ememb er them? I f n ot, R ev i ew the SY N T AX lesson ) tog ether w i th
the Op er a t i ons p r od u ce the Exp r essi ons.
P u z z led ? Let’ s i llu str a te i t i n a n ex a mp le:

x = ( y *z )/w ;

x,y,z a n d w, her e a r e i dent i f i er s.


=,* a n d / a r e the op er a t or s.
T he w hole li n e i s a n exp r essi on.

W h en th e ex p ressions c om b ined togeth er it m a k es a statement.


A nd w h en th e sta tem ents c om b ined togeth er it m a k es a f u nc ti o n a nd w h en th e fu nc tions
c om b ined togeth er it m a k es a p r o g r am.
I n the r ema i n i n g of thi s lesson w e a r e g oi n g to ta lk a b ou t the ki n d s op er a tor s u sed i n
M Q L4.

So, let’ s sta r t w i th the b a si c a r i thmeti ca l op er a tor s:

1- A r i t h m e t i c a l o p e r a t o r s:

I n M Q L4 ther e a r e 9 Ar i thmeti ca l op er a ti on s
T hi s i s the li st of them w i th the u sa g e of ea ch:

Op er a t or N a m e Exa m p l e D esc r i p t i on
Ad d B to C a n d a ssi g n the r esu lt to
+ Ad d i ti on op er a tor A = B + C;
A.
Su b tr a ct C f r om B a n d a ssi g n the
- Su b tr a cti on op er a tor A = B - C;
r esu lt to A.
C ha n g e the si g n of A f r om p osi ti v e
+- Si g n cha n g er op er a tor s A = -A;
to n eg a ti v e.
M u lti p ly B a n d C a n d a ssi g n the
* M u lti p li ca ti on op er a tor A = B * C;
r esu lt to A.
D i v i d e B on C a n d a ssi g n the r esu lt
/ D i v i si on op er a tor A = B / C;
to A.
A i s the r emi n d er of d i v i si on of B
% M od u lu s op er a tor A =A % C; on C. ( ex : 10 % 2 w i ll p r od u ce 0 ,
10 % 3 w i ll p r od u ce 1).
I n cr ea se A b y 1 ( ex : i f A =1 ma ke
++ I n cr emen t op er a tor A++;
i t 2).
D ecr ea se 1 f r om A ( ex : i f A =2
-- D ecr emen t op er a tor A--;
ma ke i t 1).

N ot e: T he r ema i n d er op er a tor w or ks b y d i v i d i n g the f i r st n u mb er b y the secon d n u mb er


f or the f i r st i n teg er r esu lts a n d then r etu r n s the r ema i n i n g n u mb er .

F or ex a mp le:
10 %5 =0
T hi s i s b eca u se i f y ou d i v i d e 10 b y 5 y ou w i ll g et 2 a n d ther e n o r ema i n i n g v a lu e, so the
r ema i n d er i s 0 .
10 %8 =2
T hi s i s b eca u se i f y ou d i v i d e 10 b y 8 y ou w i ll g et 1 ( 1*8 =8 ), so the r ema i n d er i s ( 10 -8 =
2).
10 0 %15 =10
T hi s i s b eca u se i f y ou d i v i d e 10 0 b y 15 y ou w i ll g et 6 ( 6*15 =90 ), so the r ema i n d er i s
( 10 0 -90 =10 ).
W h a t a b ou t 6 %8 ?
I t w i ll b e 6 b eca u se i f y ou d i v i d e 6 b y 8 y ou w i ll g et 0 ( 8 *0 =0 ), so the r ema i n d er i s ( 6-
0 =6).

N ot e: Y ou ca n ’ t comb i n e the i n cr emen t a n d d ecr emen t op er a tor w i th other ex p r essi on s.


F or ex a mp le y ou ca n ’ t sa y :

A=( B+ + )*5 ;

Bu t y ou ca n w r i te i t li ke tha t:

A+ + ;
B=A*5 ;

N ot e: H ow the a b ov e ex a mp le w or ks? Let’ s a ssu me:


i n t A=1; //set A to 1
i n t B;
A+ + ; //i n cr ea se A b y 1, n ow A=2
B=A*5 ; //w hi ch mea n s B=2*5

2- A ssi g n m e n t o p e r a t o r s:

T he p u r p ose of a n y ex p r essi on i s p r od u ci n g a r esu lt a n d the a ssi g n men t op er a tor s setti n g


the lef t op er a n d w i th thi s r esu lt.

F or ex a mp le:

A=B*C ;

H er e w e mu lti p ly B a n d C a n d a ssi g n the r esu lt to A.


(=) h ere is th e a ssignm ent op era tor.

I n M Q L4 ther e a r e 11 a ssi g n men ts op er a ti on s


T hi s i s the li st of them w i th the u sa g e of ea ch:

Op er a t or N a m e Exa m p l e D esc r i p t i on
= Assi g n men t op er a tor A = B; Assi g n B to A.
Ad d i ti v e Assi g n men t I t’ s eq u a l to: A = A + B; Ad d B to
+= A += B;
op er a tor A a n d a ssi g n the r esu lt to A.
Su b tr a cti v e Assi g n men t I t’ s eq u a l to: A = A - B; Su b tr a ct B
-= A -= B;
op er a tor s f r om A a n d a ssi g n the r esu lt to A.
M u lti p li ca ti v e I t’ s eq u a l to: A = A * B; M u lti p ly
*= A *= B;
Assi g n men t op er a tor A a n d B a n d a ssi g n the r esu lt to A.
D i v i si on a l Assi g n men t I t’ s eq u a l to: A = A / B; D i v i d e A
/= A /= B;
op er a tor on B a n d a ssi g n the r esu lt to A.
I t’ s eq u a l to: A = A % B; G et the
M od u la ti n g Assi g n men t
%= A %= B; r emi n d er of d i v i si on of A on B a n d
op er a tor
a ssi g n the r esu lt to A.
Lef t Shi f t Assi g n men t I t shi f ts the b i ts of A lef t b y the
>>= A >>= B;
op er a tor n u mb er of b i ts sp eci f i ed i n B.
R i g ht Shi f t Assi g n men t I t shi f ts the b i ts of A r i g ht b y the
<<= A <<= B;
op er a tor n u mb er of b i ts sp eci f i ed i n B.
Looks a t the b i n a r y r ep r esen ta ti on
AN D Assi g n men t
&= A &= B; of the v a lu es of A a n d B a n d d oes
op er a tor
a b i tw i se AN D op er a ti on on them.
Looks a t the b i n a r y r ep r esen ta ti on
O R Assi g n men t
|= A |= B; of the v a lu es of A a n d B a n d d oes
op er a tor
a b i tw i se O R op er a ti on on them.
Looks a t the b i n a r y r ep r esen ta ti on
XO R Assi g n men t of the v a lu es of tw o A a n d B a n d
^ = A ^ = B;
op er a tor d oes a b i tw i se ex clu si v e O R
( XO R ) op er a ti on on them.

3- R e l a t i o n a l o p e r a t o r s:

T he r ela ti on a l op er a tor s comp a r e tw o v a lu es ( op er a n d s) a n d r esu lt f a lse or tr u e on ly .


I t’ s i s li ke the q u esti on “ I s J oh n ta ller tha n Al f r ed? Y es / n o? ”
T he r esu lt w i ll b e f a lse on ly i f the ex p r essi on p r od u ce z er o a n d tr u e i f i t p r od u ces a n y
n u mb er d i f f er i n g f r om z er o;

F or ex a mp le:

4 == 4; //tr u e
4 < 4; //f a lse
4 <= 4 //tr u e;

I n M Q L4 ther e a r e 6 R ela ti on a l op er a ti on s
T hi s i s the li st of them w i th the u sa g e of ea ch:
Op er a t or N a m e Exa m p l e D esc r i p t i on
== E q u a l op er a tor A == B; T r u e i f A eq u a ls B else F a lse.
T r u e i f A d oes n ot eq u a l B else
!= N ot E q u a l op er a tor A != B;
F a lse.
< Less T ha n op er a tor s A < B; T r u e i f A i s less tha n B else F a lse.
T r u e i f A i s g r ea ter tha n B else
> G r ea ter T ha n op er a tor A > B;
F a lse.
Less T ha n or E q u a l T r u e i f A i s less tha n or eq u a ls B
<= A <= B;
op er a tor else F a lse.
G r ea ter T ha n or E q u a l T r u e i f A i s g r ea ter tha n or eq u a ls
>= A >= B;
op er a tor B else F a lse.

4- L o g i c a l o p e r a t o r s:
Log i ca l op er a tor s a r e g en er a lly d er i v ed f r om Boolea n a lg eb r a , w hi ch i s a ma thema ti ca l
w a y of ma n i p u la ti n g the tr u th v a lu es of con cep ts i n a n a b str a ct w a y w i thou t b other i n g
a b ou t w ha t the con cep ts a ctu a lly m ea n. T he tr u th v a lu e of a con cep t i n Boolea n v a lu e ca n
ha v e j u st on e of tw o p ossi b le v a lu es: tr u e or f a lse.
M Q L 4 na m es th e L ogic a l op era tors a s B oolea n op era tors

M Q L4 u ses the most i mp or ta n t 3 log i ca l op er a tor s.


T hi s i s the li st of them w i th the u sa g e of ea ch:

Op er a t or N a m e Exa m p l e D esc r i p t i on
I f ei ther of the v a lu es a r e z er o the
v a lu e of the ex p r essi on i s z er o,
other w i se the v a lu e of the
&& AN D op er a tor A && B;
ex p r essi on i s 1. I f the lef t ha n d
v a lu e i s z er o, then the r i g ht ha n d
v a lu e i s n ot con si d er ed .
I f b oth of the v a lu es a r e z er o then
the v a lu e of the ex p r essi on i s 0
other w i se the v a lu e of the
|| O R op er a tor A || B;
ex p r essi on i s 1. I f the lef t ha n d
v a lu e i s n on -z er o, then the r i g ht
ha n d v a lu e i s n ot con si d er ed .
! N O T op er a tor !A; N ot op er a tor i s a p p li ed to a n on -
z er o v a lu e then the v a lu e i s z er o, i f
i t i s a p p li ed to a z er o v a lu e, the
v a lu e i s 1.

5- B i t w i se o p e r a t o r s:
T he b i tw i se op er a tor s a r e si mi la r to the log i ca l op er a tor s, ex cep t tha t they w or k on a
sma ller sca le -- b i n a r y r ep r esen ta ti on s of d a ta .

T he f ollow i n g op er a tor s a r e a v a i la b le i n M Q L4:

Op er a t or N a m e Exa m p l e D esc r i p t i on
C omp a r es tw o b i ts a n d g en er a tes a
& AN D op er a tor A & B; r esu lt of 1 i f b oth b i ts a r e 1;
other w i se, i t r etu r n s 0 .
C omp a r es tw o b i ts a n d g en er a tes a
r esu lt of 1 i f the b i ts a r e
| O R op er a tor A | B;
comp lemen ta r y ; other w i se, i t
r etu r n s 0 .
C omp a r es tw o b i ts a n d g en er a tes a
E XC LU SI V E -O R
^ A ^ B; r esu lt of 1 i f ei ther or b oth b i ts a r e
op er a tor
1; other w i se, i t r etu r n s 0 .
C O M P LE M E N T U sed to i n v er t a ll of the b i ts of the
~ ~A;
op er a tor op er a n d .
M ov es the b i ts to the r i g ht,
d i sca r d s the f a r r i g ht b i t, a n d
T he SH I F T R I G H T
>> A >> B; a ssi g n s the lef tmost b i t a v a lu e of
op er a tor
0 . E a ch mov e to the r i g ht
ef f ecti v ely d i v i d es op1 i n ha lf .
M ov es the b i ts to the lef t, d i sca r d s
the f a r lef t b i t, a n d a ssi g n s the
T he SH I F T LE F T
<< A << B; r i g htmost b i t a v a lu e of 0 . E a ch
op er a tor
mov e to the lef t ef f ecti v ely
mu lti p li es op1 b y 2.

N ot e Both op er a n d s a ssoci a ted w i th the b i tw i se op er a tor mu st b e i n teg er s.


6- O t h e r o p e r a t o r s:
T her e a r e some op er a tor s w hi ch u sed i n M Q L4 a n d d on ’ t b elon g to on e of the p r ev i ou s
ca teg or i es:

1- T he a r r a y i n d ex i n g op er a tor ( [ ] ).
2- T he f u n cti on ca ll op er a tor ( ( ) );
3- T he f u n cti on a r g u men ts sep a r a tor op er a tor -comma ( ,)

W e w i ll kn ow mor e a b ou t the Ar r a y s a n d F u n cti on s i n the n ex t lesson s, so j u st


r ememb er these 3 op er a tor s a s “ O ther op er a tor s”.

O p e r a t o r sP r e c e d e n c e :

I f y ou d on ' t ex p li ci tly i n d i ca te the or d er i n w hi ch y ou w a n t the op er a ti on s i n a comp ou n d


ex p r essi on to b e p er f or med , the or d er i s d eter mi n ed b y the p r eced en ce a ssi g n ed to the
op er a tor s i n u se w i thi n the ex p r essi on . O p er a tor s w i th a hi g her p r eced en ce g et ev a lu a ted
f i r st. F or ex a mp le, the d i v i si on op er a tor ha s a hi g her p r eced en ce tha n d oes the a d d i ti on
op er a tor . T hu s, the tw o f ollow i n g sta temen ts a r e eq u i v a len t:

x + y / 10 0
x + (y / 100) //unambiguous, recommended

W hen w r i ti n g comp ou n d ex p r essi on s, y ou shou ld b e ex p li ci t a n d i n d i ca te w i th


p a r en theses ( ) w hi ch op er a tor s shou ld b e ev a lu a ted f i r st. T hi s p r a cti ce w i ll ma ke y ou r
cod e ea si er to r ea d a n d to ma i n ta i n .

T he f ollow i n g ta b le show s the p r eced en ce a ssi g n ed to the op er a tor s i n the M Q L4. T he


op er a tor s i n thi s ta b le a r e li sted i n p r eced en ce or d er : T he hi g her i n the ta b le a n op er a tor
a p p ea r s, the hi g her i ts p r eced en ce. O p er a tor s w i th hi g her p r eced en ce a r e ev a lu a ted b ef or e
op er a tor s w i th a r ela ti v ely low er p r eced en ce. O p er a tor s on the sa me g r ou p ha v e eq u a l
p r eced en ce. W hen op er a tor s of eq u a l p r eced en ce a p p ea r i n the sa me ex p r essi on , a r u le
mu st g ov er n w hi ch i s ev a lu a ted f i r st. All b i n a r y op er a tor s ex cep t f or the a ssi g n men t
op er a tor s a r e ev a lu a ted f r om lef t to r i g ht. Assi g n men t op er a tor s a r e ev a lu a ted r i g ht to
lef t.

() F u n cti on ca ll F rom left to righ t


[] Ar r a y elemen t selecti on

! N eg a ti on F rom left to righ t


~ Bi tw i se n eg a ti on
- Si g n cha n g i n g op er a ti on

* M u lti p li ca ti on F rom left to righ t


/ D i v i si on
% M od u le d i v i si on

+ Ad d i ti on F rom left to righ t


- Su b tr a cti on

<< Lef t shi f t F rom left to righ t


> > R i g ht shi f t

< Less tha n F rom left to righ t


<= Less tha n or eq u a ls
> G r ea ter tha n
> = G r ea ter tha n or eq u a ls

== E q u a ls F rom left to righ t


! = N ot eq u a l

& Bi tw i se AN D op er a ti on F rom left to righ t

^ Bi tw i se ex clu si v e O R F rom left to righ t

& & Log i ca l AN D F rom left to righ t

|| Log i ca l O R F rom left to righ t

= Assi g n men t F rom righ t to left


+ = Assi g n men t a d d i ti on
-= Assi g n men t su b tr a cti on
*= Assi g n men t mu lti p li ca ti on
/= Assi g n men t d i v i si on
% = Assi g n men t mod u le
> > = Assi g n men t r i g ht shi f t
<<= Assi g n men t lef t shi f t
& = Assi g n men t b i tw i se AN D
|= Assi g n men t b i tw i se O R
^ = Assi g n men t ex clu si v e O R

, C omma F rom left to righ t

I hop e y ou en j oy ed the lesson .


I w elcome v er y mu ch the q u esti on s a n d the su g g esti on s.

See y ou
Coder s’ G u r u
23-10 -20 0 5
MQL4 COURSE
By Coders’ g u ru
www.forex-t sd.c om

-5-
Loops & Decisions
Part 1
----------------------------

We l c om e to th e fifth l e sson in m y c ou r se a b ou t M Q L 4 .

Y ou c a n d ow n l oa d th e p r e v iou sle sson fr om h e re :


h ttp :/ / for e x -tsd .c om / a tta c h m e n t.p h p ? a tta c h m e n tid =3 9 9
h ttp :/ / for e x -tsd .c om / a tta c h m e n t.p h p ? a tta c h m e n tid =3 7 2
h ttp :/ / for e x -tsd .c om / a tta c h m e n t.p h p ? a tta c h m e n tid =4 6 9
h ttp :/ / for e x -tsd .c om / a tta c h m e n t.p h p ? a tta c h m e n tid =4 8 1
Don’t forget to login first.

Th e n or m a l fl ow c on tr ol of th e p r og r a m y ou w r ite in M Q L 4 ( A n d in oth e r s l a n g u a g e s a s
w e l l ) e x e c u te s fr om top to b ottom , A sta te m e n t b y a sta te m e n t.

A sta tem ent is a line of c od e telling th e c om p u ter to d o som eth ing.


F or ex a m p le:
Print("Hello World");
retu rn 0 ;
A sem ic olon a t end of th e sta tem ent is a c ru c ia l p a rt of th e sy nta x b u t u su a lly ea sy to forget,
a nd th a t' s m a k e it th e sou rc e of 9 0 % of errors.

B u t th e top b ottom e x e c u tion is n ot th e on l y c a se a n d it h a s tw o e x c e p tion s,


Th e y a r e th e l oop s a n d th e d e c ision s.

Th e p r og r a m s y ou w r ite l ik e -th e h u m a n - d e c id e s w h a t to d o in r e sp on se of c ir c u m sta n c e s


c h a n g in g . I n th e se c a se s th e fl ow of c on tr ol j u m p s fr om on e p a r t of th e p r og r a m to a n oth e r .
Sta te m e n ts c a u se su c h j u m p s is c a l l e d Con tr ol Sta te m e n ts.
Su c h c on tr ol s c on sist of L oop s a n d D e c ision s.
LOOPS
-----------------

L oop s c a u sin g a se c tion of y ou r p r og r a m to b e r e p e a te d a c e r ta in n u m b e r of tim e s.


A n d th is r e p e tition c on tin u e s w h il e som e c on d ition is tr u e a n d e n d s w h e n it b e c om e s fa l se .
W h e n th e l oop e n d it p a sse s th e c on tr ol to n e x t sta te m e n t fol l ow th e l oop se c tion .

I n M Q L 4 th e r e a r e tw o k in d s of l oop s:

T h e f o r Lo o p
--------------------------

Th e fo r l oop c on sid e r e d th e e a sie st l oop b e c a u se a l l of its c on tr ol e l e m e n ts a r e g a th e r e d in


on e p l a c e .
Th e fo r l oop e x e c u te s a se c tion of c od e a fix e d n u m b e r of tim e s.

F or e x a m p l e :

in t j ;
for ( j =0 ; j < 15 ; j + + )
P r in t( j );

H o w d o e s t h is w o r k ?

Th e fo r sta te m e n t c on sists of fo r k e y w or d , fol l ow e d b y p a r e n th e se s th a t c on ta in th r e e


e x p r e ssion s se p a r a te d b y se m ic ol on s:

fo r ( j= 0 ; j< 15 ; j+ + )

Th e se th r e e e x p r e ssion s a r e th e in it ia l iz a t io n e x p r e ssion , th e t e s t e x p r e ssion a n d th e


in c r e m e n t e x p r e ssion :

j= 0  in itia l iz a tion e x p r e ssion


j< 15  te st e x p r e ssion
J + +  in c r e m e n t e x p r e ssion

Th e b o d y of th e l oop is th e c od e to b e e x e c u te d th e fix e d n u m b e r of th e l oop :

P r in t ( j) ;

T h is ex ec u tes th e b od y of th e loop in ou r ex a m p le for 1 5 tim es.

N o t e : th e fo r sta te m e n t in n ot fol l ow e d b y a se m ic ol on . Th a t' s b e c a u se th e fo r sta te m e n t


a n d th e l oop b od y a r e tog e th e r c on sid e r e d to b e a p r og r a m sta te m e n t.

Th e i n i t i a l i z a t i o n e x p r e s s i o n :
Th e in itia l iz a tion e x p r e ssion is e x e c u te d on l y on c e , w h e n th e l oop fir st sta r ts. A n d its
p u r p ose to g iv e th e l oop v a r ia b l e a n in itia l v a l u e ( 0 in ou r e x a m p l e ).

Y ou c a n d e c l a r e th e l oop v a r ia b l e ou tsid e ( b e for e ) th e l oop l ik e ou r e x a m p l e :

in t j;

O r y ou c a n m a k e th e d e c l a r a tion in sid e th e l oop p a r e n th e se s l ik e th is:

fo r ( in t j= 0 ; j< 15 ; j+ + )

Th e p r e v iou s tw o l in e s of c od e a r e e q u a l , e x c e p t th e S c o p e of e a c h v a r ia b l e ( y ou w il l k n ow
m or e a b ou t th e v a r ia b l e d e c l a r a tion a n d sc op e s in th e V a r ia b l e s l e sson ).
Th e ou tsid e d e c l a r a tion m e th od m a k e s e v e r y l in e in th e c od e b l oc k to k n ow a b ou t th e
v a r ia b l e , w h il e th e in sid e d e c l a r a tion m a k e s on l y th e fo r l oop to k n ow a b ou t th e v a r ia b l e .

Y ou c a n u se m or e th a t on e in itia l iz a tion e x p r e ssion in fo r l oop b y se p a r a tin g th e m w ith


c om m a ( ,) l ik e th is:

in t i;
in t j ;
for ( i=0 ,j =0 ;i< 15 ;i+ + )
P r in t( i);

Th e Te s t e x p r e s s i o n :
Th e te st e x p r e ssion a l w a y s a r e l a tion a l e x p r e ssion th a t u se s r e l a tion a l op e r a tor s ( p l e a se
r e fe r to r e l a tion a l op e r a tor s in th e p r e v iou s l e sson ).

I t e v a l u a te d b y th e l oop e v e r y tim e th e l oop e x e c u te d to d e te r m in e if th e l oop w il l c on tin u e


or w il l stop . I t w il l c on tin u e if th e r e su l t of th e e x p r e ssion is tr u e a n d w il l stop if it fa l se .

I n ou r e x a m p l e th e b o d y l oop w il l c on tin u e p r in tin g i ( P r in t ( i) ) w h il e th e c a se j< 15 is tr u e .


F or e x a m p l e th e j = 0 ,1,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11,12 ,13 a n d 14 .
A n d w h e n j r e a c h e s 15 th e l oop w il l stop s a n d th e c on tr ol p a sse s to th e sta te m e n t fol l ow in g
th e l oop .

Th e I n c r e m e n t e x p r e s s i o n :
Th e in c r e m e n t e x p r e ssion c h a n g e s th e v a l u e of th e l oop v a r ia b l e ( j in ou r e x a m p l e ) b y
in c r e a se it v a l u e b y 1.
I t e x e c u te d a s th e la st ste p in th e l oop ste p s, a fte r in itia l iz in g th e l oop v a r ia b l e , te stin g th e
te st e x p r e ssion a n d e x e c u tin g th e b od y of th e l oop .

F ig u r e 1 sh ow s a fl ow c h a r t of th e fo r l oop .

I n it ia l iz a t io n
e x p r e s s io n

T e s t
E x it
e x p r e s s io n
F a ls e

B o d y o flo o p

In c r e m e n t
e x p r e s s io n

F ig u r e 1 - F l o w c h a r t o f t h e fo r l o o p

L ik e th e in itia l iz a tion e x p r e ssion , in th e in c r e m e n t e x p r e ssion y ou c a n u se m or e th a n on e


in c r e m e n t e x p r e ssion in th e fo r l oop b y se p a r a tin g th e m w ith c om m a ( ,) l ik e th is:

in t i;
in t j ;
for ( i=0 ,j =0 ;i< 15 ,i< ;i+ + ,j + + )
P r in t( i);

B u t y ou c a n on l y u se on e te st e x p r e ssion .
A n oth e r n otic e a b ou t th e in c r e m e n t e x p r e ssion , it’ s n ot on l y c a n in c r e a se th e v a r ia b l e of th e
l oop , b u t it c a n p e r for m a n d op e r a tion it l ik e for e x a m p l e d e c r e m e n ts th e l oop v a r ia b l e l ik e
th is:

in t i;
for ( i=15 ;i> 0 ,i< ;i--)
P r in t( i);

Th e a b ov e e x a m p l e w il l in itia l iz e th e i to 15 a n d sta r t th e l oop , e v e r y tim e it d e c r e a se s i b y


1 a n d c h e c k th e te st e x p r e ssion ( i> 0 ).
Th e p r og r a m w il l p r od u c e th e se r e su l ts: 15 ,14 ,13 ,12 ,11,10 ,9 ,8 ,7 ,6 ,5 ,4 ,3 ,2 ,1.

M u l t i s t a t e m e n t in t h e l o o p b o d y :

I n ou r p r e v iou s e x a m p l e s, w e u se d on l y on e sta te m e n t in th e b od y of th e l oop , th is is n ot


a l w a y s th e c a se .
Y ou c a n u se m u l ti sta te m e n ts in th e l oop b od y d e l im ite d b y b r a c e s l ik e th is:

for ( in t i=1;i< =15 ;i+ + )


{
P r in t( i);
P l a y Sou n d ( " a l e r t.w a v " );
}

I n th e a b ov e c od e th e b od y of th e l oop c on ta in s tw o sta te m e n ts, th e p r og r a m w il l e x e c u te


th e fir st sta te m e n t th e n th e se c on d on e e v e r y tim e th e l oop e x e c u te d .
D on ’ t for g e t to p u t a se m ic ol on a t th e e n d of e v e r y sta te m e n t.

T h e B r e a k S ta te m e n t:

W h e n th e k e y w or d p r e se n ts in th e fo r l oop ( a n d in w h il e l oop a n d s w it c h sta te m e n t a s


w e l l ) th e e x e c u tion of th e l oop w il l te r m in a te a n d th e c on tr ol p a sse s to th e sta te m e n t
fol l ow e d th e l oop se c tion .

F or e x a m p l e :

for ( in t i=0 ;i< 15 ;i+ + )


{
if( ( i==10 )
b re a k ;
P r in t( i);
}

Th e a b ov e e x a m p l e w il l e x e c u te th e l oop u n til i r e a c h e s 10 , in th a t c a se th e b r e a k k e y w or d
w il l te r m in a te th e l oop . Th e c od e w il l p r od u c e th e se v a l u e s: 0 ,1,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 .

T h e C o n t in u e S t a t e m e n t :

Th e b r e a k sta te m e n t ta k e s y ou ou t th e l oop , w h il e th e c on tin u e sta te m e n t w il l g e t y ou b a c k


to th e top of th e l oop ( p a r e n th e se s).
F or e x a m p l e :

for ( in t i=0 ;i< 15 ; i+ + )


{
if( i==10 ) c on tin u e ;
P r in t( i)
}

Th e a b ov e e x a m p l e w il l e x e c u te th e l oop u n til i r e a c h e s 10 , in th a t c a se th e c on tin u e


k e y w or d w il l g e t th e l oop b a c k to th e top of th e l oop w ith ou t p r in tin g i th e te n th tim e . Th e
c od e w il l p r od u c e th e se v a l u e s: 0 ,1,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,11,12 ,13 ,14 .

L a te st n o te :

Y ou c a n l e a v e ou t som e or a l l of th e e x p r e ssion s in fo r l oop if y ou w a n t, for e x a m p l e :


fo r ( ; ; )
Th is l oop is l ik e w h il e l oop w ith a te st e x p r e ssion a l w a y s se t to tr u e .
W e w il l in tr od u c e th e w h il e l oop to y ou r ig h t n ow .

T h e w h i l e Lo o p
---------------------
Th e fo r l oop u su a l l y u se d in th e c a se y ou k n ow h ow m a n y tim e s th e l oop w il l b e e x e c u te d .
W h a t h a p p e n if y ou d on ’ t k n ow h ow m a n y tim e s y ou w a n t to e x e c u te th e l oop ?
Th is th e w h il e l oop is for .

Th e w h il e l oop l ik e th e fo r l oop h a s a Te st e x p r e ssion . B u t it h a sn ’ t I n itia l iz a tion or


I n c r e m e n t e x p r e ssion s.

Th is is a n e x a m p l e :

in t i=0 ;
w h il e ( i< 15 )
{
P r in t( i);
i+ + ;
}

I n th e e x a m p l e y ou w il l n otic e th e fol l ow in g s:

• Th e l oop v a r ia b l e h a d d e c l a r e d a n d in itia l iz e d b e for e th e l oop , y ou c a n n ot d e c l a r e


or in itia l iz e it in sid e th e p a r e n th e se s of th e w h il e l oop l ik e th e fo r l oop .
• Th e i+ + sta te m e n t h e r e is n ot th e in c r e m e n t e x p r e ssion a s y ou m a y th in k , b u t th e
b od y of th e l oop m u st c on ta in som e sta te m e n t th a t c h a n g e s th e l oop v a r ia b l e ,
oth e r w ise th e l oop w ou ld n e v e r e n d .

H o w t h e a b o v e e x a m p le d o e s w o r k ?

Th e w h il e sta te m e n t c on ta in s on l y th e Te st e x p r e ssion , a n d it w il l e x a m in e it e v e r y l oop , if


it’ s tr u e th e l oop w il l c on tin u e , if it’ s fa l se th e l oop w il l e n d a n d th e c on tr ol p a sse s to th e
sta te m e n t fol l ow e d th e l oop se c tion .

I n th e e x a m p l e th e l oop w il l e x e c u te til l i r e a c h e s 16 in th is c a se i< 15 = fa l s e a n d th e l oop


e n d s.

F ig u r e 2 sh ow s a fl ow c h a r t of th e w h il e l oop .

T e s t
E x it
e x p r e s s io n
F a ls e

T r u e

B o d y o flo o p

F ig u r e 2 - F l o w c h a r t o f t h e w h il e l o o p

I tol d y ou b e for e th a t th e w h il e l oop is l ik e th e fo r l oop , th e se a r e th e s im il a r a s p e c t s :


1. Y ou c a n u se b r e a k sta te m e n t a n d c o n t in u e in b oth of th e m .
2 . Y ou c a n sin g le or m u l ti sta te m e n ts in th e b od y of th e l oop in b oth of th e m , in th e
c a se of u sin g m u l ti sta te m e n ts y ou h a v e to d e l im it th e m b y b r a c e s.
3 . Th e sim il a r c op y of fo r ( ; ; ) is w h il e ( t r u e )

I h op e y ou e n j oy e d th e l e sson .
I w e l c om e v e r y m u c h th e q u e stion s a n d th e su g g e stion s.

Se e y ou
C o d e r s’ G u r u
2 4 -10 -2 0 0 5
MQL4 COURSE
By Coders’ guru
w w w . f orex -t sd. c om

-6-
Loops & Decisions
Part 2
----------------------------

We l c o m e t o t h e s ix t h l e s s o n in m y c o u r s e a b o u t M Q L 4 .
I h o pe y o u e n j o y e d t h e pr e v io u s l e s s o n s .

I n t h e pr e v io u s l e s s o n , w e h a v e t a l k e d a b o u t t h e L o o ps .
A n d w e h a v e s e e n t h a t t h e L o o ps a r e o n e o f t w o w a y s w e u s e t o c h a n g e t h e n o r m a l f l o w
o f t h e pr o g r a m e x e c u t io n -f r o m t o p t o b o t t o m . T h e s e c o n d w a y is t h e D e c is io n s .

D e c is io n s in a pr o g r a m c a u s e a o n e -t im e j u m p t o a d if f e r e n t pa r t o f t h e pr o g r a m ,
d e pe n d in g o n t h e v a l u e o f a n e x pr e s s io n .
T h e s e a r e t h e k in d s o f d e c is io n s s t a t e m e n t s a v a il a b l e in M Q L 4 :

The i f S t a t em en t
--------------------------------

T h e i f s t a t e m e n t is t h e s im pl e s t d e c is io n s t a t e m e n t , h e r e ’ s a n e x a m pl e :

if ( x < 10 0 )
P r in t ( " h i" );

H e r e t h e i f k e y w o r d h a s f o l l o w e d b y pa r e n t h e s e s , in s id e t h e pa r e n t h e s e s t h e T e s t
e xp re s s i o n ( x < 1 0 0 ), w h e n t h e r e s u l t o f t e s t e x pr e s s io n is tru e t h e b o d y o f t h e i f w il l
e x e c u t e ( Pri n t( " h i " ) ; ) ,a n d if it is f a l s e , t h e c o n t r o l pa s s e s t o t h e s t a t e m e n t f o l l o w s t h e i f
b lo c k .

Fig u r e 1 s h o w s t h e f l o w c h a r t o f t h e i f s t a t e m e n t :
T e s t F al s e
e xp re s s i o n

T ru e

B o d y o f if

E xi t

F i g u re 1 - F l o w c h art o f th e i f s tate m e n t

M u l ti S tate m e n ts i n th e i f B o d y :

L ik e t h e l o o ps , t h e b o d y o f i f c a n c o n s is t o f m o r e t h a n s t a t e m e n t d e l im it e d b y b r a c e s .

Fo r e x a m pl e :

if ( c u r r e n t _ pr ic e = = s t o p_ l o s e )
{
P r in t ( " y o u h a v e t o c l o s e t h e o r d e r " );
P l a y S o u n d ( " w a r n in g .w a v " );
}

Notice th e s ym b ol == in th e T es t ex p r es s ion ; it' s on e of th e R el a tion a l O p er a tor s you


h a v e s tu d ied in th e l es s on 4 , op er a tion s & ex p r es s ion s .
T h is is a s ou r ce of a l ot of er r or s , w h en you f or g et a n d u s e th e a s s ig n m en t op er a tor = .

N e s ti n g :

T h e l o o ps a n d d e c is io n s t r u c t u r e s c a n b e b a s t e d in s id e o n e a n o t h e r ; y o u c a n n e s t i f s
in s id e l o o ps , l o o ps in s id e i f s , i f s in s id e i f s , a n d s o o n .

H e r e ' s a n e x a m pl e :

f o r ( in t i= 2 ; i< 10 ; i+ + )
if ( i% 2= = 0 )
{
P r in t ( " I t ' s n o t a pr im e n o m b e r " );
P l a y S o u n d ( " w a r n in g .w a v " );
}

I n t h e pr e v io u s e x a m pl e t h e i f s t r u c t u r e n e s t e d in s id e t h e f o r l o o p.

Notice: you w il l n otice th a t th er e a r e n o b r a ces a r ou n d th e l oop b od y, th is is b eca u s e th e


i f s ta tem en t a n d th e s ta tem en ts in s id e its b od y, a r e con s id er ed to b e a s in g l e s ta tem en t.

The i f . . . el s e S t a t em en t
------------------------------------------

T h e if s ta te m e n t l e t 's y o u to d o s o m e t h in g if a c o n d it io n is t r u e , s u ppo s e w e w a n t t o d o
a n o th e r t h in g if it ' s f a l s e . T h a t 's t h e i f ...e ls e s ta te m e n t c o m e s in .
It c o n s is t o f i f s ta te m e n t fo llo w e d b y s ta te m e n t o r a b lo c k o f s ta te m e n ts ,th e n th e e ls e
k e y w o rd fo llo w e d b y a n o th e r s ta te m e n t o r a b lo c k o f s ta te m e n ts .

L ik e t h is e x a m pl e :

if ( c u r r e n t _ pr ic e > s t o p_ l o s e )
P r in t ( " I t ’ s t o o l a t e t o s t o p, pl e a s e s t o p! " );
e ls e
P r in t ( " y o u pl a y in g w e l l t o d a y ! " );

I f t h e t e s t e x pr e s s io n in t h e i f s t a t e m e n t is t r u e , t h e pr o g r a m o n e m e s s a g e , if it is n ’ t t r u e , it
pr in t s t h e o t h e r .

Fig u r e 2 s h o w s t h e f l o w c h a r t o f t h e i f … e ls e s ta te m e n t:
T e s t F al s e
e xp re s s i o n

T ru e

B o d y o f if B o d y o f e ls e

E xi t

F i g u re 2 - F l o w c h art o f th e i f ..e l s e s tate m e n t

N e s te d i f … e l s e S tate m e n ts

Y o u c a n n e s t if … e l s e s t a t e m e n t in if s s t a t e m e n t s , y o u c a n n e s t if … e l s e s t a t e m e n t in
if … e l s e s t a t e m e n t , a n d s o o n .

L ik e t h is :

if ( c u r r e n t _ pr ic e > s t o p_ l o s e )
P r in t ( " It’ s to o la te t o s t o p, pl e a s e s t o p! " );
if ( c u r r e n t _ pr ic e = = s t o p_ l o se )
P r in t ( " It’ s t im e t o s t o p! " );
e ls e
P r in t ( " y o u pl a y in g w e l l t o d a y ! " );

T h e r e ’ s a po t e n t ia l pr o b l e m in n e s t e d if … e l s e s t a t e m e n t s , y o u c a n in a d v e r t e n t l y m a t c h a n
e l s e w it h t h e w r o n g if .

T o s o l v e t h is c a s e y o u c a n d o o n e o f t w o t h in g s :
1- y o u c a n d e l im it e d t h e i f … e l s e pa ir s w it h b r a c e s l ik e t h is :

if ( c u r r e n t _ pr ic e > s t o p_ l o s e )
{
P r in t ( " I t ’ s t o o l a t e t o s t o p, pl e a s e s t o p! " );
if ( c u r r e n t _ pr ic e = = s t o p_ l o s e )
P r in t ( " I t ’ s t im e t o s t o p! " );
e ls e
P r in t ( " y o u pl a y in g w e l l t o d a y ! " );
}

2- I f y o u c a n ’ t d o t h e f ir s t s o l u t io n ( in t h e c a s e o f a l o t o f if … e l s e s t a t e m e n t s o r y o u a r e
l a z y t o d o it ) t a k e it a s r u l e .
M atc h e l s e w i th th e n e are s t i f . ( H e r e it ’ s t h e l in e i f ( c u rre n t_ p ri c e = = s to p _ l o s e ) ).

The s w i t c h S t a t em en t
------------------------------------------

I f y o u h a v e a l a r g e d e c is io n t r e e , a n d a l l t h e d e c is io n s d e pe n d o n t h e v a l u e o f t h e s a m e
v a r ia b l e , y o u c a n u s e a s w it c h s t a t e m e n t h e r e .
H e r e ’ s a n e x a m pl e :

s w it c h (x )
{
c a s e 'A ':
P r in t ( " C A S E A " );
b
re a k ;
c a s e 'B ':
c a s e 'C ':
P r in t ( " C A S E B o r C " );
b re a k ;
d e fa u lt:
P r in t ( " N O T A , B o r C " );
b re a k ;
}

I n t h e a b o v e e x a m pl e t h e s w it c h k e y w o r d is f o l l o w e d b y pa r e n t h e s e s , in s id e t h e
pa r e n t h e s e s y o u ’ l l f in d t h e s w i tc h c o n s tan t, t h is c o n s t a n t c a n b e a n in t e g e r , a c h a r a c t e r
c o n s ta n t o r a c o n sta n t e x pr e s s io n . T h e c o n s t a n t e x pr e s s io n m u s t n ’ t in c l u d e v a r ia b l e f o r
e x a m pl e :
c as e X + Y : is in v a l id s w it c h c o n s t a n t .

H o w th e ab o v e e xam p l e w o rk s ?
T h e s w it c h s t a t e m e n t m a t c h e s t h e c o n s t a n t x w it h o n e o f t h e c as e s c o n s tan ts .
I n t h e c a s e x= = ' A ' t h e pr o g r a m w il l pr in t " C A S E A " a n d t h e b re ak s t a t e m e n t w il l t a k e
y o u t h e c o n t r o l o u t o f t h e s w it c h b l o c k .

I n t h e c a s e s x= = ' B ' o r x= = ' C ' , t h e pr o g r a m w il l pr in t " C A S E B o r C " . T h a t ’ s b e c a u s e


t h e r e ’ s n o b re ak s t a t e m e n t a f t e r c as e ' B ' :.

I n t h e c a s e t h a t x ! = a n y o f t h e c a s e s c o n s t a n t s t h e s w it c h s t a t e m e n t w il l e x e c u t e t h e
d e f au l t c a s e a n d pr in t " N O T A , B o r C " .

F i g u re 3 s h o w s th e f l o w c h art o f th e s w i tc h s tate m e n t
s w i tc h v ari ab l e T ru e
F i rs t c as e b o d y
e q u al s f i rs t
c as e c o n s tan t

F al s e

s w i tc h v ari ab l e T ru e
S e c o n d c as e b o d y
e q u al s s e c o n d
c as e c o n s tan t

F al s e

s w i tc h v ari ab l e T ru e
T h i rd c as e b o d y
e q u al s th i rd
c as e c o n s tan t

F al s e
D e f au l t b o d y

E xi t

F i g u re 3 - F l o w c h art o f th e s w i tc h s tate m e n t

I h o pe y o u e n j o y e d t h e l e s s o n .
I w e l c o m e v e r y m u c h t h e q u e s t io n s a n d t h e s u g g e s t io n s .

S e e y o u
C o d e rs ’ G u ru
25 -10 -20 0 5
MQL4 COURSE
By Coders’ guru
w w w . f orex -t sd. c om

-7-
Functions
-------------------

We lc o m e to th e w o r l d o f M Q L4 F u n c t i o n s .
T h e fu n c tio n s in a n y la n g u a g e ta k e tw o p h a s e s :
Le a r n i n g t h e m w h ic h s o m e tim e s a b o rin g th in g .
U s in g th e m w h ic h a l w a y s a lifeboat.

I w a n t t o t e l l y o u m y t r a di t i o n a l s e n t e n c e :
I h o p e y o u e n j o y e d t h e p r e v i o u s l e s s o n s , w h i c h y o u c a n do w n l o a d t h e m fro m h e re :

1- Le s so n 1 - W e l c o m e t o t h e M Q L4 c o u r se .
h ttp :/ / w w w .f o r e x -t s d.c o m / a t t a c h m e n t .p h p ? a t t a c h m e n t i d= 37 2
2- Le s so n 2–S Y N T A X .
h ttp :/ / w w w .f o r e x -t s d.c o m / a t t a c h m e n t .p h p ? a t t a c h m e n t i d= 39 9
3- Le s so n 3 - M Q L4 D a t a t y p e s .
h ttp :/ / w w w .f o r e x -t s d.c o m / a t t a c h m e n t .p h p ? a t t a c h m e n t i d= 469
4- Le s so n 4 - M Q L4 O p e r a t i o n s & E x p r e s s io n s .
h ttp :/ / w w w .f o r e x -t s d.c o m / a t t a c h m e n t .p h p ? a t t a c h m e n t i d= 48 1
5- Le s so n 5- Lo o p s & D e c i s i o n s ( P a r t 1).
h ttp :/ / w w w .f o r e x -t s d.c o m / a t t a c h m e n t .p h p ? a t t a c h m e n t i d= 50 4
6- Le s so n 6 - Lo o p s & D e c i s i o n s ( P a r t 2).
h ttp :/ / w w w .f o r e x -t s d.c o m / a t t a c h m e n t .p h p ? a t t a c h m e n t i d= 547

Le t ’ s s t a r t t h e s e v e n t h l e s s o n .

W h a t’ s th e m e a ning of f unctions?
T h e fu n c tio n is v e ry lik e th e s a u s a g e m ac h in e, y o u i n p u t t h e m eat a n d t h e sp ic es a n d i t
o u t s t h e sau sag e.
T h e m e a t a n d t h e s p i c e s a r e t h e fu n c tion p ar am eter s; t h e s a u s a g e i s t h e fu n c tion r etu r n
v a l u e . T h e m a c h i n e i t s e l f i s t h e fu n c tion bod y .
T h e r e ’ s o n l y o n e di f f e r e n c e b e t w e e n th e fu n c tio n s a n dy o u r s a u s a g e m a c h in e , s o m e o f
th e fu n c tio n s w ill re tu rn n o th in g (n o th in g i n M Q L4 c a l l e d v oid ).
Le t ’ s t a k e s o m e e x a m p l e s :

do u b l e // ty p e o f th e s a u s a g e –r e tu rn v a lu e
m y _ f u n c ( do u b l e a , do u b l e b , do u b l e c ) / / f u n c t i o n n a m e a n d p a r a m e t e r s l i s t ( m e a t &
s p ic e s )
{
r e t u r n ( a * b + c ); // s a u s a g e o u ts -r e tu r n e dv a lu e
}

A s y o u s e e a b o v e , t h e f u n c t i o n s t a r t s w i t h t h e ty p e o f t h e r e t u r n e d v a l u e “ d ou ble”
f o l l o w e d b y t h e fu n c tion n am e w h i c h f o l l o w e d b y p a r e n t h e s e s .
I n s i de t h e p a r e n t h e s e s y o u p u t t h e m e a t a n d s p i c e s , s o r r y , y o u p u t t h e p ar am eter s o f t h e
fu n c tio n .
H e r e w e h a v e p u t t h r e e p a r a m e t e r s d ou ble a, d ou ble b, d ou ble c .
T h e n t h e f u n c t i o n b o dy s t a r t s a n d e n ds w i t h b r a c e s . I n o u r e x a m p l e t h e f u n c t i o n b o dy w i l l
p r o du c e t h e o p e r a t i o n ( a* b + c ) .
T h e r etu r n k e y w o r d i s r e s p o n s i b l e a b o u t r e t u r n i n g t h e f i n a l r e s u l t .

R e tur n k e y w or d :

T h e r e t u r n k e y w o r d t e r m i n a t e t h e f u n c t i o n ( l i k e t h e br eak k e y w o r d do e s i n t h e l o o p ), a n d
i t g i v e s t h e c o n t r o l t o t h e fu n c tion c aller ( w e w i l l k n o w i t so o n ).
T h e r e t u r n k e y w o r d c a n i n c l u de a n e x p r e s s i o n i n s i de i t s p a r e n th e s e s lik e th e a b o v e
e x a m p l e r etu r n ( a* b + c ) ; a n d t h i s m e a n s t o t e r m i n a t e t h e fu n c tio n a n dre tu rn th e r e s u lt
o f th e e x p re s s io n .
A n dit c a n b e w ith o u t e x p re s s io n a n dits o n ly jo b in th is c a s e is to te r m in a te th e fu n c tio n .

N o t i c e : N o t a l l t h e f u n c t i o n s u s e t h e r e t u r n k e y w o r d, e s p e c i a l l y i f t h e r e ’ s n o r e t u r n v a l u e .
Li k e t h e n e x t e x a m p l e :

v o id // v o idm e a n th e r e ’ s n o s a u s a g e –re tu rn e dv a lu e .
m y _ fu n c ( s tr in g s )// fu n c tio n n a m e a n dp a r a m e te rs lis t ( m e a t & s p ic e s )
{
P r i n t ( s );
}

T h e fu n c tio n a b o v e w i l l n o t r e t u r n v a l u e , b u t i t w i l l p r i n t t h e p a r a m e t e r s y o u p r o v i de d.
W h e n th e fu n c t i o n h a s n o r e t u r n v a l u e y o u u s e “ v oid ” a s t h e f u n c i o t n r e t u r n s t y p e .
T h e se k i n ds o f f u n c t i o n s i n s o m e p r o g r a m m i n g l a n g u a g e c a l l e d “ M eth od s” , b u t M Q L4
c a llin g th e m fu n c tio n s .

Function ca l l :
W e k n o w v e r y w e l l n o w w h a t t h e f u n c t i o n i s ( I h o p e )? H o w t o u s e t h e f u n c t i o n s i n y o u r
M Q L4?
T h e r e ’ s a n e x tr a s te p s a fte r w ritin g y o u r fu n c tio n to u s e th e fu n c tio n in y o u p r o g ra m .
T h i s s t e p i s c allin g it ( u s i n g i t ).

A s s u m e y o u h a v e a fu n c tio n w h ic h c o lle c ts th e s u m m a tio n o f tw o in te g e rs .


T h is is th e fu n c tio n :

i n t c o l l e c t ( i n t f i r s t _ n u m b e r , i n t s e c o n d_ n u m b e r )
{
r e t u r n ( f i r s t _ n u m b e r + s e c o n d_ n u m b e r );
}

Y o u k n o w h o w th e p r e v io u s fu n c tio n w o rk s , b u t y o u w a n t to u s e it.

Y o u u s e it lik e th is :

in t a = 10 ;
in t b = 15;
in t s u m = c ollec t( a , b );
P rin t ( s u m );

T h e e x a m p l e a b o v e w i l l p r i n t 2 5 ( i s i t a m a g i c ). B u t h o w di d i t k n o w ?
T h e m a g i c l i n e i s in t su m = c ollec t( a, b) ; h e r e y o u de c l a r e d a v a r i a b l e ( su m ) t o h o l d t h e
f u n c t i o n r e t u r n v a l u e a n d g a v e t h e f u n c t i o n i t s t w o p a r a m e t e r s ( a, b).
Y o u b a s i c a l l y c alled th e fu n c tion .
M Q L4 w h e n s e e y o u r fu n c tion n am e, i t w i l l t a k e y o u p a r a m e t e r s a n d g o t o t h e f u n c t i o n
a n d i t w i l l r e t u r n –s o o n - w i t h t h e r e s u l t a n d p l a c e t h e m i n s a m e l i n e .
I t’ s v e r y lik e c o p y in g a ll th e lin e s o f th e f u n c tio n in s te a do f th e p la c e y o u c a lle dth e
fu n c tio n in , e a s y r ig h t?

N e sting f unctions insid e f unction:


Y o u c a n n e s t f u n c t i o n ( o r m o r e ) i n s i de t h e b o dy o f a n o t h e r f u n c t i o n . T h a t ’ s b e c a u s e t h e
c a l l e r l i n e i s t r e a t e d l i k e a n y n o r m a l s t a t e m e n t ( i t ’ s a c t u a l l y a s t a t e m e n t ).

F o r e x a m p le :

W e w i l l u s e t h e c o l l e c t f u n c t i o n de s c r i b e d a b o v e i n s i de a n o t h e r n e w f u n c t i o n w h i c h i t s
jo b is p rin tin g th e re s u lt o f th e c o lle c tio n :

v o i d p r i n t _ c o l l e c t i o n ( i n t f i r s t _ n u m b e r , i n t s e c o n d_ n u m b e r )
{
i n t s u m = c o l l e c t ( f i r s t _ n u m b e r , s e c o n d_ n u m b e r );
P r i n t ( s u m );
}

H e r e w e c a l l e d t h e c ollec t f u n c t i o n i n s i de t h e p r in t_ c ollec tion f u n c t i o n b o dy a n d p r i n t e d


t h e r e s u l t . v oid m e a n s t h e r e ’ s n o r e t u r n v a l e ( do y o u s t i l l r e m e m b e r ? ).

M Q L 4 S p e cia l f unctions init( ) , d e init( ) a nd sta r t( ) :


I n M Q L4, e v e r y p r o g ra m b e g in s w ith th e fu n c tio n “ in it( ) ” ( i n i t i a l i z e ) a n d i t o c c u r s
w h e n y o u a tta c h y o u r p r o g r a m ( E x p e r t a dv i s o r o r C u s t o m i n di c a t o r ) t o t h e M e t a T r a de r
c h a rts o r in th e c a s e y o u c h a n g e th e fin a n c ia l s y m b o l o r t h e c h a r t p e r i o di c i t y . A n d i t s
jo b is in itia liz in g th e m a in v a ria b le s o f y o u r p ro g ra m ( y o u w ill k n o w a b o u t th e v a ria b le s
in itia liz a tio n in th e n e x t l e s s o n ).
W h e n y o u r p r o g r a m f i n i s h e s i t s j o b o r y o u c l o s e t h e c h a r t w i n do w o r c h a n g e t h e
f i n a n c i a l s y m b o l o r t h e c h a r t p e r i o di c i t y o r s h u t do w n M e t a T r a de r t e r m i n a l , t h e f u n c t i o n
" d ein it( ) " ( de -i n i t i a l i z e ) w i l l o c c u r .
T h e t h i r d f u n c t i o n ( w h i c h i s t h e m o s t i m p o r t a n t o n e ) “ star t( ) ” w i l l o c c u r e v e r y t i m e
n e w q u o t a t i o n s a r e r e c e i v e d , y o u s p e n d 9 0 o f y o u r p r o g r a m m i n g l i f e i n s i de t h i s
fu n c tio n .
W e w i l l k n o w a l o t a b o u t t h e s e f u n c t i o n s i n o u r r eal w or ld lesson s w h e n w e w r i t e o u r
o w n E x p e r t a dv i s o r a n d C u s t o m I n di c t o r .

I h o p e y o u e n jo y e dth e le s s o n .
I w elc om e v er y m u c h th e q u estion s an d th e su g g estion s.

S e e y o u
C od er s’ G u r u
25-10 -20 0 5
MQL4 COURSE
By Coders’ g u ru
w w w . f orex -t sd. c om

-8-
Variables
--------------------

Welcome to my M Q L 4 v a ri a b les .

I h op e y ou en j oy ed th e p rev i ou s les s on s a n d I h op e y ou a re rea d y f or th e v a ri a b les


ch a llen g e:
I recommen d y ou to rea d th e “ D A T A T YP E S ” les s on b ef ore rea d i n g th i s les s on .
You ca n d ow n loa d i t h ere:
h ttp :/ / f orex -ts d .com/ a tta ch men t.p h p ? a tta ch men ti d = 4 6 9

N ow , let’ s enjoy th e V a ri a b les .

W h at ar e t h e v ar i abl es m ean?

A s I told y ou th e s ecret b ef ore, th e v a ri a b les a re th e n a mes th a t ref er to s ecti on s of


memory i n to w h i ch d a ta ca n b e s tored .

T o h elp y ou th i n k of th i s a s a p i ctu re, i ma g i n e th a t memory i s a s eri es of d i f f eren t s i z e


b ox es . T h e b ox s i z e i s memory s tora g e a rea req u i red i n b y tes .

• In ord er to u s e a b ox to s tore d a ta , th e b ox mu s t b e g i v en a n a me; th i s p roces s i s


k n ow n a s decl ar at i on.
• In th e d ecla ra ti on p roces s y ou u s e a w ord tell th e comp u ter w h a t’ s th e k i n d a n d
s i z e of th e b ox y ou w a n t to u s e, th i s w ord k n ow n a s k eyw or d.
• It h elp s i f y ou g i v e a b ox a mea n i n g f u l n a me th a t rela tes to th e ty p e of
i n f orma ti on w h i ch ma k e i t ea s i er to f i n d th e d a ta , th i s n a me i s th e v ar i abl e
cons t ant .
• D a ta i s p la ced i n to a b ox b y as s i g ni ng th e d a ta to th e b ox .
• W h en w e s et th e v a lu e of th e b ox y ou h a v e crea ted i n th e s a me li n e y ou d ecla red
th e v a ri a b le; th i s p roces s i s k n ow n a s i ni t i al i z at i on.

W h en w e crea te a v a ri a b le w e a re telli n g th e comp u ter th a t w e w a n t h i m to a s s i g n a


s p eci f i ed memory len g th ( i n b y tes ) to ou r v a ri a b le, s i n ce s tori n g a s i mp le n u mb er, a letter
or a la rg e n u mb er i s n ot g oi n g to occu p y th e s a me s p a ce i n memory , s o th e comp u ter w i ll
a s k u s w h a t’ s th e k i n d of d a ta a n d h ow mu ch th e len g th of th e d a ta ? T h a t i s th e D a ta ty p e
f or.

F or ex a mp le i f w e s a i d th i s li n e of cod e to th e comp u ter:

i n t M y V a ra i b le= 0 ;

T h a t’ s mea n w e a re a s k i n g th e comp u ter to s et a b lock of 4 b y tes len g th to ou r v a ri a b le


n a med “ M y V a ra i a b le” .

In th e p rev i ou s ex a mp le w e h a v e u s ed :
i nt  Key w ord
i nt  In teg er d a ta ty p e.
i nt  D ecla ra ti on
M yV ar ai bl e  V a ri a b le’ s con s ta n t.
= 0  In i ti a li z a ti on

W e w i ll k n ow more a b ou t v a ri a b les i n a comi n g les s on .

In M Q L 4 , th es e a re th e k i n d s of D a ta ty p es :

• In teg er ( i n t)
• B oolea n ( b ool)
• C h a ra cter ( ch a r)
• S tri n g ( s tri n g )
• F loa ti n g -p oi n t n u mb er ( d ou b le)
• C olor ( color)
• D a teti me ( d a teti me)

I’ v e cop i ed th e p rev i ou s f ew li n es f rom th e D A T A T YP E S les s on f or y ou . T o k n ow


w h a t’ s th e v a ri a b le, n ow h ow d o to d ecla re th e v a ri a b les :

D ec larat io n :
D ecla ri n g a v a ri a b le mea n s to i n trod u ce i t to th e w orld a n d s p eci f y i ts ty p e. B y u s i n g th e
k eyw or ds y ou h a v e lea rn ed i n th e D A T A T YP E S les s on ( i n t, d ou b le, ch a r, b ool, s tri n g ,
color a n d d a teti me) w i th th e n a me y ou ch os e to th e v a ri a b le.

F or ex a mp le:

i n t M y V a ra i b le;
H ere y ou d ecla red a v a ri a b le n a med M yV ar ai bl e w h i ch i s a n i n teg er ty p e. A n d b ef ore
th e d ecla ra ti on y ou ca n ’ t u s e th e M yV ar i abl e i n y ou r cod e. If y ou u s ed i t w i th ou t
d ecla ra ti on th e M Q L 4 comp i ler w i ll comp la i n a n d w i ll tell y ou s ometh i n g li k e
th i s :' M yV ar ai bl e' -v ar i abl e not def i ned. 1 er r or ( s ) , 0 w ar ni ng ( s ) .

I n it ializ at io n :

In i ti a li z i n g th e v a ri a b le mea n s to a s s i g n a v a lu e to i t, f or ex a mp le M yV ar ai bl e= 0 ;
You ca n i n i ti a li z e th e v a ri a b le a t th e s a me li n e of th e d ecla ra ti on li k e th e ex a mp le:
i nt M yV ar ai bl e= 0 ;

A n d y ou ca n d ecla re th e v a ri a b le i n on e p la ce a n d i n i ti a li z e i t i n a n oth er p la ce li k e th i s :

i n t M y V a ra i b le;


M y V a ra i b le= 5 ;

B u t k eep i n y ou r mi n d th i s f a ct: t h e decl ar at i on m u s t be bef or e t h e i ni t i al i z at i on.

S c o p es o f v ariables:

T h ere a re tw o s cop es of th e v a ri a b les , L oca l a n d G lob a l.

S cop e mea n s , w h i ch p a rt of cod e w i ll k n ow a b ou t th e v a ri a b le a n d ca n u s e i t.

L ocal v ar i abl e mea n s th ey a re n ot s een to ou ts i d e w orld w h ere th ey h a d d ecla red . F or


ex a mp le th e v a ri a b les d ecla red i n s i d e f u n cti on a re loca l to th e f u n cti on b lock of cod e, a n d
th e v a ri a b les d ecla red i n s i d e th e loop or d eci s i on s b lock of cod e a re loca l to th os e b lock s
a n d ca n b e s een or u s ed ou ts i d e th em.

F or ex a mp le:

d ou b le my _ f u n c ( d ou b le a , d ou b le b , d ou b le c)
{
in td ;
retu rn ( a * b + c) ;
}

In th e a b ov e ex a mp le th e v a ri a b les a,b,c a n d d a re loca l v a ri a b les , w h i ch ca n b e u s ed


on ly i n s i d e th e f u n cti on b lock of cod e ( a n y th i n g b es i d e th e b ra ces ) a n d ca n ’ t b e u s ed b y
ou ts i d e cod e. S o w e ca n ’ t w ri te a li n e a f ter th e f u n cti on a b ov e s a y i n g f or ex a mp le: d= 1 0 ;
b eca u s e d i s n ot s een to th e n ex t li n e of th e f u n cti on b eca u s e i t’ s ou ts i d e i t.
T h e s econ d k i n d of th e s cop es i s th e G l obal v ar i abl es , a n d th ey a re th e v a ri a b les w h i ch
h a d d ecla red ou ts i d e a n y b lock of cod e a n d ca n b e s een f rom a n y p a rt of y ou r cod e.

F or ex a mp le:

i n t G lob a l_ V a ri a b le;
d ou b le my _ f u n c ( d ou b le a , d ou b le b , d ou b le c)
{
retu rn ( a * b + c + G lob a l_ V a ri a b le) ;
}

H ere th e v a ri a b le G l obal _ V ar i abl e d ecla red ou ts i d e th e f u n cti on ( f u n cti on lev el


d ecla ra ti on ) s o, i t ca n b e s een b y a ll th e f u n cti on s i n y ou p rog ra m.
T h e G lob a l v a ri a b les w i ll a u toma ti ca lly s et to z er o i f y ou d i d n ’ t i n i ti a li z e th em.

E x t ern v ariables:

T h e k ey w ord “ ex t er n” u s ed to d ecla re a s p eci a l k i n d of v a ri a b les ; th os e k i n d s of


v a ri a b les a re u s ed to d ef i n e i n p u t d a te of th e p rog ra m, w h i ch y ou ca n s et th em f orm th e
p rop erty of y ou r E x p ert a d v i s or or C u s tom i n d i ca tor.

F or ex a mp le:

ex tern color In d i ca tor_ color = C ' 0 x 0 0 ,0 x 0 0 ,0 x F F ' ; / / b lu e


i n t i n i t( )
{
...
}

H ere th e v a ri a b le I ndi cat or _ col or h a d d ef i n ed a s a n ex t er n v a ri a b le w h i ch y ou w i ll s ee


i t th e f i rs t ti me y ou a tta ch y ou r i n d i ca tor ( or E A ) to th e M eta T ra d er ch a rt a n d w h i ch y ou
ca n ch a n g e i t f rom th e p rop erti es s h eet w i n d ow s . L ook a t F i g u re 1 .
F i g u r e 1 : P r op er t y s h eet of M A i ndi cat or

H ere th e v a ri a b les P er i od, S h i f t , M A _ m et h od, A p p l y_ t o a n d S t yl e a re v a ri a b les


d ef i n ed u s i n g th e “ ex t er n” k ey w ord s o th ey a p p ea r i n th e p rop erty s h eet.
A n y v a ri a b le y ou w a n t th e u s er of y ou r p rog ra m b e a b le to ch a n g e a n d s et, ma k e i t
ex tern v a ri a b le.

I h op e y ou en j oy ed th e les s on .

I w el com e v er y m u ch t h e q u es t i ons and t h e s u g g es t i ons .

S ee y ou
C oder s ’ G u r u
2 9 -1 0 -2 0 0 5
MQL4 COURSE
By Coders’ g u ru

-9-
Preprocessors
--------------------

Welcome to my last theoretical lesson i n th i s ser i es.


I n th e n ex t ser i es of lesson s w e w i ll star t to b u i ld ou r f i r st C u stomer I n d i cator ,
S o I r ecommen d you to r ead all th e n i n e lesson s car ef u lly b ef or e th e r eal w or k star ts.

N ow , let’ s en j oy th e P r ep r ocessor s:

W h a t a re t h e Preprocessors m ea n ?

P r ep r ocessor s ar e th e i n str u cti on s you g i v e to th e comp i ler to car r y th em ou t b ef or e


star ti n g ( p r ocessi n g ) you r cod e.
F or ex amp le i f you u sed th e p r ep r ocessor d i r ecti v e # in clu de < w in 3 2 . h> th at’ s mean you
telli n g th e comp i ler to i n clu d e th e con ten t of th e f i le “w in 3 2 . h” i n th e p lace you w r ote
th e i n clu d e k eyw or d b ef or e p r ocessi n g you r cod e.

I n M Q L 4 th er e ar e f ou r of p r ep r ocessor s d i r ecti v es:

1- def in e direct iv e:

def in e d i r ecti v e u sed to g en er ate a con stan t.


Th e con stan t i s v er y li k e th e v ar i ab le w i th on ly on e d i f f er en t, you set i ts v alu e on ly on ce
an d you can n ot ch an g e i ts v alu e i n you r cod e li k e th e v ar i ab le.

F or ex amp le:

# d ef i n e my_ con stan t 1 0 0


A s you can n oti ce i n th e ab ov e ex amp le th er e’ s n o assi g n men t symb ol ( =) b u t on ly sp ace
b etw een th e con stan t n ame ( m y _ con s tan t ) an d i ts v alu e ( 1 0 0 ).
A n d you can n oti ce too th at th e li n e d i d n ’ t en d w i th semi -colon b u t i t en d ed w i th a
car r i ag e-r etu r n ch ar acter ( n ew li n e).

Th e n ame of con stan t ob eys th e same r u les you h ad lear n t ab ou t ch oosi n g th e i d en ti f i er


n ames ( lesson 2 S Y N TA X ), f or ex amp le you can ’ t star t th e con stan t n ame w i th a
n u mb er or ex ceed s 3 1 ch ar acter s.

Th e v alu e of th e con ten t can b e an y typ e you w an t.

Th e comp i ler w i ll r ep lace each occu r r en ce of con stan t n ame i n you r sou r ce cod e w i th
th e cor r esp on d i n g v alu e.
S o you can u se th e ab ov e con stan t i n you r cod e li k e th at:

su m = con stan t1 * 1 0 ;

2- propert y direct iv e:

Th er e ar e p r ed ef i n ed con stan ts called “Con trollin g Com p ilation ” i n clu d ed i n th e


M Q L 4 lan g u ag e, w h i ch you can set th em i n you r p r og r am.
Th ey ar e th e p r op er ti es of you r p r og r am w h i ch you can set th em u si n g th e comp i ler
d i r ecti v e “p rop erty ” an d th e comp i ler w i ll w r i te th em i n th e setti n g s of you r ex ecu tab le
p r og r am ( ex 4 f i le).

F or ex amp le:

# p r op er ty li n k " h ttp :/ / w w w .f or ex -tsd .com"


# p r op er ty cop yr i g h t " A n yon e w an ts to u se"

Th i s i s th e li st of th e M Q L 4 p r ed ef i n ed con stan ts:

C on stan t Typ e D escr i p ti on


li n k str i n g a li n k to th e comp an y w eb si te
cop yr i g h t str i n g th e comp an y n ame
stack si z e in t stack si z e
i n d i cator _ ch ar t_ w i n d ow v oi d sh ow th e i n d i cator i n th e ch ar t w i n d ow
i n d i cator _ sep ar ate_ w i n d ow v oi d sh ow th e i n d i cator i n a sep ar ate w i n d ow
i n d i cator _ b u f f er s in t th e n u mb er of b u f f er s f or calcu lati on , u p to 8
i n d i cator _ mi n i mu m in t th e b ottom b or d er f or th e ch ar t
i n d i cator _ max i mu m in t th e top b or d er f or th e ch ar t
th e color f or d i sp layi n g li n e N , w h er e N li es b etw een
i n d i cator _ color N color
1 an d 8
p r ed ef i n ed lev el N f or sep ar ate w i n d ow cu stom
i n d i cator _ lev elN d ou b le
i n d i cator , w h er e N li es b etw een 1 an d 8
b ef or e scr i p t r u n messag e b ox w i th con f i r mati on
sh ow _ con f i r m v oi d
ap p ear s
b ef or e scr i p t r u n i ts p r op er ty sh eet ap p ear s; d i sab les
sh ow _ i n p u ts v oi d
sh ow _ con f i r m p r op er ty

3- in cl u de direct iv e:

W h en you ask i n g th e comp i ler to i n clu d e a f i le n ame w i th th e “in clu de” d i r ecti v e, i t’ s
v er y li k e w h en you cop y th e en ti r e f i le con ten t an d p aste i t i n th e p lace of th e li n e you
w r i te i n clu d e.

F or ex amp le:

# i n clu d e < w i n 3 2 .h >

I n th e ab ov e ex amp le you telli n g th e comp i ler to op en th e f i le “w in 3 2 . h” an d r ead s all of


i ts con ten t an d cop y th em i n th e same p lace of th e i n clu d e statemen t.

N ote: i n th e ab ov e ex amp le you en closed th e f i le n ame w i th A n g le b r ack ets ( < > ) an d


th at’ s mean you telli n g th e comp i ler to u se th e d ef au lt d i r ector y ( u su ally,
ter mi n al_ d i r ector y\ex p er ts\i n clu d e) to sear ch f or th e f i le w in 3 2 . h an d d on ’ t sear ch th e
cu r r en t d i r ector y.
I f th e f i le you w an t to i n clu d e located at th e same p ath of you r cod e, you h av e to u se
q u otes i n stead of an g le b r ack ets li k e th i s:
# i n clu d e “myli b .h ”

I n th e b oth cases i f th e f i le can ’ t b e f ou n d you w i ll g et an er r or messag e.

Y ou can u se i n clu d e at an yw h er e you w an t b u t i t u su ally u sed at th e b eg i n n i n g of th e


sou r ce cod e.

T ip : It’s a good programming practice to write the f req u entl y u sed code in a separate
f il e and u se incl u de directiv e to pu t it in y ou r code when y ou need ( j u st an adv ice) .

4- im port direct iv e:

I t’ s li k e i n clu d e d i r ecti v e i n th e asp ect of u si n g ou tsi d e f i le i n you r p r og r am.


B u t th er e ar e d i f f er en ces b etw een th em.
Y ou u se im p ort on ly w i th M Q L 4 ex ecu tab les f i les ( .ex 4 ) or li b r ar y f i les ( .d ll) to i mp or t
th ei r f u n cti on s to you r p r og r am.

F or ex amp le:

# i mp or t " u ser 3 2 .d ll"


i n t M essag eB ox A ( i n t h W n d ,str i n g lp Tex t,str i n g lp C ap ti on ,
i n t u Typ e);
i n t M essag eB ox E x A ( i n t h W n d ,str i n g lp Tex t,str i n g lp C ap ti on ,
i n t u Typ e,i n t w L an g u ag eI d );
# i mp or t " meli b .ex 4 "
# i mp or t " g d i 3 2 .d ll"
i n t G etD C ( i n t h W n d );
i n t R eleaseD C ( i n t h W n d ,i n t h D C );
# i mp or t

W h en you i mp or t f u n cti on s f r om “ex 4 ” f i le you h av en ’ t to d eclar e th ei r f u n cti on s to b e


r ead y f or u se.
W h i le i mp or ti n g th e f u n cti on s f r om a “.d ll” f i le r eq u i r es you to d eclar e th e f u n cti on s
you w an t to u se li k e th i s:

i n t M essag eB ox A ( i n t h W n d ,str i n g lp Tex t,str i n g lp C ap ti on ,


i n t u Typ e);

A n d on ly th e f u n cti on s you h as d eclar ed you can u se i n you r cod e.


Y ou mu st en d th e i mp or t d i r ecti v es w i th a b lan k i mp or t li n e # im p ort ( w i th ou t
p ar ameter s).

I h op e you en j oyed th e lesson . A n d I h op e you ar e r ead y n ow f or you r f i r st C u stom


I n d i cator .

I w elcom e v ery m u ch the q u es tion s an d the s u g g es tion s .

S ee you
Coders ’ G u ru
3 0 -1 0 -2 0 0 5
MQL4 COURSE
By Coders’ g u ru

-10-
Your Fi rs t In d i c a t or
P a rt 1
-------------------------------

Welcome t o t h e p r a ct i ca l w or ld of M Q L 4 cour ses; w elcome t o y our f i r st i n d i ca t or i n


M Q L 4.

I r ecommen d y ou t o r ea d t h e p r ev i ous n i n e lesson s v er y ca r ef ully , b ef or e con t i n ui n g w i t h


t h ese ser i es of cour ses, t h a t ’ s b eca use w e w i ll use t h em so much i n our ex p la n a t i on s a n d
st ud i es of t h e E x p er t A d v i sor s a n d Cust om In d i ca t or s w h i ch w e w i ll cr ea t e i n t h i s ser i es
of lesson s.

T od a y w e a r e g oi n g t o cr ea t e a si mp le i n d i ct or w h i ch w i ll n ot mea n t oo much f or our


t r a d e w or ld b ut i t mea n s t oo much t o our M Q L 4 p r og r a mmi n g un d er st a n d i n g .

It si mp ly w i ll collect t h e sub t r a ct i on of High [] of t h e p r i ce – L o w [] of t h e p r i ce; d on ’ t


b e i n a h ur r y , y ou w i ll k n ow ev er y t h i n g v er y soon .

Let’s swim!

MetaEditor:

T h i s i s t h e p r og r a m w h i ch h a s b een sh i p p ed w i t h M T 4 ( M et a T r a d er 4) en a b les y ou t o
w r i t e y our p r og r a ms, r ea d M Q L 4 h elp , comp i le y our p r og r a m a n d M or e.

I’ v e ma d e a sh or t cut f or M et a E d i t or on my d esk t op f or ea si ly a ccess t o t h e p r og r a m.


If y ou w a n t t o r un M et a E d i t or y ou h a v e t h r ee ch oi ces.

1- R un M T 4, t h en cli ck F 4 , ch oose M et a E d i t or f r om T ools men u or cli ck i t s i con on


t h e S t a n d a r d t oolb a r ( F i g ur e 1) .
2- F r om S t a r t men u P r og r a ms, f i n d M et a T r a d er 4 g r oup t h en cli ck M et a E d i t or .
3- F i n d t h e M T 4 i n st a lla t i on p a t h ( usua lly C:\P r og r a m F i les\M et a T r a d er 4) , f i n d t h e
M et a E d i t or .ex e a n d cli ck i t ( I r ecommen d t o ma k e a sh or t cut on y ou d esk t op ) .

Figure 1 – M et a T ra d er S t a n d a rd T o o l b a r
A n y met h od y ou h a v e ch osen lea d s y ou t o M et a E d i t or a s y ou ca n see i n f i g ur e 2.

A s y ou ca n see i n f i g ur e 2, t h er e a r e t h r ee w i n d ow s i n M et a E d i t or :

1- T h e E d i t or w i n d ow w h i ch y ou ca n w r i t e y our p r og r a m i n .
2- T h e T oolb ox w i n d ow w h i ch con t a i n s t h r ee t a b s:
a . E r r or s t a b , y ou see h er e t h e er r or s ( i f t h er e a n y ) i n y our cod e.
b . F i n d i n f i les t a b , y ou see h er e t h e f i les w h i ch con t a i n t h e k ey w or d y ou a r e
sea r ch i n g f or usi n g t h e t oolb a r comma n d “ F i n d i n f i les” or b y cli ck i n g
CT R L + S H IF T + F h ot k ey s.
c. H elp t a b , y ou ca n h i g h li g h t t h e k ey w or d y ou w a n t t o k n ow mor e a b out i t
a n d cli ck F 1, a n d y ou w i ll see t h e h elp t op i cs i n t h i s t a b .
3- T h e N a v i g a t or w i n d ow w h i ch con t a i n s t h r ee t a b s:
a . F i les t a b , f or ea sy a ccess t o t h e f i les sa v ed i n t h e M T 4 f old er .
b . D i ct i on a r y t a b en a b les y ou t o a ccess t h e M Q L 4 h elp sy st em.
c. S ea r ch t a b en a b les y ou t o sea r ch t h e M Q L 4 d i ct i on a r y .

N av ig ator
Editor w in dow W in dow

T ool b ox w in dow

Figure 2 – M et a E d it o r W in d o w s

I r ecommen d y ou t o n a v i g a t e a r oun d t h e M et a E d i t or M en us, T oolb a r a n d w i n d ow s t o b e


f a mi li a r w i t h i t .

N ow let ’ s en j oy cr ea t i n g our f i r st cust om i n d i ca t or .


C us t o m I n d ic a t o r is a p ro gra m w h ic h en a b l es y o u t o us e t h e f un c t io n s o f t h e t ec h n ic a l
in d ic a t o rs a n d it c a n n o t a ut o m a t e y o ur d ea l s .

F irs t th ree s tep s :


N ow y ou h a v e r un y our M et a E d i t or a n d n a v i g a t ed a r oun d i t s M en us, T oolb a r a n d
w i n d ow s, let ’ s U S E i t .

T o cr ea t e a cust om i n d i ca t or y ou h a v e t o st a r t w i t h t h r ee st ep s ( y ou w i ll lea r n la t er h ow t o
sk i p t h ese b or i n g st ep s ( my p er son a l op i n i on ) .

S t e p 1: Cli ck F il e men u  N e w ( y ou use CT R L + N h ot k ey or cli ck t h e N ew Icon i n t h e


S t a n d a r d t oolb a r ) .
Y ou w i ll g et a w i z a r d ( F i g ur e 3) g ui d i n g y ou t o t h e n ex t st ep .
Ch oose Cust om In d i ca t or P r og r a m op t i on , a n d t h en cli ck n ex t .

Figure 3 - N ew p ro j ec t w iz a rd

S t e p 2: W h en y ou cli ck ed N e x t , y ou w i ll g et t h e secon d st ep w i z a r d ( F i g ur e 4) w h i ch
w i ll en a b le y ou t o ed i t t h e p r op er t i es of y our p r og r a m. In t h i s st ep y ou ca n en t er t h ese
p r op er t i es:
1- N a m e of y our p r og r a m, t h i s i s t h e n a me w h i ch t h e w or ld w i ll ca ll y ou p r og r a m
w i t h a n d i t w i ll b e sa v ed a s t he _ n a m e _ y o u _ ha v e _ c ho s e n . m q 4
2- A u t ho r n a me, t h e cr ea t or of t h e p r og r a m n a me.
3- L in k t o y our w eb si t e.
4- E x t e r n a l v a r i a b les li st : I w a n t t o p a use h er e t o r ememb er y ou a b out ex t er n a l
v a r i a b le.
E x t er n a l v a r i a b les a r e t h e v a r i a b les w h i ch w i ll b e a v a i la b le t o t h e user of y ou
i n d i ca t or t o set f r om t h e p r op er t i es t a b of y our i n d i ca t or i n M et a T r a d er . F or
ex a mp le: M A _ P e r io d i n t h e v er y p op ula r E M A i n d i ca t or . A n d t h ese v a r i a b les
w i ll b e d ecla r ed w i t h t h e “ e x t e r n ” k ey w or d i n y our cod e ( P lea se r ev i ew
V a r ia b l e s lesson ) .
S o, t h i s sect i on of t h e w i z a r d en a b les y ou t o a d d t h ese k i n d s of v a r i a b les.

In our f i r st i n d i ca t or ex a mp le w e w i ll n ot n eed a n y ex t er n a l v a r i a b les j ust w r i t e


t h e v a lues y ou see i n f i g ur e 4 a n d let ’ s g o t o st ep 3 b y cli ck i n g N e x t b ut t on .

Figure 4 – P ro gra m p ro p ert ies w iz a rd .

S t e p 3: T h e t h i r d w i z a r d y ou w i ll g et w h en y ou cli ck ed N e x t b ut t on i s t h e D r a w i n g
p r op er t i es w i z a r d ( F i g ur e 5) .
It s j ob i s en a b li n g y ou t o set t h e d a w n i n g p r op er t i es of t h e li n es of y our i n d i ca t or , f or
ex a mp le: h ow ma n y li n es, color s a n d w h er e t o d r a w y our i n d i ca t or ( i n t h e ma i n ch a r t or
i n sep a r a t e w i n d ow s) .
T h i s w i z a r d con t a i n s t h e f ollow i n g op t i on s:

1- In d ic a t o r in s e p a r a t e w in d o w op t i on : b y cli ck i n g t h i s op t i on , y our i n d i ca t or w i ll
b e d r a w n i n sep a r a t e w i n d ow s a n d n ot on t h e ma i n ch a r t w i n d ow . If y ou d i d n ’ t
ch eck t h e op t i on , y our i n d i ca t or w i ll b e d r a w n i n t h e ma i n ch a r t w i n d ow .
2- M in im u m op t i on : i t w i ll b e a v a i la b le ( en a b led ) on ly i f y ou h a v e ch eck ed t h e
In d i ca t or i n sep a r a t e w i n d ow op t i on , a n d i t s j ob i s set t i n g t h e b ot t om b or d er f or
t h e ch a r t .
3- M a x im u m op t i on : i t w i ll b e a v a i la b le ( en a b led ) on ly i f y ou h a v e ch eck ed t h e
In d i ca t or i n sep a r a t e w i n d ow op t i on , a n d i t s j ob i s set t i n g t h e t op b or d er f or t h e
ch a r t
4- In d e x e s L i st : h er e y ou a d d y our i n d i ca t or li n e a n d set i t s d ef a ult color s.

I w a n t y ou t o w a i t t o t h e n ex t lesson ( s) t o k n ow mor e a b out t h ese op t i on s a n d d on ’ t b e i n


a h ur r y .
F or our f i r st i n d i ca t or ex a mp le, ch oose In d i ca t or i n sep a r a t e w i n d ow op t i on a n d cli ck
A d d b ut t on , w h en y ou cli ck a d d b ut t on t h e w i z a r d w i ll a d d a li n e t o t h e i n d ex es li st li k e
y ou see i n f i g ur e 5.

F i g ur e 5 - D r a w i n g p r op er t i es w i z a r d .

W h en y ou cli ck F in is h b ut t on t h e M a g i c w i ll st a r t . Y ou w i ll see t h e w i z a r d d i sa p p ea r ed
a n d t h e f ocus r et ur n ed t o t h e M et a E d i t or en v i r on men t a n d … g uess w h a t ?
Y ou h a v e r ea d y t o use f i r st i n d i ca t or d r a f t cod e.

T h i s i s t h e cod e y ou w i ll g et :

//+------------------------------------------------------------------+
//| My_First_Indicator.mq4 |
//| Codersguru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+
#property copyright "Codersguru"
#property link "http://www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Red
//---- buffers
double ExtMapBuffer1[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,ExtMapBuffer1);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start()
{
int counted_bars=IndicatorCounted();
//----

//----
return(0);
}
//+------------------------------------------------------------------+
A s y ou see i n t h e a b ov e cod e, t h e w i z a r d h a s w r i t t en a lot of cod e f or y ou, n ow I h a v e t o
t h a n k t h e w i z a r d a n d t o t h a n k y ou t oo.

In t h e n ex t lesson w e w i ll d i scov er ev er y li n e of cod e y ou h a v e seen a b ov e a n d a d d our


cod e t o ma k e our f i r st i n d i ca t or . T o t h i s lesson I h op e y ou b e r ea d y !

P lea se d on ’ t f or g et t o d ow n loa d t h e sour ce cod e of t h e f i r st i n d i ca t or a n d w a r m y our self


f or t h e n ex t lesson .

I w e l c o m e v e r y m u c h t he q u e s t io n s a n d t he s u gge s t io n s .

S ee y ou
C o d e r s’ G u r u
0 1-11-20 0 5
MQL4 COURSE
By Coders’ guru
www.forex-tsd.com

-11-
Your First Indicator
Part 2
-------------------------------

Welcome to the second part of “Your First Indicator” lesson.


In the previous lesson we didn’t write any line of code, that’s because the New Project
Wizard wrote all the code for us. Thanks!

Today we are going to add few lines to the code the wizard had generated to make our
program more useful.
Afterwards, we are going to explain the whole of the code line by line.

Let’s coding

Code we have added:

We have added the code which in a bold dark blue to our previous code:

//+------------------------------------------------------------------+
//| My_First_Indicator.mq4 |
//| Codersguru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+
#property copyright "Codersguru"
#property link "http://www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Red

//---- buffers
double ExtMapBuffer1[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,ExtMapBuffer1);
string short_name = "Your first indicator is running!";
IndicatorShortName(short_name);
//----
return(1);
}
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start()
{
int counted_bars=IndicatorCounted();

//---- check for possible errors


if (counted_bars<0) return(-1);
//---- last counted bar will be recounted
if (counted_bars>0) counted_bars--;

int pos=Bars-counted_bars;

double dHigh , dLow , dResult;


Comment("Hi! I'm here on the main chart windows!");

//---- main calculation loop


while(pos>=0)
{
dHigh = High[pos];
dLow = Low[pos];
dResult = dHigh - dLow;
ExtMapBuffer1[pos]= dResult ;
pos--;
}
//----
return(0);
}
//+------------------------------------------------------------------+

How will we work?

We will write the line(s) of the code we are going to explain then we will explain them
afterwards, if there are no topics, we will explain the line(s) of code directly. But at the
most of the time we will pause to discuss some general topics.

I want to here your suggestion about this method please!

Now let’s crack this code line by line.


//+------------------------------------------------------------------+
//| My_First_Indicator.mq4 |
//| Codersguru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+

Comments:
The first five lines of code (which are in gray color) are comments.
You use Comments to write lines in your code which the compiler will ignore them.
You are commenting your code for a lot of reasons:
• To make it clearer
• To document some parts like the copyright and creation date etc.
• To make it understandable.
• To tell us how the code you have written is work.
• …

You can write comments in two ways:

Single line comments: The Single line comment starts with “//” and ends with the new
line.

Multi-line comments: The multi-line comment start with “/*” and ends with “*/” and
you can comment more than one line.

In our program the MQL4 wizard gathered from the data we entered the name of the
program, author and the link and wrote them as comments at the top of our program.

#property copyright "Codersguru"


#property link "http://www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Red

Property directive:

As you notice all of these lines start with the word (#property). That’s because they are
kind of the Preprocessors directives called property directives.

The Preprocessors are the instructions you give to the compiler to carry them out before
starting (processing) your code.
The property directives are predefined constants called “Controlling Compilation”
built in the MQL4 language; their job is setting the properties of your program.
For example: is your Indicator will appear in the main chart window or in a separate
window? Who is the writer of the program?

Note: The preprocessors lines end with a carriage-return character (new line) not a
semi-colon symbol.

We will try to discuss here the property directives available in MQL4.

link:
This property setting the web link to your web site which you asked to enter it in step 2
in the Expert Advisor Wizard (review the previous lesson).
The data type of this property is string.

copyright:
It’s the name of the author of the program, same as the link property you asked to enter
it in step 2 in the Expert Advisor Wizard.
The data type of this property is string.

stacksize:
It’s an integer value sets the memory size for every thread, the default value is 16384.
The data type of this property is integer.

indicator_chart_window:
When you set this property, your indicator will be drawn in the main chart window
(Figure 1). You have to choose one of two options for your Indicators, drawing them in
the main chart windows by using this property, or drawing them in separate windows by
choosing the indicator_separate_window. You can’t use the both of them at the same
time.
The data type of this property is void, which means it takes no value.

indicator_separate_window:
When you set this property, your indicator will be drawn in a separate window (Figure
1). You can set the scale of the separate indicator window using two properties
indicator_minimum for the minimum value and indicator_maximum for the
maximum value of the scale.
And you can set the level of your indicators on these scales using the property
indicator_levelN where’s the N is the indicator number.
Both of the properties indicator_chart_window and indicator_separate_window are
void data type, which mean they don’t take value and you just write them.
In our program we will draw our indicator in a separate window:
#property indicator_separate_window

Main chart window

Separate window

Figure 1

indicator_minimum:
With the aid of this property we are setting the minimum value of the separate windows
scale, which is the bottom border of the windows. For example:
#propery indicator_minimum 0
#propery indicator_ maximum 100
Here we have set the bottom border of the window to 0 and the top border to 100 (see
indicator_ maximum), hence we have a scale ranged from 0 to 100 in our separate
window which we are drawing our indicator.
The data type of this property is integer.

indicator_maximum:
With the aid of this property we are setting the maximum value of the separate windows
scale, which is the top border of the windows.
This value must be greater than the indicator_minimum value.
The data type of this property is integer.
indicator_levelN:
With the aid of this property we are setting the level of the indicator in the scale we have
created with the properties indicator_minimum and indicator_maximum, this value
must be greater than the indicator_minimum value and smaller than the
indicator_maximum value.
N is the indicator number which we are setting its level, it must range from 1 to 8
(because we are allowed only to use up to 8 indicator buffers in our program, so we can
set the indicator_level for each of them using its number). For example:
#propery indicator_minimum 0
#propery indicator_minimum 100
#propery indicator_level1 10 //set the first indicator buffer level
#propery indicator_level2 65.5 //set the second indicator buffer level
The data type of this property is double.

indicator_buffers:
With the aid of this property we are setting the number of memories spaces (Arrays)
allocated to draw our line(s). When we set the number (ranged from 1 up to 8) we are
telling MQL4: “Please allocate a memory space for me to draw my indicator line”.

In our program we used only one buffer.


#property indicator_buffers 1
That’s because we will draw only one line.

indicator_colorN:
We can use up to 8 lines in our indicator, you can set the color of each of them using this
property indicator_colorN , where the N is the line number which defined by
indicator_buffers.
The user of your Indicator can change this color from the properties dialog of your
Indicator (Figure 2).
In our program the indicator line color will be red.
#property indicator_color1 Red
The data type of this property is color.
Figure 2

double ExtMapBuffer1[];

Arrays:

In our life we usually group similar objects into units, in the programming we also need
to group together the data items of the same type. We use Arrays to do this task.
Arrays are very like the list tables, you group the items in the table and access them the
number of the row. Rows in the Arrays called Indexes.

To declare an array you use a code like that:


int my_array[50];
Here, you have declared an array of integer type, which can hold up to 50 items.

You can access each item in the array using the index of the item, like that:
My_array[10] = 500;
Here, you have set the item number 10 in the array to 500.

You can initialize the array at the same line of the declaration like that:
int my_array[5] = {1,24,15,66,500};

In our program we used this line of code:


double ExtMapBuffer1[];
Here we have declared and array of double type. We will use array to calculate our
values which we will draw them on the chart.

int init()
{
}

Special functions:

Functions are blocks of code which like a machine takes inputs and returns outputs
(Please review lesson 7 – Functions).
In MQL4 there are three special functions
init():
Every program will run this function before any of the other functions, you have to put
here you initialization values of you variables.
start():
Here’s the most of the work, every time a new quotation have received your program
will call this function.
deinit():
This is the last function the program will call before it shutdown, you can put here any
removals you want.

SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,ExtMapBuffer1);
string short_name = "Your first indicator is running!";
IndicatorShortName(short_name);

Custom indicator functions:

I can’t give you a description for all of the indicators functions in this lesson. But we
will use them all in our next lessons with more details. So, we will study here the
functions used in our program.

SetIndexStyle:
void SetIndexStyle( int index, int type, int style=EMPTY, int width=EMPTY, color
clr=CLR_NONE)

This function will set the style of the drawn line.

The index parameter of this function ranges from 1 to 7 (that’s because the array
indexing start with 0 and we have limited 8 line). And it indicte which line we want to
set its style.

The type parameter is the shape type of the line and can be one of the following shape
type’s constants:
DRAW_LINE (draw a line)
DRAW_SECTION (draw section)
DRAW_HISTOGRAM (draw histogram)
DRAW_ARROW (draw arrow)
DRAW_NONE (no draw)

The style parameter is the pen style of drawing the line and can be one of the following
styles’ constants:
STYLE_SOLID (use solid pen)
STYLE_DASH (use dash pen)
STYLE_DOT (use dot pen)
STYLE_DASHDOT (use dash and dot pen)
STYLE_DASHDOTDOT (use dash and double dots)
Or it can be EMPTY (default) which means it will be no changes in the line style.

The width parameter is the width of line and ranges from 1 to 5. Or it can be EMPTY
(default) which means the width will not change.

The clr parameter is the color of the line. It can be any valid color type variable. The
default value is CLR_NONE which means empty state of colors.

In our line of code:


SetIndexStyle(0,DRAW_LINE);
We have set the index to 0 which means we will work with the first (and the only) line.
And we have set the shape type of our line to DRAW_LINE because we want to draw a
line in the chart.
And we have left the other parameters to their default values.

SetIndexBuffer:

bool SetIndexBuffer( int index, double array[])

This function will set the array which we will assign to it our indicator value to the
indicator buffer which will be drawn.

The function takes the index of the buffer where’s 0 is the first buffer and 2 is the second,
etc. Then it takes the name of the array.
It returns true if the function succeeds and false otherwise.
In our program the array which will hold our calculated values is ExtMapBuffer1.
And we have only one indicator buffer (#property indicator_buffers 1). So it
will be the buffer assigned.

IndicatorShortName:

void IndicatorShortName( string name)

This function will set the text which will be showed on the upper left corner of the chart
window (Figure 3) to the text we have inputted.
In our program we declared a string variable and assigned the value “You first indicator
is running” to it, then we passed it to the IndicatorShortName function.
string short_name = "Your first indicator is running!";
IndicatorShortName(short_name);
The short name

Figure 3

return(0);

This is the return value of the init() function which terminate the function and pass the
program to the execution of the next function start().

int deinit()
{
//----

//----
return(0);
}

Nothing new to say about deinit() function.

We will continue with remaining of the code in the next lesson.


I hope you enjoyed the lesson and I welcome your questions.

See you
Coders’ Guru
06-11-2005
MQL4 COURSE
By Coders’ guru
www.forex-tsd.com

-12-
Your First Indicator
Part 3
-------------------------------

Welcome to the third part of “Your First Indicator” lesson.


In the previous lesson we studied the code of our first indicator line by line and we
reached the function dinit().

I hope you’ve came from the previous lessons with a clear idea about what we have done.

Today we are going to study start() function and its content. And –finally- we will
compile and run our first Indicator.

Are you ready? Let’s hack the code line by line:

Our Code:
//+------------------------------------------------------------------+
//| My_First_Indicator.mq4 |
//| Codersguru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+
#property copyright "Codersguru"
#property link "http://www.forex-tsd.com"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Red

//---- buffers
double ExtMapBuffer1[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,ExtMapBuffer1);
string short_name = "Your first indicator is running!";
IndicatorShortName(short_name);
//----
return(1);
}
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start()
{
int counted_bars=IndicatorCounted();

//---- check for possible errors


if (counted_bars<0) return(-1);
//---- last counted bar will be recounted
if (counted_bars>0) counted_bars--;

int pos=Bars-counted_bars;

double dHigh , dLow , dResult;


Comment("Hi! I'm here on the main chart windows!");

//---- main calculation loop


while(pos>=0)
{
dHigh = High[pos];
dLow = Low[pos];
dResult = dHigh - dLow;
ExtMapBuffer1[pos]= dResult ;
pos--;
}
//----
return(0);
}
//+------------------------------------------------------------------+

int start()
{...
return(0);
}

As I told you before, we will spend 90% of programming life inside the braces of start()
function. That’s because it’s the most important MQL4 Special functions.

On the contrary of the init() and deinit function, start() will not be called (by the
terminal client) only one time, But every time a new quotation arrives to MetaTrader
terminal client, every time the start() function has been called.
start() function returns an integer value like all of the MQL4 special function, where 0
means no error and any number else means an error has been occurred.

int counted_bars=IndicatorCounted();

Here, we have defined the variable counted_bars as an integer type, and we have
assigned to it the returned value of the function IndicatorCounted().

int IndicatorCounted()
This function will return an integer type value holds the count of the bars which our
indicator has been calculated them.

In the first launch of your indicator this count will be 0 because the indicator didn’t
calculate any bars yet. And after that it will be the count of total bars on the chart -1.
(Please see the function Bars below).

if (counted_bars<0) return(-1);

We have got the number of counted_bars in the previous line of code by using
IndicatorCounted() function.
This number must be 0 or greater if there’s no errors have been occurred. If it’s less than
0 that’s means we have an error and we have to terminate the start() function using the
return statement.

if (counted_bars>0) counted_bars--;

We are checking here if the counted_bars are greater than 0.


If that’s true we decrease this number by subtracting 1 from it.
That’s because we want to recount the last bar again.

We use the decrement operator (please review Lesson 4 - Operations & Expressions) for
decreasing the value of counted_bars by 1.

Note: We can write the expression counted_bars-- like this:

c o u n te d _ b a rs = c o u n t e d _ b a r s -1 ;

int pos=Bars-counted_bars;

Here, we are declaring the variable pos to hold the number of times our calculation loop
will work (see while loop later in this lesson). That’s by subtracting the counted_bars
from the count of total bars on the chart, we get the total bars count using Bars()
function.
It’s a good time to discuss Bars() function and its brother.

Pre-defined MQL4 variables:

Ask, Bid, Bars, Close, Open, High, Low, Time and Volume are functions although
MQL4 called them Pre-defined variables. And I’ll proof to you why they are functions.

Variable means a space in memory and data type you specify.


Function means do something and return some value, For example Bars collects and
returns the number of the bars in chart. So, is it a variable?

Another example will proof for you that they are not variables:
If you type and compile this line of code:

Bars=1;

You will get this error: 'Bars' - unexpected token


That’s because they are not variables hence you can’t assign a value to them.

Another proof, the next line of code is a valid line and will not generate and error in
compiling:

Alert(Bars(1));

You can’t pass parameter to a variable, parameters passed only to the functions.

I’m so sorry for the lengthiness, let’s discuss every function.

int Bars

This function returns an integer type value holds count of the total bars on the current
chart.

double Ask

This function (used in your Expert Advisors) returns a double type value holds the
buyer’s price of the currency pair.

double Bid

This function (used in your Expert Advisor) returns a double type value holds the seller’s
price of the currency pair.
Note: For example, USD/JPY = 133.27/133.32 the left part is called the bid price (that is
a price at which the trader sells), the second (the right part) is called the ask price (the
price at which the trader buys the currency).

double Open[]

This function returns a double type value holds the opening price of the referenced bar.
Where opening price is the price at the beginning of a trade period (year, month, day,
week, hour etc)
For example: Open[0] will return the opening price of the current bar.

double Close[]

This function returns a double type value holds the closing price of the referenced bar.
Where closing price is the price at the end of a trade period
For example: Close[0] will return the closing price of the current bar.

double High[]

This function returns a double type value holds the highest price of the referenced bar.
Where it’s the highest price from prices observed during a trade period.
For example: High [0] will return the highest price of the current bar.

double Low[]

This function returns a double type value holds the lowest price of the referenced bar.
Where it’s the lowest price from prices observed during a trade period.
For example: Low [0] will return the lowest price of the current bar.

double Volume[]

This function returns a double type value holds the average of the total amount of
currency traded within a period of time, usually one day.
For example: Volume [0] will return this average for the current bar.

int Digits

This function returns an integer value holds number of digits after the decimal point
(usually 4).

double Point

This function returns a double value holds point value of the current bar (usually 0.0001.
datetime Time[]

This function returns a datetime type value holds the open time of the referenced bar.
For example: Time [0] will return the open time of the current bar.

double dHigh , dLow , dResult;

We declared three double type variables which we will use them later. Notice the way we
used to declare the three of them at the same line by separating them by coma.

Comment("Hi! I'm here on the main chart windows!");

This line of code uses the Comment function to print the text “Hi! I'm here on the main
chart windows!” on the left top corner of the main chart (figure1).
There are two similar functions:

void Comment( ... )

This function takes the values passed to it (they can be any type) and print them on the
left top corner of the chart (figure 1).
void Print ( ... )

This function takes the values passed to it (they can be any type) and print them to the
expert log (figure 2).

void Alert( ... )

This function takes the values passed to it (they can be any type) and display them in a
dialog box (figure 3)

Figure 1 – Comment
Figure 2- Expert log

Figure 3 - Alerts

while(pos>=0)
{
dHigh = High[pos];
dLow = Low[pos];
dResult = dHigh - dLow;
ExtMapBuffer1[pos]= dResult ;
pos--;
}

Now, it’s the time to enter the loop for calculating our indicator points to draw them.
Any value we assign to the array ExtMapBuffer1[] will be drawn on the chart (because
we have assign this array to the drawn buffer using SetIndexBuffer function).

Before we enter the loop we have got the number of times the loop will work by
subtracting the counted_bars from the total count of the bars on chart.
The number of times the loop will work called Loop variable which it’s pos variable in
our example.

We use the loop variable as a current bar of the calculation for example High[pos] will
return the highest price of the pos bar.

In the loop body we assign to the variable dHigh the value of the highest price of the
current loop variable.
And assign to the variable dLow the value of the lowest price of the current loop
variable.
The result of subtracting dLow from dHigh will be assigned to the variable dResult.

Then we using the dResult to draw or indicator line, by assigning it to the drawn buffer
array ExtMapBuffer1[].

The last line of the loop is a decrement expression which will decrease the loop variable
pos by 1 every time the loop runs. And when this variable reaches -1 the loop will be
terminated.

Finally, we can compile our indicator. Press F5 or choose Compile from file menu.
That will generate the executable file “My_First_indicator.ex4” which you can load in
your terminal client.

To load your indicator click F4 to bring the terminal client. Then From the Navigator
window find the My_First_indicator and attach it to the chart (figure4).

Note: The indicator will not do much, but it believed that the subtraction of the highest
and lowest of the price gives us the market's volatility.

Figure 4 – My_First_Indicator

I hope you enjoyed your first indicator. And be prepared to your first Expert Advisor in
the next lesson(s).

I welcome very much your questions and suggestions.

Coders’ Guru
13-11-2005
MQL4 COURSE
By Coders’ guru
www.forex-tsd.com

-13-
Your First Expert Advisor
Part 1
--------------------

In the previous lesson we created our first indicator. Although this indicator wasn’t
useful for us as trader, but it was very useful for us as programmers.

The indicators –in general- are very important for the technical analysis of the market in
trying to predict the future prices.
But with the indicators we observe the chart then use our hands to sell, buy and modify
our orders manually. You have to set in front of your terminal, and keep your eyes widely
open.

If you get tired, want to drink a cup of tea or even take a short vacation. You have to
consider one of these solutions:

You may rent someone to observe the terminal for you and calling your mobile phone
every five minutes to tell you what’s going on. If this employee is an expert, he will cost
you the pips you earn. And if he is novice one, he will cost you your capital.

The second solution is using a program to automate your trades.


That’s what the Expert Advisor is for.

The Expert advisor is a program wrote in MQL4 (we are studying MQL4 huh?) uses your
favorite indicators and trade methods to automate your orders.
It can buy, sell and modify the orders for you. It enables you to drink a cup of tea and
save the salary you gave out to your employee or the bunch of flowers you bring to your
assistant wife.

Today we are going to create our first expert advisor so let’s go.

First two steps:


Step1:

If you didn’t open your MetaEditor yet, I think it’s the time to run it.
From the MetaEditor File menu click New (you can use CTRL+N hotkey or click the
New icon in the standard toolbar). That will pop up the new program wizard which you
have seen when you created your first indicator (Figure 1).

This time we will choose the first option “Expert Advisor program” then click Next
button.

Figure 1 – the first step wizard

Step2:
When you clicked Next, you have got the general properties wizard (Figure 2).
This wizard enables you to set the properties of your expert advisor and to set the external
variables you will use in your expert advisor.

In this step you can set these properties:

1- Name of your expert advisor, in our sample we will use My_First_EA.


2- Author name of the program, type your name (I typed mine in the sample).
3- Link to your web site.
4- External variables list:

This is the list of the external variables you allow the user of your expert advisor to
change them from the Expert properties window.
To add a new variable you click the Add button, clicking it will add a new record to
the external variables list. Every record has three fields:

Name: double click this field to set the name (identifier) of the variable.
Type: double click this field to set the data type of the variable.
Initial value: double click this field to give your variable initialization value.
This field is optional which means you can leave it without setting

In our sample we have added three variables:

Varaible  Type  initial value


---------------------------------------
TakeProfit  double  350
Lots  double  0.1
TrailingStop  double  35

Figure 2 – the second step wizard

Now click the Finish button to close the wizard, and MetaEditor will bring to you the
code created by the wizard and saves the file My_First_EA.mq4 in the MetaTrader 4
\experts path.

Note: you have to put the expert advisors in MetaTrader 4\experts path and the
indicators in MetaTrader 4\experts\indicators path, otherwise they will not work.
This is the code we have got from the wizard:

//+------------------------------------------------------------------+
//| My_First_EA.mq4 |
//| Coders Guru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+
#property copyright "Coders Guru"
#property link "http://www.forex-tsd.com"

//---- input parameters


extern double TakeProfit=250.0;
extern double Lots=0.1;
extern double TrailingStop=35.0;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+

As you see above, the code generated by the wizard is a template for you to add your code without
bothering you by typing the main functions from scratch.

Now let’s add our own code:

//+------------------------------------------------------------------+
//| My_First_EA.mq4 |
//| Coders Guru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+
#property copyright "Coders Guru"
#property link "http://www.forex-tsd.com"

//---- input parameters


extern double TakeProfit=250.0;
extern double Lots=0.1;
extern double TrailingStop=35.0;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}

int Crossed (double line1 , double line2)


{
static int last_direction = 0;
static int current_dirction = 0;

if(line1>line2)current_dirction = 1; //up
if(line1<line2)current_dirction = 2; //down

if(current_dirction != last_direction) //changed


{
last_direction = current_dirction;
return (last_direction);
}
else
{
return (0);
}
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----
int cnt, ticket, total;
double shortEma, longEma;

if(Bars<100)
{
Print("bars less than 100");
return(0);
}
if(TakeProfit<10)
{
Print("TakeProfit less than 10");
return(0); // check TakeProfit
}

shortEma = iMA(NULL,0,8,0,MODE_EMA,PRICE_CLOSE,0);
longEma = iMA(NULL,0,13,0,MODE_EMA,PRICE_CLOSE,0);

int isCrossed = Crossed (shortEma,longEma);

total = OrdersTotal();
if(total < 1)
{
if(isCrossed == 1)
{

ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,
"My EA",12345,0,Green);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
Print("BUY order opened : ",OrderOpenPrice());
}
else Print("Error opening BUY order : ",GetLastError());
return(0);
}
if(isCrossed == 2)
{

ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,
Bid-TakeProfit*Point,"My EA",12345,0,Red);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
Print("SELL order opened : ",OrderOpenPrice());
}
else Print("Error opening SELL order : ",GetLastError());
return(0);
}
return(0);
}
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
{
if(OrderType()==OP_BUY) // long position is opened
{
// should it be closed?
if(isCrossed == 2)
{
OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet);
// close position
return(0); // exit
}
// check for trailing stop
if(TrailingStop>0)
{
if(Bid-OrderOpenPrice()>Point*TrailingStop)
{
if(OrderStopLoss()<Bid-Point*TrailingStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-
Point*TrailingStop,OrderTakeProfit(),0,Green);
return(0);
}
}
}
}
else // go to short position
{
// should it be closed?
if(isCrossed == 1)
{
OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet);
// close position
return(0); // exit
}
// check for trailing stop
if(TrailingStop>0)
{
if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
{
if((OrderStopLoss()>(Ask+Point*TrailingStop)) ||
(OrderStopLoss()==0))
{

OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,
OrderTakeProfit(),0,Red);
return(0);
}
}
}
}
}
}
return(0);
}
//+------------------------------------------------------------------+
Note: don’t copy and paste the code above because it warped and will not work for you,
use the code provided with lesson in www.forex-tsd.com .

Scared?
Don’t be scared of the 160 lines you have seen above, we will know everything about this
code line by line, I promise it’s an easy task.

Test the Expert Advisor:

Before studying our expert advisor code we have to be check is it profitable one or not.

Note: Our expert advisor will work with EURUSD pairs in 4 Hours timeframe.
So compile the expert advisor by pressing F5 and load it in MetaTrader.

You can test your expert advisor using two methods:

1- Live trading

In live trading testing the results are more accurate but you have to spend days (and
maybe months) to know is the expert advisor profitable or not.

You have to enable the expert advisor to automate your trades.


To enable it click Tools  Option menu (or use CTRL+O hotkey), that’s will bring
the Options windows (figure 3), click Expert Advisors tab and enable these options:

Enable Expert Advisors


Allow live trading

And click Ok button


Figure 3 – Enabling expert advisor auto trade

You will see the Smile symbol beside the expert advisor name which means your expert
advisor is working and ready to trade for you (Figure 4).

Figure 4 – Expert advisor is enabled

2- Strategy Tester:

The second method of testing your expert advisor which is less accurate but will not take
time is the Strategy tester. We will know everything about Strategy tester later, let’s now
bring its window by pressing F6 (Figure 5).
When you get the window enter these options:

Symbol: EURUSD.
Period: H4 (4 Hours).
Model: Open price only.
Figure 5 – Strategy tester window

Now click Start button to start testing the expert advisor.

You will see a progress bar and the two tabs (Settings and Journal) became five tabs.
We interested in Report tab (Figure 6); click it to see your profit.

We have a lot to say and to do in the next lesson; I hope you are ready for the challenge.
I welcome very much the questions and the suggestions.

See you
Coders’ Guru
24-11-2005
MQL4 COURSE
By Coders’ guru
www.forex-tsd.com

-14-
Your First Expert Advisor
Part 2
--------------------

Welcome to the second part of creating Your First Expert Advisor lesson.
In the previous part we have taken the code generated by the new program wizard and
added our own code which we are going to crack it today line by line.

Did you wear your coding gloves? Let’s crack.

Note: I have to repeat that our expert advisor is for educational purpose only and will
not (or aimed to) make profits.

The code we have:


//+------------------------------------------------------------------+
//| My_First_EA.mq4 |
//| Coders Guru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+
#property copyright "Coders Guru"
#property link "http://www.forex-tsd.com"

//---- input parameters


extern double TakeProfit=250.0;
extern double Lots=0.1;
extern double TrailingStop=35.0;
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}

int Crossed (double line1 , double line2)


{
static int last_direction = 0;
static int current_direction = 0;

if(line1>line2)current_direction = 1; //up
if(line1<line2)current_direction = 2; //down

if(current_direction != last_direction) //changed


{
last_direction = current_direction;
return (last_direction);
}
else
{
return (0);
}
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----

int cnt, ticket, total;


double shortEma, longEma;

if(Bars<100)
{
Print("bars less than 100");
return(0);
}
if(TakeProfit<10)
{
Print("TakeProfit less than 10");
return(0); // check TakeProfit
}

shortEma = iMA(NULL,0,8,0,MODE_EMA,PRICE_CLOSE,0);
longEma = iMA(NULL,0,13,0,MODE_EMA,PRICE_CLOSE,0);

int isCrossed = Crossed (shortEma,longEma);

total = OrdersTotal();
if(total < 1)
{
if(isCrossed == 1)
{

ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,
"My EA",12345,0,Green);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
Print("BUY order opened : ",OrderOpenPrice());
}
else Print("Error opening BUY order : ",GetLastError());
return(0);
}
if(isCrossed == 2)
{

ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,
Bid-TakeProfit*Point,"My EA",12345,0,Red);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES))
Print("SELL order opened : ",OrderOpenPrice());
}
else Print("Error opening SELL order : ",GetLastError());
return(0);
}
return(0);
}
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL && OrderSymbol()==Symbol())
{
if(OrderType()==OP_BUY) // long position is opened
{
// should it be closed?
if(isCrossed == 2)
{
OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet);
// close position
return(0); // exit
}
// check for trailing stop
if(TrailingStop>0)
{
if(Bid-OrderOpenPrice()>Point*TrailingStop)
{
if(OrderStopLoss()<Bid-Point*TrailingStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-
Point*TrailingStop,OrderTakeProfit(),0,Green);
return(0);
}
}
}
}
else // go to short position
{
// should it be closed?
if(isCrossed == 1)
{
OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet);
// close position
return(0); // exit
}
// check for trailing stop
if(TrailingStop>0)
{
if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
{
if((OrderStopLoss()>(Ask+Point*TrailingStop)) ||
(OrderStopLoss()==0))
{

OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,
OrderTakeProfit(),0,Red);
return(0);
}
}
}
}
}
}
return(0);
}
//+------------------------------------------------------------------+

The idea behind our expert advisor.


Before digging into cracking our code we have to explain the idea behind our expert
advisor. Any expert advisor has to decide when to enter the market and when to exit.
And the idea behind any expert advisor is what the entering and exiting conditions are?
Our expert advisor is a simple one and the idea behind it is a simple too, let’s see it.

We use two EMA indicators, the first one is the EMA of 8 days (sort EMA) and the
second one is the EMA of 13 days (long EMA).

Note: using those EMAs or any thought in this lesson is not a recommendation of mine,
they are for educational purpose only.

Entering (Open):
Our expert advisor will enter the market when the short EMA line crosses the long
EMA line, the direction of each lines will determine the order type:
If the short EMA is above the long EMA will buy (long).
If the short EMA is below the long EMA we will sell (short).
We will open only one order at the same time.

Exiting (Close):
Our expert advisor will close the buy order when the short EMA crosses the long EMA
and the short EMA is below the long EMA.
And will close the sell order when the short EMA crosses the long EMA and the short
EMA is above the long EMA.

Our order (buy or sell) will automatically be closed too when the Take profit or the Stop
loss points are reached.

Modifying:

Beside entering (opening) and exiting (closing) the market (positions) our expert advisor
has the ability to modify existing positions based on the idea of Trailing stop point.
We will know how we implemented the idea of Trialing stop later in this lesson.

Now let’s resume our code cracking.

//---- input parameters


extern double TakeProfit=250.0;
extern double Lots=0.1;
extern double TrailingStop=35.0;

In the above lines we have asked the wizard to declare three external variables (which
the user can set them from the properties window of our expert advisor).
The three variables are double data type. We have initialized them to default values (the
user can change these values from the properties window, but it recommended to leave
the defaults).

I have to pause again to tell you a little story about those variables.

Stop loss:

It’s a limit point you set to your order when reached the order will be closed, this is
useful to minimize your lose when the market going against you.
Stop losses points are always set below the current asking price on a buy or above the
current bid price on a sell.

Trailing Stop

It’s a kind of stop loss order that is set at a percentage level below (for a long position) or
above (for a short position) the market price. The price is adjusted as the price fluctuates.
We will talk about this very important concept later in this lesson.
Take profit:

It’s similar to stop lose in that it’s a limit point you set to your order when reached the
order will be closed

There are, however, two differences:

• There is no “trailing” point.


• The exit point must be set above the current market price, instead of below.

Figure 1 – Setting Stop loss and Take profit points

int Crossed (double line1 , double line2)


{
static int last_direction = 0;
static int current_direction = 0;

if(line1>line2)current_direction = 1; //up
if(line1<line2)current_direction = 2; //down

if(current_direction != last_direction) //changed


{
last_direction = current_direction;
return (last_direction);
}
else
{
return (0);
}

}
As I told you before, the idea behind our expert advisor is monitor the crossing of the
short EMA and the long EMA lines. And getting the direction of the crossing (which line
is above and which line is below) which will determine the type of the order (buy, sell,
buy-close and sell-close).

For this goal we have created the Crossed function.

The Crossed function takes two double values as parameters and returns an integer.
The first parameter is the value of the first line we want to monitor (the short EMA in our
case) and the second parameter is the value of the second we want to (the long EMA).

The function will monitor the two lines every time we call it by saving the direction of
the two lines in static variables to remember their state between the repeated calls.

• It will return 0 if there’s no change happened in the last directions saved.


• It will return 1 if the direction has changed (the lines crossed each others) and the
first line is above the second line.
• It will return 2 if the direction has changed (the lines crossed each others) and the
first line is below the second line.

Note: You can use this function in your coming expert advisor to monitor any two lines
and get the crossing direction.

Let’s see how did we write it?

int Crossed (double line1 , double line2)

The above line is the function declaration, it means we want to create Crossed function
which takes two double data type parameters and returns an integer.

When you call this function you have to pass to it two double parameters and it will
return an integer to you.

You have to declare the function before using (calling) it. The place of the function
doesn't matter, I placed it above start() function, but you can place it anywhere else.

static int last_direction = 0;


static int current_direction = 0;

Here we declared two static integers to hold the current and the last direction of the two
lines. We are going to use these variables (they are static variables which means they
save their value between the repeated calls) to check if there’s a change in the direction of
the lines or not.
we have initialized them to 0 because we don’t want them to work in the first call to the
function (if they worked in the first call the expert advisor will open an order as soon as
we load it in the terminal).

if(current_direction != last_direction) //changed

In this line we compare the two static variables to check for changes between the last call
of our function and the current call.
If last_direction not equal current_direction that’s mean there’s a change happened in the
direction.

last_direction = current_direction;
return (last_direction);

In this case (last_direction not equal current_direction) we have to reset our


last_direction by assigning to it the value of the current_direction.
And we will return the value of the last_direction. This value will be 1 if the first line is
above the second line and 2 if the first line is below the second line.

else
{
return (0);
}

Else (last_direction is equal current_direction) there’s no change in the lines direction


and we have to return 0.

Our program will call this function in its start() function body and use the returned value
to determine the appropriate action.

In the coming part of this lesson we will know how did we call the function, and we will
know a lot about the very important trading functions.
To that day I hope you the best luck.

I welcome very much the questions and the suggestions.

See you
Coders’ Guru
01-12-2005
MetaQuotes Language 4
MQL4 quick reference
Account Information
Array Functions
Common functions
Conversion functions
Custom Indicator functions
Date & Time functions
File functions
Global Variables functions
Math & Trig
Object functions
Pre-defined Variables
Standard Constants
String functions
Technical Indicator calls
Trading functions
Window functions

MQL4 quick reference


About MetaQuotes Language 4
Syntax
Data types
Operations & Expressions
Operators
Functions
Variables
Preprocessor

About MetaQuotes Language 4


MetaQuotes Language 4 (MQL4) is a new built-in language for programming trading strategies. This language allows
to create your own Expert Advisors that render the trade process management automatic and are perfectly suitable
for implementing your own trade strategies. Also, with the help of MQL4 you can create your own Custom Indicators,
Scripts and Libraries of functions.
A large number of functions necessary for the analysis of the current and past quotations, the basic arithmetic and
logic operations are included in MQL4 structure. There are also basic indicators built in and commands of order
placement and control.
The MetaEditor 4 text editor that highlights different constructions of MQL4 language is used for writing the program
code. It helps users to orient in the expert system text quite easily. As an information book for MQL4 language we
use MetaQuotes Language Dictionary. A brief guide contains functions divided into categories, operations, reserved
words, and other language constructions and allows finding the description of every element we use.
Programs written in MetaQuotes Language 4 have different features and purposes:
• Expert Advisors is a mechanical trade system (MTS) linked up to a certain plot. The Advisor can not only
inform you about a possibility to strike bargains, but also can make deals on the trade account automatically
and direct them right to the trade server. Like most trade systems, the terminal supports testing strategies
on historical data with displaying on the chart the spots where trades come in and out.
• Custom Indicators are an analogue of a technical indicator. In other words, Custom Indicators allow to create
technical indicators in addition to those already integrated into client terminal. Like built-in indicators, they
cannot make deals automatically and are aimed only at implementing analytical functions.
• Scripts are programs intended for single execution of some actions. Unlike Expert Advisors, Scripts are not
run tick wise and have no access to indicator functions.
• Libraries are user functions libraries where frequently used blocks of user programs are stored.
Syntax
Format
Comments
Identifiers
Reserved words

Format
Spaces, tabs, line feed/form feed symbols are used as separators. You can use any amount of such symbols instead
of one. You should use tab symbols to enhance the readability of the text .

Comments
Multi line comments start with /* symbols and end with */ symbols. Such comments cannot be nested. Single
comments start with // symbols, end with the symbol of a new line and can be nested into multi line comments.
Comments are allowed where blank spaces are possible and tolerate any number of spaces.
Examples:
// single comment
/* multi-
line // nested single comment
comment
*/

Identifiers
Identifiers are used as names of variables, functions, and data types. The length of an identifier cannot exceed 31
characters.
Symbols you can use: the numbers 0-9, Latin capital and small letters a-z, A-Z (recognized as different symbols), the
symbol of underlining (_). The first symbol cannot be a number. The identifier must not coincide with any reserved
word.
Examples:
NAME1 namel Total_5 Paper

Reserved words
The identifiers listed below are fixed reserved words. A certain action is assigned to each of them, and they cannot
be used for other purposes:
Data types Memory classes Operators Other
bool extern break false
color static case true
datetime continue
double default
int else
string for
void if
return
switch
while

Data types
Data types overview
Integer constants
Literal constants
Boolean constants
Floating-point number constants
String constants
Color constants
Datetime constants

Data types overview

The main data types are:

• Integer (int)
• Boolean (bool)
• Literals (char)
• String (string)
• Floating-point number (double)
• Color (color)
• Datetime (datetime)

We need the Color and Datetime types only to facilitate visualization and entering those parameters that we set from
expert advisor property tab or custom indicator "Input parameters" tab. The data of Color and Datetime types are
represented as integer values.
We use implicit type transformation. The priority of types at a transformation in ascending order is the following:
int (bool,color,datetime);
double;
string;
Before operations (except for the assignment ones) are performed, the data have been transferred to the maximum
precision type. Before assignment operations are performed, the data have been transferred to the integer type.

Integer constants
Decimal: numbers from 0 to 9; Zero should not be the first number.
Examples:
12, 111, -956 1007
Hexadecimal: numbers from 0 to 9, letters a-f or A-F to represent the values 10-15; they start with 0x or 0X.
Examples:
0x0A, 0x12, 0X12, 0x2f, 0xA3, 0Xa3, 0X7C7
Integer constants can assume values from -2147483648 to 2147483647. If a constant exceeds this range, the result
will not be defined.

Literal constants
Any single character enclosed in single quotes or a hexadecimal ASCII-code of a character looking like '\x10' is a
character constant of integer type. Some characters like a single quote ('), double quote (") a question mark (?), a
reverse slash (\) and control characters can be represented as a combination of characters starting with a reverse
slash (\) according to the table below:
line feed NL (LF) \n
horizontal tab HT \t
carriage return CR \r
reverse slash \ \\
single quote ' \'
double quote " \"
hexadecimal ASCII-code hh \xhh
If a character different from those listed above follows the reverse slash, the result will not be defined.
Examples:
int a = 'A';
int b = '$';
int c = '©'; // code 0xA9
int d = '\xAE'; // symbol code ®

Boolean constants
Boolean constants may have the value of true or false, numeric representation of them is 1 or 0 respectively. We can
also use synonyms True and TRUE, False and FALSE.
Examples:
bool a = true;
bool b = false;
bool c = 1;

Floating-point number constants


Floating-point constants consist of an integer part, a dot (.) and a fractional part. The integer and the fractional parts
are a succession of decimal numbers. An unimportant fractional part with the dot can be absent.
Examples:
double a = 12.111;
double b = -956.1007;
double c = 0.0001;
double d = 16;
Floating-point constants can assume values from 2.2e-308 to 1.8e308. If a constant exceeds this range, the result
will not be defined.

String constants
String constant is a succession of ASCII-code characters enclosed in double quotes: "Character constant".
A string constant is an array of characters enclosed in quotes. It is of the string type. Each string constant, even if it
is identical to another string constant, is saved in a separate memory space. If you need to insert a double quote (")
into the line, you must place a reverse slash (\) before it. You can insert any special character constants into the line
if they have a reverse slash (\) before them. The length of a string constant lies between 0 and 255 characters. If the
string constant is longer, the superfluous characters on the right are rejected.
Examples:
"This is a character string"
"Copyright symbol \t\xA9"
"this line with LF symbol \n"
"A" "1234567890" "0" "$"

Color constants
Color constants can be represented in three ways: by character representation; by integer representation; by name
(for concrete Web colors only).
Character representation consists of four parts representing numerical rate values of three main color components -
red, green, blue. The constant starts with the symbol C and is enclosed in single quotes. Numerical rate values of a
color component lie in the range from 0 to 255.
Integer-valued representation is written in a form of hexadecimal or a decimal number. A hexadecimal number looks
like 0x00BBGGRR where RR is the rate of the red color component, GG - of the green one and BB - of the blue one.
Decimal constants are not directly reflected in RGB. They represent the decimal value of the hexadecimal integer
representation.
Specific colors reflect the so-called Web colors set.
Examples:
// symbol constants
C'128,128,128' // gray
C'0x00,0x00,0xFF' // blue
// named color
Red
Yellow
Black
// integer-valued representation
0xFFFFFF // white
16777215 // white
0x008000 // green
32768 // green

Datetime constants
Datetime constants can be represented as a character line consisting of 6 parts for value of year, month, date, hour,
minutes, and seconds. The constant is enclosed in simple quotes and starts with a D character.
Datetime constant can vary from Jan 1, 1970 to Dec 31, 2037.
Examples:
D'2004.01.01 00:00' // New Year
D'1980.07.19 12:30:27'
D'19.07.1980 12:30:27'
D'19.07.1980 12' //equal to D'1980.07.19 12:00:00'
D'01.01.2004' //equal to D'01.01.2004 00:00:00'
D'12:30:27' //equal to D'[compilation date] 12:30:27'
D'' //equal to D'[compilation date] 00:00:00'

Operations & Expressions


Expressions
Arithmetical operations
The operation of assignment
Operations of relation
Boolean operations
Bitwise operations
Other operations
Precedence rules

Expressions
An expression consists of one or more operands and operation characters. An expression can be written in several
lines.
Example:
a++; b = 10; x = (y*z)/w;
Note: An expression that ends with a semicolon is an operator.

Arithmetical operations
Sum of values i = j + 2;
Difference of values i = j - 3;
Changing the operation sign x = - x;
Product of values z = 3 * x;
Division quotient i = j / 5;
Division remainder minutes = time % 60;
Adding 1 to the variable value i++;
Subtracting 1 from the variable value k--;
The operations of adding/subtracting 1 cannot be implemented in expressions.
Example:
int a=3;
a++; // valid expression
int b=(a++)*3; // invalid expression

The operation of assignment


Note: The value of the expression that includes this operation is the value of the left operand following the bind
character.

Assigning the y value to the x variable y = x;


Adding x to the y variable y += x;
Subtracting x from the y variable y -= x;
Multiplying the y variable by x y *= x;
Dividing the y variable by x y /= x;
Module x value of y y %= x;
Logical shift of y representation to the right by x bit y >>= x;
Logical shift of y representation to the left by x bit y <<= x;
Bitwise operation AND y &= x;
Bitwise operation OR y |= x;
Bitwise operation exclusive OR y ^= x;
Note: There can be only one operation of assignment in the expression. You can implement bitwise operations with
integer numbers only. The logical shift operation uses values of x less than 5 binary digits. The greater digits are
rejected, so the shift is for the range of 0-31 bit. By %= operation a result sign is equal to the sign of divided
number.

Operations of relation
The logical value false is represented with an integer zero value, while the logical value true is represented with any
value differing from zero.
The value of expressions containing operations of relation or logical operations is 0 (false) or 1 (true).
True if a equals b a == b;
True if a does not equal b a != b;
True if a is less than b a < b;
True if a is greater than b a > b;
True if a is less than or equals b a <= b;
True if a is greater than or equals b a >= b;
Two unnormalized floating-point numbers cannot be linked by == or != operations. That is why it is necessary to
subtract one from another, and the normalized outcome needs to be compared to null.

Boolean operations
The operand of negation NOT (!) must be of arithmetic type; the result equals 1 if the operand value is 0; the result
equals 0 if the operand differs from 0.
// True if a is false.
if(!a)
Print("not 'a'");
The logical operation OR (||) of values k and 1. The value k is checked first, the value 1 is checked only if k value is
false. The value of this expression is true if the value of k or 1 is true.
Example:
if(x<k || x>l)
Print("out of range");
The logical operation AND (&&) of values x and y. The value x is checked first; the value y is checked only if k value
is true. The value of this expression is true if the values of both x and y are true.
Example:
if(p!=x && p>y)
Print("true");
n++;

Bitwise operations
One's complement of values of variables. The value of the expression contains 1 in all digits where n contains 0; the
value of the expression contains 0 in all digits where n contains 1.
b = ~n;
Binary-coded representation of x is shifted to the right by y digits. The right shift is logical shift, that is the freed left-
side bits will be filled with zeros.
Example:
x = x >> y;
The binary-coded representation of x is shifted to the right by y digits; the free digits on the right will be filled with
zeroes.
Example:
x = x << y;
Bitwise operation AND of binary-coded x and y representations. The value of the expression contains 1 (true) in all
digits where both x and y are not equal to zero; the value of the expression contains 0 (false) in all other digits.
Example:
b = ((x & y) != 0);
Bitwise operation OR of binary-coded x and y representations. The expression contains 1 in all digits where x and y
not equals 0; the value of the expression contains 0 in all other digits.
Example:
b = x | y;
Bitwise operation EXCLUSIVE OR of binary-coded x and y representations. The expression contains 1 in all digits
where x and y have different binary values; the value of the expression contains 0 in all other digits.
Example:
b = x ^ y;
Note: Bitwise operations are executed with integers only.

Other operations
Indexing. At addressing to i element of array, the value of the expression equals the value of the variable numbered
as i.
Example:
array[i] = 3;
//Assign the value of 3 to array element with index i.
//Mind that the first array element
//is described with the expression array [0].
The call of function with x1,x2,...,xn arguments. The expression accepts the value returned by the function. If the
returned value is of the void type, you cannot place such function call on the right in the assignment operation. Mind
that the expressions x1,x2,...,xn are surely executed in this order.
Example:
double SL=Ask-25*Point;
double TP=Ask+25*Point;
int ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,SL,TP,
"My comment",123,0,Red);
The "comma" operation is executed from left to right. A pair of expressions separated by a comma is calculated from
left to right with a subsequent deletion of the left expression value. All side effects of left expression calculation can
appear before we calculate the right expression. The result type and value coincide with the type and value of the
right expression.
Precedence rules
Each group of operations in the table has the same priority. The higher the priority is, the higher the position of the
group in the table is.
The execution order determines the grouping of operations and operands.
() Function call From left to right
[] Array element selection
! Negation From left to right
~ Bitwise negation
- Sign changing operation
* Multiplication From left to right
/ Division
% Module division
+ Addition From left to right
- Subtraction
<< Left shift From left to right
>> Right shift
< Less than From left to right
<= Less than or equals
> Greater than
>= Greater than or equals
== Equals From left to right
!= Not equal
& Bitwise AND operation From left to right
^ Bitwise exclusive OR From left to right
| Bitwise OR operation From left to right
&& Logical AND From left to right
|| Logical OR From left to right
= Assignment From right to left
+= Assignment addition
-= Assignment subtraction
*= Assignment multiplication
/= Assignment division
%= Assignment module
>>= Assignment right shift
<<= Assignment left shift
&= Assignment bitwise AND
|= Assignment bitwise OR
^= Assignment exclusive OR
, Comma From left to right
Use parentheses to change the execution order of the operations.

Operators
Format and nesting
Compound operator
Expression operator
Break operator
Continue operator
Return operator
Conditional operator if
Conditional operator if-else
Switch operator
Cycle operator while
Cycle operator for
Format and nesting
Format. One operator can occupy one or several lines. Two or more operators can be located in the same line.
Nesting. Execution order control operators (if, if-else, switch, while and for) can be nested into each other.

Compound operator
A compound operator (a block) consists of one or more operators of any type enclosed in braces {}. The closing
brace should not be followed by a semicolon (;).
Example:
if(x==0)
{
x=1; y=2; z=3;
}

Expression operator
Any expression followed by a semicolon (;) is an operator. Here are some examples of expression operators:
Assignment operator.
Identifier=expression;
Example:
x=3;
y=x=3; // error
You can use an assignment operator in an expression only once.
Function call operator
Function_name(argument1,..., argumentN);
Example:
fclose(file);
Null operator
It consists of a semicolon (;) only. We use it to denote a null body of a control operator.

Break operator
A break; operator terminates the execution of the nearest nested outward operator switch, while or for. The control
is given to the operator that follows the terminated one. One of the purposes of this operator is to finish the looping
execution when a certain value is assigned to a variable.
Example:
// searching first zero element
for(i=0;i<array_size;i++)
if((array[i]==0)
break;

Continue operator
A continue; operator gives control to the beginning of the nearest outward cycle operator while or for, calling the
next iteration. The purpose of this operator is opposite to that of break.
Example:
// summary of nonzero elements of array
int func(int array[])
{
int array_size=ArraySize(array);
int sum=0;
for(int i=0;i<array_size; i++)
{
if(a[i]==0) continue;
sum+=a[i];
}
return(sum);
}

Return operator
A return; operator terminates the current function execution and returns the control to the calling program.
A return(expression); operator terminates the current function execution and returns the control to the calling
program together with the expression value. The operator expression is enclosed in parentheses. The expression
should not contain an assignment operator.
Example:
return(x+y);

Conditional operator if
if (expression)
operator;
If the expression is true, the operator will be executed. If the expression is false, the control will be given to the
expression following the operator.
Example:
if(a==x)
temp*=3;
temp=MathAbs(temp);

Conditional operator if-else


if (expression)
operator1
else
operator2
If the expression is true, operator1 is executed and the control is given to the operator that follows operator2
(operator2 is not executed). If the expression is false, operator2 is executed.
The "else" part of the "if" operator can be omitted. Thus, a divergence may appear in nested "if" operators with an
omitted "else" part. If it happens, "else" addresses to the nearest previous operator "if" in the block that has no
"else" part.
Example:
// The "else" part refers to the second "if" operator:
if(x>1)
if(y==2)
z=5;
else
z=6;
// The "else" part refers to the first "if" operator:
if(x>l)
{
if(y==2) z=5;
}
else
{
z=6;
}
// Nested operators
if(x=='a')
{
y=1;
}
else if(x=='b')
{
y=2;
z=3;
}
else if(x=='c')
{
y = 4;
}
else
{
Print("ERROR");
}

Switch operator
switch (expression)
{
case constant1: operators; break;
case constant2: operators; break;
...
default: operators; break;
}
It compares the expression value with constants in all variants of case and gives control to the operator that
resembles the expression value. Each variant of the case can be marked with an integer or character constant or a
constant expression. The constant expression must not include variables and function calls.
Example:
case 3+4: //valid
case X+Y: //invalid
Operators connected with a default label are executed if none of the constants in case operators equals the
expression value. The default variant is not obligatory final. If none of the constants resembles the expression value
and the default variant is absent, no actions are executed. The keyword case and the constant are just labels and if
operators are executed for some variant of case the program will further execute the operators of all following
variants until it hits a break operator. It allows linking one succession of operators with several variants. A constant
expression is calculated during compilation.
None of two constants in one switch operator can have the same values.
Example:
switch(x)
{
case 'A':
Print("CASE A\n");
break;
case 'B':
case 'C':
Print("CASE B or C\n");
break;
default:
Print("NOT A, B or C\n");
break;
}

Cycle operator while


while (expression)
operator;
If the expression is true, the operator is executed till the expression becomes false. If the expression is false, the
control will be given to the next operator.

Note: An expression value has been defined before the operator is executed. Therefore, if the expression is false
from the very beginning, the operator is not executed at all.
Example:
while(k<n)
{
y=y*x;
k++;
}

Cycle operator for


for (expression1; expression2; expression3)
operator;
Expression1 describes the initialization of the cycle. Expression2 is the cycle termination check. If it is true, the loop
body operator will be executed, Expression3 is executed. The cycle is repeated until Expression2 becomes false. If it
is not false, the cycle is terminated, and the control is given to the next operator. Expression3 is calculated after each
iteration. The 'for' operator is equivalent to the following succession of operators:
expression1;
while (expression2)
{
operator;
expression3;
};
Example:
for(x=1;x<=7;x++)
Print(MathPower(x,2));
Any of the three or all three expressions can be absent in the FOR operator, but you should not omit the semicolons
(;) that separate them.

If Expression2 is omitted, it is considered constantly true. The FOR (;;) operator is a continuous cycle equivalent to
the WHILE(l) operator.
Each of the expressions 1 to 3 can consist of several expressions united by a comma operator ','.
Example:
//
for(i=0,j=n-l;i<n;i++,j--)
a[i]=a[j];

Functions
Function definition
Function call
Special functions init(), deinit() and start()

Function definition
A function is defined by return value type declaration, by formal parameters and a compound operator (block) that
describes actions the function executes.
Example:
double // type
linfunc (double x, double a, double b) // function name and
// parameters list
{
// nested operators
return (a*x + b); // returned value
}
The "return" operator can return the value of the expression included into this operator. In case of a necessity, the
expression value assumes the type of function result. A function that does not return a value must be of "void" type.
Example:
void errmesg(string s)
{
Print("error: "+s);
}

Function call
function_name (x1,x2,...,xn)
Arguments (actual parameters) are transferred according to their value. Each expression x1,...,xn is calculated, and
the value is passed to the function. The order of expressions calculation and the order of values loading are
guaranteed. During the execution, the system checks the number and type of arguments given to the function. Such
way of addressing to the function is called a value call. There is also another way: call by link. A function call is an
expression that assumes the value returned by the function. This function type must correspond with the type of the
returned value. The function can be declared or described in any part of the program:
int somefunc()
{
double a=linfunc(0.3, 10.5, 8);
}
double linfunc(double x, double a, double b)
{
return (a*x + b);
}

Special functions init(), deinit() and start()


Any program begins its work with the "init()" function. "Init()" function attached to charts is launched also after client
terminal has started and in case of changing financial symbol and/or charts periodicity.
Every program finishes its work with the "deinit()" function. "deinit()" function is launched also by client terminal
shutdown, chart window closing, changing financial symbol and/or charts periodicity.
When new quotations are received, the "start()" function of attached expert advisors and custom indicator programs
is executed. If, when receiving new quotations, the "start()" function triggered on the previous quotations was
performed, the next calling "start()" function is executed only after "return()" instruction. All new quotations received
during the program execution are ignored by the program.
Detaching of the program from charts, changing financial symbol and/or charts periodicity, charts closing and also
client terminal exiting interrupts execution of program.
Execution of scripts does not depend on quotations coming.

Variables
Definitions
Defining local variables
Static variables
Defining global variables
Defining extern variables
Initializing variables
External function definition

Definitions
Definitions are used to define variables and to declare types of variables and functions defined somewhere else. A
definition is not an operator. Variables must be declared before being used. Only constants can be used to initialize
variables.
The basic types are:

• string - a string of characters;


• int - an integer;
• double - a floating-point number (double precision);
• bool - a boolean number "true" or "false".

Example:
string MessageBox;
int Orders;
double SymbolPrice;
bool bLog;
The additional types are:

• datetime is date and time, unsigned integer, containing seconds since 0 o'clock on January, 1, 1970.
• color - integer reflecting a collection of three color components.

The additional data types make sense only at the declaration of input data for more convenient their representation
in a property sheet.
Example:
extern datetime tBegin_Data = D'2004.01.01 00:00';
extern color cModify_Color = C'0x44,0xB9,0xE6';
Arrays
Array is the indexed sequence of the identical-type data.
Example:
int a[50]; //A one-dimensional array of 50 integers.
double m[7][50]; //Two-dimensional array of seven arrays,
//each of them consisting of 50 integers.
Only an integer can be an array index. No more than four-dimensional arrays can be declared.

Defining local variables


The variable declared inside any function is local. The scope of a local variable is limited to limits of the function
inside which it is declared. The local variable can be initialized by outcome of any expression. Every call of function
execute the initialization of local variables. Local variables are stored in memory area of corresponding function.
Formal parameters
Examples:
void func(int x, double y, bool z)
{
...
}
Formal parameters are local. Scope is the block of the function. Formal parameters must have names differing from
those of external variables and local variables defined within one function. In the block of the function to the formal
parameters some values can be assigned. Formal parameters can be initialized by constants. In this case, the
initializing value is considered as a default value. The parameters following the initialized parameter should be
initialized, as well.
By calling this function the initialized parameters can be omitted, instead of them defaults will be substituted.
Example:
func(123, 0.5);
Parameters are passed by value. These are modifications of a corresponding local variable inside the called function
will not be reflected in any way in the calling function. It is possible to pass arrays as parameters. However, for an
array passed as parameter, it is impossible to change the array elements.
There is a possibility to pass parameters by reference. In this case, modification of such parameters will be reflected
on corresponded variables in the called function. To point, that the parameter is passed by reference, after a data
type, it is necessary to put the modifier &.
Example:
void func(int& x, double& y, double& z[])
{
...
}
Arrays also can be passed by reference, all modifications will be reflected in the initial array. The parameters that
passed by reference, cannot be initialized by default values.

Static variables
The memory class "static" defines a static variable. The specifier "static" is declared before a data type.
Example:
{
static int flag
}
Static variables are constant ones since their values are not lost when the function is exited. Any variables in a block,
except the formal parameters of the function, can be defined as static. The static variable can be initialized by
corresponded type constant, as against a simple local variable which can be initialized by any expression. If there is
no explicit initialization, the static variable is initialized with zero. Static variables are initialized only once before
calling "init()" function. That is at exit from the function inside which the static variable is declared, the value of this
variable being not lost.

Defining global variables


They are defined on the same level as functions, i.e. they are not local in any block.
Example:
int Global_flag;
int start()
{
...
}
Scope of global variables is the whole program. Global variables are accessible from all functions defined in the
program. They are initialized with zero if no other initial value is explicitly defined. The global variable can be
initialized only by corresponded type constant. Initialization of global variables is made only once before execution of
"init()" function.
Note: it is not necessary to confuse the variables declared at a global level, to global variables of Client Terminal,
access to which is carried out by GlobalVariable...() function.

Defining extern variables


The memory class "extern" defines an extern variable. The specifier "extern" is declared before a data type.
Example:
extern double InputParameter1 = 1.0;
int init()
{
...
}
Extern variables define input data of the program, they are accessible from a property program sheet. It is not
meaningful to define extern variables in scripts. Arrays cannot represent itself as extern variables.

Initializing variables
Any variable can be initialized during its definition. Any permanently located variable is initialized with zero (0) if no
other initial value is explicitly defined. Global and static variables can be initialized only by constant of corresponded
type. Local variables can be initialized by any expression, and not just a constant. Initialization of global and static
variables is made only once. Initialization of local variables is made each time by call of corresponded functions.
Basic types
Examples:
int mt = 1; // integer initialization
// initialization floating-point number (double precision)
double p = MarketInfo(Symbol(),MODE_POINT);
// string initialization
string s = "hello";
Arrays
Example:
int mta[6] = {1,4,9,16,25,36};
The list of array elements must be enclosed by curly braces. If the array size is defined, the values being not
explicitly defined equal 0.

External function definition


The type of external functions defined in another component of a program must be explicitly defined. The absence of
such a definition may result in errors during the compilation, assembling or execution of your program. While
describing an external object, use the key word #import with the reference to the module.
Examples:
#import "user32.dll"
int MessageBoxA(int hWnd ,string szText,
string szCaption,int nType);
int SendMessageA(int hWnd,int Msg,int wParam,int lParam);
#import "lib.ex4"
double round(double value);
#import

Preprocessor
Declaring of constant
Controlling compilation
Including files
Importing functions and other modules

Declaring of constant
If the first character in a program line is #, it means that this line is a compiler command. Such a compiler command
ends with a carriage-return character.
#define identifier_value
The identifier of a constant obeys the same rules as variable names. The value can be of any type. Example:
#define ABC 100
#define PI 0.314
#define COMPANY_NAME "MetaQuotes Software Corp."
The compiler will replace each occurrence of an identifier in your source code with the corresponding value.

Controlling compilation
#property identifier_value
The list of predefined constant identifiers. Example:
#property link "http://www.metaquotes.net"
#property copyright "MetaQuotes Software Corp."
#property stacksize 1024

Constant Type Description


link string a link to the company website
copyright string the company name
stacksize int stack size
indicator_chart_window void show the indicator in the chart window
indicator_separate_window void show the indicator in a separate window
indicator_buffers int the number of buffers for calculation, up to 8
indicator_minimum int the bottom border for the chart
indicator_maximum int the top border for the chart
indicator_colorN color the color for displaying line N, where N lies between 1 and 8
predefined level N for separate window custom indicator, where N lies
indicator_levelN double
between 1 and 8
show_confirm void before script run message box with confirmation appears
before script run its property sheet appears; disables show_confirm
show_inputs void
property
The compiler
will write the declared values to the settings of the executable module.

Including files
Note: The #include command line can be placed anywhere in the program, but usually all inclusions are placed at
the beginning of the source code.
#include <file_name>
Example:
#include <win32.h>
The preprocessor replaces this line with the content of the file win32.h. Angle brackets mean that the file win32.h will
be taken from the default directory (usually, terminal_directory\experts\include). The current directory is not
searched.
#include "file_name"
Example:
#include "mylib.h"
The compiler replaces this line with the content of the file mylib.h. Since this name is enclosed in quotes, the search
is performed in the current directory (where the main file of the source code is located). If the file is not found in the
current directory, the error will be messaged.

Importing functions and other modules


#import "file_name"
func1();
func2();
#import
Example:
#import "user32.dll"
int MessageBoxA(int hWnd,string lpText,string lpCaption,
int uType);
int MessageBoxExA(int hWnd,string lpText,string lpCaption,
int uType,int wLanguageId);
#import "melib.ex4"
#import "gdi32.dll"
int GetDC(int hWnd);
int ReleaseDC(int hWnd,int hDC);
#import
Functions are imported from MQL4 compiled modules (*.ex4 files) and from operating system modules (*.dll files). In
the latter case, the imported functions are also declared. A new #import command (it can be without parameters)
finishes the description of imported functions.

Account Information
AccountBalance()
AccountCredit()
AccountCompany()
AccountCurrency()
AccountEquity()
AccountFreeMargin()
AccountLeverage()
AccountMargin()
AccountName()
AccountNumber()
AccountProfit()

double AccountBalance()

Returns balance value of the current account.

Sample
Print("Account balance = ",AccountBalance());

double AccountCredit()
Returns credit value of the current account.
Sample
Print("Account number ", AccountCredit());

string AccountCompany()
Returns the current account company name.
Sample
Print("Account company name ", AccountCompany());

string AccountCurrency()
Returns currency name of the current account.
Sample
Print("account currency is ", AccountCurrency());

double AccountEquity()
Returns equity value of the current account.
Sample
Print("Account equity = ",AccountEquity());

double AccountFreeMargin()
Returns free margin value of the current account.
Sample
Print("Account free margin = ",AccountFreeMargin());

int AccountLeverage()
Returns leverage of the current account.
Sample
Print("Account #",AccountNumber(), " leverage is ", AccountLeverage());

double AccountMargin()
Returns margin value of the current account.
Sample
Print("Account margin ", AccountMargin());

string AccountName()
Returns the current account name.
Sample
Print("Account name ", AccountName());

int AccountNumber()
Returns the number of the current account.
Sample
Print("account number ", AccountNumber());

double AccountProfit()
Returns profit value of the current account .
Sample
Print("Account profit ", AccountProfit());

Array Functions
ArrayBsearch()
ArrayCopy()
ArrayCopyRates()
ArrayCopySeries()
ArrayDimension()
ArrayGetAsSeries()
ArrayInitialize()
ArrayIsSeries()
ArrayMaximum()
ArrayMinimum()
ArrayRange()
ArrayResize()
ArraySetAsSeries()
ArraySize()
ArraySort()

int double array[], double value, int count=WHOLE_ARRAY, int start=0,


ArrayBsearch( int direction=MODE_ASCEND)
Returns the index of the first occurrence of a value in the first dimension of array if possible, or the nearest one, if the occurrence
is not found.
The function cannot be used with string arrays and serial numeric arrays.
Note: Binary search processes only sorted arrays. To sort numeric arrays use ArraySort() functions.
Parameters
array[] - The numeric array to search for.
value - The value to search for.
count - Count of elements to search for. By default, it searches in the whole array.
start - Starting index to search for. By default, the search starts on the first element.
direction - Search direction. It can be any of the following values:
MODE_ASCEND searching in forward direction,
MODE_DESCEND searching in the backward direction.
Sample
datetime daytimes[];
int shift=10,dayshift;
// All the Time[] timeseries are sorted in descendant mode
ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1);
if(Time[shift]>=daytimes[0]) dayshift=0;
else
{
dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND);
if(Period()<PERIOD_D1) dayshift++;
}
Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar opened at ",
TimeToStr(daytimes[dayshift]));

int object& dest[], object source[], int start_dest=0, int start_source=0,


ArrayCopy( int count=WHOLE_ARRAY)
Copies an array to another one. Arrays must be of the same type, but arrays with type double[], int[], datetime[], color[], and
bool[] can be copied as arrays with same type.
Returns the amount of copied elements.
Parameters
dest[] - Destination array.
source[] - Source array.
start_dest - Starting index for the destination array. By default, start index is 0.
start_source - Starting index for the source array. By default, start index is 0.
count - The count of elements that should be copied. By default, it is WHOLE_ARRAY constant.
Sample
double array1[][6];
double array2[10][6];
// fill array with some data
ArrayCopyRates(array1);
ArrayCopy(array2, array1,0,Bars-9,10);
// now array2 has first 10 bars in the history
int ArrayCopyRates(double& dest_array[], string symbol=NULL, int timeframe=0)
Copies rates to the two-dimensional array from chart RateInfo array, where second dimension has 6 elements:
0 - time,
1 - open,
2 - low,
3 - high,
4 - close,
5 - volume.
Note: Usually retrieved array used to pass large blocks of data to the DLL functions.
Parameters
dest_array[] - Reference to the two-dimensional destination numeric array.
symbol - symbol name, by default, current chart symbol name is used.
timeframe - Time frame, by default, the current chart time frame is used. It can be any of Time frame enumeration values.
Sample
double array1[][6];
ArrayCopyRates(array1,"EURUSD", PERIOD_H1);
Print("Current bar ",TimeToStr(array1[0][0]),"Open", array1[0][1]);

int double& array[], int series_index, string symbol=NULL,


ArrayCopySeries( int timeframe=0)
Copies a series array to another one and returns the count of copied elements.
Note: If series_index is MODE_TIME, the first parameter must be a datetime array.
Parameters
array[] - Reference to the destination one-dimensional numeric array.
series_index - Series array identifier. It can be any of Series array identifiers enumeration values.
symbol - Symbol name, by default, the current chart symbol name is used.
timeframe - Time frame, by default, the current chart time frame is used. It can be any of Time frame enumeration values.
Sample
datetime daytimes[];
int shift=10,dayshift;
// All the Time[] timeseries are sorted in descendant mode
ArrayCopySeries(daytimes,MODE_TIME,Symbol(),PERIOD_D1);
if(Time[shift]>=daytimes[0]) dayshift=0;
else
{
dayshift=ArrayBsearch(daytimes,Time[shift],WHOLE_ARRAY,0,MODE_DESCEND);
if(Period()<PERIOD_D1) dayshift++;
}
Print(TimeToStr(Time[shift])," corresponds to ",dayshift," day bar opened at ",
TimeToStr(daytimes[dayshift]));

int ArrayDimension(int array[])


Returns array rank (dimensions count).
Parameters
array[] - array to retrieve dimensions count.
Sample
int num_array[10][5];
int dim_size;
dim_size=ArrayDimension(num_array);
// dim_size is 2
bool ArrayGetAsSeries(object array[])
Returns true if array is organized as a series array (array elements indexed from last to first) otherwise return false.
Parameters
array[] - Array to check.
Sample
if(ArrayGetAsSeries(array1)==true)
Print("array1 is indexed as a series array");
else
Print("array1 is indexed normally (from left to right)");

int ArrayInitialize(double& array[], double value)


Sets all elements of numeric array to the same value. Returns the count of initialized element.
Note: It is useless to initialize index buffers in the custom indicator init() function.
Parameters
array[] - Numeric array to be initialized.
value - New value to be set.
Sample
//---- setting all elements of array to 2.1
double myarray[10];
ArrayInitialize(myarray,2.1);

bool ArrayIsSeries(object array[])


Returns true if the array checked is a series array (time,open,close,high,low, or volume).
Parameters
array[] - Array to check.
Sample
if(ArrayIsSeries(array1)==false)
ArrayInitialize(array1,0);
else
{
Print("Series array cannot be initialized!");
return(-1);
}

int ArrayMaximum(double array[], int count=WHOLE_ARRAY, int start=0)


Searches for elements with maximum value and returns its position.
Parameters
array[] - The numeric array to search for.
count - Scans for the count of elements in the array.
start - Start searching on the start index.
Sample
double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9};
int maxValueIdx=ArrayMaximum(num_array);
Print("Max value = ", num_array[maxValueIdx]);

int ArrayMinimum(double array[], int count=WHOLE_ARRAY, int start=0)


Searches for element with minimum value and returns its position.
Parameters
array[] - The numeric array to search for.
count - Scans for the count of elements in the array.
start - Start searching on the start index.
Sample
double num_array[15]={4,1,6,3,9,4,1,6,3,9,4,1,6,3,9};
double minValueidx=ArrayMinimum(num_array);
Print("Min value = ", num_array[minValueIdx]);

int ArrayRange(object array[], int range_index)


Returns the count of elements in the indicated dimension of the array. Since indexes are zero-based, the size of dimension is 1
greater than the largest index.
Parameters
array[] - Array to check
range_index - Dimension index.
Sample
int dim_size;
double num_array[10,10,10];
dim_size=ArrayRange(num_array, 1);

int ArrayResize(object& array[], int new_size)


Sets new size to the first dimension. If success returns count of all elements contained in the array after resizing, otherwise,
returns zero and array is not resized.
Parameters
array[] - Array to resize.
new_size - New size for the first dimension.
Sample
double array1[][4];
int element_count=ArrayResize(array, 20);
// element count is 80 elements

bool ArraySetAsSeries(double& array[], bool set)


Sets indexing order of the array like a series arrays, i.e. last element has zero index. Returns previous state.
Parameters
array[] - The numeric array to set.
set - The Series flag to set (true) or drop (false).
Sample
double macd_buffer[300];
double signal_buffer[300];
int i,limit=ArraySize(macd_buffer);
ArraySetAsSeries(macd_buffer,true);
for(i=0; i<limit; i++)
macd_buffer[i]=iMA(NULL,0,12,0,MODE_EMA,PRICE_CLOSE,i)-
iMA(NULL,0,26,0,MODE_EMA,PRICE_CLOSE,i);
for(i=0; i<limit; i++)
signal_buffer[i]=iMAOnArray(macd_buffer,limit,9,0,MODE_SMA,i);

int ArraySize(object array[])


Returns the count of elements contained in the array.
Parameters
array[] - Array of any type.
Sample
int count=ArraySize(array1);
for(int i=0; i<count; i++)
{
// do some calculations.
}

int double& array[], int count=WHOLE_ARRAY, int start=0,


ArraySort( int sort_dir=MODE_ASCEND)
Sorts numeric arrays by first dimension. Series arrays cannot be sorted by ArraySort().
Parameters
array[] - The numeric array to sort.
count - Count of elements to sort.
start - Starting index.
sort_dir - Array sorting direction. It can be any of the following values:
MODE_ASCEND - sort ascending,
MODE_DESCEND - sort descending.
Sample
double num_array[5]={4,1,6,3,9};
// now array contains values 4,1,6,3,9
ArraySort(num_array);
// now array is sorted 1,3,4,6,9
ArraySort(num_array,MODE_DESCEND);
// now array is sorted 9,6,4,3,1

Common functions
Alert()
ClientTerminalName()
CompanyName()
Comment()
GetLastError()
GetTickCount()
HideTestIndicators()
IsConnected()
IsDemo()
IsDllsAllowed()
IsLibrariesAllowed()
IsStopped()
IsTesting()
IsTradeAllowed()
MarketInfo()
MessageBox()
Period()
PlaySound()
Print()
RefreshRates()
SendMail()
ServerAddress()
Sleep()
SpeechText()
Symbol()
UninitializeReason()
void Alert(... )
Displays a dialog box containing the user-defined data. Parameters can be of any type. Arrays cannot be passed to the Alert
function. Data of double type printed with 4 decimal digits after point. To print with more precision use DoubleToStr() function.
Data of bool, datetime and color types will be printed as its numeric presentation. To print values of datetime type as string
convert it by TimeToStr() function.

See also: Comment() and Print() functions.


Parameters
... - Any values, separated by commas.
Sample
if(Close[0]>SignalLevel)
Alert("Close price coming ", Close[0],"!!!");

string ClientTerminalName()
Returns Client Terminal Name.
Sample
Print("Terminal name is ",ClientTerminalName());

string CompanyName()
Returns Company name
Sample
Print("Company name is ",CompanyName());

void Comment(... )
Prints some message to the left top corner of the chart. Parameters can be of any type. Arrays cannot be passed to the
Comment() function. Arrays should be output elementwise. Data of double type printed with 4 decimal digits after point. To print
with more precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation.
To print values of datetime type as string convert it by TimeToStr() function.
See also: Alert() and Print() functions.
Parameters
... - Any values, separated by commas.
Sample
double free=AccountFreeMargin();
Comment("Account free margin is ",DoubleToStr(free,2),"\n","Current time is
",TimeToStr(CurTime()));

int GetLastError()
Returns last occurred error after an operation and sets internal last error value to zero.
Sample
int err;
int handle=FileOpen("somefile.dat", FILE_READ|FILE_BIN);
if(handle<1)
{
err=GetLastError();
Print("error(",err,"): ",ErrorDescription(err));
return(0);
}
int GetTickCount()
The GetTickCount() function retrieves the number of milliseconds that have elapsed since the system was started. It is limited to
the resolution of the system timer.
Sample
int start=GetTickCount();
// do some hard calculation...
Print("Calculation time is ", GetTickCount()-start, " milliseconds.");

void HideTestIndicators(bool hide)


The function sets a flag hiding indicators called by the Expert Advisor. After the chart has been tested and opened the flagged
indicators will not be drawn on the testing chart. Every indicator called will first be flagged with the current hiding flag.
Parameters
hide - TRUE - if indicators must be hidden, otherwise, FALSE.
Sample
HideTestIndicators(true);

bool IsConnected()
Returns true if client terminal has opened connection to the server, otherwise returns false.
Sample
if(!IsConnected())
{
Print("Connection is broken!");
return(0);
}
// Expert body that need opened connection
// ...

bool IsDemo()
Returns true if expert runs on demo account, otherwise returns false.
Sample
if(IsDemo()) Print("I am working on demo account");
else Print("I am working on real account");

bool IsDllsAllowed()
Returns true if DLL function call is allowed for the expert, otherwise returns false. See also IsLibrariesAllowed(),
IsTradeAllowed().
Sample
#import "user32.dll"
int MessageBoxA(int hWnd ,string szText, string szCaption,int nType);
...
...
if(IsDllsAllowed()==false)
{
Print("DLL call is not allowed. Experts cannot run.");
return(0);
}
// expert body that calls external DLL functions
MessageBoxA(0,"an message","Message",MB_OK);
bool IsLibrariesAllowed()
Returns true if expert can call library function, otherwise returns false. See also IsDllsAllowed(), IsTradeAllowed().
Sample
#import "somelibrary.ex4"
int somefunc();
...
...
if(IsLibrariesAllowed()==false)
{
Print("Library call is not allowed. Experts cannot run.");
return(0);
}
// expert body that calls external DLL functions
somefunc();

bool IsStopped()
Returns true if expert in the stopping state, otherwise returns false. This function can be used in the cycles to determine expert
unloading.
Sample
while(expr!=false)
{
if(IsStopped()==true) return(0);
// long time procesing cycle
// ...
}

bool IsTesting()
Returns true if expert runs in the testing mode, otherwise returns false.
Sample
if(IsTesting()) Print("I am testing now");

bool IsTradeAllowed()
Returns true if trade is allowed for the expert, otherwise returns false. See also IsDllsAllowed(), IsLibrariesAllowed().
Sample
if(IsTradeAllowed()) Print("Trade allowed");

double MarketInfo(string symbol, int type)


Returns value from Market watch window.
Parameters
symbol - Instrument symbol.
type - Returning data type index. It can be any of Market information identifiers value.
Sample
double var;
var=MarketInfo("EURUSD",MODE_BID);

int MessageBox(string text=NULL, string caption=NULL, int flags=EMPTY)


The MessageBox function creates, displays, and operates a message box. The message box contains an application-defined
message and title, plus any combination of predefined icons and push buttons.
If the function succeeds, the return value is one of the MessageBox return code values.
Parameters
text - Optional text that contains the message to be displayed.
caption - Optional text that contains the dialog box title.If this parameter is NULL, the title will be name of expert.
flags - Specifies the contents and behavior of the dialog box.This optional parameter can be a combination of flags from the following
groups of flags.
Sample
#include <WinUser32.mqh>

if(ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045)==false)


{
int ret=MessageBox("ObjectCreate() fails with code
"+GetLastError()+"\nContinue?", "Question", MB_YESNO|MB_ICONQUESTION);
if(ret==IDNO) return(false);
}
// continue

int Period()
Returns the number of minutes defining the used period (chart timeframe).
Sample
Print("Period is ", Period());

void PlaySound(string filename)


Function plays sound file. File must be located at the terminal_dir\sounds directory or its subdirectory.
Parameters
filename - Sound file name.
Sample
if(IsDemo()) PlaySound("alert.wav");

void Print(... )
Prints some message to the experts log. Parameters can be of any type. Arrays cannot be passed to the Print() function. Arrays
should be printed elementwise. Data of double type printed with 4 decimal digits after point. To print with more precision use
DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print values of
datetime type as string convert it by TimeToStr() function.
See also: Alert() and Comment() functions.
Parameters
... - Any values, separated by commas.
Sample
Print("Account free margin is ", AccountFreeMargin());
Print("Current time is ", TimeToStr(CurTime()));
double pi=3.141592653589793;
Print("PI number is ", DoubleToStr(pi,8));
// Output: PI number is 3.14159265
// Array printing
for(int i=0;i<10;i++)
Print(Close[i]);

bool RefreshRates()
Refreshing data in the built-in variables and series arrays. This function is used when expert advisor calculates for a long time and
needs refreshing data. Returns true if data are refreshed, otherwise false.
Sample
int ticket;
while(true)
{
ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert
comment",255,0,CLR_NONE);
if(ticket<=0)
{
int error=GetLastError();
if(error==134) break; // not enough money
if(error==135) RefreshRates(); // prices changed
break;
}
else { OrderPrint(); break; }
//---- 10 seconds wait
Sleep(10000);
}

void SendMail(string subject, string some_text)


Sends mail to address set in the Tools->Options->EMail tab if enabled. Note: Posting e-mail can be denied or address can be
empty.
Parameters
subject - Subject text.
some_text - Mail body.
Sample
double lastclose=Close[0];
if(lastclose<my_signal)
SendMail("from your expert", "Price dropped down to "+DoubleToStr(lastclose));

string ServerAddress()
Returns connected server address in form of a text string.
Sample
Print("Server address is ", ServerAddress());

void Sleep(int milliseconds)


The Sleep function suspends the execution of the current expert for a specified interval.
Parameters
milliseconds - Sleeping interval in milliseconds.
Sample
Sleep(5);

void SpeechText(string text, int lang_mode=SPEECH_ENGLISH)


Computer speaks some text.
Parameters
text - Speaking text.
lang_mode - SPEECH_ENGLISH (by default) or SPEECH_NATIVE values.
Sample
double lastclose=Close[0];
SpeechText("Price dropped down to "+DoubleToStr(lastclose));
string Symbol()
Returns a text string with the name of the current financial instrument.
Sample
int total=OrdersTotal();
for(int pos=0;pos<total;pos++)
{
// check selection result becouse order may be closed or deleted at this time!
if(OrderSelect(pos, SELECT_BY_POS)==false) continue;
if(OrderType()>OP_SELL || OrderSymbol()!=Symbol()) continue;
// do some orders processing...
}

int UninitializeReason()
Returns the code of the uninitialization reason for the experts, custom indicators, and scripts. Return values can be one of
Uninitialize reason codes.
Sample
// this is example
int deinit()
{
switch(UninitializeReason())
{
case REASON_CHARTCLOSE:
case REASON_REMOVE: CleanUp(); break; // clean up and free all expert's
resources.
case REASON_RECOMPILE:
case REASON_CHARTCHANGE:
case REASON_PARAMETERS:
case REASON_ACCOUNT: StoreData(); break; // prepare to restart
}
//...
}

Conversion functions
CharToStr()
DoubleToStr()
NormalizeDouble()
StrToDouble()
StrToInteger()
StrToTime()
TimeToStr()

string CharToStr(int char_code)


Returns string with one symbol that have specified code
Parameters
char_code - ASCII char code.
Sample
string str="WORL" + CharToStr(44); // 44 is code for 'D'
// resulting string will be WORLD
string DoubleToStr(double value, int digits)
Returns text string with the specified numerical value transformed into the specified precision format.
Parameters
value - Numerical value.
digits - Precision format, number of digits after decimal point (0-8).
Sample
string value=DoubleToStr(1.28473418, 5);
// value is 1.28473

double NormalizeDouble(double value, int digits)


Rounds floating point number to specified decimal places.
Parameters
value - Floating point value.
digits - Precision format, number of digits after decimal point (0-8).
Sample
double var1=0.123456789;
Print(NormalizeDouble(var1,5));
// output: 0.12346

double StrToDouble(string value)


Converts string representation of number to type double.
Parameters
value - String containing value in fixed number format.
Sample
double var=StrToDouble("103.2812");

int StrToInteger(string value)


Converts string representation of number to type integer.
Parameters
value - String containing integer number.
Sample
int var1=StrToInteger("1024");

datetime StrToTime(string value)


Converts string in the format "yyyy.mm.dd hh:mi" to type datetime.
Parameters
value - String value of date/time format such as "yyyy.mm.dd hh:mi".
Sample
datetime var1;
var1=StrToTime("2003.8.12 17:35");
var1=StrToTime("17:35"); // returns with current date
var1=StrToTime("2003.8.12"); // returns with midnight time "00:00"
string TimeToStr(datetime value, int mode=TIME_DATE|TIME_MINUTES)
Returns time as string in the format "yyyy.mm.dd hh:mi".
Parameters
value - Positive number of seconds from 00:00 January 1, 1970.
mode - Optional data output mode can be one or combination of:
TIME_DATE get result in form "yyyy.mm.dd",
TIME_MINUTES get result in form "hh:mi",
TIME_SECONDS get result in form "hh:mi:ss".
Sample
strign var1=TimeToStr(CurTime(),TIME_DATE|TIME_SECONDS);

Custom Indicator functions


IndicatorBuffers()
IndicatorCounted()
IndicatorDigits()
IndicatorShortName()
SetIndexArrow()
SetIndexBuffer()
SetIndexDrawBegin()
SetIndexEmptyValue()
SetIndexLabel()
SetIndexShift()
SetIndexStyle()
SetLevelStyle()
SetLevelValue()

void IndicatorBuffers(int count)


Allocates memory for buffers used for custom indicator calculations. Cannot be greater than 8 and less than indicator_buffers
property. If custom indicator requires additional buffers for counting then use this function for pointing common buffers count.
Parameters
count - Buffers count to allocate. Should be up to 8 buffers.
Sample
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//---- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//---- indicator buffers
double ind_buffer1[];
double ind_buffer2[];
double ind_buffer3[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}

int IndicatorCounted()
Returns bars count that does not changed after last indicator launch. In most cases same count of index values do not need for
recalculation. Used for optimizing calculations.
Sample
int start()
{
int limit;
int counted_bars=IndicatorCounted();
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- main loop
for(int i=0; i<limit; i++)
{
//---- ma_shift set to 0 because SetIndexShift called abowe
ExtBlueBuffer[i]=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtRedBuffer[i]=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtLimeBuffer[i]=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
}
//---- done
return(0);
}

void IndicatorDigits(int digits)


Sets default precision format for indicators visualization.
Parameters
digits - Precision format, number of digits after decimal point.
Sample
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//---- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//---- indicator buffers
double ind_buffer1[];
double ind_buffer2[];
double ind_buffer3[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}

void IndicatorShortName(string name)


Sets indicator short name for showing on the chart subwindow.
Parameters
name - New short name.
Sample
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//---- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//---- indicator buffers
double ind_buffer1[];
double ind_buffer2[];
double ind_buffer3[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}

void SetIndexArrow(int index, int code)


Sets arrow symbol for indicators that draws some lines as arrow.
Parameters
index - Line index. Should be from 0 to 7.
code - Symbol code from Wingdings font or Array constants.
Sample
SetIndexArrow(0, 217);

bool SetIndexBuffer(int index, double array[])


Sets buffer for calculating line. The indicated array bound with previously allocated custom indicator buffer. If the function
succeeds, the return value is true. If the function fails, the return value is false. To get the detailed error information, call
GetLastError().
Parameters
index - Line index. Should be from 0 to 7.
array[] - Array that stores calculated indicator values.
Sample
double ExtBufferSilver[];
int init()
{
SetIndexBuffer(0, ExtBufferSilver); // set buffer for first line
// ...
}

void SetIndexDrawBegin(int index, int begin)


Sets first bar from what index will be drawn. Index values before draw begin are not significant and does not drawn and not show
in the DataWindow.
Parameters
index - Line index. Should be from 0 to 7.
begin - First drawing bar position number.
Sample
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//---- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//---- indicator buffers
double ind_buffer1[];
double ind_buffer2[];
double ind_buffer3[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ind_buffer1);
SetIndexBuffer(1,ind_buffer2);
SetIndexBuffer(2,ind_buffer3);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}

void SetIndexEmptyValue(int index, double value)


Sets drawing line empty value. By default, empty value line is EMPTY_VALUE. Empty values are not drawn and not show in the
DataWindow.
Parameters
index - Line index. Should be from 0 to 7.
value - New empty value.
Sample
SetIndexEmptyValue(6,0.0001);

void SetIndexLabel(int index, string text)


Sets drawing line description for showing in the DataWindow.
Parameters
index - Line index. Should be from 0 to 7.
text - Label text. NULL means that index value does not show in the DataWindow.
Sample
//+------------------------------------------------------------------+
//| Ichimoku Kinko Hyo initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,Tenkan_Buffer);
SetIndexDrawBegin(0,Tenkan-1);
SetIndexLabel(0,"Tenkan Sen");
//----
SetIndexStyle(1,DRAW_LINE);
SetIndexBuffer(1,Kijun_Buffer);
SetIndexDrawBegin(1,Kijun-1);
SetIndexLabel(1,"Kijun Sen");
//----
a_begin=Kijun; if(a_begin<Tenkan) a_begin=Tenkan;
SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_DOT);
SetIndexBuffer(2,SpanA_Buffer);
SetIndexDrawBegin(2,Kijun+a_begin-1);
SetIndexShift(2,Kijun);
//---- Up Kumo bounding line does not show in the DataWindow
SetIndexLabel(2,NULL);
SetIndexStyle(5,DRAW_LINE,STYLE_DOT);
SetIndexBuffer(5,SpanA2_Buffer);
SetIndexDrawBegin(5,Kijun+a_begin-1);
SetIndexShift(5,Kijun);
SetIndexLabel(5,"Senkou Span A");
//----
SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_DOT);
SetIndexBuffer(3,SpanB_Buffer);
SetIndexDrawBegin(3,Kijun+Senkou-1);
SetIndexShift(3,Kijun);
//---- Down Kumo bounding line does not show in the DataWindow
SetIndexLabel(3,NULL);
//----
SetIndexStyle(6,DRAW_LINE,STYLE_DOT);
SetIndexBuffer(6,SpanB2_Buffer);
SetIndexDrawBegin(6,Kijun+Senkou-1);
SetIndexShift(6,Kijun);
SetIndexLabel(6,"Senkou Span B");
//----
SetIndexStyle(4,DRAW_LINE);
SetIndexBuffer(4,Chinkou_Buffer);
SetIndexShift(4,-Kijun);
SetIndexLabel(4,"Chinkou Span");
//----
return(0);
}

void SetIndexShift(int index, int shift)


Sets offset for drawing line. Line will be counted on the current bar, but will be drawn shifted.
Parameters
index - Line index. Should be from 0 to 7.
shift - Shitf value in bars.
Sample
//+------------------------------------------------------------------+
//| Alligator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- line shifts when drawing
SetIndexShift(0,JawsShift);
SetIndexShift(1,TeethShift);
SetIndexShift(2,LipsShift);
//---- first positions skipped when drawing
SetIndexDrawBegin(0,JawsShift+JawsPeriod);
SetIndexDrawBegin(1,TeethShift+TeethPeriod);
SetIndexDrawBegin(2,LipsShift+LipsPeriod);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ExtBlueBuffer);
SetIndexBuffer(1,ExtRedBuffer);
SetIndexBuffer(2,ExtLimeBuffer);
//---- drawing settings
SetIndexStyle(0,DRAW_LINE);
SetIndexStyle(1,DRAW_LINE);
SetIndexStyle(2,DRAW_LINE);
//---- index labels
SetIndexLabel(0,"Gator Jaws");
SetIndexLabel(1,"Gator Teeth");
SetIndexLabel(2,"Gator Lips");
//---- initialization done
return(0);
}
void int index, int type, int style=EMPTY, int width=EMPTY,
SetIndexStyle( color clr=CLR_NONE)
Sets new type, style, width and color for a given indicator line.
Parameters
index - Line index. Should be from 0 to 7.
type - Shape style.Can be one of Drawing shape style enumeration.
style - Drawing style. Except STYLE_SOLID style all other styles valid when width is 1 pixel.Can be one of Shape style enumeration.
EMPTY value indicates that style does not changed.
width - Line width. valid values - 1,2,3,4,5. EMPTY value indicates that width does not changed.
clr - Line color.
Sample
SetIndexStyle(3, DRAW_LINE, EMPTY, 2, Red);

void SetLevelStyle(int draw_style, int line_width, color clr=CLR_NONE)


Function sets new style, width and color of indicator levels.
Parameters
draw_style - Drawing style. Except for STYLE_SOLID, all other styles are valid if the width is 1 pixel.Can be one of Shape style
constants.EMPTY value indicates that style will not be changed.
line_width - Line width. Valid values are 1,2,3,4,5. EMPTY value indicates that width will not be changed.
clr - Line color.
Sample
//---- show levels as thick red lines
SetLevelStyle(STYLE_SOLID,2,Red)

int SetLevelValue(int level, double value)


Function sets a new value for the given indicator level.
Parameters
level - Level index (0-31).
value - Value for the given indicator level.
Sample
SetLevelValue(1,3.14);

Date & Time functions


CurTime()
Day()
DayOfWeek()
DayOfYear()
Hour()
LocalTime()
Minute()
Month()
Seconds()
TimeDay()
TimeDayOfWeek()
TimeDayOfYear()
TimeHour()
TimeMinute()
TimeMonth()
TimeSeconds()
TimeYear()
Year()
datetime CurTime()
Returns the last known server time, number of seconds elapsed from 00:00 January 1, 1970.
Sample
if(CurTime()-OrderOpenTime()<360) return(0);

int Day()
Returns the current day of the month.
Sample
if(Day()<5) return(0);

int DayOfWeek()
Returns the current zero based day of the week (0-Sunday,1,2,3,4,5,6).
Sample
// do not work on holidays.
if(DayOfWeek()==0 || DayOfWeek()==6) return(0);

int DayOfYear()
Returns the current day of the year (1-1 january,..,365(6) - 31 december).
Sample
if(DayOfYear()==245)
return(true);

int Hour()
Returns current hour (0,1,2,..23)
Sample
bool is_siesta=false;
if(Hour()>=12 || Hour()<17)
is_siesta=true;

datetime LocalTime()
Returns local computer time, number of seconds elapsed from 00:00 January 1, 1970.
Sample
if(LocalTime()-OrderOpenTime()<360) return(0);

int Minute()
Returns current minute (0,1,2,..59).
Sample
if(Minute()<=15)
return("first quarter");

int Month()
Returns current month as number (1-January,2,3,4,5,6,7,8,9,10,11,12).
Sample
if(Month()<=5)
return("first half of year");

int Seconds()
Returns current second (0,1,2,..59).
Sample
if(Seconds()<=15)
return(0);

int TimeDay(datetime date)


Returns day of month (1 - 31) for specified date.
Parameters
date - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample
int day=TimeDay(D'2003.12.31');
// day is 31

int TimeDayOfWeek(datetime date)


Returns zero based day of week (0-Sunday,1,2,3,4,5,6) for specified date.
Parameters
date - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample
int weekday=TimeDayOfWeek(D'2004.11.2');
// day is 2 - tuesday

int TimeDayOfYear(datetime date)


Returns day (1-1 january,..,365(6) - 31 december) of year for specified date.
Parameters
date - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample
int day=TimeDayOfYear(CurTime());

int TimeHour(datetime time)


Returns hour for specified time.
Parameters
time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample
int h=TimeHour(CurTime());

int TimeMinute(datetime time)


Returns minute for specified time.
Parameters
time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample
int m=TimeMinute(CurTime());
int TimeMonth(datetime time)
Returns month for specified time.
Parameters
time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample
int m=TimeMonth(CurTime());

int TimeSeconds(datetime time)


Returns seconds after minute (0 – 59) for specified time.
Parameters
time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample
int m=TimeSeconds(CurTime());

int TimeYear(datetime time)


Returns year for specified date. Return values can be in range 1970-2037.
Parameters
time - Datetime is the number of seconds elapsed since midnight (00:00:00), January 1, 1970.
Sample
int y=TimeYear(CurTime());

int Year()
Returns current year.
Sample
// return if date before 1 May 2002
if(Year()==2002 && Month()<5)
return(0);

File functions
FileClose()
FileDelete()
FileFlush()
FileIsEnding()
FileIsLineEnding()
FileOpen()
FileOpenHistory()
FileReadArray()
FileReadDouble()
FileReadInteger()
FileReadNumber()
FileReadString()
FileSeek()
FileSize()
FileTell()
FileWrite()
FileWriteArray()
FileWriteDouble()
FileWriteInteger()
FileWriteString()

void FileClose(int handle)


Closes file previously opened by FileOpen() functions.
Parameters
handle - File handle, returned by FileOpen() functions
Sample
int handle=FileOpen("filename", FILE_CSV|FILE_READ);
if(handle>0)
{
// working with file ...
FileClose(handle);
}

void FileClose(int handle)


Closes file previously opened by FileOpen() functions.
Parameters
handle - File handle, returned by FileOpen() functions
Sample
int handle=FileOpen("filename", FILE_CSV|FILE_READ);
if(handle>0)
{
// working with file ...
FileClose(handle);
}

void FileFlush(int handle)


Flushes all data stored in the file buffer to disk.
Parameters
handle - File handle, returned by FileOpen() functions.
Sample
int bars_count=Bars;
int handle=FileOpen("mydat.csv",FILE_CSV|FILE_WRITE);
if(handle>0)
{
FileWrite(handle, "#","OPEN","CLOSE","HIGH","LOW");
for(int i=0;i<bars_count;i++)
FileWrite(handle, i+1,Open[i],Close[i],High[i], Low[i]);
FileFlush(handle);
...
for(int i=0;i<bars_count;i++)
FileWrite(handle, i+1,Open[i],Close[i],High[i], Low[i]);
FileClose(handle);
}

bool FileIsEnding(int handle)


Returns logical true if file pointer is at the end of the file, otherwise returns false. To get the detailed error information, call
GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() functions.
Sample
if(FileIsEnding(h1))
{
FileClose(h1);
return(false);
}

bool FileIsLineEnding(int handle)


For CSV file returns logical true if file pointer is at the end of the line, otherwise returns false. To get the detailed error
information, call GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() function.
Sample
if(FileIsLineEnding(h1))
{
FileClose(h1);
return(false);
}

int FileOpen(string filename, int mode, int delimiter=';')


Opens file for input and/or output. Returns a file handle for the opened file. If the function fails, the return value less than 1. To
get the detailed error information, call GetLastError() function.
Note: Files can be opened only from terminal_dir\experts\files directory and its subdirectories.
Parameters
filename - File name, file may be with any extensions.
mode - Open mode. can be one or combination of values: FILE_BIN, FILE_CSV, FILE_READ, FILE_WRITE.
delimiter - Delimiter character for csv files. By default passed ';' symbol.
Sample
int handle;
handle=FileOpen("my_data.csv",FILE_CSV|FILE_READ,';');
if(handle<1)
{
Print("File my_data.dat not found, the last error is ", GetLastError());
return(false);
}

int FileOpenHistory(string filename, int mode, int delimiter=';')


Opens file in the current history directory for input and/or output. Returns a file handle for the opened file. If the function fails,
the return value less than 1. To get the detailed error information, call GetLastError().
Parameters
filename - File name, file may be with any extensions.
mode - Open mode. can be one or combination of values: FILE_BIN, FILE_CSV, FILE_READ, FILE_WRITE.
delimiter - Delimiter character for csv files. By default passed ';' symbol.
Sample
int handle=FileOpenHistory("USDX240.HST",FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("Cannot create file USDX240.HST");
return(false);
}
// work with file
// ...
FileClose(handle);

int FileReadArray(int handle, object& array[], int start, int count)


Reads the indicated count of elements from the binary file to array. Returns actual read elements count.
To get the detailed error information, call GetLastError() function. Note: Before reading the data, array must be resized to a
sufficient size.
Parameters
handle - File handle, returned by FileOpen() function.
array[] - Array where data will be stored.
start - Storing start position into array.
count - Count of elements to read.
Sample
int handle;
double varray[10];
handle=FileOpen("filename.dat", FILE_BIN|FILE_READ);
if(handle>0)
{
FileReadArray(handle, varray, 0, 10);
FileClose(handle);
}

int FileReadArray(int handle, object& array[], int start, int count)


Reads the indicated count of elements from the binary file to array. Returns actual read elements count.
To get the detailed error information, call GetLastError() function. Note: Before reading the data, array must be resized to a
sufficient size.
Parameters
handle - File handle, returned by FileOpen() function.
array[] - Array where data will be stored.
start - Storing start position into array.
count - Count of elements to read.
Sample
int handle;
double varray[10];
handle=FileOpen("filename.dat", FILE_BIN|FILE_READ);
if(handle>0)
{
FileReadArray(handle, varray, 0, 10);
FileClose(handle);
}

int FileReadInteger(int handle, int size=LONG_VALUE)


Read the integer from binary files from the current file position. Integer format size can be 1, 2 or 4 bytes length. If the format
size is not specified system attempts to read 4 bytes length value. To get the detailed error information, call GetLastError()
function.
Parameters
handle - File handle, returned by FileOpen() function.
size - Format size. Can be CHAR_VALUE(1 byte), SHORT_VALUE(2 bytes) or LONG_VALUE(4 bytes).
Sample
int handle;
int value;
handle=FileOpen("mydata.dat", FILE_BIN|FILE_READ);
if(handle>0)
{
value=FileReadInteger(h1,2);
FileClose(handle);
}

double FileReadNumber(int handle)


Read the number from the current file position to the delimiter. Only for CSV files. To get the detailed error information, call
GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() function.
Sample
int handle;
int value;
handle=FileOpen("filename.csv", FILE_CSV, ';');
if(handle>0)
{
value=FileReadNumber(handle);
FileClose(handle);
}

string FileReadString(int handle, int length=0)


Read the string from the current file position. Applied to both CSV and binary files. For text files string will be read to the delimiter
and for binary file string will be read for the count of characters indicated. To get the detailed error information, call
GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() function.
length - Reading characters count.
Sample
int handle;
string str;
handle=FileOpen("filename.csv", FILE_CSV|FILE_READ);
if(handle>0)
{
str=FileReadString(handle);
FileClose(handle);
}

bool FileSeek(int handle, int offset, int origin)


Moves the file pointer to a specified location. The FileSeek() function moves the file pointer associated with handle to a new
location that is offset bytes from origin. The next operation on the file occurs at the new location. If successful, function returns
TRUE. Otherwise, it returns FALSE. To get the detailed error information, call GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() functions.
offset - Offset in bytes from origin.
origin - Initial position. Value can be one of this constants:
SEEK_CUR - from current position,
SEEK_SET - from begin,
SEEK_END - from end of file.
Sample
int handle=FileOpen("filename.csv", FILE_CSV|FILE_READ, ';');
if(handle>0)
{
FileSeek(handle, 10, SEEK_SET);
FileReadInteger(handle);
FileClose(handle);
handle=0;
}

int FileSize(int handle)


Returns file size in bytes. To get the detailed error information, call GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() function.
Sample
int handle;
int size;
handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ);
if(handle>0)
{
size=FileSize(handle);
Print("my_table.dat size is ", size, " bytes");
FileClose(handle);
}

int FileSize(int handle)


Returns file size in bytes. To get the detailed error information, call GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() function.
Sample
int handle;
int size;
handle=FileOpen("my_table.dat", FILE_BIN|FILE_READ);
if(handle>0)
{
size=FileSize(handle);
Print("my_table.dat size is ", size, " bytes");
FileClose(handle);
}

int FileWrite(int handle, ... )


Writes to the CSV file some values, delimiter inserted automatically. Returns the number of characters written, or a negative value
if an error occurs. To get the detailed error information, call GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() function.
... - User data to write, separated with commas.
Note: int and double types automatically converted to string,but color, datetime and bool types does not automatically converted
and will be writen to file in it's as integers.
Sample
int handle;
datetime orderOpen=OrderOpenTime();
handle=FileOpen("filename", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
FileWrite(handle, Close[0], Open[0], High[0], Low[0], TimeToStr(orderOpen));
FileClose(handle);
}

int FileWriteArray(int handle, object array[], int start, int count)


Writes array to the binary file. Arrays of type int, bool, datetime and color will be written as 4 bytes integers. Arrays of type
double will be written as 8 bytes floating point numbers. Arrays of string will be written as one string where elements will be
divided by Carriage return and Line feed symbols (0D 0A).
Returns the number of elements wrote, or a negative value if an error occurs. To get the detailed error information, call
GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() function.
array[] - Array to write.
start - Starting index into array to write.
count - Count of elements to write.
Sample
int handle;
double BarOpenValues[10];
// copy first ten bars to the array
for(int i=0;i<10; i++)
BarOpenValues[i]=Open[i];
// writing array to the file
handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE);
if(handle>0)
{
FileWriteArray(handle, BarOpenValues, 3, 7); // writing last 7 elements
FileClose(handle);
}

int FileWriteDouble(int handle, double value, int size=DOUBLE_VALUE)


Writes double value to the binary file. If size is FLOAT_VALUE, value will be written as 4 bytes floating point format, else will be
written in 8 bytes floating point format. Returns actual written bytes count.
To get the detailed error information, call GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() function.
value - Value to write.
size - Optional format flag. It can be any of the following values:
DOUBLE_VALUE (8 bytes, default)
FLOAT_VALUE (4 bytes).
Sample
int handle;
double var1=0.345;
handle=FileOpen("mydata.dat", FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("can't open file error-",GetLastError());
return(0);
}
FileWriteDouble(h1, var1, DOUBLE_VALUE);
//...
FileClose(handle);

int FileWriteInteger(int handle, int value, int size=LONG_VALUE)


Writes integer value to the binary file. If size is SHORT_VALUE, value will be written as 2 bytes integer, if size is CHAR_VALUE,
value will be written as 1 bytes integer and if size is LONG_VALUE, value will be written as 4 bytes integer. Returns actual written
bytes count.
To get the detailed error information, call GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() function.
value - Value to write.
size - Optional format flag. It can be any of the following values:
CHAR_VALUE (1 byte),
SHORT_VALUE (2 bytes),
LONG_VALUE (4 bytes, default).
Sample
int handle;
int value=10;
handle=FileOpen("filename.dat", FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("can't open file error-",GetLastError());
return(0);
}
FileWriteInteger(handle, value, SHORT_VALUE);
//...
FileClose(handle);

int FileWriteString(int handle, string value, int length)


Writes string to the binary file from current file position. Returns actual written bytes count.
To get the detailed error information, call GetLastError() function.
Parameters
handle - File handle, returned by FileOpen() function.
value - Text to write.
length - Counts of characters to write.
Sample
int handle;
string str="some string";
handle=FileOpen("filename.bin", FILE_BIN|FILE_WRITE);
if(handle<1)
{
Print("can't open file error-",GetLastError());
return(0);
}
FileWriteString(h1, str, 8);
FileClose(handle);

Global Variables functions


GlobalVariableCheck()
GlobalVariableDel()
GlobalVariableGet()
GlobalVariableSet()
GlobalVariableSetOnCondition()
GlobalVariablesDeleteAll()

bool GlobalVariableCheck(string name)


Return logical true if global variable exists, otherwise returns false. To get the detailed error information, call GetLastError()
function.
Parameters
name - Global variable name.
Sample
// check variable before use
if(!GlobalVariableCheck("g1"))
GlobalVariableSet("g1",1);

bool GlobalVariableDel(string name)


Deletes global variable. If the function succeeds, the return value will be true. If the function fails, the return value is false. To get
the detailed error information, call GetLastError().
Parameters
name - Global variable name.
Sample
// deleting global variable with name "gvar_1"
GlobalVariableDel("gvar_1");

double GlobalVariableGet(string name)


Returns global variable value. To check function failure, check error information by calling GetLastError().
Parameters
name - Global variable name.
Sample
double v1=GlobalVariableGet("g1");
//---- check function call result
if(GetLastError()!=0) return(false);
//---- continue processing

datetime GlobalVariableSet(string name, double value)


Sets global variable value. If it does not exist, the system creates a new variable. If the function succeeds, the return value is last
access time. If the function fails, the return value is 0. To get the detailed error information, call GetLastError().
Parameters
name - Global variable name.
value - Numeric value to set.
Sample
//---- try to set new value
if(GlobalVariableSet("BarsTotal",Bars)==0)
return(false);
//---- continue processing
bool GlobalVariableSetOnCondition(string name, double value, double check_value)
Sets the new value of the global variable if the current value equals to the third parameter check_value. If there is no variable at
all, the function will return false and set the value of ERR_GLOBAL_VARIABLE_NOT_FOUND constant to LastError. When
successfully executed, the function returns true, otherwise it does false. To receive the information about the error, call
GetLastError() function.
The function can be used as a semaphore for the access to common resources.
Parameters
name - Global variable name.
value - Numeric value to set.
check_value - Value to compare with the current global variable value.
Sample
int init()
{
//---- create global variable
GlobalVariableSet("DATAFILE_SEM",0);
//...
}

int start()
{
//---- try to lock common resource
while(!IsStopped())
{
//---- locking
if(GlobalVariableSetOnCondition("DATAFILE_SEM",1,0)==true) break;
//---- may be variable deleted?
if(GetLastError()==ERR_GLOBAL_VARIABLE_NOT_FOUND) return(0);
//---- sleeping
Sleep(500);
}
//---- resource locked
// ... do some work
//---- unlock resource
GlobalVariableSet("DATAFILE_SEM",0);
}

void GlobalVariablesDeleteAll()
Deletes all global variables. This function never fails.
Sample
GlobalVariablesDeleteAll();

Math & Trig


MathAbs()
MathArccos()
MathArcsin()
MathArctan()
MathCeil()
MathCos()
MathExp()
MathFloor()
MathLog()
MathMax()
MathMin()
MathMod()
MathPow()
MathRand()
MathRound()
MathSin()
MathSqrt()
MathSrand()
MathTan()

double MathAbs(double value)


Returns the absolute value (modulus) of the specified numeric value.
Parameters
value - Numeric value.
Sample
double dx=-3.141593, dy;
// calc MathAbs
dy=MathAbs(dx);
Print("The absolute value of ",dx," is ",dy);
// Output: The absolute value of -3.141593 is 3.141593

double MathArccos(double x)
The MathArccos function returns the arccosine of x in the range 0 to π radians. If x is less than -1 or greater than 1, MathArccos
returns an indefinite (same as a quiet NaN).
Parameters
x - Value between -1 and 1 arc cosine of which should be calculated.
Sample
double x=0.32696, y;
y=asin(x);
Print("Arcsine of ",x," = ",y);
y=acos(x);
Print("Arccosine of ",x," = ",y);
//Output: Arcsine of 0.326960=0.333085
//Output: Arccosine of 0.326960=1.237711

double MathArcsin(double x)
The MathArcsin function returns the arcsine of x in the range -π/2 to π/2 radians. If x is less than -1 or greater than 1, arcsine
returns an indefinite (same as a quiet NaN).
Parameters
x - Value the arcsine of which should be calculated
Sample
double x=0.32696, y;
y=MathArcsin(x);
Print("Arcsine of ",x," = ",y);
y=acos(x);
Print("Arccosine of ",x," = ",y);
//Output: Arcsine of 0.326960=0.333085
//Output: Arccosine of 0.326960=1.237711
double MathArctan(double x)
The MathArctan returns the arctangent of x. If x is 0, MathArctan returns 0. MathArctan returns a value in the range -π/2 to π/2
radians.
Parameters
x - A number representing a tangent.
Sample
double x=-862.42, y;
y=MathArctan(x);
Print("Arctangent of ",x," is ",y);
//Output: Arctangent of -862.42 is -1.5696

double MathCeil(double x)
The MathCeil function returns a numeric value representing the smallest integer that is greater than or equal to x.
Parameters
x - Numeric value.
Sample
double y;
y=MathCeil(2.8);
Print("The ceil of 2.8 is ",y);
y=MathCeil(-2.8);
Print("The ceil of -2.8 is ",y);
/*Output:
The ceil of 2.8 is 3
The ceil of -2.8 is -2*/

double MathCos(double value)


Returns the cosine of the specified angle.
Parameters
value - An angle, measured in radians.
Sample
double pi=3.1415926535;
double x, y;
x=pi/2;
y=MathSin(x);
Print("MathSin(",x,") = ",y);
y=MathCos(x);
Print("MathCos(",x,") = ",y);
//Output: MathSin(1.5708)=1
// MathCos(1.5708)=0

double MathExp(double d)
Returns value the number e raised to the power d. On overflow, the function returns INF (infinite) and on underflow, MathExp
returns 0.
Parameters
d - A number specifying a power.
Sample
double x=2.302585093,y;
y=MathExp(x);
Print("MathExp(",x,") = ",y);
//Output: MathExp(2.3026)=10

double MathFloor(double x)
The MathFloor function returns a numeric value representing the largest integer that is less than or equal to x.
Parameters
x - Numeric value.
Sample
double y;
y=MathFloor(2.8);
Print("The floor of 2.8 is ",y);
y=MathFloor(-2.8);
Print("The floor of -2.8 is ",y);
/*Output:
The floor of 2.8 is 2
The floor of -2.8 is -3*/

double MathLog(double x)
The MathLog functions return the logarithm of x if successful. If x is negative, these functions return an indefinite (same as a
quiet NaN). If x is 0, they return INF (infinite).
Parameters
x - Value whose logarithm is to be found.
Sample
double x=9000.0,y;
y=MathLog(x);
Print("MathLog(",x,") = ", y);
//Output: MathLog(9000)=9.10498

double MathMax(double value1, double value2)


Returns maximum value of two numeric values.
Parameters
value1 - First numeric value.
value2 - Second numeric value.
Sample
double result=MathMax(1.08,Bid);

double MathMin(double value1, double value2)


Returns minimum value of two numeric values.
Parameters
value1 - First numeric value.
value2 - Second numeric value.
Sample
double result=MathMin(1.08,Ask);

double MathMod(double value, double value2)


Divides two numbers and returns only the remainder.
Parameters
value - Dividend value.
value2 - Divider value.
Sample
double x=-10.0,y=3.0,z;
z=MathMod(x,y);
Print("The remainder of ",x," / ",y," is ",z);
//Output: The remainder of -10 / 3 is -1

double MathPow(double base, double exponent)


Returns the value of a base expression taken to a specified power.
Parameters
base - Base value.
exponent - Exponent value.
Sample
double x=2.0,y=3.0,z;
z=MathPow(x,y);
Printf(x," to the power of ",y," is ", z);
//Output: 2 to the power of 3 is 8
int MathRand()
The MathRand function returns a pseudorandom integer in the range 0 to 0x7fff (32767). Use the MathSrand function to seed the
pseudorandom-number generator before calling rand.
Sample
MathSrand(LocalTime());
// Display 10 numbers.
for(int i=0;i<10;i++ )
Print("random value ", MathRand());

double MathRound(double value)


Returns value rounded to the nearest integer of the specified numeric value.
Parameters
value - Numeric value to round.
Sample
double y=MathRound(2.8);
Print("The round of 2.8 is ",y);
y=MathRound(2.4);
Print("The round of -2.4 is ",y);
//Output: The round of 2.8 is 3
// The round of -2.4 is -2
double MathSin(double value)
Returns the sine of the specified angle.
Parameters
value - An angle, measured in radians.
Sample
double pi=3.1415926535;
double x, y;
x=pi/2;
y=MathSin(x);
Print("MathSin(",x,") = ",y);
y=MathCos(x);
Print("MathCos(",x,") = ",y);
//Output: MathSin(1.5708)=1
// MathCos(1.5708)=0

double MathSqrt(double x)
The MathSqrt function returns the square-root of x. If x is negative, MathSqrt returns an indefinite (same as a quiet NaN).
Parameters
x - Positive numeric value.
Sample
double question=45.35, answer;
answer=MathSqrt(question);
if(question<0)
Print("Error: MathSqrt returns ",answer," answer");
else
Print("The square root of ",question," is ", answer);
//Output: The square root of 45.35 is 6.73

void MathSrand(int seed)


The MathSrand() function sets the starting point for generating a series of pseudorandom integers. To reinitialize the generator,
use 1 as the seed argument. Any other value for seed sets the generator to a random starting point. MathRand retrieves the
pseudorandom numbers that are generated. Calling MathRand before any call to MathSrand generates the same sequence as
calling MathSrand with seed passed as 1.
Parameters
seed - Seed for random-number generation.
Sample
MathSrand(LocalTime());
// Display 10 numbers.
for(int i=0;i<10;i++ )
Print("random value ", MathRand());

double MathTan(double x)
MathTan returns the tangent of x. If x is greater than or equal to 263, or less than or equal to -263, a loss of significance in the
result occurs, in which case the function returns an indefinite (same as a quiet NaN).
Parameters
x - Angle in radians.
Sample
double pi=3.1415926535;
double x,y;
x=MathTan(pi/4);
Print("MathTan(",pi/4," = ",x);
//Output: MathTan(0.7856)=1

Object functions
ObjectCreate()
ObjectDelete()
ObjectDescription()
ObjectFind()
ObjectGet()
ObjectGetFiboDescription()
ObjectGetShiftByValue()
ObjectGetValueByShift()
ObjectGetVisibility()
ObjectMove()
ObjectName()
ObjectsDeleteAll()
ObjectSet()
ObjectSetFiboDescription()
ObjectSetText()
ObjectSetVisibility()
ObjectsRedraw
ObjectsTotal()
ObjectType()

bool string name, int type, int window, datetime time1, double price1,
ObjectCreate( datetime time2=0, double price2=0, datetime time3=0, double price3=0)
Create object with specified name, type and initial coordinates in the specified window. Count of coordinates related from object
type (1-3). If the function succeeds, the return value will be true. If the function succeeds, the return value is true. If the function
fails, the return value is false. To get the detailed error information, call GetLastError(). For objects with type OBJ_LABEL first
coordinate ignored. To set coordinate for label use ObjectSet() function to set OBJPROP_XDISTANCE and OBJPROP_YDISTANCE
properties.
Note: Coordinates must be passed with both part - time and price. For example: Object OBJ_VLINE required 1 coordinate part
time. But function wants also the seconds part of coordinate price.
Parameters
name - Unique object name.
type - Object type. It can be any of the Object type enumeration values.
window - Window index where object will be added. Window index must be greater or equal to 0 and less than WindowsTotal().
time1 - Time part of first point.
price1 - Price part of first point.
time2 - Time part of second point.
price2 - Price part of second point.
time3 - Time part of third point.
price3 - Price part of third point.
Sample
// new text object
if(!ObjectCreate("text_object", OBJ_TEXT, 0, D'2004.02.20 12:30', 1.0045))
{
Print("error: can't create text_object! code #",GetLastError());
return(0);
}
// new label object
if(!ObjectCreate("label_object", OBJ_LABEL, 0, 0, 0))
{
Print("error: can't create label_object! code #",GetLastError());
return(0);
}
ObjectSet("label_object", OBJPROP_XDISTANCE, 200);
ObjectSet("label_object", OBJPROP_YDISTANCE, 100);

bool ObjectDelete(string name)


Deletes object with specified name. If the function succeeds, the return value will be true. If the function succeeds, the return
value is true. If the function fails, the return value is false. To get the detailed error information, call GetLastError().
Parameters
name - Deleting object name.
Sample
ObjectDelete("text_object");

string ObjectDescription(string name)


Return object description. To get error information, call GetLastError() function.
Parameters
name - Object name.
Sample
// writing chart's object list to the file
int handle, total;
string obj_name,fname;
// file name
fname="objlist_"+Symbol();
handle=FileOpen(fname,FILE_CSV|FILE_WRITE);
if(handle!=false)
{
total=ObjectsTotal();
for(int i=-;i<total;i++)
{
obj_name=ObjectName(i);
FileWrite(handle,"Object "+obj_name+" description=
"+ObjectDescription(obj_name));
}
FileClose(handle);
}

int ObjectFind(string name)


Return object owner's window index. If the function fails, the return value will be -1. To get the detailed error information, call
GetLastError() function.
Parameters
name - Object name to check.
Sample
if(ObjectFind("line_object2")!=win_idx) return(0);
double ObjectGet(string name, int index)
Returns objects property value by index. To check errors, call GetLastError() function.
Parameters
name - Object name.
index - Object property index. It can be any of the Object properties enumeration values.
Sample
color oldColor=ObjectGet("hline12", OBJPROP_COLOR);

string ObjectGetFiboDescription(string name, int index)


Function returns description of Fibonacci level. The amount of Fibonacci levels depends on the object type. The maximum amount
of Fibonacci levels never exceeds 32.
To get the detailed error information, call GetLastError() function.
Parameters
name - Object name.
index - Index of the Fibonacci level.
Sample
#include <stdlib.mqh>
...
string text;
for(int i=0;i<32;i++)
{
text=ObjectGetFiboDescription(MyObjectName,i);
//---- check. may be objects's level count less than 32
if(GetLastError()!=ERR_NO_ERROR) break;
Print(MyObjectName,"level: ",i," description: ",text);
}

int ObjectGetShiftByValue(string name, double value)


Calculates and returns bar index for the indicated price. Calculated by first and second coordinate. Applied to trendlines. To get
the detailed error information, call GetLastError() function.
Parameters
name - Object name.
value - Price value.
Sample
int shift=ObjectGetShiftByValue("MyTrendLine#123", 1.34);

double ObjectGetValueByShift(string name, int shift)


Calculates and returns price value for the indicated bar. Calculated by first and second coordinate. Applied to trendlines. To get
the detailed error information, call GetLastError() function.
Parameters
name - Object name
shift - Bar index.
Sample
double price=ObjectGetValueByShift("MyTrendLine#123", 11);

int ObjectGetVisibility(string name)


Function returns flags of the object visibility on the chart. Value can be single or combined (bitwise addition) of object visibility
constants.
Parameters
name - Object name.
Sample
// is object visible on the chart?
if((ObjectGetVisibility()&OBJ_PERIOD_M5)!=0 && Period()==PERIOD_M5)
{
// working with object
}

bool ObjectMove(string name, int point, datetime time1, double price1)


Moves objects point on the chart. Objects can have from one to three points related to its type. If the function succeeds, the
return value will be true. If the function fails, the return value will be false. To get the detailed error information, call
GetLastError().
Parameters
name - Object name.
point - Coordinate index.
time1 - New time value.
price1 - New price value.
Sample
ObjectMove("MyTrend", 1, D'2005.02.25 12:30', 1.2345);

string ObjectName(int index)


Returns object name by index.
Parameters
index - Object index on the chart. Object index must be greater or equal to 0 and less than ObjectsTotal().
Sample
int obj_total=ObjectsTotal();
string name;
for(int i=0;i<obj_total;i++)
{
name=ObjectName(i);
Print(i,"Object name is " + name);
}

int ObjectsDeleteAll(int window, int type=EMPTY)


Removes all objects with specified type and on the specified subwindow of the chart. Returns removed objects count.
Parameters
window - Window index from objects will be deleted. Window index must be greater or equal to 0 and less than WindowsTotal().
type - Optional object type to delete.It can be any of the Object type enumeration values or EMPTY constant to delete all objects with
any types.
Sample
ObjectsDeleteAll(2, OBJ_HLINE); // removes all horizontal line objects from window
3 (index 2).

bool ObjectSet(string name, int index, double value)


Changes named objects property with new value. If the function succeeds, the return value will be true. If the function fails, the
return value will be false. To get the detailed error information, call GetLastError().
Parameters
name - Object name.
index - Object value index. It can be any of Object properties enumeration values.
value - New value for property.
Sample
// moving first coord to last bar time
ObjectSet("MyTrend", OBJPROP_TIME1, Time[0]);
// setting second fibo level
ObjectSet("MyFibo", OBJPROP_FIRSTLEVEL+1, 1.234);
// setting object visibility. object will be shown only on 15 minute and 1 hour
charts
ObjectSet("MyObject", OBJPROP_TIMEFRAMES, OBJ_PERIOD_M15 | OBJ_PERIOD_H1);

bool ObjectSetFiboDescription(string name, int index, string text)


Function assigns a new description to a Fibonacci level. The amount of Fibonacci levels depends on the object type. The maximum
amount of Fibonacci levels never exceeds 32.
To get the detailed error information, call GetLastError() function.
Parameters
name - Object name.
index - Index of the Fibonacci level (0-31).
text - New description to be assigned to the Fibonacci level.
Sample
ObjectSetFiboDescription("MyFiboObject,2,"Second line");

bool string name, string text, int font_size, string font=NULL,


ObjectSetText( color text_color=CLR_NONE)
Sets object description. If the function succeeds, the return value will be true. If the function fails, the return value will be false.
To get the detailed error information, call GetLastError() function.
Parameters
name - Object name.
text - Some text.
font_size - Font size in points.
font - Font name.
text_color - Text color.
Sample
ObjectSetText("text_object", "Hello world!", 10, "Times New Roman", Green);

int ObjectSetVisibility(string name, int flag)


Function sets new value to the object visibility property. Function returns previous value.
Parameters
name - Object name.
flag - New value of the object visibility property. Value can be single or combined (bitwise addition) of object visibility constants.
Sample
// The object will be shown on 1-hour charts only.
ObjectSetVisibility("MyObj1",OBJ_PERIOD_H1);

void ObjectsRedraw()
Redraws all objects on the char.
Sample
ObjectsRedraw();

int ObjectsTotal()
Returns total count of objects on the chart.
Sample
int obj_total=ObjectsTotal();
string name;
for(int i=0;i<obj_total;i++)
{
name=ObjectName(i);
Print(i,"Object name is for object #",i," is " + name);
}

int ObjectType(string name)


Returns Object type enumeration value.
Parameters
name - Object name.
Sample
if(ObjectType("line_object2")!=OBJ_HLINE) return(0);

Pre-defined Variables
Ask
Bars
Bid
Close
Digits
High
Low
Open
Point
Time
Volume

double Ask

Ask price (the Buyer's price).

if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25)
{
OrderSend(Symbol(),OP_BUY,Lots,Ask,3,Ask-StopLoss*Point,Ask+TakeProfit*Point,
"My order #2",3,D'2005.10.10 12:30',Red);
return;
}
int Bars

Number of bars on the chart.

int counter=1;
for(int i=1;i<=Bars;i++)
{
Print(Close[i-1]);
}

double Bid

Bid price (the Seller's price).

if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)
{
OrderSend("EURUSD",OP_SELL,Lots,Bid,3,Bid+StopLoss*Point,Bid-TakeProfit*Point,
"My order #2",3,D'2005.10.10 12:30',Red);
return(0);
}

double Close[]

Returns the closing price of the bar being referenced.

int handle, bars=Bars;


handle=FileOpen("file.csv",FILE_CSV|FILE_WRITE,';');
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// write data
for(int i=0; i<bars; i++)
FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]);
FileClose(handle);
}

int Digits

Number of digits after decimal point for the current symbol.

Print(DoubleToStr(Close[i-1], Digits));

double High[]
Returns the highest price of the bar referenced.

int handle, bars=Bars;


handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// write data
for(int i=0; i<bars; i++)
FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]);
FileClose(handle);
}

double Low[]

Returns the lowest price of the bar referenced.

int handle, bars=Bars;


handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ";");
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// write data
for(int i=0; i<bars; i++)
FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]);
FileClose(handle);
}

double Open[]

Returns the opening price of the bar referenced.

int handle, bars=Bars;


handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// write data
for(int i=0; i<bars; i++)
FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]);
FileClose(handle);
}

double Point

Point value for the current chart.


OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,Red);

datetime Time[]

Open time of the bars. Datetime is the number of seconds elapsed from 00:00 January 1, 1970.

int handle, bars=Bars;


handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// write data
for(int i=0; i<bars; i++)
FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]);
FileClose(handle);
}

double Volume[]

Returns the ticks count for the referenced bar.

int handle, bars=Bars;


handle=FileOpen("file.csv", FILE_CSV|FILE_WRITE, ';');
if(handle>0)
{
// write table columns headers
FileWrite(handle, "Time;Open;High;Low;Close;Volume");
// erite data
for(int i=0; i<bars; i++)
FileWrite(handle, Time[i], Open[i], High[i], Low[i], Close[i], Volume[i]);
FileClose(handle);
}

Standard Constants
Applied price enumeration
Drawing shape style enumeration
Error codes
Ichimoku Kinko Hyo modes enumeration
Indicators line identifiers
Market information identifiers
MessageBox return codes
MessageBox behavior flags
Moving Average method enumeration
Object properties enumeration
Object type enumeration
Object visibility enumeration
Predefined Arrow codes enumeration
Series array identifier
Special constants
Time frame enumeration
Trade operation enumeration
Uninitialize reason codes
Wingdings symbols
Web colors table

Applied price enumeration


Applied price constants. It can be any of the following values:
Constant Value Description
PRICE_CLOSE 0 Close price.
PRICE_OPEN 1 Open price.
PRICE_HIGH 2 High price.
PRICE_LOW 3 Low price.
PRICE_MEDIAN 4 Median price, (high+low)/2.
PRICE_TYPICAL 5 Typical price, (high+low+close)/3.
PRICE_WEIGHTED 6 Weighted close price, (high+low+close+close)/4.

Drawing shape style enumeration


Drawing shape style enumeration for SetIndexStyle() function.
It can be any of the following values:
Constant Value Description
DRAW_LINE 0 Drawing line.
DRAW_SECTION 1 Drawing sections.
DRAW_HISTOGRAM 2 Drawing histogram.
DRAW_ARROW 3 Drawing arrows (symbols).
DRAW_NONE 12 No drawing.
Drawing style. Valid when width=1. It can be any of the
following values:
Constant Value Description
STYLE_SOLID 0 The pen is solid.
STYLE_DASH 1 The pen is dashed.
STYLE_DOT 2 The pen is dotted.
STYLE_DASHDOT 3 The pen has alternating dashes and dots.
STYLE_DASHDOTDOT 4 The pen has alternating dashes and double dots.

Error codes
The GetLastError() function return codes. Error code constants defined at stderror.mqh file. To print text messages
use ErrorDescription() function defined at stdlib.mqh file.
#include <stdlib.mqh>
void SendMyMessage(string text)
{
int check;
SendMail("some subject", text);
check=GetLastError();
if(check!=ERR_NO_MQLERROR) Print("Cannot send message, error:
",ErrorDescription(check));
}

Error codes returned from trade server.


Constant Value Description
ERR_NO_ERROR 0 No error returned.
ERR_NO_RESULT 1 No error returned, but the result is unknown.
ERR_COMMON_ERROR 2 Common error.
ERR_INVALID_TRADE_PARAMETERS 3 Invalid trade parameters.
ERR_SERVER_BUSY 4 Trade server is busy.
ERR_OLD_VERSION 5 Old version of the client terminal.
ERR_NO_CONNECTION 6 No connection with trade server.
ERR_NOT_ENOUGH_RIGHTS 7 Not enough rights.
ERR_TOO_FREQUENT_REQUESTS 8 Too frequent requests.
ERR_MALFUNCTIONAL_TRADE 9 Malfunctional trade operation.
ERR_ACCOUNT_DISABLED 64 Account disabled.
ERR_INVALID_ACCOUNT 65 Invalid account.
ERR_TRADE_TIMEOUT 128 Trade timeout.
ERR_INVALID_PRICE 129 Invalid price.
ERR_INVALID_STOPS 130 Invalid stops.
ERR_INVALID_TRADE_VOLUME 131 Invalid trade volume.
ERR_MARKET_CLOSED 132 Market is closed.
ERR_TRADE_DISABLED 133 Trade is disabled.
ERR_NOT_ENOUGH_MONEY 134 Not enough money.
ERR_PRICE_CHANGED 135 Price changed.
ERR_OFF_QUOTES 136 Off quotes.
ERR_BROKER_BUSY 137 Broker is busy.
ERR_REQUOTE 138 Requote.
ERR_ORDER_LOCKED 139 Order is locked.
ERR_LONG_POSITIONS_ONLY_ALLOWED 140 Long positions only allowed.
ERR_TOO_MANY_REQUESTS 141 Too many requests.
ERR_TRADE_MODIFY_DENIED 145 Modification denied because order too close to market.
ERR_TRADE_CONTEXT_BUSY 146 Trade context is busy.
MQL4 run time error codes
Constant Value Description
ERR_NO_MQLERROR 4000 No error.
ERR_WRONG_FUNCTION_POINTER 4001 Wrong function pointer.
ERR_ARRAY_INDEX_OUT_OF_RANGE 4002 Array index is out of range.
ERR_NO_MEMORY_FOR_FUNCTION_CALL_STACK 4003 No memory for function call stack.
ERR_RECURSIVE_STACK_OVERFLOW 4004 Recursive stack overflow.
ERR_NOT_ENOUGH_STACK_FOR_PARAMETER 4005 Not enough stack for parameter.
ERR_NO_MEMORY_FOR_PARAMETER_STRING 4006 No memory for parameter string.
ERR_NO_MEMORY_FOR_TEMP_STRING 4007 No memory for temp string.
ERR_NOT_INITIALIZED_STRING 4008 Not initialized string.
ERR_NOT_INITIALIZED_ARRAYSTRING 4009 Not initialized string in array.
ERR_NO_MEMORY_FOR_ARRAYSTRING 4010 No memory for array string.
ERR_TOO_LONG_STRING 4011 Too long string.
ERR_REMAINDER_FROM_ZERO_DIVIDE 4012 Remainder from zero divide.
ERR_ZERO_DIVIDE 4013 Zero divide.
ERR_UNKNOWN_COMMAND 4014 Unknown command.
ERR_WRONG_JUMP 4015 Wrong jump (never generated error).
ERR_NOT_INITIALIZED_ARRAY 4016 Not initialized array.
ERR_DLL_CALLS_NOT_ALLOWED 4017 DLL calls are not allowed.
ERR_CANNOT_LOAD_LIBRARY 4018 Cannot load library.
ERR_CANNOT_CALL_FUNCTION 4019 Cannot call function.
ERR_EXTERNAL_EXPERT_CALLS_NOT_ALLOWED 4020 Expert function calls are not allowed.
ERR_NOT_ENOUGH_MEMORY_FOR_RETURNED_STRING 4021 Not enough memory for temp string returned from function.
ERR_SYSTEM_BUSY 4022 System is busy (never generated error).
ERR_INVALID_FUNCTION_PARAMETERS_COUNT 4050 Invalid function parameters count.
ERR_INVALID_FUNCTION_PARAMETER_VALUE 4051 Invalid function parameter value.
ERR_STRING_FUNCTION_INTERNAL_ERROR 4052 String function internal error.
ERR_SOME_ARRAY_ERROR 4053 Some array error.
ERR_INCORRECT_SERIES_ARRAY_USING 4054 Incorrect series array using.
ERR_CUSTOM_INDICATOR_ERROR 4055 Custom indicator error.
ERR_INCOMPATIBLE_ARRAYS 4056 Arrays are incompatible.
ERR_GLOBAL_VARIABLES_PROCESSING_ERROR 4057 Global variables processing error.
ERR_GLOBAL_VARIABLE_NOT_FOUND 4058 Global variable not found.
ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE 4059 Function is not allowed in testing mode.
ERR_FUNCTION_NOT_CONFIRMED 4060 Function is not confirmed.
ERR_SEND_MAIL_ERROR 4061 Send mail error.
ERR_STRING_PARAMETER_EXPECTED 4062 String parameter expected.
ERR_INTEGER_PARAMETER_EXPECTED 4063 Integer parameter expected.
ERR_DOUBLE_PARAMETER_EXPECTED 4064 Double parameter expected.
ERR_ARRAY_AS_PARAMETER_EXPECTED 4065 Array as parameter expected.
ERR_HISTORY_WILL_UPDATED 4066 Requested history data in updating state.
ERR_END_OF_FILE 4099 End of file.
ERR_SOME_FILE_ERROR 4100 Some file error.
ERR_WRONG_FILE_NAME 4101 Wrong file name.
ERR_TOO_MANY_OPENED_FILES 4102 Too many opened files.
ERR_CANNOT_OPEN_FILE 4103 Cannot open file.
Ichimoku Kinko Hyo modes enumeration
Ichimoku Kinko Hyo source of data. Used in iIchimoku() indicators.
It can be one of the following values:
Constant Value Description
MODE_TENKANSEN 1 Tenkan-sen.
MODE_KIJUNSEN 2 Kijun-sen.
MODE_SENKOUSPANA 3 Senkou Span A.
MODE_SENKOUSPANB 4 Senkou Span B.
MODE_CHINKOUSPAN 5 Chinkou Span.

Indicators line identifiers


Indicator line identifiers used in iMACD(), iRVI() and iStochastic() indicators.
It can be one of the following values:
Constant Value Description
MODE_MAIN 0 Base indicator line.
MODE_SIGNAL 1 Signal line.
Indicator line identifiers used in iADX() indicator.
Constant Value Description
MODE_MAIN 0 Base indicator line.
MODE_PLUSDI 1 +DI indicator line.
MODE_MINUSDI 2 -DI indicator line.
Indicator line identifiers used in iBands(), iEnvelopes(),
iEnvelopesOnArray(), iFractals() and iGator() indicators.
Constant Value Description
MODE_UPPER 1 Upper line.
MODE_LOWER 2 Lower line.

Market information identifiers


Market information identifiers, used with MarketInfo() function.
It can be any of the following values:
Constant Value Description
MODE_LOW 1 Low day price.
MODE_HIGH 2 High day price.
MODE_TIME 5 The last incoming quotation time.
MODE_BID 9 Last incoming bid price.
MODE_ASK 10 Last incoming ask price.
MODE_POINT 11 Point size.
MODE_DIGITS 12 Digits after decimal point.
MODE_SPREAD 13 Spread value in points.
MODE_STOPLEVEL 14 Stop level in points.
MODE_LOTSIZE 15 Lot size in the base currency.
MODE_TICKVALUE 16 Tick value.
MODE_TICKSIZE 17 Tick size.
MODE_SWAPLONG 18 Swap of the long position.
MODE_SWAPSHORT 19 Swap of the short position.
MODE_STARTING 20 Market starting date (usually used for future markets).
MODE_EXPIRATION 21 Market expiration date (usually used for future markets).
MODE_TRADEALLOWED 22 Trade is allowed for the symbol.
MODE_MINLOT 22 The minimum lot size in points.
MODE_LOTSTEP 22 Step for changing lots in points.

MessageBox return codes

The MessageBox() function return codes.


If a message box has a Cancel button, the function returns the IDCANCEL value if either the ESC key is pressed or
the Cancel button is selected. If the message box has no Cancel button, pressing ESC has no effect.
Note: MessageBox return codes defined in the WinUser32.mqh file

Constant Value Description


IDOK 1 OK button was selected.
IDCANCEL 2 Cancel button was selected.
IDABORT 3 Abort button was selected.
IDRETRY 4 Retry button was selected.
IDIGNORE 5 Ignore button was selected.
IDYES 6 Yes button was selected.
IDNO 7 No button was selected.
IDTRYAGAIN 10 Try Again button was selected.
IDCONTINUE 11 Continue button was selected.

MessageBox behavior flags

The MessageBox function flags specify the contents and behavior of the dialog box. This value can be a
combination of flags from the following groups of flags.
Note: MessageBox return codes defined in the WinUser32.mqh file

To indicate the buttons displayed in the message box, specify one of the following values.
Constant Value Description
MB_OK 0x00000000 The message box contains one push button: OK. This is the default.
MB_OKCANCEL 0x00000001 The message box contains two push buttons: OK and Cancel.
MB_ABORTRETRYIGNORE 0x00000002 The message box contains three push buttons: Abort, Retry, and Ignore.
MB_YESNOCANCEL 0x00000003 The message box contains three push buttons: Yes, No, and Cancel.
MB_YESNO 0x00000004 The message box contains two push buttons: Yes and No.
MB_RETRYCANCEL 0x00000005 The message box contains two push buttons: Retry and Cancel.
Windows 2000: The message box contains three push buttons: Cancel, Try Again,
MB_CANCELTRYCONTINUE 0x00000006
Continue. Use this message box type instead of MB_ABORTRETRYIGNORE.
To display an icon in the message box, specify one of the following values.

Constant Value Description


MB_ICONSTOP, MB_ICONERROR, MB_ICONHAND 0x00000010 A stop-sign icon appears in the message box.
MB_ICONQUESTION 0x00000020 A question-mark icon appears in the message box.
MB_ICONEXCLAMATION, MB_ICONWARNING 0x00000030 An exclamation-point icon appears in the message box.
An icon consisting of a lowercase letter i in a circle appears in
MB_ICONINFORMATION, MB_ICONASTERISK 0x00000040
the message box.
To indicate the default button, specify one of the following values.

Constant Value Description


The first button is the default button. MB_DEFBUTTON1 is the default unless
MB_DEFBUTTON1 0x00000000
MB_DEFBUTTON2, MB_DEFBUTTON3, or MB_DEFBUTTON4 is specified.
MB_DEFBUTTON2 0x00000100 The second button is the default button.
MB_DEFBUTTON3 0x00000200 The third button is the default button.
MB_DEFBUTTON4 0x00000300 The fourth button is the default button.

Moving Average method enumeration


Moving Average calculation method. used with iAlligator(), iEnvelopes(), iEnvelopesOnArray, iForce(), iGator(), iMA(),
iMAOnArray(), iStdDev(), iStdDevOnArray(), iStochastic() indicators.
It can be any of the following values:
Constant Value Description
MODE_SMA 0 Simple moving average,
MODE_EMA 1 Exponential moving average,
MODE_SMMA 2 Smoothed moving average,
MODE_LWMA 3 Linear weighted moving average.

Object properties enumeration


Object value index used with ObjectGet() and ObjectSet() functions. It can be any of the following values:
Constant Value Description
OBJPROP_TIME1 0 Datetime value to set/get first coordinate time part.
OBJPROP_PRICE1 1 Double value to set/get first coordinate price part.
OBJPROP_TIME2 2 Datetime value to set/get second coordinate time part.
OBJPROP_PRICE2 3 Double value to set/get second coordinate price part.
OBJPROP_TIME3 4 Datetime value to set/get third coordinate time part.
OBJPROP_PRICE3 5 Double value to set/get third coordinate price part.
OBJPROP_COLOR 6 Color value to set/get object color.
Value is one of STYLE_SOLID, STYLE_DASH, STYLE_DOT, STYLE_DASHDOT,
OBJPROP_STYLE 7
STYLE_DASHDOTDOT constants to set/get object line style.
OBJPROP_WIDTH 8 Integer value to set/get object line width. Can be from 1 to 5.
OBJPROP_BACK 9 Boolean value to set/get background drawing flag for object.
OBJPROP_RAY 10 Boolean value to set/get ray flag of object.
OBJPROP_ELLIPSE 11 Boolean value to set/get ellipse flag for fibo arcs.
OBJPROP_SCALE 12 Double value to set/get scale object property.
OBJPROP_ANGLE 13 Double value to set/get angle object property in degrees.
OBJPROP_ARROWCODE 14 Integer value or arrow enumeration to set/get arrow code object property.
Value can be one or combination (bitwise addition) of object visibility constants to set/get
OBJPROP_TIMEFRAMES 15
timeframe object property.
OBJPROP_DEVIATION 16 Double value to set/get deviation property for Standard deviation objects.
OBJPROP_FONTSIZE 100 Integer value to set/get font size for text objects.
OBJPROP_CORNER 101 Integer value to set/get anchor corner property for label objects. Must be from 0-3.
OBJPROP_XDISTANCE 102 Integer value to set/get anchor X distance object property in pixels.
OBJPROP_YDISTANCE 103 Integer value is to set/get anchor Y distance object property in pixels.
OBJPROP_FIBOLEVELS 200 Integer value to set/get Fibonacci object level count. Can be from 0 to 32.
OBJPROP_FIRSTLEVEL+n 210 Fibonacci object level index, where n is level index to set/get. Can be from 0 to 31.

Object type enumeration


Object type identifier constants used with ObjectCreate(), ObjectsDeleteAll() and ObjectType() functions. It can be
any of the following values:
Objects can have 1-3 coordinates related to type.
Constant Value Description
OBJ_VLINE 0 Vertical line. Uses time part of first coordinate.
OBJ_HLINE 1 Horizontal line. Uses price part of first coordinate.
OBJ_TREND 2 Trend line. Uses 2 coordinates.
OBJ_TRENDBYANGLE 3 Trend by angle. Uses 1 coordinate. To set angle of line use ObjectSet() function.
OBJ_REGRESSION 4 Regression. Uses time parts of first two coordinates.
OBJ_CHANNEL 5 Channel. Uses 3 coordinates.
OBJ_STDDEVCHANNEL 6 Standard deviation channel. Uses time parts of first two coordinates.
OBJ_GANNLINE 7 Gann line. Uses 2 coordinate, but price part of second coordinate ignored.
OBJ_GANNFAN 8 Gann fan. Uses 2 coordinate, but price part of second coordinate ignored.
OBJ_GANNGRID 9 Gann grid. Uses 2 coordinate, but price part of second coordinate ignored.
OBJ_FIBO 10 Fibonacci retracement. Uses 2 coordinates.
OBJ_FIBOTIMES 11 Fibonacci time zones. Uses 2 coordinates.
OBJ_FIBOFAN 12 Fibonacci fan. Uses 2 coordinates.
OBJ_FIBOARC 13 Fibonacci arcs. Uses 2 coordinates.
OBJ_EXPANSION 14 Fibonacci expansions. Uses 3 coordinates.
OBJ_FIBOCHANNEL 15 Fibonacci channel. Uses 3 coordinates.
OBJ_RECTANGLE 16 Rectangle. Uses 2 coordinates.
OBJ_TRIANGLE 17 Triangle. Uses 3 coordinates.
OBJ_ELLIPSE 18 Ellipse. Uses 2 coordinates.
OBJ_PITCHFORK 19 Andrews pitchfork. Uses 3 coordinates.
OBJ_CYCLES 20 Cycles. Uses 2 coordinates.
OBJ_TEXT 21 Text. Uses 1 coordinate.
OBJ_ARROW 22 Arrows. Uses 1 coordinate.
OBJ_LABEL 23 Text label. Uses 1 coordinate in pixels.

Object visibility enumeration


Time frames where object may be shown. Used in ObjectSet() function to set OBJPROP_TIMEFRAMES property.
Constant Value Description
OBJ_PERIOD_M1 0x0001 Object shown is only on 1-minute charts.
OBJ_PERIOD_M5 0x0002 Object shown is only on 5-minute charts.
OBJ_PERIOD_M15 0x0004 Object shown is only on 15-minute charts.
OBJ_PERIOD_M30 0x0008 Object shown is only on 30-minute charts.
OBJ_PERIOD_H1 0x0010 Object shown is only on 1-hour charts.
OBJ_PERIOD_H4 0x0020 Object shown is only on 4-hour charts.
OBJ_PERIOD_D1 0x0040 Object shown is only on daily charts.
OBJ_PERIOD_W1 0x0080 Object shown is only on weekly charts.
OBJ_PERIOD_MN1 0x0100 Object shown is only on monthly charts.
OBJ_ALL_PERIODS 0x01FF Object shown is on all timeframes.
NULL 0 Object shown is on all timeframes.
EMPTY -1 Hidden object on all timeframes.

Predefined Arrow codes enumeration


Predefined Arrow codes enumeration. Arrows code constants. It can be one of the following values:
Constant Value Description

SYMBOL_THUMBSUP 67 Thumb up symbol ().

SYMBOL_THUMBSDOWN 68 Thumb down symbol ().

SYMBOL_ARROWUP 241 Arrow up symbol ().

SYMBOL_ARROWDOWN 242 Arrow down symbol ().

SYMBOL_STOPSIGN 251 Stop sign symbol ().

SYMBOL_CHECKSIGN 252 Check sign symbol ().


Special Arrow codes that exactly points to price and time.
It can be one of the following values:
Constant Value Description

1 Upwards arrow with tip rightwards (↱).

2 Downwards arrow with tip rightwards (↳).

3 Left pointing triangle (◄).


4 En Dash symbol (–).
SYMBOL_LEFTPRICE 5 Left sided price label.
SYMBOL_RIGHTPRICE 6 Right sided price label.

Series array identifier


Series array identifier used with ArrayCopySeries(), Highest() and Lowest() functions.
It can be any of the following values:
Constant Value Description
MODE_OPEN 0 Open price.
MODE_LOW 1 Low price.
MODE_HIGH 2 High price.
MODE_CLOSE 3 Close price.
MODE_VOLUME 4 Volume, used in Lowest() and Highest() functions.
MODE_TIME 5 Bar open time, used in ArrayCopySeries() function.

Special constants
Special constants used to indicate parameters and variables states. It can be one of the following values:
Constant value Description
NULL 0 Indicates empty state of the string.
EMPTY -1 Indicates empty state of the parameter.
EMPTY_VALUE 0x7FFFFFFF Default custom indicator empty value.
CLR_NONE 0xFFFFFFFF Indicates empty state of colors.
WHOLE_ARRAY 0 Used with array functions. Indicates that all array elements will be processed.

Time frame enumeration


Time frame on the chart. It can be any of the following values:
Constant Value Description
PERIOD_M1 1 1 minute.
PERIOD_M5 5 5 minutes.
PERIOD_M15 15 15 minutes.
PERIOD_M30 30 30 minutes.
PERIOD_H1 60 1 hour.
PERIOD_H4 240 4 hour.
PERIOD_D1 1440 Daily.
PERIOD_W1 10080 Weekly.
PERIOD_MN1 43200 Monthly.
0 (zero) 0 Time frame used on the chart.

Trade operation enumeration


Operation type for the OrderSend() function. It can be any of the following values:
Constant Value Description
OP_BUY 0 Buying position.
OP_SELL 1 Selling position.
OP_BUYLIMIT 2 Buy limit pending position.
OP_SELLLIMIT 3 Sell limit pending position.
OP_BUYSTOP 4 Buy stop pending position.
OP_SELLSTOP 5 Sell stop pending position.

Uninitialize reason codes


Uninitialize reason codes returned by UninitializeReason() function. It can be any one of the following values:
Constant Value Description
REASON_REMOVE 1 Expert removed from chart.
REASON_RECOMPILE 2 Expert recompiled.
REASON_CHARTCHANGE 3 symbol or timeframe changed on the chart.
REASON_CHARTCLOSE 4 Chart closed.
REASON_PARAMETERS 5 Inputs parameters was changed by user.
REASON_ACCOUNT 6 Other account activated.

Wingdings symbols
Wingdings font symbols used with Arrow objects.
32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47
 48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63
 64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79
 80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95
10 10 10
 96  97  98  99  0  1  2  10
3  10
4  10
5  10
6  10
7 
10
8  10
9  11
0  11
1
11 11 11 11 11 11 11 11
 2  3  4  5  6  7  8  9  12 12
0 1 
12
2  12
3  12
4  12
5  12
6  12
7
12 12 13 13 13 13 13 13 13
 8  9  0  1  2 … 3  4  5  6 ‰13
7 
13
8  13
9  14
0  14
1  14
2  14
3
14 14 14 14 14 14 15 15
 4 ‘ 5 ’ 6 “ 7 ” 8  9 – 0 — 1  15 15
2  3 
15
4  15
5  15
6  15
7  15
8  15
9
16 16 16 16 16 16 16 16 16 16 17 17 17
 0  1  2  3  4  5  6  7  8  9  0  1  2 - 17
3 
17
4  17
5
17 17 17 17 18 18 18 18 18 18 18 18 18 18 19 19
 6  7  8  9  0  1  2  3  4  5  6  7  8  9  0  1
19 19 19 19 19 19 19
 2  3  4  5  6  7  8  19 20 20 20
9 0 1  2 
20
3  20
4  20
5  20
6  20
7

 20
8 
20
9  21
0  21
1  21
2  21 21
3 4 
21
5  21
6  21
7  21
8  21
9  22
0  22
1  22
2  22
3
22 22 22 22 22 22 23
 4  5  6  7  8  9  0  23 23
1 2 
23
3  23
4  23
5  23
6  23
7  23
8  23
9
24 24 24 24 24 24 24 24 24 24 25 25 25 25 25 25
 0  1  2  3  4  5  6  7  8  9  0  1  2  3  4  5

Web colors table

Black DarkGreen DarkSlateGray Olive Green Teal Navy Purple


Maroon Indigo MidnightBlue DarkBlue DarkOliveGreen SaddleBrown ForestGreen OliveDrab
SeaGreen DarkGoldenrod DarkSlateBlue Sienna MediumBlue Brown DarkTurquoise DimGray
LightSeaGreen DarkViolet FireBrick MediumVioletRed MediumSeaGreen Chocolate Crimson SteelBlue
Goldenrod MediumSpringGreen LawnGreen CadetBlue DarkOrchid YellowGreen LimeGreen OrangeRed
DarkOrange Orange Gold Yellow Chartreuse Lime SpringGreen Aqua
DeepSkyBlue Blue Magenta Red Gray SlateGray Peru BlueViolet
LightSlateGray DeepPink MediumTurquoise DodgerBlue Turquoise RoyalBlue SlateBlue DarkKhaki
IndianRed MediumOrchid GreenYellow MediumAquamarine DarkSeaGreen Tomato RosyBrown Orchid
MediumPurple PaleVioletRed Coral CornflowerBlue DarkGray SandyBrown MediumSlateBlue Tan
DarkSalmon BurlyWood HotPink Salmon Violet LightCoral SkyBlue LightSalmon
Plum Khaki LightGreen Aquamarine Silver LightSkyBlue LightSteelBlue LightBlue
PaleGreen Thistle PowderBlue PaleGoldenrod PaleTurquoise LightGray Wheat NavajoWhite
Moccasin LightPink Gainsboro PeachPuff Pink Bisque LightGoldenRod BlanchedAlmond
LemonChiffon Beige AntiqueWhite PapayaWhip Cornsilk LightYellow LightCyan Linen
Lavender MistyRose OldLace WhiteSmoke Seashell Ivory Honeydew AliceBlue
LavenderBlush MintCream Snow White

String functions
StringConcatenate()
StringFind()
StringGetChar()
StringLen()
StringSetChar()
StringSubstr()
StringTrimLeft()
StringTrimRight()
string StringConcatenate(... )
Writes data to the string and returns it. Parameters can be of any type. Arrays cannot be passed to the StringConcatenate()
function. Arrays should be printed elementwise. Data of double type printed with 4 decimal digits after point. To print with more
precision use DoubleToStr() function. Data of bool, datetime and color types will be printed as its numeric presentation. To print
values of datetime type as string convert it by TimeToStr() function.
StringConcatenate() function work faster than concatenating strings by + operator.
See also: Print(), Alert() and Comment() functions.
Parameters
... - Any values, separated by commas.
Sample
string text;
text=StringConcatenate("Account free margin is ", AccountFreeMargin(), "Current
time is ", TimeToStr(CurTime()));
// slow text="Account free margin is " + AccountFreeMargin() + "Current time is " +
TimeToStr(CurTime())
Print(text);

int StringFind(string text, string matched_text, int start=0)


Scans this string for the first match of a substring.
Parameters
text - String to search for.
matched_text - String to search for.
start - Starting index in the string.
Sample
string text="The quick brown dog jumps over the lazy fox";
int index=StringFind(text, "dog jumps", 0);
if(index!=16)
Print("oops!");

int StringGetChar(string text, int pos)


Returns character (code) from specified position in the string.
Parameters
text - String where character will be retrieved.
pos - Char zero based position in the string.
Sample
int char_code=StringGetChar("abcdefgh", 3);
// char code 'c' is 99

int StringLen(string text)


Returns character count of a string.
Parameters
text - String to calculate length.
Sample
string str="some text";
if(StringLen(str)<5) return(0);

string StringSetChar(string text, int pos, int value)


Returns string copy with changed character at the indicated position with new value.
Parameters
text - String where character will be changed.
pos - Zero based character position in the string. Can be from 0 to StringLen()-1.
value - New char ASCII code.
Sample
string str="abcdefgh";
string str1=StringSetChar(str, 3, 'D');
// str1 is "abcDefgh"
string StringSubstr(string text, int start, int count=EMPTY)
Extracts a substring from text string, starting at position (zero-based).
The function returns a copy of the extracted substring if possible, otherwise returns empty string.
Parameters
text - String from substring will be extracted.
start - Substring starting index
count - Character count.
Sample
string text="The quick brown dog jumps over the lazy fox";
string substr=StringSubstr(text, 4, 5);
// subtracted string is "quick" word

string StringTrimLeft(string text)


Call the function to trim leading white space characters from the string. StringTrimLeft removes new line, space, and tab
characters. The function returns a copy of the trimmed string if possible, otherwise returns empty string. Returns new string with
changes.
Parameters
text - String to trim left.
Sample
string str1=" Hello world ";
string str2=StringTrimLeft(str);
// after trimming the str2 variable will be "Hello World "

string StringTrimRight(string text)


Call the function to trim leading white space characters from the string. StringTrimRight removes new line, space, and tab
characters. The function returns a copy of the trimmed string if possible, otherwise return empty string.
Parameters
text - String to trim right.
Sample
string str1=" Hello world ";
string str2=StringTrimRight(str);
// after trimming the str2 variable will be " Hello World"

Technical Indicator calls


Accelerator Oscillator - iAC()
Accumulation/Distribution - iAD()
Alligator - iAlligator()
Average Directional Movement Index - iADX()
Average True Range - iATR()
Awesome Oscillator - iAO()
Bears Power - iBearsPower()
Bollinger Bands - iBands()
Bollinger Bands on buffer - iBandsOnArray()
Bulls Power - iBullsPower()
Commodity Channel Index - iCCI()
Commodity Channel Index on buffer - iCCIOnArray()
Custom Indicator - iCustom()
DeMarker - iDeMarker()
Envelopes - iEnvelopes()
Envelopes on buffer - iEnvelopesOnArray()
Force Index - iForce()
Fractals - iFractals()
Gator Oscillator - iGator()
Ichimoku Kinko Hyo - iIchimoku()
Market Facilitation Index (Bill Williams) - iBWMFI()
Momentum - iMomentum()
Momentum on buffer - iMomentumOnArray()
Money Flow Index - iMFI()
Moving Average - iMA()
Moving Average on buffer - iMAOnArray()
Moving Average of Oscillator - iOsMA()
Moving Averages Convergence/Divergence - iMACD()
On Balance Volume - iOBV()
Parabolic SAR - iSAR()
Relative Strength Index - iRSI()
Relative Strength Index on buffer - iRSIOnArray()
Relative Vigor Index - iRVI()
Standard Deviation - iStdDev()
Standard Deviation on buffer - iStdDevOnArray()
Stochastic Oscillator - iStochastic()
William's Percent Range - iWPR()
iBars()
iBarShift()
iClose()
iHigh()
iLow()
iOpen()
iTime()
iVolume()
Highest()
Lowest()

double iAC(string symbol, int timeframe, int shift)


Calculates the Bill Williams' Accelerator/Decelerator oscillator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double result=iAC(NULL, 0, 1);

double iAD(string symbol, int timeframe, int shift)


Calculates the Accumulation/Distribution indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double result=iAD(NULL, 0, 1);

double string symbol, int timeframe, int jaw_period, int jaw_shift,


iAlligator( int teeth_period, int teeth_shift, int lips_period, int lips_shift,
int ma_method, int applied_price, int mode, int shift)
Calculates the Bill Williams' Alligator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
jaw_period - Jaw period.
jaw_shift - Jaw line shift.
teeth_period - Teeth period.
teeth_shift - Teeth line shift.
lips_period - Lips period.
lips_shift - Lips line shift.
ma_method - MA method. It can be any of Moving Average method enumeration value.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - Source of data. It can be any of the following values:
MODE_GATORJAW - Gator Jaw (blue) balance line,
MODE_GATORTEETH - Gator Teeth (red) balance line,
MODE_GATORLIPS - Gator Lips (green) balance line.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double jaw_val=iAlligator(NULl, 0, 13, 8, 8, 5, 5, 3, MODE_SMMA, PRICE_MEDIAN,
MODE_GATORJAW, 1);

double string symbol, int timeframe, int period, int applied_price, int mode,
iADX( int shift)
Calculates the Movement directional index and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - Indicator line array index. It can be any of the Indicators line identifiers enumeration value.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iADX(NULL,0,14,PRICE_HIGH,MODE_MAIN,0)>iADX(NULL,0,14,PRICE_HIGH,MODE_PLUSDI,0))
return(0);

double iATR(string symbol, int timeframe, int period, int shift)


Calculates the Indicator of the average true range and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iATR(NULL,0,12,0)>iATR(NULL,0,20,0)) return(0);

double iAO(string symbol, int timeframe, int shift)


Calculates the Bill Williams' Awesome oscillator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iAO(NULL, 0, 2);
double string symbol, int timeframe, int period, int applied_price,
iBearsPower( int shift)
Calculates the Bears Power indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iBearsPower(NULL, 0, 13,PRICE_CLOSE,0);

double string symbol, int timeframe, int period, int deviation, int bands_shift,
iBands( int applied_price, int mode, int shift)
Calculates the Bollinger bands indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
deviation - Deviation.
bands_shift - Bands shift.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - Indicator line array index. It can be any of the Indicators line identifiers enumeration value.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iBands(NULL,0,20,2,0,PRICE_LOW,MODE_LOWER,0)>Low[0]) return(0);

double double array[], int total, int period, double deviation,


iBandsOnArray( int bands_shift, int mode, int shift)
Calculates the Bollinger bands indicator and returns its value.
Parameters
array[] - Array with data.
total - The number of items to be counted.
period - Number of periods for calculation.
deviation - Deviation.
bands_shift - Bands shift.
mode - Series array identifier. It can be any of the Series array identifier enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iBands(ExtBuffer,total,2,0,MODE_LOWER,0)>Low[0]) return(0);

double string symbol, int timeframe, int period, int applied_price,


iBullsPower( int shift)
Calculates the Bulls Power indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iBullsPower(NULL, 0, 13,PRICE_CLOSE,0);
double iCCI(string symbol, int timeframe, int period, int applied_price, int shift)
Calculates the Commodity channel index and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iCCI(NULL,0,12,0)>iCCI(NULL,0,20,0)) return(0);

double iCCIOnArray(double array[], int total, int period, int shift)


Calculates the Commodity channel index and returns its value.
Parameters
array[] - Array with data.
total - The number of items to be counted.
period - Number of periods for calculation.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iCCIOnArray(ExtBuffer,total,12,0)>iCCI(NULL,0,20,PRICE_OPEN, 0)) return(0);

double iCustom(string symbol, int timeframe, string name, ... , int mode, int shift)
Calculates the Custom indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
name - Custom indicator compiled program name.
... - Parameters set (if needed).
mode - Line index. Can be from 0 to 7.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iCustom(NULL, 0, "SampleInd",13,1,0);

double iDeMarker(string symbol, int timeframe, int period, int shift)


Calculates the DeMarker indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iDeMarker(NULL, 0, 13, 1);

double string symbol, int timeframe, int ma_period, int ma_method,


iEnvelopes( int ma_shift, int applied_price, double deviation, int mode, int shift)
Calculates the Envelopes indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
ma_period - Number of periods for calculation.
ma_method - MA method. It can be any of Moving Average method enumeration value.
ma_shift - MA shift. Indicator line offset relate to the chart by timeframe.
applied_price - Applied price. It can be any of Applied price enumeration values.
deviation - Deviation.
mode - Indicator line array index. It can be any of Indicators line identifiers enumeration value.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iEnvelopes(NULL, 0, 13,MODE_SMA,10,PRICE_CLOSE,0.2,MODE_UPPER,0);
double double array[], int total, int ma_period, int ma_method,
iEnvelopesOnArray( int ma_shift, double deviation, int mode, int shift)
Calculates the Envelopes indicator counted on buffer and returns its value.
Parameters
array[] - Array with data.
total - The number of items to be counted.
ma_period - Number of periods for calculation.
ma_method - MA method. It can be any of Moving Average method enumeration value.
ma_shift - MA shift. Indicator line offset relate to the chart by timeframe.
deviation - Deviation.
mode - Indicator line array index. It can be any of Indicators line identifiers enumeration value.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iEnvelopesOnArray(ExtBuffer, 0, 13, MODE_SMA, 0.2, MODE_UPPER,0 );

double string symbol, int timeframe, int period, int ma_method,


iForce( int applied_price, int shift)
Calculates the Force index and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
ma_method - MA method. It can be any of Moving Average method enumeration value.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iForce(NULL, 0, 13,MODE_SMA,PRICE_CLOSE,0);

double iFractals(string symbol, int timeframe, int mode, int shift)


Calculates the Fractals and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
mode - Indicator line array index. It can be any of the Indicators line identifiers enumeration value.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iFractals(NULL, 0, MODE_UPPER,0);

double string symbol, int timeframe, int jaw_period, int jaw_shift,


iGator( int teeth_period, int teeth_shift, int lips_period, int lips_shift,
int ma_method, int applied_price, int mode, int shift)
Calculates the Gator Oscillator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
jaw_period - Jaw period.
jaw_shift - Jaw line shift.
teeth_period - Teeth period.
teeth_shift - Teeth line shift.
lips_period - Lips period.
lips_shift - Lips line shift.
ma_method - MA method. It can be any of Moving Average method enumeration value.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - Indicator line array index. It can be any of Indicators line identifiers enumeration value.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double jaw_val=iGator(NULL, 0, 13, 8, 8, 5, 5, 3, MODE_SMMA, PRICE_MEDIAN,
MODE_UPPER, 1);

double string symbol, int timeframe, int tenkan_sen, int kijun_sen,


iIchimoku( int senkou_span_b, int mode, int shift)
Calculates the Ichimoku Kinko Hyo and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
tenkan_sen - Tenkan Sen.
kijun_sen - Kijun Sen.
senkou_span_b - Senkou SpanB.
mode - Source of data. It can be one of the Ichimoku Kinko Hyo mode enumeration.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double tenkan_sen=iIchimoku(NULL, 0, 9, 26, 52, MODE_TENKANSEN, 1);

double iBWMFI(string symbol, int timeframe, int shift)


Calculates the Bill Williams Market Facilitation index and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iBWMFI(NULL, 0, 0);

double string symbol, int timeframe, int period, int applied_price,


iMomentum( int shift)
Calculates the Momentum indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator.NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iMomentum(NULL,0,12,PRICE_CLOSE,0)>iMomentum(NULL,0,20,PRICE_CLOSE,0))
return(0);

double iMomentumOnArray(double array[], int total, int period, int shift)


Calculates the Momentum indicator counted on buffer and returns its value.
Parameters
array[] - Array with data.
total - The number of items to be counted.
period - Number of periods for calculation.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iMomentumOnArray(mybuffer,100,12,0)>iMomentumOnArray(mubuffer,100,20,0))
return(0);

double iMFI(string symbol, int timeframe, int period, int shift)


Calculates the Money flow index and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iMFI(NULL,0,14,0)>iMFI(NULL,0,14,1)) return(0);

double string symbol, int timeframe, int period, int ma_shift, int ma_method,
iMA( int applied_price, int shift)
Calculates the Moving average indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
ma_shift - MA shift. Indicators line offset relate to the chart by timeframe.
ma_method - MA method. It can be any of the Moving Average method enumeration value.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
AlligatorJawsBuffer[i]=iMA(NULL,0,13,8,MODE_SMMA,PRICE_MEDIAN,i);

double double array[], int total, int period, int ma_shift, int ma_method,
iMAOnArray( int shift)
Calculates the Moving average counted on buffer and returns its value.
Parameters
array[] - Array with data.
total - The number of items to be counted. 0 means whole array.
period - Number of periods for calculation.
ma_shift - MA shift
ma_method - MA method. It can be any of the Moving Average method enumeration value.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double macurrent=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,0);
double macurrentslow=iMAOnArray(ExtBuffer,0,10,0,MODE_LWMA,0);
double maprev=iMAOnArray(ExtBuffer,0,5,0,MODE_LWMA,1);
double maprevslow=iMAOnArray(ExtBuffer,0,10,0,MODE_LWMA,1);
//----
if(maprev<maprevslow && macurrent>=macurrentslow)
Alert("crossing up");

double string symbol, int timeframe, int fast_ema_period, int slow_ema_period,


iOsMA( int signal_period, int applied_price, int shift)
Calculates the Moving Average of Oscillator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
fast_ema_period - Number of periods for fast moving average calculation.
slow_ema_period - Nmber of periods for slow moving average calculation.
signal_period - Number of periods for signal moving average calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iOsMA(NULL,0,12,26,9,PRICE_OPEN,1)>iOsMA(NULL,0,12,26,9,PRICE_OPEN,0))
return(0);

double string symbol, int timeframe, int fast_ema_period, int slow_ema_period,


iMACD( int signal_period, int applied_price, int mode, int shift)
Calculates the Moving averages convergence/divergence and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
fast_ema_period - Number of periods for fast moving average calculation.
slow_ema_period - Number of periods for slow moving average calculation.
signal_period - Number of periods for signal moving average calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
mode - Indicator line array index. It can be any of the Indicators line identifiers enumeration value.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0)>iMACD(NULL,0,12,26,9,PRICE_CLOSE,M
ODE_SIGNAL,0)) return(0);

double iOBV(string symbol, int timeframe, int applied_price, int shift)


Calculates the On Balance Volume indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iOBV(NULL, 0, PRICE_CLOSE, 1);

double iSAR(string symbol, int timeframe, double step, double maximum, int shift)
Calculates the Parabolic Sell and Reverse system and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
step - Increment, usually 0.02.
maximum - Maximum value, usually 0.2.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iSAR(NULL,0,0.02,0.2,0)>Close[0]) return(0);

double iRSI(string symbol, void timeframe, int period, int applied_price, int shift)
Calculates the Relative strength index and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>iRSI(NULL,0,14,PRICE_CLOSE,1)) return(0);

double iRSIOnArray(double array[], int total, int period, int shift)


Calculates the Relative strength index counted on buffer and returns its value.
Parameters
array[] - Array with data.
total - The number of items to be counted.
period - Number of periods for calculation.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iRSIOnBuffer(ExtBuffer,1000,14,0)>iRSI(NULL,0,14,PRICE_CLOSE,1)) return(0);

double iRVI(string symbol, int timeframe, int period, int mode, int shift)
Calculates the Relative Vigor index and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
mode - Indicator line array index. It can be any of Indicators line identifiers enumeration value.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iRVI(NULL, 0, 10,MODE_MAIN,0);

double string symbol, int timeframe, int ma_period, int ma_method, int ma_shift,
iStdDev( int applied_price, int shift)
Calculates the Standard Deviation indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
ma_period - MA period.
ma_method - MA method. It can be any of Moving Average method enumeration value.
ma_shift - MA shift.
applied_price - Applied price. It can be any of Applied price enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iStdDev(NULL,0,10,MODE_EMA,0,PRICE_CLOSE,0);

double double array[], int total, int ma_period, int ma_method,


iStdDevOnArray( int ma_shift, int shift)
Calculates the Standard Deviation counted on buffer and returns its value.
Parameters
array[] - Array with data.
total - The number of items to be counted.
ma_period - MA period.
ma_method - MA method. It can be any of Moving Average method enumeration value.
ma_shift - iMA shift.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
double val=iStdDevOnArray(ExtBuffer,100,10,MODE_EMA,0,0);

double string symbol, int timeframe, int %Kperiod, int %Dperiod, int slowing,
iStochastic( int method, int price_field, int mode, int shift)
Calculates the Stochastic oscillator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
%Kperiod - %K line period.
%Dperiod - %D line period.
slowing - Slowing value.
method - MA method. It can be any ofMoving Average method enumeration value.
price_field - Price field parameter. Can be one of this values: 0 - Low/High or 1 - Close/Close.
mode - Indicator line array index. It can be any of the Indicators line identifiers enumeration value.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iStochastic(NULL,0,5,3,3,MODE_SMA,0,MODE_MAIN,0)>iStochastic(NULL,0,5,3,3,MODE_S
MA,0,MODE_SIGNAL,0))
return(0);

double iWPR(string symbol, int timeframe, int period, int shift)


Calculates the Larry William's percent range indicator and returns its value.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
period - Number of periods for calculation.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
if(iWPR(NULL,0,14,0)>iWPR(NULL,0,14,1)) return(0);
int iBars(string symbol, int timeframe)
Returns the number of bars on the specified chart.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
Sample
Print("Bar count on the 'EUROUSD' symbol with PERIOD_H1
is",iBars("EUROUSD",PERIOD_H1));

int iBarShift(string symbol, int timeframe, datetime time, bool exact=false)


Search for bar by open time. The function returns bar shift with the open time specified. If the bar having the specified open time
is absent the function will return, depending on the exact parameter, -1 or the nearest bar shift.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
time - value to find (bar's open time).
exact - Return mode when bar not found. false - iBarShift returns nearest. true - iBarShift returns -1.
Sample
datetime some_time=D'2004.03.21 12:00';
int shift=iBarShift("EUROUSD",PERIOD_M1,some_time);
Print("shift of bar with open time ",TimeToStr(some_time)," is ",shift);

double iClose(string symbol, int timeframe, int shift)


Returns Close value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function
returns 0.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ",
iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ",
iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ",
iVolume("USDCHF",PERIOD_H1,i));

double iHigh(string symbol, int timeframe, int shift)


Returns High value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function
returns 0.
Parameters
symbol - Symbol on that data need to calculate indicator. NULL means current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ",
iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ",
iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ",
iVolume("USDCHF",PERIOD_H1,i));
double iLow(string symbol, int timeframe, int shift)
Returns Low value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function
returns 0.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ",
iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ",
iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ",
iVolume("USDCHF",PERIOD_H1,i));

double iOpen(string symbol, int timeframe, int shift)


Returns Open value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function
returns 0.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ",
iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ",
iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ",
iVolume("USDCHF",PERIOD_H1,i));

datetime iTime(string symbol, int timeframe, int shift)


Returns Time value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function
returns 0.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ",
iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ",
iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ",
iVolume("USDCHF",PERIOD_H1,i));

double iVolume(string symbol, int timeframe, int shift)


Returns Volume value for the bar of indicated symbol with timeframe and shift. If local history is empty (not loaded), function
returns 0.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
shift - Shift relative to the current bar (number of periods back), where the data should be taken from.
Sample
Print("Current bar for USDCHF H1: ",iTime("USDCHF",PERIOD_H1,i),", ",
iOpen("USDCHF",PERIOD_H1,i),", ",
iHigh("USDCHF",PERIOD_H1,i),", ",
iLow("USDCHF",PERIOD_H1,i),", ",
iClose("USDCHF",PERIOD_H1,i),", ",
iVolume("USDCHF",PERIOD_H1,i));

int Highest(string symbol, int timeframe, int type, int count=WHOLE_ARRAY, int start=0)
Returns the shift of the maximum value over a specific number of periods depending on type.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
type - Series array identifier. It can be any of the Series array identifier enumeration values.
count - Number of periods (in direction from the start bar to the back one) on which the calculation is carried out.
start - Shift showing the bar, relative to the current bar, that the data should be taken from.
Sample
double val;
// calculating the highest value in the range from 5 element to 25 element
// indicator charts symbol and indicator charts time frame
val=High[Highest(NULL,0,MODE_HIGH,20,4)];

int Lowest(string symbol, int timeframe, int type, int count=WHOLE_ARRAY, int start=0)
Returns the shift of the least value over a specific number of periods depending on type.
Parameters
symbol - Symbol the data of which should be used to calculate indicator. NULL means the current symbol.
timeframe - Time frame. It can be any of Time frame enumeration values.
type - Series array identifier. It can be any of Series array identifier enumeration values.
count - Number of periods (in direction from the start bar to the back one) on which the calculation is carried out.
start - Shift showing the bar, relative to the current bar, that the data should be taken from.
Sample
double val=Low[Lowest(NULL,0,MODE_LOW,10,10)];

Trading functions
HistoryTotal()
OrderClose()
OrderCloseBy()
OrderClosePrice()
OrderCloseTime()
OrderComment()
OrderCommission()
OrderDelete()
OrderExpiration()
OrderLots()
OrderMagicNumber()
OrderModify()
OrderOpenPrice()
OrderOpenTime()
OrderPrint()
OrderProfit()
OrderSelect()
OrderSend()
OrderStopLoss()
OrdersTotal()
OrderSwap()
OrderSymbol()
OrderTakeProfit()
OrderTicket()
OrderType()

int HistoryTotal()
Returns the number of closed orders in the account history loaded into the terminal. To get the detailed error information, call
GetLastError() function.
Sample
// retrieving info from trade history
int i,hstTotal=HistoryTotal();
for(i=0;i<hstTotal;i++)
{
//---- check selection result
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false)
{
Print("Access to history failed with error (",GetLastError(),")");
break;
}
// some work with order
}

bool int ticket, double lots, double price, int slippage,


OrderClose( color Color=CLR_NONE)
Closes opened order. If the function succeeds, the return value is true. If the function fails, the return value is false. To get the
detailed error information, call GetLastError().
Parameters
ticket - Unique number of the order ticket.
lots - Number of lots.
price - Preferred closing price.
slippage - Value of the maximum price slippage in points.
Color - Color of the closing arrow on the chart.If the parameter is absent or has CLR_NONE value closing arrow will not be drawn on
the chart.
Sample
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)
{
OrderClose(order_id,1,Ask,3,Red);
return(0);
}

bool OrderCloseBy(int ticket, int opposite, color Color=CLR_NONE)


Closes opened order by another opposite opened order. If the function succeeds, the return value is true. If the function fails, the
return value is false. To get the detailed error information, call GetLastError().
Parameters
ticket - Unique number of the order ticket.
opposite - Unique number of the opposite order ticket.
Color - Color of the closing arrow on the chart.If the parameter is absent or has CLR_NONE value closing arrow will not be drawn on
the chart.
Sample
if(iRSI(NULL,0,14,PRICE_CLOSE,0)>75)
{
OrderCloseBy(order_id,opposite_id);
return(0);
}

double OrderClosePrice()
Returns close price for the currently selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(ticket,SELECT_BY_POS)==true)
Print("Close price for the order ",ticket," = ",OrderClosePrice());
else
Print("OrderSelect failed error code is",GetLastError());

datetime OrderCloseTime()
Returns close time for the currently selected order. If order close time is not 0 then the order selected and has been closed and
retrieved from the account history.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(10,SELECT_BY_POS,MODE_HISTORY)==true)
{
datetime ctm=OrderOpenTime();
if(ctm>0) Print("Open time for the order 10 ", ctm);
ctm=OrderCloseTime();
if(ctm>0) Print("Close time for the order 10 ", ctm);
}
else
Print("OrderSelect failed error code is",GetLastError());

string OrderComment()
Returns comment for the selected order.
Note: Order must be selected by OrderSelect() function.
Sample
string comment;
if(OrderSelect(10,SELECT_BY_TICKET)==false)
{
Print("OrderSelect failed error code is",GetLastError());
return(0);
}
comment = OrderComment();
// ...

double OrderCommission()
Returns calculated commission for the currently selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(10,SELECT_BY_POS)==true)
Print("Commission for the order 10 ",OrderCommission());
else
Print("OrderSelect failed error code is",GetLastError());
bool OrderDelete(int ticket)
Deletes previously opened pending order. If the function succeeds, the return value is true. If the function fails, the return value is
false. To get the detailed error information, call GetLastError().
Parameters
ticket - Unique number of the order ticket.
Sample
if(Ask>var1)
{
OrderDelete(order_ticket);
return(0);
}

datetime OrderExpiration()
Returns expiration date for the selected pending order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(10, SELECT_BY_TICKET)==true)
Print("Order expiration for the order #10 is ",OrderExpiration());
else
Print("OrderSelect failed error code is",GetLastError());

double OrderLots()
Returns lots value for the selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(10,SELECT_BY_POS)==true)
Print("lots for the order 10 ",OrderLots());
else
Print("OrderSelect failed error code is",GetLastError());

int OrderMagicNumber()
Returns magic number for the currently selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(10,SELECT_BY_POS)==true)
Print("Magic number for the order 10 ", OrderMagicNumber());
else
Print("OrderSelect failed error code is",GetLastError());

bool int ticket, double price, double stoploss, double takeprofit,


OrderModify( datetime expiration, color arrow_color=CLR_NONE)
Modification of characteristics for the previously opened position or a pending order. If the function succeeds, the return value is
true. If the function fails, the return value is false. To get the detailed error information, call GetLastError().
Parameters
ticket - Unique number of the order ticket.
price - New price (for pending orders only).
stoploss - New stoploss level.
takeprofit - New profit-taking level.
expiration - Order expiration server date/time (for pending orders only).
arrow_color - Arrow color of the pictogram on the chart.If the parameter is absent or has CLR_NONE value arrow will not be drawn on
the chart.
Sample
if(TrailingStop>0)
{
SelectOrder(12345,SELECT_BY_TICKET);
if(Bid-OrderOpenPrice()>Point*TrailingStop)
{
if(OrderStopLoss()<Bid-Point*TrailingStop)
{
OrderModify(OrderTicket(),Ask-10*Point,Ask-
35*Point,OrderTakeProfit(),0,Blue);
return(0);
}
}
}

double OrderOpenPrice()
Returns open price for the currently selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(10, SELECT_BY_POS)==true)
Print("open price for the order 10 ",OrderOpenPrice());
else
Print("OrderSelect failed error code is",GetLastError());

datetime OrderOpenTime()
Returns open time for the currently selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(10, SELECT_BY_POS)==true)
Print("open time for the order 10 ",OrderOpenTime());
else
Print("OrderSelect failed error code is",GetLastError());

void OrderPrint()
Prints selected order data to the log for the selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(10, SELECT_BY_TICKET)==true)
OrderPrint();
else
Print("OrderSelect failed error code is",GetLastError());

double OrderProfit()
Returns profit for the currently selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(10, SELECT_BY_POS)==true)
Print("Profit for the order 10 ",OrderProfit());
else
Print("OrderSelect failed error code is",GetLastError());

bool OrderSelect(int index, int select, int pool=MODE_TRADES)


Selects order by index or ticket to further processing. If the function fails, the return value will be false. To get the extended error
information, call GetLastError().
Parameters
index - Order index or order ticket depending from second parameter.
select - Selecting flags. It can be any of the following values:
SELECT_BY_POS - index in the order pool,
SELECT_BY_TICKET - index is order ticket.
pool - Optional order pool index. Used when select parameter is SELECT_BY_POS.It can be any of the following values:
MODE_TRADES (default)- order selected from trading pool(opened and pending orders),
MODE_HISTORY - order selected from history pool (closed and canceled order).
Sample
if(OrderSelect(12470, SELECT_BY_TICKET)==true)
{
Print("order #12470 open price is ", OrderOpenPrice());
Print("order #12470 close price is ", OrderClosePrice());
}
else
Print("OrderSelect failed error code is",GetLastError());

int string symbol, int cmd, double volume, double price, int slippage,
OrderSend( double stoploss, double takeprofit, string comment=NULL, int magic=0,
datetime expiration=0, color arrow_color=CLR_NONE)
Main function used to open a position or set a pending order. Returns ticket of the placed order or -1 if failed. To check error code
use GetLastError() function.
Parameters
symbol - Symbol for trading.
cmd - Operation type. It can be any of the Trade operation enumeration.
volume - Number of lots.
price - Preferred price of the trade.
slippage - Maximum price slippage for buy or sell orders.
stoploss - Stop loss level.
takeprofit - Take profit level.
comment - Order comment text. Last part of the comment may be changed by server.
magic - Order magic number. May be used as user defined identifier.
expiration - Order expiration time (for pending orders only).
arrow_color - Color of the opening arrow on the chart. If parameter is absent or has CLR_NONE value opening arrow is not drawn on the
chart.
Sample
int ticket;
if(iRSI(NULL,0,14,PRICE_CLOSE,0)<25)
{
ticket=OrderSend(Symbol(),OP_BUY,1,Ask,3,Ask-25*Point,Ask+25*Point,"My order
#2",16384,0,Green);
if(ticket<0)
{
Print("OrderSend failed with error #",GetLastError());
return(0);
}
}

double OrderStopLoss()
Returns stop loss value for the currently selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(ticket,SELECT_BY_POS)==true)
Print("Stop loss value for the order 10 ", OrderStopLoss());
else
Print("OrderSelect failed error code is",GetLastError());

int OrdersTotal()
Returns market and pending orders count.
Sample
int handle=FileOpen("OrdersReport.csv",FILE_WRITE|FILE_CSV,"\t");
if(handle<0) return(0);
// write header
FileWrite(handle,"#","open price","open time","symbol","lots");
int total=OrdersTotal();
// write open orders
for(int pos=0;pos<total;pos++)
{
if(OrderSelect(pos,SELECT_BY_POS)==false) continue;
FileWrite(handle,OrderTicket(),OrderOpenPrice(),OrderOpenTime(),OrderSymbol(),Or
derLots());
}
FileClose(handle);

double OrderSwap()
Returns swap value for the currently selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(order_id, SELECT_BY_TICKET)==true)
Print("Swap for the order #", order_id, " ",OrderSwap());
else
Print("OrderSelect failed error code is",GetLastError());

string OrderSymbol()
Returns the order symbol value for selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(12, SELECT_BY_POS)==true)
Print("symbol of order #", OrderTicket(), " is ", OrderSymbol());
else
Print("OrderSelect failed error code is",GetLastError());

double OrderTakeProfit()
Returns take profit value for the currently selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(12, SELECT_BY_POS)==true)
Print("Order #",OrderTicket()," profit: ", OrderTakeProfit());
else
Print("OrderSelect() 忮痦箅 铠栳牦 - ",GetLastError());

int OrderTicket()
Returns ticket number for the currently selected order.
Note: Order must be selected by OrderSelect() function.
Sample
if(OrderSelect(12, SELECT_BY_POS)==true)
order=OrderTicket();
else
Print("OrderSelect failed error code is",GetLastError());

int OrderType()
Returns order operation type for the currently selected order. It can be any of the following values:
OP_BUY - buying position,
OP_SELL - selling position,
OP_BUYLIMIT - buy limit pending position,
OP_BUYSTOP - buy stop pending position,
OP_SELLLIMIT - sell limit pending position,
OP_SELLSTOP - sell stop pending position.
Note: Order must be selected by OrderSelect() function.
Sample
int order_type;
if(OrderSelect(12, SELECT_BY_POS)==true)
{
order_type=OrderType();
// ...
}
else
Print("OrderSelect() returned error - ",GetLastError());

Window functions
BarsPerWindow()
FirstVisibleBar()
PriceOnDropped()
TimeOnDropped()
WindowFind()
WindowHandle()
WindowIsVisible
WindowOnDropped()
WindowsTotal()
WindowXOnDropped()
WindowYOnDropped()

int BarsPerWindow()
Function returns the amount of bars visible on the chart.
Sample
// work with visible bars.
int bars_count=BarsPerWindow();
int bar=FirstVisibleBar();
for(int i=0; i<bars_count; i++,bar--)
{
// ...
}

int FirstVisibleBar()
Function returns index of the first visible bar.
Sample
// work with visible bars.
int bars_count=BarsPerWindow();
int bar=FirstVisibleBar();
for(int i=0; i<bars_count; i++,bar--)
{
// ...
}

int FirstVisibleBar()
Function returns index of the first visible bar.
Sample
// work with visible bars.
int bars_count=BarsPerWindow();
int bar=FirstVisibleBar();
for(int i=0; i<bars_count; i++,bar--)
{
// ...
}

datetime TimeOnDropped()
Returns time part of dropped point where expert or script was dropped. This value is valid when expert or script dropped by
mouse.
Note: For custom indicators this value is undefined.
Sample
double drop_price=PriceOnDropped();
datetime drop_time=TimeOnDropped();
//---- may be undefined (zero)
if(drop_time>0)
{
ObjectCreate("Dropped price line", OBJ_HLINE, 0, drop_price);
ObjectCreate("Dropped time line", OBJ_VLINE, 0, drop_time);
}

int WindowFind(string name)


If indicator with name found returns the window index containing specified indicator, otherwise returns -1.
Note: WindowFind() returns -1 if ñustom indicator searches itself when init() function works.
Parameters
name - Indicator short name.
Sample
int win_idx=WindowFind("MACD(12,26,9)");

int WindowHandle(string symbol, int timeframe)


If chart of symbol and timeframe is currently opened returns the window handle, otherwise returns 0.
Parameters
symbol - symbol name.
timeframe - Time frame. It can be any of Time frame enumeration values.
Sample
int win_handle=WindowHandle("USDX",PERIOD_H1);
if(win_handle!=0)
Print("Window with USDX,H1 detected. Rates array will be copied immediately.");

bool WindowIsVisible(int index)


Returns true if the chart subwindow is visible, otherwise returns false.
Parameters
index - Chart subwindow index.
Sample
int maywin=WindowFind("MyMACD");
if(maywin>-1 && WindowIsVisible(maywin)==true)
Print("window of MyMACD is visible");
else
Print("window of MyMACD not found or is not visible");

int WindowOnDropped()
Returns window index where expert, custom indicator or script was dropped. This value is valid when expert, custom indicator or
script dropped by mouse.
Note: For custom indicators this index is undefined when init() function works and returning index is window index where custom
indicator works (may be different from dropping window index, because custom indicator can create its own new window). See
also WindowXOnDropped(), WindowYOnDropped()
Sample
if(WindowOnDropped()!=0)
{
Print("Indicator 'MyIndicator' must be applied to main chart window!");
return(false);
}

int WindowsTotal()
Returns count of indicator windows on the chart (including main chart).
Sample
Print("Windows count = ", WindowsTotal());

int WindowXOnDropped()
Returns x-axis coordinate in pixels were expert or script dropped to the chart. See also WindowYOnDropped(),
WindowOnDropped()
Sample
Print("Expert dropped point x=",WindowXOnDropped()," y=",WindowYOnDropped());
int WindowYOnDropped()
Returns y-axis coordinate in pixels were expert or script dropped to the chart. See also WindowYOnDropped(),
WindowOnDropped()
Sample
Print("Expert dropped point x=",WindowXOnDropped()," y=",WindowYOnDropped());

Include Files
//+------------------------------------------------------------------+
//| stderror.mqh |
//| Copyright © 2004-2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
//---- errors returned from trade server
#define ERR_NO_ERROR 0
#define ERR_NO_RESULT 1
#define ERR_COMMON_ERROR 2
#define ERR_INVALID_TRADE_PARAMETERS 3
#define ERR_SERVER_BUSY 4
#define ERR_OLD_VERSION 5
#define ERR_NO_CONNECTION 6
#define ERR_NOT_ENOUGH_RIGHTS 7
#define ERR_TOO_FREQUENT_REQUESTS 8
#define ERR_MALFUNCTIONAL_TRADE 9
#define ERR_ACCOUNT_DISABLED 64
#define ERR_INVALID_ACCOUNT 65
#define ERR_TRADE_TIMEOUT 128
#define ERR_INVALID_PRICE 129
#define ERR_INVALID_STOPS 130
#define ERR_INVALID_TRADE_VOLUME 131
#define ERR_MARKET_CLOSED 132
#define ERR_TRADE_DISABLED 133
#define ERR_NOT_ENOUGH_MONEY 134
#define ERR_PRICE_CHANGED 135
#define ERR_OFF_QUOTES 136
#define ERR_BROKER_BUSY 137
#define ERR_REQUOTE 138
#define ERR_ORDER_LOCKED 139
#define ERR_LONG_POSITIONS_ONLY_ALLOWED 140
#define ERR_TOO_MANY_REQUESTS 141
#define ERR_TRADE_MODIFY_DENIED 145
#define ERR_TRADE_CONTEXT_BUSY 146
//---- mql4 run time errors
#define ERR_NO_MQLERROR 4000
#define ERR_WRONG_FUNCTION_POINTER 4001
#define ERR_ARRAY_INDEX_OUT_OF_RANGE 4002
#define ERR_NO_MEMORY_FOR_FUNCTION_CALL_STACK 4003
#define ERR_RECURSIVE_STACK_OVERFLOW 4004
#define ERR_NOT_ENOUGH_STACK_FOR_PARAMETER 4005
#define ERR_NO_MEMORY_FOR_PARAMETER_STRING 4006
#define ERR_NO_MEMORY_FOR_TEMP_STRING 4007
#define ERR_NOT_INITIALIZED_STRING 4008
#define ERR_NOT_INITIALIZED_ARRAYSTRING 4009
#define ERR_NO_MEMORY_FOR_ARRAYSTRING 4010
#define ERR_TOO_LONG_STRING 4011
#define ERR_REMAINDER_FROM_ZERO_DIVIDE 4012
#define ERR_ZERO_DIVIDE 4013
#define ERR_UNKNOWN_COMMAND 4014
#define ERR_WRONG_JUMP 4015
#define ERR_NOT_INITIALIZED_ARRAY 4016
#define ERR_DLL_CALLS_NOT_ALLOWED 4017
#define ERR_CANNOT_LOAD_LIBRARY 4018
#define ERR_CANNOT_CALL_FUNCTION 4019
#define ERR_EXTERNAL_EXPERT_CALLS_NOT_ALLOWED 4020
#define ERR_NOT_ENOUGH_MEMORY_FOR_RETURNED_STRING 4021
#define ERR_SYSTEM_BUSY 4022
#define ERR_INVALID_FUNCTION_PARAMETERS_COUNT 4050
#define ERR_INVALID_FUNCTION_PARAMETER_VALUE 4051
#define ERR_STRING_FUNCTION_INTERNAL_ERROR 4052
#define ERR_SOME_ARRAY_ERROR 4053
#define ERR_INCORRECT_SERIES_ARRAY_USING 4054
#define ERR_CUSTOM_INDICATOR_ERROR 4055
#define ERR_INCOMPATIBLE_ARRAYS 4056
#define ERR_GLOBAL_VARIABLES_PROCESSING_ERROR 4057
#define ERR_GLOBAL_VARIABLE_NOT_FOUND 4058
#define ERR_FUNCTION_NOT_ALLOWED_IN_TESTING_MODE 4059
#define ERR_FUNCTION_NOT_CONFIRMED 4060
#define ERR_SEND_MAIL_ERROR 4061
#define ERR_STRING_PARAMETER_EXPECTED 4062
#define ERR_INTEGER_PARAMETER_EXPECTED 4063
#define ERR_DOUBLE_PARAMETER_EXPECTED 4064
#define ERR_ARRAY_AS_PARAMETER_EXPECTED 4065
#define ERR_HISTORY_WILL_UPDATED 4066
#define ERR_END_OF_FILE 4099
#define ERR_SOME_FILE_ERROR 4100
#define ERR_WRONG_FILE_NAME 4101
#define ERR_TOO_MANY_OPENED_FILES 4102
#define ERR_CANNOT_OPEN_FILE 4103
#define ERR_INCOMPATIBLE_ACCESS_TO_FILE 4104
#define ERR_NO_ORDER_SELECTED 4105
#define ERR_UNKNOWN_SYMBOL 4106
#define ERR_INVALID_PRICE_PARAM 4107
#define ERR_INVALID_TICKET 4108
#define ERR_TRADE_NOT_ALLOWED 4109
#define ERR_LONGS__NOT_ALLOWED 4110
#define ERR_SHORTS_NOT_ALLOWED 4111
#define ERR_OBJECT_ALREADY_EXISTS 4200
#define ERR_UNKNOWN_OBJECT_PROPERTY 4201
#define ERR_OBJECT_DOES_NOT_EXIST 4202
#define ERR_UNKNOWN_OBJECT_TYPE 4203
#define ERR_NO_OBJECT_NAME 4204
#define ERR_OBJECT_COORDINATES_ERROR 4205
#define ERR_NO_SPECIFIED_SUBWINDOW 4206

//+------------------------------------------------------------------+
//| stdlib.mqh |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#import "stdlib.ex4"

string ErrorDescription(int error_code);


int RGB(int red_value,int green_value,int blue_value);
bool CompareDoubles(double number1,double number2);
string DoubleToStrMorePrecision(double number,int precision);
string IntegerToHexString(int integer_number);

//+------------------------------------------------------------------+
//| WinUser32.mqh |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#define copyright "Copyright © 2004, MetaQuotes Software Corp."
#define link "http://www.metaquotes.net/"

#import "user32.dll"
//---- messages
int SendMessageA(int hWnd,int Msg,int wParam,int lParam);
int SendNotifyMessageA(int hWnd,int Msg,int wParam,int lParam);
int PostMessageA(int hWnd,int Msg,int wParam,int lParam);
void keybd_event(int bVk,int bScan,int dwFlags,int dwExtraInfo);
void mouse_event(int dwFlags,int dx,int dy,int dwData,int dwExtraInfo);
//---- windows
int FindWindowA(string lpClassName ,string lpWindowName);
int SetWindowTextA(int hWnd,string lpString);
int GetWindowTextA(int hWnd,string lpString,int nMaxCount);
int GetWindowTextLengthA(int hWnd);
int GetWindow(int hWnd,int uCmd);

int UpdateWindow(int hWnd);


int EnableWindow(int hWnd,int bEnable);
int DestroyWindow(int hWnd);
int ShowWindow(int hWnd,int nCmdShow);
int SetActiveWindow(int hWnd);
int AnimateWindow(int hWnd,int dwTime,int dwFlags);
int FlashWindow(int hWnd,int dwFlags /*bInvert*/);
int CloseWindow(int hWnd);
int MoveWindow(int hWnd,int X,int Y,int nWidth,int nHeight,int bRepaint);
int SetWindowPos(int hWnd,int hWndInsertAfter ,int X,int Y,int cx,int cy,int
uFlags);
int IsWindowVisible(int hWnd);
int IsIconic(int hWnd);
int IsZoomed(int hWnd);
int SetFocus(int hWnd);
int GetFocus();
int GetActiveWindow();
int IsWindowEnabled(int hWnd);
//---- miscelaneouse
int MessageBoxA(int hWnd ,string lpText,string lpCaption,int uType);
int MessageBoxExA(int hWnd ,string lpText,string lpCaption,int uType,int
wLanguageId);
int MessageBeep(int uType);
int GetSystemMetrics(int nIndex);
int ExitWindowsEx(int uFlags,int dwReserved);
int SwapMouseButton(int fSwap);
#import

//---- Window Messages


#define WM_NULL 0x0000
#define WM_CREATE 0x0001
#define WM_DESTROY 0x0002
#define WM_MOVE 0x0003
#define WM_SIZE 0x0005
#define WM_ACTIVATE 0x0006
#define WM_SETFOCUS 0x0007
#define WM_KILLFOCUS 0x0008
#define WM_ENABLE 0x000A
#define WM_SETREDRAW 0x000B
#define WM_SETTEXT 0x000C
#define WM_GETTEXT 0x000D
#define WM_GETTEXTLENGTH 0x000E
#define WM_PAINT 0x000F
#define WM_CLOSE 0x0010
#define WM_QUERYENDSESSION 0x0011
#define WM_QUIT 0x0012
#define WM_QUERYOPEN 0x0013
#define WM_ERASEBKGND 0x0014
#define WM_SYSCOLORCHANGE 0x0015
#define WM_ENDSESSION 0x0016
#define WM_SHOWWINDOW 0x0018
#define WM_WININICHANGE 0x001A
#define WM_SETTINGCHANGE 0x001A // WM_WININICHANGE
#define WM_DEVMODECHANGE 0x001B
#define WM_ACTIVATEAPP 0x001C
#define WM_FONTCHANGE 0x001D
#define WM_TIMECHANGE 0x001E
#define WM_CANCELMODE 0x001F
#define WM_SETCURSOR 0x0020
#define WM_MOUSEACTIVATE 0x0021
#define WM_CHILDACTIVATE 0x0022
#define WM_QUEUESYNC 0x0023
#define WM_GETMINMAXINFO 0x0024
#define WM_PAINTICON 0x0026
#define WM_ICONERASEBKGND 0x0027
#define WM_NEXTDLGCTL 0x0028
#define WM_SPOOLERSTATUS 0x002A
#define WM_DRAWITEM 0x002B
#define WM_MEASUREITEM 0x002C
#define WM_DELETEITEM 0x002D
#define WM_VKEYTOITEM 0x002E
#define WM_CHARTOITEM 0x002F
#define WM_SETFONT 0x0030
#define WM_GETFONT 0x0031
#define WM_SETHOTKEY 0x0032
#define WM_GETHOTKEY 0x0033
#define WM_QUERYDRAGICON 0x0037
#define WM_COMPAREITEM 0x0039
#define WM_GETOBJECT 0x003D
#define WM_COMPACTING 0x0041
#define WM_WINDOWPOSCHANGING 0x0046
#define WM_WINDOWPOSCHANGED 0x0047
#define WM_COPYDATA 0x004A
#define WM_CANCELJOURNAL 0x004B
#define WM_NOTIFY 0x004E
#define WM_INPUTLANGCHANGEREQUEST 0x0050
#define WM_INPUTLANGCHANGE 0x0051
#define WM_TCARD 0x0052
#define WM_HELP 0x0053
#define WM_USERCHANGED 0x0054
#define WM_NOTIFYFORMAT 0x0055
#define WM_CONTEXTMENU 0x007B
#define WM_STYLECHANGING 0x007C
#define WM_STYLECHANGED 0x007D
#define WM_DISPLAYCHANGE 0x007E
#define WM_GETICON 0x007F
#define WM_SETICON 0x0080
#define WM_NCCREATE 0x0081
#define WM_NCDESTROY 0x0082
#define WM_NCCALCSIZE 0x0083
#define WM_NCHITTEST 0x0084
#define WM_NCPAINT 0x0085
#define WM_NCACTIVATE 0x0086
#define WM_GETDLGCODE 0x0087
#define WM_SYNCPAINT 0x0088
#define WM_NCMOUSEMOVE 0x00A0
#define WM_NCLBUTTONDOWN 0x00A1
#define WM_NCLBUTTONUP 0x00A2
#define WM_NCLBUTTONDBLCLK 0x00A3
#define WM_NCRBUTTONDOWN 0x00A4
#define WM_NCRBUTTONUP 0x00A5
#define WM_NCRBUTTONDBLCLK 0x00A6
#define WM_NCMBUTTONDOWN 0x00A7
#define WM_NCMBUTTONUP 0x00A8
#define WM_NCMBUTTONDBLCLK 0x00A9
#define WM_KEYFIRST 0x0100
#define WM_KEYDOWN 0x0100
#define WM_KEYUP 0x0101
#define WM_CHAR 0x0102
#define WM_DEADCHAR 0x0103
#define WM_SYSKEYDOWN 0x0104
#define WM_SYSKEYUP 0x0105
#define WM_SYSCHAR 0x0106
#define WM_SYSDEADCHAR 0x0107
#define WM_KEYLAST 0x0108
#define WM_INITDIALOG 0x0110
#define WM_COMMAND 0x0111
#define WM_SYSCOMMAND 0x0112
#define WM_TIMER 0x0113
#define WM_HSCROLL 0x0114
#define WM_VSCROLL 0x0115
#define WM_INITMENU 0x0116
#define WM_INITMENUPOPUP 0x0117
#define WM_MENUSELECT 0x011F
#define WM_MENUCHAR 0x0120
#define WM_ENTERIDLE 0x0121
#define WM_MENURBUTTONUP 0x0122
#define WM_MENUDRAG 0x0123
#define WM_MENUGETOBJECT 0x0124
#define WM_UNINITMENUPOPUP 0x0125
#define WM_MENUCOMMAND 0x0126
#define WM_CTLCOLORMSGBOX 0x0132
#define WM_CTLCOLOREDIT 0x0133
#define WM_CTLCOLORLISTBOX 0x0134
#define WM_CTLCOLORBTN 0x0135
#define WM_CTLCOLORDLG 0x0136
#define WM_CTLCOLORSCROLLBAR 0x0137
#define WM_CTLCOLORSTATIC 0x0138
#define WM_MOUSEFIRST 0x0200
#define WM_MOUSEMOVE 0x0200
#define WM_LBUTTONDOWN 0x0201
#define WM_LBUTTONUP 0x0202
#define WM_LBUTTONDBLCLK 0x0203
#define WM_RBUTTONDOWN 0x0204
#define WM_RBUTTONUP 0x0205
#define WM_RBUTTONDBLCLK 0x0206
#define WM_MBUTTONDOWN 0x0207
#define WM_MBUTTONUP 0x0208
#define WM_MBUTTONDBLCLK 0x0209
#define WM_PARENTNOTIFY 0x0210
#define WM_ENTERMENULOOP 0x0211
#define WM_EXITMENULOOP 0x0212
#define WM_NEXTMENU 0x0213
#define WM_SIZING 0x0214
#define WM_CAPTURECHANGED 0x0215
#define WM_MOVING 0x0216
#define WM_DEVICECHANGE 0x0219
#define WM_MDICREATE 0x0220
#define WM_MDIDESTROY 0x0221
#define WM_MDIACTIVATE 0x0222
#define WM_MDIRESTORE 0x0223
#define WM_MDINEXT 0x0224
#define WM_MDIMAXIMIZE 0x0225
#define WM_MDITILE 0x0226
#define WM_MDICASCADE 0x0227
#define WM_MDIICONARRANGE 0x0228
#define WM_MDIGETACTIVE 0x0229
#define WM_MDISETMENU 0x0230
#define WM_ENTERSIZEMOVE 0x0231
#define WM_EXITSIZEMOVE 0x0232
#define WM_DROPFILES 0x0233
#define WM_MDIREFRESHMENU 0x0234
#define WM_MOUSEHOVER 0x02A1
#define WM_MOUSELEAVE 0x02A3
#define WM_CUT 0x0300
#define WM_COPY 0x0301
#define WM_PASTE 0x0302
#define WM_CLEAR 0x0303
#define WM_UNDO 0x0304
#define WM_RENDERFORMAT 0x0305
#define WM_RENDERALLFORMATS 0x0306
#define WM_DESTROYCLIPBOARD 0x0307
#define WM_DRAWCLIPBOARD 0x0308
#define WM_PAINTCLIPBOARD 0x0309
#define WM_VSCROLLCLIPBOARD 0x030A
#define WM_SIZECLIPBOARD 0x030B
#define WM_ASKCBFORMATNAME 0x030C
#define WM_CHANGECBCHAIN 0x030D
#define WM_HSCROLLCLIPBOARD 0x030E
#define WM_QUERYNEWPALETTE 0x030F
#define WM_PALETTEISCHANGING 0x0310
#define WM_PALETTECHANGED 0x0311
#define WM_HOTKEY 0x0312
#define WM_PRINT 0x0317
#define WM_PRINTCLIENT 0x0318
#define WM_HANDHELDFIRST 0x0358
#define WM_HANDHELDLAST 0x035F
#define WM_AFXFIRST 0x0360
#define WM_AFXLAST 0x037F
#define WM_PENWINFIRST 0x0380
#define WM_PENWINLAST 0x038F
#define WM_APP 0x8000

//---- keybd_event routines


#define KEYEVENTF_EXTENDEDKEY 0x0001
#define KEYEVENTF_KEYUP 0x0002
//---- mouse_event routines
#define MOUSEEVENTF_MOVE 0x0001 // mouse move
#define MOUSEEVENTF_LEFTDOWN 0x0002 // left button down
#define MOUSEEVENTF_LEFTUP 0x0004 // left button up
#define MOUSEEVENTF_RIGHTDOWN 0x0008 // right button down
#define MOUSEEVENTF_RIGHTUP 0x0010 // right button up
#define MOUSEEVENTF_MIDDLEDOWN 0x0020 // middle button down
#define MOUSEEVENTF_MIDDLEUP 0x0040 // middle button up
#define MOUSEEVENTF_WHEEL 0x0800 // wheel button rolled
#define MOUSEEVENTF_ABSOLUTE 0x8000 // absolute move

//---- GetSystemMetrics() codes


#define SM_CXSCREEN 0
#define SM_CYSCREEN 1
#define SM_CXVSCROLL 2
#define SM_CYHSCROLL 3
#define SM_CYCAPTION 4
#define SM_CXBORDER 5
#define SM_CYBORDER 6
#define SM_CXDLGFRAME 7
#define SM_CYDLGFRAME 8
#define SM_CYVTHUMB 9
#define SM_CXHTHUMB 10
#define SM_CXICON 11
#define SM_CYICON 12
#define SM_CXCURSOR 13
#define SM_CYCURSOR 14
#define SM_CYMENU 15
#define SM_CXFULLSCREEN 16
#define SM_CYFULLSCREEN 17
#define SM_CYKANJIWINDOW 18
#define SM_MOUSEPRESENT 19
#define SM_CYVSCROLL 20
#define SM_CXHSCROLL 21
#define SM_DEBUG 22
#define SM_SWAPBUTTON 23
#define SM_RESERVED1 24
#define SM_RESERVED2 25
#define SM_RESERVED3 26
#define SM_RESERVED4 27
#define SM_CXMIN 28
#define SM_CYMIN 29
#define SM_CXSIZE 30
#define SM_CYSIZE 31
#define SM_CXFRAME 32
#define SM_CYFRAME 33
#define SM_CXMINTRACK 34
#define SM_CYMINTRACK 35
#define SM_CXDOUBLECLK 36
#define SM_CYDOUBLECLK 37
#define SM_CXICONSPACING 38
#define SM_CYICONSPACING 39
#define SM_MENUDROPALIGNMENT 40
#define SM_PENWINDOWS 41
#define SM_DBCSENABLED 42
#define SM_CMOUSEBUTTONS 43
#define SM_SECURE 44
#define SM_CXEDGE 45
#define SM_CYEDGE 46
#define SM_CXMINSPACING 47
#define SM_CYMINSPACING 48
#define SM_CXSMICON 49
#define SM_CYSMICON 50
#define SM_CYSMCAPTION 51
#define SM_CXSMSIZE 52
#define SM_CYSMSIZE 53
#define SM_CXMENUSIZE 54
#define SM_CYMENUSIZE 55
#define SM_ARRANGE 56
#define SM_CXMINIMIZED 57
#define SM_CYMINIMIZED 58
#define SM_CXMAXTRACK 59
#define SM_CYMAXTRACK 60
#define SM_CXMAXIMIZED 61
#define SM_CYMAXIMIZED 62
#define SM_NETWORK 63
#define SM_CLEANBOOT 67
#define SM_CXDRAG 68
#define SM_CYDRAG 69
#define SM_SHOWSOUNDS 70
#define SM_CXMENUCHECK 71 // Use instead of
GetMenuCheckMarkDimensions()!
#define SM_CYMENUCHECK 72
#define SM_SLOWMACHINE 73
#define SM_MIDEASTENABLED 74
#define SM_MOUSEWHEELPRESENT 75
#define SM_XVIRTUALSCREEN 76
#define SM_YVIRTUALSCREEN 77
#define SM_CXVIRTUALSCREEN 78
#define SM_CYVIRTUALSCREEN 79
#define SM_CMONITORS 80
#define SM_SAMEDISPLAYFORMAT 81

//---- GetWindow() Constants


#define GW_HWNDFIRST 0
#define GW_HWNDLAST 1
#define GW_HWNDNEXT 2
#define GW_HWNDPREV 3
#define GW_OWNER 4
#define GW_CHILD 5

//---- AnimateWindow() Commands


#define AW_HOR_POSITIVE 0x00000001
#define AW_HOR_NEGATIVE 0x00000002
#define AW_VER_POSITIVE 0x00000004
#define AW_VER_NEGATIVE 0x00000008
#define AW_CENTER 0x00000010
#define AW_HIDE 0x00010000
#define AW_ACTIVATE 0x00020000
#define AW_SLIDE 0x00040000
#define AW_BLEND 0x00080000

//---- MessageBox() Flags


#define MB_OK 0x00000000
#define MB_OKCANCEL 0x00000001
#define MB_ABORTRETRYIGNORE 0x00000002
#define MB_YESNOCANCEL 0x00000003
#define MB_YESNO 0x00000004
#define MB_RETRYCANCEL 0x00000005
#define MB_ICONHAND 0x00000010
#define MB_ICONQUESTION 0x00000020
#define MB_ICONEXCLAMATION 0x00000030
#define MB_ICONASTERISK 0x00000040
#define MB_USERICON 0x00000080
#define MB_ICONWARNING MB_ICONEXCLAMATION
#define MB_ICONERROR MB_ICONHAND
#define MB_ICONINFORMATION MB_ICONASTERISK
#define MB_ICONSTOP MB_ICONHAND
#define MB_DEFBUTTON1 0x00000000
#define MB_DEFBUTTON2 0x00000100
#define MB_DEFBUTTON3 0x00000200
#define MB_DEFBUTTON4 0x00000300
#define MB_APPLMODAL 0x00000000
#define MB_SYSTEMMODAL 0x00001000
#define MB_TASKMODAL 0x00002000
#define MB_HELP 0x00004000 // Help Button
#define MB_NOFOCUS 0x00008000
#define MB_SETFOREGROUND 0x00010000
#define MB_DEFAULT_DESKTOP_ONLY 0x00020000
#define MB_TOPMOST 0x00040000
#define MB_RIGHT 0x00080000
#define MB_RTLREADING 0x00100000

//---- Dialog Box Command IDs


#define IDOK 1
#define IDCANCEL 2
#define IDABORT 3
#define IDRETRY 4
#define IDIGNORE 5
#define IDYES 6
#define IDNO 7
#define IDCLOSE 8
#define IDHELP 9

//+------------------------------------------------------------------+

Scripts
//+------------------------------------------------------------------+
//| Period_Converter.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"
#property show_inputs
#include <WinUser32.mqh>

extern int ExtPeriodMultiplier=3; // new period multiplier factor


int ExtHandle=-1;
//+------------------------------------------------------------------+
//| script program start function |
//+------------------------------------------------------------------+
int start()
{
int i, start_pos, i_time, time0, last_fpos, periodseconds;
double d_open, d_low, d_high, d_close, d_volume, last_volume;
int hwnd=0,cnt=0;
//---- History header
int version=400;
string c_copyright;
string c_symbol=Symbol();
int i_period=Period()*ExtPeriodMultiplier;
int i_digits=Digits;
int i_unused[13];
//----
ExtHandle=FileOpenHistory(c_symbol+i_period+".hst", FILE_BIN|FILE_WRITE);
if(ExtHandle < 0) return(-1);
//---- write history file header
c_copyright="(C)opyright 2003, MetaQuotes Software Corp.";
FileWriteInteger(ExtHandle, version, LONG_VALUE);
FileWriteString(ExtHandle, c_copyright, 64);
FileWriteString(ExtHandle, c_symbol, 12);
FileWriteInteger(ExtHandle, i_period, LONG_VALUE);
FileWriteInteger(ExtHandle, i_digits, LONG_VALUE);
FileWriteInteger(ExtHandle, 0, LONG_VALUE); //timesign
FileWriteInteger(ExtHandle, 0, LONG_VALUE); //last_sync
FileWriteArray(ExtHandle, i_unused, 0, 13);
//---- write history file
periodseconds=i_period*60;
start_pos=Bars-1;
d_open=Open[start_pos];
d_low=Low[start_pos];
d_high=High[start_pos];
d_volume=Volume[start_pos];
//---- normalize open time
i_time=Time[start_pos]/periodseconds;
i_time*=periodseconds;
for(i=start_pos-1;i>=0; i--)
{
time0=Time[i];
if(time0>=i_time+periodseconds || i==0)
{
if(i==0 && time0<i_time+periodseconds)
{
d_volume+=Volume[0];
if (Low[0]<d_low) d_low=Low[0];
if (High[0]>d_high) d_high=High[0];
d_close=Close[0];
}
last_fpos=FileTell(ExtHandle);
last_volume=Volume[i];
FileWriteInteger(ExtHandle, i_time, LONG_VALUE);
FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE);
FileFlush(ExtHandle);
cnt++;
if(time0>=i_time+periodseconds)
{
i_time=time0/periodseconds;
i_time*=periodseconds;
d_open=Open[i];
d_low=Low[i];
d_high=High[i];
d_close=Close[i];
d_volume=last_volume;
}
}
else
{
d_volume+=Volume[i];
if (Low[i]<d_low) d_low=Low[i];
if (High[i]>d_high) d_high=High[i];
d_close=Close[i];
}
}
FileFlush(ExtHandle);
Print(cnt," record(s) written");
//---- collect incoming ticks
int last_time=LocalTime()-5;
while(true)
{
int cur_time=LocalTime();
//---- check for new rates
if(RefreshRates())
{
time0=Time[0];
FileSeek(ExtHandle,last_fpos,SEEK_SET);
//---- is there current bar?
if(time0<i_time+periodseconds)
{
d_volume+=Volume[0]-last_volume;
last_volume=Volume[0];
if (Low[0]<d_low) d_low=Low[0];
if (High[0]>d_high) d_high=High[0];
d_close=Close[0];
}
else
{
//---- no, there is new bar
d_volume+=Volume[1]-last_volume;
if (Low[1]<d_low) d_low=Low[1];
if (High[1]>d_high) d_high=High[1];
//---- write previous bar remains
FileWriteInteger(ExtHandle, i_time, LONG_VALUE);
FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE);
last_fpos=FileTell(ExtHandle);
//----
i_time=time0/periodseconds;
i_time*=periodseconds;
d_open=Open[0];
d_low=Low[0];
d_high=High[0];
d_close=Close[0];
d_volume=Volume[0];
last_volume=d_volume;
}
//----
FileWriteInteger(ExtHandle, i_time, LONG_VALUE);
FileWriteDouble(ExtHandle, d_open, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_low, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_high, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_close, DOUBLE_VALUE);
FileWriteDouble(ExtHandle, d_volume, DOUBLE_VALUE);
FileFlush(ExtHandle);
//----
if(hwnd==0)
{
hwnd=WindowHandle(Symbol(),i_period);
if(hwnd!=0) Print("Chart window detected");
}
//---- refresh window not frequently than 1 time in 2 seconds
if(hwnd!=0 && cur_time-last_time>=2)
{
PostMessageA(hwnd,WM_COMMAND,33324,0);
last_time=cur_time;
}
}
}
//----
return(0);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void deinit()
{
if(ExtHandle>=0) { FileClose(ExtHandle); ExtHandle=-1; }
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| rotate_text.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
#include <stdlib.mqh>

string line_name="rotating_line";
string object_name1="rotating_text";

void init()
{
Print("point = ", Point," bars=",Bars);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void deinit()
{
ObjectDelete(line_name);
ObjectDelete(object_name1);
ObjectsRedraw();
}
//+------------------------------------------------------------------+
//| script program start function |
//+------------------------------------------------------------------+
int start()
{
int time2;
int error,index,fontsize=10;
double price,price1,price2;
double angle=0.0;
//----
price2=High[10]+Point*10;
ObjectCreate(line_name, OBJ_TRENDBYANGLE, 0, Time[10], price2);
index=20;
ObjectCreate(object_name1, OBJ_TEXT, 0, Time[index], Low[index]-Point*100);
ObjectSetText(object_name1, "rotating_text", fontsize);
while(IsStopped()==false)
{
index++;
price=ObjectGet(object_name1, OBJPROP_PRICE1)+Point;
error=GetLastError();
if(error!=0)
{
Print(object_name1," : ",ErrorDescription(error));
break;
}
ObjectMove(object_name1, 0, Time[index], price);
ObjectSet(object_name1, OBJPROP_ANGLE, angle*2);
ObjectSet(object_name1, OBJPROP_FONTSIZE, fontsize);
ObjectSet(line_name, OBJPROP_WIDTH, angle/18.0);
double line_angle=360.0-angle;
if(line_angle==90.0) ObjectSet(line_name, OBJPROP_PRICE2, price2+Point*50);
if(line_angle==270.0) ObjectSet(line_name, OBJPROP_PRICE2, price2-Point*50);
time2=ObjectGet(line_name,OBJPROP_TIME2);
if(line_angle>90.0 && line_angle<270.0) time2=Time[index+10];
else time2=Time[0];
ObjectSet(line_name, OBJPROP_TIME2, time2);
ObjectSet(line_name, OBJPROP_ANGLE, line_angle);
ObjectsRedraw();
angle+=3.0;
if(angle>=360.0) angle=360.0-angle;
fontsize++;
if(fontsize>48) fontsize=6;
Sleep(500);
price1=ObjectGetValueByShift(line_name, index);
if(GetLastError()==0)
{
if(MathAbs(price1-price) < Point*50)
{
Print("price=",price," price1=", price1);
ObjectSetText(object_name1, "REMOVED", 48, "Arial", RGB(255,215,0));
ObjectsRedraw();
Sleep(5000);
// ObjectDelete(object_name1);
}
}
}
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| trade.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#include <stdlib.mqh>
#include <WinUser32.mqh>
//+------------------------------------------------------------------+
//| script "trading for all money" |
//+------------------------------------------------------------------+
int start()
{
//----
if(MessageBox("Do you really want to BUY 1.00 "+Symbol()+" at ASK price? ",
"Script",MB_YESNO|MB_ICONQUESTION)!=IDYES) return(1);
//----
int ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert comment",255,0,CLR_NONE);
if(ticket<1)
{
int error=GetLastError();
Print("Error = ",ErrorDescription(error));
return;
}
//----
OrderPrint();
return(0);
}
//+------------------------------------------------------------------+

Templates
<expert>
type=INDICATOR_ADVISOR
description=Accelerator Oscilator
separate_window=1
used_buffers=4
<ind>
color=Green
type=DRAW_HISTOGRAM
</ind>
<ind>
color=Red
type=DRAW_HISTOGRAM
</ind>
</expert>
#header#
#property copyright "#copyright#"
#property link "#link#"

#indicator_properties#
#extern_variables#
#mapping_buffers#
//---- indicator buffers
double ExtGreenBuffer[];
double ExtRedBuffer[];
double ExtMABuffer[];
double ExtBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
#buffers_used#;
//---- indicator buffers mapping
SetIndexBuffer(0, ExtGreenBuffer);
SetIndexBuffer(1, ExtRedBuffer);
SetIndexBuffer(2, ExtMABuffer);
SetIndexBuffer(3, ExtBuffer);
//---- drawing settings
#indicators_init#
//----
IndicatorDigits(6);
SetIndexDrawBegin(0,38);
SetIndexDrawBegin(1,38);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("AC");
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Accelerator/Decelerator Oscillator |
//+------------------------------------------------------------------+
int start()
{
int limit;
int counted_bars=IndicatorCounted();
double prev,current;
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- macd counted in the 1-st additional buffer
for(int i=0; i<limit; i++)
ExtMABuffer[i]=iMA(NULL,0,5,0,MODE_SMA,PRICE_MEDIAN,i)-
iMA(NULL,0,34,0,MODE_SMA,PRICE_MEDIAN,i);
//---- signal line counted in the 2-nd additional buffer
for(i=0; i<limit; i++)
ExtBuffer[i]=iMAOnArray(ExtMABuffer,Bars,5,0,MODE_SMA,i);
//---- dispatch values between 2 buffers
bool up=true;
for(i=limit-1; i>=0; i--)
{
current=ExtMABuffer[i]-ExtBuffer[i];
prev=ExtMABuffer[i+1]-ExtBuffer[i+1];
if(current>prev) up=true;
if(current<prev) up=false;
if(!up)
{
ExtRedBuffer[i]=current;
ExtGreenBuffer[i]=0.0;
}
else
{
ExtGreenBuffer[i]=current;
ExtRedBuffer[i]=0.0;
}
}
//---- done
return(0);
}
//+------------------------------------------------------------------+

<expert>
type=INDICATOR_ADVISOR
description=
used_buffers=3
<param>
name=JawsPeriod
type=int
value=13
</param>
<param>
name=JawsShift
type=int
value=8
</param>
<param>
name=TeethPeriod
type=int
value=8
</param>
<param>
name=TeethShift
type=int
value=5
</param>
<param>
name=LipsPeriod
type=int
value=5
</param>
<param>
name=LipsShift
type=int
value=3
</param>
<ind>
color=Blue
</ind>
<ind>
color=Red
</ind>
<ind>
color=Lime
</ind>
</expert>
#header#
#property copyright "#copyright#"
#property link "#link#"

#indicator_properties#
#extern_variables#
#mapping_buffers#
//---- indicator buffers
double ExtBlueBuffer[];
double ExtRedBuffer[];
double ExtLimeBuffer[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
#buffers_used#
//---- line shifts when drawing
SetIndexShift(0,JawsShift);
SetIndexShift(1,TeethShift);
SetIndexShift(2,LipsShift);
//---- first positions skipped when drawing
SetIndexDrawBegin(0,JawsShift+JawsPeriod);
SetIndexDrawBegin(1,TeethShift+TeethPeriod);
SetIndexDrawBegin(2,LipsShift+LipsPeriod);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ExtBlueBuffer);
SetIndexBuffer(1,ExtRedBuffer);
SetIndexBuffer(2,ExtLimeBuffer);
//---- drawing settings
#indicators_init#
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Bill Williams' Alligator |
//+------------------------------------------------------------------+
int start()
{
int limit;
int counted_bars=IndicatorCounted();
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- main loop
for(int i=0; i<limit; i++)
{
//---- ma_shift set to 0 because SetIndexShift called abowe
ExtBlueBuffer[i]=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtRedBuffer[i]=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtLimeBuffer[i]=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
}
//---- done
return(0);
}
//+------------------------------------------------------------------+

<expert>
type=INDICATOR_ADVISOR
description=Awesome Oscilator
separate_window=1
used_buffers=3;
<ind>
color=Green
type=DRAW_HISTOGRAM
</ind>
<ind>
color=Red
type=DRAW_HISTOGRAM
</ind>
</expert>
#header#
#property copyright "#copyright#"
#property link "#link#"

#indicator_properties#
#extern_variables#
#mapping_buffers#
//---- indicator buffers
double ExtGreenBuffer[];
double ExtRedBuffer[];
double ExtMABuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
#buffers_used#
//---- drawing settings
#indicators_init#
IndicatorDigits(5);
SetIndexDrawBegin(0,34);
SetIndexDrawBegin(1,34);
//---- indicator buffers mapping
SetIndexBuffer(0, ExtGreenBuffer);
SetIndexBuffer(1, ExtRedBuffer);
SetIndexBuffer(2, ExtMABuffer);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("AO");
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Awesome Oscillator |
//+------------------------------------------------------------------+
int start()
{
int limit;
int counted_bars=IndicatorCounted();
double prev,current;
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- macd counted in the 1-st additional buffer
for(int i=0; i<limit; i++)
ExtMABuffer[i]=iMA(NULL,0,5,0,MODE_SMA,PRICE_MEDIAN,i)-
iMA(NULL,0,34,0,MODE_SMA,PRICE_MEDIAN,i);
//---- dispatch values between 2 buffers
bool up=true;
for(i=limit-1; i>=0; i--)
{
current=ExtMABuffer[i];
prev=ExtMABuffer[i+1];
if(current>prev) up=true;
if(current<prev) up=false;
if(!up)
{
ExtRedBuffer[i]=current;
ExtGreenBuffer[i]=0.0;
}
else
{
ExtGreenBuffer[i]=current;
ExtRedBuffer[i]=0.0;
}
}
//---- done
return(0);
}
//+------------------------------------------------------------------+

<expert>
type=EXPERT_ADVISOR
</expert>
#header#
#property copyright "#copyright#"
#property link "#link#"

#extern_variables#
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| expert start function |
//+------------------------------------------------------------------+
int start()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+

<expert>
type=INDICATOR_ADVISOR
</expert>
#header#
#property copyright "#copyright#"
#property link "#link#"
#indicator_properties#
#extern_variables#
#mapping_buffers#
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
#buffers_used#
//---- indicators
#indicators_init#
//----
return(0);
}
//+------------------------------------------------------------------+
//| Custor indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start()
{
int counted_bars=IndicatorCounted();
//----

//----
return(0);
}
//+------------------------------------------------------------------+

<expert>
type=INDICATOR_ADVISOR
separate_window=1
used_buffers=2
<param>
type=int
name=FastEMA
value=12
</param>
<param>
type=int
name=SlowEMA
value=26
</param>
<param>
type=int
name=SignalSMA
value=9
</param>
<ind>
color=Silver
type=DRAW_HISTOGRAM
</ind>
<ind>
color=Red
</ind>
</expert>
#header#
#property copyright "#copyright#"
#property link "#link#"

#indicator_properties#
#extern_variables#
#mapping_buffers#
//---- indicator buffers
double ExtSilverBuffer[];
double ExtRedBuffer[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
#buffers_used#;
//---- drawing settings
#indicators_init#
//----
SetIndexDrawBegin(1,SignalSMA);
IndicatorDigits(5);
//---- indicator buffers mapping
SetIndexBuffer(0, ExtSilverBuffer);
SetIndexBuffer(1, ExtRedBuffer);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("MACD("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Moving Averages Convergence/Divergence |
//+------------------------------------------------------------------+
int start()
{
int limit;
int counted_bars=IndicatorCounted();
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- macd counted in the 1-st buffer
for(int i=0; i<limit; i++)
ExtSilverBuffer[i]=iMA(NULL,0,FastEMA,0,MODE_EMA,PRICE_CLOSE,i)-
iMA(NULL,0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,i);
//---- signal line counted in the 2-nd buffer
for(i=0; i<limit; i++)
ExtRedBuffer[i]=iMAOnArray(ExtSilverBuffer,Bars,SignalSMA,0,MODE_SMA,i);
//---- done
return(0);
}
//+------------------------------------------------------------------+

<expert>
type=INDICATOR_ADVISOR
separate_window=1
used_buffers=3
<param>
name=FastEMA
type=int
value=12
</param>
<param>
name=SlowEMA
type=int
value=26
</param>
<param>
name=SignalSMA
type=int
value=9
</param>
<ind>
type=DRAW_HISTOGRAM
color=Silver
</ind>
</expert>
#header#
#property copyright "#copyright#"
#property link "#link#"

#indicator_properties#
#extern_variables#
#mapping_buffers#
//---- indicator buffers
double ExtSilverBuffer[];
double ExtMABuffer[];
double ExtBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
#buffers_used#;
//---- drawing settings
#indicators_init#
//----
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(6);
//---- indicator buffers mapping
SetIndexBuffer(0,ExtSilverBuffer);
SetIndexBuffer(1,ExtMABuffer);
SetIndexBuffer(2,ExtBuffer);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Moving Average of Oscillator |
//+------------------------------------------------------------------+
int start()
{
int limit;
int counted_bars=IndicatorCounted();
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- macd counted in the 1-st additional buffer
for(int i=0; i<limit; i++)
ExtMABuffer[i]=iMA(NULL,0,FastEMA,0,MODE_EMA,PRICE_CLOSE,i)-
iMA(NULL,0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,i);
//---- signal line counted in the 2-nd additional buffer
for(i=0; i<limit; i++)
ExtBuffer[i]=iMAOnArray(ExtMABuffer,Bars,SignalSMA,0,MODE_SMA,i);
//---- main loop
for(i=0; i<limit; i++)
ExtSilverBuffer[i]=ExtMABuffer[i]-ExtBuffer[i];
//---- done
return(0);
}
//+------------------------------------------------------------------+
<expert>
type=SCRIPT_ADVISOR
</expert>
#header#
#property copyright "#copyright#"
#property link "#link#"

#extern_variables#
//+------------------------------------------------------------------+
//| script program start function |
//+------------------------------------------------------------------+
int start()
{
//----

//----
return(0);
}
//+------------------------------------------------------------------+

Library
//+------------------------------------------------------------------+
//| stdlib.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
#property library
/*
int init()
{
Print("Init function defined as feature sample");
}
int deinit()
{
Print("Deinit function defined as feature sample too");
}
*/
//+------------------------------------------------------------------+
//| return error description |
//+------------------------------------------------------------------+
string ErrorDescription(int error_code)
{
string error_string;
//----
switch(error_code)
{
//---- codes returned from trade server
case 0:
case 1: error_string="no error";
break;
case 2: error_string="common error";
break;
case 3: error_string="invalid trade parameters";
break;
case 4: error_string="trade server is busy";
break;
case 5: error_string="old version of the client terminal";
break;
case 6: error_string="no connection with trade server";
break;
case 7: error_string="not enough rights";
break;
case 8: error_string="too frequent requests";
break;
case 9: error_string="malfunctional trade operation";
break;
case 64: error_string="account disabled";
break;
case 65: error_string="invalid account";
break;
case 128: error_string="trade timeout";
break;
case 129: error_string="invalid price";
break;
case 130: error_string="invalid stops";
break;
case 131: error_string="invalid trade volume";
break;
case 132: error_string="market is closed";
break;
case 133: error_string="trade is disabled";
break;
case 134: error_string="not enough money";
break;
case 135: error_string="price changed";
break;
case 136: error_string="off quotes";
break;
case 137: error_string="broker is busy";
break;
case 138: error_string="requote";
break;
case 139: error_string="order is locked";
break;
case 140: error_string="long positions only allowed";
break;
case 141: error_string="too many requests";
break;
case 145: error_string="modification denied because order too close to market";
break;
case 146: error_string="trade context is busy";
break;
//---- mql4 errors
case 4000: error_string="no error";
break;
case 4001: error_string="wrong function pointer";
break;
case 4002: error_string="array index is out of range";
break;
case 4003: error_string="no memory for function call stack";
break;
case 4004: error_string="recursive stack overflow";
break;
case 4005: error_string="not enough stack for parameter";
break;
case 4006: error_string="no memory for parameter string";
break;
case 4007: error_string="no memory for temp string";
break;
case 4008: error_string="not initialized string";
break;
case 4009: error_string="not initialized string in array";
break;
case 4010: error_string="no memory for array\' string";
break;
case 4011: error_string="too long string";
break;
case 4012: error_string="remainder from zero divide";
break;
case 4013: error_string="zero divide";
break;
case 4014: error_string="unknown command";
break;
case 4015: error_string="wrong jump (never generated error)";
break;
case 4016: error_string="not initialized array";
break;
case 4017: error_string="dll calls are not allowed";
break;
case 4018: error_string="cannot load library";
break;
case 4019: error_string="cannot call function";
break;
case 4020: error_string="expert function calls are not allowed";
break;
case 4021: error_string="not enough memory for temp string returned from
function"; break;
case 4022: error_string="system is busy (never generated error)";
break;
case 4050: error_string="invalid function parameters count";
break;
case 4051: error_string="invalid function parameter value";
break;
case 4052: error_string="string function internal error";
break;
case 4053: error_string="some array error";
break;
case 4054: error_string="incorrect series array using";
break;
case 4055: error_string="custom indicator error";
break;
case 4056: error_string="arrays are incompatible";
break;
case 4057: error_string="global variables processing error";
break;
case 4058: error_string="global variable not found";
break;
case 4059: error_string="function is not allowed in testing mode";
break;
case 4060: error_string="function is not confirmed";
break;
case 4061: error_string="send mail error";
break;
case 4062: error_string="string parameter expected";
break;
case 4063: error_string="integer parameter expected";
break;
case 4064: error_string="double parameter expected";
break;
case 4065: error_string="array as parameter expected";
break;
case 4066: error_string="requested history data in update state";
break;
case 4099: error_string="end of file";
break;
case 4100: error_string="some file error";
break;
case 4101: error_string="wrong file name";
break;
case 4102: error_string="too many opened files";
break;
case 4103: error_string="cannot open file";
break;
case 4104: error_string="incompatible access to a file";
break;
case 4105: error_string="no order selected";
break;
case 4106: error_string="unknown symbol";
break;
case 4107: error_string="invalid price parameter for trade function";
break;
case 4108: error_string="invalid ticket";
break;
case 4109: error_string="trade is not allowed";
break;
case 4110: error_string="longs are not allowed";
break;
case 4111: error_string="shorts are not allowed";
break;
case 4200: error_string="object is already exist";
break;
case 4201: error_string="unknown object property";
break;
case 4202: error_string="object is not exist";
break;
case 4203: error_string="unknown object type";
break;
case 4204: error_string="no object name";
break;
case 4205: error_string="object coordinates error";
break;
case 4206: error_string="no specified subwindow";
break;
default: error_string="unknown error";
}
//----
return(error_string);
}
//+------------------------------------------------------------------+
//| convert red, green and blue values to color |
//+------------------------------------------------------------------+
int RGB(int red_value,int green_value,int blue_value)
{
//---- check parameters
if(red_value<0) red_value=0;
if(red_value>255) red_value=255;
if(green_value<0) green_value=0;
if(green_value>255) green_value=255;
if(blue_value<0) blue_value=0;
if(blue_value>255) blue_value=255;
//----
green_value<<=8;
blue_value<<=16;
return(red_value+green_value+blue_value);
}
//+------------------------------------------------------------------+
//| right comparison of 2 doubles |
//+------------------------------------------------------------------+
bool CompareDoubles(double number1,double number2)
{
if(NormalizeDouble(number1-number2,8)==0) return(true);
else return(false);
}
//+------------------------------------------------------------------+
//| up to 16 digits after decimal point |
//+------------------------------------------------------------------+
string DoubleToStrMorePrecision(double number,int precision)
{
double rem,integer,integer2;
double DecimalArray[17]={ 1.0, 10.0, 100.0, 1000.0, 10000.0, 100000.0, 1000000.0,
10000000.0, 100000000.0,
1000000000.0, 10000000000.0, 100000000000.0,
10000000000000.0, 100000000000000.0,
1000000000000000.0, 1000000000000000.0,
10000000000000000.0 };
string intstring,remstring,retstring;
bool isnegative=false;
int rem2;
//----
if(precision<0) precision=0;
if(precision>16) precision=16;
//----
double p=DecimalArray[precision];
if(number<0.0) { isnegative=true; number=-number; }
integer=MathFloor(number);
rem=MathRound((number-integer)*p);
remstring="";
for(int i=0; i<precision; i++)
{
integer2=MathFloor(rem/10);
rem2=NormalizeDouble(rem-integer2*10,0);
remstring=rem2+remstring;
rem=integer2;
}
//----
intstring=DoubleToStr(integer,0);
if(isnegative) retstring="-"+intstring;
else retstring=intstring;
if(precision>0) retstring=retstring+"."+remstring;
return(retstring);
}
//+------------------------------------------------------------------+
//| convert integer to string contained input's hexadecimal notation |
//+------------------------------------------------------------------+
string IntegerToHexString(int integer_number)
{
string hex_string="00000000";
int value, shift=28;
// Print("Parameter for IntegerHexToString is ",integer_number);
//----
for(int i=0; i<8; i++)
{
value=(integer_number>>shift)&0x0F;
if(value<10) hex_string=StringSetChar(hex_string, i, value+'0');
else hex_string=StringSetChar(hex_string, i, (value-10)+'A');
shift-=4;
}
//----
return(hex_string);
}

Indicators
//+------------------------------------------------------------------+
//| CCI.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 LightSeaGreen
//---- input parameters
extern int CCIPeriod=14;
//---- buffers
double CCIBuffer[];
double RelBuffer[];
double DevBuffer[];
double MovBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
string short_name;
//---- 3 additional buffers are used for counting.
IndicatorBuffers(4);
SetIndexBuffer(1, RelBuffer);
SetIndexBuffer(2, DevBuffer);
SetIndexBuffer(3, MovBuffer);
//---- indicator lines
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,CCIBuffer);
//---- name for DataWindow and indicator subwindow label
short_name="CCI("+CCIPeriod+")";
IndicatorShortName(short_name);
SetIndexLabel(0,short_name);
//----
SetIndexDrawBegin(0,CCIPeriod);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Commodity Channel Index |
//+------------------------------------------------------------------+
int start()
{
int i,k,counted_bars=IndicatorCounted();
double price,sum,mul;
if(Bars<=CCIPeriod) return(0);
//---- initial zero
if(counted_bars<1)
{
for(i=1;i<=CCIPeriod;i++) CCIBuffer[Bars-i]=0.0;
for(i=1;i<=CCIPeriod;i++) DevBuffer[Bars-i]=0.0;
for(i=1;i<=CCIPeriod;i++) MovBuffer[Bars-i]=0.0;
}
//---- last counted bar will be recounted
int limit=Bars-counted_bars;
if(counted_bars>0) limit++;
//---- moving average
for(i=0; i<limit; i++)
MovBuffer[i]=iMA(NULL,0,CCIPeriod,0,MODE_SMA,PRICE_TYPICAL,i);
//---- standard deviations
i=Bars-CCIPeriod+1;
if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1;
mul=0.015/CCIPeriod;
while(i>=0)
{
sum=0.0;
k=i+CCIPeriod-1;
while(k>=i)
{
price=(High[k]+Low[k]+Close[k])/3;
sum+=MathAbs(price-MovBuffer[i]);
k--;
}
DevBuffer[i]=sum*mul;
i--;
}
i=Bars-CCIPeriod+1;
if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1;
while(i>=0)
{
price=(High[i]+Low[i]+Close[i])/3;
RelBuffer[i]=price-MovBuffer[i];
i--;
}
//---- cci counting
i=Bars-CCIPeriod+1;
if(counted_bars>CCIPeriod-1) i=Bars-counted_bars-1;
while(i>=0)
{
if(DevBuffer[i]==0.0) CCIBuffer[i]=0.0;
else CCIBuffer[i]=RelBuffer[i]/DevBuffer[i];
i--;
}
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Ichimoku.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_chart_window
#property indicator_buffers 7
#property indicator_color1 Red
#property indicator_color2 Blue
#property indicator_color3 SandyBrown
#property indicator_color4 Thistle
#property indicator_color5 Lime
#property indicator_color6 SandyBrown
#property indicator_color7 Thistle
//---- input parameters
extern int Tenkan=9;
extern int Kijun=26;
extern int Senkou=52;
//---- buffers
double Tenkan_Buffer[];
double Kijun_Buffer[];
double SpanA_Buffer[];
double SpanB_Buffer[];
double Chinkou_Buffer[];
double SpanA2_Buffer[];
double SpanB2_Buffer[];
//----
int a_begin;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//----
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,Tenkan_Buffer);
SetIndexDrawBegin(0,Tenkan-1);
SetIndexLabel(0,"Tenkan Sen");
//----
SetIndexStyle(1,DRAW_LINE);
SetIndexBuffer(1,Kijun_Buffer);
SetIndexDrawBegin(1,Kijun-1);
SetIndexLabel(1,"Kijun Sen");
//----
a_begin=Kijun; if(a_begin<Tenkan) a_begin=Tenkan;
SetIndexStyle(2,DRAW_HISTOGRAM,STYLE_DOT);
SetIndexBuffer(2,SpanA_Buffer);
SetIndexDrawBegin(2,Kijun+a_begin-1);
SetIndexShift(2,Kijun);
SetIndexLabel(2,NULL);
SetIndexStyle(5,DRAW_LINE,STYLE_DOT);
SetIndexBuffer(5,SpanA2_Buffer);
SetIndexDrawBegin(5,Kijun+a_begin-1);
SetIndexShift(5,Kijun);
SetIndexLabel(5,"Senkou Span A");
//----
SetIndexStyle(3,DRAW_HISTOGRAM,STYLE_DOT);
SetIndexBuffer(3,SpanB_Buffer);
SetIndexDrawBegin(3,Kijun+Senkou-1);
SetIndexShift(3,Kijun);
SetIndexLabel(3,NULL);
SetIndexStyle(6,DRAW_LINE,STYLE_DOT);
SetIndexBuffer(6,SpanB2_Buffer);
SetIndexDrawBegin(6,Kijun+Senkou-1);
SetIndexShift(6,Kijun);
SetIndexLabel(6,"Senkou Span B");
//----
SetIndexStyle(4,DRAW_LINE);
SetIndexBuffer(4,Chinkou_Buffer);
SetIndexShift(4,-Kijun);
SetIndexLabel(4,"Chinkou Span");
//----
return(0);
}
//+------------------------------------------------------------------+
//| Ichimoku Kinko Hyo |
//+------------------------------------------------------------------+
int start()
{
int i,k;
int counted_bars=IndicatorCounted();
double high,low,price;
//----
if(Bars<=Tenkan || Bars<=Kijun || Bars<=Senkou) return(0);
//---- initial zero
if(counted_bars<1)
{
for(i=1;i<=Tenkan;i++) Tenkan_Buffer[Bars-i]=0;
for(i=1;i<=Kijun;i++) Kijun_Buffer[Bars-i]=0;
for(i=1;i<=a_begin;i++) { SpanA_Buffer[Bars-i]=0; SpanA2_Buffer[Bars-i]=0; }
for(i=1;i<=Senkou;i++) { SpanB_Buffer[Bars-i]=0; SpanB2_Buffer[Bars-i]=0; }
}
//---- Tenkan Sen
i=Bars-Tenkan;
if(counted_bars>Tenkan) i=Bars-counted_bars-1;
while(i>=0)
{
high=High[i]; low=Low[i]; k=i-1+Tenkan;
while(k>=i)
{
price=High[k];
if(high<price) high=price;
price=Low[k];
if(low>price) low=price;
k--;
}
Tenkan_Buffer[i]=(high+low)/2;
i--;
}
//---- Kijun Sen
i=Bars-Kijun;
if(counted_bars>Kijun) i=Bars-counted_bars-1;
while(i>=0)
{
high=High[i]; low=Low[i]; k=i-1+Kijun;
while(k>=i)
{
price=High[k];
if(high<price) high=price;
price=Low[k];
if(low>price) low=price;
k--;
}
Kijun_Buffer[i]=(high+low)/2;
i--;
}
//---- Senkou Span A
i=Bars-a_begin+1;
if(counted_bars>a_begin-1) i=Bars-counted_bars-1;
while(i>=0)
{
price=(Kijun_Buffer[i]+Tenkan_Buffer[i])/2;
SpanA_Buffer[i]=price;
SpanA2_Buffer[i]=price;
i--;
}
//---- Senkou Span B
i=Bars-Senkou;
if(counted_bars>Senkou) i=Bars-counted_bars-1;
while(i>=0)
{
high=High[i]; low=Low[i]; k=i-1+Senkou;
while(k>=i)
{
price=High[k];
if(high<price) high=price;
price=Low[k];
if(low>price) low=price;
k--;
}
price=(high+low)/2;
SpanB_Buffer[i]=price;
SpanB2_Buffer[i]=price;
i--;
}
//---- Chinkou Span
i=Bars-1;
if(counted_bars>1) i=Bars-counted_bars-1;
while(i>=0) { Chinkou_Buffer[i]=Close[i]; i--; }
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Custom MACD.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
//---- indicator settings
#property indicator_separate_window
#property indicator_buffers 2
#property indicator_color1 Silver
#property indicator_color2 Red
//---- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//---- indicator buffers
double ind_buffer1[];
double ind_buffer2[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(1,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+1);
//---- indicator buffers mapping
if(!SetIndexBuffer(0,ind_buffer1) && !SetIndexBuffer(1,ind_buffer2))
Print("cannot set indicator buffers!");
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("MACD("+FastEMA+","+SlowEMA+","+SignalSMA+")");
SetIndexLabel(0,"MACD");
SetIndexLabel(1,"Signal");
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Moving Averages Convergence/Divergence |
//+------------------------------------------------------------------+
int start()
{
int limit;
int counted_bars=IndicatorCounted();
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- macd counted in the 1-st buffer
for(int i=0; i<limit; i++)
ind_buffer1[i]=iMA(NULL,0,FastEMA,0,MODE_EMA,PRICE_CLOSE,i)-
iMA(NULL,0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,i);
//---- signal line counted in the 2-nd buffer
for(i=0; i<limit; i++)
ind_buffer2[i]=iMAOnArray(ind_buffer1,Bars,SignalSMA,0,MODE_SMA,i);
//---- done
return(0);
}

//+------------------------------------------------------------------+
//| Momentum.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 DodgerBlue
//---- input parameters
extern int MomPeriod=14;
//---- buffers
double MomBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
string short_name;
//---- indicator line
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,MomBuffer);
//---- name for DataWindow and indicator subwindow label
short_name="Mom("+MomPeriod+")";
IndicatorShortName(short_name);
SetIndexLabel(0,short_name);
//----
SetIndexDrawBegin(0,MomPeriod);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Momentum |
//+------------------------------------------------------------------+
int start()
{
int i,counted_bars=IndicatorCounted();
//----
if(Bars<=MomPeriod) return(0);
//---- initial zero
if(counted_bars<1)
for(i=1;i<=MomPeriod;i++) MomBuffer[Bars-i]=0.0;
//----
i=Bars-MomPeriod-1;
if(counted_bars>=MomPeriod) i=Bars-counted_bars-1;
while(i>=0)
{
MomBuffer[i]=Close[i]*100/Close[i+MomPeriod];
i--;
}
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Custom Moving Average.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Red
//---- indicator parameters
extern int MA_Period=13;
extern int MA_Shift=0;
extern int MA_Method=0;
//---- indicator buffers
double ExtMapBuffer[];
//----
int ExtCountedBars=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
int draw_begin;
string short_name;
//---- drawing settings
SetIndexStyle(0,DRAW_LINE);
SetIndexShift(0,MA_Shift);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS));
if(MA_Period<2) MA_Period=13;
draw_begin=MA_Period-1;
//---- indicator short name
switch(MA_Method)
{
case 1 : short_name="EMA("; draw_begin=0; break;
case 2 : short_name="SMMA("; break;
case 3 : short_name="LWMA("; break;
default :
MA_Method=0;
short_name="SMA(";
}
IndicatorShortName(short_name+MA_Period+")");
SetIndexDrawBegin(0,draw_begin);
//---- indicator buffers mapping
SetIndexBuffer(0,ExtMapBuffer);
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int start()
{
if(Bars<=MA_Period) return(0);
ExtCountedBars=IndicatorCounted();
//---- check for possible errors
if (ExtCountedBars<0) return(-1);
//---- last counted bar will be recounted
if (ExtCountedBars>0) ExtCountedBars--;
//----
switch(MA_Method)
{
case 0 : sma(); break;
case 1 : ema(); break;
case 2 : smma(); break;
case 3 : lwma();
}
//---- done
return(0);
}
//+------------------------------------------------------------------+
//| Simple Moving Average |
//+------------------------------------------------------------------+
void sma()
{
double sum=0;
int i,pos=Bars-ExtCountedBars-1;
//---- initial accumulation
if(pos<MA_Period) pos=MA_Period;
for(i=1;i<MA_Period;i++,pos--)
sum+=Close[pos];
//---- main calculation loop
while(pos>=0)
{
sum+=Close[pos];
ExtMapBuffer[pos]=sum/MA_Period;
sum-=Close[pos+MA_Period-1];
pos--;
}
//---- zero initial bars
if(ExtCountedBars<1)
for(i=1;i<MA_Period;i++) ExtMapBuffer[Bars-i]=0;
}
//+------------------------------------------------------------------+
//| Exponential Moving Average |
//+------------------------------------------------------------------+
void ema()
{
double pr=2.0/(MA_Period+1);
int pos=Bars-2;
if(ExtCountedBars>2) pos=Bars-ExtCountedBars-1;
//---- main calculation loop
while(pos>=0)
{
if(pos==Bars-2) ExtMapBuffer[pos+1]=Close[pos+1];
ExtMapBuffer[pos]=Close[pos]*pr+ExtMapBuffer[pos+1]*(1-pr);
pos--;
}
}
//+------------------------------------------------------------------+
//| Smoothed Moving Average |
//+------------------------------------------------------------------+
void smma()
{
double sum=0;
int i,k,pos=Bars-ExtCountedBars+1;
//---- main calculation loop
pos=Bars-MA_Period;
if(pos>Bars-ExtCountedBars) pos=Bars-ExtCountedBars;
while(pos>=0)
{
if(pos==Bars-MA_Period)
{
//---- initial accumulation
for(i=0,k=pos;i<MA_Period;i++,k++)
{
sum+=Close[k];
//---- zero initial bars
ExtMapBuffer[k]=0;
}
}
else sum=ExtMapBuffer[pos+1]*(MA_Period-1)+Close[pos];
ExtMapBuffer[pos]=sum/MA_Period;
pos--;
}
}
//+------------------------------------------------------------------+
//| Linear Weighted Moving Average |
//+------------------------------------------------------------------+
void lwma()
{
double sum=0.0,lsum=0.0;
double price;
int i,weight=0,pos=Bars-ExtCountedBars-1;
//---- initial accumulation
if(pos<MA_Period) pos=MA_Period;
for(i=1;i<=MA_Period;i++,pos--)
{
price=Close[pos];
sum+=price*i;
lsum+=price;
weight+=i;
}
//---- main calculation loop
pos++;
i=pos+MA_Period;
while(pos>=0)
{
ExtMapBuffer[pos]=sum/weight;
if(pos==0) break;
pos--;
i--;
price=Close[pos];
sum=sum-lsum+price*MA_Period;
lsum-=Close[i];
lsum+=price;
}
//---- zero initial bars
if(ExtCountedBars<1)
for(i=1;i<MA_Period;i++) ExtMapBuffer[Bars-i]=0;
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| OsMA.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
//---- indicator settings
#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//---- indicator parameters
extern int FastEMA=12;
extern int SlowEMA=26;
extern int SignalSMA=9;
//---- indicator buffers
double ind_buffer1[];
double ind_buffer2[];
double ind_buffer3[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
//---- drawing settings
SetIndexStyle(0,DRAW_HISTOGRAM,STYLE_SOLID,3);
SetIndexDrawBegin(0,SignalSMA);
IndicatorDigits(MarketInfo(Symbol(),MODE_DIGITS)+2);
//---- 3 indicator buffers mapping
if(!SetIndexBuffer(0,ind_buffer1) &&
!SetIndexBuffer(1,ind_buffer2) &&
!SetIndexBuffer(2,ind_buffer3))
Print("cannot set indicator buffers!");
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("OsMA("+FastEMA+","+SlowEMA+","+SignalSMA+")");
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Moving Average of Oscillator |
//+------------------------------------------------------------------+
int start()
{
int limit;
int counted_bars=IndicatorCounted();
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- macd counted in the 1-st additional buffer
for(int i=0; i<limit; i++)
ind_buffer2[i]=iMA(NULL,0,FastEMA,0,MODE_EMA,PRICE_CLOSE,i)-
iMA(NULL,0,SlowEMA,0,MODE_EMA,PRICE_CLOSE,i);
//---- signal line counted in the 2-nd additional buffer
for(i=0; i<limit; i++)
ind_buffer3[i]=iMAOnArray(ind_buffer2,Bars,SignalSMA,0,MODE_SMA,i);
//---- main loop
for(i=0; i<limit; i++)
ind_buffer1[i]=ind_buffer2[i]-ind_buffer3[i];
//---- done
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Parabolic.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Lime
//---- input parameters
extern double Step=0.02;
extern double Maximum=0.2;
//---- buffers
double SarBuffer[];
//----
int save_lastreverse;
bool save_dirlong;
double save_start;
double save_last_high;
double save_last_low;
double save_ep;
double save_sar;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
IndicatorDigits(Digits);
SetIndexStyle(0,DRAW_ARROW);
SetIndexArrow(0,159);
SetIndexBuffer(0,SarBuffer);
//----
return(0);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void SaveLastReverse(int last,int dir,double start,double low,double high,double
ep,double sar)
{
save_lastreverse=last;
save_dirlong=dir;
save_start=start;
save_last_low=low;
save_last_high=high;
save_ep=ep;
save_sar=sar;
}
//+------------------------------------------------------------------+
//| Parabolic Sell And Reverse system |
//+------------------------------------------------------------------+
int start()
{
static bool first=true;
bool dirlong;
double start,last_high,last_low;
double ep,sar,price_low,price_high,price;
int i,counted_bars=IndicatorCounted();
//----
if(Bars<3) return(0);
//---- initial settings
i=Bars-2;
if(counted_bars==0 || first)
{
first=false;
dirlong=true;
start=Step;
last_high=-10000000.0;
last_low=10000000.0;
while(i>0)
{
save_lastreverse=i;
price_low=Low[i];
if(last_low>price_low) last_low=price_low;
price_high=High[i];
if(last_high<price_high) last_high=price_high;
if(price_high>High[i+1] && price_low>Low[i+1]) break;
if(price_high<High[i+1] && price_low<Low[i+1]) { dirlong=false; break; }
i--;
}
//---- initial zero
int k=i;
while(k<Bars)
{
SarBuffer[k]=0.0;
k++;
}
//---- check further
if(dirlong) { SarBuffer[i]=Low[i+1]; ep=High[i]; }
else { SarBuffer[i]=High[i+1]; ep=Low[i]; }
i--;
}
else
{
i=save_lastreverse+1;
start=save_start;
dirlong=save_dirlong;
last_high=save_last_high;
last_low=save_last_low;
ep=save_ep;
sar=save_sar;
}
//----
while(i>=0)
{
price_low=Low[i];
price_high=High[i];
//--- check for reverse
if(dirlong && price_low<SarBuffer[i+1])
{
SaveLastReverse(i,true,start,price_low,last_high,ep,sar);
start=Step; dirlong=false;
ep=price_low; last_low=price_low;
SarBuffer[i]=last_high;
i--;
continue;
}
if(!dirlong && price_high>SarBuffer[i+1])
{
SaveLastReverse(i,false,start,last_low,price_high,ep,sar);
start=Step; dirlong=true;
ep=price_high; last_high=price_high;
SarBuffer[i]=last_low;
i--;
continue;
}
//---
price=SarBuffer[i+1];
sar=price+start*(ep-price);
if(dirlong)
{
if(ep<price_high && (start+Step)<=Maximum) start+=Step;
if(price_high<High[i+1] && i==Bars-2) sar=SarBuffer[i+1];

price=Low[i+1];
if(sar>price) sar=price;
price=Low[i+2];
if(sar>price) sar=price;
if(sar>price_low)
{
SaveLastReverse(i,true,start,price_low,last_high,ep,sar);
start=Step; dirlong=false; ep=price_low;
last_low=price_low;
SarBuffer[i]=last_high;
i--;
continue;
}
if(ep<price_high) { last_high=price_high; ep=price_high; }
}
else
{
if(ep>price_low && (start+Step)<=Maximum) start+=Step;
if(price_low<Low[i+1] && i==Bars-2) sar=SarBuffer[i+1];

price=High[i+1];
if(sar<price) sar=price;
price=High[i+2];
if(sar<price) sar=price;
if(sar<price_high)
{
SaveLastReverse(i,false,start,last_low,price_high,ep,sar);
start=Step; dirlong=true; ep=price_high;
last_high=price_high;
SarBuffer[i]=last_low;
i--;
continue;
}
if(ep>price_low) { last_low=price_low; ep=price_low; }
}
SarBuffer[i]=sar;
i--;
}
// sar=SarBuffer[0];
// price=iSAR(NULL,0,Step,Maximum,0);
// if(sar!=price) Print("custom=",sar," SAR=",price," counted=",counted_bars);
// if(sar==price) Print("custom=",sar," SAR=",price," counted=",counted_bars);
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| RSI.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_separate_window
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_buffers 1
#property indicator_color1 DodgerBlue
//---- input parameters
extern int RSIPeriod=14;
//---- buffers
double RSIBuffer[];
double PosBuffer[];
double NegBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
string short_name;
//---- 2 additional buffers are used for counting.
IndicatorBuffers(3);
SetIndexBuffer(1,PosBuffer);
SetIndexBuffer(2,NegBuffer);
//---- indicator line
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,RSIBuffer);
//---- name for DataWindow and indicator subwindow label
short_name="RSI("+RSIPeriod+")";
IndicatorShortName(short_name);
SetIndexLabel(0,short_name);
//----
SetIndexDrawBegin(0,RSIPeriod);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Relative Strength Index |
//+------------------------------------------------------------------+
int start()
{
int i,counted_bars=IndicatorCounted();
double rel,negative,positive;
//----
if(Bars<=RSIPeriod) return(0);
//---- initial zero
if(counted_bars<1)
for(i=1;i<=RSIPeriod;i++) RSIBuffer[Bars-i]=0.0;
//----
i=Bars-RSIPeriod-1;
if(counted_bars>=RSIPeriod) i=Bars-counted_bars-1;
while(i>=0)
{
double sumn=0.0,sump=0.0;
if(i==Bars-RSIPeriod-1)
{
int k=Bars-2;
//---- initial accumulation
while(k>=i)
{
rel=Close[k]-Close[k+1];
if(rel>0) sump+=rel;
else sumn-=rel;
k--;
}
positive=sump/RSIPeriod;
negative=sumn/RSIPeriod;
}
else
{
//---- smoothed moving average
rel=Close[i]-Close[i+1];
if(rel>0) sump=rel;
else sumn=-rel;
positive=(PosBuffer[i+1]*(RSIPeriod-1)+sump)/RSIPeriod;
negative=(NegBuffer[i+1]*(RSIPeriod-1)+sumn)/RSIPeriod;
}
PosBuffer[i]=positive;
NegBuffer[i]=negative;
if(negative==0.0) RSIBuffer[i]=0.0;
else RSIBuffer[i]=100.0-100.0/(1+positive/negative);
i--;
}
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Stochastic.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_separate_window
#property indicator_minimum 0
#property indicator_maximum 100
#property indicator_buffers 2
#property indicator_color1 LightSeaGreen
#property indicator_color2 Red
//---- input parameters
extern int KPeriod=5;
extern int DPeriod=3;
extern int Slowing=3;
//---- buffers
double MainBuffer[];
double SignalBuffer[];
double HighesBuffer[];
double LowesBuffer[];
//----
int draw_begin1=0;
int draw_begin2=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
string short_name;
//---- 2 additional buffers are used for counting.
IndicatorBuffers(4);
SetIndexBuffer(2, HighesBuffer);
SetIndexBuffer(3, LowesBuffer);
//---- indicator lines
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0, MainBuffer);
SetIndexStyle(1,DRAW_LINE);
SetIndexBuffer(1, SignalBuffer);
//---- name for DataWindow and indicator subwindow label
short_name="Sto("+KPeriod+","+DPeriod+","+Slowing+")";
IndicatorShortName(short_name);
SetIndexLabel(0,short_name);
SetIndexLabel(1,"Signal");
//----
draw_begin1=KPeriod+Slowing;
draw_begin2=draw_begin1+DPeriod;
SetIndexDrawBegin(0,draw_begin1);
SetIndexDrawBegin(1,draw_begin2);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Stochastic oscillator |
//+------------------------------------------------------------------+
int start()
{
int i,k;
int counted_bars=IndicatorCounted();
double price;
//----
if(Bars<=draw_begin2) return(0);
//---- initial zero
if(counted_bars<1)
{
for(i=1;i<=draw_begin1;i++) MainBuffer[Bars-i]=0;
for(i=1;i<=draw_begin2;i++) SignalBuffer[Bars-i]=0;
}
//---- minimums counting
i=Bars-KPeriod;
if(counted_bars>KPeriod) i=Bars-counted_bars-1;
while(i>=0)
{
double min=1000000;
k=i+KPeriod-1;
while(k>=i)
{
price=Low[k];
if(min>price) min=price;
k--;
}
LowesBuffer[i]=min;
i--;
}
//---- maximums counting
i=Bars-KPeriod;
if(counted_bars>KPeriod) i=Bars-counted_bars-1;
while(i>=0)
{
double max=-1000000;
k=i+KPeriod-1;
while(k>=i)
{
price=High[k];
if(max<price) max=price;
k--;
}
HighesBuffer[i]=max;
i--;
}
//---- %K line
i=Bars-draw_begin1;
if(counted_bars>draw_begin1) i=Bars-counted_bars-1;
while(i>=0)
{
double sumlow=0.0;
double sumhigh=0.0;
for(k=(i+Slowing-1);k>=i;k--)
{
sumlow+=Close[k]-LowesBuffer[k];
sumhigh+=HighesBuffer[k]-LowesBuffer[k];
}
if(sumhigh==0.0) MainBuffer[i]=100.0;
else MainBuffer[i]=sumlow/sumhigh*100;
i--;
}
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
int limit=Bars-counted_bars;
//---- signal line is simple movimg average
for(i=0; i<limit; i++)
SignalBuffer[i]=iMAOnArray(MainBuffer,Bars,DPeriod,0,MODE_SMA,i);
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Custom Moving Average.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_chart_window
#property indicator_buffers 1
#property indicator_color1 Red
//---- indicator parameters
extern int ExtDepth=12;
extern int ExtDeviation=5;
extern int ExtBackstep=3;
//---- indicator buffers
double ExtMapBuffer[];
double ExtMapBuffer2[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
IndicatorBuffers(2);
//---- drawing settings
SetIndexStyle(0,DRAW_SECTION);
//---- indicator buffers mapping
SetIndexBuffer(0,ExtMapBuffer);
SetIndexBuffer(1,ExtMapBuffer2);
SetIndexEmptyValue(0,0.0);
ArraySetAsSeries(ExtMapBuffer,true);
ArraySetAsSeries(ExtMapBuffer2,true);
//---- indicator short name
IndicatorShortName("ZigZag("+ExtDepth+","+ExtDeviation+","+ExtBackstep+")");
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int start()
{
int shift, back,lasthighpos,lastlowpos;
double val,res;
double curlow,curhigh,lasthigh,lastlow;

for(shift=Bars-ExtDepth; shift>=0; shift--)


{
val=Low[Lowest(NULL,0,MODE_LOW,ExtDepth,shift)];
if(val==lastlow) val=0.0;
else
{
lastlow=val;
if((Low[shift]-val)>(ExtDeviation*Point)) val=0.0;
else
{
for(back=1; back<=ExtBackstep; back++)
{
res=ExtMapBuffer[shift+back];
if((res!=0)&&(res>val)) ExtMapBuffer[shift+back]=0.0;
}
}
}
ExtMapBuffer[shift]=val;
//--- high
val=High[Highest(NULL,0,MODE_HIGH,ExtDepth,shift)];
if(val==lasthigh) val=0.0;
else
{
lasthigh=val;
if((val-High[shift])>(ExtDeviation*Point)) val=0.0;
else
{
for(back=1; back<=ExtBackstep; back++)
{
res=ExtMapBuffer2[shift+back];
if((res!=0)&&(res<val)) ExtMapBuffer2[shift+back]=0.0;
}
}
}
ExtMapBuffer2[shift]=val;
}

// final cutting
lasthigh=-1; lasthighpos=-1;
lastlow=-1; lastlowpos=-1;

for(shift=Bars-ExtDepth; shift>=0; shift--)


{
curlow=ExtMapBuffer[shift];
curhigh=ExtMapBuffer2[shift];
if((curlow==0)&&(curhigh==0)) continue;
//---
if(curhigh!=0)
{
if(lasthigh>0)
{
if(lasthigh<curhigh) ExtMapBuffer2[lasthighpos]=0;
else ExtMapBuffer2[shift]=0;
}
//---
if(lasthigh<curhigh || lasthigh<0)
{
lasthigh=curhigh;
lasthighpos=shift;
}
lastlow=-1;
}
//----
if(curlow!=0)
{
if(lastlow>0)
{
if(lastlow>curlow) ExtMapBuffer[lastlowpos]=0;
else ExtMapBuffer[shift]=0;
}
//---
if((curlow<lastlow)||(lastlow<0))
{
lastlow=curlow;
lastlowpos=shift;
}
lasthigh=-1;
}
}

for(shift=Bars-1; shift>=0; shift--)


{
if(shift>=Bars-ExtDepth) ExtMapBuffer[shift]=0.0;
else
{
res=ExtMapBuffer2[shift];
if(res!=0.0) ExtMapBuffer[shift]=res;
}
}
}

//+------------------------------------------------------------------+
//| Accelerator.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
//---- indicator settings
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1 Black
#property indicator_color2 Green
#property indicator_color3 Red
//---- indicator buffers
double ExtBuffer0[];
double ExtBuffer1[];
double ExtBuffer2[];
double ExtBuffer3[];
double ExtBuffer4[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- 2 additional buffers are used for counting.
IndicatorBuffers(5);
//---- drawing settings
SetIndexStyle(0,DRAW_NONE);
SetIndexStyle(1,DRAW_HISTOGRAM);
SetIndexStyle(2,DRAW_HISTOGRAM);
IndicatorDigits(Digits+2);
SetIndexDrawBegin(0,38);
SetIndexDrawBegin(1,38);
SetIndexDrawBegin(2,38);
//---- 4 indicator buffers mapping
SetIndexBuffer(0,ExtBuffer0);
SetIndexBuffer(1,ExtBuffer1);
SetIndexBuffer(2,ExtBuffer2);
SetIndexBuffer(3,ExtBuffer3);
SetIndexBuffer(4,ExtBuffer4);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("AC");
SetIndexLabel(1,NULL);
SetIndexLabel(2,NULL);
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Accelerator/Decelerator Oscillator |
//+------------------------------------------------------------------+
int start()
{
int limit;
int counted_bars=IndicatorCounted();
double prev,current;
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- macd counted in the 1-st additional buffer
for(int i=0; i<limit; i++)
ExtBuffer3[i]=iMA(NULL,0,5,0,MODE_SMA,PRICE_MEDIAN,i)-
iMA(NULL,0,34,0,MODE_SMA,PRICE_MEDIAN,i);
//---- signal line counted in the 2-nd additional buffer
for(i=0; i<limit; i++)
ExtBuffer4[i]=iMAOnArray(ExtBuffer3,Bars,5,0,MODE_SMA,i);
//---- dispatch values between 2 buffers
bool up=true;
for(i=limit-1; i>=0; i--)
{
current=ExtBuffer3[i]-ExtBuffer4[i];
prev=ExtBuffer3[i+1]-ExtBuffer4[i+1];
if(current>prev) up=true;
if(current<prev) up=false;
if(!up)
{
ExtBuffer2[i]=current;
ExtBuffer1[i]=0.0;
}
else
{
ExtBuffer1[i]=current;
ExtBuffer2[i]=0.0;
}
ExtBuffer0[i]=current;
}
//---- done
return(0);
}

//+------------------------------------------------------------------+
//| ADX.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1 LightSeaGreen
#property indicator_color2 YellowGreen
#property indicator_color3 Wheat
//---- input parameters
extern int ADXPeriod=14;
//---- buffers
double ADXBuffer[];
double PlusDiBuffer[];
double MinusDiBuffer[];
double PlusSdiBuffer[];
double MinusSdiBuffer[];
double TempBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- 3 additional buffers are used for counting.
IndicatorBuffers(6);
//---- indicator buffers
SetIndexBuffer(0,ADXBuffer);
SetIndexBuffer(1,PlusDiBuffer);
SetIndexBuffer(2,MinusDiBuffer);
SetIndexBuffer(3,PlusSdiBuffer);
SetIndexBuffer(4,MinusSdiBuffer);
SetIndexBuffer(5,TempBuffer);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("ADX("+ADXPeriod+")");
SetIndexLabel(0,"ADX");
SetIndexLabel(1,"+DI");
SetIndexLabel(2,"-DI");
//----
SetIndexDrawBegin(0,ADXPeriod);
SetIndexDrawBegin(1,ADXPeriod);
SetIndexDrawBegin(2,ADXPeriod);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Average Directional Movement Index |
//+------------------------------------------------------------------+
int start()
{
double pdm,mdm,tr;
double price_high,price_low;
int starti,i,counted_bars=IndicatorCounted();
//----
i=Bars-2;
PlusSdiBuffer[i+1]=0;
MinusSdiBuffer[i+1]=0;
if(counted_bars>=i) i=Bars-counted_bars-1;
starti=i;
//----
while(i>=0)
{
price_low=Low[i];
price_high=High[i];
//----
pdm=price_high-High[i+1];
mdm=Low[i+1]-price_low;
if(pdm<0) pdm=0; // +DM
if(mdm<0) mdm=0; // -DM
if(pdm==mdm) { pdm=0; mdm=0; }
else if(pdm<mdm) pdm=0;
else if(mdm<pdm) mdm=0;
//---- âû÷èñëÿåì èñòèííûé èíòåðâàë
double num1=MathAbs(price_high-price_low);
double num2=MathAbs(price_high-Close[i+1]);
double num3=MathAbs(price_low-Close[i+1]);
tr=MathMax(num1,num2);
tr=MathMax(tr,num3);
//---- counting plus/minus direction
if(tr==0) { PlusSdiBuffer[i]=0; MinusSdiBuffer[i]=0; }
else { PlusSdiBuffer[i]=100.0*pdm/tr; MinusSdiBuffer[i]=100.0*mdm/tr; }
//----
i--;
}
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
int limit=Bars-counted_bars;
//---- apply EMA to +DI
for(i=0; i<=limit; i++)
PlusDiBuffer[i]=iMAOnArray(PlusSdiBuffer,Bars,ADXPeriod,0,MODE_EMA,i);
//---- apply EMA to -DI
for(i=0; i<=limit; i++)
MinusDiBuffer[i]=iMAOnArray(MinusSdiBuffer,Bars,ADXPeriod,0,MODE_EMA,i);
//---- Directional Movement (DX)
i=Bars-2;
TempBuffer[i+1]=0;
i=starti;
while(i>=0)
{
double div=MathAbs(PlusDiBuffer[i]+MinusDiBuffer[i]);
if(div==0.00) TempBuffer[i]=0;
else TempBuffer[i]=100*(MathAbs(PlusDiBuffer[i]-MinusDiBuffer[i])/div);
i--;
}
//---- ADX is exponential moving average on DX
for(i=0; i<limit; i++)
ADXBuffer[i]=iMAOnArray(TempBuffer,Bars,ADXPeriod,0,MODE_EMA,i);
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Alligator.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1 Blue
#property indicator_color2 Red
#property indicator_color3 Lime
//---- input parameters
extern int JawsPeriod=13;
extern int JawsShift=8;
extern int TeethPeriod=8;
extern int TeethShift=5;
extern int LipsPeriod=5;
extern int LipsShift=3;
//---- indicator buffers
double ExtBlueBuffer[];
double ExtRedBuffer[];
double ExtLimeBuffer[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- line shifts when drawing
SetIndexShift(0,JawsShift);
SetIndexShift(1,TeethShift);
SetIndexShift(2,LipsShift);
//---- first positions skipped when drawing
SetIndexDrawBegin(0,JawsShift+JawsPeriod);
SetIndexDrawBegin(1,TeethShift+TeethPeriod);
SetIndexDrawBegin(2,LipsShift+LipsPeriod);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ExtBlueBuffer);
SetIndexBuffer(1,ExtRedBuffer);
SetIndexBuffer(2,ExtLimeBuffer);
//---- drawing settings
SetIndexStyle(0,DRAW_LINE);
SetIndexStyle(1,DRAW_LINE);
SetIndexStyle(2,DRAW_LINE);
//---- index labels
SetIndexLabel(0,"Gator Jaws");
SetIndexLabel(1,"Gator Teeth");
SetIndexLabel(2,"Gator Lips");
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Bill Williams' Alligator |
//+------------------------------------------------------------------+
int start()
{
int limit;
int counted_bars=IndicatorCounted();
//---- check for possible errors
if(counted_bars<0) return(-1);
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- main loop
for(int i=0; i<limit; i++)
{
//---- ma_shift set to 0 because SetIndexShift called abowe
ExtBlueBuffer[i]=iMA(NULL,0,JawsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtRedBuffer[i]=iMA(NULL,0,TeethPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
ExtLimeBuffer[i]=iMA(NULL,0,LipsPeriod,0,MODE_SMMA,PRICE_MEDIAN,i);
}
//---- done
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Awesome.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
//---- indicator settings
#property indicator_separate_window
#property indicator_buffers 3
#property indicator_color1 Black
#property indicator_color2 Green
#property indicator_color3 Red

//---- indicator buffers


double ExtBuffer0[];
double ExtBuffer1[];
double ExtBuffer2[];

//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- drawing settings
SetIndexStyle(0,DRAW_NONE);
SetIndexStyle(1,DRAW_HISTOGRAM);
SetIndexStyle(2,DRAW_HISTOGRAM);
IndicatorDigits(Digits+1);
SetIndexDrawBegin(0,34);
SetIndexDrawBegin(1,34);
SetIndexDrawBegin(2,34);
//---- 3 indicator buffers mapping
SetIndexBuffer(0,ExtBuffer0);
SetIndexBuffer(1,ExtBuffer1);
SetIndexBuffer(2,ExtBuffer2);
//---- name for DataWindow and indicator subwindow label
IndicatorShortName("AO");
SetIndexLabel(1,NULL);
SetIndexLabel(2,NULL);
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Awesome Oscillator |
//+------------------------------------------------------------------+
int start()
{
int limit;
int counted_bars=IndicatorCounted();
double prev,current;
//---- last counted bar will be recounted
if(counted_bars>0) counted_bars--;
limit=Bars-counted_bars;
//---- macd
for(int i=0; i<limit; i++)
ExtBuffer0[i]=iMA(NULL,0,5,0,MODE_SMA,PRICE_MEDIAN,i)-
iMA(NULL,0,34,0,MODE_SMA,PRICE_MEDIAN,i);
//---- dispatch values between 2 buffers
bool up=true;
for(i=limit-1; i>=0; i--)
{
current=ExtBuffer0[i];
prev=ExtBuffer0[i+1];
if(current>prev) up=true;
if(current<prev) up=false;
if(!up)
{
ExtBuffer2[i]=current;
ExtBuffer1[i]=0.0;
}
else
{
ExtBuffer1[i]=current;
ExtBuffer2[i]=0.0;
}
}
//---- done
return(0);
}

Samples Includes
#import "ExpertSample.dll"
int GetIntValue(int);
double GetDoubleValue(double);
string GetStringValue(string);
double GetArrayItemValue(double arr[],int,int);
bool SetArrayItemValue(double& arr[],int,int,double);
double GetRatesItemValue(double rates[][6],int,int,int);
int SortStringArray(string& arr[],int);
int ProcessStringArray(string& arr[],int);

Samples Indicators
//+------------------------------------------------------------------+
//| ATR.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 DodgerBlue
//---- input parameters
extern int AtrPeriod=14;
//---- buffers
double AtrBuffer[];
double TempBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
string short_name;
//---- 1 additional buffer used for counting.
IndicatorBuffers(2);
//---- indicator line
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,AtrBuffer);
SetIndexBuffer(1,TempBuffer);
//---- name for DataWindow and indicator subwindow label
short_name="ATR("+AtrPeriod+")";
IndicatorShortName(short_name);
SetIndexLabel(0,short_name);
//----
SetIndexDrawBegin(0,AtrPeriod);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Average True Range |
//+------------------------------------------------------------------+
int start()
{
int i,counted_bars=IndicatorCounted();
//----
if(Bars<=AtrPeriod) return(0);
//---- initial zero
if(counted_bars<1)
for(i=1;i<=AtrPeriod;i++) AtrBuffer[Bars-i]=0.0;
//----
i=Bars-counted_bars-1;
while(i>=0)
{
double high=High[i];
double low =Low[i];
if(i==Bars-1) TempBuffer[i]=high-low;
else
{
double prevclose=Close[i+1];
TempBuffer[i]=MathMax(high,prevclose)-MathMin(low,prevclose);
}
i--;
}
//----
if(counted_bars>0) counted_bars--;
int limit=Bars-counted_bars;
for(i=0; i<limit; i++)
AtrBuffer[i]=iMAOnArray(TempBuffer,Bars,AtrPeriod,0,MODE_SMA,i);
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Bands.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_chart_window
#property indicator_buffers 3
#property indicator_color1 LightSeaGreen
#property indicator_color2 LightSeaGreen
#property indicator_color3 LightSeaGreen
//---- indicator parameters
extern int BandsPeriod=20;
extern int BandsShift=0;
extern double BandsDeviations=2.0;
//---- buffers
double MovingBuffer[];
double UpperBuffer[];
double LowerBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
//---- indicators
SetIndexStyle(0,DRAW_LINE);
SetIndexBuffer(0,MovingBuffer);
SetIndexStyle(1,DRAW_LINE);
SetIndexBuffer(1,UpperBuffer);
SetIndexStyle(2,DRAW_LINE);
SetIndexBuffer(2,LowerBuffer);
//----
SetIndexDrawBegin(0,BandsPeriod+BandsShift);
SetIndexDrawBegin(1,BandsPeriod+BandsShift);
SetIndexDrawBegin(2,BandsPeriod+BandsShift);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Bollinger Bands |
//+------------------------------------------------------------------+
int start()
{
int i,k,counted_bars=IndicatorCounted();
double deviation;
double sum,oldval,newres;
//----
if(Bars<=BandsPeriod) return(0);
//---- initial zero
if(counted_bars<1)
for(i=1;i<=BandsPeriod;i++)
{
MovingBuffer[Bars-i]=EMPTY_VALUE;
UpperBuffer[Bars-i]=EMPTY_VALUE;
LowerBuffer[Bars-i]=EMPTY_VALUE;
}
//----
int limit=Bars-counted_bars;
if(counted_bars>0) limit++;
for(i=0; i<limit; i++)
MovingBuffer[i]=iMA(NULL,0,BandsPeriod,BandsShift,MODE_SMA,PRICE_CLOSE,i);
//----
i=Bars-BandsPeriod+1;
if(counted_bars>BandsPeriod-1) i=Bars-counted_bars-1;
while(i>=0)
{
sum=0.0;
k=i+BandsPeriod-1;
oldval=MovingBuffer[i];
while(k>=i)
{
newres=Close[k]-oldval;
sum+=newres*newres;
k--;
}
deviation=BandsDeviations*MathSqrt(sum/BandsPeriod);;
UpperBuffer[i]=oldval+deviation;
LowerBuffer[i]=oldval-deviation;
i--;
}
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Bears.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//---- input parameters
extern int BearsPeriod=13;
//---- buffers
double BearsBuffer[];
double TempBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
string short_name;
//---- 1 additional buffer used for counting.
IndicatorBuffers(2);
IndicatorDigits(Digits);
//---- indicator line
SetIndexStyle(0,DRAW_HISTOGRAM);
SetIndexBuffer(0,BearsBuffer);
SetIndexBuffer(1,TempBuffer);
//---- name for DataWindow and indicator subwindow label
short_name="Bears("+BearsPeriod+")";
IndicatorShortName(short_name);
SetIndexLabel(0,short_name);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Bears Power |
//+------------------------------------------------------------------+
int start()
{
int i,counted_bars=IndicatorCounted();
//----
if(Bars<=BearsPeriod) return(0);
//----
int limit=Bars-counted_bars;
if(counted_bars>0) limit++;
for(i=0; i<limit; i++)
TempBuffer[i]=iMA(NULL,0,BearsPeriod,0,MODE_EMA,PRICE_CLOSE,i);
//----
i=Bars-counted_bars-1;
while(i>=0)
{
BearsBuffer[i]=Low[i]-TempBuffer[i];
i--;
}
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Bulls.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#property indicator_separate_window
#property indicator_buffers 1
#property indicator_color1 Silver
//---- input parameters
extern int BullsPeriod=13;
//---- buffers
double BullsBuffer[];
double TempBuffer[];
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int init()
{
string short_name;
//---- 1 additional buffer used for counting.
IndicatorBuffers(2);
IndicatorDigits(Digits);
//---- indicator line
SetIndexStyle(0,DRAW_HISTOGRAM);
SetIndexBuffer(0,BullsBuffer);
SetIndexBuffer(1,TempBuffer);
//---- name for DataWindow and indicator subwindow label
short_name="Bulls("+BullsPeriod+")";
IndicatorShortName(short_name);
SetIndexLabel(0,short_name);
//----
return(0);
}
//+------------------------------------------------------------------+
//| Bulls Power |
//+------------------------------------------------------------------+
int start()
{
int i,counted_bars=IndicatorCounted();
//----
if(Bars<=BullsPeriod) return(0);
//----
int limit=Bars-counted_bars;
if(counted_bars>0) limit++;
for(i=0; i<limit; i++)
TempBuffer[i]=iMA(NULL,0,BullsPeriod,0,MODE_EMA,PRICE_CLOSE,i);
//----
i=Bars-counted_bars-1;
while(i>=0)
{
BullsBuffer[i]=High[i]-TempBuffer[i];
i--;
}
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| Heiken Ashi.mq4 |
//| Copyright c 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net |
//+------------------------------------------------------------------+
//| For Heiken Ashi we recommend next chart settings ( press F8 or |
//| select on menu 'Charts'->'Properties...'): |
//| - On 'Color' Tab select 'Black' for 'Line Graph' |
//| - On 'Common' Tab disable 'Chart on Foreground' checkbox and |
//| select 'Line Chart' radiobutton |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net"

#property indicator_chart_window
#property indicator_buffers 4
#property indicator_color1 Red
#property indicator_color2 White
#property indicator_color3 Red
#property indicator_color4 White
//---- buffers
double ExtMapBuffer1[];
double ExtMapBuffer2[];
double ExtMapBuffer3[];
double ExtMapBuffer4[];
//----
int ExtCountedBars=0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//|------------------------------------------------------------------|
int init()
{
//---- indicators
SetIndexStyle(0,DRAW_HISTOGRAM, 0, 1, Red);
SetIndexBuffer(0, ExtMapBuffer1);
SetIndexStyle(1,DRAW_HISTOGRAM, 0, 1, White);
SetIndexBuffer(1, ExtMapBuffer2);
SetIndexStyle(2,DRAW_HISTOGRAM, 0, 3, Red);
SetIndexBuffer(2, ExtMapBuffer3);
SetIndexStyle(3,DRAW_HISTOGRAM, 0, 3, White);
SetIndexBuffer(3, ExtMapBuffer4);
//----
SetIndexDrawBegin(0,10);
SetIndexDrawBegin(1,10);
SetIndexDrawBegin(2,10);
SetIndexDrawBegin(3,10);
//---- indicator buffers mapping
SetIndexBuffer(0,ExtMapBuffer1);
SetIndexBuffer(1,ExtMapBuffer2);
SetIndexBuffer(2,ExtMapBuffer3);
SetIndexBuffer(3,ExtMapBuffer4);
//---- initialization done
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//---- TODO: add your code here
//----
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int start()
{
double haOpen, haHigh, haLow, haClose;
if(Bars<=10) return(0);
ExtCountedBars=IndicatorCounted();
//---- check for possible errors
if (ExtCountedBars<0) return(-1);
//---- last counted bar will be recounted
if (ExtCountedBars>0) ExtCountedBars--;
int pos=Bars-ExtCountedBars-1;
while(pos>=0)
{
haOpen=(ExtMapBuffer3[pos+1]+ExtMapBuffer4[pos+1])/2;
haClose=(Open[pos]+High[pos]+Low[pos]+Close[pos])/4;
haHigh=MathMax(High[pos], MathMax(haOpen, haClose));
haLow=MathMin(Low[pos], MathMin(haOpen, haClose));
if (haOpen<haClose)
{
ExtMapBuffer1[pos]=haLow;
ExtMapBuffer2[pos]=haHigh;
}
else
{
ExtMapBuffer1[pos]=haHigh;
ExtMapBuffer2[pos]=haLow;
}
ExtMapBuffer3[pos]=haOpen;
ExtMapBuffer4[pos]=haClose;
pos--;
}
//----
return(0);
}
//+------------------------------------------------------------------+

Samples Scripts
//+------------------------------------------------------------------+
//| close.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
#property show_confirm

//+------------------------------------------------------------------+
//| script "close first market order if it is first in the list" |
//+------------------------------------------------------------------+
int start()
{
bool result;
double price;
int cmd,error;
//----
if(OrderSelect(0,SELECT_BY_POS,MODE_TRADES))
{
cmd=OrderType();
//---- first order is buy or sell
if(cmd==OP_BUY || cmd==OP_SELL)
{
while(true)
{
if(cmd==OP_BUY) price=Bid;
else price=Ask;
result=OrderClose(OrderTicket(),OrderLots(),price,3,CLR_NONE);
if(result!=TRUE) { error=GetLastError(); Print("LastError = ",error); }
else error=0;
if(error==135) RefreshRates();
else break;
}
}
}
else Print( "Error when order select ", GetLastError());
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| delete_pending.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
#property show_confirm

//+------------------------------------------------------------------+
//| script "delete first pending order" |
//+------------------------------------------------------------------+
int start()
{
bool result;
int cmd,total;
//----
total=OrdersTotal();
//----
for(int i=0; i<total; i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
cmd=OrderType();
//---- pending orders only are considered
if(cmd!=OP_BUY && cmd!=OP_SELL)
{
//---- print selected order
OrderPrint();
//---- delete first pending order
result=OrderDelete(OrderTicket());
if(result!=TRUE) Print("LastError = ", GetLastError());
break;
}
}
else { Print( "Error when order select ", GetLastError()); break; }
}
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| modify.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
#property show_confirm

//+------------------------------------------------------------------+
//| script "modify first market order" |
//+------------------------------------------------------------------+
int start()
{
bool result;
double stop_loss,point;
int cmd,total;
//----
total=OrdersTotal();
point=MarketInfo(Symbol(),MODE_POINT);
//----
for(int i=0; i<total; i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
//---- print selected order
OrderPrint();
cmd=OrderType();
//---- buy or sell orders are considered
if(cmd==OP_BUY || cmd==OP_SELL)
{
//---- modify first market order
while(true)
{
if(cmd==OP_BUY) stop_loss=Bid-20*point;
else stop_loss=Ask+20*point;
result=OrderModify(OrderTicket(),0,stop_loss,0,0,CLR_NONE);
if(result!=TRUE) Print("LastError = ", GetLastError());
if(result==135) RefreshRates();
else break;
}
//---- print modified order (it still selected after modify)
OrderPrint();
break;
}
}
else { Print( "Error when order select ", GetLastError()); break; }
}
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| modify_pending.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
#property show_confirm

//+------------------------------------------------------------------+
//| script "modify first pending order" |
//+------------------------------------------------------------------+
int start()
{
bool result;
double price,point;
int cmd,total;
int expiration;
//----
total=OrdersTotal();
point=MarketInfo(Symbol(),MODE_POINT);
//----
for(int i=0; i<total; i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES))
{
cmd=OrderType();
//---- pending orders only are considered
if(cmd!=OP_BUY && cmd!=OP_SELL)
{
//---- print selected order
OrderPrint();
//---- modify first pending order
price=OrderOpenPrice()-10*point;
expiration=OrderExpiration();
result=OrderModify(OrderTicket(),price,0,0,expiration,CLR_NONE);
if(result!=TRUE) Print("LastError = ", GetLastError());
//---- print modified order (it still selected after modify)
else OrderPrint();
break;
}
}
else { Print( "Error when order select ", GetLastError()); break; }
}
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| rotate_text.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
#include <stdlib.mqh>

string line_name="rotating_line";
string object_name1="rotating_text";

void init()
{
Print("point = ", Point," bars=",Bars);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void deinit()
{
ObjectDelete(line_name);
ObjectDelete(object_name1);
ObjectsRedraw();
}
//+------------------------------------------------------------------+
//| script program start function |
//+------------------------------------------------------------------+
int start()
{
int time2;
int error,index,fontsize=10;
double price,price1,price2;
double angle=0.0;
//----
price2=High[10]+Point*10;
ObjectCreate(line_name, OBJ_TRENDBYANGLE, 0, Time[10], price2);
index=20;
ObjectCreate(object_name1, OBJ_TEXT, 0, Time[index], Low[index]-Point*100);
ObjectSetText(object_name1, "rotating_text", fontsize);
while(IsStopped()==false)
{
index++;
price=ObjectGet(object_name1, OBJPROP_PRICE1)+Point;
error=GetLastError();
if(error!=0)
{
Print(object_name1," : ",ErrorDescription(error));
break;
}
ObjectMove(object_name1, 0, Time[index], price);
ObjectSet(object_name1, OBJPROP_ANGLE, angle*2);
ObjectSet(object_name1, OBJPROP_FONTSIZE, fontsize);
ObjectSet(line_name, OBJPROP_WIDTH, angle/18.0);
double line_angle=360.0-angle;
if(line_angle==90.0) ObjectSet(line_name, OBJPROP_PRICE2, price2+Point*50);
if(line_angle==270.0) ObjectSet(line_name, OBJPROP_PRICE2, price2-Point*50);
time2=ObjectGet(line_name,OBJPROP_TIME2);
if(line_angle>90.0 && line_angle<270.0) time2=Time[index+10];
else time2=Time[0];
ObjectSet(line_name, OBJPROP_TIME2, time2);
ObjectSet(line_name, OBJPROP_ANGLE, line_angle);
ObjectsRedraw();
angle+=3.0;
if(angle>=360.0) angle=360.0-angle;
fontsize++;
if(fontsize>48) fontsize=6;
Sleep(500);
price1=ObjectGetValueByShift(line_name, index);
if(GetLastError()==0)
{
if(MathAbs(price1-price) < Point*50)
{
Print("price=",price," price1=", price1);
ObjectSetText(object_name1, "REMOVED", 48, "Arial", RGB(255,215,0));
ObjectsRedraw();
Sleep(5000);
// ObjectDelete(object_name1);
}
}
}
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| send_pending.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
#property show_confirm

//+------------------------------------------------------------------+
//| script "send pending order with expiration data" |
//+------------------------------------------------------------------+
int start()
{
int ticket,expiration;
double point;
//----
point=MarketInfo(Symbol(),MODE_POINT);
expiration=CurTime()+PERIOD_D1*60;
//----
while(true)
{
ticket=OrderSend(Symbol(),OP_SELLSTOP,1.0,Bid-100*point,0,0,0,"some
comment",16384,expiration,Green);
if(ticket<=0) Print("Error = ",GetLastError());
else { Print("ticket = ",ticket); break; }
//---- 10 seconds wait
Sleep(10000);
}
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| trade.mq4 |
//| Copyright © 2004, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2004, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"

#include <stdlib.mqh>
#include <WinUser32.mqh>
//+------------------------------------------------------------------+
//| script "trading for all money" |
//+------------------------------------------------------------------+
int start()
{
//----
if(MessageBox("Do you really want to BUY 1.00 "+Symbol()+" at ASK price? ",
"Script",MB_YESNO|MB_ICONQUESTION)!=IDYES) return(1);
//----
int ticket=OrderSend(Symbol(),OP_BUY,1.0,Ask,3,0,0,"expert comment",255,0,CLR_NONE);
if(ticket<1)
{
int error=GetLastError();
Print("Error = ",ErrorDescription(error));
return;
}
//----
OrderPrint();
return(0);
}
//+------------------------------------------------------------------+

Samples Program
//+------------------------------------------------------------------+
//| ExportFunctions.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#property copyright "Copyright © 2005, MetaQuotes Software Corp."
#property link "http://www.metaquotes.net/"
#include <sampledll.mqh>

#define TIME_INDEX 0
#define OPEN_INDEX 1
#define LOW_INDEX 2
#define HIGH_INDEX 3
#define CLOSE_INDEX 4
#define VOLUME_INDEX 5
//+------------------------------------------------------------------+
//| expert initialization function |
//+------------------------------------------------------------------+
int init()
{
double ret,some_value=10.5;
string sret;
int cnt;
string strarray[6]={ "first", "second", "third", "fourth", "fifth" };
//---- simple dll-functions call
cnt=GetIntValue(some_value);
Print("Returned value is ",cnt);
ret=GetDoubleValue(some_value);
Print("Returned value is ",ret);
sret=GetStringValue("some string");
Print("Returned value is ",sret);
//----
cnt=SortStringArray(strarray,ArraySize(strarray));
for(int i=0; i<cnt; i++) Print(i," - ",strarray[i]);
cnt=ProcessStringArray(strarray,ArraySize(strarray));
for(i=0; i<cnt; i++) Print(i," - ",strarray[i]);
//----
return(0);
}
//+------------------------------------------------------------------+
//| array functions call |
//+------------------------------------------------------------------+
int start()
{
double price;
double arr[5]={1.5, 2.6, 3.7, 4.8, 5.9 };
double rates[][6];
//---- get first item from passed array
price=GetArrayItemValue(arr,5,0);
Print("Returned from arr[0] ",price);
//---- change second item in the passed array
if(SetArrayItemValue(arr,5,1,1234.5)==true)
Print("Changed to ",arr[1]);
//---- get current close
ArrayCopyRates(rates);
price=GetRatesItemValue(rates,Bars,0,CLOSE_INDEX);
Print("Returned from Close ",price);
//----
return(0);
}
//+------------------------------------------------------------------+

//+------------------------------------------------------------------+
//| MACD Sample.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+

extern double TakeProfit = 50;


extern double Lots = 0.1;
extern double TrailingStop = 30;
extern double MACDOpenLevel=3;
extern double MACDCloseLevel=2;
extern double MATrendPeriod=26;

//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
int start()
{
double MacdCurrent, MacdPrevious, SignalCurrent;
double SignalPrevious, MaCurrent, MaPrevious;
int cnt, ticket, total;
// initial data checks
// it is important to make sure that the expert works with a normal
// chart and the user did not make any mistakes setting external
// variables (Lots, StopLoss, TakeProfit,
// TrailingStop) in our case, we check TakeProfit
// on a chart of less than 100 bars
if(Bars<100)
{
Print("bars less than 100");
return(0);
}
if(TakeProfit<10)
{
Print("TakeProfit less than 10");
return(0); // check TakeProfit
}
// to simplify the coding and speed up access
// data are put into internal variables
MacdCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,0);
MacdPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_MAIN,1);
SignalCurrent=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,0);
SignalPrevious=iMACD(NULL,0,12,26,9,PRICE_CLOSE,MODE_SIGNAL,1);
MaCurrent=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,0);
MaPrevious=iMA(NULL,0,MATrendPeriod,0,MODE_EMA,PRICE_CLOSE,1);

total=OrdersTotal();
if(total<1)
{
// no opened orders identified
if(AccountFreeMargin()<(1000*Lots))
{
Print("We have no money. Free Margin = ", AccountFreeMargin());
return(0);
}
// check for long position (BUY) possibility
if(MacdCurrent<0 && MacdCurrent>SignalCurrent && MacdPrevious<SignalPrevious &&
MathAbs(MacdCurrent)>(MACDOpenLevel*Point) && MaCurrent>MaPrevious)
{
ticket=OrderSend(Symbol(),OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,"macd
sample",16384,0,Green);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("BUY order
opened : ",OrderOpenPrice());
}
else Print("Error opening BUY order : ",GetLastError());
return(0);
}
// check for short position (SELL) possibility
if(MacdCurrent>0 && MacdCurrent<SignalCurrent && MacdPrevious>SignalPrevious &&
MacdCurrent>(MACDOpenLevel*Point) && MaCurrent<MaPrevious)
{
ticket=OrderSend(Symbol(),OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,"macd
sample",16384,0,Red);
if(ticket>0)
{
if(OrderSelect(ticket,SELECT_BY_TICKET,MODE_TRADES)) Print("SELL order
opened : ",OrderOpenPrice());
}
else Print("Error opening SELL order : ",GetLastError());
return(0);
}
return(0);
}
// it is important to enter the market correctly,
// but it is more important to exit it correctly...
for(cnt=0;cnt<total;cnt++)
{
OrderSelect(cnt, SELECT_BY_POS, MODE_TRADES);
if(OrderType()<=OP_SELL && // check for opened position
OrderSymbol()==Symbol()) // check for symbol
{
if(OrderType()==OP_BUY) // long position is opened
{
// should it be closed?
if(MacdCurrent>0 && MacdCurrent<SignalCurrent &&
MacdPrevious>SignalPrevious &&
MacdCurrent>(MACDCloseLevel*Point))
{
OrderClose(OrderTicket(),OrderLots(),Bid,3,Violet); // close position
return(0); // exit
}
// check for trailing stop
if(TrailingStop>0)
{
if(Bid-OrderOpenPrice()>Point*TrailingStop)
{
if(OrderStopLoss()<Bid-Point*TrailingStop)
{
OrderModify(OrderTicket(),OrderOpenPrice(),Bid-
Point*TrailingStop,OrderTakeProfit(),0,Green);
return(0);
}
}
}
}
else // go to short position
{
// should it be closed?
if(MacdCurrent<0 && MacdCurrent>SignalCurrent &&
MacdPrevious<SignalPrevious &&
MathAbs(MacdCurrent)>(MACDCloseLevel*Point))
{
OrderClose(OrderTicket(),OrderLots(),Ask,3,Violet); // close position
return(0); // exit
}
// check for trailing stop
if(TrailingStop>0)
{
if((OrderOpenPrice()-Ask)>(Point*TrailingStop))
{
if((OrderStopLoss()>(Ask+Point*TrailingStop)) ||
(OrderStopLoss()==0))
{
OrderModify(OrderTicket(),OrderOpenPrice(),Ask+Point*TrailingStop,
OrderTakeProfit(),0,Red);
return(0);
}
}
}
}
}
}
return(0);
}
// the end.

//+------------------------------------------------------------------+
//| Moving Average.mq4 |
//| Copyright © 2005, MetaQuotes Software Corp. |
//| http://www.metaquotes.net/ |
//+------------------------------------------------------------------+
#define MAGICMA 20050610
extern double Lots = 0.1;
extern double MaximumRisk = 0.02;
extern double DecreaseFactor = 3;
extern double MovingPeriod = 12;
extern double MovingShift = 6;
//+------------------------------------------------------------------+
//| Calculate open positions |
//+------------------------------------------------------------------+
int CalculateCurrentOrders(string symbol)
{
int buys=0,sells=0;
//----
for(int i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if(OrderSymbol()==Symbol() && OrderMagicNumber()==MAGICMA)
{
if(OrderType()==OP_BUY) buys++;
if(OrderType()==OP_SELL) sells++;
}
}
//---- return orders volume
if(buys>0) return(buys);
else return(-sells);
}
//+------------------------------------------------------------------+
//| Calculate optimal lot size |
//+------------------------------------------------------------------+
double LotsOptimized()
{
double lot=Lots;
int orders=HistoryTotal(); // history orders total
int losses=0; // number of losses orders without a break
//---- select lot size
lot=NormalizeDouble(AccountFreeMargin()*MaximumRisk/1000.0,1);
//---- calcuulate number of losses orders without a break
if(DecreaseFactor>0)
{
for(int i=orders-1;i>=0;i--)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_HISTORY)==false) { Print("Error in
history!"); break; }
if(OrderSymbol()!=Symbol() || OrderType()>OP_SELL) continue;
//----
if(OrderProfit()>0) break;
if(OrderProfit()<0) losses++;
}
if(losses>1) lot=NormalizeDouble(lot-lot*losses/DecreaseFactor,1);
}
//---- return lot size
if(lot<0.1) lot=0.1;
return(lot);
}
//+------------------------------------------------------------------+
//| Check for open order conditions |
//+------------------------------------------------------------------+
void CheckForOpen()
{
double ma;
int res;
//---- go trading only for first tiks of new bar
if(Volume[0]>1) return;
//---- get Moving Average
ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
//---- sell conditions
if(Open[1]>ma && Close[1]<ma)
{
res=OrderSend(Symbol(),OP_SELL,LotsOptimized(),Bid,3,0,0,"",MAGICMA,0,Red);
return;
}
//---- buy conditions
if(Open[1]<ma && Close[1]>ma)
{
res=OrderSend(Symbol(),OP_BUY,LotsOptimized(),Ask,3,0,0,"",MAGICMA,0,Blue);
return;
}
//----
}
//+------------------------------------------------------------------+
//| Check for close order conditions |
//+------------------------------------------------------------------+
void CheckForClose()
{
double ma;
//---- go trading only for first tiks of new bar
if(Volume[0]>1) return;
//---- get Moving Average
ma=iMA(NULL,0,MovingPeriod,MovingShift,MODE_SMA,PRICE_CLOSE,0);
//----
for(int i=0;i<OrdersTotal();i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==false) break;
if(OrderMagicNumber()!=MAGICMA || OrderSymbol()!=Symbol()) continue;
//---- check order type
if(OrderType()==OP_BUY)
{
if(Open[1]>ma && Close[1]<ma)
OrderClose(OrderTicket(),OrderLots(),Bid,3,White);
break;
}
if(OrderType()==OP_SELL)
{
if(Open[1]<ma && Close[1]>ma)
OrderClose(OrderTicket(),OrderLots(),Ask,3,White);
break;
}
}
//----
}
//+------------------------------------------------------------------+
//| Start function |
//+------------------------------------------------------------------+
void start()
{
//---- check for history and trading
if(Bars<100 || IsTradeAllowed()==false) return;
//---- calculate open orders by current symbol
if(CalculateCurrentOrders(Symbol())==0) CheckForOpen();
else CheckForClose();
//----
}
//+------------------------------------------------------------------+

Potrebbero piacerti anche