Forex Stock Exchange Forum
Would you like to react to this message? Create an account in a few clicks or log in to continue.
Forex Stock Exchange Forum

Forum About Trading on Forex,Stock,Binary Options, CryptoCurrency and NFTs


Thor Expert Advisor

You are not connected. Please login or register

Expert Advisors

Go to page : 1, 2  Next

Go down  Message [Page 1 of 2]

1Technical - Expert Advisors Empty Parabolic SAR Sat Jun 13, 2015 9:24 pm

dzonefx

dzonefx
Moderator

The Parabolic SAR indicator is plotted on the price chart. This indicator is similar to moving average in its
sense, but the difference is that the "Parabolic SAR" moves with much more acceleration. This indicator is
often used as a line of moving stop-signal.

The Parabolic SAR defines the points at which one should leave the market excellently. Long positions
should be closed when the price falls below SAR line, and the short ones should be closed when the price
increases above SAR line.

If you have a long position opened (i.e., the price is above SAR line), the SAR line will move upwards
independent on that in which direction the prices move. The value of the SAR line shift depends on the value
of price movement.
[You must be registered and logged in to see this image.]

2Technical - Expert Advisors Empty On Balance Volume (OBV) Sat Jun 13, 2015 9:23 pm

dzonefx

dzonefx
Moderator

On Balance Volume (OBV) indicator connects the volume and the price change accompanying the given
volume. The sense of this indicator, developed by Josef Granville, is simple. If the closing price of the
current bar is higher than that of the previous bar, the value of the volume of the current bar will be added to
the previous value of OBV, if the closing price of the current bar is lower than that of the previous bar, the
volume will be taken from the previous value of OBV.

Signals given by OBV are better to be used as confirming, these signals are more likely secondary in the
importance being compared with those of oscillators or tendency indicators, though, nevertheless, OBV like
oscillators gives a strong signal of turn at the divergence with the price. Moreover, the increase of OBV up to
a new maximum or its decrease to the new minimum confirm the power of bulls or bears and gives the
signal of increase or decrease respectively.
[You must be registered and logged in to see this image.]

3Technical - Expert Advisors Empty Moving Average of Oscillator Sat Jun 13, 2015 9:21 pm

dzonefx

dzonefx
Moderator

Moving Average of Oscillator is, in general case, the difference between the oscillator and the smoothing
of oscillator. In this case, the basic line of MACD is used as an oscillator, and the signal line of MACD is
used for smoothing.
[You must be registered and logged in to see this image.]

4Technical - Expert Advisors Empty Moving Average (MA) Sat Jun 13, 2015 9:20 pm

dzonefx

dzonefx
Moderator

The Moving Average (MA) indicator is the most frequently used indicator in technical analysis. The moving
average line will be plotted directly in the price movement chart. The moving average is calculated with a
certain predefined period. The shorter the period is, the higher the probability of false signals is. The longer
the period is, the weaker the sensibility of the moving average is.
Moving average variants:
• Simple Moving Average;
• Exponential Moving Average;
• Smoothed Moving Average;
• Linear Weighted Moving Average.
[You must be registered and logged in to see this image.]

5Technical - Expert Advisors Empty Money Flow Index (MFI) Sat Jun 13, 2015 9:19 pm

dzonefx

dzonefx
Moderator

taken out of it. Forming and interpreting this indicator are similar to those of RSI, the only difference is that
the MFI takes volume into consideration, as well.
When analyzing the MFI the following should be taken into account:
• divergences between indicator and price movement. If prices increase and MFI falls (or vice
versa), the probability of price turning is very high.
• MFI values higher than 80 and lower than 20 signalizes respectively about potential peak or
foundation of the market.
[You must be registered and logged in to see this image.]

6Technical - Expert Advisors Empty Momentum Sat Jun 13, 2015 9:17 pm

dzonefx

dzonefx
Moderator

The Momentum indicator measures the value of the commodity price change during a certain period.
These are the basic methods of use this indicator:
• As an oscillator following the tendency, like MACD. In this case, the signal to buy appears if
the indicator makes trough and begins to grow; the signal to sell appears if it comes up to its peak and
turns downwards. To define the turning points of the indicator it is better to use its short moving average.
The extremely high or low values of the "Momentum" indicator presume that the current tendency will
continue. So, if the indicator reaches the extremely high values and then turns downwards, the coming price
increasing should be expected. But, in any case, one should not open/close position before the prices
confirm the signal of the indicator.
• As a leading indicator. This method is based on the presuming that the final phase of upward
tendency is usually accompanied with sheer price increase (since everybody believes that it will continue),
and the closing of the bears' market is usually accompanied with sheer fall in prices (since everybody seeks
after leaving the market). This happens very often in this way, but it is still a too sweeping generalization.
[You must be registered and logged in to see this image.]

7Technical - Expert Advisors Empty Market Facilitation Index (BW MFI) Sat Jun 13, 2015 9:16 pm

dzonefx

dzonefx
Moderator

tick. Absolute values of the indicator do not mean anything as they are, only indicator changes have sense.
Bill Williams emphasizes the interchanging of MFI and volume:
• MFI increases and volume increases – this points out that:
1. the number of players coming into the market increases (volume increases),
2. the new coming players open positions in the direction of bar development, i.e., the
movement has begun and picks up speed.
• MFI falls and volume falls. It means the market participants are not interested anymore.
• MFI increases, but the volume falls. It is most likely, that the market is not supported with the
volume from clients, and the price is changing due to traders' (brokers and dealers) "on the floor"
speculations.
• MFI falls, but the volume increases. This is the battle between bulls and bears where the volume
of buying and selling is large, but movements of the price itself are insignificant as a result of powers being
approximately equal. One of the fighting parties (buyers against sellers) will win. Usually, the break of such a
bar lets you know if this bar determines the continuation of the trend or annuls the trend. Bill Williams calls
such bar "curtsying".
[You must be registered and logged in to see this image.]

dzonefx

dzonefx
Moderator

Moving Average Convergence/Divergence (MACD) is the dynamic indicator following the tendency. It
shows the ratio between two moving averages of the price.
The MACD is developed as the difference between two exponential moving averages (EMA) having periods
of 12 and 26 days. To define the best opportunities for buying or selling clearly, the so called signal line will
be plotted in the MACD chart: it is the 9-days-moving-average of the indicator.
MACD is the most effective under conditions when the market swings with high amplitude in trading. The
most frequently used signals of MACD are intersections, overbuying/overselling states and divergences.
[You must be registered and logged in to see this image.]

9Technical - Expert Advisors Empty Ichimoku Kinko Hyo Sat Jun 13, 2015 9:13 pm

dzonefx

dzonefx
Moderator

