Collections, objects, and properties in the framework

2.1 Framework collections

All the collections in the framework are Dictionary objects, though some of them modify or extend the standard dictionary functions and behaviour.

You can listen for changes to prices or in the order list using an OnMessage() handler. You need to make explicit requests for prices which you are interested in. Prices in the Instruments list do not automatically update.

2.2 Framework objects

The Framework object contains the following sub-objects describing the current Sway Charts Pro environment:

There is also a class which is widely used as a response from actions such as trading requests and dialogs:

2.3 Framework properties

The framework provides the following properties. All of these are read-only.

2.4 Framework.Instruments collection

The framework provides a list of all the markets available on the current trading account. The Framework.Instruments collection is a Dictionary of Sway.Instrument objects keyed by their instrumentId values. For example, you can get a specific market using Instruments.get() or iterate through all markets using Instruments.forEach().

2.4.1 Instruments.get(), Instruments.getOrBlank(), and standardisation

Sway Charts Pro is designed to work with FX/CFD platforms, and they have almost no standardisation of market names and IDs across different brokers, or even between accounts with the same broker. Sway Charts Pro tries to impose some standardisation of its own: for example, it will try always to give the euro-dollar FX pair the instrumentId "EUR/USD". But there are limits to what is possible.

As a result, Instruments.get() is not a standard dictionary getter. Its behaviour is overridden. If you do a get() for an instrumentId which does not exist, then get() will try a number of other possible matches:

· Does your key match an instrument's .caption?

