-
Notifications
You must be signed in to change notification settings - Fork 21
/
client.js
2406 lines (1833 loc) · 73.4 KB
/
client.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
import EventEmitter from 'events';
import assert from 'assert';
import util from 'util';
const debuglog = util.debuglog('ib-tws-api');
import ProtocolBytes from './protocol-bytes.js';
import IncomeFieldsetHandler from './income-fieldset-handler.js';
import IncomeMessageType from './const-income-message-type.js';
import OutcomeMessageType from './const-outcome-message-type.js';
import RateLimiter from './rate-limiter.js';
import ServerVersion from './const-server-version.js';
import {
request_mktData,
request_tickByTickData,
request_cancelTickByTickData
} from './requests/market-data.js';
import {
request_placeOrder
} from './requests/order.js';
/* Protocol's fieldset-level handing */
class Client {
/* connectionParameters: {
host,
port,
clientId,
timeoutMs
}
*/
constructor(connectionParameters = {}) {
this._connectionParameters = connectionParameters;
this._emitter = new EventEmitter();
this._emitter.on('error', (e) => {
// error handler to ignore it by default
});
this._connectionPromise = null;
this._connected = false;
// marketDataType is connection's mode of operation
// should be restored on reconnection if specified by reqMarketDataType
this._marketDataType = null;
}
/**
* Attaches event listener
*
* @param {string} eventName
* @param {function} listener
*/
on(eventName, listener) {
this._emitter.on(eventName, listener);
}
async connect(p) {
if (p != null) {
this._connectionParameters = p;
console.error('ib-tws-api: deprecated use of Client.connect - please pass connection parameters to constructor instead');
}
await this._maybeConnect();
}
async _maybeConnect() {
if (this._connected) {
return;
}
if (this._connectionPromise == null) {
this._connectionPromise = this._connect();
}
try {
await this._connectionPromise;
this._connected = true;
} finally {
this._connectionPromise = null;
}
}
async _connect() {
if (this._protocolBytes) {
this._protocolBytes.removeAllListeners(); // allow gc to remove old
}
this._clientId = this._connectionParameters.clientId || 1;
this._serverVersion = 0;
// build protocol bytes object
this._protocolBytes = new ProtocolBytes();
const timeoutMs = this._connectionParameters.timeoutMs || 30000;
this._rateLimiter = new RateLimiter((data) => {
return this._protocolBytes.sendFieldset(data);
}, 45, 1000, timeoutMs);
this._protocolBytes.on('message_fieldset', (o) => {
this._onMessageFieldset(o);
});
this._protocolBytes.on('close', (e) => {
this._connected = false;
this._emitter.emit('close');
});
this._protocolBytes.on('error', (e) => {
this._emitter.emit('error', e);
});
await this._protocolBytes.connect({
host: this._connectionParameters.host,
port: this._connectionParameters.port,
clientId: this._clientId
});
this._protocolBytes.sendHandshake();
// attach messages handler
this._incomeHandler = new IncomeFieldsetHandler({
timeoutMs,
eventEmitter: this._emitter
});
let serverVersion = await this._incomeHandler.awaitMessageType(
IncomeMessageType._SERVER_VERSION);
this._serverVersion = serverVersion;
this._incomeHandler.setServerVersion(serverVersion);
this._connectSendStartApi();
let [nextValidId, accounts] = await Promise.all([
this._incomeHandler.awaitMessageType(IncomeMessageType.NEXT_VALID_ID),
this._incomeHandler.awaitMessageType(IncomeMessageType.MANAGED_ACCTS)
]);
this._nextValidId = nextValidId;
debuglog('connected');
debuglog({nextValidId: nextValidId, accounts: accounts});
if (this._marketDataType != null) {
debuglog('set marketDataType to ' + this._marketDataType);
this._protocolBytes.sendFieldset([
OutcomeMessageType.REQ_MARKET_DATA_TYPE,
1 /*VERSION */,
this._marketDataType
]);
}
}
_connectSendStartApi() {
const START_API = 71;
const VERSION = 2;
const optCapab = '';
this._protocolBytes.sendFieldset(
[START_API, VERSION, this._clientId, optCapab]);
}
async _sendFieldsetRateLimited(fields) {
await this._maybeConnect();
this._rateLimiter.run(fields);
}
async _sendFieldsetExpirable(fields) {
await this._maybeConnect();
this._rateLimiter.runExpirable(fields);
}
_onMessageFieldset(fields) {
if (!this._serverVersion) {
this._incomeHandler.processMessageFieldsetBeforeServerVersion(fields);
} else {
this._incomeHandler.processMessageFieldset(fields);
}
}
async _allocateRequestId() {
await this._maybeConnect();
return ++this._nextValidId;
}
async getCurrentTime() {
/* Asks the current system time on the server side. */
await this._sendFieldsetExpirable([
OutcomeMessageType.REQ_CURRENT_TIME,
1 /* VERSION */
]);
return await this._incomeHandler.awaitMessageType(
IncomeMessageType.CURRENT_TIME);
}
/*########################################################################
################## Market Data
##########################################################################*/
/**
* Starts to stream market data
* see reqMktData for parameters
*/
async streamMarketData(p) {
assert(!p.requestId);
assert(p.snapshot == null);
assert(p.regulatorySnapshot == null);
p.requestId = await this._allocateRequestId();
p.genericTickList = p.genericTickList || '';
p.snapshot = false;
p.regulatorySnapshot = false;
await this._sendFieldsetRateLimited(request_mktData(this._serverVersion, p));
return this._incomeHandler.requestIdEmitter(p.requestId, () => {
this._sendFieldsetRateLimited([
OutcomeMessageType.CANCEL_MKT_DATA,
2 /* VERSION */,
p.requestId
]);
});
}
/**
* Returns market data snapshot
* see reqMktData for parameters
*/
async getMarketDataSnapshot(p) {
assert(!p.requestId);
assert(p.snapshot == null);
p.requestId = await this._allocateRequestId();
p.genericTickList = p.genericTickList || '';
p.snapshot = true;
p.regulatorySnapshot = p.regulatorySnapshot || false;
await this._sendFieldsetExpirable(request_mktData(this._serverVersion, p));
return await this._incomeHandler.awaitRequestId(p.requestId);
}
/**
* The API can receive frozen market data from Trader Workstation.
* Frozen market data is the last data recorded in our system.
* During normal trading hours, the API receives real-time market data. If
* you use this function, you are telling TWS to automatically switch to
* frozen market data after the close. Then, before the opening of the next
* trading day, market data will automatically switch back to real-time
* market data.
* @param {int} marketDataType: - 1 for real-time streaming market data or
* 2 for frozen market data
*/
async reqMarketDataType(marketDataType) {
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_REQ_MARKET_DATA_TYPE) {
throw new Error("It does not support market data type requests.");
}
// API doesnt send any response to that packet.
// Only data available is marketDataType tick sent to each
// getMarketDataSnapshot/streamMarketData
await this._sendFieldsetRateLimited([
OutcomeMessageType.REQ_MARKET_DATA_TYPE,
1 /*VERSION */,
marketDataType
]);
// it's not connection-level mode to restore on reconnection
this._marketDataType = marketDataType;
}
async reqSmartComponents(/*self, requestId: int, bboExchange: str*/) {
throw new Error('not implemented yet');
/*
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_REQ_SMART_COMPONENTS) {
throw new Error( " It does not support smart components request.")
return
msg = flds.push(OutcomeMessageType.REQ_SMART_COMPONENTS) \
+ flds.push(requestId) \
+ flds.push(bboExchange)
this._sendFieldsetRateLimited(msg)
*/
}
async reqMarketRule(/*self, marketRuleId: int*/) {
throw new Error('not implemented yet');
/*
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_MARKET_RULES) {
throw new Error( " It does not support market rule requests.")
return
msg = flds.push(OutcomeMessageType.REQ_MARKET_RULE) \
+ flds.push(marketRuleId)
this._sendFieldsetRateLimited(msg)
*/
}
async streamTickByTickData(p) {
/*
contract: Contract,
tickType: str,
numberOfTicks: int,
ignoreSize: bool
*/
assert(!p.requestId);
p.requestId = await this._allocateRequestId();
await this._sendFieldsetRateLimited(request_tickByTickData(this._serverVersion, p));
return this._incomeHandler.requestIdEmitter(p.requestId, () => {
this._sendFieldsetRateLimited(
request_cancelTickByTickData(this._serverVersion, p.requestId));
});
}
/*
##########################################################################
################## Options
##########################################################################
*/
async calculateImpliedVolatility(/*self, requestId:TickerId, contract:Contract,
optionPrice:float, underPrice:float,
implVolOptions:TagValueList*/) {
throw new Error('not implemented yet');
/*
"""calculate volatility for a supplied
option price and underlying price. Result will be delivered
via EWrapper.tickOptionComputation()
requestId:TickerId - The request id.
contract:Contract - Describes the contract.
optionPrice:double - The price of the option.
underPrice:double - Price of the underlying."""
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT) {
throw new Error(
" It does not support calculateImpliedVolatility req.")
return
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_TRADING_CLASS) {
if contract.tradingClass:
throw new Error(
" It does not support tradingClass parameter in calculateImpliedVolatility.")
return
const VERSION = 3;
// send req mkt data msg
let flds = []
flds += [flds.push(OutcomeMessageType.REQ_CALC_IMPLIED_VOLAT),
flds.push(VERSION),
flds.push(requestId),
// send contract fields
flds.push(contract.conId),
flds.push(contract.symbol),
flds.push(contract.secType),
flds.push(contract.lastTradeDateOrContractMonth),
flds.push(contract.strike),
flds.push(contract.right),
flds.push(contract.multiplier),
flds.push(contract.exchange),
flds.push(contract.primaryExchange),
flds.push(contract.currency),
flds.push(contract.localSymbol)]
if (this._serverVersion >= ServerVersion.MIN_SERVER_VER_TRADING_CLASS) {
flds += [flds.push(contract.tradingClass),]
flds += [ flds.push(optionPrice),
flds.push(underPrice)]
if (this._serverVersion >= ServerVersion.MIN_SERVER_VER_LINKING) {
implVolOptStr = ""
tagValuesCount = len(implVolOptions) if implVolOptions else 0
if implVolOptions:
for implVolOpt in implVolOptions:
implVolOptStr += str(implVolOpt)
flds += [flds.push(tagValuesCount),
flds.push(implVolOptStr)]
msg = "".join(flds)
this._sendFieldsetRateLimited(msg)
*/
}
async cancelCalculateImpliedVolatility(/*self, requestId:TickerId*/) {
throw new Error('not implemented yet');
/*
"""cancel a request to calculate
volatility for a supplied option price and underlying price.
requestId:TickerId - The request ID. """
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT) {
throw new Error(
" It does not support calculateImpliedVolatility req.")
return
const VERSION = 1;
msg = flds.push(OutcomeMessageType.CANCEL_CALC_IMPLIED_VOLAT) \
+ flds.push(VERSION) \
+ flds.push(requestId)
this._sendFieldsetRateLimited(msg)
*/
}
async calculateOptionPrice(/*self, requestId:TickerId, contract:Contract,
volatility:float, underPrice:float,
optPrcOptions:TagValueList*/) {
throw new Error('not implemented yet');
/*
"""calculate option price and greek values
for a supplied volatility and underlying price.
requestId:TickerId - The ticker ID.
contract:Contract - Describes the contract.
volatility:double - The volatility.
underPrice:double - Price of the underlying."""
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT) {
throw new Error(
" It does not support calculateImpliedVolatility req.")
return
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_TRADING_CLASS) {
if contract.tradingClass:
throw new Error(
" It does not support tradingClass parameter in calculateImpliedVolatility.")
return
const VERSION = 3;
// send req mkt data msg
let flds = []
flds += [flds.push(OutcomeMessageType.REQ_CALC_OPTION_PRICE),
flds.push(VERSION),
flds.push(requestId),
// send contract fields
flds.push(contract.conId),
flds.push(contract.symbol),
flds.push(contract.secType),
flds.push(contract.lastTradeDateOrContractMonth),
flds.push(contract.strike),
flds.push(contract.right),
flds.push(contract.multiplier),
flds.push(contract.exchange),
flds.push(contract.primaryExchange),
flds.push(contract.currency),
flds.push(contract.localSymbol)]
if (this._serverVersion >= ServerVersion.MIN_SERVER_VER_TRADING_CLASS) {
flds += [flds.push(contract.tradingClass),]
flds += [ flds.push(volatility),
flds.push(underPrice)]
if (this._serverVersion >= ServerVersion.MIN_SERVER_VER_LINKING) {
optPrcOptStr = ""
tagValuesCount = len(optPrcOptions) if optPrcOptions else 0
if optPrcOptions:
for implVolOpt in optPrcOptions:
optPrcOptStr += str(implVolOpt)
flds += [flds.push(tagValuesCount),
flds.push(optPrcOptStr)]
msg = "".join(flds)
this._sendFieldsetRateLimited(msg)
*/
}
async cancelCalculateOptionPrice(/*self, requestId:TickerId*/) {
throw new Error('not implemented yet');
/*
"""cancel a request to calculate the option
price and greek values for a supplied volatility and underlying price.
requestId:TickerId - The request ID. """
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_REQ_CALC_IMPLIED_VOLAT) {
throw new Error(
" It does not support calculateImpliedVolatility req.")
return
const VERSION = 1;
msg = flds.push(OutcomeMessageType.CANCEL_CALC_OPTION_PRICE) \
+ flds.push(VERSION) \
+ flds.push(requestId)
this._sendFieldsetRateLimited(msg)
*/
}
async exerciseOptions(/*self, requestId:TickerId, contract:Contract,
exerciseAction:int, exerciseQuantity:int,
account:str, override:int*/) {
throw new Error('not implemented yet');
/*
"""requestId:TickerId - The ticker id. multipleust be a unique value.
contract:Contract - This structure contains a description of the
contract to be exercised
exerciseAction:int - Specifies whether you want the option to lapse
or be exercised.
Values are 1 = exercise, 2 = lapse.
exerciseQuantity:int - The quantity you want to exercise.
account:str - destination account
override:int - Specifies whether your setting will override the system's
natural action. For example, if your action is "exercise" and the
option is not in-the-money, by natural action the option would not
exercise. If you have override set to "yes" the natural action would
be overridden and the out-of-the money option would be exercised.
Values are: 0 = no, 1 = yes."""
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_TRADING_CLASS) {
if contract.tradingClass:
throw new Error(
" It does not support conId, multiplier, tradingClass parameter in exerciseOptions.")
return
const VERSION = 2;
// send req mkt data msg
let flds = []
flds += [flds.push(OutcomeMessageType.EXERCISE_OPTIONS),
flds.push(VERSION),
flds.push(requestId)]
// send contract fields
if (this._serverVersion >= ServerVersion.MIN_SERVER_VER_TRADING_CLASS) {
flds += [flds.push(contract.conId),]
flds += [flds.push(contract.symbol),
flds.push(contract.secType),
flds.push(contract.lastTradeDateOrContractMonth),
flds.push(contract.strike),
flds.push(contract.right),
flds.push(contract.multiplier),
flds.push(contract.exchange),
flds.push(contract.currency),
flds.push(contract.localSymbol)]
if (this._serverVersion >= ServerVersion.MIN_SERVER_VER_TRADING_CLASS) {
flds += [flds.push(contract.tradingClass),]
flds += [flds.push(exerciseAction),
flds.push(exerciseQuantity),
flds.push(account),
flds.push(override)]
msg = "".join(flds)
this._sendFieldsetRateLimited(msg)
*/
}
/*
#########################################################################
################## Orders
########################################################################
*/
async placeOrder(p) {
/*
place an order. The order status will
be returned by the orderStatus event.
contract:Contract - This structure contains a description of the
contract which is being traded.
order:Order - This structure contains the details of tradedhe order.
Note: Each client MUST connect with a unique clientId.*/
assert(!p.orderId);
p.orderId = await this._allocateRequestId();
p.order.clientId = this._clientId;
await this._sendFieldsetRateLimited(
request_placeOrder(this._serverVersion, p));
return p.orderId;
}
async cancelOrder(orderId) {
/* cancel an order. */
await this._sendFieldsetExpirable([
OutcomeMessageType.CANCEL_ORDER,
1 /* VERSION */,
orderId
]);
return await this._incomeHandler.awaitRequestIdErrorCode(orderId, 202);
}
async getOpenOrders() {
/* request the open orders that were placed from this client.
Note: The client with a clientId of 0 will also receive the TWS-owned
open orders. These orders will be associated with the client and a new
orderId will be generated. This association will persist over multiple
API and TWS sessions. */
await this._sendFieldsetExpirable([
OutcomeMessageType.REQ_OPEN_ORDERS,
1 /* VERSION */
]);
return await this._incomeHandler.awaitMessageType(
IncomeMessageType.OPEN_ORDER_END);
}
async reqAutoOpenOrders(bAutoBind) {
/* request that newly created TWS orders
be implicitly associated with the client. When a new TWS order is
created, the order will be associated with the client.
Note: This request can only be made from a client with clientId of 0.
bAutoBind: If set to TRUE, newly created TWS orders will be implicitly
associated with the client. If set to FALSE, no association will be
made.*/
await this._sendFieldsetRateLimited([
OutcomeMessageType.REQ_AUTO_OPEN_ORDERS,
1 /* VERSION */,
bAutoBind
]);
}
async getAllOpenOrders() {
/* request the open orders placed from all
clients and also from TWS.
Note: No association is made between the returned orders and the
requesting client. */
await this._sendFieldsetExpirable([
OutcomeMessageType.REQ_ALL_OPEN_ORDERS,
1 /* VERSION */
]);
return await this._incomeHandler.awaitMessageType(
IncomeMessageType.OPEN_ORDER_END);
}
async reqGlobalCancel() {
/* Use this function to cancel all open orders globally. It
cancels both API and TWS open orders.
If the order was created in TWS, it also gets canceled. If the order
was initiated in the API, it also gets canceled. */
await this._sendFieldsetRateLimited([
OutcomeMessageType.REQ_GLOBAL_CANCEL,
1 /* VERSION */
]);
}
/*
#########################################################################
################## Account and Portfolio
########################################################################
*/
async reqAccountUpdates(p) {
/* start getting account values, portfolio, and last update time information
subscribe:bool - If set to TRUE, the client will start receiving account
and Portfoliolio updates. If set to FALSE, the client will stop
receiving this information.
accountCode:str -The account code for which to receive account and
portfolio updates.*/
const VERSION = 2;
await this._sendFieldsetRateLimited([
OutcomeMessageType.REQ_ACCT_DATA,
VERSION,
p.subscribe, // TRUE = subscribe, FALSE = unsubscribe.
p.accountCode // srv v9 and above, the account code. This will only be used for FA clients
]);
}
async reqAccountSummary(/*self, requestId:int, groupName:str, tags:str*/) {
throw new Error('not implemented yet');
/*
"""Call this method to request and keep up to date the data that appears
on the TWS Account Window Summary tab. The data is returned by
accountSummary().
Note: This request is designed for an FA managed account but can be
used for any multi-account structure.
requestId:int - The ID of the data request. Ensures that responses are matched
to requests If several requests are in process.
groupName:str - Set to All to returnrn account summary data for all
accounts, or set to a specific Advisor Account Group name that has
already been created in TWS Global Configuration.
tags:str - A comma-separated list of account tags. Available tags are:
accountountType
NetLiquidation,
TotalCashValue - Total cash including futures pnl
SettledCash - For cash accounts, this is the same as
TotalCashValue
AccruedCash - Net accrued interest
BuyingPower - The maximum amount of marginable US stocks the
account can buy
EquityWithLoanValue - Cash + stocks + bonds + mutual funds
PreviousDayEquityWithLoanValue,
GrossPositionValue - The sum of the absolute value of all stock
and equity option positions
RegTEquity,
RegTMargin,
SMA - Special Memorandum Account
InitMarginReq,
MaintMarginReq,
AvailableFunds,
ExcessLiquidity,
Cushion - Excess liquidity as a percentage of net liquidation value
FullInitMarginReq,
FullMaintMarginReq,
FullAvailableFunds,
FullExcessLiquidity,
LookAheadNextChange - Time when look-ahead values take effect
LookAheadInitMarginReq,
LookAheadMaintMarginReq,
LookAheadAvailableFunds,
LookAheadExcessLiquidity,
HighestSeverity - A measure of how close the account is to liquidation
DayTradesRemaining - The Number of Open/Close trades a user
could put on before Pattern Day Trading is detected. A value of "-1"
means that the user can put on unlimited day trades.
Leverage - GrossPositionValue / NetLiquidation
$LEDGER - Single flag to relay all cash balance tags*, only in base
currency.
$LEDGER:CURRENCY - Single flag to relay all cash balance tags*, only in
the specified currency.
$LEDGER:ALL - Single flag to relay all cash balance tags* in all
currencies."""
const VERSION = 1;
msg = flds.push(OutcomeMessageType.REQ_ACCOUNT_SUMMARY) \
+ flds.push(VERSION) \
+ flds.push(requestId) \
+ flds.push(groupName) \
+ flds.push(tags)
this._sendFieldsetRateLimited(msg)
*/
}
async cancelAccountSummary(/*self, requestId:int*/) {
throw new Error('not implemented yet');
/*
"""Cancels the request for Account Window Summary tab data.
requestId:int - The ID of the data request being canceled."""
const VERSION = 1;
msg = flds.push(OutcomeMessageType.CANCEL_ACCOUNT_SUMMARY) \
+ flds.push(VERSION) \
+ flds.push(requestId)
this._sendFieldsetRateLimited(msg)
*/
}
async getPositions() {
/* Returns real-time position data for all accounts. */
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_POSITIONS) {
throw new Error("It does not support positions request.");
}
const VERSION = 1;
await this._sendFieldsetExpirable([OutcomeMessageType.REQ_POSITIONS, VERSION]);
return await this._incomeHandler.awaitMessageType(IncomeMessageType.POSITION_END);
}
async cancelPositions() {
/* Cancels real-time position updates. */
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_POSITIONS) {
throw new Error("It does not support positions request.");
}
const VERSION = 1;
await this._sendFieldsetRateLimited([OutcomeMessageType.CANCEL_POSITIONS, VERSION]);
}
async reqPositionsMulti(/*self, requestId:int, account:str, modelCode:str*/) {
throw new Error('not implemented yet');
/*
"""Requests positions for account and/or model.
Results are delivered via EWrapper.positionMulti() and
EWrapper.positionMultiEnd() """
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_MODELS_SUPPORT) {
throw new Error( " It does not support positions multi request.")
return
const VERSION = 1;
msg = flds.push(OutcomeMessageType.REQ_POSITIONS_MULTI) \
+ flds.push(VERSION) \
+ flds.push(requestId) \
+ flds.push(account) \
+ flds.push(modelCode)
this._sendFieldsetRateLimited(msg)
*/
}
async cancelPositionsMulti(/*self, requestId:int*/) {
throw new Error('not implemented yet');
/*
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_MODELS_SUPPORT) {
throw new Error( " It does not support cancel positions multi request.")
return
const VERSION = 1;
msg = flds.push(OutcomeMessageType.CANCEL_POSITIONS_MULTI) \
+ flds.push(VERSION) \
+ flds.push(requestId) \
this._sendFieldsetRateLimited(msg)
*/
}
async reqAccountUpdatesMulti(/*self, requestId: int, account:str, modelCode:str,
ledgerAndNLV:bool*/) {
throw new Error('not implemented yet');
/*
"""Requests account updates for account and/or model."""
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_MODELS_SUPPORT) {
throw new Error( " It does not support account updates multi request.")
return
const VERSION = 1;
msg = flds.push(OutcomeMessageType.REQ_ACCOUNT_UPDATES_MULTI) \
+ flds.push(VERSION) \
+ flds.push(requestId) \
+ flds.push(account) \
+ flds.push(modelCode) \
+ flds.push(ledgerAndNLV)
this._sendFieldsetRateLimited(msg)
*/
}
async cancelAccountUpdatesMulti(/*self, requestId:int*/) {
throw new Error('not implemented yet');
/*
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_MODELS_SUPPORT) {
throw new Error( " It does not support cancel account updates multi request.")
return
const VERSION = 1;
msg = flds.push(OutcomeMessageType.CANCEL_ACCOUNT_UPDATES_MULTI) \
+ flds.push(VERSION) \
+ flds.push(requestId) \
this._sendFieldsetRateLimited(msg)
*/
}
/*
#########################################################################
################## Daily PnL
#########################################################################
*/
async reqPnL(/*self, requestId: int, account: str, modelCode: str*/) {
throw new Error('not implemented yet');
/*
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_PNL) {
throw new Error( " It does not support PnL request.")
return
msg = flds.push(OutcomeMessageType.REQ_PNL) \
+ flds.push(requestId) \
+ flds.push(account) \
+ flds.push(modelCode)
this._sendFieldsetRateLimited(msg)
*/
}
async cancelPnL(/*self, requestId: int*/) {
throw new Error('not implemented yet');
/*
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_PNL) {
throw new Error( " It does not support PnL request.")
return
msg = flds.push(OutcomeMessageType.CANCEL_PNL) \
+ flds.push(requestId)
this._sendFieldsetRateLimited(msg)
*/
}
async reqPnLSingle(/*self, requestId: int, account: str, modelCode: str, conid: int*/) {
throw new Error('not implemented yet');
/*
if (this._serverVersion < ServerVersion.MIN_SERVER_VER_PNL) {
throw new Error( " It does not support PnL request.")
return
msg = flds.push(OutcomeMessageType.REQ_PNL_SINGLE) \
+ flds.push(requestId) \
+ flds.push(account) \
+ flds.push(modelCode) \
+ flds.push(conid)