Messages and event handlers

You can listen for changes in prices, the order list, account metrics etc using an OnMessage() handler. For example:

Framework.OnMessage = function(Msg) {

if (Msg.is(Sway.MessageTypes.PRICE)) {

… update a quote board

}

};

Some types of message such as changes to account metrics are issued automatically. Other types of message, such as prices or account history, must be specifically requested by your widget/script/UDIX.

By the time that message handlers are called, the framework's objects and collections have already been updated. For example, if you receive an ORDER_OPEN message, the new order(s) will already be present in the Framework.Orders collection.

As well as using the main OnMessage handler, you can also define individual handlers for some types of message. For example, you can define an OnPriceChange function. All price changes are then sent to that function as well as to the main OnMessage handler.

It's possible for your code to have multiple message handlers (each of which receives all messages). You can do the following as well as or instead of using OnMessage().

var handler1 = Framework.AddMessageHandler(function (Msg) { … a handler function});

var handler2 = Framework.AddMessageHandler(function (Msg) { … a second handler });

The return value from AddMessageHandler() is an ID which assists with the common Javascript problem of detaching anonymous functions. If you only need a message handler temporarily, you can store its ID and then later disconnect it using RemoveMessageHandler():

Framework.RemoveMessageHandler(handler1);

Note: you may observe that everything passes through OnMessage: initial load, results of trading actions etc. It's possible to handle the results of something like a trading action by watching OnMessage rather than supplying a callback function to SendOrder(). But there's generally no good reason to do that, and this section of the guide only covers the expected uses of OnMessage.

4.1 Multiple updates in a single message

The framework can issue multiple updates in a single message. For example, a single message and a single call to OnMessage can contain changes to multiple prices and also updates to the order list.

Therefore, you should generally process messages along the following lines:

Framework.OnMessage = function(Msg) {

if (Msg.is(Sway.MessageTypes.PRICE)) {

… update a quote board

}

if (Msg.is([Sway.MessageTypes.ORDER_OPEN, Sway.MessageTypes.ORDER_CLOSE])) {

… update a trade list

}

};

The following – else-if instead of if-if – is not safe because a message may be both a price update and an order update, and the order update will be ignored by the code if the message is also a price update:

Framework.OnMessage = function(Msg) {

if (Msg.is(Sway.MessageTypes.PRICE)) {

… update a quote board

// NOT SAFE!

} else if (Msg.is([Sway.MessageTypes.ORDER_OPEN, Sway.MessageTypes.ORDER_CLOSE])) {

… update a trade list

}

};

4.2 The Sway.Message object

The parameter which is passed to OnMessage() is an Sway.Message object. This is a Dictionary, because a message can contain multiple types of update.

In addition to the list of message-types in the message, which you can test using the Dictionary's is() or has(), there can be further properties in the object depending on the type(s) of message. For example, a PRICE message will contain a quotes[] array of new prices. These extra properties are described below.

4.3 Types of message

The types of message which you can receive via OnMessage() are as follows, from the Sway.MessageTypes enumeration:

Sway.MessageTypes.

Description

PRICE

Update to one or more prices

ORDER_OPEN

New pending order or open trade

ORDER_CHANGE

Change to a pending order or open trade (including non-trading changes such as fluctuating profit on an open trade)

ORDER_CLOSE

Closure of an open trade or cancellation of a pending order

POSITION_CHANGE

Change to a net position

ACCOUNT_METRICS

Change to account metrics such as balance or margin usage

ACCOUNT_HISTORY

Initial load or subsequent change to the account history

MARKET_DEPTH

Update to market depth

ORDER_BOOK

Update to order book

MAILBOX

Event within Sway Charts Pro's internal mail system

THEME

Change by the user to the software's graphical theme

CATEGORY_SETTINGS_CHANGE

Change to the category settings of your widget, script, or UDIX

WIDGET_CONTEXT_CHANGE

Change of context – synchronisation of markets and/or timeframes – in the Sway Charts Pro page container

