Requesting Market Data

View as MarkdownOpen in Claude

Requesting market data first requires the definition of a contract object for which to return market data for.

The reqMarketDataType() function sets the market data type. The type can either be live, frozen, delayed, or delayed frozen. The differences between these types are described here.

The reqMktData() function returns data through the tickPrice() and tickSize() callback functions.

Comprehensive example code for C++, C#, Java, Python and Visual Basic can be found in the /samples directory of the downloaded TWS API file.

Python
1from ibapi.client import *
2from ibapi.wrapper import *
3import time
4import threading
5from ibapi.ticktype import TickTypeEnum
6
7# Default Ports:
8# TWS Live Account: 7946
9# TWS Paper Account: 7947
10# IB Gateway Live Account: 4001
11# IB Gateway Paper Account: 4002
12port = 4002
13
14
15class TestApp(EClient, EWrapper):
16 def __init__(self):
17 EClient.__init__(self, self)
18
19 def nextValidId(self, orderId: OrderId):
20 self.orderId = orderId
21
22 def nextId(self):
23 self.orderId += 1
24 return self.orderId
25
26 def error(self, reqId, errorTime, errorCode, errorString, advancedOrderReject=""):
27 print(
28 f"reqId: {reqId}, errorCode: {errorCode}, errorString: {errorString}, orderReject: {advancedOrderReject}"
29 )
30
31 def tickPrice(self, reqId, tickType, price, attrib):
32 print(
33 f"reqId: {reqId}, tickType: {TickTypeEnum.toStr(tickType)}, price: {price}, attrib: {attrib}"
34 )
35
36 def tickSize(self, reqId, tickType, size):
37 print(f"reqId: {reqId}, tickType: {TickTypeEnum.toStr(tickType)}, size: {size}")
38
39
40app = TestApp()
41app.connect("127.0.0.1", port, 0)
42threading.Thread(target=app.run).start()
43time.sleep(1)
44
45mycontract = Contract()
46mycontract.symbol = "AAPL"
47mycontract.secType = "STK"
48mycontract.exchange = "SMART"
49mycontract.currency = "USD"
50
51app.reqMarketDataType(3)
52app.reqMktData(app.nextId(), mycontract, "", False, False, [])