Giter VIP home page Giter VIP logo

vnpy_ib's Introduction

VeighNa框架的InteractiveBrokers交易接口

说明

基于ibapi的10.19.1版本开发的InteractiveBrokers交易接口。

IbGateway中的合约代码支持两种风格:数字代码和字符串代码。

数字代码基于IB平台的ConId,查询方式:在TWS软件中【右键点击任意合约】->【金融产品信息】->【详情】,然后在弹出的网页上即可找到合约的ConId。

字符串代码基于合约的具体描述信息,命名规则和举例:

合约类型 代码规则 代码(symbol) 交易所(exchange)
股票 名称-货币-类别 SPY-USD-STK SMART
外汇 名称-货币-类别 EUR-USD-CASH IDEALPRO
贵金属 名称-货币-类别 XAUUSD-USD-CMDTY SMART
期货 名称-到期年月-货币-类别 ES-202002-USD-FUT GLOBEX
期货(指定乘数) 名称-到期年月-合约乘数-类别 SI-202006-1000-USD-FUT NYMEX
期货期权 名称-到期年月-期权类型-行权价-合约乘数-货币-类别 ES-2020006-C-2430-50-USD-FOP GLOBEX

委托、成交、持仓信息中的合约代码,默认采用数字代码。如果用户使用字符串代码订阅过行情,则使用字符串代码。

安装

安装环境推荐基于3.9.0版本以上的【VeighNa Studio】。

安装ibapi

IB官网下载TWS API的msi安装文件,并运行安装。

找到安装目录下的source\pythonclient文件夹,在cmd中运行下述命令安装:

python setup.py install

安装vnpy_ib

直接使用pip命令:

pip install vnpy_ib

或者下载源代码后,解压后在cmd中运行:

pip install .

使用

以脚本方式启动(script/run.py):

from vnpy.event import EventEngine
from vnpy.trader.engine import MainEngine
from vnpy.trader.ui import MainWindow, create_qapp

from vnpy_ib import IbGateway


def main():
    """主入口函数"""
    qapp = create_qapp()

    event_engine = EventEngine()
    main_engine = MainEngine(event_engine)
    main_engine.add_gateway(IbGateway)

    main_window = MainWindow(main_engine, event_engine)
    main_window.showMaximized()

    qapp.exec()


if __name__ == "__main__":
    main()

vnpy_ib's People

Contributors

edanflame avatar lanceyliao avatar noranhe avatar ruyisee avatar tingle2008 avatar vnpy avatar youyuanrsq avatar zhouyuzhouyu avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

vnpy_ib's Issues

CTA策略初始化 錯誤

TWS:10.19.1j

CTA策略初始化 出現異常訊號:Your API version does not support fractional share size rules. Please upgrade to a minimum version 163. Trimmed value 79.76 to 79
Exception in thread Thread-24 (run):

ib产品类型映射里少了指数类型

PRODUCT_IB2VT: Dict[str, Product] = {
"STK": Product.EQUITY,
"CASH": Product.FOREX,
"CMDTY": Product.SPOT,
"FUT": Product.FUTURES,
"OPT": Product.OPTION,
"FOT": Product.OPTION,
"CONTFUT": Product.FUTURES
}

查了下ib的文档
指数应该是
"IND": Product.INDEX

没有的话会导致在录入指数数据时报错

时间格式

ERROR 1 2174 警告: 您提交的请求包含日期-时间属性,但未明确指定时区。请切换以使用格式为yyyymmdd-hh:mm:ss的协调世界时或使用产品的时区(如US/Eastern)。隐含时区的功能将在下一次API发布时被移除。

这个似乎是新格式,目前代码中是 yyyymmdd hh:mm:ss

window VeighNa Station 启动 Trader 时,盈透启动报错

2024-05-12 21:54:31	--------------------------------------------------
2024-05-12 21:54:31	VeighNa Trader进程启动
2024-05-12 21:54:34	Traceback (most recent call last):
  File "C:\veighna_studio\lib\runpy.py", line 196, in _run_module_as_main
