RunwiseFX CSA Rule Writing Guide
RunwiseFX CSA Rule Writing Guide
1 INTRODUCTION................................................................................................ 1
1.1 Document Conventions ............................................................................ 1
2 CONFIGURATION FILE .................................................................................... 2
2.1 Configuration File Format......................................................................... 2
3 CAPTURING INDICATORS & CHART OBJECTS ............................................ 4
3.1 Capturing Indicators with Weighting Box Set ......................................... 4
3.2 Capturing Indicators with Weighting Box Blank ..................................... 5
3.3 Direct Capturing of Chart Objects............................................................ 6
4 GUI CONTROLS................................................................................................ 9
4.1.1 Label .................................................................................................... 9
4.1.2 Tick Box ............................................................................................... 9
4.1.3 Text Box............................................................................................... 9
4.1.4 List Box .............................................................................................. 10
4.1.5 Button ................................................................................................ 10
5 SPECIFYING RULES ...................................................................................... 11
5.1 Operands ................................................................................................. 14
5.1.1 Account/System (a.*) ......................................................................... 14
5.1.2 Indicator Values (i.*) ........................................................................... 16
5.1.3 Functions (f.*)..................................................................................... 16
5.1.4 Trade (t.*) ........................................................................................... 20
5.2 Commands .............................................................................................. 21
5.3 Expressions {….} .................................................................................... 26
6 CONTACTS ..................................................................................................... 27
1 INTRODUCTION
This document covers how write/amend trading rules for our EA that goes beyond
what is supplied by default and in our library: https://www.runwisefx.com/library/
Our ‘factory’ supplied built-in rules will trade when configured indicators are in
agreement and exit if go opposite. So, only if you need to go beyond this and cant’
find what you need in our library then you will need this document.
Top tip – shortcut or other useful information that can make the system
easier to use
Advanced feature/subject – can skip over when you are first learning
how to use the system
Technical ‘behind the scenes’ detail that you don’t strictly need to know
but maybe interested in
The file can be edited in a text editor, such as Notepad. The EA will auto re-read the
file if it detects a change in the file date/time. Note, if any errors are detected by the
EA then it will alerted with the line number in the file of where the problem is. If you
wish to try the configuration in MetaTrader’s Strategy Tester then recommend using
the ‘Copy Config to Strategy Tester’ button in the CONFIG button pop-up.
[indi.sma]
indicatorName=F:MovingAverage
inputProperties=200,0,sma,close
colorIndex=
captureMode=0
shift=1
period=0
priority=2
nullValue=AUTO
minBars=
holdBars=
min=
max=
midPoint=
weighting=1
digits=AUTO
[rule.<type>.<refID>] Trading rule. Again, each rule has its own section.
More details on these sections and how to configure them in is the rest of the
document.
Normally, the indicators don’t need to be loaded on to the chart in order for the
values to be captured. The exception is where capturing objects that indicators place
on the chart. In this case, those indicators that create the objects will need to be
present on the chart.
1) With Weighting box set which will cause the EA to derive the buy/sell indication
from the indicator and keep a running total of whether buy or sell is being signalled
for all the indicators configured with weighting set. Our trading rule supplied by
default can then trade based on this total outcome.
2) Where Weighting box is blank and the system just captures and records the raw
indicator value which will need to referenced later in a trading rule. This gives you the
maximum flexibility without the EA tyring to work out buy / sell itself. You can add a
trading rule based on the indicators to do exactly what you want.
Lets look at these two ways in more detail an explain the differences.
Firstly, would need to capture the fast moving average with a period of 8. Notice, the
Capture Mode box is Default Value which just captures the raw value from the
indicator, i.e. price from the moving average. Also, notice the Weighting box is blank.
We would now need a trading rule to trade what has been captured. We explain this
more later in the document, but would look like this in the configuration file:
[rule.entry.movingAverageEntry]
,i.maFast,/>,i.maSlow,TRADE_OPEN
The i.* allow the capture indicator values to be referenced. The > means greater
than. Rules are evaluated for both buy and sell and the / before > means the > will be
auto inverted to a < when evaluating for a sell. Finally, the TRADE_OPEN is the
command which will signal trade open, subject to the Auto Mode configured in
CONFIG | General Settings, which will either alert, set up pending order or open
trade at market price, etc., on this trade signal.
Note, trade exit on opposite would need to configured separately. For example:
[rule.exit.movingAverageExit]
,i.maFast,/<,i.maSlow,TRADE_CLOSE
[rule.entry.movingAverageEntry]
,f.pipDiffAuto({i.maFast};{i.maSlow}),>=,5,TRADE_OPEN
Here we are calling a function, which we explain later, that returns the number of pips
between two supplied prices. Those prices are coming from the captured indicators.
Note, we need { } around the indicator references in order to include them in function
parameters. We call the { } an expression and will explain later. Finally, the ‘Auto’ in
the function name means it will auto invert when being evaluated for a sell and do
slow – fast, so the >= 5 is still valid.
Finally, for completeness, there is a high chance you wouldn’t want the 5 hard coded
in the configuration file, but would want it on the panel, so could easily adjust. Here is
how you would configure that. Again, this explained more in the later sections:
[gui.textBox.minPips]
caption=Min Pips:
defualtValue=5
[rule.entry.movingAverageEntry]
,f.pipDiffAuto({i.maFast};{i.maSlow}),>=,g.minPips,TRADE_OPEN
Here we have added a text box GUI control to the bottom of the EA’s panel, with a
default value of 5. We have then adjusted the entry rule to reference the value from
this text box rather than hard coding the 5.
[indi.example]
indicatorNameOnMetaTrader= OBJ:<objectName>
colorIndex=-1
period=0
shift=0
inputProperties=<objectProperty>
interpretationMethod=A
interpretationParameters=
digits=AUTO
nullValue=AUTO
<objectProperty> is property of the object to capture and can be one of the following:
a = arrow code
ad = arrow distance. Will search back through chart and return number of bars to
supplied arrow object name. Can set shift to offset where to start search back from.
Note, <objectName> only needs to contain part of the expected object name. Note,
the distance is always measured from shift 0, i.e. 1 will be returned if arrow on closed
candle even if supplied shift offset 1. So, shift 1 would just mean live candle is
ignored when searching back, but doesn’t offset returned value.
rd = rectangle distance. Will search back through chart and return number of bars to
supplied rectangle object name. Can set shift to offset where to start search back
from. Note, <objectName> only needs to contain part of the expected object name.
Note, the distance is always measured from shift 0, i.e. 1 will be returned if arrow on
closed candle even if supplied shift offset 1. So, shift 1 would just mean live candle is
ignored when searching back, but doesn’t offset returned value. Can also set
inputProprties to color and 2 meaning search for most recent price 2 (as rectangle is
made up of two prices defining left and right edge), e.g. rd,clrGreen,2
This will return distance of rectangle that is colored green that is the most recent
based on price 2 (most often right edge).
p = price 1
bgc = background color, in the format of R,G,B where each color is 0-255, e.g.
0,255,0
bgc2 = as background color but will attempt to convert to color constant, such
clrOrange. For full list see:
https://www.mql5.com/en/docs/constants/objectconstants/webcolors
c = color, in the format of R,G,B where each color is 0-255, e.g. 0,255,0
s = style
d = text/description
dn = as d but will only return number in object text/description, i.e. removes non-
numeric characters
dt = as d but will apply a text trim which removes spaces before and after text
dtf = as dt but not necessary to supply exact <objectName> can be just part of it
t2 = time 2
t3 = time 3
p2 = price 2
Note, period is of no use as only objects that are shown on the current chart, i.e.
current period, can be captured.
Sometimes object names that indicators place on charts can include the current chart
symbol in that name. You can cater for this by using the expression {t.symbol} in the
object name. The following example will successfully capture the text of an object
that is named ‘dfsrEURUSD57’, where EURUSD is the current chart symbol:
[indi.dfsr]
indicatorNameOnMetaTrader=OBJ:dfsr{t.symbol}57
colorIndex=-1
period=0
shift=0
inputProperties=dt
interpretationMethod=A
interpretationParameters=
digits=0
nullValue=AUTO
4.1.1 Label
[gui.label.<labelName>]
defaultValue=<value to appear on the label>
color=<color of label>
The <labelName> is name that can used in the rules to refer to the GUI item and
should be unique and meaningful, e.g. totalProfit. The defaultValue is what the label
text should be initially, but can be changed by the rules. color is the initial color of the
label, bus also can be changed by the rules. If left blank then the default will be color
used.
The <tickBoxName> is name that can used in the rules to refer to the GUI item and
should be unique and meaningful, e.g. trendExitOn. Example:
[gui.tickBox.trendExitOn]
caption=Trend Exit
defaultValue=0
Creates a tick box with the caption ‘Trend Exit’, which is not ticked by default. The
tick box can be referred to in the rules by g.trendExitOn and will have the value 1 if
ticked else 0 if not ticked.
The <textBoxName> is name that can used in the rules to refer to the GUI item and
should be unique and meaningful, e.g. pipTarget. Example:
[gui.textBox.pipTarget]
caption=Pips Target
defaultValue=40
The <listBoxName> is name that can used in the rules to refer to the GUI item and
should be unique and meaningful, e.g. pipTarget. Example:
[gui.listBox.timeframe]
caption=Timeframe:
defaultValue=M1
selList=M1,M5,M15
4.1.5 Button
[gui.button.<buttonName>]
defaultValue=<text to appear on the button>
direction=buy|sell
The <buttonName> is name that can used in the rules to refer to button and should
be unique and meaningful, e.g. closeInProfitTrades. Example:
[gui.button.closeInProfitTrades]
defaultValue=Close In Profit Trades
Note, to add a rule that is executed when the button is pressed, the button name
should be used in the rule header, for example:
[rule.gui.closeInProfitTrades]
,t.profit,>,0,FORCE_CLOSE
The direction is optional and if set will only execute the configure rule for that
direction. This allows you to have a but for doing something related to a sell and
another button for buy.
[rule.<ruleType>.ruleName]
<flags>,<operand1>,<operator>,<operand2>,<commands>,<failComment>
<flags>,<operand1>,<operator>,<operand2>,<commands>,<failComment>
<flags>,<operand1>,<operator>,<operand2>,<commands>,<failComment>
...
For example, an entry rule for the popular TDI indicator (Traders Dynamic Index)
might be:
[rule.entry.TDIentry]
N,i.tdiGreen,/>,50,AND,”green not crossed 50”
N,i.tdiRed,/>,i.tdiYellow,TRADE_OPEN,”red not crossed yellow”
This will open a trade on the open of a new bar (signified by the flag N) when the TDI
green line has crossed 50 and the TDI red line has crossed the TDI yellow line. Note,
the ‘/’ next to the greater than sign ‘>’, is used to indicate that the ‘>’ should be flipped
to a ‘<’ when evaluating the rule for a sell. The optional fail comment is used to report
status back to the user (you) in the status text, i.e. whether it is the green or red line
that is being waited for.
entry Entry rules. Note, will be evaluated even when trade is open in case
what to scale-in (add to position). You can use t.tradeOpen operand to
know if trade is already open or not. The entry rules are evaluated on
every tick from the market, i.e. will not be evaluated if market is closed.
exit Exit rules. Only evaluated when trade is open in that direction and a
tick has come in from the market.
keypress Evaluated on keyboard key press. Can be used to take action when a
certain key is pressed. Use t.keyPressCode operand in order to know
which key has been pressed. Note, you’ll need the $ flag when
evaluating lines containing text, see later.
[rule.exit.TDIexit]
,i.tdiGreen,/<,50,TRADE_CLOSE,”green okay”
This will close the trade when the TDI green crosses back over 50. This the rule
doesn’t just operate on the open of new bar, but is evaluated on every tick. The
optional fail comment will write on the status “green okay” if rule is active but green
not yet crossed 50.
GUI rules and entry rules are evaluated in both directions (sell and
buy). Hence, any TRADE_OPEN commands will open a trade in the
direction that is being evaluated and for which the rules match.
The <flags> can be empty or one of N,B,S,$,%. N means evaluate line on a newly
opened bar (candle). B means evaluate line when evaluating for buy, otherwise
ignore the line. S means evaluate the line when evaluating for a sell, otherwise
ignore the line. $ means evaluate as a string (text). % means evaluate as an integer
(whole number), i.e. any floating point numbers will be rounded up.
A variety of commands are available, see 5.1. <command> can also be AND which
means the following line(s) must match also, or OR which means either this line or
the next one or one after if OR is still specified. Multiple commands can be specified
separated by ‘|’ (vertical bar). If a command is preceded by a ‘!’ then the command is
only executed if the expression does not match.
The <failComment> is optional and is displayed in the status lines on the control
panel if rule fails to match on the line. It can be used to know why the rule is not
performing the action associated with it. Note, if the comment contains a comma then
Rules can have multiple lines that end in a command(s). However, the
END_EVAL command can be used to stop the evaluation of the
particular rule, regardless of what follows.
If any fields on rule logic line contain a ‘,’ (comma) then place double
quotes around the field so that the parser doesn’t get confused, as
commas are also used to delimitate fields.
When specifying operands in a logic line they can just be a value too.
The various types of operands are described in this section, including example
usage.
a.currency Text label to describe the currency that the account is in. Can
used visually or in alerts to display amounts nicely.
a.gmtOffset Returns the current difference between GMT time and the
local computer time in seconds, taking into account switch to
winter or summer time. Depends on the time settings of your
computer.
a.tb Numbers of bars under test for our stats. Will vary depending
on what ‘how far back’ is set in CONFIG | Stats /
Optimization. Useful for indicator inputs to tell indicator how
many bars (candles) to calculate over.
Example, open trade if TDI green value crosses 50, where TDI is green is being
captured and stored in ref TDIgrn:
,i.TDIgrn,/>,50,TRADE_OPEN
Note, the / will invert if evaluating for a sell, i.e. > automatically becomes a <
Note, if the Weighting box is not blank then the system to derive the buy/sell
indication from the indicator and return 100 for buy and -100 for sell. If you wish to
access the raw indicator value with Weighting box set then use a ~ before the
reference ID, e.g. i.~ma
Some functions contain the word ‘auto’ in their name. That means they will be auto
inverted when being evaluated for a sell. A good example of this is
f.pipsDiffAuto(<price1>;<price2>), which will return pips difference of price1-price2
when evaluating for a buy and give price2-price1 for sell. You should find that this will
make writing rules easier without having a specify separate lines for buy and for sell.
Many functions have a ‘period’ parameter which refers to chart period. Can be 0 for
current or something like M15. Another common parameter is ‘shift’, which refers to
candle shift where 0 is live candle and 1 is candle just closed and 2 is candle before
that and so on.
objName parameter can just be object name but if starts with * then will add
rwfx_<appID>_uo_ which allows object to identified as from RunwiseFX and auto
deleted if EA removed from chart.
f.candleAvg( Will examine chart and return the average number of pips
numCandles; between high and low of specified number candles, given
period; by numCandles. Optionally, candle period and shift can be
shift) supplied for the operation. Note, if shift is not specified
then will use 1.
f.iLowset(period;shift; Returns shift of highest candle high price. Will check back
count) number of candles given by count. If count is omitted then
will return highest price in the chart.
f.iHighest(period;shift; Returns shift of lowest candle low price. Will check back
count) number of candles given by count. If count is omitted then
will return highest price in the chart.
f.iLowestClose( Returns lowest candle close price. Will check back number
period;shift; of candles given by count. If count is omitted then will
count) return highest price in the chart.
f.iHighestPrice( Returns highest candle high price. Will check back number
period;shift;count) of candles given by count. If count is omitted then will
return highest price in the chart.
f.iLowestPrice( Returns lowest candle low price. Will check back number
period;shift;count) of candles given by count. If count is omitted then will
return highest price in the chart.
f.objLatest(objType; Returns latest, i.e. most recent, object details. Useful for
f.tpExit(level) Returns if take profit exit is enabled for supplied take profit
level, numbered 1 upwards. Will be 1 if enabled, else 0 if
not.
f.tpPrice(level) Returns the price that the supplied take profit level is set
to. Can return 0 if not set.
f.tpTaken(level) Returns 1 if take profit level has been taken, i.e. already
reached. 0 if not.
t.buySell Returns ‘buy’ of buy trade or being evaluated for buy and
otherwise, ‘sell’
t.durationBars How long trade has been opened for. If 0 the still in candle
where trade was opened.
t.peakProfit Peak profit amount trade has reached whilst been open
t.peakRR Peak risk reward reached whilst trade has been open
Parameters can use single quotes for strings. Parameters can also reference
operands by enclosing them inside curly brackets {}. E.g.:
ALERT(‘TDI yellow is now {i.tdiYellow}’)
This would raise an alert and text would include the value of tdiYellow indicator.
ALERT(<msg>) Will issue an alert with the text supplied in <msg>. Note, the alert will
be push notified / emailed if the EA has been configured to do this via
it’s inputs. You must have logic in the rule to prevent repeated alerts
that are not desired.
ALERT_LOCAL(<msg) Similar to alert. However, we only be shown in the alert pop-up and not
push notified or emailed, even if the EA has been configured to that.
AND Not strictly a command but is used to join logic lines together. AND
means the line and lines above must match the following lines (see OR
as well).
CLEAR_BREAKEVEN Will clear the breakeven tick box on the EA control panel for the
direction being evaluated (see SET_BREAKEVEN).
END_EVAL( Will stop the rule from being evaluated any further. An optional
<failComment>) <failComment> will be shown on the status on the EA control panel,
which is intended to indicate why the rule is not being evaluated any
further.
FORCE_CLOSE( Will close any open trade with the specified percentage of the trade to
<prct>) close. If <prct> is not specified then the entire trade will closed,
including any scale-in tickets. The command will execute as long as
the EA is not set to manual mode for the direction (see
TRADE_CLOSE that only has an effect if the EA is in alert/trade mode
for the direction).
GUI_SET_LABEL( Will set GUI control panel text label item with supplied text and optional
<name>;<text>; color and font size.
<color>;<size>)
MESSAGE_CONFIRM( Will pop-up a message dialog box showing the supplied <msg>. If the
<msg>) Cancel button is pressed then the rule will not be evaluated any
further. Useful for confirming actions, e.g. button press, with the user.
PLAY_SOUND( Will play wav file located in Sounds folder of Data Folder. If no
<wavFileName>) parameter is specified then any playing sound will be stopped.
SCREENSHOT Will take screenshot of current chart that the EA is running on and
place in the File folder of the Data Folder. Screen shot files are name
rwfx_ss_* and can be controlled by Gen_screenShot* input
properties.
SEND_EVENT Will send text string to other instances of the EA, includig itself. This
can be picked up in a trade rule of type event and acted upon. The
string sent can be accessd by t.eventStr operand. See rule s-asbe in
the library as an example.
SEND_MAIL( Will email (if MetaTrader has been configured to do this) with the
<subject>;<msg>) supplied subject and message.
SET_HIDDEN_SL(<price>; Will set hidden stop loss price and optionally stop loss mode. Note,
<mode>) hidden SL price only updated if mode is RULE or if a mode is specified,
e.g. MAN
SET_HIDDEN_TP(<level>; Will set hidden take profit (switch from auto to manual) of supplied level
<price>) (number 1 upwards) and supplied price.
OBJ_CREATE( Will create chart object of specified name and type. If <name> starts
<name>;<type>) with ‘*’ then the runwiseFX application ID will be inserted that allows
the object to automatically deleted if the EA is removed from the chart.
Note, initially objects are created with a location so they cannot be
seen. TIP: Rule of type initGui can be used to create objects before the
EA control panel is created, so they appear behind the control panel.
<type> = object type OBJ_* with the OBJ_ omitted, e.g. HLINE will
create a horizontal line object. A full list of object types can be found at:
http://docs.mql4.com/constants/objectconstants/enum_object
OBJ_SET_COLOR( Will set object color and optionally style. <color> can be RGB comma
<name>;<color>; separated or one of web –color constants, e.g. clrMagenta, see:
<style>) http://docs.mql4.com/constants/objectconstants/webcolors.
OBJ_SET_FONT( Will set object font size and font name. If either parameter is blank (or
<name>;<fontSize>; in the case <fontName> not supplied) then no change will be made to
<fontName>) that property.
OBJ_SET_POSITION( Will set position of the object on the chart with supplied X and Y co-
<name>;<x>;<y>; ordinates and corner settings. Corner can be one of LU (left upper), LL
<corner>) (left lower), RL (right lower), RU (right upper). Note, if any parameter is
blank then it will not be set, also <corner> may be omitted.
OBJ_ SET_PT( Will set object price and time. This can be used for objects that are
<name>; placed on the chart at a particular time and price. Note, <price2> and
<price1>;<time1>; <time2> are optional. <time1> can also be omitted just to set price, e.g.
<price2>;<time2>;…) for horizontal line. If <price1> is blank but <time1> is set then just
TIME1 will be set, e.g. for vertical lines.
OBJ_SET_TEXT( Will set the text property of the object with the supplied text and
<name>;<text>; optional color (see OBJ_SET_COLOR for more details about setting
<color>) object colors)
RESET_ALERT Will reset alert price so that alert/trade is possible when indicators line-
up. Otherwise, will need to get signal in opposite direction for reset.
SET_VAR(<name>; Will set a global variable of supplied name and value. Note, value has
<value>;<symbol>; to be a number. Optionally <symbol> can also be specified to set of a
<temp>) specific symbol, which if ‘*’ will cause the variable for all symbols to be
set. If <symbol> = ‘..’ then will replace with current symbol and period,
concatenated together. If the optional <temp> is set as TEMP then the
global variable will be marked as temporary, i.e. not preserved
between closedown/restart of MetaTrader.
Note, if name begins with # then variable stored within EA rather than
using MetaTrader’s global variables. Note, currently if # used then
SEND_NOTIF(<msg>) Will send push notification email (if MetaTrader has been configured to
do this) with the supplied message.
SET_BREAKEVEN Will set the breakeven tick box on the EA control panel for the direction
being evaluated. This command should only be issued when a trade is
open and in profit – if not in profit then would immediately exit the trade
(see CLEAR_BREAKEVEN).
SET_PEND(<price>; Set pending line for the direction being evaluated, including setting
<action>) type and mode. <action> as shown in Pend: pop-up, e.g. TT. Note, the
limit/stop type will be set depending on where the line is placed in
relation to the price. However, if the trade is open then the type will be
set to scale-in, provided the price is appropriate for a scale-ion, e.g. if
buy then price needs to be above current price. The <action> can be
omitted to leave as is.
SET_PEND_PRICE( Set the pending line price for the direction being evaluated. However,
<price>) the price will not be updated if it causes the pending line to jump over
current price, e.g. from Limit to Stop type, i.e. is only intended to
update the price not the type (Limit/Stop).
TRADE_CLOSE( Will close any open trade (or alert if alert mode is set) with the
<prct>) specified percentage of the trade to close, if the mode is set to trade. If
<prct> is not specified then the entire trade will closed, including any
scale-in tickets. See FORCE_CLOSE that will work regardless of mode
setting unless the mode is manual.
TRADE_OPEN( Will open a trade in the direction that is being evaluated using the
<riskAdjustPrct>; settings on the EA control panel, provided mode is set to trade. Will
<alertText>) alert if mode is set to alert. If a trade is already open then no action will
be taken. Note, if you want to open additional tickets then use the
SCALE_IN command. The optional <riskAdjust> can be used to adjust
the risk that has been specified on the EA control panel, e.g. if risk is
3% of account but this parameter is 10, i.e. 10%, then the risk used will
be 3.3%. Negative values can be used to reduce risk. This parameter
allows (for example) rules to adjust risk based the probability of the
trade being successful. The optional <alertText> will replace the
standard text used when the EA is in alert mode rather than trade
mode.
VOID_ALERT Sets the alert price 0, which means won’t open a trade even if
TRADE_OPEN command is run (will just show as ‘stale’). Will have to
wait to next time alert is reset. Generally, this is when the market is in
the opposite direction.
Be careful if using nested parameters, where need to use single quotes so that will
be parsed correctly. For example,
OBJ_SET_PT(*confirmPrice;'{f.priceAddPipsAuto({g.breakPrice};7
)}') - will set confirmPrice chart object with value from GUI control breakPrice
offset by 7 pips
Email: [email protected]
Web: www.runwisefx.com
END OF DOCUMENT