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.

Collection

Description

Instruments

List of all available markets for the current trading account.

Orders

List of all open trades and pending orders (potentially multiple open trades for each market unless the account is netting/non-hedging)

Positions

List of open trades aggregated into a single long/short position for each market

TradeHistory

List of historic trades and credit movements on the account. This collection is empty by default and must be explicitly requested using Framework.RequestAccountHistory()

2.2 Framework objects

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

Object

Description

Account

The trading account which Sway Charts Pro is currently logged into. Availability of some features in the framework depends on the functionality provided by the broker account, and reported in the account's features.

Environment

Contains a persistent identifier for the client's browser/app

Translation

Contains functions for translating variables into the user's currently selected language

Theme

Contains information about the user's selected graphical theme for the software (e.g. light, dark)

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

Object

Description

Sway.Result

Standard response/error object

2.3 Framework properties

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

Property

Description

RELEASE

See introduction

isReady

Indicates whether the framework is ready for use. Always immediately true in scripts and UDIXes. Not immediately true in widgets.

id

Unique ID for this instance of the widget/script/UDIX. This changes each time your code is loaded. For widgets loaded into the Sway Charts Pro page container, it is not a persistent ID across reloads of the widget's page, or across the user logging out and back in. It changes on each load of the widget.

type

Not applicable to scripts and UDIXes. For widgets, a unique category allocated to your widget. Can be used for displaying a widget as its own dialog.

_parentWidget

Not applicable to scripts and UDIXes. For widgets, the ID of the widget's parent/creator

inWindow

Not applicable to scripts and UDIXes. Boolean indicating whether a widget has been loaded into a pop-up browser window rather than the main window.

inPageContainer

Not applicable to scripts and UDIXes. Boolean indicating whether a widget has been loaded into the main Sway Charts Pro page container, or whether it is a temporary dialog or floating panel.

isDialog

Not applicable to scripts and UDIXes. Boolean indicating whether a widget is being displayed as a dialog or floating panel rather than being persistently loaded into the Sway Charts Pro page container.

fullScreen

Not applicable to scripts and UDIXes. Boolean indicating whether a widget is being displayed in full-screen mode on a small device such as mobile phone.

privateSettings

See the section about settings and state storage

categorySettings

See the section about settings and state storage

context

Any context of market and/or timeframe selection, for a widget which is loaded in the Sway Charts Pro page container.

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.

Property

Description

instrumentId

ID of the instrument, potentially the result of standardisation

caption

Display-name of the market

tradeable

Boolean indicating whether the market can be traded, or is included by the broker for information only

categoryId

Market category – forex, metal, index etc

underlyingCurrency

Underlying/profit currency of the market, e.g. USD for the DJIA. For FX pairs AAA/BBB, it is reported as BBB. See note on spread-betting accounts.

isFX

Boolean indicating whether the market is an FX pair

baseCurrency

For FX pairs only, the AAA currency of the AAA/BBB pair

quoteCurrency

For FX pairs only, the BBB currency of the AAA/BBB pair. See note on spread-betting accounts.

digits

Number of digits in the market's price

tickSize

Minimum price movement in the market. Typically 10^-digits, but not necessarily so; a market may have digits=2 but tickSize=0.05

pipSize

For FX pairs, the standard definition of a "pip": 0.01 on JPY and HUF pairs; 0.0001 on everything else. For other asset classes, there is no universal consensus on what constitutes a "pip". The framework will generally report a value of 1.00 on non-fx markets, with some special exceptions for markets such as gold and oil.

contractSize

Market contract size, e.g. typically 100,000 on FX markets

minVolume

Minimum trading volume (as cash/notional, such as 1000, rather than a value in lots, such as 0.01)

maxVolume

Maximum trading volume (again cash/notional, not lots)

incrementVolume

Minimum step in trading volume. Almost always the same as minVolume.

time

Time of the most recent quote

bid

Latest bid price

ask

Latest ask price

high

High of the current period. Availability depends on account features.

low

Low of the current period. Availability depends on account features.

change

Change amount during the current period. Availability depends on account features.

changePc

Change amount as a percentage. Availability depends on account features.

spread *

Difference between ask and bid (as price amount such as 0.00023)

spreadPips *