BROADCASTx

Range of messages, from BROADCAST1 to BROADCAST10, which widgets, scripts, or UDIXes can use to broadcast their existence to other components

GENERICx

Range of messages, from GENERIC1 to GENERIC10, which a widget, script, or UDIX can use to send a direct message to a component whose ID it knows

4.4 Sway.MessageTypes.PRICE and OnPriceChange

You need to request messages for the prices you are interested in. You don't automatically receive notifications about all price changes.

Once you have requested price updates, there are two ways of receiving and processing them:

· By using the main OnMessage handler, and listening for the PRICE message

· By defining an OnPriceChange handler

There is a subtle difference between these two routes:

· PRICE messages may contain other instruments, in addition to those you have requested, in their quotes[] array.

· The OnPriceChange handler is guaranteed only to be called in relation to the market(s) you have requested.

4.4.1 PRICE messages in OnMessage

Whenever there is a change to a requested price, the main OnMessage handler receives a PRICE message. For example:

Framework.OnMessage = function(Msg) {

if (Msg.is(Sway.MessageTypes.PRICE)) {

Msg.quotes[] contains a list of price changes

}

};

The Sway.Message object will contain a quotes[] array listing the changed prices. You may receive notifications for other markets in addition to the one(s) you have requested. For example, if you have only requested prices for a single market, you cannot rely on quotes.length being 1.

Each object in the quotes[] array has the following properties:

Property

Description

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.

updateMarker

See below

You can react to the changed prices either by looking at the quotes[] array, or by looking at the prices in the Framework.Instruments collection which will already have been updated.

The updateMarker is a bit-mask of what is changing in a quote. This is designed to help you minimise the work in updating a user interface. For example, if the bit-mask contains FLAG_PRICE_BID but not FLAG_PRICE_ASK, then you know that you only need to update the display of the bid price. You don't need to make the browser to do extra work updating an ask price which hasn't changed.

The possible flags are members of the Sway.UpdateFlags enumeration:

Sway.UpdateFlags.

Description

BID

Bid has changed

ASK

Ask has changed

HIGH

High has changed

LOW

Low has changed

CHANGEONDAY

Change-on-day has changed

4.4.2 OnPriceChange handler

Instead of using the main OnMessage handler, you may find it easier to watch price changes using an OnPriceChange handler. If defined, this is called by the framework with each individual price which is changing:

Framework.OnPriceChange = function(quote) {

// The quote object contains the same time, bid, ask etc properties listed above

};

4.5 Sway.MessageTypes.ORDER_x and OnOrderX handlers

There are two ways of tracking changes in the order list (which includes both pending orders and open trades):

· By using the main OnMessage handler to listen for the ORDER_OPEN, ORDER_CHANGE, and ORDER_CLOSE messages

· By defining any or all of OnOrderOpen, OnOrderChange, and OnOrderClose handlers

4.5.1 ORDER_x messages in OnMessage

The ORDER_OPEN, ORDER_CHANGE, and ORDER_CLOSE messages are issued on changes to the order list (which includes both pending orders and open trades).

ORDER_CHANGE is issued for changes in the current price and/or profit on an open trade, as well as trading actions such as moving its stop-loss.

The Sway.Message object will contain arrays listing the new/changed/closed orders:

Sway.MessageTypes.

Array

ORDER_OPEN

ordersOpened[]

ORDER_CHANGE

ordersChanged[]

ORDER_CLOSE

ordersClosed[]

A single message from the framework can contain multiple updates, and therefore the message may contain all of these arrays. For example:

Framework.OnMessage = function(Msg) {

if (Msg.is(Sway.MessageTypes.ORDER_OPEN)) {

… process changes in Msg.ordersOpened[]

}

if (Msg.is(Sway.MessageTypes.ORDER_CLOSE)) {

… process changes in Msg.ordersClosed[]

}

};

Each item in one of these arrays is simply an Sway.Order object describing the new/changed/closed order or trade.

