
In this page:
You can program your own indicators and develop your own system using a JavaScript-like language. This powerful tool is aimed for advanced users.
Some quick notes before we dive into details
Select the following menu item in order to insert your script:
.
Use your defined indicator in the chart
.
You may add parameters specific to currecnt script running. You may use the same definition multiple times with different parameters each time.
Examine non-graphical results and errors in the debugging console.
.
The minimal script should implement at least two functions: init and newdata - none takes parameters.
The init function is the entry point of the script and is called once. It should be used for definitions and allocations of resources needed for your indicator or backtest system.
The newdata function is called every time there is new data (time or rates has changed), ie, it is called for each bar in the chart at least once, but commonly more. The function is commonly called evey 1-minute history change, so for timeframes longer than 1-minute it may be called several times for each bar. The methods isNewBar and isBarSealed may help you determine whether the calling is for a new bar or an update of the last one.
Interaction with the application is done using a global object named fp. For example,
There are few limitations on using the global scope. all your code should reside inside functions, avoid writing in the global scope. You may add your own functions and objects, but you should call them and use them only from the context of init or newdata functions.
When using the var keyword the variable is known only until end of current scope. When using variables without this keyword the conent of the variable is preserved. A good practice is to use the var keyword whenever possible, and omit it only when you really want to preserve data between calls of init and newdata. For example-
The predefined object fp has the following interface :
function ForexPractice()
{
/* PREDEFINED COLORS */
this.COLOR_BLACK = ... ;
this.COLOR_WHITE = ... ;
this.COLOR_GRAY = ... ;
this.COLOR_DARK_GRAY = ... ;
this.COLOR_LIGHT_GRAY = ... ;
this.COLOR_RED = ... ;
this.COLOR_GREEN = ... ;
this.COLOR_BLUE = ... ;
this.COLOR_YELLOW = ... ;
this.COLOR_ORANGE = ... ;
this.COLOR_PINK = ... ;
this.COLOR_CYAN = ... ;
this.COLOR_MAGENTA = ... ;
/* PREDEFINED PEN-STYLES */
this.PENSTYLE_SOLID = ... ;
this.PENSTYLE_DASH = ... ;
this.PENSTYLE_DOT = ... ;
/* PREDEFINED SYMBOLS */
this.SYMBOL_BUY = ... ;
this.SYMBOL_SELL = ... ;
this.SYMBOL_OPEN = ... ;
this.SYMBOL_CLOSE = ... ;
this.SYMBOL_EXIT_LONG = ... ;
this.SYMBOL_EXIT_SHORT = ... ;
/* PREDEFINED LOCATIONS */
this.POS_ABOVE = ... ;
this.POS_BELOW = ... ;
/* ACCOUNT STATUS */
this.POSITION_UNKNOWN = ... ;
this.POSITION_NONE = ... ;
this.POSITION_LONG = ... ;
this.POSITION_SHORT = ... ;
/* NOTIFICATIONS */
/* Send a message to the debugging-console */
this.inform = function(message) {...};
/* Send a warning-message to the debugging-console */
this.warn = function(message) {...};
/* Send an error-message to the debugging-console and
halt running the script. */
this.error = function(message) {...};
/* FIELDS DEFINITIONS */
/* define field of numbers (flaoting point values). */
this.defineNumber = function(fieldname, precision) {...};
/* define field of flags (boolean values) */
this.defineFlag = function(fieldname, nameTrue, nameFalse) {...};
/* VALUE RETRIEVING */
/* Retrieve a number value of either a defined-field, a predefiend-field or a parameter. */
this.getValue = function(fieldname, defaultVal, ago) {...};
/* Retrieve a state of a defined flag */
this.getFlag = function(fieldname, defaultVal, ago) {...};
/* VALUE SETTING */
this.setNumber = function(fieldname, value) {...};
this.setFlag = function(fieldname, value) {...};
/* DRAWINGS DEFINITIONS */
this.drawLine = function(fieldname, graphname, color, penstyle, sensitivity) {...};
this.drawStaticBaseline = function(y, graphname, color, penstyle ) {...};
this.drawDynamicBaseline = function(fieldname, graphname, color, penstyle ) {...};
this.drawSignal = function(fieldnameFlag, graphname, fieldnameY, pos, color, symbol) {...};
/* ACCOUNT */
this.resetAccount = function() {...};
this.buy = function(lots) {...};
this.sell = function(lots) {...};
this.exitAllPositions = function() {...};
this.getAccountStatus = function() {...};
/* MISCELLANEOUS */
this.getName = function() {...};
this.getBidSymbol = function() {...};
this.getAskSymbol = function() {...};
this.getTimeFrame = function() {...};
this.getDepth = function() {...};
this.isNewBar = function() {...};
this.isBarSealed = function() {...};
this.rgb = function(red, green, blue) {...};
this.getColor = function(index) {...};
this.createIndicator = function(name) {...};
}
/* the object is already predefined for you in the global scope and can be accessed from any function */
var fp= new ForexPractice;
About: Send a normal-message to the debugging-console.
Returns: none.
Parameter message: String.
About: Send a warning-message to the debugging-console.
Returns: none.
Parameter message: String.
About: Send an error-message to the debugging-console and halt running the script.
Returns: none.
Parameter message: String.
About: Define a numeric-field. Numeric-fields are arrays of numeric-variables with a value for each bar in the chart. A new element is automatically attached to the array's head every time a new bar is created in the chart, tail of the array may be automatically truncated once the array is longer then supported length (about 500 bars). If rates of currecnt bar are updated - the field-value of current bar is reset.
Returns: none.
Parameter fieldname: String. A unique valid name. It should not be any of the predefined fields.
Parameter precision: Numeric, Optional, Range: 0 to 8. The amount of fraction digits to display right to the floating-point. This affect only the display and have no influence on the stored values.
Contexts: init.
About: Define a boolean-field. Boolean-fields are arrays of boolean-variables with a value for each bar in the chart. A new element is automatically attached to the array's head every time a new bar is created in the chart, tail of the array may be automatically truncated once the array is longer then supported length (about 500 bars). If rates of currecnt bar are updated - the field-value of current bar is reset.
Returns: none.
Parameter fieldname: String. A unique valid name. It should not be any of the predefined fields.
Parameter nameTrue: String, Optional. A label to display when the flag is set to true.
Parameter nameFalse: String, Optional. A label to display when the flag is set to false.
Contexts: init.
About: Retrieve a numeric value of either a defined-field, a predefiend-field or a parameter.
Returns: Numeric value.
Parameter fieldname: String. Any predefined field, or any field previously defined with defineNumber, or parameter name.
Parameter defaultVal: Numeric, Optional (Default: 0). A default value to be return if the specified field-value could not be retrieved.
Parameter ago: Numeric, Optional (Default: 0). Indicate which bar relative to current should be inquired. When this value is zero the value attached to current bar is returned, 1 for previous bar, and so forth. If value is greater than getDepth the defaultVal will be returned.
Contexts: init (only for parameters), newdata (for all fields).
About: Retrieve a state of a defined flag.
Returns: Boolean value.
Parameter fieldname: String. Any field previously defined with defineFlag.
Parameter defaultVal: Boolean, Optional (Default: false). A default value to be return if the specified field-value could not be retrieved.
Parameter ago: Numeric, Optional (Default: 0). Indicate which bar relative to current should be inquired. When this value is zero the value attached to current bar is returned, 1 for previous bar, and so forth. If value is greater than getDepth the defaultVal will be returned.
Contexts: newdata.
About: Set numeric value to a field.
Returns: none.
Parameter fieldname: String. Any field previously defined with defineNumber.
Parameter defaultVal: Numeric.
Contexts: newdata.
About: Set boolean value to a field.
Returns: none.
Parameter fieldname: String. Any field previously defined with defineFlag.
Parameter defaultVal: Boolean.
Contexts: newdata.
About: Draw a continuous line on the chart.
Returns: none.
Parameter fieldname: String. Any field previously defined with defineNumber. The values of this field will be used to determine the vertical position of the dot through which the line will go.
Parameter graphname: String. If the parameter is set to null the drawing will be put in the main pane. Otherwise will draw on a pane with the specified name. If no pane with that name exists - a new pane is created.
Parameter color: Numeric, Optional (default: COLOR_GRAY). The color to use - any of the predefeind colors, or any value returned by rgb or getColor.
Parameter penstyle: Numeric, Optional (default: PENSTYLE_SOLID). The pen-style to use - any of the predefeind pen-styles.
Parameter sensitivity: Numeric, Optional. Sensitivity implies which values are considered discrete for grid drawing and vertical-lines placement. The discrete values are 1/sensitivity. for example, sensitivity of 10000 will match pips of most tickers (ie, 0.0001).
Contexts: init.
About: Draw an horizontal line on the chart at a predefined vertical location.
Returns: none.
Parameter y: Numeric. Vertical position at which the line will be placed.
Parameter graphname: String. If the parameter is set to null the drawing will be put in the main pane. Otherwise will draw on a pane with the specified name. If no pane with that name exists - a new pane is created.
Parameter color: Numeric, Optional (default: COLOR_GRAY). The color to use - any of the predefeind colors, or any value returned by rgb or getColor.
Parameter penstyle: Numeric, Optional (default: PENSTYLE_DASH). The pen-style to use - any of the predefeind pen-styles.
Contexts: init.
About: Draw an horizontal line on the chart at a changing vertical position.
Returns: none.
Parameter fieldname: String. Any field previously defined with defineNumber. The last value of this field will be used to determine the vertical position at which the line will be placed.
Parameter graphname: String. If the parameter is set to null the drawing will be put in the main pane. Otherwise will draw on a pane with the specified name. If no pane with that name exists - a new pane is created.
Parameter color: Numeric, Optional (default: COLOR_GRAY). The color to use - any of the predefeind colors, or any value returned by rgb or getColor.
Parameter penstyle: Numeric, Optional (default: PENSTYLE_DASH). The pen-style to use - any of the predefeind pen-styles.
Contexts: init.
About: Draw signals on the chart according to a flag field.
Returns: none.
Parameter fieldnameFlag: String. Any field previously defined with defineFlag. A symbol will be placed For every bar the field is true.
Parameter graphname: String. If the parameter is set to null the drawing will be put in the main pane. Otherwise will draw on a pane with the specified name. If no pane with that name exists - a new pane is created.
Parameter fieldnameY: String. Any field previously defined with defineNumber. The value will be used to determine the vertical location of the symbol.
Parameter pos: Numeric, Optional. Any of the predefined locations to indicate whether the symbol will be placed slightly above the vertical position indicated by the fieldnameY, or below it. The offset is useful to avoid hiding the graph.
Parameter color: Numeric, Optional (default: COLOR_GRAY). The color to use - any of the predefeind colors, or any value returned by rgb or getColor.
Parameter symbol: Numeric, Optional (default: SYMBOL_OPEN). The symbol to use - any of the predefeind symbols.
Contexts: init.
About: This function initialize the account. This account must be reset before any call to other account functions. The account is reset and any trades or orders previously attached to the account are forgotten, including closed positions.
ATTENTION: The account functions can be used only in a single script at a time. Do not run multiple scripts that use the account functions concurrently. That implies that you should backtest only one ticker in one timeframe at a time.
Returns: none.
Contexts: init
About: Submit a buy order at market rate. This order may either:
Parameter lot: Numeric, Optional (default: 1.0). The amount of lots to order.
Returns: none.
Contexts: newdata
About: .
About: Submit a sell order at market rate. This order may either:
Parameter lot: Numeric, Optional (default: 1.0). The amount of lots to order.
Returns: none.
Contexts: newdata
About: Close any open trade at market rate. If no open trade exists this function does nothing.
Returns: none.
Contexts: newdata
About: Retrieve information whether there are open trades, and what is their direction.
Returns: One of account status values.
Contexts: newdata
About: Retrieve the symbol of the bid-currency. For example- USD, EUR, JPY, CHF, GBP.
Returns: String.
About: Retrieve the symbol of the bid-currency. For example- USD, EUR, JPY, CHF, GBP.
Returns: String.
About: Retrieve a code for the chart's time-frame. The code is minute-based. For example, 1 implies 1-minute bars, 60 implies 1-hour bars, 1440 implies 1-day bars, etc.
Returns: Numeric.
About: Retrieve the amount of bars already processed in this chart. This is actually the limit of the ago parameter of the getValue and getFlag methods.
Returns: String.
Contexts: newdata.
About: The method returns true if the call to newdata was for a new bar, or false if this is an update for last bar.
For example, on a 5-minutes timeframe chart - this methods returns true for data representing history of the times 00:01, 00:06, 00:11, 00:16 etc.
Returns: Boolean value.
Contexts: newdata.
About: The method returns true if the call to newdata is the last update of the current bar, and successive calls to newdata will be for a new bar. Data retured from getValue for the most recent bar (ie, the ago parameter is zero) will be the final and committed for this bar.
For example, on a 5-minutes timeframe chart - this methods returns true for data representing history of the times 00:05, 00:10, 00:15, 00:20 etc.
If your calculation should refer only to committed bars, consider the following example,
Returns: Boolean value.
Contexts: newdata.
About: Creates a color with the specified red, green and blue components. The returned color can be used by any of the drawing methods.
Returns: Numeric.
Parameter red: Numeric, Range: 0 to 255.
Parameter green: Numeric, Range: 0 to 255.
Parameter blue: Numeric, Range: 0 to 255.
About: Return one of the predefined colors according to index. The returned color can be used by any of the drawing methods.
Returns: Numeric.
Parameter index: Numeric, Range: 0 to 12. Zero-base index. 0 - Black, 1 - White, 2-4 Grays, 5-7 RGB basic colors, 8-12 Other colors. More colors may be added in the future. If parameter is out of range an arbitrary color will be returned.
About: Creates an objects that calculates certain predefined indicator. Read more about indicators objects.
Returns: Indicator object.
Parameter name: String.
open - Return a numeric value representing the opening-rate of the specified chart's bar.
high- Return a numeric value representing the highest-rate of the specified chart's bar.
low - Return a numeric value representing the lowest-rate of the specified chart's bar.
close - Return a numeric value representing the closing-rate of the specified chart's bar.
time - Return a numeric value representing the closing-time of the specified chart's bar as milliseconds since epoch. in order to transform it into a Date object please use the setTime method of the Date object. Example,
You can pass numeric values to the script in the Indicators/User Defined dialog. This way you can run the same script multiple times with different parameters.
Indicators are auxiliary objects to calculate certain predefined indicators or statistics.
These objects are created by the createIndicator function. Supported indicators are-
| # | Indicator | name used by createIndicator function |
|---|---|---|
| 1 | Simple statistics | Simple |
| 2 | Simple Moving Average | SMA |
| 3 | Exponential Moving Average | EMA |
| 4 | Wilder Smoothing | Wilder |
| 5 | Directional Movement Index | DMI |
| 6 | Moving Average Divergence Convergence | MACD |
| 7 | Parabolic Stop and Reversal | ParSAR |
| 8 | Stochastics oscillator | stochastics |
| 9 | Williams %R | WilliamsR |
| 10 | Rate of Change | ROC |
| 11 | Momentum | momentum |
| 12 | Relative Strength Index | RSI |
| 13 | Commodity Channel Index | CCI |
| 14 | De Marker | DeMarker |
All indicator-objects have the following interface-
function IndicatorObj()
{
/* INITIALIZING */
this.init = function(fieldname, value) {...}
this.reset = function() {...}
/* SETTING OBSERVATIONS */
this.set = function(fieldname, value) {...}
this.commit = function(isnew) {...}
this.autoset = function() {...}
/* VALUE RETRIEVING */
/* Retrieve a numeric value */
this.getValue = function(fieldname, defaultVal) {...}
/* Retrieve a state of a flag */
this.getFlag = function(fieldname, defaultVal) {...}
}
About: Set an initializing parameter. Once all parameters are set - call reset.
Returns: none.
Parameter fieldname: String. A predefined field.
Parameter value: Numeric. A value to which the parameter should be set.
About: Reinitializing the indicator. Reread all initializing parameters and clear all observations.
Returns: none.
About: Set an observation parameter. Once all parameters are set - call commit.
Returns: none.
Parameter fieldname: String. Any predefined field relevant for this indicator.
Parameter defaultVal: Numeric. A value to which the parameter should be set.
About: Commit all set parameters as an observation.
Returns: none.
Parameter isnew: Boolean, Optional (Default: true). true - add a new observation, false - replace the last observation. Common usage is to pass the value retrieved from isNewBar.
About: Add observations to the indicator based on current bar rates. This is commonly equivalent to the following code-
ATTENTION: Not all indicators support this method, yet this is a preferred way for those which do support it.
Returns: none.
Contexts: newdata
About: Retrieve a numeric value of a field.
Returns: Numeric value.
Parameter fieldname: String. Any predefined field relevant for this indicator.
Parameter defaultVal: Numeric, Optional (Default: 0). A default value to be return if the specified field-value could not be retrieved.
About: Retrieve a state of a flag.
Returns: Boolean value.
Parameter fieldname: String. Any predefined field relevant for this indicator.
Parameter defaultVal: Boolean, Optional (Default: false). A default value to be return if the specified field-value could not be retrieved.
Indicator: Simple statistics.
creation name: simple
autoset method: not-supported.
initializing fields: none.
setting observation fields: val.
retrieving numeric fields: mean, sum, ss (sum-of-squares), count, std (standard deviation), var (variance).
retrieving flag fields: none.
Indicator: Simple Moving Average.
creation name: SMA
autoset method: supported.
initializing fields: periods.
setting observation fields: val.
retrieving numeric fields: mean, count, std (standard-deviation).
retrieving flag fields: valid.
Indicator: Exponential Moving Average.
creation name: EMA
autoset method: supported.
initializing fields: periods.
setting observation fields: val.
retrieving numeric fields: mean, count, std (standard-deviation).
retrieving flag fields: valid.
Indicator: Wilder Smoothing.
creation name: Wilder
autoset method: supported.
initializing fields: periods.
setting observation fields: val.
retrieving numeric fields: mean, count.
retrieving flag fields: valid.
Indicator: Directional Movement Index
creation name: DMI
autoset method: supported.
initializing fields: periods, smooth.
setting observation fields: close, high, low.
retrieving numeric fields: adx, di+, di-.
retrieving flag fields: valid.
Indicator: Moving Average Divergence Convergence
creation name: MACD
autoset method: supported.
initializing fields: short, long, signal.
setting observation fields: val.
retrieving numeric fields: short, long, macd, signal, diff.
retrieving flag fields: valid.
Indicator: Parabolic Stop and Reversal
creation name: ParSAR
autoset method: supported.
initializing fields: acceleration (acceleration percent), max (max. acceleration percent).
setting observation fields: high, low.
retrieving numeric fields: sar.
retrieving flag fields: valid, short, long.
Indicator: Stochastics Oscillator
creation name: stochastics
autoset method: supported.
initializing fields: k, d, slow.
setting observation fields: close, high, low.
retrieving numeric fields: k, d.
retrieving flag fields: valid.
Indicator: Williams %R
creation name: WilliamsR
autoset method: supported.
initializing fields: periods.
setting observation fields: close, high, low.
retrieving numeric fields: r.
retrieving flag fields: valid.
Indicator: Rate of Change
creation name: ROC
autoset method: supported.
initializing fields: periods.
setting observation fields: val.
retrieving numeric fields: roc.
retrieving flag fields: valid.
Indicator: Momentum
creation name: momentum
autoset method: supported.
initializing fields: periods.
setting observation fields: val.
retrieving numeric fields: momentum.
retrieving flag fields: valid.
Indicator: Relative Strength Index
creation name: RSI
autoset method: supported.
initializing fields: periods.
setting observation fields: val.
retrieving numeric fields: rsi.
retrieving flag fields: valid.
Indicator: Commodity Channel Index
creation name: CCI
autoset method: supported.
initializing fields: periods.
setting observation fields: close, high, low.
retrieving numeric fields: cci.
retrieving flag fields: valid.
Indicator: De Marker
creation name: DeMarker
autoset method: supported.
initializing fields: periods.
setting observation fields: high, low.
retrieving numeric fields: dm.
retrieving flag fields: valid.
Complexity: Simple
This example calculates a simple 3-factors pivot and draws it on the chart.
Preview.
Complexity: Medium
This example calculates and draws the moving-average and Bollinger-bands and also signals when the rates become volitile and passes a certain threshold of the standard-deviation.
Preview.
Complexity: Medium
This example backtest MACD. It simulates buying whenever MACD crosses the zero from negative to positive value, and simulate selling whenever MACD crosses the zero from positive to negative value.