Spread in pips, i.e. spread divided by pipSize

midPrice *

Mid price: (ask + bid) / 2

minLot *

Minimum trade volume, in lots: minVolume / contractSize

maxLot *

Maximum trade volume, in lots: maxVolume / contractSize

lotStep *

Minimum trade increment, in lots: incrementVolume / contractSize

tickValue *

Cash value, in the account's deposit currency, of a change in price by the tickSize when trading the contractSize. For example, if trading EUR/USD on a GBP account, with a contractSize of 100K and a tickSize of 0.00001, then tickValue will be the current GBP equivalent of USD 1.00.

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.

Sway.InstrumentCategories.

Description

FX_MAJOR

FX majors: USD crosses with major currencies. EUR/USD, USD/JPY etc

FX_MINOR

FX minors: non-USD crosses between major currencies. EUR/GBP etc.

FX_EXOTIC

Crosses involving non-major currencies.

FOREX

(Present in Sway.InstrumentCategories, but unused)

COMMODITY

Commodity such as oil or gas

EQUITY_INDEX

Equity index such as the DJIA or DAX

EQUITY

Individual equity (can currently be either physical or CFD)

INTEREST_RATE

Interest rates such as US Treasuries

METAL

Metals: gold, silver, palladium etc

CFD

General category for non-FX CFD markets

CRYPTO

Cryptocurrency

OTHER

Anything not categories as any of the above

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.

Sway.Instrument.

Description

ConvertVolumeToLots(x)

Converts a cash/unit amount x to lots: simply divides by the contract size

ConvertLotsToVolume(x)

Converts a lots amount x to cash/units: simply multiplies by the contract size

RoundPrice(x)

Rounds a price x (or a price differential, such as 0.0020) to the nearest multiple of the tickSize, i.e. closest valid price

GetPriceMovementValue(x, volume)

For a price movement, such as 0.0020, and a volume (in cash/units, not lots), calculates the value of the move in the account's deposit currency. The volume parameter can be omitted, and defaults to the contractSize. For example, for EUR/USD on a GBP account, a price movement of 0.0020 with a volume of 100,000 is worth USD 200, and this function will return the current GBP equivalent of USD 200.

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:

Property

Description

tradeNetProfit

Current net profit on all open trades – should normally match Account.floatingPL

openTradeCount

Number of open trades

pendingOrderCount

Number of pending orders

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.

Property

Description

orderId

ID of the order (usually but not necessarily numeric)

reference

Client-facing reference number for the order

orderType

Type of order (or credit movement etc)

instrumentId

ID of the Sway.Instrument

volume

Trading volume – always specified in cash/units terms, such as 10000, not lots such as 0.10

openPrice

Opening price of the order

openTime

Open/creation time

sl

Current stop-loss price on the order, or zero if none

tp

Current take-profit price on the order, or zero if none

trail

Current trailing-stop distance on the order, as a price amount such as 0.0020, or zero. Requires the account to offer trailing stops.

comment

Textual comment on the order. Requires the account to support order comments.

magicNumber

MT4/5-style "magic number" on the order. Requires the account to support magic numbers.

profit

Profit on the order (zero for pending or cancelled orders)

swap

Accumulated rollover/interest/swap on the order

commission

Commission charged on the order

closeTime

Close/cancellation time of the order. Zero for open trades and pending orders.

closePrice

Current or close price. For closed trades and cancelled orders: the final price. For open trades: the opposite side of the spread. For pending orders: the same side of the spread (e.g. the bid price on a pending sell-limit).

2.7.1 Order types

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

Sway.OrderTypes.

Trades and pending orders

BUY

Open or closed buy trade

SELL

Open or closed sell trade

BUY_LIMIT

Pending or cancelled buy-limit order

SELL_LIMIT

Pending or cancelled sell-limit order

BUY_STOP

Pending or cancelled buy-stop order

SELL_STOP

Pending or cancelled sell-stop order

BUY_STOP_LIMIT

Pending or cancelled buy-stop-limit order (see below)

SELL_STOP_LIMIT

Pending or cancelled sell-stop-limit order (see below)

Sway.OrderTypes.

Credit movements

DEPOSIT

Account deposit

WITHDRAWAL

Account withdrawal

