Вы находитесь на странице: 1из 168

MegaTrader 1.

User guide
Table of Contents
MegaTrader 1.4 ..................................................................................................................................... 5
Overview .............................................................................................................................................. 6
Getting started ..................................................................................................................................... 7
Installation .......................................................................................................................................... 8
Setting up MetaTrader ...................................................................................................................... 9
Setting up SaxoTrader .................................................................................................................... 14
Program setting up .......................................................................................................................... 15
Working with multiple Megatrader instances ................................................................................... 21
Launching Megatrader ..................................................................................................................... 22
Program interface .............................................................................................................................. 23
Main menu ....................................................................................................................................... 25
File ................................................................................................................................................. 26
Connection .................................................................................................................................... 28
Chart .............................................................................................................................................. 30
Script ............................................................................................................................................. 32
Settings ......................................................................................................................................... 33
Help ............................................................................................................................................... 34
Chart ................................................................................................................................................ 35
Trade panel ..................................................................................................................................... 37
Trading tab .................................................................................................................................... 38
Messages tab ................................................................................................................................ 40
Settings ............................................................................................................................................ 41
Common settings .......................................................................................................................... 43
MetaTrader settings ...................................................................................................................... 45
Composite instrument settings ........................................................................................................ 46
Instruments tab ............................................................................................................................. 48
Additional settings ......................................................................................................................... 52
MetaTrader instrument settings ....................................................................................................... 53
Common settings .......................................................................................................................... 54
Additional settings ......................................................................................................................... 56
SaxoTrader instrument settings ...................................................................................................... 57
Common settings .......................................................................................................................... 58
Additional settings ......................................................................................................................... 59
QuoteSpeed instrument settings ..................................................................................................... 60
Common settings .......................................................................................................................... 61
Additional settings ......................................................................................................................... 62
Script editor ..................................................................................................................................... 63
Toolbar ........................................................................................................................................... 64
Menu ............................................................................................................................................. 66
File .............................................................................................................................................. 67
Edit .............................................................................................................................................. 68
Global variables ............................................................................................................................... 69
Script backtester .............................................................................................................................. 71
Settings tab ................................................................................................................................... 73
Report tab ..................................................................................................................................... 75
Transactions tab ............................................................................................................................ 76
Balance chart tab .......................................................................................................................... 77
Indicator parameters ....................................................................................................................... 78
License management ...................................................................................................................... 80
Indicators ........................................................................................................................................... 81
Mean Price ...................................................................................................................................... 82
Moving Average .............................................................................................................................. 83
Exponential Moving Average ........................................................................................................... 84
Bollinger Bands ............................................................................................................................... 85
Scripting language ............................................................................................................................. 86
Language description ...................................................................................................................... 87
Language elements ....................................................................................................................... 88
Operations and expressions ......................................................................................................... 90
Statements .................................................................................................................................... 92
Data types ..................................................................................................................................... 95
Variables ........................................................................................................................................ 97
Functions ....................................................................................................................................... 99
Program execution ...................................................................................................................... 100
Built-in functions ............................................................................................................................ 101
Type conversion .......................................................................................................................... 102
Integer ....................................................................................................................................... 103
Float .......................................................................................................................................... 104
String ......................................................................................................................................... 105
Date and time ............................................................................................................................. 106
DataTimeToStr .......................................................................................................................... 107
DateToStr .................................................................................................................................. 108
TimeToStr .................................................................................................................................. 109
StrToDateTime .......................................................................................................................... 110
StrToDate .................................................................................................................................. 111
StrToTime .................................................................................................................................. 112
Day ............................................................................................................................................ 113
Month ........................................................................................................................................ 114
Year ........................................................................................................................................... 115
Hour .......................................................................................................................................... 116
Minute ....................................................................................................................................... 117
Sec ............................................................................................................................................ 118
MilliSec ...................................................................................................................................... 119
DayOfWeek ............................................................................................................................... 120
Global variables .......................................................................................................................... 121
GetGlobVar ................................................................................................................................ 122
SetGlobVar ................................................................................................................................ 123
Mathematics ................................................................................................................................ 124
Abs ............................................................................................................................................ 125
Ceil ............................................................................................................................................ 126
Floor .......................................................................................................................................... 127
Sign ........................................................................................................................................... 128
Max ........................................................................................................................................... 129
Min ............................................................................................................................................ 130
Pow ........................................................................................................................................... 131
Sqrt ............................................................................................................................................ 132
Data ............................................................................................................................................. 133
Bid ............................................................................................................................................. 134
Offer .......................................................................................................................................... 135
SymbolBid ................................................................................................................................. 136
SymbolOffer .............................................................................................................................. 137
SymbolLastChange ................................................................................................................... 138
Chart data functions .................................................................................................................... 139
PointCount ................................................................................................................................ 140
Point .......................................................................................................................................... 141
SymbolBidPoint ......................................................................................................................... 142
SymbolOfferPoint ...................................................................................................................... 143
DateTime ................................................................................................................................... 144
Index ......................................................................................................................................... 145
Shift ........................................................................................................................................... 146
Trading functions ......................................................................................................................... 147
Balance ..................................................................................................................................... 148
Disbalance ................................................................................................................................ 149
TradeQnty ................................................................................................................................. 150
GetMaxQnty .............................................................................................................................. 151
SetMaxQnty .............................................................................................................................. 152
Buy ............................................................................................................................................ 153
Sell ............................................................................................................................................ 154
Close ......................................................................................................................................... 155
Information output ....................................................................................................................... 156
Message .................................................................................................................................... 157
Alert ........................................................................................................................................... 158
FileClear .................................................................................................................................... 159
FileWrite .................................................................................................................................... 160
System functions ......................................................................................................................... 161
CurrentDateTime ....................................................................................................................... 162
GetTickCount ............................................................................................................................ 163
Script examples ............................................................................................................................. 164
Additional modules .......................................................................................................................... 167
SaxoExporter ................................................................................................................................. 168
MegaTrader 1.4

USER GUIDE
Overview

MegaTrader 1.4 is a software complex for spread and basket trading automation, including pair trading and
arbitrage strategies. MegaTrader 1.4's functionality covers all the aspects of spread trading and uncovers all its
advantages, from spread creation and charting to automatic strategy backtesting and trading on live accounts.
One of game-breaker features of MegaTrader 1.4 is the ability to create spreads and baskets of any complexity,
combining different instruments from a majority of trading platforms including the popular Metatrader 4.

Key features:

Creating spreads of any complexity

Simultaneous work with MetaTrader 4, QuoteSpeed and SaxoTrader (can also be


connected to Quik - russian equities market platform) platforms with the possibility of
combining instruments from different terminals provides a bunch of opportunities:

Cross-broker Forex arbitrage;


Latency Forex arbitrage (MetaTrader to MetaTrader or SaxoTrader to
MetaTrader, one-legged and two-legged);
Spread trading (pair trading) between ANY instruments available on ANY
MetaTrader 4 broker (a lot of variations);
Basket trading on Forex and derivatives market;
and many others.

Spread charting with the possibility to apply basic integrated indicators (moving
averages, Bollinger bands, etc.)
One-click buying/selling of spread.

Creation of automated trading systems using an integrated scripting language

Backtesting strategies on historical data.

Ability to backfill orders with trade delays during backtesting to emulate real market
conditions

How does the program work?

Megatrader can receive quotes from any combination of MetaTrader 4, Quik, QuoteSpeed or SaxoTrader
terminals. Then according to entered spread parameters it automatically calculates and charts the spread in real
time. When you need to buy or sell spread, the program sends orders to appropriate trading terminals, where
they are executed according to their weight in spread (lotsizes are calculated automatically). So, one can just
analyze synthetic composite instrument like its an individual one: look at the chart, buy or sell the whole basket,
while Megatrader does all the needed calculations and cross-program communications.
Getting started
Installation

To install the program you should first download the setup file and run it. Next, you will need to choose the
installation directory and then follow the installer instructions.

If you want to run multiple instances of the program, you will need to install each instance in a separate directory
(see Working with multiple Megatrader instances).

By default, installer will create a "Start" menu group "MegaTrader", with which you can launch the program, open
the help file, and delete the program from your computer. In addition, the program can be run directly from the
installation directory. To do this, run a file called "MegaTrader 1.4.exe".

Remark. You cannot run two copies of the program at the same time from the same directory. To run multiple
instances of the program, you must install the appropriate number of copies in different directories.
Setting up MetaTrader

For MegaTrader 1.4 to exchange data with and send trade orders to MetaTrader 4, the following actions must be
performed:

Install the MegaTraderExchange 1.2 EA in MT4.


Set the MetaTrader 4 terminal up.
Launch the MegaTraderExchange 1.2 EA.

Installing the expert advisor

MegaTraderExchange 1.2 EA was developed to provide a data exchange channel between MegaTrader 1.4 and
MetaTrader 4. EA file is called "MegaTraderExchange 1.2.ex4" and is located in MegaTrader 1.4's installation
directory. You should place the file into "experts" folder of Metatrader 4 directory.

If done correctly, MegaTraderExchange 1.2 should appear in the "Navigator" tab:

Setting up MetaTrader 4

First open settings window by going to "Tools > Options":

In the appearing window choose the "Experts" tab, then you should check "Enable expert advisors", "Allow live
trading", "Allow DLL imports", "Allow external experts imports" and turn "Ask manual confirmation" and "Confirm
DLL functions calls" off:
Also, it would make terminal faster and lessen internet traffic consumption if symbols that are not used were
removed from Market Watch window.