2024-05-12 21:54:34	    return _run_code(code, main_globals, None,
  File "C:\veighna_studio\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "build\bdist.win-amd64\egg\veighna_station\trader.py", line 39, in <module>
2024-05-12 21:54:34	  File "build\bdist.win-amd64\egg\veighna_station\trader.py", line 23, in run_trader
  File "C:\veighna_studio\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\veighna_studio\lib\site-packages\vnpy_ib\__init__.py", line 25, in <module>
    from .ib_gateway import IbGateway
  File "C:\veighna_studio\lib\site-packages\vnpy_ib\ib_gateway.py", line 24, in <module>
    from ibapi.client import EClient
ModuleNotFoundError: No module named 'ibapi'
2024-05-12 21:54:50	VeighNa Trader进程终止

HistoryRequest 是None

Exception in thread Thread-9 (run): Traceback (most recent call last): File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/site-packages/ibapi/client.py", line 263, in run self.decoder.interpret(fields) File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/site-packages/ibapi/decoder.py", line 1296, in interpret handleInfo.processMeth(self, iter(fields)) File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/site-packages/ibapi/decoder.py", line 519, in processHistoricalDataMsg self.wrapper.historicalData(reqId, bar) File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/site-packages/vnpy_ib/ib_gateway.py", line 619, in historicalData symbol=self.history_req.symbol, AttributeError: 'NoneType' object has no attribute 'symbol'

这个应该是api返回了None或者是还没有等到返回值?

ConId合约代码合法性检查

当用户输入的代码时Conid类型的时候,如果里面有非数字(比如尾部有空格或者其他),会导致与TWS或者IbGateway之间的连接断开,必须重启vnpy。所以优化方向有两个:

  1. Conid发送前检查是否是纯数字
    2.代码symbol应该去掉两侧可能出现的空格

timezone问题

有好意思又开一个

更新数据时候

ib_gateway.py

Traceback (most recent call last):
  File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/site-packages/vnpy_datamanager/ui/widget.py", line 384, in update_data
    self.engine.download_bar_data(
  File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/site-packages/vnpy_datamanager/engine.py", line 206, in download_bar_data
    data: List[BarData] = self.main_engine.query_history(
  File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/site-packages/vnpy/trader/engine.py", line 223, in query_history
    return gateway.query_history(req)
  File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/site-packages/vnpy_ib/ib_gateway.py", line 232, in query_history
    return self.api.query_history(req)
  File "/opt/homebrew/Caskroom/miniforge/base/envs/py310/lib/python3.10/site-packages/vnpy_ib/ib_gateway.py", line 773, in query_history
    delta: timedelta = end - req.start
TypeError: can't subtract offset-naive and offset-aware datetimes

换掉pytz的原因?
`@dataclass
class HistoryRequest:
"""
Request sending to specific gateway for querying history data.
"""

symbol: str
exchange: Exchange
start: datetime
end: datetime = None
interval: Interval = None

def __post_init__(self) -> None:
    """"""
    self.vt_symbol: str = f"{self.symbol}.{self.exchange.value}"`

generate_symbol always uses numeric code

generate_symbol seems to be misimplemented now:

if symbol not in self.contracts: symbol = str(ib_contract.conId)

this condition is always true because self.contracts keys contains Exchange, e.g. 'BAS-EUR-STK.SMART'. while symbol does not have exchange information

IB外汇成交后保存状态报错

错误信息如下。委托成交后同步数据时json保存出错。

Traceback (most recent call last):
File "C:\Softwares\veighna_studio\lib\threading.py", line 1016, in _bootstrap_inner
self.run()
File "C:\Softwares\veighna_studio\lib\threading.py", line 953, in run
self._target(*self._args, **self._kwargs)
File "C:\Softwares\veighna_studio\lib\site-packages\vnpy\event\engine.py", line 60, in _run
self._process(event)
File "C:\Softwares\veighna_studio\lib\site-packages\vnpy\event\engine.py", line 73, in _process
[handler(event) for handler in self._handlers[event.type]]
File "C:\Softwares\veighna_studio\lib\site-packages\vnpy\event\engine.py", line 73, in
[handler(event) for handler in self.handlers[event.type]]
File "C:\Softwares\veighna_studio\lib\site-packages\vnpy_ctastrategy\engine.py", line 211, in process_trade_event
self.sync_strategy_data(strategy)
File "C:\Softwares\veighna_studio\lib\site-packages\vnpy_ctastrategy\engine.py", line 842, in sync_strategy_data
save_json(self.data_filename, self.strategy_data)
File "C:\Softwares\veighna_studio\lib\site-packages\vnpy\trader\utility.py", line 119, in save_json
json.dump(
File "C:\Softwares\veighna_studio\lib\json_init
.py", line 179, in dump
for chunk in iterable:
File "C:\Softwares\veighna_studio\lib\json\encoder.py", line 431, in _iterencode
yield from _iterencode_dict(o, _current_indent_level)
File "C:\Softwares\veighna_studio\lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Softwares\veighna_studio\lib\json\encoder.py", line 405, in _iterencode_dict
yield from chunks
File "C:\Softwares\veighna_studio\lib\json\encoder.py", line 438, in _iterencode
o = _default(o)
File "C:\Softwares\veighna_studio\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.class.name} '
TypeError: Object of type int32 is not JSON serializable

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.