forked from anthonyng2/ib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIBWrapper.py
619 lines (403 loc) · 19.8 KB
/
IBWrapper.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
'''
Wrapper - Organised by groups. E.g., Accont and Portfolio group, Orders group etc
2016-01-31
Updated 20 Nov 2016 for Python 3.
Updated 5 Apr 2018 to include limit price
'''
from __future__ import print_function
from ib.ext.EWrapper import EWrapper
from ib.ext.Contract import Contract
from ib.ext.ExecutionFilter import ExecutionFilter
from ib.ext.Order import Order
class IBWrapper(EWrapper):
def initiate_variables(self):
# Account and Portfolio
setattr(self, "accountDownloadEnd_flag", False)
setattr(self, "update_AccountTime", None)
setattr(self, "update_AccountValue", [])
setattr(self, "update_Portfolio", [])
setattr(self, 'account_Summary', [])
setattr(self, 'account_SummaryEnd_flag', False)
setattr(self, 'update_Position', [])
setattr(self, 'positionEnd_flag', False)
# Orders
setattr(self, 'order_Status', [])
setattr(self, 'open_Order', [])
setattr(self, 'open_OrderEnd_flag', True)
# Market Data
setattr(self, 'tick_Price', [])
setattr(self, 'tick_Size', [])
setattr(self, 'tick_OptionComputation', [])
setattr(self, 'tick_Generic', [])
setattr(self, 'tick_String', [])
setattr(self, 'tick_EFP', [])
setattr(self, 'tickSnapshotEnd_reqId', [])
setattr(self, 'tickSnapshotEnd_flag', False)
# Connection and Server
setattr(self, 'connection_Closed', False)
# Executions
setattr(self, "exec_Details_reqId", [])
setattr(self, "exec_Details_contract", [])
setattr(self, "exec_Details_execution", [])
setattr(self, "exec_DetailsEnd_flag", False)
# Contract
setattr(self, "contract_Details_flag", False)
# Market Depth
setattr(self, 'update_MktDepth', [])
setattr(self, 'update_MktDepthL2', [])
# Historical Data
setattr(self, 'historical_Data', [])
setattr(self, 'historical_DataEnd_flag', False)
# Market Scanners
setattr(self, 'scanner_Data_End_flag', False)
setattr(self, 'scanner_Data', [])
# Real Time Bars
setattr(self, 'real_timeBar', [])
# Account and Portfolio ###################################################
def updateAccountValue(self, key, value, currency, accountName):
update_AccountValue = self.update_AccountValue
update_AccountValue.append((key, value, currency, accountName))
def updatePortfolio(self, contract, position, marketPrice, marketValue,
averageCost, unrealizedPnL, realizedPnL, accountName):
update_Portfolio = self.update_Portfolio
update_Portfolio.append((contract.m_conId, contract.m_currency,
contract.m_expiry, contract.m_includeExpired,
contract.m_localSymbol, contract.m_multiplier,
contract.m_primaryExch, contract.m_right,
contract.m_secType, contract.m_strike,
contract.m_symbol, contract.m_tradingClass,
position, marketPrice, marketValue,
averageCost, unrealizedPnL, realizedPnL,
accountName))
def updateAccountTime(self, timeStamp):
self.update_AccountTime = timeStamp
def accountDownloadEnd(self, accountName=None):
self.accountDownloadEnd_accountName = accountName
self.accountDownloadEnd_flag = True
def accountSummary(self, reqId=None, account=None, tag=None, value=None,
currency=None):
account_Summary = self.account_Summary
account_Summary.append((reqId, account, tag, value, currency))
def accountSummaryEnd(self, reqId):
self.accountSummaryEnd_reqId = reqId
self.account_SummaryEnd_flag = True
def position(self, account, contract, pos, avgCost):
update_Position = self.update_Position
update_Position.append((account, contract.m_conId, contract.m_currency,
contract.m_exchange, contract.m_expiry,
contract.m_includeExpired, contract.m_localSymbol,
contract.m_multiplier, contract.m_right,
contract.m_secType, contract.m_strike,
contract.m_symbol, contract.m_tradingClass,
pos, avgCost))
def positionEnd(self):
setattr(self, 'positionEnd_flag', True)
# Orders ###################################################################
def orderStatus(self, orderId, status, filled, remaining, avgFillPrice,
permId, parentId, lastFillPrice, clientId, whyHeld):
order_Status = self.order_Status
order_Status.append((orderId, status, filled, remaining, avgFillPrice,
permId, parentId, lastFillPrice, clientId, whyHeld))
def openOrder(self, orderId, contract, order, orderState):
open_Order = self.open_Order
open_Order.append((orderId, contract, order, orderState))
def openOrderEnd(self):
setattr(self, 'open_OrderEnd_flag', True)
def nextValidId(self, orderId):
self.next_ValidId = orderId
def deltaNeutralValidation(self, reqId, underComp):
pass
# Market Data ##############################################################
def tickPrice(self, tickerId, field, price, canAutoExecute):
tick_Price = self.tick_Price
tick_Price.append((tickerId, field, price, canAutoExecute))
def tickSize(self, tickerId, field, size):
tick_Size = self.tick_Size
tick_Size.append((tickerId, field, size))
def tickOptionComputation(self, tickerId, field, impliedVol, delta,
optPrice, pvDividend, gamma, vega, theta,
undPrice):
tick_OptionComputation = self.tick_OptionComputation
tick_OptionComputation.append((tickerId, field, impliedVol, delta,
optPrice, pvDividend, gamma, vega,
theta, undPrice))
def tickGeneric(self, tickerId, tickType, value):
tick_Generic = self.tick_Generic
tick_Generic.append((tickerId, tickType, value))
def tickString(self, tickerId, field, value):
tick_String = self.tick_String
tick_String.append((tickerId, field, value))
def tickEFP(self, tickerId, tickType, basisPoints, formattedBasisPoints,
impliedFuture, holdDays, futureExpiry, dividendImpact,
dividendsToExpiry):
tick_EFP = self.tick_EFP
tick_EFP.append((tickerId, tickType, basisPoints, formattedBasisPoints,
impliedFuture, holdDays, futureExpiry, dividendImpact,
dividendsToExpiry))
def tickSnapshotEnd(self, reqId):
self.tickSnapshotEnd_reqId = reqId
setattr(self, 'tickSnapshotEnd_flag', True)
def marketDataType(self, reqId, marketDataType):
setattr(self, 'market_DataType', marketDataType)
print("market_DataType" + str(self.market_DataType))
# Connection and Server ####################################################
def currentTime(self, time):
self.current_Time = time
def error(self, id=None, errorCode=None, errorString=None):
#print id
print([id, errorCode, errorString])
def error_0(self, strval=None):
print("error_0")
def error_1(self, id=0, errorCode=None, errorMsg=None):
print("error_1")
'''def error_0(self, strval):
pass
def error_1(self, id, errorCode, errorMsg):
pass'''
def connectionClosed(self):
self.connection_Closed = True
# Executions ###############################################################
def execDetails(self, reqId, contract, execution):
self.exec_Details_reqId = reqId
self.exec_Details_contract = contract
self.exec_Details_execution = execution
def execDetailsEnd(self, reqId):
self.exec_DetailsEnd_reqId = reqId
setattr(self, "exec_DetailsEnd_flag", True)
def commissionReport(self, commissionReport):
self.commission_Report = commissionReport
# Contract #################################################################
def contractDetails(self, reqId, contractDetails):
self.contract_Details_reqId = reqId
self.contract_Details = contractDetails
def contractDetailsEnd(self, reqId):
self.contract_DetailsEnd_reqId = reqId
self.contract_Details_flag = True
def bondContractDetails(self, reqId, contractDetails):
self.bond_ContractDetails_reqId = reqId
self.bond_ContractDetails = contractDetails
# Market Depth #############################################################
def updateMktDepth(self, tickerId, position, operation, side, price, size):
update_MktDepth = self.update_MktDepth
update_MktDepth.append((tickerId, position, operation, side, price, size))
#df = pd.DataFrame(self.update_MktDepth, columns = ["tickerId", "position",
# "operation", "side",
# "price", "size"])
def updateMktDepthL2(self, tickerId, position, marketMaker, operation,
side, price, size):
# I don't get any of this so I can't test it. Following are just place holders.
print("blah blah. You have L2 data!!!")
update_MktDepthL2 = self.update_MktDepthL2
update_MktDepthL2.append((tickerId, position, operation, side,
price, size))
# News Bulletin ############################################################
def updateNewsBulletin(self, msgId, msgType, message, origExchange):
# During the time I test this, I don't get anything. Can't verify. Sorry.
print("You get News!!!")
self.update_NewsBulletin_msgId = msgId
self.update_NewsBulletin_msgType = msgType
self.update_NewsBulletin_message = message
self.update_NewsBulletin_origExchange = origExchange
# Financial Advisors #######################################################
def managedAccounts(self, accountsList):
self.managed_Accounts = accountsList
def receiveFA(self, faDataType, xml):
pass
# Historical Data #########################################################
def historicalData(self, reqId, date, open, high, low, close, volume,
count, WAP, hasGaps):
historical_Data = self.historical_Data
historical_Data.append((reqId, date, open, high, low, close, volume,
count, WAP, hasGaps))
#df = pd.DataFrame(self.historical_Data, columns = ["reqId", "date", "open",
# "high", "low", "close",
# "volume", "count", "WAP",
# "hasGaps"])
# Market Scanners #########################################################
def scannerParameters(self, xml):
self.scanner_Parameters = xml
def scannerData(self, reqId, rank, contractDetails, distance, benchmark,
projetion, legsStr):
scanner_Data = self.scanner_Data
scanner_Data.append((reqId, rank, contractDetails, distance, benchmark,
projetion, legsStr))
def scannerDataEnd(self, reqId):
self.scanner_Data_End_reqID = reqId
self.scanner_Data_End_flag = True
# Real Tume Bars ###########################################################
def realtimeBar(self, reqId, time, open, high, low, close, volume,
wap, count):
real_timeBar = self.real_timeBar
real_timeBar.append((reqId, time, open, high, low, close, volume,
wap, count))
#df = pd.DataFrame(self.real_timeBar, columns = ["reqId", "time", "open", "high",
# "low", "close", "volume", "wap",
# "count"])
# Fundamental Data #########################################################
def fundamentalData(self, reqId, data):
print("Getting Fundamental Data Feed Through")
self.fundamental_Data_reqId = reqId
self.fundamental_Data_data = data
# Display Groups #########################################################
def displayGroupList(self, reqId, groups):
pass
def displayGroupUpdate(self, reqId, contractInfo):
pass
# Create Contract
class contract():
def create_contract(self, symbol, secType, exchange, currency,
right = None, strike = None, expiry = None,
multiplier = None, tradingClass = None,
localSymbol = None, includeExpired=None):
contract = Contract()
contract.m_symbol = symbol
contract.m_secType = secType
contract.m_exchange = exchange
contract.m_currency = currency
contract.m_right = right
contract.m_strike = strike
contract.m_expiry = expiry
contract.m_multiplier = multiplier
contract.m_tradingClass = tradingClass
contract.m_localSymbol = localSymbol
contract.m_includeExpired = includeExpired
return contract
def create_order(self, account, orderType, totalQuantity, action,
lmt_price=None):
order = Order()
order.m_account = account
order.m_orderType = orderType
order.m_totalQuantity = totalQuantity
order.m_action = action
if orderType == "LMT":
order.m_lmtPrice = lmt_price
return order
def exec_filter(self, client_id, accountName, contract):
filt = ExecutionFilter()
filt.m_clientId = client_id
filt.m_acctCode = accountName
#filt.m_time = "20160122-00:00:00"
filt.m_symbol = contract.m_symbol
filt.m_secType = contract.m_secType
filt.m_exchange = contract.m_exchange
return filt
'''
openOrder contains the following fields:
self.tmp = [orderId, contract.m_comboLegs,
contract.m_comboLegsDescrip,
contract.m_conId,
contract.m_currency,
contract.m_exchange,
contract.m_expiry,
contract.m_includeExpired,
contract.m_localSymbol,
contract.m_multiplier,
contract.m_primaryExch,
contract.m_right,
contract.m_secId,
contract.m_secIdType,
contract.m_secType,
contract.m_strike,
contract.m_symbol,
contract.m_tradingClass,
contract.m_underComp,
order.m_account,
order.m_action,
order.m_activeStartTime,
order.m_activeStopTime,
order.m_algoParams,
order.m_algoStrategy,
order.m_allOrNone,
order.m_auctionStrategy,
order.m_auxPrice,
order.m_basisPoints,
order.m_basisPointsType,
order.m_blockOrder,
order.m_clearingAccount,
order.m_clearingIntent,
order.m_clientId,
order.m_continuousUpdate,
order.m_delta,
order.m_deltaNeutralAuxPrice,
order.m_deltaNeutralClearingAccount,
order.m_deltaNeutralClearingIntent,
order.m_deltaNeutralConId,
order.m_deltaNeutralDesignatedLocation,
order.m_deltaNeutralOpenClose,
order.m_deltaNeutralOrderType,
order.m_deltaNeutralSettlingFirm,
order.m_deltaNeutralShortSale,
order.m_deltaNeutralShortSaleSlot,
order.m_designatedLocation,
order.m_discretionaryAmt,
order.m_displaySize,
order.m_eTradeOnly,
order.m_exemptCode,
order.m_faGroup,
order.m_faMethod,
order.m_faPercentage,
order.m_faProfile,
order.m_firmQuoteOnly,
order.m_goodAfterTime,
order.m_goodTillDate,
order.m_hedgeParam,
order.m_hedgeType,
order.m_hidden,
order.m_lmtPrice,
order.m_minQty,
order.m_nbboPriceCap,
order.m_notHeld,
order.m_ocaGroup,
order.m_ocaType,
order.m_openClose,
order.m_optOutSmartRouting,
order.m_orderComboLegs,
order.m_orderId,
order.m_orderRef,
order.m_orderType,
order.m_origin,
order.m_outsideRth,
order.m_overridePercentageConstraints,
order.m_parentId,
order.m_percentOffset,
order.m_permId,
order.m_referencePriceType,
order.m_rule80A,
order.m_scaleAutoReset,
order.m_scaleInitFillQty,
order.m_scaleInitLevelSize,
order.m_scaleInitPosition,
order.m_scalePriceAdjustInterval,
order.m_scalePriceAdjustValue,
order.m_scalePriceIncrement,
order.m_scaleProfitOffset,
order.m_scaleRandomPercent,
order.m_scaleSubsLevelSize,
order.m_scaleTable,
order.m_settlingFirm,
order.m_shortSaleSlot,
order.m_smartComboRoutingParams,
order.m_startingPrice,
order.m_stockRangeLower,
order.m_stockRangeUpper,
order.m_stockRefPrice,
order.m_sweepToFill,
order.m_tif,
order.m_totalQuantity,
order.m_trailStopPrice,
order.m_trailingPercent,
order.m_transmit,
order.m_triggerMethod,
order.m_volatility,
order.m_volatilityType,
order.m_whatIf,
orderState.m_commission,
orderState.m_commissionCurrency,
orderState.m_equityWithLoan,
orderState.m_initMargin,
orderState.m_maintMargin,
orderState.m_maxCommission,
orderState.m_minCommission,
orderState.m_status,
orderState.m_warningText]
'''