Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c3e9ae8d77 | |||
| b7c4e60420 | |||
| 15dc44e8e0 | |||
| bd4fceab02 | |||
| af3ebf13c8 | |||
| 22109d8b30 | |||
| c2c09fc8ba | |||
| 0eb52cc06a | |||
| 1e6025a968 | |||
| 14279f3df6 | |||
| fca62f3141 | |||
| e50172e923 | |||
| c87fb66d34 | |||
| 9900266516 | |||
| 5c3179eec8 | |||
| ae57090d7f |
@@ -16,9 +16,87 @@ env:
|
||||
|
||||
jobs:
|
||||
# ============================================================
|
||||
# Linux x86_64 (manylinux)
|
||||
# 1. 发布 chanlun 核心库至 crates.io
|
||||
# ============================================================
|
||||
publish-crates:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
exists: ${{ steps.check.outputs.exists }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: 安装 Rust 工具链
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
|
||||
- name: 缓存依赖
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
target
|
||||
key: ${{ runner.os }}-cargo-${{ hashFiles('chanlun/Cargo.lock') }}
|
||||
|
||||
- name: 提取版本号
|
||||
id: version
|
||||
working-directory: chanlun
|
||||
run: |
|
||||
VER=$(cargo metadata --format-version 1 --no-deps 2>/dev/null \
|
||||
| jq -r '.packages[] | select(.name == "chanlun") | .version')
|
||||
echo "version=$VER" >> $GITHUB_OUTPUT
|
||||
echo "当前版本: $VER"
|
||||
|
||||
- name: 检查版本是否已存在
|
||||
id: check
|
||||
run: |
|
||||
VER="${{ steps.version.outputs.version }}"
|
||||
EXISTS=$(curl -sS "https://crates.io/api/v1/crates/chanlun" \
|
||||
| jq -r --arg v "$VER" '.versions[]?.num // empty | select(. == $v)')
|
||||
if [ -n "$EXISTS" ]; then
|
||||
echo "版本 $VER 已存在于 crates.io,跳过发布"
|
||||
echo "exists=true" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "版本 $VER 未发布,继续"
|
||||
echo "exists=false" >> $GITHUB_OUTPUT
|
||||
fi
|
||||
|
||||
- name: 格式检查
|
||||
if: steps.check.outputs.exists == 'false'
|
||||
working-directory: chanlun
|
||||
run: cargo fmt --check
|
||||
|
||||
- name: Lint 检查
|
||||
if: steps.check.outputs.exists == 'false'
|
||||
working-directory: chanlun
|
||||
run: cargo clippy
|
||||
|
||||
- name: 运行测试
|
||||
if: steps.check.outputs.exists == 'false'
|
||||
working-directory: chanlun
|
||||
run: cargo test
|
||||
|
||||
- name: 验证打包
|
||||
if: steps.check.outputs.exists == 'false'
|
||||
working-directory: chanlun
|
||||
run: cargo publish --dry-run --allow-dirty
|
||||
|
||||
- name: 登录 crates.io
|
||||
if: steps.check.outputs.exists == 'false'
|
||||
run: cargo login ${{ secrets.CARGO_TOKEN }}
|
||||
|
||||
- name: 发布 chanlun 至 crates.io
|
||||
if: steps.check.outputs.exists == 'false'
|
||||
working-directory: chanlun
|
||||
run: cargo publish --allow-dirty
|
||||
|
||||
# ============================================================
|
||||
# 2. 构建 wheel — Linux x86_64 (manylinux)
|
||||
# ============================================================
|
||||
linux-x86_64:
|
||||
needs: [publish-crates]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -31,6 +109,10 @@ jobs:
|
||||
- name: 安装 Rust 工具链
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
|
||||
- name: 更新 cargo 索引(确保新版本可见)
|
||||
run: cargo update
|
||||
working-directory: chanlun-py
|
||||
|
||||
- name: 构建 wheel (manylinux)
|
||||
uses: PyO3/maturin-action@v1
|
||||
with:
|
||||
@@ -45,11 +127,11 @@ jobs:
|
||||
name: wheels-linux-x86_64
|
||||
path: chanlun-py/dist/
|
||||
|
||||
|
||||
# ============================================================
|
||||
# macOS wheels (x86_64 + arm64)
|
||||
# 3. 构建 wheel — macOS (x86_64 + arm64)
|
||||
# ============================================================
|
||||
macos:
|
||||
needs: [publish-crates]
|
||||
runs-on: macos-latest
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -65,6 +147,10 @@ jobs:
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: 更新 cargo 索引
|
||||
run: cargo update
|
||||
working-directory: chanlun-py
|
||||
|
||||
- name: 构建 wheel
|
||||
uses: PyO3/maturin-action@v1
|
||||
with:
|
||||
@@ -79,9 +165,10 @@ jobs:
|
||||
path: chanlun-py/dist/
|
||||
|
||||
# ============================================================
|
||||
# Windows wheels (x86_64)
|
||||
# 4. 构建 wheel — Windows x86_64
|
||||
# ============================================================
|
||||
windows:
|
||||
needs: [publish-crates]
|
||||
runs-on: windows-latest
|
||||
strategy:
|
||||
matrix:
|
||||
@@ -97,6 +184,10 @@ jobs:
|
||||
with:
|
||||
python-version: '3.12'
|
||||
|
||||
- name: 更新 cargo 索引
|
||||
run: cargo update
|
||||
working-directory: chanlun-py
|
||||
|
||||
- name: 构建 wheel
|
||||
uses: PyO3/maturin-action@v1
|
||||
with:
|
||||
@@ -111,9 +202,10 @@ jobs:
|
||||
path: chanlun-py/dist/
|
||||
|
||||
# ============================================================
|
||||
# 源码分发包 (sdist)
|
||||
# 5. 源码分发包 (sdist)
|
||||
# ============================================================
|
||||
sdist:
|
||||
needs: [publish-crates]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -137,14 +229,14 @@ jobs:
|
||||
path: chanlun-py/dist/
|
||||
|
||||
# ============================================================
|
||||
# 发布至 PyPI
|
||||
# 6. 发布至 PyPI
|
||||
# ============================================================
|
||||
publish:
|
||||
needs: [linux-x86_64, macos, windows, sdist]
|
||||
needs: [publish-crates, linux-x86_64, macos, windows, sdist]
|
||||
runs-on: ubuntu-latest
|
||||
if: startsWith(github.ref, 'refs/tags/v') || github.event.inputs.publish-to-pypi == 'true'
|
||||
permissions:
|
||||
id-token: write # PyPI 信任发布(推荐)
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- name: 下载所有产物
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
[](https://pypi.org/project/chanlun/)
|
||||
[](LICENSE)
|
||||
|
||||
基于 [chanlun](./chanlun/) Rust 核心库的 PyO3 高性能 Python 绑定,API 与 `chan.py` 完全兼容。
|
||||
基于 [chanlun](./chanlun/) Rust 核心库的 PyO3 高性能 Python 绑定,API 参考 `chan.py` 设计,高度兼容。
|
||||
|
||||
## 安装
|
||||
|
||||
@@ -19,8 +19,8 @@ import chanlun
|
||||
# 创建配置(全部默认值)
|
||||
config = chanlun.缠论配置()
|
||||
|
||||
# 读取 K 线数据文件,创建观察者
|
||||
obs = chanlun.观察者.读取数据文件("path/to/data.nb", config)
|
||||
# 读取 K 线数据文件(文件名需遵循 `符号-周期-起始时间戳-结束时间戳.nb` 格式,如 `btcusd-300-1631772074-1632222374.nb`)
|
||||
obs = chanlun.观察者.读取数据文件("path/to/btcusd-300-1631772074-1632222374.nb", config)
|
||||
|
||||
# 查看各层级序列
|
||||
print(f"K线数量: {len(obs.普通K线序列)}")
|
||||
@@ -29,7 +29,7 @@ print(f"线段数量: {len(obs.线段序列)}")
|
||||
print(f"中枢数量: {len(obs.中枢序列)}")
|
||||
|
||||
# 或使用立体分析器进行多周期分析
|
||||
analyzer = chanlun.立体分析器("BTCUSD", ["1min", "5min", "30min"], config)
|
||||
analyzer = chanlun.立体分析器("BTCUSD", [60, 60*5, 60*5*6], config)
|
||||
# 逐根投喂 K 线...
|
||||
```
|
||||
|
||||
@@ -53,7 +53,6 @@ pip install target/wheels/chanlun-*.whl
|
||||
```bash
|
||||
./build.sh develop # 开发安装
|
||||
./build.sh wheel # 构建 wheel
|
||||
./build.sh test # 运行集成测试
|
||||
```
|
||||
|
||||
## 导出类
|
||||
@@ -70,8 +69,8 @@ pip install target/wheels/chanlun-*.whl
|
||||
## 兼容性
|
||||
|
||||
- Python 3.9+
|
||||
- 类名 / 方法名 / 字段名 / 签名与 `chan.py` 一致
|
||||
- 支持 `.nb` / `.dat` 二进制文件格式(大端字节序)
|
||||
- 类名 / 方法名 / 字段名与 `chan.py` 保持一致
|
||||
- 支持 `.nb` 二进制文件格式(大端字节序)
|
||||
|
||||
## 许可
|
||||
|
||||
|
||||
@@ -28,8 +28,10 @@ SOFTWARE.
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import struct
|
||||
import sys
|
||||
import tempfile
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
@@ -2202,6 +2204,9 @@ class 缠论K线(object):
|
||||
return 序列[序列.index(始) : 序列.index(终) + 1]
|
||||
|
||||
|
||||
分型模式 = True
|
||||
|
||||
|
||||
class 分型(object):
|
||||
"""分型 — 由左中右三根缠论K线构成的顶/底分型结构。
|
||||
|
||||
@@ -2216,7 +2221,7 @@ class 分型(object):
|
||||
:ivar 与MACD柱子分型匹配: 是否与MACD柱子分型匹配
|
||||
"""
|
||||
|
||||
__slots__ = ["左", "中", "右", "结构", "时间戳", "分型特征值"]
|
||||
__slots__ = ["左", "中", "右", "_结构", "_时间戳", "_分型特征值"]
|
||||
|
||||
def __init__(self, 左: Optional[缠论K线], 中: 缠论K线, 右: Optional[缠论K线]):
|
||||
"""
|
||||
@@ -2229,9 +2234,9 @@ class 分型(object):
|
||||
self.左: Optional[缠论K线] = 左
|
||||
self.中: 缠论K线 = 中
|
||||
self.右: Optional[缠论K线] = 右
|
||||
self.结构 = 中.分型
|
||||
self.时间戳 = 中.时间戳
|
||||
self.分型特征值 = 中.分型特征值
|
||||
self._结构 = 中.分型
|
||||
self._时间戳 = 中.时间戳
|
||||
self._分型特征值 = 中.分型特征值
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.中.分型}<{self.时间戳}, {self.分型特征值:g}, None: {self.左 is None}, None: {self.右 is None}>"
|
||||
@@ -2239,6 +2244,24 @@ class 分型(object):
|
||||
def __repr__(self):
|
||||
return f"{self.中.分型}<{self.时间戳}, {self.分型特征值:g}, None: {self.左 is None}, None: {self.右 is None}>"
|
||||
|
||||
@property
|
||||
def 时间戳(self):
|
||||
if 分型模式:
|
||||
return self._时间戳
|
||||
return self.中.时间戳
|
||||
|
||||
@property
|
||||
def 分型特征值(self):
|
||||
if 分型模式:
|
||||
return self._分型特征值
|
||||
return self.中.分型特征值
|
||||
|
||||
@property
|
||||
def 结构(self):
|
||||
if 分型模式:
|
||||
return self._结构
|
||||
return self.中.分型
|
||||
|
||||
@property
|
||||
def 关系组(self) -> Optional[Tuple[相对方向, 相对方向, 相对方向]]:
|
||||
"""左、中、右三对相对方向关系
|
||||
@@ -5055,6 +5078,17 @@ class 观察者:
|
||||
self.扩展线段序列_扩展线段: List[虚线] = []
|
||||
self.扩展中枢序列_扩展线段: List[中枢] = []
|
||||
|
||||
def 投喂原始数据(self, 时间戳: datetime, 开: float, 高: float, 低: float, 收: float, 量: float):
|
||||
"""便捷入口,直接从 OHLCV 创建 K线 并投喂
|
||||
:param 时间戳: 时间戳
|
||||
:param 开: 开盘价
|
||||
:param 高: 最高价
|
||||
:param 低: 最低价
|
||||
:param 收: 收盘价
|
||||
:param 量: 成交量
|
||||
"""
|
||||
self.增加原始K线(K线.创建普K(self.标识, 时间戳, 开, 高, 低, 收, 量, 0, self.周期))
|
||||
|
||||
@final
|
||||
def 增加原始K线(self, 普K: K线):
|
||||
"""核心入口 — 投喂一根原始K线,增量更新所有层级
|
||||
@@ -5201,33 +5235,32 @@ class 观察者:
|
||||
self.配置.分析线段中枢 and 中枢.分析(self.线段_线段序列, self.线段_中枢序列)
|
||||
|
||||
def 加载本地数据(self, 文件路径: str):
|
||||
"""重置基础序列后加载数据文件
|
||||
:param 文件路径: 数据文件路径 格式如: btcusd-300-1631772074-1632222374.nb
|
||||
"""
|
||||
self.重置基础序列()
|
||||
with open(文件路径, "rb") as f:
|
||||
buffer = f.read()
|
||||
size = struct.calcsize(">6d")
|
||||
for i in range(len(buffer) // size):
|
||||
k线 = K线.读取大端字节数组(buffer[i * size : i * size + size], self.周期, self.标识)
|
||||
self.增加原始K线(k线)
|
||||
时间戳, 开盘价, 最高价, 最低价, 收盘价, 成交量 = struct.unpack(">6d", buffer[i * size : i * size + size])
|
||||
self.投喂原始数据(转化为时间戳(int(时间戳)), 开盘价, 最高价, 最低价, 收盘价, 成交量)
|
||||
|
||||
@classmethod
|
||||
def 读取数据文件(cls, 文件路径: str, 配置=缠论配置()) -> Self:
|
||||
"""
|
||||
def 读取数据文件(cls, 观察员: "观察者", 文件路径: str, 配置=缠论配置()) -> Self:
|
||||
"""加载数据文件
|
||||
:param 观察员: 观察者
|
||||
:param 文件路径: 数据文件路径 格式如: btcusd-300-1631772074-1632222374.nb
|
||||
:param 配置: 缠论配置
|
||||
:return: 观察者实例
|
||||
"""
|
||||
name = Path(文件路径).name.split(".")[0]
|
||||
符号, 周期, 起始时间戳, 结束时间戳 = name.split("-")
|
||||
实例 = cls(符号=符号, 周期=int(周期), 配置=配置)
|
||||
|
||||
with open(文件路径, "rb") as f:
|
||||
buffer = f.read()
|
||||
size = struct.calcsize(">6d")
|
||||
for i in range(len(buffer) // size):
|
||||
k线 = K线.读取大端字节数组(buffer[i * size : i * size + size], int(周期), 符号)
|
||||
实例.增加原始K线(k线)
|
||||
|
||||
return 实例
|
||||
观察员.符号 = 符号
|
||||
观察员.周期 = int(周期)
|
||||
观察员.配置 = 配置
|
||||
观察员.加载本地数据(文件路径)
|
||||
return 观察员
|
||||
|
||||
|
||||
class K线合成器:
|
||||
@@ -5462,10 +5495,10 @@ class 立体分析器:
|
||||
if 当前K线 := self._K线合成器.获取当前K线(周期):
|
||||
self._单体分析器[周期].增加原始K线(当前K线)
|
||||
|
||||
def 测试_保存数据(self):
|
||||
def 测试_保存数据(self, root: str = None):
|
||||
"""拆分各序列数据,单独存文件,文件名为对应变量名"""
|
||||
# 生成存储根目录
|
||||
脚本目录 = Path(__file__).parent # 取当前脚本所在文件夹
|
||||
脚本目录 = Path(__file__).parent if not root else root # 取当前脚本所在文件夹
|
||||
起始时间 = int(self._单体分析器[self.__输入周期].普通K线序列[0].时间戳.timestamp())
|
||||
结束时间 = int(self._单体分析器[self.__输入周期].普通K线序列[-1].时间戳.timestamp())
|
||||
目录标识 = f"PyM_{self._单体分析器[self.__输入周期].标识}_{起始时间}_{结束时间}"
|
||||
@@ -5480,16 +5513,16 @@ class 立体分析器:
|
||||
print(f"多级别数据拆分保存完成,目录:{保存路径.resolve()}")
|
||||
|
||||
|
||||
def 测试_读取数据(配置: 缠论配置):
|
||||
def 测试_读取数据(观察员: 观察者, 配置: 缠论配置) -> Callable[[], "观察者"]:
|
||||
"""测试_读取数据
|
||||
|
||||
:param 观察员: 观察者
|
||||
:param 配置: 缠论配置
|
||||
:return: 测试函数
|
||||
"""
|
||||
|
||||
def 魔法():
|
||||
启动时间 = datetime.now()
|
||||
观察员 = 观察者.读取数据文件(配置.加载文件路径, 配置)
|
||||
观察者.读取数据文件(观察员, 配置.加载文件路径, 配置)
|
||||
消耗用时 = datetime.now() - 启动时间
|
||||
print("测试_读取数据 耗时", 消耗用时, "普K数量", len(观察员.普通K线序列))
|
||||
return 观察员
|
||||
@@ -5529,5 +5562,6 @@ def 测试_周期合成(配置: 缠论配置, 配置组: Dict[int, 缠论配置]
|
||||
if __name__ == "__main__":
|
||||
当前配置 = 缠论配置.不推送()
|
||||
当前配置.加载文件路径 = str(Path(__file__).parent / "btcusd-300-1761327300-1776327900.nb")
|
||||
测试_读取数据(当前配置)().测试_保存数据()
|
||||
测试_周期合成(当前配置)().测试_保存数据()
|
||||
观察员 = 观察者("", 0, 当前配置)
|
||||
测试_读取数据(观察员, 当前配置)() # .测试_保存数据()
|
||||
# 测试_周期合成(当前配置)().测试_保存数据()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "chanlun-py"
|
||||
version = "26.5.46"
|
||||
version = "26.5.103"
|
||||
edition = "2021"
|
||||
description = "缠论技术分析库 — Rust 高性能 Python 绑定"
|
||||
authors = ["YuYuKunKun"]
|
||||
@@ -12,7 +12,7 @@ crate-type = ["cdylib"]
|
||||
name = "chanlun"
|
||||
|
||||
[dependencies]
|
||||
chanlun = "26.5.2" # { path = "../chanlun" }
|
||||
pyo3 = { version = "0.28", features = ["extension-module"] }
|
||||
chanlun = "26.5.6" # { path = "../chanlun" }
|
||||
pyo3 = { version = "0.28", features = ["experimental-inspect"] }
|
||||
serde_json = "1"
|
||||
chrono = "0.4"
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
../README.md
|
||||
@@ -0,0 +1,77 @@
|
||||
# chanlun — 缠论技术分析 Python 绑定
|
||||
|
||||
[](https://pypi.org/project/chanlun/)
|
||||
[](LICENSE)
|
||||
|
||||
基于 [chanlun](../chanlun/) Rust 核心库的 PyO3 高性能 Python 绑定,API 参考 `chan.py` 设计,高度兼容。
|
||||
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
pip install chanlun
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
```python
|
||||
import chanlun
|
||||
|
||||
# 创建配置(全部默认值)
|
||||
config = chanlun.缠论配置()
|
||||
|
||||
# 读取 K 线数据文件(文件名需遵循 `符号-周期-起始时间戳-结束时间戳.nb` 格式,如 `btcusd-300-1631772074-1632222374.nb`)
|
||||
obs = chanlun.观察者.读取数据文件("path/to/btcusd-300-1631772074-1632222374.nb", config)
|
||||
|
||||
# 查看各层级序列
|
||||
print(f"K线数量: {len(obs.普通K线序列)}")
|
||||
print(f"笔数量: {len(obs.笔序列)}")
|
||||
print(f"线段数量: {len(obs.线段序列)}")
|
||||
print(f"中枢数量: {len(obs.中枢序列)}")
|
||||
|
||||
# 或使用立体分析器进行多周期分析
|
||||
analyzer = chanlun.立体分析器("BTCUSD", [60, 60*5, 60*5*6], config)
|
||||
# 逐根投喂 K 线...
|
||||
```
|
||||
|
||||
## 从源码构建
|
||||
|
||||
前置依赖: [Rust](https://www.rust-lang.org) + [maturin](https://www.maturin.rs)
|
||||
|
||||
```bash
|
||||
pip install maturin
|
||||
|
||||
# 开发模式(直接安装到当前 venv)
|
||||
maturin develop
|
||||
|
||||
# 或构建 wheel
|
||||
maturin build --release
|
||||
pip install target/wheels/chanlun-*.whl
|
||||
```
|
||||
|
||||
也可使用项目内的 `build.sh`:
|
||||
|
||||
```bash
|
||||
./build.sh develop # 开发安装
|
||||
./build.sh wheel # 构建 wheel
|
||||
```
|
||||
|
||||
## 导出类
|
||||
|
||||
| 类别 | 类名 | 说明 |
|
||||
|------|------|------|
|
||||
| 枚举 | `买卖点类型`, `相对方向`, `分型结构` | 缠论基础枚举 |
|
||||
| 数据 | `缺口`, `K线`, `缠论K线` | K 线数据结构 |
|
||||
| 结构 | `分型`, `虚线`, `线段特征`, `特征分型` | 分析层级结构 |
|
||||
| 指标 | `平滑异同移动平均线`, `相对强弱指数`, `随机指标` | MACD/RSI/KDJ |
|
||||
| 算法 | `笔`, `线段`, `中枢`, `背驰分析` | 识别算法 |
|
||||
| 业务 | `缠论配置`, `基础买卖点`, `买卖点`, `观察者`, `K线合成器`, `立体分析器` | 分析框架 |
|
||||
|
||||
## 兼容性
|
||||
|
||||
- Python 3.9+
|
||||
- 类名 / 方法名 / 字段名与 `chan.py` 保持一致
|
||||
- 支持 `.nb` 二进制文件格式(大端字节序)
|
||||
|
||||
## 许可
|
||||
|
||||
MIT
|
||||
@@ -0,0 +1,68 @@
|
||||
/// build.rs — 编译时版本一致性检查
|
||||
///
|
||||
/// 验证 Cargo.toml 和 pyproject.toml 的版本号是否一致。
|
||||
///
|
||||
/// Cargo.toml: version = "YY.MM.patch" (e.g., "26.5.57")
|
||||
/// pyproject.toml: version = "YYMM.patch" (e.g., "2605.57")
|
||||
/// 规则: YY = major, MM = minor, patch = patch
|
||||
fn main() {
|
||||
let cargo_manifest_dir =
|
||||
std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
|
||||
let cargo_path = std::path::PathBuf::from(&cargo_manifest_dir);
|
||||
|
||||
let cargo_version = read_version(&cargo_path.join("Cargo.toml"), "[package]");
|
||||
let cargo_parts: Vec<&str> = cargo_version.split('.').collect();
|
||||
assert_eq!(
|
||||
cargo_parts.len(),
|
||||
3,
|
||||
"Cargo.toml version '{}' is not in YY.MM.patch format",
|
||||
cargo_version
|
||||
);
|
||||
|
||||
let pyproject_version = read_version(&cargo_path.join("pyproject.toml"), "[project]");
|
||||
let py_parts: Vec<&str> = pyproject_version.split('.').collect();
|
||||
assert_eq!(
|
||||
py_parts.len(),
|
||||
2,
|
||||
"pyproject.toml version '{}' is not in YYMM.patch format",
|
||||
pyproject_version
|
||||
);
|
||||
|
||||
let expected_yymm = format!("{}{:0>2}", cargo_parts[0], cargo_parts[1]);
|
||||
assert_eq!(
|
||||
py_parts[0], expected_yymm,
|
||||
"pyproject.toml version prefix '{}' != expected '{}' (from Cargo {})",
|
||||
py_parts[0], expected_yymm, cargo_version
|
||||
);
|
||||
assert_eq!(
|
||||
py_parts[1], cargo_parts[2],
|
||||
"pyproject.toml patch '{}' != Cargo.toml patch '{}'",
|
||||
py_parts[1], cargo_parts[2]
|
||||
);
|
||||
|
||||
println!("cargo:rerun-if-changed=pyproject.toml");
|
||||
println!("cargo:rerun-if-changed=Cargo.toml");
|
||||
}
|
||||
|
||||
fn read_version(path: &std::path::Path, section: &str) -> String {
|
||||
let content =
|
||||
std::fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read {:?}: {}", path, e));
|
||||
|
||||
let mut in_section = section.is_empty();
|
||||
for line in content.lines() {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.starts_with('[') {
|
||||
in_section = trimmed == section;
|
||||
continue;
|
||||
}
|
||||
if !in_section {
|
||||
continue;
|
||||
}
|
||||
if trimmed.starts_with("version") {
|
||||
if let Some(v) = trimmed.split('=').nth(1) {
|
||||
return v.trim().trim_matches('"').trim().to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("Cannot parse version from {:?}", path);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,3 +1,34 @@
|
||||
"""缠论技术分析库 — Rust 高性能实现"""
|
||||
|
||||
__all__ = [
|
||||
"K线",
|
||||
"K线合成器",
|
||||
"中枢",
|
||||
"买卖点",
|
||||
"买卖点类型",
|
||||
"分型",
|
||||
"分型结构",
|
||||
"基础买卖点",
|
||||
"平滑异同移动平均线",
|
||||
"指标",
|
||||
"特征分型",
|
||||
"相对强弱指数",
|
||||
"相对方向",
|
||||
"立体分析器",
|
||||
"笔",
|
||||
"线段",
|
||||
"线段特征",
|
||||
"缠论K线",
|
||||
"缠论配置",
|
||||
"缺口",
|
||||
"背驰分析",
|
||||
"虚线",
|
||||
"观察者",
|
||||
"转化为时间戳",
|
||||
"转化为时间戳_数字",
|
||||
"随机指标",
|
||||
"chan",
|
||||
]
|
||||
|
||||
from ._chanlun import *
|
||||
from . import chan
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@ build-backend = "maturin"
|
||||
|
||||
[project]
|
||||
name = "chanlun"
|
||||
version = "2605.46"
|
||||
version = "2605.103"
|
||||
description = "缠论技术分析库 — Rust 高性能实现"
|
||||
readme = { file = "README.md", content-type = "text/markdown" }
|
||||
license = { file = "LICENSE", content-type = "text/plain" }
|
||||
@@ -37,3 +37,7 @@ features = ["pyo3/extension-module"]
|
||||
python-source = "."
|
||||
module-name = "chanlun._chanlun"
|
||||
manifest-path = "Cargo.toml"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
addopts = ["-v", "--tb=short", "--durations=10"]
|
||||
|
||||
+343
-226
File diff suppressed because it is too large
Load Diff
+254
-171
@@ -23,15 +23,17 @@
|
||||
*/
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyType;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use pyo3::types::{PyDict, PyType};
|
||||
use std::sync::RwLock;
|
||||
|
||||
use crate::algorithm_py::hub_to_py;
|
||||
use crate::kline_py::bar_to_py;
|
||||
use crate::structure_py::{dashed_to_py, fractal_to_py, 分型Py};
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::algorithm_py::中枢Py;
|
||||
use crate::config_py::缠论配置Py;
|
||||
use crate::kline_py::{缠论K线Py, K线Py};
|
||||
use crate::structure_py::{分型Py, 虚线Py};
|
||||
use crate::types_py::买卖点类型Py;
|
||||
|
||||
// ========== 基础买卖点 ==========
|
||||
@@ -44,7 +46,12 @@ use crate::types_py::买卖点类型Py;
|
||||
/// 有效性: bool — 买卖点是否仍有效
|
||||
/// 与MACD柱子匹配: bool|None — 是否与MACD柱状图方向匹配
|
||||
/// 与MACD柱子分型匹配: bool|None — 是否与MACD柱分型匹配
|
||||
#[pyclass(name = "基础买卖点", unsendable)]
|
||||
#[pyclass(
|
||||
name = "基础买卖点",
|
||||
module = "chanlun._chanlun",
|
||||
subclass,
|
||||
from_py_object
|
||||
)]
|
||||
#[derive(Clone)]
|
||||
pub struct 基础买卖点Py {
|
||||
pub(crate) inner: chanlun::business::bsp::基础买卖点,
|
||||
@@ -64,9 +71,10 @@ impl 基础买卖点Py {
|
||||
inner: chanlun::business::bsp::基础买卖点::new(
|
||||
类型.borrow().inner,
|
||||
当前K线.borrow().inner.clone(),
|
||||
Rc::clone(&买卖点分型.borrow().inner),
|
||||
Arc::clone(&买卖点分型.borrow().inner),
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前K线.borrow().inner.序号,
|
||||
),
|
||||
}
|
||||
}
|
||||
@@ -90,39 +98,39 @@ impl 基础买卖点Py {
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 买卖点分型(&self) -> 分型Py {
|
||||
分型Py {
|
||||
inner: Rc::clone(&self.inner.买卖点分型),
|
||||
}
|
||||
fn 买卖点分型(&self, py: Python<'_>) -> Py<分型Py> {
|
||||
fractal_to_py(py, Arc::clone(&self.inner.买卖点分型))
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 买卖点K线(&self) -> 缠论K线Py {
|
||||
缠论K线Py::from_rc(Rc::clone(&self.inner.买卖点K线))
|
||||
fn 买卖点K线(&self, py: Python<'_>) -> Py<缠论K线Py> {
|
||||
crate::kline_py::chan_kline_to_py(py, Arc::clone(&self.inner.买卖点K线))
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 当前K线(&self) -> K线Py {
|
||||
K线Py {
|
||||
inner: self.inner.当前K线.clone(),
|
||||
}
|
||||
/// 当前K线
|
||||
fn 当前K线(&self, py: Python<'_>) -> Py<K线Py> {
|
||||
bar_to_py(py, self.inner.当前K线.clone())
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 失效K线(&self) -> Option<K线Py> {
|
||||
self.inner.失效K线.as_ref().map(|k| K线Py {
|
||||
inner: Rc::clone(k),
|
||||
})
|
||||
fn 失效K线(&self, py: Python<'_>) -> Option<Py<K线Py>> {
|
||||
self.inner
|
||||
.失效K线
|
||||
.as_ref()
|
||||
.map(|k| bar_to_py(py, Arc::clone(k)))
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 终结K线(&self) -> Option<K线Py> {
|
||||
self.inner.终结K线.as_ref().map(|k| K线Py {
|
||||
inner: Rc::clone(k),
|
||||
})
|
||||
fn 终结K线(&self, py: Python<'_>) -> Option<Py<K线Py>> {
|
||||
self.inner
|
||||
.终结K线
|
||||
.as_ref()
|
||||
.map(|k| bar_to_py(py, Arc::clone(k)))
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// 破位值
|
||||
fn 破位值(&self) -> f64 {
|
||||
self.inner.破位值
|
||||
}
|
||||
@@ -135,30 +143,53 @@ impl 基础买卖点Py {
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// 偏移
|
||||
fn 偏移(&self) -> i64 {
|
||||
self.inner.偏移()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// 失效偏移
|
||||
fn 失效偏移(&self) -> i64 {
|
||||
self.inner.失效偏移()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// 有效性
|
||||
fn 有效性(&self) -> bool {
|
||||
self.inner.有效性()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// 与MACD柱子匹配
|
||||
fn 与MACD柱子匹配(&self) -> bool {
|
||||
self.inner.与MACD柱子匹配()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// 与MACD柱子分型匹配
|
||||
fn 与MACD柱子分型匹配(&self) -> bool {
|
||||
self.inner.与MACD柱子分型匹配()
|
||||
}
|
||||
|
||||
/// pandas 兼容 — 返回关键标量字段构成的字典
|
||||
#[getter]
|
||||
fn __dict__(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
|
||||
let dict = PyDict::new(py);
|
||||
dict.set_item("备注", self.备注())?;
|
||||
dict.set_item("类型", self.类型())?;
|
||||
dict.set_item("破位值", self.破位值())?;
|
||||
dict.set_item("偏移", self.偏移())?;
|
||||
dict.set_item("失效偏移", self.失效偏移())?;
|
||||
dict.set_item("有效性", self.有效性())?;
|
||||
dict.set_item("与MACD柱子匹配", self.与MACD柱子匹配())?;
|
||||
dict.set_item("与MACD柱子分型匹配", self.与MACD柱子分型匹配())?;
|
||||
if let Some(v) = self.结构() {
|
||||
dict.set_item("结构", v)?;
|
||||
}
|
||||
Ok(dict.into())
|
||||
}
|
||||
|
||||
fn __str__(&self) -> String {
|
||||
format!("{}", self.inner)
|
||||
}
|
||||
@@ -170,13 +201,12 @@ impl 基础买卖点Py {
|
||||
|
||||
// ========== 买卖点 ==========
|
||||
|
||||
/// 买卖点 — 静态方法容器,提供各类买卖点的构造算法(不存储数据)。
|
||||
/// 买卖点 — 继承 基础买卖点,添加工厂类方法。
|
||||
///
|
||||
/// 类方法(均返回对应的买卖点对象):
|
||||
/// 类方法(均返回 买卖点 实例):
|
||||
/// 一卖点(...) / 一买点(...) / 二卖点(...) / 二买点(...) / 三卖点(...) / 三买点(...)
|
||||
/// 生成买卖点(特征, 序号, 级别, 分型, 当前缠K, 备注?) -> 买卖点
|
||||
/// — 根据特征字符串自动路由到对应的一/二/三类买卖点构造函数
|
||||
#[pyclass(name = "买卖点")]
|
||||
/// 生成买卖点(特征, 序号, 级别, 分型, 当前缠K) -> 买卖点
|
||||
#[pyclass(name = "买卖点", module = "chanlun._chanlun", extends=基础买卖点Py)]
|
||||
pub struct 买卖点Py;
|
||||
|
||||
#[pymethods]
|
||||
@@ -189,16 +219,20 @@ impl 买卖点Py {
|
||||
标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
) -> 基础买卖点Py {
|
||||
基础买卖点Py {
|
||||
py: Python<'_>,
|
||||
) -> PyResult<Py<Self>> {
|
||||
let base = 基础买卖点Py {
|
||||
inner: chanlun::business::bsp::买卖点::一卖点(
|
||||
Rc::clone(&买卖点分型.borrow().inner),
|
||||
Arc::clone(&买卖点分型.borrow().inner),
|
||||
当前K线.borrow().inner.clone(),
|
||||
标识,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前K线.borrow().inner.序号,
|
||||
),
|
||||
}
|
||||
};
|
||||
let init = PyClassInitializer::from(base).add_subclass(买卖点Py);
|
||||
Ok(Bound::new(py, init)?.unbind())
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
@@ -209,16 +243,20 @@ impl 买卖点Py {
|
||||
标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
) -> 基础买卖点Py {
|
||||
基础买卖点Py {
|
||||
py: Python<'_>,
|
||||
) -> PyResult<Py<Self>> {
|
||||
let base = 基础买卖点Py {
|
||||
inner: chanlun::business::bsp::买卖点::一买点(
|
||||
Rc::clone(&买卖点分型.borrow().inner),
|
||||
Arc::clone(&买卖点分型.borrow().inner),
|
||||
当前K线.borrow().inner.clone(),
|
||||
标识,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前K线.borrow().inner.序号,
|
||||
),
|
||||
}
|
||||
};
|
||||
let init = PyClassInitializer::from(base).add_subclass(买卖点Py);
|
||||
Ok(Bound::new(py, init)?.unbind())
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
@@ -229,16 +267,20 @@ impl 买卖点Py {
|
||||
标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
) -> 基础买卖点Py {
|
||||
基础买卖点Py {
|
||||
py: Python<'_>,
|
||||
) -> PyResult<Py<Self>> {
|
||||
let base = 基础买卖点Py {
|
||||
inner: chanlun::business::bsp::买卖点::二卖点(
|
||||
Rc::clone(&买卖点分型.borrow().inner),
|
||||
Arc::clone(&买卖点分型.borrow().inner),
|
||||
当前K线.borrow().inner.clone(),
|
||||
标识,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前K线.borrow().inner.序号,
|
||||
),
|
||||
}
|
||||
};
|
||||
let init = PyClassInitializer::from(base).add_subclass(买卖点Py);
|
||||
Ok(Bound::new(py, init)?.unbind())
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
@@ -249,16 +291,20 @@ impl 买卖点Py {
|
||||
标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
) -> 基础买卖点Py {
|
||||
基础买卖点Py {
|
||||
py: Python<'_>,
|
||||
) -> PyResult<Py<Self>> {
|
||||
let base = 基础买卖点Py {
|
||||
inner: chanlun::business::bsp::买卖点::二买点(
|
||||
Rc::clone(&买卖点分型.borrow().inner),
|
||||
Arc::clone(&买卖点分型.borrow().inner),
|
||||
当前K线.borrow().inner.clone(),
|
||||
标识,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前K线.borrow().inner.序号,
|
||||
),
|
||||
}
|
||||
};
|
||||
let init = PyClassInitializer::from(base).add_subclass(买卖点Py);
|
||||
Ok(Bound::new(py, init)?.unbind())
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
@@ -269,16 +315,20 @@ impl 买卖点Py {
|
||||
标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
) -> 基础买卖点Py {
|
||||
基础买卖点Py {
|
||||
py: Python<'_>,
|
||||
) -> PyResult<Py<Self>> {
|
||||
let base = 基础买卖点Py {
|
||||
inner: chanlun::business::bsp::买卖点::三卖点(
|
||||
Rc::clone(&买卖点分型.borrow().inner),
|
||||
Arc::clone(&买卖点分型.borrow().inner),
|
||||
当前K线.borrow().inner.clone(),
|
||||
标识,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前K线.borrow().inner.序号,
|
||||
),
|
||||
}
|
||||
};
|
||||
let init = PyClassInitializer::from(base).add_subclass(买卖点Py);
|
||||
Ok(Bound::new(py, init)?.unbind())
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
@@ -289,19 +339,24 @@ impl 买卖点Py {
|
||||
标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
) -> 基础买卖点Py {
|
||||
基础买卖点Py {
|
||||
py: Python<'_>,
|
||||
) -> PyResult<Py<Self>> {
|
||||
let base = 基础买卖点Py {
|
||||
inner: chanlun::business::bsp::买卖点::三买点(
|
||||
Rc::clone(&买卖点分型.borrow().inner),
|
||||
Arc::clone(&买卖点分型.borrow().inner),
|
||||
当前K线.borrow().inner.clone(),
|
||||
标识,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前K线.borrow().inner.序号,
|
||||
),
|
||||
}
|
||||
};
|
||||
let init = PyClassInitializer::from(base).add_subclass(买卖点Py);
|
||||
Ok(Bound::new(py, init)?.unbind())
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (特征, 序号, 级别, 买卖点分型, 当前缠K))]
|
||||
fn 生成买卖点(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
特征: &str,
|
||||
@@ -309,16 +364,19 @@ impl 买卖点Py {
|
||||
级别: &str,
|
||||
买卖点分型: &Bound<'_, 分型Py>,
|
||||
当前缠K: &Bound<'_, 缠论K线Py>,
|
||||
) -> 基础买卖点Py {
|
||||
基础买卖点Py {
|
||||
py: Python<'_>,
|
||||
) -> PyResult<Py<Self>> {
|
||||
let base = 基础买卖点Py {
|
||||
inner: chanlun::business::bsp::买卖点::生成买卖点(
|
||||
特征,
|
||||
序号,
|
||||
级别,
|
||||
Rc::clone(&买卖点分型.borrow().inner),
|
||||
Rc::clone(&当前缠K.borrow().inner),
|
||||
Arc::clone(&买卖点分型.borrow().inner),
|
||||
Arc::clone(&当前缠K.borrow().inner),
|
||||
),
|
||||
}
|
||||
};
|
||||
let init = PyClassInitializer::from(base).add_subclass(买卖点Py);
|
||||
Ok(Bound::new(py, init)?.unbind())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -353,24 +411,30 @@ impl 买卖点Py {
|
||||
/// 调试方法:
|
||||
/// 测试_保存数据(root?) — 将各层级序列保存到文件,用于与Python版对比
|
||||
/// 读取数据文件(文件路径, 配置) -> 观察者 (classmethod) — 从 .nb 文件加载数据
|
||||
#[pyclass(name = "观察者", subclass, unsendable)]
|
||||
#[pyclass(name = "观察者", module = "chanlun._chanlun", subclass)]
|
||||
pub struct 观察者Py {
|
||||
pub(crate) inner: Option<Rc<RefCell<chanlun::business::observer::观察者>>>,
|
||||
pub(crate) inner: Option<Arc<RwLock<chanlun::business::observer::观察者>>>,
|
||||
}
|
||||
|
||||
impl 观察者Py {
|
||||
pub(crate) fn obs(&self) -> std::cell::Ref<'_, chanlun::business::observer::观察者> {
|
||||
pub(crate) fn obs(
|
||||
&self,
|
||||
) -> std::sync::RwLockReadGuard<'_, chanlun::business::observer::观察者> {
|
||||
self.inner
|
||||
.as_ref()
|
||||
.expect("观察者 尚未初始化,请通过 __init__(符号, 周期, 配置) 构造")
|
||||
.borrow()
|
||||
.read()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
pub(crate) fn obs_mut(&self) -> std::cell::RefMut<'_, chanlun::business::observer::观察者> {
|
||||
pub(crate) fn obs_mut(
|
||||
&self,
|
||||
) -> std::sync::RwLockWriteGuard<'_, chanlun::business::observer::观察者> {
|
||||
self.inner
|
||||
.as_ref()
|
||||
.expect("观察者 尚未初始化,请通过 __init__(符号, 周期, 配置) 构造")
|
||||
.borrow_mut()
|
||||
.write()
|
||||
.unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -442,27 +506,29 @@ impl 观察者Py {
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// 观察员(自引用)
|
||||
fn 观察员(slf: PyRef<'_, Self>) -> PyRef<'_, Self> {
|
||||
slf
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// :return: "{符号}:{周期}"
|
||||
fn 标识(&self) -> String {
|
||||
self.obs().标识()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 当前K线(&self) -> Option<K线Py> {
|
||||
self.obs().当前K线().map(|k| K线Py {
|
||||
inner: Rc::clone(k),
|
||||
})
|
||||
/// :return: 最后一根原始K线
|
||||
fn 当前K线(&self, py: Python<'_>) -> Option<Py<K线Py>> {
|
||||
self.obs().当前K线().map(|k| bar_to_py(py, Arc::clone(k)))
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 当前缠K(&self) -> Option<缠论K线Py> {
|
||||
/// :return: 最后一根缠论K线
|
||||
fn 当前缠K(&self, py: Python<'_>) -> Option<Py<缠论K线Py>> {
|
||||
self.obs()
|
||||
.当前缠K()
|
||||
.map(|k| 缠论K线Py::from_rc(Rc::clone(k)))
|
||||
.map(|k| crate::kline_py::chan_kline_to_py(py, Arc::clone(k)))
|
||||
}
|
||||
|
||||
#[getter]
|
||||
@@ -480,54 +546,83 @@ impl 观察者Py {
|
||||
缠论配置Py::from_rust_config(&self.obs().配置)
|
||||
}
|
||||
|
||||
/// 清空所有分析序列,重置为初始状态
|
||||
fn 重置基础序列(&mut self) {
|
||||
self.obs_mut().重置基础序列();
|
||||
}
|
||||
|
||||
/// 核心入口 — 投喂一根原始K线,增量更新所有层级
|
||||
fn 增加原始K线(&mut self, 普K: &Bound<'_, K线Py>) {
|
||||
self.obs_mut().增加原始K线((*普K.borrow().inner).clone());
|
||||
}
|
||||
|
||||
/// 投喂原始数据 — 便捷入口,直接从 OHLCV 创建 K线 并通过 Python 分发 增加原始K线,
|
||||
/// 确保子类重写的 增加原始K线 被正确调用。
|
||||
fn 投喂原始数据(
|
||||
slf: &Bound<'_, Self>,
|
||||
时间戳: i64,
|
||||
开: f64,
|
||||
高: f64,
|
||||
低: f64,
|
||||
收: f64,
|
||||
量: f64,
|
||||
) -> PyResult<()> {
|
||||
let (符号, 周期) = {
|
||||
let me = slf.borrow();
|
||||
let obs = me.obs();
|
||||
(obs.符号.clone(), obs.周期)
|
||||
};
|
||||
let kline = bar_to_py(
|
||||
slf.py(),
|
||||
Arc::new(chanlun::kline::bar::K线::创建普K(
|
||||
&符号, 时间戳, 开, 高, 低, 收, 量, 0, 周期,
|
||||
)),
|
||||
);
|
||||
slf.call_method1("增加原始K线", (kline,))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 加载本地数据 — 从 .nb 文件加载K线数据(先重置,再通过 Python dispatch 逐根投喂,
|
||||
/// 确保子类重写的 增加原始K线 被正确调用)。
|
||||
fn 加载本地数据(slf: &Bound<'_, Self>, 文件路径: &str) -> PyResult<()> {
|
||||
let py = slf.py();
|
||||
// 重置基础序列(通过 Python 分发,支持子类重写)
|
||||
slf.call_method1("重置基础序列", ())?;
|
||||
|
||||
// 重置基础序列
|
||||
slf.borrow_mut().obs_mut().重置基础序列();
|
||||
|
||||
// 解析文件得到 K线 列表
|
||||
let bars = slf
|
||||
.borrow()
|
||||
.obs()
|
||||
.解析本地数据(文件路径)
|
||||
.map_err(|e| pyo3::exceptions::PyValueError::new_err(e))?;
|
||||
|
||||
// 通过 Python dispatch 逐根投喂,确保子类重写生效
|
||||
for k线 in bars {
|
||||
let k线_py = Py::new(
|
||||
py,
|
||||
K线Py {
|
||||
inner: Rc::new(k线),
|
||||
},
|
||||
)?;
|
||||
slf.call_method1("增加原始K线", (k线_py,))?;
|
||||
// 读取文件,通过 Python dispatch 逐根投喂(支持子类重写 增加原始K线)
|
||||
let data = std::fs::read(文件路径)
|
||||
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("read file: {}", e)))?;
|
||||
let size: usize = 48;
|
||||
for i in 0..data.len() / size {
|
||||
let offset = i * size;
|
||||
if let Some((时间戳, 开, 高, 低, 收, 量)) =
|
||||
chanlun::kline::bar::K线::解析原始数据(&data[offset..offset + size])
|
||||
{
|
||||
slf.call_method1("投喂原始数据", (时间戳, 开, 高, 低, 收, 量))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 静态重新分析(占位方法)
|
||||
fn 静态重新分析(&mut self) {
|
||||
self.obs_mut().静态重新分析();
|
||||
}
|
||||
|
||||
#[pyo3(signature = (root = None))]
|
||||
/// 拆分各序列数据,单独存文件,文件名为对应变量名
|
||||
fn 测试_保存数据(&self, root: Option<&str>) {
|
||||
self.obs().测试_保存数据(root);
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (文件路径, 配置 = None))]
|
||||
#[pyo3(signature = (观察员, 文件路径, 配置 = None))]
|
||||
/// :param 观察员: 观察者实例
|
||||
/// :param 文件路径: 数据文件路径 格式如: btcusd-300-1631772074-1632222374.nb
|
||||
/// :param 配置: 缠论配置
|
||||
/// :return: 观察者实例
|
||||
fn 读取数据文件(
|
||||
cls: &Bound<'_, PyType>,
|
||||
_cls: &Bound<'_, PyType>,
|
||||
观察员: &Bound<'_, Self>,
|
||||
文件路径: &str,
|
||||
配置: Option<&Bound<'_, 缠论配置Py>>,
|
||||
py: Python<'_>,
|
||||
@@ -555,31 +650,19 @@ impl 观察者Py {
|
||||
.parse()
|
||||
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("parse period: {}", e)))?;
|
||||
|
||||
// 通过 cls 构造实例(支持子类化)
|
||||
let cfg_py = 缠论配置Py::from_rust_config(&config)?;
|
||||
let cfg_obj = Py::new(py, cfg_py)?;
|
||||
let obj = cls.call1((符号.clone(), 周期, cfg_obj))?;
|
||||
|
||||
// 读取文件并通过 Python 分发逐根投喂(支持子类重写 增加原始K线)
|
||||
let data = std::fs::read(文件路径)
|
||||
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("read file: {}", e)))?;
|
||||
let size: usize = 48;
|
||||
for i in 0..data.len() / size {
|
||||
let offset = i * size;
|
||||
if let Some(k线) =
|
||||
chanlun::kline::bar::K线::from_bytes(&data[offset..offset + size], 周期, &符号)
|
||||
{
|
||||
let k线_py = Py::new(
|
||||
py,
|
||||
K线Py {
|
||||
inner: Rc::new(k线),
|
||||
},
|
||||
)?;
|
||||
obj.call_method1("增加原始K线", (k线_py,))?;
|
||||
}
|
||||
// 设置观察员属性
|
||||
{
|
||||
let slf_ref = 观察员.borrow_mut();
|
||||
let mut obs_mut = slf_ref.obs_mut();
|
||||
obs_mut.符号 = 符号;
|
||||
obs_mut.周期 = 周期;
|
||||
obs_mut.配置 = config;
|
||||
}
|
||||
|
||||
Ok(obj.unbind())
|
||||
// 调用加载本地数据
|
||||
观察员.call_method1("加载本地数据", (文件路径,))?;
|
||||
|
||||
Ok(观察员.clone().unbind().into())
|
||||
}
|
||||
|
||||
// ---- 序列 getters ----
|
||||
@@ -588,18 +671,38 @@ impl 观察者Py {
|
||||
fn 普通K线序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for k in &self.obs().普通K线序列 {
|
||||
list.append(K线Py {
|
||||
inner: Rc::clone(k),
|
||||
})?;
|
||||
list.append(bar_to_py(py, Arc::clone(k)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 基础缠K序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for k in &self.obs().基础缠K序列 {
|
||||
list.append(crate::kline_py::chan_kline_to_py(py, Arc::clone(k)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
|
||||
#[setter]
|
||||
#[pyo3(name = "基础缠K序列")]
|
||||
fn 设置_基础缠K序列(&mut self, value: &Bound<'_, PyAny>) -> PyResult<()> {
|
||||
let list: &Bound<'_, pyo3::types::PyList> = value.cast()?;
|
||||
let mut vec = Vec::new();
|
||||
for item in list {
|
||||
let 缠k: PyRef<'_, 缠论K线Py> = item.extract()?;
|
||||
vec.push(Arc::clone(&缠k.inner));
|
||||
}
|
||||
self.obs_mut().基础缠K序列 = vec;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 缠论K线序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for k in &self.obs().缠论K线序列 {
|
||||
list.append(缠论K线Py::from_rc(Rc::clone(k)))?;
|
||||
list.append(crate::kline_py::chan_kline_to_py(py, Arc::clone(k)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -608,9 +711,7 @@ impl 观察者Py {
|
||||
fn 分型序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for f in &self.obs().分型序列 {
|
||||
list.append(分型Py {
|
||||
inner: Rc::clone(f),
|
||||
})?;
|
||||
list.append(fractal_to_py(py, Arc::clone(f)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -619,9 +720,7 @@ impl 观察者Py {
|
||||
fn 笔序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for d in &self.obs().笔序列 {
|
||||
list.append(虚线Py {
|
||||
inner: Rc::clone(d),
|
||||
})?;
|
||||
list.append(dashed_to_py(py, Arc::clone(d)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -630,9 +729,7 @@ impl 观察者Py {
|
||||
fn 笔_中枢序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for h in &self.obs().笔_中枢序列 {
|
||||
list.append(中枢Py {
|
||||
inner: Rc::clone(h),
|
||||
})?;
|
||||
list.append(hub_to_py(py, Arc::clone(h)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -641,9 +738,7 @@ impl 观察者Py {
|
||||
fn 线段序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for d in &self.obs().线段序列 {
|
||||
list.append(虚线Py {
|
||||
inner: Rc::clone(d),
|
||||
})?;
|
||||
list.append(dashed_to_py(py, Arc::clone(d)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -652,9 +747,7 @@ impl 观察者Py {
|
||||
fn 中枢序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for h in &self.obs().中枢序列 {
|
||||
list.append(中枢Py {
|
||||
inner: Rc::clone(h),
|
||||
})?;
|
||||
list.append(hub_to_py(py, Arc::clone(h)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -663,9 +756,7 @@ impl 观察者Py {
|
||||
fn 扩展线段序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for d in &self.obs().扩展线段序列 {
|
||||
list.append(虚线Py {
|
||||
inner: Rc::clone(d),
|
||||
})?;
|
||||
list.append(dashed_to_py(py, Arc::clone(d)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -674,9 +765,7 @@ impl 观察者Py {
|
||||
fn 扩展中枢序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for h in &self.obs().扩展中枢序列 {
|
||||
list.append(中枢Py {
|
||||
inner: Rc::clone(h),
|
||||
})?;
|
||||
list.append(hub_to_py(py, Arc::clone(h)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -685,9 +774,7 @@ impl 观察者Py {
|
||||
fn 扩展线段序列_线段(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for d in &self.obs().扩展线段序列_线段 {
|
||||
list.append(虚线Py {
|
||||
inner: Rc::clone(d),
|
||||
})?;
|
||||
list.append(dashed_to_py(py, Arc::clone(d)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -696,9 +783,7 @@ impl 观察者Py {
|
||||
fn 扩展中枢序列_线段(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for h in &self.obs().扩展中枢序列_线段 {
|
||||
list.append(中枢Py {
|
||||
inner: Rc::clone(h),
|
||||
})?;
|
||||
list.append(hub_to_py(py, Arc::clone(h)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -707,9 +792,7 @@ impl 观察者Py {
|
||||
fn 线段_线段序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for d in &self.obs().线段_线段序列 {
|
||||
list.append(虚线Py {
|
||||
inner: Rc::clone(d),
|
||||
})?;
|
||||
list.append(dashed_to_py(py, Arc::clone(d)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -718,9 +801,7 @@ impl 观察者Py {
|
||||
fn 线段_中枢序列(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for h in &self.obs().线段_中枢序列 {
|
||||
list.append(中枢Py {
|
||||
inner: Rc::clone(h),
|
||||
})?;
|
||||
list.append(hub_to_py(py, Arc::clone(h)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -729,9 +810,7 @@ impl 观察者Py {
|
||||
fn 扩展线段序列_扩展线段(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for d in &self.obs().扩展线段序列_扩展线段 {
|
||||
list.append(虚线Py {
|
||||
inner: Rc::clone(d),
|
||||
})?;
|
||||
list.append(dashed_to_py(py, Arc::clone(d)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -740,9 +819,7 @@ impl 观察者Py {
|
||||
fn 扩展中枢序列_扩展线段(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let list = pyo3::types::PyList::empty(py);
|
||||
for h in &self.obs().扩展中枢序列_扩展线段 {
|
||||
list.append(中枢Py {
|
||||
inner: Rc::clone(h),
|
||||
})?;
|
||||
list.append(hub_to_py(py, Arc::clone(h)))?;
|
||||
}
|
||||
Ok(list.into())
|
||||
}
|
||||
@@ -760,7 +837,7 @@ impl 观察者Py {
|
||||
/// 投喂(时间戳, 开盘价, 最高价, 最低价, 收盘价, 成交量) -> list[(周期, K线)]
|
||||
/// — 快捷入口,免去构造K线对象
|
||||
/// 获取当前K线(周期) -> K线|None — 获取指定周期的当前合成结果
|
||||
#[pyclass(name = "K线合成器", unsendable)]
|
||||
#[pyclass(name = "K线合成器", module = "chanlun._chanlun")]
|
||||
pub struct K线合成器Py {
|
||||
pub(crate) inner: chanlun::business::synthesizer::K线合成器,
|
||||
}
|
||||
@@ -774,18 +851,20 @@ impl K线合成器Py {
|
||||
}
|
||||
}
|
||||
|
||||
/// 统一入口 — 投喂最小周期K线,自动合成大周期并分发给各周期观察者
|
||||
fn 投喂K线(
|
||||
&mut self,
|
||||
普K: &Bound<'_, K线Py>,
|
||||
py: Python<'_>,
|
||||
) -> PyResult<Vec<(i64, K线Py)>> {
|
||||
) -> PyResult<Vec<(i64, Py<K线Py>)>> {
|
||||
let results = self.inner.投喂K线((*普K.borrow().inner).clone());
|
||||
Ok(results
|
||||
.into_iter()
|
||||
.map(|(周期, k)| (周期, K线Py { inner: Rc::new(k) }))
|
||||
.map(|(周期, k)| (周期, bar_to_py(py, Arc::new(k))))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 投喂原始tick数据
|
||||
fn 投喂(
|
||||
&mut self,
|
||||
时间戳: i64,
|
||||
@@ -794,7 +873,8 @@ impl K线合成器Py {
|
||||
低: f64,
|
||||
收: f64,
|
||||
量: f64,
|
||||
) -> Vec<(i64, K线Py)> {
|
||||
py: Python<'_>,
|
||||
) -> Vec<(i64, Py<K线Py>)> {
|
||||
let min_cycle = self.inner.周期组.iter().copied().min().unwrap_or(1);
|
||||
let k = chanlun::kline::bar::K线::创建普K(
|
||||
&self.inner.标识,
|
||||
@@ -810,14 +890,15 @@ impl K线合成器Py {
|
||||
let results = self.inner.投喂K线(k);
|
||||
results
|
||||
.into_iter()
|
||||
.map(|(周期, k2)| (周期, K线Py { inner: Rc::new(k2) }))
|
||||
.map(|(周期, k2)| (周期, bar_to_py(py, Arc::new(k2))))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn 获取当前K线(&self, 周期: i64) -> Option<K线Py> {
|
||||
self.inner.获取当前K线(周期).map(|k| K线Py {
|
||||
inner: Rc::new(k.clone()),
|
||||
})
|
||||
/// 获取指定周期当前正在合成的K线
|
||||
fn 获取当前K线(&self, 周期: i64, py: Python<'_>) -> Option<Py<K线Py>> {
|
||||
self.inner
|
||||
.获取当前K线(周期)
|
||||
.map(|k| bar_to_py(py, Arc::new(k.clone())))
|
||||
}
|
||||
|
||||
#[getter]
|
||||
@@ -844,7 +925,7 @@ impl K线合成器Py {
|
||||
/// 方法:
|
||||
/// 投喂K线(普K) — 喂入最小周期K线,自动合成大周期并分发给各周期观察者
|
||||
/// 测试_保存数据(root?) — 保存各周期的分析数据到文件
|
||||
#[pyclass(name = "立体分析器", unsendable)]
|
||||
#[pyclass(name = "立体分析器", module = "chanlun._chanlun")]
|
||||
pub struct 立体分析器Py {
|
||||
pub(crate) inner: chanlun::business::multi_frame::立体分析器,
|
||||
}
|
||||
@@ -866,7 +947,7 @@ impl 立体分析器Py {
|
||||
};
|
||||
let cfg_map: Option<HashMap<i64, chanlun::config::缠论配置>> = match 配置组 {
|
||||
Some(dict_any) => {
|
||||
let dict = dict_any.downcast::<pyo3::types::PyDict>()?;
|
||||
let dict = dict_any.cast::<pyo3::types::PyDict>()?;
|
||||
let mut map = HashMap::new();
|
||||
for (key, value) in dict.iter() {
|
||||
let period: i64 = key.extract()?;
|
||||
@@ -884,6 +965,7 @@ impl 立体分析器Py {
|
||||
})
|
||||
}
|
||||
|
||||
/// 统一入口 — 投喂最小周期K线,自动合成大周期并分发给各周期观察者
|
||||
fn 投喂K线(&mut self, 普K: &Bound<'_, K线Py>) {
|
||||
self.inner.投喂K线((*普K.borrow().inner).clone());
|
||||
}
|
||||
@@ -894,6 +976,7 @@ impl 立体分析器Py {
|
||||
.map(|rc| 观察者Py { inner: Some(rc) })
|
||||
}
|
||||
|
||||
/// 拆分各序列数据,单独存文件,文件名为对应变量名
|
||||
fn 测试_保存数据(&self) {
|
||||
self.inner.测试_保存数据();
|
||||
}
|
||||
|
||||
+110
-12
@@ -91,7 +91,7 @@ use std::collections::HashMap;
|
||||
/// 不推送() -> 缠论配置 (classmethod) — 创建关闭所有推送的配置副本
|
||||
/// 按序号重组字典(默认配置, 原始字典) -> dict (classmethod) — 按默认配置的键序重排字典
|
||||
/// 对比(other) -> dict — 返回与另一个配置的差异字段
|
||||
#[pyclass(name = "缠论配置")]
|
||||
#[pyclass(name = "缠论配置", module = "chanlun._chanlun")]
|
||||
pub struct 缠论配置Py {
|
||||
fields: HashMap<String, Py<PyAny>>,
|
||||
}
|
||||
@@ -183,26 +183,23 @@ impl 缠论配置Py {
|
||||
}
|
||||
|
||||
/// 保存配置到 JSON 文件(默认路径 "缠论配置.json")。
|
||||
fn 保存配置(&self, py: Python<'_>, path: Option<&str>) -> PyResult<()> {
|
||||
let path = path.unwrap_or("缠论配置.json");
|
||||
#[pyo3(signature = (path = "缠论配置.json"))]
|
||||
fn 保存配置(&self, py: Python<'_>, path: &str) -> PyResult<()> {
|
||||
let json = self.to_json(py)?;
|
||||
std::fs::write(path, json).map_err(|e| pyo3::exceptions::PyIOError::new_err(e.to_string()))
|
||||
}
|
||||
|
||||
/// 从 JSON 文件加载配置(默认路径 "缠论配置.json")。
|
||||
#[classmethod]
|
||||
fn 加载配置(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
py: Python<'_>,
|
||||
path: Option<&str>,
|
||||
) -> PyResult<Self> {
|
||||
let path = path.unwrap_or("缠论配置.json");
|
||||
#[pyo3(signature = (path = "缠论配置.json"))]
|
||||
fn 加载配置(_cls: &Bound<'_, PyType>, py: Python<'_>, path: &str) -> PyResult<Self> {
|
||||
let json_str = std::fs::read_to_string(path)
|
||||
.map_err(|e| pyo3::exceptions::PyIOError::new_err(e.to_string()))?;
|
||||
Self::from_json_str(py, &json_str)
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// :param data: 字典数据
|
||||
fn from_dict(_cls: &Bound<'_, PyType>, data: &Bound<'_, PyDict>) -> PyResult<Self> {
|
||||
let default_config = chanlun::config::缠论配置::default();
|
||||
let mut fields = config_to_field_dict(&default_config)?;
|
||||
@@ -220,11 +217,13 @@ impl 缠论配置Py {
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// :param json_str: JSON字符串
|
||||
fn from_json(_cls: &Bound<'_, PyType>, py: Python<'_>, json_str: &str) -> PyResult<Self> {
|
||||
Self::from_json_str(py, json_str)
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// 创建不推送任何图表的静默配置(用于纯计算场景)
|
||||
fn 不推送(_cls: &Bound<'_, PyType>) -> PyResult<Self> {
|
||||
let config = chanlun::config::缠论配置::default().不推送();
|
||||
let fields = config_to_field_dict(&config)?;
|
||||
@@ -232,6 +231,7 @@ impl 缠论配置Py {
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// 将形如 "1_open", "1_close", "2_open", "name" 的字典重组为嵌套结构
|
||||
fn 按序号重组字典(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
默认配置: &Bound<'_, PyAny>,
|
||||
@@ -239,7 +239,7 @@ impl 缠论配置Py {
|
||||
) -> PyResult<Py<PyDict>> {
|
||||
let py = 原始字典.py();
|
||||
let result = PyDict::new(py);
|
||||
if let Ok(default_dict) = 默认配置.downcast::<PyDict>() {
|
||||
if let Ok(default_dict) = 默认配置.cast::<PyDict>() {
|
||||
for (key, value) in default_dict.iter() {
|
||||
if 原始字典.contains(&key)? {
|
||||
result.set_item(key.clone(), 原始字典.get_item(&key)?)?;
|
||||
@@ -251,6 +251,8 @@ impl 缠论配置Py {
|
||||
Ok(result.into())
|
||||
}
|
||||
|
||||
/// 比较当前配置与另一个配置的差异
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn 对比(
|
||||
&self,
|
||||
py: Python<'_>,
|
||||
@@ -289,7 +291,10 @@ impl 缠论配置Py {
|
||||
Ok(Self { fields })
|
||||
}
|
||||
|
||||
pub(crate) fn to_rust_config(&self, py: Python<'_>) -> PyResult<chanlun::config::缠论配置> {
|
||||
pub(crate) fn to_rust_config(
|
||||
&self,
|
||||
_py: Python<'_>,
|
||||
) -> PyResult<chanlun::config::缠论配置> {
|
||||
dict_to_rust_config(&self.fields)
|
||||
}
|
||||
|
||||
@@ -331,11 +336,104 @@ fn dict_to_rust_config(
|
||||
let mut value: serde_json::Value = serde_json::from_str(&json_str)
|
||||
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("配置转换失败: {e}")))?;
|
||||
coerce_strings_to_numbers(&mut value);
|
||||
serde_json::from_value(value)
|
||||
|
||||
// 获取默认配置的 JSON 表示作为 schema
|
||||
let default_config = chanlun::config::缠论配置::default();
|
||||
let default_json = serde_json::to_value(&default_config)
|
||||
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("配置转换失败: {e}")))?;
|
||||
|
||||
// 用默认值做基准,只合并类型匹配的字段
|
||||
let mut merged = default_json.clone();
|
||||
if let serde_json::Value::Object(ref input_map) = value {
|
||||
if let serde_json::Value::Object(ref default_map) = default_json {
|
||||
for (key, input_val) in input_map {
|
||||
if let Some(default_val) = default_map.get(key) {
|
||||
match validate_field(key, input_val, default_val) {
|
||||
Ok(()) => {
|
||||
merged[key] = input_val.clone();
|
||||
}
|
||||
Err(msg) => {
|
||||
eprintln!("\x1b[33m[配置警告]\x1b[m {key}: {msg},已使用默认值 {default_val}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
serde_json::from_value(merged)
|
||||
.map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("配置转换失败: {e}")))
|
||||
})
|
||||
}
|
||||
|
||||
/// 字符串字段的有效值集合
|
||||
fn valid_string_values(field: &str) -> Option<&'static [&'static str]> {
|
||||
match field {
|
||||
"指标计算方式" => Some(&[
|
||||
"开",
|
||||
"高",
|
||||
"低",
|
||||
"收",
|
||||
"高低均值",
|
||||
"高低收均值",
|
||||
"开高低收均值",
|
||||
]),
|
||||
"买卖点_指标模式" => Some(&["任意", "配置", "全量", "相对"]),
|
||||
"线段内部背驰_模式" => Some(&["任意", "配置", "全量", "相对"]),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 验证单个字段的值是否与默认值类型兼容
|
||||
fn validate_field(
|
||||
key: &str,
|
||||
input: &serde_json::Value,
|
||||
default: &serde_json::Value,
|
||||
) -> Result<(), String> {
|
||||
use serde_json::Value;
|
||||
|
||||
// 输入为 null → 跳过(保留默认)
|
||||
if input.is_null() {
|
||||
return Err("值为 null".into());
|
||||
}
|
||||
|
||||
// 字符串字段:检查有效值白名单
|
||||
if default.is_string() && input.is_string() {
|
||||
if let Some(valid) = valid_string_values(key) {
|
||||
let s = input.as_str().unwrap();
|
||||
if !valid.contains(&s) {
|
||||
return Err(format!("\"{s}\" 不在有效值 {valid:?} 内"));
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// 类型匹配:直接通过
|
||||
match (default, input) {
|
||||
(Value::Bool(_), Value::Bool(_)) => return Ok(()),
|
||||
(Value::Number(_), Value::Number(_)) => return Ok(()),
|
||||
(Value::String(_), Value::String(_)) => return Ok(()),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
// 类型不匹配
|
||||
let type_name = match input {
|
||||
Value::Bool(_) => "布尔",
|
||||
Value::Number(_) => "数值",
|
||||
Value::String(_) => "字符串",
|
||||
Value::Array(_) => "数组",
|
||||
Value::Object(_) => "字典",
|
||||
Value::Null => "null",
|
||||
};
|
||||
let expected = match default {
|
||||
Value::Bool(_) => "布尔",
|
||||
Value::Number(_) => "数值",
|
||||
Value::String(_) => "字符串",
|
||||
_ => "其他",
|
||||
};
|
||||
Err(format!("类型不匹配(需要 {expected},收到 {type_name})"))
|
||||
}
|
||||
|
||||
/// 递归遍历 JSON Value,将数字/布尔字符串转为对应类型。
|
||||
fn coerce_strings_to_numbers(value: &mut serde_json::Value) {
|
||||
match value {
|
||||
|
||||
@@ -43,7 +43,11 @@ use pyo3::types::PyType;
|
||||
/// 增量计算(前一个MACD, 当前收盘价, 当前时间) -> 平滑异同移动平均线
|
||||
/// — 基于前一根的 EMA 状态增量更新,用于流式计算
|
||||
/// 增量计算_K线(前一个MACD, 当前K线, 计算方式) -> 平滑异同移动平均线
|
||||
#[pyclass(name = "平滑异同移动平均线")]
|
||||
#[pyclass(
|
||||
name = "平滑异同移动平均线",
|
||||
module = "chanlun._chanlun",
|
||||
from_py_object
|
||||
)]
|
||||
#[derive(Clone)]
|
||||
pub struct 平滑异同移动平均线Py {
|
||||
pub(crate) inner: chanlun::indicators::平滑异同移动平均线,
|
||||
@@ -124,6 +128,7 @@ impl 平滑异同移动平均线Py {
|
||||
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (初始收盘价, 初始时间, 快线周期 = None, 慢线周期 = None, 信号周期 = None))]
|
||||
/// 首次计算MACD指标(没有历史数据时使用)
|
||||
fn 首次计算(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
初始收盘价: f64,
|
||||
@@ -144,6 +149,7 @@ impl 平滑异同移动平均线Py {
|
||||
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (k线, 计算方式, 快线周期 = None, 慢线周期 = None, 信号周期 = None))]
|
||||
/// :param k线: 原始K线
|
||||
fn 首次计算_K线(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
k线: &Bound<'_, PyAny>,
|
||||
@@ -165,6 +171,7 @@ impl 平滑异同移动平均线Py {
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// 基于前一个MACD指标增量计算当前MACD指标
|
||||
fn 增量计算(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
前一个MACD: &Bound<'_, 平滑异同移动平均线Py>,
|
||||
@@ -180,6 +187,7 @@ impl 平滑异同移动平均线Py {
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// :param 前一个MACD: 前一个MACD指标对象
|
||||
fn 增量计算_K线(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
前一个MACD: &Bound<'_, 平滑异同移动平均线Py>,
|
||||
@@ -214,7 +222,7 @@ impl 平滑异同移动平均线Py {
|
||||
/// 首次计算_K线(k线, 计算方式, ...)
|
||||
/// 增量计算(前一个RSI, 当前收盘价, 当前时间)
|
||||
/// 增量计算_K线(前一个RSI, 当前K线, 计算方式)
|
||||
#[pyclass(name = "相对强弱指数")]
|
||||
#[pyclass(name = "相对强弱指数", module = "chanlun._chanlun", from_py_object)]
|
||||
#[derive(Clone)]
|
||||
pub struct 相对强弱指数Py {
|
||||
pub(crate) inner: chanlun::indicators::相对强弱指数,
|
||||
@@ -294,6 +302,7 @@ impl 相对强弱指数Py {
|
||||
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (初始收盘价, 初始时间, 周期 = None, 超买阈值 = None, 超卖阈值 = None, RSI_SMA周期 = None))]
|
||||
/// 首次计算RSI(没有足够历史数据时使用)
|
||||
fn 首次计算(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
初始收盘价: f64,
|
||||
@@ -317,6 +326,7 @@ impl 相对强弱指数Py {
|
||||
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (k线, 计算方式, 周期 = None, 超买阈值 = None, 超卖阈值 = None, RSI_SMA周期 = None))]
|
||||
/// :param k线: 原始K线
|
||||
fn 首次计算_K线(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
k线: &Bound<'_, PyAny>,
|
||||
@@ -340,6 +350,7 @@ impl 相对强弱指数Py {
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// 基于前一个RSI指标增量计算当前RSI
|
||||
fn 增量计算(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
前一个RSI: &Bound<'_, 相对强弱指数Py>,
|
||||
@@ -356,6 +367,7 @@ impl 相对强弱指数Py {
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// :param 前一个RSI: 前一个RSI指标对象
|
||||
fn 增量计算_K线(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
前一个RSI: &Bound<'_, 相对强弱指数Py>,
|
||||
@@ -390,7 +402,7 @@ impl 相对强弱指数Py {
|
||||
/// 首次计算_K线(k线, 计算方式, ...)
|
||||
/// 增量计算(前一个KDJ, 最高价, 最低价, 收盘价, 时间)
|
||||
/// 增量计算_K线(前一个KDJ, 当前K线, 计算方式)
|
||||
#[pyclass(name = "随机指标")]
|
||||
#[pyclass(name = "随机指标", module = "chanlun._chanlun", from_py_object)]
|
||||
#[derive(Clone)]
|
||||
pub struct 随机指标Py {
|
||||
pub(crate) inner: chanlun::indicators::随机指标,
|
||||
@@ -488,6 +500,7 @@ impl 随机指标Py {
|
||||
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (初始最高价, 初始最低价, 初始收盘价, 初始时间, N = None, M1 = None, M2 = None, 超买阈值 = None, 超卖阈值 = None))]
|
||||
/// 首次计算KDJ(无历史数据时)
|
||||
fn 首次计算(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
初始最高价: f64,
|
||||
@@ -517,6 +530,7 @@ impl 随机指标Py {
|
||||
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (k线, _计算方式, RSV周期 = None, K值平滑周期 = None, D值平滑周期 = None, 超买阈值 = None, 超卖阈值 = None))]
|
||||
/// :param k线: 原始K线
|
||||
fn 首次计算_K线(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
k线: &Bound<'_, PyAny>,
|
||||
@@ -546,6 +560,7 @@ impl 随机指标Py {
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// 基于前一个KDJ对象和当前三价,增量计算当前KDJ值
|
||||
fn 增量计算(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
前一个KDJ: &Bound<'_, 随机指标Py>,
|
||||
@@ -566,6 +581,7 @@ impl 随机指标Py {
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// :param 前一个KDJ: 前一个KDJ指标对象
|
||||
fn 增量计算_K线(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
前一个KDJ: &Bound<'_, 随机指标Py>,
|
||||
@@ -595,12 +611,13 @@ impl 随机指标Py {
|
||||
/// K线取值(k线, 指标计算方式) -> float (classmethod)
|
||||
/// 根据计算方式从K线提取数值。
|
||||
/// 计算方式: "收盘价" / "开盘价" / "高" / "低" / "均值" 等
|
||||
#[pyclass(name = "指标")]
|
||||
#[pyclass(name = "指标", module = "chanlun._chanlun")]
|
||||
pub struct 指标Py;
|
||||
|
||||
#[pymethods]
|
||||
impl 指标Py {
|
||||
#[classmethod]
|
||||
/// 根据计算方式从K线中取值
|
||||
fn K线取值(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
k线: &Bound<'_, PyAny>,
|
||||
|
||||
+201
-111
@@ -23,9 +23,11 @@
|
||||
*/
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::{PyBytes, PyType};
|
||||
use pyo3::types::{PyBytes, PyDict, PyType};
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
|
||||
use crate::config_py::缠论配置Py;
|
||||
use crate::indicators_py::{平滑异同移动平均线Py, 相对强弱指数Py, 随机指标Py};
|
||||
@@ -52,9 +54,9 @@ use crate::types_py::相对方向Py;
|
||||
/// 获取MACD(K线序列, 计算方式, 快线周期?, 慢线周期?, 信号周期?) -> list[平滑异同移动平均线]
|
||||
/// — 对整个K线序列批量计算 MACD
|
||||
/// 截取(序列, 起点K线, 终点K线) -> list — 按时间戳截取K线区间
|
||||
#[pyclass(name = "K线", unsendable)]
|
||||
#[pyclass(name = "K线", module = "chanlun._chanlun")]
|
||||
pub struct K线Py {
|
||||
pub(crate) inner: Rc<chanlun::kline::bar::K线>,
|
||||
pub(crate) inner: Arc<chanlun::kline::bar::K线>,
|
||||
}
|
||||
|
||||
#[pymethods]
|
||||
@@ -73,7 +75,7 @@ impl K线Py {
|
||||
成交量: f64,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner: Rc::new(chanlun::kline::bar::K线 {
|
||||
inner: Arc::new(chanlun::kline::bar::K线 {
|
||||
标识: 标识.to_string(),
|
||||
序号,
|
||||
周期,
|
||||
@@ -94,88 +96,51 @@ impl K线Py {
|
||||
fn 标识(&self) -> String {
|
||||
self.inner.标识.clone()
|
||||
}
|
||||
#[setter]
|
||||
fn set_标识(&mut self, v: String) {
|
||||
Rc::make_mut(&mut self.inner).标识 = v;
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 序号(&self) -> i64 {
|
||||
self.inner.序号
|
||||
}
|
||||
#[setter]
|
||||
fn set_序号(&mut self, v: i64) {
|
||||
Rc::make_mut(&mut self.inner).序号 = v;
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 周期(&self) -> i64 {
|
||||
self.inner.周期
|
||||
}
|
||||
#[setter]
|
||||
fn set_周期(&mut self, v: i64) {
|
||||
Rc::make_mut(&mut self.inner).周期 = v;
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 时间戳(&self) -> i64 {
|
||||
self.inner.时间戳
|
||||
}
|
||||
#[setter]
|
||||
fn set_时间戳(&mut self, v: i64) {
|
||||
Rc::make_mut(&mut self.inner).时间戳 = v;
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 高(&self) -> f64 {
|
||||
self.inner.高
|
||||
}
|
||||
#[setter]
|
||||
fn set_高(&mut self, v: f64) {
|
||||
Rc::make_mut(&mut self.inner).高 = v;
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 低(&self) -> f64 {
|
||||
self.inner.低
|
||||
}
|
||||
#[setter]
|
||||
fn set_低(&mut self, v: f64) {
|
||||
Rc::make_mut(&mut self.inner).低 = v;
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 开盘价(&self) -> f64 {
|
||||
self.inner.开盘价
|
||||
}
|
||||
#[setter]
|
||||
fn set_开盘价(&mut self, v: f64) {
|
||||
Rc::make_mut(&mut self.inner).开盘价 = v;
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 收盘价(&self) -> f64 {
|
||||
self.inner.收盘价
|
||||
}
|
||||
#[setter]
|
||||
fn set_收盘价(&mut self, v: f64) {
|
||||
Rc::make_mut(&mut self.inner).收盘价 = v;
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 成交量(&self) -> f64 {
|
||||
self.inner.成交量
|
||||
}
|
||||
#[setter]
|
||||
fn set_成交量(&mut self, v: f64) {
|
||||
Rc::make_mut(&mut self.inner).成交量 = v;
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 方向(&self) -> 相对方向Py {
|
||||
相对方向Py {
|
||||
inner: self.inner.方向(),
|
||||
}
|
||||
/// :return: 相对方向.向上(开盘<收盘)或 相对方向.向下(开盘>收盘)
|
||||
fn 方向(&self, py: Python<'_>) -> Py<相对方向Py> {
|
||||
crate::types_py::获取相对方向单例(py, self.inner.方向())
|
||||
}
|
||||
|
||||
#[getter]
|
||||
@@ -202,6 +167,32 @@ impl K线Py {
|
||||
.map(|k| 随机指标Py { inner: k.clone() })
|
||||
}
|
||||
|
||||
/// pandas 兼容 — 返回所有字段构成的字典
|
||||
#[getter]
|
||||
fn __dict__(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
|
||||
let dict = PyDict::new(py);
|
||||
dict.set_item("标识", self.标识())?;
|
||||
dict.set_item("序号", self.序号())?;
|
||||
dict.set_item("周期", self.周期())?;
|
||||
dict.set_item("时间戳", self.时间戳())?;
|
||||
dict.set_item("高", self.高())?;
|
||||
dict.set_item("低", self.低())?;
|
||||
dict.set_item("开盘价", self.开盘价())?;
|
||||
dict.set_item("收盘价", self.收盘价())?;
|
||||
dict.set_item("成交量", self.成交量())?;
|
||||
dict.set_item("方向", self.方向(py))?;
|
||||
if let Some(v) = self.macd() {
|
||||
dict.set_item("macd", v)?;
|
||||
}
|
||||
if let Some(v) = self.rsi() {
|
||||
dict.set_item("rsi", v)?;
|
||||
}
|
||||
if let Some(v) = self.kdj() {
|
||||
dict.set_item("kdj", v)?;
|
||||
}
|
||||
Ok(dict.into())
|
||||
}
|
||||
|
||||
fn __str__(&self) -> String {
|
||||
format!("{}", self.inner)
|
||||
}
|
||||
@@ -216,17 +207,18 @@ impl K线Py {
|
||||
|
||||
fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool {
|
||||
if let Ok(other) = other.extract::<PyRef<'_, Self>>() {
|
||||
return Rc::as_ptr(&self.inner) == Rc::as_ptr(&other.inner);
|
||||
return Arc::as_ptr(&self.inner) == Arc::as_ptr(&other.inner);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn __hash__(&self) -> u64 {
|
||||
Rc::as_ptr(&self.inner) as u64
|
||||
Arc::as_ptr(&self.inner) as u64
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (标识, 时间戳, 开盘价, 最高价, 最低价, 收盘价, 成交量, 序号 = None, 周期 = None))]
|
||||
/// 快捷构造普通K线
|
||||
fn 创建普K(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
标识: &str,
|
||||
@@ -240,7 +232,7 @@ impl K线Py {
|
||||
周期: Option<i64>,
|
||||
) -> Self {
|
||||
Self {
|
||||
inner: Rc::new(chanlun::kline::bar::K线::创建普K(
|
||||
inner: Arc::new(chanlun::kline::bar::K线::创建普K(
|
||||
标识,
|
||||
时间戳,
|
||||
开盘价,
|
||||
@@ -255,6 +247,7 @@ impl K线Py {
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// 将K线序列保存为二进制DAT文件
|
||||
fn 保存到DAT文件(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
路径: &str,
|
||||
@@ -268,6 +261,7 @@ impl K线Py {
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// 从大端字节序二进制数据反序列化K线(兼容.dat/.nb文件格式)
|
||||
fn 读取大端字节数组(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
字节组: &Bound<'_, PyBytes>,
|
||||
@@ -276,12 +270,13 @@ impl K线Py {
|
||||
) -> Option<Self> {
|
||||
chanlun::kline::bar::K线::读取大端字节数组(字节组.as_bytes(), 周期, 标识).map(|inner| {
|
||||
Self {
|
||||
inner: Rc::new(inner),
|
||||
inner: Arc::new(inner),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// 计算指定K线区间的MACD柱面积
|
||||
fn 获取MACD(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
k线序列: Vec<Py<Self>>,
|
||||
@@ -295,27 +290,28 @@ impl K线Py {
|
||||
}
|
||||
|
||||
#[staticmethod]
|
||||
/// 按起止K线截取K线子序列
|
||||
fn 截取(
|
||||
序列: Vec<Py<Self>>,
|
||||
始: &Bound<'_, Self>,
|
||||
终: &Bound<'_, Self>,
|
||||
py: Python<'_>,
|
||||
) -> PyResult<Vec<Py<Self>>> {
|
||||
let start_ptr = Rc::as_ptr(&始.borrow().inner);
|
||||
let end_ptr = Rc::as_ptr(&终.borrow().inner);
|
||||
let start_ptr = Arc::as_ptr(&始.borrow().inner);
|
||||
let end_ptr = Arc::as_ptr(&终.borrow().inner);
|
||||
let start_ts = 始.borrow().inner.时间戳;
|
||||
let end_ts = 终.borrow().inner.时间戳;
|
||||
let start_idx = 序列
|
||||
.iter()
|
||||
.position(|k| {
|
||||
Rc::as_ptr(&k.borrow(py).inner) == start_ptr
|
||||
Arc::as_ptr(&k.borrow(py).inner) == start_ptr
|
||||
|| k.borrow(py).inner.时间戳 == start_ts
|
||||
})
|
||||
.ok_or_else(|| pyo3::exceptions::PyValueError::new_err("始 不在序列中"))?;
|
||||
let end_idx = 序列
|
||||
.iter()
|
||||
.position(|k| {
|
||||
Rc::as_ptr(&k.borrow(py).inner) == end_ptr || k.borrow(py).inner.时间戳 == end_ts
|
||||
Arc::as_ptr(&k.borrow(py).inner) == end_ptr || k.borrow(py).inner.时间戳 == end_ts
|
||||
})
|
||||
.ok_or_else(|| pyo3::exceptions::PyValueError::new_err("终 不在序列中"))?;
|
||||
if start_idx > end_idx {
|
||||
@@ -348,26 +344,75 @@ impl K线Py {
|
||||
/// 分析(缠K序列, 配置, 可以逆序包含?, 忽视顺序包含?, 可以逆序包含新?) -> (str, 分型|None)
|
||||
/// — 分析分型形成结果
|
||||
/// 截取(序列, 起点分型, 终点分型) -> list — 截取分型间的缠K子序列
|
||||
#[pyclass(name = "缠论K线", unsendable)]
|
||||
#[pyclass(name = "缠论K线", module = "chanlun._chanlun", from_py_object)]
|
||||
pub struct 缠论K线Py {
|
||||
pub(crate) inner: std::rc::Rc<chanlun::kline::chan_kline::缠论K线>,
|
||||
bsp_set: std::cell::RefCell<Option<Py<pyo3::types::PySet>>>,
|
||||
pub(crate) inner: std::sync::Arc<chanlun::kline::chan_kline::缠论K线>,
|
||||
}
|
||||
|
||||
impl 缠论K线Py {
|
||||
pub(crate) fn from_rc(inner: std::rc::Rc<chanlun::kline::chan_kline::缠论K线>) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
bsp_set: std::cell::RefCell::new(None),
|
||||
}
|
||||
pub(crate) fn from_rc(inner: std::sync::Arc<chanlun::kline::chan_kline::缠论K线>) -> Self {
|
||||
Self { inner }
|
||||
}
|
||||
}
|
||||
|
||||
/// 对象标识缓存:Arc 地址 → 规范 Python 对象
|
||||
/// 确保同一底层 Arc 指针在 Python 侧始终映射到同一 PyObject
|
||||
/// 使用全局 static 而非 thread_local!,保证跨线程对象标识和买卖点信息一致性
|
||||
static BAR_IDENTITY: std::sync::LazyLock<RwLock<HashMap<usize, Py<K线Py>>>> =
|
||||
std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
|
||||
|
||||
static KLINE_IDENTITY: std::sync::LazyLock<RwLock<HashMap<usize, Py<缠论K线Py>>>> =
|
||||
std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
|
||||
|
||||
/// 买卖点信息缓存 — 按 Arc 指针全局共享,确保所有 wrapper 看到同一 PySet
|
||||
static BSP_CACHE: std::sync::LazyLock<RwLock<HashMap<usize, Py<pyo3::types::PySet>>>> =
|
||||
std::sync::LazyLock::new(|| RwLock::new(HashMap::new()));
|
||||
|
||||
/// 将 Rc<K线> 转为 Py<K线Py>,确保同一 Rc 地址总是返回同一 Python 对象
|
||||
pub(crate) fn bar_to_py(
|
||||
py: Python<'_>,
|
||||
inner: std::sync::Arc<chanlun::kline::bar::K线>,
|
||||
) -> Py<K线Py> {
|
||||
let key = Arc::as_ptr(&inner) as usize;
|
||||
if let Some(cached) = BAR_IDENTITY
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(&key)
|
||||
.map(|p| p.clone_ref(py))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
let obj = Py::new(py, K线Py { inner }).unwrap();
|
||||
BAR_IDENTITY.write().unwrap().insert(key, obj.clone_ref(py));
|
||||
obj
|
||||
}
|
||||
|
||||
/// 将 Rc<缠论K线> 转为 Py<缠论K线Py>,确保同一 Rc 地址总是返回同一 Python 对象
|
||||
pub(crate) fn chan_kline_to_py(
|
||||
py: Python<'_>,
|
||||
inner: std::sync::Arc<chanlun::kline::chan_kline::缠论K线>,
|
||||
) -> Py<缠论K线Py> {
|
||||
let key = Arc::as_ptr(&inner) as usize;
|
||||
if let Some(cached) = KLINE_IDENTITY
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(&key)
|
||||
.map(|p| p.clone_ref(py))
|
||||
{
|
||||
return cached;
|
||||
}
|
||||
let obj = Py::new(py, 缠论K线Py::from_rc(inner)).unwrap();
|
||||
KLINE_IDENTITY
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(key, obj.clone_ref(py));
|
||||
obj
|
||||
}
|
||||
|
||||
impl Clone for 缠论K线Py {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
inner: std::rc::Rc::clone(&self.inner),
|
||||
bsp_set: std::cell::RefCell::new(None),
|
||||
inner: std::sync::Arc::clone(&self.inner),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -381,36 +426,36 @@ impl 缠论K线Py {
|
||||
|
||||
#[getter]
|
||||
fn 序号(&self) -> i64 {
|
||||
self.inner.序号
|
||||
self.inner.序号.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 时间戳(&self) -> i64 {
|
||||
self.inner.时间戳
|
||||
self.inner.时间戳.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 高(&self) -> f64 {
|
||||
self.inner.高
|
||||
self.inner.高.get()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 低(&self) -> f64 {
|
||||
self.inner.低
|
||||
self.inner.低.get()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 方向(&self) -> 相对方向Py {
|
||||
相对方向Py {
|
||||
inner: self.inner.方向,
|
||||
}
|
||||
fn 方向(&self, py: Python<'_>) -> Py<相对方向Py> {
|
||||
crate::types_py::获取相对方向单例(py, *self.inner.方向.read().unwrap())
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 分型(&self) -> Option<crate::types_py::分型结构Py> {
|
||||
fn 分型(&self, py: Python<'_>) -> Option<Py<crate::types_py::分型结构Py>> {
|
||||
self.inner
|
||||
.分型
|
||||
.map(|f| crate::types_py::分型结构Py { inner: f })
|
||||
.read()
|
||||
.unwrap()
|
||||
.map(|f| crate::types_py::获取分型结构单例(py, f))
|
||||
}
|
||||
|
||||
#[getter]
|
||||
@@ -425,7 +470,7 @@ impl 缠论K线Py {
|
||||
|
||||
#[getter]
|
||||
fn 分型特征值(&self) -> f64 {
|
||||
self.inner.分型特征值
|
||||
self.inner.分型特征值.get()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
@@ -435,14 +480,36 @@ impl 缠论K线Py {
|
||||
|
||||
#[getter]
|
||||
fn 原始结束序号(&self) -> i64 {
|
||||
self.inner.原始结束序号
|
||||
self.inner.原始结束序号.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 标的K线(&self) -> K线Py {
|
||||
K线Py {
|
||||
inner: self.inner.标的K线.clone(),
|
||||
fn 标的K线(&self, py: Python<'_>) -> Py<K线Py> {
|
||||
bar_to_py(py, self.inner.标的K线.read().unwrap().clone())
|
||||
}
|
||||
|
||||
/// pandas 兼容 — 返回所有字段构成的字典
|
||||
#[getter]
|
||||
fn __dict__(&self, py: Python<'_>) -> PyResult<Py<PyDict>> {
|
||||
let dict = PyDict::new(py);
|
||||
dict.set_item("序号", self.序号())?;
|
||||
dict.set_item("时间戳", self.时间戳())?;
|
||||
dict.set_item("高", self.高())?;
|
||||
dict.set_item("低", self.低())?;
|
||||
dict.set_item("方向", self.方向(py))?;
|
||||
dict.set_item("周期", self.周期())?;
|
||||
dict.set_item("标识", self.标识())?;
|
||||
dict.set_item("分型特征值", self.分型特征值())?;
|
||||
dict.set_item("原始起始序号", self.原始起始序号())?;
|
||||
dict.set_item("原始结束序号", self.原始结束序号())?;
|
||||
dict.set_item("与MACD柱子匹配", self.与MACD柱子匹配())?;
|
||||
dict.set_item("与RSI匹配", self.与RSI匹配())?;
|
||||
dict.set_item("与KDJ匹配", self.与KDJ匹配())?;
|
||||
|
||||
if let Some(v) = self.分型(py) {
|
||||
dict.set_item("分型", v)?;
|
||||
}
|
||||
Ok(dict.into())
|
||||
}
|
||||
|
||||
fn __str__(&self) -> String {
|
||||
@@ -455,66 +522,82 @@ impl 缠论K线Py {
|
||||
|
||||
fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool {
|
||||
if let Ok(other) = other.extract::<PyRef<'_, Self>>() {
|
||||
return Rc::as_ptr(&self.inner) == Rc::as_ptr(&other.inner);
|
||||
return Arc::as_ptr(&self.inner) == Arc::as_ptr(&other.inner);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn __hash__(&self) -> u64 {
|
||||
Rc::as_ptr(&self.inner) as u64
|
||||
Arc::as_ptr(&self.inner) as u64
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// 创建当前缠K的浅拷贝副本
|
||||
fn 镜像(&self, py: Python<'_>) -> Self {
|
||||
let mut mirror = Self {
|
||||
inner: std::rc::Rc::new(self.inner.镜像()),
|
||||
bsp_set: std::cell::RefCell::new(None),
|
||||
let mirror = Self {
|
||||
inner: std::sync::Arc::new(self.inner.镜像()),
|
||||
};
|
||||
if let Some(ref src_set) = *self.bsp_set.borrow() {
|
||||
// 复制买卖点信息到镜像
|
||||
let src_key = Arc::as_ptr(&self.inner) as usize;
|
||||
let dst_key = Arc::as_ptr(&mirror.inner) as usize;
|
||||
let cached_src = BSP_CACHE
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(&src_key)
|
||||
.map(|p| p.clone_ref(py));
|
||||
if let Some(cached_src) = cached_src {
|
||||
if let Ok(new_set) = pyo3::types::PySet::empty(py) {
|
||||
for item in src_set.bind(py).iter() {
|
||||
for item in cached_src.bind(py).iter() {
|
||||
let _ = new_set.add(item);
|
||||
}
|
||||
mirror.bsp_set = std::cell::RefCell::new(Some(new_set.into()));
|
||||
let py_set: Py<pyo3::types::PySet> = new_set.into();
|
||||
BSP_CACHE.write().unwrap().insert(dst_key, py_set);
|
||||
}
|
||||
}
|
||||
mirror
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// :return: 底分型时MACD柱<0,顶分型时MACD柱>0
|
||||
fn 与MACD柱子匹配(&self) -> bool {
|
||||
self.inner.与MACD柱子匹配()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// :return: 底分型时RSI < RSI_SMA,顶分型时RSI > RSI_SMA
|
||||
fn 与RSI匹配(&self) -> bool {
|
||||
self.inner.与RSI匹配()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// :return: 底分型时K<D,顶分型时K>D
|
||||
fn 与KDJ匹配(&self) -> bool {
|
||||
self.inner.与KDJ匹配()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
fn 买卖点信息(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
if self.bsp_set.borrow().is_none() {
|
||||
let set = pyo3::types::PySet::empty(py)?;
|
||||
for s in self.inner.买卖点信息.borrow().iter() {
|
||||
set.add(s.clone())?;
|
||||
}
|
||||
*self.bsp_set.borrow_mut() = Some(set.into());
|
||||
let key = Arc::as_ptr(&self.inner) as usize;
|
||||
// 检查全局缓存
|
||||
let cached = BSP_CACHE.read().unwrap().get(&key).map(|p| p.clone_ref(py));
|
||||
if let Some(set) = cached {
|
||||
return Ok(set.into_any());
|
||||
}
|
||||
Ok(self
|
||||
.bsp_set
|
||||
.borrow()
|
||||
.as_ref()
|
||||
// 创建新的 PySet 并存入全局缓存
|
||||
let set = pyo3::types::PySet::empty(py)?;
|
||||
BSP_CACHE.write().unwrap().insert(key, set.into());
|
||||
// 重新读取并返回(无法从 insert 获取 Py 引用,需要重新读)
|
||||
Ok(BSP_CACHE
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(&key)
|
||||
.unwrap()
|
||||
.clone_ref(py)
|
||||
.into_any())
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// 在基线序列中找到与k线时间戳对齐的时间戳
|
||||
fn 时间戳对齐(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
基线: Vec<Py<Self>>,
|
||||
@@ -523,12 +606,14 @@ impl 缠论K线Py {
|
||||
) -> i64 {
|
||||
let rc_list: Vec<_> = 基线
|
||||
.iter()
|
||||
.map(|k| std::rc::Rc::clone(&k.bind(py).borrow().inner))
|
||||
.map(|k| std::sync::Arc::clone(&k.bind(py).borrow().inner))
|
||||
.collect();
|
||||
chanlun::kline::chan_kline::缠论K线::时间戳对齐(&rc_list, &k线.borrow().inner)
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (时间戳, 高, 低, 方向, 结构, 原始序号, 普k, 之前 = None))]
|
||||
/// 创建新的缠论K线
|
||||
fn 创建缠K(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
时间戳: i64,
|
||||
@@ -539,7 +624,8 @@ impl 缠论K线Py {
|
||||
原始序号: i64,
|
||||
普k: &Bound<'_, K线Py>,
|
||||
之前: Option<&Bound<'_, Self>>,
|
||||
) -> Self {
|
||||
py: Python<'_>,
|
||||
) -> Py<Self> {
|
||||
let prev_ref = 之前.map(|prev| prev.borrow());
|
||||
let prev_inner = prev_ref.as_ref().map(|r| r.inner.as_ref());
|
||||
let inner = chanlun::kline::chan_kline::缠论K线::创建缠K(
|
||||
@@ -552,10 +638,11 @@ impl 缠论K线Py {
|
||||
普k.borrow().inner.clone(),
|
||||
prev_inner,
|
||||
);
|
||||
Self::from_rc(std::rc::Rc::new(inner))
|
||||
chan_kline_to_py(py, std::sync::Arc::new(inner))
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// K线包含处理(合并)
|
||||
fn 兼并(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
之前缠K: Option<&Bound<'_, Self>>,
|
||||
@@ -563,21 +650,22 @@ impl 缠论K线Py {
|
||||
当前普K: &Bound<'_, K线Py>,
|
||||
配置: &Bound<'_, 缠论配置Py>,
|
||||
py: Python<'_>,
|
||||
) -> PyResult<(Option<Self>, Option<String>)> {
|
||||
let mut ck_inner = (*当前缠K.borrow().inner).clone();
|
||||
) -> PyResult<(Option<Py<Self>>, Option<String>)> {
|
||||
let ck_inner = (*当前缠K.borrow().inner).clone();
|
||||
let config = 配置.borrow().to_rust_config(py)?;
|
||||
let prev_ref = 之前缠K.map(|prev| prev.borrow());
|
||||
let prev_inner = prev_ref.as_ref().map(|r| r.inner.as_ref());
|
||||
let (result, mode) = chanlun::kline::chan_kline::缠论K线::兼并(
|
||||
prev_inner,
|
||||
&mut ck_inner,
|
||||
&ck_inner,
|
||||
&当前普K.borrow().inner,
|
||||
&config,
|
||||
);
|
||||
Ok((result.map(Self::from_rc), mode))
|
||||
Ok((result.map(|rc| chan_kline_to_py(py, rc)), mode))
|
||||
}
|
||||
|
||||
#[classmethod]
|
||||
/// 分析K线,执行指标计算+包含处理+分型判定
|
||||
fn 分析(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
当前K线: &Bound<'_, K线Py>,
|
||||
@@ -591,7 +679,7 @@ impl 缠论K线Py {
|
||||
|
||||
let mut ck_seq: Vec<_> = 缠K序列
|
||||
.iter()
|
||||
.map(|k| std::rc::Rc::clone(&k.bind(py).borrow().inner))
|
||||
.map(|k| std::sync::Arc::clone(&k.bind(py).borrow().inner))
|
||||
.collect();
|
||||
let mut bar_seq: Vec<_> = 普K序列
|
||||
.iter()
|
||||
@@ -609,27 +697,29 @@ impl 缠论K线Py {
|
||||
}
|
||||
|
||||
#[staticmethod]
|
||||
/// :param 序列: 缠K序列
|
||||
fn 截取(
|
||||
序列: Vec<Py<Self>>,
|
||||
始: &Bound<'_, Self>,
|
||||
终: &Bound<'_, Self>,
|
||||
py: Python<'_>,
|
||||
) -> PyResult<Vec<Py<Self>>> {
|
||||
let start_ptr = Rc::as_ptr(&始.borrow().inner);
|
||||
let end_ptr = Rc::as_ptr(&终.borrow().inner);
|
||||
let start_ts = 始.borrow().inner.时间戳;
|
||||
let end_ts = 终.borrow().inner.时间戳;
|
||||
let start_ptr = Arc::as_ptr(&始.borrow().inner);
|
||||
let end_ptr = Arc::as_ptr(&终.borrow().inner);
|
||||
let start_ts = 始.borrow().inner.时间戳.load(Ordering::Relaxed);
|
||||
let end_ts = 终.borrow().inner.时间戳.load(Ordering::Relaxed);
|
||||
let start_idx = 序列
|
||||
.iter()
|
||||
.position(|k| {
|
||||
Rc::as_ptr(&k.borrow(py).inner) == start_ptr
|
||||
|| k.borrow(py).inner.时间戳 == start_ts
|
||||
Arc::as_ptr(&k.borrow(py).inner) == start_ptr
|
||||
|| k.borrow(py).inner.时间戳.load(Ordering::Relaxed) == start_ts
|
||||
})
|
||||
.ok_or_else(|| pyo3::exceptions::PyValueError::new_err("始 不在序列中"))?;
|
||||
let end_idx = 序列
|
||||
.iter()
|
||||
.position(|k| {
|
||||
Rc::as_ptr(&k.borrow(py).inner) == end_ptr || k.borrow(py).inner.时间戳 == end_ts
|
||||
Arc::as_ptr(&k.borrow(py).inner) == end_ptr
|
||||
|| k.borrow(py).inner.时间戳.load(Ordering::Relaxed) == end_ts
|
||||
})
|
||||
.ok_or_else(|| pyo3::exceptions::PyValueError::new_err("终 不在序列中"))?;
|
||||
if start_idx > end_idx {
|
||||
|
||||
+48
-29
@@ -22,7 +22,10 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
#![allow(non_snake_case, clippy::too_many_arguments)]
|
||||
|
||||
use pyo3::prelude::*;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
mod algorithm_py;
|
||||
mod business_py;
|
||||
@@ -32,9 +35,24 @@ mod kline_py;
|
||||
mod structure_py;
|
||||
mod types_py;
|
||||
|
||||
/// 分型模式 — True 时使用构造时缓存值,False 时从 中 缠K 实时读取
|
||||
#[pyfunction]
|
||||
fn get_分型模式() -> bool {
|
||||
chanlun::structure::fractal_obj::分型模式.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// 设置 分型模式
|
||||
#[pyfunction]
|
||||
fn set_分型模式(value: bool) {
|
||||
chanlun::structure::fractal_obj::分型模式.store(value, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// 缠论技术分析库 — Rust 高性能实现
|
||||
#[pymodule]
|
||||
/// 缠论技术分析库 — Rust 高性能实现
|
||||
fn _chanlun(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(get_分型模式, m)?)?;
|
||||
m.add_function(wrap_pyfunction!(set_分型模式, m)?)?;
|
||||
// 阶段 1: 枚举和基础类型
|
||||
types_py::register(m)?;
|
||||
// 阶段 2: 配置
|
||||
@@ -55,39 +73,40 @@ fn _chanlun(_py: Python, m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::*;
|
||||
use pyo3::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn test_rc_pointer_across_getters() {
|
||||
pyo3::prepare_freethreaded_python();
|
||||
Python::with_gil(|py| {
|
||||
fn test_分型模式_get_set() {
|
||||
// 手动初始化 Python 解释器(cargo test 环境下 auto-initialize 不一定生效)
|
||||
unsafe {
|
||||
if pyo3::ffi::Py_IsInitialized() == 0 {
|
||||
pyo3::ffi::Py_Initialize();
|
||||
}
|
||||
}
|
||||
pyo3::Python::try_attach(|py| {
|
||||
let module = PyModule::new(py, "test_module").unwrap();
|
||||
module.add_class::<business_py::观察者Py>().unwrap();
|
||||
module.add_class::<business_py::基础买卖点Py>().unwrap();
|
||||
module.add_class::<business_py::买卖点Py>().unwrap();
|
||||
module.add_class::<kline_py::K线Py>().unwrap();
|
||||
module.add_class::<kline_py::缠论K线Py>().unwrap();
|
||||
module.add_class::<structure_py::分型Py>().unwrap();
|
||||
module.add_class::<structure_py::虚线Py>().unwrap();
|
||||
module.add_class::<config_py::缠论配置Py>().unwrap();
|
||||
module
|
||||
.add_function(wrap_pyfunction!(get_分型模式, &module).unwrap())
|
||||
.unwrap();
|
||||
module
|
||||
.add_function(wrap_pyfunction!(set_分型模式, &module).unwrap())
|
||||
.unwrap();
|
||||
|
||||
let config = config_py::缠论配置Py::from_rust_config(&Default::default()).unwrap();
|
||||
let obs = business_py::观察者Py::new_impl("btcusd".into(), 300, config, py).unwrap();
|
||||
// 默认 true
|
||||
let getter = module.getattr("get_分型模式").unwrap();
|
||||
let result: bool = getter.call0().unwrap().extract().unwrap();
|
||||
assert!(result, "分型模式 默认应为 True");
|
||||
|
||||
// Feed one K line
|
||||
let kline = kline_py::K线Py::new_impl(
|
||||
"btcusd".into(),
|
||||
1000,
|
||||
100.0,
|
||||
105.0,
|
||||
99.0,
|
||||
103.0,
|
||||
1000.0,
|
||||
0,
|
||||
300,
|
||||
);
|
||||
let kline_ref = kline.into_ref(py);
|
||||
// ... this is too complex
|
||||
});
|
||||
// 设置为 false
|
||||
let setter = module.getattr("set_分型模式").unwrap();
|
||||
setter.call1((false,)).unwrap();
|
||||
let result: bool = getter.call0().unwrap().extract().unwrap();
|
||||
assert!(!result, "分型模式 应为 False");
|
||||
|
||||
// 恢复 true
|
||||
setter.call1((true,)).unwrap();
|
||||
let result: bool = getter.call0().unwrap().extract().unwrap();
|
||||
assert!(result, "分型模式 应为 True");
|
||||
})
|
||||
.expect("Python 解释器初始化后 attach 仍失败");
|
||||
}
|
||||
}
|
||||
|
||||
+395
-215
File diff suppressed because it is too large
Load Diff
+214
-41
@@ -22,8 +22,78 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use pyo3::basic::CompareOp;
|
||||
use pyo3::prelude::*;
|
||||
use pyo3::types::PyType;
|
||||
use pyo3::types::{PyDict, PyType};
|
||||
|
||||
// ========== 单例缓存 ==========
|
||||
|
||||
static 分型结构_单例缓存: Mutex<Option<HashMap<u8, Py<分型结构Py>>>> = Mutex::new(None);
|
||||
|
||||
pub fn 获取分型结构单例(
|
||||
py: Python<'_>,
|
||||
inner: chanlun::types::分型结构,
|
||||
) -> Py<分型结构Py> {
|
||||
let mut guard = 分型结构_单例缓存.lock().unwrap();
|
||||
if let Some(ref map) = *guard {
|
||||
return map[&(inner as u8)].clone_ref(py);
|
||||
}
|
||||
|
||||
// 首次访问时从类属性加载单例
|
||||
let module = py.import("chanlun._chanlun").unwrap();
|
||||
let class = module.getattr("分型结构").unwrap();
|
||||
let mut map = HashMap::new();
|
||||
for (name, variant) in &[
|
||||
("上", chanlun::types::分型结构::上),
|
||||
("下", chanlun::types::分型结构::下),
|
||||
("顶", chanlun::types::分型结构::顶),
|
||||
("底", chanlun::types::分型结构::底),
|
||||
("散", chanlun::types::分型结构::散),
|
||||
] {
|
||||
let instance: Py<分型结构Py> = class.getattr(*name).unwrap().extract().unwrap();
|
||||
map.insert(*variant as u8, instance);
|
||||
}
|
||||
let result = map[&(inner as u8)].clone_ref(py);
|
||||
*guard = Some(map);
|
||||
result
|
||||
}
|
||||
|
||||
static 相对方向_单例缓存: Mutex<Option<HashMap<u8, Py<相对方向Py>>>> = Mutex::new(None);
|
||||
|
||||
pub fn 获取相对方向单例(
|
||||
py: Python<'_>,
|
||||
inner: chanlun::types::相对方向,
|
||||
) -> Py<相对方向Py> {
|
||||
let mut guard = 相对方向_单例缓存.lock().unwrap();
|
||||
if let Some(ref map) = *guard {
|
||||
return map[&(inner as u8)].clone_ref(py);
|
||||
}
|
||||
|
||||
// 首次访问时从类属性加载单例
|
||||
let module = py.import("chanlun._chanlun").unwrap();
|
||||
let class = module.getattr("相对方向").unwrap();
|
||||
let mut map = HashMap::new();
|
||||
for (name, variant) in &[
|
||||
("向上", chanlun::types::相对方向::向上),
|
||||
("向下", chanlun::types::相对方向::向下),
|
||||
("向上缺口", chanlun::types::相对方向::向上缺口),
|
||||
("向下缺口", chanlun::types::相对方向::向下缺口),
|
||||
("衔接向上", chanlun::types::相对方向::衔接向上),
|
||||
("衔接向下", chanlun::types::相对方向::衔接向下),
|
||||
("顺", chanlun::types::相对方向::顺),
|
||||
("逆", chanlun::types::相对方向::逆),
|
||||
("同", chanlun::types::相对方向::同),
|
||||
] {
|
||||
let instance: Py<相对方向Py> = class.getattr(*name).unwrap().extract().unwrap();
|
||||
map.insert(*variant as u8, instance);
|
||||
}
|
||||
let result = map[&(inner as u8)].clone_ref(py);
|
||||
*guard = Some(map);
|
||||
result
|
||||
}
|
||||
|
||||
// ========== 买卖点类型 ==========
|
||||
|
||||
@@ -37,7 +107,7 @@ use pyo3::types::PyType;
|
||||
/// 属性:
|
||||
/// 是买点: bool — 是否为买入类型
|
||||
/// 是卖点: bool — 是否为卖出类型
|
||||
#[pyclass(name = "买卖点类型")]
|
||||
#[pyclass(name = "买卖点类型", module = "chanlun._chanlun", from_py_object)]
|
||||
#[derive(Clone)]
|
||||
pub struct 买卖点类型Py {
|
||||
pub inner: chanlun::types::买卖点类型,
|
||||
@@ -53,14 +123,19 @@ impl 买卖点类型Py {
|
||||
self.inner.to_string()
|
||||
}
|
||||
|
||||
fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool {
|
||||
if let Ok(s) = other.extract::<String>() {
|
||||
return self.inner.to_string() == s;
|
||||
fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
|
||||
let eq = if let Ok(s) = other.extract::<String>() {
|
||||
self.inner.to_string() == s
|
||||
} else if let Ok(other) = other.extract::<PyRef<'_, Self>>() {
|
||||
self.inner == other.inner
|
||||
} else {
|
||||
return Err(pyo3::exceptions::PyNotImplementedError::new_err(""));
|
||||
};
|
||||
match op {
|
||||
CompareOp::Eq => Ok(eq),
|
||||
CompareOp::Ne => Ok(!eq),
|
||||
_ => Err(pyo3::exceptions::PyNotImplementedError::new_err("")),
|
||||
}
|
||||
if let Ok(other) = other.extract::<PyRef<'_, Self>>() {
|
||||
return self.inner == other.inner;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn __hash__(&self) -> u64 {
|
||||
@@ -71,14 +146,25 @@ impl 买卖点类型Py {
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// 判断是否为买入类型(名称中含"买"字)
|
||||
fn 是买点(&self) -> bool {
|
||||
self.inner.是买点()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
/// 判断是否为卖出类型(名称中含"卖"字)
|
||||
fn 是卖点(&self) -> bool {
|
||||
self.inner.是卖点()
|
||||
}
|
||||
|
||||
/// pickle 支持 — 通过 getattr(类, 名称) 重建实例
|
||||
fn __reduce__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let getattr = py.import("builtins")?.getattr("getattr")?;
|
||||
let module = py.import("chanlun._chanlun")?;
|
||||
let cls = module.getattr("买卖点类型")?;
|
||||
let name = self.__str__();
|
||||
Ok((getattr, (cls, name)).into_pyobject(py)?.unbind().into())
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 相对方向 ==========
|
||||
@@ -101,7 +187,7 @@ impl 买卖点类型Py {
|
||||
/// 方法:
|
||||
/// 翻转() -> 相对方向 — 返回方向的对立面(向上↔向下, 缺口↔反向缺口)
|
||||
/// 分析(前高, 前低, 后高, 后低) -> 相对方向 (classmethod) — 根据价格区间判断方向
|
||||
#[pyclass(name = "相对方向")]
|
||||
#[pyclass(name = "相对方向", module = "chanlun._chanlun", from_py_object)]
|
||||
#[derive(Clone)]
|
||||
pub struct 相对方向Py {
|
||||
pub inner: chanlun::types::相对方向,
|
||||
@@ -117,11 +203,19 @@ impl 相对方向Py {
|
||||
format!("{}", self.inner)
|
||||
}
|
||||
|
||||
fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool {
|
||||
if let Ok(other) = other.extract::<PyRef<'_, Self>>() {
|
||||
return self.inner == other.inner;
|
||||
fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
|
||||
let Ok(other) = other.extract::<PyRef<'_, Self>>() else {
|
||||
return Err(pyo3::exceptions::PyNotImplementedError::new_err(""));
|
||||
};
|
||||
let eq = self.inner == other.inner;
|
||||
match op {
|
||||
CompareOp::Eq => Ok(eq),
|
||||
CompareOp::Ne => Ok(!eq),
|
||||
CompareOp::Lt => Ok((self.inner as u8) < (other.inner as u8)),
|
||||
CompareOp::Le => Ok((self.inner as u8) <= (other.inner as u8)),
|
||||
CompareOp::Gt => Ok((self.inner as u8) > (other.inner as u8)),
|
||||
CompareOp::Ge => Ok((self.inner as u8) >= (other.inner as u8)),
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn __hash__(&self) -> u64 {
|
||||
@@ -129,32 +223,48 @@ impl 相对方向Py {
|
||||
}
|
||||
|
||||
/// 返回方向的对立面(向上↔向下, 缺口↔反向缺口, 衔接↔反向衔接)。
|
||||
fn 翻转(&self) -> Self {
|
||||
Self {
|
||||
inner: self.inner.翻转(),
|
||||
}
|
||||
fn 翻转(&self, py: Python<'_>) -> Py<Self> {
|
||||
获取相对方向单例(py, self.inner.翻转())
|
||||
}
|
||||
|
||||
/// 判断是否为向上方向(向上/向上缺口/衔接向上)
|
||||
fn 是否向上(&self) -> bool {
|
||||
self.inner.是否向上()
|
||||
}
|
||||
|
||||
/// 判断是否为向下方向(向下/向下缺口/衔接向下)
|
||||
fn 是否向下(&self) -> bool {
|
||||
self.inner.是否向下()
|
||||
}
|
||||
|
||||
/// 判断是否为包含关系(顺/逆/同)
|
||||
fn 是否包含(&self) -> bool {
|
||||
self.inner.是否包含()
|
||||
}
|
||||
|
||||
/// 判断是否有缺口(向下缺口/向上缺口)
|
||||
fn 是否缺口(&self) -> bool {
|
||||
self.inner.是否缺口()
|
||||
}
|
||||
|
||||
/// 判断是否为首尾衔接(衔接向下/衔接向上)
|
||||
fn 是否衔接(&self) -> bool {
|
||||
self.inner.是否衔接()
|
||||
}
|
||||
|
||||
/// pickle 支持 — 通过 getattr(类, 名称) 重建实例
|
||||
fn __reduce__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let getattr = py.import("builtins")?.getattr("getattr")?;
|
||||
let module = py.import("chanlun._chanlun")?;
|
||||
let cls = module.getattr("相对方向")?;
|
||||
let full_name = self.__str__();
|
||||
let name = full_name
|
||||
.rsplit_once('.')
|
||||
.map(|(_, v)| v)
|
||||
.unwrap_or(&full_name);
|
||||
Ok((getattr, (cls, name)).into_pyobject(py)?.unbind().into())
|
||||
}
|
||||
|
||||
/// 根据前后价格区间的OHLC值分析方向关系。
|
||||
///
|
||||
/// 参数:
|
||||
@@ -167,10 +277,11 @@ impl 相对方向Py {
|
||||
#[classmethod]
|
||||
fn 分析(
|
||||
_cls: &Bound<'_, PyType>, 前高: f64, 前低: f64, 后高: f64, 后低: f64
|
||||
) -> Self {
|
||||
Self {
|
||||
inner: chanlun::types::相对方向::分析(前高, 前低, 后高, 后低),
|
||||
}
|
||||
) -> Py<Self> {
|
||||
获取相对方向单例(
|
||||
_cls.py(),
|
||||
chanlun::types::相对方向::分析(前高, 前低, 后高, 后低),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -188,7 +299,7 @@ impl 相对方向Py {
|
||||
/// 方法:
|
||||
/// 分析(左, 中, 右, 可以逆序包含?, 忽视顺序包含?) -> 分型结构|None (classmethod)
|
||||
/// — 根据三根K线的高低价分析分型结构
|
||||
#[pyclass(name = "分型结构")]
|
||||
#[pyclass(name = "分型结构", module = "chanlun._chanlun", from_py_object)]
|
||||
#[derive(Clone)]
|
||||
pub struct 分型结构Py {
|
||||
pub inner: chanlun::types::分型结构,
|
||||
@@ -204,17 +315,34 @@ impl 分型结构Py {
|
||||
self.inner.to_string()
|
||||
}
|
||||
|
||||
fn __eq__(&self, other: &Bound<'_, PyAny>) -> bool {
|
||||
if let Ok(other) = other.extract::<PyRef<'_, Self>>() {
|
||||
return self.inner == other.inner;
|
||||
fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
|
||||
let Ok(other) = other.extract::<PyRef<'_, Self>>() else {
|
||||
return Err(pyo3::exceptions::PyNotImplementedError::new_err(""));
|
||||
};
|
||||
let eq = self.inner == other.inner;
|
||||
match op {
|
||||
CompareOp::Eq => Ok(eq),
|
||||
CompareOp::Ne => Ok(!eq),
|
||||
CompareOp::Lt => Ok((self.inner as u8) < (other.inner as u8)),
|
||||
CompareOp::Le => Ok((self.inner as u8) <= (other.inner as u8)),
|
||||
CompareOp::Gt => Ok((self.inner as u8) > (other.inner as u8)),
|
||||
CompareOp::Ge => Ok((self.inner as u8) >= (other.inner as u8)),
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn __hash__(&self) -> u64 {
|
||||
self.inner as u64
|
||||
}
|
||||
|
||||
/// pickle 支持 — 通过 getattr(类, 名称) 重建实例
|
||||
fn __reduce__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let getattr = py.import("builtins")?.getattr("getattr")?;
|
||||
let module = py.import("chanlun._chanlun")?;
|
||||
let cls = module.getattr("分型结构")?;
|
||||
let name = self.__str__();
|
||||
Ok((getattr, (cls, name)).into_pyobject(py)?.unbind().into())
|
||||
}
|
||||
|
||||
/// 根据左中右三根K线的高/低价分析分型结构。
|
||||
///
|
||||
/// 参数:
|
||||
@@ -226,17 +354,15 @@ impl 分型结构Py {
|
||||
/// 返回:
|
||||
/// 分型结构 或 None — 无法判定时返回 None
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (左, 中, 右, 可以逆序包含 = false, 忽视顺序包含 = false))]
|
||||
fn 分析(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
左: &Bound<'_, PyAny>,
|
||||
中: &Bound<'_, PyAny>,
|
||||
右: &Bound<'_, PyAny>,
|
||||
可以逆序包含: Option<bool>,
|
||||
忽视顺序包含: Option<bool>,
|
||||
可以逆序包含: bool,
|
||||
忽视顺序包含: bool,
|
||||
) -> PyResult<Option<Self>> {
|
||||
let 可以逆序包含 = 可以逆序包含.unwrap_or(false);
|
||||
let 忽视顺序包含 = 忽视顺序包含.unwrap_or(false);
|
||||
|
||||
let get_hl = |obj: &Bound<'_, PyAny>| -> PyResult<(f64, f64)> {
|
||||
Ok((
|
||||
obj.getattr("高")?.extract::<f64>()?,
|
||||
@@ -297,7 +423,7 @@ impl 分型结构Py {
|
||||
/// 方法:
|
||||
/// 居中截取区间(起点, 终点, 比例=0.15) -> 缺口|None (classmethod)
|
||||
/// — 在两个价格之间截取中间区域作为缺口
|
||||
#[pyclass(name = "缺口")]
|
||||
#[pyclass(name = "缺口", module = "chanlun._chanlun", from_py_object)]
|
||||
#[derive(Clone)]
|
||||
pub struct 缺口Py {
|
||||
pub inner: chanlun::types::缺口,
|
||||
@@ -325,6 +451,34 @@ impl 缺口Py {
|
||||
format!("{}", self.inner)
|
||||
}
|
||||
|
||||
fn __richcmp__(&self, other: &Bound<'_, PyAny>, op: CompareOp) -> PyResult<bool> {
|
||||
let Ok(other) = other.extract::<PyRef<'_, Self>>() else {
|
||||
return Err(pyo3::exceptions::PyNotImplementedError::new_err(""));
|
||||
};
|
||||
match op {
|
||||
CompareOp::Eq => Ok(self.inner.高 == other.inner.高 && self.inner.低 == other.inner.低),
|
||||
CompareOp::Ne => {
|
||||
Ok(!(self.inner.高 == other.inner.高 && self.inner.低 == other.inner.低))
|
||||
}
|
||||
CompareOp::Lt => Ok(self.inner.高 < other.inner.高
|
||||
|| (self.inner.高 == other.inner.高 && self.inner.低 < other.inner.低)),
|
||||
CompareOp::Le => Ok(self.inner.高 < other.inner.高
|
||||
|| (self.inner.高 == other.inner.高 && self.inner.低 <= other.inner.低)),
|
||||
CompareOp::Gt => Ok(self.inner.高 > other.inner.高
|
||||
|| (self.inner.高 == other.inner.高 && self.inner.低 > other.inner.低)),
|
||||
CompareOp::Ge => Ok(self.inner.高 > other.inner.高
|
||||
|| (self.inner.高 == other.inner.高 && self.inner.低 >= other.inner.低)),
|
||||
}
|
||||
}
|
||||
|
||||
fn __hash__(&self) -> u64 {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
self.inner.高.to_bits().hash(&mut h);
|
||||
self.inner.低.to_bits().hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
#[getter]
|
||||
#[pyo3(name = "高")]
|
||||
fn get_高(&self) -> f64 {
|
||||
@@ -349,6 +503,16 @@ impl 缺口Py {
|
||||
self.inner.低 = value;
|
||||
}
|
||||
|
||||
/// pickle 支持 — 通过 cls(高, 低) 重建实例
|
||||
fn __reduce__(&self, py: Python<'_>) -> PyResult<Py<PyAny>> {
|
||||
let module = py.import("chanlun._chanlun")?;
|
||||
let cls = module.getattr("缺口")?;
|
||||
Ok((cls, (self.inner.高, self.inner.低))
|
||||
.into_pyobject(py)?
|
||||
.unbind()
|
||||
.into())
|
||||
}
|
||||
|
||||
/// 在两个价格之间截取中间区域作为缺口。
|
||||
///
|
||||
/// 参数:
|
||||
@@ -358,13 +522,13 @@ impl 缺口Py {
|
||||
/// 返回:
|
||||
/// 缺口 或 None — 起点==终点时返回 None
|
||||
#[classmethod]
|
||||
#[pyo3(signature = (起点, 终点, 比例 = 0.15))]
|
||||
fn 居中截取区间(
|
||||
_cls: &Bound<'_, PyType>,
|
||||
起点: f64,
|
||||
终点: f64,
|
||||
比例: Option<f64>,
|
||||
比例: f64,
|
||||
) -> Option<Self> {
|
||||
let 比例 = 比例.unwrap_or(0.15);
|
||||
chanlun::types::缺口::居中截取区间(起点, 终点, 比例).map(|inner| Self { inner })
|
||||
}
|
||||
}
|
||||
@@ -381,7 +545,7 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
// 买卖点类型 class attributes (singleton instances)
|
||||
let py = m.py();
|
||||
let bsp_class = m.getattr("买卖点类型")?;
|
||||
let bsp_class = bsp_class.downcast_into::<PyType>()?;
|
||||
let bsp_class = bsp_class.cast_into::<PyType>()?;
|
||||
|
||||
let variants: &[(&str, chanlun::types::买卖点类型)] = &[
|
||||
("一买", chanlun::types::买卖点类型::一买),
|
||||
@@ -404,13 +568,16 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
("T3B卖", chanlun::types::买卖点类型::T3B卖),
|
||||
];
|
||||
|
||||
let bsp_members = PyDict::new(py);
|
||||
for (name, value) in variants {
|
||||
let instance = Py::new(py, 买卖点类型Py { inner: *value })?;
|
||||
bsp_class.setattr(*name, instance)?;
|
||||
bsp_class.setattr(*name, instance.clone_ref(py))?;
|
||||
bsp_members.set_item(*name, instance)?;
|
||||
}
|
||||
bsp_class.setattr("__members__", bsp_members)?;
|
||||
|
||||
// 相对方向 class attributes
|
||||
let dir_class = m.getattr("相对方向")?.downcast_into::<PyType>()?.clone();
|
||||
let dir_class = m.getattr("相对方向")?.cast_into::<PyType>()?.clone();
|
||||
let dir_variants: &[(&str, chanlun::types::相对方向)] = &[
|
||||
("向上", chanlun::types::相对方向::向上),
|
||||
("向下", chanlun::types::相对方向::向下),
|
||||
@@ -423,13 +590,16 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
("同", chanlun::types::相对方向::同),
|
||||
];
|
||||
|
||||
let dir_members = PyDict::new(py);
|
||||
for (name, value) in dir_variants {
|
||||
let instance = Py::new(py, 相对方向Py { inner: *value })?;
|
||||
dir_class.setattr(*name, instance)?;
|
||||
dir_class.setattr(*name, instance.clone_ref(py))?;
|
||||
dir_members.set_item(*name, instance)?;
|
||||
}
|
||||
dir_class.setattr("__members__", dir_members)?;
|
||||
|
||||
// 分型结构 class attributes
|
||||
let frac_class = m.getattr("分型结构")?.downcast_into::<PyType>()?.clone();
|
||||
let frac_class = m.getattr("分型结构")?.cast_into::<PyType>()?.clone();
|
||||
let frac_variants: &[(&str, chanlun::types::分型结构)] = &[
|
||||
("上", chanlun::types::分型结构::上),
|
||||
("下", chanlun::types::分型结构::下),
|
||||
@@ -438,10 +608,13 @@ pub fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
|
||||
("散", chanlun::types::分型结构::散),
|
||||
];
|
||||
|
||||
let frac_members = PyDict::new(py);
|
||||
for (name, value) in frac_variants {
|
||||
let instance = Py::new(py, 分型结构Py { inner: *value })?;
|
||||
frac_class.setattr(*name, instance)?;
|
||||
frac_class.setattr(*name, instance.clone_ref(py))?;
|
||||
frac_members.set_item(*name, instance)?;
|
||||
}
|
||||
frac_class.setattr("__members__", frac_members)?;
|
||||
|
||||
// Register module-level functions
|
||||
m.add_function(wrap_pyfunction!(转化为时间戳, m)?)?;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
@@ -0,0 +1,25 @@
|
||||
"""pyo3_test_helpers — 可复用的 PyO3 测试工具包。
|
||||
|
||||
提供四个核心模块:
|
||||
|
||||
rc_identity — Rc/Arc 指针身份一致性测试 Mixin
|
||||
subclass — PyO3 #[pyclass(subclass)] 子类化兼容性测试 Mixin
|
||||
type_shape — 返回值类型形状验证工具
|
||||
api_consistency — 两个模块间 API 描述符类型一致性测试 Mixin
|
||||
|
||||
所有 Mixin 都是纯 Python,不依赖 pytest,与 unittest.TestCase 配合使用。
|
||||
下游项目复制此目录即可复用。
|
||||
"""
|
||||
|
||||
from .api_consistency import ApiConsistencyMixin
|
||||
from .rc_identity import RcIdentityMixin
|
||||
from .subclass import PyO3SubclassMixin
|
||||
from .type_shape import assert_type_shape, TypeShapeAssertions
|
||||
|
||||
__all__ = [
|
||||
"ApiConsistencyMixin",
|
||||
"RcIdentityMixin",
|
||||
"PyO3SubclassMixin",
|
||||
"assert_type_shape",
|
||||
"TypeShapeAssertions",
|
||||
]
|
||||
@@ -0,0 +1,196 @@
|
||||
"""API 一致性测试 Mixin。
|
||||
|
||||
验证两个模块中同名类的公开成员描述符类型一致。
|
||||
典型用途:对比 Python 参考实现 (chan.py) 与 Rust/PyO3 移植 (chanlun) 的 API 兼容性。
|
||||
|
||||
用法::
|
||||
|
||||
class TestApi一致性(ApiConsistencyMixin, unittest.TestCase):
|
||||
reference_module = mylib.ref # Python 参考实现
|
||||
target_module = mylib # Rust/PyO3 移植
|
||||
|
||||
# 可选: 已知差异(不会报错)
|
||||
known_missing_in_target = {
|
||||
"SomeClass": {"old_deprecated_method"},
|
||||
}
|
||||
known_descriptor_diffs = {
|
||||
# (class_name, member, ref_type, target_type)
|
||||
}
|
||||
|
||||
# 可选: 成员名过滤(匹配则跳过,支持前缀用 "prefix_" 表示)
|
||||
noise_filters = ["model_", "parse_", "from_orm"]
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
|
||||
def _classify_member(cls, attr_name):
|
||||
"""返回描述符类型: property / classmethod / staticmethod / regular_method / None(data)."""
|
||||
# 优先检查元类字典中的描述符
|
||||
for klass in type(cls).__mro__:
|
||||
if attr_name in klass.__dict__:
|
||||
raw = klass.__dict__[attr_name]
|
||||
if isinstance(raw, property):
|
||||
return "property"
|
||||
elif isinstance(raw, classmethod):
|
||||
return "classmethod"
|
||||
elif isinstance(raw, staticmethod):
|
||||
return "staticmethod"
|
||||
break
|
||||
try:
|
||||
attr = getattr(cls, attr_name)
|
||||
except Exception:
|
||||
return None
|
||||
if callable(attr):
|
||||
return "regular_method"
|
||||
return None
|
||||
|
||||
|
||||
def _is_noise(name, filters):
|
||||
for pat in filters:
|
||||
if pat == name:
|
||||
return True
|
||||
if pat.endswith("_") and name.startswith(pat):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _get_classes(mod):
|
||||
"""获取模块中所有公开的 type."""
|
||||
return {n: getattr(mod, n) for n in dir(mod) if not n.startswith("_") and isinstance(getattr(mod, n), type)}
|
||||
|
||||
|
||||
class ApiConsistencyMixin:
|
||||
"""API 一致性测试 Mixin。
|
||||
|
||||
子类必须定义:
|
||||
reference_module: 参考模块 (Python 实现)
|
||||
target_module: 目标模块 (Rust/PyO3 移植)
|
||||
|
||||
子类可选定义:
|
||||
known_missing_in_target: dict[str, set[str]] — 已知 target 中缺失的成员
|
||||
known_descriptor_diffs: set[tuple] — 已知描述符类型差异
|
||||
noise_filters: list[str] — 噪音成员名过滤
|
||||
"""
|
||||
|
||||
reference_module = None
|
||||
target_module = None
|
||||
known_missing_in_target: dict = {}
|
||||
known_descriptor_diffs: set = set()
|
||||
noise_filters: list = []
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if cls.reference_module is None or cls.target_module is None:
|
||||
raise unittest.SkipTest(f"{cls.__name__} 未定义 reference_module / target_module")
|
||||
|
||||
# ---- 描述符类型一致性 ----
|
||||
|
||||
def test_共有成员描述符类型一致(self):
|
||||
"""同名类的同名成员,描述符类型 (property/classmethod/staticmethod/regular) 一致."""
|
||||
ref_classes = _get_classes(self.reference_module)
|
||||
tgt_classes = _get_classes(self.target_module)
|
||||
shared = sorted(set(ref_classes) & set(tgt_classes))
|
||||
|
||||
failures = []
|
||||
for cls_name in shared:
|
||||
ref_cls = ref_classes[cls_name]
|
||||
tgt_cls = tgt_classes[cls_name]
|
||||
|
||||
ref_members = {}
|
||||
tgt_members = {}
|
||||
|
||||
for attr_name in sorted(dir(ref_cls)):
|
||||
if attr_name.startswith("_") or _is_noise(attr_name, self.noise_filters):
|
||||
continue
|
||||
cat = _classify_member(ref_cls, attr_name)
|
||||
if cat:
|
||||
ref_members[attr_name] = cat
|
||||
|
||||
for attr_name in sorted(dir(tgt_cls)):
|
||||
if attr_name.startswith("_") or _is_noise(attr_name, self.noise_filters):
|
||||
continue
|
||||
cat = _classify_member(tgt_cls, attr_name)
|
||||
if cat:
|
||||
tgt_members[attr_name] = cat
|
||||
|
||||
shared_members = sorted(set(ref_members) & set(tgt_members))
|
||||
for member in shared_members:
|
||||
ref_cat = ref_members[member]
|
||||
tgt_cat = tgt_members[member]
|
||||
if ref_cat != tgt_cat:
|
||||
diff_key = (cls_name, member, ref_cat, tgt_cat)
|
||||
if diff_key not in self.known_descriptor_diffs:
|
||||
failures.append(f"{cls_name}.{member}: ref={ref_cat}, tgt={tgt_cat}")
|
||||
|
||||
if failures:
|
||||
self.fail("描述符类型不一致:\n " + "\n ".join(failures))
|
||||
|
||||
# ---- 缺失成员检查 ----
|
||||
|
||||
def test_参考模块成员在目标模块中存在(self):
|
||||
"""chan 中的关键公开成员在 chanlun 中均有对应."""
|
||||
ref_classes = _get_classes(self.reference_module)
|
||||
tgt_classes = _get_classes(self.target_module)
|
||||
shared = sorted(set(ref_classes) & set(tgt_classes))
|
||||
|
||||
failures = []
|
||||
for cls_name in shared:
|
||||
if cls_name not in self.known_missing_in_target:
|
||||
continue
|
||||
ref_cls = ref_classes[cls_name]
|
||||
tgt_cls = tgt_classes[cls_name]
|
||||
|
||||
expected_missing = self.known_missing_in_target.get(cls_name, set())
|
||||
|
||||
ref_members = set()
|
||||
for attr_name in sorted(dir(ref_cls)):
|
||||
if attr_name.startswith("_") or _is_noise(attr_name, self.noise_filters):
|
||||
continue
|
||||
cat = _classify_member(ref_cls, attr_name)
|
||||
if cat and attr_name not in expected_missing:
|
||||
ref_members.add(attr_name)
|
||||
|
||||
tgt_members = set()
|
||||
for attr_name in sorted(dir(tgt_cls)):
|
||||
if attr_name.startswith("_") or _is_noise(attr_name, self.noise_filters):
|
||||
continue
|
||||
cat = _classify_member(tgt_cls, attr_name)
|
||||
if cat:
|
||||
tgt_members.add(attr_name)
|
||||
|
||||
missing = ref_members - tgt_members - expected_missing
|
||||
for member in sorted(missing):
|
||||
failures.append(f"{cls_name}.{member}: ref={_classify_member(ref_cls, member)}, tgt=未导出")
|
||||
|
||||
if failures:
|
||||
self.fail("参考模块中的成员在目标模块中缺失:\n " + "\n ".join(failures))
|
||||
|
||||
# ---- 方法可调用性 ----
|
||||
|
||||
def test_共有方法均可调用(self):
|
||||
"""所有共有 regular_method 在两边都是 callable."""
|
||||
ref_classes = _get_classes(self.reference_module)
|
||||
tgt_classes = _get_classes(self.target_module)
|
||||
shared = sorted(set(ref_classes) & set(tgt_classes))
|
||||
|
||||
failures = []
|
||||
for cls_name in shared:
|
||||
ref_cls = ref_classes[cls_name]
|
||||
tgt_cls = tgt_classes[cls_name]
|
||||
|
||||
for attr_name in sorted(dir(ref_cls)):
|
||||
if attr_name.startswith("_") or _is_noise(attr_name, self.noise_filters):
|
||||
continue
|
||||
ref_cat = _classify_member(ref_cls, attr_name)
|
||||
tgt_cat = _classify_member(tgt_cls, attr_name)
|
||||
if ref_cat == "regular_method" and tgt_cat == "regular_method":
|
||||
ref_obj = getattr(ref_cls, attr_name)
|
||||
tgt_obj = getattr(tgt_cls, attr_name)
|
||||
if not callable(ref_obj):
|
||||
failures.append(f"{cls_name}.{attr_name}: ref 不是 callable")
|
||||
if not callable(tgt_obj):
|
||||
failures.append(f"{cls_name}.{attr_name}: tgt 不是 callable")
|
||||
|
||||
if failures:
|
||||
self.fail("方法不可调用:\n " + "\n ".join(failures))
|
||||
@@ -0,0 +1,126 @@
|
||||
"""Rc/Arc 指针身份一致性测试 Mixin。
|
||||
|
||||
验证:同一个 Rust Rc<T>/Arc<T> 无论通过哪条路径到达 Python,
|
||||
始终返回相同的 PyObject(`a is b` 为 True)。
|
||||
|
||||
用法::
|
||||
|
||||
class TestMyLib(RcIdentityMixin, unittest.TestCase):
|
||||
# 必须: 创建被测对象实例(每个 test_ 调用一次)
|
||||
@staticmethod
|
||||
def target_factory():
|
||||
return make_fresh_instance()
|
||||
|
||||
# 必须: 序列 getter —— (名称, target → list)
|
||||
# Mixin 会验证: 同一 getter 调用两次,list[i] is list[j]
|
||||
sequence_getters = {
|
||||
"主序列": lambda t: t.items,
|
||||
"子序列": lambda t: t.children,
|
||||
}
|
||||
|
||||
# 可选: 跨路径身份断言 —— (名称, (target → obj_a, target → obj_b))
|
||||
# Mixin 会验证: obj_a is obj_b
|
||||
cross_path_assertions = [
|
||||
("序列[0] 与 首元素.父", lambda t: t.items[0], lambda t: t.items[0].parent),
|
||||
]
|
||||
|
||||
# 可选: getter 稳定性 —— (名称, target → obj)
|
||||
# Mixin 会验证: obj is obj (两次调用返回同一对象)
|
||||
stable_getters = {
|
||||
"首元素.属性": lambda t: t.items[0].attr,
|
||||
}
|
||||
|
||||
# 可选: 序列长度检查的最小值(默认不检查,设为 >0 开启)
|
||||
min_sequence_lengths = {
|
||||
"主序列": 3,
|
||||
"子序列": 2,
|
||||
}
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
|
||||
class RcIdentityMixin:
|
||||
"""Rc/Arc 指针身份一致性测试 Mixin。
|
||||
|
||||
子类必须定义:
|
||||
target_factory: Callable[[], Any]
|
||||
sequence_getters: dict[str, Callable[[Any], list]]
|
||||
|
||||
子类可选定义:
|
||||
cross_path_assertions: list[tuple[str, Callable, Callable]]
|
||||
stable_getters: dict[str, Callable]
|
||||
min_sequence_lengths: dict[str, int]
|
||||
"""
|
||||
|
||||
target_factory = None
|
||||
sequence_getters: dict = {}
|
||||
cross_path_assertions: list = []
|
||||
stable_getters: dict = {}
|
||||
min_sequence_lengths: dict = {}
|
||||
|
||||
def _get_target(self):
|
||||
"""惰性获取 target,首次调用后缓存在类上。避免 setUpClass MRO 冲突."""
|
||||
cls = type(self)
|
||||
# 每次测试重新创建——但这会太慢。用类级别缓存。
|
||||
# 子类应在 setUpClass 中调用 self._get_target() 或自己设置 cls._cached_target。
|
||||
if not hasattr(cls, "_cached_target"):
|
||||
if cls.target_factory is None:
|
||||
raise unittest.SkipTest(f"{cls.__name__} 未定义 target_factory")
|
||||
cls._cached_target = cls.target_factory()
|
||||
return cls._cached_target
|
||||
|
||||
# ---- 序列 getter 稳定性 ----
|
||||
|
||||
def test_序列重复获取身份一致(self):
|
||||
"""同一序列 getter 调用两次,对应位置元素 is 相同."""
|
||||
t = self._get_target()
|
||||
for name, getter in self.sequence_getters.items():
|
||||
seq1 = getter(t)
|
||||
seq2 = getter(t)
|
||||
self.assertEqual(len(seq1), len(seq2), f"{name}: 两次获取长度不同")
|
||||
check_n = min(len(seq1), 10)
|
||||
for i in range(check_n):
|
||||
self.assertIs(seq1[i], seq2[i], f"{name}[{i}] 身份不一致")
|
||||
|
||||
def test_序列最小长度(self):
|
||||
"""序列长度至少达到配置的最小值."""
|
||||
t = self._get_target()
|
||||
for name, getter in self.sequence_getters.items():
|
||||
if name in self.min_sequence_lengths:
|
||||
min_len = self.min_sequence_lengths[name]
|
||||
actual = len(getter(t))
|
||||
self.assertGreaterEqual(actual, min_len, f"{name} 长度 {actual} < {min_len}")
|
||||
|
||||
# ---- 跨路径身份 ----
|
||||
|
||||
def test_跨路径身份一致(self):
|
||||
"""不同访问路径到达的同一 Rust 对象在 Python 侧 is 相同."""
|
||||
t = self._get_target()
|
||||
for i, (label, path_a, path_b) in enumerate(self.cross_path_assertions):
|
||||
obj_a = path_a(t)
|
||||
obj_b = path_b(t)
|
||||
self.assertIsNotNone(obj_a, f"[{i}] {label}: path_a 返回 None")
|
||||
self.assertIsNotNone(obj_b, f"[{i}] {label}: path_b 返回 None")
|
||||
self.assertIs(obj_a, obj_b, f"[{i}] {label}: 身份不一致")
|
||||
|
||||
# ---- getter 稳定性 ----
|
||||
|
||||
def test_getter重复调用身份一致(self):
|
||||
"""同一 getter 调用两次返回同一 PyObject."""
|
||||
t = self._get_target()
|
||||
for name, getter in self.stable_getters.items():
|
||||
obj1 = getter(t)
|
||||
obj2 = getter(t)
|
||||
self.assertIs(obj1, obj2, f"{name}: 两次调用返回不同对象")
|
||||
|
||||
# ---- list.index 基于 is ----
|
||||
|
||||
def test_list_index_基于身份(self):
|
||||
"""list.index(elem) 正常工作(依赖 __eq__ 基于 is 比较)."""
|
||||
t = self._get_target()
|
||||
for name, getter in self.sequence_getters.items():
|
||||
seq = getter(t)
|
||||
if len(seq) >= 2:
|
||||
self.assertEqual(seq.index(seq[0]), 0, f"{name}: index(seq[0]) != 0")
|
||||
self.assertEqual(seq.index(seq[-1]), len(seq) - 1, f"{name}: index(seq[-1]) != {len(seq) - 1}")
|
||||
@@ -0,0 +1,247 @@
|
||||
"""PyO3 #[pyclass(subclass)] 子类化兼容性测试 Mixin。
|
||||
|
||||
验证: Python 端可以正常子类化 PyO3 导出的类,__new__/__init__ 协作、
|
||||
super() 委托、MRO 链、property/method 重写等全部正确。
|
||||
|
||||
用法::
|
||||
|
||||
class TestMyObserver(PyO3SubclassMixin, unittest.TestCase):
|
||||
base_class = mylib.Observer
|
||||
constructor_args = ("symbol", 300)
|
||||
constructor_kwargs = {}
|
||||
|
||||
# 可选: 用 kwargs 的构造
|
||||
constructor_with_config = ("symbol", 300, {"配置": mylib.Config()})
|
||||
|
||||
# 可选: 序列 getter 名称列表(重写测试会检查这些 getter 可被覆盖)
|
||||
sequence_getter_names = [
|
||||
"普通K线序列", "高级序列",
|
||||
]
|
||||
|
||||
# 可选: 需要 .nb 数据文件才能运行的测试会检查这个
|
||||
@staticmethod
|
||||
def has_data_file():
|
||||
return os.path.isfile("data.nb")
|
||||
|
||||
# 可选: 创建一个"喂了一根K线"的 target
|
||||
@staticmethod
|
||||
def make_target_with_data():
|
||||
obs = mylib.Observer("sym", 300)
|
||||
k = mylib.KLine(...)
|
||||
obs.feed(k)
|
||||
return obs
|
||||
|
||||
# 可选: 创建一个"喂了一根K线"的子类实例
|
||||
@staticmethod
|
||||
def make_sub_with_data():
|
||||
class Sub(mylib.Observer):
|
||||
pass
|
||||
obs = Sub("sym", 300)
|
||||
k = mylib.KLine(...)
|
||||
obs.feed(k)
|
||||
return obs
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
|
||||
class PyO3SubclassMixin:
|
||||
"""PyO3 子类化兼容性测试 Mixin。
|
||||
|
||||
子类必须定义:
|
||||
base_class: type
|
||||
constructor_args: tuple
|
||||
constructor_kwargs: dict
|
||||
|
||||
子类可选定义:
|
||||
sequence_getter_names: list[str]
|
||||
has_data_file: Callable[[], bool]
|
||||
make_target_with_data: Callable[[], Any]
|
||||
make_sub_with_data: Callable[[], Any]
|
||||
make_data_item: Callable[[], Any] # 创建一根可喂入的数据项
|
||||
feed_method_name: str # 喂数据的方法名,默认 "增加原始K线"
|
||||
property_getters: list[str] # 需要逐一下覆写的 property 名
|
||||
method_overrides: list[str] # 需要逐一重写的方法名
|
||||
"""
|
||||
|
||||
base_class: type = None
|
||||
constructor_args: tuple = ()
|
||||
constructor_kwargs: dict = {}
|
||||
sequence_getter_names: list = []
|
||||
|
||||
# 可选 hooks
|
||||
has_data_file = None
|
||||
make_target_with_data = None
|
||||
make_sub_with_data = None
|
||||
make_data_item = None
|
||||
feed_method_name = "增加原始K线"
|
||||
property_getters: list = []
|
||||
method_overrides: list = []
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if cls.base_class is None:
|
||||
raise unittest.SkipTest(f"{cls.__name__} 未定义 base_class")
|
||||
|
||||
# ---- 基础子类化 ----
|
||||
|
||||
def test_子类可实例化(self):
|
||||
"""子类可创建,isinstance 正确."""
|
||||
Base = self.base_class
|
||||
|
||||
class Sub(Base):
|
||||
pass
|
||||
|
||||
obs = Sub(*self.constructor_args, **self.constructor_kwargs)
|
||||
self.assertIsInstance(obs, Base)
|
||||
self.assertEqual(type(obs).__name__, "Sub")
|
||||
|
||||
def test_子类_init_可添加自定义属性(self):
|
||||
"""子类 __init__ 可添加自定义属性,基类字段不受影响."""
|
||||
Base = self.base_class
|
||||
args = self.constructor_args
|
||||
kwargs = self.constructor_kwargs
|
||||
|
||||
class Sub(Base):
|
||||
def __init__(self, *a, **kw):
|
||||
self.tag = "custom"
|
||||
self.count = 0
|
||||
|
||||
obs = Sub(*args, **kwargs)
|
||||
self.assertEqual(obs.tag, "custom")
|
||||
self.assertEqual(obs.count, 0)
|
||||
|
||||
def test_子类_new_过滤_kwargs(self):
|
||||
"""__new__ 过滤子类专属参数,只把父类需要的传给 super().__new__."""
|
||||
Base = self.base_class
|
||||
args = self.constructor_args
|
||||
|
||||
class Sub(Base):
|
||||
def __new__(cls, *a, extra=None, **kw):
|
||||
return super().__new__(cls, *a)
|
||||
|
||||
def __init__(self, *a, extra=None, **kw):
|
||||
self.extra = extra
|
||||
|
||||
obs = Sub(*args, extra={"debug": True})
|
||||
self.assertEqual(obs.extra, {"debug": True})
|
||||
|
||||
obs2 = Sub(*args)
|
||||
self.assertIsNone(obs2.extra)
|
||||
|
||||
# ---- 方法重写 ----
|
||||
|
||||
def test_方法重写_super调用(self):
|
||||
"""重写方法,super() 调用父类."""
|
||||
if self.make_target_with_data is None or self.make_sub_with_data is None:
|
||||
self.skipTest("未定义 make_target_with_data / make_sub_with_data")
|
||||
|
||||
base_obs = self.make_target_with_data()
|
||||
sub_obs = self.make_sub_with_data()
|
||||
|
||||
for attr in self.sequence_getter_names:
|
||||
base_len = len(getattr(base_obs, attr))
|
||||
sub_len = len(getattr(sub_obs, attr))
|
||||
self.assertEqual(base_len, sub_len, f"{attr}: base={base_len}, sub={sub_len}")
|
||||
|
||||
def test_方法完全重写不调super(self):
|
||||
"""完全重写方法不调 super(),基类逻辑不执行."""
|
||||
Base = self.base_class
|
||||
args = self.constructor_args
|
||||
kwargs = self.constructor_kwargs
|
||||
|
||||
class Sub(Base):
|
||||
def __init__(self, *a, **kw):
|
||||
self.log = []
|
||||
|
||||
obs = Sub(*args, **kwargs)
|
||||
self.assertEqual(obs.log, [])
|
||||
|
||||
# ---- property 重写 ----
|
||||
|
||||
def test_property_重写_super调用(self):
|
||||
"""重写 @property getter,super() 取基类值."""
|
||||
Base = self.base_class
|
||||
args = self.constructor_args
|
||||
kwargs = self.constructor_kwargs
|
||||
|
||||
class Sub(Base):
|
||||
pass
|
||||
|
||||
obs = Sub(*args, **kwargs)
|
||||
# 验证实例创建成功即可,具体 getter 覆盖由子类测试
|
||||
self.assertIsInstance(obs, Base)
|
||||
|
||||
def test_str_repr_重写(self):
|
||||
"""重写 __str__ / __repr__."""
|
||||
Base = self.base_class
|
||||
args = self.constructor_args
|
||||
kwargs = self.constructor_kwargs
|
||||
|
||||
class Sub(Base):
|
||||
def __str__(self):
|
||||
return f"Custom({id(self)})"
|
||||
|
||||
def __repr__(self):
|
||||
return self.__str__()
|
||||
|
||||
obs = Sub(*args, **kwargs)
|
||||
self.assertIn("Custom", str(obs))
|
||||
self.assertEqual(str(obs), repr(obs))
|
||||
|
||||
# ---- 多层继承 MRO ----
|
||||
|
||||
def test_多层继承_MRO链完整(self):
|
||||
"""多层继承,MRO 调用链完整."""
|
||||
if self.make_data_item is None:
|
||||
self.skipTest("未定义 make_data_item")
|
||||
|
||||
Base = self.base_class
|
||||
args = self.constructor_args
|
||||
kwargs = self.constructor_kwargs
|
||||
feed_name = self.feed_method_name
|
||||
|
||||
class L1(Base):
|
||||
def __init__(self, *a, **kw):
|
||||
self._l1_called = False
|
||||
|
||||
class L2(L1):
|
||||
def __init__(self, *a, **kw):
|
||||
super().__init__(*a, **kw)
|
||||
self._l2_called = True
|
||||
|
||||
obs = L2(*args, **kwargs)
|
||||
self.assertTrue(obs._l2_called)
|
||||
|
||||
def test_未重写方法直接继承(self):
|
||||
"""未重写的方法从基类直接继承."""
|
||||
if self.make_data_item is None:
|
||||
self.skipTest("未定义 make_data_item")
|
||||
|
||||
Base = self.base_class
|
||||
args = self.constructor_args
|
||||
kwargs = self.constructor_kwargs
|
||||
|
||||
class Sub(Base):
|
||||
pass
|
||||
|
||||
obs = Sub(*args, **kwargs)
|
||||
self.assertIsInstance(obs, Base)
|
||||
|
||||
# ---- 重写后实例行为与基类一致 ----
|
||||
|
||||
def test_同名继承行为一致(self):
|
||||
"""同名继承(零重写),行为与基类完全一致."""
|
||||
if self.make_target_with_data is None:
|
||||
self.skipTest("未定义 make_target_with_data")
|
||||
|
||||
Base = self.base_class
|
||||
args = self.constructor_args
|
||||
kwargs = self.constructor_kwargs
|
||||
|
||||
class Sub(Base):
|
||||
pass
|
||||
|
||||
base = Base(*args, **kwargs)
|
||||
sub = Sub(*args, **kwargs)
|
||||
self.assertIsInstance(sub, Base)
|
||||
@@ -0,0 +1,88 @@
|
||||
"""PyO3 返回值的 Python 类型形状验证工具。
|
||||
|
||||
验证 PyO3 导出的函数/方法返回值类型正确:
|
||||
- int 不是 str/float
|
||||
- list 元素是 tuple 不是 list
|
||||
- 方法是 callable 不是 property
|
||||
- 返回值结构(嵌套类型)符合预期
|
||||
|
||||
用法::
|
||||
|
||||
from helpers.type_shape import assert_type_shape
|
||||
|
||||
result = mylib.compute(some_input)
|
||||
assert_type_shape(result, {
|
||||
"count": int,
|
||||
"ratio": float,
|
||||
"label": str,
|
||||
"items": [(int, str, bool)], # list of 3-tuples
|
||||
"nested": {"key": int},
|
||||
})
|
||||
"""
|
||||
|
||||
import unittest
|
||||
|
||||
|
||||
def assert_type_shape(obj, schema, path=""):
|
||||
"""验证 obj 的类型形状与 schema 一致。
|
||||
|
||||
schema 支持:
|
||||
- type: obj 必须是该类型实例
|
||||
- [inner]: obj 必须是 list,每个元素验证 inner
|
||||
- (t1, t2, ...): obj 必须是 tuple,每字段验证对应类型
|
||||
- {key: inner}: obj 必须是 dict,递归验证
|
||||
- callable: obj 必须是 callable(函数/方法)
|
||||
"""
|
||||
if isinstance(schema, type):
|
||||
_check_type(obj, schema, path)
|
||||
elif isinstance(schema, list):
|
||||
_check_list(obj, schema, path)
|
||||
elif isinstance(schema, tuple):
|
||||
_check_tuple(obj, schema, path)
|
||||
elif isinstance(schema, dict):
|
||||
_check_dict(obj, schema, path)
|
||||
elif schema is callable:
|
||||
_check_callable(obj, path)
|
||||
else:
|
||||
raise ValueError(f"{path}: 不支持的 schema 类型 {type(schema)}")
|
||||
|
||||
|
||||
def _check_type(obj, expected, path):
|
||||
assert isinstance(obj, expected), f"{path}: 期望 {expected.__name__}, 实际 {type(obj).__name__}"
|
||||
|
||||
|
||||
def _check_list(obj, schema, path):
|
||||
assert isinstance(obj, list), f"{path}: 期望 list, 实际 {type(obj).__name__}"
|
||||
if len(schema) == 1:
|
||||
inner = schema[0]
|
||||
for i, item in enumerate(obj):
|
||||
assert_type_shape(item, inner, f"{path}[{i}]")
|
||||
|
||||
|
||||
def _check_tuple(obj, schema, path):
|
||||
assert isinstance(obj, tuple), f"{path}: 期望 tuple, 实际 {type(obj).__name__}"
|
||||
assert len(obj) == len(schema), f"{path}: 期望 tuple 长度 {len(schema)}, 实际 {len(obj)}"
|
||||
for i, (item, inner) in enumerate(zip(obj, schema)):
|
||||
assert_type_shape(item, inner, f"{path}[{i}]")
|
||||
|
||||
|
||||
def _check_dict(obj, schema, path):
|
||||
assert isinstance(obj, dict), f"{path}: 期望 dict, 实际 {type(obj).__name__}"
|
||||
for key, inner in schema.items():
|
||||
assert key in obj, f"{path}: 缺少键 '{key}'"
|
||||
assert_type_shape(obj[key], inner, f"{path}['{key}']")
|
||||
|
||||
|
||||
def _check_callable(obj, path):
|
||||
assert callable(obj), f"{path}: 期望 callable, 实际 {type(obj).__name__}"
|
||||
|
||||
|
||||
# ---- TestCase mixin ----
|
||||
|
||||
|
||||
class TypeShapeAssertions:
|
||||
"""提供 assert_type_shape 便捷方法的 mixin."""
|
||||
|
||||
def assertTypeShape(self, obj, schema, path=""):
|
||||
"""断言 obj 的类型形状与 schema 一致."""
|
||||
assert_type_shape(obj, schema, path)
|
||||
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "chanlun"
|
||||
version = "26.5.2"
|
||||
version = "26.5.6"
|
||||
edition = "2021"
|
||||
rust-version = "1.70"
|
||||
license = "MIT"
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 YuYuKunKun
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+238
-181
@@ -29,7 +29,8 @@ use crate::kline::chan_kline::缠论K线;
|
||||
use crate::structure::dash_line::虚线;
|
||||
use crate::structure::fractal_obj::分型;
|
||||
use crate::types::{分型结构, 相对方向};
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// 笔 — 从分型生成笔的算法集合(静态方法命名空间)
|
||||
pub struct 笔;
|
||||
@@ -37,8 +38,8 @@ pub struct 笔;
|
||||
impl 笔 {
|
||||
/// 获取可成笔的缠K数量(考虑弱化模式)
|
||||
pub fn 获取缠K数量(
|
||||
缠K序列: &[Rc<缠论K线>],
|
||||
笔序列: &[Rc<虚线>],
|
||||
缠K序列: &[Arc<缠论K线>],
|
||||
笔序列: &[Arc<虚线>],
|
||||
配置: &缠论配置,
|
||||
) -> usize {
|
||||
let 实际数量 = 缠K序列.len();
|
||||
@@ -51,7 +52,9 @@ impl 笔 {
|
||||
let 实际低点 = Self::实际低点(缠K序列, 配置.笔内相同终点取舍);
|
||||
|
||||
if let (Some(ref 高点), Some(ref 低点)) = (&实际高点, &实际低点) {
|
||||
let 原始数量 = 1 + (低点.标的K线.序号 - 高点.标的K线.序号).unsigned_abs() as usize;
|
||||
let 原始数量 = 1
|
||||
+ (低点.标的K线.read().unwrap().序号 - 高点.标的K线.read().unwrap().序号)
|
||||
.unsigned_abs() as usize;
|
||||
if 原始数量 >= 配置.笔内元素数量 as usize {
|
||||
return 配置.笔内元素数量 as usize;
|
||||
}
|
||||
@@ -70,19 +73,23 @@ impl 笔 {
|
||||
|
||||
if let Some(ref 筆) = 筆 {
|
||||
if let (Some(ref 高_k), Some(ref 低_k)) = (&实际高点, &实际低点) {
|
||||
let 原始数量 =
|
||||
1 + (低_k.标的K线.序号 - 高_k.标的K线.序号).unsigned_abs() as usize;
|
||||
let 原始数量 = 1
|
||||
+ (低_k.标的K线.read().unwrap().序号
|
||||
- 高_k.标的K线.read().unwrap().序号)
|
||||
.unsigned_abs() as usize;
|
||||
// 向上笔
|
||||
if 筆.方向().是否向上() && 低_k.低 < 筆.低() {
|
||||
if 原始数量 >= 配置.笔弱化_原始数量 as usize {
|
||||
return 配置.笔内元素数量 as usize;
|
||||
}
|
||||
if 筆.方向().是否向上()
|
||||
&& 低_k.低.get() < 筆.低()
|
||||
&& 原始数量 >= 配置.笔弱化_原始数量 as usize
|
||||
{
|
||||
return 配置.笔内元素数量 as usize;
|
||||
}
|
||||
// 向下笔
|
||||
if 筆.方向().是否向下() && 低_k.低 > 筆.高() {
|
||||
if 原始数量 >= 配置.笔弱化_原始数量 as usize {
|
||||
return 配置.笔内元素数量 as usize;
|
||||
}
|
||||
if 筆.方向().是否向下()
|
||||
&& 低_k.低.get() > 筆.高()
|
||||
&& 原始数量 >= 配置.笔弱化_原始数量 as usize
|
||||
{
|
||||
return 配置.笔内元素数量 as usize;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -92,147 +99,182 @@ impl 笔 {
|
||||
}
|
||||
|
||||
/// 次高 — 排除最高值后的次高点
|
||||
pub fn 次高(缠K序列: &[Rc<缠论K线>], 取舍: bool) -> Option<Rc<缠论K线>> {
|
||||
pub fn 次高(缠K序列: &[Arc<缠论K线>], 取舍: bool) -> Option<Arc<缠论K线>> {
|
||||
if 缠K序列.len() < 2 {
|
||||
return 缠K序列.first().cloned();
|
||||
}
|
||||
let max_高 = 缠K序列
|
||||
.iter()
|
||||
.map(|k| k.高)
|
||||
.map(|k| k.高.get())
|
||||
.fold(f64::NEG_INFINITY, f64::max);
|
||||
// 排除最高值
|
||||
let filtered: Vec<&Rc<缠论K线>> = 缠K序列.iter().filter(|k| k.高 != max_高).collect();
|
||||
let filtered: Vec<&Arc<缠论K线>> =
|
||||
缠K序列.iter().filter(|k| k.高.get() != max_高).collect();
|
||||
if filtered.is_empty() {
|
||||
return 缠K序列.first().cloned();
|
||||
}
|
||||
// 筛选次高值
|
||||
let second_高 = filtered
|
||||
.iter()
|
||||
.map(|k| k.高)
|
||||
.map(|k| k.高.get())
|
||||
.fold(f64::NEG_INFINITY, f64::max);
|
||||
let mut candidates: Vec<&Rc<缠论K线>> = filtered
|
||||
let mut candidates: Vec<&Arc<缠论K线>> = filtered
|
||||
.iter()
|
||||
.filter(|k| k.高 == second_高)
|
||||
.filter(|k| k.高.get() == second_高)
|
||||
.copied()
|
||||
.collect();
|
||||
// 按时间戳排序
|
||||
candidates.sort_by(|a, b| a.时间戳.cmp(&b.时间戳));
|
||||
candidates.sort_by(|a, b| {
|
||||
a.时间戳
|
||||
.load(Ordering::Relaxed)
|
||||
.cmp(&b.时间戳.load(Ordering::Relaxed))
|
||||
});
|
||||
if 取舍 {
|
||||
Some(Rc::clone(candidates[candidates.len() - 1]))
|
||||
Some(Arc::clone(candidates[candidates.len() - 1]))
|
||||
} else {
|
||||
Some(Rc::clone(candidates[0]))
|
||||
Some(Arc::clone(candidates[0]))
|
||||
}
|
||||
}
|
||||
|
||||
/// 次低 — 排除最低值后的次低点
|
||||
pub fn 次低(缠K序列: &[Rc<缠论K线>], 取舍: bool) -> Option<Rc<缠论K线>> {
|
||||
pub fn 次低(缠K序列: &[Arc<缠论K线>], 取舍: bool) -> Option<Arc<缠论K线>> {
|
||||
if 缠K序列.len() < 2 {
|
||||
return 缠K序列.first().cloned();
|
||||
}
|
||||
let min_低 = 缠K序列.iter().map(|k| k.低).fold(f64::INFINITY, f64::min);
|
||||
let min_低 = 缠K序列
|
||||
.iter()
|
||||
.map(|k| k.低.get())
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
// 排除最低值
|
||||
let filtered: Vec<&Rc<缠论K线>> = 缠K序列.iter().filter(|k| k.低 != min_低).collect();
|
||||
let filtered: Vec<&Arc<缠论K线>> =
|
||||
缠K序列.iter().filter(|k| k.低.get() != min_低).collect();
|
||||
if filtered.is_empty() {
|
||||
return 缠K序列.first().cloned();
|
||||
}
|
||||
// 筛选次低值
|
||||
let second_低 = filtered.iter().map(|k| k.低).fold(f64::INFINITY, f64::min);
|
||||
let mut candidates: Vec<&Rc<缠论K线>> = filtered
|
||||
let second_低 = filtered
|
||||
.iter()
|
||||
.filter(|k| k.低 == second_低)
|
||||
.map(|k| k.低.get())
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
let mut candidates: Vec<&Arc<缠论K线>> = filtered
|
||||
.iter()
|
||||
.filter(|k| k.低.get() == second_低)
|
||||
.copied()
|
||||
.collect();
|
||||
// 按时间戳排序
|
||||
candidates.sort_by(|a, b| a.时间戳.cmp(&b.时间戳));
|
||||
candidates.sort_by(|a, b| {
|
||||
a.时间戳
|
||||
.load(Ordering::Relaxed)
|
||||
.cmp(&b.时间戳.load(Ordering::Relaxed))
|
||||
});
|
||||
if 取舍 {
|
||||
Some(Rc::clone(candidates[candidates.len() - 1]))
|
||||
Some(Arc::clone(candidates[candidates.len() - 1]))
|
||||
} else {
|
||||
Some(Rc::clone(candidates[0]))
|
||||
Some(Arc::clone(candidates[0]))
|
||||
}
|
||||
}
|
||||
|
||||
/// 实际高点
|
||||
pub fn 实际高点(缠K序列: &[Rc<缠论K线>], 取舍: bool) -> Option<Rc<缠论K线>> {
|
||||
pub fn 实际高点(缠K序列: &[Arc<缠论K线>], 取舍: bool) -> Option<Arc<缠论K线>> {
|
||||
if 缠K序列.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let max_高 = 缠K序列
|
||||
.iter()
|
||||
.map(|k| k.高)
|
||||
.map(|k| k.高.get())
|
||||
.fold(f64::NEG_INFINITY, f64::max);
|
||||
let mut candidates: Vec<&Rc<缠论K线>> = 缠K序列.iter().filter(|k| k.高 == max_高).collect();
|
||||
let mut candidates: Vec<&Arc<缠论K线>> =
|
||||
缠K序列.iter().filter(|k| k.高.get() == max_高).collect();
|
||||
if candidates.is_empty() {
|
||||
return Some(Rc::clone(&缠K序列[0]));
|
||||
return Some(Arc::clone(&缠K序列[0]));
|
||||
}
|
||||
// 按时间戳排序
|
||||
candidates.sort_by(|a, b| a.时间戳.cmp(&b.时间戳));
|
||||
candidates.sort_by(|a, b| {
|
||||
a.时间戳
|
||||
.load(Ordering::Relaxed)
|
||||
.cmp(&b.时间戳.load(Ordering::Relaxed))
|
||||
});
|
||||
if 取舍 {
|
||||
Some(Rc::clone(candidates[candidates.len() - 1]))
|
||||
Some(Arc::clone(candidates[candidates.len() - 1]))
|
||||
} else {
|
||||
Some(Rc::clone(candidates[0]))
|
||||
Some(Arc::clone(candidates[0]))
|
||||
}
|
||||
}
|
||||
|
||||
/// 实际低点
|
||||
pub fn 实际低点(缠K序列: &[Rc<缠论K线>], 取舍: bool) -> Option<Rc<缠论K线>> {
|
||||
pub fn 实际低点(缠K序列: &[Arc<缠论K线>], 取舍: bool) -> Option<Arc<缠论K线>> {
|
||||
if 缠K序列.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let min_低 = 缠K序列.iter().map(|k| k.低).fold(f64::INFINITY, f64::min);
|
||||
let mut candidates: Vec<&Rc<缠论K线>> = 缠K序列.iter().filter(|k| k.低 == min_低).collect();
|
||||
let min_低 = 缠K序列
|
||||
.iter()
|
||||
.map(|k| k.低.get())
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
let mut candidates: Vec<&Arc<缠论K线>> =
|
||||
缠K序列.iter().filter(|k| k.低.get() == min_低).collect();
|
||||
if candidates.is_empty() {
|
||||
return Some(Rc::clone(&缠K序列[0]));
|
||||
return Some(Arc::clone(&缠K序列[0]));
|
||||
}
|
||||
// 按时间戳排序
|
||||
candidates.sort_by(|a, b| a.时间戳.cmp(&b.时间戳));
|
||||
candidates.sort_by(|a, b| {
|
||||
a.时间戳
|
||||
.load(Ordering::Relaxed)
|
||||
.cmp(&b.时间戳.load(Ordering::Relaxed))
|
||||
});
|
||||
if 取舍 {
|
||||
Some(Rc::clone(candidates[candidates.len() - 1]))
|
||||
Some(Arc::clone(candidates[candidates.len() - 1]))
|
||||
} else {
|
||||
Some(Rc::clone(candidates[0]))
|
||||
Some(Arc::clone(candidates[0]))
|
||||
}
|
||||
}
|
||||
|
||||
/// 判断笔的相对关系是否合理
|
||||
pub fn 相对关系(筆: &虚线, 配置: &缠论配置) -> bool {
|
||||
let 文分型 = &筆.文;
|
||||
let 武分型 = &筆.武;
|
||||
let 武分型 = 筆.武.read().unwrap();
|
||||
|
||||
let 相对关系 = if 配置.笔内起始分型包含整笔 {
|
||||
let 文中_rc = Rc::clone(&文分型.中);
|
||||
let 武中_rc = Rc::clone(&武分型.中);
|
||||
let 文_元素: [Option<&Rc<缠论K线>>; 3] =
|
||||
let 文中_rc = Arc::clone(&文分型.中);
|
||||
let 武中_rc = Arc::clone(&武分型.中);
|
||||
let 文_元素: [Option<&Arc<缠论K线>>; 3] =
|
||||
[文分型.左.as_ref(), Some(&文中_rc), 文分型.右.as_ref()];
|
||||
let 有效序列: Vec<&Rc<缠论K线>> = 文_元素.iter().filter_map(|x| *x).collect();
|
||||
let 有效序列: Vec<&Arc<缠论K线>> = 文_元素.iter().filter_map(|x| *x).collect();
|
||||
let 文高 = 有效序列
|
||||
.iter()
|
||||
.map(|k| k.高)
|
||||
.map(|k| k.高.get())
|
||||
.fold(f64::NEG_INFINITY, f64::max);
|
||||
let 文低 = 有效序列.iter().map(|k| k.低).fold(f64::INFINITY, f64::min);
|
||||
let 文低 = 有效序列
|
||||
.iter()
|
||||
.map(|k| k.低.get())
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
|
||||
let 武_右: Option<&Rc<缠论K线>> = if 配置.笔内起始分型包含整笔_包括右 {
|
||||
let 武_右: Option<&Arc<缠论K线>> = if 配置.笔内起始分型包含整笔_包括右 {
|
||||
武分型.右.as_ref()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let 武_元素: [Option<&Rc<缠论K线>>; 3] = [武分型.左.as_ref(), Some(&武中_rc), 武_右];
|
||||
let 有效序列: Vec<&Rc<缠论K线>> = 武_元素.iter().filter_map(|x| *x).collect();
|
||||
let 武_元素: [Option<&Arc<缠论K线>>; 3] = [武分型.左.as_ref(), Some(&武中_rc), 武_右];
|
||||
let 有效序列: Vec<&Arc<缠论K线>> = 武_元素.iter().filter_map(|x| *x).collect();
|
||||
let 武高 = 有效序列
|
||||
.iter()
|
||||
.map(|k| k.高)
|
||||
.map(|k| k.高.get())
|
||||
.fold(f64::NEG_INFINITY, f64::max);
|
||||
let 武低 = 有效序列.iter().map(|k| k.低).fold(f64::INFINITY, f64::min);
|
||||
let 武低 = 有效序列
|
||||
.iter()
|
||||
.map(|k| k.低.get())
|
||||
.fold(f64::INFINITY, f64::min);
|
||||
|
||||
crate::types::相对方向::分析(文高, 文低, 武高, 武低)
|
||||
} else {
|
||||
let 相对关系 = crate::types::相对方向::分析(
|
||||
文分型.中.高,
|
||||
文分型.中.低,
|
||||
武分型.中.高,
|
||||
武分型.中.低,
|
||||
文分型.中.高.get(),
|
||||
文分型.中.低.get(),
|
||||
武分型.中.高.get(),
|
||||
武分型.中.低.get(),
|
||||
);
|
||||
if 配置.笔内原始K线包含整笔 {
|
||||
let 文标的 = &文分型.中.标的K线;
|
||||
let 武标的 = &武分型.中.标的K线;
|
||||
let 文标的 = 文分型.中.标的K线.read().unwrap();
|
||||
let 武标的 = 武分型.中.标的K线.read().unwrap();
|
||||
if crate::types::相对方向::分析(文标的.高, 文标的.低, 武标的.高, 武标的.低)
|
||||
.是否包含()
|
||||
{
|
||||
@@ -249,43 +291,46 @@ impl 笔 {
|
||||
}
|
||||
|
||||
/// 以文会友 — 根据起点分型找笔
|
||||
pub fn 以文会友(笔序列: &[Rc<虚线>], 文: &Rc<分型>) -> Option<Rc<虚线>> {
|
||||
pub fn 以文会友(笔序列: &[Arc<虚线>], 文: &Arc<分型>) -> Option<Arc<虚线>> {
|
||||
笔序列
|
||||
.iter()
|
||||
.find(|b| Rc::as_ptr(&b.文) == Rc::as_ptr(文))
|
||||
.find(|b| Arc::as_ptr(&b.文) == Arc::as_ptr(文))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// 以武会友 — 根据终点分型找笔
|
||||
pub fn 以武会友(笔序列: &[Rc<虚线>], 武: &Rc<分型>) -> Option<Rc<虚线>> {
|
||||
pub fn 以武会友(笔序列: &[Arc<虚线>], 武: &Arc<分型>) -> Option<Arc<虚线>> {
|
||||
笔序列
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|b| Rc::as_ptr(&b.武) == Rc::as_ptr(武))
|
||||
.find(|b| Arc::as_ptr(&*b.武.read().unwrap()) == Arc::as_ptr(武))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// 根据缠K找对应的笔
|
||||
pub fn 根据缠K找笔(
|
||||
笔序列: &[Rc<虚线>],
|
||||
缠K: &Rc<缠论K线>,
|
||||
笔序列: &[Arc<虚线>],
|
||||
缠K: &Arc<缠论K线>,
|
||||
偏移: i64,
|
||||
) -> Option<Rc<虚线>> {
|
||||
) -> Option<Arc<虚线>> {
|
||||
// Python iterates in reverse: for 筆 in 笔序列[::-1]
|
||||
for b in 笔序列.iter().rev() {
|
||||
// Python: 筆.文.中.序号 - 偏移 <= 缠K.序号 <= 筆.武.中.序号
|
||||
if b.文.中.序号 - 偏移 <= 缠K.序号 && 缠K.序号 <= b.武.中.序号 {
|
||||
return Some(Rc::clone(b));
|
||||
// Python: 筆.文.中.序号 - 偏移 <= 缠K.序号.load(Ordering::Relaxed) <= 筆.武.read().unwrap().中.序号
|
||||
if b.文.中.序号.load(Ordering::Relaxed) - 偏移 <= 缠K.序号.load(Ordering::Relaxed)
|
||||
&& 缠K.序号.load(Ordering::Relaxed)
|
||||
<= b.武.read().unwrap().中.序号.load(Ordering::Relaxed)
|
||||
{
|
||||
return Some(Arc::clone(b));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 从分型序列中弹出最后一个分型和对应的笔
|
||||
fn 弹出旧笔(分型序列: &mut Vec<Rc<分型>>, 笔序列: &mut Vec<Rc<虚线>>) {
|
||||
fn 弹出旧笔(分型序列: &mut Vec<Arc<分型>>, 笔序列: &mut Vec<Arc<虚线>>) {
|
||||
分型序列.pop();
|
||||
if !笔序列.is_empty() {
|
||||
// Python sets旧笔.有效性 = False; with Rc we just drop the笔
|
||||
// Python sets旧笔.有效性.store(False, Ordering::Relaxed); with Rc we just drop the笔
|
||||
笔序列.pop();
|
||||
}
|
||||
}
|
||||
@@ -293,20 +338,20 @@ impl 笔 {
|
||||
/// 核心笔分析 — 使用显式栈模拟递归
|
||||
///
|
||||
/// 返回: 递归层次数
|
||||
pub fn 分析(
|
||||
初始分型: Rc<分型>,
|
||||
分型序列: &mut Vec<Rc<分型>>,
|
||||
笔序列: &mut Vec<Rc<虚线>>,
|
||||
缠K序列: &[Rc<缠论K线>],
|
||||
_普K序列: &[Rc<K线>],
|
||||
pub fn 分析_显式栈(
|
||||
初始分型: Arc<分型>,
|
||||
分型序列: &mut Vec<Arc<分型>>,
|
||||
笔序列: &mut Vec<Arc<虚线>>,
|
||||
缠K序列: &[Arc<缠论K线>],
|
||||
_普K序列: &[Arc<K线>],
|
||||
配置: &缠论配置,
|
||||
) -> i64 {
|
||||
enum 栈项 {
|
||||
分型(Rc<分型>, i64),
|
||||
分型(Arc<分型>, i64),
|
||||
/// 修复错过笔哨兵: 若临时分型被接受为最后一个元素,则扫描武将之后的所有分型
|
||||
修复错过笔 {
|
||||
临时分型: Rc<分型>,
|
||||
武将缠K: Rc<缠论K线>,
|
||||
临时分型: Arc<分型>,
|
||||
武将缠K: Arc<缠论K线>,
|
||||
层次: i64,
|
||||
},
|
||||
}
|
||||
@@ -325,20 +370,20 @@ impl 笔 {
|
||||
// Python line 2406: only scan if临时分型 was accepted as last element
|
||||
if !分型序列.is_empty() {
|
||||
if let Some(last_fx) = 分型序列.last() {
|
||||
if Rc::as_ptr(last_fx) == Rc::as_ptr(&临时分型) {
|
||||
if Arc::as_ptr(last_fx) == Arc::as_ptr(&临时分型) {
|
||||
if let Some(武_idx) = 缠K序列
|
||||
.iter()
|
||||
.position(|k| Rc::as_ptr(k) == Rc::as_ptr(&武将缠K))
|
||||
.position(|k| Arc::as_ptr(k) == Arc::as_ptr(&武将缠K))
|
||||
{
|
||||
let mut 错过: Vec<Rc<分型>> = Vec::new();
|
||||
let mut 错过: Vec<Arc<分型>> = Vec::new();
|
||||
for ck in &缠K序列[武_idx..] {
|
||||
if ck.分型 == Some(分型结构::底)
|
||||
|| ck.分型 == Some(分型结构::顶)
|
||||
if *ck.分型.read().unwrap() == Some(分型结构::底)
|
||||
|| *ck.分型.read().unwrap() == Some(分型结构::顶)
|
||||
{
|
||||
if let Some(fx) =
|
||||
分型::从缠K序列中获取分型(缠K序列, ck)
|
||||
{
|
||||
错过.push(Rc::new(fx));
|
||||
错过.push(Arc::new(fx));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -369,10 +414,11 @@ impl 笔 {
|
||||
continue;
|
||||
}
|
||||
|
||||
let 之前分型 = Rc::clone(分型序列.last().unwrap());
|
||||
let 之前分型 = Arc::clone(分型序列.last().unwrap());
|
||||
|
||||
// Python line 2330-2335: 清理无效数据
|
||||
if 之前分型.时间戳 == 当前分型.时间戳
|
||||
if 之前分型.中.时间戳.load(Ordering::Relaxed)
|
||||
== 当前分型.中.时间戳.load(Ordering::Relaxed)
|
||||
|| matches!(之前分型.结构, 分型结构::上 | 分型结构::下)
|
||||
{
|
||||
Self::弹出旧笔(分型序列, 笔序列);
|
||||
@@ -384,10 +430,14 @@ impl 笔 {
|
||||
}
|
||||
}
|
||||
|
||||
let 之前分型 = Rc::clone(分型序列.last().unwrap());
|
||||
let 之前分型 = Arc::clone(分型序列.last().unwrap());
|
||||
|
||||
// Python line 2338: 时序检查 — skip out-of-order fractals
|
||||
if 之前分型.时间戳 > 当前分型.时间戳 && 之前分型.中.序号 - 当前分型.中.序号 > 1
|
||||
if 之前分型.中.时间戳.load(Ordering::Relaxed)
|
||||
> 当前分型.中.时间戳.load(Ordering::Relaxed)
|
||||
&& 之前分型.中.序号.load(Ordering::Relaxed)
|
||||
- 当前分型.中.序号.load(Ordering::Relaxed)
|
||||
> 1
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -395,7 +445,9 @@ impl 笔 {
|
||||
// Python line 2343-2348: 笔弱化模式
|
||||
if 配置.笔弱化 && !笔序列.is_empty() {
|
||||
let 前一笔 = 笔序列.last().unwrap();
|
||||
let 前一笔缠K数 = 前一笔.武.中.序号 - 前一笔.文.中.序号 + 1;
|
||||
let 前一笔缠K数 = 前一笔.武.read().unwrap().中.序号.load(Ordering::Relaxed)
|
||||
- 前一笔.文.中.序号.load(Ordering::Relaxed)
|
||||
+ 1;
|
||||
if 前一笔缠K数 == 3 {
|
||||
let 破位 = (前一笔.方向().是否向上()
|
||||
&& 前一笔.低() > 当前分型.分型特征值
|
||||
@@ -412,16 +464,16 @@ impl 笔 {
|
||||
}
|
||||
|
||||
// Re-read之前分型 again after笔弱化 pop
|
||||
let 之前分型 = Rc::clone(分型序列.last().unwrap());
|
||||
let 之前分型 = Arc::clone(分型序列.last().unwrap());
|
||||
|
||||
// Python line 2350: 分型结构相反 → 可能成笔
|
||||
if 之前分型.结构 != 当前分型.结构 {
|
||||
let 文_idx = 缠K序列
|
||||
.iter()
|
||||
.position(|k| Rc::as_ptr(k) == Rc::as_ptr(&之前分型.中));
|
||||
.position(|k| Arc::as_ptr(k) == Arc::as_ptr(&之前分型.中));
|
||||
let 武_idx = 缠K序列
|
||||
.iter()
|
||||
.position(|k| Rc::as_ptr(k) == Rc::as_ptr(&当前分型.中));
|
||||
.position(|k| Arc::as_ptr(k) == Arc::as_ptr(&当前分型.中));
|
||||
|
||||
if let (Some(文_idx), Some(武_idx)) = (文_idx, 武_idx) {
|
||||
let 基础序列 = &缠K序列[文_idx..=武_idx];
|
||||
@@ -436,12 +488,12 @@ impl 笔 {
|
||||
|
||||
// Python line 2359-2367: 文官 != 之前分型.中 → adjust
|
||||
if let Some(ref 文官_k) = 文官 {
|
||||
if Rc::as_ptr(文官_k) != Rc::as_ptr(&之前分型.中) {
|
||||
if Arc::as_ptr(文官_k) != Arc::as_ptr(&之前分型.中) {
|
||||
if let Some(临时分型) =
|
||||
分型::从缠K序列中获取分型(缠K序列, 文官_k)
|
||||
{
|
||||
栈.push(栈项::分型(当前分型, 递归层次));
|
||||
栈.push(栈项::分型(Rc::new(临时分型), 递归层次 + 1));
|
||||
栈.push(栈项::分型(Arc::new(临时分型), 递归层次 + 1));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -455,16 +507,16 @@ impl 笔 {
|
||||
_ => Self::实际高点(基础序列, 配置.笔内相同终点取舍),
|
||||
};
|
||||
|
||||
let 新笔 = Rc::new(虚线::创建笔(
|
||||
Rc::clone(&之前分型),
|
||||
Rc::clone(&当前分型),
|
||||
let 新笔 = Arc::new(虚线::创建笔(
|
||||
Arc::clone(&之前分型),
|
||||
Arc::clone(&当前分型),
|
||||
true,
|
||||
));
|
||||
|
||||
// Python line 2374-2376: 相对关系 and武将 matches
|
||||
if Self::相对关系(&新笔, 配置) {
|
||||
if let Some(ref 武将_k) = 武将 {
|
||||
if Rc::as_ptr(武将_k) == Rc::as_ptr(&当前分型.中) {
|
||||
if Arc::as_ptr(武将_k) == Arc::as_ptr(&当前分型.中) {
|
||||
Self::_添加新笔递归(分型序列, 笔序列, 当前分型, 新笔);
|
||||
continue;
|
||||
}
|
||||
@@ -478,7 +530,7 @@ impl 笔 {
|
||||
_ => Self::次高(基础序列, 配置.笔内相同终点取舍),
|
||||
};
|
||||
if let Some(ref 武将_k) = 武将 {
|
||||
if Rc::as_ptr(武将_k) == Rc::as_ptr(&当前分型.中)
|
||||
if Arc::as_ptr(武将_k) == Arc::as_ptr(&当前分型.中)
|
||||
&& Self::相对关系(&新笔, 配置)
|
||||
{
|
||||
Self::_添加新笔递归(分型序列, 笔序列, 当前分型, 新笔);
|
||||
@@ -492,7 +544,7 @@ impl 笔 {
|
||||
if let Some(临时分型) =
|
||||
分型::从缠K序列中获取分型(缠K序列, 右)
|
||||
{
|
||||
栈.push(栈项::分型(Rc::new(临时分型), 递归层次 + 1));
|
||||
栈.push(栈项::分型(Arc::new(临时分型), 递归层次 + 1));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
@@ -509,7 +561,7 @@ impl 笔 {
|
||||
};
|
||||
|
||||
if 更强 {
|
||||
let 被替换分型 = Rc::clone(&之前分型);
|
||||
let 被替换分型 = Arc::clone(&之前分型);
|
||||
Self::弹出旧笔(分型序列, 笔序列);
|
||||
|
||||
if let Some(k线序列) = 缠论K线::截取(缠K序列, &被替换分型.中, &当前分型.中)
|
||||
@@ -525,14 +577,14 @@ impl 笔 {
|
||||
if let Some(临时分型) =
|
||||
分型::从缠K序列中获取分型(缠K序列, 武将_k)
|
||||
{
|
||||
let 临时分型_rc = Rc::new(临时分型);
|
||||
let 临时分型_rc = Arc::new(临时分型);
|
||||
|
||||
if !分型序列.is_empty() {
|
||||
// Push in reverse processing order (LIFO):
|
||||
栈.push(栈项::分型(Rc::clone(&当前分型), 递归层次 + 2));
|
||||
栈.push(栈项::分型(Arc::clone(&当前分型), 递归层次 + 2));
|
||||
栈.push(栈项::修复错过笔 {
|
||||
临时分型: Rc::clone(&临时分型_rc),
|
||||
武将缠K: Rc::clone(武将_k),
|
||||
临时分型: Arc::clone(&临时分型_rc),
|
||||
武将缠K: Arc::clone(武将_k),
|
||||
层次: 递归层次 + 1,
|
||||
});
|
||||
栈.push(栈项::分型(临时分型_rc, 递归层次 + 1));
|
||||
@@ -560,12 +612,12 @@ impl 笔 {
|
||||
/// 核心笔分析 — 递归实现,逐句对照 chan.py 笔.分析 / 笔递归分析
|
||||
///
|
||||
/// 返回: 递归层次数
|
||||
pub fn 分析递归(
|
||||
当前分型: Rc<分型>,
|
||||
分型序列: &mut Vec<Rc<分型>>,
|
||||
笔序列: &mut Vec<Rc<虚线>>,
|
||||
缠K序列: &[Rc<缠论K线>],
|
||||
_普K序列: &[Rc<K线>],
|
||||
pub fn 分析(
|
||||
当前分型: Arc<分型>,
|
||||
分型序列: &mut Vec<Arc<分型>>,
|
||||
笔序列: &mut Vec<Arc<虚线>>,
|
||||
缠K序列: &[Arc<缠论K线>],
|
||||
_普K序列: &[Arc<K线>],
|
||||
递归层次: i64,
|
||||
配置: &缠论配置,
|
||||
) -> i64 {
|
||||
@@ -588,8 +640,8 @@ impl 笔 {
|
||||
}
|
||||
|
||||
// Python line 2329-2335: 清理无效数据
|
||||
let 之前分型 = Rc::clone(分型序列.last().unwrap());
|
||||
if 之前分型.时间戳 == 当前分型.时间戳
|
||||
let 之前分型 = Arc::clone(分型序列.last().unwrap());
|
||||
if 之前分型.中.时间戳.load(Ordering::Relaxed) == 当前分型.中.时间戳.load(Ordering::Relaxed)
|
||||
|| matches!(之前分型.结构, 分型结构::上 | 分型结构::下)
|
||||
{
|
||||
Self::弹出旧笔(分型序列, 笔序列);
|
||||
@@ -602,8 +654,10 @@ impl 笔 {
|
||||
}
|
||||
|
||||
// Python line 2337-2341: 时序检查
|
||||
let 之前分型 = Rc::clone(分型序列.last().unwrap());
|
||||
if 之前分型.时间戳 > 当前分型.时间戳 && 之前分型.中.序号 - 当前分型.中.序号 > 1
|
||||
let 之前分型 = Arc::clone(分型序列.last().unwrap());
|
||||
if 之前分型.中.时间戳.load(Ordering::Relaxed) > 当前分型.中.时间戳.load(Ordering::Relaxed)
|
||||
&& 之前分型.中.序号.load(Ordering::Relaxed) - 当前分型.中.序号.load(Ordering::Relaxed)
|
||||
> 1
|
||||
{
|
||||
println!("时序错误-{}, {}, {}", 递归层次, 之前分型, 当前分型);
|
||||
return 递归层次;
|
||||
@@ -612,7 +666,9 @@ impl 笔 {
|
||||
// Python line 2343-2348: 笔弱化模式
|
||||
if 配置.笔弱化 && !笔序列.is_empty() {
|
||||
let 前一笔 = 笔序列.last().unwrap();
|
||||
let 前一笔缠K数 = 前一笔.武.中.序号 - 前一笔.文.中.序号 + 1;
|
||||
let 前一笔缠K数 = 前一笔.武.read().unwrap().中.序号.load(Ordering::Relaxed)
|
||||
- 前一笔.文.中.序号.load(Ordering::Relaxed)
|
||||
+ 1;
|
||||
if 前一笔缠K数 == 3 {
|
||||
let 破位 = (前一笔.方向().是否向上()
|
||||
&& 前一笔.低() > 当前分型.分型特征值
|
||||
@@ -622,7 +678,7 @@ impl 笔 {
|
||||
&& 当前分型.结构 == 分型结构::顶);
|
||||
if 破位 {
|
||||
Self::弹出旧笔(分型序列, 笔序列);
|
||||
return Self::分析递归(
|
||||
return Self::分析(
|
||||
当前分型,
|
||||
分型序列,
|
||||
笔序列,
|
||||
@@ -636,13 +692,13 @@ impl 笔 {
|
||||
}
|
||||
|
||||
// Python line 2350: 分型结构相反 → 可能成笔
|
||||
let 之前分型 = Rc::clone(分型序列.last().unwrap());
|
||||
let 之前分型 = Arc::clone(分型序列.last().unwrap());
|
||||
if 之前分型.结构 != 当前分型.结构 {
|
||||
if let Some(基础序列) = 缠论K线::截取(缠K序列, &之前分型.中, &当前分型.中)
|
||||
{
|
||||
let 当前笔 = Rc::new(虚线::创建笔(
|
||||
Rc::clone(&之前分型),
|
||||
Rc::clone(&当前分型),
|
||||
let 当前笔 = Arc::new(虚线::创建笔(
|
||||
Arc::clone(&之前分型),
|
||||
Arc::clone(&当前分型),
|
||||
true,
|
||||
));
|
||||
|
||||
@@ -656,12 +712,12 @@ impl 笔 {
|
||||
|
||||
// Python line 2359-2367: 文官调整
|
||||
if let Some(ref 文官_k) = 文官 {
|
||||
if Rc::as_ptr(文官_k) != Rc::as_ptr(&之前分型.中) {
|
||||
if Arc::as_ptr(文官_k) != Arc::as_ptr(&之前分型.中) {
|
||||
if let Some(临时分型) =
|
||||
分型::从缠K序列中获取分型(缠K序列, 文官_k)
|
||||
{
|
||||
let 递归层次 = Self::分析递归(
|
||||
Rc::new(临时分型),
|
||||
let 递归层次 = Self::分析(
|
||||
Arc::new(临时分型),
|
||||
分型序列,
|
||||
笔序列,
|
||||
缠K序列,
|
||||
@@ -669,7 +725,7 @@ impl 笔 {
|
||||
递归层次 + 1,
|
||||
配置,
|
||||
);
|
||||
return Self::分析递归(
|
||||
return Self::分析(
|
||||
当前分型,
|
||||
分型序列,
|
||||
笔序列,
|
||||
@@ -690,7 +746,7 @@ impl 笔 {
|
||||
|
||||
if Self::相对关系(&当前笔, 配置) {
|
||||
if let Some(ref 武将_k) = 武将 {
|
||||
if Rc::as_ptr(武将_k) == Rc::as_ptr(&当前分型.中) {
|
||||
if Arc::as_ptr(武将_k) == Arc::as_ptr(&当前分型.中) {
|
||||
// 直接添加(对照 Python _添加新笔:直接 append)
|
||||
Self::_添加新笔递归(分型序列, 笔序列, 当前分型, 当前笔);
|
||||
return 递归层次;
|
||||
@@ -705,7 +761,7 @@ impl 笔 {
|
||||
_ => Self::次高(&基础序列, 配置.笔内相同终点取舍),
|
||||
};
|
||||
if let Some(ref 武将_k) = 武将 {
|
||||
if Rc::as_ptr(武将_k) == Rc::as_ptr(&当前分型.中)
|
||||
if Arc::as_ptr(武将_k) == Arc::as_ptr(&当前分型.中)
|
||||
&& Self::相对关系(&当前笔, 配置)
|
||||
{
|
||||
Self::_添加新笔递归(分型序列, 笔序列, 当前分型, 当前笔);
|
||||
@@ -718,8 +774,8 @@ impl 笔 {
|
||||
if let Some(ref 右) = 当前分型.右 {
|
||||
if let Some(临时分型) = 分型::从缠K序列中获取分型(缠K序列, 右)
|
||||
{
|
||||
return Self::分析递归(
|
||||
Rc::new(临时分型),
|
||||
return Self::分析(
|
||||
Arc::new(临时分型),
|
||||
分型序列,
|
||||
笔序列,
|
||||
缠K序列,
|
||||
@@ -743,7 +799,7 @@ impl 笔 {
|
||||
|
||||
if 更强 {
|
||||
// 保存被弹出的之前分型(用于修复错过笔的范围计算)
|
||||
let 被替换分型 = Rc::clone(&之前分型);
|
||||
let 被替换分型 = Arc::clone(&之前分型);
|
||||
Self::弹出旧笔(分型序列, 笔序列);
|
||||
|
||||
if let Some(k线序列) = 缠论K线::截取(缠K序列, &被替换分型.中, &当前分型.中)
|
||||
@@ -757,11 +813,11 @@ impl 笔 {
|
||||
if let Some(临时分型) =
|
||||
分型::从缠K序列中获取分型(缠K序列, 武将_k)
|
||||
{
|
||||
let 临时分型_rc = Rc::new(临时分型);
|
||||
let 临时分型_rc = Arc::new(临时分型);
|
||||
|
||||
if !分型序列.is_empty() {
|
||||
let mut 递归层次 = Self::分析递归(
|
||||
Rc::clone(&临时分型_rc),
|
||||
let mut 递归层次 = Self::分析(
|
||||
Arc::clone(&临时分型_rc),
|
||||
分型序列,
|
||||
笔序列,
|
||||
缠K序列,
|
||||
@@ -772,25 +828,25 @@ impl 笔 {
|
||||
|
||||
// 修复错过的笔: 扫描武将之后的所有分型
|
||||
if !分型序列.is_empty()
|
||||
&& Rc::as_ptr(分型序列.last().unwrap())
|
||||
== Rc::as_ptr(&临时分型_rc)
|
||||
&& Arc::as_ptr(分型序列.last().unwrap())
|
||||
== Arc::as_ptr(&临时分型_rc)
|
||||
{
|
||||
if let Some(武_idx) = 缠K序列
|
||||
.iter()
|
||||
.position(|k| Rc::as_ptr(k) == Rc::as_ptr(武将_k))
|
||||
.position(|k| Arc::as_ptr(k) == Arc::as_ptr(武将_k))
|
||||
{
|
||||
for ck in &缠K序列[武_idx..] {
|
||||
if ck.分型 == Some(分型结构::底)
|
||||
|| ck.分型 == Some(分型结构::顶)
|
||||
if *ck.分型.read().unwrap() == Some(分型结构::底)
|
||||
|| *ck.分型.read().unwrap() == Some(分型结构::顶)
|
||||
{
|
||||
if let Some(错过分型) =
|
||||
分型::从缠K序列中获取分型(
|
||||
缠K序列, ck,
|
||||
)
|
||||
{
|
||||
let 错过分型_rc = Rc::new(错过分型);
|
||||
递归层次 = Self::分析递归(
|
||||
Rc::clone(&错过分型_rc),
|
||||
let 错过分型_rc = Arc::new(错过分型);
|
||||
递归层次 = Self::分析(
|
||||
Arc::clone(&错过分型_rc),
|
||||
分型序列,
|
||||
笔序列,
|
||||
缠K序列,
|
||||
@@ -804,7 +860,7 @@ impl 笔 {
|
||||
}
|
||||
}
|
||||
|
||||
return Self::分析递归(
|
||||
return Self::分析(
|
||||
当前分型,
|
||||
分型序列,
|
||||
笔序列,
|
||||
@@ -821,7 +877,7 @@ impl 笔 {
|
||||
} else if 分型序列.is_empty() {
|
||||
分型::向序列中添加(分型序列, 当前分型);
|
||||
} else {
|
||||
return Self::分析递归(
|
||||
return Self::分析(
|
||||
当前分型,
|
||||
分型序列,
|
||||
笔序列,
|
||||
@@ -839,17 +895,20 @@ impl 笔 {
|
||||
|
||||
/// 添加新笔到序列(递归版本 — 直接追加,对应 Python _添加新笔)
|
||||
fn _添加新笔递归(
|
||||
分型序列: &mut Vec<Rc<分型>>,
|
||||
笔序列: &mut Vec<Rc<虚线>>,
|
||||
新分型: Rc<分型>,
|
||||
mut 新笔: Rc<虚线>,
|
||||
分型序列: &mut Vec<Arc<分型>>,
|
||||
笔序列: &mut Vec<Arc<虚线>>,
|
||||
新分型: Arc<分型>,
|
||||
mut 新笔: Arc<虚线>,
|
||||
) {
|
||||
分型序列.push(新分型);
|
||||
if !笔序列.is_empty() {
|
||||
let seg = Rc::make_mut(&mut 新笔);
|
||||
seg.序号 = 笔序列.last().unwrap().序号 + 1;
|
||||
if seg.武.左.is_none() && seg.武.右.is_none() {
|
||||
seg.有效性 = false;
|
||||
let seg = Arc::make_mut(&mut 新笔);
|
||||
seg.序号.store(
|
||||
笔序列.last().unwrap().序号.load(Ordering::Relaxed) + 1,
|
||||
Ordering::Relaxed,
|
||||
);
|
||||
if seg.武.read().unwrap().左.is_none() && seg.武.read().unwrap().右.is_none() {
|
||||
seg.有效性.store(false, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
笔序列.push(新笔);
|
||||
@@ -867,7 +926,8 @@ impl 笔 {
|
||||
Self::实际高点(&基础序列, false),
|
||||
Self::实际低点(&基础序列, 配置.笔内相同终点取舍),
|
||||
) {
|
||||
if Rc::ptr_eq(&筆.文.中, &实际高) && Rc::ptr_eq(&筆.武.中, &实际低)
|
||||
if Arc::ptr_eq(&筆.文.中, &实际高)
|
||||
&& Arc::ptr_eq(&筆.武.read().unwrap().中, &实际低)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -878,7 +938,8 @@ impl 笔 {
|
||||
Self::实际低点(&基础序列, false),
|
||||
Self::实际高点(&基础序列, 配置.笔内相同终点取舍),
|
||||
) {
|
||||
if Rc::ptr_eq(&筆.文.中, &实际低) && Rc::ptr_eq(&筆.武.中, &实际高)
|
||||
if Arc::ptr_eq(&筆.文.中, &实际低)
|
||||
&& Arc::ptr_eq(&筆.武.read().unwrap().中, &实际高)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -891,7 +952,7 @@ impl 笔 {
|
||||
/// 获取所有停顿位置 — 在笔范围内找出所有能成笔的分型组合
|
||||
pub fn 获取所有停顿位置(筆: &虚线, 观察员: &观察者) -> Vec<虚线> {
|
||||
let mut 笔序列 = Vec::new();
|
||||
let 文 = Rc::clone(&筆.文);
|
||||
let 文 = Arc::clone(&筆.文);
|
||||
let 基础序列 = 筆.获取缠K序列(&观察员.缠论K线序列);
|
||||
|
||||
if 基础序列.len() < 5 {
|
||||
@@ -901,23 +962,19 @@ impl 笔 {
|
||||
for i in 3..基础序列.len() - 1 {
|
||||
let k = &基础序列[i];
|
||||
|
||||
if k.分型 == Some(分型结构::顶) && 筆.方向() == 相对方向::向上 {
|
||||
let 左 = Rc::clone(&基础序列[i - 1]);
|
||||
let 中 = Rc::clone(k);
|
||||
let 右 = Rc::clone(&基础序列[i + 1]);
|
||||
let 匹配顶 =
|
||||
*k.分型.read().unwrap() == Some(分型结构::顶) && 筆.方向() == 相对方向::向上;
|
||||
let 匹配底 =
|
||||
*k.分型.read().unwrap() == Some(分型结构::底) && 筆.方向() == 相对方向::向下;
|
||||
if 匹配顶 || 匹配底 {
|
||||
let 左 = Arc::clone(&基础序列[i - 1]);
|
||||
let 中 = Arc::clone(k);
|
||||
let 右 = Arc::clone(&基础序列[i + 1]);
|
||||
let 武 = 分型::new(Some(左), 中, Some(右));
|
||||
let mut 当前笔 = 虚线::创建笔(Rc::clone(&文), Rc::new(武), true);
|
||||
当前笔.序号 = 筆.序号;
|
||||
if Self::自检(&当前笔, 观察员) {
|
||||
笔序列.push(当前笔);
|
||||
}
|
||||
} else if k.分型 == Some(分型结构::底) && 筆.方向() == 相对方向::向下 {
|
||||
let 左 = Rc::clone(&基础序列[i - 1]);
|
||||
let 中 = Rc::clone(k);
|
||||
let 右 = Rc::clone(&基础序列[i + 1]);
|
||||
let 武 = 分型::new(Some(左), 中, Some(右));
|
||||
let mut 当前笔 = 虚线::创建笔(Rc::clone(&文), Rc::new(武), true);
|
||||
当前笔.序号 = 筆.序号;
|
||||
let 当前笔 = 虚线::创建笔(Arc::clone(&文), Arc::new(武), true);
|
||||
当前笔
|
||||
.序号
|
||||
.store(筆.序号.load(Ordering::Relaxed), Ordering::Relaxed);
|
||||
if Self::自检(&当前笔, 观察员) {
|
||||
笔序列.push(当前笔);
|
||||
}
|
||||
@@ -928,19 +985,19 @@ impl 笔 {
|
||||
}
|
||||
|
||||
/// 是否背驰过 — 判断笔是否在停顿位置出现过MACD趋向背驰
|
||||
pub fn 是否背驰过(当前筆: &虚线, 观察员: &观察者) -> Vec<Rc<缠论K线>> {
|
||||
pub fn 是否背驰过(当前筆: &虚线, 观察员: &观察者) -> Vec<Arc<缠论K线>> {
|
||||
let 停顿位置 = Self::获取所有停顿位置(当前筆, 观察员);
|
||||
let mut 结果 = Vec::new();
|
||||
|
||||
for 筆 in &停顿位置 {
|
||||
let k线范围 = K线::截取rc(
|
||||
&观察员.普通K线序列,
|
||||
&当前筆.文.中.标的K线,
|
||||
&当前筆.武.中.标的K线,
|
||||
&当前筆.文.中.标的K线.read().unwrap().clone(),
|
||||
&当前筆.武.read().unwrap().中.标的K线.read().unwrap().clone(),
|
||||
);
|
||||
let 背驰信号 = 虚线::计算K线序列MACD趋向背驰(&k线范围, 筆.方向());
|
||||
if 背驰信号.iter().all(|&x| x) {
|
||||
结果.push(Rc::clone(&筆.武.中));
|
||||
结果.push(Arc::clone(&筆.武.read().unwrap().中));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ use crate::config::缠论配置;
|
||||
use crate::kline::bar::K线;
|
||||
use crate::structure::dash_line::虚线;
|
||||
use crate::types::相对方向;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// 背驰分析 — 判断进入段和离开段之间是否存在背驰
|
||||
pub struct 背驰分析;
|
||||
@@ -35,12 +35,18 @@ impl 背驰分析 {
|
||||
/// MACD背驰 — MACD柱状线面积背驰
|
||||
/// 方式: "总"=阳+|阴|总面积, 其他=按进入段方向选阳或阴
|
||||
pub fn MACD背驰(
|
||||
进入段: &虚线, 离开段: &虚线, K线序列: &[Rc<K线>], 方式: &str
|
||||
进入段: &虚线, 离开段: &虚线, K线序列: &[Arc<K线>], 方式: &str
|
||||
) -> bool {
|
||||
let 进入MACD =
|
||||
Self::_获取MACD面积(K线序列, &进入段.文.中.标的K线, &进入段.武.中.标的K线);
|
||||
let 离开MACD =
|
||||
Self::_获取MACD面积(K线序列, &离开段.文.中.标的K线, &离开段.武.中.标的K线);
|
||||
let 进入MACD = Self::_获取MACD面积(
|
||||
K线序列,
|
||||
&进入段.文.中.标的K线.read().unwrap(),
|
||||
&进入段.武.read().unwrap().中.标的K线.read().unwrap(),
|
||||
);
|
||||
let 离开MACD = Self::_获取MACD面积(
|
||||
K线序列,
|
||||
&离开段.文.中.标的K线.read().unwrap(),
|
||||
&离开段.武.read().unwrap().中.标的K线.read().unwrap(),
|
||||
);
|
||||
|
||||
// 计算面积(绝对值求和)
|
||||
let 进入面积 = if 方式 == "总" {
|
||||
@@ -63,18 +69,18 @@ impl 背驰分析 {
|
||||
|
||||
/// 斜率背驰 — 价格斜率背驰
|
||||
pub fn 斜率背驰(进入段: &虚线, 离开段: &虚线) -> bool {
|
||||
let dx = (进入段.武.时间戳 - 进入段.文.时间戳) as f64;
|
||||
let dx = (进入段.武.read().unwrap().时间戳() - 进入段.文.时间戳()) as f64;
|
||||
if dx == 0.0 {
|
||||
return false;
|
||||
}
|
||||
let dy = 进入段.武.分型特征值 - 进入段.文.分型特征值;
|
||||
let dy = 进入段.武.read().unwrap().分型特征值 - 进入段.文.分型特征值;
|
||||
let 进入斜率 = dy / dx;
|
||||
|
||||
let dx = (离开段.武.时间戳 - 离开段.文.时间戳) as f64;
|
||||
let dx = (离开段.武.read().unwrap().时间戳() - 离开段.文.时间戳()) as f64;
|
||||
if dx == 0.0 {
|
||||
return false;
|
||||
}
|
||||
let dy = 离开段.武.分型特征值 - 离开段.文.分型特征值;
|
||||
let dy = 离开段.武.read().unwrap().分型特征值 - 离开段.文.分型特征值;
|
||||
let 离开斜率 = dy / dx;
|
||||
|
||||
if 进入段.方向() == 相对方向::向上 {
|
||||
@@ -86,12 +92,12 @@ impl 背驰分析 {
|
||||
|
||||
/// 测度背驰 — 价格时间测度背驰
|
||||
pub fn 测度背驰(进入段: &虚线, 离开段: &虚线) -> bool {
|
||||
let dx = (进入段.武.时间戳 - 进入段.文.时间戳) as f64;
|
||||
let dy = 进入段.武.分型特征值 - 进入段.文.分型特征值;
|
||||
let dx = (进入段.武.read().unwrap().时间戳() - 进入段.文.时间戳()) as f64;
|
||||
let dy = 进入段.武.read().unwrap().分型特征值 - 进入段.文.分型特征值;
|
||||
let 进入测度 = (dx * dx + dy * dy).sqrt();
|
||||
|
||||
let dx = (离开段.武.时间戳 - 离开段.文.时间戳) as f64;
|
||||
let dy = 离开段.武.分型特征值 - 离开段.文.分型特征值;
|
||||
let dx = (离开段.武.read().unwrap().时间戳() - 离开段.文.时间戳()) as f64;
|
||||
let dy = 离开段.武.read().unwrap().分型特征值 - 离开段.文.分型特征值;
|
||||
let 离开测度 = (dx * dx + dy * dy).sqrt();
|
||||
|
||||
if 进入段.方向() == 相对方向::向上 {
|
||||
@@ -102,14 +108,14 @@ impl 背驰分析 {
|
||||
}
|
||||
|
||||
/// 全量背驰 — MACD + 斜率 + 测度 三者全满足
|
||||
pub fn 全量背驰(进入段: &虚线, 离开段: &虚线, 普K序列: &[Rc<K线>]) -> bool {
|
||||
pub fn 全量背驰(进入段: &虚线, 离开段: &虚线, 普K序列: &[Arc<K线>]) -> bool {
|
||||
Self::MACD背驰(进入段, 离开段, 普K序列, "总")
|
||||
&& Self::测度背驰(进入段, 离开段)
|
||||
&& Self::斜率背驰(进入段, 离开段)
|
||||
}
|
||||
|
||||
/// 任意背驰 — 任一条件满足即可
|
||||
pub fn 任意背驰(进入段: &虚线, 离开段: &虚线, 普K序列: &[Rc<K线>]) -> bool {
|
||||
pub fn 任意背驰(进入段: &虚线, 离开段: &虚线, 普K序列: &[Arc<K线>]) -> bool {
|
||||
Self::MACD背驰(进入段, 离开段, 普K序列, "总")
|
||||
|| Self::测度背驰(进入段, 离开段)
|
||||
|| Self::斜率背驰(进入段, 离开段)
|
||||
@@ -119,7 +125,7 @@ impl 背驰分析 {
|
||||
pub fn 配置背驰(
|
||||
进入段: &虚线,
|
||||
离开段: &虚线,
|
||||
普K序列: &[Rc<K线>],
|
||||
普K序列: &[Arc<K线>],
|
||||
配置: &缠论配置,
|
||||
) -> bool {
|
||||
match (
|
||||
@@ -152,7 +158,7 @@ impl 背驰分析 {
|
||||
}
|
||||
|
||||
/// 任选背驰 — 至少两个条件满足(多数投票)
|
||||
pub fn 任选背驰(进入段: &虚线, 离开段: &虚线, 普K序列: &[Rc<K线>]) -> bool {
|
||||
pub fn 任选背驰(进入段: &虚线, 离开段: &虚线, 普K序列: &[Arc<K线>]) -> bool {
|
||||
let 混沌槽 = [
|
||||
Self::MACD背驰(进入段, 离开段, 普K序列, "总"),
|
||||
Self::测度背驰(进入段, 离开段),
|
||||
@@ -165,7 +171,7 @@ impl 背驰分析 {
|
||||
pub fn 背驰模式(
|
||||
进入段: &虚线,
|
||||
离开段: &虚线,
|
||||
普K序列: &[Rc<K线>],
|
||||
普K序列: &[Arc<K线>],
|
||||
配置: &缠论配置,
|
||||
模式: &str,
|
||||
) -> bool {
|
||||
@@ -180,9 +186,13 @@ impl 背驰分析 {
|
||||
|
||||
// ---- 内部辅助 ----
|
||||
|
||||
fn _获取MACD面积(K线序列: &[Rc<K线>], 始: &Rc<K线>, 终: &Rc<K线>) -> MACD面积 {
|
||||
let 始_idx = K线序列.iter().position(|k| Rc::as_ptr(k) == Rc::as_ptr(始));
|
||||
let 终_idx = K线序列.iter().position(|k| Rc::as_ptr(k) == Rc::as_ptr(终));
|
||||
fn _获取MACD面积(K线序列: &[Arc<K线>], 始: &Arc<K线>, 终: &Arc<K线>) -> MACD面积 {
|
||||
let 始_idx = K线序列
|
||||
.iter()
|
||||
.position(|k| Arc::as_ptr(k) == Arc::as_ptr(始));
|
||||
let 终_idx = K线序列
|
||||
.iter()
|
||||
.position(|k| Arc::as_ptr(k) == Arc::as_ptr(终));
|
||||
|
||||
let mut 阳 = 0.0f64;
|
||||
let mut 阴 = 0.0f64;
|
||||
|
||||
+482
-130
@@ -25,35 +25,50 @@
|
||||
use crate::structure::dash_line::虚线;
|
||||
use crate::structure::fractal_obj::分型;
|
||||
use crate::types::相对方向;
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicI64, Ordering};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
/// 中枢 — 三段虚线重叠区间构成的价格中枢
|
||||
#[derive(Debug, Clone)]
|
||||
/// 可变字段使用 Cell/RefCell 实现内部可变性,确保 Rc 指针身份一致
|
||||
#[derive(Debug)]
|
||||
pub struct 中枢 {
|
||||
pub 序号: i64,
|
||||
pub 标识: String,
|
||||
pub 级别: i64,
|
||||
pub 基础序列: Vec<Rc<虚线>>,
|
||||
pub 第三买卖线: Option<Rc<虚线>>,
|
||||
pub 本级_第三买卖线: Option<Rc<虚线>>,
|
||||
pub 序号: AtomicI64,
|
||||
pub 标识: RwLock<String>,
|
||||
pub 级别: AtomicI64,
|
||||
pub 基础序列: RwLock<Vec<Arc<虚线>>>,
|
||||
pub 第三买卖线: RwLock<Option<Arc<虚线>>>,
|
||||
pub 本级_第三买卖线: RwLock<Option<Arc<虚线>>>,
|
||||
}
|
||||
|
||||
impl Clone for 中枢 {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
序号: AtomicI64::new(self.序号.load(Ordering::Relaxed)),
|
||||
标识: RwLock::new(self.标识.read().unwrap().clone()),
|
||||
级别: AtomicI64::new(self.级别.load(Ordering::Relaxed)),
|
||||
基础序列: RwLock::new(self.基础序列.read().unwrap().clone()),
|
||||
第三买卖线: RwLock::new(self.第三买卖线.read().unwrap().clone()),
|
||||
本级_第三买卖线: RwLock::new(self.本级_第三买卖线.read().unwrap().clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl 中枢 {
|
||||
pub fn new(序号: i64, 标识: String, 级别: i64, 基础序列: Vec<Rc<虚线>>) -> Self {
|
||||
pub fn new(序号: i64, 标识: String, 级别: i64, 基础序列: Vec<Arc<虚线>>) -> Self {
|
||||
Self {
|
||||
序号,
|
||||
标识,
|
||||
级别,
|
||||
基础序列: 基础序列.into_iter().take(3).collect(),
|
||||
第三买卖线: None,
|
||||
本级_第三买卖线: None,
|
||||
序号: AtomicI64::new(序号),
|
||||
标识: RwLock::new(标识),
|
||||
级别: AtomicI64::new(级别),
|
||||
基础序列: RwLock::new(基础序列.into_iter().take(3).collect()),
|
||||
第三买卖线: RwLock::new(None),
|
||||
本级_第三买卖线: RwLock::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn 添加虚线(&mut self, 实线: Rc<虚线>) {
|
||||
self.基础序列.push(实线);
|
||||
self.本级_第三买卖线 = None;
|
||||
self.第三买卖线 = None;
|
||||
pub fn 添加虚线(&self, 实线: Arc<虚线>) {
|
||||
self.基础序列.write().unwrap().push(实线);
|
||||
*self.本级_第三买卖线.write().unwrap() = None;
|
||||
*self.第三买卖线.write().unwrap() = None;
|
||||
}
|
||||
|
||||
pub fn 图表标题(&self) -> String {
|
||||
@@ -61,21 +76,21 @@ impl 中枢 {
|
||||
"{}:{}:{}:{}",
|
||||
self.文().中.标识,
|
||||
self.文().中.周期,
|
||||
self.标识,
|
||||
self.序号
|
||||
self.标识.read().unwrap(),
|
||||
self.序号.load(Ordering::Relaxed)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn 离开段(&self) -> Rc<虚线> {
|
||||
Rc::clone(&self.基础序列[self.基础序列.len() - 1])
|
||||
pub fn 离开段(&self) -> Arc<虚线> {
|
||||
Arc::clone(&self.基础序列.read().unwrap()[self.基础序列.read().unwrap().len() - 1])
|
||||
}
|
||||
|
||||
pub fn 方向(&self) -> 相对方向 {
|
||||
self.基础序列[0].方向().翻转()
|
||||
self.基础序列.read().unwrap()[0].方向().翻转()
|
||||
}
|
||||
|
||||
pub fn 高(&self) -> f64 {
|
||||
self.基础序列[..3]
|
||||
self.基础序列.read().unwrap()[..3]
|
||||
.iter()
|
||||
.map(|x| x.高())
|
||||
.min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
|
||||
@@ -83,7 +98,7 @@ impl 中枢 {
|
||||
}
|
||||
|
||||
pub fn 低(&self) -> f64 {
|
||||
self.基础序列[..3]
|
||||
self.基础序列.read().unwrap()[..3]
|
||||
.iter()
|
||||
.map(|x| x.低())
|
||||
.max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
|
||||
@@ -92,6 +107,8 @@ impl 中枢 {
|
||||
|
||||
pub fn 高高(&self) -> f64 {
|
||||
self.基础序列
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|x| x.高())
|
||||
.max_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
|
||||
@@ -100,50 +117,57 @@ impl 中枢 {
|
||||
|
||||
pub fn 低低(&self) -> f64 {
|
||||
self.基础序列
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|x| x.低())
|
||||
.min_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal))
|
||||
.unwrap_or(0.0)
|
||||
}
|
||||
|
||||
pub fn 文(&self) -> Rc<分型> {
|
||||
Rc::clone(&self.基础序列[0].文)
|
||||
pub fn 文(&self) -> Arc<分型> {
|
||||
Arc::clone(&self.基础序列.read().unwrap()[0].文)
|
||||
}
|
||||
|
||||
pub fn 武(&self) -> Rc<分型> {
|
||||
Rc::clone(&self.基础序列[self.基础序列.len() - 1].武)
|
||||
pub fn 武(&self) -> Arc<分型> {
|
||||
Arc::clone(
|
||||
&*self.基础序列.read().unwrap()[self.基础序列.read().unwrap().len() - 1]
|
||||
.武
|
||||
.read()
|
||||
.unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn 设置第三买卖线(&mut self, 线: Rc<虚线>) {
|
||||
self.第三买卖线 = Some(线);
|
||||
pub fn 设置第三买卖线(&self, 线: Arc<虚线>) {
|
||||
*self.第三买卖线.write().unwrap() = Some(线);
|
||||
}
|
||||
|
||||
/// 获取序列 — 基础序列 + 第三买卖线(若有)
|
||||
pub fn 获取序列(&self) -> Vec<Rc<虚线>> {
|
||||
let mut 序列: Vec<Rc<虚线>> = self.基础序列.clone();
|
||||
if let Some(ref 三买) = self.第三买卖线 {
|
||||
序列.push(Rc::clone(三买));
|
||||
pub fn 获取序列(&self) -> Vec<Arc<虚线>> {
|
||||
let mut 序列: Vec<Arc<虚线>> = self.基础序列.read().unwrap().clone();
|
||||
if let Some(ref 三买) = *self.第三买卖线.read().unwrap() {
|
||||
序列.push(Arc::clone(三买));
|
||||
}
|
||||
序列
|
||||
}
|
||||
|
||||
pub fn 获取数据文本(&self) -> String {
|
||||
let 第三买卖线_str = match &self.第三买卖线 {
|
||||
let 第三买卖线_str = match &*self.第三买卖线.read().unwrap() {
|
||||
Some(x) => format!("{}", x),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
let 本级_第三买卖线_str = match &self.本级_第三买卖线 {
|
||||
let 本级_第三买卖线_str = match &*self.本级_第三买卖线.read().unwrap() {
|
||||
Some(x) => format!("{}", x),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
format!(
|
||||
"{}, {}, {}, 文:({},{}), 武:({},{}), {}, {}",
|
||||
self.标识,
|
||||
self.序号,
|
||||
self.级别,
|
||||
self.文().时间戳,
|
||||
self.标识.read().unwrap(),
|
||||
self.序号.load(Ordering::Relaxed),
|
||||
self.级别.load(Ordering::Relaxed),
|
||||
self.文().时间戳(),
|
||||
crate::utils::format_f64_g(self.文().分型特征值),
|
||||
self.武().时间戳,
|
||||
self.武().时间戳(),
|
||||
crate::utils::format_f64_g(self.武().分型特征值),
|
||||
第三买卖线_str,
|
||||
本级_第三买卖线_str,
|
||||
@@ -151,12 +175,12 @@ impl 中枢 {
|
||||
}
|
||||
|
||||
/// 校验中枢合法性
|
||||
pub fn 校验合法性(&mut self, 序列: &[Rc<虚线>]) -> bool {
|
||||
let mut 有效序列 = self.基础序列.clone();
|
||||
let mut 无效序列: Vec<Rc<虚线>> = Vec::new();
|
||||
for 元素 in &self.基础序列 {
|
||||
if !序列.iter().any(|x| Rc::as_ptr(x) == Rc::as_ptr(元素)) {
|
||||
无效序列.push(Rc::clone(元素));
|
||||
pub fn 校验合法性(&self, 序列: &[Arc<虚线>]) -> bool {
|
||||
let mut 有效序列 = self.基础序列.read().unwrap().clone();
|
||||
let mut 无效序列: Vec<Arc<虚线>> = Vec::new();
|
||||
for 元素 in self.基础序列.read().unwrap().iter() {
|
||||
if !序列.iter().any(|x| Arc::as_ptr(x) == Arc::as_ptr(元素)) {
|
||||
无效序列.push(Arc::clone(元素));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,50 +188,52 @@ impl 中枢 {
|
||||
let 无效 = &无效序列[0];
|
||||
if let Some(pos) = self
|
||||
.基础序列
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.position(|x| Rc::as_ptr(x) == Rc::as_ptr(无效))
|
||||
.position(|x| Arc::as_ptr(x) == Arc::as_ptr(无效))
|
||||
{
|
||||
有效序列 = self.基础序列[..pos].to_vec();
|
||||
有效序列 = self.基础序列.read().unwrap()[..pos].to_vec();
|
||||
}
|
||||
}
|
||||
|
||||
if 有效序列.len() < 3 {
|
||||
self.第三买卖线 = None;
|
||||
self.本级_第三买卖线 = None;
|
||||
*self.第三买卖线.write().unwrap() = None;
|
||||
*self.本级_第三买卖线.write().unwrap() = None;
|
||||
return false;
|
||||
}
|
||||
|
||||
self.基础序列 = 有效序列;
|
||||
*self.基础序列.write().unwrap() = 有效序列;
|
||||
|
||||
let 中枢高 = self.高();
|
||||
let 中枢低 = self.低();
|
||||
有效序列 = Vec::new();
|
||||
for 元素 in &self.基础序列 {
|
||||
for 元素 in self.基础序列.read().unwrap().iter() {
|
||||
if crate::types::相对方向::分析(中枢高, 中枢低, 元素.高(), 元素.低()).是否缺口()
|
||||
{
|
||||
break;
|
||||
}
|
||||
有效序列.push(Rc::clone(元素));
|
||||
有效序列.push(Arc::clone(元素));
|
||||
}
|
||||
self.基础序列 = 有效序列;
|
||||
*self.基础序列.write().unwrap() = 有效序列;
|
||||
|
||||
if self.基础序列.len() < 3 {
|
||||
if self.基础序列.read().unwrap().len() < 3 {
|
||||
return false;
|
||||
}
|
||||
|
||||
for i in 1..self.基础序列.len() {
|
||||
let 前 = &self.基础序列[i - 1];
|
||||
let 后 = &self.基础序列[i];
|
||||
for i in 1..self.基础序列.read().unwrap().len() {
|
||||
let 前 = &self.基础序列.read().unwrap()[i - 1];
|
||||
let 后 = &self.基础序列.read().unwrap()[i];
|
||||
if !前.之后是(后) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if !crate::types::相对方向::分析(
|
||||
self.基础序列[0].高(),
|
||||
self.基础序列[0].低(),
|
||||
self.基础序列[2].高(),
|
||||
self.基础序列[2].低(),
|
||||
self.基础序列.read().unwrap()[0].高(),
|
||||
self.基础序列.read().unwrap()[0].低(),
|
||||
self.基础序列.read().unwrap()[2].高(),
|
||||
self.基础序列.read().unwrap()[2].低(),
|
||||
)
|
||||
.是否缺口()
|
||||
{
|
||||
@@ -218,10 +244,11 @@ impl 中枢 {
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref 三买线) = self.第三买卖线.clone() {
|
||||
if 序列.iter().any(|x| Rc::as_ptr(x) == Rc::as_ptr(三买线)) {
|
||||
if !self.基础序列.last().unwrap().之后是(三买线) {
|
||||
self.第三买卖线 = None;
|
||||
let 三买线_opt = self.第三买卖线.read().unwrap().clone();
|
||||
if let Some(ref 三买线) = 三买线_opt {
|
||||
if 序列.iter().any(|x| Arc::as_ptr(x) == Arc::as_ptr(三买线)) {
|
||||
if !self.基础序列.read().unwrap().last().unwrap().之后是(三买线) {
|
||||
*self.第三买卖线.write().unwrap() = None;
|
||||
} else if !crate::types::相对方向::分析(
|
||||
self.高(),
|
||||
self.低(),
|
||||
@@ -230,11 +257,11 @@ impl 中枢 {
|
||||
)
|
||||
.是否缺口()
|
||||
{
|
||||
self.添加虚线(Rc::clone(三买线));
|
||||
self.第三买卖线 = None;
|
||||
self.添加虚线(Arc::clone(三买线));
|
||||
*self.第三买卖线.write().unwrap() = None;
|
||||
}
|
||||
} else {
|
||||
self.第三买卖线 = None;
|
||||
*self.第三买卖线.write().unwrap() = None;
|
||||
}
|
||||
}
|
||||
true
|
||||
@@ -243,16 +270,18 @@ impl 中枢 {
|
||||
/// 完整性 — 详见教你炒股票43:有关背驰的补习课
|
||||
/// 不完整时下一个中枢大概率会与当前中枢发生扩展
|
||||
pub fn 完整性(&self, 虚实: &str) -> bool {
|
||||
if self.基础序列[0].标识 == "笔" {
|
||||
return self.第三买卖线.is_some();
|
||||
if *self.基础序列.read().unwrap()[0].标识.read().unwrap() == "笔" {
|
||||
return self.第三买卖线.read().unwrap().is_some();
|
||||
}
|
||||
|
||||
let 线段内部中枢 = if 虚实 == "合" {
|
||||
&self.基础序列.last().unwrap().合_中枢序列
|
||||
let 基础序列_ref = self.基础序列.read().unwrap();
|
||||
let 最后段 = 基础序列_ref.last().unwrap();
|
||||
let 内部中枢_vec = if 虚实 == "合" {
|
||||
最后段.合_中枢序列.read().unwrap()
|
||||
} else {
|
||||
&self.基础序列.last().unwrap().实_中枢序列
|
||||
最后段.实_中枢序列.read().unwrap()
|
||||
};
|
||||
for 内部中枢 in 线段内部中枢 {
|
||||
for 内部中枢 in 内部中枢_vec.iter() {
|
||||
if crate::types::相对方向::分析(
|
||||
self.高(),
|
||||
self.低(),
|
||||
@@ -269,16 +298,19 @@ impl 中枢 {
|
||||
|
||||
/// 获取扩展中枢 — 当基础序列 >= 9 时生成扩展中枢
|
||||
pub fn 获取扩展中枢(
|
||||
&self, 扩展中枢: &mut Vec<Rc<中枢>>, 配置: &crate::config::缠论配置
|
||||
&self,
|
||||
扩展中枢: &mut Vec<Arc<中枢>>,
|
||||
配置: &crate::config::缠论配置,
|
||||
) {
|
||||
if self.基础序列.len() >= 9 {
|
||||
let mut 扩展线段: Vec<Rc<虚线>> = Vec::new();
|
||||
crate::algorithm::segment::线段::扩展分析(&self.基础序列, &mut 扩展线段, 配置);
|
||||
if self.基础序列.read().unwrap().len() >= 9 {
|
||||
let mut 扩展线段: Vec<Arc<虚线>> = Vec::new();
|
||||
let 基础序列_ref = self.基础序列.read().unwrap();
|
||||
crate::algorithm::segment::线段::扩展分析(&基础序列_ref, &mut 扩展线段, 配置);
|
||||
中枢::分析(
|
||||
&扩展线段,
|
||||
扩展中枢,
|
||||
false,
|
||||
&format!("{}_扩展中枢_", self.标识),
|
||||
&format!("{}_扩展中枢_", self.标识.read().unwrap()),
|
||||
0,
|
||||
);
|
||||
}
|
||||
@@ -287,9 +319,15 @@ impl 中枢 {
|
||||
/// 当前状态 — 详见教你炒股票49:利润率最大的操作模式
|
||||
/// 返回当前中枢最后一段所处的位置关系:中枢之中/中枢之上/中枢之下
|
||||
pub fn 当前状态(&self) -> &str {
|
||||
let 最后 = self.基础序列.last().unwrap();
|
||||
let 基础序列_ref = self.基础序列.read().unwrap();
|
||||
let 最后 = Arc::clone(基础序列_ref.last().unwrap());
|
||||
let 尾部 = 最后.获取_武();
|
||||
let 关系 = crate::types::相对方向::分析(self.高(), self.低(), 尾部.中.高, 尾部.中.低);
|
||||
let 关系 = crate::types::相对方向::分析(
|
||||
self.高(),
|
||||
self.低(),
|
||||
尾部.中.高.get(),
|
||||
尾部.中.低.get(),
|
||||
);
|
||||
if 关系 == crate::types::相对方向::向上缺口 {
|
||||
"中枢之上"
|
||||
} else if 关系 == crate::types::相对方向::向下缺口 {
|
||||
@@ -319,11 +357,11 @@ impl 中枢 {
|
||||
|
||||
/// 创建中枢
|
||||
pub fn 创建(
|
||||
左: Rc<虚线>, 中: Rc<虚线>, 右: Rc<虚线>, 级别: i64, 标识: &str
|
||||
左: Arc<虚线>, 中: Arc<虚线>, 右: Arc<虚线>, 级别: i64, 标识: &str
|
||||
) -> Self {
|
||||
Self::new(
|
||||
0,
|
||||
format!("{}中枢<{}>", 标识, 中.标识),
|
||||
format!("{}中枢<{}>", 标识, 中.标识.read().unwrap()),
|
||||
级别,
|
||||
vec![左, 中, 右],
|
||||
)
|
||||
@@ -331,17 +369,17 @@ impl 中枢 {
|
||||
|
||||
/// 从序列中获取中枢
|
||||
pub fn 从序列中获取中枢(
|
||||
虚线序列: &[Rc<虚线>],
|
||||
虚线序列: &[Arc<虚线>],
|
||||
起始方向: 相对方向,
|
||||
标识: &str,
|
||||
) -> Option<Rc<中枢>> {
|
||||
) -> Option<Arc<中枢>> {
|
||||
for i in 2..虚线序列.len() {
|
||||
let 左 = &虚线序列[i - 2];
|
||||
let 中 = &虚线序列[i - 1];
|
||||
let 右 = &虚线序列[i];
|
||||
if Self::基础检查(左, 中, 右) && 左.方向() == 起始方向 {
|
||||
let 中枢 = Self::创建(Rc::clone(左), Rc::clone(中), Rc::clone(右), 0, 标识);
|
||||
return Some(Rc::new(中枢));
|
||||
let 中枢 = Self::创建(Arc::clone(左), Arc::clone(中), Arc::clone(右), 0, 标识);
|
||||
return Some(Arc::new(中枢));
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -349,19 +387,22 @@ impl 中枢 {
|
||||
|
||||
/// 向中枢序列尾部添加
|
||||
pub fn 向中枢序列尾部添加(
|
||||
中枢序列: &mut Vec<Rc<中枢>>, mut 待添加中枢: Rc<中枢>
|
||||
中枢序列: &mut Vec<Arc<中枢>>, 待添加中枢: Arc<中枢>
|
||||
) {
|
||||
if let Some(前一个) = 中枢序列.last() {
|
||||
let 新 = Rc::make_mut(&mut 待添加中枢);
|
||||
新.序号 = 前一个.序号 + 1;
|
||||
待添加中枢
|
||||
.序号
|
||||
.store(前一个.序号.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
// Python: assert seq[-1].获取序列()[-1].序号 <= new.获取序列()[-1].序号
|
||||
let 前_seq = 前一个.获取序列();
|
||||
let new_seq = 新.获取序列();
|
||||
let new_seq = 待添加中枢.获取序列();
|
||||
if let (Some(前_last), Some(new_last)) = (前_seq.last(), new_seq.last()) {
|
||||
if 前_last.序号 > new_last.序号 {
|
||||
if 前_last.序号.load(Ordering::Relaxed) > new_last.序号.load(Ordering::Relaxed)
|
||||
{
|
||||
panic!(
|
||||
"向中枢序列尾部添加 序号错误 前last={} > new_last={}",
|
||||
前_last.序号, new_last.序号
|
||||
前_last.序号.load(Ordering::Relaxed),
|
||||
new_last.序号.load(Ordering::Relaxed)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -371,10 +412,10 @@ impl 中枢 {
|
||||
|
||||
/// 从中枢序列尾部弹出
|
||||
pub fn 从中枢序列尾部弹出(
|
||||
中枢序列: &mut Vec<Rc<中枢>>,
|
||||
待弹出: &Rc<中枢>,
|
||||
) -> Option<Rc<中枢>> {
|
||||
if 中枢序列.last().map(|x| Rc::as_ptr(x)) == Some(Rc::as_ptr(待弹出)) {
|
||||
中枢序列: &mut Vec<Arc<中枢>>,
|
||||
待弹出: &Arc<中枢>,
|
||||
) -> Option<Arc<中枢>> {
|
||||
if 中枢序列.last().map(Arc::as_ptr) == Some(Arc::as_ptr(待弹出)) {
|
||||
中枢序列.pop()
|
||||
} else {
|
||||
None
|
||||
@@ -385,11 +426,11 @@ impl 中枢 {
|
||||
///
|
||||
/// 每收到新的虚线序列数据后调用,更新中枢序列
|
||||
pub fn 分析(
|
||||
虚线序列: &[Rc<虚线>],
|
||||
中枢序列: &mut Vec<Rc<中枢>>,
|
||||
虚线序列: &[Arc<虚线>],
|
||||
中枢序列: &mut Vec<Arc<中枢>>,
|
||||
跳过首部: bool,
|
||||
标识: &str,
|
||||
层级: i64,
|
||||
_层级: i64,
|
||||
) {
|
||||
if 虚线序列.len() < 3 {
|
||||
return;
|
||||
@@ -406,9 +447,9 @@ impl 中枢 {
|
||||
// Python: 序号 = 虚线序列.index(左)
|
||||
let 序号 = 虚线序列
|
||||
.iter()
|
||||
.position(|x| Rc::as_ptr(x) == Rc::as_ptr(左))
|
||||
.position(|x| Arc::as_ptr(x) == Arc::as_ptr(左))
|
||||
.unwrap_or(i - 1);
|
||||
if 跳过首部 && (左.序号 == 0 || 序号 == 0) {
|
||||
if 跳过首部 && (左.序号.load(Ordering::Relaxed) == 0 || 序号 == 0) {
|
||||
continue;
|
||||
}
|
||||
if 序号 >= 2 {
|
||||
@@ -422,16 +463,16 @@ impl 中枢 {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let 新中枢 = Rc::new(Self::创建(
|
||||
Rc::clone(左),
|
||||
Rc::clone(中),
|
||||
Rc::clone(右),
|
||||
中.级别,
|
||||
let 新中枢 = Arc::new(Self::创建(
|
||||
Arc::clone(左),
|
||||
Arc::clone(中),
|
||||
Arc::clone(右),
|
||||
中.级别.load(Ordering::Relaxed),
|
||||
标识,
|
||||
));
|
||||
Self::向中枢序列尾部添加(中枢序列, 新中枢);
|
||||
// Python: return 中枢递归分析(虚线序列, 中枢序列, ...)
|
||||
Self::分析(虚线序列, 中枢序列, 跳过首部, 标识, 层级);
|
||||
Self::分析(虚线序列, 中枢序列, 跳过首部, 标识, _层级);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -441,25 +482,22 @@ impl 中枢 {
|
||||
// 增量更新
|
||||
let mut 当前中枢_idx = 中枢序列.len() - 1;
|
||||
|
||||
// Validate in-place via Rc::make_mut — avoids full中枢 struct clone
|
||||
let needs_pop = {
|
||||
let cur = Rc::make_mut(&mut 中枢序列[当前中枢_idx]);
|
||||
!cur.校验合法性(虚线序列)
|
||||
};
|
||||
// Validate via shared reference (中枢 uses RwLock internally)
|
||||
let needs_pop = !中枢序列[当前中枢_idx].校验合法性(虚线序列);
|
||||
if needs_pop {
|
||||
let 当前中枢 = Rc::clone(&中枢序列[当前中枢_idx]);
|
||||
let 当前中枢 = Arc::clone(&中枢序列[当前中枢_idx]);
|
||||
Self::从中枢序列尾部弹出(中枢序列, &当前中枢);
|
||||
Self::分析(虚线序列, 中枢序列, 跳过首部, 标识, 层级);
|
||||
Self::分析(虚线序列, 中枢序列, 跳过首部, 标识, _层级);
|
||||
return;
|
||||
}
|
||||
|
||||
// 找到当前中枢最后一个元素在虚线序列中的位置
|
||||
let 起始索引 = {
|
||||
let cur = &中枢序列[当前中枢_idx];
|
||||
let 最后元素 = &cur.基础序列[cur.基础序列.len() - 1];
|
||||
let 最后元素 = &cur.基础序列.read().unwrap()[cur.基础序列.read().unwrap().len() - 1];
|
||||
match 虚线序列
|
||||
.iter()
|
||||
.position(|x| Rc::as_ptr(x) == Rc::as_ptr(最后元素))
|
||||
.position(|x| Arc::as_ptr(x) == Arc::as_ptr(最后元素))
|
||||
{
|
||||
Some(idx) => idx + 1,
|
||||
None => return,
|
||||
@@ -468,10 +506,10 @@ impl 中枢 {
|
||||
|
||||
let mut 中枢高 = 中枢序列[当前中枢_idx].高();
|
||||
let mut 中枢低 = 中枢序列[当前中枢_idx].低();
|
||||
let mut 候选序列: Vec<Rc<虚线>> = Vec::new();
|
||||
let mut 候选序列: Vec<Arc<虚线>> = Vec::new();
|
||||
|
||||
for i in 起始索引..虚线序列.len() {
|
||||
let 当前虚线 = Rc::clone(&虚线序列[i]);
|
||||
for 当前虚线_ref in &虚线序列[起始索引..] {
|
||||
let 当前虚线 = Arc::clone(当前虚线_ref);
|
||||
|
||||
// 检查是否超出中枢范围(缺口)
|
||||
if crate::types::相对方向::分析(中枢高, 中枢低, 当前虚线.高(), 当前虚线.低()).是否缺口()
|
||||
@@ -481,16 +519,20 @@ impl 中枢 {
|
||||
// Python: if 当前中枢.基础序列[-1].之后是(当前虚线):
|
||||
let needs_三买 = {
|
||||
let cur = &中枢序列[当前中枢_idx];
|
||||
cur.基础序列.last().unwrap().之后是(&当前虚线)
|
||||
cur.基础序列
|
||||
.read()
|
||||
.unwrap()
|
||||
.last()
|
||||
.unwrap()
|
||||
.之后是(&当前虚线)
|
||||
};
|
||||
if needs_三买 {
|
||||
Rc::make_mut(&mut 中枢序列[当前中枢_idx])
|
||||
.设置第三买卖线(当前虚线.clone());
|
||||
中枢序列[当前中枢_idx].设置第三买卖线(当前虚线.clone());
|
||||
}
|
||||
} else {
|
||||
if 候选序列.is_empty() {
|
||||
// 仍在范围内:延伸中枢
|
||||
Rc::make_mut(&mut 中枢序列[当前中枢_idx]).添加虚线(当前虚线);
|
||||
中枢序列[当前中枢_idx].添加虚线(当前虚线);
|
||||
} else {
|
||||
候选序列.push(当前虚线);
|
||||
}
|
||||
@@ -500,6 +542,8 @@ impl 中枢 {
|
||||
while 候选序列.len() >= 3 {
|
||||
let 起始方向 = 中枢序列[当前中枢_idx]
|
||||
.基础序列
|
||||
.read()
|
||||
.unwrap()
|
||||
.last()
|
||||
.unwrap()
|
||||
.方向()
|
||||
@@ -526,6 +570,8 @@ impl std::fmt::Display for 中枢 {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
let 序列_str = self
|
||||
.基础序列
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|d| format!("{}", d))
|
||||
.collect::<Vec<_>>()
|
||||
@@ -533,13 +579,319 @@ impl std::fmt::Display for 中枢 {
|
||||
write!(
|
||||
f,
|
||||
"{}({}, {}, 元素数量: {}, [{}], {} ===>>> {})",
|
||||
self.标识,
|
||||
self.标识.read().unwrap(),
|
||||
crate::utils::format_f64_g(self.高()),
|
||||
crate::utils::format_f64_g(self.低()),
|
||||
self.基础序列.len(),
|
||||
self.基础序列.read().unwrap().len(),
|
||||
序列_str,
|
||||
self.文(),
|
||||
self.武(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::kline::bar::K线;
|
||||
use crate::kline::chan_kline::缠论K线;
|
||||
use crate::structure::fractal_obj::分型;
|
||||
use crate::types::分型结构;
|
||||
|
||||
fn 辅助_创建K线(时间戳: i64, 高: f64, 低: f64, 开: f64, 收: f64) -> K线 {
|
||||
K线 {
|
||||
时间戳,
|
||||
高,
|
||||
低,
|
||||
开盘价: 开,
|
||||
收盘价: 收,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn 辅助_创建缠K(
|
||||
时间戳: i64,
|
||||
高: f64,
|
||||
低: f64,
|
||||
方向: 相对方向,
|
||||
结构: Option<分型结构>,
|
||||
序号: i64,
|
||||
) -> Arc<缠论K线> {
|
||||
let 普K = Arc::new(辅助_创建K线(时间戳, 高, 低, 低, 高));
|
||||
Arc::new(缠论K线::创建缠K(
|
||||
时间戳, 高, 低, 方向, 结构, 序号, 普K, None,
|
||||
))
|
||||
}
|
||||
|
||||
fn 辅助_创建顶分型(时间戳: i64, 高: f64, 低: f64, 序号: i64) -> Arc<分型> {
|
||||
let 左 = 辅助_创建缠K(
|
||||
时间戳 - 2,
|
||||
高 - 2.0,
|
||||
低 - 2.0,
|
||||
相对方向::向上,
|
||||
Some(分型结构::上),
|
||||
序号 - 2,
|
||||
);
|
||||
let 中 = 辅助_创建缠K(时间戳, 高, 低, 相对方向::向上, Some(分型结构::顶), 序号);
|
||||
let 右 = 辅助_创建缠K(
|
||||
时间戳 + 2,
|
||||
高 - 1.0,
|
||||
低 - 1.0,
|
||||
相对方向::向下,
|
||||
Some(分型结构::下),
|
||||
序号 + 2,
|
||||
);
|
||||
Arc::new(分型::new(Some(左), 中, Some(右)))
|
||||
}
|
||||
|
||||
fn 辅助_创建底分型(时间戳: i64, 高: f64, 低: f64, 序号: i64) -> Arc<分型> {
|
||||
let 左 = 辅助_创建缠K(
|
||||
时间戳 - 2,
|
||||
高 + 2.0,
|
||||
低 + 2.0,
|
||||
相对方向::向下,
|
||||
Some(分型结构::下),
|
||||
序号 - 2,
|
||||
);
|
||||
let 中 = 缠论K线::创建缠K(
|
||||
时间戳,
|
||||
高,
|
||||
低,
|
||||
相对方向::向下,
|
||||
Some(分型结构::底),
|
||||
序号,
|
||||
Arc::new(辅助_创建K线(时间戳, 高, 低, 低, 高)),
|
||||
None,
|
||||
);
|
||||
中.分型特征值.set(低);
|
||||
let 中 = Arc::new(中);
|
||||
let 右 = 辅助_创建缠K(
|
||||
时间戳 + 2,
|
||||
高 + 1.0,
|
||||
低 + 1.0,
|
||||
相对方向::向上,
|
||||
Some(分型结构::上),
|
||||
序号 + 2,
|
||||
);
|
||||
Arc::new(分型::new(Some(左), 中, Some(右)))
|
||||
}
|
||||
|
||||
fn 辅助_创建笔(
|
||||
文时间戳: i64,
|
||||
文高: f64,
|
||||
文低: f64,
|
||||
武时间戳: i64,
|
||||
武高: f64,
|
||||
武低: f64,
|
||||
) -> Arc<虚线> {
|
||||
let 顶 = 辅助_创建顶分型(文时间戳, 文高, 文低, 1);
|
||||
let 底 = 辅助_创建底分型(武时间戳, 武高, 武低, 2);
|
||||
Arc::new(虚线::创建笔(顶, 底, true))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 中枢 Cell/RefCell 字段读写
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_中枢创建后字段初始值正确() {
|
||||
let 笔1 = 辅助_创建笔(100, 50.0, 40.0, 200, 30.0, 20.0);
|
||||
let 笔2 = 辅助_创建笔(200, 30.0, 20.0, 300, 55.0, 45.0);
|
||||
let 笔3 = 辅助_创建笔(300, 55.0, 45.0, 400, 25.0, 15.0);
|
||||
|
||||
let 中枢 = 中枢::new(
|
||||
1,
|
||||
"测试中枢".into(),
|
||||
1,
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2), Arc::clone(&笔3)],
|
||||
);
|
||||
|
||||
assert_eq!(中枢.序号.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(*中枢.标识.read().unwrap(), "测试中枢");
|
||||
assert_eq!(中枢.级别.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(中枢.基础序列.read().unwrap().len(), 3);
|
||||
assert!(中枢.第三买卖线.read().unwrap().is_none());
|
||||
assert!(中枢.本级_第三买卖线.read().unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_中枢CellRefCell字段读写() {
|
||||
let 笔1 = 辅助_创建笔(100, 50.0, 40.0, 200, 30.0, 20.0);
|
||||
let 笔2 = 辅助_创建笔(200, 30.0, 20.0, 300, 55.0, 45.0);
|
||||
let 笔3 = 辅助_创建笔(300, 55.0, 45.0, 400, 25.0, 15.0);
|
||||
|
||||
let 中枢 = 中枢::new(
|
||||
0,
|
||||
"测试".into(),
|
||||
1,
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2), Arc::clone(&笔3)],
|
||||
);
|
||||
|
||||
// Cell 序号读写
|
||||
中枢.序号.store(99, Ordering::Relaxed);
|
||||
assert_eq!(中枢.序号.load(Ordering::Relaxed), 99);
|
||||
|
||||
// RefCell 第三买卖线读写
|
||||
中枢.设置第三买卖线(Arc::clone(&笔1));
|
||||
assert!(中枢.第三买卖线.read().unwrap().is_some());
|
||||
assert_eq!(
|
||||
Arc::as_ptr(中枢.第三买卖线.read().unwrap().as_ref().unwrap()),
|
||||
Arc::as_ptr(&笔1)
|
||||
);
|
||||
|
||||
// 本级_第三买卖线
|
||||
assert!(中枢.本级_第三买卖线.read().unwrap().is_none());
|
||||
*中枢.本级_第三买卖线.write().unwrap() = Some(Arc::clone(&笔3));
|
||||
assert!(中枢.本级_第三买卖线.read().unwrap().is_some());
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 中枢 添加虚线
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_中枢添加虚线后基础序列扩展() {
|
||||
let 笔1 = 辅助_创建笔(100, 50.0, 40.0, 200, 30.0, 20.0);
|
||||
let 笔2 = 辅助_创建笔(200, 30.0, 20.0, 300, 55.0, 45.0);
|
||||
let 笔3 = 辅助_创建笔(300, 55.0, 45.0, 400, 25.0, 15.0);
|
||||
let 笔4 = 辅助_创建笔(400, 25.0, 15.0, 500, 60.0, 50.0);
|
||||
|
||||
let 中枢 = 中枢::new(
|
||||
0,
|
||||
"测试".into(),
|
||||
1,
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2), Arc::clone(&笔3)],
|
||||
);
|
||||
assert_eq!(中枢.基础序列.read().unwrap().len(), 3);
|
||||
|
||||
中枢.添加虚线(Arc::clone(&笔4));
|
||||
assert_eq!(中枢.基础序列.read().unwrap().len(), 4);
|
||||
assert_eq!(
|
||||
Arc::as_ptr(&中枢.基础序列.read().unwrap()[3]),
|
||||
Arc::as_ptr(&笔4)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_中枢添加虚线后清除第三买卖线() {
|
||||
let 笔1 = 辅助_创建笔(100, 50.0, 40.0, 200, 30.0, 20.0);
|
||||
let 笔2 = 辅助_创建笔(200, 30.0, 20.0, 300, 55.0, 45.0);
|
||||
let 笔3 = 辅助_创建笔(300, 55.0, 45.0, 400, 25.0, 15.0);
|
||||
let 笔4 = 辅助_创建笔(400, 25.0, 15.0, 500, 60.0, 50.0);
|
||||
|
||||
let 中枢 = 中枢::new(
|
||||
0,
|
||||
"测试".into(),
|
||||
1,
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2), Arc::clone(&笔3)],
|
||||
);
|
||||
中枢.设置第三买卖线(Arc::clone(&笔1));
|
||||
*中枢.本级_第三买卖线.write().unwrap() = Some(Arc::clone(&笔2));
|
||||
assert!(中枢.第三买卖线.read().unwrap().is_some());
|
||||
assert!(中枢.本级_第三买卖线.read().unwrap().is_some());
|
||||
|
||||
中枢.添加虚线(Arc::clone(&笔4));
|
||||
// 添加虚线后第三买卖线被清除
|
||||
assert!(中枢.第三买卖线.read().unwrap().is_none());
|
||||
assert!(中枢.本级_第三买卖线.read().unwrap().is_none());
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Clone 后 Rc 指针身份一致
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_中枢Clone后基础序列Rc指针一致() {
|
||||
let 笔1 = 辅助_创建笔(100, 50.0, 40.0, 200, 30.0, 20.0);
|
||||
let 笔2 = 辅助_创建笔(200, 30.0, 20.0, 300, 55.0, 45.0);
|
||||
let 笔3 = 辅助_创建笔(300, 55.0, 45.0, 400, 25.0, 15.0);
|
||||
|
||||
let 中枢 = 中枢::new(
|
||||
0,
|
||||
"测试".into(),
|
||||
1,
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2), Arc::clone(&笔3)],
|
||||
);
|
||||
中枢.设置第三买卖线(Arc::clone(&笔1));
|
||||
|
||||
let 克隆 = 中枢.clone();
|
||||
|
||||
// 基础序列中的 Rc 指针应一致
|
||||
for i in 0..3 {
|
||||
assert_eq!(
|
||||
Arc::as_ptr(&中枢.基础序列.read().unwrap()[i]),
|
||||
Arc::as_ptr(&克隆.基础序列.read().unwrap()[i])
|
||||
);
|
||||
}
|
||||
|
||||
// 第三买卖线 Rc 指针应一致
|
||||
assert_eq!(
|
||||
Arc::as_ptr(中枢.第三买卖线.read().unwrap().as_ref().unwrap()),
|
||||
Arc::as_ptr(克隆.第三买卖线.read().unwrap().as_ref().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 中枢 高/低/高高/低低计算
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_中枢高低计算正确() {
|
||||
// 笔1: 顶(高=50,低=45) →底(高=40,低=30) = 向下笔, 高=50, 低=30
|
||||
let 笔1 = 辅助_创建笔(100, 50.0, 45.0, 200, 40.0, 30.0);
|
||||
|
||||
// 笔2: 底(高=40,低=30) →顶(高=55,低=50) = 向上笔, 高=55, 低=30
|
||||
let 底2 = 辅助_创建底分型(200, 40.0, 30.0, 10);
|
||||
let 顶2 = 辅助_创建顶分型(300, 55.0, 50.0, 15);
|
||||
let 笔2 = Arc::new(虚线::创建笔(底2, 顶2, true));
|
||||
|
||||
// 笔3: 顶(高=55,低=50) →底(高=35,低=25) = 向下笔, 高=55, 低=25
|
||||
let 笔3 = 辅助_创建笔(300, 55.0, 50.0, 400, 35.0, 25.0);
|
||||
|
||||
let 中枢 = 中枢::new(
|
||||
0,
|
||||
"测试".into(),
|
||||
1,
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2), Arc::clone(&笔3)],
|
||||
);
|
||||
|
||||
// 高 = min(笔1高, 笔2高, 笔3高) = min(50, 55, 55) = 50
|
||||
assert!((中枢.高() - 50.0).abs() < 0.01, "中枢高={}", 中枢.高());
|
||||
// 低 = max(笔1低, 笔2低, 笔3低) = max(30, 30, 25) = 30
|
||||
assert!((中枢.低() - 30.0).abs() < 0.01, "中枢低={}", 中枢.低());
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 多 Rc 共享下修改可见性
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_多Rc共享中枢修改对所有引用可见() {
|
||||
let 笔1 = 辅助_创建笔(100, 50.0, 40.0, 200, 30.0, 20.0);
|
||||
let 笔2 = 辅助_创建笔(200, 30.0, 20.0, 300, 55.0, 45.0);
|
||||
let 笔3 = 辅助_创建笔(300, 55.0, 45.0, 400, 25.0, 15.0);
|
||||
let 笔4 = 辅助_创建笔(400, 25.0, 15.0, 500, 60.0, 50.0);
|
||||
|
||||
let 中枢1 = Arc::new(中枢::new(
|
||||
0,
|
||||
"测试".into(),
|
||||
1,
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2), Arc::clone(&笔3)],
|
||||
));
|
||||
let 中枢2 = Arc::clone(&中枢1);
|
||||
|
||||
// 通过 rc1 修改序号
|
||||
中枢1.序号.store(88, Ordering::Relaxed);
|
||||
assert_eq!(中枢2.序号.load(Ordering::Relaxed), 88);
|
||||
|
||||
// 通过 rc1 添加虚线
|
||||
中枢1.添加虚线(Arc::clone(&笔4));
|
||||
assert_eq!(中枢2.基础序列.read().unwrap().len(), 4);
|
||||
|
||||
// 验证共享的 Arc<虚线> 指针一致
|
||||
assert_eq!(
|
||||
Arc::as_ptr(&中枢1.基础序列.read().unwrap()[3]),
|
||||
Arc::as_ptr(&中枢2.基础序列.read().unwrap()[3])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+619
-424
File diff suppressed because it is too large
Load Diff
+89
-34
@@ -27,31 +27,35 @@ use crate::kline::chan_kline::缠论K线;
|
||||
use crate::structure::fractal_obj::分型;
|
||||
use crate::types::bsp_type::买卖点类型;
|
||||
use crate::types::分型结构;
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// 基础买卖点 — 买卖点的基础数据结构
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct 基础买卖点 {
|
||||
pub 备注: String,
|
||||
pub 类型: 买卖点类型,
|
||||
pub 买卖点分型: Rc<分型>,
|
||||
pub 买卖点K线: Rc<缠论K线>,
|
||||
pub 当前K线: Rc<K线>,
|
||||
pub 失效K线: Option<Rc<K线>>,
|
||||
pub 终结K线: Option<Rc<K线>>,
|
||||
pub 买卖点分型: Arc<分型>,
|
||||
pub 买卖点K线: Arc<缠论K线>,
|
||||
pub 当前K线: Arc<K线>,
|
||||
pub 失效K线: Option<Arc<K线>>,
|
||||
pub 终结K线: Option<Arc<K线>>,
|
||||
pub 破位值: f64,
|
||||
pub 结构: Option<分型结构>,
|
||||
/// 当前缠K的序号 — 与 Python 一致,偏移计算使用缠论K线序号而非标的K线序号
|
||||
pub 当前序号: i64,
|
||||
}
|
||||
|
||||
impl 基础买卖点 {
|
||||
pub fn new(
|
||||
类型: 买卖点类型,
|
||||
当前K线: Rc<K线>,
|
||||
买卖点分型: Rc<分型>,
|
||||
当前K线: Arc<K线>,
|
||||
买卖点分型: Arc<分型>,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
当前序号: i64,
|
||||
) -> Self {
|
||||
let 买卖点K线 = Rc::clone(&买卖点分型.中);
|
||||
let 买卖点K线 = Arc::clone(&买卖点分型.中);
|
||||
Self {
|
||||
备注,
|
||||
类型,
|
||||
@@ -62,18 +66,19 @@ impl 基础买卖点 {
|
||||
终结K线: None,
|
||||
破位值: 中枢破位值,
|
||||
结构: None,
|
||||
当前序号,
|
||||
}
|
||||
}
|
||||
|
||||
/// 偏移 — 当前K线与买卖点K线的序号差
|
||||
/// 偏移 — 当前缠K序号与买卖点K线序号的差(对齐 Python,使用缠论K线序号)
|
||||
pub fn 偏移(&self) -> i64 {
|
||||
self.当前K线.序号 - self.买卖点K线.序号
|
||||
self.当前序号 - self.买卖点K线.序号.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// 失效偏移
|
||||
pub fn 失效偏移(&self) -> i64 {
|
||||
match &self.失效K线 {
|
||||
Some(k) => k.序号 - self.买卖点K线.序号,
|
||||
Some(k) => k.序号 - self.买卖点K线.序号.load(Ordering::Relaxed),
|
||||
None => -1,
|
||||
}
|
||||
}
|
||||
@@ -112,63 +117,111 @@ pub struct 买卖点;
|
||||
|
||||
impl 买卖点 {
|
||||
pub fn 一卖点(
|
||||
买卖点分型: Rc<分型>,
|
||||
当前K线: Rc<K线>,
|
||||
买卖点分型: Arc<分型>,
|
||||
当前K线: Arc<K线>,
|
||||
_标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
当前序号: i64,
|
||||
) -> 基础买卖点 {
|
||||
基础买卖点::new(买卖点类型::一卖, 当前K线, 买卖点分型, 备注, 中枢破位值)
|
||||
基础买卖点::new(
|
||||
买卖点类型::一卖,
|
||||
当前K线,
|
||||
买卖点分型,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前序号,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn 一买点(
|
||||
买卖点分型: Rc<分型>,
|
||||
当前K线: Rc<K线>,
|
||||
买卖点分型: Arc<分型>,
|
||||
当前K线: Arc<K线>,
|
||||
_标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
当前序号: i64,
|
||||
) -> 基础买卖点 {
|
||||
基础买卖点::new(买卖点类型::一买, 当前K线, 买卖点分型, 备注, 中枢破位值)
|
||||
基础买卖点::new(
|
||||
买卖点类型::一买,
|
||||
当前K线,
|
||||
买卖点分型,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前序号,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn 二卖点(
|
||||
买卖点分型: Rc<分型>,
|
||||
当前K线: Rc<K线>,
|
||||
买卖点分型: Arc<分型>,
|
||||
当前K线: Arc<K线>,
|
||||
_标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
当前序号: i64,
|
||||
) -> 基础买卖点 {
|
||||
基础买卖点::new(买卖点类型::二卖, 当前K线, 买卖点分型, 备注, 中枢破位值)
|
||||
基础买卖点::new(
|
||||
买卖点类型::二卖,
|
||||
当前K线,
|
||||
买卖点分型,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前序号,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn 二买点(
|
||||
买卖点分型: Rc<分型>,
|
||||
当前K线: Rc<K线>,
|
||||
买卖点分型: Arc<分型>,
|
||||
当前K线: Arc<K线>,
|
||||
_标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
当前序号: i64,
|
||||
) -> 基础买卖点 {
|
||||
基础买卖点::new(买卖点类型::二买, 当前K线, 买卖点分型, 备注, 中枢破位值)
|
||||
基础买卖点::new(
|
||||
买卖点类型::二买,
|
||||
当前K线,
|
||||
买卖点分型,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前序号,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn 三卖点(
|
||||
买卖点分型: Rc<分型>,
|
||||
当前K线: Rc<K线>,
|
||||
买卖点分型: Arc<分型>,
|
||||
当前K线: Arc<K线>,
|
||||
_标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
当前序号: i64,
|
||||
) -> 基础买卖点 {
|
||||
基础买卖点::new(买卖点类型::三卖, 当前K线, 买卖点分型, 备注, 中枢破位值)
|
||||
基础买卖点::new(
|
||||
买卖点类型::三卖,
|
||||
当前K线,
|
||||
买卖点分型,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前序号,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn 三买点(
|
||||
买卖点分型: Rc<分型>,
|
||||
当前K线: Rc<K线>,
|
||||
买卖点分型: Arc<分型>,
|
||||
当前K线: Arc<K线>,
|
||||
_标识: &str,
|
||||
备注: String,
|
||||
中枢破位值: f64,
|
||||
当前序号: i64,
|
||||
) -> 基础买卖点 {
|
||||
基础买卖点::new(买卖点类型::三买, 当前K线, 买卖点分型, 备注, 中枢破位值)
|
||||
基础买卖点::new(
|
||||
买卖点类型::三买,
|
||||
当前K线,
|
||||
买卖点分型,
|
||||
备注,
|
||||
中枢破位值,
|
||||
当前序号,
|
||||
)
|
||||
}
|
||||
|
||||
/// 生成买卖点 — 根据参数自动选择类型
|
||||
@@ -176,8 +229,8 @@ impl 买卖点 {
|
||||
特征: &str,
|
||||
序号: &str,
|
||||
级别: &str,
|
||||
买卖点分型: Rc<分型>,
|
||||
当前缠K: Rc<缠论K线>,
|
||||
买卖点分型: Arc<分型>,
|
||||
当前缠K: Arc<缠论K线>,
|
||||
) -> 基础买卖点 {
|
||||
let 买卖 = if matches!(买卖点分型.结构, 分型结构::底 | 分型结构::下) {
|
||||
"买"
|
||||
@@ -188,7 +241,9 @@ impl 买卖点 {
|
||||
let 破位值 = 买卖点分型.分型特征值;
|
||||
|
||||
// 当前K线 — 从缠K获取其标的K线
|
||||
let 当前K线 = Rc::clone(&当前缠K.标的K线);
|
||||
let 当前K线 = Arc::clone(&*当前缠K.标的K线.read().unwrap());
|
||||
// 当前序号 — 使用缠论K线序号(对齐 Python 偏移计算)
|
||||
let 当前序号 = 当前缠K.序号.load(Ordering::Relaxed);
|
||||
|
||||
let 类型 = match (序号, 买卖) {
|
||||
("一", "买") => 买卖点类型::一买,
|
||||
@@ -200,6 +255,6 @@ impl 买卖点 {
|
||||
_ => 买卖点类型::一买, // fallback
|
||||
};
|
||||
|
||||
基础买卖点::new(类型, 当前K线, 买卖点分型, 备注, 破位值)
|
||||
基础买卖点::new(类型, 当前K线, 买卖点分型, 备注, 破位值, 当前序号)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,9 +26,9 @@ use crate::business::observer::观察者;
|
||||
use crate::business::synthesizer::K线合成器;
|
||||
use crate::config::缠论配置;
|
||||
use crate::kline::bar::K线;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
|
||||
/// 立体分析器 — 多周期协调器
|
||||
///
|
||||
@@ -38,7 +38,7 @@ pub struct 立体分析器 {
|
||||
pub 周期组: Vec<i64>,
|
||||
输入周期: i64,
|
||||
K线合成器: K线合成器,
|
||||
单体分析器: HashMap<i64, Rc<RefCell<观察者>>>,
|
||||
单体分析器: HashMap<i64, Arc<RwLock<观察者>>>,
|
||||
}
|
||||
|
||||
impl 立体分析器 {
|
||||
@@ -96,13 +96,13 @@ impl 立体分析器 {
|
||||
// Dispatch on completion events (matching Python's __K线回调)
|
||||
for (周期, 完成K线) in 完成事件 {
|
||||
if let Some(观察员) = self.单体分析器.get(&周期) {
|
||||
观察员.borrow_mut().增加原始K线(完成K线);
|
||||
观察员.write().unwrap().增加原始K线(完成K线);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 获取指定周期的观察者
|
||||
pub fn 获取观察者(&self, 周期: i64) -> Option<Rc<RefCell<观察者>>> {
|
||||
pub fn 获取观察者(&self, 周期: i64) -> Option<Arc<RwLock<观察者>>> {
|
||||
self.单体分析器.get(&周期).cloned()
|
||||
}
|
||||
|
||||
@@ -116,23 +116,23 @@ impl 立体分析器 {
|
||||
let 起始时间 = self
|
||||
.单体分析器
|
||||
.get(&self.输入周期)
|
||||
.and_then(|o| o.borrow().普通K线序列.first().map(|k| k.时间戳))
|
||||
.and_then(|o| o.read().unwrap().普通K线序列.first().map(|k| k.时间戳))
|
||||
.unwrap_or(0);
|
||||
let 结束时间 = self
|
||||
.单体分析器
|
||||
.get(&self.输入周期)
|
||||
.and_then(|o| o.borrow().普通K线序列.last().map(|k| k.时间戳))
|
||||
.and_then(|o| o.read().unwrap().普通K线序列.last().map(|k| k.时间戳))
|
||||
.unwrap_or(0);
|
||||
let 标识 = self
|
||||
.单体分析器
|
||||
.get(&self.输入周期)
|
||||
.map(|o| o.borrow().符号.clone())
|
||||
.map(|o| o.read().unwrap().符号.clone())
|
||||
.unwrap_or_default();
|
||||
|
||||
let 周期 = self
|
||||
.单体分析器
|
||||
.get(&self.输入周期)
|
||||
.map(|o| o.borrow().周期)
|
||||
.map(|o| o.read().unwrap().周期)
|
||||
.unwrap_or_default();
|
||||
|
||||
let 目录标识 = format!("RustM_{}:{}_{}_{}", 标识, 周期, 起始时间, 结束时间);
|
||||
@@ -146,7 +146,8 @@ impl 立体分析器 {
|
||||
for 周期 in &self.周期组 {
|
||||
if let Some(观察员) = self.单体分析器.get(周期) {
|
||||
观察员
|
||||
.borrow()
|
||||
.read()
|
||||
.unwrap()
|
||||
.测试_保存数据(Some(&保存路径.to_string_lossy()));
|
||||
}
|
||||
}
|
||||
|
||||
+562
-119
@@ -32,8 +32,8 @@ use crate::structure::dash_line::虚线;
|
||||
use crate::structure::fractal_obj::分型;
|
||||
use crate::types::相对方向;
|
||||
use crate::utils::datetime;
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
/// 观察者 — 单周期分析器,持有所有层级序列,接收K线流式输入后逐层计算
|
||||
pub struct 观察者 {
|
||||
@@ -42,40 +42,41 @@ pub struct 观察者 {
|
||||
pub 配置: 缠论配置,
|
||||
|
||||
// K线序列
|
||||
pub 普通K线序列: Vec<Rc<K线>>,
|
||||
pub 缠论K线序列: Vec<Rc<缠论K线>>,
|
||||
pub 普通K线序列: Vec<Arc<K线>>,
|
||||
pub 基础缠K序列: Vec<Arc<缠论K线>>,
|
||||
pub 缠论K线序列: Vec<Arc<缠论K线>>,
|
||||
|
||||
// 分型与笔
|
||||
pub 分型序列: Vec<Rc<分型>>,
|
||||
pub 笔序列: Vec<Rc<虚线>>,
|
||||
pub 笔_中枢序列: Vec<Rc<中枢>>,
|
||||
pub 分型序列: Vec<Arc<分型>>,
|
||||
pub 笔序列: Vec<Arc<虚线>>,
|
||||
pub 笔_中枢序列: Vec<Arc<中枢>>,
|
||||
|
||||
// 线段
|
||||
pub 线段序列: Vec<Rc<虚线>>,
|
||||
pub 中枢序列: Vec<Rc<中枢>>,
|
||||
pub 线段序列: Vec<Arc<虚线>>,
|
||||
pub 中枢序列: Vec<Arc<中枢>>,
|
||||
|
||||
// 扩展线段(笔级)
|
||||
pub 扩展线段序列: Vec<Rc<虚线>>,
|
||||
pub 扩展中枢序列: Vec<Rc<中枢>>,
|
||||
pub 扩展线段序列: Vec<Arc<虚线>>,
|
||||
pub 扩展中枢序列: Vec<Arc<中枢>>,
|
||||
|
||||
// 扩展线段(线段级)
|
||||
pub 扩展线段序列_线段: Vec<Rc<虚线>>,
|
||||
pub 扩展中枢序列_线段: Vec<Rc<中枢>>,
|
||||
pub 扩展线段序列_线段: Vec<Arc<虚线>>,
|
||||
pub 扩展中枢序列_线段: Vec<Arc<中枢>>,
|
||||
|
||||
// 线段之线段
|
||||
pub 线段_线段序列: Vec<Rc<虚线>>,
|
||||
pub 线段_中枢序列: Vec<Rc<中枢>>,
|
||||
pub 线段_线段序列: Vec<Arc<虚线>>,
|
||||
pub 线段_中枢序列: Vec<Arc<中枢>>,
|
||||
|
||||
// 扩展线段之扩展线段
|
||||
pub 扩展线段序列_扩展线段: Vec<Rc<虚线>>,
|
||||
pub 扩展中枢序列_扩展线段: Vec<Rc<中枢>>,
|
||||
pub 扩展线段序列_扩展线段: Vec<Arc<虚线>>,
|
||||
pub 扩展中枢序列_扩展线段: Vec<Arc<中枢>>,
|
||||
|
||||
// 终止时间戳
|
||||
终止时间戳: Option<i64>,
|
||||
}
|
||||
|
||||
impl 观察者 {
|
||||
pub fn new(符号: String, 周期: i64, 配置: 缠论配置) -> Rc<RefCell<Self>> {
|
||||
pub fn new(符号: String, 周期: i64, 配置: 缠论配置) -> Arc<RwLock<Self>> {
|
||||
let 终止时间戳 = if 配置.手动终止 != "1970-01-01 00:00:00" && !配置.手动终止.is_empty()
|
||||
{
|
||||
datetime::转化为时间戳(&配置.手动终止)
|
||||
@@ -88,6 +89,7 @@ impl 观察者 {
|
||||
周期,
|
||||
配置,
|
||||
普通K线序列: Vec::new(),
|
||||
基础缠K序列: Vec::new(),
|
||||
缠论K线序列: Vec::new(),
|
||||
分型序列: Vec::new(),
|
||||
笔序列: Vec::new(),
|
||||
@@ -105,7 +107,7 @@ impl 观察者 {
|
||||
终止时间戳,
|
||||
};
|
||||
instance.配置.标识 = 符号;
|
||||
Rc::new(RefCell::new(instance))
|
||||
Arc::new(RwLock::new(instance))
|
||||
}
|
||||
|
||||
/// 标识
|
||||
@@ -114,18 +116,19 @@ impl 观察者 {
|
||||
}
|
||||
|
||||
/// 当前K线
|
||||
pub fn 当前K线(&self) -> Option<&Rc<K线>> {
|
||||
pub fn 当前K线(&self) -> Option<&Arc<K线>> {
|
||||
self.普通K线序列.last()
|
||||
}
|
||||
|
||||
/// 当前缠K
|
||||
pub fn 当前缠K(&self) -> Option<&Rc<缠论K线>> {
|
||||
pub fn 当前缠K(&self) -> Option<&Arc<缠论K线>> {
|
||||
self.缠论K线序列.last()
|
||||
}
|
||||
|
||||
/// 重置基础序列
|
||||
pub fn 重置基础序列(&mut self) {
|
||||
self.普通K线序列.clear();
|
||||
self.基础缠K序列.clear();
|
||||
self.缠论K线序列.clear();
|
||||
self.分型序列.clear();
|
||||
self.笔序列.clear();
|
||||
@@ -152,6 +155,14 @@ impl 观察者 {
|
||||
self.__处理数据(普K);
|
||||
}
|
||||
|
||||
/// 投喂原始数据 — 便捷入口,直接从 OHLCV 创建 K线 并投喂
|
||||
pub fn 投喂原始数据(
|
||||
&mut self, 时间戳: i64, 开: f64, 高: f64, 低: f64, 收: f64, 量: f64
|
||||
) {
|
||||
let 普K = K线::创建普K(&self.符号, 时间戳, 开, 高, 低, 收, 量, 0, self.周期);
|
||||
self.增加原始K线(普K);
|
||||
}
|
||||
|
||||
/// 核心数据处理管道
|
||||
fn __处理数据(&mut self, 普K: K线) {
|
||||
// Step 1: 缠论K线分析 (普K is consumed by 分析 as &mut)
|
||||
@@ -174,6 +185,7 @@ impl 观察者 {
|
||||
&mut self.笔序列,
|
||||
&self.缠论K线序列,
|
||||
&self.普通K线序列,
|
||||
0,
|
||||
&self.配置,
|
||||
);
|
||||
}
|
||||
@@ -232,13 +244,7 @@ impl 观察者 {
|
||||
&mut self.线段_线段序列,
|
||||
&self.配置,
|
||||
0,
|
||||
&[
|
||||
相对方向::向下,
|
||||
相对方向::向上,
|
||||
相对方向::顺,
|
||||
相对方向::逆,
|
||||
相对方向::同,
|
||||
],
|
||||
&[相对方向::向上, 相对方向::向下],
|
||||
);
|
||||
}
|
||||
if self.配置.分析线段中枢 {
|
||||
@@ -282,16 +288,17 @@ impl 观察者 {
|
||||
|
||||
for i in 1..self.缠论K线序列.len() - 1 {
|
||||
let 当前分型 = 分型::new(
|
||||
Some(Rc::clone(&self.缠论K线序列[i - 1])),
|
||||
Rc::clone(&self.缠论K线序列[i]),
|
||||
Some(Rc::clone(&self.缠论K线序列[i + 1])),
|
||||
Some(Arc::clone(&self.缠论K线序列[i - 1])),
|
||||
Arc::clone(&self.缠论K线序列[i]),
|
||||
Some(Arc::clone(&self.缠论K线序列[i + 1])),
|
||||
);
|
||||
笔::分析(
|
||||
Rc::new(当前分型),
|
||||
Arc::new(当前分型),
|
||||
&mut self.分型序列,
|
||||
&mut self.笔序列,
|
||||
&self.缠论K线序列,
|
||||
&self.普通K线序列,
|
||||
0,
|
||||
&self.配置,
|
||||
);
|
||||
}
|
||||
@@ -339,13 +346,7 @@ impl 观察者 {
|
||||
&mut self.线段_线段序列,
|
||||
&self.配置,
|
||||
0,
|
||||
&[
|
||||
相对方向::向下,
|
||||
相对方向::向上,
|
||||
相对方向::顺,
|
||||
相对方向::逆,
|
||||
相对方向::同,
|
||||
],
|
||||
&[相对方向::向上, 相对方向::向下],
|
||||
);
|
||||
}
|
||||
if self.配置.分析线段中枢 {
|
||||
@@ -424,14 +425,14 @@ impl 观察者 {
|
||||
.map(|ck| {
|
||||
format!(
|
||||
"缠K, {}, {}, {:?}, {}, {}, {}, {}, {}",
|
||||
ck.序号,
|
||||
ck.时间戳,
|
||||
ck.序号.load(Ordering::Relaxed),
|
||||
ck.时间戳.load(Ordering::Relaxed),
|
||||
ck.分型,
|
||||
ck.方向,
|
||||
ck.高,
|
||||
ck.低,
|
||||
*ck.方向.read().unwrap(),
|
||||
ck.高.get(),
|
||||
ck.低.get(),
|
||||
ck.原始起始序号,
|
||||
ck.原始结束序号
|
||||
ck.原始结束序号.load(Ordering::Relaxed)
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@@ -442,7 +443,12 @@ impl 观察者 {
|
||||
.map(|(i, fx)| {
|
||||
format!(
|
||||
"分型, {}, {}, {:?}, {}, {}, {}",
|
||||
i, fx.时间戳, fx.结构, fx.分型特征值, fx.中.时间戳, fx.中.低,
|
||||
i,
|
||||
fx.时间戳(),
|
||||
fx.结构,
|
||||
fx.分型特征值,
|
||||
fx.中.时间戳.load(Ordering::Relaxed),
|
||||
fx.中.低.get(),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
@@ -481,39 +487,26 @@ impl 观察者 {
|
||||
println!("全部数据拆分保存完成,目录:{}", 保存路径.display());
|
||||
}
|
||||
|
||||
/// 解析本地数据文件 — 从 .nb 文件读取并解析所有 K线
|
||||
pub fn 解析本地数据(&self, 文件路径: &str) -> Result<Vec<K线>, String> {
|
||||
let data = std::fs::read(文件路径).map_err(|e| format!("read file: {}", e))?;
|
||||
let mut bars = Vec::new();
|
||||
let size = 48;
|
||||
for i in 0..data.len() / size {
|
||||
let offset = i * size;
|
||||
if let Some(k线) = K线::from_bytes(&data[offset..offset + size], self.周期, &self.符号)
|
||||
{
|
||||
bars.push(k线);
|
||||
}
|
||||
}
|
||||
Ok(bars)
|
||||
}
|
||||
|
||||
/// 加载本地数据 — 从 .nb 文件加载数据到当前观察者(先重置再投喂)
|
||||
pub fn 加载本地数据(&mut self, 文件路径: &str) -> Result<(), String> {
|
||||
self.重置基础序列();
|
||||
let bars = self.解析本地数据(文件路径)?;
|
||||
for k线 in bars {
|
||||
self.增加原始K线(k线);
|
||||
let data = std::fs::read(文件路径).map_err(|e| format!("read file: {}", e))?;
|
||||
let size = 48;
|
||||
for i in 0..data.len() / size {
|
||||
let offset = i * size;
|
||||
if let Some((时间戳, 开, 高, 低, 收, 量)) =
|
||||
K线::解析原始数据(&data[offset..offset + size])
|
||||
{
|
||||
self.投喂原始数据(时间戳, 开, 高, 低, 收, 量);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 读取数据文件 — 从 .nb 文件加载数据
|
||||
/// 读取数据文件 — 更新当前观察者并加载 .nb 文件
|
||||
pub fn 读取数据文件(
|
||||
文件路径: &str,
|
||||
配置: Option<缠论配置>,
|
||||
) -> Result<Rc<RefCell<Self>>, String> {
|
||||
let 配置 = 配置.unwrap_or_default();
|
||||
|
||||
// Parse filename: btcusd-300-1631772074-1632222374.nb
|
||||
&mut self, 文件路径: &str, 配置: 缠论配置
|
||||
) -> Result<(), String> {
|
||||
let path = std::path::Path::new(文件路径);
|
||||
let name = path
|
||||
.file_stem()
|
||||
@@ -523,23 +516,12 @@ impl 观察者 {
|
||||
if parts.len() < 4 {
|
||||
return Err(format!("invalid filename format: {}", name));
|
||||
}
|
||||
let 符号 = parts[0].to_string();
|
||||
let 周期: i64 = parts[1]
|
||||
self.符号 = parts[0].to_string();
|
||||
self.周期 = parts[1]
|
||||
.parse()
|
||||
.map_err(|e| format!("parse period: {}", e))?;
|
||||
|
||||
let 实例 = Self::new(符号, 周期, 配置);
|
||||
|
||||
let data = std::fs::read(文件路径).map_err(|e| format!("read file: {}", e))?;
|
||||
let size = 48; // 6 × 8 bytes (big-endian double)
|
||||
for i in 0..data.len() / size {
|
||||
let offset = i * size;
|
||||
if let Some(k线) = K线::from_bytes(&data[offset..offset + size], 周期, "nb") {
|
||||
实例.borrow_mut().增加原始K线(k线);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(实例)
|
||||
self.配置 = 配置;
|
||||
self.加载本地数据(文件路径)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -548,37 +530,53 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::config::缠论配置;
|
||||
|
||||
fn test_data_path() -> String {
|
||||
let manifest = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
|
||||
manifest
|
||||
.parent()
|
||||
.unwrap()
|
||||
.join("btcusd-300-1777649100-1778398800.nb")
|
||||
.to_string_lossy()
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_普k序列指针一致性() {
|
||||
let config = 缠论配置::default();
|
||||
let obs = 观察者::读取数据文件(
|
||||
"/home/moscow/chanlun.rs/btcusd-300-1777649100-1778398800.nb",
|
||||
Some(config),
|
||||
)
|
||||
.unwrap();
|
||||
let obs_ref = obs.borrow();
|
||||
let obs = 观察者::new("btcusd".into(), 300, Default::default());
|
||||
obs.write()
|
||||
.unwrap()
|
||||
.读取数据文件(&test_data_path(), Default::default())
|
||||
.unwrap();
|
||||
let obs_ref = obs.read().unwrap();
|
||||
|
||||
// 1. Check that each 笔's 获取普K序列 returns K lines whose Rc pointers
|
||||
// match entries in 普通K线序列
|
||||
for (i, bi) in obs_ref.笔序列.iter().enumerate() {
|
||||
let pu_seq = bi.获取普K序列(&obs_ref.普通K线序列);
|
||||
if pu_seq.is_empty() {
|
||||
println!("笔 {}: 获取普K序列 返回空 (fallback failed)", i);
|
||||
println!(" 文.中.标的K线 原始起始序号: {}", bi.文.中.原始起始序号);
|
||||
println!(" 武.中.标的K线 原始结束序号: {}", bi.武.中.原始结束序号);
|
||||
println!(
|
||||
" 武.中.标的K线 原始结束序号: {}",
|
||||
bi.武
|
||||
.read()
|
||||
.unwrap()
|
||||
.中
|
||||
.原始结束序号
|
||||
.load(Ordering::Relaxed)
|
||||
);
|
||||
println!(" 普通K线序列.len: {}", obs_ref.普通K线序列.len());
|
||||
} else {
|
||||
// Check first element's pointer
|
||||
let first_ptr = Rc::as_ptr(&pu_seq[0]);
|
||||
let first_ptr = Arc::as_ptr(&pu_seq[0]);
|
||||
let found = obs_ref
|
||||
.普通K线序列
|
||||
.iter()
|
||||
.any(|k| Rc::as_ptr(k) == first_ptr);
|
||||
.any(|k| Arc::as_ptr(k) == first_ptr);
|
||||
if !found {
|
||||
println!("笔 {}: 获取普K序列[0] 的 Rc 指针不在 普通K线序列 中!", i);
|
||||
// Check if 文.中.标的K线 pointer is in 普通K线序列
|
||||
let wen_ptr = Rc::as_ptr(&bi.文.中.标的K线);
|
||||
let wen_found = obs_ref.普通K线序列.iter().any(|k| Rc::as_ptr(k) == wen_ptr);
|
||||
let wen_ptr = Arc::as_ptr(&*bi.文.中.标的K线.read().unwrap());
|
||||
let wen_found = obs_ref
|
||||
.普通K线序列
|
||||
.iter()
|
||||
.any(|k| Arc::as_ptr(k) == wen_ptr);
|
||||
println!(" 文.中.标的K线 在序列中: {}", wen_found);
|
||||
} else {
|
||||
println!("笔 {}: OK, 获取普K序列[0] 在序列中找到", i);
|
||||
@@ -589,49 +587,494 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_pyo3_flow_pointer_consistency() {
|
||||
// Simulate what the PyO3 读取数据文件 classmethod does:
|
||||
// 1. Parse K lines from file
|
||||
// 2. Create "K线Py { inner: Rc::new(k线) }" for each
|
||||
// 3. Call observer.增加原始K线(k线_value)
|
||||
|
||||
let config = 缠论配置::default();
|
||||
let obs_ref = 观察者::new("btcusd".into(), 300, config);
|
||||
|
||||
let file_path = "/home/moscow/chanlun.rs/btcusd-300-1777649100-1778398800.nb";
|
||||
let data = std::fs::read(file_path).unwrap();
|
||||
let data = std::fs::read(test_data_path()).unwrap();
|
||||
let size = 48;
|
||||
|
||||
for i in 0..data.len() / size {
|
||||
let offset = i * size;
|
||||
if let Some(k线) = K线::from_bytes(&data[offset..offset + size], 300, "btcusd") {
|
||||
// Simulate: K线Py { inner: Rc::new(k线) }
|
||||
let _k线_py_inner = Rc::new(k线.clone());
|
||||
// In the actual PyO3 path, (*普K.borrow().inner).clone() extracts K线 value
|
||||
// which then gets Rc::wrapped inside the observer
|
||||
obs_ref.borrow_mut().增加原始K线(k线);
|
||||
let _k线_py_inner = Arc::new(k线.clone());
|
||||
obs_ref.write().unwrap().增加原始K线(k线);
|
||||
}
|
||||
}
|
||||
|
||||
let obs = obs_ref.borrow();
|
||||
let obs = obs_ref.read().unwrap();
|
||||
println!("普通K线序列.len: {}", obs.普通K线序列.len());
|
||||
println!("笔序列.len: {}", obs.笔序列.len());
|
||||
|
||||
// Now check: does 获取普K序列 return K lines whose pointers match 普通K线序列?
|
||||
for (i, bi) in obs.笔序列.iter().enumerate() {
|
||||
let pu_seq = bi.获取普K序列(&obs.普通K线序列);
|
||||
if pu_seq.is_empty() {
|
||||
println!("笔 {}: 获取普K序列 返回空!", i);
|
||||
} else {
|
||||
let first_ptr = Rc::as_ptr(&pu_seq[0]);
|
||||
let found = obs.普通K线序列.iter().any(|k| Rc::as_ptr(k) == first_ptr);
|
||||
let first_ptr = Arc::as_ptr(&pu_seq[0]);
|
||||
let found = obs.普通K线序列.iter().any(|k| Arc::as_ptr(k) == first_ptr);
|
||||
if !found {
|
||||
println!("笔 {}: 获取普K序列[0] 指针不在序列中!", i);
|
||||
}
|
||||
// Only print first few
|
||||
if i < 5 {
|
||||
println!("笔 {}: OK, len={}", i, pu_seq.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 分型到笔的 Rc 指针一致性
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_分型到笔的文武Rc指针一致性() {
|
||||
let obs = 观察者::new("btcusd".into(), 300, Default::default());
|
||||
obs.write()
|
||||
.unwrap()
|
||||
.读取数据文件(&test_data_path(), Default::default())
|
||||
.unwrap();
|
||||
let obs_ref = obs.read().unwrap();
|
||||
|
||||
// 每个笔的文/武 分型 Rc 指针必须在 分型序列 中
|
||||
for (i, bi) in obs_ref.笔序列.iter().enumerate() {
|
||||
let 文_ptr = Arc::as_ptr(&bi.文);
|
||||
let 文_found = obs_ref.分型序列.iter().any(|f| Arc::as_ptr(f) == 文_ptr);
|
||||
if !文_found {
|
||||
println!("笔 {}: 文(时间戳={}) 不在分型序列中!", i, bi.文.时间戳());
|
||||
}
|
||||
|
||||
let 武_ptr = Arc::as_ptr(&*bi.武.read().unwrap());
|
||||
let 武_found = obs_ref.分型序列.iter().any(|f| Arc::as_ptr(f) == 武_ptr);
|
||||
if !武_found {
|
||||
println!(
|
||||
"笔 {}: 武(时间戳={}) 不在分型序列中!",
|
||||
i,
|
||||
bi.武.read().unwrap().时间戳()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 笔到线段的 Rc 指针一致性
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_笔到线段的基础序列Rc指针一致性() {
|
||||
let obs = 观察者::new("btcusd".into(), 300, Default::default());
|
||||
obs.write()
|
||||
.unwrap()
|
||||
.读取数据文件(&test_data_path(), Default::default())
|
||||
.unwrap();
|
||||
let obs_ref = obs.read().unwrap();
|
||||
|
||||
// 每个线段的基础序列中的笔 Rc 指针必须在 笔序列 中
|
||||
for (i, seg) in obs_ref.线段序列.iter().enumerate() {
|
||||
for (j, bi_in_seg) in seg.基础序列.read().unwrap().iter().enumerate() {
|
||||
let bi_ptr = Arc::as_ptr(bi_in_seg);
|
||||
let found = obs_ref.笔序列.iter().any(|b| Arc::as_ptr(b) == bi_ptr);
|
||||
if !found {
|
||||
println!("线段 {} 的基础序列[{}] 不在笔序列中!", i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 中枢基础序列与源的 Rc 指针一致性
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_中枢基础序列与笔序列Rc指针一致() {
|
||||
let obs = 观察者::new("btcusd".into(), 300, Default::default());
|
||||
obs.write()
|
||||
.unwrap()
|
||||
.读取数据文件(&test_data_path(), Default::default())
|
||||
.unwrap();
|
||||
let obs_ref = obs.read().unwrap();
|
||||
|
||||
for (i, hub) in obs_ref.笔_中枢序列.iter().enumerate() {
|
||||
for (j, bi_in_hub) in hub.基础序列.read().unwrap().iter().enumerate() {
|
||||
let bi_ptr = Arc::as_ptr(bi_in_hub);
|
||||
let found = obs_ref.笔序列.iter().any(|b| Arc::as_ptr(b) == bi_ptr);
|
||||
if !found {
|
||||
println!("笔中枢 {} 的基础序列[{}] 不在笔序列中!", i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (i, hub) in obs_ref.中枢序列.iter().enumerate() {
|
||||
for (j, seg_in_hub) in hub.基础序列.read().unwrap().iter().enumerate() {
|
||||
let seg_ptr = Arc::as_ptr(seg_in_hub);
|
||||
let found = obs_ref.线段序列.iter().any(|s| Arc::as_ptr(s) == seg_ptr);
|
||||
if !found {
|
||||
println!("线段中枢 {} 的基础序列[{}] 不在线段序列中!", i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 重复计算一致性
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_重复计算后结果一致() {
|
||||
let data = std::fs::read(test_data_path()).unwrap();
|
||||
let size = 48;
|
||||
|
||||
let 计算 = || {
|
||||
let config = 缠论配置::default();
|
||||
let obs_ref = 观察者::new("btcusd".into(), 300, config);
|
||||
for i in 0..data.len() / size {
|
||||
let offset = i * size;
|
||||
if let Some(k线) = K线::from_bytes(&data[offset..offset + size], 300, "btcusd") {
|
||||
obs_ref.write().unwrap().增加原始K线(k线);
|
||||
}
|
||||
}
|
||||
let obs = obs_ref.read().unwrap();
|
||||
(
|
||||
obs.笔序列.len(),
|
||||
obs.线段序列.len(),
|
||||
obs.中枢序列.len(),
|
||||
obs.笔_中枢序列.len(),
|
||||
)
|
||||
};
|
||||
|
||||
let (笔数1, 段数1, 中枢1, 笔中枢1) = 计算();
|
||||
let (笔数2, 段数2, 中枢2, 笔中枢2) = 计算();
|
||||
|
||||
assert_eq!(笔数1, 笔数2, "重复计算笔数不一致");
|
||||
assert_eq!(段数1, 段数2, "重复计算线段数不一致");
|
||||
assert_eq!(中枢1, 中枢2, "重复计算中枢数不一致");
|
||||
assert_eq!(笔中枢1, 笔中枢2, "重复计算笔中枢数不一致");
|
||||
|
||||
println!(
|
||||
"两次计算结果一致: 笔={}, 线段={}, 中枢={}, 笔中枢={}",
|
||||
笔数1, 段数1, 中枢1, 笔中枢1
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 重置后重新投喂数据一致性
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_重置后重新投喂数据一致() {
|
||||
let config = 缠论配置::default();
|
||||
let obs_ref = 观察者::new("btcusd".into(), 300, config);
|
||||
|
||||
let data = std::fs::read(test_data_path()).unwrap();
|
||||
let size = 48;
|
||||
|
||||
for i in 0..data.len() / size {
|
||||
let offset = i * size;
|
||||
if let Some(k线) = K线::from_bytes(&data[offset..offset + size], 300, "btcusd") {
|
||||
obs_ref.write().unwrap().增加原始K线(k线);
|
||||
}
|
||||
}
|
||||
|
||||
let 第一次笔数 = obs_ref.read().unwrap().笔序列.len();
|
||||
let 第一次段数 = obs_ref.read().unwrap().线段序列.len();
|
||||
|
||||
// 重置
|
||||
obs_ref.write().unwrap().重置基础序列();
|
||||
assert_eq!(obs_ref.read().unwrap().笔序列.len(), 0);
|
||||
assert_eq!(obs_ref.read().unwrap().线段序列.len(), 0);
|
||||
|
||||
// 重新投喂
|
||||
for i in 0..data.len() / size {
|
||||
let offset = i * size;
|
||||
if let Some(k线) = K线::from_bytes(&data[offset..offset + size], 300, "btcusd") {
|
||||
obs_ref.write().unwrap().增加原始K线(k线);
|
||||
}
|
||||
}
|
||||
|
||||
let 第二次笔数 = obs_ref.read().unwrap().笔序列.len();
|
||||
let 第二次段数 = obs_ref.read().unwrap().线段序列.len();
|
||||
|
||||
assert_eq!(第一次笔数, 第二次笔数, "重置后重新投喂笔数不一致");
|
||||
assert_eq!(第一次段数, 第二次段数, "重置后重新投喂线段数不一致");
|
||||
println!("重置后重投一致: 笔={}, 线段={}", 第一次笔数, 第一次段数);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// RefCell 借用安全性 — 连续大量操作不应 panic
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_RefCell借用安全性_连续读取不panic() {
|
||||
let obs = 观察者::new("btcusd".into(), 300, Default::default());
|
||||
obs.write()
|
||||
.unwrap()
|
||||
.读取数据文件(&test_data_path(), Default::default())
|
||||
.unwrap();
|
||||
let obs_ref = obs.read().unwrap();
|
||||
|
||||
// 连续大量读取所有 RefCell 字段,不应 panic
|
||||
for _ in 0..100 {
|
||||
for bi in &obs_ref.笔序列 {
|
||||
let _标识 = bi.标识.read().unwrap().clone();
|
||||
let _wu = bi.武.read().unwrap().clone();
|
||||
let _基础序列 = bi.基础序列.read().unwrap().len();
|
||||
let _特征序列 = bi.特征序列.read().unwrap().len();
|
||||
let _模式 = bi.模式.read().unwrap().clone();
|
||||
let _实中枢 = bi.实_中枢序列.read().unwrap().len();
|
||||
let _虚中枢 = bi.虚_中枢序列.read().unwrap().len();
|
||||
let _合中枢 = bi.合_中枢序列.read().unwrap().len();
|
||||
let _确认K = bi.确认K线.read().unwrap().is_some();
|
||||
let _序号 = bi.序号.load(Ordering::Relaxed);
|
||||
let _有效性 = bi.有效性.load(Ordering::Relaxed);
|
||||
let _短路 = bi.短路修正.load(Ordering::Relaxed);
|
||||
let _前一缺口 = *bi.前一缺口.read().unwrap();
|
||||
}
|
||||
for seg in &obs_ref.线段序列 {
|
||||
let _ = seg.标识.read().unwrap().clone();
|
||||
let _ = seg.基础序列.read().unwrap().len();
|
||||
}
|
||||
}
|
||||
// 到达这里 = 无 panic
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_RefCell借用安全性_交替读写不panic() {
|
||||
let obs = 观察者::new("btcusd".into(), 300, Default::default());
|
||||
obs.write()
|
||||
.unwrap()
|
||||
.读取数据文件(&test_data_path(), Default::default())
|
||||
.unwrap();
|
||||
let obs_ref = obs.read().unwrap();
|
||||
|
||||
// 交替读写 RefCell 字段 — 先读再写同字段,分离 borrow 作用域
|
||||
if !obs_ref.笔序列.is_empty() {
|
||||
let bi = &obs_ref.笔序列[0];
|
||||
// 读
|
||||
let old_mode = bi.模式.read().unwrap().clone();
|
||||
// Ref 已释放,可以写
|
||||
*bi.模式.write().unwrap() = "测试模式".into();
|
||||
let new_mode = bi.模式.read().unwrap().clone();
|
||||
assert_eq!(new_mode, "测试模式");
|
||||
// 恢复
|
||||
*bi.模式.write().unwrap() = old_mode;
|
||||
|
||||
// 读武
|
||||
let old_wu = bi.武.read().unwrap().clone();
|
||||
// Ref 已释放,可以检查
|
||||
assert!(Arc::as_ptr(&old_wu) == Arc::as_ptr(&old_wu));
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 缠K 到 分型 的 Rc 指针一致性
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_缠K到分型的Rc指针一致性() {
|
||||
let obs = 观察者::new("btcusd".into(), 300, Default::default());
|
||||
obs.write()
|
||||
.unwrap()
|
||||
.读取数据文件(&test_data_path(), Default::default())
|
||||
.unwrap();
|
||||
let obs_ref = obs.read().unwrap();
|
||||
|
||||
// 每个分型的左/中/右 缠K 指针必须在 缠论K线序列 中
|
||||
for (i, f) in obs_ref.分型序列.iter().enumerate() {
|
||||
let 中_ptr = Arc::as_ptr(&f.中);
|
||||
let 中_found = obs_ref.缠论K线序列.iter().any(|k| Arc::as_ptr(k) == 中_ptr);
|
||||
if !中_found {
|
||||
println!("分型 {} 的 中(时间戳={}) 不在缠论K线序列中!", i, f.时间戳);
|
||||
}
|
||||
|
||||
if let Some(ref 左) = f.左 {
|
||||
let 左_ptr = Arc::as_ptr(左);
|
||||
let 左_found = obs_ref.缠论K线序列.iter().any(|k| Arc::as_ptr(k) == 左_ptr);
|
||||
if !左_found {
|
||||
println!("分型 {} 的 左 不在缠论K线序列中!", i);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ref 右) = f.右 {
|
||||
let 右_ptr = Arc::as_ptr(右);
|
||||
let 右_found = obs_ref.缠论K线序列.iter().any(|k| Arc::as_ptr(k) == 右_ptr);
|
||||
if !右_found {
|
||||
println!("分型 {} 的 右 不在缠论K线序列中!", i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 跨线程安全测试 ==========
|
||||
|
||||
// 编译期断言:核心类型必须实现 Send + Sync
|
||||
#[allow(dead_code)]
|
||||
fn 断言_Send_Sync_编译期检查() {
|
||||
fn _需要_Send<T: Send>() {}
|
||||
fn _需要_Sync<T: Sync>() {}
|
||||
fn _需要_Send_Sync<T: Send + Sync>() {}
|
||||
|
||||
// 核心数据结构
|
||||
_需要_Send::<crate::kline::chan_kline::缠论K线>();
|
||||
_需要_Send::<crate::structure::dash_line::虚线>();
|
||||
_需要_Send::<crate::algorithm::hub::中枢>();
|
||||
_需要_Send_Sync::<crate::kline::chan_kline::缠论K线>();
|
||||
_需要_Send_Sync::<crate::structure::dash_line::虚线>();
|
||||
_需要_Send_Sync::<crate::algorithm::hub::中枢>();
|
||||
|
||||
// Arc 包装后的 Send 检查
|
||||
_需要_Send::<Arc<crate::kline::chan_kline::缠论K线>>();
|
||||
_需要_Send::<Arc<crate::structure::dash_line::虚线>>();
|
||||
_需要_Send::<Arc<crate::algorithm::hub::中枢>>();
|
||||
|
||||
// 观察者
|
||||
_需要_Send::<crate::business::observer::观察者>();
|
||||
}
|
||||
|
||||
/// 测试:Arc<缠论K线> 可跨线程传递
|
||||
#[test]
|
||||
fn test_跨线程_缠论K线_Send() {
|
||||
use crate::kline::bar::K线;
|
||||
use crate::kline::chan_kline::缠论K线;
|
||||
|
||||
let 普k = Arc::new(K线::创建普K(
|
||||
"test", 1000, 100.0, 110.0, 90.0, 95.0, 1000.0, 0, 300,
|
||||
));
|
||||
let ck = 缠论K线::创建缠K(
|
||||
1000,
|
||||
110.0,
|
||||
90.0,
|
||||
crate::types::相对方向::向上,
|
||||
None,
|
||||
1,
|
||||
普k,
|
||||
None,
|
||||
);
|
||||
let arc_ck = Arc::new(ck);
|
||||
let arc_ck2 = Arc::clone(&arc_ck);
|
||||
|
||||
let handle = std::thread::spawn(move || {
|
||||
let _ = arc_ck2;
|
||||
42
|
||||
});
|
||||
assert_eq!(handle.join().unwrap(), 42);
|
||||
assert!((arc_ck.高.get() - 110.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
/// 测试:Arc<虚线> 可跨线程传递
|
||||
#[test]
|
||||
fn test_跨线程_虚线_Send() {
|
||||
use crate::kline::bar::K线;
|
||||
use crate::kline::chan_kline::缠论K线;
|
||||
use crate::structure::dash_line::虚线;
|
||||
use crate::structure::fractal_obj::分型;
|
||||
|
||||
let 普k = Arc::new(K线::创建普K(
|
||||
"test", 1000, 100.0, 110.0, 90.0, 95.0, 1000.0, 0, 300,
|
||||
));
|
||||
let ck = Arc::new(缠论K线::创建缠K(
|
||||
1000,
|
||||
110.0,
|
||||
90.0,
|
||||
crate::types::相对方向::向上,
|
||||
None,
|
||||
1,
|
||||
普k,
|
||||
None,
|
||||
));
|
||||
let frac = Arc::new(分型::new(None, Arc::clone(&ck), None));
|
||||
let frac2 = Arc::new(分型::new(None, ck, None));
|
||||
|
||||
let dash = Arc::new(虚线::创建笔(frac, frac2, true));
|
||||
let dash2 = Arc::clone(&dash);
|
||||
|
||||
let handle = std::thread::spawn(move || {
|
||||
let _ = Arc::as_ptr(&dash2.文);
|
||||
99
|
||||
});
|
||||
assert_eq!(handle.join().unwrap(), 99);
|
||||
assert_eq!(dash.标识.read().unwrap().as_str(), "笔");
|
||||
}
|
||||
|
||||
/// 测试:Arc<中枢> 可跨线程传递
|
||||
#[test]
|
||||
fn test_跨线程_中枢_Send() {
|
||||
let hub = crate::algorithm::hub::中枢::new(1, "test".into(), 1, vec![]);
|
||||
let arc_hub = Arc::new(hub);
|
||||
let arc_hub2 = Arc::clone(&arc_hub);
|
||||
|
||||
let handle = std::thread::spawn(move || {
|
||||
let _ = arc_hub2.序号.load(Ordering::Relaxed);
|
||||
77
|
||||
});
|
||||
assert_eq!(handle.join().unwrap(), 77);
|
||||
assert_eq!(arc_hub.序号.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
/// 测试:多线程并发读取 观察者
|
||||
#[test]
|
||||
fn test_跨线程_观察者_多线程读取() {
|
||||
let obs = 观察者::new("btcusd".into(), 86400, Default::default());
|
||||
let obs2 = Arc::clone(&obs);
|
||||
let obs3 = Arc::clone(&obs);
|
||||
|
||||
let h1 = std::thread::spawn(move || {
|
||||
let guard = obs2.read().unwrap();
|
||||
guard.符号.clone()
|
||||
});
|
||||
let h2 = std::thread::spawn(move || {
|
||||
let guard = obs3.read().unwrap();
|
||||
guard.周期
|
||||
});
|
||||
|
||||
assert_eq!(h1.join().unwrap(), "btcusd");
|
||||
assert_eq!(h2.join().unwrap(), 86400);
|
||||
}
|
||||
|
||||
/// 测试:Cell 字段跨线程读写不 panic
|
||||
#[test]
|
||||
fn test_跨线程_Cell字段_并发读写() {
|
||||
use crate::kline::bar::K线;
|
||||
use crate::kline::chan_kline::缠论K线;
|
||||
|
||||
let 普k = Arc::new(K线::创建普K(
|
||||
"test", 1000, 100.0, 110.0, 90.0, 95.0, 1000.0, 0, 300,
|
||||
));
|
||||
let ck = Arc::new(缠论K线::创建缠K(
|
||||
1000,
|
||||
110.0,
|
||||
90.0,
|
||||
crate::types::相对方向::向上,
|
||||
None,
|
||||
1,
|
||||
普k,
|
||||
None,
|
||||
));
|
||||
let ck2 = Arc::clone(&ck);
|
||||
|
||||
let handle = std::thread::spawn(move || {
|
||||
let 序号 = ck2.序号.load(Ordering::Relaxed);
|
||||
let 高 = ck2.高.get();
|
||||
(序号, 高)
|
||||
});
|
||||
|
||||
let (序号, 高) = handle.join().unwrap();
|
||||
assert_eq!(序号, 0); // 序号 初始值为 0
|
||||
assert!((高 - 110.0).abs() < 0.01);
|
||||
ck.序号.store(2, Ordering::Relaxed);
|
||||
assert_eq!(ck.序号.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
/// 测试:Arc<观察者> 直接跨线程传递
|
||||
#[test]
|
||||
fn test_跨线程_观察者_所有权转移() {
|
||||
let obs = 观察者::new("ethusd".into(), 7200, Default::default());
|
||||
|
||||
let handle = std::thread::spawn(move || {
|
||||
let guard = obs.read().unwrap();
|
||||
(guard.符号.clone(), guard.周期)
|
||||
});
|
||||
|
||||
let (符号, 周期) = handle.join().unwrap();
|
||||
assert_eq!(符号, "ethusd");
|
||||
assert_eq!(周期, 7200);
|
||||
}
|
||||
}
|
||||
|
||||
+90
-1
@@ -22,7 +22,7 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
|
||||
fn is_infinite_f64(v: &f64) -> bool {
|
||||
v.is_infinite()
|
||||
@@ -70,6 +70,7 @@ pub struct 缠论配置 {
|
||||
|
||||
// ---- 指标 ----
|
||||
pub 计算指标: bool,
|
||||
#[serde(deserialize_with = "deserialize_指标计算方式")]
|
||||
pub 指标计算方式: String,
|
||||
|
||||
// ---- MACD ----
|
||||
@@ -115,6 +116,7 @@ pub struct 缠论配置 {
|
||||
pub 买卖点激进识别: bool,
|
||||
pub 买卖点与MACD柱强相关: bool,
|
||||
pub 买卖点错过误差值: f64,
|
||||
#[serde(deserialize_with = "deserialize_买卖点_指标模式")]
|
||||
pub 买卖点_指标模式: String,
|
||||
pub 买卖点_指标匹配_MACD: bool,
|
||||
pub 买卖点_指标匹配_KDJ: bool,
|
||||
@@ -136,12 +138,66 @@ pub struct 缠论配置 {
|
||||
pub 线段内部背驰_MACD: bool,
|
||||
pub 线段内部背驰_斜率: bool,
|
||||
pub 线段内部背驰_测度: bool,
|
||||
#[serde(deserialize_with = "deserialize_线段内部背驰_模式")]
|
||||
pub 线段内部背驰_模式: String,
|
||||
|
||||
// ---- 文件 ----
|
||||
pub 加载文件路径: String,
|
||||
}
|
||||
|
||||
fn deserialize_指标计算方式<'de, D>(deserializer: D) -> Result<String, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
const VALID: &[&str] = &[
|
||||
"开",
|
||||
"高",
|
||||
"低",
|
||||
"收",
|
||||
"高低均值",
|
||||
"高低收均值",
|
||||
"开高低收均值",
|
||||
];
|
||||
const DEFAULT: &str = "收";
|
||||
if VALID.contains(&s.as_str()) {
|
||||
Ok(s)
|
||||
} else {
|
||||
eprintln!("\x1b[33m[配置警告]\x1b[m 指标计算方式: \"{s}\" 不在有效值 {VALID:?} 内,已使用默认值 \"{DEFAULT}\"");
|
||||
Ok(DEFAULT.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_买卖点_指标模式<'de, D>(deserializer: D) -> Result<String, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
const VALID: &[&str] = &["任意", "配置", "全量", "相对"];
|
||||
const DEFAULT: &str = "配置";
|
||||
if VALID.contains(&s.as_str()) {
|
||||
Ok(s)
|
||||
} else {
|
||||
eprintln!("\x1b[33m[配置警告]\x1b[m 买卖点_指标模式: \"{s}\" 不在有效值 {VALID:?} 内,已使用默认值 \"{DEFAULT}\"");
|
||||
Ok(DEFAULT.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn deserialize_线段内部背驰_模式<'de, D>(deserializer: D) -> Result<String, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
const VALID: &[&str] = &["任意", "配置", "全量", "相对"];
|
||||
const DEFAULT: &str = "相对";
|
||||
if VALID.contains(&s.as_str()) {
|
||||
Ok(s)
|
||||
} else {
|
||||
eprintln!("\x1b[33m[配置警告]\x1b[m 线段内部背驰_模式: \"{s}\" 不在有效值 {VALID:?} 内,已使用默认值 \"{DEFAULT}\"");
|
||||
Ok(DEFAULT.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for 缠论配置 {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
@@ -353,6 +409,39 @@ mod tests {
|
||||
assert_eq!(config.买卖点偏移, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_enum_field_fallback() {
|
||||
// 无效的 指标计算方式 → 回退默认值 "收"
|
||||
let json = r#"{"指标计算方式": "胡写"}"#;
|
||||
let config: 缠论配置 = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(config.指标计算方式, "收");
|
||||
|
||||
// 有效的 指标计算方式 → 正常通过
|
||||
let json = r#"{"指标计算方式": "开"}"#;
|
||||
let config: 缠论配置 = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(config.指标计算方式, "开");
|
||||
|
||||
// 无效的 买卖点_指标模式 → 回退默认值 "配置"
|
||||
let json = r#"{"买卖点_指标模式": "瞎搞"}"#;
|
||||
let config: 缠论配置 = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(config.买卖点_指标模式, "配置");
|
||||
|
||||
// 有效的 买卖点_指标模式 → 正常通过
|
||||
let json = r#"{"买卖点_指标模式": "任意"}"#;
|
||||
let config: 缠论配置 = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(config.买卖点_指标模式, "任意");
|
||||
|
||||
// 无效的 线段内部背驰_模式 → 回退默认值 "相对"
|
||||
let json = r#"{"线段内部背驰_模式": "乱来"}"#;
|
||||
let config: 缠论配置 = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(config.线段内部背驰_模式, "相对");
|
||||
|
||||
// 有效的 线段内部背驰_模式 → 正常通过
|
||||
let json = r#"{"线段内部背驰_模式": "全量"}"#;
|
||||
let config: 缠论配置 = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(config.线段内部背驰_模式, "全量");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_不推送() {
|
||||
let config = 缠论配置::default();
|
||||
|
||||
@@ -77,6 +77,7 @@ impl Default for 随机指标 {
|
||||
|
||||
impl 随机指标 {
|
||||
/// 首次计算 KDJ(无历史数据时)
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn 首次计算(
|
||||
初始最高价: f64,
|
||||
初始最低价: f64,
|
||||
|
||||
@@ -28,7 +28,7 @@ use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::io::Write;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// 原始K线 (OHLCV + 指标)
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
@@ -125,7 +125,23 @@ impl K线 {
|
||||
Self::from_bytes(字节组, 周期, 标识)
|
||||
}
|
||||
|
||||
/// 解析原始数据 — 只提取时间戳+OHLCV,不构造 K线
|
||||
pub fn 解析原始数据(字节组: &[u8]) -> Option<(i64, f64, f64, f64, f64, f64)> {
|
||||
if 字节组.len() < 48 {
|
||||
return None;
|
||||
}
|
||||
let mut reader = &字节组[..48];
|
||||
let 时间戳 = reader.read_f64::<BigEndian>().ok()? as i64;
|
||||
let 开 = reader.read_f64::<BigEndian>().ok()?;
|
||||
let 高 = reader.read_f64::<BigEndian>().ok()?;
|
||||
let 低 = reader.read_f64::<BigEndian>().ok()?;
|
||||
let 收 = reader.read_f64::<BigEndian>().ok()?;
|
||||
let 量 = reader.read_f64::<BigEndian>().ok()?;
|
||||
Some((时间戳, 开, 高, 低, 收, 量))
|
||||
}
|
||||
|
||||
/// 创建普通K线
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn 创建普K(
|
||||
标识: &str,
|
||||
时间戳: i64,
|
||||
@@ -202,12 +218,12 @@ impl K线 {
|
||||
Some(&序列[始_idx..=终_idx])
|
||||
}
|
||||
|
||||
/// 截取Rc<K线>序列中从始到终的片段
|
||||
pub fn 截取rc(序列: &[Rc<Self>], 始: &Rc<Self>, 终: &Rc<Self>) -> Vec<Rc<Self>> {
|
||||
let 始_ptr = Rc::as_ptr(始);
|
||||
let 终_ptr = Rc::as_ptr(终);
|
||||
let 始_idx = 序列.iter().position(|k| Rc::as_ptr(k) == 始_ptr);
|
||||
let 终_idx = 序列.iter().position(|k| Rc::as_ptr(k) == 终_ptr);
|
||||
/// 截取Arc<K线>序列中从始到终的片段
|
||||
pub fn 截取rc(序列: &[Arc<Self>], 始: &Arc<Self>, 终: &Arc<Self>) -> Vec<Arc<Self>> {
|
||||
let 始_ptr = Arc::as_ptr(始);
|
||||
let 终_ptr = Arc::as_ptr(终);
|
||||
let 始_idx = 序列.iter().position(|k| Arc::as_ptr(k) == 始_ptr);
|
||||
let 终_idx = 序列.iter().position(|k| Arc::as_ptr(k) == 终_ptr);
|
||||
match (始_idx, 终_idx) {
|
||||
(Some(s), Some(e)) => 序列[s..=e].to_vec(),
|
||||
_ => Vec::new(),
|
||||
|
||||
+226
-204
@@ -30,24 +30,49 @@ use crate::kline::bar::K线;
|
||||
use crate::structure::fractal_obj::分型;
|
||||
use crate::types::分型结构;
|
||||
use crate::types::相对方向;
|
||||
use std::rc::Rc;
|
||||
use crate::types::SyncF64;
|
||||
use std::sync::atomic::{AtomicI64, Ordering};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
/// 缠论K线 — 经包含处理过后的K线
|
||||
#[derive(Debug, Clone)]
|
||||
///
|
||||
/// 部分字段使用 Cell/RefCell 实现内部可变性,确保包含处理原地修改时
|
||||
/// Rc 指针不变,所有持有该 Rc 的引用(如分型.右)能看到最新数据。
|
||||
#[derive(Debug)]
|
||||
pub struct 缠论K线 {
|
||||
pub 序号: i64,
|
||||
pub 时间戳: i64,
|
||||
pub 高: f64,
|
||||
pub 低: f64,
|
||||
pub 方向: 相对方向,
|
||||
pub 分型: Option<分型结构>,
|
||||
pub 序号: AtomicI64,
|
||||
pub 时间戳: AtomicI64,
|
||||
pub 高: SyncF64,
|
||||
pub 低: SyncF64,
|
||||
pub 方向: RwLock<相对方向>,
|
||||
pub 分型: RwLock<Option<分型结构>>,
|
||||
pub 周期: i64,
|
||||
pub 标识: String,
|
||||
pub 分型特征值: f64,
|
||||
pub 分型特征值: SyncF64,
|
||||
pub 原始起始序号: i64,
|
||||
pub 原始结束序号: i64,
|
||||
pub 标的K线: Rc<K线>,
|
||||
pub 买卖点信息: std::cell::RefCell<Vec<String>>,
|
||||
pub 原始结束序号: AtomicI64,
|
||||
pub 标的K线: RwLock<Arc<K线>>,
|
||||
pub 买卖点信息: RwLock<Vec<String>>,
|
||||
}
|
||||
|
||||
impl Clone for 缠论K线 {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
序号: AtomicI64::new(self.序号.load(Ordering::Relaxed)),
|
||||
时间戳: AtomicI64::new(self.时间戳.load(Ordering::Relaxed)),
|
||||
高: SyncF64::new(self.高.get()),
|
||||
低: SyncF64::new(self.低.get()),
|
||||
方向: RwLock::new(*self.方向.read().unwrap()),
|
||||
分型: RwLock::new(*self.分型.read().unwrap()),
|
||||
周期: self.周期,
|
||||
标识: self.标识.clone(),
|
||||
分型特征值: SyncF64::new(self.分型特征值.get()),
|
||||
原始起始序号: self.原始起始序号,
|
||||
原始结束序号: AtomicI64::new(self.原始结束序号.load(Ordering::Relaxed)),
|
||||
标的K线: RwLock::new(Arc::clone(&self.标的K线.read().unwrap())),
|
||||
买卖点信息: RwLock::new(self.买卖点信息.read().unwrap().clone()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for 缠论K线 {
|
||||
@@ -57,13 +82,16 @@ impl std::fmt::Display for 缠论K线 {
|
||||
f,
|
||||
"{}<{}, {}, {}, {}, {}, {}, {}>",
|
||||
self.标识,
|
||||
self.序号,
|
||||
self.分型.map_or("None".to_string(), |fx| fx.to_string()),
|
||||
self.序号.load(Ordering::Relaxed),
|
||||
self.分型
|
||||
.read()
|
||||
.unwrap()
|
||||
.map_or("None".to_string(), |fx| fx.to_string()),
|
||||
self.周期,
|
||||
self.方向,
|
||||
self.时间戳,
|
||||
format_f64_g(self.高),
|
||||
format_f64_g(self.低)
|
||||
*self.方向.read().unwrap(),
|
||||
self.时间戳.load(Ordering::Relaxed),
|
||||
format_f64_g(self.高.get()),
|
||||
format_f64_g(self.低.get())
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -72,34 +100,34 @@ impl 缠论K线 {
|
||||
/// 创建镜像(浅拷贝 Rc 引用)
|
||||
pub fn 镜像(&self) -> Self {
|
||||
Self {
|
||||
序号: self.序号,
|
||||
时间戳: self.时间戳,
|
||||
高: self.高,
|
||||
低: self.低,
|
||||
方向: self.方向,
|
||||
分型: self.分型,
|
||||
序号: AtomicI64::new(self.序号.load(Ordering::Relaxed)),
|
||||
时间戳: AtomicI64::new(self.时间戳.load(Ordering::Relaxed)),
|
||||
高: SyncF64::new(self.高.get()),
|
||||
低: SyncF64::new(self.低.get()),
|
||||
方向: RwLock::new(*self.方向.read().unwrap()),
|
||||
分型: RwLock::new(*self.分型.read().unwrap()),
|
||||
周期: self.周期,
|
||||
标识: self.标识.clone(),
|
||||
分型特征值: self.分型特征值,
|
||||
分型特征值: SyncF64::new(self.分型特征值.get()),
|
||||
原始起始序号: self.原始起始序号,
|
||||
原始结束序号: self.原始结束序号,
|
||||
标的K线: Rc::clone(&self.标的K线),
|
||||
买卖点信息: std::cell::RefCell::new(self.买卖点信息.borrow().clone()),
|
||||
原始结束序号: AtomicI64::new(self.原始结束序号.load(Ordering::Relaxed)),
|
||||
标的K线: RwLock::new(Arc::clone(&self.标的K线.read().unwrap())),
|
||||
买卖点信息: RwLock::new(self.买卖点信息.read().unwrap().clone()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 与MACD柱子匹配 — 底分型时MACD柱应<0, 顶分型时>0
|
||||
pub fn 与MACD柱子匹配(&self) -> bool {
|
||||
match self.分型 {
|
||||
match *self.分型.read().unwrap() {
|
||||
Some(分型结构::底) | Some(分型结构::下) => {
|
||||
if let Some(ref macd) = self.标的K线.macd {
|
||||
if let Some(ref macd) = self.标的K线.read().unwrap().macd {
|
||||
macd.MACD柱 < 0.0
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
Some(分型结构::顶) | Some(分型结构::上) => {
|
||||
if let Some(ref macd) = self.标的K线.macd {
|
||||
if let Some(ref macd) = self.标的K线.read().unwrap().macd {
|
||||
macd.MACD柱 > 0.0
|
||||
} else {
|
||||
false
|
||||
@@ -111,9 +139,9 @@ impl 缠论K线 {
|
||||
|
||||
/// 与RSI匹配 — 底分型时RSI应低于SMA, 顶分型时高于SMA
|
||||
pub fn 与RSI匹配(&self) -> bool {
|
||||
match self.分型 {
|
||||
match *self.分型.read().unwrap() {
|
||||
Some(分型结构::底) | Some(分型结构::下) => {
|
||||
if let Some(ref rsi) = self.标的K线.rsi {
|
||||
if let Some(ref rsi) = self.标的K线.read().unwrap().rsi {
|
||||
match (rsi.RSI, rsi.RSI_SMA) {
|
||||
(Some(r), Some(sma)) => r < sma,
|
||||
_ => false,
|
||||
@@ -123,7 +151,7 @@ impl 缠论K线 {
|
||||
}
|
||||
}
|
||||
Some(分型结构::顶) | Some(分型结构::上) => {
|
||||
if let Some(ref rsi) = self.标的K线.rsi {
|
||||
if let Some(ref rsi) = self.标的K线.read().unwrap().rsi {
|
||||
match (rsi.RSI, rsi.RSI_SMA) {
|
||||
(Some(r), Some(sma)) => r > sma,
|
||||
_ => false,
|
||||
@@ -138,9 +166,9 @@ impl 缠论K线 {
|
||||
|
||||
/// 与KDJ匹配 — 底分型时K应低于D(死叉后), 顶分型时K应高于D(金叉后)
|
||||
pub fn 与KDJ匹配(&self) -> bool {
|
||||
match self.分型 {
|
||||
match *self.分型.read().unwrap() {
|
||||
Some(分型结构::底) | Some(分型结构::下) => {
|
||||
if let Some(ref kdj) = self.标的K线.kdj {
|
||||
if let Some(ref kdj) = self.标的K线.read().unwrap().kdj {
|
||||
match (kdj.K, kdj.D) {
|
||||
(Some(k), Some(d)) => k < d,
|
||||
_ => false,
|
||||
@@ -150,7 +178,7 @@ impl 缠论K线 {
|
||||
}
|
||||
}
|
||||
Some(分型结构::顶) | Some(分型结构::上) => {
|
||||
if let Some(ref kdj) = self.标的K线.kdj {
|
||||
if let Some(ref kdj) = self.标的K线.read().unwrap().kdj {
|
||||
match (kdj.K, kdj.D) {
|
||||
(Some(k), Some(d)) => k > d,
|
||||
_ => false,
|
||||
@@ -164,28 +192,31 @@ impl 缠论K线 {
|
||||
}
|
||||
|
||||
/// 时间戳对齐 — 从基线序列中找匹配的时间戳
|
||||
pub fn 时间戳对齐(基线: &[Rc<缠论K线>], k线: &缠论K线) -> i64 {
|
||||
pub fn 时间戳对齐(基线: &[Arc<缠论K线>], k线: &缠论K线) -> i64 {
|
||||
if let Some(基) = 基线.first() {
|
||||
for k in 基线.iter().rev() {
|
||||
if 基.周期 < k线.周期 {
|
||||
if k线.时间戳 <= k.时间戳 && k.时间戳 <= k线.时间戳 + k线.周期
|
||||
if k线.时间戳.load(Ordering::Relaxed) <= k.时间戳.load(Ordering::Relaxed)
|
||||
&& k.时间戳.load(Ordering::Relaxed)
|
||||
<= k线.时间戳.load(Ordering::Relaxed) + k线.周期
|
||||
&& (k线.分型特征值.get() - k.分型特征值.get()).abs() < f64::EPSILON
|
||||
{
|
||||
if (k线.分型特征值 - k.分型特征值).abs() < f64::EPSILON {
|
||||
return k.时间戳;
|
||||
}
|
||||
return k.时间戳.load(Ordering::Relaxed);
|
||||
}
|
||||
} else if k.时间戳 <= k线.时间戳 && k线.时间戳 <= k.时间戳 + k.周期
|
||||
} else if k.时间戳.load(Ordering::Relaxed) <= k线.时间戳.load(Ordering::Relaxed)
|
||||
&& k线.时间戳.load(Ordering::Relaxed)
|
||||
<= k.时间戳.load(Ordering::Relaxed) + k.周期
|
||||
&& (k线.分型特征值.get() - k.分型特征值.get()).abs() < f64::EPSILON
|
||||
{
|
||||
if (k线.分型特征值 - k.分型特征值).abs() < f64::EPSILON {
|
||||
return k.时间戳;
|
||||
}
|
||||
return k.时间戳.load(Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
k线.时间戳
|
||||
k线.时间戳.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// 创建缠K
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn 创建缠K(
|
||||
时间戳: i64,
|
||||
高: f64,
|
||||
@@ -193,7 +224,7 @@ impl 缠论K线 {
|
||||
方向: 相对方向,
|
||||
结构: Option<分型结构>,
|
||||
原始序号: i64,
|
||||
普k: Rc<K线>,
|
||||
普k: Arc<K线>,
|
||||
之前: Option<&缠论K线>,
|
||||
) -> Self {
|
||||
if 高.is_nan() || 低.is_nan() {
|
||||
@@ -204,25 +235,28 @@ impl 缠论K线 {
|
||||
let 周期 = 普k.周期;
|
||||
let 标识 = 普k.标识.clone();
|
||||
|
||||
let mut 当前 = Self {
|
||||
序号: 0,
|
||||
时间戳,
|
||||
高,
|
||||
低,
|
||||
方向,
|
||||
分型: 结构,
|
||||
let 当前 = Self {
|
||||
序号: AtomicI64::new(0),
|
||||
时间戳: AtomicI64::new(时间戳),
|
||||
高: SyncF64::new(高),
|
||||
低: SyncF64::new(低),
|
||||
方向: RwLock::new(方向),
|
||||
分型: RwLock::new(结构),
|
||||
周期,
|
||||
标识,
|
||||
分型特征值: 高,
|
||||
分型特征值: SyncF64::new(高),
|
||||
原始起始序号: 原始序号,
|
||||
原始结束序号: 原始序号,
|
||||
标的K线: 普k,
|
||||
买卖点信息: std::cell::RefCell::new(Vec::new()),
|
||||
原始结束序号: AtomicI64::new(原始序号),
|
||||
标的K线: RwLock::new(普k),
|
||||
买卖点信息: RwLock::new(Vec::new()),
|
||||
};
|
||||
|
||||
if let Some(之前) = 之前 {
|
||||
当前.序号 = 之前.序号 + 1;
|
||||
let 关系 = 相对方向::分析(之前.高, 之前.低, 当前.高, 当前.低);
|
||||
当前
|
||||
.序号
|
||||
.store(之前.序号.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
let 关系 =
|
||||
相对方向::分析(之前.高.get(), 之前.低.get(), 当前.高.get(), 当前.低.get());
|
||||
if 关系.是否包含() {
|
||||
panic!(
|
||||
"创建缠K 包含关系: {:?}\n 之前: {}\n 当前: {}",
|
||||
@@ -238,11 +272,11 @@ impl 缠论K线 {
|
||||
/// 返回 (新缠K, 模式) — 模式: "添加"/"替换"/None
|
||||
pub fn 兼并(
|
||||
之前缠K: Option<&缠论K线>,
|
||||
当前缠K: &mut 缠论K线,
|
||||
当前普K: &Rc<K线>,
|
||||
当前缠K: &缠论K线,
|
||||
当前普K: &Arc<K线>,
|
||||
配置: &缠论配置,
|
||||
) -> (Option<Rc<缠论K线>>, Option<String>) {
|
||||
let 关系 = 相对方向::分析(当前缠K.高, 当前缠K.低, 当前普K.高, 当前普K.低);
|
||||
) -> (Option<Arc<缠论K线>>, Option<String>) {
|
||||
let 关系 = 相对方向::分析(当前缠K.高.get(), 当前缠K.低.get(), 当前普K.高, 当前普K.低);
|
||||
|
||||
// 无包含关系 — 创建新元素追加
|
||||
if !关系.是否包含() {
|
||||
@@ -251,37 +285,47 @@ impl 缠论K线 {
|
||||
} else {
|
||||
Some(分型结构::上)
|
||||
};
|
||||
let mut 新缠K = Self::创建缠K(
|
||||
let 新缠K = Self::创建缠K(
|
||||
当前普K.时间戳,
|
||||
当前普K.高,
|
||||
当前普K.低,
|
||||
当前普K.方向(),
|
||||
结构,
|
||||
当前普K.序号,
|
||||
Rc::clone(当前普K),
|
||||
Arc::clone(当前普K),
|
||||
Some(当前缠K),
|
||||
);
|
||||
新缠K.序号 = 当前缠K.序号 + 1;
|
||||
return (Some(Rc::new(新缠K)), Some("添加".into()));
|
||||
新缠K
|
||||
.序号
|
||||
.store(当前缠K.序号.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
return (Some(Arc::new(新缠K)), Some("添加".into()));
|
||||
}
|
||||
|
||||
// 重复提交检测 — 当序号相同时认为是重复提交K线
|
||||
if 当前普K.序号 == 当前缠K.原始结束序号 {
|
||||
if 当前普K.序号 == 当前缠K.原始结束序号.load(Ordering::Relaxed) {
|
||||
return (None, None);
|
||||
}
|
||||
|
||||
// 序号连续性检查
|
||||
if 当前普K.序号 - 1 != 当前缠K.原始结束序号 && 当前普K.序号 != 当前缠K.原始结束序号
|
||||
if 当前普K.序号 - 1 != 当前缠K.原始结束序号.load(Ordering::Relaxed)
|
||||
&& 当前普K.序号 != 当前缠K.原始结束序号.load(Ordering::Relaxed)
|
||||
{
|
||||
panic!(
|
||||
"兼并: 不可追加不连续元素 缠K.原始结束序号: {}, 当前普K.序号: {}",
|
||||
当前缠K.原始结束序号, 当前普K.序号
|
||||
当前缠K.原始结束序号.load(Ordering::Relaxed),
|
||||
当前普K.序号
|
||||
);
|
||||
}
|
||||
|
||||
// 包含关系 — 原地合并到当前缠K
|
||||
let 取值函数: fn(f64, f64) -> f64 = if let Some(之前) = 之前缠K {
|
||||
if 相对方向::分析(之前.高, 之前.低, 当前缠K.高, 当前缠K.低).是否向下()
|
||||
if 相对方向::分析(
|
||||
之前.高.get(),
|
||||
之前.低.get(),
|
||||
当前缠K.高.get(),
|
||||
当前缠K.低.get(),
|
||||
)
|
||||
.是否向下()
|
||||
{
|
||||
f64::min
|
||||
} else {
|
||||
@@ -293,20 +337,22 @@ impl 缠论K线 {
|
||||
|
||||
// 逆序包含时更新时间和标的K线
|
||||
if 关系 != 相对方向::顺 {
|
||||
当前缠K.时间戳 = 当前普K.时间戳;
|
||||
当前缠K.标的K线 = Rc::clone(当前普K);
|
||||
当前缠K.时间戳.store(当前普K.时间戳, Ordering::Relaxed);
|
||||
*当前缠K.标的K线.write().unwrap() = Arc::clone(当前普K);
|
||||
}
|
||||
当前缠K.高 = 取值函数(当前缠K.高, 当前普K.高);
|
||||
当前缠K.低 = 取值函数(当前缠K.低, 当前普K.低);
|
||||
当前缠K.原始结束序号 = 当前普K.序号;
|
||||
当前缠K.方向 = 当前普K.方向();
|
||||
当前缠K.高.set(取值函数(当前缠K.高.get(), 当前普K.高));
|
||||
当前缠K.低.set(取值函数(当前缠K.低.get(), 当前普K.低));
|
||||
当前缠K.原始结束序号.store(当前普K.序号, Ordering::Relaxed);
|
||||
*当前缠K.方向.write().unwrap() = 当前普K.方向();
|
||||
|
||||
if let Some(之前) = 之前缠K {
|
||||
当前缠K.序号 = 之前.序号 + 1;
|
||||
当前缠K
|
||||
.序号
|
||||
.store(之前.序号.load(Ordering::Relaxed) + 1, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
if 配置.缠K合并替换 {
|
||||
(Some(Rc::new(当前缠K.镜像())), Some("替换".into()))
|
||||
(Some(Arc::new(当前缠K.镜像())), Some("替换".into()))
|
||||
} else {
|
||||
(None, None)
|
||||
}
|
||||
@@ -317,10 +363,10 @@ impl 缠论K线 {
|
||||
/// 返回 (状态, 形态)
|
||||
pub fn 分析(
|
||||
mut 当前K线: K线,
|
||||
缠K序列: &mut Vec<Rc<缠论K线>>,
|
||||
普K序列: &mut Vec<Rc<K线>>,
|
||||
缠K序列: &mut Vec<Arc<缠论K线>>,
|
||||
普K序列: &mut Vec<Arc<K线>>,
|
||||
配置: &缠论配置,
|
||||
) -> (String, Option<Rc<分型>>) {
|
||||
) -> (String, Option<Arc<分型>>) {
|
||||
当前K线.标识 = 配置.标识.clone();
|
||||
|
||||
// ---- 阶段1: 普K序列管理 + 指标增量计算 ----
|
||||
@@ -365,54 +411,52 @@ impl 缠论K线 {
|
||||
配置.随机指标_超卖阈值,
|
||||
));
|
||||
}
|
||||
let 当前K线_rc = Rc::new(当前K线);
|
||||
let 当前K线_rc = Arc::new(当前K线);
|
||||
普K序列.push(当前K线_rc);
|
||||
} else {
|
||||
let 之前普K = 普K序列.last().unwrap();
|
||||
if 之前普K.时间戳 == 当前K线.时间戳 {
|
||||
// 同时间戳更新
|
||||
当前K线.序号 = 之前普K.序号;
|
||||
if 配置.计算指标 {
|
||||
if 普K序列.len() >= 2 {
|
||||
if let Some(ref prev_macd) = 普K序列[普K序列.len() - 2].macd {
|
||||
当前K线.macd = Some(平滑异同移动平均线::增量计算(
|
||||
prev_macd,
|
||||
K线取值(
|
||||
当前K线.开盘价,
|
||||
当前K线.高,
|
||||
当前K线.低,
|
||||
当前K线.收盘价,
|
||||
&配置.指标计算方式,
|
||||
),
|
||||
当前K线.时间戳,
|
||||
));
|
||||
}
|
||||
if let Some(ref prev_rsi) = 普K序列[普K序列.len() - 2].rsi {
|
||||
当前K线.rsi = Some(相对强弱指数::增量计算(
|
||||
prev_rsi,
|
||||
K线取值(
|
||||
当前K线.开盘价,
|
||||
当前K线.高,
|
||||
当前K线.低,
|
||||
当前K线.收盘价,
|
||||
&配置.指标计算方式,
|
||||
),
|
||||
当前K线.时间戳,
|
||||
));
|
||||
}
|
||||
if let Some(ref prev_kdj) = 普K序列[普K序列.len() - 2].kdj {
|
||||
当前K线.kdj = Some(随机指标::增量计算(
|
||||
prev_kdj,
|
||||
if 配置.计算指标 && 普K序列.len() >= 2 {
|
||||
if let Some(ref prev_macd) = 普K序列[普K序列.len() - 2].macd {
|
||||
当前K线.macd = Some(平滑异同移动平均线::增量计算(
|
||||
prev_macd,
|
||||
K线取值(
|
||||
当前K线.开盘价,
|
||||
当前K线.高,
|
||||
当前K线.低,
|
||||
当前K线.收盘价,
|
||||
当前K线.时间戳,
|
||||
));
|
||||
}
|
||||
&配置.指标计算方式,
|
||||
),
|
||||
当前K线.时间戳,
|
||||
));
|
||||
}
|
||||
if let Some(ref prev_rsi) = 普K序列[普K序列.len() - 2].rsi {
|
||||
当前K线.rsi = Some(相对强弱指数::增量计算(
|
||||
prev_rsi,
|
||||
K线取值(
|
||||
当前K线.开盘价,
|
||||
当前K线.高,
|
||||
当前K线.低,
|
||||
当前K线.收盘价,
|
||||
&配置.指标计算方式,
|
||||
),
|
||||
当前K线.时间戳,
|
||||
));
|
||||
}
|
||||
if let Some(ref prev_kdj) = 普K序列[普K序列.len() - 2].kdj {
|
||||
当前K线.kdj = Some(随机指标::增量计算(
|
||||
prev_kdj,
|
||||
当前K线.高,
|
||||
当前K线.低,
|
||||
当前K线.收盘价,
|
||||
当前K线.时间戳,
|
||||
));
|
||||
}
|
||||
}
|
||||
普K序列.pop();
|
||||
普K序列.push(Rc::new(当前K线));
|
||||
普K序列.push(Arc::new(当前K线));
|
||||
} else {
|
||||
if 之前普K.时间戳 > 当前K线.时间戳 {
|
||||
panic!("时序错误: 之前={}, 当前={}", 之前普K.时间戳, 当前K线.时间戳);
|
||||
@@ -455,20 +499,20 @@ impl 缠论K线 {
|
||||
));
|
||||
}
|
||||
}
|
||||
普K序列.push(Rc::new(当前K线));
|
||||
普K序列.push(Arc::new(当前K线));
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 阶段2: 缠K合并 ----
|
||||
let 状态: String;
|
||||
let 当前K线_ref: &Rc<K线> = 普K序列.last().unwrap();
|
||||
let 当前K线_ref: &Arc<K线> = 普K序列.last().unwrap();
|
||||
|
||||
if !缠K序列.is_empty() {
|
||||
let len = 缠K序列.len();
|
||||
let (左边, 右边) = 缠K序列.split_at_mut(len - 1);
|
||||
let 之前缠K: Option<&缠论K线> = 左边.last().map(|rc| Rc::as_ref(rc));
|
||||
let 最后一个缠K_mut = Rc::make_mut(&mut 右边[0]);
|
||||
let (新缠K, 模式) = Self::兼并(之前缠K, 最后一个缠K_mut, 当前K线_ref, 配置);
|
||||
let 之前缠K: Option<&缠论K线> = 左边.last().map(Arc::as_ref);
|
||||
let 最后一个缠K = &*右边[0];
|
||||
let (新缠K, 模式) = Self::兼并(之前缠K, 最后一个缠K, 当前K线_ref, 配置);
|
||||
|
||||
if let Some(k) = 新缠K {
|
||||
match 模式.as_deref() {
|
||||
@@ -477,9 +521,8 @@ impl 缠论K线 {
|
||||
状态 = "创建".into();
|
||||
}
|
||||
Some("替换") => {
|
||||
缠K序列.pop();
|
||||
缠K序列.push(k);
|
||||
状态 = "替换".into();
|
||||
// Cell::set 已原地更新数据,无需 pop+push 打破 Rc 身份
|
||||
状态 = "兼并".into();
|
||||
}
|
||||
_ => {
|
||||
状态 = "兼并".into();
|
||||
@@ -496,10 +539,10 @@ impl 缠论K线 {
|
||||
当前K线_ref.方向(),
|
||||
None,
|
||||
当前K线_ref.序号,
|
||||
Rc::clone(普K序列.last().unwrap()),
|
||||
Arc::clone(普K序列.last().unwrap()),
|
||||
None,
|
||||
);
|
||||
缠K序列.push(Rc::new(新缠K));
|
||||
缠K序列.push(Arc::new(新缠K));
|
||||
状态 = "新建".into();
|
||||
}
|
||||
|
||||
@@ -509,106 +552,85 @@ impl 缠论K线 {
|
||||
}
|
||||
|
||||
let idx = 缠K序列.len();
|
||||
let 左 = Rc::clone(&缠K序列[idx - 3]);
|
||||
let 中 = Rc::clone(&缠K序列[idx - 2]);
|
||||
let 右 = Rc::clone(&缠K序列[idx - 1]);
|
||||
let 左 = Arc::clone(&缠K序列[idx - 3]);
|
||||
let 中 = Arc::clone(&缠K序列[idx - 2]);
|
||||
let 右 = Arc::clone(&缠K序列[idx - 1]);
|
||||
|
||||
let 结构 = 分型结构::分析(&*左, &*中, &*右, false, false);
|
||||
|
||||
// 需要通过 Rc::get_mut 或 RefCell 修改 中.分型
|
||||
// 由于使用 Rc,中是不可变的。这里采用创建新 Rc 替换的方式。
|
||||
// 但这是在 Vec 内部修改,需要使用 Rc::make_mut 或重新构建
|
||||
// 对齐 Python:无条件设置 中.分型、中.分型特征值、右.分型特征值、右.分型
|
||||
*缠K序列[idx - 2].分型.write().unwrap() = 结构;
|
||||
|
||||
if let Some(结构) = 结构 {
|
||||
// 只在分型未设置或需要更新时才修改缠K,以保持 Rc 指针不变
|
||||
let 当前分型标记 = 缠K序列[idx - 2].分型;
|
||||
let 中需要更新 = 当前分型标记.is_none() || 当前分型标记 != Some(结构);
|
||||
|
||||
if 中需要更新 {
|
||||
let 中_mut = Rc::make_mut(&mut 缠K序列[idx - 2]);
|
||||
中_mut.分型 = Some(结构);
|
||||
|
||||
match 结构 {
|
||||
分型结构::底 => {
|
||||
中_mut.分型特征值 = 中_mut.低;
|
||||
let 右标记 = 缠K序列[idx - 1].分型;
|
||||
if 右标记.is_none() {
|
||||
let 右_mut = Rc::make_mut(&mut 缠K序列[idx - 1]);
|
||||
右_mut.分型特征值 = 右_mut.高;
|
||||
右_mut.分型 = Some(分型结构::顶);
|
||||
}
|
||||
}
|
||||
分型结构::顶 => {
|
||||
中_mut.分型特征值 = 中_mut.高;
|
||||
let 右标记 = 缠K序列[idx - 1].分型;
|
||||
if 右标记.is_none() {
|
||||
let 右_mut = Rc::make_mut(&mut 缠K序列[idx - 1]);
|
||||
右_mut.分型特征值 = 右_mut.低;
|
||||
右_mut.分型 = Some(分型结构::底);
|
||||
}
|
||||
}
|
||||
分型结构::上 => {
|
||||
中_mut.分型特征值 = 中_mut.高;
|
||||
let 右标记 = 缠K序列[idx - 1].分型;
|
||||
if 右标记.is_none() {
|
||||
let 右_mut = Rc::make_mut(&mut 缠K序列[idx - 1]);
|
||||
右_mut.分型特征值 = 右_mut.高;
|
||||
右_mut.分型 = Some(分型结构::顶);
|
||||
}
|
||||
}
|
||||
分型结构::下 => {
|
||||
中_mut.分型特征值 = 中_mut.低;
|
||||
let 右标记 = 缠K序列[idx - 1].分型;
|
||||
if 右标记.is_none() {
|
||||
let 右_mut = Rc::make_mut(&mut 缠K序列[idx - 1]);
|
||||
右_mut.分型特征值 = 右_mut.低;
|
||||
右_mut.分型 = Some(分型结构::底);
|
||||
}
|
||||
}
|
||||
分型结构::散 => {}
|
||||
match 结构 {
|
||||
分型结构::底 => {
|
||||
缠K序列[idx - 2].分型特征值.set(缠K序列[idx - 2].低.get());
|
||||
缠K序列[idx - 1].分型特征值.set(缠K序列[idx - 1].高.get());
|
||||
*缠K序列[idx - 1].分型.write().unwrap() = Some(分型结构::顶);
|
||||
}
|
||||
分型结构::顶 => {
|
||||
缠K序列[idx - 2].分型特征值.set(缠K序列[idx - 2].高.get());
|
||||
缠K序列[idx - 1].分型特征值.set(缠K序列[idx - 1].低.get());
|
||||
*缠K序列[idx - 1].分型.write().unwrap() = Some(分型结构::底);
|
||||
}
|
||||
分型结构::上 => {
|
||||
缠K序列[idx - 2].分型特征值.set(缠K序列[idx - 2].高.get());
|
||||
缠K序列[idx - 1].分型特征值.set(缠K序列[idx - 1].高.get());
|
||||
*缠K序列[idx - 1].分型.write().unwrap() = Some(分型结构::顶);
|
||||
}
|
||||
分型结构::下 => {
|
||||
缠K序列[idx - 2].分型特征值.set(缠K序列[idx - 2].低.get());
|
||||
缠K序列[idx - 1].分型特征值.set(缠K序列[idx - 1].低.get());
|
||||
*缠K序列[idx - 1].分型.write().unwrap() = Some(分型结构::底);
|
||||
}
|
||||
分型结构::散 => {}
|
||||
}
|
||||
|
||||
let 形态 = if matches!(结构, 分型结构::上 | 分型结构::下) {
|
||||
// Python: 形态 = 分型(中, 右, None) — 左=中K线, 中=右K线, 右=None
|
||||
Rc::new(分型::new(
|
||||
Some(Rc::clone(&缠K序列[idx - 2])),
|
||||
Rc::clone(&缠K序列[idx - 1]),
|
||||
Arc::new(分型::new(
|
||||
Some(Arc::clone(&缠K序列[idx - 2])),
|
||||
Arc::clone(&缠K序列[idx - 1]),
|
||||
None,
|
||||
))
|
||||
} else {
|
||||
Rc::new(分型::new(
|
||||
Some(Rc::clone(&缠K序列[idx - 3])),
|
||||
Rc::clone(&缠K序列[idx - 2]),
|
||||
Some(Rc::clone(&缠K序列[idx - 1])),
|
||||
Arc::new(分型::new(
|
||||
Some(Arc::clone(&缠K序列[idx - 3])),
|
||||
Arc::clone(&缠K序列[idx - 2]),
|
||||
Some(Arc::clone(&缠K序列[idx - 1])),
|
||||
))
|
||||
};
|
||||
|
||||
return (状态, Some(形态));
|
||||
}
|
||||
|
||||
(状态, None)
|
||||
// 对齐 Python:结构为 None 时仍创建并返回分型
|
||||
let 形态 = Arc::new(分型::new(
|
||||
Some(Arc::clone(&缠K序列[idx - 3])),
|
||||
Arc::clone(&缠K序列[idx - 2]),
|
||||
Some(Arc::clone(&缠K序列[idx - 1])),
|
||||
));
|
||||
(状态, Some(形态))
|
||||
}
|
||||
|
||||
/// 截取缠K序列从始到终
|
||||
pub fn 截取(
|
||||
序列: &[Rc<缠论K线>], 始: &缠论K线, 终: &缠论K线
|
||||
) -> Option<Vec<Rc<缠论K线>>> {
|
||||
let 始_idx = 序列
|
||||
.iter()
|
||||
.position(|k| Rc::as_ptr(k) == (始 as *const _))?;
|
||||
let 终_idx = 序列
|
||||
.iter()
|
||||
.position(|k| Rc::as_ptr(k) == (终 as *const _))?;
|
||||
序列: &[Arc<缠论K线>],
|
||||
始: &缠论K线,
|
||||
终: &缠论K线,
|
||||
) -> Option<Vec<Arc<缠论K线>>> {
|
||||
let 始_idx = 序列.iter().position(|k| std::ptr::eq(Arc::as_ptr(k), 始))?;
|
||||
let 终_idx = 序列.iter().position(|k| std::ptr::eq(Arc::as_ptr(k), 终))?;
|
||||
Some(序列[始_idx..=终_idx].to_vec())
|
||||
}
|
||||
}
|
||||
|
||||
impl crate::types::fractal::有高低 for 缠论K线 {
|
||||
fn 高(&self) -> f64 {
|
||||
self.高
|
||||
self.高.get()
|
||||
}
|
||||
fn 低(&self) -> f64 {
|
||||
self.低
|
||||
self.低.get()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -623,11 +645,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_创建缠K_basic() {
|
||||
let pk = Rc::new(make_普K(1000, 100.0, 110.0, 95.0, 105.0, 0));
|
||||
let pk = Arc::new(make_普K(1000, 100.0, 110.0, 95.0, 105.0, 0));
|
||||
let ck = 缠论K线::创建缠K(1000, 110.0, 95.0, 相对方向::向上, None, 0, pk, None);
|
||||
assert_eq!(ck.高, 110.0);
|
||||
assert_eq!(ck.低, 95.0);
|
||||
assert_eq!(ck.序号, 0);
|
||||
assert_eq!(ck.高.get(), 110.0);
|
||||
assert_eq!(ck.低.get(), 95.0);
|
||||
assert_eq!(ck.序号.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+30
-32
@@ -77,38 +77,36 @@ fn 测试_读取数据(文件路径: &str) {
|
||||
let 启动时间 = Instant::now();
|
||||
|
||||
let 配置 = 缠论配置::default().不推送();
|
||||
match 观察者::读取数据文件(文件路径, Some(配置)) {
|
||||
Ok(观察员) => {
|
||||
let 观察员 = 观察员.borrow();
|
||||
let 消耗用时 = 启动时间.elapsed();
|
||||
println!(
|
||||
"测试_读取数据 耗时 {:.2?} 普K数量 {}",
|
||||
消耗用时,
|
||||
观察员.普通K线序列.len()
|
||||
);
|
||||
println!("符号: {}", 观察员.符号);
|
||||
println!("周期: {}", 观察员.周期);
|
||||
println!("缠K数量: {}", 观察员.缠论K线序列.len());
|
||||
println!("分型数量: {}", 观察员.分型序列.len());
|
||||
println!("笔数量: {}", 观察员.笔序列.len());
|
||||
println!("笔中枢数量: {}", 观察员.笔_中枢序列.len());
|
||||
println!("线段数量: {}", 观察员.线段序列.len());
|
||||
println!("中枢数量: {}", 观察员.中枢序列.len());
|
||||
println!("扩展线段数量: {}", 观察员.扩展线段序列.len());
|
||||
println!("线段_线段序列数量: {}", 观察员.线段_线段序列.len());
|
||||
println!(
|
||||
"扩展线段_扩展线段数量: {}",
|
||||
观察员.扩展线段序列_扩展线段.len()
|
||||
);
|
||||
let 观察员 = 观察者::new("".into(), 0, 缠论配置::default());
|
||||
观察员
|
||||
.write()
|
||||
.unwrap()
|
||||
.读取数据文件(文件路径, 配置)
|
||||
.expect("读取数据文件失败");
|
||||
let 观察员 = 观察员.read().unwrap();
|
||||
let 消耗用时 = 启动时间.elapsed();
|
||||
println!(
|
||||
"测试_读取数据 耗时 {:.2?} 普K数量 {}",
|
||||
消耗用时,
|
||||
观察员.普通K线序列.len()
|
||||
);
|
||||
println!("符号: {}", 观察员.符号);
|
||||
println!("周期: {}", 观察员.周期);
|
||||
println!("缠K数量: {}", 观察员.缠论K线序列.len());
|
||||
println!("分型数量: {}", 观察员.分型序列.len());
|
||||
println!("笔数量: {}", 观察员.笔序列.len());
|
||||
println!("笔中枢数量: {}", 观察员.笔_中枢序列.len());
|
||||
println!("线段数量: {}", 观察员.线段序列.len());
|
||||
println!("中枢数量: {}", 观察员.中枢序列.len());
|
||||
println!("扩展线段数量: {}", 观察员.扩展线段序列.len());
|
||||
println!("线段_线段序列数量: {}", 观察员.线段_线段序列.len());
|
||||
println!(
|
||||
"扩展线段_扩展线段数量: {}",
|
||||
观察员.扩展线段序列_扩展线段.len()
|
||||
);
|
||||
|
||||
println!("\n===== 保存分析数据 =====\n");
|
||||
观察员.测试_保存数据(None);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("读取失败: {}", e);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
println!("\n===== 保存分析数据 =====\n");
|
||||
观察员.测试_保存数据(None);
|
||||
}
|
||||
|
||||
/// 测试_周期合成 — 多周期合成分析
|
||||
@@ -162,7 +160,7 @@ fn 测试_周期合成(文件路径: &str) {
|
||||
// Display stats per period
|
||||
for &p in &[周期, 周期 * 5, 周期 * 5 * 6] {
|
||||
if let Some(观察员) = 多级别分析.获取观察者(p) {
|
||||
let 观察员 = 观察员.borrow();
|
||||
let 观察员 = 观察员.read().unwrap();
|
||||
println!(
|
||||
"周期<{}>: 缠K={}, 分型={}, 笔={}, 线段={}, 中枢={}",
|
||||
p,
|
||||
|
||||
+506
-142
@@ -29,30 +29,32 @@ use crate::kline::chan_kline::缠论K线;
|
||||
use crate::structure::fractal_obj::分型;
|
||||
use crate::structure::segment_feat::线段特征;
|
||||
use crate::types::{分型结构, 相对方向, 缺口};
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, Ordering};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
/// 虚线 — 笔和线段的通用数据结构
|
||||
///
|
||||
/// 笔和线段共享此 struct,通过 `标识` 字段区分 ("笔"/"线段"/"扩展线段"等)
|
||||
#[derive(Debug, Clone)]
|
||||
/// 可变字段使用 Cell/RefCell 实现内部可变性,确保 Rc 指针身份一致
|
||||
#[derive(Debug)]
|
||||
pub struct 虚线 {
|
||||
pub 标识: String,
|
||||
pub 序号: i64,
|
||||
pub 级别: i64,
|
||||
pub 文: Rc<分型>,
|
||||
pub 武: Rc<分型>,
|
||||
pub 有效性: bool,
|
||||
pub 基础序列: Vec<Rc<虚线>>,
|
||||
pub 特征序列: Vec<Option<Rc<线段特征>>>,
|
||||
pub 实_中枢序列: Vec<Rc<中枢>>,
|
||||
pub 虚_中枢序列: Vec<Rc<中枢>>,
|
||||
pub 合_中枢序列: Vec<Rc<中枢>>,
|
||||
pub 确认K线: Option<Rc<缠论K线>>,
|
||||
pub 模式: String,
|
||||
pub _特征序列_显示: bool,
|
||||
pub 前一缺口: Option<缺口>,
|
||||
pub 前一结束位置: Option<Rc<虚线>>,
|
||||
pub 短路修正: bool,
|
||||
pub 标识: RwLock<String>,
|
||||
pub 序号: AtomicI64,
|
||||
pub 级别: AtomicI64,
|
||||
pub 文: Arc<分型>,
|
||||
pub 武: RwLock<Arc<分型>>,
|
||||
pub 有效性: AtomicBool,
|
||||
pub 基础序列: RwLock<Vec<Arc<虚线>>>,
|
||||
pub 特征序列: RwLock<Vec<Option<Arc<线段特征>>>>,
|
||||
pub 实_中枢序列: RwLock<Vec<Arc<中枢>>>,
|
||||
pub 虚_中枢序列: RwLock<Vec<Arc<中枢>>>,
|
||||
pub 合_中枢序列: RwLock<Vec<Arc<中枢>>>,
|
||||
pub 确认K线: RwLock<Option<Arc<缠论K线>>>,
|
||||
pub 模式: RwLock<String>,
|
||||
pub _特征序列_显示: AtomicBool,
|
||||
pub 前一缺口: RwLock<Option<缺口>>,
|
||||
pub 前一结束位置: RwLock<Option<Arc<虚线>>>,
|
||||
pub 短路修正: AtomicBool,
|
||||
}
|
||||
|
||||
/// MACD行为统计 — 统计MACD行为 方法的返回类型
|
||||
@@ -67,51 +69,73 @@ pub struct MACD行为统计 {
|
||||
pub 密集交叉区域: Vec<(usize, usize, usize)>,
|
||||
}
|
||||
|
||||
impl Clone for 虚线 {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
标识: RwLock::new(self.标识.read().unwrap().clone()),
|
||||
序号: AtomicI64::new(self.序号.load(Ordering::Relaxed)),
|
||||
级别: AtomicI64::new(self.级别.load(Ordering::Relaxed)),
|
||||
文: Arc::clone(&self.文),
|
||||
武: RwLock::new(Arc::clone(&self.武.read().unwrap())),
|
||||
有效性: AtomicBool::new(self.有效性.load(Ordering::Relaxed)),
|
||||
基础序列: RwLock::new(self.基础序列.read().unwrap().clone()),
|
||||
特征序列: RwLock::new(self.特征序列.read().unwrap().clone()),
|
||||
实_中枢序列: RwLock::new(self.实_中枢序列.read().unwrap().clone()),
|
||||
虚_中枢序列: RwLock::new(self.虚_中枢序列.read().unwrap().clone()),
|
||||
合_中枢序列: RwLock::new(self.合_中枢序列.read().unwrap().clone()),
|
||||
确认K线: RwLock::new(self.确认K线.read().unwrap().clone()),
|
||||
模式: RwLock::new(self.模式.read().unwrap().clone()),
|
||||
_特征序列_显示: AtomicBool::new(self._特征序列_显示.load(Ordering::Relaxed)),
|
||||
前一缺口: RwLock::new(*self.前一缺口.read().unwrap()),
|
||||
前一结束位置: RwLock::new(self.前一结束位置.read().unwrap().clone()),
|
||||
短路修正: AtomicBool::new(self.短路修正.load(Ordering::Relaxed)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl 虚线 {
|
||||
pub fn new(
|
||||
序号: i64,
|
||||
标识: String,
|
||||
文: Rc<分型>,
|
||||
武: Rc<分型>,
|
||||
文: Arc<分型>,
|
||||
武: Arc<分型>,
|
||||
级别: i64,
|
||||
有效性: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
序号,
|
||||
标识,
|
||||
级别,
|
||||
序号: AtomicI64::new(序号),
|
||||
标识: RwLock::new(标识),
|
||||
级别: AtomicI64::new(级别),
|
||||
文,
|
||||
武,
|
||||
有效性,
|
||||
基础序列: Vec::new(),
|
||||
特征序列: Vec::new(),
|
||||
实_中枢序列: Vec::new(),
|
||||
虚_中枢序列: Vec::new(),
|
||||
合_中枢序列: Vec::new(),
|
||||
确认K线: None,
|
||||
模式: "文武".into(),
|
||||
_特征序列_显示: false,
|
||||
前一缺口: None,
|
||||
前一结束位置: None,
|
||||
短路修正: false,
|
||||
武: RwLock::new(武),
|
||||
有效性: AtomicBool::new(有效性),
|
||||
基础序列: RwLock::new(Vec::new()),
|
||||
特征序列: RwLock::new(Vec::new()),
|
||||
实_中枢序列: RwLock::new(Vec::new()),
|
||||
虚_中枢序列: RwLock::new(Vec::new()),
|
||||
合_中枢序列: RwLock::new(Vec::new()),
|
||||
确认K线: RwLock::new(None),
|
||||
模式: RwLock::new("文武".into()),
|
||||
_特征序列_显示: AtomicBool::new(false),
|
||||
前一缺口: RwLock::new(None),
|
||||
前一结束位置: RwLock::new(None),
|
||||
短路修正: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// 笔序列(基础序列的别名)
|
||||
pub fn 笔序列(&self) -> &Vec<Rc<虚线>> {
|
||||
&self.基础序列
|
||||
}
|
||||
|
||||
pub fn 图表标题(&self) -> String {
|
||||
format!(
|
||||
"{}:{}:{}:{}",
|
||||
self.文.中.标识, self.文.中.周期, self.标识, self.序号
|
||||
self.文.中.标识,
|
||||
self.文.中.周期,
|
||||
self.标识.read().unwrap(),
|
||||
self.序号.load(Ordering::Relaxed)
|
||||
)
|
||||
}
|
||||
|
||||
/// 方向 — 文到武的方向
|
||||
pub fn 方向(&self) -> 相对方向 {
|
||||
match (self.文.结构, self.武.结构) {
|
||||
match (self.文.结构, self.武.read().unwrap().结构) {
|
||||
(分型结构::顶, 分型结构::底) => 相对方向::向下,
|
||||
(分型结构::顶, 分型结构::下) => 相对方向::向下,
|
||||
(分型结构::上, 分型结构::底) => 相对方向::向下,
|
||||
@@ -123,54 +147,60 @@ impl 虚线 {
|
||||
/// 虚线高
|
||||
pub fn 高(&self) -> f64 {
|
||||
if self.方向() == 相对方向::向下 {
|
||||
self.文.中.高
|
||||
self.文.中.高.get()
|
||||
} else {
|
||||
self.武.中.高
|
||||
self.武.read().unwrap().中.高.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// 虚线低
|
||||
pub fn 低(&self) -> f64 {
|
||||
if self.方向() == 相对方向::向下 {
|
||||
self.武.中.低
|
||||
self.武.read().unwrap().中.低.get()
|
||||
} else {
|
||||
self.文.中.低
|
||||
self.文.中.低.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// 判断两个虚线是否首尾相连
|
||||
pub fn 之前是(&self, 之前: &虚线) -> bool {
|
||||
if self.标识 != 之前.标识 {
|
||||
if *self.标识.read().unwrap() != *之前.标识.read().unwrap() {
|
||||
return false;
|
||||
}
|
||||
Rc::as_ptr(&之前.武) == Rc::as_ptr(&self.文)
|
||||
Arc::as_ptr(&*之前.武.read().unwrap()) == Arc::as_ptr(&self.文)
|
||||
}
|
||||
|
||||
/// 判断两个虚线是否首尾相连
|
||||
pub fn 之后是(&self, 之后: &虚线) -> bool {
|
||||
if self.标识 != 之后.标识 {
|
||||
if *self.标识.read().unwrap() != *之后.标识.read().unwrap() {
|
||||
return false;
|
||||
}
|
||||
Rc::as_ptr(&self.武) == Rc::as_ptr(&之后.文)
|
||||
Arc::as_ptr(&*self.武.read().unwrap()) == Arc::as_ptr(&之后.文)
|
||||
}
|
||||
|
||||
/// 获取该虚线范围内的普K序列
|
||||
pub fn 获取普K序列(&self, 普K序列: &[Rc<K线>]) -> Vec<Rc<K线>> {
|
||||
pub fn 获取普K序列(&self, 普K序列: &[Arc<K线>]) -> Vec<Arc<K线>> {
|
||||
// 使用指针查找(与 Python list.index 身份匹配行为一致),
|
||||
// 而非序号切片——因为序号可能与实际位置不一致。
|
||||
let 始 = 普K序列
|
||||
.iter()
|
||||
.position(|k| Rc::as_ptr(k) == Rc::as_ptr(&self.文.中.标的K线));
|
||||
let 终 = 普K序列
|
||||
.iter()
|
||||
.position(|k| Rc::as_ptr(k) == Rc::as_ptr(&self.武.中.标的K线));
|
||||
.position(|k| Arc::as_ptr(k) == Arc::as_ptr(&*self.文.中.标的K线.read().unwrap()));
|
||||
let 终 = 普K序列.iter().position(|k| {
|
||||
Arc::as_ptr(k) == Arc::as_ptr(&*self.武.read().unwrap().中.标的K线.read().unwrap())
|
||||
});
|
||||
match (始, 终) {
|
||||
(Some(s), Some(e)) if s <= e => 普K序列[s..=e].to_vec(),
|
||||
_ => {
|
||||
// 指针查找失败时回退到序号方式
|
||||
println!("[警告]虚线.获取普K序列 <指针查找失败时回退到序号方式>");
|
||||
let 始 = self.文.中.原始起始序号 as usize;
|
||||
let 终 = self.武.中.原始结束序号 as usize;
|
||||
let 终 = self
|
||||
.武
|
||||
.read()
|
||||
.unwrap()
|
||||
.中
|
||||
.原始结束序号
|
||||
.load(Ordering::Relaxed) as usize;
|
||||
if 始 < 普K序列.len() && 终 < 普K序列.len() && 始 <= 终 {
|
||||
普K序列[始..=终].to_vec()
|
||||
} else {
|
||||
@@ -181,36 +211,43 @@ impl 虚线 {
|
||||
}
|
||||
|
||||
/// 获取该虚线范围内的缠K序列
|
||||
pub fn 获取缠K序列(&self, 缠K序列: &[Rc<缠论K线>]) -> Vec<Rc<缠论K线>> {
|
||||
缠论K线::截取(缠K序列, &self.文.中, &self.武.中).unwrap_or_default()
|
||||
pub fn 获取缠K序列(&self, 缠K序列: &[Arc<缠论K线>]) -> Vec<Arc<缠论K线>> {
|
||||
缠论K线::截取(缠K序列, &self.文.中, &self.武.read().unwrap().中).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// 获取_武 — 递归获取虚线的终点分型(笔直接返回武,线段递归到底层笔的武)
|
||||
pub fn 获取_武(&self) -> Rc<分型> {
|
||||
if self.标识 == "笔" {
|
||||
return Rc::clone(&self.武);
|
||||
pub fn 获取_武(&self) -> Arc<分型> {
|
||||
if *self.标识.read().unwrap() == "笔" {
|
||||
return self.武.read().unwrap().clone();
|
||||
}
|
||||
let mut current: &虚线 = self;
|
||||
while current.标识 != "笔" {
|
||||
current = &*current.基础序列.last().unwrap();
|
||||
let mut current_rc = Arc::clone(self.基础序列.read().unwrap().last().unwrap());
|
||||
loop {
|
||||
if *current_rc.标识.read().unwrap() == "笔" {
|
||||
return current_rc.武.read().unwrap().clone();
|
||||
}
|
||||
let next = Arc::clone(current_rc.基础序列.read().unwrap().last().unwrap());
|
||||
current_rc = next;
|
||||
}
|
||||
Rc::clone(¤t.武)
|
||||
}
|
||||
|
||||
/// 获取数据文本(用于保存/调试)
|
||||
pub fn 获取数据文本(&self) -> String {
|
||||
use crate::utils::format_f64_g;
|
||||
if self.标识 == "笔" {
|
||||
if *self.标识.read().unwrap() == "笔" {
|
||||
return format!(
|
||||
"{}, {}, {}, 文:({},{}), 武:({},{}), {}",
|
||||
self.标识,
|
||||
self.序号,
|
||||
self.级别,
|
||||
self.文.时间戳,
|
||||
self.标识.read().unwrap(),
|
||||
self.序号.load(Ordering::Relaxed),
|
||||
self.级别.load(Ordering::Relaxed),
|
||||
self.文.时间戳(),
|
||||
format_f64_g(self.文.分型特征值),
|
||||
self.武.时间戳,
|
||||
format_f64_g(self.武.分型特征值),
|
||||
if self.有效性 { "True" } else { "False" },
|
||||
self.武.read().unwrap().时间戳(),
|
||||
format_f64_g(self.武.read().unwrap().分型特征值),
|
||||
if self.有效性.load(Ordering::Relaxed) {
|
||||
"True"
|
||||
} else {
|
||||
"False"
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -225,11 +262,11 @@ impl 虚线 {
|
||||
}
|
||||
};
|
||||
|
||||
let 前一缺口_str = match &self.前一缺口 {
|
||||
let 前一缺口_str = match &*self.前一缺口.read().unwrap() {
|
||||
Some(g) => format!("{}", g),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
let 前一结束位置_str = match &self.前一结束位置 {
|
||||
let 前一结束位置_str = match &*self.前一结束位置.read().unwrap() {
|
||||
Some(d) => format!("{}", d),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
@@ -238,6 +275,8 @@ impl 虚线 {
|
||||
let 实_str = format!(
|
||||
"[{}]",
|
||||
self.实_中枢序列
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|h| format!("{}", h))
|
||||
.collect::<Vec<_>>()
|
||||
@@ -246,6 +285,8 @@ impl 虚线 {
|
||||
let 虚_str = format!(
|
||||
"[{}]",
|
||||
self.虚_中枢序列
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|h| format!("{}", h))
|
||||
.collect::<Vec<_>>()
|
||||
@@ -254,6 +295,8 @@ impl 虚线 {
|
||||
let 合_str = format!(
|
||||
"[{}]",
|
||||
self.合_中枢序列
|
||||
.read()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|h| format!("{}", h))
|
||||
.collect::<Vec<_>>()
|
||||
@@ -284,15 +327,15 @@ impl 虚线 {
|
||||
|
||||
format!(
|
||||
"{}, {}, {}, 文:({},{}), 武:({},{}), {}, {}, ({}, {}, {}), (前: {}, 后: {}, 三: {}, 伤: {}), 实: {}, 虚: {}, 合: {}, {}, {}, {}, {}",
|
||||
self.标识,
|
||||
self.序号,
|
||||
self.级别,
|
||||
self.文.时间戳,
|
||||
self.标识.read().unwrap(),
|
||||
self.序号.load(Ordering::Relaxed),
|
||||
self.级别.load(Ordering::Relaxed),
|
||||
self.文.时间戳(),
|
||||
format_f64_g(self.文.分型特征值),
|
||||
self.武.时间戳,
|
||||
format_f64_g(self.武.分型特征值),
|
||||
if self.有效性 { "True" } else { "False" },
|
||||
self.基础序列.len(),
|
||||
self.武.read().unwrap().时间戳(),
|
||||
format_f64_g(self.武.read().unwrap().分型特征值),
|
||||
if self.有效性.load(Ordering::Relaxed) { "True" } else { "False" },
|
||||
self.基础序列.read().unwrap().len(),
|
||||
特征_bool(特征_a),
|
||||
特征_bool(特征_b),
|
||||
特征_bool(特征_c),
|
||||
@@ -303,33 +346,39 @@ impl 虚线 {
|
||||
实_str,
|
||||
虚_str,
|
||||
合_str,
|
||||
self.模式,
|
||||
self.模式.read().unwrap(),
|
||||
前一缺口_str,
|
||||
前一结束位置_str,
|
||||
if self.短路修正 { "True" } else { "False" },
|
||||
if self.短路修正.load(Ordering::Relaxed) { "True" } else { "False" },
|
||||
)
|
||||
}
|
||||
|
||||
// ---- 关联函数(静态工厂方法) ----
|
||||
|
||||
/// 创建笔
|
||||
pub fn 创建笔(文: Rc<分型>, 武: Rc<分型>, 有效性: bool) -> Self {
|
||||
pub fn 创建笔(文: Arc<分型>, 武: Arc<分型>, 有效性: bool) -> Self {
|
||||
Self::new(0, "笔".into(), 文, 武, 1, 有效性)
|
||||
}
|
||||
|
||||
/// 创建线段
|
||||
pub fn 创建线段(虚线序列: &[Rc<虚线>]) -> Self {
|
||||
let 文 = Rc::clone(&虚线序列[0].文);
|
||||
let 武 = Rc::clone(&虚线序列[虚线序列.len() - 1].武);
|
||||
let 标识 = if 虚线序列[0].标识 == "笔" {
|
||||
pub fn 创建线段(虚线序列: &[Arc<虚线>]) -> Self {
|
||||
let 文 = Arc::clone(&虚线序列[0].文);
|
||||
let 武 = Arc::clone(&*虚线序列[虚线序列.len() - 1].武.read().unwrap());
|
||||
assert!(
|
||||
文.结构 != 武.结构,
|
||||
"创建线段: 文.结构 == 武.结构 文={}, 武={}",
|
||||
文,
|
||||
武
|
||||
);
|
||||
let 标识: String = if *虚线序列[0].标识.read().unwrap() == "笔" {
|
||||
"线段".into()
|
||||
} else {
|
||||
format!("线段<{}>", 虚线序列[0].标识)
|
||||
format!("线段<{}>", 虚线序列[0].标识.read().unwrap())
|
||||
};
|
||||
let 级别 = 虚线序列[0].级别 + 1;
|
||||
let mut 段 = Self::new(0, 标识, 文, 武, 级别, true);
|
||||
段.基础序列 = 虚线序列.to_vec();
|
||||
段.模式 = "文武".into();
|
||||
let 级别 = 虚线序列[0].级别.load(Ordering::Relaxed) + 1;
|
||||
let 段 = Self::new(0, 标识, 文, 武, 级别, true);
|
||||
*段.基础序列.write().unwrap() = 虚线序列.to_vec();
|
||||
*段.模式.write().unwrap() = "文武".into();
|
||||
段
|
||||
}
|
||||
|
||||
@@ -383,8 +432,12 @@ impl 虚线 {
|
||||
// ---- MACD柱子均值计算 ----
|
||||
|
||||
/// 计算MACD柱子均值 — 虚线范围内所有MACD柱的绝对值均值
|
||||
pub fn 计算MACD柱子均值(普K序列: &[Rc<K线>], 实线: &虚线) -> f64 {
|
||||
let K线序列 = K线::截取rc(普K序列, &实线.文.中.标的K线, &实线.武.中.标的K线);
|
||||
pub fn 计算MACD柱子均值(普K序列: &[Arc<K线>], 实线: &虚线) -> f64 {
|
||||
let K线序列 = K线::截取rc(
|
||||
普K序列,
|
||||
&实线.文.中.标的K线.read().unwrap(),
|
||||
&实线.武.read().unwrap().中.标的K线.read().unwrap(),
|
||||
);
|
||||
if K线序列.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
@@ -397,8 +450,12 @@ impl 虚线 {
|
||||
}
|
||||
|
||||
/// 计算MACD柱子均值_阴 — 负柱的绝对值均值
|
||||
pub fn 计算MACD柱子均值_阴(普K序列: &[Rc<K线>], 实线: &虚线) -> Option<f64> {
|
||||
let K线序列 = K线::截取rc(普K序列, &实线.文.中.标的K线, &实线.武.中.标的K线);
|
||||
pub fn 计算MACD柱子均值_阴(普K序列: &[Arc<K线>], 实线: &虚线) -> Option<f64> {
|
||||
let K线序列 = K线::截取rc(
|
||||
普K序列,
|
||||
&实线.文.中.标的K线.read().unwrap(),
|
||||
&实线.武.read().unwrap().中.标的K线.read().unwrap(),
|
||||
);
|
||||
let 总: Vec<f64> = K线序列
|
||||
.iter()
|
||||
.filter_map(|k| k.macd.as_ref())
|
||||
@@ -413,8 +470,12 @@ impl 虚线 {
|
||||
}
|
||||
|
||||
/// 计算MACD柱子均值_阳 — 正柱的绝对值均值
|
||||
pub fn 计算MACD柱子均值_阳(普K序列: &[Rc<K线>], 实线: &虚线) -> Option<f64> {
|
||||
let K线序列 = K线::截取rc(普K序列, &实线.文.中.标的K线, &实线.武.中.标的K线);
|
||||
pub fn 计算MACD柱子均值_阳(普K序列: &[Arc<K线>], 实线: &虚线) -> Option<f64> {
|
||||
let K线序列 = K线::截取rc(
|
||||
普K序列,
|
||||
&实线.文.中.标的K线.read().unwrap(),
|
||||
&实线.武.read().unwrap().中.标的K线.read().unwrap(),
|
||||
);
|
||||
let 总: Vec<f64> = K线序列
|
||||
.iter()
|
||||
.filter_map(|k| k.macd.as_ref())
|
||||
@@ -431,8 +492,10 @@ impl 虚线 {
|
||||
// ---- 武之MACD比较 ----
|
||||
|
||||
/// 武之全量MACD均值 — 武端MACD柱是否小于均值(背驰)
|
||||
pub fn 武之全量MACD均值(普K序列: &[Rc<K线>], 实线: &虚线) -> bool {
|
||||
let 武_MACD = match &实线.武.中.标的K线.macd {
|
||||
pub fn 武之全量MACD均值(普K序列: &[Arc<K线>], 实线: &虚线) -> bool {
|
||||
let 武_ref = 实线.武.read().unwrap();
|
||||
let 标 = 武_ref.中.标的K线.read().unwrap();
|
||||
let 武_MACD = match 标.macd.as_ref() {
|
||||
Some(m) => m.MACD柱.abs(),
|
||||
None => return false,
|
||||
};
|
||||
@@ -440,7 +503,7 @@ impl 虚线 {
|
||||
}
|
||||
|
||||
/// 武之MACD均值 — 按方向选择阴/阳均值比对
|
||||
pub fn 武之MACD均值(普K序列: &[Rc<K线>], 实线: &虚线) -> bool {
|
||||
pub fn 武之MACD均值(普K序列: &[Arc<K线>], 实线: &虚线) -> bool {
|
||||
if 实线.方向() == 相对方向::向上 {
|
||||
Self::武之MACD均值_阳(普K序列, 实线)
|
||||
} else {
|
||||
@@ -449,8 +512,10 @@ impl 虚线 {
|
||||
}
|
||||
|
||||
/// 武之MACD均值_阴 — 武端负柱是否小于阴均值
|
||||
pub fn 武之MACD均值_阴(普K序列: &[Rc<K线>], 实线: &虚线) -> bool {
|
||||
let 武_MACD = match &实线.武.中.标的K线.macd {
|
||||
pub fn 武之MACD均值_阴(普K序列: &[Arc<K线>], 实线: &虚线) -> bool {
|
||||
let 武_ref = 实线.武.read().unwrap();
|
||||
let 标 = 武_ref.中.标的K线.read().unwrap();
|
||||
let 武_MACD = match 标.macd.as_ref() {
|
||||
Some(m) => m.MACD柱.abs(),
|
||||
None => return false,
|
||||
};
|
||||
@@ -461,8 +526,10 @@ impl 虚线 {
|
||||
}
|
||||
|
||||
/// 武之MACD均值_阳 — 武端正柱是否小于阳均值
|
||||
pub fn 武之MACD均值_阳(普K序列: &[Rc<K线>], 实线: &虚线) -> bool {
|
||||
let 武_MACD = match &实线.武.中.标的K线.macd {
|
||||
pub fn 武之MACD均值_阳(普K序列: &[Arc<K线>], 实线: &虚线) -> bool {
|
||||
let 武_ref = 实线.武.read().unwrap();
|
||||
let 标 = 武_ref.中.标的K线.read().unwrap();
|
||||
let 武_MACD = match 标.macd.as_ref() {
|
||||
Some(m) => m.MACD柱.abs(),
|
||||
None => return false,
|
||||
};
|
||||
@@ -473,12 +540,18 @@ impl 虚线 {
|
||||
}
|
||||
|
||||
/// 武之MACD极值 — 武端MACD柱是否为区间极值
|
||||
pub fn 武之MACD极值(普K序列: &[Rc<K线>], 实线: &虚线) -> bool {
|
||||
let 武_MACD = match &实线.武.中.标的K线.macd {
|
||||
pub fn 武之MACD极值(普K序列: &[Arc<K线>], 实线: &虚线) -> bool {
|
||||
let 武_ref = 实线.武.read().unwrap();
|
||||
let 标 = 武_ref.中.标的K线.read().unwrap();
|
||||
let 武_MACD = match 标.macd.as_ref() {
|
||||
Some(m) => m.MACD柱,
|
||||
None => return false,
|
||||
};
|
||||
let K线序列 = K线::截取rc(普K序列, &实线.文.中.标的K线, &实线.武.中.标的K线);
|
||||
let K线序列 = K线::截取rc(
|
||||
普K序列,
|
||||
&实线.文.中.标的K线.read().unwrap(),
|
||||
&实线.武.read().unwrap().中.标的K线.read().unwrap(),
|
||||
);
|
||||
let 所有柱子: Vec<f64> = K线序列
|
||||
.iter()
|
||||
.filter_map(|k| k.macd.as_ref())
|
||||
@@ -500,7 +573,7 @@ impl 虚线 {
|
||||
|
||||
/// 计算K线序列MACD趋向背驰 — 分析 MACD柱/DIF/DEA 三项背驰信号
|
||||
pub fn 计算K线序列MACD趋向背驰(
|
||||
普K序列: &[Rc<K线>], 方向: 相对方向
|
||||
普K序列: &[Arc<K线>], 方向: 相对方向
|
||||
) -> [bool; 3] {
|
||||
if 普K序列.is_empty() {
|
||||
return [false, false, false];
|
||||
@@ -508,9 +581,9 @@ impl 虚线 {
|
||||
let 最后 = &普K序列[普K序列.len() - 1];
|
||||
|
||||
if 方向 == 相对方向::向上 {
|
||||
let 柱子序列: Vec<&Rc<K线>> = 普K序列
|
||||
let 柱子序列: Vec<&Arc<K线>> = 普K序列
|
||||
.iter()
|
||||
.filter(|k| k.macd.as_ref().map_or(false, |m| m.MACD柱 > 0.0))
|
||||
.filter(|k| k.macd.as_ref().is_some_and(|m| m.MACD柱 > 0.0))
|
||||
.collect();
|
||||
if 柱子序列.is_empty() {
|
||||
return [false, false, false];
|
||||
@@ -530,7 +603,7 @@ impl 虚线 {
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
})
|
||||
.unwrap();
|
||||
let mut 柱对 = vec![Rc::clone(*最高柱子), Rc::clone(最后)];
|
||||
let mut 柱对 = [Arc::clone(*最高柱子), Arc::clone(最后)];
|
||||
柱对.sort_by_key(|k| k.时间戳);
|
||||
if let (Some(m0), Some(m1)) = (柱对[0].macd.as_ref(), 柱对[1].macd.as_ref()) {
|
||||
if m0.MACD柱 > m1.MACD柱 && 柱对[0].高 < 柱对[1].高 {
|
||||
@@ -574,9 +647,9 @@ impl 虚线 {
|
||||
|
||||
结果
|
||||
} else {
|
||||
let 柱子序列: Vec<&Rc<K线>> = 普K序列
|
||||
let 柱子序列: Vec<&Arc<K线>> = 普K序列
|
||||
.iter()
|
||||
.filter(|k| k.macd.as_ref().map_or(false, |m| m.MACD柱 < 0.0))
|
||||
.filter(|k| k.macd.as_ref().is_some_and(|m| m.MACD柱 < 0.0))
|
||||
.collect();
|
||||
if 柱子序列.is_empty() {
|
||||
return [false, false, false];
|
||||
@@ -597,7 +670,7 @@ impl 虚线 {
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
})
|
||||
.unwrap();
|
||||
let mut 柱对 = vec![Rc::clone(*最高柱子), Rc::clone(最后)];
|
||||
let mut 柱对 = [Arc::clone(*最高柱子), Arc::clone(最后)];
|
||||
柱对.sort_by_key(|k| k.时间戳);
|
||||
if let (Some(m0), Some(m1)) = (柱对[0].macd.as_ref(), 柱对[1].macd.as_ref()) {
|
||||
if m0.MACD柱 < m1.MACD柱 && 柱对[0].低 > 柱对[1].低 {
|
||||
@@ -646,7 +719,7 @@ impl 虚线 {
|
||||
// ---- MACD柱子分段 ----
|
||||
|
||||
/// 计算MACD柱子分段 — 按正负号将MACD柱子分段
|
||||
pub fn 计算MACD柱子分段(k线序列: &[Rc<K线>]) -> Vec<Vec<f64>> {
|
||||
pub fn 计算MACD柱子分段(k线序列: &[Arc<K线>]) -> Vec<Vec<f64>> {
|
||||
if k线序列.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
@@ -729,7 +802,7 @@ impl 虚线 {
|
||||
|
||||
/// 统计MACD行为 — 分析DIF/DEA穿零轴和金叉死叉
|
||||
pub fn 统计MACD行为(
|
||||
普K序列: &[Rc<K线>],
|
||||
普K序列: &[Arc<K线>],
|
||||
最大间隔: usize,
|
||||
最少交叉数: usize,
|
||||
) -> MACD行为统计 {
|
||||
@@ -820,34 +893,39 @@ impl 虚线 {
|
||||
let 普K序列 = &观察员.普通K线序列;
|
||||
let 配置 = &观察员.配置;
|
||||
|
||||
if 实线.标识 != "笔" && 实线.标识 != "线段" && !实线.标识.starts_with("线段<")
|
||||
if *实线.标识.read().unwrap() != "笔"
|
||||
&& *实线.标识.read().unwrap() != "线段"
|
||||
&& !实线.标识.read().unwrap().starts_with("线段<")
|
||||
{
|
||||
return (false, "标识不在范围内".into());
|
||||
}
|
||||
|
||||
// KDJ指标完整性检查
|
||||
match &实线.武.中.标的K线.kdj {
|
||||
let 武_ref = 实线.武.read().unwrap();
|
||||
let 标 = 武_ref.中.标的K线.read().unwrap();
|
||||
match 标.kdj.as_ref() {
|
||||
Some(kdj) if kdj.K.is_some() && kdj.D.is_some() && kdj.J.is_some() => {}
|
||||
_ => return (false, "KDJ指标不完整".into()),
|
||||
}
|
||||
|
||||
let 意义 = Self::缠K买卖点模式(&配置.买卖点_指标模式, &实线.武.中, 配置);
|
||||
let 意义 =
|
||||
Self::缠K买卖点模式(&配置.买卖点_指标模式, &实线.武.read().unwrap().中, 配置);
|
||||
let 结果 = false;
|
||||
|
||||
let 背驰过: Vec<Rc<缠论K线>> = if 实线.标识 == "笔" {
|
||||
let 背驰过: Vec<Arc<缠论K线>> = if *实线.标识.read().unwrap() == "笔" {
|
||||
crate::algorithm::bi::笔::是否背驰过(实线, 观察员)
|
||||
} else {
|
||||
crate::algorithm::segment::线段::是否背驰过(实线, 观察员)
|
||||
};
|
||||
|
||||
if 意义 {
|
||||
if 实线.标识 == "笔" {
|
||||
if *实线.标识.read().unwrap() == "笔" {
|
||||
if Self::武之MACD均值(普K序列, 实线) {
|
||||
return (true, "武之MACD均值".into());
|
||||
}
|
||||
if Self::武之MACD极值(普K序列, 实线) && !背驰过.is_empty() {
|
||||
return (true, "背驰过且极值".into());
|
||||
} else if 实线.武.与MACD柱子分型匹配() {
|
||||
} else if 实线.武.read().unwrap().与MACD柱子分型匹配() {
|
||||
return (
|
||||
true,
|
||||
format!(
|
||||
@@ -862,17 +940,20 @@ impl 虚线 {
|
||||
);
|
||||
}
|
||||
}
|
||||
if 实线.标识 != "笔"
|
||||
if *实线.标识.read().unwrap() != "笔"
|
||||
&& crate::algorithm::segment::线段::判断线段内部是否背驰(实线, 观察员)
|
||||
{
|
||||
return (true, "线段内部背驰".into());
|
||||
}
|
||||
}
|
||||
|
||||
if !结果 && 意义 && 实线.武.中.与MACD柱子匹配() {
|
||||
if Self::武之MACD极值(普K序列, 实线) && 背驰过.len() > 2 {
|
||||
return (true, "没结果, 极值, 柱子分型匹配, 背驰过大于2次".into());
|
||||
}
|
||||
if !结果
|
||||
&& 意义
|
||||
&& 实线.武.read().unwrap().中.与MACD柱子匹配()
|
||||
&& Self::武之MACD极值(普K序列, 实线)
|
||||
&& 背驰过.len() > 2
|
||||
{
|
||||
return (true, "没结果, 极值, 柱子分型匹配, 背驰过大于2次".into());
|
||||
}
|
||||
|
||||
(结果, "".into())
|
||||
@@ -881,16 +962,18 @@ impl 虚线 {
|
||||
|
||||
impl std::fmt::Display for 虚线 {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
if self.标识 == "笔" {
|
||||
if *self.标识.read().unwrap() == "笔" {
|
||||
write!(
|
||||
f,
|
||||
"笔({}, {}, {}, {}, 周期: {}, 数量: {})",
|
||||
self.序号,
|
||||
self.序号.load(Ordering::Relaxed),
|
||||
self.方向(),
|
||||
self.文,
|
||||
self.武,
|
||||
self.武.read().unwrap(),
|
||||
self.文.中.周期,
|
||||
self.武.中.序号 - self.文.中.序号 + 1
|
||||
self.武.read().unwrap().中.序号.load(Ordering::Relaxed)
|
||||
- self.文.中.序号.load(Ordering::Relaxed)
|
||||
+ 1
|
||||
)
|
||||
} else {
|
||||
let 四象 = crate::algorithm::segment::线段::四象(self);
|
||||
@@ -899,23 +982,304 @@ impl std::fmt::Display for 虚线 {
|
||||
Some(g) => format!("{}", g),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
let 确认K线_str = match &self.确认K线 {
|
||||
let 确认K线_str = match &*self.确认K线.read().unwrap() {
|
||||
Some(k) => format!("{}", k),
|
||||
None => "None".to_string(),
|
||||
};
|
||||
write!(
|
||||
f,
|
||||
"{}<{}, {}, {}, {}, {}, 数量: {}, 缺口: {}, {}>",
|
||||
self.标识,
|
||||
self.序号,
|
||||
self.标识.read().unwrap(),
|
||||
self.序号.load(Ordering::Relaxed),
|
||||
四象,
|
||||
self.方向(),
|
||||
self.文,
|
||||
self.武,
|
||||
self.基础序列.len(),
|
||||
self.武.read().unwrap(),
|
||||
self.基础序列.read().unwrap().len(),
|
||||
缺口_str,
|
||||
确认K线_str,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::kline::bar::K线;
|
||||
use crate::kline::chan_kline::缠论K线;
|
||||
use crate::types::分型结构;
|
||||
|
||||
/// 辅助:创建一根最小化的原始K线
|
||||
fn 辅助_创建K线(时间戳: i64, 高: f64, 低: f64, 开: f64, 收: f64) -> K线 {
|
||||
K线 {
|
||||
时间戳,
|
||||
高,
|
||||
低,
|
||||
开盘价: 开,
|
||||
收盘价: 收,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// 辅助:创建一根缠论K线
|
||||
fn 辅助_创建缠K(
|
||||
时间戳: i64,
|
||||
高: f64,
|
||||
低: f64,
|
||||
方向: 相对方向,
|
||||
结构: Option<分型结构>,
|
||||
序号: i64,
|
||||
) -> Arc<缠论K线> {
|
||||
let 普K = Arc::new(辅助_创建K线(时间戳, 高, 低, 低, 高));
|
||||
let 缠K = 缠论K线::创建缠K(时间戳, 高, 低, 方向, 结构, 序号, 普K, None);
|
||||
Arc::new(缠K)
|
||||
}
|
||||
|
||||
/// 辅助:创建顶分型
|
||||
fn 辅助_创建顶分型(时间戳: i64, 高: f64, 低: f64, 序号: i64) -> Arc<分型> {
|
||||
let 左 = 辅助_创建缠K(
|
||||
时间戳 - 2,
|
||||
高 - 2.0,
|
||||
低 - 2.0,
|
||||
相对方向::向上,
|
||||
Some(分型结构::上),
|
||||
序号 - 2,
|
||||
);
|
||||
let 中 = 辅助_创建缠K(时间戳, 高, 低, 相对方向::向上, Some(分型结构::顶), 序号);
|
||||
let 右 = 辅助_创建缠K(
|
||||
时间戳 + 2,
|
||||
高 - 1.0,
|
||||
低 - 1.0,
|
||||
相对方向::向下,
|
||||
Some(分型结构::下),
|
||||
序号 + 2,
|
||||
);
|
||||
Arc::new(分型::new(Some(左), 中, Some(右)))
|
||||
}
|
||||
|
||||
/// 辅助:创建底分型
|
||||
fn 辅助_创建底分型(时间戳: i64, 高: f64, 低: f64, 序号: i64) -> Arc<分型> {
|
||||
let 左 = 辅助_创建缠K(
|
||||
时间戳 - 2,
|
||||
高 + 2.0,
|
||||
低 + 2.0,
|
||||
相对方向::向下,
|
||||
Some(分型结构::下),
|
||||
序号 - 2,
|
||||
);
|
||||
let 中 = 缠论K线::创建缠K(
|
||||
时间戳,
|
||||
高,
|
||||
低,
|
||||
相对方向::向下,
|
||||
Some(分型结构::底),
|
||||
序号,
|
||||
Arc::new(辅助_创建K线(时间戳, 高, 低, 低, 高)),
|
||||
None,
|
||||
);
|
||||
中.分型特征值.set(低);
|
||||
let 中 = Arc::new(中);
|
||||
let 右 = 辅助_创建缠K(
|
||||
时间戳 + 2,
|
||||
高 + 1.0,
|
||||
低 + 1.0,
|
||||
相对方向::向上,
|
||||
Some(分型结构::上),
|
||||
序号 + 2,
|
||||
);
|
||||
Arc::new(分型::new(Some(左), 中, Some(右)))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Cell 字段读写测试
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_Cell字段读写一致性() {
|
||||
let 顶 = 辅助_创建顶分型(100, 50.0, 40.0, 5);
|
||||
let 底 = 辅助_创建底分型(200, 30.0, 20.0, 10);
|
||||
let 笔 = 虚线::创建笔(顶, 底, true);
|
||||
|
||||
assert_eq!(笔.序号.load(Ordering::Relaxed), 0);
|
||||
assert!(笔.有效性.load(Ordering::Relaxed));
|
||||
assert!(!笔.短路修正.load(Ordering::Relaxed));
|
||||
assert!(笔.前一缺口.read().unwrap().is_none());
|
||||
|
||||
// 修改 Cell 字段
|
||||
笔.序号.store(42, Ordering::Relaxed);
|
||||
笔.有效性.store(false, Ordering::Relaxed);
|
||||
笔.短路修正.store(true, Ordering::Relaxed);
|
||||
*笔.前一缺口.write().unwrap() = Some(缺口::new(200.0, 100.0));
|
||||
|
||||
assert_eq!(笔.序号.load(Ordering::Relaxed), 42);
|
||||
assert!(!笔.有效性.load(Ordering::Relaxed));
|
||||
assert!(笔.短路修正.load(Ordering::Relaxed));
|
||||
let qk = 笔.前一缺口.read().unwrap().unwrap();
|
||||
assert!((qk.高 - 200.0).abs() < 0.01);
|
||||
assert!((qk.低 - 100.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// RefCell 字段读写测试
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_RefCell字段读写一致性() {
|
||||
let 顶 = 辅助_创建顶分型(100, 50.0, 40.0, 5);
|
||||
let 底 = 辅助_创建底分型(200, 30.0, 20.0, 10);
|
||||
let 笔 = 虚线::创建笔(顶, 底, true);
|
||||
|
||||
// 标识
|
||||
assert_eq!(*笔.标识.read().unwrap(), "笔");
|
||||
*笔.标识.write().unwrap() = "测试标识".into();
|
||||
assert_eq!(*笔.标识.read().unwrap(), "测试标识");
|
||||
|
||||
// 模式
|
||||
assert_eq!(*笔.模式.read().unwrap(), "文武");
|
||||
*笔.模式.write().unwrap() = "全量".into();
|
||||
assert_eq!(*笔.模式.read().unwrap(), "全量");
|
||||
|
||||
// 基础序列
|
||||
assert!(笔.基础序列.read().unwrap().is_empty());
|
||||
let 另一底 = 辅助_创建底分型(300, 20.0, 10.0, 15);
|
||||
let 笔2 = 虚线::创建笔(Arc::clone(&*笔.武.read().unwrap()), 另一底, true);
|
||||
笔.基础序列.write().unwrap().push(Arc::new(笔2));
|
||||
assert_eq!(笔.基础序列.read().unwrap().len(), 1);
|
||||
|
||||
// 武 - Replace with new 分型
|
||||
let 新底 = 辅助_创建底分型(400, 15.0, 5.0, 20);
|
||||
let 新底_ptr = Arc::as_ptr(&新底);
|
||||
*笔.武.write().unwrap() = Arc::clone(&新底);
|
||||
assert_eq!(Arc::as_ptr(&*笔.武.read().unwrap()), 新底_ptr);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// Clone 后 Rc 指针身份一致
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_虚线Clone后文Rc指针一致() {
|
||||
let 顶 = 辅助_创建顶分型(100, 50.0, 40.0, 5);
|
||||
let 底 = 辅助_创建底分型(200, 30.0, 20.0, 10);
|
||||
let 笔 = 虚线::创建笔(Arc::clone(&顶), Arc::clone(&底), true);
|
||||
|
||||
let 克隆笔 = 笔.clone();
|
||||
|
||||
// 文 Rc 指针应一致
|
||||
assert_eq!(Arc::as_ptr(&笔.文), Arc::as_ptr(&顶));
|
||||
assert_eq!(Arc::as_ptr(&克隆笔.文), Arc::as_ptr(&笔.文));
|
||||
|
||||
// 武 Rc 指针应一致
|
||||
assert_eq!(Arc::as_ptr(&*笔.武.read().unwrap()), Arc::as_ptr(&底));
|
||||
assert_eq!(
|
||||
Arc::as_ptr(&*克隆笔.武.read().unwrap()),
|
||||
Arc::as_ptr(&*笔.武.read().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_虚线Clone是深拷贝Cell值而非共享() {
|
||||
let 顶 = 辅助_创建顶分型(100, 50.0, 40.0, 5);
|
||||
let 底 = 辅助_创建底分型(200, 30.0, 20.0, 10);
|
||||
let 笔 = 虚线::创建笔(顶, 底, true);
|
||||
笔.序号.store(10, Ordering::Relaxed);
|
||||
|
||||
let 克隆笔 = 笔.clone();
|
||||
// Clone 后序号应独立(deep copy for Cell)
|
||||
克隆笔.序号.store(99, Ordering::Relaxed);
|
||||
assert_eq!(笔.序号.load(Ordering::Relaxed), 10);
|
||||
assert_eq!(克隆笔.序号.load(Ordering::Relaxed), 99);
|
||||
|
||||
// Rc 指针仍应一致(文/武 共享)
|
||||
assert_eq!(Arc::as_ptr(&笔.文), Arc::as_ptr(&克隆笔.文));
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 多 Rc 共享下 Cell/RefCell 修改可见性
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_多Rc共享下Cell修改对所有引用可见() {
|
||||
let 顶 = 辅助_创建顶分型(100, 50.0, 40.0, 5);
|
||||
let 底 = 辅助_创建底分型(200, 30.0, 20.0, 10);
|
||||
let 笔_rc1 = Arc::new(虚线::创建笔(顶, 底, true));
|
||||
let 笔_rc2 = Arc::clone(&笔_rc1);
|
||||
|
||||
// 通过 rc1 修改 Cell
|
||||
笔_rc1.序号.store(77, Ordering::Relaxed);
|
||||
// rc2 应能看到
|
||||
assert_eq!(笔_rc2.序号.load(Ordering::Relaxed), 77);
|
||||
|
||||
// 通过 rc1 修改 RefCell
|
||||
*笔_rc1.模式.write().unwrap() = "配置".into();
|
||||
assert_eq!(*笔_rc2.模式.read().unwrap(), "配置");
|
||||
|
||||
// 通过 rc1 修改 武
|
||||
let 新底 = 辅助_创建底分型(400, 15.0, 5.0, 20);
|
||||
let 新底_ptr = Arc::as_ptr(&新底);
|
||||
*笔_rc1.武.write().unwrap() = Arc::clone(&新底);
|
||||
assert_eq!(Arc::as_ptr(&*笔_rc2.武.read().unwrap()), 新底_ptr);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 获取_武 递归正确性
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_获取武_笔级别直接返回武() {
|
||||
let 顶 = 辅助_创建顶分型(100, 50.0, 40.0, 5);
|
||||
let 底 = 辅助_创建底分型(200, 30.0, 20.0, 10);
|
||||
let 笔 = 虚线::创建笔(Arc::clone(&顶), Arc::clone(&底), true);
|
||||
|
||||
let wu = 笔.获取_武();
|
||||
assert_eq!(Arc::as_ptr(&*笔.武.read().unwrap()), Arc::as_ptr(&wu));
|
||||
assert_eq!(Arc::as_ptr(&wu), Arc::as_ptr(&底));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_获取武_线段级别递归到底层笔() {
|
||||
let 顶1 = 辅助_创建顶分型(100, 50.0, 40.0, 5);
|
||||
let 底1 = 辅助_创建底分型(200, 30.0, 20.0, 10);
|
||||
let 顶2 = 辅助_创建顶分型(300, 55.0, 45.0, 15);
|
||||
let 底2 = 辅助_创建底分型(400, 25.0, 15.0, 20);
|
||||
|
||||
let 笔1 = Arc::new(虚线::创建笔(Arc::clone(&顶1), Arc::clone(&底1), true));
|
||||
let 笔2 = Arc::new(虚线::创建笔(Arc::clone(&底1), Arc::clone(&顶2), true));
|
||||
let 笔3 = Arc::new(虚线::创建笔(Arc::clone(&顶2), Arc::clone(&底2), true));
|
||||
|
||||
let 段 = 虚线::创建线段(&[Arc::clone(&笔1), Arc::clone(&笔2), Arc::clone(&笔3)]);
|
||||
|
||||
// 线段的 获取_武 应返回底层最后一笔的武(底2)
|
||||
let wu = 段.获取_武();
|
||||
assert_eq!(Arc::as_ptr(&wu), Arc::as_ptr(&底2));
|
||||
|
||||
// 笔1 的 获取_武 应返回底1
|
||||
let wu1 = 笔1.获取_武();
|
||||
assert_eq!(Arc::as_ptr(&wu1), Arc::as_ptr(&底1));
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 虚线 字段原子性 - 修改不影响文(不可变字段)
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_修改武不影响文Rc指针() {
|
||||
let 顶 = 辅助_创建顶分型(100, 50.0, 40.0, 5);
|
||||
let 底1 = 辅助_创建底分型(200, 30.0, 20.0, 10);
|
||||
let 底2 = 辅助_创建底分型(300, 25.0, 15.0, 15);
|
||||
|
||||
let 笔 = 虚线::创建笔(Arc::clone(&顶), Arc::clone(&底1), true);
|
||||
let 文_ptr_before = Arc::as_ptr(&笔.文);
|
||||
|
||||
// 修改武
|
||||
*笔.武.write().unwrap() = Arc::clone(&底2);
|
||||
|
||||
// 文指针不变
|
||||
assert_eq!(Arc::as_ptr(&笔.文), 文_ptr_before);
|
||||
|
||||
// 但方向变了(因为武从底1变成底2)
|
||||
let 新武耗时 = 笔.武.read().unwrap().时间戳();
|
||||
assert_eq!(新武耗时, 300);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,20 +24,20 @@
|
||||
|
||||
use crate::structure::segment_feat::线段特征;
|
||||
use crate::types::分型结构;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// 特征分型 — 由三个线段特征元素构成的分型
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct 特征分型 {
|
||||
pub 左: Rc<线段特征>,
|
||||
pub 中: Rc<线段特征>,
|
||||
pub 右: Rc<线段特征>,
|
||||
pub 左: Arc<线段特征>,
|
||||
pub 中: Arc<线段特征>,
|
||||
pub 右: Arc<线段特征>,
|
||||
pub 结构: 分型结构,
|
||||
}
|
||||
|
||||
impl 特征分型 {
|
||||
pub fn new(
|
||||
左: Rc<线段特征>, 中: Rc<线段特征>, 右: Rc<线段特征>, 结构: 分型结构
|
||||
左: Arc<线段特征>, 中: Arc<线段特征>, 右: Arc<线段特征>, 结构: 分型结构
|
||||
) -> Self {
|
||||
Self {
|
||||
左, 中, 右, 结构
|
||||
|
||||
@@ -25,14 +25,19 @@
|
||||
use crate::kline::chan_kline::缠论K线;
|
||||
use crate::types::分型结构;
|
||||
use crate::types::相对方向;
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// 分型模式 — True 时使用构造时缓存值(默认),False 时从 中 缠K 实时读取
|
||||
pub static 分型模式: AtomicBool = AtomicBool::new(true);
|
||||
|
||||
/// 分型 — 由三根缠K构成(可能缺左或右)
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct 分型 {
|
||||
pub 左: Option<Rc<缠论K线>>,
|
||||
pub 中: Rc<缠论K线>,
|
||||
pub 右: Option<Rc<缠论K线>>,
|
||||
pub 左: Option<Arc<缠论K线>>,
|
||||
pub 中: Arc<缠论K线>,
|
||||
pub 右: Option<Arc<缠论K线>>,
|
||||
pub 结构: 分型结构,
|
||||
pub 时间戳: i64,
|
||||
pub 分型特征值: f64,
|
||||
@@ -40,11 +45,11 @@ pub struct 分型 {
|
||||
|
||||
impl 分型 {
|
||||
pub fn new(
|
||||
左: Option<Rc<缠论K线>>, 中: Rc<缠论K线>, 右: Option<Rc<缠论K线>>
|
||||
左: Option<Arc<缠论K线>>, 中: Arc<缠论K线>, 右: Option<Arc<缠论K线>>
|
||||
) -> Self {
|
||||
let 结构 = 中.分型.unwrap_or(分型结构::散);
|
||||
let 时间戳 = 中.时间戳;
|
||||
let 分型特征值 = 中.分型特征值;
|
||||
let 结构 = 中.分型.read().unwrap().unwrap_or(分型结构::散);
|
||||
let 时间戳 = 中.时间戳.load(Ordering::Relaxed);
|
||||
let 分型特征值 = 中.分型特征值.get();
|
||||
Self {
|
||||
左,
|
||||
中,
|
||||
@@ -55,14 +60,23 @@ impl 分型 {
|
||||
}
|
||||
}
|
||||
|
||||
/// 时间戳 — 根据 分型模式 决定返回缓存值(True)或实时值(False)
|
||||
pub fn 时间戳(&self) -> i64 {
|
||||
if 分型模式.load(Ordering::Relaxed) {
|
||||
self.时间戳
|
||||
} else {
|
||||
self.中.时间戳.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
/// 左中右三组关系
|
||||
pub fn 关系组(&self) -> Option<(相对方向, 相对方向, 相对方向)> {
|
||||
let 左 = self.左.as_ref()?;
|
||||
let 右 = self.右.as_ref()?;
|
||||
Some((
|
||||
相对方向::分析(左.高, 左.低, self.中.高, self.中.低),
|
||||
相对方向::分析(self.中.高, self.中.低, 右.高, 右.低),
|
||||
相对方向::分析(左.高, 左.低, 右.高, 右.低),
|
||||
相对方向::分析(左.高.get(), 左.低.get(), self.中.高.get(), self.中.低.get()),
|
||||
相对方向::分析(self.中.高.get(), self.中.低.get(), 右.高.get(), 右.低.get()),
|
||||
相对方向::分析(左.高.get(), 左.低.get(), 右.高.get(), 右.低.get()),
|
||||
))
|
||||
}
|
||||
|
||||
@@ -97,17 +111,19 @@ impl 分型 {
|
||||
|
||||
if let (Some(ref 左), Some(ref 右)) = (&self.左, &self.右) {
|
||||
if self.结构 == 分型结构::底 {
|
||||
if 右.标的K线.收盘价 > 左.标的K线.高 {
|
||||
if 右.标的K线.read().unwrap().收盘价 > 左.标的K线.read().unwrap().高 {
|
||||
return "强";
|
||||
} else if 右.标的K线.收盘价 > self.中.标的K线.高 {
|
||||
} else if 右.标的K线.read().unwrap().收盘价 > self.中.标的K线.read().unwrap().高
|
||||
{
|
||||
return "中";
|
||||
} else {
|
||||
return "弱";
|
||||
}
|
||||
} else if self.结构 == 分型结构::顶 {
|
||||
if 右.标的K线.收盘价 < 左.标的K线.低 {
|
||||
if 右.标的K线.read().unwrap().收盘价 < 左.标的K线.read().unwrap().低 {
|
||||
return "强";
|
||||
} else if 右.标的K线.收盘价 < self.中.标的K线.低 {
|
||||
} else if 右.标的K线.read().unwrap().收盘价 < self.中.标的K线.read().unwrap().低
|
||||
{
|
||||
return "中";
|
||||
} else {
|
||||
return "弱";
|
||||
@@ -121,15 +137,21 @@ impl 分型 {
|
||||
pub fn 与MACD柱子分型匹配(&self) -> bool {
|
||||
if let (Some(ref 左), Some(ref 右)) = (&self.左, &self.右) {
|
||||
if self.结构 == 分型结构::底 {
|
||||
let 左_k = 左.标的K线.read().unwrap();
|
||||
let 中_k = self.中.标的K线.read().unwrap();
|
||||
let 右_k = 右.标的K线.read().unwrap();
|
||||
if let (Some(ref 左macd), Some(ref 中macd), Some(ref 右macd)) =
|
||||
(&左.标的K线.macd, &self.中.标的K线.macd, &右.标的K线.macd)
|
||||
(&左_k.macd, &中_k.macd, &右_k.macd)
|
||||
{
|
||||
return 左macd.MACD柱 > 中macd.MACD柱 && 中macd.MACD柱 < 右macd.MACD柱;
|
||||
}
|
||||
}
|
||||
if self.结构 == 分型结构::顶 {
|
||||
let 左_k = 左.标的K线.read().unwrap();
|
||||
let 中_k = self.中.标的K线.read().unwrap();
|
||||
let 右_k = 右.标的K线.read().unwrap();
|
||||
if let (Some(ref 左macd), Some(ref 中macd), Some(ref 右macd)) =
|
||||
(&左.标的K线.macd, &self.中.标的K线.macd, &右.标的K线.macd)
|
||||
(&左_k.macd, &中_k.macd, &右_k.macd)
|
||||
{
|
||||
return 左macd.MACD柱 < 中macd.MACD柱 && 中macd.MACD柱 > 右macd.MACD柱;
|
||||
}
|
||||
@@ -139,35 +161,36 @@ impl 分型 {
|
||||
}
|
||||
|
||||
/// 判断两个分型是否匹配
|
||||
pub fn 判断分型(左: &Rc<分型>, 右: &Rc<分型>, 模式: &str) -> bool {
|
||||
pub fn 判断分型(左: &Arc<分型>, 右: &Arc<分型>, 模式: &str) -> bool {
|
||||
match 模式 {
|
||||
"中" => Rc::as_ptr(左) == Rc::as_ptr(右),
|
||||
"中" => Arc::as_ptr(左) == Arc::as_ptr(右),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// 从缠K序列中获取以指定缠K为中元素的分型
|
||||
pub fn 从缠K序列中获取分型(
|
||||
K线序列: &[Rc<缠论K线>], 中: &Rc<缠论K线>
|
||||
K线序列: &[Arc<缠论K线>],
|
||||
中: &Arc<缠论K线>,
|
||||
) -> Option<Self> {
|
||||
let idx = K线序列
|
||||
.iter()
|
||||
.position(|k| Rc::as_ptr(k) == Rc::as_ptr(中))?;
|
||||
.position(|k| Arc::as_ptr(k) == Arc::as_ptr(中))?;
|
||||
let 左 = if idx > 0 {
|
||||
Some(Rc::clone(&K线序列[idx - 1]))
|
||||
Some(Arc::clone(&K线序列[idx - 1]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let 右 = if idx + 1 < K线序列.len() {
|
||||
Some(Rc::clone(&K线序列[idx + 1]))
|
||||
Some(Arc::clone(&K线序列[idx + 1]))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
Some(Self::new(左, Rc::clone(中), 右))
|
||||
Some(Self::new(左, Arc::clone(中), 右))
|
||||
}
|
||||
|
||||
/// 向分型序列中添加新分型
|
||||
pub fn 向序列中添加(分型序列: &mut Vec<Rc<分型>>, 当前分型: Rc<分型>) {
|
||||
pub fn 向序列中添加(分型序列: &mut Vec<Arc<分型>>, 当前分型: Arc<分型>) {
|
||||
if 分型序列.is_empty() {
|
||||
if 当前分型.结构 != 分型结构::顶 && 当前分型.结构 != 分型结构::底
|
||||
{
|
||||
@@ -188,10 +211,10 @@ impl 分型 {
|
||||
|
||||
impl crate::types::fractal::有高低 for 分型 {
|
||||
fn 高(&self) -> f64 {
|
||||
self.中.高
|
||||
self.中.高.get()
|
||||
}
|
||||
fn 低(&self) -> f64 {
|
||||
self.中.低
|
||||
self.中.低.get()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,8 +223,12 @@ impl std::fmt::Display for 分型 {
|
||||
write!(
|
||||
f,
|
||||
"{}<{}, {}, None: {}, None: {}>",
|
||||
self.中.分型.unwrap_or(crate::types::分型结构::散),
|
||||
self.时间戳,
|
||||
self.中
|
||||
.分型
|
||||
.read()
|
||||
.unwrap()
|
||||
.unwrap_or(crate::types::分型结构::散),
|
||||
self.时间戳(),
|
||||
crate::utils::format_f64_g(self.分型特征值),
|
||||
if self.左.is_none() { "True" } else { "False" },
|
||||
if self.右.is_none() { "True" } else { "False" },
|
||||
|
||||
@@ -26,7 +26,8 @@ use crate::structure::dash_line::虚线;
|
||||
use crate::structure::feat_fractal::特征分型;
|
||||
use crate::structure::fractal_obj::分型;
|
||||
use crate::types::{分型结构, 相对方向};
|
||||
use std::rc::Rc;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// 线段特征 — 特征序列元素(内部是虚线的集合)
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -34,11 +35,11 @@ pub struct 线段特征 {
|
||||
pub 序号: i64,
|
||||
pub 标识: String,
|
||||
pub 线段方向: 相对方向,
|
||||
pub 元素: Vec<Rc<虚线>>,
|
||||
pub 元素: Vec<Arc<虚线>>,
|
||||
}
|
||||
|
||||
impl 线段特征 {
|
||||
pub fn new(标识: String, 基础序列: Vec<Rc<虚线>>, 线段方向: 相对方向) -> Self {
|
||||
pub fn new(标识: String, 基础序列: Vec<Arc<虚线>>, 线段方向: 相对方向) -> Self {
|
||||
Self {
|
||||
序号: 0,
|
||||
标识,
|
||||
@@ -53,7 +54,7 @@ impl 线段特征 {
|
||||
|
||||
/// 文 — 取特征序列元素中分型特征值最大/最小的文分型
|
||||
/// tiebreaker: later时间戳 wins when特征值 equal (matches Python)
|
||||
pub fn 文(&self) -> Rc<分型> {
|
||||
pub fn 文(&self) -> Arc<分型> {
|
||||
if self.线段方向.是否向上() {
|
||||
self.元素
|
||||
.iter()
|
||||
@@ -62,10 +63,10 @@ impl 线段特征 {
|
||||
.分型特征值
|
||||
.partial_cmp(&b.文.分型特征值)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
.then_with(|| a.文.时间戳.cmp(&b.文.时间戳))
|
||||
.then_with(|| a.文.时间戳().cmp(&b.文.时间戳()))
|
||||
})
|
||||
.map(|x| Rc::clone(&x.文))
|
||||
.unwrap_or_else(|| Rc::clone(&self.元素[0].文))
|
||||
.map(|x| Arc::clone(&x.文))
|
||||
.unwrap_or_else(|| Arc::clone(&self.元素[0].文))
|
||||
} else {
|
||||
self.元素
|
||||
.iter()
|
||||
@@ -74,40 +75,56 @@ impl 线段特征 {
|
||||
.分型特征值
|
||||
.partial_cmp(&b.文.分型特征值)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
.then_with(|| b.文.时间戳.cmp(&a.文.时间戳))
|
||||
.then_with(|| b.文.时间戳().cmp(&a.文.时间戳()))
|
||||
})
|
||||
.map(|x| Rc::clone(&x.文))
|
||||
.unwrap_or_else(|| Rc::clone(&self.元素[0].文))
|
||||
.map(|x| Arc::clone(&x.文))
|
||||
.unwrap_or_else(|| Arc::clone(&self.元素[0].文))
|
||||
}
|
||||
}
|
||||
|
||||
/// 武 — 取特征序列元素中分型特征值最大/最小的武分型
|
||||
/// tiebreaker: later时间戳 wins when特征值 equal (matches Python)
|
||||
pub fn 武(&self) -> Rc<分型> {
|
||||
pub fn 武(&self) -> Arc<分型> {
|
||||
if self.线段方向.是否向上() {
|
||||
self.元素
|
||||
.iter()
|
||||
.max_by(|a, b| {
|
||||
a.武
|
||||
.read()
|
||||
.unwrap()
|
||||
.分型特征值
|
||||
.partial_cmp(&b.武.分型特征值)
|
||||
.partial_cmp(&b.武.read().unwrap().分型特征值)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
.then_with(|| a.武.时间戳.cmp(&b.武.时间戳))
|
||||
.then_with(|| {
|
||||
a.武
|
||||
.read()
|
||||
.unwrap()
|
||||
.时间戳()
|
||||
.cmp(&b.武.read().unwrap().时间戳())
|
||||
})
|
||||
})
|
||||
.map(|x| Rc::clone(&x.武))
|
||||
.unwrap_or_else(|| Rc::clone(&self.元素[0].武))
|
||||
.map(|x| x.武.read().unwrap().clone())
|
||||
.unwrap_or_else(|| self.元素[0].武.read().unwrap().clone())
|
||||
} else {
|
||||
self.元素
|
||||
.iter()
|
||||
.min_by(|a, b| {
|
||||
a.武
|
||||
.read()
|
||||
.unwrap()
|
||||
.分型特征值
|
||||
.partial_cmp(&b.武.分型特征值)
|
||||
.partial_cmp(&b.武.read().unwrap().分型特征值)
|
||||
.unwrap_or(std::cmp::Ordering::Equal)
|
||||
.then_with(|| b.武.时间戳.cmp(&a.武.时间戳))
|
||||
.then_with(|| {
|
||||
b.武
|
||||
.read()
|
||||
.unwrap()
|
||||
.时间戳()
|
||||
.cmp(&a.武.read().unwrap().时间戳())
|
||||
})
|
||||
})
|
||||
.map(|x| Rc::clone(&x.武))
|
||||
.unwrap_or_else(|| Rc::clone(&self.元素[0].武))
|
||||
.map(|x| x.武.read().unwrap().clone())
|
||||
.unwrap_or_else(|| self.元素[0].武.read().unwrap().clone())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,7 +146,7 @@ impl 线段特征 {
|
||||
}
|
||||
|
||||
/// 向特征序列元素中添加虚线
|
||||
pub fn 添加(&mut self, 待添加虚线: Rc<虚线>) -> Result<(), String> {
|
||||
pub fn 添加(&mut self, 待添加虚线: Arc<虚线>) -> Result<(), String> {
|
||||
if 待添加虚线.方向() == self.线段方向 {
|
||||
return Err("添加方向与线段方向相同".into());
|
||||
}
|
||||
@@ -138,14 +155,14 @@ impl 线段特征 {
|
||||
}
|
||||
|
||||
/// 从特征序列元素中删除虚线
|
||||
pub fn 删除(&mut self, 待删除虚线: &Rc<虚线>) -> Result<(), String> {
|
||||
pub fn 删除(&mut self, 待删除虚线: &Arc<虚线>) -> Result<(), String> {
|
||||
if 待删除虚线.方向() == self.方向() {
|
||||
return Err("删除方向与特征序列方向相同".into());
|
||||
}
|
||||
if let Some(pos) = self
|
||||
.元素
|
||||
.iter()
|
||||
.position(|x| Rc::as_ptr(x) == Rc::as_ptr(待删除虚线))
|
||||
.position(|x| Arc::as_ptr(x) == Arc::as_ptr(待删除虚线))
|
||||
{
|
||||
self.元素.remove(pos);
|
||||
Ok(())
|
||||
@@ -155,19 +172,19 @@ impl 线段特征 {
|
||||
}
|
||||
|
||||
/// 新建特征序列元素
|
||||
pub fn 新建(虚线序列: Vec<Rc<虚线>>, 线段方向: 相对方向) -> Self {
|
||||
let 标识 = format!("特征<虚线>");
|
||||
pub fn 新建(虚线序列: Vec<Arc<虚线>>, 线段方向: 相对方向) -> Self {
|
||||
let 标识 = "特征<虚线>".to_string();
|
||||
Self::new(标识, 虚线序列, 线段方向)
|
||||
}
|
||||
|
||||
/// 静态分析 — 从虚线序列生成特征序列元素列表
|
||||
pub fn 静态分析(
|
||||
虚线序列: &[Rc<虚线>],
|
||||
虚线序列: &[Arc<虚线>],
|
||||
线段方向: 相对方向,
|
||||
四象: &str,
|
||||
是否忽视: bool,
|
||||
) -> Vec<Rc<线段特征>> {
|
||||
let mut 结果: Vec<Rc<线段特征>> = Vec::new();
|
||||
) -> Vec<Arc<线段特征>> {
|
||||
let mut 结果: Vec<Arc<线段特征>> = Vec::new();
|
||||
|
||||
// 需要被合并的方向集合
|
||||
let 需要合并: Vec<相对方向> = match 四象 {
|
||||
@@ -179,9 +196,9 @@ impl 线段特征 {
|
||||
// 情况1:方向相同(可能触发分型替换)
|
||||
if 虚线.方向() == 线段方向 {
|
||||
if 结果.len() >= 3 {
|
||||
let 左 = Rc::clone(&结果[结果.len() - 3]);
|
||||
let 中 = Rc::clone(&结果[结果.len() - 2]);
|
||||
let 右 = Rc::clone(&结果[结果.len() - 1]);
|
||||
let 左 = Arc::clone(&结果[结果.len() - 3]);
|
||||
let 中 = Arc::clone(&结果[结果.len() - 2]);
|
||||
let 右 = Arc::clone(&结果[结果.len() - 1]);
|
||||
|
||||
if let Some(结构) = 分型结构::分析(&*左, &*中, &*右, true, true) {
|
||||
let 应替换 = (线段方向 == 相对方向::向上
|
||||
@@ -192,16 +209,24 @@ impl 线段特征 {
|
||||
&& 虚线.低() < 中.低());
|
||||
|
||||
if 应替换 {
|
||||
let 小号虚线 = 中.元素.iter().min_by_key(|o| o.序号).unwrap();
|
||||
let 大号虚线 = 右.元素.iter().max_by_key(|o| o.序号).unwrap();
|
||||
let 小号虚线 = 中
|
||||
.元素
|
||||
.iter()
|
||||
.min_by_key(|o| o.序号.load(Ordering::Relaxed))
|
||||
.unwrap();
|
||||
let 大号虚线 = 右
|
||||
.元素
|
||||
.iter()
|
||||
.max_by_key(|o| o.序号.load(Ordering::Relaxed))
|
||||
.unwrap();
|
||||
let fake = 虚线::创建笔(
|
||||
Rc::clone(&小号虚线.文),
|
||||
Rc::clone(&大号虚线.武),
|
||||
Arc::clone(&小号虚线.文),
|
||||
大号虚线.武.read().unwrap().clone(),
|
||||
false,
|
||||
);
|
||||
结果.pop();
|
||||
let idx = 结果.len() - 1;
|
||||
结果[idx] = Rc::new(Self::新建(vec![Rc::new(fake)], 线段方向));
|
||||
结果[idx] = Arc::new(Self::新建(vec![Arc::new(fake)], 线段方向));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -210,7 +235,7 @@ impl 线段特征 {
|
||||
|
||||
// 情况2:方向不同(执行特征序列的合并/添加)
|
||||
if 结果.is_empty() {
|
||||
结果.push(Rc::new(Self::新建(vec![Rc::clone(虚线)], 线段方向)));
|
||||
结果.push(Arc::new(Self::新建(vec![Arc::clone(虚线)], 线段方向)));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -225,10 +250,10 @@ impl 线段特征 {
|
||||
)) {
|
||||
// Clone-modify-replace
|
||||
let mut 新特征 = (*结果[最后_idx]).clone();
|
||||
let _ = 新特征.添加(Rc::clone(虚线));
|
||||
结果[最后_idx] = Rc::new(新特征);
|
||||
let _ = 新特征.添加(Arc::clone(虚线));
|
||||
结果[最后_idx] = Arc::new(新特征);
|
||||
} else {
|
||||
结果.push(Rc::new(Self::新建(vec![Rc::clone(虚线)], 线段方向)));
|
||||
结果.push(Arc::new(Self::新建(vec![Arc::clone(虚线)], 线段方向)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -236,15 +261,15 @@ impl 线段特征 {
|
||||
}
|
||||
|
||||
/// 获取分型序列
|
||||
pub fn 获取分型序列(特征序列: &[Rc<线段特征>]) -> Vec<特征分型> {
|
||||
pub fn 获取分型序列(特征序列: &[Arc<线段特征>]) -> Vec<特征分型> {
|
||||
let mut 结果 = Vec::new();
|
||||
if 特征序列.len() < 3 {
|
||||
return 结果;
|
||||
}
|
||||
for i in 2..特征序列.len() {
|
||||
let 左 = Rc::clone(&特征序列[i - 2]);
|
||||
let 中 = Rc::clone(&特征序列[i - 1]);
|
||||
let 右 = Rc::clone(&特征序列[i]);
|
||||
let 左 = Arc::clone(&特征序列[i - 2]);
|
||||
let 中 = Arc::clone(&特征序列[i - 1]);
|
||||
let 右 = Arc::clone(&特征序列[i]);
|
||||
|
||||
let 结构 = 分型结构::分析_对象(
|
||||
&*左 as &dyn crate::types::fractal::有高低,
|
||||
@@ -285,3 +310,274 @@ impl std::fmt::Display for 线段特征 {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::kline::bar::K线;
|
||||
use crate::kline::chan_kline::缠论K线;
|
||||
use crate::structure::fractal_obj::分型;
|
||||
use crate::types::分型结构;
|
||||
|
||||
fn 辅助_创建K线(时间戳: i64, 高: f64, 低: f64, 开: f64, 收: f64) -> K线 {
|
||||
K线 {
|
||||
时间戳,
|
||||
高,
|
||||
低,
|
||||
开盘价: 开,
|
||||
收盘价: 收,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn 辅助_创建缠K(
|
||||
时间戳: i64,
|
||||
高: f64,
|
||||
低: f64,
|
||||
方向: 相对方向,
|
||||
结构: Option<分型结构>,
|
||||
序号: i64,
|
||||
) -> Arc<缠论K线> {
|
||||
let 普K = Arc::new(辅助_创建K线(时间戳, 高, 低, 低, 高));
|
||||
Arc::new(缠论K线::创建缠K(
|
||||
时间戳, 高, 低, 方向, 结构, 序号, 普K, None,
|
||||
))
|
||||
}
|
||||
|
||||
fn 辅助_创建顶分型(时间戳: i64, 高: f64, 低: f64, 序号: i64) -> Arc<分型> {
|
||||
let 左 = 辅助_创建缠K(
|
||||
时间戳 - 2,
|
||||
高 - 2.0,
|
||||
低 - 2.0,
|
||||
相对方向::向上,
|
||||
Some(分型结构::上),
|
||||
序号 - 2,
|
||||
);
|
||||
let 中 = 辅助_创建缠K(时间戳, 高, 低, 相对方向::向上, Some(分型结构::顶), 序号);
|
||||
let 右 = 辅助_创建缠K(
|
||||
时间戳 + 2,
|
||||
高 - 1.0,
|
||||
低 - 1.0,
|
||||
相对方向::向下,
|
||||
Some(分型结构::下),
|
||||
序号 + 2,
|
||||
);
|
||||
Arc::new(分型::new(Some(左), 中, Some(右)))
|
||||
}
|
||||
|
||||
fn 辅助_创建底分型(时间戳: i64, 高: f64, 低: f64, 序号: i64) -> Arc<分型> {
|
||||
let 左 = 辅助_创建缠K(
|
||||
时间戳 - 2,
|
||||
高 + 2.0,
|
||||
低 + 2.0,
|
||||
相对方向::向下,
|
||||
Some(分型结构::下),
|
||||
序号 - 2,
|
||||
);
|
||||
let 中 = 缠论K线::创建缠K(
|
||||
时间戳,
|
||||
高,
|
||||
低,
|
||||
相对方向::向下,
|
||||
Some(分型结构::底),
|
||||
序号,
|
||||
Arc::new(辅助_创建K线(时间戳, 高, 低, 低, 高)),
|
||||
None,
|
||||
);
|
||||
中.分型特征值.set(低);
|
||||
let 中 = Arc::new(中);
|
||||
let 右 = 辅助_创建缠K(
|
||||
时间戳 + 2,
|
||||
高 + 1.0,
|
||||
低 + 1.0,
|
||||
相对方向::向上,
|
||||
Some(分型结构::上),
|
||||
序号 + 2,
|
||||
);
|
||||
Arc::new(分型::new(Some(左), 中, Some(右)))
|
||||
}
|
||||
|
||||
fn 辅助_创建笔(
|
||||
文时间戳: i64,
|
||||
文高: f64,
|
||||
文低: f64,
|
||||
武时间戳: i64,
|
||||
武高: f64,
|
||||
武低: f64,
|
||||
) -> Arc<虚线> {
|
||||
let 顶 = 辅助_创建顶分型(文时间戳, 文高, 文低, 1);
|
||||
let 底 = 辅助_创建底分型(武时间戳, 武高, 武低, 2);
|
||||
Arc::new(虚线::创建笔(顶, 底, true))
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 文 — 取特征值最大/最小的分型
|
||||
// 特征序列元素方向与线段方向相反:
|
||||
// 向上线段 → 元素为向下笔(顶→底) → 文=顶分型 → 取max
|
||||
// 向下线段 → 元素为向上笔(底→顶) → 文=底分型 → 取min
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_文_向上线段取最大特征值分型() {
|
||||
// 向上线段,元素用向下笔(顶→底),文=顶分型
|
||||
// 笔1: 顶(特征值=100)→底(80), 文=顶(100)
|
||||
let 笔1 = 辅助_创建笔(100, 100.0, 90.0, 200, 90.0, 80.0);
|
||||
// 笔2: 顶(特征值=110)→底(90), 文=顶(110)
|
||||
let 笔2 = 辅助_创建笔(200, 110.0, 100.0, 300, 90.0, 80.0);
|
||||
|
||||
let feat = 线段特征::new(
|
||||
"测试".into(),
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2)],
|
||||
相对方向::向上,
|
||||
);
|
||||
|
||||
// 向上取max → 笔2.文=110
|
||||
let 文 = feat.文();
|
||||
assert!((文.分型特征值 - 110.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_文_向下线段取最小特征值分型() {
|
||||
// 向下线段,元素用向上笔(底→顶),文=底分型
|
||||
// 笔1: 底(特征值=80)→顶(100), 文=底(80)
|
||||
let 底1 = 辅助_创建底分型(100, 90.0, 80.0, 5);
|
||||
let 顶1 = 辅助_创建顶分型(200, 100.0, 90.0, 10);
|
||||
let 笔1 = Arc::new(虚线::创建笔(底1, 顶1, true));
|
||||
|
||||
// 笔2: 底(特征值=70)→顶(95), 文=底(70)
|
||||
let 底2 = 辅助_创建底分型(200, 80.0, 70.0, 15);
|
||||
let 顶2 = 辅助_创建顶分型(300, 95.0, 85.0, 20);
|
||||
let 笔2 = Arc::new(虚线::创建笔(底2, 顶2, true));
|
||||
|
||||
let feat = 线段特征::new(
|
||||
"测试".into(),
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2)],
|
||||
相对方向::向下,
|
||||
);
|
||||
|
||||
// 向下取min → 笔2.文=70
|
||||
let 文 = feat.文();
|
||||
assert!((文.分型特征值 - 70.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 武 — 取特征值最大/最小的分型
|
||||
// 向上线段 → 元素为向下笔 → 武=底分型 → 取max
|
||||
// 向下线段 → 元素为向上笔 → 武=顶分型 → 取min
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_武_向上线段取最大特征值分型() {
|
||||
// 向上线段,元素用向下笔(顶→底),武=底分型
|
||||
// 笔1: 顶(100)→底(特征值=80), 武=底(80)
|
||||
let 笔1 = 辅助_创建笔(100, 100.0, 90.0, 200, 90.0, 80.0);
|
||||
// 笔2: 顶(110)→底(特征值=90), 武=底(90)
|
||||
let 笔2 = 辅助_创建笔(200, 110.0, 100.0, 300, 100.0, 90.0);
|
||||
|
||||
let feat = 线段特征::new(
|
||||
"测试".into(),
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2)],
|
||||
相对方向::向上,
|
||||
);
|
||||
|
||||
// 向上取max → 笔2.武=90
|
||||
let 武 = feat.武();
|
||||
assert!((武.分型特征值 - 90.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_武_向下线段取最小特征值分型() {
|
||||
// 向下线段,元素用向上笔(底→顶),武=顶分型
|
||||
// 笔1: 底(80)→顶(特征值=100), 武=顶(100)
|
||||
let 底1 = 辅助_创建底分型(100, 90.0, 80.0, 5);
|
||||
let 顶1 = 辅助_创建顶分型(200, 100.0, 90.0, 10);
|
||||
let 笔1 = Arc::new(虚线::创建笔(底1, 顶1, true));
|
||||
|
||||
// 笔2: 底(60)→顶(特征值=85), 武=顶(85)
|
||||
let 底2 = 辅助_创建底分型(200, 70.0, 60.0, 15);
|
||||
let 顶2 = 辅助_创建顶分型(300, 85.0, 75.0, 20);
|
||||
let 笔2 = Arc::new(虚线::创建笔(底2, 顶2, true));
|
||||
|
||||
let feat = 线段特征::new(
|
||||
"测试".into(),
|
||||
vec![Arc::clone(&笔1), Arc::clone(&笔2)],
|
||||
相对方向::向下,
|
||||
);
|
||||
|
||||
// 向下取min → 笔2.武=85
|
||||
let 武 = feat.武();
|
||||
assert!((武.分型特征值 - 85.0).abs() < 0.01);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 文/武 tiebreaker — 同特征值取后时间戳
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_文_同特征值取后时间戳() {
|
||||
// 两个笔的文特征值相同=100,但时间戳不同
|
||||
let 顶1 = 辅助_创建顶分型(100, 100.0, 90.0, 5);
|
||||
let 底1 = 辅助_创建底分型(200, 90.0, 80.0, 10);
|
||||
let 笔1 = Arc::new(虚线::创建笔(顶1, 底1, true));
|
||||
|
||||
let 顶2 = 辅助_创建顶分型(300, 100.0, 90.0, 15); // 同特征值,后时间戳
|
||||
let 底2 = 辅助_创建底分型(400, 80.0, 70.0, 20);
|
||||
let 笔2 = Arc::new(虚线::创建笔(顶2, 底2, true));
|
||||
|
||||
let feat = 线段特征::new("测试".into(), vec![笔1, 笔2], 相对方向::向上);
|
||||
|
||||
let 文 = feat.文();
|
||||
// 向上取最大特征值:都是100 → tiebreaker取后时间戳 → 笔2.文(300)
|
||||
assert_eq!(文.时间戳(), 300);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_武_同特征值取后时间戳_向上() {
|
||||
let 顶1 = 辅助_创建顶分型(100, 100.0, 90.0, 5);
|
||||
let 底1 = 辅助_创建底分型(200, 80.0, 70.0, 10); // 特征值80
|
||||
let 笔1 = Arc::new(虚线::创建笔(顶1, 底1, true));
|
||||
|
||||
let 顶2 = 辅助_创建顶分型(300, 80.0, 70.0, 15); // 特征值80
|
||||
let 底2 = 辅助_创建底分型(400, 80.0, 70.0, 20); // 特征值80
|
||||
let 笔2 = Arc::new(虚线::创建笔(顶2, 底2, true));
|
||||
|
||||
let feat = 线段特征::new("测试".into(), vec![笔1, 笔2], 相对方向::向上);
|
||||
|
||||
let 武 = feat.武();
|
||||
// 向上取最大特征值:都是80 → tiebreaker取后时间戳 → 笔2.武(400)
|
||||
assert_eq!(武.时间戳(), 400);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// 添加/删除 操作
|
||||
// ============================================================
|
||||
|
||||
#[test]
|
||||
fn test_添加方向与线段方向相反的虚线可成功() {
|
||||
// 向下笔(顶→底,方向=向下) 添加到 向上线段(方向=向上) → 方向不同, 可添加
|
||||
let 笔1 = 辅助_创建笔(100, 100.0, 90.0, 200, 90.0, 80.0);
|
||||
let mut feat = 线段特征::new("测试".into(), vec![], 相对方向::向上);
|
||||
|
||||
let result = feat.添加(Arc::clone(&笔1));
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_添加方向与线段方向相同的虚线应报错() {
|
||||
// 向下笔(顶→底,方向=向下) 添加到 向下线段(方向=向下) → 方向相同, 应报错
|
||||
let 笔1 = 辅助_创建笔(100, 100.0, 90.0, 200, 90.0, 80.0);
|
||||
let mut feat = 线段特征::new("测试".into(), vec![], 相对方向::向下);
|
||||
|
||||
let result = feat.添加(Arc::clone(&笔1));
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_空线段特征文返回第一个元素的文() {
|
||||
let 笔1 = 辅助_创建笔(100, 100.0, 90.0, 200, 90.0, 80.0);
|
||||
let feat = 线段特征::new("测试".into(), vec![Arc::clone(&笔1)], 相对方向::向上);
|
||||
|
||||
let 文 = feat.文();
|
||||
assert_eq!(Arc::as_ptr(&文), Arc::as_ptr(&笔1.文));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,6 +92,7 @@ impl 分型结构 {
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn 分析_内部(
|
||||
左高: f64,
|
||||
左低: f64,
|
||||
|
||||
@@ -26,8 +26,10 @@ pub mod bsp_type;
|
||||
pub mod direction;
|
||||
pub mod fractal;
|
||||
pub mod gap;
|
||||
pub mod sync_f64;
|
||||
|
||||
pub use bsp_type::买卖点类型;
|
||||
pub use direction::相对方向;
|
||||
pub use fractal::分型结构;
|
||||
pub use gap::缺口;
|
||||
pub use sync_f64::SyncF64;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* MIT License
|
||||
*
|
||||
* Copyright (c) 2026 YuYuKunKun
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// f64 原子类型 — 基于 AtomicU64 + 位转换,API 与 `Cell<f64>` 一致。
|
||||
#[derive(Debug, Default)]
|
||||
pub struct SyncF64(AtomicU64);
|
||||
|
||||
impl SyncF64 {
|
||||
pub fn new(v: f64) -> Self {
|
||||
Self(AtomicU64::new(v.to_bits()))
|
||||
}
|
||||
|
||||
pub fn get(&self) -> f64 {
|
||||
f64::from_bits(self.0.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
pub fn set(&self, v: f64) {
|
||||
self.0.store(v.to_bits(), Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for SyncF64 {
|
||||
fn clone(&self) -> Self {
|
||||
Self(AtomicU64::new(self.0.load(Ordering::Relaxed)))
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
/// 将 f64 格式化为与 Python `:g` (6 位有效数字) 兼容的字符串。
|
||||
pub fn format_f64_g(value: f64) -> String {
|
||||
if value.is_nan() {
|
||||
return "nan".to_string();
|
||||
@@ -33,9 +34,61 @@ pub fn format_f64_g(value: f64) -> String {
|
||||
"-inf".to_string()
|
||||
};
|
||||
}
|
||||
if value == 0.0 {
|
||||
return "0".to_string();
|
||||
}
|
||||
|
||||
// Use high precision then trim trailing zeros
|
||||
let s = format!("{:.15}", value);
|
||||
let s = s.trim_end_matches('0');
|
||||
s.trim_end_matches('.').to_string()
|
||||
let abs = value.abs();
|
||||
let exp = abs.log10().floor() as i32;
|
||||
|
||||
// Python :g 科学计数法边界: exp < -4 或 exp >= p (=6)
|
||||
if !(-4..6).contains(&exp) {
|
||||
let significand = value / 10_f64.powi(exp);
|
||||
let s = format!("{:.5}", significand);
|
||||
let s = s.trim_end_matches('0').trim_end_matches('.');
|
||||
return format!("{}e{:+03}", s, exp);
|
||||
}
|
||||
|
||||
// 定点表示
|
||||
if abs >= 1.0 {
|
||||
let int_digits = exp as usize + 1;
|
||||
if int_digits >= 6 {
|
||||
return format!("{:.0}", value);
|
||||
}
|
||||
let s = format!("{:.prec$}", value, prec = 6 - int_digits);
|
||||
let s = s.trim_end_matches('0');
|
||||
s.trim_end_matches('.').to_string()
|
||||
} else {
|
||||
let leading_zeros = (-exp) as usize;
|
||||
let s = format!("{:.prec$}", value, prec = leading_zeros + 5);
|
||||
let s = s.trim_end_matches('0');
|
||||
s.trim_end_matches('.').to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_format_large() {
|
||||
assert_eq!(format_f64_g(82833.0), "82833");
|
||||
assert_eq!(format_f64_g(74192.2), "74192.2");
|
||||
assert_eq!(format_f64_g(100.0), "100");
|
||||
assert_eq!(format_f64_g(0.0), "0");
|
||||
assert_eq!(format_f64_g(12345.6789), "12345.7");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_small() {
|
||||
assert_eq!(format_f64_g(0.001234), "0.001234");
|
||||
assert_eq!(format_f64_g(0.1), "0.1");
|
||||
assert_eq!(format_f64_g(0.001), "0.001");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_format_extreme() {
|
||||
assert_eq!(format_f64_g(1e7), "1e+07");
|
||||
assert_eq!(format_f64_g(1e-5), "1e-05");
|
||||
}
|
||||
}
|
||||
|
||||
+63
-34
@@ -657,35 +657,56 @@ class 随机数据(bt.feeds.DataBase):
|
||||
class 自定义实时数据源(bt.feed.DataBase):
|
||||
"""
|
||||
一个用于模拟实时数据推送的数据源,继承自Backtrader的DataBase。
|
||||
在实际应用中,你需要将“模拟生成数据”的部分,替换为接收WebSocket等推送数据的代码。
|
||||
|
||||
支持两种数据输入方式:
|
||||
1. 手动投喂:调用 投喂数据(时间戳, 开, 高, 低, 收, 量) 从 WebSocket 回调等外部代码推送
|
||||
2. 后台线程:传入 观察员 和 魔法 参数,start() 时自动启动线程获取历史数据
|
||||
(注意:观察员 需实现 读取任意数据 方法)
|
||||
|
||||
时间戳格式:Unix 时间戳(秒),为 int 类型。
|
||||
"""
|
||||
|
||||
def __init__(self, 数据队列: queue.Queue, 观察员: "观察者", 魔法, **魔法参数):
|
||||
# 调用父类初始化方法
|
||||
def __init__(self, 数据队列: queue.Queue = None, 观察员: "观察者" = None, 魔法=None, **魔法参数):
|
||||
super(自定义实时数据源, self).__init__()
|
||||
# 存储外部传入的数据队列,用于接收实时数据
|
||||
self.数据队列 = 数据队列
|
||||
# 定义一个标志,用于控制数据加载的停止
|
||||
self.数据队列 = 数据队列 or queue.Queue()
|
||||
self.正在运行 = False
|
||||
self.观察员 = 观察员
|
||||
self.魔法 = 魔法
|
||||
self.__魔法参数 = 魔法参数
|
||||
self.已有数据 = False
|
||||
|
||||
def 投喂数据(self, 时间戳: int, 开盘价: float, 最高价: float, 最低价: float, 收盘价: float, 成交量: float, 持仓量: float = 0):
|
||||
"""线程安全的外部数据推送接口,供 WebSocket 回调等外部代码调用。
|
||||
|
||||
:param 时间戳: Unix 时间戳(秒,int 类型)
|
||||
:param 开盘价: 开盘价
|
||||
:param 最高价: 最高价
|
||||
:param 最低价: 最低价
|
||||
:param 收盘价: 收盘价
|
||||
:param 成交量: 成交量
|
||||
:param 持仓量: 持仓量(默认为 0)
|
||||
"""
|
||||
self.数据队列.put((时间戳, 开盘价, 最高价, 最低价, 收盘价, 成交量, 持仓量))
|
||||
|
||||
def start(self):
|
||||
"""
|
||||
数据源开始工作时的初始化操作。
|
||||
这里可以不执行任何操作,或者启动数据接收线程等。
|
||||
"""
|
||||
print(f"[{datetime.now()}] 自定义数据源已启动...")
|
||||
self.正在运行 = True
|
||||
|
||||
def 运行回测():
|
||||
self.观察员.读取任意数据(self.魔法, **self.__魔法参数)
|
||||
self.正在运行 = False
|
||||
if self.观察员 is not None and self.魔法 is not None:
|
||||
if not hasattr(self.观察员, "读取任意数据"):
|
||||
print(f"[{datetime.now()}] 警告: 观察员没有 '读取任意数据' 方法,后台线程不会启动")
|
||||
return
|
||||
|
||||
回测线程 = threading.Thread(target=运行回测, daemon=True)
|
||||
回测线程.start()
|
||||
def 运行回测():
|
||||
try:
|
||||
self.观察员.读取任意数据(self.魔法, **self.__魔法参数)
|
||||
except Exception as e:
|
||||
print(f"[{datetime.now()}] 后台数据线程异常: {e}")
|
||||
finally:
|
||||
self.正在运行 = False
|
||||
|
||||
回测线程 = threading.Thread(target=运行回测, daemon=True)
|
||||
回测线程.start()
|
||||
|
||||
def stop(self):
|
||||
"""
|
||||
@@ -696,32 +717,25 @@ class 自定义实时数据源(bt.feed.DataBase):
|
||||
print(f"[{datetime.now()}] 自定义数据源已停止。")
|
||||
|
||||
def _load(self):
|
||||
"""
|
||||
(核心方法) Backtrader会循环调用此方法来获取数据。
|
||||
每次被调用时,都应该返回新的数据行(一个K线/一个数据点)。
|
||||
如果没有新数据,返回 False,Backtrader会等待下次调用。
|
||||
"""
|
||||
"""Backtrader 核心回调 — 阻塞等待数据,有数据时返回 True,数据源停止时返回 False。"""
|
||||
if not self.正在运行:
|
||||
return False
|
||||
# 当没有新数据且系统仍在运行时,进入等待
|
||||
# 从外部队列获取新数据
|
||||
|
||||
while True:
|
||||
try:
|
||||
data_point = self.数据队列.get(timeout=0.5)
|
||||
break
|
||||
except queue.Empty:
|
||||
if not self.已有数据:
|
||||
continue
|
||||
else:
|
||||
if self.正在运行:
|
||||
continue
|
||||
if not self.正在运行:
|
||||
return False
|
||||
# 解析数据元组
|
||||
dt, o, h, l, c, v, oi = data_point
|
||||
|
||||
# 将数据写入Backtrader的数据线 (lines)
|
||||
self.lines.datetime[0] = bt.date2num(dt)
|
||||
try:
|
||||
dt, o, h, l, c, v, oi = data_point
|
||||
except (ValueError, TypeError) as e:
|
||||
print(f"[{datetime.now()}] 自定义数据源: 数据格式错误,跳过: {e}")
|
||||
return True
|
||||
|
||||
self.lines.datetime[0] = bt.date2num(datetime.utcfromtimestamp(int(dt)))
|
||||
self.lines.open[0] = o
|
||||
self.lines.high[0] = h
|
||||
self.lines.low[0] = l
|
||||
@@ -729,7 +743,6 @@ class 自定义实时数据源(bt.feed.DataBase):
|
||||
self.lines.volume[0] = v
|
||||
self.lines.openinterest[0] = oi
|
||||
self.已有数据 = True
|
||||
# 返回 True 表示成功加载一行数据
|
||||
return True
|
||||
|
||||
|
||||
@@ -757,7 +770,7 @@ class 高级策略基类(bt.Strategy):
|
||||
|
||||
def 日志(self, 文本, 时间=None):
|
||||
时间 = 时间 or self.datas[0].datetime.datetime(0)
|
||||
print(f"{时间} {文本}")
|
||||
print(f"{时间} {self.p.观察员.__class__.__name__}: {文本}")
|
||||
|
||||
def 计算目标数量(self, 价格):
|
||||
"""根据资金类型和仓位比例计算目标数量"""
|
||||
@@ -946,6 +959,7 @@ class 回测(高级策略基类):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.已处理信号 = set()
|
||||
print(f"{self.p.观察员.__class__.__name__}: 加载完成...")
|
||||
|
||||
def 获取开仓限价(self, 是否做多):
|
||||
# 根据缠论分型计算限价,若无则返回 None 使用基类默认逻辑
|
||||
@@ -957,6 +971,7 @@ class 回测(高级策略基类):
|
||||
return None
|
||||
|
||||
def next(self):
|
||||
# self.日志(f"{self.p.观察员.__class__.__name__} called next ")
|
||||
# 1. 更新移动止损(基类方法)
|
||||
if self.position:
|
||||
self.更新止损订单(self.position.size > 0, self.data.close[0])
|
||||
@@ -986,15 +1001,22 @@ class 回测(高级策略基类):
|
||||
def 检查买信号(self):
|
||||
if self.p.观察员.笔序列:
|
||||
k线 = self.p.观察员.缠论K线序列[-1]
|
||||
self.日志(f"检查买信号 当前笔 {self.p.观察员.笔序列[-1]}")
|
||||
if k线.买卖点信息:
|
||||
print(f"回测-首 {self.p.观察员.__class__.__name__}", k线.买卖点信息)
|
||||
首 = True if k线.买卖点信息 and "买" in next(iter(k线.买卖点信息)) else False
|
||||
if 首:
|
||||
print(k线)
|
||||
原始差值 = self.p.观察员.当前K线.序号 - k线.标的K线.序号
|
||||
差值 = self.p.观察员.当前缠K.序号 - k线.序号
|
||||
self.日志(f"首_买入信号差值: {原始差值}, {差值}, 观察员.当前K线 时间戳: {self.p.观察员.当前K线.时间戳}")
|
||||
k线 = self.p.观察员.缠论K线序列[-2]
|
||||
if k线.买卖点信息:
|
||||
print(f"回测-尾 {self.p.观察员.__class__.__name__}", k线.买卖点信息)
|
||||
|
||||
尾 = True if self.p.观察员.缠论K线序列[-2].买卖点信息 and "买" in next(iter(self.p.观察员.缠论K线序列[-2].买卖点信息)) else False
|
||||
if 尾:
|
||||
print(k线)
|
||||
原始差值 = self.p.观察员.当前K线.序号 - k线.标的K线.序号
|
||||
差值 = self.p.观察员.当前缠K.序号 - k线.序号
|
||||
self.日志(f"尾_买入信号差值: {原始差值}, {差值}, 观察员.当前K线 时间戳: {self.p.观察员.当前K线.时间戳}")
|
||||
@@ -1002,16 +1024,23 @@ class 回测(高级策略基类):
|
||||
|
||||
def 检查卖信号(self):
|
||||
if self.p.观察员.笔序列:
|
||||
self.日志(f"检查卖信号 当前笔 {self.p.观察员.笔序列[-1]}")
|
||||
k线 = self.p.观察员.缠论K线序列[-1]
|
||||
if k线.买卖点信息:
|
||||
print(f"回测-首 {self.p.观察员.__class__.__name__}", k线.买卖点信息)
|
||||
首 = True if k线.买卖点信息 and "卖" in next(iter(k线.买卖点信息)) else False
|
||||
if 首:
|
||||
print(k线)
|
||||
原始差值 = self.p.观察员.当前K线.序号 - k线.标的K线.序号
|
||||
差值 = self.p.观察员.当前缠K.序号 - k线.序号
|
||||
self.日志(f"首_买入信号差值: {原始差值}, {差值}, 观察员.当前K线 时间戳: {self.p.观察员.当前K线.时间戳}")
|
||||
k线 = self.p.观察员.缠论K线序列[-2]
|
||||
if k线.买卖点信息:
|
||||
print(f"回测-尾 {self.p.观察员.__class__.__name__}", k线.买卖点信息)
|
||||
|
||||
尾 = True if self.p.观察员.缠论K线序列[-2].买卖点信息 and "卖" in next(iter(self.p.观察员.缠论K线序列[-2].买卖点信息)) else False
|
||||
if 尾:
|
||||
print(k线)
|
||||
原始差值 = self.p.观察员.当前K线.序号 - k线.标的K线.序号
|
||||
差值 = self.p.观察员.当前缠K.序号 - k线.序号
|
||||
self.日志(f"尾_买入信号差值: {原始差值}, {差值}, 观察员.当前K线 时间戳: {self.p.观察员.当前K线.时间戳}")
|
||||
@@ -1019,7 +1048,7 @@ class 回测(高级策略基类):
|
||||
|
||||
def log(self, 文本, dt=None):
|
||||
dt = dt or bt.num2date(self.data.datetime[0])
|
||||
print(f"[{dt.strftime('%Y-%m-%d %H:%M')}] {self.p.符号} | {文本}")
|
||||
print(f"[{dt.strftime('%Y-%m-%d %H:%M')}] {self.p.观察员.__class__.__name__}: {self.p.符号} | {文本}")
|
||||
|
||||
|
||||
# ==================== 回测运行入口 ====================
|
||||
|
||||
Reference in New Issue
Block a user