Ichimoku Kinko Hyo is predefined to characterize the market trend, support and opposition levels, and to
generate signals of buying and selling. This indicator works best at week and day charts.
When defining the dimension of parameters, four time intervals of different length are used. The values of
individual lines composing this indicator are based on these intervals:
• Tenkan-sen shows the average price value during the first time interval defined as the sum of
maximum and minimum within this time, divide by two.
• Kijun-sen shows the average price value during the second time interval.
• Senkou Span A shows the middle of the distance between two previous lines shifted forwards by
the value of the second time interval.
• Senkou Span B shows the average price value during the third time interval shifted forwards by
the value of the second time interval.

Chinkou Span shows the closing price of the current candle shifted backwards by the value of the second
time interval. The distance between the Senkou lines is hatched with another color and called 'cloud'. If the
price is between these lines, the market should be considered as non-trend, and then the cloud margins
form the support and opposition levels.

If the price is above the cloud, its upper line forms the first support
level, and the second line forms the second support level. If the price is below cloud, the lower line forms the
first opposition level, and the upper one forms the second level. If the "Chinkou Span" line traverses the
price chart in the bottom-up direction it is signal to buy. If the "Chinkou Span" line traverses the price chart in
the top-down direction it is signal to sell. "Kijun-sen" is used as an indicator of the market movement. If the
price is higher than this indicator, the prices will probably continue to increase. When the price traverses this
line the further trend changing is possible.

Another kind of using the "Kijun-sen" is giving signals. Signal to buy is generated when the "Tenkan-sen"
line traverses the "Kijun-sen" in the bottom-up direction. Top-down direction is the signal to sell. "Tenkansen"
is used as an indicator of the market trend. If this line increases or decreases, the trend exists. When it
goes horizontally, it means that the market has come into the channel.
[You must be registered and logged in to see this image.]

10Technical - Expert Advisors Empty Force Index Sat Jun 13, 2015 9:11 pm

dzonefx

dzonefx
Moderator

The Force Index was developed by Alexander Elder. This index measures the Bulls Power at each
increase, and the Bulls Power at each decrease. It connects the basic elements of market information: price
trend, its drops, and volumes of transactions. This index can be used as it is, but it is better to approximate it
with the help of moving average. Approximation with the help a short moving average (the author proposes
to use 2 intervals) contributes to finding the best opportunity to open and close positions. If the
approximations is made with long moving average (period 13), the index shows the tendencies and their
changes.
• It is better to buy when the forces become minus (fall below zero) in the period of indicator
increasing tendency;
• The force index signalizes the continuation of the increasing tendency when it increases to the new
peak;
• The signal to sell comes when the index becomes positive during the decreasing tendency;
• The force index signalizes the Bears Power and continuation of the decreasing tendency when the
index falls to the new trough.
[You must be registered and logged in to see this image.]

11Technical - Expert Advisors Empty Envelopes Sat Jun 13, 2015 9:10 pm

dzonefx

dzonefx
Moderator

The Envelopes are formed with two moving averages one of which is shifted upward and another one is
shifted downward. The selection of optimum relative number of band margins shifting is determined with the
market volatility: the higher the latter is, the stronger the shift is. Envelopes define the upper and the lower
margins of the price range.
• Signal to sell appears when the price reaches the upper margin of the band;
• Signal to buy appears when the price reaches the lower margin.
[You must be registered and logged in to see this image.]

12Technical - Expert Advisors Empty Elder-rays Sat Jun 13, 2015 9:08 pm

dzonefx

dzonefx
Moderator

The Elder-rays combine the properties of trend following indicators and oscillators. They use exponential
moving average indicator (EMA, the best period is 13) as a tracing indicator. The oscillators reflect the
power of bulls and bears. To plot the Elder-rays three charts should be used: on one side, the price chart
and EMA will be plotted, on two other sides bulls power oscillator (Bulls Power) and bears power oscillator
(Bears Power) will be plotted.
Elder-rays are used both individually and together with other methods. If using them individually, one should
take into account that the EMA slope determines the trend movement, and position should be opened in its
direction. Bulls and bears power oscillators are applied for defining the moment of positions opening/closing.
The following positions should be opened:
• Buy, if:
1. there is an increasing trend (determined with the EMA movement);
2. the Bears Power oscillator is negative, but increasing at the same time;
3. the last peak of the Bulls Power oscillator is higher than the previous one;
4. the Bears Power oscillator increases after the Bulls divergence.
At the positive values of the Bears Power oscillator, it is better to keep back.
• Sell, if:
1. there is a decreasing trend (determined with the EMA movement);
2. the Bulls Power oscillator is positive, but decreases gradually;
3. the last trough of the Bulls Power oscillator is lower than the previous one;
4. the Bulls Power oscillator decreases leaving the Bears' divergence.
Do not open short positions when the Bulls Power oscillator is negative.
Divergence between the Bulls and Bears Power and prices is the best time for trading
[You must be registered and logged in to see this image.]

13Technical - Expert Advisors Empty DeMarker Sat Jun 13, 2015 9:06 pm

dzonefx

dzonefx
Moderator

The DeMarker indicator registers the regions of price depletion which usually coincide with the peaks and
troughs of prices. The indicator varies between 0 and 1. When indicator is below the 0.3 point, the price turn
upward is to be expected. When the indicator is above 0.7, the price turn downward is to be expected.
[You must be registered and logged in to see this image.]

14Technical - Expert Advisors Empty Commodity Channel Index (CCI) Sat Jun 13, 2015 9:05 pm

dzonefx

dzonefx
Moderator

Commodity Channel Index (CCI) measures the deviation of the commodity price from its average
statistical price. High values of the index point out that the price is unusually high being compared with the
average one, and low values show that the price is too low. In spite of its name, the CCI can be applied for
any financial instrument, and not only for the wares.
There are two basic techniques of using CCI:
• For finding the divergences.
The divergence appears when the price reaches a new maximum, and CCI can not grow above the previous
maximums. This classical divergence is normally followed by the price correction.
• As an indicator of overbuying/overselling.
CCI usually varies in the range of +/-100. Values above +100 inform about overbuying state (and about a
probability of correcting decay), and the values below 100 inform about the overselling state (and about a
probability of correcting increase).
[You must be registered and logged in to see this image.]

15Technical - Expert Advisors Empty Bollinger Bands Sat Jun 13, 2015 9:03 pm

dzonefx

dzonefx
Moderator

Bollinger Bands are similar to moving average envelopes. The difference between them consists in that the
margins of envelopes are positioned above and below the moving average curve at the fixed distance
expressed as percentage, whereas the margins of Bollinger Bands are based on distances equal to a
certain amount of standard deviations. Inasmuch as the value of the standard deviation depends on
volatility, the bands regulate their own width: it increases when the market is unstable, and decreases during
more stable periods.

Bollinger Bands are usually plotted in the price chart, but they can also be plotted in the indicator chart. All
mentioned below concerns the bands plotted in price charts. Like in the case of envelope moving averages,
the Bollinger Bands interpretation is based on that it is inherent to the prices to stay in the range of highest
and lowest margins of the band. A distinctive feature of Bollinger Bands is their variable width determined
with the volatility of prices. In the periods of significant price changes (i.e., of high volatility), the bands
become wider giving space to prices. In the economic glut periods (i.e., of low volatility) the bands become
narrow keeping the prices in the range of their margins.