TRANSFER

Internal credit transfer between accounts

COMMISSION

Commission debit or credit

DIVIDEND

Dividend

FINANCING

Financing – rollover/interest/swap

CREDIT

Account credit (typically a temporary incentive by the broker)

INTEREST

Interest payment or charge

TAX

Tax charge

BONUS

Bonus

OTHERCHARGE

Any credit movement not allocated to another category above

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

Sway.OrderTypes.

Helper function

IsLong(x)

Tests whether the orderType represents a long order or trade (is one of BUY, BUY_LIMIT, BUY_STOP, BUY_STOP_LIMIT)

IsShort(x)

Tests whether the orderType represents a short order or trade (is one of SELL, SELL_LIMIT, SELL_STOP, SELL_STOP_LIMIT)

IsMarket(x)

Tests whether the orderType represents a trade rather than pending order (is one of BUY, SELL)

IsPending(x)

Tests whether the orderType represents a pending order rather than a trade (is one of BUY_LIMIT, BUY_STOP, SELL_LIMIT, SELL_STOP, BUY_STOP_LIMIT, SELL_STOP_LIMIT)

IsLimit(x)

Tests whether the orderType represents a limit pending order (is one of BUY_LIMIT, SELL_LIMIT)

IsStop(x)

Tests whether the orderType represents a limit pending order (is one of BUY_STOP, SELL_STOP)

IsStopLimit(x)

Tests whether the orderType represents a stop-limit pending order (is one of BUY_STOP_LIMIT, SELL_STOP_LIMIT)

IsCredit(x)

Tests whether the orderType represents a credit movement rather than an order or trade

Invert(x)

Inverts the order-type. For example, Invert(Sway.OrderTypes.BUY) = Sway.OrderTypes.SELL, and Invert(Sway.OrderTypes.SELL_LIMIT) = 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:

Instrument.Positions.

Description

getOrEmpty(x)

Extends the standard Dictionary get(), and returns an object representing no position if the market with instrumentId=x has no open trades or pending orders, and so no entry in the dictionary. The no-position object has positionType:EMPTY and zero for all values.

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:

Property

Description

instrumentId

ID of the Sway.Instrument

positionType

Type of position – one of the values below.

longTradeCount

Number of open long trades

longVolume

Total volume on open long trades (as cash/units, not lots)

longVWAP

Average entry price for the long trades, or zero if none

shortTradeCount

Number of open short trades

shortVolume

Total volume on open short trades (as cash/units, not lots)

shortVWAP

Average entry price for the short trades, or zero if none

pendingOrderCount

Number of open pending orders for the market

netVolume

Net volume: long volume minus short volume. Therefore, directional: positive values indicate net long and negative values indicate net short.

hasHedging

Whether the position is partially or fully hedged; whether there are both long and short open trades

netVWAP

Net average entry price

profit

Current profit on all the open trades

swap

Current accumulated swap on all the open trades

commission

Commission charged on all the open trades

netProfit

Net profit: profit + swap + commission

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

Sway.PositionTypes.

Description

LONG

Position in the market is net-long (but may consist of both long and short trades)

SHORT

Position in the market is net-short (but may consist of both long and short trades)

FULLYHEDGED

Position is fully hedged; flat. Long volume and short volume are non-zero and exactly equal.

PENDINGONLY

No open position, but the market has pending orders

EMPTY

No open trades or pending orders. Only exists in the context of the Positions.getOrEmpty() helper function.

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.

Property

Description

accountId

ID for the account. Broker-dependent, and not necessarily numeric.

caption

User-defined caption for the account, created on the Sway Charts Pro login screen

depositCurrency

Deposit currency of the account

currencySymbol

A suggested display symbol for the depositCurrency. For example, $ for US dollar, £ for sterling, A$ for Australian dollar

accountReadOnly

Boolean indicating whether access to the account is read-only, and all trading requests will fail (e.g. logged in to an MT4 or MT5 account using the read-only "investor" password)

balance

Current account balance

equity

Current account equity: cash balance plus/minus the profit on any open trades

floatingPL

Current profit/loss on open trades

usedMargin

Margin currently in use

freeMargin

Margin currently free and available for use

isSpreadBet

