-
Notifications
You must be signed in to change notification settings - Fork 25
/
demo.js
434 lines (417 loc) · 20.8 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
/*jslint browser: true, long: true, unordered: true */
/*global window console demonstrationHelper */
(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"),
"assetTypesList": document.getElementById("idCbxAssetType"), // Optional
"selectedAssetType": "Stock", // Is required when assetTypesList is available
"footerElm": document.getElementById("idFooter")
});
let lastOrderId = "0";
let lastOrderIdCondition = "0";
/**
* Helper function to convert the json string to an object, with error handling.
* @return {Object} The newOrderObject from the input field - null if invalid
*/
function getOrderObjectFromJson() {
let newOrderObject = null;
try {
newOrderObject = JSON.parse(document.getElementById("idNewOrderObject").value);
if (newOrderObject.hasOwnProperty("AccountKey")) {
// This is the case for single orders, or conditional/related orders
// This function is used for other order types as well, so more order types are considered
newOrderObject.AccountKey = demo.user.accountKey;
}
if (newOrderObject.hasOwnProperty("Orders")) {
// This is the case for OCO, related and conditional orders
newOrderObject.Orders.forEach(function (order) {
if (order.hasOwnProperty("AccountKey")) {
order.AccountKey = demo.user.accountKey;
}
});
}
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
} catch (e) {
console.error(e);
}
return newOrderObject;
}
/**
* This is an example of getting the trading settings of an instrument.
* There is a much more detailed example of this in the Stock sample.
* That sample checks amongst others the MinimumOrderSize, TradingStatus, SupportedAccounts.
* This one is just to verify the supported conditions.
* @return {void}
*/
function getConditions() {
const newOrderObject = getOrderObjectFromJson();
fetch(
demo.apiUrl + "/ref/v1/instruments/details/" + newOrderObject.Uic + "/" + newOrderObject.AssetType + "?AccountKey=" + encodeURIComponent(demo.user.accountKey) + "&FieldGroups=OrderSetting",
{
"method": "GET",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
const orderConditions = Array.from(document.getElementById("idCbxCondition").options).map(function (opt) {
return opt.value;
});
const supportedConditions = [];
let description;
responseJson.SupportedOrderTypes.forEach(function (orderType) {
if (orderConditions.indexOf(orderType) > -1) {
supportedConditions.push(orderType);
}
});
if (supportedConditions.length === 0) {
description = "Conditional orders are not supported for this instrument and the selected account.";
} else {
description = "Supported conditions are: " + supportedConditions.join(", ");
description += "\nSupported TriggerPriceTypes: " + responseJson.SupportedOrderTriggerPriceTypes.join(", ");
}
console.log(description + "\n\n" + JSON.stringify(responseJson, null, 4));
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of an order validation.
* @return {void}
*/
function preCheckNewOrder() {
// The PreCheck only checks the order, not the trigger!
// Bug: Preview doesn't check for limit outside market hours
function getErrorMessage(responseJson, defaultMessage) {
let errorMessage;
if (responseJson.hasOwnProperty("ErrorInfo")) {
// Be aware that the ErrorInfo.Message might contain line breaks, escaped like "\r\n"!
errorMessage = (
responseJson.ErrorInfo.hasOwnProperty("Message")
? responseJson.ErrorInfo.Message
: responseJson.ErrorInfo.ErrorCode // In some cases (AllocationKeyDoesNotMatchAccount) the message is not available
);
// There can be error messages per order. Try to add them.
if (responseJson.hasOwnProperty("Orders")) {
responseJson.Orders.forEach(function (order) {
errorMessage += "\n- " + getErrorMessage(order, "");
});
}
} else {
errorMessage = defaultMessage;
}
return errorMessage;
}
const newOrderObject = getOrderObjectFromJson();
newOrderObject.FieldGroups = ["Costs", "MarginImpactBuySell"];
fetch(
demo.apiUrl + "/trade/v2/orders/precheck",
{
"method": "POST",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value,
"Content-Type": "application/json; charset=utf-8",
"X-Request-ID": Math.random() // This prevents error 409 (Conflict) from identical previews within 15 seconds
},
"body": JSON.stringify(newOrderObject)
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
// Response must have PreCheckResult property being "Ok"
if (responseJson.PreCheckResult === "Ok") {
// Secondly, you can have a PreCheckResult of "Ok", but still a (functional) error
// Order could be placed if the account had sufficient margin and funding.
// In this case all calculated cost and margin values are in the response, together with an ErrorInfo object:
if (responseJson.hasOwnProperty("ErrorInfo")) {
// Be aware that the ErrorInfo.Message might contain line breaks, escaped like "\r\n"!
console.error(getErrorMessage(responseJson, "") + "\n\n" + JSON.stringify(responseJson, null, 4));
} else {
// The order can be placed
console.log("The order can be placed:\n\n" + JSON.stringify(responseJson, null, 4));
}
} else {
// Order request is syntactically correct, but the order cannot be placed, as it would violate semantic rules
// This can be something like: {"ErrorInfo":{"ErrorCode":"IllegalInstrumentId","Message":"Instrument ID is invalid"},"EstimatedCashRequired":0.0,"PreCheckResult":"Error"}
console.error(getErrorMessage(responseJson, "Order request is syntactically correct, but the order cannot be placed, as it would violate semantic rules:") + "\n\n" + JSON.stringify(responseJson, null, 4) + "\n\nX-Correlation header (for troubleshooting with Saxo): " + response.headers.get("X-Correlation"));
}
});
} else {
// This can be something like: {"Message":"One or more properties of the request are invalid!","ModelState":{"Orders":["Stop leg of OCO order must have OrderType of either: TrailingStopIfTraded, StopIfTraded, StopLimit"]},"ErrorCode":"InvalidModelState"}
// The developer (you) must fix this.
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of placing a conditional order.
* @return {void}
*/
function placeNewOrder() {
const headersObject = {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value,
"Content-Type": "application/json; charset=utf-8"
};
const newOrderObject = getOrderObjectFromJson();
fetch(
demo.apiUrl + "/trade/v2/orders",
{
"method": "POST",
"headers": headersObject,
"body": JSON.stringify(newOrderObject)
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
const xRequestId = response.headers.get("X-Request-ID");
console.log("Successful request:\n" + JSON.stringify(responseJson, null, 4) + (
xRequestId === null
? ""
: "\nX-Request-ID response header: " + xRequestId
));
lastOrderId = responseJson.OrderId;
lastOrderIdCondition = responseJson.Orders[0].OrderId;
});
} else {
console.debug(response);
if (response.status === 403) {
// Don't add this check to your application, but for learning purposes:
// An HTTP Forbidden indicates that your app is not enabled for trading.
// See https://www.developer.saxo/openapi/appmanagement
demo.processError(response, "Your app might not be enabled for trading.");
} else {
demo.processError(response);
}
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of updating a conditional order.
* @return {void}
*/
function modifyLastOrder() {
const newOrderObject = getOrderObjectFromJson();
const headersObject = {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value,
"Content-Type": "application/json; charset=utf-8"
};
newOrderObject.OrderId = lastOrderId;
newOrderObject.Orders[0].OrderId = lastOrderIdCondition;
fetch(
demo.apiUrl + "/trade/v2/orders",
{
"method": "PATCH",
"headers": headersObject,
"body": JSON.stringify(newOrderObject)
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
const xRequestId = response.headers.get("X-Request-ID");
console.log("Successful request:\n" + JSON.stringify(responseJson, null, 4) + (
xRequestId === null
? ""
: "\nX-Request-ID response header: " + xRequestId
));
});
} else {
// If you get a 404 NotFound, the order might already be executed!
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of removing an order from the book.
* @return {void}
*/
function cancelLastOrder() {
fetch(
demo.apiUrl + "/trade/v2/orders/" + lastOrderId + "?AccountKey=" + encodeURIComponent(demo.user.accountKey),
{
"method": "DELETE",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
// Response must have an OrderId
console.log(JSON.stringify(responseJson, null, 4));
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* Create a description of the order with condition.
* @return {void}
*/
function getConditionInText(conditionalOrder) {
function priceTypeInText() {
switch (conditionalOrder.TriggerOrderData.PriceType) {
case "LastTraded":
return "last traded";
default:
return conditionalOrder.TriggerOrderData.PriceType.toLowerCase();
}
}
let description = "Activate this order when the following condition is met:\n";
let expirationDate;
switch (conditionalOrder.OrderType) {
case "TriggerStop": // Distance
description += conditionalOrder.AssetType + " " + conditionalOrder.Uic + " " + priceTypeInText() + " price is " + conditionalOrder.TrailingStopDistanceToMarket + " " + (
conditionalOrder.BuySell === "Sell"
? "above lowest "
: "below highest "
) + priceTypeInText() + " price";
break;
case "TriggerBreakout": // Breakout
description += conditionalOrder.AssetType + " " + conditionalOrder.Uic + " " + priceTypeInText() + " price is outside " + conditionalOrder.TriggerOrderData.LowerPrice + "-" + conditionalOrder.TriggerOrderData.UpperPrice;
break;
case "TriggerLimit": // Price
description += conditionalOrder.AssetType + " " + conditionalOrder.Uic + " last traded price is at or " + (
conditionalOrder.BuySell === "Sell"
? "above"
: "below"
) + " " + conditionalOrder.TriggerOrderData.LowerPrice;
break;
}
description += ".\n";
switch (conditionalOrder.OrderDuration.DurationType) {
case "GoodTillDate":
expirationDate = new Date(conditionalOrder.OrderDuration.ExpirationDateTime);
description += "Valid until trade day " + expirationDate.toLocaleDateString() + ".";
break;
case "DayOrder":
description += "Valid for current trade day.";
break;
case "GoodTillCancel":
description += "Valid until met or canceled.";
break;
}
return description;
}
/**
* This function is called when the value of idCbxCondition is changed.
* @return {void}
*/
function changeCondition() {
// Conditions are Price, Breakout and Distance.
// A price condition is met when the price of the trigger instrument reaches a certain value.
// Example of a price condition: Microsoft Corp. last traded price is at or below 250.00. Valid until met or cancelled.
// .. of a breakout condition: EURUSD close price is outside 1.1500-1.1600. Valid until trade day 22-Dec-2022.
// .. of a distance condition: DAX Index is 1,000 below highest open price. Valid for current trade day.
const newOrderObject = getOrderObjectFromJson();
const conditionalOrder = newOrderObject.Orders[0];
const newCondition = document.getElementById("idCbxCondition").value;
conditionalOrder.OrderType = newCondition;
delete conditionalOrder.TrailingStopStep;
delete conditionalOrder.TrailingStopDistanceToMarket;
delete conditionalOrder.TriggerOrderData.UpperPrice;
switch (newCondition) {
case "TriggerStop": // Distance
conditionalOrder.TrailingStopStep = 0.05;
conditionalOrder.TrailingStopDistanceToMarket = 50;
conditionalOrder.TriggerOrderData.LowerPrice = 700;
conditionalOrder.BuySell = document.getElementById("idCbxOperator").value;
break;
case "TriggerBreakout": // Breakout
conditionalOrder.TriggerOrderData.LowerPrice = 10;
conditionalOrder.TriggerOrderData.UpperPrice = 1500;
delete conditionalOrder.BuySell;
break;
case "TriggerLimit": // Price
conditionalOrder.TriggerOrderData.LowerPrice = 1000;
conditionalOrder.BuySell = document.getElementById("idCbxOperator").value;
break;
}
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
console.log(getConditionInText(conditionalOrder));
}
/**
* This function is called when the value of idCbxOperator is changed.
* @return {void}
*/
function changeOperator() {
// Applicable for Limits. When "At or above": Sell, when "At or below": Buy.
const newOrderObject = getOrderObjectFromJson();
newOrderObject.Orders[0].BuySell = document.getElementById("idCbxOperator").value;
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
console.log(getConditionInText(newOrderObject.Orders[0]));
}
/**
* This function is called when the value of idCbxTrigger is changed.
* @return {void}
*/
function changeTrigger() {
// Triggers differ per condition.
const newOrderObject = getOrderObjectFromJson();
newOrderObject.Orders[0].TriggerOrderData.PriceType = document.getElementById("idCbxTrigger").value;
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
console.log(getConditionInText(newOrderObject.Orders[0]));
}
/**
* This function is called when the value of idCbxExpiry is changed.
* @return {void}
*/
function changeExpiry() {
const expiry = document.getElementById("idCbxExpiry").value;
const expiryDate = new Date();
const newOrderObject = getOrderObjectFromJson();
const conditionalOrder = newOrderObject.Orders[0];
switch (expiry) {
case "EOM":
conditionalOrder.OrderDuration.DurationType = "GoodTillDate";
expiryDate.setMonth(expiryDate.getMonth() + 1, 0);
conditionalOrder.OrderDuration.ExpirationDateTime = expiryDate.toISOString().split("T")[0];
conditionalOrder.OrderDuration.ExpirationDateContainsTime = false;
break;
case "EOY":
conditionalOrder.OrderDuration.DurationType = "GoodTillDate";
expiryDate.setFullYear(expiryDate.getFullYear() + 1, 0, 0);
conditionalOrder.OrderDuration.ExpirationDateTime = expiryDate.toISOString().split("T")[0];
conditionalOrder.OrderDuration.ExpirationDateContainsTime = false;
break;
default:
conditionalOrder.OrderDuration.DurationType = expiry;
delete conditionalOrder.OrderDuration.ExpirationDateTime;
delete conditionalOrder.OrderDuration.ExpirationDateContainsTime;
}
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
console.log(getConditionInText(conditionalOrder));
}
demo.setupEvents([
{"evt": "change", "elmId": "idCbxCondition", "func": changeCondition, "funcsToDisplay": [changeCondition, getConditionInText]},
{"evt": "change", "elmId": "idCbxOperator", "func": changeOperator, "funcsToDisplay": [changeOperator, getConditionInText]},
{"evt": "change", "elmId": "idCbxTrigger", "func": changeTrigger, "funcsToDisplay": [changeTrigger, getConditionInText]},
{"evt": "change", "elmId": "idCbxExpiry", "func": changeExpiry, "funcsToDisplay": [changeExpiry, getConditionInText]},
{"evt": "click", "elmId": "idBtnGetConditions", "func": getConditions, "funcsToDisplay": [getConditions]},
{"evt": "click", "elmId": "idBtnPreCheckOrder", "func": preCheckNewOrder, "funcsToDisplay": [preCheckNewOrder]},
{"evt": "click", "elmId": "idBtnPlaceNewOrder", "func": placeNewOrder, "funcsToDisplay": [placeNewOrder]},
{"evt": "click", "elmId": "idBtnModifyLastOrder", "func": modifyLastOrder, "funcsToDisplay": [modifyLastOrder]},
{"evt": "click", "elmId": "idBtnCancelLastOrder", "func": cancelLastOrder, "funcsToDisplay": [cancelLastOrder]}
]);
demo.displayVersion("trade");
}());