kaq-quant-common 0.1.97__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.
Files changed (66) hide show
  1. kaq_quant_common-0.1.97/PKG-INFO +66 -0
  2. kaq_quant_common-0.1.97/README.md +21 -0
  3. kaq_quant_common-0.1.97/kaq_quant_common/__init__.py +0 -0
  4. kaq_quant_common-0.1.97/kaq_quant_common/api/__init__.py +0 -0
  5. kaq_quant_common-0.1.97/kaq_quant_common/api/common/__init__.py +1 -0
  6. kaq_quant_common-0.1.97/kaq_quant_common/api/common/api_interface.py +38 -0
  7. kaq_quant_common-0.1.97/kaq_quant_common/api/common/auth.py +118 -0
  8. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/__init__.py +0 -0
  9. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/api_client_base.py +42 -0
  10. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/api_server_base.py +135 -0
  11. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/instruction/helper/order_helper.py +324 -0
  12. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/instruction/instruction_client.py +86 -0
  13. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/instruction/instruction_server_base.py +154 -0
  14. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/instruction/models/__init__.py +17 -0
  15. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/instruction/models/account.py +49 -0
  16. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/instruction/models/order.py +248 -0
  17. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/instruction/models/position.py +70 -0
  18. kaq_quant_common-0.1.97/kaq_quant_common/api/rest/instruction/models/transfer.py +32 -0
  19. kaq_quant_common-0.1.97/kaq_quant_common/api/ws/__init__.py +0 -0
  20. kaq_quant_common-0.1.97/kaq_quant_common/api/ws/exchange/models.py +23 -0
  21. kaq_quant_common-0.1.97/kaq_quant_common/api/ws/exchange/ws_exchange_client.py +31 -0
  22. kaq_quant_common-0.1.97/kaq_quant_common/api/ws/exchange/ws_exchange_server.py +440 -0
  23. kaq_quant_common-0.1.97/kaq_quant_common/api/ws/instruction/__init__.py +0 -0
  24. kaq_quant_common-0.1.97/kaq_quant_common/api/ws/instruction/ws_instruction_client.py +82 -0
  25. kaq_quant_common-0.1.97/kaq_quant_common/api/ws/instruction/ws_instruction_server_base.py +139 -0
  26. kaq_quant_common-0.1.97/kaq_quant_common/api/ws/models.py +46 -0
  27. kaq_quant_common-0.1.97/kaq_quant_common/api/ws/ws_client_base.py +235 -0
  28. kaq_quant_common-0.1.97/kaq_quant_common/api/ws/ws_server_base.py +288 -0
  29. kaq_quant_common-0.1.97/kaq_quant_common/common/__init__.py +0 -0
  30. kaq_quant_common-0.1.97/kaq_quant_common/common/ddb_table_monitor.py +106 -0
  31. kaq_quant_common-0.1.97/kaq_quant_common/common/http_monitor.py +69 -0
  32. kaq_quant_common-0.1.97/kaq_quant_common/common/modules/limit_order_helper.py +81 -0
  33. kaq_quant_common-0.1.97/kaq_quant_common/common/modules/limit_order_symbol_monitor.py +76 -0
  34. kaq_quant_common-0.1.97/kaq_quant_common/common/modules/limit_order_symbol_monitor_group.py +69 -0
  35. kaq_quant_common-0.1.97/kaq_quant_common/common/monitor_base.py +84 -0
  36. kaq_quant_common-0.1.97/kaq_quant_common/common/monitor_group.py +97 -0
  37. kaq_quant_common-0.1.97/kaq_quant_common/common/redis_table_monitor.py +123 -0
  38. kaq_quant_common-0.1.97/kaq_quant_common/common/statistics/funding_rate_history_statistics.py +208 -0
  39. kaq_quant_common-0.1.97/kaq_quant_common/common/statistics/kline_history_statistics.py +211 -0
  40. kaq_quant_common-0.1.97/kaq_quant_common/common/ws_wrapper.py +21 -0
  41. kaq_quant_common-0.1.97/kaq_quant_common/config/config.yaml +5 -0
  42. kaq_quant_common-0.1.97/kaq_quant_common/resources/__init__.py +0 -0
  43. kaq_quant_common-0.1.97/kaq_quant_common/resources/kaq_ddb_pool_stream_read_resources.py +56 -0
  44. kaq_quant_common-0.1.97/kaq_quant_common/resources/kaq_ddb_stream_init_resources.py +88 -0
  45. kaq_quant_common-0.1.97/kaq_quant_common/resources/kaq_ddb_stream_read_resources.py +81 -0
  46. kaq_quant_common-0.1.97/kaq_quant_common/resources/kaq_ddb_stream_write_resources.py +250 -0
  47. kaq_quant_common-0.1.97/kaq_quant_common/resources/kaq_mysql_init_resources.py +23 -0
  48. kaq_quant_common-0.1.97/kaq_quant_common/resources/kaq_mysql_resources.py +346 -0
  49. kaq_quant_common-0.1.97/kaq_quant_common/resources/kaq_postgresql_resources.py +58 -0
  50. kaq_quant_common-0.1.97/kaq_quant_common/resources/kaq_quant_hive_resources.py +107 -0
  51. kaq_quant_common-0.1.97/kaq_quant_common/resources/kaq_redis_resources.py +117 -0
  52. kaq_quant_common-0.1.97/kaq_quant_common/utils/__init__.py +0 -0
  53. kaq_quant_common-0.1.97/kaq_quant_common/utils/dagster_job_check_utils.py +29 -0
  54. kaq_quant_common-0.1.97/kaq_quant_common/utils/dagster_utils.py +19 -0
  55. kaq_quant_common-0.1.97/kaq_quant_common/utils/date_util.py +204 -0
  56. kaq_quant_common-0.1.97/kaq_quant_common/utils/enums_utils.py +79 -0
  57. kaq_quant_common-0.1.97/kaq_quant_common/utils/error_utils.py +22 -0
  58. kaq_quant_common-0.1.97/kaq_quant_common/utils/hash_utils.py +48 -0
  59. kaq_quant_common-0.1.97/kaq_quant_common/utils/log_time_utils.py +32 -0
  60. kaq_quant_common-0.1.97/kaq_quant_common/utils/logger_utils.py +97 -0
  61. kaq_quant_common-0.1.97/kaq_quant_common/utils/mytt_utils.py +372 -0
  62. kaq_quant_common-0.1.97/kaq_quant_common/utils/signal_utils.py +23 -0
  63. kaq_quant_common-0.1.97/kaq_quant_common/utils/sqlite_utils.py +169 -0
  64. kaq_quant_common-0.1.97/kaq_quant_common/utils/uuid_utils.py +5 -0
  65. kaq_quant_common-0.1.97/kaq_quant_common/utils/yml_utils.py +148 -0
  66. kaq_quant_common-0.1.97/pyproject.toml +57 -0