To set up symbols list right-click on the "Market Watch" and in the resulting menu choose "Hide all":
As a result,all symbols except those with open charts will dissapear. Now only necessary symbols can be added.
From the "Market Watch" menu "Symbols" should be chosen:

A window with a list of available symbols, divided into groups, appears. To add a symbol to the list of instruments
that need to get quotes, just select the symbol and click "Show" or simply double-click it in the list:

Running advisor
To start EA it should be attached to any chart. To do this, just drag the MegaTraderExchange 1.1 from the
"Navigator" tab on any open schedule. In this case, a window appears expert special settings, two tabs:
"General" and "Inputs".

On the "Common" tab, make sure that the "Positions" are set to "Long & Short", check the "Allow live trading",
"Allow DLL imports", "Allow external experts imports" to be turned on and flags "Ask manual confirmation" and
"Confirm DLL functions calls" off:

"Inputs" tab contains expert advisor's settings:

"RestartTerminal" - this parameter specifies if the EA should restart Metatrader in the case of error. It is a well
known issue with Metatrader 4 that it does not recover correctly after disconnecting from the server or other
errors. The only solution in this situation is to restart the terminal. If set to true, in the event of such failure, the
terminal will be automatically restarted.

"ModifyOrders" - this parameter specifies method of setting SL and TP levels. When using a broker with Market
Execution (most ECN/STP brokers), order should first be placed without TP and SL, then the values are sent
with an order modification request (OrderModify function). So you should better turn it on if on a ECN broker and
using TP and SL.

After configuring the advisor and clicking "Ok" it will be attached to the chart. In the upper-right corner a smiley
with the name of EA should appear:

Make sure that "Expert advisors" is turned on on the toolbar, if turned off click it to turn it on:

If everything is set up correctly, the smiley icon will smile, otherwise it will be a sad smiley.
Setting up SaxoTrader

SaxoTrader does not support any means of direct quotes export like MetaTrader, so we had to develop a special
module, SaxoExporter, which gets quotes directly from Saxotraders Forex Orders and "Futures Orders"
windows. So, all the pairs that are exported from SaxoTrader should have a "Futures Orders" or Forex Orders
window opened:
Program setting up

Standard configuration of the program includes two steps:

General software set-up.


Spread creation

Note. This section covers only basic settings required for software's correct operation. Detailed description of
all program settings can be found in sections Main settings window, Composite instrument settings window,
MetaTrader instrument window and SaxoTrader instrument window.

1. Main settings

Common settings can be changed in Main settings window, you can get here by going "Settings > Main settings".

Common Tab of Main settings shows the parameters to be changed:

These parameters can basically be left default if needed otherwise. You can read about each parameter's
function here.

Metatrader settings, if needed, are set in the MetaTrader tab:


A unique ID number of 0 to 19 should be set for each instance of MegaTrader 1.4 working with Metatrader 4 in
the "Terminal ID" tab (more information here).

2. Spread creation.

You can create a spread symbol in Composite instrument settings, going to "Settings > Composite instrument
settings". On Instruments Tab you can see two lists of instruments. In the left list positive symbols (they are
calculated with a + sign in spread) are listed, while negative symbols, calculated with a minus sign, are in the
right list:
You can edit the instruments making the spread using the "Add", "Delete" and "Edit" buttons.

When adding a symbol to a composite instrument you will first be prompted with a terminal (Quik, MetaTrader,
SaxoTrader or QuoteSpeed) selection window:

Then, depending of your choice, MetaTrader instrument settings, SaxoTrader instrument settings or QuoteSpeed
instrument settings window will appear for further setting up.

If Metatrader was chosen, MetaTrader instrument settings window appears:


Those are mandatory fields when adding a Metatrader symbol:

"Account" - your account number in MetaTrader (can usually be found in Metatrader's caption).
"Instrument" - instrument name in Metatrader (exactly as is, with suffixes/prefixes, e.g. EURUSD.arm or
i_EURUSD).
"Weight" - weight coefficient for spread calculation.
"Lots in spread unit" - a parameter that determines the actual number of lots that will be traded when buying
or selling one unit of the spread.

Note. Detailed description of all settings can be found in section MetaTrader instrument settings.

SaxoTrader's symbols set up is made in SaxoTrader instrument settings:

Mandatory fields when adding a SaxoTrader symbol are:

"Instrument" - instrument name in SaxoTrader (if Saxo has EUR/USD, you should write EURUSD without
slash).
"Weight" - weight coefficient for spread calculation.

Note. Detailed description of all settings can be found in sectionSaxoTrader instrument settings.

If QuoteSpeed symbol is going to be added, there go QuoteSpeed instrument settings:


Mandatory fields for QuoteSpeed:

"Instrument" - instrument name in QuoteSpeed.


"Weight" - weight coefficient for spread calculation.
"DDE Bid code" - DDE code for Bid price (is as follows .
"DDE Ask code" - DDE (Ask) QuoteSpeed.

Note. Detailed description of all settings can be found in section QuoteSpeed instrument settings.

For software to work correctly trading time should be set. It can be set Additional Composite instrument settings
by changing the "Trading time" parameter:

When trading Forex and Futures time should best be set 00:00:00 23:59:59. For stock trading, trade session
time is better set. If your trading strategy operates in different time "brackets", you should set them (please take
the GMT time difference set in each composite instrument Additional settings into consideration!).
Working with multiple Megatrader instances

One copy of MegaTrader 1.4 can simultaneously work with only one spread, with its parameters set in composite
instrument options. To be able to simultaneously trade multiple spreads, you can run multiple instances
simultaneously, each configured to work with any spread. To work correctly with multiple instances of the
program, observe the following rules:

1. Each copy must be installed in a separate directory.

2. When working with MetaTrader it is required that each instance has been assigned a unique ID-number (0 to
19) (see "Terminal ID" Main settings\Metatrader).
Launching Megatrader

Depending on terminals used with MegaTrader 1.4, following steps to software launch can be mentioned:

System launch when working with MetaTrader.


System launch when working with SaxoTrader.
System launch when working with QuoteSpeed.

In the case of using multiple terminals combining all necessary for each terminal steps is enough.

Working with MetaTrader terminals

Following steps are required:

1. Launch MegaTrader 1.4 and all the necessary MetaTrader terminals.

Note. Please make sure that MegaTraderExchange 1.2 expert advisor is started in all Metatrader terminals
(Setting up MetaTrader).

2. Establish MegaTrader 1.4 connection to MetaTrader. To do that, go to "Connection > Connect to MetaTrader".

Working with SaxoTrader

Following steps are required:

1. Launch MegaTrader 1.4 and SaxoTrader terminal.

2. Every symbol used should have an Orders window opened in SaxoTrader (Setting up SaxoTrader).

3. Establish MegaTrader 1.4 connection to SaxoTrader. To do that, go to "Connection > Connect to SaxoTrader".

Working with QuoteSpeed

Following steps are required:

1. Launch MegaTrader 1.4 and QuoteSpeed.

2. Establish MegaTrader 1.4 connection to QuoteSpeed. To do that, go to "Connection > Connect to


QuoteSpeed".
Program interface

MegaTrader's user interface consists of the following:

Main menu. All the basic commands and functions can be found here, except for the trade execution and
management functions.
Chart. The spread chart represents the spread's movement in time. Also, indicators can be displayed on the
chart.
Trade panel. Trade panel is a multifuntional trading execution and management tab where trading
operations can be performed and program logs can be viewed.

There are also auxilliary windows that can be opened by choosing them in the main menu.:

Settings window. Here MegaTrader's common settings can be changed (chart display settings, data archive
size etc.) and MetaTrader terminal settings.
Composite instrument settings. Here user can form the spread from several trading instruments and change
parameters for each instrument.
MetaTrader instrument settings, SaxoTrader instrument settings QuoteSpeed instrument settings. These
windows are used to change the parameters of each instrument in the spread.
Script editor. User can create and edit scripts - trading robots on a special built-in programming language
that enables the development of automated trading systems, with the help of script editor.
Global variables. Global variables window allow creating, changing and removing global variables. Global
variables allow storing persistent information (data is not lost between script and Megatrader launches).
Script backtester. With the help of script backtester user can assess his trading script for profitability on
historical data. In the process, backtester executes the script on each tick and emulates trading results.
Indicator parameters. Here user can change indicators' parameters. The window appears everytime a new
indicator is added to the spread chart or when changing an indicator's parameters.
License management. User can purchase, install or delete a license from here.
Main menu

All program's functions and commands are in the main menu, except of those.

File

File menu group.

Connection

Connection menu group.

Chart

Chart menu group.

Script

Script menu group.

Settings

Settings menu group.

Help

Help menu group.


File

Load settings

Loads settings from file.

Note. When saving or loading settings file its location is automatically storen within the program. After
this operation, program will automatically load settings from it upon its launch and save settings on exit.

Save settings

Save settings to file.

Note. When saving or loading settings file its location is automatically storen within the program. After
this operation, program will automatically load settings from it upon its launch and save settings on exit.

Clear data

Clears tick data history in the program (current program settings are not changed).

Load data

Loads tick history data from file (current program settings are not changed).

Note. When saving or loading settings file its location is automatically storen within the program. After
this operation, program will automatically load settings from it upon its launch and save settings on exit.
Save data

Saves tick history data to a file.

Note. When saving or loading settings file its location is automatically storen within the program. After
this operation, program will automatically load settings from it upon its launch and save settings on exit.

Exit

Quits the program.

Current settings and data archive are automatically saved on exit.


Connection

Connect to Quik

Connects to Quik. Orders can be sent to Quik only if the connection is active (Quik should have external
transactions support enabled or it will be impossible to establish connection).

Disconnect from Quik

Disconnects from Quik. While disconnected it's impossible to send orders to Quik, although receiving
quotes is still possible.

Connect to Meta Trader

Connects to MetaTrader. After establishing the connection program will be able to get quotes from
MetaTrader and send trade orders (MegaTraderExchange 1.2 should be running in MetaTrader).

Disconnect from MetaTrader

Disconnects from MetaTrader. After disconnecting getting quotes and sending orders will be impossible.

Connect to SaxoTrader

Connects to SaxoTrader. After establishing the connection program will be able to get quotes from
SaxoTrader.

SaxoExporter is automatically launched by MegaTrader when clicking "Connection > Connect to


SaxoTrader". Module's icon should appear in system tray when it's running.
Note. Auxiliary module SaxoExporter is developed to allow quotes import from SaxoTrader terminal to
MegaTrader. As SaxoTrader does not have any quote export functions, they are being read directly from
the program interface, or rather - "Forex orders" and "Futures orders" modal windows. So, for quote
export to be possible from SaxoTrader, it is necessary to have the corresponding windows opened for all
the instruments you plan to work with.

Disconnect from SaxoTrader

Disconnects from SaxoTrader. After disconnecting Megatrader will stop getting quotes.

Connect to QuoteSpeed

Connects to QuoteSpeed. After establishing the connection program will be able to get quotes from
QuoteSpeed.

Disconnect from QuoteSpeed

Disconnects from QuoteSpeed. After disconnecting Megatrader will stop getting quotes.
Chart

Add chart

Add an indicator to the spread chart. When this option is selected, a list of all available indicators
appears. After selecting to add an indicator on the screen, Indicator parameters window will appear to
set its parameters.

Chart parameters

This menu allows user to change indicator settings. When selecting this option, a list of all currently used
indicators will appear, among which user chooses. After selecting, Indicator parameters window will
appear.

Remove chart

Removes an indicator from the chart. When selecting this option, a list of all currently used indicators will
appear, among which user chooses the indicator to delete. Along with the indicator itself all indicators it
was the data source for will also be deleted.

Cursor

Changes chart cursor mode to "Cursor".

Magnifier

Changes chart cursor mode to "Magnifier". It becomes possible to change chart zoom using the mouse
in this mode (Chart).
Zoom in

Zooms the chart in.

Zoom out

Zooms the chart out.

Show all

Shows all the available data on the chart.


Script

Script editor

Opens Script editor window. User can create and edit scripts - trading robots on a special built-in
programming language that enables the development of automated trading systems, with the help of
script editor.

Global variables

Opens Global variables window. Global variables allow storing persistent information (data is not lost
between script and Megatrader launches).

Script backtester

Opens Script backtester window. With the help of script backtester user can assess his trading script for
profitability on historical data. In the process, backtester executes the script on each tick and emulates
trading results.

Run script

Starts script execution. If launched, script will execute and calculate on each tick.

Stop script

Stops script execution.


Settings

Settings

Opens Settings window. Here user can change general program settings.

Composite instrument settings

Open Composite instrument settings window. Here user can form the spread from several trading
instruments and change parameters for each instrument.

Language

Changing MegaTrader's interface language.


Help

Help

Opens help file.

License

Opens License management window. User can purchase, install or delete a license from here.
Chart

Spread chart displays the spread's price dynamics in time. The chart always shows two lines: red line is Offer
(selling at that price) line and green line is Bid (buying at that price) line. Charts also can have an unlimited
number of indicators applied.

Note. In Common settings two parameters: "Maximum ticks on chart" "Maximum ticks in data archive" can be
set. These options allow controlling the data shown on the chart and data stored on HDD.

Chart tools

Chart scaling
Chart scaling can be achieved either via main menu or with the help of your mouse.

Chart scaling can be done with the help of "Zoom in" and "Zoom out" Chart menu commands. Zooming can be
cancelled via "Show all" command.

Zooming with mouse can be done with "Magnifier" chart mode turned on (Chart menu). To zoom, you should
select the zooming zone with your mouse pressed down, moving the crosshair down and right. After releasing
mouse the chart will be zoomed to the selected area. To reset the zooming, press the left mouse button
anywhere on the plot, and while holding the button down, move the cursor left and up. Once the button is
released, the scale will be reset.

Chart scrolling and auto-scrolling


Scrolling is offsetting data displayed to the left or right. Scrolling may be realized using either the scroll bar graph
located beneath the window , or using the mouse. To scroll the chart by using the mouse , press the right mouse
button and, move the cursor in the direction needed while keeping the button pressed down.

Auto-scrolling is automatic data offsetting on the chart when new ticks arrive. It will work if chart zooming is
turned on and the last tick can be seen on the chart. In this case chart is automatically scrolled upon receiving a
new tick. If zoom is turned off (all available data is shown), chart will be automatically rescaled to fit all data each
tick.

Indicators
In addition to Bid and Offer price lines an unlimited number of indicators can be added to a chart. Adding,
changing parameters and deleting indicators is managed with "Add chart", "Delete chart" "Chart parameters"
commands of Chart menu group.

Also, indicator parameters can be changed by pressing right mouse button on an indicator line on the chart.
Context menu appearing consists of two options:
"Parameters" - Indicator parameters.
"Delete" - deletes an indicator from the chart.
Trade panel

Trade panel allows user to view program messages and trade manually, as well as monitor current trading
statistics.

Trading tab

Trading buttons and elements are concentrated here (Trading tab).

Messages tab

This tab shows messages generated by the program (Messages tab).


Trading tab

Balance

Balance is the current market position. Balance value shows a balanced number of units spread in
market position, and the sign of balance is the position's direction: positive - buying (long), negative -
selling, or short (for example, the balance of 2 means having 2 units of spread in long position, if it is -2 -
short position of the corresponding size ).

Note. Only balanced spread units number is shown in Balance tab. Unbalanced units are counted on
"Disbalance" tab.

Disbalance

The disbalance shows the unbalanced number of spread units in current position. The disbalance is the
result of portfolio lacking positions on some instruments. The disbalance shows the number of spread
units to be added to the current position balance if missing positions will be opened (long/short), and
imbalance sign is the direction of potential position added.

Bid

Current spread's best Bid price (spread can be sold at that price) is shown.

Offer

Current spread's best Offer price (spread can be bought at that price) is shown.

Buy button
Buys spread unit/units (quantity is set by "Quantity" parameter).

Sell button

Sells spread unit/units (quantity is set by "Quantity" parameter).

Close button

Closes all opened positions on click.

Restore balance button

Pressing this button will get rid of the imbalance by buying/selling missing instruments. As a result, if the
operation is successful, the unbalanced number of units of the spread will be balanced and added to the
current balance.

Quantity

Here number of spread units to be bought/sold in each buy/sell order can be changed.

Maximum quantity

This option sets a limit on maximum number of spread units in open positions (so the program can't
buy or sell spread units over this number). Restrictions imposed by this parameter apply to both trades
performed manually and ones performed by a script.
Messages tab

"Messages" tab records information about events that occurred during program execution. Event log is stored in
"MegaTrader.log", located in the same folder where the program is.
Settings

In Settings window, general settings (chart parameters, data file size, etc.) and settings for interaction with
MetaTrader terminal are located.

You can get here by pressing "Settings" of Settings menu group.

Common

Tab where common system settings are located. (Common settings).

Quik

Quik settings are located here.

MetaTrader

Tab with MetaTrader interaction settings.(MetaTrader settings).

Ok

Closes the window saving and applying the changes.


Cancel

Closing the window without saving the changes.


Common settings

Chart update

Selects the charting update period

"When new tick arrives" - chart will be updated with each tick update arriving to the program
"Every n seconds" - chart will be updated each specified number of seconds (ie. 1, 60, 3600 -
interval of your choice).

Selecting "When new tick arrives" may boggle system performance when tick stream is tight and fast.
Thus, in order to save resources, when the refresh rate schedule is not important (for example, when
the system is trading in automatic mode), as well as on slower computers, it is always recommended to
choose "every n seconds" update period.

Maximal ticks on chart

Specifies the maximum number of ticks that are displayed on chart. This parameter strongly influences
the speed of chart rendering and updating, so there is no need to set it too large (ie. 10000 ticks is more
than enough in most cases).

Maximal ticks in data archive

Specifies maximum number of ticks that are saved to data archive. Each time program is closed it saves
no more than specified number of ticks into the achive file.

Last order number


Displays the counter of transactions sent to MetaTrader terminal. Transaction count is used for statistics
of received and filled orders, changing it does not change the way program behaves.
MetaTrader settings

Terminal ID

Current MegaTrader's instance ID. Up to 20 MegaTrader instances can be working with multiple
MetaTrader terminals simultaneously. A unique ID number of 0 to 19 should be set for each instance of
MegaTrader 1.4 working with MetaTrader 4.
Composite instrument settings

Here the intrument list a spread consists of can be created and edited.

You can get here by pressing "Composite instrument settings" of Settings menu group.

Instruments tab

Instrument list settings tab (Instruments tab).

Additional tab

Additional spread settings tab (Additional settings).

OK button

Closes and saves the changes.

Close button
Closes without saving the changes.
Instruments tab

Positive spread side list

List for instruments included in the positive part of composite symbol (they are used in the formula with
the "+" sign.

Move upper

Moves selected instrument one position upper.


Move lower

Moves selected instrument one position lower.

Add

Adds a new instrument to the list. First you should choose a terminal from which the instrument will be
imported.

Then, depending on your choice, MetaTrader instrument settings window, SaxoTrader instrument
settings window or QuoteSpeed instrument settings window appear, where you can thoroughly set up the
instrument.

Delete

Deletes an instrument from the list.

Edit

Edits selected instrument. Depending on the terminal, a corresponding Instrument settings window will
appear.

Negative spread side list


List for instruments included in the negative part of composite symbol (they are used in the formula with
the "-" sign.

Move upper

Moves selected instrument one position upper.

Move lower

Moves selected instrument one position lower.

Add

Adds a new instrument to the list. First you should choose a terminal from which the instrument will be
imported.

Then, depending on your choice, MetaTrader instrument settings window, SaxoTrader instrument
settings window or QuoteSpeed instrument settings window appear, where you can thoroughly set up the
instrument.

Delete
Deletes an instrument from the list.

Edit

Edits selected instrument. Depending on the terminal, a corresponding Instrument settings window will
appear.

Move to the right list

Transfers an instrument to the right list.

Move to the left list

Transfers an instrument to the left list.


Additional settings

Trading time

Specifies time interval during which the program will collect data and trade.
MetaTrader instrument settings

This window appears when you add or edit MetaTrader instruments in Composite instrument settings.

Common settings

Common instrument settings tab (Common settings tab).

Additional settings

Additional instrument settings tab (Additional settings tab).

OK button

Closes the window and saves the changes.

Close button

Closes the window without saving the changes.


Common settings

Account number

MetaTrader account number (can be often seen in the MetaTrader's title).

Instrument code

Instrument name in MetaTrader. Should be mentioned as seen in MetaTrader, with suffixes and prefixes.

Weight in spread

Multiplication factor for an instrument in spread

This option only affects the spread calculation, the actual number of lots that will be bought or sold is set
by the "lots in spread unit" parameter.

Lots in spread unit

Lots that will be traded when buying or selling one unit of the spread.

Execute first

Turning the "Execute first" option on means that program will try to fill the order by the price at the
moment of sending the order (taking the preset slippage amount in consideration). If the order gets filled
by the specified price, then orders will be sent to other instruments in the spread, if not (if price exceeds
one of the slippage levels) - no other instruments will be traded.

The use of this option, in some cases, can significantly reduce the slippage, because it ensures that at
least one instrument transaction will be implemented a fair price.
Slippage

Admitted slippage value for opening and closing orders.


Additional settings

Time source

Specifies the timestamp source for incoming quotes:

"Terminal" - trading terminal's time (MetaTrader) will be used.


"Computes" - local computer's time will be used.

If there are several data sources, "Computer" is best used, because it helps avoiding time lagging
problems in different terminals. This happens because time in some terminals (even without taking GMT
difference into calculation) can lag or lead other terminals' time by several seconds. If "Computer" time
source is chosen, quotes timestamp will be the actual PC's time which will eliminate the lagging problem
and calculate the spread correctly.

Time difference

Specifies quotes timestamp shift in hours.

Accumulate data

If this option is turned on, tick data for the selected instrument will be saved, which will allow individual
backtesting in it. (It will become available in Settings tab of Script backtester.

These options allow you to set stop-loss and take profit levels for each order placed in MetaTrader. "Take
Profit" specifies the distance from opening price (in profit direction) where profit target will be placed.
"Stop-loss" sets the distance from opening (in losing direction), where a stop-loss will be placed. A zero
value of a parameter means that either SL or TP will not be placed.
SaxoTrader instrument settings

This window appears when you add or edit SaxoTrader instruments in Composite instrument settings.

Common settings

Common instrument settings tab (Common settings tab).

Additional settings

Additional instrument settings tab (Additional settings tab).

OK button

Closes the window and saves the changes.

Close button

Closes the window without saving the changes.


Common settings

Instrument code

Instrument name in SaxoTrader.

Weight in spread

Multiplication factor for an instrument in spread


Additional settings

Time source

Specifies the timestamp source for incoming quotes:

"Terminal" - trading terminal's time (MetaTrader) will be used.


"Computes" - local computer's time will be used.

If there are several data sources, "Computer" is best used, because it helps avoiding time lagging problems
in different terminals. This happens because time in some terminals (even without taking GMT difference
into calculation) can lag or lead other terminals' time by several seconds. If "Computer" time source is
chosen, quotes timestamp will be the actual PC's time which will eliminate the lagging problem and calculate
the spread correctly.

Time difference

Specifies quotes timestamp shift in hours.

Accumulate data

If this option is turned on, tick data for the selected instrument will be saved, which will allow individual
backtesting in it. (It will become available in Settings tab of Script backtester.
QuoteSpeed instrument settings

This window appears when you add or edit QuoteSpeed instruments in Composite instrument settings.

Common settings

Common instrument settings tab (Common settings tab).

Additional settings

Additional instrument settings tab (Additional settings tab).

OK button

Closes the window and saves the changes.

Close button

Closes the window without saving the changes.


Common settings

Instrument

Instrument's name in QuoteSpeed.

Weight

Multiplication factor for an instrument in spread

DDE Bid code

Current best Bid price DDE code in QuoteSpeed.

DDE Ask code

Current best Ask (Offer) price DDE code in QuoteSpeed.


Additional settings

Time source

Specifies the timestamp source for incoming quotes:

"Terminal" - trading terminal's time (MetaTrader) will be used.


"Computes" - local computer's time will be used.

If there are several data sources, "Computer" is best used, because it helps avoiding time lagging problems
in different terminals. This happens because time in some terminals (even without taking GMT difference
into calculation) can lag or lead other terminals' time by several seconds. If "Computer" time source is
chosen, quotes timestamp will be the actual PC's time which will eliminate the lagging problem and calculate
the spread correctly.

Time difference

Specifies quotes timestamp shift in hours.

Accumulate data

If this option is turned on, tick data for the selected instrument will be saved, which will allow individual
backtesting in it. (It will become available in Settings tab of Script backtester.
Script editor

Script editor allows to create and edit scripts - automated trading systems written in a special built-in
programming language.

This window appears when "Script editor" command is launched from the Script menu group.

Menu

Code redactor's main menu.

Toolbar

Code redactor's toolbar.


Toolbar

Toolbar provides user with buttons for most commonly used operations, such as opening a file, copying and
pasting text etc.

New script

Creates new script (a blank file).

Open script

Loads script from a file.

Save script

Saves script in a file with current name.

Undo

Reverts the last change done to the script (equivalent to CTRL+Z hotkey).

Cut

Cuts selected text out of the script editor and puts it into copy buffer (equivalent to CTRL+X hotkey).

Copy

Copies selected text and puts it into copy buffer (equivalent to CTRL+C hotkey).

Paste
Pastes text from copy buffer (equivalent to CTRL+V hotkey).
Menu

File

File menu group.

Edit

Edit menu group.


File

New

Creates new script (a blank file).

Open

Loads script from a file.

Save

Saves script in a file with current name.

Save as...

Saves script in a file with another name (file saving window will appear).

Exit

Exits script editor.


Edit

Undo

Reverts the last change done to the script (equivalent to CTRL+Z hotkey).

Cut

Cuts selected text out of the script editor and puts it into copy buffer (equivalent to CTRL+X hotkey).

Copy

Copies selected text and puts it into copy buffer (equivalent to CTRL+C hotkey).

Paste

Pastes text from copy buffer (equivalent to CTRL+V hotkey).

Select all

Selects all text (equivalent to CTRL+A hotkey).


Global variables

This window allows to manage global variables. Global variables allow user to store information between different
script launches, as well as between program launches and restart (unlike local variables declared within the
script, values of which are lost at the end of script execution).

This window appears upon choosing "Global variables" in Script menu group.

Global variables table


Here all the global variables's names are as well as their values. To change a global variable's name or
value simply click the corresponding text field and write necessary value.

Add

Adds new global variable.

Delete

Deletes selected global variable.

OK button

Closes the window and saves the changes.

Close button

Closes the window without saving the changes.


Script backtester

Script backtester allows user to test script performance on historical data, thus measuring its profitability and
effectiveness. During backtesting script executes on each tick of historical data, emulating order management
and quote stream.

This window appears upon choosing "Script backtester" of Script menu group.

Settings tab

Backtesting settings are here to be analyzed or changed (Settings tab).

Report tab

Generalized backtesting results are shown here (Report tab).

Transactions tab

All transactions made during the backtesting are presented here (Transactions).
Chart tab

Balance graph is displayed here (Balance chart).

Test

Pressing this button launches script backtesting with parameters specified on Settings tab. During
backtesting script executes on each tick of historical data, emulating order management and quote
stream. After backtesting its results become available on Report, Transaction and Chart tabs.

Close

Closes the backtester.


Settings tab

Backtesting period

Data period used for script backtesting.

Instrument

Instrument on which the script will be backtested.

Note. In addition to Spread instrument itself, only instruments with "Accumulate data" option turned on
will be available for individual instrument backtesting.

Comission

Commision size for buying or selling one spread unit (it's half-turn comission).

Backtesting step

If set to 1 (default), all the ticks will be backtested on. If more than 1, each n tick will be backtested on,
where n - backtesting step.

Setting backtesting step to more than 1 can significantly reduce backtesting time: this way overall data
point number for backtesting is reduced by n times, because only each n tick will be backtested on, so
backtesting time will also be approximately n times less. But it should be taken into consideration that
such way of backtesting gives only approximate results. Thus it is recommended to use backtesting step
over 1 only for getting acquainted with approximate system results on large data archives.

Delay (ticks)

Number of ticks transaction execution will be delayed during backtesting.

A certain time passes between forming a trade order in the program and its registration on the exchange.
During this time, the price can change, and, as a result, the transaction can be made at a price different
(most of the time detriment for the trader) from the one that was at the time of trade order sending. Such
delays in the execution may be the reason why some trading system give good results when tested on
historical data but lose during real-time trading. Using the "Delay (ticks)" parameter can simulate the
delays appearing while trading real-time, thus assessing their influence on system's profitability.

Delay (milliseconds)

Number of milliseconds transaction execution will be delayed during backtesting.

A certain time passes between forming a trade order in the program and its registration on the exchange.
During this time, the price can change, and, as a result, the transaction can be made at a price different
(most of the time detriment for the trader) from the one that was at the time of trade order sending. Such
delays in the execution may be the reason why some trading system give good results when tested on
historical data but lose during real-time trading. Using the "Delay (milliseconds)" parameter can simulate
the delays appearing while trading real-time, thus assessing their influence on system's profitability.
Report tab

Generalized backtesting results are presented in "Report" tab, such as:

Net profit - financial result of all transactions. Represents the difference in the "Gross profit" and "Gross
loss";
Gross profit - sum of all profitable trades;
Gross loss - sum of all losing trades;
Total trades - total number of trades;
Profit trades - number of profitable trades;
Profit trades percent - share of profitable trades in total trades represented as percentage;
Loss trades - number of losing trades;
Loss trades percent - share of losing trades in total trades represented as percentage;
Average trade - average profit/loss per trade ("Net profit" divided by "Total trades");
Average profit - average profit per profitable trade ("Gross profit" divided by "Total trades");
Average loss - average loss per losing trade ("Gross loss" divided by "Total trades");
Maximal drawdown - maximum loss relative to last local profit maximum, achieved while backtesting.

A trade is considered to be an opened and then closed position (a round-turn trade).

Note. If opened positions exist by the end of backtesting, they are closed on the last tick.
Transactions tab

A table in "Transactions" tab shows detailed information about all executed orders during script backtesting. Each
table line represents a trade and contains the following information:

Date - transaction date;


Time - transaction time;
Type- transaction type: buying/selling the spread;
Size - spread units bought or sold;
Price - spread price at the moment of transaction;
Balance - total number of spread units in the portfolio after the transaction;
Profit - profit value (net profit) since backtesting started.

Note. If opened positions exist by the end of backtesting, they are closed on the last tick.
Balance chart tab

"Balance chart" tab shows a chart picturing the changes of account balance and profit/loss over time. It allows
user to profoundly analyze backtesting results in an easy visual fashion.

Note. If opened positions exist by the end of backtesting, they are closed on the last tick.
Indicator parameters

This window allows user to change indicators parameters.

This window appears every time an indicator is added to the chart ("Add chart" of Chart menu group) or upon
changing an indicator's parameters ("Chart parameters" of ). Also parameters window can
be opened using the "Settings" in the context menu that appears upon right-clicking an indicator line in the chart
window.

Input parameters

Input parameters panel. Certain indicators have their own parameter sets, for example, "Moving
Average" indicator has two: data source and period while "Bollinger Bands" has three - data source,
period and deviation.
Output parameters

Output parameters panel. Indicator's output is a set of lines that are the indicator's calculations results.
Certain indicators have their own output parameter sets, for example, "Moving Average" has one - the
average line itself, "Bollinger Bands" - three: top BB line, middle BB line and bottom BB line.

Each output parameter has two of its own parameters to change:

"Identifier" - identifier to call the said parameter from a script.


"Line color" - chart window line color.

OK button

Closes the window and saves the changes.

Cancel button

Closes the window without saving the changes.


License management

Here you can purchase, install or delete program license.

This window appears upon choosing "License" of Help menu group.

Purchase license

Allows user to read the instructions on purchasing a program license and save the registration file (which
is required to purchase a license.)

Install license

Starts the license installation process. First, user will be offered to accept the License Agreement. If user
agrees to the terms of the Agreement installation will proceed offering user to locate license key file. After
installing license it is necessary to restart the program.

Delete license

Deletes current program license. License will be removed permanently so it won't be possible to restore
it. After removal new registration file will be generated. License removal is most commonly used when
user needs to transfer his license to another computer or after a OS/hardware installation.
Indicators

An indicator is a mathematical transformation that converts one set of time series, serving as a data source into
another, which is the result of the conversion.

The indicators usually have a set of input parameters, that include the data source and conversion parameters,
and a set of output parameters - time series resulting from the conversion. Each output parameter may be
displayed as a curve.

The program contains a set of built-in indicators. To add indicators on the chart use the command "Add chart" in
Chart menu group.
Mean Price

Mean Price (Average Price) indicator shows the average of best bid and offer prices. This indicator is primarily
intended for use as a data source for other indicators.

Output:

Mean price (MP) - arithmetic mean of bid and offer prices.

MP = (Bid+Ask)/2
Moving Average

Moving Average shows the time series' average value for a certain period of time.

Input parameters

Source - time series used for calculation.

Period - averaging period.

Output parameters

Average line (MA) - arithmetic mean of the source time series for the specified period of time.

MA(i) = ( V(i) + V(i-1) + ... + V(i-(N-1)) ) / N

where:
V(i) - value of data source time series at the time i,
N - period
Exponential Moving Average

Indicator Exponential Moving Average performs time series smoothing by adding a certain percentage of the
current time series value to the previous value of the moving average. When using an exponential moving
average greater weight are given to last values of the series.

Input parameters

Source - time series used for calculation.

Period - averaging period.

Output parameters

Average line (EMA) - the result of source time series exponential smoothing.

EMA(i) = (1-P) * EMA(i-1) + P * V(i)

:
V(i) - value of data source time series at the time i,
P = 2 / (N+1) - smoothing coefficient,
N - period.
Bollinger Bands

Bollinger Bands set the upper and lower limit of normal range the time series' distribution. The Bollinger bands
top and bottom lines are calculated as a certain number of standard deviations from the moving average. Since
standard deviation is a measure of the time series' oscillations, the bands' width increases during high volatility
times and decreases during flat or nonvolatile market times.

Input parameters

Source - time series used for calculation.

Period - averaging period.

- number of deviations which determine how far BB top and bottom will be from the moving
average

Output parameters

Central line (ML) - moving average of the source time series.

ML(i) = ( V(i) + V(i-1) + ... + V(i-(N-1)) ) / N

Top bands line (TL) - central line shifted a defined number of standard deviations up.

TL(i) = ML(i) + D * StdDev(i)

Bottom bands line (BL) - central line shifted a defined number of standard deviations up.

BL(i) = ML(i) - D * StdDev(i)

where:
V(i) - value of data source time series at the time i,
N - period,
D - number of standard deviations,
StdDev(i) - standard deviation for i moment of time,
Sqrt - root square.

StdDev(i) = Sqrt( ( (V(i) - ML(i))^2 + (V(i-1) - ML(i))^2 + ... + (V(i-(N-1)) - ML(i))^2 ) / N )


Scripting language

MegaTrader 1.4 includes a special programming language allowing to create scripts - programs that automate
trading processes. The language includes a large number of built-in functions that are required for market
analysis and trade management.

Language is very simple to learn, in addition script examples are included, which allows you to quickly master the
language and begin implementing your own trading strategies.
Language description
Language elements

Space delimiters

Space delimiters are used to determine the beginning and end of lexemes - minimum language units. By space
delimiters spaces, tabs, and new line characters are meant.

Comments

Comment is a part of program's text, which is ignored during program compilation and execution. First of all, they
serve to explain different sections of code. The system supports two types of comments: single-line and multiline.
Multiple-line comments start with /* and end with */. They can not be nested. Single-line comments start with a
pair of slashes // on a new line and can be embedded in multi-line comments. Comments are allowed wherever
spaces are possible, and allow an unlimited number of spaces.

Examples.

// Single-line comment

/* Multiple-line
comment
*/

Lexemes

Lexeme is a minimum unit of language with a meaning. There are five types of lexemes:

identifiers;
keywords;
constants;
operation signs;
punctuation signs.

Identifiers

Identifiers are used as variable and function names. Identifiers can consist of latin letters (uppercase and
lowercase letters are not distinguished), 0-9 and the underscore character (_). The first character must be a
letter.

Keywords

Keywords are identifiers already reserved by the language:

do
else
for
if
null
return
var
while

Constants
Constants are lexemes representing a fixed, numeric, string, or a character value.

Numeric constants consist of an integer part and , optionally, a period (.) and the fraction. The integer and
fractional parts are sequences of decimal digits.

String constants are a sequence of characters enclosed in double quotes (").

Character constants - is a single character enclosed in single quotes. The internal representation of a character
constant is an integer containing the character code.

Examples:

10, -3.14, 0.0001 // numeric constants


"This is a string" // string constants
't', '$' // character constants

Operation signs

Operation signs help the development and evaluation of expressions. In language, there are following operation
signs:
=,+,-,*,/,%,!,&&,||,==,!=,<,<=,>,>=.

Punctuation signs

Punctuations signs include the following:


() {} , ;

The parentheses () are used to group expressions and change the order of operations. In addition, parentheses
are used in conditional statement if and loop statement for.

The curly braces {} denote beginning and end of the compound statement or block.

The comma (,) is used as a parameter separator in functions, as well as a generic separator - in cycle statement
for.

The semicolon (;) terminates each statement. Any valid expression followed by a semicolon is treated as an
statement.
Operations and expressions

Exressions

An expression consists of one or more operands and operation symbols.

Examples:

x=10;
y=(x+5)/2;

Expressions ending with a semicolon (;) are statements.

Assignment

= Value assignment

The assignment statement can be used only once in an assignment expression.

Arithmetic operations

+ Addition
- Subtraction
- Change of sign
* Multiplication
/ Division
% Modulo operation

Logic operations

! Logical "NOT"
&& Logical "AND"
|| Logical "OR"

Relation operations

== Equal
!= Not equal
< Less
<= Less or equal
> More
>= More or equal

Function call

f(x1,x2,...,xn) Calling a function named f with arguments x1, x2, ... , Xn. The
argument can be a constant, variable or expression.
Operation priority

f(x1,x2,...,xn) - Function call


() - Parentheses
- - Change of sign
! - Logical "NO"
* - Multiplication
/ - Division
% - Modulo operation
+ - Addition
- - Subtraction
== - Equal
!= - Not equal
< - Less
<= - Less or equal
> - More
>= - More or equal
&& - Logical "AND"
|| - Logical "OR"
= - Value assignment

Each group of operations in the table has the same priority. The higher the priority, the higher is the group
situated in the table.

Parentheses (), which have the highest priority, are used for changing operation priority..

Example.

x=2*(1+3); // Result: x=8


Statements

Language statements describe the basic algorithmic steps that a program performs. The body of the program is
literally a sequence of statements. statements must be separated by a semicolon (;).

Expression statements

Any expression ending with a semicolon (;) is considered an statement.

Examples.

// A value of 5 is assigned to x variable:

x=5;

// A result of using an Abs function to


// y variable is assigned to x variable:

x=Abs(y);

Compound statements

Compound statements (blocks) are composed of one or more statements of any type, enclosed in curly braces {}.
There should be no semicolon (;) after a closing curly bracket.

An example.

if(x<2){
Alert("x less then 2");
}

Conditional if-else statement

if(expression){
statement1;
}
else{
statement2;
}

If the expression is true, statement1 is performed, otherwise statement2 is. The braces {} are mandatory.

Example.

if(x>y){
z=x;
}
else{
z=y;
}

Else and statement2 part can be omitted. In this case, if the expression is false, no action will be performed:

if(expression){
statement1;
}

Example.

if(x<0){
x=-x;
}

Statement1 and statement2 can be compound statements, even nested ones:

Example.

if(x>0){
if(x>y){
z=x;
}
else{
z=y;
}
}
else{
z=0;
}

while loop statement

while(expression){
statement;
}

If expression is true, statement will perform until expression becomes false. The expression value should be
determined before loop execution. So, if the expression is false from the very beginning, the loop will be simply
skipped and not executed.

Example.

// Example calculates the factorial of 4:

i=1;
x=1;
while(i<5){
x=x*i;
i=i+1;
}

do-while loop statement

do{
statement;
}while(expression);

If expression is true, statement will perform until expression becomes false. The expression value is determined
after loop execution. So, the loop will be executed at least once.

Example.
// Example of sum calculation - 10+20+30+40:

i=1;
x=0;
do{
x=x+i*10;
i=i+1;
}while(i<5)

for loop statement

for(expression1;expression2;expression3){
statement;
}

Expression1 determines the cycle initialization. Expression2 checks its condition within every cycle. Loop body is
executed while expression2 is true. Expression3 is evaluated after each iteration.

Example.

// An example calculates the average best bid


// value within the last 5 ticks:

x=0;
for(i=0;i<5;i=i+1){
x=x+Point("Bid",i);
}
x=x/5;

return statement

return expression;

The return statement terminates the current function execution and returns the value of the expression.

Example.

// Function returns the sum of its arguments

Sum(x,y){
return x+y;
}
Data types

Basic data types

Following data types are used in the language:

variant - non-specific data type.


integer - integer data type.
float - floating point value.
string - string data type.
bool - boolean data type.

Type casting

Language uses implicit casting. This means that program attempts to convert all variables to the same data type.
However, in some situations where such type conversion is not possible, an error occurs.

Example.

// Type casting error

var x;
x=5+"Str"; // Error

To avoid such errors, you must explicitly convert variables to the correct data type. For these purposes, there are
built-in functions used for data type conversion (look Type conversion).

// Example of explicit type conversion


// After the program's execution
// x variable will have a value of "5Str":

var x;
x=String(5)+"Str";

Date and time

Date and time appear in the form of a floating point type variable (float), the integer part of which is equal to the
number of days since 30.12.1899, and the fractional part - the proportion of elapsed time to the 24-hour day.

Some examples of floating point values and the corresponding date and time:

0 30.12.1899 00:00:00
2.75 01.01.1900 18:00:00
35065.5 01.01.1996 12:00:00

Such a representation of date and time is convenient because it allows correct date comparison, as well as
addition and subtraction. For example, to get the number of days, hours, minutes and seconds between two
dates, simply subtract one value from another. The resulting integer will represent the number of days and
fractional part will show hours, minutes and seconds separating the dates. Similarly, you can increase the value
by a needed number of days, hours, minutes and seconds, to do so convert the number of days, hours, minutes
and seconds in the format of a floating point value (e.g. a day and 16 hours will be 1.66), then just add it to given
date and time.

It's enough to drop the fractional part to get date without time . To get time value without date, you need to drop
the integer part.

Example.

// Getting current computer time


// without date.

var x;
x=CurrentDateTime();
x=x-Floor(x);

The null value

The null value has variant data type and is used to represent non-specific data. Null is returned by many
built-in functions if they cannot execute correctly or if errors appear while the execution.

x=Float(s);
if(x==null){
Alert("Could not convert to a number");
}
Variables

Variable is an indicator of a certain area in memory that stores the value of the variable. This value can change
during program execution.

Variable declaration

Before using a variable it should be declared with a keyword var.

var var_name1,var_name2,...,var_nameN;

Variables of the language are not explicitly typed and can change their data type during program execution.

Example.

var i,j,k;
var x,y;

Variable initialization

Variable initialization occurs at the time of assigning a value. Before that a variable posesses the variant data
type. After assigning a value the variable converts to a type matching the value's data type.

Example.

// Variable declaration and initialization:

var x; // Data type is variant


x="Str"; // Data type converts to string

Because of variables not strictly typed, they can change their data type during program execution.

Example.

// Variable data type change


// during program execution:

var x; // Data type is variant


x=0.001 // Data type converts to float
x="Str"; // Data type changes to string

Variable visibility

Variable scope is the part of the program where the variable can be referenced and called. There are local and
global visibility scopes in the language.

Variable declared in the body of some function has a local visibility scope. It can be referenced only in the body of
function it has been declared in.

A variable declared outside of any function has global visibility scope. It can be called from entire program and
any function defined in the program

Examples.

// In this example variable a with a global


// visibility scope and x, y variables with
// local scope are declared.
// Variables x and y can be referenced only
// in main() function body.

var a;

main(){
var x,y;
}

// Variable x has a global


// scope and can be referenced to in
// all the program's functions.
// Program execution result
// will be an alert message with "10" text.

var x;

f(){
x=10;
}

main(){
f();
Alert(String(x));
}

If local and global variables' names are the same, local variable will have the call priority when referencing to it.

// Variable x with global scope


// and another variable x, but with local
// scope are declared.
// Program execution will result
// in alert message with "1" text, because
// local variable has the call priority
// when referencing to it.

var x; // global variable

f(){
x=10; // global x reference
}

main(){
var x; // local variable
x=1;
f();
Alert(String(x)); // local variable reference
}
Functions

User functions

Function is a named part of program which can be called from other program parts.

function_name(parameter1,parameter2,...,parameterN){
statement;
}

Function consists of a name function_name, function parameters parameter1, parameter2, ... ,


parameterN, and a compound operator (block) containing function body with statements and expressions for
execution.

Example.

// Function displays a message box with the value of


// its parameter:

Show(x){
Alert("value is "+String(x));
}

If a function should return some value, return operator must be used.

Example.

// The function calculates the average best bid


// value within the last Num ticks:

Average(Num){
var i,x;
x=0;
for(i=0;i<Num;i=i+1){
x=x+Point("Bid",i);
}
x=x/Num;
return x;
}

Function call

function_name(parameter1,parameter2,...,parameterN);

Function call is an expression with the value being calculations' result returned by the function. The function call
transfers code execution from the place of a function call to the function body. Arguments, if any, are passed by
value, ie every argument1, argument2 ... , argumentN value is calculated and passed to the function. At the end
of its execution function returns the calculations' result to the place of its call. If the function does not return a
value, its call cannot be placed on the right side of assignment operation (ie x = function();).
Program execution

Program structure

The script must have a main() function to execute. main() should not have any parameters.

Example.

main(){
// function body
}

Script execution starts from the main()function call, other functions can be called from the main function's body.
End of main() function execution means script execution end.

Script execution

Script can be executed by choosing one of two options: first, running the script (. "Run the script"
Script menu group), and the second, backtesting script on historical data (. Script backtester window).

If the script is launched, it will be executed when new ticks arrive. If script iteration started on previous tick still
executes when new tick arrives, the tick will be ignored. Until a script iteration is executed, all incoming ticks will
be ignored. After that, a new iteration of script will be started only when a new tick arrives.

If script backtesting is launched, backtester software will execute the script on every tick in the historical data
provided. The software will only start a new iteration of script when current tick iteration ends executing.
Built-in functions
Type conversion
Integer

integer Integer(variant value)

The function converts the transmitted numeric or string value to an integer. In case of failure, null value is
returned.

Parameters:

value - nonspecific data.


Float

float Float(variant value)

The function converts the transmitted numeric or string value to a float value. In case of failure, null value is
returned.

Parameters:

value - nonspecific data.


String

string String(variant value)

The function converts the transmitted numeric or string value to a string. In case of failure, null value is
returned.

Parameters:

value - nonspecific data.


Date and time
DataTimeToStr

string DateTimeToStr(float datetime)

Returns a string representation of date and time given. The representation format depends on current OS
settings.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


DateToStr

string DateToStr(float datetime)

Returns a string representation of date and time given (time is omitted). The representation format depends on
current OS settings.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


TimeToStr

string TimeToStr(float datetime)

Returns a string representation of date and time given (date is omitted). The representation format depends on
current OS settings.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


StrToDateTime

float StrToDateTime(string str)

Converts the specified string in the date-time float value. The string format must match the format of the date /
time set in OS settings. In case of failure, returns null.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

str - String containing date and time value.


StrToDate

float StrToDate(string str)

Converts the specified string in the date-time float value (time will be set to 00:00). The string format must match
the format of the date / time set in OS settings. In case of failure, returns null.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

str - String containing date value.


StrToTime

float StrToTime(string str)

Converts the specified string in the date-time float value (date will be set to 30.12.1899). The string format must
match the format of the date / time set in OS settings. In case of failure, returns null.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

str - String containing time value.


Day

integer Day(float datetime)

Returns the day of the month (1 - 31) for specified date and time.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


Month

integer Month(float datetime)

Returns the month number (1 - 12) for specified date and time.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


Year

integer Year(float datetime)

Returns the year number (0 - 9999) for specified date and time.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


Hour

integer Hour(float datetime)

Returns the hour (0 - 23) for specified date and time.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


Minute

integer Minute(float datetime)

Returns the minute (0 - 59) for specified date and time.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


Sec

integer Sec(float datetime)

Returns the second (0 - 59) for specified date and time.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


MilliSec

integer MilliSec(float datetime)

Returns the millisecond (0 - 999) for specified date and time.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


DayOfWeek

integer DayOfWeek(float datetime)

Returns day of the week (1 - 7, where 1 - monday, 2 - tuesday, ... , 7 - sunday), for specified date and time.

Note. Date and time in the program is represented as a float, the whole part equal to the number of days since
30.12.1899, the fractional part is the proportion of elapsed time in the 24-hour day.

Parameters:

datetime - Date-time value.


Global variables
GetGlobVar

variant GetGlobVar(string name)

Returns the value of global variable name. If no variable with such name exists, returns null.

Parameters:

name - Global variable name.


SetGlobVar

SetGlobVar(string name,variant value)

Writes new value to the global variable name. If no variable with such name exists, new global variable is
created.

Parameters:

name - Global variable name.


value - New global variable value.
Mathematics
Abs

float Abs(float value)

Returns the absolute value (or modulus) of the passed number.

Parameters:

value - Numeric value.


Ceil

integer Ceil(float value)

Returns the smallest integer greater or equal than value (performs rounding up).

Parameters:

value - Numeric value.


Floor

integer Floor(float x)

Returns the largest integer that is less or equal than value (performs rounding down).

Parameters:

value - Numeric value.


Sign

integer Sign(float value)

Determines the sign of the number passed.

Returns:

0 - the value is zero.


1 - the value is greater than zero.
-1 - the value is less than zero.

Parameters:

value - Numeric value.


Max

float Max(float value1, float value2)

Returns the maximum of two numeric values passed.

Parameters:

value1 - First numeric value.


value2 - Second numeric value.
Min

float Min(float value1, float value2)

Returns the maximum of two numeric values passed.

Parameters:

value1 - First numeric value.


value2 - Second numeric value.
Pow

float Pow(float base, float exponent)

Returns the value of base raised to a power of exponent.

Parameters:

base - Base value.


exponent - Power value.
Sqrt

float Sqrt(float value)

Returns the square root of value. If value is less than zero, returns null.

Parameters:

value - Numeric value.


Data
Bid

float Bid()

Returns current best Bid value.


Offer

float Offer()

Returns current best Offer value.


SymbolBid

float SymbolBid(string name, integer account)

Returns current best Bid value for the instrument with name name (code) and account account number. If no
istrument with such name and account number exists, returns null.

Note. Depending on trading terminal, instrument code is set in various composite instrument windows (eg
MetaTrader instrument settings, SaxoTrader instrument settings and QuoteSpeed instrument settings). Account
number should be given only for MetaTrader instruments in MetaTrader instrument settings. For other trading
terminals you should set account to 0.

Function will only work correctly when the script is launched for real-time execution (eg script is started). When
backtesting (in Script Backtester) function always returns null.

Parameters:

name - Instrument name (code)


account - Instrument account number. For non-MetaTrader instruments should be set to 0.
SymbolOffer

float SymbolOffer(string name, integer account)

Returns current best Offer value for the instrument with name name (code) and account account number. If no
istrument with such name and account number exists, returns null.

Note. Depending on trading terminal, instrument code is set in various composite instrument windows (eg
MetaTrader instrument settings, SaxoTrader instrument settings and QuoteSpeed instrument settings). Account
number should be given only for MetaTrader instruments in MetaTrader instrument settings. For other trading
terminals you should set account to 0.

Function will only work correctly when the script is launched for real-time execution (eg script is started). When
backtesting (in Script Backtester) function always returns null.

Parameters:

name - Instrument name (code)


account - Instrument account number. For non-MetaTrader instruments should be set to 0.
SymbolLastChange

float SymbolLastChange(string name, integer account)

Returns last tick date-time value for the instrument with name name (code) and account account number. If no
istrument with such name and account number exists, returns null.

Note. Depending on trading terminal, instrument code is set in various composite instrument windows (eg
MetaTrader instrument settings, SaxoTrader instrument settings and QuoteSpeed instrument settings). Account
number should be given only for MetaTrader instruments in MetaTrader instrument settings. For other trading
terminals you should set account to 0.

When backtesting (in Script Backtester) function will only work correctly when an "Accumulate data" ticker
is checked (eg. MetaTrader instrument Additional settings, SaxoTrader instrument Additional settings
QuoteSpeed instrument Additional settings). Otherwise function will always return null.

Parameters:

name - Instrument name (code)


account - Instrument account number. For non-MetaTrader instruments should be set to 0.
Chart data functions
PointCount

float PointCount()

Returns number of ticks in the historical data archive.


Point

float Point(string id,integer shift)

Returns a time series line value with id identifier at a point offset backwards to the last point by shift points. If
a line with such id does not exist or a point specified by shift goes beyond available data, returns null.

Note. Line ID is set in the indicator settings for each indicator (eg. Indicator parameters). Bid and Offer lines have
their IDs preset as "Bid" and "Offer".

Example.

Point("Bid",0) will return current (the last) best bid value,


Point("Bid",1) will return previous best bid value.

Parameters:

id - Line identifier
shift - Offset value relative to the last line point.
SymbolBidPoint

float SymbolBidPoint(string name, integer account,integer shift)

Returns current best Bid value for the instrument with name name (code) and account account number, offset
backwards from the current value by shift. If a line with such id does not exist or a point specified by shift
goes beyond available data, returns null.

Note. Depending on trading terminal, instrument code is set in various composite instrument windows (eg
MetaTrader instrument settings, SaxoTrader instrument settings and QuoteSpeed instrument settings). Account
number should be given only for MetaTrader instruments in MetaTrader instrument settings. For other trading
terminals you should set account to 0.

Function will only work correctly when an "Accumulate data" ticker is checked (eg. MetaTrader instrument
Additional settings, SaxoTrader instrument Additional settings QuoteSpeed instrument Additional settings).
Otherwise function will always return null.

Example.

SymbolBidPoint("EURUSD",12345,0) will return current (the last) best bid value for "EURUSD" instrument
and "12345" account number,
SymbolBidPoint("EURUSD",12345,1) will return previous best bid value for "EURUSD" instrument and
"12345" account number

Parameters:

name - Instrument name (code)


account - Instrument account number. For non-MetaTrader instruments should be set to 0.
shift - Offset value relative to the last line point.
SymbolOfferPoint

float SymbolOfferPoint(string name, integer account,integer shift)

Returns current best Offer value for the instrument with name name (code) and account account number,
offset backwards from the current value by shift. If a line with such id does not exist or a point specified by
shift goes beyond available data, returns null.

Note. Depending on trading terminal, instrument code is set in various composite instrument windows (eg
MetaTrader instrument settings, SaxoTrader instrument settings and QuoteSpeed instrument settings). Account
number should be given only for MetaTrader instruments in MetaTrader instrument settings. For other trading
terminals you should set account to 0.

Function will only work correctly when an "Accumulate data" ticker is checked (eg. MetaTrader instrument
Additional settings, SaxoTrader instrument Additional settings QuoteSpeed instrument Additional settings).
Otherwise function will always return null.

SymbolOfferPoint("EURUSD",12345,0) will return current (the last) best bid value for "EURUSD"
instrument and "12345" account number,
SymbolOfferPoint("EURUSD",12345,1) will return previous best offer value for "EURUSD" instrument and
"12345" account number.

Parameters:

name - Instrument name (code)


account - Instrument account number. For non-MetaTrader instruments should be set to 0.
shift - Offset value relative to the last line point.
DateTime

float DateTime(integer shift)

Returns date-time value of the point offset backwards from the last point by shift. If a point specified by shift
goes beyond available data, returns null.

Example:

DateTime(0) will return current (the last) point date-time value.


DateTime(1) will return previous point date-time value.

Parameters:

shift - Offset value relative to the last line point.


Index

integer Index(integer shift)

Returns the index of a point offset from the last data point by shift. Indexing starts with 0. If resulting index is
less than zero (ie. beyond available data), the returns null.

For example: Let the number of data archive points be N. Then the first point has 0 index, and current (last) has
N-1 index.

Index(0) will return N-1,


Index(1) will return N-2,
...
Index(N-1) will return 0.

Parameters:

shift - Offset value relative to the last line point.


Shift

integer Shift(integer index)

Returns an index number data point's shift relative to last data point. Indexing starts with 0. If index is beyond
available data, returns null.

For example: Let the number of data archive points be N. Then the first point has 0 index, and current (last) has
N-1 index.

Shift(N-1) will return 0,


Shift(N-2) will return 1,
...
Shift(0) will return N-1.

Parameters:

index - Offset index.


Trading functions
Balance

integer Balance()

Returns the current market position balance. Balance value shows a balanced number of units spread in market
position, and the sign of balance is the position's direction: positive - buying (long), negative - selling, or short
(for example, the balance of 2 means having 2 units of spread in long position, if it is -2 - short position of the
corresponding size ).
Disbalance

integer Disbalance()

Returns the current position imbalance. The imbalance shows the unbalanced number of spread units in current
position. The imbalance is the result of portfolio lacking positions on some instruments. The imbalance shows
the number of spread units to be added to the current position balance if missing positions will be opened (long/
short), and imbalance sign is the direction of potential position added.
TradeQnty

integer TradeQnty()

Returns the default number of spread units to be bought/sold in each buy/sell order.

Note. This parameter can be set in "Quantity" field Trading tab.


GetMaxQnty

integer GetMaxQnty()

Returns the maximum number of spread units in open positions (ie. specified number of spread units is the
maximum to be in Balance tab).

Note. The parameter can be set with "Max. quantity" option on Trading tab, or set with SetMaxQnty function.
SetMaxQnty

SetMaxQnty(integer quantity)

Sets the maximum number of spread units in open positions (ie. specified number of spread units is the
maximum to be in Balance tab). The limit applies to both positions opened by the user and ones opened by
script.

Note. The parameter can be set with "Max. quantity" option on Trading tab

Parameters:

quantity - Limit in spread units.


Buy

Buy(integer quantity)

Buys quantity spread units.

Parameters:

quantity - Spread units quantity.


Sell

Sell(integer quantity)

Sells quantity spread units.

Parameters:

quantity - Spread units quantity.


Close

Close()

Closes all opened positions.


Information output
Message

Message(string msg)

Displays the msg message to messages tab on the trade panel (. Messages tab).

Parameters:

msg - String - message text.


Alert

Alert(string msg)

Displays a modal window with msg message.

Parameters:

msg - String - message text.


FileClear

integer FileClear(string file)

Clears a text file with file name. Returns 1 if successful, 0 otherwise.

Parameters:

file - File name.


FileWrite

integer FileWrite(string file,string str)

Adds a str string to a text file with file name. If file with such name doesn't exist, it is automatically created.
Returns 1 if successful, 0 otherwise.

Parameters:

file - File name.


str - String.
System functions
CurrentDateTime

float CurrentDateTime()

Returns the current OS date-time value.


GetTickCount

integer GetTickCount()

Returns the number of milliseconds elapsed since system start. The counter is limited to system timer's
resolution.
Script examples

Example 1

A simplistic strategy, buying one spread unit when the best Bid price exceeds a set level and selling it when best
Offer price goes below the level.

0 main(){ //
1 if(Bid()>10){ //If Bid price exceeds 10
2 Sell(1); //Sell one spread unit
3 } //
4 if(Offer()<-10){ //If Offer price is less than -10
5 Buy(1); //Buy one spread unit
6 } //
7 } //

Example 2

This example shows a classic pair trading strategy, selling as a spread rises above a set number of standard
deviations from a moving average and buying when it falls below a set number of standard deviations from a moving
average. Closing of positions occurs when the spread returns to the mean.

To implement the strategy, it is necessary to add the Bollinger Bands indicator to the spread chart. The Bollinger
bands top and bottom lines are calculated as a certain number of standard deviations from the moving average.
It's better to use Mean Price showing an average of Bid and Offer prices as a data source for Bollinger Bands. In
order for the script to work correctly, you must set the Bollinger Bands output parameters as follows: the central line -
"BBandCenter", top line - "BBandTop", bottom line - "BBandBottom".

0 main(){ //
1 var BBTop,BBBottom,BBCenter; //
2 BBCenter=Point("BBandCenter",0); //Central BB line
3 BBTop=Point("BBandTop",0); //Top BB line
4 BBBottom=Point("BBandBottom",0); //Bottom BB line
5 if(BBCenter!=null){ //If indicator values are available
6 if(Balance()==0){ //If no market position is present
7 if(Bid()>BBTop){ //If Bid is above BB top line
8 Sell(1); //We sell one spread unit
9 } //
10 else{ //
11 if(Offer()<BBBottom){ //If Offer is below BB bottom line
12 Buy(1); //We buy one spread unit
13 } //
14 } //
15 } //
16 else{ //
17 if(Balance()>0){ //If current market position is Long
18 if(Bid()>BBCenter){ //If Bid is above BB central line
19 Close(); //We close the position
20 } //
21 } //
22 else{ //If current market position is Short
23 if(Offer()<BBCenter){ //If Offer is below BB central line
24 Close(); //We close the position
25 } //
26 } //
27 } //
28 } //
29 } //
In this example the program first gets current top, center and bottom Bollinger Bands values and stores them in
BBCenter, BBTop and BBBottom variables (strings 2-4). Then if(BBCenter!=null) condition (string 5) checks
if the indicator values are available. It is because if Bollinger Bands has an N averaging period, data will be available
after only N-1 index data point occurs. So, if current point index is less than BB averaging period, Point function will
return null.

Then program checks the opened positions. If market balance equals zero (string 6), script checks position opening
conditions: if current best Bid price goes above Bollinger Bands top line (string 7), one spread unit is sold (string 8),
and if Offer price goes below BB bottom line ( string 11), one spread unit is bought (string 12). If current position is
positive - long (string 17), then if Bid goes above BB central line (string 18), position is closed (string 19). Vice versa,
if we are in a short position (string 22), position is closed when Offer price goes below Bollinger Bands central line
(string 23).

Example 3

This example is basically a more complex example 2 due to adding position averaging (increasing the volume size of
losing positions). Position averaging is performed at set levels from order opening price.

It is enough to add just a bit of code to Example 2 to get Example 3 working:

0 main(){ //
1 var BBTop,BBBottom,BBCenter; //
2 var Price,Level; //
3 BBCenter=Point("BBandCenter",0); //Central BB line
4 BBTop=Point("BBandTop",0); //Top BB line
5 BBBottom=Point("BBandBottom",0); //Bottom BB line
6 Level=20; //Distance between averaging levels
7 if(BBCenter!=null){ //If indicator values are available
8 if(Balance()==0){ //If no market position is present
9 if(Bid()>BBTop){ //If Bid is above BB top line
10 Sell(1); //We sell one spread unit
11 SetGlobVar("OpenPrice",Bid()); //We memorize opening price
12 } //
13 else{ //
14 if(Offer()<BBBottom){ //If Offer is below BB bottom line
15 Buy(1); //We buy one spread unit
16 SetGlobVar("OpenPrice",Offer()); //We memorize opening price
17 } //
18 } //
19 } //
20 else{ //
21 if(Balance()>0){ //If current market position is Long
22 if(Bid()>BBCenter){ //If Bid is above BB central line
23 Close(); //We close the position
24 } //
25 else{ //
26 Price=GetGlobVar("OpenPrice"); //Getting opening price from glob. var.
27 if(Price!=null){ //If successful
28 if(Offer()<Price-Level*Balance()){ //If Offer is below averaging level
29 Buy(1); //We buy one more spread unit
30 } //
31 } //
32 } //
33 } //
34 else{ //If current market position is Short
35 if(Offer()<BBCenter){ //If Offer is below BB central line
36 Close(); //We close the position
37 } //
38 else{ //
39 Price=GetGlobVar("OpenPrice"); //Getting opening price from glob. var.
40 if(Price!=null){ //If successful
41 if(Bid()>Price-Level*Balance()){ //If Bid is above averaging level
42 Sell(1); //We sell one more spread unit
43 } //
44 } //
45 } //
46 } //
47 } //
48 } //
49 } //
In this example script stores the spread price at the moment of opening a position in a global variable OpenPrice
(string 11 and 16). Then, if position is a long one (string 21) or a short one (string 34), first position closing conditions
are checked for (string 22 and 35), and averaging condition is checked for if unsuccessful (string 28 and 41).
Averaging condition is checked as follows: first opening price is restored from OpenPrice global variable (string 26
and 39), then script checks if spread's price had gone through preset averaging levels (string 28 and 41). Averaging
levels are calculated by a formula: Price-Level*Balance(), where Level is the distance between the averaging
levels. If spread reaches the level, position averaging occurs (string 29 and 42).
Additional modules
SaxoExporter

Auxiliary module SaxoExporter is developed to allow quotes import from SaxoTrader terminal to MegaTrader.
As SaxoTrader does not have any quote export functions, they are being read directly from the program
interface, or rather - "Forex orders" and "Futures orders" modal windows. So, for quote export to be possible from
SaxoTrader, it is necessary to have the corresponding windows opened for all the instruments you plan to work
with.

Module's UI consists of only two buttons: "Run" and "Stop", which launch and stop quote export respectively.

If a new Orders window is opened in SaxoTrader after quotes export already started, for SaxoExporter to "fetch"
it module should be restarted by pressing "Stop" and then "Run").

SaxoExporter is automatically launched by MegaTrader when clicking "Connection > Connect to SaxoTrader".
So in most cases manual intervention will not be required. Module's icon should appear in system tray when it's
running.

Вам также может понравиться