Bollinger Bands features:
• Price leaps usually happen after band narrowing corresponding with the volatility decrease.
• If prices exceed the range of the band the continuation of the current tendency should be predicted.
• If the peaks and troughs outside the band are followed by peaks and troughs inside of the band,
the turn of the tendency is possible.
• Price movement having started from one of the band margins usually reaches the opposite margin.
The latter observation is useful for predicting price guideposts.
[You must be registered and logged in to see this image.]

16Technical - Expert Advisors Empty Average True Range (ATR) Sat Jun 13, 2015 9:00 pm

dzonefx

dzonefx
Moderator

Average True Range (ATR) is the indicator of volatility of the market. It was introduced by Wells Wilder in
his book New Concepts of Technical Trading Systems, and since then the indicator is applied as a
constituent of many other indicators and trading systems.

ATR often reaches high values in the market foundations after sheer fall in prices caused with panic selling.
Low values of the indicator often correspond with long periods of horizontal movement being observed in the market summits and during the consolidation time.

It can be interpreted by the same rules as other volatility indicators. The principle of prediction with the help of this indicator is formulated as follows: the higher the value of the indicator is, the more probable the trend change is; the lower this value is, the weaker the trend orientation is.
[You must be registered and logged in to see this image.]

17Technical - Expert Advisors Empty ADX (Average Directional Movement Index) Sat Jun 13, 2015 8:58 pm

dzonefx

dzonefx
Moderator

Average Directional Movement Index (ADX) is the indicator developed by Wells Wilder for measuring the
intensity of market trend. When calculating ADX the values of indicators of ordered motions are used (+DI
and -DI). It is considered that if ADX goes up and exceeds 15 the trend is observed in the market.
[You must be registered and logged in to see this image.]

18Technical - Expert Advisors Empty Accumulation/Distribution (A/D) Sat Jun 13, 2015 8:57 pm

dzonefx

dzonefx
Moderator

Accumulation/Distribution is an indicator which is determined by the price and volume changing. The
volume represents the weighting factor at the price changing: the larger the factor (volume) is, the more
significant the contribution of the price changing (for the given period of time) to the indicator's value is.

The indicator was developed by Larry Williams and represents the accumulation of the difference between all
movements upward (accumulation) during the days, when the price has arisen by the closing point, and
downward (distribution) during the days, when the price has fallen by the closing point.

This indicator gives rather infrequent signals forming divergence with the price at the critical breaks of
tendencies.
[You must be registered and logged in to see this image.]

19Technical - Expert Advisors Empty Technical Indicators Sat Jun 13, 2015 8:53 pm

dzonefx

dzonefx
Moderator

Review
• Programming language MetaQuotes Language II (MQL II)
• Step-By-Step Creation of Simple Expert
• Features of Writing Experts
• Features of Writing Custom Indicators and User Functions
Technical Indicators
Indicator is a result of mathematical calculations on the basis of price and/or volume indexes. The values
obtained are used for prediction of price changes. There is a large amount of developed technical indicators
in the world, some of them are represented in FXDirectDealer:
• Accumulation/Distribution;
• ADX;
• Average True Range;
• Bollinger Bands;
• Commodity Channel Index;
• DeMarker;
• Elder-rays;
• Envelopes;
• Force Index;
• Ichimoku Kinko Hyo;
• MACD;
• Market Facilitation Index;
• Momentum;
• Money Flow Index;
• Moving Average;
• Moving Average of Oscillator;
• On Balance Volume;
• Parabolic SAR;

dzonefx

dzonefx
Moderator

Writing user indicators and functions in trading system has a number of features, as well:

• Parameters to be taken into consideration for user indicators and functions should be described in
the Inputs section and be of numeric data type.
Inputs: nPeriod(13),nDeviation(0.1),nAccountedBars(300);

• Parameters will be sent to the function of custom indicator calculation in the order in which they are
described. For example, call the custom indicator having the parameters listed above will appear as follows:
iCustom( "SomeIndicator", 13, 0.1, 300, MODE_FIRST, 0 );

• Strictly speaking, parameters should not be necessarily sent to the function. If the function does not
have an Inputs section it is no use to send the parameters. Or one can use the initial values being applied
for describing parameters. For example, call the same custom indicator without parameters will appear as
follows:
iCustom( "SomeIndicator", MODE_FIRST, 0 );
This means that those values will be used which are stored in variables described in the Inputs section,i.e.
13, 0.1 and 300.

• What is the difference between the function of custom indicator calculation and a simple user
function? It is defined by the methods of call. The function of custom indicator is called once when
recalculation of the whole array of price data. The simple user function is called during the expert program
working, i.e. with each tick. The function of custom indicator calculation has access to two arrays storing the
results of calculation with the help of functions named SetIndexValue, SetIndexValue2, GetIndexValue,
GetIndexValue2. And the simple user function has access to these arrays with the help of iCustom
function. The function of custom indicator calculation can not call trading functions and functions of call of
user functions. User function should be finished with the call of the Return function in order to send the
value calculated to the expert-caller.

• There is a special value of index array which means the absence of data, it is 0. If zero value is
significant in any of the custom indicators, it is necessary to use a very small value, for example,
0.00000001. It is necessary to note that when displaying the custom indicators in the pop-up prompts, the
accuracy of 4 signs after the dot in decimal fraction will be used. Indicator placed in the price chart can not
have negative data as they can not be displayed in any case. That is why negative values of the indicator
placed in the price chart will also be considered as special ones. (The features of use of special values of
custom indicators being placed in the price chart are discussed below.)

• The values of the variables in the function of custom indicator calculation, and the data arrays with
the results of custom indicator calculation will be initialized at the first run of the indicator, and at the period
or instrument change at the chart. It means, all values will be stored between initializations! When custom
indicator is programmed in a proper and accurate way it is possible to provide the possibility of calculation of
only last, not calculated values, data arrays of the indicator. An example of an indicator of a simple moving
average:

/*[[
Name := SimpleMA
Author := Copyright (c) 2003, MetaQuotes Software Corp.
Link := [You must be registered and logged in to see this link.]
Separate Window := No
First Color := Red
First Draw Type := Line
Use Second Data := No
]]*/


Inputs : MAPeriod(13);

Variables : shift(0), cnt(0), loopbegin(0), first(True), prevbars(0), sum(0);

SetLoopCount(0);

// initial checkings

If MAPeriod < 1 Then Exit;

// check for additional bars loading or total reloading

If Bars < prevbars Or Bars-prevbars>1 Then first = True;

prevbars = Bars;

If first Then Begin

//loopbegin prevent couning of counted bars exclude current

loopbegin = Bars-MAPeriod-1;

If loopbegin < 0 Then Exit; // not enough bars for counting

first = False;

End;

// moving average

loopbegin = loopbegin+1; // current bar is to be recounted too

For shift = loopbegin Downto 0 Begin

sum = 0;

