我已按照以下步骤在远程计算机上安装了ibapi
python3 setup.py bdist_wheel
python3 -m pip install --user --upgrade dist/ibapi-9.76.1-py3-none-any.whl
此后,我能够在python会话中导入ibapi,并设置了一个应用程序。
from ibapi import wrapper
from ibapi.client import EClient
from ibapi.utils import iswrapper #just for decorator
from ibapi.common import *
from ibapi.contract import *
from ibapi.ticktype import *
class TestApp(wrapper.EWrapper, EClient):
def __init__(self):
wrapper.EWrapper.__init__(self)
EClient.__init__(self, wrapper=self)
@iswrapper
def nextValidId(self, orderId:int):
print("setting nextValidOrderId: %d", orderId)
self.nextValidOrderId = orderId
#here is where you start using api
contract = Contract()
contract.symbol = "AAPL"
contract.secType = "STK"
contract.currency = "USD"
contract.exchange = "SMART"
self.reqMktData(1101, contract, "", False, None)
@iswrapper
def error(self, reqId:TickerId, errorCode:int, errorString:str):
print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString)
@iswrapper
def tickPrice(self, reqId: TickerId , tickType: TickType, price: float,
attrib:TickAttrib):
print("Tick Price. Ticker Id:", reqId, "tickType:", tickType, "Price:", price)
#this will disconnect and end this program because loop finishes
self.done = True
[当我尝试使用app.connect("127.0.0.1", 7497, clientId=123)
连接该应用程序时,它引发了以下错误
Error. Id: -1 Code: 502 Msg: Couldn't connect to TWS. Confirm that "Enable ActiveX and Socket EClients"
is enabled and connection port is the same as "Socket Port" on the
TWS "Edit->Global Configuration...->API->Settings" menu. Live Trading ports:
TWS: 7496; IB Gateway: 4001. Simulated Trading ports for new installations
of version 954.1 or newer: TWS: 7497; IB Gateway: 4002
大部分资源讨论如何在gui上设置tws。如何在python客户端上解决此问题?
即在此处连接app.connect("127.0.0.1", 7497, clientId=123)
的端口'7497'。