-
-
Notifications
You must be signed in to change notification settings - Fork 72
/
ib.py
2566 lines (2175 loc) · 88.3 KB
/
ib.py
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
"""High-level interface to Interactive Brokers."""
import asyncio
import copy
import datetime
import logging
import time
from typing import Any, Awaitable, Dict, Iterator, List, Optional, Union
from eventkit import Event
from enum import Flag, auto
import ib_async.util as util
from ib_async.client import Client
from ib_async.contract import Contract, ContractDescription, ContractDetails
from ib_async.objects import (
AccountValue,
BarDataList,
DepthMktDataDescription,
Execution,
ExecutionFilter,
Fill,
HistogramData,
HistoricalNews,
HistoricalSchedule,
NewsArticle,
NewsBulletin,
NewsProvider,
NewsTick,
OptionChain,
OptionComputation,
PnL,
PnLSingle,
PortfolioItem,
Position,
PriceIncrement,
RealTimeBarList,
ScanDataList,
ScannerSubscription,
SmartComponent,
TagValue,
TradeLogEntry,
WshEventData,
)
from ib_async.order import (
BracketOrder,
LimitOrder,
Order,
OrderState,
OrderStatus,
StopOrder,
Trade,
)
from ib_async.ticker import Ticker
from ib_async.wrapper import Wrapper
class StartupFetch(Flag):
POSITIONS = auto()
ORDERS_OPEN = auto()
ORDERS_COMPLETE = auto()
ACCOUNT_UPDATES = auto()
SUB_ACCOUNT_UPDATES = auto()
EXECUTIONS = auto()
StartupFetchNONE = StartupFetch(0)
StartupFetchALL = (
StartupFetch.POSITIONS
| StartupFetch.ORDERS_OPEN
| StartupFetch.ORDERS_COMPLETE
| StartupFetch.ACCOUNT_UPDATES
| StartupFetch.SUB_ACCOUNT_UPDATES
| StartupFetch.EXECUTIONS
)
class IB:
"""
Provides both a blocking and an asynchronous interface
to the IB API, using asyncio networking and event loop.
The IB class offers direct access to the current state, such as
orders, executions, positions, tickers etc. This state is
automatically kept in sync with the TWS/IBG application.
This class has most request methods of EClient, with the
same names and parameters (except for the reqId parameter
which is not needed anymore).
Request methods that return a result come in two versions:
* Blocking: Will block until complete and return the result.
The current state will be kept updated while the request is ongoing;
* Asynchronous: All methods that have the "Async" postfix.
Implemented as coroutines or methods that return a Future and
intended for advanced users.
**The One Rule:**
While some of the request methods are blocking from the perspective
of the user, the framework will still keep spinning in the background
and handle all messages received from TWS/IBG. It is important to
not block the framework from doing its work. If, for example,
the user code spends much time in a calculation, or uses time.sleep()
with a long delay, the framework will stop spinning, messages
accumulate and things may go awry.
The one rule when working with the IB class is therefore that
**user code may not block for too long**.
To be clear, the IB request methods are okay to use and do not
count towards the user operation time, no matter how long the
request takes to finish.
So what is "too long"? That depends on the situation. If, for example,
the timestamp of tick data is to remain accurate within a millisecond,
then the user code must not spend longer than a millisecond. If, on
the other extreme, there is very little incoming data and there
is no desire for accurate timestamps, then the user code can block
for hours.
If a user operation takes a long time then it can be farmed out
to a different process.
Alternatively the operation can be made such that it periodically
calls IB.sleep(0); This will let the framework handle any pending
work and return when finished. The operation should be aware
that the current state may have been updated during the sleep(0) call.
For introducing a delay, never use time.sleep() but use
:meth:`.sleep` instead.
Parameters:
RequestTimeout (float): Timeout (in seconds) to wait for a
blocking request to finish before raising ``asyncio.TimeoutError``.
The default value of 0 will wait indefinitely.
Note: This timeout is not used for the ``*Async`` methods.
RaiseRequestErrors (bool):
Specifies the behaviour when certain API requests fail:
* :data:`False`: Silently return an empty result;
* :data:`True`: Raise a :class:`.RequestError`.
MaxSyncedSubAccounts (int): Do not use sub-account updates
if the number of sub-accounts exceeds this number (50 by default).
TimezoneTWS (str): Specifies what timezone TWS (or gateway)
is using. The default is to assume local system timezone.
Events:
* ``connectedEvent`` ():
Is emitted after connecting and synchronzing with TWS/gateway.
* ``disconnectedEvent`` ():
Is emitted after disconnecting from TWS/gateway.
* ``updateEvent`` ():
Is emitted after a network packet has been handled.
* ``pendingTickersEvent`` (tickers: Set[:class:`.Ticker`]):
Emits the set of tickers that have been updated during the last
update and for which there are new ticks, tickByTicks or domTicks.
* ``barUpdateEvent`` (bars: :class:`.BarDataList`,
hasNewBar: bool): Emits the bar list that has been updated in
real time. If a new bar has been added then hasNewBar is True,
when the last bar has changed it is False.
* ``newOrderEvent`` (trade: :class:`.Trade`):
Emits a newly placed trade.
* ``orderModifyEvent`` (trade: :class:`.Trade`):
Emits when order is modified.
* ``cancelOrderEvent`` (trade: :class:`.Trade`):
Emits a trade directly after requesting for it to be cancelled.
* ``openOrderEvent`` (trade: :class:`.Trade`):
Emits the trade with open order.
* ``orderStatusEvent`` (trade: :class:`.Trade`):
Emits the changed order status of the ongoing trade.
* ``execDetailsEvent`` (trade: :class:`.Trade`, fill: :class:`.Fill`):
Emits the fill together with the ongoing trade it belongs to.
* ``commissionReportEvent`` (trade: :class:`.Trade`,
fill: :class:`.Fill`, report: :class:`.CommissionReport`):
The commission report is emitted after the fill that it belongs to.
* ``updatePortfolioEvent`` (item: :class:`.PortfolioItem`):
A portfolio item has changed.
* ``positionEvent`` (position: :class:`.Position`):
A position has changed.
* ``accountValueEvent`` (value: :class:`.AccountValue`):
An account value has changed.
* ``accountSummaryEvent`` (value: :class:`.AccountValue`):
An account value has changed.
* ``pnlEvent`` (entry: :class:`.PnL`):
A profit- and loss entry is updated.
* ``pnlSingleEvent`` (entry: :class:`.PnLSingle`):
A profit- and loss entry for a single position is updated.
* ``tickNewsEvent`` (news: :class:`.NewsTick`):
Emit a new news headline.
* ``newsBulletinEvent`` (bulletin: :class:`.NewsBulletin`):
Emit a new news bulletin.
* ``scannerDataEvent`` (data: :class:`.ScanDataList`):
Emit data from a scanner subscription.
* ``wshMetaEvent`` (dataJson: str):
Emit WSH metadata.
* ``wshEvent`` (dataJson: str):
Emit WSH event data (such as earnings dates, dividend dates,
options expiration dates, splits, spinoffs and conferences).
* ``errorEvent`` (reqId: int, errorCode: int, errorString: str,
contract: :class:`.Contract`):
Emits the reqId/orderId and TWS error code and string (see
https://interactivebrokers.github.io/tws-api/message_codes.html)
together with the contract the error applies to (or None if no
contract applies).
* ``timeoutEvent`` (idlePeriod: float):
Is emitted if no data is received for longer than the timeout period
specified with :meth:`.setTimeout`. The value emitted is the period
in seconds since the last update.
Note that it is not advisable to place new requests inside an event
handler as it may lead to too much recursion.
"""
events = (
"connectedEvent",
"disconnectedEvent",
"updateEvent",
"pendingTickersEvent",
"barUpdateEvent",
"newOrderEvent",
"orderModifyEvent",
"cancelOrderEvent",
"openOrderEvent",
"orderStatusEvent",
"execDetailsEvent",
"commissionReportEvent",
"updatePortfolioEvent",
"positionEvent",
"accountValueEvent",
"accountSummaryEvent",
"pnlEvent",
"pnlSingleEvent",
"scannerDataEvent",
"tickNewsEvent",
"newsBulletinEvent",
"wshMetaEvent",
"wshEvent",
"errorEvent",
"timeoutEvent",
)
RequestTimeout: float = 0
RaiseRequestErrors: bool = False
MaxSyncedSubAccounts: int = 50
TimezoneTWS: str = ""
def __init__(self):
self._createEvents()
self.wrapper = Wrapper(self)
self.client = Client(self.wrapper)
self.errorEvent += self._onError
self.client.apiEnd += self.disconnectedEvent
self._logger = logging.getLogger("ib_async.ib")
def _createEvents(self):
self.connectedEvent = Event("connectedEvent")
self.disconnectedEvent = Event("disconnectedEvent")
self.updateEvent = Event("updateEvent")
self.pendingTickersEvent = Event("pendingTickersEvent")
self.barUpdateEvent = Event("barUpdateEvent")
self.newOrderEvent = Event("newOrderEvent")
self.orderModifyEvent = Event("orderModifyEvent")
self.cancelOrderEvent = Event("cancelOrderEvent")
self.openOrderEvent = Event("openOrderEvent")
self.orderStatusEvent = Event("orderStatusEvent")
self.execDetailsEvent = Event("execDetailsEvent")
self.commissionReportEvent = Event("commissionReportEvent")
self.updatePortfolioEvent = Event("updatePortfolioEvent")
self.positionEvent = Event("positionEvent")
self.accountValueEvent = Event("accountValueEvent")
self.accountSummaryEvent = Event("accountSummaryEvent")
self.pnlEvent = Event("pnlEvent")
self.pnlSingleEvent = Event("pnlSingleEvent")
self.scannerDataEvent = Event("scannerDataEvent")
self.tickNewsEvent = Event("tickNewsEvent")
self.newsBulletinEvent = Event("newsBulletinEvent")
self.wshMetaEvent = Event("wshMetaEvent")
self.wshEvent = Event("wshEvent")
self.errorEvent = Event("errorEvent")
self.timeoutEvent = Event("timeoutEvent")
def __del__(self):
self.disconnect()
def __enter__(self):
return self
def __exit__(self, *_exc):
self.disconnect()
def __repr__(self):
conn = (
f"connected to {self.client.host}:"
f"{self.client.port} clientId={self.client.clientId}"
if self.client.isConnected()
else "not connected"
)
return f"<{self.__class__.__qualname__} {conn}>"
def connect(
self,
host: str = "127.0.0.1",
port: int = 7497,
clientId: int = 1,
timeout: float = 4,
readonly: bool = False,
account: str = "",
raiseSyncErrors: bool = False,
fetchFields: StartupFetch = StartupFetchALL,
):
"""
Connect to a running TWS or IB gateway application.
After the connection is made the client is fully synchronized
and ready to serve requests.
This method is blocking.
Args:
host: Host name or IP address.
port: Port number.
clientId: ID number to use for this client; must be unique per
connection. Setting clientId=0 will automatically merge manual
TWS trading with this client.
timeout: If establishing the connection takes longer than
``timeout`` seconds then the ``asyncio.TimeoutError`` exception
is raised. Set to 0 to disable timeout.
readonly: Set to ``True`` when API is in read-only mode.
account: Main account to receive updates for.
raiseSyncErrors: When ``True`` this will cause an initial
sync request error to raise a `ConnectionError``.
When ``False`` the error will only be logged at error level.
fetchFields: By default, all account data is loaded and cached
when a new connection is made. You can optionally disable all
or some of the account attribute fetching during a connection
using the StartupFetch field flags. See ``StartupFetch`` in ``ib.py``
for member details. There is also StartupFetchNONE and StartupFetchALL
as shorthand. Individual flag field members can be added or removed
to the ``fetchFields`` parameter as needed.
"""
return self._run(
self.connectAsync(
host,
port,
clientId,
timeout,
readonly,
account,
raiseSyncErrors,
fetchFields,
)
)
def disconnect(self):
"""
Disconnect from a TWS or IB gateway application.
This will clear all session state.
"""
if not self.client.isConnected():
return
stats = self.client.connectionStats()
self._logger.info(
f"Disconnecting from {self.client.host}:{self.client.port}, "
f"{util.formatSI(stats.numBytesSent)}B sent "
f"in {stats.numMsgSent} messages, "
f"{util.formatSI(stats.numBytesRecv)}B received "
f"in {stats.numMsgRecv} messages, "
f"session time {util.formatSI(stats.duration)}s."
)
self.client.disconnect()
self.disconnectedEvent.emit()
def isConnected(self) -> bool:
"""Is there an API connection to TWS or IB gateway?"""
return self.client.isReady()
def _onError(self, reqId, errorCode, errorString, contract):
if errorCode == 1102:
# "Connectivity between IB and Trader Workstation has been
# restored": Resubscribe to account summary.
asyncio.ensure_future(self.reqAccountSummaryAsync())
run = staticmethod(util.run)
schedule = staticmethod(util.schedule)
sleep = staticmethod(util.sleep)
timeRange = staticmethod(util.timeRange)
timeRangeAsync = staticmethod(util.timeRangeAsync)
waitUntil = staticmethod(util.waitUntil)
def _run(self, *awaitables: Awaitable):
return util.run(*awaitables, timeout=self.RequestTimeout)
def waitOnUpdate(self, timeout: float = 0) -> bool:
"""
Wait on any new update to arrive from the network.
Args:
timeout: Maximum time in seconds to wait.
If 0 then no timeout is used.
.. note::
A loop with ``waitOnUpdate`` should not be used to harvest
tick data from tickers, since some ticks can go missing.
This happens when multiple updates occur almost simultaneously;
The ticks from the first update are then cleared.
Use events instead to prevent this.
Returns:
``True`` if not timed-out, ``False`` otherwise.
"""
if timeout:
try:
util.run(asyncio.wait_for(self.updateEvent, timeout))
except asyncio.TimeoutError:
return False
else:
util.run(self.updateEvent)
return True
def loopUntil(self, condition=None, timeout: float = 0) -> Iterator[object]:
"""
Iterate until condition is met, with optional timeout in seconds.
The yielded value is that of the condition or False when timed out.
Args:
condition: Predicate function that is tested after every network
update.
timeout: Maximum time in seconds to wait.
If 0 then no timeout is used.
"""
endTime = time.time() + timeout
while True:
test = condition and condition()
if test:
yield test
return
if timeout and time.time() > endTime:
yield False
return
yield test
self.waitOnUpdate(endTime - time.time() if timeout else 0)
def setTimeout(self, timeout: float = 60):
"""
Set a timeout for receiving messages from TWS/IBG, emitting
``timeoutEvent`` if there is no incoming data for too long.
The timeout fires once per connected session but can be set again
after firing or after a reconnect.
Args:
timeout: Timeout in seconds.
"""
self.wrapper.setTimeout(timeout)
def managedAccounts(self) -> List[str]:
"""List of account names."""
return list(self.wrapper.accounts)
def accountValues(self, account: str = "") -> List[AccountValue]:
"""
List of account values for the given account,
or of all accounts if account is left blank.
Args:
account: If specified, filter for this account name.
"""
if account:
return [
v for v in self.wrapper.accountValues.values() if v.account == account
]
return list(self.wrapper.accountValues.values())
def accountSummary(self, account: str = "") -> List[AccountValue]:
"""
List of account values for the given account,
or of all accounts if account is left blank.
This method is blocking on first run, non-blocking after that.
Args:
account: If specified, filter for this account name.
"""
return self._run(self.accountSummaryAsync(account))
def portfolio(self, account: str = "") -> List[PortfolioItem]:
"""
List of portfolio items for the given account,
or of all retrieved portfolio items if account is left blank.
Args:
account: If specified, filter for this account name.
"""
if account:
return list(self.wrapper.portfolio[account].values())
return [v for d in self.wrapper.portfolio.values() for v in d.values()]
def positions(self, account: str = "") -> List[Position]:
"""
List of positions for the given account,
or of all accounts if account is left blank.
Args:
account: If specified, filter for this account name.
"""
if account:
return list(self.wrapper.positions[account].values())
return [v for d in self.wrapper.positions.values() for v in d.values()]
def pnl(self, account="", modelCode="") -> List[PnL]:
"""
List of subscribed :class:`.PnL` objects (profit and loss),
optionally filtered by account and/or modelCode.
The :class:`.PnL` objects are kept live updated.
Args:
account: If specified, filter for this account name.
modelCode: If specified, filter for this account model.
"""
return [
v
for v in self.wrapper.reqId2PnL.values()
if (not account or v.account == account)
and (not modelCode or v.modelCode == modelCode)
]
def pnlSingle(
self, account: str = "", modelCode: str = "", conId: int = 0
) -> List[PnLSingle]:
"""
List of subscribed :class:`.PnLSingle` objects (profit and loss for
single positions).
The :class:`.PnLSingle` objects are kept live updated.
Args:
account: If specified, filter for this account name.
modelCode: If specified, filter for this account model.
conId: If specified, filter for this contract ID.
"""
return [
v
for v in self.wrapper.reqId2PnlSingle.values()
if (not account or v.account == account)
and (not modelCode or v.modelCode == modelCode)
and (not conId or v.conId == conId)
]
def trades(self) -> List[Trade]:
"""List of all order trades from this session."""
return list(self.wrapper.trades.values())
def openTrades(self) -> List[Trade]:
"""List of all open order trades."""
return [
v
for v in self.wrapper.trades.values()
if v.orderStatus.status not in OrderStatus.DoneStates
]
def orders(self) -> List[Order]:
"""List of all orders from this session."""
return list(trade.order for trade in self.wrapper.trades.values())
def openOrders(self) -> List[Order]:
"""List of all open orders."""
return [
trade.order
for trade in self.wrapper.trades.values()
if trade.orderStatus.status not in OrderStatus.DoneStates
]
def fills(self) -> List[Fill]:
"""List of all fills from this session."""
return list(self.wrapper.fills.values())
def executions(self) -> List[Execution]:
"""List of all executions from this session."""
return list(fill.execution for fill in self.wrapper.fills.values())
def ticker(self, contract: Contract) -> Optional[Ticker]:
"""
Get ticker of the given contract. It must have been requested before
with reqMktData with the same contract object. The ticker may not be
ready yet if called directly after :meth:`.reqMktData`.
Args:
contract: Contract to get ticker for.
"""
return self.wrapper.tickers.get(id(contract))
def tickers(self) -> List[Ticker]:
"""Get a list of all tickers."""
return list(self.wrapper.tickers.values())
def pendingTickers(self) -> List[Ticker]:
"""Get a list of all tickers that have pending ticks or domTicks."""
return list(self.wrapper.pendingTickers)
def realtimeBars(self) -> List[Union[BarDataList, RealTimeBarList]]:
"""
Get a list of all live updated bars. These can be 5 second realtime
bars or live updated historical bars.
"""
return list(self.wrapper.reqId2Subscriber.values())
def newsTicks(self) -> List[NewsTick]:
"""
List of ticks with headline news.
The article itself can be retrieved with :meth:`.reqNewsArticle`.
"""
return self.wrapper.newsTicks
def newsBulletins(self) -> List[NewsBulletin]:
"""List of IB news bulletins."""
return list(self.wrapper.msgId2NewsBulletin.values())
def reqTickers(
self, *contracts: Contract, regulatorySnapshot: bool = False
) -> List[Ticker]:
"""
Request and return a list of snapshot tickers.
The list is returned when all tickers are ready.
This method is blocking.
Args:
contracts: Contracts to get tickers for.
regulatorySnapshot: Request NBBO snapshots (may incur a fee).
"""
return self._run(
self.reqTickersAsync(*contracts, regulatorySnapshot=regulatorySnapshot)
)
def qualifyContracts(self, *contracts: Contract) -> List[Contract]:
"""
Fully qualify the given contracts in-place. This will fill in
the missing fields in the contract, especially the conId.
Returns a list of contracts that have been successfully qualified.
This method is blocking.
Args:
contracts: Contracts to qualify.
"""
return self._run(self.qualifyContractsAsync(*contracts))
def bracketOrder(
self,
action: str,
quantity: float,
limitPrice: float,
takeProfitPrice: float,
stopLossPrice: float,
**kwargs,
) -> BracketOrder:
"""
Create a limit order that is bracketed by a take-profit order and
a stop-loss order. Submit the bracket like:
.. code-block:: python
for o in bracket:
ib.placeOrder(contract, o)
https://interactivebrokers.github.io/tws-api/bracket_order.html
Args:
action: 'BUY' or 'SELL'.
quantity: Size of order.
limitPrice: Limit price of entry order.
takeProfitPrice: Limit price of profit order.
stopLossPrice: Stop price of loss order.
"""
assert action in ("BUY", "SELL")
reverseAction = "BUY" if action == "SELL" else "SELL"
parent = LimitOrder(
action,
quantity,
limitPrice,
orderId=self.client.getReqId(),
transmit=False,
**kwargs,
)
takeProfit = LimitOrder(
reverseAction,
quantity,
takeProfitPrice,
orderId=self.client.getReqId(),
transmit=False,
parentId=parent.orderId,
**kwargs,
)
stopLoss = StopOrder(
reverseAction,
quantity,
stopLossPrice,
orderId=self.client.getReqId(),
transmit=True,
parentId=parent.orderId,
**kwargs,
)
return BracketOrder(parent, takeProfit, stopLoss)
@staticmethod
def oneCancelsAll(orders: List[Order], ocaGroup: str, ocaType: int) -> List[Order]:
"""
Place the trades in the same One Cancels All (OCA) group.
https://interactivebrokers.github.io/tws-api/oca.html
Args:
orders: The orders that are to be placed together.
"""
for o in orders:
o.ocaGroup = ocaGroup
o.ocaType = ocaType
return orders
def whatIfOrder(self, contract: Contract, order: Order) -> OrderState:
"""
Retrieve commission and margin impact without actually
placing the order. The given order will not be modified in any way.
This method is blocking.
Args:
contract: Contract to test.
order: Order to test.
"""
return self._run(self.whatIfOrderAsync(contract, order))
def placeOrder(self, contract: Contract, order: Order) -> Trade:
"""
Place a new order or modify an existing order.
Returns a Trade that is kept live updated with
status changes, fills, etc.
Args:
contract: Contract to use for order.
order: The order to be placed.
"""
orderId = order.orderId or self.client.getReqId()
self.client.placeOrder(orderId, contract, order)
now = datetime.datetime.now(datetime.timezone.utc)
key = self.wrapper.orderKey(self.wrapper.clientId, orderId, order.permId)
trade = self.wrapper.trades.get(key)
if trade:
# this is a modification of an existing order
assert trade.orderStatus.status not in OrderStatus.DoneStates
logEntry = TradeLogEntry(now, trade.orderStatus.status, "Modify")
trade.log.append(logEntry)
self._logger.info(f"placeOrder: Modify order {trade}")
trade.modifyEvent.emit(trade)
self.orderModifyEvent.emit(trade)
else:
# this is a new order
order.clientId = self.wrapper.clientId
order.orderId = orderId
orderStatus = OrderStatus(orderId=orderId, status=OrderStatus.PendingSubmit)
logEntry = TradeLogEntry(now, orderStatus.status)
trade = Trade(contract, order, orderStatus, [], [logEntry])
self.wrapper.trades[key] = trade
self._logger.info(f"placeOrder: New order {trade}")
self.newOrderEvent.emit(trade)
return trade
def cancelOrder(
self, order: Order, manualCancelOrderTime: str = ""
) -> Optional[Trade]:
"""
Cancel the order and return the Trade it belongs to.
Args:
order: The order to be canceled.
manualCancelOrderTime: For audit trail.
"""
self.client.cancelOrder(order.orderId, manualCancelOrderTime)
now = datetime.datetime.now(datetime.timezone.utc)
key = self.wrapper.orderKey(order.clientId, order.orderId, order.permId)
trade = self.wrapper.trades.get(key)
if trade:
if not trade.isDone():
status = trade.orderStatus.status
if (
status == OrderStatus.PendingSubmit
and not order.transmit
or status == OrderStatus.Inactive
):
newStatus = OrderStatus.Cancelled
else:
newStatus = OrderStatus.PendingCancel
logEntry = TradeLogEntry(now, newStatus)
trade.log.append(logEntry)
trade.orderStatus.status = newStatus
self._logger.info(f"cancelOrder: {trade}")
trade.cancelEvent.emit(trade)
trade.statusEvent.emit(trade)
self.cancelOrderEvent.emit(trade)
self.orderStatusEvent.emit(trade)
if newStatus == OrderStatus.Cancelled:
trade.cancelledEvent.emit(trade)
else:
self._logger.error(f"cancelOrder: Unknown orderId {order.orderId}")
return trade
def reqGlobalCancel(self):
"""
Cancel all active trades including those placed by other
clients or TWS/IB gateway.
"""
self.client.reqGlobalCancel()
self._logger.info("reqGlobalCancel")
def reqCurrentTime(self) -> datetime.datetime:
"""
Request TWS current time.
This method is blocking.
"""
return self._run(self.reqCurrentTimeAsync())
def reqAccountUpdates(self, account: str = ""):
"""
This is called at startup - no need to call again.
Request account and portfolio values of the account
and keep updated. Returns when both account values and portfolio
are filled.
This method is blocking.
Args:
account: If specified, filter for this account name.
"""
self._run(self.reqAccountUpdatesAsync(account))
def reqAccountUpdatesMulti(self, account: str = "", modelCode: str = ""):
"""
It is recommended to use :meth:`.accountValues` instead.
Request account values of multiple accounts and keep updated.
This method is blocking.
Args:
account: If specified, filter for this account name.
modelCode: If specified, filter for this account model.
"""
self._run(self.reqAccountUpdatesMultiAsync(account, modelCode))
def reqAccountSummary(self):
"""
It is recommended to use :meth:`.accountSummary` instead.
Request account values for all accounts and keep them updated.
Returns when account summary is filled.
This method is blocking.
"""
self._run(self.reqAccountSummaryAsync())
def reqAutoOpenOrders(self, autoBind: bool = True):
"""
Bind manual TWS orders so that they can be managed from this client.
The clientId must be 0 and the TWS API setting "Use negative numbers
to bind automatic orders" must be checked.
This request is automatically called when clientId=0.
https://interactivebrokers.github.io/tws-api/open_orders.html
https://interactivebrokers.github.io/tws-api/modifying_orders.html
Args:
autoBind: Set binding on or off.
"""
self.client.reqAutoOpenOrders(autoBind)
def reqOpenOrders(self) -> List[Trade]:
"""
Request and return a list of open orders.
This method can give stale information where a new open order is not
reported or an already filled or cancelled order is reported as open.
It is recommended to use the more reliable and much faster
:meth:`.openTrades` or :meth:`.openOrders` methods instead.
This method is blocking.
"""
return self._run(self.reqOpenOrdersAsync())
def reqAllOpenOrders(self) -> List[Trade]:
"""
Request and return a list of all open orders over all clients.
Note that the orders of other clients will not be kept in sync,
use the master clientId mechanism instead to see other
client's orders that are kept in sync.
"""
return self._run(self.reqAllOpenOrdersAsync())
def reqCompletedOrders(self, apiOnly: bool) -> List[Trade]:
"""
Request and return a list of completed trades.
Args:
apiOnly: Request only API orders (not manually placed TWS orders).
"""
return self._run(self.reqCompletedOrdersAsync(apiOnly))
def reqExecutions(self, execFilter: Optional[ExecutionFilter] = None) -> List[Fill]:
"""
It is recommended to use :meth:`.fills` or
:meth:`.executions` instead.
Request and return a list of fills.
This method is blocking.
Args:
execFilter: If specified, return executions that match the filter.
"""
return self._run(self.reqExecutionsAsync(execFilter))
def reqPositions(self) -> List[Position]:
"""
It is recommended to use :meth:`.positions` instead.
Request and return a list of positions for all accounts.
This method is blocking.
"""
return self._run(self.reqPositionsAsync())
def reqPnL(self, account: str, modelCode: str = "") -> PnL:
"""
Start a subscription for profit and loss events.
Returns a :class:`.PnL` object that is kept live updated.
The result can also be queried from :meth:`.pnl`.
https://interactivebrokers.github.io/tws-api/pnl.html
Args:
account: Subscribe to this account.
modelCode: If specified, filter for this account model.
"""
key = (account, modelCode)
assert key not in self.wrapper.pnlKey2ReqId
reqId = self.client.getReqId()
self.wrapper.pnlKey2ReqId[key] = reqId
pnl = PnL(account, modelCode)
self.wrapper.reqId2PnL[reqId] = pnl
self.client.reqPnL(reqId, account, modelCode)
return pnl
def cancelPnL(self, account, modelCode: str = ""):
"""
Cancel PnL subscription.