以下是一个使用IB TWS API和Python解决Bracket问题的示例代码:
from ibapi.contract import Contract
from ibapi.order import Order
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
class BracketTrader(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
self.nextOrderId = None
def nextValidId(self, orderId: int):
super().nextValidId(orderId)
self.nextOrderId = orderId
def placeBracketOrder(self, symbol, quantity, limitPrice, stopLossPrice, takeProfitPrice):
# 创建合约对象
contract = Contract()
contract.symbol = symbol
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = "USD"
# 创建主订单
mainOrder = Order()
mainOrder.action = "BUY"
mainOrder.orderType = "LMT"
mainOrder.totalQuantity = quantity
mainOrder.lmtPrice = limitPrice
# 创建止损订单
stopLossOrder = Order()
stopLossOrder.action = "SELL"
stopLossOrder.orderType = "STP"
stopLossOrder.totalQuantity = quantity
stopLossOrder.auxPrice = stopLossPrice
# 创建止盈订单
takeProfitOrder = Order()
takeProfitOrder.action = "SELL"
takeProfitOrder.orderType = "LMT"
takeProfitOrder.totalQuantity = quantity
takeProfitOrder.lmtPrice = takeProfitPrice
# 发送订单
self.placeOrder(self.nextOrderId, contract, mainOrder)
self.nextOrderId += 1
self.placeOrder(self.nextOrderId, contract, stopLossOrder)
self.nextOrderId += 1
self.placeOrder(self.nextOrderId, contract, takeProfitOrder)
self.nextOrderId += 1
def main():
app = BracketTrader()
app.connect("127.0.0.1", 7497, 0)
# 等待连接成功
while not app.isConnected():
pass
# 发送Bracket订单
app.placeBracketOrder("AAPL", 100, 150, 140, 160)
# 等待订单完成
while app.nextOrderId > 0:
pass
# 断开连接
app.disconnect()
if __name__ == "__main__":
main()
上述代码中,BracketTrader
类继承了EWrapper
和EClient
类,并重写了nextValidId
方法,用于获取下一个有效的订单ID。placeBracketOrder
方法用于创建并发送Bracket订单,包括主订单、止损订单和止盈订单。main
函数创建了一个BracketTrader
对象,连接到TWS API,并发送Bracket订单。最后,在订单完成之前,程序会一直等待。