@dsh-ft/dsh-fft-paper-trading 0.7.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/client.js +1 -1
- package/package.json +1 -4
- package/node_modules/@ftshare-lab/dsh-kline/CHANGELOG.md +0 -611
- package/node_modules/@ftshare-lab/dsh-kline/LICENSE +0 -21
- package/node_modules/@ftshare-lab/dsh-kline/PROVENANCE.md +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/README.en.md +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/README.md +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/chart_service.py +0 -687
- package/node_modules/@ftshare-lab/dsh-kline/config/basic-symbols.json +0 -570
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-kline.patch.yml +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/config/dsh-tool-catalog.json +0 -3875
- package/node_modules/@ftshare-lab/dsh-kline/cordis.patch.yml +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/core/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/core/adjustment.py +0 -16
- package/node_modules/@ftshare-lab/dsh-kline/core/calc.py +0 -691
- package/node_modules/@ftshare-lab/dsh-kline/core/rows.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/core/ta_engine.py +0 -99
- package/node_modules/@ftshare-lab/dsh-kline/lib/candle-sequence.js +0 -15
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-adjustment.js +0 -7
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-annotations.js +0 -33
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-applications.js +0 -171
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-context.js +0 -164
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-observation.js +0 -251
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-service-status.js +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-source-status.js +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/lib/chart-sources.js +0 -354
- package/node_modules/@ftshare-lab/dsh-kline/lib/client.js +0 -17581
- package/node_modules/@ftshare-lab/dsh-kline/lib/drawing-feedback.js +0 -284
- package/node_modules/@ftshare-lab/dsh-kline/lib/fibonacci.js +0 -18
- package/node_modules/@ftshare-lab/dsh-kline/lib/ftshare-settings-bridge.js +0 -159
- package/node_modules/@ftshare-lab/dsh-kline/lib/index.js +0 -279
- package/node_modules/@ftshare-lab/dsh-kline/lib/labeled-polyline.js +0 -17
- package/node_modules/@ftshare-lab/dsh-kline/lib/pattern-groups.js +0 -91
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-bands.js +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-series.js +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/price-sticks.js +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/candle-sequence.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-adjustment.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-annotations.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-applications.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-context.d.ts +0 -14
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-observation.d.ts +0 -8
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-service-status.d.ts +0 -22
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-source-status.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/chart-sources.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/BetterSidebarTab.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ClassicShell.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/KlineContent.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/PanelHost.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-apply.d.ts +0 -13
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-context.d.ts +0 -23
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-handoff.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/chart-session-resolver.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/client-context.d.ts +0 -16
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/conversation.d.ts +0 -43
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/default-tab.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/embed.d.ts +0 -37
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/generated-view.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/horizontal-lines.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-options.d.ts +0 -38
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/host-panels.d.ts +0 -55
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/index.d.ts +0 -4
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/mode-preferences.d.ts +0 -25
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-contract.d.ts +0 -52
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-register.d.ts +0 -46
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar-services.d.ts +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/native-sidebar.d.ts +0 -47
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/sidebar-integration.d.ts +0 -12
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/ui-onboarding.d.ts +0 -7
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/client/version.d.ts +0 -1
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/drawing-feedback.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/fibonacci.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/ftshare-settings-bridge.d.ts +0 -50
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/index.d.ts +0 -26
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/labeled-polyline.d.ts +0 -11
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/pattern-groups.d.ts +0 -2
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-bands.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-series.d.ts +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/lib/types/price-sticks.d.ts +0 -3
- package/node_modules/@ftshare-lab/dsh-kline/package.json +0 -157
- package/node_modules/@ftshare-lab/dsh-kline/requirements.txt +0 -6
- package/node_modules/@ftshare-lab/dsh-kline/scripts/bootstrap.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-bootstrap.mjs +0 -179
- package/node_modules/@ftshare-lab/dsh-kline/scripts/dsh-mcp-plugin.mjs +0 -27
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.mjs +0 -658
- package/node_modules/@ftshare-lab/dsh-kline/scripts/run-dsh-kline.sh +0 -5
- package/node_modules/@ftshare-lab/dsh-kline/server.py +0 -1755
- package/node_modules/@ftshare-lab/dsh-kline/tools/__init__.py +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/tools/annotations.py +0 -119
- package/node_modules/@ftshare-lab/dsh-kline/tools/automatic_analysis.py +0 -158
- package/node_modules/@ftshare-lab/dsh-kline/tools/baostock_source.py +0 -176
- package/node_modules/@ftshare-lab/dsh-kline/tools/calc.py +0 -39
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_candidates.py +0 -260
- package/node_modules/@ftshare-lab/dsh-kline/tools/channel_preview.py +0 -82
- package/node_modules/@ftshare-lab/dsh-kline/tools/channels.py +0 -104
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_applications.py +0 -204
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_context.py +0 -186
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_edits.py +0 -363
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_functions.py +0 -451
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_indicators.py +0 -65
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_measurements.py +0 -84
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_source_status.py +0 -32
- package/node_modules/@ftshare-lab/dsh-kline/tools/chart_sources.py +0 -31
- package/node_modules/@ftshare-lab/dsh-kline/tools/closed_daily.py +0 -68
- package/node_modules/@ftshare-lab/dsh-kline/tools/draw.py +0 -410
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_feedback.py +0 -45
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_interaction.py +0 -117
- package/node_modules/@ftshare-lab/dsh-kline/tools/drawing_verification.py +0 -141
- package/node_modules/@ftshare-lab/dsh-kline/tools/fetch.py +0 -4680
- package/node_modules/@ftshare-lab/dsh-kline/tools/fibonacci.py +0 -83
- package/node_modules/@ftshare-lab/dsh-kline/tools/foreign_daily.py +0 -185
- package/node_modules/@ftshare-lab/dsh-kline/tools/free_sources.py +0 -483
- package/node_modules/@ftshare-lab/dsh-kline/tools/lines.py +0 -91
- package/node_modules/@ftshare-lab/dsh-kline/tools/nine_count.py +0 -66
- package/node_modules/@ftshare-lab/dsh-kline/tools/pattern_groups.py +0 -103
- package/node_modules/@ftshare-lab/dsh-kline/tools/pivots.py +0 -60
- package/node_modules/@ftshare-lab/dsh-kline/tools/polylines.py +0 -131
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_bands.py +0 -165
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_patterns.py +0 -311
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_series.py +0 -162
- package/node_modules/@ftshare-lab/dsh-kline/tools/price_sticks.py +0 -114
- package/node_modules/@ftshare-lab/dsh-kline/tools/range_candidates.py +0 -170
- package/node_modules/@ftshare-lab/dsh-kline/tools/recent_drawing_candidates.py +0 -123
- package/node_modules/@ftshare-lab/dsh-kline/tools/rectangles.py +0 -76
- package/node_modules/@ftshare-lab/dsh-kline/tools/regression_channels.py +0 -87
- package/node_modules/@ftshare-lab/dsh-kline/tools/ta_functions.py +0 -228
- package/node_modules/@ftshare-lab/dsh-kline/tools/trend_lines.py +0 -106
- package/node_modules/@ftshare-lab/dsh-kline/tools/watchlist.py +0 -149
- package/node_modules/@ftshare-lab/dsh-kline/view/ft-logo.jpg +0 -0
- package/node_modules/@ftshare-lab/dsh-kline/view/vendor/klinecharts.min.js +0 -7
|
@@ -1,311 +0,0 @@
|
|
|
1
|
-
"""Causal, read-only daily price patterns. Shared by DSH and Codex hosts."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
from collections import Counter
|
|
5
|
-
from datetime import datetime
|
|
6
|
-
from math import isfinite
|
|
7
|
-
|
|
8
|
-
import numpy as np
|
|
9
|
-
import talib
|
|
10
|
-
|
|
11
|
-
from tools.closed_daily import closed_daily
|
|
12
|
-
from tools.lines import LineError
|
|
13
|
-
from tools.range_candidates import DEFAULT_WINDOW_SIZES, range_candidates
|
|
14
|
-
|
|
15
|
-
RULE_VERSION = "price_patterns_v1"
|
|
16
|
-
TYPES = ("double_top", "double_bottom", "head_shoulders_top", "head_shoulders_bottom", "platform")
|
|
17
|
-
# The older, geometry-only range proposal tolerates a half-box close drift.
|
|
18
|
-
# A labelled price pattern needs a visibly flatter base. Keep that proposal
|
|
19
|
-
# API unchanged, but reject directional boxes during historical replay.
|
|
20
|
-
MAX_PLATFORM_DRIFT_TO_WIDTH = .35
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
def _pivots(rows):
|
|
24
|
-
result = {}
|
|
25
|
-
for index in range(2, len(rows) - 2):
|
|
26
|
-
neighbors = rows[index - 2:index] + rows[index + 1:index + 3]
|
|
27
|
-
high = all(rows[index]["high"] > x["high"] for x in neighbors)
|
|
28
|
-
low = all(rows[index]["low"] < x["low"] for x in neighbors)
|
|
29
|
-
if high != low:
|
|
30
|
-
result.setdefault(index + 2, []).append({"index": index, "side": "high" if high else "low",
|
|
31
|
-
"price": rows[index]["high"] if high else rows[index]["low"],
|
|
32
|
-
"time": rows[index]["time"]})
|
|
33
|
-
return result
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
def _neckline(anchors, index):
|
|
37
|
-
a, b = anchors[1], anchors[3]
|
|
38
|
-
return a["price"] + (b["price"] - a["price"]) * (index - a["index"]) / (b["index"] - a["index"])
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
def _structure(kind, anchors, atr, rows, reasons):
|
|
42
|
-
top = kind.endswith("top")
|
|
43
|
-
first = anchors[0]["index"]
|
|
44
|
-
# Twenty completed intervals before the anchor require 21 earlier closes.
|
|
45
|
-
# At first == 20, first - 21 would wrap to the final (future) row.
|
|
46
|
-
if first < 21:
|
|
47
|
-
reasons["insufficient_prior_trend"] += 1
|
|
48
|
-
return None
|
|
49
|
-
trend = rows[first - 1]["close"] - rows[first - 21]["close"]
|
|
50
|
-
if (trend if top else -trend) < 2 * atr:
|
|
51
|
-
reasons["prior_trend_below_2_atr"] += 1
|
|
52
|
-
return None
|
|
53
|
-
if kind.startswith("double"):
|
|
54
|
-
a, middle, b = anchors
|
|
55
|
-
gap = b["index"] - a["index"]
|
|
56
|
-
mean = (a["price"] + b["price"]) / 2
|
|
57
|
-
depth = (min(a["price"], b["price"]) - middle["price"]) if top else (middle["price"] - max(a["price"], b["price"]))
|
|
58
|
-
if not 10 <= gap <= 120 or abs(a["price"] - b["price"]) > min(atr, .03 * mean) or depth < 2 * atr:
|
|
59
|
-
reasons["double_geometry_rejected"] += 1
|
|
60
|
-
return None
|
|
61
|
-
neck = middle["price"]
|
|
62
|
-
outer = max(a["price"], b["price"]) if top else min(a["price"], b["price"])
|
|
63
|
-
return {"neckline": {"type": "horizontal", "price": neck}, "outer": outer}
|
|
64
|
-
a, n1, head, n2, b = anchors
|
|
65
|
-
gaps = [anchors[j + 1]["index"] - anchors[j]["index"] for j in range(4)]
|
|
66
|
-
span = b["index"] - a["index"]
|
|
67
|
-
left, right = head["index"] - a["index"], b["index"] - head["index"]
|
|
68
|
-
neck_at_head = _neckline(anchors, head["index"])
|
|
69
|
-
height = (head["price"] - neck_at_head) if top else (neck_at_head - head["price"])
|
|
70
|
-
mean_shoulder = (a["price"] + b["price"]) / 2
|
|
71
|
-
protrudes = min((head["price"] - a["price"] if top else a["price"] - head["price"]),
|
|
72
|
-
(head["price"] - b["price"] if top else b["price"] - head["price"]))
|
|
73
|
-
if (min(gaps) < 3 or not 20 <= span <= 160 or not .5 <= left / right <= 2
|
|
74
|
-
or protrudes < atr or height < 2 * atr or abs(a["price"] - b["price"]) > min(.5 * height, .03 * mean_shoulder)
|
|
75
|
-
or abs(n1["price"] - n2["price"]) > .5 * height):
|
|
76
|
-
reasons["head_shoulders_geometry_rejected"] += 1
|
|
77
|
-
return None
|
|
78
|
-
return {"neckline": {"type": "sloped", "from": {"index": n1["index"], "time": n1["time"], "price": n1["price"]},
|
|
79
|
-
"to": {"index": n2["index"], "time": n2["time"], "price": n2["price"]}},
|
|
80
|
-
"outer": head["price"]}
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
def _boundary(item, index):
|
|
84
|
-
if item["type"] == "platform":
|
|
85
|
-
return item["box"]
|
|
86
|
-
neck = item["neckline"]
|
|
87
|
-
if neck["type"] == "horizontal":
|
|
88
|
-
return neck["price"]
|
|
89
|
-
a, b = neck["from"], neck["to"]
|
|
90
|
-
return a["price"] + (b["price"] - a["price"]) * (index - a["index"]) / (b["index"] - a["index"])
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def _outside(item, row, index, direction):
|
|
94
|
-
base = _boundary(item, index)
|
|
95
|
-
if item["type"] == "platform":
|
|
96
|
-
edge = base["upper_price"] if direction == "up" else base["lower_price"]
|
|
97
|
-
else:
|
|
98
|
-
edge = base
|
|
99
|
-
return row["close"] > edge + item["buffer"] if direction == "up" else row["close"] < edge - item["buffer"]
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def _reclaimed(item, row, index):
|
|
103
|
-
base = _boundary(item, index)
|
|
104
|
-
if item["type"] == "platform":
|
|
105
|
-
# Back inside the frozen box, not merely below its upper breakout edge.
|
|
106
|
-
return (row["close"] < base["upper_price"] - item["buffer"] if item["break_direction"] == "up"
|
|
107
|
-
else row["close"] > base["lower_price"] + item["buffer"])
|
|
108
|
-
return (row["close"] > base + item["buffer"] if item["break_direction"] == "down"
|
|
109
|
-
else row["close"] < base - item["buffer"])
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
def _advance(item, row, index):
|
|
113
|
-
if item["status"] in {"structurally_invalid", "expired", "breakout_failed"}:
|
|
114
|
-
return
|
|
115
|
-
def event(name):
|
|
116
|
-
item["events"].append({"type": name, "time": row["time"], "index": index})
|
|
117
|
-
if item["confirmed_index"] is None:
|
|
118
|
-
if item["type"] != "platform" and ((item["direction"] == "down" and row["high"] > item["outer"] + item["buffer"])
|
|
119
|
-
or (item["direction"] == "up" and row["low"] < item["outer"] - item["buffer"])):
|
|
120
|
-
item["status"] = "structurally_invalid"; item["invalidated_at"] = row["time"]; event("structurally_invalid"); return
|
|
121
|
-
if index - item["available_index"] > 60:
|
|
122
|
-
item["status"] = "expired"; item["invalidated_at"] = row["time"]; event("expired"); return
|
|
123
|
-
direction = item.get("pending_direction") or item["direction"]
|
|
124
|
-
if item["pending_direction"] and _outside(item, row, index, direction):
|
|
125
|
-
item["status"] = "price_confirmed"; item["confirmed_at"] = row["time"]
|
|
126
|
-
item["confirmed_index"] = index; item["break_direction"] = direction
|
|
127
|
-
item["pending_direction"] = None; event("price_confirmed")
|
|
128
|
-
return
|
|
129
|
-
if item["pending_direction"]:
|
|
130
|
-
item["pending_direction"] = None; item["status"] = "candidate"; event("pending_cancelled")
|
|
131
|
-
directions = ("up", "down") if item["type"] == "platform" else (item["direction"],)
|
|
132
|
-
for side in directions:
|
|
133
|
-
if _outside(item, row, index, side):
|
|
134
|
-
item["pending_direction"] = side; item["status"] = "pending_confirmation"; event("pending_confirmation"); break
|
|
135
|
-
return
|
|
136
|
-
age = index - item["confirmed_index"]
|
|
137
|
-
if age > 20 or item["followup_complete"]:
|
|
138
|
-
return
|
|
139
|
-
if _reclaimed(item, row, index):
|
|
140
|
-
item["reclaim_count"] += 1
|
|
141
|
-
if item["reclaim_count"] == 2:
|
|
142
|
-
item["status"] = "breakout_failed"; item["invalidated_at"] = row["time"]; event("breakout_failed")
|
|
143
|
-
return
|
|
144
|
-
else:
|
|
145
|
-
item["reclaim_count"] = 0
|
|
146
|
-
if age == 20:
|
|
147
|
-
item["followup_complete"] = True; event("followup_complete")
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
def _volume_evidence(rows, item, provider, volume_unit):
|
|
151
|
-
if provider not in {"ftshare", "eastmoney_free", "tencent_free", "builtin_free"} or volume_unit not in {"shares", "lots"}:
|
|
152
|
-
return {"status": "unknown", "reason": "source_or_unit_unverified"}
|
|
153
|
-
i = item["confirmed_index"]
|
|
154
|
-
if i is None or i < 20:
|
|
155
|
-
return {"status": "unknown", "reason": "insufficient_preceding_volume"}
|
|
156
|
-
baseline = [r["volume"] for r in rows[i - 20:i]]
|
|
157
|
-
if any(not isfinite(x) or x < 0 for x in baseline) or sum(baseline) <= 0:
|
|
158
|
-
return {"status": "unknown", "reason": "volume_unavailable"}
|
|
159
|
-
return {"status": "known", "relative_to_preceding_20": rows[i]["volume"] / (sum(baseline) / 20),
|
|
160
|
-
"unit": volume_unit}
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
def _same_platform_family(a, b):
|
|
164
|
-
"""Coalesce near-identical displayed boxes without changing their lifecycle."""
|
|
165
|
-
if a["type"] != "platform" or b["type"] != "platform":
|
|
166
|
-
return False
|
|
167
|
-
tolerance = .25 * min(a["atr"], b["atr"])
|
|
168
|
-
return (a["status"] == b["status"] and a["confirmed_at"] == b["confirmed_at"]
|
|
169
|
-
and a["break_direction"] == b["break_direction"]
|
|
170
|
-
and abs(a["available_index"] - b["available_index"]) <= 3
|
|
171
|
-
and abs(a["box"]["upper_price"] - b["box"]["upper_price"]) <= tolerance
|
|
172
|
-
and abs(a["box"]["lower_price"] - b["box"]["lower_price"]) <= tolerance)
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
def _alternating_platform_touches(box):
|
|
176
|
-
"""A rectangle needs boundary visits in alternating time order.
|
|
177
|
-
|
|
178
|
-
Two upper touches followed by two lower touches describe a directional
|
|
179
|
-
move, even when a broad envelope and its fitted close drift pass.
|
|
180
|
-
"""
|
|
181
|
-
touches = sorted([(time, "upper") for time in box["upper_touch_times"]]
|
|
182
|
-
+ [(time, "lower") for time in box["lower_touch_times"]])
|
|
183
|
-
if any(touches[i][0] == touches[i - 1][0] for i in range(1, len(touches))):
|
|
184
|
-
return False
|
|
185
|
-
return 1 + sum(touches[i][1] != touches[i - 1][1] for i in range(1, len(touches))) >= 3
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
def price_pattern_candidates(rows, *, symbol: str, interval: str = "day", source_interval: str | None = "day",
|
|
189
|
-
interval_value: int | None = 1, provider: str | None = None,
|
|
190
|
-
volume_unit: str | None = None, pattern_types=None,
|
|
191
|
-
lookback_bars: int = 240, max_candidates: int = 5,
|
|
192
|
-
anchor_times: tuple[int, ...] | None = None, now: datetime | None = None):
|
|
193
|
-
if type(lookback_bars) is not int or not 60 <= lookback_bars <= 300:
|
|
194
|
-
raise LineError("invalid_pattern_lookback", "价格形态观察范围必须为60至300根日线。")
|
|
195
|
-
if type(max_candidates) is not int or not 1 <= max_candidates <= 5:
|
|
196
|
-
raise LineError("invalid_pattern_limit", "价格形态最多返回1至5个候选。")
|
|
197
|
-
selected = tuple(pattern_types or TYPES)
|
|
198
|
-
if not selected or len(set(selected)) != len(selected) or any(x not in TYPES for x in selected):
|
|
199
|
-
raise LineError("invalid_pattern_types", "形态类型仅支持双顶、双底、头肩顶、头肩底及平台,且不得重复。")
|
|
200
|
-
if anchor_times is not None and (len(anchor_times) not in {3, 5}
|
|
201
|
-
or any(type(t) is not int for t in anchor_times)
|
|
202
|
-
or tuple(sorted(set(anchor_times))) != anchor_times):
|
|
203
|
-
raise LineError("invalid_pattern_anchor_selection", "请按时间顺序选择3个或5个不同的 K 线锚点。")
|
|
204
|
-
candles, metadata = closed_daily(rows, symbol=symbol, interval=interval, source_interval=source_interval,
|
|
205
|
-
interval_value=interval_value, provider=provider, now=now)
|
|
206
|
-
candles = candles[-4000:]
|
|
207
|
-
if len(candles) < 35:
|
|
208
|
-
raise LineError("insufficient_pattern_history", "价格形态需要至少35根已收盘日线,未补取行情。")
|
|
209
|
-
atr_values = talib.ATR(np.asarray([x["high"] for x in candles], dtype=float),
|
|
210
|
-
np.asarray([x["low"] for x in candles], dtype=float),
|
|
211
|
-
np.asarray([x["close"] for x in candles], dtype=float), timeperiod=14)
|
|
212
|
-
pivot_events = _pivots(candles)
|
|
213
|
-
alternating = []
|
|
214
|
-
active = []
|
|
215
|
-
results = []
|
|
216
|
-
reasons = Counter()
|
|
217
|
-
seen = set()
|
|
218
|
-
active_boxes = {}
|
|
219
|
-
for index, row in enumerate(candles):
|
|
220
|
-
atr = float(atr_values[index])
|
|
221
|
-
for pivot in pivot_events.get(index, ()):
|
|
222
|
-
if alternating and alternating[-1]["side"] == pivot["side"]:
|
|
223
|
-
if ((pivot["side"] == "high" and pivot["price"] > alternating[-1]["price"])
|
|
224
|
-
or (pivot["side"] == "low" and pivot["price"] < alternating[-1]["price"])):
|
|
225
|
-
alternating[-1] = pivot
|
|
226
|
-
continue
|
|
227
|
-
alternating.append(pivot)
|
|
228
|
-
alternating = alternating[-5:]
|
|
229
|
-
if not isfinite(atr) or atr <= 0:
|
|
230
|
-
reasons["atr_unavailable"] += 1
|
|
231
|
-
continue
|
|
232
|
-
for size, prefix, side in ((3, "double", "high"), (5, "head_shoulders", "high"),
|
|
233
|
-
(3, "double", "low"), (5, "head_shoulders", "low")):
|
|
234
|
-
kind = prefix + ("_top" if side == "high" else "_bottom")
|
|
235
|
-
if kind not in selected or len(alternating) < size:
|
|
236
|
-
continue
|
|
237
|
-
anchors = alternating[-size:]
|
|
238
|
-
if anchors[0]["side"] != side:
|
|
239
|
-
continue
|
|
240
|
-
key = (kind, tuple(p["index"] for p in anchors))
|
|
241
|
-
if key in seen:
|
|
242
|
-
continue
|
|
243
|
-
seen.add(key)
|
|
244
|
-
shape = _structure(kind, anchors, atr, candles, reasons)
|
|
245
|
-
if shape is None:
|
|
246
|
-
continue
|
|
247
|
-
item = {"type": kind, "anchors": [dict(p) for p in anchors], **shape,
|
|
248
|
-
"direction": "down" if side == "high" else "up", "atr": atr, "buffer": .25 * atr,
|
|
249
|
-
"available_at": row["time"], "available_index": index,
|
|
250
|
-
"as_of": metadata["as_of"], "status": "candidate", "events": [{"type": "candidate", "time": row["time"], "index": index}],
|
|
251
|
-
"pending_direction": None, "break_direction": None, "confirmed_at": None,
|
|
252
|
-
"confirmed_index": None, "invalidated_at": None, "reclaim_count": 0,
|
|
253
|
-
"followup_complete": False}
|
|
254
|
-
active.append(item); results.append(item)
|
|
255
|
-
if "platform" in selected and index >= min(DEFAULT_WINDOW_SIZES) - 1 and isfinite(atr) and atr > 0:
|
|
256
|
-
proposed = range_candidates(candles[max(0, index - max(DEFAULT_WINDOW_SIZES) + 1):index + 1],
|
|
257
|
-
window_sizes=DEFAULT_WINDOW_SIZES, limit=5)
|
|
258
|
-
for box in proposed["candidates"]:
|
|
259
|
-
if any(box[field] > MAX_PLATFORM_DRIFT_TO_WIDTH for field in (
|
|
260
|
-
"close_drift_to_width", "fitted_close_drift_to_width",
|
|
261
|
-
"recent_close_drift_to_width", "recent_fitted_close_drift_to_width")):
|
|
262
|
-
reasons["platform_directional_drift"] += 1
|
|
263
|
-
continue
|
|
264
|
-
if not _alternating_platform_touches(box):
|
|
265
|
-
reasons["platform_non_alternating_touches"] += 1
|
|
266
|
-
continue
|
|
267
|
-
key = (box["lower_price"], box["upper_price"])
|
|
268
|
-
if key in active_boxes:
|
|
269
|
-
continue
|
|
270
|
-
item = {"type": "platform", "anchors": [], "box": {k: box[k] for k in ("start_time", "end_time", "lower_price", "upper_price")},
|
|
271
|
-
"direction": None, "atr": atr, "buffer": .25 * atr,
|
|
272
|
-
"available_at": row["time"], "available_index": index, "as_of": metadata["as_of"],
|
|
273
|
-
"status": "candidate", "events": [{"type": "candidate", "time": row["time"], "index": index}], "pending_direction": None, "break_direction": None,
|
|
274
|
-
"confirmed_at": None, "confirmed_index": None, "invalidated_at": None,
|
|
275
|
-
"reclaim_count": 0, "followup_complete": False}
|
|
276
|
-
active_boxes[key] = item; active.append(item); results.append(item)
|
|
277
|
-
for item in active[:]:
|
|
278
|
-
if index > item["available_index"]:
|
|
279
|
-
_advance(item, row, index)
|
|
280
|
-
if item["status"] in {"structurally_invalid", "expired", "breakout_failed"} or item["followup_complete"]:
|
|
281
|
-
active.remove(item)
|
|
282
|
-
if item["type"] == "platform":
|
|
283
|
-
active_boxes.pop((item["box"]["lower_price"], item["box"]["upper_price"]), None)
|
|
284
|
-
if index > 300:
|
|
285
|
-
results = [r for r in results if r["available_index"] >= index - 300]
|
|
286
|
-
earliest = len(candles) - lookback_bars
|
|
287
|
-
recent = [r for r in results if r["available_index"] >= earliest]
|
|
288
|
-
if anchor_times is not None:
|
|
289
|
-
recent = [r for r in recent if tuple(a["time"] for a in r["anchors"]) == anchor_times]
|
|
290
|
-
if not recent: reasons["manual_selection_not_recognized"] += 1
|
|
291
|
-
recent.sort(key=lambda r: (r["available_index"], r["type"], tuple(a["index"] for a in r["anchors"])), reverse=True)
|
|
292
|
-
distinct = []
|
|
293
|
-
nearby_suppressed = 0
|
|
294
|
-
for item in recent:
|
|
295
|
-
if any(_same_platform_family(item, prior) for prior in distinct):
|
|
296
|
-
nearby_suppressed += 1
|
|
297
|
-
else:
|
|
298
|
-
distinct.append(item)
|
|
299
|
-
recent = distinct
|
|
300
|
-
for item in recent:
|
|
301
|
-
item["volume_evidence"] = _volume_evidence(candles, item, provider, volume_unit)
|
|
302
|
-
item.pop("pending_direction", None); item.pop("reclaim_count", None)
|
|
303
|
-
item.pop("confirmed_index", None); item.pop("available_index", None)
|
|
304
|
-
item.pop("followup_complete", None)
|
|
305
|
-
return {"rule_version": RULE_VERSION, "as_of": metadata["as_of"], "data_quality": metadata,
|
|
306
|
-
"lookback_bars": lookback_bars, "loaded_bars": len(candles),
|
|
307
|
-
"candidate_count": len(recent), "returned": min(len(recent), max_candidates),
|
|
308
|
-
"truncated": len(recent) > max_candidates, "nearby_platforms_suppressed": nearby_suppressed,
|
|
309
|
-
"rejected_reasons": dict(reasons),
|
|
310
|
-
"candidates": recent[:max_candidates], "drawing_created": False,
|
|
311
|
-
"limitations": ["rule_based_geometry_not_trading_forecast"]}
|
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
"""Deterministic price-series lines on the currently loaded candles only."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
from copy import deepcopy
|
|
5
|
-
import hashlib
|
|
6
|
-
import json
|
|
7
|
-
import math
|
|
8
|
-
import secrets
|
|
9
|
-
import struct
|
|
10
|
-
from typing import Literal
|
|
11
|
-
|
|
12
|
-
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
|
13
|
-
|
|
14
|
-
from core.calc import series_ma
|
|
15
|
-
from core.ta_engine import calculate
|
|
16
|
-
from tools.lines import LineError, validate_line_fields
|
|
17
|
-
|
|
18
|
-
SERIES_COMMAND = "DRAW_AGENT_SERIES_LINE"
|
|
19
|
-
MAX_SERIES_LINES = 8
|
|
20
|
-
MAX_SERIES_BARS = 4000
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
def candle_sequence_hash(rows):
|
|
24
|
-
"""Stable browser-compatible identity for candle-index-aligned drawings."""
|
|
25
|
-
value = 0xcbf29ce484222325
|
|
26
|
-
for row in rows:
|
|
27
|
-
for key in ("time", "open", "high", "low", "close", "volume"):
|
|
28
|
-
for byte in struct.pack(">d", float(row[key])):
|
|
29
|
-
value = ((value ^ byte) * 0x100000001b3) & 0xffffffffffffffff
|
|
30
|
-
return f"{value:016x}"
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
class PriceSource(BaseModel):
|
|
34
|
-
model_config = ConfigDict(extra="forbid")
|
|
35
|
-
kind: Literal["open", "high", "low", "close", "sma", "ema"]
|
|
36
|
-
period: int | None = Field(default=None, strict=True, ge=2, le=200)
|
|
37
|
-
|
|
38
|
-
@model_validator(mode="after")
|
|
39
|
-
def valid_period(self):
|
|
40
|
-
if (self.kind in {"sma", "ema"}) != (self.period is not None):
|
|
41
|
-
raise ValueError("period is required only for sma or ema")
|
|
42
|
-
return self
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
class PriceOperand(BaseModel):
|
|
46
|
-
model_config = ConfigDict(extra="forbid")
|
|
47
|
-
source: PriceSource | None = None
|
|
48
|
-
constant: float | None = Field(default=None, strict=True, gt=0, allow_inf_nan=False)
|
|
49
|
-
|
|
50
|
-
@model_validator(mode="after")
|
|
51
|
-
def one_value(self):
|
|
52
|
-
if (self.source is None) == (self.constant is None):
|
|
53
|
-
raise ValueError("exactly one of source or constant is required")
|
|
54
|
-
return self
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
class PriceCondition(BaseModel):
|
|
58
|
-
model_config = ConfigDict(extra="forbid")
|
|
59
|
-
left: PriceSource
|
|
60
|
-
op: Literal["gt", "gte", "lt", "lte"]
|
|
61
|
-
right: PriceOperand
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
def _source_values(rows, source: PriceSource):
|
|
65
|
-
if source.kind not in {"sma", "ema"}:
|
|
66
|
-
return [row[source.kind] for row in rows]
|
|
67
|
-
if source.kind == "sma":
|
|
68
|
-
ma = series_ma(rows, [source.period])[f"ma{source.period}"]
|
|
69
|
-
return [ma.get(row["time"]) for row in rows]
|
|
70
|
-
return calculate("EMA", rows, parameters={"timeperiod": source.period})[1]["real"]
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
def calculate_price_series(rows, source: PriceSource, condition: PriceCondition | None = None):
|
|
74
|
-
if not isinstance(rows, list) or not 1 <= len(rows) <= MAX_SERIES_BARS:
|
|
75
|
-
raise LineError("invalid_price_series_history", "仅支持当前图1至4000根已加载K线,不补取行情。")
|
|
76
|
-
values = _source_values(rows, source)
|
|
77
|
-
left = _source_values(rows, condition.left) if condition else None
|
|
78
|
-
right = (_source_values(rows, condition.right.source) if condition and condition.right.source else
|
|
79
|
-
[condition.right.constant] * len(rows) if condition else None)
|
|
80
|
-
operations = {"gt": lambda a, b: a > b, "gte": lambda a, b: a >= b,
|
|
81
|
-
"lt": lambda a, b: a < b, "lte": lambda a, b: a <= b}
|
|
82
|
-
output = []
|
|
83
|
-
for index, value in enumerate(values):
|
|
84
|
-
allowed = (condition is None or left[index] is not None and right[index] is not None
|
|
85
|
-
and operations[condition.op](left[index], right[index]))
|
|
86
|
-
output.append(float(value) if value is not None and allowed else None)
|
|
87
|
-
matches = sum(value is not None for value in output)
|
|
88
|
-
segments = sum(value is not None and (index == 0 or output[index - 1] is None)
|
|
89
|
-
for index, value in enumerate(output))
|
|
90
|
-
return {"values": output, "summary": {"loaded_bars": len(rows), "matched_bars": matches,
|
|
91
|
-
"segment_count": segments, "empty": matches == 0,
|
|
92
|
-
"warmup_or_condition_gaps": len(rows) - matches, "drawing_created": False}}
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
def validate_series_values(values, count):
|
|
96
|
-
if (not isinstance(values, list) or len(values) != count or not 1 <= count <= MAX_SERIES_BARS
|
|
97
|
-
or any(value is not None and (type(value) not in (int, float) or not math.isfinite(value) or value <= 0)
|
|
98
|
-
for value in values)):
|
|
99
|
-
raise LineError("invalid_price_series_values", "序列长度、价格或当前K线对齐关系无效。")
|
|
100
|
-
if not any(value is not None for value in values):
|
|
101
|
-
raise LineError("empty_price_series", "条件没有命中可绘制K线,未创建空图形。")
|
|
102
|
-
return list(values)
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
def edit_price_series(payload, action, *, series_id=None, source=None, condition=None, values=None,
|
|
106
|
-
name=None, color=None, request_id=None):
|
|
107
|
-
result = deepcopy(payload)
|
|
108
|
-
commands = result.get("chartCommands", [])
|
|
109
|
-
rows = next((c["rows"] for c in commands if c.get("type") == "SET_CANDLES"), [])
|
|
110
|
-
matches = [c for c in commands if c.get("type") == SERIES_COMMAND and c.get("id") == series_id]
|
|
111
|
-
if len(matches) > 1:
|
|
112
|
-
raise LineError("ambiguous_drawing_id", "同一序列对象 ID 不唯一,不能安全修改。")
|
|
113
|
-
previous = matches[0] if matches else None
|
|
114
|
-
if action in {"update", "delete"} and previous is None:
|
|
115
|
-
raise LineError("series_line_not_found", "当前快照不存在该 AI 序列线,请先读回对象 ID。")
|
|
116
|
-
if action == "delete":
|
|
117
|
-
if any(item is not None for item in (source, condition, values, name, color)):
|
|
118
|
-
raise LineError("invalid_edit_fields", "删除序列线只需对象 ID。")
|
|
119
|
-
commands.remove(previous)
|
|
120
|
-
return result, deepcopy(previous)
|
|
121
|
-
if action not in {"create", "update"}:
|
|
122
|
-
raise LineError("invalid_action", "不支持的序列线操作。")
|
|
123
|
-
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
124
|
-
if action == "create" and (source is None or values is None):
|
|
125
|
-
raise LineError("series_result_required", "创建序列线必须使用函数结果引用。")
|
|
126
|
-
if (source is None) != (values is None):
|
|
127
|
-
raise LineError("series_result_required", "修改计算条件时须重新运行函数并传完整结果引用。")
|
|
128
|
-
if action == "update" and source is None and name is None and color is None:
|
|
129
|
-
raise LineError("empty_update", "请指定新函数结果、名称或颜色。")
|
|
130
|
-
if values is not None:
|
|
131
|
-
clean = validate_series_values(values, len(rows))
|
|
132
|
-
normalized_source = PriceSource.model_validate(source).model_dump(exclude_none=True)
|
|
133
|
-
normalized_condition = (PriceCondition.model_validate(condition).model_dump(exclude_none=True)
|
|
134
|
-
if condition is not None else None)
|
|
135
|
-
else:
|
|
136
|
-
clean = validate_series_values(previous["values"], len(rows))
|
|
137
|
-
normalized_source, normalized_condition = previous["source"], previous.get("condition")
|
|
138
|
-
obj = {"type": SERIES_COMMAND, "id": previous["id"] if previous else "series_" + secrets.token_hex(12),
|
|
139
|
-
"interval": payload.get("interval"), "bar_count": len(rows),
|
|
140
|
-
"row_hash": candle_sequence_hash(rows),
|
|
141
|
-
"source": normalized_source, "condition": normalized_condition, "values": clean,
|
|
142
|
-
"label": name if name is not None else previous.get("label", "") if previous else "",
|
|
143
|
-
"color": color if color is not None else previous.get("color", "info") if previous else "info"}
|
|
144
|
-
obj["series_hash"] = hashlib.sha256(json.dumps({"source": normalized_source, "condition": normalized_condition,
|
|
145
|
-
"values": clean}, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
|
|
146
|
-
if previous and previous.get("create_request_id"):
|
|
147
|
-
obj["create_request_id"] = previous["create_request_id"]
|
|
148
|
-
if action == "create":
|
|
149
|
-
if request_id:
|
|
150
|
-
obj["create_request_id"] = request_id
|
|
151
|
-
obj["id"] = "series_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
152
|
-
retry = next((c for c in commands if c.get("type") == SERIES_COMMAND and c.get("create_request_id") == request_id), None)
|
|
153
|
-
if retry:
|
|
154
|
-
if any(retry.get(key) != obj[key] for key in ("bar_count", "source", "condition", "values", "label", "color", "interval")):
|
|
155
|
-
raise LineError("request_conflict", "同一 request_id 的序列线参数不同。")
|
|
156
|
-
return result, deepcopy(retry)
|
|
157
|
-
if sum(c.get("type") == SERIES_COMMAND for c in commands) >= MAX_SERIES_LINES:
|
|
158
|
-
raise LineError("too_many_series_lines", "当前图表最多保存8条 AI 序列线。")
|
|
159
|
-
commands.append(obj)
|
|
160
|
-
else:
|
|
161
|
-
commands[commands.index(previous)] = obj
|
|
162
|
-
return result, deepcopy(obj)
|
|
@@ -1,114 +0,0 @@
|
|
|
1
|
-
"""Deterministic, bounded per-candle sticks on the current price pane."""
|
|
2
|
-
from __future__ import annotations
|
|
3
|
-
|
|
4
|
-
from copy import deepcopy
|
|
5
|
-
import hashlib
|
|
6
|
-
import json
|
|
7
|
-
import math
|
|
8
|
-
import secrets
|
|
9
|
-
|
|
10
|
-
from tools.lines import LineError, validate_line_fields
|
|
11
|
-
from tools.price_series import (PriceCondition, PriceSource, MAX_SERIES_BARS,
|
|
12
|
-
calculate_price_series, candle_sequence_hash)
|
|
13
|
-
|
|
14
|
-
STICKS_COMMAND = "DRAW_AGENT_PRICE_STICKS"
|
|
15
|
-
MAX_PRICE_STICKS = 4
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def calculate_price_sticks(rows, first_source: PriceSource, second_source: PriceSource,
|
|
19
|
-
condition: PriceCondition | None = None):
|
|
20
|
-
first = calculate_price_series(rows, first_source, condition)["values"]
|
|
21
|
-
second = calculate_price_series(rows, second_source, condition)["values"]
|
|
22
|
-
start, end = [], []
|
|
23
|
-
equal_endpoints = 0
|
|
24
|
-
for one, two in zip(first, second):
|
|
25
|
-
if one is None or two is None or one == two:
|
|
26
|
-
start.append(None)
|
|
27
|
-
end.append(None)
|
|
28
|
-
if one is not None and two is not None: equal_endpoints += 1
|
|
29
|
-
else:
|
|
30
|
-
start.append(one)
|
|
31
|
-
end.append(two)
|
|
32
|
-
matches = sum(value is not None for value in start)
|
|
33
|
-
return {"start_values": start, "end_values": end,
|
|
34
|
-
"summary": {"loaded_bars": len(rows), "matched_bars": matches,
|
|
35
|
-
"empty": matches == 0, "warmup_or_condition_gaps": len(rows) - matches,
|
|
36
|
-
"equal_endpoints_skipped": equal_endpoints, "drawing_created": False}}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
def validate_stick_values(start_values, end_values, count):
|
|
40
|
-
if (type(count) is not int or not 1 <= count <= MAX_SERIES_BARS
|
|
41
|
-
or not isinstance(start_values, list) or not isinstance(end_values, list)
|
|
42
|
-
or len(start_values) != count or len(end_values) != count):
|
|
43
|
-
raise LineError("invalid_price_stick_values", "柱线序列长度与当前K线不一致。")
|
|
44
|
-
for start, end in zip(start_values, end_values):
|
|
45
|
-
if start is None and end is None: continue
|
|
46
|
-
if (type(start) not in (int, float) or type(end) not in (int, float)
|
|
47
|
-
or not math.isfinite(start) or not math.isfinite(end)
|
|
48
|
-
or start <= 0 or end <= 0 or start == end):
|
|
49
|
-
raise LineError("invalid_price_stick_values", "柱线端点无效、等价或空值未成对出现。")
|
|
50
|
-
if not any(value is not None for value in start_values):
|
|
51
|
-
raise LineError("empty_price_sticks", "条件没有命中可绘制柱线,未创建空对象。")
|
|
52
|
-
return list(start_values), list(end_values)
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
def edit_price_sticks(payload, action, *, sticks_id=None, start_source=None, end_source=None,
|
|
56
|
-
condition=None, start_values=None, end_values=None, name=None, color=None,
|
|
57
|
-
request_id=None):
|
|
58
|
-
result = deepcopy(payload)
|
|
59
|
-
commands = result.get("chartCommands", [])
|
|
60
|
-
rows = next((c.get("rows", []) for c in commands if c.get("type") == "SET_CANDLES"), [])
|
|
61
|
-
matches = [c for c in commands if c.get("type") == STICKS_COMMAND and c.get("id") == sticks_id]
|
|
62
|
-
if len(matches) > 1: raise LineError("ambiguous_drawing_id", "同一柱线对象 ID 不唯一。")
|
|
63
|
-
previous = matches[0] if matches else None
|
|
64
|
-
if action in {"update", "delete"} and previous is None:
|
|
65
|
-
raise LineError("price_sticks_not_found", "当前图不存在该 AI 柱线对象。")
|
|
66
|
-
if action == "delete":
|
|
67
|
-
if any(value is not None for value in (start_source, end_source, condition, start_values,
|
|
68
|
-
end_values, name, color)):
|
|
69
|
-
raise LineError("invalid_edit_fields", "删除柱线对象只需对象 ID。")
|
|
70
|
-
commands.remove(previous)
|
|
71
|
-
return result, deepcopy(previous)
|
|
72
|
-
if action not in {"create", "update"}: raise LineError("invalid_action", "不支持的柱线对象操作。")
|
|
73
|
-
_, name, color = validate_line_fields(name=name, color=color, request_id=request_id)
|
|
74
|
-
supplied = [start_source, end_source, start_values, end_values]
|
|
75
|
-
if action == "create" and any(value is None for value in supplied):
|
|
76
|
-
raise LineError("sticks_result_required", "创建柱线对象必须使用完整函数结果引用。")
|
|
77
|
-
if any(value is None for value in supplied) and any(value is not None for value in supplied):
|
|
78
|
-
raise LineError("sticks_result_required", "修改端点或条件时须重新运行函数并使用完整结果引用。")
|
|
79
|
-
if action == "update" and all(value is None for value in supplied) and name is None and color is None:
|
|
80
|
-
raise LineError("empty_update", "请指定新函数结果、名称或颜色。")
|
|
81
|
-
if all(value is not None for value in supplied):
|
|
82
|
-
start_values, end_values = validate_stick_values(start_values, end_values, len(rows))
|
|
83
|
-
start_source = PriceSource.model_validate(start_source).model_dump(exclude_none=True)
|
|
84
|
-
end_source = PriceSource.model_validate(end_source).model_dump(exclude_none=True)
|
|
85
|
-
condition = PriceCondition.model_validate(condition).model_dump(exclude_none=True) if condition is not None else None
|
|
86
|
-
else:
|
|
87
|
-
start_values, end_values = validate_stick_values(previous["start_values"], previous["end_values"], len(rows))
|
|
88
|
-
start_source, end_source, condition = previous["start_source"], previous["end_source"], previous.get("condition")
|
|
89
|
-
obj = {"type": STICKS_COMMAND, "id": previous["id"] if previous else "sticks_" + secrets.token_hex(12),
|
|
90
|
-
"interval": payload.get("interval"), "bar_count": len(rows), "row_hash": candle_sequence_hash(rows),
|
|
91
|
-
"start_source": start_source, "end_source": end_source, "condition": condition,
|
|
92
|
-
"start_values": start_values, "end_values": end_values,
|
|
93
|
-
"label": name if name is not None else previous.get("label", "") if previous else "",
|
|
94
|
-
"color": color if color is not None else previous.get("color", "info") if previous else "info"}
|
|
95
|
-
obj["sticks_hash"] = hashlib.sha256(json.dumps({"start_source": start_source, "end_source": end_source,
|
|
96
|
-
"condition": condition, "start_values": start_values, "end_values": end_values},
|
|
97
|
-
ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
|
|
98
|
-
if previous and previous.get("create_request_id"): obj["create_request_id"] = previous["create_request_id"]
|
|
99
|
-
if action == "create":
|
|
100
|
-
if request_id:
|
|
101
|
-
obj["create_request_id"] = request_id
|
|
102
|
-
obj["id"] = "sticks_" + hashlib.sha256(request_id.encode()).hexdigest()[:24]
|
|
103
|
-
retry = next((c for c in commands if c.get("type") == STICKS_COMMAND and c.get("create_request_id") == request_id), None)
|
|
104
|
-
if retry:
|
|
105
|
-
if any(retry.get(key) != obj[key] for key in ("interval", "bar_count", "start_source", "end_source",
|
|
106
|
-
"condition", "start_values", "end_values", "label", "color")):
|
|
107
|
-
raise LineError("request_conflict", "同一 request_id 的柱线参数不同。")
|
|
108
|
-
return result, deepcopy(retry)
|
|
109
|
-
if sum(c.get("type") == STICKS_COMMAND for c in commands) >= MAX_PRICE_STICKS:
|
|
110
|
-
raise LineError("too_many_price_sticks", "当前图最多保存4组 AI 柱线。")
|
|
111
|
-
commands.append(obj)
|
|
112
|
-
else:
|
|
113
|
-
commands[commands.index(previous)] = obj
|
|
114
|
-
return result, deepcopy(obj)
|