-
Notifications
You must be signed in to change notification settings - Fork 41
/
ib_class.py
329 lines (254 loc) · 14.1 KB
/
ib_class.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
import time
from datetime import datetime
from IBWrapper import IBWrapper, contract
from ib.ext.EClientSocket import EClientSocket
from ib.ext.ScannerSubscription import ScannerSubscription
from __future__ import print_function
if __name__=="__main__":
callback = IBWrapper() # Instantiate IBWrapper
tws = EClientSocket(callback) # Instantiate EClientSocket
host = ""
port = 7496
clientId = 5000
tws.eConnect(host, port, clientId) # Connect to TWS
tws.setServerLogLevel(5)
accountName = "DU123456" # Change to your own account
create = contract() # Instantiate contract class
# Initiate attributes to receive data. At some point we need a separate class for this
callback.initiate_variables()
# Account and Portfolio ##############################################################
# reqAccountUpdates ---> updateAccountTime self.update_AccountTime
# updateAccountValue self.update_AccountValue
# updatePortfolio self.update_Portfolio
# accountDownloadEnd self.accountDownloadEnd_flag
# reqAccountSummary ---> accountSummary self.account_Summary
# cancelAccountSummary
# accountSummaryEnd self.account_SummaryEnd_flag
# reqPositions ---> position self.update_Position
# cancelPositions
# positionEnd self.positionEnd_flag
###################################################################################'''
print "Testing Account and Portfolio \n"
tws.reqAccountUpdates(1, accountName)
tws.reqAccountSummary(1,"All","NetLiquidation")
#tws.cancelAccountSummary(1)
tws.reqPositions()
#tws.cancelPositions()
# Orders #############################################################################
# placeOrder ---> orderStatus** self.order_Status
# cancelorder
# ---> openOrderEnd self.open_OrderEnd_flag
# reqOpenOrders ---> openOrder* self.open_Order
# ---> orderStatus**
# reqAllOpenOrders ---> openOrder*
# ---> orderStatus**
# reqAutoOpenOrders ---> openOrder*
# ---> orderStatus**
# reqIds ---> nextValidId self.next_ValidId
# ---> deltaNeutralValidation
# exerciseOptions
# reqGlobalCancel
###################################################################################'''
print "Testing Orders Group \n"
# Example 1 - placing order to buy stock
tws.reqIds(1) # Need to request next valid order Id
time.sleep(2) # wait for response from server
order_id = callback.next_ValidId
contract_info1 = create.create_contract('GOOG', 'STK', 'SMART', 'USD')
order_info1 = create.create_order(accountName, 'MKT', 100, 'BUY')
tws.placeOrder(order_id, contract_info1, order_info1)
# Example 2 - placing order to buy FX
tws.reqIds(1)
time.sleep(1)
order_id = callback.next_ValidId
contract_info2 = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
order_info2 = create.create_order(accountName, 'MKT', 100000, 'BUY')
tws.placeOrder(order_id, contract_info2, order_info2)
#tws.cancelOrder(order_id) # Cancel example 2 order
#tws.reqOpenOrders()
#tws.reqAllOpenOrders()
#tws.reqAutoOpenOrders(1) # clientId had to be 0 for this to work
tws.reqGlobalCancel()
# Market Data ########################################################################
# reqMktData ---> tickPrice self.tick_Price
# ---> tickSize self.tick_Size
# ---> tickOptionComputation self.tick_OptionComputation
# ---> tickGeneric self.tick_Generic
# ---> tickString self.tick_String
# ---> tickEFP self.tick_EFP
# ---> tickSnapshotEnd self.tickSnapshotEnd_flag
# cancelMktData
# calculateImpliedVolatility >tickOptionComputation self.tick_OptionComputation
# cancelcalculateImpliedVolatility
# calculateOptionPrice ---> tickOptionComputation self.tick_OptionComputation
# cancelCalculateOptionPrice
# reqMktDataType ---> marketDataType self.market_DataType
###################################################################################'''
'''print "Testing Market Data Group \n"
contract_info3 = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
tws.reqMktData(1, contract_info3, "", False)
contract_info4 = create.create_contract('NFLX 160318C00100000',
'OPT', 'SMART', 'USD',
'CALL', '100', '20160318',
100, "NFLX")
tws.calculateImpliedVolatility(2, contract_info4, 3.60, 94.41)
tws.calculateOptionPrice(3, contract_info4, 0.42, 94.41)
tws.reqMarketDataType(2) # need to test this when mkt opens
time.sleep(2)
tws.cancelMktData(1)
tws.cancelCalculateImpliedVolatility(2)
tws.cancelCalculateOptionPrice(3)
# Connection and Server ##############################################################
# EClientSocket
# eConnect
# eDisconnect ---> connectionClosed
# isConnected
# setServerLogLevel
# reqCurrentTime ---> currentTime self.current_Time
# serverVersion
# TwsConnectionTime
# ---> error
###################################################################################'''
print "Testing Connection and Server Group \n"
print tws.isConnected()
tws.setServerLogLevel(5)
tws.reqCurrentTime()
print "Server Version " + str(tws.serverVersion())
print "TWS Connection Time %s " % tws.TwsConnectionTime()
# Executions #########################################################################
# reqExecutions ---> execDetails self.exec_Details_reqId
# self.exec_Details_contract
# self.exec_Details_execution
# ---> execDetailsEnd self.exec_DetailsEnd_flag
# ---> commissionReport self.commission_Report
###################################################################################'''
print "Testing Executions Group \n"
order_id = []
tws.reqIds(1)
while not order_id:
time.sleep(0.1)
order_id = callback.next_ValidId
print "waiting for id"
order_id = callback.next_ValidId
print ("Just got it. The next order id is: ", order_id)
contract_info5 = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
order_info5 = create.create_order(accountName, 'MKT', 100000, 'BUY')
tws.placeOrder(order_id, contract_info5, order_info5)
time.sleep(2)
tws.reqExecutions(0, create.exec_filter(9999, accountName, contract_info5))
# Contract ###########################################################################
# reqContractDetails ---> contractDetails self.contract_Details_reqId
# self.contract_Details
# ---> contractDetailsEnd self.contract_DetailsEnd_reqId
# self.contract_Details_flag
# ---> bondContractDetails self.bond_ContractDetails_reqId
# self.bond_ContractDetails
###################################################################################'''
print "Testing Contract Group \n"
# Example 1 - Option
contract_Details6 = create.create_contract('NFLX 160318C00100000', 'OPT', 'SMART',
'USD', 'CALL', '100', '20160318',
100, "NFLX")
tws.reqContractDetails(5000, contract_Details6)
while not callback.contract_Details_flag:
time.sleep(1)
callback.contract_Details_flag = False
print callback.contract_Details_reqId
print callback.contract_Details.__dict__
# Example 2 - Stock
contract_Details7 = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
tws.reqContractDetails(5001, contract_Details7)
while not callback.contract_Details_flag:
time.sleep(1)
callback.contract_Details_flag = False
print callback.contract_Details_reqId
print callback.contract_Details.__dict__
# Example 3 - FX
contract_Details8 = create.create_contract('IBCID143913442',
'BOND', 'SMART',
'USD','CORP')
tws.reqContractDetails(5002, contract_Details8)
while not callback.contract_Details_flag:
time.sleep(1)
callback.contract_Details_flag = False
print callback.bond_ContractDetails_reqId
print callback.bond_ContractDetails.__dict__
# Market Depth #######################################################################
# reqMktDepth ---> updateMktDepth self.update_MktDepth
# ---> update_MktDepthL2 self.update_MktDepthL2
###################################################################################'''
print "Testing Market Depth Group \n"
contract_info9 = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
tws.reqMktDepth(7000, contract_info9, 3)
time.sleep(5)
print callback.update_MktDepth
tws.cancelMktDepth(7000)
# News Bulletin ######################################################################
# reqNewsBulletins ---> updateNewsBulletin self.update_NewsBulletin_msgId
# self.update_NewsBulletin_msgType
# self.update_NewsBulletin_message
# self.update_NewsBulletin_origExchange
###################################################################################'''
print "Testing News Bulletin Group \n"
tws.reqNewsBulletins(1)
time.sleep(20)
tws.cancelNewsBulletins()
# Financial Advisors Group ###########################################################
# reqManagedAccts ---> managedAccounts self.managed_Accounts
###################################################################################'''
print "Testing Financial Advisors Group \n"
tws.reqManagedAccts()
#tws.requestFA() # non FA account. Unable to test.
# Historical Data ####################################################################
# reqHistoricalData ---> historicalData self.historical_Data
###################################################################################'''
print "Testing Historical Data Group \n"
contract_Details10 = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
data_endtime = datetime.now().strftime("%Y%m%d %H:%M:%S")
tws.reqHistoricalData(9000, contract_Details10, data_endtime,
"1 M", "1 day", "BID", 0, 1)
time.sleep(3)
tws.cancelHistoricalData(9000)
# Market Scanners ####################################################################
# reqScannerParameters ---> scannerParameters self.scanner_Parameters
# ---> scannerData self.scanner_Data
# ---> scannerDataEnd self.scanner_Data_End_reqID
# self.scanner_Data_reqID
###################################################################################'''
print "Testing Market Scanners Group \n"
subscript = ScannerSubscription()
subscript.numberOfRows(3)
subscript.locationCode('STK.NYSE')
tws.reqScannerSubscription(700, subscript)
tws.reqScannerParameters()
time.sleep(3)
tws.cancelScannerSubscription(700)
# Real Time Bars #####################################################################
# reqRealTimeBars ---> realtimeBar self.real_timeBar
###################################################################################'''
print "Testing Real Time Bars Group \n"
contract_Details11 = create.create_contract('EUR', 'CASH', 'IDEALPRO', 'USD')
tws.reqRealTimeBars(10000, contract_Details11, 5, "MIDPOINT", 0)
time.sleep(10)
tws.cancelRealTimeBars(10000)
# Fundamental Data ###################################################################
# reportType = ReportSnapshot
# ReportsFinSummary
# ReportsFinSummary
# ReportRatios
# ReportFinStatements
# RESC
# Calendar Report
# Unfortunately, no access. 430, 'We are sorry, but fundamentals data for the
# security specified is not available.Not allowed'
###################################################################################'''
'''print "Testing Fundamental Data Group \n"
contract_info12 = create.create_contract('AAPL', 'STK', 'SMART', 'USD')
reportType = "ReportSnapshot"
tws.reqFundamentalData(10100, contract_info12, reportType)
time.sleep(10)
tws.cancelFundamentalData(10100)'''
# Disconnect from TWS
time.sleep(2)
tws.isConnected()
tws.eDisconnect()