qka 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,70 @@
1
+ name: Python package
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ Test:
10
+ runs-on: windows-latest
11
+ permissions: write-all
12
+
13
+ steps:
14
+ - name: Checkout repository
15
+ uses: actions/checkout@v4
16
+ with:
17
+ fetch-depth: 0 # Ensure full history for semantic-release
18
+
19
+ - name: Set up Python 3.10
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: '3.10' # You can specify your required Python version here
23
+
24
+ - name: Install Flit
25
+ run: |
26
+ pip install flit
27
+ shell: bash
28
+
29
+ - name: Check release status
30
+ id: release-status
31
+ run: |
32
+ pip install python-semantic-release
33
+ if semantic-release --noop --strict version; then
34
+ echo "::set-output name=released::true"
35
+ else
36
+ echo "::set-output name=released::false"
37
+ fi
38
+ shell: bash
39
+ env:
40
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
41
+
42
+ - name: Semantic Release Version
43
+ if: steps.release-status.outputs.released == 'true'
44
+ run: |
45
+ semantic-release version
46
+ shell: bash
47
+ env:
48
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
49
+ PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
50
+
51
+ - name: Release to PyPI
52
+ if: steps.release-status.outputs.released == 'true'
53
+ run: |
54
+ flit build
55
+ flit publish --repository pypi
56
+ shell: bash
57
+ env:
58
+ FLIT_USERNAME: __token__
59
+ FLIT_PASSWORD: ${{ secrets.PYPI_TOKEN }}
60
+
61
+ - name: Release to GitHub
62
+ if: steps.release-status.outputs.released == 'true'
63
+ run: |
64
+ git fetch --tags
65
+ for file in ./dist/*; do
66
+ gh release upload "${{ steps.release-status.outputs.tag }}" $file
67
+ done
68
+ shell: bash
69
+ env:
70
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
qka-0.1.0/.gitignore ADDED
@@ -0,0 +1,164 @@
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
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
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
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ #.idea/
163
+
164
+ *.ipynb
@@ -0,0 +1,3 @@
1
+ {
2
+ "editor.tabSize": 4
3
+ }
qka-0.1.0/CHANGELOG.md ADDED
@@ -0,0 +1,23 @@
1
+ # CHANGELOG
2
+
3
+
4
+ ## v0.1.0 (2025-01-19)
5
+
6
+ ### Bug Fixes
7
+
8
+ - 优化 ([`c77eae5`](https://github.com/zsrl/qka/commit/c77eae539e5bd64674a6e280af1eb19c8f9c75e5))
9
+
10
+ ### Features
11
+
12
+ - Qmt服务端与客户端
13
+ ([`23baabf`](https://github.com/zsrl/qka/commit/23baabfc001ed1ac3f24c17cef55f190f86fc23a))
14
+
15
+ - 初始化项目 ([`c6fbea5`](https://github.com/zsrl/qka/commit/c6fbea5eea52311856b67bba48b11c5e298d0cf3))
16
+
17
+ ### Performance Improvements
18
+
19
+ - 初始化包 ([`9ec3368`](https://github.com/zsrl/qka/commit/9ec3368bdf6d866ff5334f379c0e7a2a2c883663))
20
+
21
+ - 初始化框架 ([`e549e45`](https://github.com/zsrl/qka/commit/e549e45c6f4c16ab04076c7854e4cef25013b263))
22
+
23
+ - 增加发布流程 ([`e08523a`](https://github.com/zsrl/qka/commit/e08523a02b08f36bcca339dacac0059b0821eb8e))
qka-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 量化投资技术
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.
qka-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.3
2
+ Name: qka
3
+ Version: 0.1.0
4
+ Summary:
5
+ Author-email: myc <mayuanchi1029@gmail.com>
6
+ Description-Content-Type: text/markdown
7
+ Classifier: License :: OSI Approved :: MIT License
8
+ Requires-Dist: xtquant
9
+ Requires-Dist: fastapi
10
+ Requires-Dist: uvicorn
11
+ Project-URL: Home, https://github.com/zsrl/qka
12
+
13
+ # qka (快量化)
14
+
15
+ 快捷量化助手(Quick Quantitative Assistant)是一个简洁易用,可实操A股的量化交易框架。
16
+
17
+ ## 安装
18
+
19
+ ```bash
20
+ pip install qka
21
+ ```
22
+
23
+ ## 使用方法
24
+
25
+ ### QMTServer
26
+
27
+ ```python
28
+ from qka.server import QMTServer
29
+
30
+ server = QMTServer("YOUR_ACCOUNT_ID", "YOUR_QMT_PATH")
31
+ # 服务器启动时会打印生成的token
32
+ server.start()
33
+ ```
34
+
35
+ ### QMTClient
36
+
37
+ #### 查询
38
+
39
+ ```python
40
+ from qka.client import QMTClient
41
+
42
+ client = QMTClient(token="服务器打印的token")
43
+ # 调用接口
44
+ result = client.api("query_stock_asset")
45
+ ```
46
+
47
+ #### 下单
48
+
49
+ ```python
50
+ from qka.client import QMTClient
51
+ from xtquant import xtconstant
52
+
53
+ client = QMTClient(token="服务器打印的token")
54
+ # 调用接口
55
+ result = client.api("order_stock", stock_code='600000.SH', order_type=xtconstant.STOCK_BUY, order_volume =1000, price_type=xtconstant.FIX_PRICE, price=10.5)
56
+ ```
57
+ <!-- ```python
58
+ datas = qka.data(
59
+ stock_list=[],
60
+ period='tick',
61
+ indicators=[
62
+ 'MA',
63
+ 'BOLL'
64
+ ]
65
+ )
66
+
67
+
68
+ def strategy(bar, bars, borker):
69
+ pass
70
+
71
+ res = qka.backtest(datas, start_time='', end_time='', strategy=strategy)
72
+
73
+ borker = qka.broker(type='qmt', config={})
74
+
75
+ qka.trade(datas, start_time='', strategy=strategy, borker=borker)
76
+
77
+ ``` -->
qka-0.1.0/README.md ADDED
@@ -0,0 +1,65 @@
1
+ # qka (快量化)
2
+
3
+ 快捷量化助手(Quick Quantitative Assistant)是一个简洁易用,可实操A股的量化交易框架。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ pip install qka
9
+ ```
10
+
11
+ ## 使用方法
12
+
13
+ ### QMTServer
14
+
15
+ ```python
16
+ from qka.server import QMTServer
17
+
18
+ server = QMTServer("YOUR_ACCOUNT_ID", "YOUR_QMT_PATH")
19
+ # 服务器启动时会打印生成的token
20
+ server.start()
21
+ ```
22
+
23
+ ### QMTClient
24
+
25
+ #### 查询
26
+
27
+ ```python
28
+ from qka.client import QMTClient
29
+
30
+ client = QMTClient(token="服务器打印的token")
31
+ # 调用接口
32
+ result = client.api("query_stock_asset")
33
+ ```
34
+
35
+ #### 下单
36
+
37
+ ```python
38
+ from qka.client import QMTClient
39
+ from xtquant import xtconstant
40
+
41
+ client = QMTClient(token="服务器打印的token")
42
+ # 调用接口
43
+ result = client.api("order_stock", stock_code='600000.SH', order_type=xtconstant.STOCK_BUY, order_volume =1000, price_type=xtconstant.FIX_PRICE, price=10.5)
44
+ ```
45
+ <!-- ```python
46
+ datas = qka.data(
47
+ stock_list=[],
48
+ period='tick',
49
+ indicators=[
50
+ 'MA',
51
+ 'BOLL'
52
+ ]
53
+ )
54
+
55
+
56
+ def strategy(bar, bars, borker):
57
+ pass
58
+
59
+ res = qka.backtest(datas, start_time='', end_time='', strategy=strategy)
60
+
61
+ borker = qka.broker(type='qmt', config={})
62
+
63
+ qka.trade(datas, start_time='', strategy=strategy, borker=borker)
64
+
65
+ ``` -->
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["flit_core >=3.2,<4"]
3
+ build-backend = "flit_core.buildapi"
4
+
5
+ [project]
6
+ name = "qka"
7
+ version = "0.1.0"
8
+ description = ""
9
+ authors = [{name = "myc", email = "mayuanchi1029@gmail.com"}]
10
+ readme = "README.md"
11
+ license = {file = "LICENSE"}
12
+ classifiers = ["License :: OSI Approved :: MIT License"]
13
+ dependencies = [
14
+ "xtquant",
15
+ "fastapi",
16
+ "uvicorn"
17
+ ]
18
+
19
+ [project.urls]
20
+ Home = "https://github.com/zsrl/qka"
21
+
22
+ [tool.semantic_release]
23
+ version_toml = [
24
+ "pyproject.toml:project.version"
25
+ ]
26
+
27
+ branch = "main"
28
+ upload_to_PyPI = true
29
+ upload_to_release = true
30
+ commit_author = "github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>"
31
+
32
+ [tool.semantic_release.commit_parser_options]
33
+ allowed_tags = [
34
+ "build",
35
+ "chore",
36
+ "ci",
37
+ "docs",
38
+ "feat",
39
+ "fix",
40
+ "perf",
41
+ "style",
42
+ "refactor",
43
+ "test"
44
+ ]
45
+ minor_tags = ["feat"]
46
+ patch_tags = ["fix", "perf"]
@@ -0,0 +1,5 @@
1
+ from qka.data import data
2
+ from qka.backtest import backtest
3
+ from qka.trade import create_trader
4
+
5
+ __all__ = ['data', 'backtest', 'create_trader']
qka-0.1.0/qka/anis.py ADDED
@@ -0,0 +1,6 @@
1
+ # ANSI 转义序列
2
+ RED = "\033[91m"
3
+ GREEN = "\033[92m"
4
+ YELLOW = "\033[93m"
5
+ BLUE = "\033[94m"
6
+ RESET = "\033[0m"
@@ -0,0 +1,3 @@
1
+
2
+ def backtest():
3
+ pass
@@ -0,0 +1,43 @@
1
+ import requests
2
+ from typing import Any, Dict
3
+ from qka.logger import logger
4
+
5
+ class QMTClient:
6
+ def __init__(self, base_url: str = "http://localhost:8000", token: str = None):
7
+ """初始化交易客户端
8
+ Args:
9
+ base_url: API服务器地址,默认为本地8000端口
10
+ token: 访问令牌,必须与服务器的token一致
11
+ """
12
+ self.base_url = base_url.rstrip('/')
13
+ self.session = requests.Session()
14
+ if not token:
15
+ raise ValueError("必须提供访问令牌(token)")
16
+ self.token = token
17
+ self.headers = {"X-Token": self.token}
18
+
19
+ def api(self, method_name: str, **params) -> Any:
20
+ """通用调用接口方法
21
+ Args:
22
+ method_name: 要调用的接口名称
23
+ **params: 接口参数,作为关键字参数传入
24
+ Returns:
25
+ 接口返回的数据
26
+ """
27
+ try:
28
+ response = self.session.post(
29
+ f"{self.base_url}/api/{method_name}",
30
+ json=params or {},
31
+ headers=self.headers
32
+ )
33
+ response.raise_for_status()
34
+ result = response.json()
35
+
36
+ if not result.get('success'):
37
+ raise Exception(f"API调用失败: {result.get('detail')}")
38
+
39
+ return result.get('data')
40
+ except Exception as e:
41
+ logger.error(f"调用 {method_name} 失败: {str(e)}")
42
+ raise
43
+
qka-0.1.0/qka/data.py ADDED
@@ -0,0 +1,54 @@
1
+ import time
2
+ from datetime import datetime
3
+ from xtquant import xtdata
4
+ import numpy as np
5
+ from qka.logger import logger
6
+
7
+ class QMTData:
8
+ def __init__(self, stocks=None, sector=None, indicators=None):
9
+ self.stocks = stocks
10
+ if sector is not None:
11
+ self.stocks = xtdata.get_stock_list_in_sector(sector)
12
+
13
+ self.indicators = indicators
14
+
15
+ def get(self, period, start_time='', end_time=''):
16
+
17
+ for stock in self.stocks:
18
+ xtdata.download_history_data(stock_code=stock, period=period, start_time=start_time, end_time=end_time, incrementally=True)
19
+
20
+ res = xtdata.get_local_data(stock_list=self.stocks, period=period, start_time=start_time, end_time=end_time)
21
+
22
+ return res
23
+
24
+ def subscribe(self, callback):
25
+
26
+ delays = []
27
+
28
+ def task(res):
29
+ for code, item in res.items():
30
+ rate = (item['lastPrice'] - item['lastClose']) / item['lastClose']
31
+ timetag = datetime.fromtimestamp(item['time'] / 1000)
32
+ current_time = datetime.fromtimestamp(time.time())
33
+ delay_seconds = (current_time - timetag).total_seconds()
34
+ if delay_seconds < 1000:
35
+
36
+ # delays.append(delay_seconds)
37
+
38
+ # if len(delays) >= 1_000_000:
39
+ # arr = np.array(delays)
40
+ # mean = arr.mean()
41
+ # delays.clear()
42
+ # logger.info(f'平均延迟 {mean}')
43
+
44
+ if delay_seconds > 3:
45
+ logger.warning(f'{code} 延迟 {delay_seconds}')
46
+
47
+ callback(code, item)
48
+
49
+ xtdata.subscribe_whole_quote(code_list=self.stocks, callback=task)
50
+
51
+ xtdata.run()
52
+
53
+ def data(stocks=None, sector=None, indicators=None):
54
+ return QMTData(stocks, sector, indicators)
@@ -0,0 +1,69 @@
1
+ import logging
2
+ import requests
3
+ import os
4
+ import re
5
+ from datetime import date
6
+
7
+ formatter = logging.Formatter('[%(levelname)s][%(asctime)s]%(message)s', datefmt='%Y-%m-%d %H:%M:%S')
8
+
9
+ class RemoveAnsiEscapeCodes(logging.Filter):
10
+ def filter(self, record):
11
+ record.msg = re.sub(r'\033\[[0-9;]*m', '', str(record.msg))
12
+ return True
13
+
14
+ def create_logger():
15
+
16
+ logger = logging.getLogger('log')
17
+ logger.setLevel(logging.DEBUG)
18
+
19
+ stream_handler = logging.StreamHandler()
20
+ stream_handler.setFormatter(formatter)
21
+ logger.addHandler(stream_handler)
22
+
23
+ # 创建日志文件夹(如果不存在)
24
+ log_dir = 'logs'
25
+ if not os.path.exists(log_dir):
26
+ os.makedirs(log_dir)
27
+
28
+ # 创建文件处理器,并将日志写入文件
29
+ file_handler = logging.FileHandler(f"{log_dir}/{date.today().strftime('%Y-%m-%d')}.log", encoding='utf-8')
30
+ file_handler.setLevel(logging.DEBUG)
31
+ file_handler.setFormatter(formatter)
32
+ file_handler.addFilter(RemoveAnsiEscapeCodes())
33
+ logger.addHandler(file_handler)
34
+
35
+ return logger
36
+
37
+
38
+ class WeChatHandler(logging.Handler):
39
+ def __init__(self, webhook_url):
40
+ super().__init__()
41
+ self.webhook_url = webhook_url
42
+
43
+ def emit(self, record):
44
+ log_entry = self.format(record)
45
+ payload = {
46
+ "msgtype": "text",
47
+ "text": {
48
+ "content": log_entry
49
+ }
50
+ }
51
+ try:
52
+ response = requests.post(self.webhook_url, json=payload)
53
+ response.raise_for_status()
54
+ except requests.exceptions.RequestException as e:
55
+ print(f"Failed to send log to WeChat: {e}")
56
+
57
+ def add_wechat_handler(logger, level, wechat_webhook_url):
58
+
59
+ if wechat_webhook_url is not None:
60
+
61
+ # 创建企业微信处理器,并将日志发送到企业微信
62
+ wechat_handler = WeChatHandler(wechat_webhook_url)
63
+ wechat_handler.setLevel(level or logging.INFO)
64
+ wechat_handler.setFormatter(formatter)
65
+ wechat_handler.addFilter(RemoveAnsiEscapeCodes())
66
+ logger.addHandler(wechat_handler)
67
+
68
+
69
+ logger = create_logger()
@@ -0,0 +1,126 @@
1
+ from fastapi import FastAPI, HTTPException, Header, Depends
2
+ from pydantic import BaseModel
3
+ import inspect
4
+ from typing import Any, Dict
5
+ from qka.trade import create_trader
6
+ import uvicorn
7
+ import uuid
8
+ import hashlib
9
+
10
+ class QMTServer:
11
+ def __init__(self, account_id: str, mini_qmt_path: str, host: str = "0.0.0.0", port: int = 8000, token: str = None):
12
+ """初始化交易服务器
13
+ Args:
14
+ account_id: 账户ID
15
+ mini_qmt_path: miniQMT路径
16
+ host: 服务器地址,默认0.0.0.0
17
+ port: 服务器端口,默认8000
18
+ token: 可选的自定义token
19
+ """
20
+ self.account_id = account_id
21
+ self.mini_qmt_path = mini_qmt_path
22
+ self.host = host
23
+ self.port = port
24
+ self.app = FastAPI()
25
+ self.trader = None
26
+ self.account = None
27
+ self.token = token if token else self.generate_token() # 使用自定义token或生成固定token
28
+ print(f"\n授权Token: {self.token}\n") # 打印token供客户端使用
29
+
30
+ def generate_token(self) -> str:
31
+ """生成基于机器码的固定token"""
32
+ # 获取机器码(例如MAC地址)
33
+ mac = uuid.getnode()
34
+ # 将机器码转换为字符串
35
+ mac_str = str(mac)
36
+ # 使用SHA256哈希生成固定长度的token
37
+ token = hashlib.sha256(mac_str.encode()).hexdigest()
38
+ return token
39
+
40
+ async def verify_token(self, x_token: str = Header(...)):
41
+ """验证token的依赖函数"""
42
+ if x_token != self.token:
43
+ raise HTTPException(status_code=401, detail="无效的Token")
44
+ return x_token
45
+
46
+ def init_trader(self):
47
+ """初始化交易对象"""
48
+ self.trader, self.account = create_trader(self.account_id, self.mini_qmt_path)
49
+
50
+ def convert_to_dict(self, obj):
51
+ """将结果转换为可序列化的字典"""
52
+ # 如果是基本类型,直接返回
53
+ if isinstance(obj, (int, float, str, bool)):
54
+ return obj
55
+ # 如果已经是字典类型,直接返回
56
+ elif isinstance(obj, dict):
57
+ return obj
58
+ # 如果是列表或元组,递归转换每个元素
59
+ elif isinstance(obj, (list, tuple)):
60
+ return [self.convert_to_dict(item) for item in obj]
61
+ # 如果是自定义对象,获取所有公开属性
62
+ elif hasattr(obj, '__dir__'):
63
+ attrs = obj.__dir__()
64
+ # 过滤掉内部属性和方法
65
+ public_attrs = {attr: getattr(obj, attr)
66
+ for attr in attrs
67
+ if not attr.startswith('_') and not callable(getattr(obj, attr))}
68
+ return public_attrs
69
+ # 其他类型直接返回
70
+ return str(obj) # 将无法处理的类型转换为字符串
71
+
72
+ def convert_method_to_endpoint(self, method_name: str, method):
73
+ """将 XtQuantTrader 方法转换为 FastAPI 端点"""
74
+ sig = inspect.signature(method)
75
+ param_names = list(sig.parameters.keys())
76
+
77
+ # 创建动态的请求模型
78
+ class_fields = {
79
+ '__annotations__': {} # 添加类型注解字典
80
+ }
81
+
82
+ for param in param_names:
83
+ if param in ['self', 'account']:
84
+ continue
85
+ class_fields['__annotations__'][param] = Any
86
+ class_fields[param] = None
87
+
88
+ RequestModel = type(f'{method_name}Request', (BaseModel,), class_fields)
89
+
90
+ async def endpoint(request: RequestModel, token: str = Depends(self.verify_token)):
91
+ try:
92
+ params = request.dict(exclude_unset=True)
93
+ if 'account' in param_names:
94
+ params['account'] = self.account
95
+ result = getattr(self.trader, method_name)(**params)
96
+ converted_result = self.convert_to_dict(result)
97
+ return {'success': True, 'data': converted_result}
98
+ except Exception as e:
99
+ raise HTTPException(status_code=500, detail=str(e))
100
+
101
+ self.app.post(f'/api/{method_name}')(endpoint)
102
+
103
+ def setup_routes(self):
104
+ """设置所有路由"""
105
+ trader_methods = inspect.getmembers(
106
+ self.trader.__class__,
107
+ predicate=lambda x: inspect.isfunction(x) or inspect.ismethod(x)
108
+ )
109
+
110
+ excluded_methods = {'__init__', '__del__', 'register_callback', 'start', 'stop',
111
+ 'connect', 'sleep', 'run_forever', 'set_relaxed_response_order_enabled'}
112
+
113
+ for method_name, method in trader_methods:
114
+ if not method_name.startswith('_') and method_name not in excluded_methods:
115
+ self.convert_method_to_endpoint(method_name, method)
116
+
117
+ def start(self):
118
+ """启动服务器"""
119
+ self.init_trader()
120
+ self.setup_routes()
121
+ uvicorn.run(self.app, host=self.host, port=self.port)
122
+
123
+ def qmt_server(account_id: str, mini_qmt_path: str, host: str = "0.0.0.0", port: int = 8000, token: str = None):
124
+ """快速创建并启动服务器的便捷函数"""
125
+ server = QMTServer(account_id, mini_qmt_path, host, port, token)
126
+ server.start()
qka-0.1.0/qka/trade.py ADDED
@@ -0,0 +1,71 @@
1
+ from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback
2
+ from xtquant.xttype import StockAccount
3
+ import random
4
+ from qka.utils import timestamp_to_datetime_string, parse_order_type, convert_to_current_date
5
+ from qka.anis import RED, GREEN, YELLOW, BLUE, RESET
6
+ from qka.logger import logger
7
+
8
+ error_orders = []
9
+
10
+ class MyXtQuantTraderCallback(XtQuantTraderCallback):
11
+ def on_disconnected(self):
12
+ """
13
+ 连接状态回调
14
+ :return:
15
+ """
16
+ print("connection lost")
17
+ def on_stock_order(self, order):
18
+ """
19
+ 委托信息推送
20
+ :param order: XtOrder对象
21
+ :return:
22
+ """
23
+ # 委托
24
+ if order.order_status == 50:
25
+ logger.info(f"{BLUE}【已委托】{RESET} {parse_order_type(order.order_type)} 代码:{order.stock_code} 名称:{order.order_remark} 委托价格:{order.price:.2f} 委托数量:{order.order_volume} 订单编号:{order.order_id} 委托时间:{timestamp_to_datetime_string(convert_to_current_date(order.order_time))}")
26
+ elif order.order_status == 53 or order.order_status == 54:
27
+ logger.warning(f"{YELLOW}【已撤单】{RESET} {parse_order_type(order.order_type)} 代码:{order.stock_code} 名称:{order.order_remark} 委托价格:{order.price:.2f} 委托数量:{order.order_volume} 订单编号:{order.order_id} 委托时间:{timestamp_to_datetime_string(convert_to_current_date(order.order_time))}")
28
+
29
+ def on_stock_trade(self, trade):
30
+ """
31
+ 成交信息推送
32
+ :param trade: XtTrade对象
33
+ :return:
34
+ """
35
+ logger.info(f"{GREEN}【已成交】{RESET} {parse_order_type(trade.order_type)} 代码:{trade.stock_code} 名称:{trade.order_remark} 成交价格:{trade.traded_price:.2f} 成交数量:{trade.traded_volume} 成交编号:{trade.order_id} 成交时间:{timestamp_to_datetime_string(convert_to_current_date(trade.traded_time))}")
36
+
37
+ def on_order_error(self, data):
38
+ if data.order_id in error_orders:
39
+ return
40
+ error_orders.append(data.order_id)
41
+ logger.error(f"{RED}【委托失败】{RESET}错误信息:{data.error_msg.strip()}")
42
+
43
+ def on_cancel_error(self, data):
44
+ if data.order_id in error_orders:
45
+ return
46
+ error_orders.append(data.order_id)
47
+ logger.error(f"{RED}【撤单失败】{RESET}错误信息:{data.error_msg.strip()}")
48
+
49
+
50
+ def create_trader(account_id, mini_qmt_path):
51
+ # 创建session_id
52
+ session_id = int(random.randint(100000, 999999))
53
+ # 创建交易对象
54
+ xt_trader = XtQuantTrader(mini_qmt_path, session_id)
55
+ # 启动交易对象
56
+ xt_trader.start()
57
+ # 连接客户端
58
+ connect_result = xt_trader.connect()
59
+
60
+ if connect_result == 0:
61
+ logger.debug(f"{GREEN}【miniQMT连接成功】{RESET} 路径:{mini_qmt_path}")
62
+
63
+ # 创建账号对象
64
+ account = StockAccount(account_id)
65
+ # 订阅账号
66
+ xt_trader.subscribe(account)
67
+ logger.debug(f"{GREEN}【账号订阅成功】{RESET} 账号ID:{account_id}")
68
+ # 注册回调类
69
+ xt_trader.register_callback(MyXtQuantTraderCallback())
70
+
71
+ return xt_trader, account
qka-0.1.0/qka/utils.py ADDED
@@ -0,0 +1,50 @@
1
+ from xtquant import xtconstant
2
+ from datetime import datetime
3
+ from qka.anis import RED, GREEN, YELLOW, BLUE, RESET
4
+
5
+ def add_stock_suffix(stock_code):
6
+ """
7
+ 为给定的股票代码添加相应的后缀。
8
+ """
9
+ # 检查股票代码是否为6位数字
10
+ if len(stock_code) != 6 or not stock_code.isdigit():
11
+ raise ValueError("股票代码必须是6位数字")
12
+
13
+ # 根据股票代码的前缀添加相应的后缀
14
+ if stock_code.startswith("00") or stock_code.startswith("30") or stock_code.startswith("15") or stock_code.startswith("16") or stock_code.startswith("18") or stock_code.startswith("12"):
15
+ return f"{stock_code}.SZ" # 深圳证券交易所
16
+ elif stock_code.startswith("60") or stock_code.startswith("68") or stock_code.startswith("11"):
17
+ return f"{stock_code}.SH" # 上海证券交易所
18
+ elif stock_code.startswith("83") or stock_code.startswith("43"):
19
+ return f"{stock_code}.BJ" # 北京证券交易所
20
+
21
+ return f"{stock_code}.SH"
22
+
23
+ def timestamp_to_datetime_string(timestamp):
24
+ """
25
+ 将时间戳转换为时间字符串。
26
+
27
+ :param timestamp: 时间戳(秒级)
28
+ :return: 格式化的时间字符串 'YYYY-MM-DD HH:MM:SS'
29
+ """
30
+ dt_object = datetime.fromtimestamp(timestamp)
31
+ time_string = dt_object.strftime('%Y-%m-%d %H:%M:%S')
32
+ return time_string
33
+
34
+ def parse_order_type(order_type):
35
+ if order_type == xtconstant.STOCK_BUY:
36
+ return f"{RED}买入{RESET}"
37
+ elif order_type == xtconstant.STOCK_SELL:
38
+ return f"{GREEN}卖出{RESET}"
39
+
40
+ def convert_to_current_date(timestamp):
41
+ # 将时间戳转换为 datetime 对象
42
+ dt = datetime.fromtimestamp(timestamp)
43
+
44
+ # 获取当前日期
45
+ current_date = datetime.now().date()
46
+
47
+ # 创建一个新的 datetime 对象,使用当前日期和原始时间戳的时间部分
48
+ new_dt = datetime.combine(current_date, dt.time())
49
+
50
+ return new_dt.timestamp()
qka-0.1.0/test.py ADDED
@@ -0,0 +1,4 @@
1
+ from qka.server import QMTServer
2
+
3
+ server = QMTServer(account_id='55003152', mini_qmt_path=r'D:\国金QMT交易端模拟\userdata_mini')
4
+ server.start()