You can react to the changes either by looking at the arrays of orders, or by looking at the Framework.Orders collection which will already have been updated.

However, in addition to the standard members of Sway.Order, each item in the arrays also has an updateMarker. This is a bit-mask describing what has changed about the order. Particularly for changes rather than opens and closes, this is designed to help you minimise the work in updating a user interface, avoiding updates to HTML elements which don't need to be changed.

The possible flags are members of the Sway.UpdateFlags enumeration:

Sway.UpdateFlags.

Description

FLAG_ORDER_NEW

Order is new (should only exist in ordersOpened[] array)

FLAG_ORDER_TYPE

Change in orderType – for example, when logged in to a back-end platform where an order can change from pending to filled without changing ticket/reference number

FLAG_ORDER_VOLUME

Volume has changed, for example as a result of a partial close

FLAG_ORDER_PROFIT

Profit has changed

FLAG_ORDER_SLTP

Stop-loss and/or take-profit has changed

FLAG_ORDER_CURRENTPRICE

Current price (closePrice) has changed

FLAG_ORDER_OPENPRICE

Open price has changed – alteration to the entry price on a pending order

FLAG_ORDER_COMMENT

Order comment has changed

FLAG_ORDER_OTHER

Any other change to order properties

FLAG_ORDER_CLOSED

Order is closed/cancelled (should only exist in ordersClosed[] array)

4.5.2 OnOrderX handlers