For cnt = 0 To MAPeriod-1 Begin

sum = sum + Close[shift+cnt];

End;

SetIndexValue(shift,sum/MAPeriod);

loopbegin = loopbegin-1; // prevent to previous bars recounting

End;


Explanations for the code. In the first variable after initialization the True value is stored. As soon as the
indicator runs for the first time the check of the first variable will be conducted and the value of the loopbegin
variable will be established on the assumption that the cycle would run from the data beginning.

When the cycle is running the loopbegin variable is modified and contents in fact the value of the index of the last value calculated in the indicator array. In the case of "loop detected", the indicator expert will stop its work.

But the first variable is established in False, it means that at the next start the loopbegin variable will not be
established at the beginning of the indicator array. It means that the new calculation will be continued from
the point where the previous calculation has been made. At the end, all the bars will be calculated. But if we
need to recalculate the indicator value at the current bar with the coming of each new quote we modify the
loopbegin variable before the cycle starts, increasing it by 1 to realize at least 1 cycle iteration.

If the historical data were spooled (Refresh Chart) or reloaded (Erase and Refresh Chart) the condition of
the comparing of the current number of bars with the previous number of those would allow us to recalculate
indicator on all data.

• Custom indicator function can be called not only from the expert program, but also from the
"Navigator" window when selecting Custom Indicator. In this connection, there are several features of
designing such a program. An example of the "Envelopes" indicator:

/*[[
Name := Envelopes
Author := Copyright (c) 2003, MetaQuotes Software Corp.
Link := [You must be registered and logged in to see this link.]
Notes := Sample Custom Indicator program
Separate Window := No
First Color := Blue
First Draw Type := Line
Use Second Data := Yes
Second Color := Red
Second Draw Type := Line
]]*/


Inputs : nPeriod(13),nDeviation(0.1),nAccountedBars(300);

Vars : CurrentBar(0),shift(0),i(0),sum(0),UpperBand(0),LowerBand(0),BeginBar(0);

Vars : prevBars(0);

If prevBars = Bars Then Exit;

prevBars = Bars;

SetLoopCount(0);

BeginBar = Bars – nAccountedBars;

If BeginBar < 0 then BeginBar = 0;

For CurrentBar = 0 To BeginBar-1 Begin

shift = Bars-1-CurrentBar;

SetIndexValue(shift, 0);

SetIndexValue2(shift, 0);

End;

For CurrentBar = BeginBar To Bars-1 Begin

shift = Bars – 1 – CurrentBar;

If CurrentBar < nPeriod-1 Then Begin;

SetIndexValue(shift, 0);

SetIndexValue2(shift, 0);

Continue;

End;

sum = 0;

For i=0 To nPeriod-1 Begin

sum = sum + Close[shift+i];

End;

sum = sum / nPeriod;

UpperBand = sum * (1 + nDeviation/100);

LowerBand = sum * (1 – nDeviation/100);

SetIndexValue(shift, UpperBand);

SetIndexValue2(shift, LowerBand);

End;

As you can see the "Experts Wizard" creates the description of custom indicator differing from the
description of the expert program.

Separate Window := No – means that the indicator chart will be developed in the same window where the
price chart is developed. If the values calculated with the custom indicator differ from the current prices very
much, the indicator chart must be shown in a separate window.

Draw Type := Line – means that the indicator chart will be developed as a line. It is also possible to develop
a histogram (Histogram) or to show a separate symbol (Symbol; in this case, the symbol will be set as a
number defining the position of the symbol in the "Wingdings" table. For example, First Symbol := 217).

Use Second Data := Yes – means that the indicator calculation results in 2 charts, and not the only one
(another example: MACD histogram and signal line). First Color, First Draw Type and First Symbol
belong to the first indicator chart, the Second Color, Second Draw Type and Second Symbol belong to
the second one.

If the indicator is shown in a separate window and the limiting values of the minimum and/or maximum are
known beforehand, these limiting values can be defined to accelerate the displaying and, in some case, to
make the displaying more beautiful (this especially concerns histograms). Experts Master will, for example,
design it, as follows:
Minimum Chart Limits := –1.000000
Maximum Chart Limits := 1.000000


All parameters listed and made with the Expert Master help in quick setting of Custom Indicator.
[You must be registered and logged in to see this image.]
• As it was mentioned above, the user expert chart can be displayed as a histogram. There is a
feature of displaying the histogram in the price chart window. Both data arrays of the Custom Indicator
participate in the process of histogram displaying. The line will be drawn at the chart from the first value to
the second corresponding one. If the first value is more than the second one the line will be drawn with the
first color. Otherwise, it will be drawn with the second color. This feature can be used when coloring the bars
with different colors.

/*[[
Name := ColoredBars
Author := Copyright (c) 2003, MetaQuotes Software Corp.
Link := [You must be registered and logged in to see this link.]
Notes := Sample Custom Indicator program
Separate Window := No
First Color := Blue
First Draw Type := Histogram
Use Second Data := Yes
Second Color := Pink
Second Draw Type := Histogram
]]*/


Variables : CurrentBar(0),shift(0),nBWMFI(0),prevBWMFI(0),value1(0),value2(0);

SetLoopCount(0);

For CurrentBar = 0 To Bars-1 Begin

shift = Bars-1-CurrentBar;

nBWMFI = (High[shift] – Low[shift]) / Volume[shift];

If CurrentBar < 1 Then Begin

SetIndexValue(shift, 0);

SetIndexValue2(shift, 0);

prevBWMFI = nBWMFI;

Continue;

End;

value1 = 0;

value2 = 0;

If nBWMFI > prevBWMFI and Volume[shift] < Volume[shift+1] Then Begin

value1 = High[shift];

value2 = Low[shift];

End;

If nBWMFI < prevBWMFI and Volume[shift] > Volume[shift+1] Then Begin

value1 = Low[shift];

value2 = High[shift];

End;

SetIndexValue(shift, value1);

SetIndexValue2(shift, value2);

prevBWMFI = nBWMFI;

End;

The example given above illustrates coloring the bars in "Bill Williams" style. If necessary, it is possible to
prepare another program of custom indicator to color bars with two other colors corresponding with other
conditions.

• The features of special values processing were mentioned above which had been less or equal to 0
and concerned the "line" custom indicators placed in the price chart. 0 means the absence of data. The line
will be plotted between points having positive values. A negative value means the end of the previous line.
I.e., lines can be interrupted. As an illustration of the "absence of data" an example of the "ZigZag" indicator
is given below which plots lines between local price extremes.

/*[[
Name := ZigZag
Author := Copyright (c) 2003, MetaQuotes Software Corp.
Link := [You must be registered and logged in to see this link.]
Separate Window := No
First Color := Blue
First Draw Type := Line
Use Second Data := No
]]*/


Inputs: depth(12),deviation(5),backstep(3);

Variables : shift(0),lasthigh(-1),lastlow(-1),lasthighpos(0),lastlowpos(0);

Variables : val(0),back(0),res(0);

Variables : curlow(0),curhigh(0);

