首页 > 解决方案 > Interactive Brokers (IB) Python API:无法在 VS Code 上运行 IB 教程示例

问题描述

我是 Python 新手,我使用的是 Windows 7,并且已经下载并安装了 TWS API (9.76.01)(我的 TWS 正在运行 972.1),并按照说明成功安装了 ibapi python:

1) python setup.py sdist
2) python setup.py bdist_wheel
3) python -m pip install --user --upgrade dist/ibapi-9.76.01-py3-none-any.whl

我加载了 VS Code 并从 IB 复制了教程示例代码: https ://cdcdyn.interactivebrokers.com/webinars/TA-2018-TWS-Python-Receiving-Market-Data-Study-Notes.pdf (Youtube 视频:https ://www.youtube.com/watch?v=GmTPDzcko6k )

我使用的示例代码来自文档“为 AAPL 请求流市场数据的示例”的第 2 页

运行代码后,终端上没有输出。但是,在 VS Code 上的“main()”末尾有一条消息,说明以下截图:

Unable to import 'ibapi.client'pylint(import-error)
Unable to import 'ibapi.wrapper'pylint(import-error)
Unable to import 'ibapi.contract'pylint(import-error)
Unable to import 'ibapi.ticktype'pylint(import-error)
Undefined variable 'TestApp'pylint(undefined-variable)

我错过了什么或一些步骤吗?谢谢!

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.ticktype import TickTypeEnum


class TestApp(EWrapper, EClient):
 def __init__(self):
 EClient.__init__(self, self)
 def error(self, reqId, errorCode, errorString):
 print("Error: ", reqId, " ", errorCode, " ", errorString)
 def tickPrice(self, reqId, tickType, price, attrib):
 print("Tick Price. Ticker Id:", reqId, "tickType:",
       TickTypeEnum.to_str(tickType), "Price:", price, end=' ')

 def tickSize(self, reqId, tickType, size):
 print("Tick Size. Ticker Id:", reqId, "tickType:",
       TickTypeEnum.to_str(tickType), "Size:", size)


def main():
 app = TestApp()
 app.connect("127.0.0.1", 7497, 0)
 contract = Contract()
 contract.symbol = "AAPL"
 contract.secType = "STK"
 contract.exchange = "SMART"
 contract.currency = "USD"
 contract.primaryExchange = "NASDAQ"
 # switch to delayed-frozen data if live is not available
 app.reqMarketDataType(4)
 app.reqMktData(1, contract, "", False, False, [])
 app.run()


if __name__ == "__main__":
 main()

在此处输入图像描述

标签: pythonapiinteractive-brokers

解决方案


如果您查看 TWS API 安装,您会发现一个名为 ibapi 的文件夹。这包含定义您缺少的 TWS 类的 Python 模块。您需要设置 PYTHONPATH 环境变量以包含此目录。


推荐阅读