Placing Orders

View as MarkdownOpen in Claude

Placing orders first requires a contract to be defined.

In the code below, the reqContractDetails() function initiates the sequence of function calls that place an order. Inside the defined contractDetails() callback function below, the placeOrder() function is called, which places the order.

Data from the placeOrder() function is returned via the openOrder() and orderStatus() 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.

The requested contract object is returned via the contractDetails() callback function.

Python
1import time
2import threading
3from ibapi.client import *
4from ibapi.wrapper import *
5
6host = "127.0.0.1"
7
8# Default Ports:
9# TWS Live Account: 7946
10# TWS Paper Account: 7947
11# IB Gateway Live Account: 4001
12# IB Gateway Paper Account: 4002
13port = 4002
14
15
16class TestApp(EClient, EWrapper):
17 def __init__(self):
18 EClient.__init__(self, self)
19 self.nextOrderId = None
20
21 def nextValidId(self, orderId: OrderId):
22 self.nextOrderId = orderId
23
24 def contractDetails(self, reqId: int, contractDetails: ContractDetails):
25 print(contractDetails.contract)
26 self.placeOrder(myOrder.orderId, contractDetails.contract, myOrder)
27
28 def openOrder(
29 self, orderId: OrderId, contract: Contract, order: Order, orderState: OrderState
30 ):
31 print(f"openOrder. orderId: {orderId}, contract: {contract}, order: {order}")
32
33 def orderStatus(
34 self,
35 orderId: OrderId,
36 status: str,
37 filled: Decimal,
38 remaining: Decimal,
39 avgFillPrice: float,
40 permId: int,
41 parentId: int,
42 lastFillPrice: float,
43 clientId: int,
44 whyHeld: str,
45 mktCapPrice: float,
46 ):
47 print(
48 f"orderId: {orderId}, status: {status}, filled: {filled}, remaining: {remaining}, avgFillPrice: {avgFillPrice}, permId: {permId}, parentId: {parentId}, lastFillPrice: {lastFillPrice}, clientId: {clientId}, whyHeld: {whyHeld}, mktCapPrice: {mktCapPrice}"
49 )
50
51 def execDetails(self, reqId: int, contract: Contract, execution: Execution):
52 print(f"reqId: {reqId}, contract: {contract}, execution: {execution}")
53
54
55app = TestApp()
56app.connect("127.0.0.1", port, 0)
57threading.Thread(target=app.run).start()
58time.sleep(1)
59
60myContract = Contract()
61myContract.symbol = "AAPL"
62myContract.secType = "STK"
63myContract.exchange = "SMART"
64myContract.currency = "USD"
65
66myOrder = Order()
67myOrder.orderId = app.nextOrderId
68myOrder.action = "BUY"
69myOrder.tif = "GTC"
70myOrder.orderType = "LMT"
71myOrder.lmtPrice = 310.00
72myOrder.totalQuantity = 10
73
74app.myOrder = myOrder
75app.reqContractDetails(app.nextOrderId, myContract)