SetLoopCount(0);

lasthigh=-1;

lastlow=-1;

for shift = Bars-300 downto 0

{

//-- low

val=Low[Lowest(MODE_LOW,shift+depth-1,depth)];

if val==lastlow then val=0

else

{

lastlow=val;

if (Low[shift]-val)>(deviation*Point) then val=0

else

{

for back=1 to backstep

{

res=GetIndexValue(shift+back);

if res!=0 and res>val then SetIndexValue(shift+back,0);

};

};

};

SetIndexValue(shift,val);

//-- high

val=High[Highest(MODE_HIGH,shift+depth-1,depth)];

if val==lasthigh then val=0

else

{

lasthigh=val;

if (val-High[shift])>(deviation*Point) then val=0

else

{

for back=1 to backstep

{

res=GetIndexValue2(shift+back);

if res!=0 and res

};

};

};

SetIndexValue2(shift,val);

};

// final cutting

lasthigh=-1; lasthighpos=-1;

lastlow=-1; lastlowpos=-1;

for shift = Bars-300 downto 0

{

curlow=GetIndexValue(shift);

curhigh=GetIndexValue2(shift);

if curlow == 0 & curhigh == 0 then continue;

//--

if curhigh!=0 then

{

if lasthigh>0 then

{

if lasthigh

else SetIndexValue2(shift,0);

};

//--

if lasthigh

{

lasthigh=curhigh;

lasthighpos=shift;

};

lastlow=-1;

};

if curlow!=0 then

{

if lastlow>0 then

{

if lastlow>curlow then SetIndexValue(lastlowpos,0)

else SetIndexValue(shift,0);

};

//--

if curlow

{

lastlow=curlow;

lastlowpos=shift;

};

lasthigh=-1;

};

};

for shift = Bars-300 downto 0

{

res=GetIndexValue2(shift);

if res!=0 then SetIndexValue(shift,res);

};

As a result, the indicator given above fills the first indicator data array with the extreme values. The values
between extremes are zero values. The lines are drawn between extremes (i.e., between positive values).

• As an illustration of symbols displaying in defining the position of the price chart a program of the
simplest calculation of "Bill Williams" fractals is given below:

/*[[
Name := Fractals
Author := Copyright (c) 2003, MetaQuotes Software Corp.
Link := [You must be registered and logged in to see this link.]
Notes := Sample Custom Indicator program
Separate Window := No
First Color := Blue
First Draw Type := Symbol
First Symbol := 217
Use Second Data := Yes
Second Color := Red
Second Draw Type := Symbol
Second Symbol := 218
]]*/


Variable : value(0),CurrentBar(0), price(0);

SetLoopCount(0);

For CurrentBar = 0 To Bars-1 Begin

If CurrentBar < 2 Or CurrentBar >= Bars-2 Then Begin

SetIndexValue(CurrentBar, 0);

SetIndexValue2(CurrentBar, 0);

Continue;

End;

value = 0;

price = High[CurrentBar];

If price>High[CurrentBar+1] and price>High[CurrentBar+2] and

price>High[CurrentBar-1] and price>High[CurrentBar-2]

then value = price;

SetIndexValue(CurrentBar, value);

value = 0;

price = Low[CurrentBar];

If price

price

then value = price;

SetIndexValue2(CurrentBar, value);

End;

A user function example. Before using the function, it is necessary to be sure that it has been successfully

translated, and that there is a corresponding exp-file in the expert catalogue.

/*[[
Name := UserFunc
Author := Copyright (c) 2003, Metaquotes Software Corp.
Link := [You must be registered and logged in to see this link.]
]]*/


Input : parameter(0);

print( "Input parameter is ", parameter );

return( parameter );

User Function call sample:

Variable: ReturnValue(0);

ReturnValue = UserFunction( "UserFunc", Close );

print( "Return value is ", ReturnValue );

• It must be noted that the overflow of custom indicators, improperly written user functions can
slow down the functioning of the client terminal!

21Technical - Expert Advisors Empty Features of Writing Experts Tue May 12, 2015 11:13 pm

dzonefx

dzonefx
Moderator

Writing and testing experts trading system has a number of features.
• Before opening a position it is necessary to check if there is any free money at the account. If there
is not enough money at the account the operation of opening a position will end unsuccessfully. And at the
same time, when being tested the FreeMargin value must necessarily be above 1000 because when being
tested one lot price makes 1000.
If FreeMargin < 1000 Then Exit; // no money – exit

• After having opened, closed or changed a position or after having deleted a pending order (i.e.,
after having used any of the following commands: SetOrder, CloseOrder, ModifyOrder or DeleteOrder), it
is recommended to finish the expert program using the Exit instruction, as after completing the operation a
10-seconds-timeout begins which is used for processing trading operations. But for all that, this 10-secondstimeout does not function during the testing (it is possible to process several operations one after another), and, if one does not finish the expert running by executing the Exit instruction after having completed the operation, the testing results can differ from those of the real expert trading.

SetOrder(OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,RED); // execute
Exit; // exit
To prevent a possibility of processing several trade operations with an interval of less than 10 seconds
during the testing it is also possible to check before processing the next operation that no less than 10
seconds have passed after completing the last trade operation.
// check that the current time is more than the time taken for
// completing the last trade operation more than 10 seconds
If CurTime > LastTradeTime + 10 Then Begin
SetOrder(OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,RED); // execute
Exit;
End;

• The admittance for historical data can be obtained using indexing predefined variables Open,
Close, High, Low, and Volume. Index in this case is the number of periods necessary to be counted back.
// if Close at the last bar is less than Close at the bar before last
If Close[1] < Close[2] Then Exit;

• Experts testing in FXDirectDealer trading system supports 4 models.
o OHLC points (Open/High/Low/Close). When testing an expert only Open, High, Low,
Close prices are used. This model of testing is the quickest one. But the results of the testing can differ from
those of the real expert trading.
o Every spread/2 points. When testing an expert the candle development having the
"spread/2"(usually 2) points step is simulated.
o Every 1 point. When testing an expert the candle development having the 1 point step is
simulated. This model of testing is the slowest one. But the results of the testing are identical with those of
the real expert trading (when keeping the 10 seconds interval between completing trading operations).

• When writing and testing an expert, like testing any other program, it is sometimes necessary to
display some additional debugging information. The MQL II language gives a number of opportunities to
display such information.
o The Alert function displays a dialogue box containing data defined by the user.
Alert("Free margin is ", FreeMargin);

o The Comment function shows the data defined by the user in the upper left corner of the
chart. The "\n" char sequence is used for line feed.
Comment("Free margin is ", FreeMargin, "\nEquity is ", Equity);
o The Print function prints data defined by the user in the log file.
Print("Total trades are ", TotalTrades, "; Equity is ", Equity, "; Credit is ", Credit);
o The PrintTrade function prints data of selected trade position in the log-file.
PrintTrade(1);

