Mql4 Course: MQL4? What, Why An D Whe R e ?
Mql4 Course: MQL4? What, Why An D Whe R e ?
Mql4 Course: MQL4? What, Why An D Whe R e ?
By Coders’ g u ru
w w w . f orex -t sd. c om
-1-
WELCOME
--------------------
1- E x p ert Ad v i sors.
2- C ustom I n d i ca tors.
3- S cri p ts.
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 .
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
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.
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
--------------------
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”
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;
# 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."
F or ex a m pl e thi s l i ne i s v a l i d:
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.
1- S i ng l e l i ne c om m ents
/ / T hi s i s a c om m ent
ex ter n i nt MA_P er i od= 13;
/ * thi s
is
m ul ti
l i ne
c om m ent* /
/ * 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:
B ut thi s i s i nv a l i d c om m ent:
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.
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
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 :
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
--------------------
W h a t ’ s t h e D a t a t yp e m ea n?
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 .
i nt M y V a ra i ble= 0 ;
• 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
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
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:
F or ex a mp le:
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:
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 ) ).
F or ex a mp le:
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.
F or ex a mp le:
F or ex a mp le:
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
F or ex a mp le:
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
--------------------
x = ( y *z )/w ;
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).
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).
A=( B+ + )*5 ;
Bu t y ou ca n w r i te i t li ke tha t:
A+ + ;
B=A*5 ;
2- A ssi g n m e n t o p e r a t o r s:
F or ex a mp le:
A=B*C ;
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:
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
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 .
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.
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 ( ,)
O p e r a t o r sP r e c e d e n c e :
x + y / 10 0
x + (y / 100) //unambiguous, recommended
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 .
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.
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
--------------------------
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 ?
fo r ( j= 0 ; j< 15 ; j+ + )
P r in t ( j) ;
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 ).
in t j;
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 .
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 ).
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
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);
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 :
T h e B r e a k S ta te m e n t:
F or e x a m p l e :
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 :
L a te st n o te :
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 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:
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 ?
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 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 " );
}
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.
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
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 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 ).
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?
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 );
}
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 .
W h at ar e t h e v ar i abl es m ean?
i n t M y V a ra i b le= 0 ;
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
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)
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 ;
S c o p es o f v ariables:
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) ;
}
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) ;
}
E x t ern v ariables:
F or ex a mp le:
I h op e y ou en j oy ed th e les s on .
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
--------------------
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 ?
1- def in e direct iv e:
F or ex amp le:
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:
F or ex amp le:
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:
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:
F or ex amp le:
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
-------------------------------
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.
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
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 ) .
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.
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.
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.
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
-------------------------------
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
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();
int pos=Bars-counted_bars;
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.
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.
• …
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 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.
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
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”.
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.
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};
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);
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)
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.
SetIndexBuffer:
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:
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);
}
See you
Coders’ Guru
06-11-2005
MQL4 COURSE
By Coders’ guru
www.forex-tsd.com
-12-
Your First Indicator
Part 3
-------------------------------
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.
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();
int pos=Bars-counted_bars;
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 use the decrement operator (please review Lesson 4 - Operations & Expressions) for
decreasing the value of counted_bars by 1.
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.
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.
Another example will proof for you that they are not variables:
If you type and compile this line of code:
Bars=1;
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.
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.
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.
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:
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).
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).
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 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.
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.
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.
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
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"
//----
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.
//+------------------------------------------------------------------+
//| My_First_EA.mq4 |
//| Coders Guru |
//| http://www.forex-tsd.com |
//+------------------------------------------------------------------+
#property copyright "Coders Guru"
#property link "http://www.forex-tsd.com"
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
if(line1>line2)current_dirction = 1; //up
if(line1<line2)current_dirction = 2; //down
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);
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.
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.
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 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).
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
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.
Note: I have to repeat that our expert advisor is for educational purpose only and will
not (or aimed to) make profits.
//----
return(0);
}
//+------------------------------------------------------------------+
//| expert deinitialization function |
//+------------------------------------------------------------------+
int deinit()
{
//----
//----
return(0);
}
if(line1>line2)current_direction = 1; //up
if(line1<line2)current_direction = 2; //down
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);
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);
}
//+------------------------------------------------------------------+
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.
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
if(line1>line2)current_direction = 1; //up
if(line1<line2)current_direction = 2; //down
}
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).
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.
Note: You can use this function in your coming expert advisor to monitor any two lines
and get the crossing direction.
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.
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).
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);
else
{
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.
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
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
• 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;
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'
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
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);
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;
}
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++;
}
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);
}
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:
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.
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.
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.
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
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.
Account Information
AccountBalance()
AccountCredit()
AccountCompany()
AccountCurrency()
AccountEquity()
AccountFreeMargin()
AccountLeverage()
AccountMargin()
AccountName()
AccountNumber()
AccountProfit()
double AccountBalance()
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()
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.
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.");
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");
int Period()
Returns the number of minutes defining the used period (chart timeframe).
Sample
Print("Period is ", Period());
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);
}
string ServerAddress()
Returns connected server address in form of a text string.
Sample
Print("Server address is ", ServerAddress());
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()
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);
}
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 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()
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();
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 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 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
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);
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);
}
Pre-defined Variables
Ask
Bars
Bid
Close
Digits
High
Low
Open
Point
Time
Volume
double Ask
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
int counter=1;
for(int i=1;i<=Bars;i++)
{
Print(Close[i-1]);
}
double Bid
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[]
int Digits
Print(DoubleToStr(Close[i-1], Digits));
double High[]
Returns the highest price of the bar referenced.
double Low[]
double Open[]
double Point
datetime Time[]
Open time of the bars. Datetime is the number of seconds elapsed from 00:00 January 1, 1970.
double Volume[]
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
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));
}
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.
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.
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
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);
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 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 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 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 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 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 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);
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
}
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());
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());
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 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"
//+------------------------------------------------------------------+
//| 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);
//+------------------------------------------------------------------+
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>
//+------------------------------------------------------------------+
//| 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;
// final cutting
lasthigh=-1; lasthighpos=-1;
lastlow=-1; lastlowpos=-1;
//+------------------------------------------------------------------+
//| 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
//+------------------------------------------------------------------+
//| 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/ |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
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();
//----
}
//+------------------------------------------------------------------+