├── .flake8
├── .gitignore
├── CHANGELOG.md
├── LICENSE
├── README.md
├── setup.cfg
├── setup.py
└── vnpy_chartwizard
├── __init__.py
├── engine.py
└── ui
├── __init__.py
├── cw.ico
└── widget.py
/.flake8:
--------------------------------------------------------------------------------
1 | [flake8]
2 | exclude = build,__pycache__,__init__.py
3 | ignore =
4 | E501 line too long, fixed by black
5 | W503 line break before binary operator
6 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # 1.0.5版本
2 |
3 | 1. 替换所有的Qt信号pyqtSignal为Signal
4 |
5 | # 1.0.4版本
6 |
7 | 1. 增加单个图表关闭支持
8 | 2. 修复vnpy_spreadtrading升级后报错找不到'to_tick'的问题
9 |
10 | # 1.0.3版本
11 |
12 | 1. 使用zoneinfo替换pytz库
13 | 2. 调整安装脚本setup.cfg,添加Python版本限制
14 |
15 | # 1.0.2版本
16 |
17 | 1. 将模块的图标文件信息,改为完整路径字符串
18 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015-present, Xiaoyou Chen
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # VeighNa框架的K线图表模块
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 | ## 说明
15 |
16 | ChartWizard是用于实时K线图表展示的功能模块,用户可以通过其UI界面查看实时和历史K线行情,目前只支持显示1分钟级别的K线数据,实时K线(最新的一根K线)为Tick级刷新。
17 |
18 | ## 安装
19 |
20 | 安装环境推荐基于3.9.0版本以上的【[**VeighNa Studio**](https://www.vnpy.com)】。
21 |
22 | 直接使用pip命令:
23 |
24 | ```
25 | pip install vnpy_chartwizard
26 | ```
27 |
28 |
29 | 或者下载源代码后,解压后在cmd中运行:
30 |
31 | ```
32 | pip install .
33 | ```
34 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | name = vnpy_chartwizard
3 | version = 1.0.5
4 | url = https://www.vnpy.com
5 | license = MIT
6 | author = Xiaoyou Chen
7 | author_email = xiaoyou.chen@mail.vnpy.com
8 | description = Chart wizard application for VeighNa quant trading framework.
9 | long_description = file: README.md
10 | long_description_content_type = text/markdown
11 | keywords =
12 | quant
13 | quantitative
14 | investment
15 | trading
16 | algotrading
17 | classifiers =
18 | Development Status :: 5 - Production/Stable
19 | Operating System :: OS Independent
20 | Programming Language :: Python :: 3
21 | Programming Language :: Python :: 3.10
22 | Programming Language :: Python :: 3.11
23 | Programming Language :: Python :: 3.12
24 | Programming Language :: Python :: 3.13
25 | Topic :: Office/Business :: Financial :: Investment
26 | Programming Language :: Python :: Implementation :: CPython
27 | License :: OSI Approved :: MIT License
28 | Natural Language :: Chinese (Simplified)
29 |
30 | [options]
31 | packages = find:
32 | zip_safe = False
33 | python_requires = >=3.7
34 | install_requires =
35 | pyqtgraph
36 |
37 | [options.package_data]
38 | * = *.ico
39 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 |
4 | setup()
5 |
--------------------------------------------------------------------------------
/vnpy_chartwizard/__init__.py:
--------------------------------------------------------------------------------
1 | # The MIT License (MIT)
2 | #
3 | # Copyright (c) 2015-present, Xiaoyou Chen
4 | #
5 | # Permission is hereby granted, free of charge, to any person obtaining a copy
6 | # of this software and associated documentation files (the "Software"), to deal
7 | # in the Software without restriction, including without limitation the rights
8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | # copies of the Software, and to permit persons to whom the Software is
10 | # furnished to do so, subject to the following conditions:
11 | #
12 | # The above copyright notice and this permission notice shall be included in all
13 | # copies or substantial portions of the Software.
14 | #
15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | # SOFTWARE.
22 |
23 |
24 | from pathlib import Path
25 |
26 | from vnpy.trader.app import BaseApp
27 |
28 | from .engine import ChartWizardEngine, APP_NAME
29 |
30 |
31 | class ChartWizardApp(BaseApp):
32 | """"""
33 |
34 | app_name: str = APP_NAME
35 | app_module: str = __module__
36 | app_path: Path = Path(__file__).parent
37 | display_name: str = "K线图表"
38 | engine_class: ChartWizardEngine = ChartWizardEngine
39 | widget_name: str = "ChartWizardWidget"
40 | icon_name: str = str(app_path.joinpath("ui", "cw.ico"))
41 |
--------------------------------------------------------------------------------
/vnpy_chartwizard/engine.py:
--------------------------------------------------------------------------------
1 | from datetime import datetime
2 | from threading import Thread
3 | from typing import List, Optional
4 |
5 | from vnpy.event import Event, EventEngine
6 | from vnpy.trader.engine import BaseEngine, MainEngine
7 | from vnpy.trader.constant import Interval
8 | from vnpy.trader.object import BarData, HistoryRequest, ContractData
9 | from vnpy.trader.utility import extract_vt_symbol
10 | from vnpy.trader.database import get_database, BaseDatabase
11 | from vnpy.trader.datafeed import get_datafeed, BaseDatafeed
12 |
13 |
14 | APP_NAME = "ChartWizard"
15 |
16 | EVENT_CHART_HISTORY = "eChartHistory"
17 |
18 |
19 | class ChartWizardEngine(BaseEngine):
20 | """
21 | For running chartWizard.
22 | """
23 |
24 | def __init__(self, main_engine: MainEngine, event_engine: EventEngine) -> None:
25 | """"""
26 | super().__init__(main_engine, event_engine, APP_NAME)
27 |
28 | self.datafeed: BaseDatafeed = get_datafeed()
29 | self.database: BaseDatabase = get_database()
30 |
31 | def query_history(
32 | self,
33 | vt_symbol: str,
34 | interval: Interval,
35 | start: datetime,
36 | end: datetime
37 | ) -> None:
38 | """"""
39 | thread: Thread = Thread(
40 | target=self._query_history,
41 | args=[vt_symbol, interval, start, end]
42 | )
43 | thread.start()
44 |
45 | def _query_history(
46 | self,
47 | vt_symbol: str,
48 | interval: Interval,
49 | start: datetime,
50 | end: datetime
51 | ) -> None:
52 | """"""
53 | symbol, exchange = extract_vt_symbol(vt_symbol)
54 |
55 | req: HistoryRequest = HistoryRequest(
56 | symbol=symbol,
57 | exchange=exchange,
58 | interval=interval,
59 | start=start,
60 | end=end
61 | )
62 |
63 | contract: Optional[ContractData] = self.main_engine.get_contract(vt_symbol)
64 | if contract:
65 | if contract.history_data:
66 | data: Optional[List[BarData]] = self.main_engine.query_history(req, contract.gateway_name)
67 | else:
68 | data: Optional[List[BarData]] = self.datafeed.query_bar_history(req)
69 | else:
70 | data: List[BarData] = self.database.load_bar_data(
71 | symbol,
72 | exchange,
73 | interval,
74 | start,
75 | end
76 | )
77 |
78 | event: Event = Event(EVENT_CHART_HISTORY, data)
79 | self.event_engine.put(event)
80 |
--------------------------------------------------------------------------------
/vnpy_chartwizard/ui/__init__.py:
--------------------------------------------------------------------------------
1 | from .widget import ChartWizardWidget
2 |
--------------------------------------------------------------------------------
/vnpy_chartwizard/ui/cw.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/vnpy/vnpy_chartwizard/b7e909e844a0fc1194963a8ebe4aa28ee99ebe49/vnpy_chartwizard/ui/cw.ico
--------------------------------------------------------------------------------
/vnpy_chartwizard/ui/widget.py:
--------------------------------------------------------------------------------
1 | from copy import copy
2 | from typing import Dict, List, Optional
3 | from datetime import datetime, timedelta
4 | from tzlocal import get_localzone_name
5 |
6 | from vnpy.event import EventEngine, Event
7 | from vnpy.chart import ChartWidget, CandleItem, VolumeItem
8 | from vnpy.trader.engine import MainEngine
9 | from vnpy.trader.ui import QtWidgets, QtCore
10 | from vnpy.trader.event import EVENT_TICK
11 | from vnpy.trader.object import ContractData, TickData, BarData, SubscribeRequest
12 | from vnpy.trader.utility import BarGenerator, ZoneInfo
13 | from vnpy.trader.constant import Interval, Exchange
14 | from vnpy_spreadtrading.base import SpreadItem, EVENT_SPREAD_DATA
15 |
16 | from ..engine import APP_NAME, EVENT_CHART_HISTORY, ChartWizardEngine
17 |
18 |
19 | class ChartWizardWidget(QtWidgets.QWidget):
20 | """K线图表控件"""
21 |
22 | signal_tick: QtCore.Signal = QtCore.Signal(Event)
23 | signal_spread: QtCore.Signal = QtCore.Signal(Event)
24 | signal_history: QtCore.Signal = QtCore.Signal(Event)
25 |
26 | def __init__(self, main_engine: MainEngine, event_engine: EventEngine) -> None:
27 | """构造函数"""
28 | super().__init__()
29 |
30 | self.main_engine: MainEngine = main_engine
31 | self.event_engine: EventEngine = event_engine
32 | self.chart_engine: ChartWizardEngine = main_engine.get_engine(APP_NAME)
33 |
34 | self.bgs: Dict[str, BarGenerator] = {}
35 | self.charts: Dict[str, ChartWidget] = {}
36 |
37 | self.init_ui()
38 | self.register_event()
39 |
40 | def init_ui(self) -> None:
41 | """初始化界面"""
42 | self.setWindowTitle("K线图表")
43 |
44 | self.tab: QtWidgets.QTabWidget = QtWidgets.QTabWidget()
45 |
46 | self.tab.setTabsClosable(True)
47 | self.tab.tabCloseRequested.connect(self.close_tab)
48 |
49 | self.symbol_line: QtWidgets.QLineEdit = QtWidgets.QLineEdit()
50 |
51 | self.button: QtWidgets.QPushButton = QtWidgets.QPushButton("新建图表")
52 | self.button.clicked.connect(self.new_chart)
53 |
54 | hbox: QtWidgets.QHBoxLayout = QtWidgets.QHBoxLayout()
55 | hbox.addWidget(QtWidgets.QLabel("本地代码"))
56 | hbox.addWidget(self.symbol_line)
57 | hbox.addWidget(self.button)
58 | hbox.addStretch()
59 |
60 | vbox: QtWidgets.QVBoxLayout = QtWidgets.QVBoxLayout()
61 | vbox.addLayout(hbox)
62 | vbox.addWidget(self.tab)
63 |
64 | self.setLayout(vbox)
65 |
66 | def create_chart(self) -> ChartWidget:
67 | """创建图表对象"""
68 | chart: ChartWidget = ChartWidget()
69 | chart.add_plot("candle", hide_x_axis=True)
70 | chart.add_plot("volume", maximum_height=200)
71 | chart.add_item(CandleItem, "candle", "candle")
72 | chart.add_item(VolumeItem, "volume", "volume")
73 | chart.add_cursor()
74 | return chart
75 |
76 | def show(self) -> None:
77 | """最大化显示"""
78 | self.showMaximized()
79 |
80 | def close_tab(self, index: int) -> None:
81 | """关闭标签"""
82 | vt_symbol: str = self.tab.tabText(index)
83 |
84 | self.tab.removeTab(index)
85 | self.charts.pop(vt_symbol)
86 | self.bgs.pop(vt_symbol)
87 |
88 | def new_chart(self) -> None:
89 | """创建新的图表"""
90 | # Filter invalid vt_symbol
91 | vt_symbol: str = self.symbol_line.text()
92 | if not vt_symbol:
93 | return
94 |
95 | if vt_symbol in self.charts:
96 | return
97 |
98 | if "LOCAL" not in vt_symbol:
99 | contract: Optional[ContractData] = self.main_engine.get_contract(vt_symbol)
100 | if not contract:
101 | return
102 |
103 | # Create new chart
104 | self.bgs[vt_symbol] = BarGenerator(self.on_bar)
105 |
106 | chart: ChartWidget = self.create_chart()
107 | self.charts[vt_symbol] = chart
108 |
109 | self.tab.addTab(chart, vt_symbol)
110 |
111 | # Query history data
112 | end: datetime = datetime.now(ZoneInfo(get_localzone_name()))
113 | start: datetime = end - timedelta(days=5)
114 |
115 | self.chart_engine.query_history(
116 | vt_symbol,
117 | Interval.MINUTE,
118 | start,
119 | end
120 | )
121 |
122 | def register_event(self) -> None:
123 | """注册事件监听"""
124 | self.signal_tick.connect(self.process_tick_event)
125 | self.signal_history.connect(self.process_history_event)
126 | self.signal_spread.connect(self.process_spread_event)
127 |
128 | self.event_engine.register(EVENT_CHART_HISTORY, self.signal_history.emit)
129 | self.event_engine.register(EVENT_TICK, self.signal_tick.emit)
130 | self.event_engine.register(EVENT_SPREAD_DATA, self.signal_spread.emit)
131 |
132 | def process_tick_event(self, event: Event) -> None:
133 | """处理Tick事件"""
134 | tick: TickData = event.data
135 | bg: Optional[BarGenerator] = self.bgs.get(tick.vt_symbol, None)
136 |
137 | if bg:
138 | bg.update_tick(tick)
139 |
140 | chart: ChartWidget = self.charts[tick.vt_symbol]
141 | bar: BarData = copy(bg.bar)
142 | bar.datetime = bar.datetime.replace(second=0, microsecond=0)
143 | chart.update_bar(bar)
144 |
145 | def process_history_event(self, event: Event) -> None:
146 | """处理历史事件"""
147 | history: List[BarData] = event.data
148 | if not history:
149 | return
150 |
151 | bar: BarData = history[0]
152 | chart: ChartWidget = self.charts[bar.vt_symbol]
153 | chart.update_history(history)
154 |
155 | # Subscribe following data update
156 | contract: Optional[ContractData] = self.main_engine.get_contract(bar.vt_symbol)
157 | if contract:
158 | req: SubscribeRequest = SubscribeRequest(
159 | contract.symbol,
160 | contract.exchange
161 | )
162 | self.main_engine.subscribe(req, contract.gateway_name)
163 |
164 | def process_spread_event(self, event: Event) -> None:
165 | """处理价差事件"""
166 | spread_item: SpreadItem = event.data
167 | tick: TickData = TickData(
168 | symbol=spread_item.name,
169 | exchange=Exchange.LOCAL,
170 | datetime=spread_item.datetime,
171 | name=spread_item.name,
172 | last_price=(spread_item.bid_price + spread_item.ask_price) / 2,
173 | bid_price_1=spread_item.bid_price,
174 | ask_price_1=spread_item.ask_price,
175 | bid_volume_1=spread_item.bid_volume,
176 | ask_volume_1=spread_item.ask_volume,
177 | gateway_name="SPREAD"
178 | )
179 |
180 | bg: Optional[BarGenerator] = self.bgs.get(tick.vt_symbol, None)
181 | if bg:
182 | bg.update_tick(tick)
183 |
184 | chart: ChartWidget = self.charts[tick.vt_symbol]
185 | bar: BarData = copy(bg.bar)
186 | bar.datetime = bar.datetime.replace(second=0, microsecond=0)
187 | chart.update_bar(bar)
188 |
189 | def on_bar(self, bar: BarData) -> None:
190 | """K线合成回调"""
191 | chart: ChartWidget = self.charts[bar.vt_symbol]
192 | chart.update_bar(bar)
193 |
--------------------------------------------------------------------------------