• When testing an expert the test results are stored in files having ".log" extension in a subdirectory
of the "logs"-directory where you have already installed your FXDirectDealer trading system. When you
often test experts do not forget to delete log files periodically as they can have a size of several megabytes.

• It occurs that it is necessary to perform a large preparatory work before the experts start working.
This work is so large that the expert will close forcedly with the error of loop detected. (It is necessary to note
that the expert runs with each price tick and may not work long). But you can perform the preparatory work,
for example, initialization of any array, in several movements. For example, in this way:
var: cnt(0), initvalue(0);
array: arr[6000](0);
SetLoopCount( 50000 ); // for example only. Illustrates an initialization in 3 times
If initvalue <=6000 Then Begin
print( "beginning from ", initvalue );
For cnt = initvalue To 6000 Begin // initialization loop
arr[cnt] = cnt;
// strongly recommended last instruction in the initialization loop as follow
initvalue = cnt + 1;
End;
print( "stopped with ", initvalue, " –- initialization is complete." );
End
Else print( "initialization is complete" );
If it is necessary to initialize several arrays you should use several variables. For example, "initvalue",
"initvalue2", "initvalue3", etc.

• How to assess the beginning of the next bar? (This is necessary to know that the previous bar has
just been formed.) There are several ways:
Variable: prevbars(0);...
If prevbars = Bars Then exit;
prevbars = Bars;
...
This method can sometimes fail when spooling the history. I.e., the number of bars has changed, and the
"previous" bar has not been formed yet. In this case, it is possible to complicate checking the difference
between values being equal to 1.

The next way is based on the fact that the value of Volume is formed on the base of the number of ticks
having come for each bar, and the first tick means that the value of the bar being newly formed the Volume
value is equal to 1:
If Volume > 1 Then exit;
...
This method can fail when price ticks come too intensively. As a matter of fact, the processing of the price
ticks coming is performed in a separate traffic. And if this traffic is occupied during the next tick coming, this
coming tick will not be processed to prevent overloading the computing power! In this case, it is possible to
complicate the checking using storage of the previous Volume value.
The third way is based on the bar opening time:
Variable: prevtime(0);
...
If prevtime = Time Then exit;
prevtime = Time;
...
This method is the most effective. It will work under any conditions.

• An example of working with the file is given below:
vars : handle(0), cnt1(0), cnt2(0), position(0), size(0);
vars : string(""), number(0);
handle = FileOpen( "test", "," );
print( "file size is ", FileSize( handle ) );
size = 0;
while not IsFileEnded( handle ) begin
string = FileReadString( handle );
number = FileReadNumber( handle );
// lines counting
if IsFileLineEnded( handle ) then size = size + 1;
end;
print( "file has ", size, " lines" );
if size < 20 then begin
cnt2 = 0;
for cnt1 = size to 19 begin
FileWrite(handle, "teststring"+cnt1, cnt1+1);
cnt2 = cnt2 + 1;
size = size + 1;
if cnt2 = 5 then break;
end;
print( "there are ", cnt2, " lines added" );
print( "file size is ", FileSize( handle ) );
end;
position = FileSeek( handle, 0, SEEK_SET );
// file reading from begin
for cnt1=1 to size begin
print( FileReadString( handle ), ";", FileReadNumber( handle ) );
If IsFileEnded( handle ) then break;
end;
FileClose(handle);

Here are several explanations to the code. The file will be opened first, then the line-by-line reading should
be performed. It is presumed that the structure of each line of the file consists of one text variable and one
numeric variable. If the number of lines being counted is less than 20 the next portion of 5 lines will be
added.

 Since the pointer of the current position of reading-recording is at the end of the file after the lines have been counted, the recording of the next record will be made to the end of the file, after that the pointer
of the current position will be moved to the end of the file. If the record should be done to the end of the file
immediately after it has been opened it is necessary to use the following function:
position = FileSeek( handle, 0, SEEK_END );
after that the data should be stored in the file.In the second part of the code the reading of records from the file will be conducted from its very beginning.

dzonefx

dzonefx
Moderator

Step IV:
[You must be registered and logged in to see this image.]
We have written the Expert Advisor – now we are impatient to evaluate it by testing it on historical data. Let's take as an example 15-minute intervals for EUR/USD, approximately 4000 bars.

Let's open EURUSD, M15 chart, attach the MACD Sample Expert Advisor to the chart using the Attach to a chart command (by selecting the MACD Sample line by the mouse pointer in the "Navigator"
window, pressing the right mouse button and selecting the command in the appearing menu).

After that we go the the Expert Advisor settings, where we can change the predefined external variables Lots, Stop Loss, Take Profit, Trailing Stop, as well as the user-defined variables. To allow the Expert Advisor not only to advise, but also to gamble on the trading account in real-time on its own, you need to activate the Allow Live Trading button. We are going to do testing on historical data, though, so we leave the settings unchanged, switch to the Strategy Tester tab, activate the Arrows on the chart tick (to be able to see the arrows on the chart) and start our test with the Start button:
[You must be registered and logged in to see this image.]

dzonefx

dzonefx
Moderator

Step III:
Let's open the Expert Advisor settings (using a button or a line in the Properties... menu). We are offered a
window in which we have to define the external settings of the working parameters:
[You must be registered and logged in to see this image.]

Let's assemble all the code from the previous section:

defines: MACDOpenLevel(3),MACDCloseLevel(2);

defines: MATrendPeriod(56);

var: MacdCurrent(0),MacdPrevious(0),SignalCurrent(0),SignalPrevious(0);

var: MaCurrent(0),MaPrevious(0);

var: cnt(0);

// initial data checks

// it is important to make sure that the Expert Advisor runs on a normal chart and that

// the user has correctly set the external variables (Lots, StopLoss,

// TakeProfit, TrailingStop)

// in our case we only check the TakeProfit

If Bars<200 or TakeProfit<10 then Exit; // less than 200 bars on the chart

// to simplify and speed up the procedure, we store the necessary

// indicator data in temporary variables

MacdCurrent = iMACD(12,26,9,0,MODE_MAIN);

MacdPrevious = iMACD(12,26,9,1,MODE_MAIN);

SignalCurrent = iMACD(12,26,9,0,MODE_SIGNAL);

SignalPrevious= iMACD(12,26,9,1,MODE_SIGNAL);

MaCurrent = iMA(MATrendPeriod,MODE_EMA,0);

MaPrevious = iMA(MATrendPeriod,MODE_EMA,1);

// now we have to check the status of the trading terminal.

// we are going to see whether there are any previously opened positions or orders.

If TotalTrades<1 then

