User Guide
UnlaxTrader EA
UnlaxTrader EA (or Robot in cTrader) listens for trade signals in the signal repository, and executes market orders based on the criteria defined in its EA properties. There are 2 types of properties: fixed or dynamic.
Fixed property is the static value you defined in the EA properties pane, and will remain the same until you change it manually, e.g. fixed lot size of 1. Dynamic property value is obtained in real-time from the signal file content created by Unlax Signaler, and originates from your algo function. For example, you can define dynamic take profit to 100 points on Fridays and 200 points on other days:
function DemoAlgo(signalName) {
= ...
Buy = ...
Sell return TradeConfig(signalName,"EURUSD",in1Minute,300,IIf(DayOfWeek()==5,100,200),1);
}
TradeConfig()
gives you a consistent mean to define dynamic properties for both backtesting and live trading. The syntax is:
TradeConfig (SignalName, SymbolName, BarInterval, StopLoss, TakeProfit, LotSize)
A property value can be either a single literal value or a JSON syntax with multiple attributes. Relaxed JSON format is supported and curly braces are optional. For example, Lot Size
is a JSON property that has 4 attributes: {buy:?, short:?, type:?, max:?}
. The benefits of using JSON syntax is it allows more attributes to be added in future.
Note that all date/time related properties refer to your Windows system date/time settings, not the broker’s. Our EA is designed to be platform/broker neutral, so it does not depend on MetaTrader/cTrader date/time settings.
Below is the complete list of configuration properties for UnlaxTrader EA:
Property | Description |
---|---|
Trade Mode | Options: Default | CloseOnly | LongOnly | ShortOnly Default mode has no trade restrictions. CloseOnly executes SELL and COVER signals. LongOnly executes BUY and SELL signals. ShortOnly executes SHORT and COVER signals. |
Signal Name | Default: <chart symbol name> Listens to signal name generated by Unlax Signaler in the repository. |
Order Comment | Default: <signal name> Uniquely identify orders managed by this EA instance. |
Order Magic Number | Default: 0 MetaTrader Order Magic Number |
Max Spread | Default: 30 points Maximum real-time spread in points (1 pip=10 points) allowed, don’t open trade if exceeded. Only applies to entry order, not when closing position. |
Max Open Positions | Default: 2 Maximum number of open positions allowed in this account, don’t trade if exceeded. |
Order Re-entry Delay | Default: 0 min Don’t open new trade within specified minutes from the most recent trade. |
Lot Size | Default: buy:0.1, short:0.1, type:fixed, hidden:no, max:0.1 Options: type: fixed | dynamic | fractional Lot size for BUY & SHORT orders. Maximum lot size is a hard limit regardless of type. Hidden SL is tracked by EA and not set in the order to prevent stop hunting. Fractional means Fixed Fractional Sizing iLotSize = AccountEquity * RiskPerTrade / StopLoss e.g. LotSize = $10000 * 5% / 500pts = 1 lot (if SL=0, calc as 500). You define Risk % in BUY and SHORT attributes, e.g. buy:0.05 means 5% risk per trade. |
Stop Loss | Default: buy:0, short:0, type:fixed Options: type: fixed | dynamic Stop Loss level in points (1 pip=10 points) for BUY & SHORT orders. Set to zero to disable. |
Take Profit | Default: buy:0, short:0, type:fixed Options: type: fixed | dynamic Take Profit level in points (1 pip=10 points) for BUY & SHORT orders. Set to zero to disable. |
End of Week Close Position | Default: dow:5 hhmm:1655 Close position before end of week on day-of-week (5=Friday) at time (HHmm). Set to unreachable values to disable. |
Disable Stops during Rollover | Default: disable:1656, enable:1810 Remove Stop Loss level in opened position during Rollover period to avoid typical huge spreads hitting your SL. Define time (HHmm) to disable and re-enable SL. Set to unreachable values to turn off this feature. |
Correlated Orders Strategy | Default: takeLotProfit:50, delayOrder:60, direct:<auto>, inverse:<auto> Correlation is automatically derived from symbol name if not defined, e.g. “EURUSD” has default correlation direct:EUR, inverse:USD .When opening a trade e.g. BUY EURUSD , if there exists other correlated positions e.g. BUY EURCHF (direct) or SHORT USDCAD (inverse), close that correlated position if its profit per lot exceeds takeLotProfit points, otherwise don’t open new trades until delayOrder minutes have passed. Set to unreachable profit value and zero delay to disable. |
Account Watermark | Default: bod:1800, first:<account balance>, high:<account balance> BOD is beginning of day (HHmm in EST) when DailyDD resets. First watermark is initial deposit. High watermark is highest account balance recorded. |
Max Drawdown | Default: daily:0.1, relative:0.2, absolute:0.2, action:noEntry Options: action: notify | noEntry | exitAll When any DD is breached, Circuit Breaker activates and sends notification. For MT4/MT5, push notification is sent to your MetaQuote ID, so you must configure Push Notification. For cTrader, email is sent to email:? attribute value and you must configure cTrader Email Settings. If action is noEntry, EA will not open new positions but existing opened positions will remain. If action is exitAll, EA will close all its positions and won’t open new positions. Circuit Breaker will deactivate when all drawdown violations are resolved. iDaily DD = (BalanceAtBOD - Equity) / DepositRelative DD = (HighWatermark - Equity) / Deposit Absolute DD = (Deposit - Equity) / Deposit |
EA Timer Interval | Default: 1000 ms EA execution refresh interval in milliseconds. |
One-to-Many Mode
Usually one instance of UnlaxTrader EA handles one symbol. There is a special mode where you can configure one EA instance to handle multiple symbols. The requirements to use this mode are:
- Signal Name consists of comma-separated names e.g. “XAUUSD,USDJPY,GBPUSD”
- Signal Name must be the same as Symbol Name to trade
- Order Comment is left empty i.e. it will follow same name as signal name
- Trade configurations will be the same for all defined symbols. If each symbol has different configurations (e.g. SL or TP), you should use Dynamic property accordingly.
- If your broker uses symbol suffix (e.g. EURUSD.pro), specify "suffix:" in Order Comment (e.g "suffix:.pro")
See our Reference Trading System for an example of trading 10 symbols using 1 EA instance.
Unlax AFL Libraries
We provide the following open source AFL libraries for AmiBroker: Common, Algos, Signaler, Export and DDEHealthCheck.
Common.afl
This contains common utility functions that are used by several Unlax AFL libraries. It also comes with useful functions that you can use in your trading algo. If you wish to use this library in your own AFL file, you need to include the following line:
"Formulas/Unlax/Common.afl" #include
Algos.afl
This file holds your trading algo functions as well as a mandatory RunAlgo()
function that is called by Signaler
during live trading. This is the only AFL that you need to modify. Refer to Quick Start on how to add your algo function into this file.
Signaler.afl
Signaler is responsible for calling your trading algo and generates trade signals into the signal repository. You need to attach Signaler to a chart to use it. Signaler calls RunAlgo()
in Algos.afl
, which then calls your trading algo function based on signal name. It does so whenever your live chart generates a new bar, hence it corresponds to Trade NEXT BAR on OPEN
backtest behavior in AmiBroker Analysis settings, i.e the BUY/SELL/SHORT/COVER values of the last closed bar is used. The calling frequency depends on your selected bar interval, if you use 1-minute bar, then Signaler will call your algo at the start of every minute.
Signaler configuration parameters:
Parameter | Description |
---|---|
Signal Name | Default: Chart Symbol Name A text string that determines which algo function should be called for this Signaler instance. It must match the signal name you defined in the switch block of RunAlgo() . |
Signal Mode | Default: Enabled Options: Enabled | Disabled | CloseOnly | LongOnly | ShortOnly Enabled generates all signals. CloseOnly generates SELL and COVER signals. LongOnly generates BUY and SELL signals. ShortOnly generates SHORT and COVER signals. |
Refresh Interval | Default: 1000ms Interval in milliseconds to call Signaler. Note that Signaler will only call RunAlgo() when a new bar is formed in the live chart. |
Trigger Algo | Trigger button to call RunAlgo() manually for testing/verification purpose. |
Export.afl
This is an optional library to help you export your quotes data from AmiBroker. For example, you have a 10 years historical database for backtesting but you only need 6 months of backfill data in live trading, so you use this library to export the past 6 months of data to your live trading server.
It also allows you to change the time zone of your data when exported. For example, your quotes data are based on London timezone but you want to convert them into US Eastern timezone. You can define the timezone offset in this library and export the converted data.
DDEHealthCheck.afl
This library is optional and only applicable if you are using AmiBroker DDE Data Plugin as live quotes provider. It checks and alerts any data gaps in AmiBroker live chart, and prevents consuming garbage bars from MT4 over the weekends. In rare situations where DDE Data Plugin loses connection to MT4 DDE Server, this library will automatically try to reconnect, and optionally sends an email alert to notify you.
MT4 DDE Server may generate garbage Forex quotes over the weekend when market is closed. This may affect your AFL algo if it gets propagated to AmiBroker charts creating extra flat bars like this:
To prevent this, DDEHealthCheck
automatically disables the DDE connection at the start of weekend (e.g. Friday 17:00 EST) and enable again on start of week (e.g. Sunday 16:59 EST). It assumes EST timezone by default, you can change the timings accordingly since it is open sourced.
To use this library, attach it to a live chart via AmiBroker
> Charts
> Unlax
> DDEHealthCheck
> Overlay
. If you want to receive email notification when a data gap occurs, configure by right-clicking on live chart Parameters
> Enable with Email Alert
. It uses AmiBroker email alert mechanism, so please configure email settings accordingly.
Parameter | Description |
---|---|
DDE Health Check | Default: Enable Options: Enable | Enable with Email Alert |
Signal Repository and Files
Signal repository is a folder that stores trade signals generated by Unlax Signaler and allows UnlaxTrader EA to consume signals from. The default location is %UNLAX_HOME%\signals\
which is a local folder. You can change the location by defining system environment variable %UNLAX_REPO%
. This destination can be another local folder, a shared network folder, a cloud drive like OneDrive / GoogleDrive / Dropbox, or any storage solution that provides a mount point. You must have Read/Write permissions to this destination.
Signal Files
A trade signal is persisted as a plain text file with filename <SignalName>.<SignalType>
, where signal type is either BUY, SELL, SHORT or COVER. For example, a BUY signal for symbol EURUSD will be EURUSD.BUY
, assuming you use default signal name which follows symbol name.
The signal file will remain in the repository for UnlaxTrader EAs to consume, as long as the signal type array returns TRUE from your AFL algorithm. Our EA will not send repeated orders for the same signal. It will also ignore conflicting signals e.g. EURUSD.BUY & EURUSD.SELL
or EURUSD.SHORT & EURUSD.COVER
. When the signal type returns FALSE from your algo, Unlax Signaler deletes the signal file.
A signal file contains JSON data that serves as Dynamic Properties. Currently 3 dynamic properties are supported: sl
(StopLoss), tp
(TakeProfit), lot
(LotSize). An example of signal file content: {sl:300, tp:200, lot:1}
. If you configure the EA property to non-dynamic (e.g. Lot Size type:fixed), the JSON value in the file will be ignored.
Unlax Cluster
Unlax Cluster provides high availability across geographical region, so you will not have any trading system downtime even when your computer or network is down. A cluster comprises an Active and Standby pair of nodes (machines), both having similar automated trading setup. Under normal circumstances, Active node performs trade execution while Standby node simply monitors its health and doesn’t trade.
Every 30 seconds the Active node publishes a heartbeat
, if all applications you defined are running, to a shared cloud folder where the Standby node monitors. If no heartbeat is observed after timeout (default is 90s), the Standby node sends email alert and takes over trade execution. When the Active node recovers from failure and resumes heartbeat, Standby node relinquishes trade execution and returns to hot standby mode. Unlax Cluster
application must be running at all time on both nodes, but you can minimize its GUI into the background.
Active Node
In Active node, start Unlax Cluster
and select Active
mode, specify the shared cloud folder (e.g. OneDrive), and add applications to be monitored (e.g. AmiBroker, MetaTrader 4). The application name can be full or sub-string title of application window. You can click Health Check
button to verify the local health monitoring is working. Clicking Save Cluster
will save your configuration and start local monitoring of Active node periodically.
Standby Node
In Standby node, start Unlax Cluster
and select Standby mode, specify the shared cloud folder, email for alert notification, and timeout seconds. You can click Health Check
button to verify it could receive heartbeat from the Active node. Clicking Save Cluster
will save your configuration and start remote monitoring periodically. It uses its own email alert mechanism, not AmiBroker’s.
UnlaxTrader EA is cluster-aware, so no trades will be done on the Standby node under normal circumstances. You can verify that UnlaxTrader EA status in your MT/cTrader chart shows Standby instead of the usual Active.
When a failure occurs in Active node (e.g. machine, network or application down), the Standby node enters Failover mode after the timeout period expires. UnlaxTrader EA automatically switches from Standby to Active. If you want Standby node to only handle exit signals (SELL, COVER) and not entry signals (BUY, SHORT), as a safety precaution in failure situation, configure its EA Trade Mode to CloseOnly
.
Web Monitoring
If you don’t want to run a Standby machine and doesn’t need the failover feature, you can still monitor your Active node using free web monitoring services like UptimeRobot. Unlax Cluster has a built-in HTTP server that allows monitoring of heartbeats via HTTP request URL http://<your_ip_address>:<port_number>
. You configure the HTTP Port
to enable web monitoring, a zero value means this feature is disabled. Your Active node must have an external IP address that is reachable from internet and the port number not blocked by your firewall. There are two possible outcome from a web monitoring request, 200 OK
and 500 Internal Server Error
. Use your web monitoring service to periodically (say 5min) poll this URL.
DDE Plugin Setup
This is an optional setup wizard to simplify the configuration of AmiBroker DDE Data Plugin to connect with MT4/MT5 DDE Server. You may achieve the same by following the instructions from AmiBroker, albeit more tedious.
The wizard is pretty straight forward. Ensure AmiBroker and MT4/MT5 terminal are running before clicking Configure
. For MT4, ensure you have Enable DDE Server
. For MT5, see the section below on using MT5 DDE Source and Server. AmiBroker Data Plugin status will show CONN as long as your live chart symbol matches MT4/MT5 chart symbol.
DDE Server for MT5
Unlike MT4, MT5 does not have a built-in DDE Server for exporting live quotes. To overcome this, you can use another MT4 terminal or third-party live quotes provider that AmiBroker supports. The drawback is that the quotes may not be exactly the same as those you trade on MT5.
If you want your AFL algo to run on the exact MT5 quotes, we provide a DDE Server and DDE Source EA for MT5 to achieve what MT4 does. In MT5 select Navigator
> Expert Advisors
> Unlax
> DDESource
> Attach to Chart
. You need to Allow DLL imports
in the EA Dependencies
tab. DDESource periodically sends live quotes to a shared Unlax DDE Server
, which is automatically started for you. Configure AmiBroker to receive these quotes using DDE Plugin Setup. The EA refresh interval is 1000ms by default, you can change it via EA properties if needed.
Unlax DDE Server:
Historical Data Management
Importing Data
You need to import historical data in order to backtest your AFL strategy. AmiBroker supports a list of import data formats out-of-the-box. You can also define your own import formats using AmiBroker Import Wizard or %AmiBroker_Home%\Formats\import.types
. UnlaxTrader provides additional formats of popular data providers such as Tickstory, Dukascopy, MT4, Pi Trading, Forexite, Finam, CBOE, Google Finance.
For example, you can use free Tickstory Lite to download Dukascopy historical tick data and export as CSV file (see screenshot below). You can then import this file into AmiBroker via File
> Import ASCII
> Files of type: Tickstory(*.csv)
.
Backfilling Data
Some AmiBroker real-time data sources (e.g. eSignal, IQFeed) have backfill capabilities. For those that don’t (e.g. DDE Source), you can backfill your live data with historical data from a different source (e.g. TickStory, MT4), by merging the historical data into the live data symbol using AmiBroker
> Symbol
> Merge
(see screenshot below). Make sure the time zone of both data sets are the same, else you need to adjust the offset.
Exporting Data
You may want to export quotes data from AmiBroker for several reasons:
- You need only a recent subset of your multi-years backtesting historical database to backfill your real-time quotes for live trading.
- You want to change the time zone of imported data (e.g GMT) to another (e.g. EST).
- You want to export your data into a different format (e.g. CSV, HTML).
We provide Export.afl
for your convenience to export data into Tickstory compatible CSV format. Open Analysis
> New Analysis
, choose Export.afl
and specify date range, click Explore
> File
> Export HTML/CSV
and save as CSV file. Export.afl
allows you to define time zone offset via DateTimeAdd()
function.
Configure Forex Spreads
To get realistic backtesting results, you need to configure the cost/commission per trade that is similar to your perspective broker. AmiBroker allows you to configure this in two ways:
- globally in
Commissions & rates
of Analysis settings window. - individually in AFL via
SetOption("CommissionMode"...)
andSetOption("CommissionAmount"...)
APIs.
In Forex the round-trip cost per trade is often expressed in terms of spreads, if there is a commission it can be included into the spreads as well, and every Forex pair has different spreads. None of the above methods fulfill this requirements easily.
To simplify things, our library Common.afl
provides a function TradeConfig()
that reads the spreads for the backtested symbol from a pre-configured file %UNLAX_HOME%\fxspreads.txt
. You can change the spreads in this text file to suit your broker’s trading conditions. You can insert additional symbols and their spreads easily. The file contains two columns: the symbol name and its spreads in points (1 pip=10 points):
=10
AUDUSD=10
EURUSD=15
GBPUSD=15
USDCAD=10
USDJPY=15
XAUUSD......
Debug Mode
By default, UnlaxTrader EA only logs important messages to the terminal output. These include TRADE transactional events when an order is opened, closed or modified, as well as error messages if order execution failed. There are also non-transactional DEBUG messages that are only visible in Debug Mode. These include notifications when a trade signal is ignored due to violation of trade configurations e.g. “Max open positions 2 reached, new order forbidden”.
Debug Mode can be enabled on two levels:
Per Machine - by creating a file
debug
in folder%UNLAX_HOME%
. This affects our EAs in all trading terminals running on that machine.Per Terminal - by creating a file
debug
in a terminal’s “Files” folder e.g.{MT4 Home}\MQL4\Files
. This affects only our EAs in that terminal. This mode is only supported in MT4 and MT5.
The debug
file is just an empty text file without file extension, and file name must be lowercase. To disable Debug Mode, simply delete the file. Debug Mode can be enabled or disabled in real-time, there is no need to restart our EA or trading terminal.
Reference Live Trading System
Below is our fully automated live trading system that serves as a reference implementation of UnlaxTrader solution. It trades ten pairs of Forex currencies using only one EA instance via One-to-Many Mode. It uses fixed lot size, dynamic stop loss and take profit levels, and closes all positions before weekend. The charts use MT4 live quotes via AmiBroker DDE Data Source, and DDE Health Check ensures the quotes are always clean and up-to-date. Unlax Cluster monitors the system, it will alert and failover to a hot standby machine when downtime detected.