-
Notifications
You must be signed in to change notification settings - Fork 25
/
demo.js
845 lines (810 loc) · 41.1 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
/*jslint browser: true, for: 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")
});
const fictivePrice = 70; // SIM doesn't allow calls to price endpoint for most instruments
let lastOrderId = "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;
}
/**
* Modify the order object so the elements comply to the order type.
* @return {void}
*/
function changeOrderType() {
const newOrderObject = getOrderObjectFromJson();
newOrderObject.OrderType = document.getElementById("idCbxOrderType").value;
delete newOrderObject.OrderPrice;
delete newOrderObject.StopLimitPrice;
delete newOrderObject.TrailingstopDistanceToMarket;
delete newOrderObject.TrailingStopStep;
switch (newOrderObject.OrderType) {
case "Limit": // A buy order will be executed when the price falls below the provided price point; a sell order when the price increases beyond the provided price point.
fetch(
demo.apiUrl + "/trade/v1/infoprices?AssetType=" + newOrderObject.AssetType + "&uic=" + newOrderObject.Uic + "&FieldGroups=" + encodeURIComponent("DisplayAndFormat,Quote"),
{
"method": "GET",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
if (responseJson.Quote.PriceTypeBid === "NoAccess") {
newOrderObject.OrderPrice = fictivePrice; // SIM doesn't supply prices for most instruments (only FxSpot)
console.error("Price not available, so using fictive price (only for testing).");
} else {
newOrderObject.OrderPrice = responseJson.Quote.Bid;
}
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
console.log("Result of price request due to switch to 'Limit':\n" + JSON.stringify(responseJson, null, 4));
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
break;
case "Market": // Order is attempted filled at best price in the market.
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
break;
case "StopIfBid": // A buy order will be executed when the bid price increases to the provided price point; a sell order when the price falls below.
case "StopIfOffered": // A buy order will be executed when the ask price increases to the provided price point; a sell order when the price falls below.
case "StopIfTraded": // A buy order will be executed when the last price increases to the provided price point; a sell order when the price falls below.
newOrderObject.OrderPrice = fictivePrice;
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
break;
case "StopLimit": // A buy StopLimit order will turn in to a regular limit order once the price goes beyond the OrderPrice. The limit order will have a OrderPrice of the StopLimitPrice.
newOrderObject.OrderPrice = fictivePrice;
newOrderObject.StopLimitPrice = fictivePrice + 1; // Some other fictivePrice
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
break;
case "TrailingStop": // A trailing stop order type is used to guard a position against a potential loss, but the order price follows that of the position when the price goes up. It does so in steps, trying to keep a fixed distance to the current price.
case "TrailingStopIfBid":
case "TrailingStopIfOffered":
case "TrailingStopIfTraded":
newOrderObject.OrderPrice = fictivePrice;
newOrderObject.TrailingstopDistanceToMarket = 1;
newOrderObject.TrailingStopStep = 0.1;
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
break;
case "TriggerBreakout":
case "TriggerLimit":
case "TriggerStop":
console.error("You've selected an ordertype for a conditional order, which is not covered by this sample.\nSee for conditional orders:\nhttps://saxobank.github.io/openapi-samples-js/orders/conditional-orders/");
break;
default:
console.error("Unsupported order type " + newOrderObject.OrderType);
}
populateSupportedOrderDurations(newOrderObject.OrderDuration.DurationType);
}
/**
* Adjust the order object in the textarea so the related properties comply with the chosen order duration.
* @return {void}
*/
function changeOrderDuration() {
/**
* Prefix number with zero, if it has one digit.
* @param {number} n The one or two digit number representing day or month.
* @return {string} The formatted number.
*/
function addLeadingZero(n) {
return (
n > 9
? String(n)
: "0" + n
);
}
const newOrderObject = getOrderObjectFromJson();
const now = new Date();
newOrderObject.OrderDuration.DurationType = document.getElementById("idCbxOrderDuration").value;
switch (newOrderObject.OrderDuration.DurationType) {
case "AtTheClose":
case "AtTheOpening":
case "DayOrder":
case "GoodForPeriod":
case "GoodTillCancel":
case "FillOrKill":
case "ImmediateOrCancel": // The order is working for a very short duration and when the time is up, the order is canceled. What ever fills happened in the short time, is what constitute a position. Primarily used for Fx and CFDs.
delete newOrderObject.OrderDuration.ExpirationDateTime;
delete newOrderObject.OrderDuration.ExpirationDateContainsTime;
break;
case "GoodTillDate": // Requires an explicit date. Cancellation of the order happens at some point on that date.
now.setDate(now.getDate() + 3); // Add 3x24 hours to now
now.setSeconds(0, 0);
newOrderObject.OrderDuration.ExpirationDateTime = now.getFullYear() + "-" + addLeadingZero(now.getMonth() + 1) + "-" + addLeadingZero(now.getDate()) + "T" + addLeadingZero(now.getHours()) + ":" + addLeadingZero(now.getMinutes()) + ":00"; // Example: 2020-03-20T14:00:00
newOrderObject.OrderDuration.ExpirationDateContainsTime = true;
break;
default:
console.error("Unsupported order duration " + newOrderObject.OrderDuration.DurationType);
}
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
}
/**
* Add the order durations available for the selected order type to the combo box. Pre-select the type which was selected before, when available.
* @param {string} selectedOrderDuration The order duration to be selected.
* @return {void}
*/
function populateSupportedOrderDurations(selectedOrderDuration) {
const cbxOrderType = document.getElementById("idCbxOrderType");
const cbxOrderDuration = document.getElementById("idCbxOrderDuration");
// The durations were stored, when parsing the instrument details. The can differ per OrderType.
const supportedDurations = cbxOrderType.options[cbxOrderType.selectedIndex].dataset.durations.split("|");
let isSelectedDurationSupported = false;
let option;
let i;
// Make the list empty first..
for (i = cbxOrderDuration.options.length - 1; i >= 0; i -= 1) {
cbxOrderDuration.remove(i);
}
supportedDurations.forEach(function (orderDuration) {
option = document.createElement("option");
option.text = orderDuration;
option.value = orderDuration;
if (orderDuration === selectedOrderDuration) {
option.setAttribute("selected", true); // Make the selected type the default one
isSelectedDurationSupported = true;
}
cbxOrderDuration.add(option);
});
if (!isSelectedDurationSupported) {
// Update the duration in the order object, because it is not supported.
changeOrderDuration();
}
}
/**
* Add the order types available for this instrument (and account) to the combo box. Pre-select the type which was selected before, when available.
* @param {Array} orderTypeSettings The order types to be added.
* @param {string} selectedOrderType The order type to be selected.
* @return {void}
*/
function populateSupportedOrderTypes(orderTypeSettings, selectedOrderType) {
const cbxOrderType = document.getElementById("idCbxOrderType");
let option;
let isSelectedOrderTypeSupported = false;
let i;
// Make the list empty first..
for (i = cbxOrderType.options.length - 1; i >= 0; i -= 1) {
cbxOrderType.remove(i);
}
orderTypeSettings.forEach(function (orderTypeSetting) {
option = document.createElement("option");
option.text = orderTypeSetting.OrderType;
option.value = orderTypeSetting.OrderType;
// Store the supported durations for this OrderType:
option.dataset.durations = orderTypeSetting.DurationTypes.join("|");
if (orderTypeSetting.OrderType === selectedOrderType) {
option.setAttribute("selected", true); // Make the selected type the default one
isSelectedOrderTypeSupported = true;
}
cbxOrderType.add(option);
});
if (!isSelectedOrderTypeSupported) {
changeOrderType(); // The current order type is not supported. Change to a different one
}
}
/**
* This demo can be used for not only Stocks. You can change the model in the editor to Bond, SrdOnStock, etc.
* @param {Object} responseJson The response with the references.
* @return {string} A message pointing you at the feature to change the order object.
*/
function getRelatedAssetTypesMessage(responseJson) {
let result = "";
let i;
let relatedInstrument;
function addAssetTypeToMessage(assetType) {
if (relatedInstrument.AssetType === assetType) {
result += (
result === ""
? ""
: "\n\n"
) + "The response below indicates there is a related " + assetType + ".\nYou can change the order object to AssetType '" + assetType + "' and Uic '" + relatedInstrument.Uic + "' to test " + assetType + " orders.";
}
}
if (responseJson.hasOwnProperty("RelatedInstruments")) {
for (i = 0; i < responseJson.RelatedInstruments.length; i += 1) {
relatedInstrument = responseJson.RelatedInstruments[i];
addAssetTypeToMessage("Bond");
addAssetTypeToMessage("SrdOnStock");
// The other way around works as well. Show message for Stock.
addAssetTypeToMessage("Stock");
}
}
if (responseJson.hasOwnProperty("RelatedOptionRootsEnhanced")) {
// Don't loop. Just take the first, for demo purposes.
relatedInstrument = responseJson.RelatedOptionRootsEnhanced[0];
result += (
result === ""
? ""
: "\n\n"
) + "The response below indicates there are related options.\nYou can use OptionRootId '" + relatedInstrument.OptionRootId + "' in the options example.";
}
return result;
}
/**
* 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);
if (responseJson.AccessRights.CanTrade) {
console.log("You are allowed to place orders." + responseText);
} else {
console.error("You are not allowed to place orders." + responseText);
}
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of getting the trading settings of an instrument.
* @return {void}
*/
function getConditions() {
/**
* The instrument is tradable, but there might be limitations. If so, display them.
* @param {Object} detailsObject The response with the instrument details.
* @return {void}
*/
function checkTradingStatus(detailsObject) {
let statusDescription = "This instrument has trading limitations:\n";
if (detailsObject.TradingStatus !== "Tradable") {
if (detailsObject.hasOwnProperty("NonTradableReason")) {
switch (detailsObject.NonTradableReason) {
case "ETFsWithoutKIIDs":
statusDescription += "The issuer has not provided a Key Information Document (KID) for this instrument.";
break;
case "ExpiredInstrument":
statusDescription += "This instrument has expired.";
break;
case "NonShortableInstrument":
statusDescription += "Short selling is not available for this instrument.";
break;
case "NotOnlineClientTradable":
statusDescription += "This instrument is not tradable online.";
break;
case "OfflineTradableBonds":
statusDescription += "This instrument is tradable offline.";
break;
case "ReduceOnlyInstrument":
statusDescription += "This instrument is reduce-only.";
break;
default:
// There are reasons "OtherReason" and "None".
statusDescription += "This instrument is not tradable.";
}
statusDescription += "\n(" + detailsObject.NonTradableReason + ")";
} else {
// Somehow not reason was supplied.
statusDescription += "Status: " + detailsObject.TradingStatus;
}
window.alert(statusDescription);
}
}
/**
* Verify if the selected account is capable of handling this instrument.
* @param {Array<string>} tradableOn Supported account list.
* @return {void}
*/
function checkSupportedAccounts(tradableOn) {
// First, get the id of the active account:
const activeAccountId = demo.user.accounts.find(function (i) {
return i.accountKey === demo.user.accountKey;
}).accountId;
// Next, check if instrument is allowed on this account:
if (tradableOn.length === 0) {
window.alert("This instrument cannot be traded on any of your accounts.");
} else if (tradableOn.indexOf(activeAccountId) === -1) {
window.alert("This instrument cannot be traded on the selected account " + activeAccountId + ", but only on " + tradableOn.join(", ") + ".");
}
}
function calculateFactor(tickSize) {
let numberOfDecimals = 0;
if ((tickSize % 1) !== 0) {
numberOfDecimals = tickSize.toString().split(".")[1].length;
}
return Math.pow(10, numberOfDecimals);
}
function checkTickSize(orderObject, tickSize) {
const factor = calculateFactor(tickSize); // Modulo doesn't support fractions, so multiply with a factor
if (Math.round(orderObject.OrderPrice * factor) % Math.round(tickSize * factor) !== 0) {
window.alert("The price of " + orderObject.OrderPrice + " doesn't match the tick size of " + tickSize);
}
}
function checkTickSizes(orderObject, tickSizeScheme) {
let tickSize = tickSizeScheme.DefaultTickSize;
let i;
for (i = 0; i < tickSizeScheme.Elements.length; i += 1) {
if (orderObject.OrderPrice <= tickSizeScheme.Elements[i].HighPrice) {
tickSize = tickSizeScheme.Elements[i].TickSize; // The price is below a threshold and therefore not the default
break;
}
}
checkTickSize(orderObject, tickSize);
}
function checkMinimumTradeSize(orderObject, detailsObject) {
if (orderObject.Amount < detailsObject.MinimumTradeSize) {
window.alert("The order amount must be at least the minimumTradeSize of " + detailsObject.MinimumTradeSize);
}
}
function checkMinimumOrderValue(orderObject, detailsObject) {
const price = (
orderObject.hasOwnProperty("OrderPrice")
? orderObject.OrderPrice
: fictivePrice // SIM doesn't allow calls to price endpoint for most instruments so just take something
);
if (orderObject.Amount * price < detailsObject.MinimumOrderValue) {
window.alert("The order value (amount * price) must be at least the minimumOrderValue of " + detailsObject.MinimumOrderValue);
}
}
function checkLotSizes(orderObject, detailsObject) {
if (orderObject.Amount < detailsObject.MinimumLotSize) {
window.alert("The amount must be at least the minimumLotSize of " + detailsObject.MinimumLotSize);
}
if (detailsObject.hasOwnProperty("LotSize") && orderObject.Amount % detailsObject.LotSize !== 0) {
window.alert("The amount must be the lot size or a multiplication of " + detailsObject.LotSize);
}
}
const newOrderObject = getOrderObjectFromJson();
// This requests gets the order settings of the selected instrument.
// By adding the AccountKey, specific account settings are considered as well.
fetch(
demo.apiUrl + "/ref/v1/instruments/details/" + newOrderObject.Uic + "/" + newOrderObject.AssetType + "?AccountKey=" + encodeURIComponent(demo.user.accountKey) + "&FieldGroups=SupportedOrderTypeSettings",
{
"method": "GET",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
populateSupportedOrderTypes(responseJson.SupportedOrderTypeSettings, newOrderObject.OrderType);
populateSupportedOrderDurations(newOrderObject.OrderDuration.DurationType);
console.log(getRelatedAssetTypesMessage(responseJson) + "\n\n" + JSON.stringify(responseJson, null, 4));
if (responseJson.IsTradable === false) {
window.alert("This instrument is not tradable!");
// For demonstration purposes the validation continues, but an order ticket shouldn't be shown!
}
checkTradingStatus(responseJson);
if (newOrderObject.OrderType !== "Market" && newOrderObject.OrderType !== "TraspasoIn") {
if (responseJson.hasOwnProperty("TickSizeScheme")) {
checkTickSizes(newOrderObject, responseJson.TickSizeScheme);
} else if (responseJson.hasOwnProperty("TickSize")) {
checkTickSize(newOrderObject, responseJson.TickSize);
}
}
checkSupportedAccounts(responseJson.TradableOn);
checkMinimumTradeSize(newOrderObject, responseJson);
if (newOrderObject.AssetType === "Stock") {
checkMinimumOrderValue(newOrderObject, responseJson);
}
if (newOrderObject.AssetType === "Stock" && responseJson.LotSizeType !== "NotUsed") {
checkLotSizes(newOrderObject, responseJson);
}
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* Returns trading schedule for a given uic and asset type.
* @return {void}
*/
function getTradingSchedule() {
const newOrderObject = getOrderObjectFromJson();
fetch(
demo.apiUrl + "/ref/v1/instruments/tradingschedule/" + newOrderObject.Uic + "/" + newOrderObject.AssetType,
{
"method": "GET",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
const now = new Date();
let responseText = "";
responseJson.Sessions.forEach(function (session) {
const startTime = new Date(session.StartTime);
const endTime = new Date(session.EndTime);
if (now >= startTime && now < endTime) {
// This is the session we are in now, usually the first.
responseText += "--> ";
}
responseText += session.State + " from " + startTime.toLocaleString() + " to " + endTime.toLocaleString() + "\n";
});
console.log(responseText);
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of an order validation.
* @return {void}
*/
function preCheckNewOrder() {
// 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 single leg order.
* @return {void}
*/
function placeNewOrder() {
const headersObject = {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value,
"Content-Type": "application/json; charset=utf-8"
};
const newOrderObject = getOrderObjectFromJson();
if (document.getElementById("idChkRequestIdHeader").checked) {
headersObject["X-Request-ID"] = newOrderObject.ExternalReference; // Warning! Prevent error 409 (Conflict) from identical orders within 15 seconds
}
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;
});
} 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 getting detailed information of a specific order (in this case the last placed order).
* @return {void}
*/
function getOrderDetails() {
fetch(
demo.apiUrl + "/port/v1/orders/" + encodeURIComponent(demo.user.clientKey) + "/" + lastOrderId,
{
"method": "GET",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
if (responseJson.Data.length === 0) {
console.error("The order wasn't found in the list of active orders. Is order " + lastOrderId + " still open?");
} else {
console.log("Response: " + JSON.stringify(responseJson, null, 4));
}
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* This is an example of updating a single leg 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;
if (document.getElementById("idChkRequestIdHeader").checked) {
headersObject["X-Request-ID"] = newOrderObject.ExternalReference; // Warning! Prevent error 409 (Conflict) from identical orders within 15 seconds
}
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);
});
}
/**
* This sample can be used for other AssetTypes than Stock. After switching, retrieve a valid Asset.
* @return {void}
*/
function findInstrumentsForAssetType() {
/**
* For options, the identifier is an OptionRoot. Convert this to a Uic.
* @param {number} optionRootId The identifier from the instrument response
* @return {void}
*/
function convertOptionRootIdToUic(optionRootId) {
fetch(
demo.apiUrl + "/ref/v1/instruments/contractoptionspaces/" + optionRootId,
{
"method": "GET",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
const newOrderObject = getOrderObjectFromJson();
newOrderObject.Uic = responseJson.OptionSpace[0].SpecificOptions[0].Uic; // Select first contract
newOrderObject.ToOpenClose = "ToOpen";
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
const assetType = document.getElementById("idCbxAssetType").value;
fetch(
demo.apiUrl + "/ref/v1/instruments?AssetTypes=" + assetType + "&IncludeNonTradable=false&$top=1" + "&AccountKey=" + encodeURIComponent(demo.user.accountKey),
{
"method": "GET",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
const newOrderObject = getOrderObjectFromJson();
let instrument;
if (responseJson.Data.length === 0) {
console.error("No instrument of type " + assetType + " found.");
} else {
instrument = responseJson.Data[0]; // Just take the first instrument - it's a demo
newOrderObject.AssetType = assetType;
newOrderObject.Uic = instrument.Identifier; // This might only be an OptionRootId!
if (assetType === "MutualFund") {
newOrderObject.AmountType = "Quantity"; // DurationType might be GoodTillCancel
} else {
delete newOrderObject.AmountType;
}
if (instrument.SummaryType === "Instrument") {
delete newOrderObject.ToOpenClose;
}
document.getElementById("idNewOrderObject").value = JSON.stringify(newOrderObject, null, 4);
console.log("Changed object to asset of type " + assetType + ".");
if (instrument.SummaryType === "ContractOptionRoot") {
// Get the first option of this option series.
convertOptionRootIdToUic(instrument.Identifier);
}
}
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
/**
* Order changes are broadcasted via ENS. Retrieve the recent events to see what you can expect.
* @return {void}
*/
function getHistoricalEnsEvents() {
const fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() - 10);
fetch(
demo.apiUrl + "/ens/v1/activities?Activities=Orders&FromDateTime=" + fromDate.toISOString(),
{
"method": "GET",
"headers": {
"Authorization": "Bearer " + document.getElementById("idBearerToken").value
}
}
).then(function (response) {
if (response.ok) {
response.json().then(function (responseJson) {
console.log("Found " + responseJson.Data.length + " event(s) in the last 10 minutes:\n\n" + JSON.stringify(responseJson, null, 4));
});
} else {
demo.processError(response);
}
}).catch(function (error) {
console.error(error);
});
}
demo.setupEvents([
{"evt": "change", "elmId": "idCbxAssetType", "func": findInstrumentsForAssetType, "funcsToDisplay": [findInstrumentsForAssetType]},
{"evt": "change", "elmId": "idCbxOrderType", "func": changeOrderType, "funcsToDisplay": [changeOrderType, populateSupportedOrderDurations, changeOrderDuration]},
{"evt": "change", "elmId": "idCbxOrderDuration", "func": changeOrderDuration, "funcsToDisplay": [changeOrderDuration]},
{"evt": "click", "elmId": "idBtnGetAccessRights", "func": getAccessRights, "funcsToDisplay": [getAccessRights]},
{"evt": "click", "elmId": "idBtnGetConditions", "func": getConditions, "funcsToDisplay": [getConditions]},
{"evt": "click", "elmId": "idBtnGetTradingSchedule", "func": getTradingSchedule, "funcsToDisplay": [getTradingSchedule]},
{"evt": "click", "elmId": "idBtnPreCheckOrder", "func": preCheckNewOrder, "funcsToDisplay": [preCheckNewOrder]},
{"evt": "click", "elmId": "idBtnPlaceNewOrder", "func": placeNewOrder, "funcsToDisplay": [placeNewOrder]},
{"evt": "click", "elmId": "idBtnGetOrderDetails", "func": getOrderDetails, "funcsToDisplay": [getOrderDetails]},
{"evt": "click", "elmId": "idBtnModifyLastOrder", "func": modifyLastOrder, "funcsToDisplay": [modifyLastOrder]},
{"evt": "click", "elmId": "idBtnCancelLastOrder", "func": cancelLastOrder, "funcsToDisplay": [cancelLastOrder]},
{"evt": "click", "elmId": "idBtnHistoricalEnsEvents", "func": getHistoricalEnsEvents, "funcsToDisplay": [getHistoricalEnsEvents]}
]);
demo.displayVersion("trade");
}());