{

// there are no opened orders

// just to be on the safe side, we make sure we have free funds on our account.

// the "1000" value is taken just as an example, usually it is possible to open 1 lot

If FreeMargin<1000 then Exit; // no money – we exit

// checking for the possibility to take a long position (BUY)

If MacdCurrent<0 and MacdCurrent>SignalCurrent and

MacdPrevious(MACDOpenLevel*Point) and

MaCurrent>MaPrevious then

{

SetOrder(OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,RED); // executing

Exit; // exiting, since after the execution of a trade

// there is a 10-second trading timeout

};

// checking for the possibility of taking a short position (SELL)

If MacdCurrent>0 and MacdCurrent

MacdPrevious>SignalPrevious and MacdCurrent>(MACDOpenLevel*Point) and

MaCurrent

{

SetOrder(OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,RED); // executing

Exit; // exiting

};

// here we completed the check for the possibility of opening new positions.

// no new positions were opened and we simply exit the programme using the Exit command, as

// there is nothing to analyze

Exit;

};

// we come over to an important part of the Expert Advisor – the control of open positions

// it is important to enter the market correctly, but it is even more important to exit it...'

for cnt=1 to TotalTrades

{

if OrderValue(cnt,VAL_TYPE)<=OP_SELL and // is this an open position? OP_BUY or OP_SELL

OrderValue(cnt,VAL_SYMBOL)=Symbol then // does the instrument match?

{

If OrderValue(cnt,VAL_TYPE)=OP_BUY then // long position opened

{

// we check – maybe, it's already time to close it?

If MacdCurrent>0 and MacdCurrent

MacdPrevious>SignalPrevious and MacdCurrent>(MACDCloseLevel*Point) then

{

CloseOrder(OrderValue(cnt,VAL_TICKET),OrderValue(cnt,VAL_LOTS),Bid,3,Violet);

Exit; // exiting

};

// we check – maybe, we already may or it's already time to set a trailing stop?

If TrailingStop>0 then // the user has put a trailing stop in his settings

{ // so, we set out to check it

If (Bid-OrderValue(cnt,VAL_OPENPRICE))>(Point*TrailingStop) then

{

If OrderValue(cnt,VAL_STOPLOSS)<(Bid-Point*TrailingStop) then

{

ModifyOrder(OrderValue(cnt,VAL_TICKET),OrderValue(cnt,VAL_OPENPRICE),

Bid-Point*TrailingStop,OrderValue(cnt,VAL_TAKEPROFIT),Red);

Exit;

};

};

};

}

else // otherwise it is a short position

{

// we check – maybe, it's already time to close it?

If MacdCurrent<0 and MacdCurrent>SignalCurrent and

MacdPrevious(MACDCloseLevel*Point) then

{

CloseOrder(OrderValue(cnt,VAL_TICKET),OrderValue(cnt,VAL_LOTS),Ask,3,Violet);

Exit; // exiting

};

// we check – maybe, we already may or it's already time to set a trailing stop?

If TrailingStop>0 then // the user has put a trailing stop in his settings

{

// so, we set out to check it

If(OrderValue(cnt,VAL_OPENPRICE)-Ask)>(Point*TrailingStop) then

{

If OrderValue(cnt,VAL_STOPLOSS)=0 or

OrderValue(cnt,VAL_STOPLOSS)>(Ask+Point*TrailingStop) then

{

ModifyOrder(OrderValue(cnt,VAL_TICKET),OrderValue(cnt,VAL_OPENPRICE),

Ask+Point*TrailingStop,OrderValue(cnt,VAL_TAKEPROFIT),Red);

Exit;

};

};

};

};

};

};

// the end.




To complete setting up the Expert Advisor we need only to specify the values of the external variables Lots
= 1, Stop Loss (S/L) = 0 (not used), Take Profit (T/P) = 120 (appropriate for one-hour intervals), Trailing
Stop (T/S) = 30. Of course, you can set your own values. Press the Verify button and, if there isn't any error
message (by the way, you can copy the text from the above programme printout against the grey
background right into the MetaEditor), press the Save button to save the Expert Advisor.

dzonefx

dzonefx
Moderator

Let's take a look at the description given below:

1. Initial data checks
- check the chart, number of bars on the chart
– check the values of external variables: Lots, S/L, T/P, T/S

2. Setting the internal variables for quick data access


3. Checking the trading terminal – is it void? If yes, then:
- checks: availability of funds on the account etc...
- is it possible to take a long position (BUY)?
» open a long position and exit
– is it possible to take a short position (SELL)?
» open a short position and exit
– exiting the Expert Advisor...

4. Control of the positions previously opened in the cycle
- if it is a long position
» should it be closed?
» should the trailing stop be reset?
– if it is a short position
» should it be closed?
» should the trailing stop be reset?
It turned out to be relatively simple, with only 4 main blocks.
Now let's try to generate pieces of code step by step for each section of the structural scheme:

1. Initial data checks
This piece of code usually migrates from one Expert Advisor to another with minor changes – it is a
practically standard block of checks:

If Bars<200 Then Exit; // the chart has less than 200 bars – exit

If TakeProfit<10 Then Exit; // wrong takeprofit parameters

2. Setting the internal variables for quick data access
In the programme code it is very often necessary to access the indicator values or handle the
computed values. To simplify the coding and speed up the access, the data is initially nested within
the internal variables.

MacdCurrent=iMACD(12,26,9,0,MODE_MAIN); // MACD value on the current bar

MacdPrevious=iMACD(12,26,9,1,MODE_MAIN); // MACD value on the previous bar

SignalCurrent=iMACD(12,26,9,0,MODE_SIGNAL); // Signal Line value on the current bar

SignalPrevious=iMACD(12,26,9,1,MODE_SIGNAL);// Signal Line value on the previous bar

MaCurrent=iMA(MATrendPeriod,MODE_EMA,0); // moving average value on the current bar

MaPrevious=iMA(MATrendPeriod,MODE_EMA,1); // moving average value on the previous bar

Now, instead of the monstrous notation of iMACD(12,26,9,MODE_MAIN,0) we can simply write in the
program text MacdCurrent. All the variables used by the Expert Advisor will have to be preliminarily
described, according to the MetaQuotes Language II description. Therefore we insert the description of
these variables at the beginning of the programme:

var: MacdCurrent(0), MacdPrevious(0), SignalCurrent(0), SignalPrevious(0);
var: MaCurrent(0), MaPrevious(0);

MetaQuotes Language II also introduces the concept of additional user-defined variables which may be set
from outside the programme, without any interference with the source source text of the Expert Advisor
programme. This feature allows added flexibility. Variable MATrendPeriod is a user-defined variable of this
very type. So, we insert the description of this variable in the beginning of the programme.
defines: MATrendPeriod(56);

3. Checking the trading terminal – is it void? If yes, then:
In our Expert Advisor we only use the current positions and don't handle the delayed orders.
orders:

If TotalTrades < 1 then // no opened orders identified {

o Checks: availability of funds on the account etc...
Before analyzing the market situation it is advisable to check the status of your account to make
sure that there are free funds for opening a position.
If FreeMargin < 1000 then Exit; // no funds – exit

o is it possible to take a long position (BUY)?
Condition of entry into the long position: MACD is below zero, goes upwards and is crossed by the
Signal Line going downwards. This is how we describe it in MQL II (note that we operate on the
indicator values which were previously saved in the variables):

If MacdCurrent < 0 and MacdCurrent > SignalCurrent and

