forked from gfiocco/node-ig-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
1143 lines (1064 loc) · 30 KB
/
index.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
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const fs = require('fs');
const https = require('https');
const path = require('path');
// required for Lighstreamer
const requirejs = require('requirejs');
requirejs.config({
deps: [__dirname + '/lib/lightstreamer.js'],
// v6.2.6 build 1678 - https://labs.ig.com/lightstreamer-downloads
// http://www.lightstreamer.com/repo/distros/Lightstreamer_Allegro-Presto-Vivace_6_0_1_20150730.zip%23/Lightstreamer/DOCS-SDKs/sdk_client_javascript/doc/API-reference/index.html
nodeRequire: require
});
// required for IG psw encryption
require('./lib/seedrandom');
require('./lib/rsa');
require('./lib/asn1');
const pidCrypt = require('./lib');
const pidCryptUtil = require('./lib/pidcrypt_util');
var lsClient;
var subscription;
var tokensDir = path.join(__dirname, 'tokens.json');
var tokens = require(tokensDir);
process.env.IG_TOKENS_EXP = tokens.tokens_exp;
process.env.IG_XST = tokens['x-security-token'];
process.env.IG_CST = tokens.cst;
process.env.IG_LIGHTSTREAMER_END_POINT = tokens.lightstreamerEndpoint;
var demo = process.env.IG_DEMO==='TRUE'?true:false;
var tokensNull = {
'tokens_exp': 0,
'x-request-id': '',
'x-security-token': '',
'cst': '',
'lightstreamerEndpoint': '',
'currentAccountId': ''
};
var lsClient = {};
var subscription = {};
///////////////////////////////
// GENERIC IG REST REQUESTER //
///////////////////////////////
// Generic REST client for the IG trading API
function _request(method, path, payload, extraHeaders) {
let headers = {
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json; charset=UTF-8',
'X-IG-API-KEY': process.env.IG_API_KEY
};
let encodedPayload = '';
if (payload) {
encodedPayload = JSON.stringify(payload);
headers['Content-Length'] = Buffer.byteLength(encodedPayload);
}
if (extraHeaders) {
headers = Object.assign(headers, extraHeaders);
}
let reqOpts = {
hostname: demo ? 'demo-api.ig.com' : 'api.ig.com',
path: '/gateway/deal' + path,
method,
headers,
};
return new Promise((resolve, reject) => {
let req = https.request(reqOpts, res => {
let status = res.statusCode;
let headers = res.headers;
let body = '';
res.on('data', data => {
body += data.toString('utf8');
});
res.on('end', () => {
try {
resolve({
status,
headers,
body: body.length === 0 ? {} : JSON.parse(body) // cannot parse an empty body
});
} catch (e) {
reject({
status,
headers,
e
});
}
});
});
req.on('error', e => {
reject({
status,
headers,
e
});
});
if (method !== 'GET') {
req.write(encodedPayload);
}
req.end();
});
}
// RSA password encryption
function _pwdEncrypter(password, encryptionKey, timestamp) {
let rsa = new pidCrypt.RSA();
let decodedKey = pidCryptUtil.decodeBase64(encryptionKey);
let asn = pidCrypt.ASN1.decode(pidCryptUtil.toByteArray(decodedKey));
let tree = asn.toHexTree();
rsa.setPublicKeyFromASN(tree);
return pidCryptUtil.encodeBase64(pidCryptUtil.convertFromHex(rsa.encrypt(password + '|' + timestamp)));
}
// Get request on ig api
function get(url, version) {
if ([2, 3].indexOf(version) === -1) {
version = 1;
}
let extraHeaders = {
'x-security-token': process.env.IG_XST,
cst: process.env.IG_CST,
'version': version
};
return _request('GET', url, false, extraHeaders);
}
// Delete request on ig api
function del(url, payload, version) {
if ([2, 3].indexOf(version) === -1) {
version = 1;
}
let extraHeaders = {
'x-security-token': process.env.IG_XST,
cst: process.env.IG_CST,
'version': version,
'_method': 'DELETE' // tweek header to bypass ig API issue
};
// IG API is not able to handle DELETE requests
return _request('POST', url, payload, extraHeaders);
}
// Put request on ig api
function put(url, payload, version) {
if ([2, 3].indexOf(version) === -1) {
version = 1;
}
let extraHeaders = {
'x-security-token': process.env.IG_XST,
cst: process.env.IG_CST,
'version': version
};
return _request('PUT', url, payload, extraHeaders);
}
// Post request on ig api
function post(url, payload, version) {
if ([2, 3].indexOf(version) === -1) {
version = 1;
}
let extraHeaders = {
'x-security-token': process.env.IG_XST,
cst: process.env.IG_CST,
'version': version
};
return _request('POST', url, payload, extraHeaders);
}
/////////////
// ACCOUNT //
/////////////
// Log in (retrive client and session tokens)
function login(encryption) {
/**
* Log in (retrive client and session tokens)
* @param {boolean} encryption
* @return {json}
*/
return new Promise((res, rej) => {
encryption = typeof(encryption) === 'undefined' ? false : encryption;
let tokens = {};
let extraHeaders = {
'Version': 2
};
if (encryption) {
_request('GET', '/session/encryptionKey') // retrieve encryptionKey and timeStamp for encryption
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
let payload = {
identifier: process.env.IG_IDENTIFIER,
password: _pwdEncrypter(process.env.IG_PASSWORD, r.body.encryptionKey, r.body.timeStamp), //process.env.IG_PASSWORD,
encryptedPassword: true
};
return _request('POST', '/session', payload, extraHeaders);
}
})
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
tokens.tokens_exp = new Date().getTime() + 43200000; // tokens expire in 12h
tokens['x-request-id'] = r.headers['x-request-id'];
tokens['x-security-token'] = r.headers['x-security-token'];
tokens.cst = r.headers.cst;
tokens.lightstreamerEndpoint = r.body.lightstreamerEndpoint;
tokens.currentAccountId = r.body.currentAccountId;
fs.writeFile(tokensDir, JSON.stringify(tokens), 'utf8', (e) => {
if (e) {
rej(e);
} else {
res(r.body);
}
});
}
})
.catch(e => {
rej(e);
});
} else {
let payload = {
identifier: process.env.IG_IDENTIFIER,
password: process.env.IG_PASSWORD,
encryptedPassword: false
};
_request('POST', '/session', payload, extraHeaders)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
tokens.tokens_exp = new Date().getTime() + 43200000; // tokens expire in 12h
tokens['x-request-id'] = r.headers['x-request-id'];
tokens['x-security-token'] = r.headers['x-security-token'];
tokens.cst = r.headers.cst;
tokens.lightstreamerEndpoint = r.body.lightstreamerEndpoint;
tokens.currentAccountId = r.body.currentAccountId;
fs.writeFile(tokensDir, JSON.stringify(tokens), 'utf8', (e) => {
if (e) {
rej(e);
} else {
res(r.body);
}
});
}
})
.catch(e => {
rej(e);
});
}
});
}
// Log out
function logout() {
return new Promise((res, rej) => {
let extraHeaders = {
'x-security-token': process.env.IG_XST,
cst: process.env.IG_CST
};
return _request('DELETE', '/session', false, extraHeaders)
.then(r => {
if (r.status !== 204) {
rej(r);
} else {
fs.writeFile(tokensDir, JSON.stringify(tokensNull), 'utf8', (e) => {
if (e) {
rej(e);
} else {
res('Tokens cleared');
}
});
}
})
.catch(e => {
rej(e);
});
});
}
// Switch Account
function switchAcct(accountId) {
return new Promise((res, rej) => {
let tokens = require(tokensDir);
let payload = {
'accountId': accountId
};
put('/session', payload)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
tokens.tokens_exp = new Date().getTime() + 43200000; // tokens expire in 12h
tokens['x-request-id'] = r.headers['x-request-id'];
tokens['x-security-token'] = r.headers['x-security-token'];
tokens.currentAccountId = accountId;
fs.writeFile(tokensDir, JSON.stringify(tokens), 'utf8', (e) => {
if (e) {
rej(e);
} else {
res(r.body);
}
});
}
})
.catch(e => {
rej(e);
});
});
}
//Returns a list of accounts belonging to the logged-in client
function acctInfo() {
return new Promise((res, rej) => {
get('/accounts')
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
// Returns the account activity history
function acctActivity(from, to, detailed, dealId, pageSize) {
return new Promise((res, rej) => {
// Constraints:
let dateReg = /^\d{4}([./-])\d{2}\1\d{2}$/;
if (!dateReg.test(from)) throw new Error('from has to have format: YYYY-MM-DD');
if (!dateReg.test(to)) throw new Error('to has to have format: YYYY-MM-DD');
if (typeof(from) === 'undefined') {
from = '?from=1990-01-01';
} else {
from = '?from=' + from;
}
if (typeof(to) === 'undefined') {
to = '&to=2099-01-01';
} else {
to = '&to=' + to;
}
if (typeof(detailed) === 'undefined') {
detailed = '&detailed=false';
} else {
detailed = '&detailed=' + detailed;
}
if (typeof(dealId) === 'undefined') {
dealId = '';
} else {
dealId = '&dealId=' + dealId;
}
if (typeof(pageSize) === 'undefined') {
pageSize = '&pageSize=500';
} else {
pageSize = '&pageSize=' + pageSize;
}
let qstring = from + to + detailed + dealId + pageSize;
get('/history/activity' + qstring, 3)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
// Returns the transaction history
function acctTransaction(type, from, to, pageSize, pageNumber) {
return new Promise((res, rej) => {
if (typeof(type) === 'undefined') {
type = '?type=ALL';
} else {
type = '?type=' + type;
} //ALL, ALL_DEAL, DEPOSIT, WITHDRAWAL
if (typeof(from) === 'undefined') {
from = '&from=1990-01-01';
} else {
from = '&from=' + from;
}
if (typeof(to) === 'undefined') {
to = '&to=2099-01-01';
} else {
to = '&to=' + to;
}
if (typeof(pageSize) === 'undefined') {
pageSize = '&pageSize=0';
} else {
pageSize = '&pageSize=' + pageSize;
}
if (typeof(pageNumber) === 'undefined') {
pageNumber = '&pageNumber=0';
} else {
pageNumber = '&pageNumber=' + pageNumber;
}
let qstring = type + from + to + pageSize + pageNumber;
get('/history/transactions' + qstring, 2)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
// List of client-owned applications
function apiInfo() {
return new Promise((res, rej) => {
get('/operations/application').
then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
/////////////
// DEALING //
/////////////
// Returns all open positions for the active account.
function showOpenPositions() {
return new Promise((res, rej) => {
get('/positions')
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
});
});
}
// Creates an OTC position.
function deal(ticket) {
return new Promise((res, rej) => {
// Constraints:
if (['AUD', 'USD', 'EUR', 'GBP', 'CHF', 'NZD', 'JPY', 'CAD'].indexOf(ticket.currencyCode) === -1) throw new Error('currencyCode has to be one of: AUD, USD, EUR, GBP, CHF, NZD, JPY, CAD]');
if (['BUY', 'SELL'].indexOf(ticket.direction) === -1) throw new Error('direction has to be BUY or SELL');
if (!ticket.epic) throw new Error('epic has to be defined');
if (!ticket.expiry) throw new Error('expiry has to be defined');
if (!ticket.size) throw new Error('size has to be defined');
if ([true, false].indexOf(ticket.forceOpen) === -1) throw new Error('forceOpen has to be true or false');
if (['LIMIT', 'MARKET'].indexOf(ticket.orderType) === -1) throw new Error('orderType has to be LIMIT or MARKET');
if ([true, false].indexOf(ticket.guaranteedStop) === -1) throw new Error('guaranteedStop has to be true or false');
if (ticket.limitDistance !== null && ticket.forceOpen === false) throw new Error('If a limitDistance is set, then forceOpen must be true');
if (ticket.limitLevel !== null && ticket.forceOpen === false) throw new Error('If a limitLevel is set, then forceOpen must be true');
if (ticket.stopDistance !== null && ticket.forceOpen === false) throw new Error('If a stopDistance is set, then forceOpen must be true');
if (ticket.stopLevel !== null && ticket.forceOpen === false) throw new Error('If a stopLevel is set, then forceOpen must be true');
if (['FILL_OR_KILL', 'EXECUTE_AND_ELIMINATE'].indexOf(ticket.timeInForce) === -1) throw new Error('timeInForce has to be FILL_OR_KILL or EXECUTE_AND_ELIMINATE');
if (ticket.stopDistance === null && ticket.stopLevel === null && ticket.guaranteedStop === true) throw new Error('If guaranteedStop equals true, then set either stopLevel or stopDistance');
if (ticket.level === null && ticket.orderType === 'LIMIT') throw new Error('If orderType equals LIMIT, then set level');
if (ticket.level !== null && ticket.orderType === 'MARKET') throw new Error('If orderType equals MARKET, then DO NOT set level');
if (ticket.trailingStopIncrement !== null && ticket.trailingStop === false) throw new Error('If trailingStop equals false, then DO NOT set trailingStopIncrement');
if (ticket.trailingStopIncrement !== null && ticket.stopLevel === false) throw new Error('If stopLevel equals false, then DO NOT set trailingStopIncrement');
if (ticket.trailingStopIncrement === null && ticket.trailingStop === true) throw new Error('If trailingStop equals true, then set trailingStopIncrement');
if (ticket.trailingStopIncrement === null && ticket.stopLevel === true) throw new Error('If stopLevel equals true, then set trailingStopIncrement');
if (ticket.trailingStop === true && ticket.guaranteedStop === true) throw new Error('If trailingStop equals true, then guaranteedStop must be false');
if (ticket.limitLevel !== null && ticket.limitDistance !== null) throw new Error('Set only one of limitLevel or limitDistance');
if (ticket.stopLevel !== null && ticket.stopDistance !== null) throw new Error('Set only one of stopLevel or stopDistance');
let response = {};
post('/positions/otc', ticket, 2)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
response.positions = r.body;
return get('/confirms/' + r.body.dealReference);
}
})
.then(r => {
// no need to reject if confirmation request fails
response.confirms = r.body;
res(response);
})
.catch(e => rej(e));
});
}
// Attach order to open position
function editPosition(dial_id, ticket) {
// [Constraint: If trailingStop equals false, then DO NOT set trailingStopDistance,trailingStopIncrement]
// [Constraint: If trailingStop equals true, then set trailingStopDistance,trailingStopIncrement,stopLevel]
return new Promise((res, rej) => {
put('/positions/otc/' + dial_id, ticket, 2)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
return get('/confirms/' + r.body.dealReference);
}
})
.then(r => {
res(r.body);
})
.catch(e => {
rej(e);
});
});
}
// Closes an open position
function closePosition(dealId) {
return new Promise((res, rej) => {
let temp1 = [];
let response = {};
get('/positions', 2)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
let temp2 = r.body.positions;
for (let i = 0; i < temp2.length; i++) {
temp1[temp2[i].position.dealId] = [
temp2[i].market.epic,
temp2[i].market.expiry,
temp2[i].position.direction,
temp2[i].position.size,
temp2[i].position.currency,
temp2[i].market.marketStatus,
temp2[i].market.streamingPricesAvailable,
temp2[i].market.bid,
temp2[i].market.offer
];
}
let ticket = {
// you can close a position by 1) dealId (exact position) or 2) epic + expiry (FIFO)
'dealId': dealId,
'direction': temp1[dealId][2] === 'BUY' ? 'SELL' : 'BUY', // invert to opposite side
// 'epic' : temp1[dealId][0],
// 'expiry': temp1[dealId][1],
'orderType': 'MARKET',
'size': temp1[dealId][3]
};
return del('/positions/otc', ticket);
}
})
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
response.positions = r.body;
return get('/confirms/' + r.body.dealReference);
}
})
.then(r => {
response.confirms = r.body;
res(response);
})
.catch(e => {
rej(e);
});
});
}
// Closes all open positions
function closeAllPositions() {
return new Promise((res, rej) => {
let response = [];
let tickets = [];
let index = 0;
get('/positions', 2)
.then(r => {
let temp = r.body.positions;
if (temp.length === 0)(res('There is no position to close'));
for (let i = 0; i < temp.length; i++) {
tickets.push({
'dealId': temp[i].position.dealId, // to be tested
'direction': temp[i].position.direction === 'BUY' ? 'SELL' : 'BUY', // invert to opposite side
// 'epic' : temp[i].market.epic,
// 'expiry': temp[i].market.expiry,
'orderType': 'MARKET',
'size': temp[i].position.size
});
}
function _close(index) {
if (tickets[index]) {
del('/positions/otc', tickets[index])
.then(r => {
get('/confirms/' + r.body.dealReference)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
index++;
_close(index);
response.push(r.body);
}
})
.catch(e => {
rej(e);
});
})
.catch(e => {
rej(e);
});
} else {
res(response);
}
}
_close(index);
}); // end .then
}); // end promise
}
////////////////////
// WORKING ORDERS //
////////////////////
// Returns all open working orders for the active account.
function showWorkingOrders() {
return new Promise((res, rej) => {
get('/workingorders')
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
// Create working order
function createOrder(ticket) {
return new Promise((res, rej) => {
// Constraints:
if (['AUD', 'USD', 'EUR', 'GBP', 'CHF', 'NZD', 'JPY', 'CAD'].indexOf(ticket.currencyCode) === -1) throw new Error('currencyCode has to be one of: AUD, USD, EUR, GBP, CHF, NZD, JPY, CAD]');
if (['BUY', 'SELL'].indexOf(ticket.direction) === -1) throw new Error('direction has to be BUY or SELL');
if (!ticket.epic) throw new Error('epic has to be defined');
if (!ticket.expiry) throw new Error('expiry has to be defined');
if (!ticket.size) throw new Error('size has to be defined');
if ([true, false].indexOf(ticket.forceOpen) === -1) throw new Error('forceOpen has to be true or false');
if (['LIMIT', 'STOP'].indexOf(ticket.type) === -1) throw new Error('type has to be LIMIT or STOP');
if ([true, false].indexOf(ticket.guaranteedStop) === -1) throw new Error('guaranteedStop has to be true or false');
if (ticket.limitDistance != null && ticket.forceOpen === false) throw new Error('If a limitDistance is set, then forceOpen must be true');
if (ticket.limitLevel != null && ticket.forceOpen === false) throw new Error('If a limitLevel is set, then forceOpen must be true');
if (ticket.stopDistance != null && ticket.forceOpen === false) throw new Error('If a stopDistance is set, then forceOpen must be true');
if (ticket.stopLevel != null && ticket.forceOpen === false) throw new Error('If a stopLevel is set, then forceOpen must be true');
if (['GOOD_TILL_CANCELLED', 'GOOD_TILL_DATE'].indexOf(ticket.timeInForce) === -1) throw new Error('timeInForce has to be GOOD_TILL_CANCELLED or GOOD_TILL_DATE');
if (ticket.stopDistance === null && ticket.stopLevel === null && ticket.guaranteedStop === true) throw new Error('If guaranteedStop equals true, then set either stopLevel or stopDistance');
if (ticket.level === null) throw new Error('level has to be defined');
if (ticket.limitLevel != null && ticket.limitDistance != null) throw new Error('Set only one of limitLevel or limitDistance');
if (ticket.stopLevel != null && ticket.stopDistance != null) throw new Error('Set only one of stopLevel or stopDistance');
post('/workingorders/otc', ticket, 2)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
return get('/confirms/' + r.body.dealReference);
}
})
.then(r => {
res(r.body);
})
.catch(e => {
rej(e);
});
});
}
// Delete existing working order
function deleteOrder(dealId) {
let response = {};
return new Promise((res, rej) => {
let close = {};
del('/workingorders/otc/' + dealId, close)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
response.workingorders = r.body;
return get('/confirms/' + r.body.dealReference);
}
})
.then(r => {
response.confirms = r.body;
res(response);
})
.catch(e => rej(e));
});
}
// Delete all existing working orders
function deleteAllOrders() {
return new Promise((res, rej) => {
let response = [];
let tickets = [];
let index = 0;
let close = {};
get('/workingorders')
.then(r => {
let temp = r.body.workingOrders;
if (temp.length === 0)(res('There is no order to close'));
for (let i = 0; i < temp.length; i++) {
tickets.push(temp[i].workingOrderData.dealId);
}
function _close(index) {
if (tickets[index]) {
del('/workingorders/otc/' + tickets[index], close)
.then(r => {
get('/confirms/' + r.body.dealReference)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
index++;
_close(index);
response.push(r.body);
}
})
.catch(e => {
rej(e);
});
})
.catch(e => {
rej(e);
});
} else {
res(response);
}
}
_close(index);
});
});
}
/////////////
// MARKETS //
/////////////
// Search a contract
function search(searchTerm) {
return new Promise((res, rej) => {
let extraHeaders = {
'x-security-token': process.env.IG_XST,
cst: process.env.IG_CST
};
get('/markets?searchTerm=' + searchTerm, false, extraHeaders)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
// Client sentiment (ig volume)
function igVolume(epics) {
return new Promise((res, rej) => {
if (epics.length > 50) throw new Error('Max number of epics is limited to 50');
let qstringEpics = '?epics=';
epics.map(epic => {
qstringEpics = qstringEpics + epic + '%2c';
});
qstringEpics = qstringEpics.slice(0, qstringEpics.length - 3);
get('/markets' + qstringEpics)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
let marketDetails = r.body.marketDetails;
let qstringMaketId = '?marketIds=';
for (var i = 0; i < marketDetails.length; i++) {
qstringMaketId = qstringMaketId + marketDetails[i].instrument.marketId + '%2c';
}
qstringMaketId = qstringMaketId.slice(0, qstringMaketId.length - 3);
return get('/clientsentiment' + qstringMaketId);
}
})
.then(r => {
res(r.body);
})
.catch(e => {
rej(e);
});
});
}
// Market node content
function marketNode(id) {
return new Promise((res, rej) => {
let url = typeof(id) === 'undefined' ? '/marketnavigation' : '/marketnavigation/' + id;
get(url)
.then(r => {
if (r.status !== 200) {
rej(r);
} else(res(r.body));
})
.catch(e => {
rej(e);
});
});
}
// Historical prices
function histPrc(epic, resolution, from, to) {
/**
* @param {string} epic
* @param {string} resolution
* Permitted values are: DAY, HOUR, HOUR_2, HOUR_3, HOUR_4, MINUTE, MINUTE_10, MINUTE_15, MINUTE_2, MINUTE_3,
* MINUTE_30, MINUTE_5, MONTH, SECOND, WEEK
* @param {from} string
* Permitted values are:
* * @param {to} string
* Permitted values are:
*/
return new Promise((res, rej) => {
get('/prices/' + epic + '?resolution=' + resolution + '&startdate=' + from + '&to=' + to, 3)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
// Epic details
function epicDetails(epics) {
/**
* @param {array} epics - Array of epics (max 50)
*/
if (epics.length > 50) throw new Error('Max number of epics is limited to 50');
return new Promise((res, rej) => {
let qstringEpics = '?epics=';
epics.map(epic => {
qstringEpics = qstringEpics + epic + '%2c';
});
qstringEpics = qstringEpics.slice(0, qstringEpics.length - 3);
get('/markets' + qstringEpics)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
///////////////
// WATCHLIST //
///////////////
// Watchlists summary and watchlist content
function watchlists(id) {
return new Promise((res, rej) => {
if (typeof(id) === 'undefined') {
get('/watchlists')
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body.watchlists);
}
})
.catch(e => {
rej(e);
});
} else {
get('/watchlists/' + id)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
}
});
}
// Create a new watchlist
function createWatchlist(name, epics) {
return new Promise((res, rej) => {
let payload = {
'epics': epics,
'name': name
};
post('/watchlists', payload)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
// Delete entire watchlist
function deleteWatchlist(id) {
return new Promise((res, rej) => {
let payload = {};
del('/watchlists/' + id, payload)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
// Insert single epic to watchlist
function addEpicWatchlist(epic, watchlistID) {
return new Promise((res, rej) => {
let payload = {
'epic': epic
};
put('/watchlists/' + watchlistID, payload)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
// Remove single epic to watchlist
function removeEpicWatchlist(epic, watchlistID) {
return new Promise((res, rej) => {
let payload = {};
del('/watchlists/' + watchlistID + '/' + epic, payload)
.then(r => {
if (r.status !== 200) {
rej(r);
} else {
res(r.body);
}
})
.catch(e => {
rej(e);
});
});
}
///////////////////