-
Notifications
You must be signed in to change notification settings - Fork 25
/
demo.js
436 lines (419 loc) · 19.6 KB
/
demo.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*jslint this: true, browser: true, long: true, bitwise: true, unordered: true */
/*global window console demonstrationHelper */
/**
* Follows WebSocket behaviour defined by spec:
* https://html.spec.whatwg.org/multipage/web-sockets.html
*/
(function () {
// Create a helper function to remove some boilerplate code from the example itself.
const demo = demonstrationHelper({
"responseElm": document.getElementById("idResponse"),
"javaScriptElm": document.getElementById("idJavaScript"),
"accessTokenElm": document.getElementById("idBearerToken"),
"retrieveTokenHref": document.getElementById("idHrefRetrieveToken"),
"tokenValidateButton": document.getElementById("idBtnValidate"),
"accountsList": document.getElementById("idCbxAccount"),
"footerElm": document.getElementById("idFooter")
});
let connection;
/**
* Test if the browser supports the features required for websockets.
* @return {boolean} True when the features are available.
*/
function isWebSocketsSupportedByBrowser() {
return (
Boolean(window.WebSocket) &&
Boolean(window.Int8Array) &&
Boolean(window.Uint8Array) &&
Boolean(window.TextDecoder)
);
}
/**
* This function collects the access rights of the logged in user.
* @return {void}
*/
function getAccessRights() {
fetch(
demo.apiUrl + "/root/v1/user",
{
"method": "GET",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
const responseText = "\n\nResponse: " + JSON.stringify(responseJson, null, 4);
// More info about the user operations can be found @ https://saxobank.github.io/openapi-samples-js/basics/user-info/
if (responseJson.Operations.indexOf("OAPI.OP.TakeTradeSession") === -1) {
console.error("You are not allowed to upgrade your TradeLevel to FullTradingAndChat.");
} else {
console.log("Session has operation 'OAPI.OP.TakeTradeSession':\nYou can upgrade your session to FullTradingAndChat!" + responseText);
}
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of constructing the websocket connection.
* @return {void}
*/
function createConnection() {
const accessToken = document.getElementById("idBearerToken").value;
const contextId = encodeURIComponent(document.getElementById("idContextId").value);
const streamerUrl = demo.streamerUrl + "?authorization=" + encodeURIComponent("BEARER " + accessToken) + "&contextId=" + contextId;
if (!isWebSocketsSupportedByBrowser()) {
console.error("This browser doesn't support WebSockets.");
throw "This browser doesn't support WebSockets.";
}
if (contextId !== document.getElementById("idContextId").value) {
console.error("Invalid characters in Context ID.");
throw "Invalid characters in Context ID.";
}
try {
connection = new window.WebSocket(streamerUrl);
connection.binaryType = "arraybuffer";
console.log("Connection created with binaryType '" + connection.binaryType + "'. ReadyState: " + connection.readyState + ".");
// Documentation on readyState: https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState
// 0=CONNECTING, 1=OPEN, 2=CLOSING, 3=CLOSED
} catch (error) {
console.error("Error creating websocket. " + error);
}
}
/**
* This function initiates the events and contains the processing of new messages.
* @return {void}
*/
function startListener() {
const utf8Decoder = new window.TextDecoder();
/**
* Creates a Long from its little endian byte representation (function is part of long.js - https://github.com/dcodeIO/long.js).
* @param {!Array.<number>} bytes Little endian byte representation
* @param {boolean=} unsigned Whether unsigned or not, defaults to signed
* @returns {number} The corresponding Long value
*/
function fromBytesLe(bytes, unsigned) {
const low = (bytes[0] | bytes[1] << 8 | bytes[2] << 16 | bytes[3] << 24) | 0;
const high = (bytes[4] | bytes[5] << 8 | bytes[6] << 16 | bytes[7] << 24) | 0;
const twoPwr16Dbl = 1 << 16;
const twoPwr32Dbl = twoPwr16Dbl * twoPwr16Dbl;
if (unsigned) {
return (high >>> 0) * twoPwr32Dbl + (low >>> 0);
}
return high * twoPwr32Dbl + (low >>> 0);
}
/**
* Parse the incoming messages. Documentation on message format: https://www.developer.saxo/openapi/learn/plain-websocket-streaming#PlainWebSocketStreaming-Receivingmessages
* @param {Object} data The received stream message
* @returns {Array.<Object>} Returns an array with all incoming messages of the frame
*/
function parseMessageFrame(data) {
const message = new DataView(data);
const parsedMessages = [];
let index = 0;
let messageId;
let referenceIdSize;
let referenceIdBuffer;
let referenceId;
let payloadFormat;
let payloadSize;
let payloadBuffer;
let payload;
while (index < data.byteLength) {
/* Message identifier (8 bytes)
* 64-bit little-endian unsigned integer identifying the message.
* The message identifier is used by clients when reconnecting. It may not be a sequence number and no interpretation
* of its meaning should be attempted at the client.
*/
messageId = fromBytesLe(new window.Uint8Array(data, index, 8));
index += 8;
/* Version number (2 bytes)
* Ignored in this example. Get it using 'messageEnvelopeVersion = message.getInt16(index)'.
*/
index += 2;
/* Reference id size 'Srefid' (1 byte)
* The number of characters/bytes in the reference id that follows.
*/
referenceIdSize = message.getInt8(index);
index += 1;
/* Reference id (Srefid bytes)
* ASCII encoded reference id for identifying the subscription associated with the message.
* The reference id identifies the source subscription, or type of control message (like '_heartbeat').
*/
referenceIdBuffer = new window.Int8Array(data, index, referenceIdSize);
referenceId = String.fromCharCode.apply(String, referenceIdBuffer);
index += referenceIdSize;
/* Payload format (1 byte)
* 8-bit unsigned integer identifying the format of the message payload. Currently the following formats are defined:
* 0: The payload is a UTF-8 encoded text string containing JSON.
* 1: The payload is a binary protobuffer message.
* The format is selected when the client sets up a streaming subscription so the streaming connection may deliver a mixture of message format.
* Control messages such as subscription resets are not bound to a specific subscription and are always sent in JSON format.
*/
payloadFormat = message.getUint8(index);
index += 1;
/* Payload size 'Spayload' (4 bytes)
* 32-bit unsigned integer indicating the size of the message payload.
*/
payloadSize = message.getUint32(index, true);
index += 4;
/* Payload (Spayload bytes)
* Binary message payload with the size indicated by the payload size field.
* The interpretation of the payload depends on the message format field.
*/
payloadBuffer = new window.Uint8Array(data, index, payloadSize);
payload = null;
switch (payloadFormat) {
case 0:
// JSON
try {
payload = JSON.parse(utf8Decoder.decode(payloadBuffer));
} catch (error) {
console.error(error);
}
break;
case 1:
// ProtoBuf is not supported in this example. See the realtime-quotes example for a Protocol Buffers implementation.
console.error("Protocol Buffers are not supported in this example.");
break;
default:
console.error("Unsupported payloadFormat: " + payloadFormat);
}
if (payload !== null) {
parsedMessages.push({
"messageId": messageId,
"referenceId": referenceId,
"payload": payload
});
}
index += payloadSize;
}
return parsedMessages;
}
connection.onopen = function () {
console.log("Streaming connected.");
};
connection.onclose = function (evt) {
// Status codes: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent
if (evt.wasClean === true) {
console.log("Streaming disconnected with code " + evt.code + "."); // Most likely 1000 (Normal Closure), or 1001 (Going Away)
} else {
console.error("Streaming disconnected with code " + evt.code + ".");
}
};
connection.onerror = function (evt) {
console.error(evt);
};
connection.onmessage = function (messageFrame) {
const messages = parseMessageFrame(messageFrame.data);
messages.forEach(function (message) {
switch (message.referenceId) {
case "MyTradeLevelChangeEvent":
console.log("Streaming trade level change event #" + message.messageId + " received: " + JSON.stringify(message.payload, null, 4));
break;
case "_heartbeat":
// https://www.developer.saxo/openapi/learn/plain-websocket-streaming#PlainWebSocketStreaming-Controlmessages
console.debug("Heartbeat event #" + message.messageId + " received: " + JSON.stringify(message.payload));
break;
case "_resetsubscriptions":
// The server is not able to send messages and client needs to reset subscriptions by recreating them.
console.error("Reset Subscription Control message received! Reset your subscriptions by recreating them.\n\n" + JSON.stringify(message.payload, null, 4));
break;
case "_disconnect":
// The server has disconnected the client. This messages requires you to re-authenticate if you wish to continue receiving messages.
console.error("The server has disconnected the client! New login is required.\n\n" + JSON.stringify(message.payload, null, 4));
break;
default:
console.error("No processing implemented for message with reference " + message.referenceId);
}
});
};
console.log("Connection subscribed to events. ReadyState: " + connection.readyState + ".");
}
/**
* This is an example of subscribing to primary price session changes.
* @return {void}
*/
function subscribe() {
const data = {
"ContextId": document.getElementById("idContextId").value,
"ReferenceId": "MyTradeLevelChangeEvent"
};
fetch(
demo.apiUrl + "/root/v1/sessions/events/subscriptions",
{
"method": "POST",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value,
"Content-Type": "application/json; charset=utf-8"
},
"body": JSON.stringify(data)
}
).then(function (response) {
if (response.ok) {
console.log("Subscription created with readyState " + connection.readyState + " and data '" + JSON.stringify(data, null, 4) + "'");
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of requesting the active session capabilities.
* @return {void}
*/
function getSessionCapabilities() {
fetch(
demo.apiUrl + "/root/v1/sessions/capabilities",
{
"method": "GET",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
console.log("Response: " + JSON.stringify(responseJson, null, 4));
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of making the current app primary, so real time prices can be shown. Other apps are notified and get delayed prices.
* @return {void}
*/
function requestPrimaryPriceSession() {
fetch(
demo.apiUrl + "/root/v1/sessions/capabilities",
{
"method": "PUT",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value,
"Content-Type": "application/json; charset=utf-8"
},
"body": JSON.stringify({
"TradeLevel": "FullTradingAndChat"
})
}
).then(function (response) {
if (response.ok) {
console.log("Requested FullTradingAndChat session capabilities..");
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of making the current app primary, so real time prices can be shown again. Other apps are notified and get delayed prices.
* @return {void}
*/
function requestPrimaryPriceSessionAgain() {
fetch(
demo.apiUrl + "/root/v1/sessions/capabilities",
{
"method": "PATCH",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value,
"Content-Type": "application/json; charset=utf-8"
},
"body": JSON.stringify({
"TradeLevel": "FullTradingAndChat"
})
}
).then(function (response) {
if (response.ok) {
console.log("Requested to become primary again (will be granted if app was no longer primary)..");
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of extending the websocket session, after a token refresh took place.
* @return {void}
*/
function extendSubscription() {
// Be sure to refresh the token first, using the OAuth2 server (not included in this sample).
// Example: https://saxobank.github.io/openapi-samples-js/authentication/oauth2-implicit-flow/
const token = document.getElementById("idBearerToken").value;
fetch(
demo.apiUrl + "/streamingws/authorize?contextid=" + encodeURIComponent(document.getElementById("idContextId").value),
{
"method": "PUT",
"headers": {
"Authorization": "Bearer " + token
}
}
).then(function (response) {
const newExpirationTime = new Date();
newExpirationTime.setSeconds(newExpirationTime.getSeconds() + demo.getSecondsUntilTokenExpiry(token));
if (response.ok) {
console.log("Subscription extended until " + newExpirationTime.toLocaleString() + ".");
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of unsubscribing to the events.
* @return {void}
*/
function unsubscribe() {
fetch(
demo.apiUrl + "/root/v1/sessions/events/subscriptions/" + encodeURIComponent(document.getElementById("idContextId").value) + "/MyTradeLevelChangeEvent",
{
"method": "DELETE",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
console.log("Unsubscribed to " + response.url + ".\nReadyState " + connection.readyState + ".");
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of disconnecting the socket.
* @return {void}
*/
function disconnect() {
const NORMAL_CLOSURE = 1000;
connection.close(NORMAL_CLOSURE); // This will trigger the onclose event
}
document.getElementById("idContextId").value = "MyApp_" + Date.now(); // Some unique value
demo.setupEvents([
{"evt": "click", "elmId": "idBtnGetAccessRights", "func": getAccessRights, "funcsToDisplay": [getAccessRights]},
{"evt": "click", "elmId": "idBtnCreateConnection", "func": createConnection, "funcsToDisplay": [createConnection]},
{"evt": "click", "elmId": "idBtnStartListener", "func": startListener, "funcsToDisplay": [startListener]},
{"evt": "click", "elmId": "idBtnSubscribe", "func": subscribe, "funcsToDisplay": [subscribe]},
{"evt": "click", "elmId": "idBtnGetSessionCapabilities", "func": getSessionCapabilities, "funcsToDisplay": [getSessionCapabilities]},
{"evt": "click", "elmId": "idBtnBecomePrimary", "func": requestPrimaryPriceSession, "funcsToDisplay": [requestPrimaryPriceSession]},
{"evt": "click", "elmId": "idBtnBecomePrimaryAgain", "func": requestPrimaryPriceSessionAgain, "funcsToDisplay": [requestPrimaryPriceSessionAgain]},
{"evt": "click", "elmId": "idBtnExtendSubscription", "func": extendSubscription, "funcsToDisplay": [extendSubscription, demo.getSecondsUntilTokenExpiry]},
{"evt": "click", "elmId": "idBtnUnsubscribe", "func": unsubscribe, "funcsToDisplay": [unsubscribe]},
{"evt": "click", "elmId": "idBtnDisconnect", "func": disconnect, "funcsToDisplay": [disconnect]}
]);
demo.displayVersion("root");
}());