· For fx markets, does your key match the base currency + quote currency? For example, if you pass in "EURUSD" (and the instrumentId of the market is "EUR/USD", and doesn't match), is there an instrument where the .baseCurrency is EUR and the .quoteCurrency is USD?

· Does your key match any common known aliases? For example, is your key "GOLD" which is known to match against an instrument where the ID is "XAU/USD"?

You also need to bear in mind that a market may exist on one account and not on another, as well as having different IDs. As a result, you need to consider the following possibility:

· Your widget/script stores the user's current settings, including a choice of market

· The user logs in to a different broker account and your widget/script is re-loaded

· The market in your saved settings does not exist on the new account

As a result, it is more common to use getOrBlank() than get(). If the key you ask for does not exist in the current list of markets, this returns a dummy Sway.Instrument with the following properties:

· instrumentId: your key for the missing market

· caption set to "?"

· Addition of missing:true

This potentially stops your code from breaking when the user logs in to an account where your saved settings refer to a market which doesn't exist. Without needing to do an explicit check for missing markets, your code will typically continue relatively gracefully – for example, displaying ? as the market's caption and zero prices.

2.4.2 Instruments.GetTradeableInstruments()

Helper function which returns an array of all instruments with tradeable:true, sorted by their caption.

2.4.3 Instruments.GetInstrumentCategories()

Helper function which returns an array of available instrument categories. It scans the list of markets, and builds a de-duplicated list from each market's categoryId.

2.5 Sway.Instrument object

The Sway.Instrument object describes an available market on the account. As well as providing properties which describe the market, it also has various helper functions.

2.5.1 Sway.Instrument properties

The properties of the Sway.Instrument are as follows. Names marked with * are derived properties – using Object.defineProperty() in Javascript – and will not get included if you clone the object.

Prices do not automatically update. You need to request prices which you are interested in.

2.5.2 Market categories

Sway Charts Pro does its own categorisation of markets (again looking to standardise across different platforms). Every Sway.Instrument is assigned a categoryId from the following Sway.InstrumentCategories list. For example, the euro-dollar FX pair (EUR/USD) will have categoryId=Sway.InstrumentCategories.FX_MAJOR.

You can translate these categories into readable text using TranslateInstrumentCategory().

2.5.3 Market data on spread-betting accounts

In the FX/CFD world, there are two different types of account:

· "Normal", CFD accounts. A trade in EUR/USD is buying or selling a number of euros, and has a profit in US dollars (converted to the account deposit currency, if different).

· Spread-bet accounts. All trades are denominated in the account deposit currency, such as GBP or AUD. A trade on EUR/USD is a bet in GBP (or AUD etc) on the EUR/USD price, on a "pound per point" basis. For example, if the EUR/USD price rises by 0.0001 (i.e. 1/100th of a US cent) then the trade has profit of GBP 1.

On a CFD account, the quoteCurrency of an FX pair will be the same as the underlyingCurrency. For an FX pair AAA/BBB, both the quoteCurrency and the underlyingCurrency will be BBB.

On a spread-bet account, the underlyingCurrency of an FX pair will be the account deposit currency, not the BBB of the AAA/BBB pair. All trades are bets denominated in the deposit currency.

2.5.4 Sway.Instrument helper functions

The Sway.Instrument provides some helper functions to assist with common conversion and calculation tasks in relation to a market.

2.6 Framework.Orders collection

The Framework.Orders collection is a Dictionary of all the pending/working orders and open trades on the account. The framework uses the same Sway.Order class to represent both pending orders and open trades (and also historic trades and credit movements).

Framework.Orders is then a collection of Sway.Order objects, keyed by their orderId.

To watch for changes in the order list, you can use an OnMessage() handler.

In addition to standard Dictionary functions, the Framework.Orders collection offers, for convenience, the following derived properties:

In other words, Orders.length (inherited from Dictionary) = Orders.openTradeCount + Orders.pendingOrderCount.

2.7 Sway.Order object

The framework uses the Sway.Order object to represent all of the following, because of their similarities:

· Pending/working orders

· Open trades

· Historic closed trades

· Historic, cancelled orders

· Credit movements on the account (such as deposits and withdrawals)

Some properties within the object are only applicable depending on its context (its orderType). For example, credit movements only have an orderId, reference, orderType, openTime, closeTime (same as openTime), profit, and comment (if the platform supports it). Properties such as instrumentId or volume are obviously inapplicable on a credit movement, and not defined.

2.7.1 Order types

The orderType of an Sway.Order can be any of the following members of the Sway.OrderTypes enumeration.

These values are numeric. You can reliably test for credit-movement types by looking at orderType >= Sway.OrderTypes.DEPOSIT – though it is more elegant to use the helper Sway.OrderTypes.IsCredit(orderType).

Granularity/accuracy of the subdivision between different types of credit movements depends on the broker platform. Some platforms will report everything as either only a deposit or withdrawal – i.e. a positive or negative movement, with no further detail.

Some platforms report commission and swap against individual orders, using the commission and swap properties, whereas others record these charges as credit movements against the account.

The Sway.OrderTypes enumeration is also used in relation to submitting trading requests, and has additional valid members in that context.

Stop-limit orders are not widely available. The account features indicate whether the account offers them.

2.7.2 Order-type helper functions

The framework provides a range of functions for helping to work with orderType values. For example:

var oppositeType = Sway.OrderTypes.Invert(Sway.OrderTypes.BUY_STOP);

2.8 Framework.Positions collection

As well as listing all the individual open trades on the account, in Instrument.Orders, the framework also calculates a total net position for each market. The Instrument.Positions collection is a Dictionary of Sway.Position objects keyed by their instrumentId properties.

(If the trading account is singleNetPosition:true, then the Positions collection should simply match the list of open trades because the back-end platform will only report one trade per market.)

The Instrument.Positions collection only contains entries for markets which have pending orders or open trades. If there is no open order/trade on a market, then it will have no entry in the Instrument.Positions collection.

However, the collection provides the following helper function for working with individual markets:

To watch for changes in positions and their profit, you can use an OnMessage() handler.

2.9 Sway.Position object

An Sway.Position object represents all the open trades in a market aggregated up into a single net position. It has the following properties:

The positionType is derived from the number of open trades and their directions. It is one of the Sway.PositionTypes enumeration:

2.10 Framework.TradeHistory collection

The Framework.TradeHistory collection is a Dictionary of all historic activity on the account: closed trades, cancelled pending orders, and also credit movements (provided that the back-end platform provides this data).

The history must be explicitly requested. It is empty by default.

To watch for the list being filled, and subsequently updated – you can use an OnMessage() handler.

If/once filled, the collection is a Dictionary of Sway.Order objects, keyed by their orderId properties. (As noted above, Sway.Order is used to represent a number of things, including all of trades, pending orders, and credit movements.)

2.11 Framework.Account object

The Framework.Account describes the broker trading account which Sway Charts Pro is currently logged into. It provides static information about the account such as its ID and deposit currency, plus changing metrics such as balance and margin usage.

Different accounts can have different capabilities – for example, availability of trailing stops or market depth. These are described by the Account.features.

2.11.1 Framework.Account properties

The Framework.Account has the following properties. To watch for changes in the account metrics – balance, equity etc – you can use an OnMessage() handler.

2.11.2 Account features

Different accounts can have different capabilities. The features available on the current account are described by its Account.features block.

2.12 Framework.Environment object

The Framework.Environment object contains information about the Sway Charts Pro environment:

The deviceId uniquely identifies a device such a web browser. The deviceId is "persistent" but not truly "permanent":

· It will be different for each web browser – Chrome, Safari etc – on a single computer.

· It will be different for an incognito/private browser window versus a normal window (and different each time an incognito session is opened)

· If the user uninstalls and reinstalls the mobile app, the deviceId will change

This deviceId in Framework.Environment is (deliberately) not the identifier for the device in the Sway Charts Pro mail system. The mail ID cannot be discovered programmatically by a widget, script, or UDIX.

2.13 Framework.Translation object

The Framework.Translation object contains functions for translating text-variables into the user's selected language for the Sway Charts Pro platform. Note: the language cannot change while code is running. It requires the user to log out of the software, and log back in.

The Framework.Translation object contains two properties:

The functions in Framework.Translation are as follows:

2.13.1 List of available language variables

The reference to the available language variables is simply the list provided by the Sway Charts Pro platform:

Here

This returns a plain-text file listing all the variables and their English equivalents, in the format variable=text. Some variables include placeholders, in the form @1, @2 etc. These are described in relation to TranslateItem().

2.13.2 Framework.Translation.TranslateDOM()

The framework supports a mechanism where language variables are included in HTML in curly brackets such as {SetMarket}, and Javascript can then use TranslateDOM() to scan the HTML and replace all these variables with the equivalent text in the user's selected language.

For example, partial HTML:

<div>

<div class="SectionHeader">{MarketList}</div>

<button title="{SetMarket}">{Market}</button>

etc.

Widget code can then automatically translate all these variables using TranslateDOM(), typically in OnLoad():

Framework.OnLoad = function() {

this.Translation.TranslateDOM();

… and other initialisation actions …

};

The TranslateDOM() can be given an optional parameter of the base node to start at. If omitted, it simply scans through the whole document body.

2.13.3 Framework.Translation.TranslateItem() and Framework.$T()

TranslateItem() translates a single variable into its equivalent text. For example:

// Will return "% of equity"

var text = Framework.Translation.TranslateItem("VolumePercentOfEquity");

Some of the available variables include placeholders, designed to be replaced by run-time values. For example, MaxSelectMarkets is defined as "Please select a maximum of @1 markets" where @1 is designed to be replaced at run-time by a number.

You can provide values for these placeholders by supplying an array as an optional second parameter to TranslateItem(). For example:

// Create message saying that the user is allowed to select a maximum of 20 markets

var maxAllowedMsg = Framework.Translation.TranslateItem("MaxSelectMarkets", [20]);

Note: because translation is so widely used within Sway Charts Pro, the framework provides a helper shortcut to stop programmers' fingers wearing down. You can use Framework.$T(…) as an abbreviation of Framework.Translation.TranslateItem(…). For example, the above code can also be written as follows:

var maxAllowedMsg = Framework.$T("MaxSelectMarkets", [20]);

2.13.4 Framework.Translation.TranslateError()

The TranslateError() function takes an FXB.Result object describing an error, for example resulting from a failed trading request, and generates the text to display to the user. For example:

Framework.SendOrder(def, function (MsgResult) {

if (MsgResult.result.isOkay) {

// Succeeded

} else {

// Failed. Display error message…

var errorText = Framework.Translation.TranslateError(MsgResult.result);

}

});

2.13.5 Framework.Translation.TranslateTimeframe()

The TranslateTimeframe() function takes a chart timeframe, such as 3600, and generates the corresponding text such as "H1". For example:

var txt = Framework.Translation.TranslateTimeframe(86400); // = "D1"

2.13.6 Framework.Translation.TranslateInstrumentCategory()

The TranslateInstrumentCategory() function takes a market category ID, such as FXB.InstrumentCategories.COMMODITY, and returns the corresponding display text. For example:

var market = Framework.Instruments.getOrBlank(someInstrumentId);

var categoryText = Framework.Translation.TranslateInstrumentCategory(market.categoryId);

2.14 Framework.Theme object

(This section is irrelevant to scripts and UDIXes because they have no user interface of their own. It is only applicable to widgets.)

The user can change the graphical theme of Sway Charts Pro – e.g. from dark to light – while it is running, without a restart. Therefore, the theme can change while your widget is running.

By including the framework's CSS and Javascript, your widget automatically responds to changes in the selected theme – for example, body background and text colour automatically change. However, you can get the ID of the current theme using the Framework.Theme object, and you can watch for user changes by listening to the THEME message.

The framework automatically sets (and changes, when applicable) a CSS class on the widget's <body> which identifies the current theme.

2.15 FXB.Result object

Results/responses to actions are widely represented within the framework using the FXB.Result class. For example, the result of trading actions and of dialogs is an FXB.Result.

An FXB.Result has the following properties:

An error FXB.Result such as a failed trade can be translated into equivalent readable text using Framework.Translation.TranslateError().

Depending on the nature of the response, the FXB.Result may contain other properties giving additional information. Commonly used properties include msg, param1, param2, and param3.

For example, in the response from the standard Ask() dialog, the msg property indicates which button the user selected:

Framework.Ask("Are you sure?", function (Msg) {

if (Msg.result) {

if (Msg.result.code == FXB.ErrorCodes.OKAY) {

if (Msg.result.msg == "Yes") {

// User selected the yes button

}

} else {

// User cancelled the dialog without clicking a button

}

} else {

// Message is an interim update from the dialog, not the final result

}

});

However, it's only usually necessary to check for a specific response or do nothing, and so the code above would/could typically be reduced to the following:

Framework.Ask("Are you sure?", function (Msg) {

if (Msg.result && Msg.result.msg == "Yes") {

// User selected the yes button (as opposed to No button, or cancellation without

// response, or an interim update from the dialog rather than a final result)

}

});

Last updated