Boolean value indicating whether the account is spread-bet, and a UI will typically want to display a caption such as "£pp" for trade-volume fields. Note: this setting is not entirely reliable. It can have false-negatives. Some broker platforms do not report whether accounts are spread-betting or not, and isSpreadBet will always be false. See also the comments in relation to Sway.Instrument values on spread-bet accounts.

defaultInstrumentId

Suggested instrumentId of the default instrument for widgets/scripts to use if they need to display a market and don't have an existing user selection. Usually "EUR/USD".

features

A block of sub-properties describing the capabilities of the account

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.

Feature

Description

platform

General ID for the type of broker platform which Sway Charts Pro is logged into (e.g. "TradingHub")

platformInstance

Specific instance of the back-end platform which Sway Charts Pro is logged into (e.g. "MyBroker-Live" or "MyBroker-Demo")

hedging

Boolean. Indicates whether the back-end platform is hedging/non-netting; whether it allows simultaneous open trades in opposite directions on the same market.

singleNetPosition

Boolean. Indicates that the back-end platform only ever reports a single net position for each market. If singleNetPosition:true then hedging will by definition be false. But if singleNetPosition:false then hedging can still be false; the platform may allow multiple open trades in a single market, but only in the same direction.

chartTimeframes[]

Array of chart timeframes for which candle data is available. For example, [60, 300, 1800, 3600 etc]

dataOnly

Boolean. Indicates that the account is a data-only connection with no actual trading account or trading functionality. All account metrics will be zero, and trade lists will be empty. (In addition, Account.accountReadOnly will be true.)

dayHighLow

Boolean. Indicates that high and low are available within Sway.Instrument data.

dayChange

Boolean. Indicates that change and changePc are available within Sway.Instrument data.

comment

Boolean. Indicates that orders can have textual comments.

magicNumber

Boolean. Indicates that orders can have MT4/5-style "magic numbers".

trail

Boolean. Indicates that orders can have trailing stops.

changePendingVolume

Boolean. Indicates that the volume can be changed on a pending order. (If not, volume can only be changed by deleting the order and placing a new one.)

hasStopLimit

Boolean. Indicates that the account supports stop-limit orders.

marketDepth

Boolean. Indicates that the account provides market depth.

orderBook

Boolean. Indicates that the account provides client order book.

noHistoricCredits

Boolean. If set, indicates that account history does not include credit movements, and only provides historic trading activity. (Therefore, not possible to calculate statistics such as % returns.)

noHistoricSLTP

Boolean. If set, indicates that account history does not include s/l or t/p on historic trades.

2.12 Framework.Environment object

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

Property

Description

deviceId

Unique ID for the user's device. See below.

loginSessionId

Unique ID for the current logged-in session. Changes each time that the user logs in to an account. (Therefore, not persistent across a browser session where the user logs in and out of accounts.)

hasMailSystem

Describes whether Sway Charts Pro's internal mail system is available in this version of the platform

hasCalendar

Describes whether an economic calendar is available in this version of the platform

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:

Property

Description

locale

An identifier for the selected language. May be a broad categorisation such as "en", or a sub-specification such as "zh-CN" or "zh-HK".

isRTL

True/false depending on whether the language is usually written right-to-left instead of left-to-right. Note: Sway Charts Pro automatically sets a CSS class on a widget's <body> depending on the text direction: either LTR or RTL. Widget CSS can therefore use BODY.RTL as a CSS selector for making changes to handle right-to-left languages.

The functions in Framework.Translation are as follows:

Function

Description

TranslateDOM()

Translates language variables in HTML

TranslateItem()

Translates a single language variable

TranslateError()

Translates an error result into the equivalent text

TranslateTimeframe()

Translates a chart timeframe, such as 3600, into corresponding text

TranslateInstrumentCategory()

Translates a market category ID into corresponding text

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.

Property

Description

id

ID of the selected theme. Subject to change/extension, but currently one of "standard" (dark), "blue", or "light"

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:

Property

Description

code

Error (or success) code from FXB.ErrorCodes

isOkay

Derived boolean property indicating whether the code describes success. Note: user-cancellation (CANCELLED) and no-action (NO_ACTION_REQUIRED) are treated as success.

isError

Derived boolean property indicating whether the code describes an error.

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