@@ -0,0 +1,66 @@
1
+ Metadata-Version: 2.3
2
+ Name: kaq_quant_common
3
+ Version: 0.1.97
4
+ Summary:
5
+ Author: kevinfuture
6
+ Author-email: liuenbofuture@foxmail.com
7
+ Requires-Python: >=3.11, <3.13
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Programming Language :: Python :: 3.11
10
+ Classifier: Programming Language :: Python :: 3.12
11
+ Requires-Dist: aiohttp (>=3.13.2,<4.0.0)
12
+ Requires-Dist: certifi (>=2025.11.12,<2026.0.0)
13
+ Requires-Dist: cryptography (>=46.0.3,<47.0.0)
14
+ Requires-Dist: dagster (==1.11.16)
15
+ Requires-Dist: dagster-embedded-elt (==0.27.16)
16
+ Requires-Dist: dagster-mysql (==0.27.16)
17
+ Requires-Dist: dagster-webserver (==1.11.16)
18
+ Requires-Dist: dlt (==1.19.1)
19
+ Requires-Dist: dolphindb (>=3.0.4.0,<4.0.0.0)
20
+ Requires-Dist: flask (>=3.1.2)
21
+ Requires-Dist: loguru (>=0.7.3,<0.8.0)
22
+ Requires-Dist: mysql-connector-python (>=9.5.0,<10.0.0)
23
+ Requires-Dist: mysqlclient (>=2.2.7,<3.0.0)
24
+ Requires-Dist: natsort (>=8.4.0,<9.0.0)
25
+ Requires-Dist: plotly (>=6.5.0,<7.0.0)
26
+ Requires-Dist: psycopg2-binary (>=2.9.11,<3.0.0)
27
+ Requires-Dist: pyarrow (>=21.0.0,<22.0.0)
28
+ Requires-Dist: pycryptodome (>=3.23.0)
29
+ Requires-Dist: pydantic (>=2.12.5)
30
+ Requires-Dist: pyhive (>=0.7.0,<0.8.0)
31
+ Requires-Dist: pyyaml (>=6.0.3,<7.0.0)
32
+ Requires-Dist: redis (>=6.4.0,<7.0.0)
33
+ Requires-Dist: requests (>=2.32.0)
34
+ Requires-Dist: requests (>=2.32.5,<3.0.0)
35
+ Requires-Dist: retrying (>=1.4.2,<2.0.0)
36
+ Requires-Dist: sqlalchemy (>=2.0.44,<3.0.0)
37
+ Requires-Dist: thrift (>=0.22.0,<0.23.0)
38
+ Requires-Dist: twine (>=6.2.0,<7.0.0)
39
+ Requires-Dist: uuid (>=1.30,<2.0)
40
+ Requires-Dist: vectorbt (>=0.28.1,<0.29.0)
41
+ Requires-Dist: websocket-client (>=1.9.0,<2.0.0)
42
+ Requires-Dist: websockets (>=15.0.1)
43
+ Requires-Dist: werkzeug (>=3.1.4)
44
+ Description-Content-Type: text/markdown
45
+
46
+ # KAQ_QUANT_COMMON
47
+
48
+ A simple Python package that does amazing things.
49
+
50
+ ## Features
51
+
52
+ - Feature 1: Does X
53
+ - Feature 2: Does Y
54
+
55
+ ## Installation
56
+
57
+ You can install this package using:
58
+
59
+ ```bash
60
+ pip install my-package
61
+ ```
62
+
63
+ ## Pub
64
+ Command:
65
+ ```bash
66
+ twine upload dist/* --verbose
@@ -0,0 +1,21 @@
1
+ # KAQ_QUANT_COMMON
2
+
3
+ A simple Python package that does amazing things.
4
+
5
+ ## Features
6
+
7
+ - Feature 1: Does X
8
+ - Feature 2: Does Y
9
+
10
+ ## Installation
11
+
12
+ You can install this package using:
13
+
14
+ ```bash
15
+ pip install my-package
16
+ ```
17
+
18
+ ## Pub
19
+ Command:
20
+ ```bash
21
+ twine upload dist/* --verbose
File without changes
@@ -0,0 +1,38 @@
1
+ from abc import ABC
2
+ from functools import wraps
3
+ from typing import Callable, Type
4
+
5
+ from pydantic import BaseModel
6
+
7
+
8
+ def api_method(request_model: Type[BaseModel], response_model: Type[BaseModel]):
9
+ """
10
+ api 方法注解
11
+ :param request_model: 请求模型
12
+ :param response_model: 响应模型
13
+ :return:
14
+ """
15
+
16
+ def decorator(func: Callable):
17
+ # 将注解信息绑定到原始函数
18
+ func._is_api_method = True
19
+ func._request_model = request_model
20
+ func._response_model = response_model
21
+
22
+ @wraps(func)
23
+ def wrapper(*args, **kwargs):
24
+ return func(*args, **kwargs)
25
+
26
+ # 同步注解信息到包装函数,便于通过inspect发现
27
+ wrapper._is_api_method = True
28
+ wrapper._request_model = request_model
29
+ wrapper._response_model = response_model
30
+
31
+ return wrapper
32
+
33
+ return decorator
34
+
35
+
36
+ # 定义 api 接口,暂时没啥用
37
+ class ApiInterface(ABC):
38
+ pass
@@ -0,0 +1,118 @@
1
+ import os
2
+ from typing import Any, Optional, Tuple
3
+
4
+ from kaq_quant_common.utils import yml_utils
5
+
6
+ # 统一的简单鉴权:基于一个共享的 token
7
+ # - 来源优先级:环境变量 KAQ_API_TOKEN > 配置文件 kaq.api_token
8
+ # - 如果未配置 token,则认为鉴权关闭(通过)
9
+
10
+
11
+ def _get_expected_token(pkg_name: Optional[str] = None) -> Optional[str]:
12
+ # 环境变量优先
13
+ token = os.getenv("KAQ_API_TOKEN")
14
+ if token:
15
+ return token.strip()
16
+ # 配置文件兜底
17
+ try:
18
+ token_cfg = yml_utils.get(pkg_name or "kaq_quant_common", "api_token")
19
+ if isinstance(token_cfg, str) and token_cfg.strip():
20
+ return token_cfg.strip()
21
+ except Exception as e:
22
+ # 配置读取失败则视为未配置
23
+ pass
24
+ return None
25
+
26
+
27
+ def _extract_token_from_authorization(auth_header: Optional[str]) -> Optional[str]:
28
+ if not auth_header:
29
+ return None
30
+ # 支持 Bearer/Token 两种前缀
31
+ val = auth_header.strip()
32
+ lower = val.lower()
33
+ if lower.startswith("bearer "):
34
+ return val[7:].strip()
35
+ if lower.startswith("token "):
36
+ return val[6:].strip()
37
+ # 若为纯 token 也接受
38
+ return val
39
+
40
+
41
+ def _extract_token_from_headers(headers: Any) -> Optional[str]:
42
+ # 兼容 Flask/Werkzeug 和 websockets.Headers
43
+ try:
44
+ # Flask/requests:大小写不敏感
45
+ auth = headers.get("Authorization") if hasattr(headers, "get") else None
46
+ if not auth and hasattr(headers, "get"):
47
+ auth = headers.get("authorization")
48
+ token = _extract_token_from_authorization(auth)
49
+ if token:
50
+ return token
51
+ # 备用头
52
+ x_token = headers.get("X-API-Token") if hasattr(headers, "get") else None
53
+ if not x_token and hasattr(headers, "get"):
54
+ x_token = headers.get("x-api-token")
55
+ return x_token.strip() if isinstance(x_token, str) and x_token.strip() else None
56
+ except Exception:
57
+ return None
58
+
59
+
60
+ def _extract_token_from_path_query(path: Optional[str]) -> Optional[str]:
61
+ # 解析 ?token=xxx 简单查询参数
62
+ if not path or "?" not in path:
63
+ return None
64
+ try:
65
+ query = path.split("?", 1)[1]
66
+ for pair in query.split("&"):
67
+ if not pair:
68
+ continue
69
+ k, _, v = pair.partition("=")
70
+ if k.lower() == "token" and v:
71
+ return v
72
+ except Exception:
73
+ pass
74
+ return None
75
+
76
+
77
+ # ----------------- 对外校验方法 -----------------
78
+
79
+
80
+ def verify_http_request(flask_request: Any, pkg_name: Optional[str] = None) -> Tuple[bool, Optional[str]]:
81
+ """校验 HTTP 请求头中的 token。
82
+ 返回 (是否通过, 错误信息)。未配置 token 时默认放行。
83
+ """
84
+ expected = _get_expected_token(pkg_name)
85
+ if not expected:
86
+ return True, None
87
+ # 从 Header 提取
88
+ token = _extract_token_from_headers(getattr(flask_request, "headers", None))
89
+ if token and token == expected:
90
+ return True, None
91
+ return False, "Unauthorized"
92
+
93
+
94
+ def verify_ws_handshake(path: Optional[str], headers: Any, pkg_name: Optional[str] = None) -> Tuple[bool, Optional[str]]:
95
+ """校验 WebSocket 握手阶段的路径与请求头。
96
+ 支持从 Header 与 ?token=xx 解析。未配置 token 时默认放行。
97
+ """
98
+ expected = _get_expected_token(pkg_name)
99
+ if not expected:
100
+ return True, None
101
+ # Header 优先
102
+ token = _extract_token_from_headers(headers)
103
+ if not token:
104
+ # 再从路径查询参数解析
105
+ token = _extract_token_from_path_query(path)
106
+ if token and token == expected:
107
+ return True, None
108
+ return False, "Unauthorized"
109
+
110
+
111
+ # ----------------- 客户端复用:获取默认 token -----------------
112
+
113
+
114
+ def get_auth_token(pkg_name: Optional[str] = None) -> Optional[str]:
115
+ """供客户端复用的获取默认 token 的方法。
116
+ 与服务器端校验使用相同的来源规则。
117
+ """
118
+ return _get_expected_token(pkg_name)
@@ -0,0 +1,42 @@
1
+ from typing import Optional, Type, TypeVar
2
+
3
+ import requests
4
+ from kaq_quant_common.api.common.auth import get_auth_token
5
+ from kaq_quant_common.utils import logger_utils
6
+ from pydantic import BaseModel
7
+
8
+ R = TypeVar("R", bound=BaseModel)
9
+
10
+
11
+ class ApiClientBase:
12
+ """
13
+ api 客户端
14
+ """
15
+
16
+ def __init__(self, base_url: str, token: Optional[str] = None):
17
+ self._base_url = base_url.rstrip("/")
18
+ self._token = token if token is not None else get_auth_token()
19
+ self._logger = logger_utils.get_logger(self)
20
+
21
+ # 发送请求
22
+ def _make_request(self, method_name: str, request_data: BaseModel, response_model: Type[R]) -> R:
23
+ url = f"{self._base_url}/api/{method_name}"
24
+ headers = {}
25
+ if self._token:
26
+ headers["Authorization"] = f"Bearer {self._token}"
27
+ try:
28
+ # 发送post请求
29
+ response = requests.post(url, json=request_data.model_dump(), headers=headers or None)
30
+ # 检查响应状态码,如果不成功,则尝试解析错误信息并抛出异常
31
+ if not response.ok:
32
+ try:
33
+ error_data = response.json()
34
+ error_message = error_data.get("error", response.text)
35
+ except ValueError:
36
+ error_message = response.text
37
+ raise requests.exceptions.HTTPError(f"HTTP error occurred: {response.status_code} - {error_message}", response=response)
38
+ # 返回请求结果
39
+ return response_model(**response.json())
40
+ except requests.exceptions.RequestException as e:
41
+ self._logger.error(f"An error occurred: {e}")
42
+ raise
@@ -0,0 +1,135 @@
1
+ import inspect
2
+ import threading
3
+ import time
4
+
5
+ from flask import Flask, jsonify, request
6
+ from werkzeug.serving import make_server
7
+
8
+ from kaq_quant_common.api.common.api_interface import ApiInterface
9
+ from kaq_quant_common.api.common.auth import verify_http_request
10
+ from kaq_quant_common.utils import logger_utils, signal_utils
11
+
12
+
13
+ class ApiServerBase:
14
+ """
15
+ API服务器基类,用于动态发现和分派API方法。
16
+ """
17
+
18
+ def __init__(self, api: ApiInterface, host="0.0.0.0", port=5000):
19
+ """
20
+ 初始化API服务器。
21
+
22
+ :param api: 实现了ApiInterface的API实例。
23
+ :param host: 服务器主机地址。
24
+ :param port: 服务器端口。
25
+ """
26
+ self._app = Flask(__name__)
27
+ self._api = api
28
+ self._host = host
29
+ self._port = port
30
+ self._server = make_server(self._host, self._port, self._app)
31
+ self._api_methods = self._discover_api_methods()
32
+ self._logger = logger_utils.get_logger(self)
33
+
34
+ @self._app.route("/api/<method_name>", methods=["POST"])
35
+ def handle_request(method_name: str):
36
+ """
37
+ 处理API请求。
38
+ """
39
+ # 简单鉴权(若未配置 token 则默认放行)
40
+ ok, err = verify_http_request(request)
41
+ if not ok:
42
+ return jsonify({"error": err or "Unauthorized"}), 401
43
+
44
+ if method_name not in self._api_methods:
45
+ return jsonify({"error": f"Method '{method_name}' not found"}), 404
46
+
47
+ method, request_model, response_model = self._api_methods[method_name]
48
+
49
+ try:
50
+ # 使用请求模型验证和解析JSON数据
51
+ request_data = request_model(**request.json)
52
+ # 调用API方法
53
+ response_data = method(request_data)
54
+ # 验证响应类型
55
+ if not isinstance(response_data, response_model):
56
+ return jsonify({"error": "Invalid response type from method"}), 500
57
+ # 允许子类包装响应
58
+ response_data = self._wrap_response(response_data)
59
+ # 返回JSON响应
60
+ return jsonify(response_data.model_dump())
61
+ except Exception as e:
62
+ # 捕获请求处理过程中的异常
63
+ return jsonify({"error": str(e)}), 400
64
+
65
+ def _discover_api_methods(self):
66
+ """
67
+ 发现并注册所有使用@api_method装饰器标记的API方法。
68
+ """
69
+ methods = {}
70
+ for name, func in inspect.getmembers(self._api, predicate=inspect.ismethod):
71
+ if hasattr(func, "_is_api_method") and func._is_api_method:
72
+ methods[name] = (func, func._request_model, func._response_model)
73
+ return methods
74
+
75
+ # 子类用来包装响应,例如添加时间戳
76
+ def _wrap_response(self, rsp: any):
77
+ return rsp
78
+
79
+ def run(self):
80
+ """
81
+ 启动API服务器。
82
+ """
83
+ self._logger.info(f"Starting server on {self._host}:{self._port}")
84
+ self._server.serve_forever()
85
+
86
+ def shutdown(self):
87
+ """
88
+ 关闭API服务器。
89
+ """
90
+ self._logger.info(f"Shutting down server on {self._host}:{self._port}")
91
+ self._server.shutdown()
92
+
93
+ def run_with_thread(self, block=True):
94
+ """
95
+ 启动API服务器在一个新线程中。
96
+ """
97
+ self._server_thread = threading.Thread(target=self.run)
98
+ self._server_thread.name = "ApiServerThread"
99
+ self._server_thread.daemon = True
100
+ self._server_thread.start()
101
+ time.sleep(1)
102
+
103
+ if block:
104
+ self.wait_for_termination()
105
+
106
+ def shutdown_with_thread(self):
107
+ """
108
+ 关闭服务器并等待线程退出
109
+ """
110
+ try:
111
+ self.shutdown()
112
+ finally:
113
+ if hasattr(self, "_server_thread") and self._server_thread.is_alive():
114
+ self._server_thread.join(timeout=3)
115
+
116
+ #
117
+ def wait_for_termination(self):
118
+ # 全局退出事件,用于传递终止信号
119
+ exit_event = threading.Event()
120
+
121
+ def handle_terminate_signal(signum, frame=None):
122
+ """信号处理函数:捕获终止信号并触发退出事件"""
123
+ self._logger.info(f"收到终止信号 {signum}")
124
+ exit_event.set()
125
+ # 优雅地停止服务器
126
+ self.shutdown()
127
+
128
+ # 监听信号
129
+ signal_utils.register_signal_handler(handle_terminate_signal)
130
+
131
+ # 监听退出事件
132
+ while not exit_event.is_set():
133
+ time.sleep(1)
134
+
135
+ self._logger.warning("ApiServer 线程退出")