Instead of using the main OnMessage handler, you can also track changes in the order list using the functions OnOrderOpen, OnOrderChange, and OnOrderClose. (You don't have to define all three of these. If you are only interested in new opens, then you only need to define OnOrderOpen).

Each of these handlers receives as a parameter the individual order which is being opened, changed, or closed. For example:

Framework.OnOrderOpen = function(newOrder)

{

// newOrder is an Sway.Order describing the new trade or pending order

};

4.6 Sway.MessageTypes.POSITION_CHANGE and OnPositionChange

You can listen for changes in the changes in the Framework.Positions list in two ways:

· By using the main OnMessage handler to listen for the POSITION_CHANGE message

· By defining an OnPositionChange handler

In both cases, position updates are not issued for changes in profit (or current price). They are only issued for changes in the net position caused by an order opening or closing. If you want to update a display of the profit on a net position, then you need to do something such as watching the market's price as a prompt telling you that the profit will have changed.

4.6.1 POSITION_CHANGE message in OnMessage

The POSITION_CHANGE message is issued about changes in the Framework.Positions list.

The Sway.Message object will contain a positionsChanged[] array listing the Sway.Position objects which have changed. You can react to the changes either by looking at the positionsChanged[] array, or by looking at the Framework.Positions collection which will already have been updated.

4.6.2 OnPositionChange handler

Instead of using the main OnMessage handler, you can also track changes in the position list by using an OnPositionChange handler. If defined, this is called by the framework for each change in a position:

Framework.OnPositionChange = function(position) {

// An Sway.Position update describing the change

};

4.7. Sway.MessageTypes.ACCOUNT_METRICS and OnAccountMetrics

You can listen for changes in the metrics in Framework.Account – change in floating P/L, margin usage etc – in two ways:

· By using the main OnMessage handler to listen for the ACCOUNT_METRICS message

· By defining an OnAccountMetrics handler

4.7.1 ACCOUNT_METRICS message in OnMessage

The ACCOUNT_METRICS message is issued about changes to the metrics in Framework.Account – change in floating P/L, margin usage etc.

The Sway.Message object will contain an accountMetrics object. The properties of Msg.accountMetrics correspond to the properties in the Framework.Account, but it only contains values which are changing. For example, for a change of floating P/L without a new closed trade which affects the balance, the accountMetrics will include a floatingPL property but not a balance property.

You can also inspect what has changed using an updateMarker in the accountMetrics. This is a bit-mask describing which metrics have changed. The possible flags are members of the Sway.UpdateFlags enumeration:

Sway.UpdateFlags.

Description

FLAG_ACCOUNT_FLOATINGPL

Change to floating P/L

FLAG_ACCOUNT_EQUITY

Change to equity (should always also imply FLAG_ACCOUNT_FLOATINGPL)

FLAG_ACCOUNT_BALANCE

Change to balance

FLAG_ACCOUNT_USEDMARGIN

Change to margin in use

FLAG_ACCOUNT_FREEMARGIN

Change to free margin

FLAG_ACCOUNT_CREDIT

Change to account credit

4.7.2 OnAccountMetrics handler

Instead of using the main OnMessage handler, you can also track changes in the account metrics such as balance and floating P/L by using an OnAccountMetrics handler. If defined, this is called by the framework each time that any of the metrics changes:

Framework.OnAccountMetrics = function(accountMetrics) {

// Receives the same accountMetrics object as in OnMessage

};

The parameter to the OnAccountMetrics handler is the same value inside an ACCOUNT_METRICS message.

4.8 Sway.MessageTypes.ACCOUNT_HISTORY

The ACCOUNT_HISTORY message is issued on initial load of the account history, followed by each addition of a new closed order or credit movement. You need to request account history; it is not issued automatically.

By the time that your message handler receives ACCOUNT_HISTORY, the Framework.TradeHistory collection will already have been updated with the changes.

You can inspect which transactions are being added by looking at the history[] array in the Sway.Message object. Like the Framework.TradeHistory collection, each item in the history[] array is an Sway.Order object describing the closed trade/order or credit movement.

4.9 Sway.MessageTypes.MARKET_DEPTH

The MARKET_DEPTH message is sent in response to a request for market depth. It can be processed either in OnMessage() or using an asynchronous callback to RequestMarketDepth(). Market depth must be explicitly requested; it is not sent automatically.

4.10 Sway.MessageTypes.ORDER_BOOK

The ORDER_BOOK message is sent in response to a request for order book. It can be processed either in OnMessage() or using an asynchronous callback to RequestOrderBook(). Order book must be explicitly requested; it is not sent automatically.

4.11 Sway.MessageTypes.MAILBOX

The MAILBOX message is a notification of a change in Sway Charts Pro's mail system – not just a new message, or deletions, but also a message being opened and treated as read.

MAILBOX messages must be specifically requested. They are not sent automatically by default.

MAILBOX messages contain a mail[] array. This always (re-)lists all messages in the mailbox, not just additions.

4.12 Sway.MessageTypes.THEME

(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 the software – e.g. from dark to light – while it is running, without a restart. Therefore, the theme can change while your widget is running.

The THEME message notifies you that this has happened. The Sway.Message object will contain a Theme object, but it is simplest to inspect the change just by using Framework.Theme.

4.13 Sway.MessageTypes.CATEGORY_SETTINGS_CHANGE

The CATEGORY_SETTINGS_CHANGE message is received by all instances of your widget, script, or UDIX when one instance saves changes using Framework.SaveCategorySettings().

The message is sent to the instance which saved the change as well as to any other running instances of the widget. The message includes a categorySettings property containing the new settings, but these are also available via Framework.categorySettings.

4.14 Sway.MessageTypes.WIDGET_CONTEXT_CHANGE

The WIDGET_CONTEXT_CHANGE message is received by a widget (only, not a script or UDIX) under the following circumstances:

· The widget has been added to the Sway Charts Pro page container

· The user has chosen to synchronize the markets and/or timeframes on the page, and another widget changes the market or timeframe

· Or, some component uses SetCurrentPageInstrument() or SetCurrentPageTimeframe()

See the section on handling context for more information.

4.15 Sway.MessageTypes.BROADCASTx and Sway.MessageTypes.GENERICx

The message types from BROADCAST1 to BROADCAST10 and from GENERIC1 to GENERIC10 are designed for transient, ad hoc messaging between different widgets, scripts, and UDIXes.

BROADCASTx messages can be sent out without a specified recipient ID (a _to in the message). GENERICx messages require a recipient.

Last updated