MacdPrevious < SignalPrevious and // a cross-section exists

Abs(MacdCurrent) > (MACDOpenLevel*Point) and // the indicator plotted a decent 'hillock'

MaCurrent > MaPrevious then // 'bull' trend

{

SetOrder(OP_BUY,Lots,Ask,3,0,Ask+TakeProfit*Point,RED); // executing

Exit; // exiting, since after the execution of a trade

// there is a 10-second trading timeout

};

Above we mentioned the method of additional monitoring of the size of the plotted 'hillocks'.
MACDOpenLevel variable is a user-defined variable which may be changed without interfering with the
programme text, to ensure greater flexibility. In the beginning of the programme we insert a
description of this variable (as well as the description of the variable used below).

defines: MACDOpenLevel(3), MACDCloseLevel(2);
o is it possible to take a short position (SELL)?

Condition of entry of a short position: MACD is above zero, goes downwards and is crossed by the
Signal Line going upwards. The notation is as follows:



If MacdCurrent > 0 and MacdCurrent < SignalCurrent and

MacdPrevious > SignalPrevious and MacdCurrent > (MACDOpenLevel*Point) and

MaCurrent < MaPrevious then

{

SetOrder(OP_SELL,Lots,Bid,3,0,Bid-TakeProfit*Point,RED); // executing

Exit; // exiting

};

Exit; // no new positions opened – just exit

4. Control of the positions previously opened in the cycle
for cnt=1 to TotalTrades

{

if OrderValue(cnt,VAL_TYPE)<=OP_SELL and // is it an open position?

OrderValue(cnt,VAL_SYMBOL)=Symbol then // position from "our" chart?

{

Cnt is the cycle variable which is to be described at the beginning of the programme as follows:

var: Cnt(0);

o if it is a long position:

If OrderValue(cnt,VAL_TYPE)=OP_BUY then // long position opened




{

  •  Should it be closed?


Condition for exiting a long position: MACD is crossed by its Signal Line, MACD being above zero,
going downwards and being crossed by the Signal Line going upwards.

If MacdCurrent > 0 and MacdCurrent < SignalCurrent and
MacdPrevious > SignalPrevious and MacdCurrent > (MACDCloseLevel*Point) then
{
CloseOrder(OrderValue(cnt,VAL_TICKET),OrderValue(cnt,VAL_LOTS),Bid,3,Violet); Exit; // exit
};

  •  should the trailing stop be reset?

We set the trailing stop only in case the position already has a profit exceeding the trailing stop
level in points, and in case the new level of the stop is better than the previous.
If TrailingStop > 0 then // if trailing stops are used

{

If (Bid-OrderValue(cnt,VAL_OPENPRICE))>(Point*TrailingStop) then
{

If OrderValue(cnt,VAL_STOPLOSS)<(Bid-Point*TrailingStop) then

{

ModifyOrder(OrderValue(cnt,VAL_TICKET),OrderValue(cnt,VAL_OPENPRICE),

Bid-Point*TrailingStop,OrderValue(cnt,VAL_TAKEPROFIT),Red);

Exit

};

};

};

o if it is a short position:

else // otherwise it is a short position

{

  •  should it be closed?

Condition for exiting a short position: MACD is crossed by its Signal Line, MACD being below zero,
going upwards and being crossed by the Signal Line going downwards.
If MacdCurrent<0 and MacdCurrent>SignalCurrent and
MacdPrevious(MACDCloseLevel*Point) then
{ \ CloseOrder(OrderValue(cnt,VAL_TICKET),OrderValue(cnt,VAL_LOTS),Ask,3,Violet);
Exit; // exit };


  •  should the trailing stop be reset?

We set the trailing stop only in case the position already has a profit exceeding the trailing stop
level in points, and in case the new level of the stop is better than the previous.
If TrailingStop>0 then // the user has put a trailing stop in his settings
{ // so, we set out to check it

If (OrderValue(cnt,VAL_OPENPRICE)-Ask)>(Point*TrailingStop) then

{

If OrderValue(cnt,VAL_STOPLOSS)=0 or

OrderValue(cnt,VAL_STOPLOSS)>(Ask+Point*TrailingStop) then

{

ModifyOrder(OrderValue(cnt,VAL_TICKET),OrderValue(cnt,VAL_OPENPRICE),

Ask+Point*TrailingStop,OrderValue(cnt,VAL_TAKEPROFIT),Red)

Exit;




};

};

};
// end. Closing all the curly bracket which remain open

};

};

};
So, following this step-by-step procedure, we have written our Expert Advisor...

25Technical - Expert Advisors Empty Step-By-Step Creation of Simple Expert Tue May 12, 2015 10:37 pm

dzonefx

dzonefx
Moderator

Let's try to create an Expert Advisor running on the standard MACD indicator, with the profit-taking
capability, supporting trailing stops and using most safeguards for secure operation. In the example given
below the trade is done by opening and controlling a single position.

Trading principles:
• Long (BUY) entry – MACD indicator is below zero, goes upwards and is crossed by the "Signal
Line" going downwards.
[You must be registered and logged in to see this image.]
• Short (SELL) entry – MACD indicator is above zero, goes downwards and is crossed by the
"Signal Line" going upwards.
[You must be registered and logged in to see this image.]
• Long exit – by execution of the take profit limit, by execution of the trailing stop or when MACD
crosses its "Signal Line" (MACD is above zero, goes downwards and is crossed by the "Signal Line" going
upwards).
• Short exit – by execution of the take profit limit, by execution of the trailing stop or when MACD
crosses its "Signal Line" (MACD is below zero, goes upwards and is crossed by the "Signal Line" going
downwards).

Important note: to exclude insignificant changes of the MACD indicator (small 'hillocks' on the chart) from our analysis, we introduce an additional measure of controlling the size of the plotted 'hillocks' as follows: the indicator size should be at least 5 units of the minimum price (5*Point, which for USD/CHF = 0.0005 and for USD/JPY = 0.05).
[You must be registered and logged in to see this image.]

Step I: Writing the Expert Advisor description
[You must be registered and logged in to see this image.]
Point the mouse pointer on the Expert Advisors section of the "Navigator" window, press the right button of the mouse and select "Create a new Expert" command in the appearing menu. The "Initializing Wisard" of the Expert Advisor will ask you to enter certain data. In the appearing window we write the name (Name) of the
Expert Advisor – "MACD Sample", the author (Author) – indicate your name, the link (Link) – a link to your website, in the notes (Notes) – "Test example of an MACD-based Expert Advisor".

Step II: Creating the primary structure of the programme
Code of the test Expert Advisor will only occupy several pages, but even such volume is often difficult to
grasp, especially in view of the fact that we are not professional programmers – otherwise we wouldn't need this description at all, right?



Last edited by dzonefx on Tue May 12, 2015 11:15 pm; edited 1 time in total

Sponsored content



Back to top  Message [Page 1 of 2]

Go to page : 1, 2  Next

Permissions in this forum:
You cannot reply to topics in this forum