Forex Practice

 

Sell your forex services here
People who are interested in currency trading are looking for you here.
www.ForexPractice.com
Your ad could be here
Forex Practice
Your ad could be here

 

Programming user-defined indicators with Forex Practice

In this page:

 

General

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

  • Explanations here assume you are familiar with JavaScript. If you are not familiar with JavaScript but know another programming language, just google for it, it is really not a difficult language...
  • The scripting language follows ECMA-262 standard (with few small exceptions).
  • JavaScript here is not used for site-building, therefore there is no support for HTML-DOM objects (such as document or window) and other objects specific to internet site programming.
  • Standard objects such as Math and Date are supported.
  • A new object is introduced using which you can interact with our application. see more details regarding the fp object below.
  • MQL4 scripts are not compatible with this language. MQL4 is C-like, while this language is Javascript-like. This language is much simpler and is better for beginners, yet allow complex programming techniques (including object-oriented programming) for advanced users.
  • The system requirements may increase according to your script demands. Your script may require additional RAM memory in order to function properly.
  • This is an experimentally feature and may change in the future.
  • RTFM !! Read This Fabulous Manual. Most question sent to us are already answered here. Please read this manual before submitting your questions. It is a bit long, but it's worth it.

 

Usage overview

Select the following menu item in order to insert your script:
toolbar button Definitions / Define a new indicator.

Use your defined indicator in the chart
toolbar button Indicators / Add to chart / User defined indicator.
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.
Definitions / Debugging console.

 

Hello World Script

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,

 

Global Scope

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-

 

Interaction with the application

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;

 

API References

Method: inform(message)

About: Send a normal-message to the debugging-console.

Returns: none.

Parameter message: String.

Contexts: init, newdata

See also:
Method: warn(message)

About: Send a warning-message to the debugging-console.

Returns: none.

Parameter message: String.

Contexts: init, newdata

See also:
Method: error(message)

About: Send an error-message to the debugging-console and halt running the script.

Returns: none.

Parameter message: String.

Contexts: init, newdata

See also:
Method: defineNumber(fieldname, precision)

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.

See also:
Method: defineFlag(fieldname, nameTrue, nameFalse)

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.

See also:
Method: Method: getValue(fieldname, defaultVal, ago)

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).

See also:
Method: getFlag(fieldname, defaultVal, ago)

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.

See also:
Method: setNumber(fieldname, value)

About: Set numeric value to a field.

Returns: none.

Parameter fieldname: String. Any field previously defined with defineNumber.

Parameter defaultVal: Numeric.

Contexts: newdata.

See also:
Method: setFlag(fieldname, value)

About: Set boolean value to a field.

Returns: none.

Parameter fieldname: String. Any field previously defined with defineFlag.

Parameter defaultVal: Boolean.

Contexts: newdata.

See also:
Method: drawLine(fieldname, graphname, color, penstyle, sensitivity)

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.

See also:
Method: drawStaticBaseline(y, graphname, color, penstyle)

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.

See also:
Method: drawDynamicBaseline(fieldname, graphname, color, penstyle)

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.

See also:
Method: drawSignal(fieldnameFlag, graphname, fieldnameY, pos, color, symbol)

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.

See also:
Method: resetAccount()

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

Method: buy(lots)

About: Submit a buy order at market rate. This order may either:

  • Open a new trade at the desired direction.
  • Close an existing trade of the opposite direction.

Parameter lot: Numeric, Optional (default: 1.0). The amount of lots to order.

Returns: none.

Contexts: newdata

Method: sell(lots)

About: .

About: Submit a sell order at market rate. This order may either:

  • Open a new trade at the desired direction.
  • Close an existing trade of the opposite direction.

Parameter lot: Numeric, Optional (default: 1.0). The amount of lots to order.

Returns: none.

Contexts: newdata

Method: exitAllPositions()

About: Close any open trade at market rate. If no open trade exists this function does nothing.

Returns: none.

Contexts: newdata

See also:
Method: getAccountStatus()

About: Retrieve information whether there are open trades, and what is their direction.

Returns: One of account status values.

Contexts: newdata

See also:
Method: getName()

About: Retrieve the definition name (AKA script name).

Returns: String.

Contexts: init, newdata

Method: getBidSymbol()

About: Retrieve the symbol of the bid-currency. For example- USD, EUR, JPY, CHF, GBP.

Returns: String.

Contexts: init, newdata

See also:
Method: getAskSymbol()

About: Retrieve the symbol of the bid-currency. For example- USD, EUR, JPY, CHF, GBP.

Returns: String.

Contexts: init, newdata

See also:
Method: getTimeFrame()

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.

Contexts: init, newdata

Method: getDepth()

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.

See also:
Method: isNewBar()

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.

See also:
Method: isBarSealed()

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.

See also:
Method: rgb(red, green, blue)

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.

Contexts: init, newdata

See also:
Method: getColor(index)

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.

Contexts: init, newdata

See also:
Method: createIndicator(name)

About: Creates an objects that calculates certain predefined indicator. Read more about indicators objects.

Returns: Indicator object.

Parameter name: String.

Contexts: init, newdata

Predefined fields

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,

Parameters

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.

See also:

 

Indicators objects

Indicators are auxiliary objects to calculate certain predefined indicators or statistics. These objects are created by the createIndicator function. Supported indicators are-

#Indicatorname used by createIndicator function
1Simple statisticsSimple
2Simple Moving AverageSMA
3Exponential Moving AverageEMA
4Wilder SmoothingWilder
5Directional Movement IndexDMI
6Moving Average Divergence ConvergenceMACD
7Parabolic Stop and ReversalParSAR
8Stochastics oscillatorstochastics
9Williams %RWilliamsR
10Rate of ChangeROC
11Momentummomentum
12Relative Strength IndexRSI
13Commodity Channel IndexCCI
14De MarkerDeMarker

Using Indicators objects

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) {...}


}

 

Method: init(fieldname, value)

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.

Contexts: init, newdata

See also:
Method: reset()

About: Reinitializing the indicator. Reread all initializing parameters and clear all observations.

Returns: none.

Contexts: init, newdata

See also:
Method: set(fieldname, value)

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.

Contexts: init, newdata

See also:
Method: commit(isnew)

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.

Contexts: init, newdata

See also:
Method: autoset()

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

See also:
Method: Method: getValue(fieldname, defaultVal)

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.

Contexts: init, newdata

See also:
Method: getFlag(fieldname, defaultVal)

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.

Contexts: init, newdata

See also:

Supported indicator-objects

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.

 

Example: Pivot

Complexity: Simple

This example calculates a simple 3-factors pivot and draws it on the chart.
Preview.

 

Example: Moving Average and Bollinger Bands

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.

 

Example: Backtesting MACD

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.

See also

© Forex Practice 2004-2009.   Tue, 07 Sep 2010 14:11:53 GMT  

 

Forex Practice Get Firefox! Site Meter Valid XHTML 1.0 Frameset Valid CSS! Valid RSS!