Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2b1b500108 | ||
|
|
c22cd48f36 | ||
|
|
b301ad22c9 | ||
|
|
2cd50f1e01 | ||
|
|
6b72ba226b | ||
|
|
080ff7d20e | ||
|
|
3bbd92784c | ||
|
|
77056a8318 | ||
|
|
f14ef540c1 | ||
|
|
7585491481 | ||
|
|
1ee4c3d4e1 | ||
|
|
e21f1103c5 | ||
|
|
84ee59ecfb | ||
|
|
93ed315a4b | ||
|
|
ed741c16b8 | ||
|
|
380d6d61cd | ||
|
|
7292ef5dd4 | ||
|
|
5695d8e983 | ||
|
|
78708ddeee | ||
|
|
e137d92b50 | ||
|
|
9efbae6ade | ||
|
|
be3602f5ba | ||
|
|
409dc2f020 | ||
|
|
30592889aa | ||
|
|
6d93975e67 | ||
|
|
1ffc4fbb18 | ||
|
|
17fe965a7c | ||
|
|
881cc5e77d | ||
|
|
5ffbadb0b2 | ||
|
|
668ebe1e44 | ||
|
|
f62b4f62a5 | ||
|
|
c513455998 | ||
|
|
7435cef61f | ||
|
|
9562b8c598 | ||
|
|
d797adc77e | ||
|
|
040810d48d | ||
|
|
d884de2c36 | ||
|
|
b6ed5c8b50 | ||
|
|
999ad924ad | ||
|
|
15f4aa088e | ||
|
|
3e3d579e35 | ||
|
|
1642b1bbfc | ||
|
|
335d891478 | ||
|
|
af029bc26e | ||
|
|
cef894376c | ||
|
|
be442783a1 | ||
|
|
f11c6507b0 | ||
|
|
bfdb2f2e2a | ||
|
|
06928d1d5f | ||
|
|
431e776905 | ||
|
|
360e4e1c41 | ||
|
|
f716ddd149 | ||
|
|
c57adc8cb0 | ||
|
|
97457b0518 | ||
|
|
0745e73b4f | ||
|
|
545fcc7c77 | ||
|
|
34a8f37b39 | ||
|
|
0a0fd2f682 | ||
|
|
c8a0062707 | ||
|
|
f5f456c523 | ||
|
|
d4fbe9d905 | ||
|
|
ef584b8d49 | ||
|
|
2b9a837a58 | ||
|
|
ef2a85dd8c | ||
|
|
27a4360ce8 | ||
|
|
7c13781f90 | ||
|
|
d13a0f85bc | ||
|
|
550eafdd9d | ||
|
|
99ae072cc6 | ||
|
|
d37bfcb26b | ||
|
|
2a59dcb9dc | ||
|
|
4a4f8727fd | ||
|
|
6c843639d5 | ||
|
|
9f4d7fec73 | ||
|
|
d2fcb27d01 | ||
|
|
0b4d7693b8 | ||
|
|
3b14bba247 | ||
|
|
75fbf4167b | ||
|
|
54792fe015 | ||
|
|
95f2b614a2 | ||
|
|
1661bbbac9 | ||
|
|
631d97e493 | ||
|
|
01c4a4ab4d | ||
|
|
28075173af | ||
|
|
181bca303f | ||
|
|
6259f7380b | ||
|
|
32c18f0201 | ||
|
|
9b72173285 | ||
|
|
7e339d2a54 | ||
|
|
66061f79a1 | ||
|
|
b286cb0137 | ||
|
|
a243edd2d3 | ||
|
|
206b27fe72 | ||
|
|
7f393b93ed | ||
|
|
5c10e35b76 | ||
|
|
8c165f11cd | ||
|
|
97e77847d0 | ||
|
|
90499533fb | ||
|
|
8ee11317d3 | ||
|
|
1e60ab3bfa | ||
|
|
d3188ca83c | ||
|
|
ac6be80278 | ||
|
|
081a57a90e | ||
|
|
df27b4dde8 | ||
|
|
9f1e7361b6 | ||
|
|
6b0f3b5837 | ||
|
|
74dec4e50b | ||
|
|
e2e45bc1bc | ||
|
|
f2e77e1bdb | ||
|
|
b31215057e | ||
|
|
2e905e7238 | ||
|
|
02a52c04dd | ||
|
|
19c8f86862 | ||
|
|
ffe7074fef | ||
|
|
7b91f459d7 | ||
|
|
3c72aa1310 | ||
|
|
8d916371e2 | ||
|
|
7e19c9858e | ||
|
|
efb721b39f | ||
|
|
7813e319b4 | ||
|
|
f391020f78 | ||
|
|
0ba5b3bd71 | ||
|
|
50a609f7b9 | ||
|
|
48e69179b3 | ||
|
|
71951019fb | ||
|
|
34040575c1 | ||
|
|
e1116edb7b | ||
|
|
8bc23c0507 | ||
|
|
c75d5e11fc | ||
|
|
8eb50e3eae | ||
|
|
42296ef971 | ||
|
|
a84a80cb62 | ||
|
|
63787b173a | ||
|
|
07f079067f | ||
|
|
ae4c79c133 | ||
|
|
743c5d342e | ||
|
|
78d02cf2ef | ||
|
|
cf9097a540 | ||
|
|
881c9d5eac | ||
|
|
b1cbdca707 | ||
|
|
5ad761fad4 | ||
|
|
9eae12f07d | ||
|
|
9b876c45ed | ||
|
|
91148a648a | ||
|
|
5dc0c4cffd | ||
|
|
f0ea6a6065 | ||
|
|
bc085171f4 | ||
|
|
050ebeb849 | ||
|
|
ca2cf86138 | ||
|
|
0dd8f8a585 | ||
|
|
ebcb3dce73 | ||
|
|
d8069e977f | ||
|
|
3f68a8305a | ||
|
|
deeea55237 | ||
|
|
5ab69c2a64 | ||
|
|
425d513a37 | ||
|
|
8ff1515f8b | ||
|
|
d8e3cdd9e9 | ||
|
|
04d8f73b94 | ||
|
|
7815eada00 |
+47
-26
@@ -1,39 +1,60 @@
|
||||
# MacOS
|
||||
.DS_Store
|
||||
|
||||
# Python编译文件和缓存
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.pyc
|
||||
*.pyo
|
||||
.pytest_cache/
|
||||
|
||||
# 策略文件的缓存
|
||||
strategies/__pycache__/
|
||||
|
||||
# Machine Learning / AI model files
|
||||
*_model*_xgb_model.json
|
||||
*modelchan*.json
|
||||
*.libsvm
|
||||
feature_meta
|
||||
*_model_feature_data.csv
|
||||
*.pem
|
||||
|
||||
# Log files
|
||||
# Logs & databases
|
||||
*.log
|
||||
|
||||
# Database files
|
||||
*.sqlite
|
||||
*.sqlite-shm
|
||||
*.sqlite-wal
|
||||
.DS_Store
|
||||
交易记录/~$交易规则.docx
|
||||
/datasvc/data
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
/data_provider/data
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
.DS_Store
|
||||
|
||||
# Office documents kept alongside the repo but not part of it.
|
||||
# "~$" files are Excel's lock files, recreated every time a workbook is opened.
|
||||
*.xlsx
|
||||
*.xls
|
||||
~$*
|
||||
|
||||
# Local data
|
||||
data/
|
||||
|
||||
# Exchange history fetched by research/live/*.py. 40MB and re-fetchable from
|
||||
# the venue, so it stays local; the small result CSVs it feeds are committed.
|
||||
research/live/cache/
|
||||
|
||||
# Scratch outputs from short shakedown runs, superseded by the real collection.
|
||||
research/out/archive/
|
||||
|
||||
# Per-trade simulation dumps from research/step*.py. 70MB+ and regenerable by
|
||||
# rerunning the step; the summaries they feed live in HANDOFF.md.
|
||||
research/out/*.feather
|
||||
|
||||
# Virtualenvs. venv writes its own .gitignore since 3.11, but only for the
|
||||
# directory it creates — declare it here so other layouts are covered too.
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# Local tooling
|
||||
.gstack/
|
||||
research/out/*.jsonl.gz
|
||||
research/out/penetration.csv
|
||||
research/out/shadow_*.csv
|
||||
research/out/run_meta_*.json
|
||||
|
||||
# Telegram 凭据。**不要提交**
|
||||
research/live/deploy/tg.env
|
||||
research/.tg.env
|
||||
|
||||
# 生产状态与信号总线。刻意放在仓库外(LIVE_HOME / BUS_DIR),这几条只防
|
||||
# 有人把它们指回仓库里:里面是日亏损累计与已处理信号键,被 git clean
|
||||
# 清掉等于两道闸静默失忆
|
||||
/live/deploy/live.env
|
||||
live_state.json
|
||||
live_trades.jsonl
|
||||
signals_live.jsonl
|
||||
|
||||
-236
@@ -1,236 +0,0 @@
|
||||
均线
|
||||
5m, 15m, 30m, 1h, 2h, 4h, 8h, 12h, 16h, 1d, 2d, 3d, 1w, 2w, 1M
|
||||
|
||||
参考时间周期
|
||||
大周期:1h
|
||||
小周期:15m
|
||||
|
||||
价格在1h周期ema156之上为大周期上涨,反之为大周期下跌
|
||||
在1h大周期上涨时,小周期15m,下跌触碰到
|
||||
|
||||
顺大逆小
|
||||
大周期看多,小周期跌完做多,跌完:顶分型和EMA52归零轴反弹
|
||||
大周期看空,小周期涨完做空,涨完:顶分型和EMA52归零轴反抽
|
||||
|
||||
中枢分类
|
||||
常规中枢
|
||||
上升中枢
|
||||
收敛中枢
|
||||
扩散中枢
|
||||
下行中枢
|
||||
止损放到顶底分型的高低点
|
||||
1. 从大周期开始找到价格接近ema52,MACD也接近零轴的周期,需要看这个周期的长级别是否高位空,大趋势方向
|
||||
2. 然后去小于这个时间周期的周期找买卖点,小级趋势方向和大趋势相反并且开始反向,小级别需要检查MACD是否归零轴反转,同时价格是否接近EMA52
|
||||
|
||||
|
||||
EMA52线的反弹比零轴的反弹弱
|
||||
EMA52线和MACD白线同时归零轴同时满足的话是完美形态,最佳买卖点
|
||||
|
||||
跟随策略,先调整小级别,然后依次往大级别调整,直到整个周期结束
|
||||
大级别MACD在零轴之上为多头趋势,回调踩EMA52做多,直到跳空背离,隐形,更大级别EMA52顶部归零轴平仓
|
||||
大级别MACD在零轴之下为空头趋势,上涨踩EMA52做空,直到跳空背离,隐形,更大级别EMA52底部归零轴平仓
|
||||
盘整趋势在零轴上下移动,价格在大级别EMA52之间移动,根据连续跳空背离,隐形,归零轴EMA52线开仓和平仓
|
||||
|
||||
|
||||
|
||||
MACD归零轴的两种情况,两者是或的关系,满足任意一种都是归零轴,归零轴的四种走势:
|
||||
1. K线下跌或者上涨后触碰当前时间级别的EMA52附近
|
||||
2. MACD的白线快线无限接近零轴,
|
||||
3. MACD归零轴时,如果此时k线始终保持在EMA24附近,如果一直是EMA24之上之后出现反弹行情就会很大(最强反弹)这种反弹是2个时间级别同时归零轴形成的反弹,容易创新高新低,一般出现在强势行情。
|
||||
4. K线先触碰EMA52,而MACD黄白线都未归零轴
|
||||
|
||||
高位空
|
||||
当MACD的黄白线远离零轴运行时,与零轴有一定的距离,形成了零轴的高危形态。随着K线出现缓慢上涨或者下跌,或者盘整,MACD的能量柱出现衰减,同时能量柱与MACD黄白线形成空间夹角,随着能量柱越来越小,夹角越来越大形成高位空。这种容易形成回调下跌,特别是导致次一级的MACD穿越零轴
|
||||
|
||||
穿越零轴的定义,需要同时满足以下条件
|
||||
1. 在某个时间级别,k线的价格或者指数有效击穿当前时间级别的EMA52
|
||||
2. MACD黄线慢线有效击穿零轴
|
||||
|
||||
MACD黄白线和零轴的几种形态:
|
||||
离开零轴
|
||||
当MACD黄白线穿过零轴那么进入第一阶段离开零轴,此时能量柱变化越来越大,不断增长,k线加速上涨
|
||||
高位
|
||||
当MACD黄白线离开零轴,到一高点时,能量柱此时处于最大,开始减弱时MACD处于高位,高位时MACD黄白线和能量柱是同向的,高位过后是高位空
|
||||
高位空
|
||||
当MACD黄白线处于高位,随着K线出现缓慢上涨或者横盘整理,MACD黄白线保持高位出现平滑横盘走势,此时,MACD的能量柱出现衰减变化,同时能量柱和黄白线之间形成一定的空间夹脚,随着能量柱的不断衰减就导致黄白线和能量柱之间的空间夹脚越来越大,因此就形成高位空
|
||||
归零轴
|
||||
当MACD黄白线在高位,驱动K线上涨的能量所产生的加速度小于或者等于零,K线减速上涨或者下跌,能量变化越来越小,能量柱呈现出一根比一根短的排列方式
|
||||
穿零轴
|
||||
同时满足以下两个条件
|
||||
1. 在某个时间级别,K线的价格或者指数有效击穿当前时间级别的EMA52
|
||||
2. 当前时间级别MACD的黄线慢线有效击穿零轴
|
||||
有效的定义是:当前K线正好击穿EMA52的支撑位后,如果当前这个K线收盘后的第二根K线任然保持在EMA52之下才算有效击穿,如果只是上下影线击穿,后期K线任然运行在EMA52之上不算有效击穿,MACD同理
|
||||
零轴缠绕/纠缠
|
||||
具体是指MACD跟零轴无限接近或者缠绕的状态,或者是已经完成第一次归零轴调整之后,在等待大级别调整的时候。
|
||||
分为无限接近和上下缠绕状态。代表本级别已经调整完毕,即不产生反弹支撑,也不形成阻力压力,不考虑次级别的技术形态,通过更大的时间级别或者其他时间级别进行分析
|
||||
|
||||
隐形形态
|
||||
当MACD的黄白线发生交叉时,必有相应的能量柱释放出来。金叉,则会释放零轴之上的能量柱,反之死叉,则会释放出零轴之下的能量柱。如果黄白线无交叉,而k线出现上涨或者下跌,则代表能量柱的隐形状态,代表K线的运行无能量配合,那么这种上涨或者下跌就变成无效的结果。无能量配合的上涨必下跌,无能量配合的下跌必反弹
|
||||
1. 远离零轴的高位隐形形态
|
||||
某个时间级别的MACD黄白线处在远离零轴的高位,且K线继续拉升上涨或者下跌,但是并没有释放出相对应方向的能量柱,此后,K线将出现归零轴的走势下跌或者上涨。此形态是高位隐形形态+高位空的形态,则当前级别的MACD在后续走势中必将出现会拉零轴甚至穿零轴的走势。因此,远离零轴的高位隐形形态解决的是当前时间级别归零轴的需求。
|
||||
2. 归零轴的隐形形态
|
||||
归零轴后反弹出现的隐形形态,我们称之为归零轴的隐形形态。这种形态必然会导致当前级别的MACD黄白线出现穿零轴的走势。MACD在归零轴的情况下,零轴所提供的反弹或者支撑能量是最大的,而如果零轴所能提供的最大能量都产生不了相应的能量柱,这种支撑就变成了无效的支撑,MACD的黄白线就只能击穿零轴渠道零轴的反方向。
|
||||
如何确认隐形形态的顶部
|
||||
1. 通过顶底分型来确认
|
||||
2. 通过次级别的背离确认隐形高位
|
||||
3. 通过单位调整周期之内的时间级别嵌套逻辑确认隐形的高位
|
||||
顶底分型在K线动能理论的应用
|
||||
1. 分型对应的MACD处在高位空的形态
|
||||
2. 分型所对应的MACD出现隐形形态
|
||||
|
||||
零轴之上高位隐形 + K线顶分型 = 下跌归零轴
|
||||
零轴之上归零轴隐形 + K线顶分型 = 下跌穿零轴
|
||||
|
||||
零轴之下高位隐形 + K线底分型 = 上涨归零轴
|
||||
零轴之下归零轴隐形 + K线底分型 = 上涨穿零轴
|
||||
|
||||
K线的3种盘整结构,上涨和下跌均适用,下面是上涨结构的分析,下跌反之
|
||||
1. K线强势的走势结构
|
||||
一般应用是在单边上涨行情中,某个时间级别的K线经过一轮拉升之后,进入调整的阶段,此时K线如果在高位一直处于横盘震荡走势,而MACD的黄白线却趋于归零轴运行,则当黄白线归零轴之后,出现有效反弹行情。
|
||||
2. K线超强势结构
|
||||
超强势结构往往容易发生破前高的走势。在某个时间级别,当K线经过一轮强势拉升上涨后,变为倾斜向上缓慢上行,K线一直处于这个时间级别的EMA24之上或者附近,经过一段时间的运行,导致当前级别的MACD黄白线无限归零轴的形态,此时,K线往往容易出现速度快,力度强且破前高的走势。对于超强势调整结构,最重要的是次级别不破零轴,并保持在当前级别的EMA24之上或者附近,而当前级别的黄白线运动一段时间后无限趋于零轴。一般来说,超强势调整结构容易出现在某个大的时间级别处于单边行情中。
|
||||
3. 弱势调整结构
|
||||
在弱势调整结构中,K线是通过下跌的方式快速地将当前级别的MACD的黄白线拉回零轴,同时,K线的价格也会快速下跌到本级别EMA52附近位置。在弱势调整结构中,MACD归零轴后所形成的支撑反弹往往不会破前高,而是走出能量不足的走势形态。在此结构中,只有MACD的黄白线出现死叉后才会继续下跌,并且只有在弱势调整结构中,死叉下跌才有效。
|
||||
|
||||
|
||||
单位调整周期
|
||||
指K线在某个时间级别,MACD的黄白线由零轴出发到远离零轴再到回到零轴的区间段称为这个时间级别的调整周期。可以分为零轴同方向和穿零轴出发两种。一个单位调整周期的起点往往是买点,同时终点也是另一个周期的买点。单位周期的判断依据是黄白线归零轴不是量能柱的多少。
|
||||
注意:如果单位调整周期的起始和终止都直接穿零轴的,代表这个时间级别在运行的过程中,是无效的时间级别,也就是这个时间级别在我们的分析的过程中要跳过的。
|
||||
隐形单位调整周期
|
||||
MACD黄白线归零轴后,由于零轴的支撑或者压力而发生的反弹或者反抽,没有释放出相应的能量柱而形成的周期,为隐形单位调整周期。隐形单位调整周期会引起黄白线反向穿零轴的走势。
|
||||
|
||||
零轴粘合
|
||||
MACD黄白线在刚穿零轴的时候会出现:黄白线离零轴的距离比较近,黄白线沿着能量柱运行,黄白线在运行的过程中没有释放出反向能量柱。零轴粘合属性是:强支撑,弱反弹。这种形态我们更强调支撑能量,弱化反弹属性。零轴粘合几乎是贴近零轴运行,因此其反弹的动能就是为无效。斜率小,黄白线喝能量柱之间基本没有空隙。能量柱可以略微减弱但是不能释放下跌方向的能量柱。由此可见黄线没有跟白线有交叉,黄线对白线有支撑作用。如果当前时间级别内部逻辑关系走完,这个时间级别则被视为无效时间级别。
|
||||
|
||||
零轴倒挂
|
||||
MACD黄白线在穿零轴的时候与零轴的距离比较近,同时黄白线沿着能量柱运行,在运行的过程中,能量柱衰减导致它跟黄白线之间形成夹角空位,同时黄白线产生交叉并释放反向能量柱。
|
||||
1. 黄白线穿零轴后未远离零轴形成一定高度,而是靠近零轴运行
|
||||
2. 能量柱的衰减导致其与黄白线之间形成了一定的夹角空位
|
||||
3. 黄白线在运行的过程中发生了交叉而放出反向能量柱
|
||||
弱支撑,弱反弹。如果当前时间级别内部逻辑关系走完,这个时间级别则被视为无效时间级别。如果某个时间级别的盘口形态是零轴倒挂,那么这个时间级别很容易直接击穿零轴,而无法形成有效的反弹和反抽行情。
|
||||
|
||||
零轴粘合和倒挂的有效性
|
||||
在上涨行情中,当K线处在零轴粘合或者零轴倒挂的形态时,如果K线的价格处在当前级别的EMA52之上或者处在多级别EMA均线交汇处之上和附近时,此时由于K线受到EMA均线的支撑,零轴粘合或者零轴倒挂反而容易形成强支撑的特点。此时需要结合MACD的形态和K线均线支撑综合分析盘面。
|
||||
|
||||
线段
|
||||
上涨线段是指MACD的黄白线第一次上穿零轴到下一次下穿零轴中间的运行区域,以黄线穿零轴为准。在这个线段找到阶段性的卖点,阶段性高点。
|
||||
下跌线段是指MACD的黄白线第一次下穿零轴到下一次上穿零轴中间的运行区域,以黄线穿零轴为准。在这个线段找到阶段性的买点,阶段性低点。
|
||||
1. 同一条线段是比较背离的区域,背离的比较不可再跨线段的区域进行
|
||||
2. 线段可以将不同时间级别的K线化繁为简,一个时间级别的形态只需要确定盘面所处的线段即可
|
||||
|
||||
背离
|
||||
在K线分析中,背离是指价格跟能量之间的相悖性,当价格创出阶段性新高点,而推动价格上涨的能量出现衰减,这种情况就是背离,也就是说价格和能量之间产生了不匹配关系。
|
||||
|
||||
顶背离 - 确认卖点
|
||||
在某个时间级别,MACD运行在零轴上方,当K线的价格走势一峰比一峰高,价格一直处在上涨趋势中时,MACD的黄白线或者能量柱的高度却一波比一波低,即当价格的高点比前一次价格的高点高,而MACD指标的高点比前一次高点低,这种形态称为顶背离形态。需要注意的是,这两次高点在运行的过程中,MACD的黄白线始终处在同一条上涨线段周期中,不能跨线段比较。
|
||||
顶背离包括黄白线背离和柱背离两种情况,也可能出现多次背离的情况。线背离以白线的最高点作为参考点,K线上影线最高点作为K线的参考点,能量堆的最高点可能和K线的最高点不是一一对应,但是不影响判断,可以使用能量堆的面积进行计算。
|
||||
|
||||
底背离 - 确认买点
|
||||
在某个时间级别,MACD运行在零轴下方,一般出现价格的低位区。当K线的价格走势持续下跌,而MACD的黄白线或者能量柱却持续靠近零轴,即当前价格的低点比前一次低点好要低,而MACD指标的低点却比前一次低点高,但是下跌能量却在衰减的现象,于是价格跌无可跌,是短期买入信号
|
||||
底背离包括黄白线背离和柱背离两种情况,也可能出现多次背离的情况。线背离以白线的最低点作为参考点,K线上影线最低点作为K线的参考点,能量堆的最低点可能和K线的最低点不是一一对应,但是不影响判断,可以使用能量堆的面积进行计算。
|
||||
|
||||
顶底背离高低点有效性的方法
|
||||
1. 通过顶底分型确认顶底背离的高低点
|
||||
2. 通过次级别的背离确认当前级别的背离高点,这里的次级别不是单指一级次级别,可以是多级的
|
||||
|
||||
单位调整周期内的连续跳空背离
|
||||
K线经过一波上涨或者下跌后,MACD的黄白线由高位回零轴且未归到零轴,能量柱在连续的衰减调整过程中,反而逐渐由衰减转为增长,于是就出现了跳空走势,这种走势称为MACD的连续跳空形态。
|
||||
1. 连续跳空发生在单位调整周期内,线跟柱在零轴同方向
|
||||
2. MACD的能量柱需包含在黄白线之内
|
||||
3. 能量柱在衰减的过程中未放出反向能量柱,而是由衰减转为增长
|
||||
单位调整周期之内的背离是价格跟能量柱之间的关系,同时单位调整周期之内的背离,解决的是归零轴的需求
|
||||
连续跳空的应用和意义
|
||||
单位调整周期之内,能量堆连接在一起的时候,出现的价格跟能量柱之间的关系即为连续跳空,而连续跳空的意义
|
||||
1. 连续跳空背离解决归零轴的需求,主要是小级别的走势,比如5分钟的连续跳空背离则为归零轴走势,因为5分钟级别只包含一个3分钟级别,是5分钟内的小级别,因此,5分钟级别如果出现连续跳空背离,会导致5分钟级别MACD黄白线归零轴走势
|
||||
2. 连续跳空更大的作用是确认穿零轴之后的第一个背离参考点,当MACD黄白线穿零轴的时候,最重要的是确认当前线段的1号参考点,有了1号参考点,后续行情才有参考的对象。连续跳空往往发生在MACD黄白线刚刚穿零轴的位置,一般由零轴粘合的形态演化而成连续跳空,这是因为零轴粘合具有强支撑的特点,容易形成跳空走势。
|
||||
|
||||
穿零轴时的参考点确认方法
|
||||
1. 如果MACD黄白线穿零轴之后出现连续跳空,则以连续跳空的高点作为1号参考点,此时连续跳空形态代表新的单位周期调整周期的开始。当黄白线穿零轴后,黄线之后的第一个能量堆没有更高的能量柱,而是到了第一个跳空高低点出现第一个高低点。穿零轴产生的能量柱左侧黄白线处在下跌线段,右侧处在上涨线段。因此穿零轴的能量柱被切成两半,左侧在下跌线段,所以不能以黄线击穿零轴的左侧作为上涨线段的1号参考点。背离一定要在同一线段中进行比较,而不能跨线段找背离。那么穿零轴之后跳空产生的高低点才能作为1号参考点。后续的背离要以这个参考点进行比较。
|
||||
2. 如果MACD黄白线穿零轴后无连续跳空,没有更高的能量柱出现则不能确定1号参考点,如果穿零轴后没有找到更高低的能量柱,那么这个线段的第一个单位调整周期是无效周期。
|
||||
3. 如果黄线穿零轴之后有更高低的能量柱,则以更高的能量柱作为1号参考点,此参考点可以是穿零轴时的能量柱高点确定。
|
||||
|
||||
单位调整周期之内的分立跳空背离
|
||||
在某个时间级别,当一个单位调整周期之内包含两个或者两个以上的能量堆,能量堆之间被反向能量堆分隔开,同时MACD黄白线一直处于远离零轴的高位,未归零轴,且一直保持原有的趋势运行,被分割的能量堆与黄白线都处在零轴的同方向,能量堆包含在黄白线之内,就形成分离跳空形态。
|
||||
分立跳空背离
|
||||
如果在某个时间级别的单位调整周期内,黄白线未归零轴,K线在经过一段时间的调整并放出反向能量柱之后,继续沿着原有方向运行,导致再一次出现的能量堆,同时黄白线再一次远离零轴,能量堆和能量堆之间形成背离关系,这种就是分离跳空背离。分立跳空背离解决的是归零轴的需求
|
||||
|
||||
分立跳空背离 + 黄白线高位 = 归零轴
|
||||
|
||||
分立跳空不背离 = 单边上涨或者下跌行情
|
||||
|
||||
最佳买卖点
|
||||
单位周期之内 + 隐形 + 分立跳空 + 背离 + 黄白线高位空
|
||||
|
||||
跳空产生的原理:跳空的产生是当前级别之下的小级别归零轴反弹或反抽导致的,比如1小时时间级别的单位调整周期跳空,是因为1小时时间级别之内包含3分钟,5分钟,15分钟,30分钟这些下级别。1小时级别的MACD归零轴的途中,必然导致其内部的小级别先于本级别归零轴。因此,当这些小级别归零轴后,如果产生反弹反抽的走势,则会导致当前1小时级别的MACD黄白线再一次被拉高,此时便产生了跳空的走势。
|
||||
时间级别在高位中归零轴的顺序是:由小级别到大级别依此归零轴。当K线经过一轮拉升下跌后,当前级别的MACD黄白线处在高位,此时如果K线进入调整状态,则这个时间级别所包含的小级别由小到大依次归零轴,直至本级别归零轴为止,如此才完成了次级别的单位调整周期的调整。
|
||||
|
||||
单位周期之内的分立跳空顶背离
|
||||
MACD黄白线在零轴之上第一个单位调整周期 + 分立跳空背离(一次或多次) + 黄白线处在零轴的高位空 + 分立跳空隐形状态
|
||||
单位周期之内的分立跳空底背离
|
||||
MACD黄白线在零轴之下第一个单位调整周期 + 分立跳空背离(一次或多次) + 黄白线处在零轴的高位空 + 分立跳空隐形形态
|
||||
|
||||
单位调整周期之内的跳空非背离
|
||||
如果在单位调整周期内发生了跳空的形态,当跳空能量堆的高度高于前一个能量堆的高度,此时的跳空则为非背离跳空。非背离跳空可以理解为单位周期的单边行情,前一个能量堆失效,以新的最高的能量堆作为后续行情的1号参考点。不管是连续跳空还是分立跳空都遵守这个法则。
|
||||
|
||||
单位调整周期之间的背离
|
||||
单位调整周期之间的背离,是指两个或者两个以上的单位调整周期相比较而建立的关系,相比较的周期必须在同一个线段周期内,不可跨线段比较。当K线在某个时间级别的线段中,MACD经过了一个单位调整周期的运行,黄白线在此回零轴后,由于零轴的支撑反弹或压力反抽的作用,因此出现第二个单位调整周期,当第二个单位调整周期的黄白线这里特指白线离开零轴的距离小于第一个单位调整周期黄白线离开零轴的距离时,单位调整周期之间就产生了相悖的关系,即价格穿新高或新低,而白线能量区出现了减弱或增强,这种背离称为单位调整周期之间的背离,单位调整周期之间的背离也叫区间背离。
|
||||
|
||||
上涨线段单位调整周期之间的顶背离为卖点(前提:长级别MACD在高位)
|
||||
下跌线段单位调整周期之间的底背离为买点(前提:长级别MACD在高位)
|
||||
|
||||
单位调整周期之间的背离,其核心的本质是描述某个时间级别在线段中的运行逻辑,即为线段完成调整的重要依据。
|
||||
单位调整周期之间的背离是为了满足线段调整的需求
|
||||
|
||||
判断某个时间级别线段结束趋势的依据为:在某个时间级别的线段中,第二个单位调整周期与第一个单位调整周期之间产生背离关系,即为此线段终结的依据,而后出现的单位调整周期无论归零轴多少次,从能量产生的逻辑上都是依次减弱直至趋于零。
|
||||
|
||||
单位调整周期之间的背离而穿零轴变盘的依据是:当某个级别在线段中出现周期之间的背离形态,同时完成了线段的调整,但是其长级别MACD的黄白线处在高位空的形态时,当前级别的背离会导致穿零轴走势。
|
||||
|
||||
在K线的时间逻辑中,判断一个时间级别完成自己的当值任务的标准是:本级别在当前的线段中产生了周期间的背离关系,并趋向于零轴的调整。本级别是否穿零轴并非由本级别背离的属性决定,而是由长级别决定。因此,当本级别完成线段调整之后,就要看长级别处在什么形态之下,长级别的形态属性决定了后续的行情走势。
|
||||
|
||||
时间级别升级:是指当本级别在其线段中产生了背离关系而趋向于零轴,达到了平衡状态且保持在零轴之上(代表完成了其线段的调整任务),其长级别同时也处在归零轴的形态,此时当前级别即要发生时间级别升级。时间级别升级之后,本级别将会产生新的线段,之后本级别的线段关系则升级为线段与线段之间的关系。
|
||||
|
||||
确定时间级别升级的条件
|
||||
1. 当前级别多次归零轴背离而完成了线段的调整,之后新的单位调整周期MACD的白线DIF比前一个单位调整周期的白线DIF高
|
||||
2. 当前级别完成线段调整,长级别MACD的黄白线无限接近零轴
|
||||
|
||||
线段背离
|
||||
当某个时间级别升级之后,便产生了一条新的线段,如果线段和线段之间构成相悖关系时,我们称为线段背离,而线段背离则必然导致当前时间级别穿零轴。线段背离比较的是两个线段中最高或最低的白线DIF。
|
||||
|
||||
动能不足
|
||||
如果K线走势中不破前高点上涨动能衰减,或者不破前低点,下跌动能也衰减,这种形态称为动能不足,本质上和背离是一样的,都是能量衰减的一种变现,背离所具有的属性和原理适用于动能不足。
|
||||
单位调整周期内,之间,线段之内,线段之间的隐形背离或隐形动能不足
|
||||
|
||||
主级别归零轴启动反弹的内部过程:
|
||||
1. 第一过程,主级别所包含的小级别在零轴之下首先完成超跌反弹的过程
|
||||
2. 第二过程,小级别完成底部调整后,才正式启动主级别归零轴反弹
|
||||
|
||||
底部形态变盘的四个阶段
|
||||
确认底部区域需要四个条件
|
||||
1. 确认引起下跌行情中的主要时间级别
|
||||
当K线出现下跌行情时,一定是某个时间级别在零轴之上进行的归零轴调整而引起的,受到零轴的引力作用,这个级别的MACD黄白线会被拉回零轴。这个时间级别是:上穿零轴后第一次开始归零轴的时间级别。
|
||||
2. 确认主级别归零轴后的形态属性
|
||||
K线价格要触碰到EMA52均线的位置附近,同时MACD的黄白线无限接近零轴。也就是说,K线的价格一旦触碰到EMA52的位置附近,因为这个位置能否形成支撑反弹,主要是看归零轴的这两个条件能否一直保持,并开始归零轴反弹的第一个过程,即主级别所包含的小级别在零轴之下的超跌反弹。
|
||||
3. 在归零轴的形态满足条件的情况下,确认子级别是否有高位空的形态
|
||||
当主级别第一次触碰到当前级别EMA52均线的位置附近时,我们要看包含在主级别之下的小级别在零轴的下方是否产生了高位空的形态。只有当这些小级别出现高位空的形态时,才能出现有效的归零轴的超跌反弹,而超跌反弹的变向则为主级别归零轴后出现的止跌反弹的走势。
|
||||
4. 确认零轴之下的最大子级别运行底部变盘的四个阶段
|
||||
当主级别进入底部区域后,小级别的超跌反弹将逐级别开始,而时间级别的运行逻辑则是从小级别依次运行。因此,当主级别包含的小级别零轴之下的最后一个子级别完成调整后,主级别的归零轴反弹才正式开启。这些零轴之下的子级别的运行逻辑即为主级别底部变盘的四个阶段。
|
||||
第一阶段:零轴之下的子级别的单边下跌
|
||||
第二阶段:零轴之下的子级别的超跌反弹
|
||||
第三阶段:零轴之下的子级别的归零轴反抽之后产生背离/动能不足
|
||||
第四阶段:零轴之下的子级别跟零轴形成粘合或者零轴纠缠
|
||||
|
||||
底部形态V字反转的条件
|
||||
当主级别归零轴后,由于小级别的超跌反弹和反抽容易在行情的底部走出横盘震荡的走势,当某个时间级别的超跌反弹导致K线突破这个横盘区间时,我们便把这种走势称为V字反转的走势
|
||||
V字反转走势发生的条件
|
||||
1. 主级别保持归零轴形态且MACD出现收敛的状态
|
||||
2. 零轴之下大多数小级别已经完成线段调整,并形成了底部的横盘结构,剩下未调整的级别没有明显的高位空
|
||||
3. 下一个长级别的超跌反弹归零轴所触碰到EMA52均线的位置需要有效突破底部横盘震荡的区间
|
||||
MACD收敛
|
||||
K线在下跌行情中进入底部区域,当MACD的黄白线由倾斜向下趋于零轴的方向转为拐头形态,同时下跌能量柱由逐渐增长转为衰减时,我们把这种形态称为MACD收敛形态
|
||||
抢底原理
|
||||
当行情运行到当前级别底部调整的第三阶段时,即背离/下跌动能不足时,即为我们最佳买入机会。因为一旦启动了V字反转的走势,K线的价格将不容易再出现大的回调机会,而V字反转的行情极容易导致剩下的海味调整的其他小级别直接击穿零轴,或者出现以横代跌的走势而不在出现明显的反抽下跌。这就是V字反转结构形成的条件下的抢底原理。
|
||||
|
||||
第一代时间级别当值的有效性满足两个条件
|
||||
1. 第一代时间级别不能击穿零轴,如果击穿零轴,则本级别当值作用失效
|
||||
2. 每个当值的第一代时间级别的反弹行情必须推动其长级别在上涨线段中的第一个单位调整周期处于高位的形态
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
# Chan — 缠论分析引擎
|
||||
|
||||
把 OHLCV K 线拆成缠论结构(K 线单元 → 合并 K 线 → 分型 → 笔 → 线段 → 中枢 → 买卖点),
|
||||
配一个 TradingView Charting Library 的 Web 界面,外加一套验证信号有效性的回测脚本。
|
||||
|
||||
标的不限:加密永续(ccxt)与 A 股(akshare)都走同一条分析链路。
|
||||
|
||||
```
|
||||
chanlun/ 缠论引擎,纯 pandas/numpy,无外部指标库依赖
|
||||
web/ Flask API + 图表界面
|
||||
research/ 信号有效性验证脚本(step1 ~ step30)
|
||||
data/ 本地 K 线(freqtrade 的 feather 格式)
|
||||
```
|
||||
|
||||
## 安装
|
||||
|
||||
需要 Python ≥ 3.11(pandas 3.x / numpy 2.x 的要求,不是本项目代码的限制)。
|
||||
|
||||
```bash
|
||||
python -m venv .venv
|
||||
.venv/bin/pip install -r requirements.txt # 核心运行时,8 个包
|
||||
.venv/bin/pip install -r requirements-dev.txt # 另加测试与 research/ 所需
|
||||
```
|
||||
|
||||
## 跑 Web
|
||||
|
||||
```bash
|
||||
cd web
|
||||
../.venv/bin/python app.py # 默认 http://0.0.0.0:8128
|
||||
```
|
||||
|
||||
从仓库根跑 `.venv/bin/python web/app.py` 也可以——Python 会把脚本所在目录放进 `sys.path`。
|
||||
但**不能用 `python -m web.app`**,也不能 `import web.app`:`web/` 内部是无前缀导入
|
||||
(`import config`、`from api.analyze import bp`),`-m` 方式下 `sys.path` 里是仓库根而不是
|
||||
`web/`,会 `ModuleNotFoundError: No module named 'config'`。
|
||||
|
||||
配置全部走环境变量,见 `web/config.py`:
|
||||
|
||||
| 变量 | 默认值 | 用途 |
|
||||
|------|--------|------|
|
||||
| `FLASK_HOST` / `FLASK_PORT` | `0.0.0.0` / `8128` | 监听地址 |
|
||||
| `DATA_SERVICE_URL` | `https://provider.jackyu66.com` | 行情 REST 源 |
|
||||
| `DATA_SERVICE_WS_URL` | `wss://jackyu66.com/ws` | 行情 WebSocket 源 |
|
||||
| `ASHARE_DP_URL` | `http://103.179.242.166:8000` | A 股数据源 |
|
||||
| `CHAN_HTTP_PROXY` | 未设置则不走代理 | ccxt / HTTP 代理 |
|
||||
| `MACD_FACTOR` / `MACD_SMOOTH` | `1` / `1` | MACD 周期倍数,默认 12/26/9 |
|
||||
|
||||
主要接口:`GET /api/analyze` 返回某标的某周期的完整缠论结构,`/api/klines/recent`
|
||||
取最新 K 线,`/api/trend_filter` 与 `/api/trend_detail` 做多周期趋势筛选,
|
||||
`/api/symbols`、`/api/search_stock`、`/api/sectors` 等负责标的检索。页面在 `/` 与 `/chan_tv`。
|
||||
|
||||
## 作为库使用
|
||||
|
||||
```python
|
||||
import pandas as pd
|
||||
from chanlun import TF_DF
|
||||
|
||||
# 需要 date/open/high/low/close/volume 六列,date 为 datetime
|
||||
df = pd.read_feather("data/binance/futures/BTC_USDT_USDT-1h-futures.feather")
|
||||
|
||||
tf = TF_DF(df, interval=1, timeframe="1h")
|
||||
|
||||
len(tf.klu_list) # K 线单元
|
||||
len(tf.klc_list) # 合并 K 线(处理包含关系后)
|
||||
len(tf.bi_list) # 笔
|
||||
len(tf.seg_list) # 线段
|
||||
len(tf.zs_list) # 中枢
|
||||
tf.bi_list[-1].dir # Chan_BI_DIR.DOWN
|
||||
tf.chanmacd # MACD 结构分析(背驰判定用)
|
||||
```
|
||||
|
||||
**`interval` 的单位是分钟**,对传入的 df 做重采样;`interval=1` 是特例,表示原样使用、
|
||||
不重采样。所以拿 1h 的 feather 要传 `interval=1`,拿 1m 数据想看 1h 才传 `interval=60`:
|
||||
|
||||
```python
|
||||
df1m = pd.read_feather("data/binance/futures/BTC_USDT_USDT-1m-futures.feather")
|
||||
TF_DF(df1m, interval=5, timeframe="5m")
|
||||
TF_DF(df1m, interval=60, timeframe="1h")
|
||||
```
|
||||
|
||||
传错不会报错,只会静默给出错误周期的结构——1h 数据配 `interval=4` 相当于按 4 分钟
|
||||
重采样,结果与 `interval=1` 完全相同。
|
||||
|
||||
## 分析流程
|
||||
|
||||
`TF_DF.init_TF_DF()` 按顺序做这几步,每步的实现在 `chanlun/pipeline/builders/` 下同名文件:
|
||||
|
||||
1. `resample_to_interval` — 重采样(`interval != 1` 时)
|
||||
2. `add_indicators` — 追加 33 列指标(MACD / BBANDS / EMA / RSI / ATR 等)
|
||||
3. `cal_kl_data` → `klu_list` — K 线单元
|
||||
4. `get_klc_list` → `klc_list` — 按包含关系合并 K 线,并标记分型
|
||||
5. `cal_bi_list` → `bi_list` — 笔
|
||||
6. `cal_bi_zs_list_pure` → `bi_zs_list` — 笔中枢
|
||||
7. `get_seg_list` → `seg_list` — 线段
|
||||
8. `get_zs_list` / `get_big_zs_list` — 中枢与大级别中枢
|
||||
9. `ChanMACD(klu_list)` — MACD 段 / 柱堆结构,供背驰判定
|
||||
|
||||
## 数据
|
||||
|
||||
`data/<交易所>/futures/<SYMBOL>-<周期>-futures.feather`,即 freqtrade 的下载格式,
|
||||
如 `data/binance/futures/BTC_USDT_USDT-1h-futures.feather`。
|
||||
`research/lib/data.py` 负责定位:`BTC/USDT:USDT` + `1h` 会解析到上面这个路径,
|
||||
找不到本地文件则回落到远端拉取。
|
||||
|
||||
## 测试
|
||||
|
||||
```bash
|
||||
.venv/bin/python -m pytest chanlun/tests web/tests -q
|
||||
```
|
||||
|
||||
`chanlun/tests/test_ta_compat.py` 有个**需要注意的陷阱**:它把 `chanlun/indicators/ta.py`
|
||||
的输出逐 bar 钉在 TA-Lib 上,但 **TA-Lib 不存在时会静默跳过**。也就是说改了 `ta.py`
|
||||
之后在没装 TA-Lib 的环境里跑,测试会显示通过,其实一项都没验证。改动那个文件时请先装:
|
||||
|
||||
```bash
|
||||
sudo apt-get install -y libta-lib0 ta-lib-dev
|
||||
.venv/bin/pip install TA-Lib technical
|
||||
```
|
||||
|
||||
## 已知问题
|
||||
|
||||
- **`web/DEPLOY_GUIDE.md` 已失效**:它引用的 `deploy_venv.sh`、`stop_venv.sh`、
|
||||
`status_venv.sh` 等 6 个脚本都在 `7f393b9` 精简提交里删掉了,目前没有部署脚本。
|
||||
两个 systemd unit 文件(`web/chanlun-web*.service`)仍可参考,但它们用 gunicorn
|
||||
且写死端口 8123,与 `config.py` 默认的 8128 不一致,gunicorn 也不在依赖清单里。
|
||||
- **`web/README.txt` 已过时**:它说的 `web/requirements.txt` 不存在,依赖清单在仓库根目录。
|
||||
- **四个零引用的死文件**:`chanlun/analysis/` 下的 `ChanPY.py`、`ChanLun_Classifier.py`、
|
||||
`Find_Trend.py`、`ChanHeng.py` 全项目无人引用。`ChanPY.py` 依赖未安装的外部 chan.py 库,
|
||||
另外三个需要 matplotlib / mplfinance / xgboost / scikit-learn——这些都**不在**依赖清单里,
|
||||
是有意为之。要用得自行安装。
|
||||
-13
@@ -1,13 +0,0 @@
|
||||
1. **第一类买卖点**:
|
||||
- 定义:趋势反转的起始点,即在下跌趋势结束时形成的买点(第一类买点),或在上涨趋势结束时形成的卖点(第一类卖点)。这是市场多空力量发生根本性转变的位置。
|
||||
- 与MACD背驰的关系:Macd背驰是指出中枢后形成的Macd的红绿柱面积比进入中枢时的面积绝对值小,背驰比较的黄白线和柱子面积都在0轴的一个方向上。第一类买点都是在0轴之下背驰形成的,第一类卖点都是在0轴之上的背驰形成的。
|
||||
|
||||
2. **第二类买卖点**:
|
||||
- 定义:趋势确认后的回调点。在第一类买卖点之后,价格会回调或反弹,形成第二类买点(回调不破前低)或第二类卖点(反弹不破前高),是对第一类买卖点的确认。第二类买点都是第一次上0轴后回抽确认形成的。第二类卖点都是第一次0轴之下上涨确认形成的。第二类买卖点只会在趋势确认后,第一类买卖点出现之后出现一次,不会重复出现,除非趋势反转之后。
|
||||
|
||||
3. **第三类买卖点**:
|
||||
- 定义:趋势延续的确认点。价格突破回调或反弹的中枢区间后,回踩不破关键位置(如中枢上沿或下沿),形成第三类买点(上升趋势延续)或第三类卖点(下降趋势延续)。第三类买卖点只会在中枢确认之后出现。
|
||||
|
||||
|
||||
|
||||
我们交易的是币安的比特币合约, 数据格式是json, 数据包括现有的持仓, 仓位历史, 账户余额, 你用缠论分析之后, 给出以下分析, 最近的一个中枢在哪里,现在的趋势是什么,现在是否是买卖点,如果是,是那一类买卖点,应该进行何种操作。
|
||||
@@ -0,0 +1,11 @@
|
||||
"""缠论引擎正式包。
|
||||
|
||||
推荐::
|
||||
from chanlun import ChanLun, TF_DF
|
||||
from chanlun.core.ChanEnum import Chan_BI_DIR
|
||||
"""
|
||||
|
||||
from chanlun.pipeline.orchestrator import ChanLun
|
||||
from chanlun.pipeline.timeframe import TF_DF
|
||||
|
||||
__all__ = ["ChanLun", "TF_DF"]
|
||||
@@ -6,22 +6,20 @@ sys.path.append(os.path.abspath("/Users/jack/Project/freqtrade/user_data/Chan"))
|
||||
import numpy as np
|
||||
from datetime import timedelta
|
||||
from pandas import DataFrame
|
||||
from ChanEnum import Chan_FX_TYPE, Chan_KLINE_DIR, Chan_BI_DIR, Chan_SEG_DIR, Chan_ZS_DIR, Chan_BSP_DIR, Chan_BSP_TYPE, Chan_KLC_FX
|
||||
from ChanKLU import ChanKLU
|
||||
from ChanKLC import ChanKLC
|
||||
from ChanBI import ChanBI
|
||||
from ChanSBI import ChanSBI
|
||||
from ChanSEG import ChanSEG
|
||||
from ChanZS import ChanZS
|
||||
from ChanBSP import ChanBSP
|
||||
import talib.abstract as ta
|
||||
from chanlun.core.ChanEnum import Chan_FX_TYPE, Chan_KLINE_DIR, Chan_BI_DIR, Chan_SEG_DIR, Chan_ZS_DIR, Chan_BSP_DIR, Chan_BSP_TYPE, Chan_KLC_FX
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
from chanlun.core.ChanKLC import ChanKLC
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
from chanlun.core.ChanSBI import ChanSBI
|
||||
from chanlun.core.ChanSEG import ChanSEG
|
||||
from chanlun.core.ChanZS import ChanZS
|
||||
from chanlun.core.ChanBSP import ChanBSP
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.dates import DateFormatter, date2num
|
||||
import matplotlib.patches as patches
|
||||
from technical.util import resample_to_interval
|
||||
from decimal import Decimal
|
||||
from ChanLun import ChanLun
|
||||
from chanlun.pipeline.orchestrator import ChanLun
|
||||
import xgboost as xgb
|
||||
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, classification_report
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
"""
|
||||
中枢结构特征提取 + 标签化
|
||||
Market Structure Dataset Builder — Phase 1
|
||||
|
||||
定位: 训练数据集构建工具,不是交易信号生成器。
|
||||
Feature 描述中枢内部结构,Label 记录中枢后实际演化。
|
||||
"""
|
||||
|
||||
import math
|
||||
import json
|
||||
from typing import Optional
|
||||
from chanlun.core.ChanEnum import Chan_BI_DIR
|
||||
|
||||
|
||||
class ChanPivotClassifier:
|
||||
"""
|
||||
中枢结构特征提取 + 标签化
|
||||
输入: bi_zs_list (list[ChanBIZS])
|
||||
输出: 结构化数据集 (list[dict])
|
||||
"""
|
||||
|
||||
DATASET_VERSION = "pivot_v1"
|
||||
FEATURE_SCHEMA = ["duration_norm", "contraction", "shift_norm"]
|
||||
LABEL_SCHEMA = {"name": "break_direction", "values": ["up", "down", "none"]}
|
||||
|
||||
def __init__(self, bi_zs_list: list, symbol: str = "", timeframe: str = ""):
|
||||
self.bi_zs_list = bi_zs_list
|
||||
self.symbol = symbol
|
||||
self.timeframe = timeframe
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Feature extraction
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def calc_duration(zs) -> int:
|
||||
"""持续时间: 第一笔首K → 最后一笔末K 的 index 差"""
|
||||
bi_list = zs.bi_list
|
||||
start_idx = bi_list[0].start_klc.index
|
||||
end_idx = bi_list[-1].end_klc.index
|
||||
return end_idx - start_idx
|
||||
|
||||
@staticmethod
|
||||
def calc_contraction(zs) -> float:
|
||||
"""收敛率: 后窗口振幅均值 / 前窗口振幅均值"""
|
||||
bi_list = zs.bi_list
|
||||
if len(bi_list) < 4:
|
||||
return 1.0
|
||||
|
||||
n = min(3, len(bi_list) // 2)
|
||||
first_ranges = [bi.high - bi.low for bi in bi_list[:n]]
|
||||
last_ranges = [bi.high - bi.low for bi in bi_list[-n:]]
|
||||
|
||||
first_mean = sum(first_ranges) / len(first_ranges)
|
||||
last_mean = sum(last_ranges) / len(last_ranges)
|
||||
|
||||
if first_mean == 0:
|
||||
return 1.0
|
||||
return last_mean / first_mean
|
||||
|
||||
@staticmethod
|
||||
def calc_shift(zs) -> tuple[float, float]:
|
||||
"""重心漂移: 前后半段重心均值差 (原始值, 归一化值)"""
|
||||
bi_list = zs.bi_list
|
||||
mid = len(bi_list) // 2
|
||||
|
||||
first_centers = [(bi.high + bi.low) / 2 for bi in bi_list[:mid]]
|
||||
last_centers = [(bi.high + bi.low) / 2 for bi in bi_list[mid:]]
|
||||
|
||||
shift_raw = (
|
||||
sum(last_centers) / len(last_centers)
|
||||
- sum(first_centers) / len(first_centers)
|
||||
)
|
||||
|
||||
zs_height = zs.zg - zs.zd
|
||||
if zs_height == 0:
|
||||
shift_norm = 0.0
|
||||
else:
|
||||
shift_norm = shift_raw / zs_height
|
||||
|
||||
return shift_raw, shift_norm
|
||||
|
||||
@staticmethod
|
||||
def compute_duration_norm(duration_raw: int, historical_durations: list) -> float:
|
||||
"""用历史窗口均值归一化 duration"""
|
||||
if not historical_durations:
|
||||
return 1.0
|
||||
avg = sum(historical_durations) / len(historical_durations)
|
||||
if avg == 0:
|
||||
return 1.0
|
||||
return duration_raw / avg
|
||||
|
||||
@staticmethod
|
||||
def compute_features(zs, historical_durations: Optional[list] = None):
|
||||
"""计算单个中枢的全部结构特征(实时友好)"""
|
||||
duration_raw = ChanPivotClassifier.calc_duration(zs)
|
||||
contraction = ChanPivotClassifier.calc_contraction(zs)
|
||||
shift_raw, shift_norm = ChanPivotClassifier.calc_shift(zs)
|
||||
|
||||
if historical_durations is not None and len(historical_durations) > 0:
|
||||
duration_norm = ChanPivotClassifier.compute_duration_norm(
|
||||
duration_raw, historical_durations
|
||||
)
|
||||
else:
|
||||
duration_norm = 1.0
|
||||
|
||||
return {
|
||||
"duration_raw": duration_raw,
|
||||
"duration_norm": round(duration_norm, 4),
|
||||
"contraction": round(contraction, 4),
|
||||
"shift_raw": round(shift_raw, 6),
|
||||
"shift_norm": round(shift_norm, 4),
|
||||
"zs_height": round(zs.zg - zs.zd, 6),
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Label computation
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _clamp(x: float, lo: float = 0.0, hi: float = 1.0) -> float:
|
||||
return max(lo, min(hi, x))
|
||||
|
||||
def _compute_label(self, zs, contraction: float, shift_norm: float) -> dict:
|
||||
"""计算标签: up / down / none + 连续置信度"""
|
||||
bi_out = zs.bi_out
|
||||
|
||||
if bi_out is None:
|
||||
return {
|
||||
"label": "none",
|
||||
"label_confidence": 0.0,
|
||||
"label_detail": {
|
||||
"bi_out_dir": "none",
|
||||
"score_breakout": 0.0,
|
||||
"score_shift": 0.0,
|
||||
"score_contraction": 0.0,
|
||||
},
|
||||
}
|
||||
|
||||
zs_height = zs.zg - zs.zd
|
||||
if zs_height == 0:
|
||||
zs_height = 1e-8
|
||||
|
||||
# ---- 向上突破分数 ----
|
||||
if bi_out.dir == Chan_BI_DIR.UP:
|
||||
raw_breakout = (bi_out.high - zs.gg) / zs_height
|
||||
score_breakout_up = self._clamp(raw_breakout)
|
||||
score_shift_up = math.tanh(self._clamp(shift_norm, -3.0, 3.0))
|
||||
score_contraction_up = max(0.0, 1.0 - contraction)
|
||||
else:
|
||||
score_breakout_up = 0.0
|
||||
score_shift_up = 0.0
|
||||
score_contraction_up = 0.0
|
||||
|
||||
up_score = (
|
||||
score_breakout_up * 0.5
|
||||
+ score_shift_up * 0.3
|
||||
+ score_contraction_up * 0.2
|
||||
)
|
||||
|
||||
# ---- 向下突破分数 ----
|
||||
if bi_out.dir == Chan_BI_DIR.DOWN:
|
||||
raw_breakout = (zs.dd - bi_out.low) / zs_height
|
||||
score_breakout_down = self._clamp(raw_breakout)
|
||||
score_shift_down = math.tanh(self._clamp(-shift_norm, -3.0, 3.0))
|
||||
score_contraction_down = max(0.0, 1.0 - contraction)
|
||||
else:
|
||||
score_breakout_down = 0.0
|
||||
score_shift_down = 0.0
|
||||
score_contraction_down = 0.0
|
||||
|
||||
down_score = (
|
||||
score_breakout_down * 0.5
|
||||
+ score_shift_down * 0.3
|
||||
+ score_contraction_down * 0.2
|
||||
)
|
||||
|
||||
# ---- 判定 ----
|
||||
threshold = 0.15
|
||||
|
||||
if up_score > down_score and up_score > threshold:
|
||||
label = "up"
|
||||
confidence = up_score
|
||||
detail = {
|
||||
"bi_out_dir": "up",
|
||||
"score_breakout": round(score_breakout_up, 4),
|
||||
"score_shift": round(score_shift_up, 4),
|
||||
"score_contraction": round(score_contraction_up, 4),
|
||||
}
|
||||
elif down_score > up_score and down_score > threshold:
|
||||
label = "down"
|
||||
confidence = down_score
|
||||
detail = {
|
||||
"bi_out_dir": "down",
|
||||
"score_breakout": round(score_breakout_down, 4),
|
||||
"score_shift": round(score_shift_down, 4),
|
||||
"score_contraction": round(score_contraction_down, 4),
|
||||
}
|
||||
else:
|
||||
label = "none"
|
||||
confidence = max(up_score, down_score)
|
||||
bi_dir = "up" if bi_out.dir == Chan_BI_DIR.UP else "down"
|
||||
detail = {
|
||||
"bi_out_dir": bi_dir,
|
||||
"score_breakout": round(max(score_breakout_up, score_breakout_down), 4),
|
||||
"score_shift": round(max(score_shift_up, score_shift_down), 4),
|
||||
"score_contraction": round(max(score_contraction_up, score_contraction_down), 4),
|
||||
}
|
||||
|
||||
return {
|
||||
"label": label,
|
||||
"label_confidence": round(confidence, 4),
|
||||
"label_detail": detail,
|
||||
}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def extract(self) -> list[dict]:
|
||||
"""主入口:对每个中枢提取 3 特征 + 1 标签"""
|
||||
|
||||
# 第一遍:计算原始值
|
||||
raw = []
|
||||
for i, zs in enumerate(self.bi_zs_list):
|
||||
if not zs.is_sure or len(zs.bi_list) < 3:
|
||||
continue
|
||||
|
||||
duration_raw = ChanPivotClassifier.calc_duration(zs)
|
||||
contraction = ChanPivotClassifier.calc_contraction(zs)
|
||||
shift_raw, shift_norm = ChanPivotClassifier.calc_shift(zs)
|
||||
|
||||
raw.append({
|
||||
"zs": zs,
|
||||
"zs_index": i,
|
||||
"duration_raw": duration_raw,
|
||||
"contraction": contraction,
|
||||
"shift_raw": shift_raw,
|
||||
"shift_norm": shift_norm,
|
||||
"zs_height": zs.zg - zs.zd,
|
||||
})
|
||||
|
||||
# 第二遍:组装输出 + 计算 label
|
||||
result = []
|
||||
for r in raw:
|
||||
zs = r["zs"]
|
||||
historical = [x["duration_raw"] for x in raw]
|
||||
duration_norm = ChanPivotClassifier.compute_duration_norm(
|
||||
r["duration_raw"], historical
|
||||
)
|
||||
label_info = self._compute_label(zs, r["contraction"], r["shift_norm"])
|
||||
|
||||
# 时间处理
|
||||
start_time = None
|
||||
end_time = None
|
||||
if hasattr(zs, "start_time") and zs.start_time is not None:
|
||||
start_time = str(zs.start_time)
|
||||
if hasattr(zs, "end_time") and zs.end_time is not None:
|
||||
end_time = str(zs.end_time)
|
||||
|
||||
result.append({
|
||||
"dataset_version": self.DATASET_VERSION,
|
||||
"feature_schema": self.FEATURE_SCHEMA,
|
||||
"label_schema": self.LABEL_SCHEMA,
|
||||
|
||||
"symbol": self.symbol,
|
||||
"timeframe": self.timeframe,
|
||||
"zs_index": r["zs_index"],
|
||||
"zs_start_time": start_time,
|
||||
"zs_end_time": end_time,
|
||||
|
||||
"duration_norm": round(duration_norm, 4),
|
||||
"contraction": round(r["contraction"], 4),
|
||||
"shift_norm": round(r["shift_norm"], 4),
|
||||
|
||||
"label": label_info["label"],
|
||||
"label_confidence": label_info["label_confidence"],
|
||||
"label_detail": label_info["label_detail"],
|
||||
|
||||
"duration_raw": r["duration_raw"],
|
||||
"shift_raw": round(r["shift_raw"], 6),
|
||||
"zs_height": round(r["zs_height"], 6),
|
||||
})
|
||||
|
||||
return result
|
||||
|
||||
def export_json(self, path: str):
|
||||
"""导出为 JSON 文件"""
|
||||
data = self.extract()
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False, default=str)
|
||||
return len(data)
|
||||
@@ -0,0 +1,145 @@
|
||||
"""
|
||||
实时中枢特征跟踪器
|
||||
Real-time Pivot Feature Tracker
|
||||
|
||||
定位: 观察者 — 不修改管线,只观察 bi_zs_list 中当前中枢的特征变化。
|
||||
每次管线重算后调用 update(),检测 bi_count 是否增长,若增长则重新计算
|
||||
shift / contraction / duration。
|
||||
"""
|
||||
|
||||
from collections import deque
|
||||
from typing import Optional
|
||||
from chanlun.analysis.ChanPivotClassifier import ChanPivotClassifier
|
||||
|
||||
|
||||
class ChanPivotMonitor:
|
||||
"""
|
||||
实时追踪当前中枢的结构特征。
|
||||
|
||||
update() 每次管线重算后调用,对比 bi_count 判断是否有新笔加入中枢。
|
||||
若 bi_count 增长则重新计算 3 个结构特征并返回最新值。
|
||||
"""
|
||||
|
||||
def __init__(self, window_size: int = 10):
|
||||
self._window_size = window_size
|
||||
self._duration_history: deque[int] = deque(maxlen=window_size)
|
||||
self._current_zs_id: Optional[tuple] = None
|
||||
self._current_bi_count: int = 0
|
||||
self._current_is_sure: bool = False
|
||||
self._current_state: Optional[dict] = None
|
||||
self._duration_added_for_zs: set = set() # 已加入窗口的中枢 ID(上限 200)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def update(self, bi_zs_list: list) -> Optional[dict]:
|
||||
"""
|
||||
主入口:检测当前中枢特征变化。
|
||||
|
||||
参数:
|
||||
bi_zs_list: 当前管线产出的笔中枢列表
|
||||
|
||||
返回:
|
||||
特征 dict(有变化时),无变化返回 None
|
||||
"""
|
||||
if not bi_zs_list:
|
||||
self._current_zs_id = None
|
||||
self._current_bi_count = 0
|
||||
self._current_is_sure = False
|
||||
self._current_state = None
|
||||
return None
|
||||
|
||||
zs = self._find_current_zs(bi_zs_list)
|
||||
if zs is None:
|
||||
return None
|
||||
|
||||
zs_id = self._make_zs_id(zs)
|
||||
bi_count = len(zs.bi_list)
|
||||
is_sure = zs.is_sure
|
||||
|
||||
# 无变化 → 跳过
|
||||
if (zs_id == self._current_zs_id
|
||||
and bi_count == self._current_bi_count
|
||||
and is_sure == self._current_is_sure):
|
||||
return None
|
||||
|
||||
# 中枢切换 → 将旧中枢 duration 加入窗口
|
||||
if zs_id != self._current_zs_id:
|
||||
self._maybe_add_to_history()
|
||||
|
||||
self._current_zs_id = zs_id
|
||||
self._current_bi_count = bi_count
|
||||
self._current_is_sure = is_sure
|
||||
|
||||
features = ChanPivotClassifier.compute_features(
|
||||
zs, list(self._duration_history)
|
||||
)
|
||||
|
||||
self._current_state = {
|
||||
"zs_id": zs_id,
|
||||
"zs_index": zs.index,
|
||||
"zs_dir": str(zs.dir),
|
||||
"bi_count": bi_count,
|
||||
"is_sure": zs.is_sure,
|
||||
"zg": round(zs.zg, 6),
|
||||
"zd": round(zs.zd, 6),
|
||||
"gg": round(zs.gg, 6),
|
||||
"dd": round(zs.dd, 6),
|
||||
**features,
|
||||
"start_time": str(t) if (t := getattr(zs, "start_time", None)) else None,
|
||||
}
|
||||
|
||||
# 中枢刚变为已确认时,将其 duration 加入滚动窗口
|
||||
if is_sure and zs_id not in self._duration_added_for_zs:
|
||||
self._add_duration(features["duration_raw"])
|
||||
self._duration_added_for_zs.add(zs_id)
|
||||
|
||||
return self._current_state
|
||||
|
||||
def get_current(self) -> Optional[dict]:
|
||||
"""返回当前中枢的最新特征"""
|
||||
return self._current_state
|
||||
|
||||
def get_duration_history(self) -> list[int]:
|
||||
"""返回用于归一化的 duration 滚动窗口"""
|
||||
return list(self._duration_history)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Internal
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _make_zs_id(zs) -> tuple:
|
||||
"""生成中枢的稳定标识(基于首笔首K线时间戳,不随 DataFrame 窗口偏移而变化)"""
|
||||
bi0 = zs.bi_list[0]
|
||||
return (bi0.start_klc.start_time,)
|
||||
|
||||
@staticmethod
|
||||
def _find_current_zs(bi_zs_list: list):
|
||||
"""
|
||||
找到当前活跃中枢:
|
||||
优先取最后一个 is_sure=False(形成中)的中枢,
|
||||
没有则取最后一个 is_sure=True 的中枢。
|
||||
"""
|
||||
forming = None
|
||||
last_sure = None
|
||||
for zs in bi_zs_list:
|
||||
if len(zs.bi_list) < 3:
|
||||
continue
|
||||
if not zs.is_sure:
|
||||
forming = zs
|
||||
else:
|
||||
last_sure = zs
|
||||
return forming if forming is not None else last_sure
|
||||
|
||||
def _add_duration(self, duration_raw: int):
|
||||
"""将已确认中枢的 duration 加入滚动窗口"""
|
||||
self._duration_history.append(duration_raw)
|
||||
|
||||
def _maybe_add_to_history(self):
|
||||
"""旧中枢切换前,若已确认且未记录过,则将其 duration 加入窗口"""
|
||||
if (self._current_state and self._current_state["is_sure"]
|
||||
and self._current_zs_id not in self._duration_added_for_zs):
|
||||
self._add_duration(self._current_state["duration_raw"])
|
||||
self._duration_added_for_zs.add(self._current_zs_id)
|
||||
@@ -0,0 +1,566 @@
|
||||
"""
|
||||
结构价值区 (Structure Zone) 系统
|
||||
|
||||
将多时间周期的 Chan 中枢边界 (ZD/ZG/GG/DD) 和 EMA52 统一表示为带强度评分的价值区对象。
|
||||
"""
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List, Dict, Optional, Any
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Dataclasses
|
||||
# ============================================================
|
||||
|
||||
@dataclass
|
||||
class RawZonePoint:
|
||||
"""内部中间结构:从 Chan 中枢提取的单个价格点"""
|
||||
price: float
|
||||
timeframe: str # '5m', '1h', '4h' 等
|
||||
structure_type: str # 'bi_zhongshu' | 'xd_zhongshu' | 'ema52'
|
||||
boundary_type: str # 'ZD' | 'ZG' | 'GG' | 'DD' | 'EMA52'
|
||||
source_zs_id: int # 来源 ZS 在列表中的 index(调试用)
|
||||
is_sure: bool # 来源 ZS 是否已完成
|
||||
candle_time: Optional[str] = None # 来源 ZS 的 end_time(用于 recency 计算)
|
||||
|
||||
|
||||
@dataclass
|
||||
class StructureZone:
|
||||
"""统一的价值区对象"""
|
||||
id: int
|
||||
lower: float
|
||||
upper: float
|
||||
center: float # (lower + upper) / 2
|
||||
width_pct: float # (upper - lower) / center * 100
|
||||
zone_type: str # 'support' | 'resistance' | 'neutral'
|
||||
timeframes: List[str] # 参与形成此区间的时间周期
|
||||
structure_types: List[str] # 参与形成的结构类型
|
||||
boundary_types: List[str] # 参与形成的边界类型
|
||||
overlap_count: int # 聚类中的原始点数
|
||||
touch_count: int # MVP: 等于 overlap_count
|
||||
recency_score: float # 0.0 - 1.0, 1.0 = 最近
|
||||
ema52_distance_pct: float # 到最近 EMA52 的距离百分比
|
||||
ema52_aligned: bool # 是否有 EMA52 落在区间内
|
||||
strength_score: float # 0-100 综合评分
|
||||
confidence: float # 0.0 - 1.0
|
||||
first_seen: Optional[str] # 最早的 candle_time
|
||||
last_seen: Optional[str] # 最晚的 candle_time
|
||||
metadata: Dict[str, Any] = field(default_factory=dict)
|
||||
|
||||
|
||||
@dataclass
|
||||
class StructureZoneConfig:
|
||||
"""StructureZone 提取与评分配置"""
|
||||
cluster_radius_pct: float = 0.5 # 价格聚类半径(百分比)
|
||||
min_overlap_for_zone: int = 2 # 最少重叠点数才能形成区间
|
||||
max_zones: int = 20 # 返回的最大区间数
|
||||
recency_halflife_bars: int = 50 # recency 衰减半衰期(K线数)
|
||||
zone_timeframes: List[str] = field(default_factory=lambda: ['4h', '1h', '30m', '15m', '5m'])
|
||||
kl_lines_per_tf: int = 500 # 每个时间周期使用最近多少根K线
|
||||
structure_weights: Dict[str, float] = field(default_factory=lambda: {
|
||||
'bi_zhongshu': 1.0, # 笔中枢 — 最直接的价格行为
|
||||
'xd_zhongshu': 0.8, # 线段中枢 — 较高级别但粒度较粗
|
||||
'ema52': 0.4, # EMA — 趋势参考,弱于结构
|
||||
})
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Extraction
|
||||
# ============================================================
|
||||
|
||||
def extract_raw_points_from_tf_df(
|
||||
tf_df_dict: Dict[str, Any],
|
||||
ema_symbols: List[str],
|
||||
config: StructureZoneConfig,
|
||||
) -> List[RawZonePoint]:
|
||||
"""
|
||||
从 ChanLun.tf_df_dict 中提取所有原始价格点。
|
||||
仅处理 config.zone_timeframes 中存在的时间周期。
|
||||
"""
|
||||
points: List[RawZonePoint] = []
|
||||
|
||||
for tf_name in config.zone_timeframes:
|
||||
if tf_name not in tf_df_dict:
|
||||
continue
|
||||
|
||||
tf_df = tf_df_dict[tf_name]
|
||||
|
||||
# 1. 笔中枢 (ChanBIZS)
|
||||
try:
|
||||
if hasattr(tf_df, 'seg_list') and tf_df.seg_list:
|
||||
bi_zs_result = tf_df.cal_bi_zs(tf_df.seg_list)
|
||||
if bi_zs_result:
|
||||
_extract_from_zs_objects(
|
||||
points, tf_name, 'bi_zhongshu', bi_zs_result, config.kl_lines_per_tf
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2. 线段中枢 (ChanZS)
|
||||
try:
|
||||
zs_list = getattr(tf_df, 'zs_list', None)
|
||||
if zs_list:
|
||||
_extract_from_zs_objects(
|
||||
points, tf_name, 'xd_zhongshu', zs_list, config.kl_lines_per_tf
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 3. EMA52 值
|
||||
for tf_name in config.zone_timeframes:
|
||||
if tf_name in tf_df_dict:
|
||||
try:
|
||||
ema_val = tf_df_dict[tf_name].get_ema52()
|
||||
if ema_val is not None and ema_val > 0:
|
||||
points.append(RawZonePoint(
|
||||
price=float(ema_val),
|
||||
timeframe=tf_name,
|
||||
structure_type='ema52',
|
||||
boundary_type='EMA52',
|
||||
source_zs_id=-1,
|
||||
is_sure=True,
|
||||
candle_time=None,
|
||||
))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return points
|
||||
|
||||
|
||||
def _extract_from_zs_objects(
|
||||
points: List[RawZonePoint],
|
||||
tf_name: str,
|
||||
structure_type: str,
|
||||
zs_list,
|
||||
kl_limit: int,
|
||||
):
|
||||
"""从 ZS 链表中提取 ZD/ZG/GG/DD 点"""
|
||||
count = 0
|
||||
node = zs_list
|
||||
while hasattr(node, 'next'):
|
||||
node = node.next
|
||||
# 从链表头开始遍历
|
||||
head = zs_list
|
||||
# 收集所有节点
|
||||
all_nodes = []
|
||||
cur = head
|
||||
while cur is not None and hasattr(cur, 'next'):
|
||||
all_nodes.append(cur)
|
||||
cur = cur.next
|
||||
# 只取最近 kl_limit 根K线内的 ZS
|
||||
all_nodes = all_nodes[-kl_limit:] if len(all_nodes) > kl_limit else all_nodes
|
||||
|
||||
for idx, zs in enumerate(all_nodes):
|
||||
if not getattr(zs, 'is_sure', False):
|
||||
continue
|
||||
try:
|
||||
zg = float(zs.zg)
|
||||
zd = float(zs.zd)
|
||||
gg = float(zs.gg) if getattr(zs, 'gg', 0) else zg
|
||||
dd = float(zs.dd) if getattr(zs, 'dd', 0) else zd
|
||||
end_time = str(zs.end_time) if hasattr(zs, 'end_time') and zs.end_time else None
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
continue
|
||||
|
||||
if zg <= 0 or zd <= 0:
|
||||
continue
|
||||
|
||||
zs_id = getattr(zs, 'index', idx)
|
||||
points.append(RawZonePoint(price=zg, timeframe=tf_name, structure_type=structure_type,
|
||||
boundary_type='ZG', source_zs_id=zs_id, is_sure=True,
|
||||
candle_time=end_time))
|
||||
points.append(RawZonePoint(price=zd, timeframe=tf_name, structure_type=structure_type,
|
||||
boundary_type='ZD', source_zs_id=zs_id, is_sure=True,
|
||||
candle_time=end_time))
|
||||
points.append(RawZonePoint(price=gg, timeframe=tf_name, structure_type=structure_type,
|
||||
boundary_type='GG', source_zs_id=zs_id, is_sure=True,
|
||||
candle_time=end_time))
|
||||
points.append(RawZonePoint(price=dd, timeframe=tf_name, structure_type=structure_type,
|
||||
boundary_type='DD', source_zs_id=zs_id, is_sure=True,
|
||||
candle_time=end_time))
|
||||
|
||||
|
||||
def extract_raw_points_from_serialized(
|
||||
analyses: Dict[str, Dict],
|
||||
ema52_dict: Dict[str, Optional[float]],
|
||||
config: StructureZoneConfig,
|
||||
) -> List[RawZonePoint]:
|
||||
"""
|
||||
从已序列化的分析结果中提取价格点(用于 web API,避免重复计算)。
|
||||
analyses: {'5m': {'zs_list': [...], 'bi_zs_list': [...]}, '15m': {...}, ...}
|
||||
ema52_dict: {'5m': 123.45, '15m': None, ...}
|
||||
"""
|
||||
points: List[RawZonePoint] = []
|
||||
|
||||
for tf_name in config.zone_timeframes:
|
||||
if tf_name not in analyses:
|
||||
continue
|
||||
|
||||
analysis = analyses[tf_name]
|
||||
|
||||
# 笔中枢
|
||||
bi_zs_items = analysis.get('bi_zs_list', [])
|
||||
for idx, zs in enumerate(bi_zs_items):
|
||||
if not zs.get('is_sure', False):
|
||||
continue
|
||||
try:
|
||||
zg = float(zs['zg']); zd = float(zs['zd'])
|
||||
gg = float(zs.get('gg', zg)); dd = float(zs.get('dd', zd))
|
||||
end_time = zs.get('end_time')
|
||||
except (ValueError, KeyError):
|
||||
continue
|
||||
if zg <= 0 or zd <= 0:
|
||||
continue
|
||||
points.append(RawZonePoint(price=zg, timeframe=tf_name, structure_type='bi_zhongshu',
|
||||
boundary_type='ZG', source_zs_id=idx, is_sure=True,
|
||||
candle_time=str(end_time) if end_time else None))
|
||||
points.append(RawZonePoint(price=zd, timeframe=tf_name, structure_type='bi_zhongshu',
|
||||
boundary_type='ZD', source_zs_id=idx, is_sure=True,
|
||||
candle_time=str(end_time) if end_time else None))
|
||||
points.append(RawZonePoint(price=gg, timeframe=tf_name, structure_type='bi_zhongshu',
|
||||
boundary_type='GG', source_zs_id=idx, is_sure=True,
|
||||
candle_time=str(end_time) if end_time else None))
|
||||
points.append(RawZonePoint(price=dd, timeframe=tf_name, structure_type='bi_zhongshu',
|
||||
boundary_type='DD', source_zs_id=idx, is_sure=True,
|
||||
candle_time=str(end_time) if end_time else None))
|
||||
|
||||
# 线段中枢
|
||||
zs_items = analysis.get('zs_list', [])
|
||||
for idx, zs in enumerate(zs_items):
|
||||
if not zs.get('is_sure', False):
|
||||
continue
|
||||
try:
|
||||
zg = float(zs['zg']); zd = float(zs['zd'])
|
||||
gg = float(zs.get('gg', zg)); dd = float(zs.get('dd', zd))
|
||||
end_time = zs.get('end_time')
|
||||
except (ValueError, KeyError):
|
||||
continue
|
||||
if zg <= 0 or zd <= 0:
|
||||
continue
|
||||
points.append(RawZonePoint(price=zg, timeframe=tf_name, structure_type='xd_zhongshu',
|
||||
boundary_type='ZG', source_zs_id=idx, is_sure=True,
|
||||
candle_time=str(end_time) if end_time else None))
|
||||
points.append(RawZonePoint(price=zd, timeframe=tf_name, structure_type='xd_zhongshu',
|
||||
boundary_type='ZD', source_zs_id=idx, is_sure=True,
|
||||
candle_time=str(end_time) if end_time else None))
|
||||
points.append(RawZonePoint(price=gg, timeframe=tf_name, structure_type='xd_zhongshu',
|
||||
boundary_type='GG', source_zs_id=idx, is_sure=True,
|
||||
candle_time=str(end_time) if end_time else None))
|
||||
points.append(RawZonePoint(price=dd, timeframe=tf_name, structure_type='xd_zhongshu',
|
||||
boundary_type='DD', source_zs_id=idx, is_sure=True,
|
||||
candle_time=str(end_time) if end_time else None))
|
||||
|
||||
# EMA52
|
||||
for tf_name in config.zone_timeframes:
|
||||
ema_val = ema52_dict.get(tf_name)
|
||||
if ema_val is not None and ema_val > 0:
|
||||
points.append(RawZonePoint(
|
||||
price=float(ema_val),
|
||||
timeframe=tf_name,
|
||||
structure_type='ema52',
|
||||
boundary_type='EMA52',
|
||||
source_zs_id=-1,
|
||||
is_sure=True,
|
||||
candle_time=None,
|
||||
))
|
||||
|
||||
return points
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Clustering
|
||||
# ============================================================
|
||||
|
||||
def cluster_raw_points(
|
||||
points: List[RawZonePoint],
|
||||
config: StructureZoneConfig,
|
||||
) -> List[List[RawZonePoint]]:
|
||||
"""
|
||||
贪心单通聚类:将价格相近的 RawZonePoint 归为一组。
|
||||
仅在 1D 价格轴上操作,O(n log n)。
|
||||
"""
|
||||
if not points:
|
||||
return []
|
||||
|
||||
sorted_points = sorted(points, key=lambda p: p.price)
|
||||
clusters: List[List[RawZonePoint]] = []
|
||||
|
||||
for p in sorted_points:
|
||||
placed = False
|
||||
for cluster in reversed(clusters):
|
||||
# 检查是否可以放入当前聚类(与聚类均价比较)
|
||||
avg_price = sum(pt.price for pt in cluster) / len(cluster)
|
||||
if abs(p.price - avg_price) / avg_price * 100 <= config.cluster_radius_pct:
|
||||
cluster.append(p)
|
||||
placed = True
|
||||
break
|
||||
if not placed:
|
||||
clusters.append([p])
|
||||
|
||||
# 过滤点数不足的聚类
|
||||
return [c for c in clusters if len(c) >= config.min_overlap_for_zone]
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Scoring & Building
|
||||
# ============================================================
|
||||
|
||||
def build_structure_zones(
|
||||
clusters: List[List[RawZonePoint]],
|
||||
current_price: float,
|
||||
ema52_values: Dict[str, Optional[float]],
|
||||
latest_candle_time: Optional[str],
|
||||
config: StructureZoneConfig,
|
||||
) -> List[StructureZone]:
|
||||
"""
|
||||
从聚类构建 StructureZone 列表,计算所有字段和评分。
|
||||
"""
|
||||
zones: List[StructureZone] = []
|
||||
|
||||
# 收集所有 EMA52 值
|
||||
ema_prices = [v for v in ema52_values.values() if v is not None and v > 0]
|
||||
|
||||
for zone_id, cluster in enumerate(clusters):
|
||||
prices = [p.price for p in cluster]
|
||||
lower = min(prices)
|
||||
upper = max(prices)
|
||||
center = (lower + upper) / 2
|
||||
width_pct = (upper - lower) / center * 100 if center > 0 else 0.0
|
||||
|
||||
# 区间类型
|
||||
if upper < current_price:
|
||||
zone_type = 'support' # 区间在当前价格下方 → 支撑
|
||||
elif lower > current_price:
|
||||
zone_type = 'resistance' # 区间在当前价格上方 → 阻力
|
||||
else:
|
||||
zone_type = 'neutral' # 区间跨越当前价格
|
||||
|
||||
timeframes = sorted(set(p.timeframe for p in cluster))
|
||||
structure_types = sorted(set(p.structure_type for p in cluster))
|
||||
boundary_types = sorted(set(p.boundary_type for p in cluster))
|
||||
overlap_count = len(cluster)
|
||||
|
||||
# Recency
|
||||
times = [p.candle_time for p in cluster if p.candle_time]
|
||||
first_seen = min(times) if times else None
|
||||
last_seen = max(times) if times else None
|
||||
recency_score = _calc_recency(last_seen, latest_candle_time, config.recency_halflife_bars)
|
||||
|
||||
# EMA52 alignment
|
||||
ema52_distance_pct = 999.0
|
||||
ema52_aligned = False
|
||||
if ema_prices:
|
||||
distances = [abs(center - ep) / ep * 100 for ep in ema_prices]
|
||||
ema52_distance_pct = round(min(distances), 2)
|
||||
ema52_aligned = any(lower <= ep <= upper for ep in ema_prices)
|
||||
|
||||
# Strength score
|
||||
strength_score = _calc_strength(cluster, config, recency_score, ema52_aligned, ema52_distance_pct, width_pct)
|
||||
|
||||
# Confidence
|
||||
confidence = _calc_confidence(overlap_count, len(timeframes), cluster)
|
||||
|
||||
zones.append(StructureZone(
|
||||
id=zone_id + 1,
|
||||
lower=round(lower, 2),
|
||||
upper=round(upper, 2),
|
||||
center=round(center, 2),
|
||||
width_pct=round(width_pct, 2),
|
||||
zone_type=zone_type,
|
||||
timeframes=timeframes,
|
||||
structure_types=structure_types,
|
||||
boundary_types=boundary_types,
|
||||
overlap_count=overlap_count,
|
||||
touch_count=overlap_count, # MVP: 等于 overlap_count
|
||||
recency_score=round(recency_score, 3),
|
||||
ema52_distance_pct=ema52_distance_pct,
|
||||
ema52_aligned=ema52_aligned,
|
||||
strength_score=round(strength_score, 1),
|
||||
confidence=round(confidence, 2),
|
||||
first_seen=first_seen,
|
||||
last_seen=last_seen,
|
||||
))
|
||||
|
||||
# 按强度降序排列
|
||||
zones.sort(key=lambda z: z.strength_score, reverse=True)
|
||||
|
||||
# 截断
|
||||
if config.max_zones > 0 and len(zones) > config.max_zones:
|
||||
zones = zones[:config.max_zones]
|
||||
|
||||
return zones
|
||||
|
||||
|
||||
def _calc_recency(
|
||||
last_seen: Optional[str],
|
||||
latest_time: Optional[str],
|
||||
halflife_bars: int,
|
||||
) -> float:
|
||||
"""计算 recency 分数:越近越高"""
|
||||
if not last_seen or not latest_time:
|
||||
return 0.5
|
||||
|
||||
try:
|
||||
# 尝试解析 ISO 格式时间
|
||||
from dateutil import parser
|
||||
t_last = parser.parse(last_seen)
|
||||
t_latest = parser.parse(latest_time)
|
||||
offset_seconds = (t_latest - t_last).total_seconds()
|
||||
if offset_seconds < 0:
|
||||
return 1.0
|
||||
# 假设每根K线平均 5 分钟
|
||||
bar_seconds = 300
|
||||
offset_bars = offset_seconds / bar_seconds
|
||||
# 指数衰减: 2 ^ (-offset / halflife)
|
||||
score = 2.0 ** (-offset_bars / halflife_bars)
|
||||
return float(score)
|
||||
except Exception:
|
||||
return 0.5
|
||||
|
||||
|
||||
def _calc_strength(
|
||||
cluster: List[RawZonePoint],
|
||||
config: StructureZoneConfig,
|
||||
recency_score: float,
|
||||
ema52_aligned: bool,
|
||||
ema52_distance_pct: float,
|
||||
width_pct: float,
|
||||
) -> float:
|
||||
"""计算综合强度评分 (0-100)"""
|
||||
|
||||
# 组件 1: 结构类型多样性 (0-40)
|
||||
structure_type_counts: Dict[str, int] = {}
|
||||
for p in cluster:
|
||||
structure_type_counts[p.structure_type] = structure_type_counts.get(p.structure_type, 0) + 1
|
||||
total = sum(structure_type_counts.values())
|
||||
structure_score = 0.0
|
||||
for st, count in structure_type_counts.items():
|
||||
weight = config.structure_weights.get(st, 0.5)
|
||||
structure_score += weight * count
|
||||
structure_score = min(structure_score / max(1, total), 1.0)
|
||||
c1 = structure_score * 40
|
||||
|
||||
# 组件 2: 多周期确认 (0-25)
|
||||
tf_set = set(p.timeframe for p in cluster)
|
||||
tf_diversity = len(tf_set)
|
||||
c2 = min(tf_diversity / 5, 1.0) * 25
|
||||
|
||||
# 组件 3: 区间紧密度 (0-15) — 越窄越强
|
||||
tightness = max(0.0, 1.0 - (width_pct / 3.0))
|
||||
c3 = tightness * 15
|
||||
|
||||
# 组件 4: Recency (0-10)
|
||||
c4 = recency_score * 10
|
||||
|
||||
# 组件 5: EMA52 共振 (0-10)
|
||||
if ema52_aligned:
|
||||
ema_proximity = max(0.0, 1.0 - (ema52_distance_pct / 2.0))
|
||||
c5 = ema_proximity * 10
|
||||
else:
|
||||
c5 = 0.0
|
||||
|
||||
return c1 + c2 + c3 + c4 + c5
|
||||
|
||||
|
||||
def _calc_confidence(
|
||||
overlap_count: int,
|
||||
tf_count: int,
|
||||
cluster: List[RawZonePoint],
|
||||
) -> float:
|
||||
"""计算置信度 (0-1)"""
|
||||
base = min(overlap_count / 6.0, 0.85)
|
||||
# 多周期加分
|
||||
tf_bonus = min(tf_count / 5.0, 0.1)
|
||||
# 是否所有点都来自 sure 的 ZS
|
||||
all_sure = all(p.is_sure for p in cluster)
|
||||
sure_bonus = 0.05 if all_sure else 0.0
|
||||
return min(base + tf_bonus + sure_bonus, 1.0)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Top-level pipeline
|
||||
# ============================================================
|
||||
|
||||
def analyze_structure_zones(
|
||||
tf_df_dict: Dict[str, Any],
|
||||
ema_symbols: List[str],
|
||||
current_price: Optional[float] = None,
|
||||
config: Optional[StructureZoneConfig] = None,
|
||||
) -> List[StructureZone]:
|
||||
"""
|
||||
一站式分析:提取 → 聚类 → 评分 → 返回排序后的 StructureZone 列表。
|
||||
"""
|
||||
if config is None:
|
||||
config = StructureZoneConfig()
|
||||
|
||||
# 提取
|
||||
raw_points = extract_raw_points_from_tf_df(tf_df_dict, ema_symbols, config)
|
||||
|
||||
if not raw_points:
|
||||
return []
|
||||
|
||||
# 获取当前价格
|
||||
if current_price is None:
|
||||
for tf_name in config.zone_timeframes:
|
||||
if tf_name in tf_df_dict:
|
||||
try:
|
||||
ema_val = tf_df_dict[tf_name].get_ema52()
|
||||
if ema_val and ema_val > 0:
|
||||
current_price = float(ema_val)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if current_price is None:
|
||||
current_price = 0.0
|
||||
|
||||
# EMA52 值
|
||||
ema52_values = {}
|
||||
for tf_name in config.zone_timeframes:
|
||||
if tf_name in tf_df_dict:
|
||||
try:
|
||||
ema52_values[tf_name] = tf_df_dict[tf_name].get_ema52()
|
||||
except Exception:
|
||||
ema52_values[tf_name] = None
|
||||
|
||||
# 最晚时间
|
||||
latest_time = None
|
||||
times = [p.candle_time for p in raw_points if p.candle_time]
|
||||
if times:
|
||||
latest_time = max(times)
|
||||
|
||||
# 聚类
|
||||
clusters = cluster_raw_points(raw_points, config)
|
||||
|
||||
# 构建 & 评分
|
||||
return build_structure_zones(clusters, current_price, ema52_values, latest_time, config)
|
||||
|
||||
|
||||
def analyze_structure_zones_from_serialized(
|
||||
analyses: Dict[str, Dict],
|
||||
ema52_dict: Dict[str, Optional[float]],
|
||||
current_price: float,
|
||||
config: Optional[StructureZoneConfig] = None,
|
||||
) -> List[StructureZone]:
|
||||
"""
|
||||
从已序列化的分析结果构建 StructureZone(用于 web API)。
|
||||
"""
|
||||
if config is None:
|
||||
config = StructureZoneConfig()
|
||||
|
||||
raw_points = extract_raw_points_from_serialized(analyses, ema52_dict, config)
|
||||
|
||||
if not raw_points:
|
||||
return []
|
||||
|
||||
# 最晚时间
|
||||
latest_time = None
|
||||
times = [p.candle_time for p in raw_points if p.candle_time]
|
||||
if times:
|
||||
latest_time = max(times)
|
||||
|
||||
# EMA52 值(用于 alignment 检测)
|
||||
ema_values = {tf: v for tf, v in ema52_dict.items() if v is not None and v > 0}
|
||||
|
||||
clusters = cluster_raw_points(raw_points, config)
|
||||
return build_structure_zones(clusters, current_price, ema_values, latest_time, config)
|
||||
@@ -2,7 +2,7 @@ import ccxt
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
import mplfinance as mpf
|
||||
from talib import MACD, SMA
|
||||
from chanlun.indicators import ta
|
||||
from datetime import datetime, timedelta
|
||||
import logging
|
||||
import datetime as dt
|
||||
@@ -249,8 +249,9 @@ def analyze_higher_timeframe(df_30m):
|
||||
# 8. Back-divergence detection (enhanced)
|
||||
def detect_back_divergence(df, strokes, higher_trend):
|
||||
try:
|
||||
macd, signal, hist = MACD(df['Close'], fastperiod=12, slowperiod=26, signalperiod=9)
|
||||
sma20 = SMA(df['Close'], timeperiod=20)
|
||||
macd_df = ta.MACD(df['Close'], fastperiod=12, slowperiod=26, signalperiod=9)
|
||||
macd, hist = macd_df['macd'], macd_df['macdhist']
|
||||
sma20 = ta.SMA(df['Close'], timeperiod=20)
|
||||
df['macd'] = macd
|
||||
df['hist'] = hist
|
||||
df['sma20'] = sma20
|
||||
@@ -0,0 +1,384 @@
|
||||
"""快速三类买卖点(引擎内称第四类,B4/S4)。
|
||||
|
||||
原本长在 `research/lib/fast_bsp3.py`,现移入引擎作为唯一实现,研究脚本改为转发导入,
|
||||
这样回测口径与 web 图表永远一致。
|
||||
|
||||
命名说明:缠论原文里没有「第四类买卖点」,但 B4/S4 也不只是「B3/S3 提前几根」——
|
||||
两者的选样口径不同,统计性质符号相反,故单独立类。形态条件是实时可判的:
|
||||
|
||||
中枢已成 -> 收盘突破 zg -> 收盘未跌回中枢 -> 重新上行
|
||||
|
||||
最后一步发生的当根就能下单,滞后约 2 根,而引擎 B3/S3 要等 pullback_bi.sure_time,
|
||||
滞后 9~10 根。但差别不止滞后:
|
||||
|
||||
判据 引擎用笔端点事后判(回拉笔低点 >= zg),本函数用收盘价实时判
|
||||
方向 引擎由离开笔方向决定,本函数由收盘从哪一侧突破决定
|
||||
口径 627 个中枢里引擎发 625 个信号(几乎不筛),本函数只认 212 个(34%);
|
||||
被拒的多数是「中枢确认时价格早已离开、此后再没回来」的历史区间
|
||||
|
||||
step30 同条件对拍(同一套 pure 笔中枢、同一组过滤器、同样的 1.5/3.0/48 出场):
|
||||
|
||||
原始 PF +大级别同向 +同向+阶梯 胜率 t值
|
||||
引擎 B3/S3 0.66 0.66 0.71 27.4% -18.76
|
||||
本函数 B4/S4 1.59 1.85 2.26 47.1% +10.09
|
||||
|
||||
同一组过滤器对 B4 有效、对 B3 无效,滞后差解释不了这一点(入场后移 1~4 根只是
|
||||
PF 3.18->2.53 的平滑衰减)。且 SL1.5/TP3.0 下随机入场胜率约 33%,引擎那 27.4%
|
||||
低于随机——它选中的是一批系统性反向的样本,不是「晚了所以差」。
|
||||
|
||||
require_touch 控制是否强求回抽碰到中枢边界。step32/33 的实测表明强求反而更差:
|
||||
这等于排除掉「突破后一去不回头」的强势段,而那正是缠论里最强的趋势形态。
|
||||
故默认 False(笔数 +21%、滞后 -1 根、PF 2.26→2.37)。
|
||||
|
||||
判据本身(收盘越过前一根极值)没有独立预测力:裸用 15 万笔样本 PF 0.95,
|
||||
把中枢换成「近20根高点」这类伪阻力位后 PF 0.90。alpha 全部来自中枢结构,
|
||||
判据只负责在这个已知价位上确认动能恢复。它也不能用于识别笔端点——
|
||||
入场前的回抽极值命中笔端点±2根的比例 19.3%,低于随机基准 22%。
|
||||
|
||||
全部判定只使用当根及之前的数据,无未来函数。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from chanlun.core.ChanEnum import Chan_FX_TYPE
|
||||
|
||||
# 中枢的「可用时刻」取第几笔的确认时间。
|
||||
# -1 = 最后一笔(历史默认)。中枢每吸收一根K线,最后一笔就可能后移,
|
||||
# 于是 available_ts 跟着漂——这是右边缘重画的根因(见 HANDOFF §5.41)。
|
||||
# 2 = 第三笔。三笔重叠即中枢成立,此后不再变,理论上更早也更稳。
|
||||
# ⛔ step47 已判定 bis[2] 作废(毛 R 0.933 → −0.000,见 HANDOFF §5.42)。
|
||||
# 开关保留只为可复现那次 A/B,**不要改默认值**。
|
||||
import os as _os
|
||||
|
||||
AVAIL_BI_INDEX = -1
|
||||
|
||||
|
||||
def _resolve_avail_bi(avail_bi: int | None) -> int:
|
||||
"""优先级:显式入参 > 环境变量 CHAN_AVAIL_BI > 模块默认。
|
||||
|
||||
环境变量在调用时读取而非 import 时——ProcessPoolExecutor 在 fork 启动方式下
|
||||
子进程会继承已 import 的模块,import 时读就固化成父进程的值了。
|
||||
"""
|
||||
if avail_bi is not None:
|
||||
return avail_bi
|
||||
return int(_os.environ.get("CHAN_AVAIL_BI", AVAIL_BI_INDEX))
|
||||
|
||||
|
||||
def timestamps_ms(src: pd.DataFrame) -> np.ndarray:
|
||||
"""取毫秒时间戳。研究侧的 df 自带 timestamp,web 侧的不一定,故按 date 回退。
|
||||
|
||||
回退写法不能用 `date.astype("int64") // 10**6`:该值单位取决于列精度,
|
||||
对毫秒精度的列会把时间戳砸平。
|
||||
"""
|
||||
if "timestamp" in src.columns:
|
||||
return src["timestamp"].to_numpy()
|
||||
d = pd.to_datetime(src["date"])
|
||||
if getattr(d.dt, "tz", None) is None:
|
||||
d = d.dt.tz_localize("UTC")
|
||||
return (d.dt.tz_convert("UTC").dt.tz_localize(None)
|
||||
.astype("datetime64[ms]").astype("int64").to_numpy())
|
||||
|
||||
|
||||
def ensure_timestamp(df: pd.DataFrame) -> pd.DataFrame:
|
||||
"""保证 df 带 timestamp 列,缺失时补一份副本,不改动调用方的对象。"""
|
||||
if "timestamp" in df.columns:
|
||||
return df
|
||||
out = df.copy()
|
||||
out["timestamp"] = timestamps_ms(out)
|
||||
return out
|
||||
|
||||
|
||||
def build_htf_zones(df_htf: pd.DataFrame, tf: str, chan=None, avail_bi: int | None = None) -> pd.DataFrame:
|
||||
"""算 pure 笔中枢,返回带生效时间的区间表。
|
||||
|
||||
available_ts —— 该中枢最早可被使用的时间戳(其确认时刻)。
|
||||
传入已构建好的 chan 可避免重复跑一遍 pipeline(大数据集上省一半时间)。
|
||||
"""
|
||||
if chan is None:
|
||||
from chanlun import TF_DF
|
||||
|
||||
chan = TF_DF(df_htf, 1, tf)
|
||||
zs_list = chan.cal_bi_zs_list_pure(chan.bi_list)
|
||||
# 用引擎自己的 dataframe 对齐,避免调用方传入的 df 与引擎内部行数不一致
|
||||
src = chan.dataframe if getattr(chan, "dataframe", None) is not None else df_htf
|
||||
return zones_from_zs_list(zs_list, src, avail_bi=avail_bi)
|
||||
|
||||
|
||||
def zones_from_zs_list(zs_list, src: pd.DataFrame, avail_bi: int | None = None) -> pd.DataFrame:
|
||||
"""把已算好的 pure 笔中枢转成区间表。
|
||||
|
||||
调用方手工跑过 cal_bi_zs_list_pure 时走这里,免得再算一遍(web 的 analyze_chan
|
||||
就是这种用法)。
|
||||
"""
|
||||
ts_of = dict(zip(src["date"].dt.strftime("%Y-%m-%d %H:%M:%S"), timestamps_ms(src)))
|
||||
# 中枢可用时刻取第几笔。在循环外解析一次,别让每个中枢都去读一遍环境变量。
|
||||
i = _resolve_avail_bi(avail_bi)
|
||||
|
||||
rows = []
|
||||
for zs in zs_list:
|
||||
bis = getattr(zs, "bi_list", [])
|
||||
if not bis:
|
||||
continue
|
||||
# 笔数不够时退回最后一笔(i=2 需要至少 3 笔才成立)
|
||||
key_bi = bis[i] if (i == -1 or len(bis) > i) else bis[-1]
|
||||
sure_key = str(getattr(key_bi, "sure_time", "") or "")
|
||||
end_key = str(getattr(key_bi, "end_time", "") or "")
|
||||
avail = ts_of.get(sure_key) or ts_of.get(end_key)
|
||||
if avail is None:
|
||||
continue
|
||||
start_key = str(bis[0].start_time)
|
||||
rows.append({
|
||||
"zg": float(zs.zg), "zd": float(zs.zd),
|
||||
"gg": float(getattr(zs, "gg", zs.zg)), "dd": float(getattr(zs, "dd", zs.zd)),
|
||||
"start_ts": ts_of.get(start_key, avail),
|
||||
"available_ts": int(avail),
|
||||
})
|
||||
out = pd.DataFrame(rows)
|
||||
return out.sort_values("available_ts").reset_index(drop=True) if not out.empty else out
|
||||
|
||||
|
||||
def add_zone_ladder(zones: pd.DataFrame) -> pd.DataFrame:
|
||||
"""标注每个中枢相对前一个中枢是否同向推进(缠论「趋势 vs 盘整」)。
|
||||
|
||||
z_above / z_below 分别对应向上、向下推进。买信号要求 z_above、卖信号要求 z_below
|
||||
时,30m/2h 的 PF 从 2.72 升到 3.41。
|
||||
"""
|
||||
out = zones.copy()
|
||||
if out.empty:
|
||||
out["z_above"], out["z_below"] = pd.Series(dtype=bool), pd.Series(dtype=bool)
|
||||
return out
|
||||
pg, pdn = out["zg"].shift(), out["zd"].shift()
|
||||
out["z_above"] = (out["zd"] > pg).fillna(False)
|
||||
out["z_below"] = (out["zg"] < pdn).fillna(False)
|
||||
return out
|
||||
|
||||
|
||||
def htf_fx_timeline(chan_htf, df_htf: pd.DataFrame | None = None) -> pd.DataFrame:
|
||||
"""把大级别分型压成一条按确认时间排序的时间线。
|
||||
|
||||
confirm_ts 是该分型最早可被使用的时刻。timestamp 是K线开盘时刻,而分型要等这根K线
|
||||
收盘才算数,所以整体后移一个大级别周期;否则小级别会提前一整根大级别K线拿到信号。
|
||||
|
||||
只取方向与确认时刻——同向过滤用不到背驰强度,省掉 MACD 面积计算。
|
||||
"""
|
||||
src = chan_htf.dataframe if getattr(chan_htf, "dataframe", None) is not None else df_htf
|
||||
if src is None or len(src) == 0:
|
||||
return pd.DataFrame(columns=["confirm_ts", "fx_ts", "direction", "price"])
|
||||
ts = timestamps_ms(src)
|
||||
idx_of = {t: i for i, t in enumerate(src["date"].dt.strftime("%Y-%m-%d %H:%M:%S"))}
|
||||
period = int(np.median(np.diff(ts))) if len(ts) > 1 else 0
|
||||
|
||||
rows = []
|
||||
for klc in getattr(chan_htf, "klc_list", []):
|
||||
if klc.fx not in (Chan_FX_TYPE.TOP, Chan_FX_TYPE.BOTTOM):
|
||||
continue
|
||||
if klc.next is None or klc.next.end_klu is None:
|
||||
continue
|
||||
e_key, c_key = str(klc.end_time), str(klc.next.end_klu.time)
|
||||
if e_key not in idx_of or c_key not in idx_of:
|
||||
continue
|
||||
fx_idx, confirm_idx = idx_of[e_key], idx_of[c_key]
|
||||
if confirm_idx <= fx_idx:
|
||||
continue
|
||||
d = 1 if klc.fx == Chan_FX_TYPE.BOTTOM else -1
|
||||
rows.append({
|
||||
"confirm_ts": int(ts[confirm_idx]) + period,
|
||||
"fx_ts": int(ts[fx_idx]),
|
||||
"direction": d,
|
||||
"price": float(klc.low if d == 1 else klc.high),
|
||||
})
|
||||
out = pd.DataFrame(rows)
|
||||
if out.empty:
|
||||
return pd.DataFrame(columns=["confirm_ts", "fx_ts", "direction", "price"])
|
||||
return out.sort_values("confirm_ts").reset_index(drop=True)
|
||||
|
||||
|
||||
def attach_htf_agree(sig: pd.DataFrame, df_ltf: pd.DataFrame, tl: pd.DataFrame) -> pd.DataFrame:
|
||||
"""给每个小级别信号挂上「入场时刻之前最近的大级别分型」是否同向。
|
||||
|
||||
产出 htf_dir(+1 底 / -1 顶)与 htf_agree(1 同向 / 0 反向 / NaN 无可用分型)。
|
||||
"""
|
||||
out = sig.copy()
|
||||
if sig.empty or tl.empty:
|
||||
out["htf_dir"] = np.nan
|
||||
out["htf_agree"] = np.nan
|
||||
return out
|
||||
|
||||
ts_ltf = timestamps_ms(df_ltf)
|
||||
entry_ts = ts_ltf[out["entry_idx"].to_numpy().astype(int)]
|
||||
k = np.searchsorted(tl["confirm_ts"].to_numpy(), entry_ts, side="right") - 1
|
||||
valid = k >= 0
|
||||
k_safe = np.clip(k, 0, len(tl) - 1)
|
||||
|
||||
fx_dir = tl["direction"].to_numpy()[k_safe].astype(float)
|
||||
out["htf_dir"] = np.where(valid, fx_dir, np.nan)
|
||||
out["htf_agree"] = np.where(
|
||||
valid, (fx_dir == out["direction"].to_numpy()).astype(float), np.nan
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def attach_zone_ladder(sig: pd.DataFrame, zones: pd.DataFrame) -> pd.DataFrame:
|
||||
"""按信号方向取该中枢的阶梯标记:买看 z_above、卖看 z_below。
|
||||
|
||||
zone_i 是 find_fast_bsp3 内 enumerate 出的位置序号,故用 iloc 定位。
|
||||
"""
|
||||
out = sig.copy()
|
||||
if sig.empty:
|
||||
out["ladder_ok"] = pd.Series(dtype=bool)
|
||||
return out
|
||||
z = zones if "z_above" in zones.columns else add_zone_ladder(zones)
|
||||
above = z["z_above"].to_numpy()
|
||||
below = z["z_below"].to_numpy()
|
||||
zi = out["zone_i"].to_numpy().astype(int)
|
||||
ok = np.where(out["direction"].to_numpy() == 1, above[zi], below[zi])
|
||||
out["ladder_ok"] = ok.astype(bool)
|
||||
return out
|
||||
|
||||
|
||||
def find_fast_bsp3(
|
||||
df: pd.DataFrame,
|
||||
zones: pd.DataFrame,
|
||||
scan: int = 200,
|
||||
pullback_win: int = 30,
|
||||
tol: float = -1.0,
|
||||
max_per_zone: int = 1,
|
||||
diag: dict | None = None,
|
||||
require_touch: bool = False,
|
||||
) -> pd.DataFrame:
|
||||
"""扫描每个中枢,找突破后回抽不回中枢的入场点。
|
||||
|
||||
zones 需含 zg / zd / available_ts,且 available_ts 已是可用时刻。
|
||||
max_per_zone > 1 时,同一中枢在首次入场后继续往后找二次、三次突破回抽,
|
||||
用来检验「趋势里同一中枢反复给机会」是否值得做。
|
||||
|
||||
tol 是「算作回抽中」的边界容差。require_touch=False 时它不再是入场门槛,
|
||||
仅决定哪些K线被视为回抽中而跳过转强判定,故 tol 越大入场越晚。
|
||||
默认负值 = 完全禁用该跳过,突破后每根都检查转强,滞后压到 2.2 根。
|
||||
step34 实测滞后与收益严格单调:9.9根 PF1.88 / 5.8根 2.37 / 2.2根 2.86。
|
||||
|
||||
返回列:
|
||||
entry_idx 实时可下单的K线
|
||||
direction +1 三买 / -1 三卖
|
||||
bo_idx 突破根
|
||||
pb_idx 回抽极值根
|
||||
lag entry_idx - bo_idx
|
||||
depth 回抽深度(相对中枢边界,负值表示曾插入中枢)
|
||||
occ 这是该中枢的第几次入场
|
||||
"""
|
||||
if zones.empty:
|
||||
return pd.DataFrame()
|
||||
|
||||
ts = df["timestamp"].to_numpy()
|
||||
close = df["close"].to_numpy(dtype=float)
|
||||
high = df["high"].to_numpy(dtype=float)
|
||||
low = df["low"].to_numpy(dtype=float)
|
||||
n = len(df)
|
||||
rows = []
|
||||
|
||||
def note(key: str) -> None:
|
||||
if diag is not None:
|
||||
diag[key] = diag.get(key, 0) + 1
|
||||
|
||||
for zone_i, (_, z) in enumerate(zones.iterrows()):
|
||||
note("中枢总数")
|
||||
zg, zd = float(z["zg"]), float(z["zd"])
|
||||
if zg <= zd:
|
||||
note("×无效中枢")
|
||||
continue
|
||||
start = int(np.searchsorted(ts, z["available_ts"], side="left"))
|
||||
if start >= n - 2:
|
||||
note("×中枢太靠后")
|
||||
continue
|
||||
# 允许多次入场时按比例放宽扫描窗口,否则后几次机会会被窗口截断
|
||||
scan_end = min(start + scan * max_per_zone, n)
|
||||
cursor = start
|
||||
|
||||
for occ in range(1, max_per_zone + 1):
|
||||
if cursor >= n - 2:
|
||||
break
|
||||
# 第一步:找突破。要求突破前确实待在中枢内,避免把远处的价格当突破。
|
||||
was_inside = False
|
||||
bo_idx, d = None, 0
|
||||
for j in range(cursor, scan_end):
|
||||
c = close[j]
|
||||
if zd <= c <= zg:
|
||||
was_inside = True
|
||||
continue
|
||||
if not was_inside:
|
||||
continue
|
||||
bo_idx, d = j, (1 if c > zg else -1)
|
||||
break
|
||||
if bo_idx is None:
|
||||
if occ == 1:
|
||||
note("×窗口内未突破")
|
||||
break
|
||||
|
||||
edge = zg if d == 1 else zd
|
||||
# 第二步:突破后监控回抽,回抽不跌回中枢且重新顺势 -> 入场
|
||||
touched = False
|
||||
pb_idx = None
|
||||
pb_ext = None
|
||||
entry_idx = None
|
||||
fell_back = False
|
||||
for j in range(bo_idx + 1, min(bo_idx + pullback_win + 1, n)):
|
||||
# 收盘跌回中枢 -> 突破失效
|
||||
if zd <= close[j] <= zg:
|
||||
fell_back = True
|
||||
break
|
||||
# 回抽触及边界附近(允许 tol 的毛刺)
|
||||
near = (low[j] <= edge * (1 + tol)) if d == 1 else (high[j] >= edge * (1 - tol))
|
||||
if near:
|
||||
touched = True
|
||||
ext = low[j] if d == 1 else high[j]
|
||||
if pb_ext is None or ((ext < pb_ext) if d == 1 else (ext > pb_ext)):
|
||||
pb_ext, pb_idx = ext, j
|
||||
continue
|
||||
# 回抽后重新顺势:收盘创出前一根之上(三买)/ 之下(三卖)
|
||||
# require_touch=False 时不强求回抽碰到中枢边界,
|
||||
# 这样「突破后一去不回头」的强势段也能收进来。
|
||||
if (touched and pb_idx is not None) or not require_touch:
|
||||
go = close[j] > high[j - 1] if d == 1 else close[j] < low[j - 1]
|
||||
if go:
|
||||
entry_idx = j
|
||||
break
|
||||
if entry_idx is None:
|
||||
if occ == 1:
|
||||
note("×突破后跌回中枢" if fell_back
|
||||
else "×回抽未触及边界" if not touched
|
||||
else "×触及边界但未转强")
|
||||
# 这次突破没走成,从突破点之后继续找下一次
|
||||
cursor = bo_idx + 1
|
||||
continue
|
||||
if pb_ext is None:
|
||||
# 未触及边界就转强(require_touch=False):取突破至入场间的实际极值
|
||||
seg = slice(bo_idx + 1, entry_idx + 1)
|
||||
pb_ext = float(low[seg].min() if d == 1 else high[seg].max())
|
||||
pb_idx = int((low[seg].argmin() if d == 1 else high[seg].argmax())
|
||||
+ bo_idx + 1)
|
||||
if occ == 1:
|
||||
note("√成交")
|
||||
|
||||
# 回抽深度:>0 表示未插入中枢,越大表示回抽越浅
|
||||
depth = (pb_ext - zg) / zg if d == 1 else (zd - pb_ext) / zd
|
||||
rows.append({
|
||||
"entry_idx": entry_idx, "direction": d,
|
||||
"bo_idx": bo_idx, "pb_idx": pb_idx,
|
||||
"lag": entry_idx - bo_idx,
|
||||
"depth": depth,
|
||||
"zg": zg, "zd": zd,
|
||||
"width_pct": (zg - zd) / close[bo_idx],
|
||||
"occ": occ,
|
||||
"zone_i": zone_i,
|
||||
})
|
||||
cursor = entry_idx + 1
|
||||
|
||||
out = pd.DataFrame(rows)
|
||||
if out.empty:
|
||||
return out
|
||||
# 相邻中枢可能突破到同一根K线,同一时刻只能有一个仓位,保留最早成型的那个
|
||||
return (out.sort_values(["entry_idx", "occ", "zone_i"])
|
||||
.drop_duplicates("entry_idx", keep="first")
|
||||
.reset_index(drop=True))
|
||||
@@ -1,6 +1,6 @@
|
||||
from decimal import Decimal
|
||||
import ChanKLC
|
||||
from ChanEnum import Chan_BI_DIR
|
||||
import chanlun.core.ChanKLC as ChanKLC
|
||||
from chanlun.core.ChanEnum import Chan_BI_DIR
|
||||
class ChanBI():
|
||||
def __init__(self, klc: ChanKLC, index, ddir=Chan_BI_DIR.UP):
|
||||
self.start_klc = klc
|
||||
@@ -15,10 +15,12 @@ class ChanBI():
|
||||
self.sure_time = None
|
||||
self.klc_list = []
|
||||
self.klc_list.append(klc)
|
||||
self._klc_idx = {klc.index}
|
||||
self.end_time = klc.end_time
|
||||
self.start_time = klc.start_time
|
||||
self.macd_hist = 0
|
||||
self.macd_div = 0
|
||||
self._macd_hist = 0
|
||||
self._macd_div = 0
|
||||
self._macd_dirty = False
|
||||
self.seg = None
|
||||
self.height = 0
|
||||
self.width = 0
|
||||
@@ -33,26 +35,57 @@ class ChanBI():
|
||||
def set_seg(self, seg):
|
||||
self.seg = seg
|
||||
self.seg_index = len(seg.bi_list)-1
|
||||
# macd_hist / macd_div 改为惰性。原来 add_klc 每加一根 KLC 就把整笔的
|
||||
# 所有 KLU 重新累加一遍,是 O(k²);而这两个值只有背驰判定(bsp.py)在读,
|
||||
# lean 模式下 bsp 根本不算,等于全程白算。这里只标脏,取值时才算。
|
||||
# 语义不变:klc_list 只增不减(set_start_klc 会重置并同时清脏),
|
||||
# dir 在 klc 累加期间固定,所以延后到读取时算与逐次重算结果相同。
|
||||
@property
|
||||
def macd_hist(self):
|
||||
if self._macd_dirty:
|
||||
self.cal_macdhist()
|
||||
return self._macd_hist
|
||||
|
||||
@macd_hist.setter
|
||||
def macd_hist(self, v):
|
||||
self._macd_hist = v
|
||||
self._macd_dirty = False
|
||||
|
||||
@property
|
||||
def macd_div(self):
|
||||
self.cal_macd_div()
|
||||
return self._macd_div
|
||||
|
||||
@macd_div.setter
|
||||
def macd_div(self, v):
|
||||
self._macd_div = v
|
||||
|
||||
def set_macdhist(self, macd_hist):
|
||||
self.macd_hist = macd_hist
|
||||
def set_macd_div(self, macd_div):
|
||||
self.macd_div = macd_div
|
||||
def cal_macd_div(self):
|
||||
self.macd_div = 0.0
|
||||
self._macd_div = 0.0
|
||||
if self.pre and self.pre.pre:
|
||||
if self.pre.pre.macd_hist == 0:
|
||||
self.macd_div = 0.0
|
||||
self._macd_div = 0.0
|
||||
else:
|
||||
self.macd_div = self.macd_hist / self.pre.pre.macd_hist
|
||||
self._macd_div = self.macd_hist / self.pre.pre.macd_hist
|
||||
#print(self.start_time, self.end_time, self.macd_hist, self.pre.pre.macd_hist, self.macd_div)
|
||||
def cal_macdhist(self):
|
||||
self.macd_hist = 0
|
||||
self._macd_dirty = False
|
||||
self._macd_hist = 0
|
||||
up = self.dir == Chan_BI_DIR.UP
|
||||
acc = 0
|
||||
for klc in self.klc_list:
|
||||
for klu in klc.klu_list:
|
||||
if self.dir == Chan_BI_DIR.UP and klu.macdhist > 0:
|
||||
self.macd_hist += klu.macdhist
|
||||
if self.dir == Chan_BI_DIR.DOWN and klu.macdhist < 0:
|
||||
self.macd_hist -= klu.macdhist
|
||||
h = klu.macdhist
|
||||
if up:
|
||||
if h > 0:
|
||||
acc += h
|
||||
elif h < 0:
|
||||
acc -= h
|
||||
self._macd_hist = acc
|
||||
def check_bi_zs_overlap(self):
|
||||
if self.next and self.next.next:
|
||||
if self.dir == Chan_BI_DIR.UP:
|
||||
@@ -95,6 +128,10 @@ class ChanBI():
|
||||
self.start_klc = klc
|
||||
self.klc_list = []
|
||||
self.klc_list.append(klc)
|
||||
# klc_list 被整个换掉,去重集合与惰性缓存都要跟着重置,
|
||||
# 否则后续 add_klc 会以为旧下标还在里面而漏加
|
||||
self._klc_idx = {klc.index}
|
||||
self._macd_dirty = True
|
||||
self.high = klc.high
|
||||
self.low = klc.low
|
||||
self.dir = ddir
|
||||
@@ -103,20 +140,14 @@ class ChanBI():
|
||||
def set_next(self, bi):
|
||||
self.next = bi
|
||||
def add_klc(self, klc):
|
||||
added = False
|
||||
if len(self.klc_list) > 0:
|
||||
for index in range(0, len(self.klc_list)):
|
||||
if self.klc_list[index].index == klc.index:
|
||||
added = True
|
||||
break
|
||||
if not added:
|
||||
# 去重原本是对 klc_list 线性扫描,配合下面每次全量重算的 macdhist,
|
||||
# 让「往一笔里加 k 根 KLC」变成 O(k²)。改用下标集合,O(1)。
|
||||
if klc.index not in self._klc_idx:
|
||||
self._klc_idx.add(klc.index)
|
||||
self.klc_list.append(klc)
|
||||
#print(self.start_time, klc.start_time)
|
||||
#print(klc.end_time, klc.index)
|
||||
self.end_klc = klc
|
||||
self.end_time = klc.klu_list[-1].time
|
||||
self.cal_macdhist()
|
||||
self.cal_macd_div()
|
||||
self._macd_dirty = True
|
||||
def append_klc_list(self, klc_list):
|
||||
self.klc_list.append(klc_list)
|
||||
def get_decimal(self, value):
|
||||
@@ -1,5 +1,5 @@
|
||||
from ChanEnum import Chan_ZS_DIR, Chan_ZS_TYPE, Chan_BI_DIR
|
||||
import ChanBI
|
||||
from chanlun.core.ChanEnum import Chan_ZS_DIR, Chan_ZS_TYPE, Chan_BI_DIR
|
||||
import chanlun.core.ChanBI as ChanBI
|
||||
# 中枢
|
||||
class ChanBIZS():
|
||||
def __init__(self, start_bi: ChanBI, index, ddir: Chan_ZS_DIR):
|
||||
@@ -1,5 +1,5 @@
|
||||
import ChanBI
|
||||
from ChanEnum import Chan_BSP_TYPE, Chan_BSP_DIR
|
||||
import chanlun.core.ChanBI as ChanBI
|
||||
from chanlun.core.ChanEnum import Chan_BSP_TYPE, Chan_BSP_DIR
|
||||
|
||||
class ChanBSP():
|
||||
def __init__(self, bi: ChanBI, index, type: Chan_BSP_TYPE, ddir: Chan_BSP_DIR, sure_time, zs_count, zs, seg):
|
||||
@@ -281,6 +281,10 @@ class Chan_BSP_TYPE(Enum):
|
||||
S1 = auto()
|
||||
S2 = auto()
|
||||
S3 = auto()
|
||||
# 第四类:三类买卖点的低滞后变体,几何位置同 B3/S3,但不等笔确认。
|
||||
# 见 chanlun/analysis/fast_bsp.py
|
||||
B4 = auto()
|
||||
S4 = auto()
|
||||
NONE = auto()
|
||||
"""
|
||||
class Chan_BSP_TYPE(Enum):
|
||||
@@ -0,0 +1,40 @@
|
||||
from chanlun.core.ChanEnum import Chan_BSP_DIR, Chan_BSP_TYPE
|
||||
|
||||
|
||||
class ChanFastBSP():
|
||||
"""第四类买卖点(B4/S4)。
|
||||
|
||||
与 ChanBSP 的区别在于它不挂在笔上:fast_bsp 刻意不等笔确认,入场点是一根具体的
|
||||
K线而非一笔的端点,所以时间与价格直接取自 K 线,没有 bi / klc 可依附。
|
||||
|
||||
htf_agree 与 ladder_ok 是两个独立的过滤标志,不在这里合成——上层(图表或策略)
|
||||
自己决定要不要用、怎么组合。
|
||||
"""
|
||||
|
||||
def __init__(self, time, price, ddir, entry_idx, bo_time=None, pb_time=None,
|
||||
lag=0, depth=0.0, zg=None, zd=None, occ=1,
|
||||
htf_dir=None, htf_agree=None, ladder_ok=None):
|
||||
self.time = time
|
||||
self.price = float(price)
|
||||
self.dir = ddir
|
||||
self.type = Chan_BSP_TYPE.B4 if ddir == Chan_BSP_DIR.BUY else Chan_BSP_TYPE.S4
|
||||
self.entry_idx = int(entry_idx)
|
||||
self.bo_time = bo_time
|
||||
self.pb_time = pb_time
|
||||
self.lag = int(lag)
|
||||
self.depth = float(depth)
|
||||
self.zg = float(zg) if zg is not None else None
|
||||
self.zd = float(zd) if zd is not None else None
|
||||
self.occ = int(occ)
|
||||
self.htf_dir = htf_dir
|
||||
self.htf_agree = htf_agree
|
||||
self.ladder_ok = ladder_ok
|
||||
# 入场即成立,没有「等待确认」这个状态;留此字段是为了与 ChanBSP 的序列化对齐
|
||||
self.is_sure = True
|
||||
self.start_time = time
|
||||
self.end_time = time
|
||||
self.sure_time = time
|
||||
|
||||
def __repr__(self):
|
||||
name = str(self.type).replace('Chan_BSP_TYPE.', '')
|
||||
return f"<ChanFastBSP {name} {self.time} {self.price} lag={self.lag}>"
|
||||
@@ -1,12 +1,12 @@
|
||||
import copy
|
||||
from typing import Dict, Optional
|
||||
|
||||
from ChanEnum import Chan_FX_TYPE, Chan_KLINE_DIR, Chan_BI_DIR, Chan_KLC_FX
|
||||
from ChanEnum import Chan_K_DIR, Chan_MACD_STATE, Chan_PRICE_TREND, Chan_EMA_POS
|
||||
from ChanEnum import Chan_EMA_SEMANTIC, Chan_BSP_TYPE, Chan_KLC_STATE, Chan_FX
|
||||
import ChanKLU
|
||||
import ChanCTime
|
||||
import Chan_FX_Box
|
||||
from chanlun.core.ChanEnum import Chan_FX_TYPE, Chan_KLINE_DIR, Chan_BI_DIR, Chan_KLC_FX
|
||||
from chanlun.core.ChanEnum import Chan_K_DIR, Chan_MACD_STATE, Chan_PRICE_TREND, Chan_EMA_POS
|
||||
from chanlun.core.ChanEnum import Chan_EMA_SEMANTIC, Chan_BSP_TYPE, Chan_KLC_STATE, Chan_FX
|
||||
import chanlun.core.ChanKLU as ChanKLU
|
||||
import chanlun.core.ChanCTime as ChanCTime
|
||||
import chanlun.core.Chan_FX_Box as Chan_FX_Box
|
||||
# 根据结合律合并K线后的K线
|
||||
class ChanKLC():
|
||||
def __init__(self, klu: ChanKLU, index, ddir=Chan_KLINE_DIR.UP):
|
||||
@@ -63,10 +63,11 @@ class ChanKLC():
|
||||
self.bsp = False
|
||||
self.bsp_type = Chan_BSP_TYPE.NONE
|
||||
# EMA状态字典:key为EMA名称,value为 {'pos': Chan_EMA_POS, 'semantic': Chan_EMA_SEMANTIC}
|
||||
self.ema_status = {}
|
||||
self._ema_status = {}
|
||||
self._ema_status_dirty = False
|
||||
# 向后兼容:保留 ema52_status 和 ema52_pos
|
||||
self.ema52_status = 0
|
||||
self.ema52_pos = Chan_EMA_POS.UNKNOWN
|
||||
self._ema52_status = 0
|
||||
self._ema52_pos = Chan_EMA_POS.UNKNOWN
|
||||
self.bb2633upper = klu.bb2633upper
|
||||
self.bb2633lower = klu.bb2633lower
|
||||
self.bb2633middle = klu.bb2633middle
|
||||
@@ -283,21 +284,44 @@ class ChanKLC():
|
||||
'ema156': self.ema156,
|
||||
'ema208': self.ema208,
|
||||
}
|
||||
self.ema_status = {}
|
||||
self._ema_status_dirty = False
|
||||
self._ema_status = {}
|
||||
for name, value in ema_configs.items():
|
||||
# 按 EMA 值的百分比自动计算阈值
|
||||
threshold = abs(value) * self.threshold_pct if value and self.threshold_pct > 0 else 0
|
||||
pos = ChanKLC.cal_ema_pos(self.high, self.low, self.close, value, threshold)
|
||||
semantic = ChanKLC.cal_ema_semantic(pos, self.dir, self.ema_dir)
|
||||
self.ema_status[name] = {
|
||||
self._ema_status[name] = {
|
||||
'pos': pos,
|
||||
'semantic': semantic,
|
||||
'value': value,
|
||||
'threshold': threshold,
|
||||
}
|
||||
# 向后兼容
|
||||
self.ema52_pos = self.ema_status['ema52']['pos']
|
||||
self.ema52_status = ChanKLC.semantic_to_int(self.ema_status['ema52']['semantic'])
|
||||
self._ema52_pos = self._ema_status['ema52']['pos']
|
||||
self._ema52_status = ChanKLC.semantic_to_int(self._ema_status['ema52']['semantic'])
|
||||
|
||||
# 以下三个改成惰性求值。原来 set_end_klu 每次合并 KLU 都会立刻重算一遍,
|
||||
# 实测占 TF_DF 构建的约 25%,而全仓(含前端)没有任何地方读取它的产出。
|
||||
# 保留属性形式是为了任何外部读取仍拿到正确值,只是推迟到真被读时才算。
|
||||
@property
|
||||
def ema_status(self):
|
||||
if self._ema_status_dirty:
|
||||
self.cal_all_ema_status()
|
||||
return self._ema_status
|
||||
|
||||
@property
|
||||
def ema52_pos(self):
|
||||
if self._ema_status_dirty:
|
||||
self.cal_all_ema_status()
|
||||
return self._ema52_pos
|
||||
|
||||
@property
|
||||
def ema52_status(self):
|
||||
if self._ema_status_dirty:
|
||||
self.cal_all_ema_status()
|
||||
return self._ema52_status
|
||||
|
||||
def get_ema_pos(self, ema_name):
|
||||
"""获取指定EMA的客观位置,如 klc.get_ema_pos('ema24')"""
|
||||
if ema_name in self.ema_status:
|
||||
@@ -372,14 +396,14 @@ class ChanKLC():
|
||||
end_time = self.next.end_time
|
||||
high = self.high
|
||||
low = self.pre.low if self.pre.low < self.next.low else self.next.low
|
||||
if self.next.close < self.pre.low:
|
||||
if self.next.close < self.pre.low or True:
|
||||
display = True
|
||||
elif self.fx == Chan_FX_TYPE.BOTTOM:
|
||||
start_time = self.pre.end_time
|
||||
end_time = self.next.end_time
|
||||
high = self.pre.high if self.pre.high > self.next.high else self.next.high
|
||||
low = self.low
|
||||
if self.next.close > self.pre.high:
|
||||
if self.next.close > self.pre.high or True:
|
||||
display = True
|
||||
if high > 0 and self.next.end_time and display:
|
||||
#print(start_time, end_time, high, low)
|
||||
@@ -448,7 +472,7 @@ class ChanKLC():
|
||||
klu.set_klc(self)
|
||||
self.klc_dir = Chan_KLINE_DIR.UP if self.close > self.open else Chan_KLINE_DIR.DOWN
|
||||
self.cal_indicators()
|
||||
self.cal_all_ema_status()
|
||||
self._ema_status_dirty = True
|
||||
if self.open > self.high:
|
||||
self.open = self.high
|
||||
if self.close > self.high:
|
||||
@@ -1,4 +1,4 @@
|
||||
from ChanEnum import Chan_FX_TYPE, Chan_KLU_TYPE, Chan_K_DIR, Chan_MACD_STATE, Chan_MACDHIST_STATE, Chan_PRICE_TREND, Chan_KLU_PATTERN, Chan_KLC_FX
|
||||
from chanlun.core.ChanEnum import Chan_FX_TYPE, Chan_KLU_TYPE, Chan_K_DIR, Chan_MACD_STATE, Chan_MACDHIST_STATE, Chan_PRICE_TREND, Chan_KLU_PATTERN, Chan_KLC_FX
|
||||
class ChanKLU:
|
||||
def __init__(self, time, open, high, low, close, volume):
|
||||
# _time, _close, _open, _high, _low, _extra_info={}
|
||||
@@ -96,7 +96,6 @@ class ChanKLU:
|
||||
self.trend = trend
|
||||
def set_separate_div(self, separate_div):
|
||||
self.separate_div = separate_div
|
||||
bb2633_status = self.check_bb2633()
|
||||
if self.klc and self.klc.pre and self.klc.next:
|
||||
fx = self.check_fx_dir(self.klc.pre, self.klc.next)
|
||||
if fx == Chan_FX_TYPE.TOP:
|
||||
@@ -109,17 +108,6 @@ class ChanKLU:
|
||||
self.separate_div = separate_div
|
||||
else:
|
||||
self.separate_div = 0
|
||||
if bb2633_status == 0:
|
||||
self.separate_div = 0
|
||||
def check_bb2633(self, threadhold=300):
|
||||
#print(self.time, self.high, self.bb2633upper, self.low, self.bb2633lower)
|
||||
if abs(self.high - self.bb2633upper) < threadhold:
|
||||
#print(self.time, self.high, self.bb2633upper)
|
||||
return 1
|
||||
if abs(self.low - self.bb2633lower) < threadhold:
|
||||
#print(self.time, self.low, self.bb2633lower)
|
||||
return -1
|
||||
return 0
|
||||
def check_fx_dir(self, pre, next):
|
||||
fx = Chan_FX_TYPE.UNKNOWN
|
||||
if pre.klc_fx_type == Chan_KLC_FX.TOP1 or pre.klc_fx_type == Chan_KLC_FX.TOP2 or next.klc_fx_type == Chan_KLC_FX.TOP1 or next.klc_fx_type == Chan_KLC_FX.TOP2 or self.klc.klc_fx_type == Chan_KLC_FX.TOP1 or self.klc.klc_fx_type == Chan_KLC_FX.TOP2:
|
||||
@@ -172,27 +160,40 @@ class ChanKLU:
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
# 属性名 ← dataframe 列名。两条赋值路径(逐行 Series / 预取 ndarray)共用这张表,
|
||||
# 免得将来加指标时只改一处、另一处静默漏掉。
|
||||
INDICATOR_FIELDS = (
|
||||
('macd', 'macd'), ('signal', 'macdsignal'), ('macdhist', 'macdhist'),
|
||||
('ema26', 'ema26'), ('ema52', 'ema52'), ('ema24', 'ema24'),
|
||||
('ema104', 'ema104'), ('ema156', 'ema156'), ('ema208', 'ema208'),
|
||||
('ema13', 'ema13'), ('ema7', 'ema7'), ('ema5', 'ema5'),
|
||||
('rsi', 'rsi'), ('volume_ratio', 'volume_ratio'),
|
||||
('bb52upper', 'bb52upper'), ('bb52lower', 'bb52lower'),
|
||||
('bb2633upper', 'bb2633upper'), ('bb2633lower', 'bb2633lower'),
|
||||
('bb2633middle', 'bb2633middle'), ('ma5', 'ma5'),
|
||||
)
|
||||
|
||||
def set_indicators(self, item):
|
||||
self.macd = float(item['macd']) if 'macd' in item and item['macd'] else 0
|
||||
self.signal = float(item['macdsignal']) if 'macdsignal' in item and item['macdsignal'] else 0
|
||||
self.macdhist = float(item['macdhist']) if 'macdhist' in item and item['macdhist'] else 0
|
||||
self.ema26 = float(item['ema26']) if 'ema26' in item and item['ema26'] else 0
|
||||
self.ema52 = float(item['ema52']) if 'ema52' in item and item['ema52'] else 0
|
||||
self.ema24 = float(item['ema24']) if 'ema24' in item and item['ema24'] else 0
|
||||
self.ema104 = float(item['ema104']) if 'ema104' in item and item['ema104'] else 0
|
||||
self.ema156 = float(item['ema156']) if 'ema156' in item and item['ema156'] else 0
|
||||
self.ema208 = float(item['ema208']) if 'ema208' in item and item['ema208'] else 0
|
||||
self.ema13 = float(item['ema13']) if 'ema13' in item and item['ema13'] else 0
|
||||
self.ema7 = float(item['ema7']) if 'ema7' in item and item['ema7'] else 0
|
||||
self.rsi = float(item['rsi']) if 'rsi' in item and item['rsi'] else 0
|
||||
self.volume_ratio = float(item['volume_ratio']) if 'volume_ratio' in item and item['volume_ratio'] else 0
|
||||
self.bb52upper = float(item['bb52upper']) if 'bb52upper' in item and item['bb52upper'] else 0
|
||||
self.bb52lower = float(item['bb52lower']) if 'bb52lower' in item and item['bb52lower'] else 0
|
||||
self.bb2633upper = float(item['bb2633upper']) if 'bb2633upper' in item and item['bb2633upper'] else 0
|
||||
self.bb2633lower = float(item['bb2633lower']) if 'bb2633lower' in item and item['bb2633lower'] else 0
|
||||
self.bb2633middle = float(item['bb2633middle']) if 'bb2633middle' in item and item['bb2633middle'] else 0
|
||||
self.ma5 = float(item['ma5']) if 'ma5' in item and item['ma5'] else 0
|
||||
self.ema5 = float(item['ema5']) if 'ema5' in item and item['ema5'] else 0
|
||||
"""单根赋值。增量追加时每次只有一根,走这条即可。
|
||||
|
||||
原写法是 `float(item[c]) if c in item and item[c] else 0`。其中的真值判断
|
||||
是空转:值为 0.0 时 float(0.0) 仍是 0,值为 NaN 时 NaN 为真值、照样透传。
|
||||
唯一起作用的是「列不存在则填 0」,所以这里只保留那一层。
|
||||
"""
|
||||
for attr, col in self.INDICATOR_FIELDS:
|
||||
v = item[col] if col in item else 0
|
||||
setattr(self, attr, float(v) if v else 0)
|
||||
|
||||
def set_indicators_from(self, cols, i):
|
||||
"""从预取的 {列名: ndarray} 按下标赋值,语义与 set_indicators 相同。
|
||||
|
||||
全量构建时用这条:避免每根 `df.iloc[i]` 构造一个 Series,再在其上做
|
||||
几十次逐键查找——那是 TF_DF 构建 96% 的耗时所在。
|
||||
"""
|
||||
for attr, col in self.INDICATOR_FIELDS:
|
||||
arr = cols.get(col)
|
||||
v = arr[i] if arr is not None else 0
|
||||
setattr(self, attr, float(v) if v else 0)
|
||||
def cal_macd_state(self):
|
||||
# 按定义精简实现:优先级 CROSS0 > 位置(HIGH/HE/RETURN_ZERO) > NEAR0 > UNKNOWN
|
||||
# 首条或缺前一根
|
||||
@@ -1,9 +1,9 @@
|
||||
import copy
|
||||
from typing import Dict, Optional
|
||||
|
||||
from ChanEnum import Chan_FX_TYPE, Chan_KLINE_DIR, Chan_BI_DIR
|
||||
import ChanKLU
|
||||
from ChanBI import ChanBI
|
||||
from chanlun.core.ChanEnum import Chan_FX_TYPE, Chan_KLINE_DIR, Chan_BI_DIR
|
||||
import chanlun.core.ChanKLU as ChanKLU
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
|
||||
class ChanSBI():
|
||||
def __init__(self, start_bi: ChanBI, index, dir=Chan_BI_DIR.UP):
|
||||
@@ -1,10 +1,10 @@
|
||||
import copy
|
||||
from typing import Dict, Optional
|
||||
|
||||
from ChanEnum import Chan_FX_TYPE, Chan_KLINE_DIR, Chan_SEG_DIR, Chan_BI_DIR, Chan_ZS_DIR
|
||||
import ChanCTime
|
||||
from ChanBI import ChanBI
|
||||
from ChanBIZS import ChanBIZS
|
||||
from chanlun.core.ChanEnum import Chan_FX_TYPE, Chan_KLINE_DIR, Chan_SEG_DIR, Chan_BI_DIR, Chan_ZS_DIR
|
||||
import chanlun.core.ChanCTime as ChanCTime
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
from chanlun.core.ChanBIZS import ChanBIZS
|
||||
class ChanSEG():
|
||||
def __init__(self, start_bi: ChanBI, index, ddir=Chan_SEG_DIR.UP, pre_end_bi: ChanBI = None):
|
||||
self.start_bi = start_bi
|
||||
@@ -43,6 +43,29 @@ class ChanSEG():
|
||||
self.macd_hist = macd_hist
|
||||
def set_macd_div(self, macd_div):
|
||||
self.macd_div = macd_div
|
||||
def cal_macdhist(self):
|
||||
# 线段面积 = 同向笔 MACD 柱面积之和(与笔面积口径一致)
|
||||
acc = 0.0
|
||||
seg_dir_name = getattr(self.dir, 'name', None)
|
||||
for bi in self.bi_list:
|
||||
if bi is None:
|
||||
continue
|
||||
if getattr(getattr(bi, 'dir', None), 'name', None) != seg_dir_name:
|
||||
continue
|
||||
acc += float(bi.macd_hist or 0)
|
||||
self.macd_hist = acc
|
||||
return acc
|
||||
def cal_macd_div(self):
|
||||
# 与前一个同向线段比面积:seg.pre 是反向邻段,pre.pre 才是同向
|
||||
self.macd_div = 0.0
|
||||
prev = self.pre.pre if self.pre and self.pre.pre else None
|
||||
if prev is None:
|
||||
return 0.0
|
||||
prev_hist = float(prev.macd_hist or 0)
|
||||
if prev_hist == 0:
|
||||
return 0.0
|
||||
self.macd_div = float(self.macd_hist or 0) / prev_hist
|
||||
return self.macd_div
|
||||
def set_end_bi(self, bi: ChanBI, sure_bi: ChanBI):
|
||||
self.end_bi = bi
|
||||
if bi and bi.is_sure:
|
||||
@@ -96,7 +119,10 @@ class ChanSEG():
|
||||
if self.dir == Chan_SEG_DIR.UP:
|
||||
for index in range(1, len(self.bi_list)):
|
||||
bi = self.bi_list[index]
|
||||
#print(bi.end_time, bi.next,"UP SEG BI ZS Index")
|
||||
if bi.next == None or bi.next.next == None:
|
||||
if last_zs and (bi.low > last_zs.zg or bi.high < last_zs.zd):
|
||||
last_zs.set_end_bi(last_zs.bi_list[-1], last_zs.bi_list[-1].sure_time)
|
||||
continue
|
||||
bi2 = bi.next
|
||||
bi3 = bi.next.next
|
||||
@@ -118,6 +144,7 @@ class ChanSEG():
|
||||
else:
|
||||
if bi.index > last_zs.bi_list[-1].index and bi.dir == Chan_BI_DIR.DOWN and bi.is_sure:
|
||||
if bi.low > last_zs.zg or bi.high < last_zs.zd:
|
||||
#print(bi.end_time, "UP SEG BI ZS End")
|
||||
last_zs.set_end_bi(last_zs.bi_list[-1], last_zs.bi_list[-1].sure_time)
|
||||
if bi3.is_sure and bi3.index <= self.bi_list[-1].index and bi.check_bi_zs_overlap() and bi.dir == Chan_BI_DIR.DOWN:
|
||||
zg = min(bi.high, bi2.high, bi3.high)
|
||||
@@ -143,6 +170,8 @@ class ChanSEG():
|
||||
for index in range(1, len(self.bi_list)):
|
||||
bi = self.bi_list[index]
|
||||
if bi.next == None or bi.next.next == None:
|
||||
if last_zs and (bi.low > last_zs.zg or bi.high < last_zs.zd):
|
||||
last_zs.set_end_bi(last_zs.bi_list[-1], last_zs.bi_list[-1].sure_time)
|
||||
continue
|
||||
bi2 = bi.next
|
||||
bi3 = bi.next.next
|
||||
@@ -1,8 +1,9 @@
|
||||
from typing import Dict, Optional
|
||||
|
||||
import ChanKLC, ChanSEG
|
||||
import ChanCTime
|
||||
from ChanEnum import Chan_ZS_DIR
|
||||
import chanlun.core.ChanKLC as ChanKLC
|
||||
import chanlun.core.ChanSEG as ChanSEG
|
||||
import chanlun.core.ChanCTime as ChanCTime
|
||||
from chanlun.core.ChanEnum import Chan_ZS_DIR
|
||||
# 中枢
|
||||
class ChanZS():
|
||||
def __init__(self, start_seg: ChanSEG, index, ddir: Chan_ZS_DIR):
|
||||
@@ -1,8 +1,8 @@
|
||||
from ChanKLU import ChanKLU
|
||||
from ChanEnum import Chan_MACD_STATE, Chan_MACDSEG_DIR, Chan_MACDHISTSET_DIR, Chan_MACDUNITTF_DIR, Chan_MACDUNITTF_TYPE
|
||||
from ChanMACDSeg import ChanMACDSeg
|
||||
from ChanMACDUnitTF import ChanMACDUnitTF
|
||||
from ChanMACDHistSet import ChanMACDHistSet
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
from chanlun.core.ChanEnum import Chan_MACD_STATE, Chan_MACDSEG_DIR, Chan_MACDHISTSET_DIR, Chan_MACDUNITTF_DIR, Chan_MACDUNITTF_TYPE
|
||||
from chanlun.indicators.ChanMACDSeg import ChanMACDSeg
|
||||
from chanlun.indicators.ChanMACDUnitTF import ChanMACDUnitTF
|
||||
from chanlun.indicators.ChanMACDHistSet import ChanMACDHistSet
|
||||
|
||||
class ChanMACD():
|
||||
def __init__(self, klu_list: list[ChanKLU]):
|
||||
@@ -31,7 +31,7 @@ class ChanMACD():
|
||||
if self.klu_list:
|
||||
for klu in self.klu_list:
|
||||
hist = klu.macdhist
|
||||
singal = False
|
||||
signal = False
|
||||
if klu.pre and klu.next:
|
||||
if klu.signal > 0:
|
||||
signal = klu.pre.signal > klu.signal and klu.next.signal < klu.signal
|
||||
@@ -1,4 +1,4 @@
|
||||
from ChanEnum import Chan_MACDHISTSET_DIR, Chan_MACDUNITTF_DIV, Chan_MACD_STATE
|
||||
from chanlun.core.ChanEnum import Chan_MACDHISTSET_DIR, Chan_MACDUNITTF_DIV, Chan_MACD_STATE
|
||||
|
||||
class ChanMACDHistSet():
|
||||
def __init__(self, index, start_time, start_klu, pre_histset, dir):
|
||||
@@ -1,4 +1,4 @@
|
||||
from ChanEnum import Chan_MACDSEG_DIR
|
||||
from chanlun.core.ChanEnum import Chan_MACDSEG_DIR
|
||||
|
||||
|
||||
class ChanMACDSeg():
|
||||
@@ -1,4 +1,4 @@
|
||||
from ChanEnum import Chan_MACD_STATE, Chan_MACDUNITTF_DIR, Chan_MACDHISTSET_DIR, Chan_MACDUNITTF_DIV, Chan_MACDUNITTF_TYPE
|
||||
from chanlun.core.ChanEnum import Chan_MACD_STATE, Chan_MACDUNITTF_DIR, Chan_MACDHISTSET_DIR, Chan_MACDUNITTF_DIV, Chan_MACDUNITTF_TYPE
|
||||
|
||||
|
||||
class ChanMACDUnitTF():
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Drop-in replacement for the `talib.abstract` calls this project makes.
|
||||
|
||||
Same call signatures, same column names, same NaN warm-up lengths, so call
|
||||
sites only change their import line.
|
||||
|
||||
Only what the codebase actually uses is implemented: SMA, MA, EMA, RSI, ATR,
|
||||
MACD, BBANDS. Numerical agreement with TA-Lib is enforced by
|
||||
`chanlun/tests/test_ta_compat.py`, which skips when talib is absent.
|
||||
|
||||
The warm-up conventions below are TA-Lib's, not the textbook ones, and they
|
||||
differ between functions — getting them wrong shifts every downstream Chan
|
||||
structure by a bar:
|
||||
|
||||
SMA/BBANDS first value at index period-1
|
||||
EMA seeded with the SMA of the first `period` values, at index period-1
|
||||
RSI/ATR Wilder smoothing (alpha = 1/period), first value at index period
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
__all__ = ["SMA", "MA", "EMA", "RSI", "ATR", "MACD", "BBANDS"]
|
||||
|
||||
|
||||
def _series(data, price: str = "close") -> pd.Series:
|
||||
"""Accept the abstract-API shapes: DataFrame, Series, or ndarray."""
|
||||
if isinstance(data, pd.DataFrame):
|
||||
return data[price].astype(float)
|
||||
if isinstance(data, pd.Series):
|
||||
return data.astype(float)
|
||||
return pd.Series(np.asarray(data, dtype=float))
|
||||
|
||||
|
||||
def _recursive(values: np.ndarray, seed: float, start: int, alpha: float, n: int) -> np.ndarray:
|
||||
"""out[start] = seed; out[i] = alpha*values[i] + (1-alpha)*out[i-1].
|
||||
|
||||
Delegates the recursion to pandas' C implementation rather than a Python
|
||||
loop — `research/` runs this over long histories.
|
||||
"""
|
||||
out = np.full(n, np.nan)
|
||||
if start >= n:
|
||||
return out
|
||||
tail = values[start:].astype(float).copy()
|
||||
tail[0] = seed
|
||||
out[start:] = pd.Series(tail).ewm(alpha=alpha, adjust=False).mean().to_numpy()
|
||||
return out
|
||||
|
||||
|
||||
def SMA(data, timeperiod: int = 30, price: str = "close") -> pd.Series:
|
||||
s = _series(data, price)
|
||||
return s.rolling(window=timeperiod, min_periods=timeperiod).mean()
|
||||
|
||||
|
||||
def MA(data, timeperiod: int = 30, matype: int = 0, price: str = "close") -> pd.Series:
|
||||
if matype != 0:
|
||||
raise NotImplementedError(f"MA matype={matype} is not used by this codebase")
|
||||
return SMA(data, timeperiod, price=price)
|
||||
|
||||
|
||||
def _ema(x: np.ndarray, period: int, start: int) -> np.ndarray:
|
||||
"""EMA whose first output lands on `start`, seeded by the SMA of the
|
||||
`period` values ending there.
|
||||
|
||||
`start` is a parameter because MACD needs the fast EMA to begin later than
|
||||
it naturally would; see the note in MACD().
|
||||
"""
|
||||
n = x.size
|
||||
if n <= start or start < period - 1:
|
||||
return np.full(n, np.nan)
|
||||
seed = x[start - period + 1: start + 1].mean()
|
||||
return _recursive(x, seed, start, 2.0 / (period + 1.0), n)
|
||||
|
||||
|
||||
def EMA(data, timeperiod: int = 30, price: str = "close") -> pd.Series:
|
||||
s = _series(data, price)
|
||||
x = s.to_numpy(dtype=float)
|
||||
return pd.Series(_ema(x, timeperiod, timeperiod - 1), index=s.index)
|
||||
|
||||
|
||||
def RSI(data, timeperiod: int = 14, price: str = "close") -> pd.Series:
|
||||
s = _series(data, price)
|
||||
x = s.to_numpy(dtype=float)
|
||||
n = x.size
|
||||
out = np.full(n, np.nan)
|
||||
if n <= timeperiod:
|
||||
return pd.Series(out, index=s.index)
|
||||
|
||||
delta = np.diff(x)
|
||||
gain = np.where(delta > 0.0, delta, 0.0)
|
||||
loss = np.where(delta < 0.0, -delta, 0.0)
|
||||
|
||||
# delta[k] corresponds to bar k+1, so the first `timeperiod` deltas seed bar `timeperiod`.
|
||||
alpha = 1.0 / timeperiod
|
||||
avg_gain = _recursive(gain, gain[:timeperiod].mean(), timeperiod - 1, alpha, n - 1)
|
||||
avg_loss = _recursive(loss, loss[:timeperiod].mean(), timeperiod - 1, alpha, n - 1)
|
||||
|
||||
ag = avg_gain[timeperiod - 1:]
|
||||
al = avg_loss[timeperiod - 1:]
|
||||
with np.errstate(divide="ignore", invalid="ignore"):
|
||||
rsi = np.where(al == 0.0, 100.0, 100.0 - 100.0 / (1.0 + ag / al))
|
||||
out[timeperiod:] = rsi
|
||||
return pd.Series(out, index=s.index)
|
||||
|
||||
|
||||
def ATR(data, timeperiod: int = 14) -> pd.Series:
|
||||
if not isinstance(data, pd.DataFrame):
|
||||
raise TypeError("ATR needs a DataFrame with high/low/close")
|
||||
high = data["high"].to_numpy(dtype=float)
|
||||
low = data["low"].to_numpy(dtype=float)
|
||||
close = data["close"].to_numpy(dtype=float)
|
||||
n = high.size
|
||||
out = np.full(n, np.nan)
|
||||
if n <= timeperiod:
|
||||
return pd.Series(out, index=data.index)
|
||||
|
||||
prev_close = close[:-1]
|
||||
tr = np.maximum.reduce([
|
||||
high[1:] - low[1:],
|
||||
np.abs(high[1:] - prev_close),
|
||||
np.abs(low[1:] - prev_close),
|
||||
])
|
||||
|
||||
# tr[k] is bar k+1; the first `timeperiod` true ranges seed bar `timeperiod`.
|
||||
smoothed = _recursive(tr, tr[:timeperiod].mean(), timeperiod - 1, 1.0 / timeperiod, n - 1)
|
||||
out[timeperiod:] = smoothed[timeperiod - 1:]
|
||||
return pd.Series(out, index=data.index)
|
||||
|
||||
|
||||
def MACD(
|
||||
data,
|
||||
fastperiod: int = 12,
|
||||
slowperiod: int = 26,
|
||||
signalperiod: int = 9,
|
||||
price: str = "close",
|
||||
) -> pd.DataFrame:
|
||||
if slowperiod < fastperiod:
|
||||
fastperiod, slowperiod = slowperiod, fastperiod
|
||||
|
||||
s = _series(data, price)
|
||||
x = s.to_numpy(dtype=float)
|
||||
n = x.size
|
||||
|
||||
macd = np.full(n, np.nan)
|
||||
signal = np.full(n, np.nan)
|
||||
hist = np.full(n, np.nan)
|
||||
empty = pd.DataFrame({"macd": macd, "macdsignal": signal, "macdhist": hist}, index=s.index)
|
||||
|
||||
# Both EMAs emit their first value on the same bar. That makes the slow one
|
||||
# ordinary, but re-seeds the fast one from the SMA of the `fastperiod`
|
||||
# values ending there instead of carrying the recursion forward from bar
|
||||
# fastperiod-1 — the two disagree by ~0.2 on a 100-priced series.
|
||||
macd_start = slowperiod - 1
|
||||
if n <= macd_start:
|
||||
return empty
|
||||
line = _ema(x, fastperiod, macd_start) - _ema(x, slowperiod, macd_start)
|
||||
|
||||
# The signal EMA runs over the MACD line, so everything shifts by another
|
||||
# signalperiod-1 bars, and TA-Lib trims the MACD line to match.
|
||||
valid = line[macd_start:]
|
||||
if valid.size < signalperiod:
|
||||
return empty
|
||||
sig = _recursive(
|
||||
valid, valid[:signalperiod].mean(), signalperiod - 1, 2.0 / (signalperiod + 1.0), valid.size
|
||||
)
|
||||
start = macd_start + signalperiod - 1
|
||||
macd[start:] = line[start:]
|
||||
signal[macd_start:] = sig
|
||||
hist = macd - signal
|
||||
|
||||
return pd.DataFrame({"macd": macd, "macdsignal": signal, "macdhist": hist}, index=s.index)
|
||||
|
||||
|
||||
def BBANDS(
|
||||
data,
|
||||
timeperiod: int = 5,
|
||||
nbdevup: float = 2.0,
|
||||
nbdevdn: float = 2.0,
|
||||
matype: int = 0,
|
||||
price: str = "close",
|
||||
) -> pd.DataFrame:
|
||||
if matype != 0:
|
||||
raise NotImplementedError(f"BBANDS matype={matype} is not used by this codebase")
|
||||
s = _series(data, price)
|
||||
middle = s.rolling(window=timeperiod, min_periods=timeperiod).mean()
|
||||
# TA-Lib uses the population standard deviation.
|
||||
std = s.rolling(window=timeperiod, min_periods=timeperiod).std(ddof=0)
|
||||
return pd.DataFrame(
|
||||
{
|
||||
"upperband": middle + nbdevup * std,
|
||||
"middleband": middle,
|
||||
"lowerband": middle - nbdevdn * std,
|
||||
},
|
||||
index=s.index,
|
||||
)
|
||||
@@ -0,0 +1,689 @@
|
||||
"""TF_DF builder mixin — 由 split_tfdf_builders 自动生成,逻辑与原 TF_DF 一致。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from pandas import DataFrame
|
||||
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
from chanlun.core.ChanBIZS import ChanBIZS
|
||||
from chanlun.core.ChanBSP import ChanBSP
|
||||
from chanlun.core.ChanEnum import (
|
||||
Chan_BI_DIR,
|
||||
Chan_BSP_DIR,
|
||||
Chan_BSP_TYPE,
|
||||
Chan_FX_TYPE,
|
||||
Chan_K_DIR,
|
||||
Chan_KLC_FX,
|
||||
Chan_KLC_STATE,
|
||||
Chan_KLINE_DIR,
|
||||
Chan_KLU_PATTERN,
|
||||
Chan_PRICE_TREND,
|
||||
Chan_SEG_DIR,
|
||||
Chan_ZS_DIR,
|
||||
)
|
||||
from chanlun.core.ChanKLC import ChanKLC
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
from chanlun.core.ChanSBI import ChanSBI
|
||||
from chanlun.core.ChanSEG import ChanSEG
|
||||
from chanlun.core.ChanZS import ChanZS, ChanZS_Big
|
||||
from chanlun.indicators.ChanMACD import ChanMACD
|
||||
|
||||
|
||||
class BiBuilderMixin:
|
||||
def cal_trend(self, klc_list):
|
||||
"""
|
||||
基于价格与EMA24/EMA52的位置关系、以及MACD/Signal/Hist的方向,
|
||||
为每个KLC打上趋势标签:'UP' / 'DOWN' / 'FLAT'。
|
||||
仅设置 klc.trend,不影响其它字段。
|
||||
"""
|
||||
if not klc_list:
|
||||
return klc_list
|
||||
last_trend = Chan_PRICE_TREND.UNKNOWN
|
||||
# 趋势延续性:参考近 N 根已完成的KLC
|
||||
lookback_n = 5
|
||||
prev_klcs = []
|
||||
for klc in klc_list:
|
||||
price = getattr(klc, 'close', None)
|
||||
ema24 = getattr(klc, 'ema24', None)
|
||||
ema52 = getattr(klc, 'ema52', None)
|
||||
macd_raw = getattr(klc, 'macd', None)
|
||||
signal_raw = getattr(klc, 'signal', None)
|
||||
hist_raw = getattr(klc, 'macdhist', None)
|
||||
macd = macd_raw if macd_raw is not None else 0
|
||||
signal = signal_raw if signal_raw is not None else 0
|
||||
hist = hist_raw if hist_raw is not None else 0
|
||||
rsi = getattr(klc, 'rsi', None)
|
||||
macd_ready = macd_raw is not None and signal_raw is not None
|
||||
hist_ready = hist_raw is not None
|
||||
trend = Chan_PRICE_TREND.UNKNOWN
|
||||
score = 0
|
||||
try:
|
||||
# 有效性
|
||||
price_valid = price is not None and price != 0
|
||||
ema24_valid = ema24 is not None and ema24 != 0
|
||||
ema52_valid = ema52 is not None and ema52 != 0
|
||||
# 多因子投票
|
||||
|
||||
# 1) 均线结构 + 价位
|
||||
if ema24_valid or ema52_valid:
|
||||
ma_votes = 0
|
||||
if ema24_valid and ema52_valid:
|
||||
ma_votes += 1 if ema24 > ema52 else -1
|
||||
if price_valid and ema24_valid:
|
||||
ma_votes += 1 if price > ema24 else 0
|
||||
if price_valid and ema52_valid:
|
||||
ma_votes += 1 if price > ema52 else -1
|
||||
# 限幅,避免相关因子重复计分
|
||||
score += max(-2, min(2, ma_votes))
|
||||
# 2) MACD结构
|
||||
if macd_ready:
|
||||
score += 1 if macd >= signal else -1
|
||||
if hist_ready and hist != 0:
|
||||
score += 1 if hist > 0 else -1
|
||||
# 3) 动量与均线差分斜率
|
||||
pre = getattr(klc, 'pre', None)
|
||||
pre_hist = getattr(pre, 'macdhist', None) if pre else None
|
||||
if pre:
|
||||
pre_close = getattr(pre, 'close', None)
|
||||
if price_valid and pre_close is not None:
|
||||
score += 1 if price >= pre_close else -1
|
||||
pre_ema24 = getattr(pre, 'ema24', None)
|
||||
pre_ema52 = getattr(pre, 'ema52', None)
|
||||
if ema24_valid and ema52_valid and pre_ema24 not in (None, 0) and pre_ema52 not in (None, 0):
|
||||
spread_now = ema24 - ema52
|
||||
spread_pre = pre_ema24 - pre_ema52
|
||||
score += 1 if spread_now >= spread_pre else -1
|
||||
# 3.1) MACD柱体动量趋势:考虑 macdhist 的斜率与过零
|
||||
if hist_ready and pre_hist is not None:
|
||||
# 柱体斜率:上升加分,下降减分
|
||||
if hist > pre_hist:
|
||||
score += 1
|
||||
elif hist < pre_hist:
|
||||
score -= 1
|
||||
# 过零加权:负转正更偏多,正转负更偏空
|
||||
if pre_hist < 0 and hist > 0:
|
||||
score += 1
|
||||
elif pre_hist > 0 and hist < 0:
|
||||
score -= 1
|
||||
# 3.2) EMA52 突破/跌破加权
|
||||
if ema52_valid and price_valid and pre_close is not None and pre_ema52 not in (None, 0):
|
||||
# 看多突破:从均线下方上破且动量配合
|
||||
if pre_close <= pre_ema52 and price > ema52 and (hist is None or pre_hist is None or hist >= pre_hist):
|
||||
score += 1
|
||||
# 看空跌破:从均线上方下破且动量配合
|
||||
if pre_close >= pre_ema52 and price < ema52 and (hist is None or pre_hist is None or hist <= pre_hist):
|
||||
score -= 1
|
||||
# 3.3) EMA52 支撑/阻力触碰(非强穿越)
|
||||
if ema52_valid and price_valid:
|
||||
low_v = getattr(klc, 'low', None)
|
||||
high_v = getattr(klc, 'high', None)
|
||||
if low_v is not None and high_v is not None and ema52 not in (None, 0):
|
||||
# 触碰容差(相对EMA52的0.15%)
|
||||
touch_tol = 0.0015
|
||||
# 作为支撑:收盘在上,最低靠近EMA52
|
||||
near_support_touch = (price > ema52) and (abs(low_v - ema52) / abs(ema52) <= touch_tol)
|
||||
# 作为阻力:收盘在下,最高靠近EMA52
|
||||
near_resistance_touch = (price < ema52) and (abs(high_v - ema52) / abs(ema52) <= touch_tol)
|
||||
if near_support_touch:
|
||||
# 若动量不弱,则更偏多
|
||||
score += 1 if (hist is None or pre_hist is None or hist >= pre_hist) else 0
|
||||
if near_resistance_touch:
|
||||
# 若动量不强,则更偏空
|
||||
score -= 1 if (hist is None or pre_hist is None or hist <= pre_hist) else 0
|
||||
# 3.4) 多次对 EMA52 的"拒绝"配合 MACD 逆向:易形成压/支并反向
|
||||
# 统计近窗口内的上/下拒绝次数:
|
||||
# - 上拒绝:价格位于 EMA52 下方,最高触及/越过 EMA52 但收盘仍在下方
|
||||
# - 下拒绝:价格位于 EMA52 上方,最低触及/跌破 EMA52 但收盘仍在上方
|
||||
recent_up_rejects = 0
|
||||
recent_down_rejects = 0
|
||||
if ema52_valid:
|
||||
window_rej = prev_klcs[-lookback_n:] if len(prev_klcs) > 0 else []
|
||||
rej_tol = 0.0015
|
||||
for wk in window_rej:
|
||||
wk_close = getattr(wk, 'close', None)
|
||||
wk_ema52 = getattr(wk, 'ema52', None)
|
||||
wk_high = getattr(wk, 'high', None)
|
||||
wk_low = getattr(wk, 'low', None)
|
||||
if wk_close is None or wk_ema52 in (None, 0):
|
||||
continue
|
||||
# 上拒绝(阻力):下方多次试图上破但未站上
|
||||
if wk_close < wk_ema52 and wk_high is not None:
|
||||
if wk_high >= wk_ema52 or abs(wk_high - wk_ema52) / abs(wk_ema52) <= rej_tol:
|
||||
recent_up_rejects += 1
|
||||
# 下拒绝(支撑):上方多次试图下破但未跌破
|
||||
if wk_close > wk_ema52 and wk_low is not None:
|
||||
if wk_low <= wk_ema52 or abs(wk_low - wk_ema52) / abs(wk_ema52) <= rej_tol:
|
||||
recent_down_rejects += 1
|
||||
# 定义 MACD 的方向偏好
|
||||
macd_bias_up = macd_ready and (macd >= signal) and (not hist_ready or pre_hist is None or hist >= pre_hist)
|
||||
macd_bias_down = macd_ready and (macd <= signal) and (not hist_ready or pre_hist is None or hist <= pre_hist)
|
||||
# 若多次上拒绝且 MACD 偏空,则更偏向下行;若多次下拒绝且 MACD 偏多,则更偏向上行
|
||||
if recent_up_rejects >= 2 and macd_bias_down:
|
||||
score -= 2
|
||||
if recent_down_rejects >= 2 and macd_bias_up:
|
||||
score += 2
|
||||
# 4) RSI 辅助
|
||||
if rsi is not None:
|
||||
if rsi >= 55:
|
||||
score += 1
|
||||
elif rsi <= 45:
|
||||
score -= 1
|
||||
# 5) 指标未就绪回退(EMA/MACD缺失时,用动量与RSI辅助,延续趋势)
|
||||
has_full_ind = ema24_valid and ema52_valid and not (macd == 0 and signal == 0 and hist == 0)
|
||||
if not has_full_ind:
|
||||
# 仅根据价动量/RSI做轻量判断,默认延续 last_trend,除非出现强反向
|
||||
strong_up = False
|
||||
strong_down = False
|
||||
pre = getattr(klc, 'pre', None)
|
||||
if pre:
|
||||
pre_close = getattr(pre, 'close', None)
|
||||
if price_valid and pre_close is not None:
|
||||
strong_up = (price >= pre_close)
|
||||
strong_down = (price < pre_close)
|
||||
if rsi is not None:
|
||||
if rsi >= 60:
|
||||
strong_up = True
|
||||
elif rsi <= 40:
|
||||
strong_down = True
|
||||
if last_trend == Chan_PRICE_TREND.UP and not strong_down:
|
||||
trend = Chan_PRICE_TREND.UP
|
||||
elif last_trend == Chan_PRICE_TREND.DOWN and not strong_up:
|
||||
trend = Chan_PRICE_TREND.DOWN
|
||||
else:
|
||||
trend = Chan_PRICE_TREND.UP if strong_up and not strong_down else (Chan_PRICE_TREND.DOWN if strong_down and not strong_up else Chan_PRICE_TREND.FLAT)
|
||||
else:
|
||||
# 6) 震荡过滤(仅当极近EMA52且MACD贴合时判作震荡)
|
||||
near_flat = False
|
||||
if price_valid and ema52_valid:
|
||||
near_ema52 = abs(price - ema52) / abs(ema52) <= 0.0005 # 0.05%
|
||||
if macd_ready:
|
||||
macd_scale = max(abs(macd), abs(signal), 1e-6)
|
||||
near_macd = abs(macd - signal) / macd_scale <= 0.05
|
||||
else:
|
||||
near_macd = False
|
||||
near_flat = near_ema52 and near_macd
|
||||
# 7) 动态阈值 + 趋势记忆(更强粘滞:趋势中容忍小幅反分)
|
||||
# 引入过去 N 根KLC 的趋势延续性来动态调整翻转阈值,并结合 EMA52 支撑/阻力触碰强化门槛
|
||||
force_flip_down = False
|
||||
force_flip_up = False
|
||||
if near_flat:
|
||||
trend = Chan_PRICE_TREND.FLAT
|
||||
else:
|
||||
# 计算过去窗口的趋势一致性
|
||||
window = prev_klcs[-lookback_n:] if len(prev_klcs) > 0 else []
|
||||
persist_up = 0
|
||||
persist_down = 0
|
||||
for wk in window:
|
||||
if getattr(wk, 'trend', None) == Chan_PRICE_TREND.UP:
|
||||
persist_up += 1
|
||||
elif getattr(wk, 'trend', None) == Chan_PRICE_TREND.DOWN:
|
||||
persist_down += 1
|
||||
persist_ratio_up = (persist_up / len(window)) if len(window) > 0 else 0
|
||||
persist_ratio_down = (persist_down / len(window)) if len(window) > 0 else 0
|
||||
# 基准阈值
|
||||
down_flip_threshold = -2
|
||||
up_flip_threshold = 2
|
||||
# 若最近多为UP,则从UP翻转需更强反向信号;同理对DOWN
|
||||
if last_trend == Chan_PRICE_TREND.UP and persist_ratio_up >= 0.6:
|
||||
down_flip_threshold = -3
|
||||
elif last_trend == Chan_PRICE_TREND.DOWN and persist_ratio_down >= 0.6:
|
||||
up_flip_threshold = 3
|
||||
# EMA52 触碰强化门槛:UP时若出现支撑触碰,下翻更难;DOWN时若出现阻力触碰,上翻更难
|
||||
if ema52_valid and price_valid:
|
||||
low_v = getattr(klc, 'low', None)
|
||||
high_v = getattr(klc, 'high', None)
|
||||
if low_v is not None and high_v is not None and ema52 not in (None, 0):
|
||||
touch_tol = 0.0015
|
||||
near_support_touch = (price > ema52) and (abs(low_v - ema52) / abs(ema52) <= touch_tol)
|
||||
near_resistance_touch = (price < ema52) and (abs(high_v - ema52) / abs(ema52) <= touch_tol)
|
||||
if last_trend == Chan_PRICE_TREND.UP and near_support_touch:
|
||||
# 强化维持UP:进一步降低向下翻转阈值
|
||||
down_flip_threshold = min(down_flip_threshold - 1, -3)
|
||||
if last_trend == Chan_PRICE_TREND.DOWN and near_resistance_touch:
|
||||
# 强化维持DOWN:进一步提高向上翻转阈值
|
||||
up_flip_threshold = max(up_flip_threshold + 1, 3)
|
||||
# 7.1) 复合拐头信号:MACD/Signal 同向拐头 + hist 连续减弱 + 多次未能越过 EMA52
|
||||
pre_macd = getattr(pre, 'macd', None) if pre else None
|
||||
pre_signal = getattr(pre, 'signal', None) if pre else None
|
||||
macd_slope = (macd - pre_macd) if (macd_ready and pre_macd is not None) else 0
|
||||
signal_slope = (signal - pre_signal) if (macd_ready and pre_signal is not None) else 0
|
||||
# hist 连续减弱(绝对值缩小)
|
||||
hist_seq = []
|
||||
for wk in prev_klcs[-2:]:
|
||||
val = getattr(wk, 'macdhist', None)
|
||||
if val is not None:
|
||||
hist_seq.append(val)
|
||||
if hist is not None:
|
||||
hist_seq.append(hist)
|
||||
weaken_steps = 0
|
||||
for i in range(1, len(hist_seq)):
|
||||
if abs(hist_seq[i]) < abs(hist_seq[i-1]):
|
||||
weaken_steps += 1
|
||||
# 近窗口对 EMA52 的"未能站上/跌破"统计(放宽窗口与条件)
|
||||
window_ema = prev_klcs[-4:] if len(prev_klcs) > 0 else []
|
||||
no_up_break = False
|
||||
no_down_break = False
|
||||
if ema52_valid:
|
||||
# 未能有效上破:最近若干根收盘大多数不在 EMA52 上方,且高点多次触及/接近
|
||||
cnt_touch_up = 0
|
||||
cnt_close_above = 0
|
||||
for wk in window_ema:
|
||||
wk_close = getattr(wk, 'close', None)
|
||||
wk_high = getattr(wk, 'high', None)
|
||||
wk_ema = getattr(wk, 'ema52', None)
|
||||
if wk_close is not None and wk_ema not in (None, 0):
|
||||
if wk_close > wk_ema:
|
||||
cnt_close_above += 1
|
||||
if wk_high is not None and (wk_high >= wk_ema or abs(wk_high - wk_ema) / abs(wk_ema) <= 0.0015):
|
||||
cnt_touch_up += 1
|
||||
no_up_break = (cnt_close_above <= 1 and cnt_touch_up >= 1 and price <= ema52)
|
||||
# 未能有效下破:最近若干根收盘大多数不在 EMA52 下方,且低点多次触及/接近
|
||||
cnt_touch_down = 0
|
||||
cnt_close_below = 0
|
||||
for wk in window_ema:
|
||||
wk_close = getattr(wk, 'close', None)
|
||||
wk_low = getattr(wk, 'low', None)
|
||||
wk_ema = getattr(wk, 'ema52', None)
|
||||
if wk_close is not None and wk_ema not in (None, 0):
|
||||
if wk_close < wk_ema:
|
||||
cnt_close_below += 1
|
||||
if wk_low is not None and (wk_low <= wk_ema or abs(wk_low - wk_ema) / abs(wk_ema) <= 0.0015):
|
||||
cnt_touch_down += 1
|
||||
no_down_break = (cnt_close_below <= 1 and cnt_touch_down >= 1 and price >= ema52)
|
||||
# 若当前为UP趋势,出现明显拐头+hist减弱+未能上破EMA52,则加速看空
|
||||
if last_trend == Chan_PRICE_TREND.UP and macd_slope < 0 and signal_slope < 0 and weaken_steps >= 1 and no_up_break and macd_bias_down:
|
||||
score -= 3
|
||||
down_flip_threshold = max(down_flip_threshold, 0)
|
||||
force_flip_down = True
|
||||
# 若当前为DOWN趋势,出现明显拐头+hist减弱+未能下破EMA52,则加速看多
|
||||
if last_trend == Chan_PRICE_TREND.DOWN and macd_slope > 0 and signal_slope > 0 and weaken_steps >= 1 and no_down_break and macd_bias_up:
|
||||
score += 3
|
||||
up_flip_threshold = min(up_flip_threshold, 0)
|
||||
force_flip_up = True
|
||||
# 多次对 EMA52 的拒绝配合 MACD 逆向:加速反向翻转(降低相反方向阈值)
|
||||
if recent_up_rejects >= 2 and macd_bias_down:
|
||||
# 从 UP 向 DOWN 的翻转更容易
|
||||
down_flip_threshold = max(down_flip_threshold, -1)
|
||||
if recent_down_rejects >= 2 and macd_bias_up:
|
||||
# 从 DOWN 向 UP 的翻转更容易
|
||||
up_flip_threshold = min(up_flip_threshold, 1)
|
||||
if force_flip_down:
|
||||
trend = Chan_PRICE_TREND.DOWN
|
||||
elif force_flip_up:
|
||||
trend = Chan_PRICE_TREND.UP
|
||||
elif last_trend == Chan_PRICE_TREND.UP:
|
||||
if score <= down_flip_threshold:
|
||||
trend = Chan_PRICE_TREND.DOWN
|
||||
else:
|
||||
trend = Chan_PRICE_TREND.UP
|
||||
elif last_trend == Chan_PRICE_TREND.DOWN:
|
||||
if score >= up_flip_threshold:
|
||||
trend = Chan_PRICE_TREND.UP
|
||||
else:
|
||||
trend = Chan_PRICE_TREND.DOWN
|
||||
else:
|
||||
# 初始无记忆时,降低进入门槛
|
||||
if score >= 1:
|
||||
trend = Chan_PRICE_TREND.UP
|
||||
elif score <= -1:
|
||||
trend = Chan_PRICE_TREND.DOWN
|
||||
else:
|
||||
trend = Chan_PRICE_TREND.FLAT
|
||||
except Exception:
|
||||
trend = Chan_PRICE_TREND.UNKNOWN
|
||||
# 写回趋势
|
||||
if klc.end_time is None:
|
||||
trend = Chan_PRICE_TREND.FLAT
|
||||
if hasattr(klc, 'set_trend'):
|
||||
klc.set_trend(trend)
|
||||
else:
|
||||
setattr(klc, 'trend', trend)
|
||||
last_trend = trend
|
||||
# 更新滑窗:仅向后看
|
||||
prev_klcs.append(klc)
|
||||
price_diff = klc.close - klc.pre.close if klc.pre else 0
|
||||
#if klc.index > len(klc_list) - 10:
|
||||
#print(klc.start_time, klc.end_time, klc.close, klc.ema24, klc.ema52, klc.macd, klc.signal, klc.macdhist, klc.trend, price_diff, score)
|
||||
#print(klc.start_time, klc.end_time, klc.trend, price_diff, score)
|
||||
return klc_list
|
||||
|
||||
def get_bi_list(self, dataframe):
|
||||
bi_list = self.cal_bi_list(self.get_klc_list(dataframe))
|
||||
#bi_list = self.cal_bi_list_chanlun(self.get_klc_list(dataframe))
|
||||
return bi_list
|
||||
|
||||
def cal_bi_list(self, klc_list):
|
||||
bi_list = []
|
||||
last_top = None
|
||||
last_bottom = None
|
||||
bi_klc_min = 4
|
||||
last_fx_klc = None
|
||||
for klc in klc_list:
|
||||
if last_fx_klc:
|
||||
klc.check_klc_state(last_fx_klc)
|
||||
klc.check_fx_confirmed(last_top, last_bottom)
|
||||
fx = self.check_fx(klc)
|
||||
if fx == Chan_FX_TYPE.TOP:
|
||||
if last_bottom:
|
||||
if self.check_top_fx(last_bottom, klc) == False:
|
||||
fx = Chan_FX_TYPE.UNKNOWN
|
||||
if fx == Chan_FX_TYPE.BOTTOM:
|
||||
if last_top:
|
||||
if self.check_bottom_fx(last_top, klc) == False:
|
||||
#print(klc.end_time, last_top.end_time, "---")
|
||||
fx = Chan_FX_TYPE.UNKNOWN
|
||||
# Do nothing
|
||||
if fx == Chan_FX_TYPE.UNKNOWN:
|
||||
if len(bi_list) > 0:
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#continue
|
||||
if len(bi_list) > 0 and klc.end_klu:
|
||||
last_bi = bi_list[-1]
|
||||
#print(klc.start_time, last_bi.start_time, last_bi.end_time, last_bi.dir, last_bi.high, last_bi.low, last_bottom.end_time, "last bi")
|
||||
if last_top and last_bi.dir == Chan_BI_DIR.DOWN:
|
||||
if last_bottom and klc.high > last_bi.high:
|
||||
#print(klc.end_time, "Top 7, 1", last_bi.start_time, klc.high, last_bi.high)
|
||||
#klc.klc_fx_type = Chan_KLC_FX.TOP7
|
||||
#klc.fx = Chan_FX_TYPE.TOP
|
||||
"""
|
||||
last_bi.set_end_klc(last_bottom, klc)
|
||||
bi = ChanBI(last_bottom, len(bi_list), Chan_BI_DIR.UP)
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM7)
|
||||
#klc.bb_out = True
|
||||
last_bi.set_next(bi)
|
||||
bi.set_pre(last_bi)
|
||||
for klc_index in range(last_bi.end_klc.index, len(klc_list)):
|
||||
bi.add_klc(klc_list[klc_index])
|
||||
bi_list.append(bi)
|
||||
last_top = klc
|
||||
klc.set_bi(bi)
|
||||
#print(klc.start_time, bi.start_time, bi.end_time, bi.dir, bi.high, bi.low, bi.is_sure)
|
||||
"""
|
||||
else:
|
||||
if last_bottom and last_bi.dir == Chan_BI_DIR.UP:
|
||||
if last_top and klc.low < last_bi.low:
|
||||
#print(klc.end_time, "Bottom 8, 2", last_bi.start_time)
|
||||
#klc.klc_fx_type = Chan_KLC_FX.BOTTOM8
|
||||
#klc.fx = Chan_FX_TYPE.BOTTOM
|
||||
"""
|
||||
last_bi.set_end_klc(last_top, klc)
|
||||
bi = ChanBI(last_top, len(bi_list), Chan_BI_DIR.DOWN)
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.TOP6)
|
||||
#klc.bb_out = True
|
||||
last_bi.set_next(bi)
|
||||
bi.set_pre(last_bi)
|
||||
for klc_index in range(last_bi.end_klc.index, len(klc_list)):
|
||||
bi.add_klc(klc_list[klc_index])
|
||||
bi_list.append(bi)
|
||||
last_bottom = klc
|
||||
klc.set_bi(bi)
|
||||
#print(klc.start_time, bi.start_time, bi.end_time, bi.dir, bi.high, bi.low, bi.is_sure)
|
||||
"""
|
||||
else:
|
||||
last_fx_klc = klc
|
||||
if fx == Chan_FX_TYPE.TOP:
|
||||
#print(klc.end_time, fx, klc.pre.high, klc.high, klc.pre.start_time, klc.pre.end_time)
|
||||
if last_top:
|
||||
if last_bottom:
|
||||
#print(klc.start_time, last_bottom.start_time, last_top.start_time)
|
||||
if last_bottom.index < last_top.index:
|
||||
# Second top lower to be second sell point
|
||||
if last_top.high > klc.high:
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.TOP3)
|
||||
#print(klc.end_time, klc.fx, "二类卖点Sell 1")
|
||||
else:
|
||||
# A new top found
|
||||
#last_top.set_fx(Chan_FX_TYPE.UNKNOWN)
|
||||
last_top = klc
|
||||
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Top Change 1")
|
||||
klc.set_klc_fx_type(Chan_KLC_FX.TOP1)
|
||||
self.check_fx_pattern(klc)
|
||||
#print(klc.end_time, klc.fx, "一类卖点Sell 1")
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
# 不满足结合律的分型
|
||||
else:
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.TOP0)
|
||||
#print(klc.end_time, klc.klc_fx_type)
|
||||
if last_bottom.index + bi_klc_min > klc.index:
|
||||
if last_top.high > klc.high:
|
||||
#print(klc.start_time, klc.fx, "二类卖点Sell 1")
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.TOP8)
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
# New TOP Found前面的UKNOWN可能出现TOP7,但是这里的也可能出现TOP8分型
|
||||
else:
|
||||
# 顶分型在出现2之前超过前一个笔的顶 TOP8
|
||||
if last_top.index + bi_klc_min < klc.index and len(bi_list) > 1:
|
||||
pre_last_bi = bi_list[-2]
|
||||
last_bi = bi_list[-1]
|
||||
if pre_last_bi.is_sure and not last_bi.is_sure and pre_last_bi.dir == Chan_BI_DIR.UP and False:
|
||||
#pre_last_bi.update_bi(klc)
|
||||
bi_list.remove(last_bi)
|
||||
pre_last_bi.set_next(None)
|
||||
#last_top.set_fx(Chan_FX_TYPE.PTOP)
|
||||
last_top = klc
|
||||
last_bottom = pre_last_bi.start_klc
|
||||
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Top Bottom Change 1")
|
||||
klc.set_klc_fx_type(Chan_KLC_FX.TOP2)
|
||||
#print(klc.start_time, last_bi.start_klc.start_time, "New TOP Found reset last bi")
|
||||
#klc.set_state("10")
|
||||
#print(klc.start_time, klc.fx, "笔卖点Sell 1")
|
||||
###klc.set_klc_fx_type(Chan_KLC_FX.TOP2) # when bi is down but the fx is top
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.TOP8)
|
||||
#print(klc.start_time, last_bi.start_klc.start_time, "New TOP Found reset last bi")
|
||||
else:
|
||||
#klc.set_fx(Chan_FX_TYPE.PTOP)
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#print(klc.end_time, klc.fx, "无效顶分型")
|
||||
# 满足结合律
|
||||
else:
|
||||
# New Temp TOP and last bottom confirmed ***** confirm last down bi(last bottom and last top)
|
||||
last_bi = bi_list[-1]
|
||||
if not last_bi.is_sure:
|
||||
last_bi.set_end_klc(last_bottom, klc)
|
||||
bi = ChanBI(last_bottom, len(bi_list), Chan_BI_DIR.UP)
|
||||
last_bi.set_next(bi)
|
||||
bi.set_pre(last_bi)
|
||||
bi.add_klc(klc)
|
||||
bi_list.append(bi)
|
||||
last_top = klc
|
||||
#print(klc.end_time, klc.fx, bi_list[-1].dir, "Last Top Change 2")
|
||||
klc.set_klc_fx_type(Chan_KLC_FX.TOP2)
|
||||
self.check_fx_pattern(klc)
|
||||
#bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#print(klc.start_time, last_bottom.start_time, "Normal TOP Found, Confirm down bi 4")
|
||||
# last bottom = None 初始化的时候用,其他时间不用
|
||||
else:
|
||||
# 初始化的时候用,其他时间不用
|
||||
if last_top.high < klc.high:
|
||||
last_bi = bi_list[-1]
|
||||
last_bi.set_start_klc(klc, Chan_BI_DIR.DOWN)
|
||||
last_top = klc
|
||||
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Top Change 3")
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
# 初始化的时候用,其他时间不用
|
||||
else:
|
||||
#klc.set_fx(Chan_FX_TYPE.TT)
|
||||
#print(klc.start_time, klc.fx, "二类卖点Sell 2")
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
# last_top == None 初始化的时候用,其他时间不用
|
||||
else:
|
||||
if last_bottom:
|
||||
# 不满足结合律的分型
|
||||
if last_bottom.index + bi_klc_min > klc.index:
|
||||
#klc.set_fx(Chan_FX_TYPE.PTOP)
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#print(klc.start_time, klc.fx, "中枢卖点Sell 1")
|
||||
else:
|
||||
# First temp top and last bottom confirmed
|
||||
last_top = klc
|
||||
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Top Change 4")
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
# Last top = None, last bottom = None, create first down bi 初始化的时候用,其他时间不用
|
||||
else:
|
||||
# First temp top
|
||||
last_top = klc
|
||||
bi = ChanBI(klc, len(bi_list), Chan_BI_DIR.DOWN)
|
||||
bi_list.append(bi)
|
||||
bi.add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Top Change 5")
|
||||
#klc.fx = Bottom ========================
|
||||
else:
|
||||
if last_bottom:
|
||||
if last_top:
|
||||
# Bottom after top and find a new bottom
|
||||
if last_top.index < last_bottom.index:
|
||||
# Second bottom uppper to be second buy point and confirm last bi
|
||||
if last_bottom.low < klc.low:
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM3)
|
||||
#print(last_bottom.start_time, last_bottom.end_time, "--------------------------------1")
|
||||
#print(klc.end_time, klc.fx, "二类买点Buy 1")
|
||||
else:
|
||||
# A new bottom found
|
||||
last_bottom = klc
|
||||
#print(klc.end_time, klc.fx, bi_list[-1].dir, "Last Bottom Change 1")
|
||||
klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM1)
|
||||
self.check_fx_pattern(klc)
|
||||
#print(klc.end_time, klc.fx, "一类买点Buy 1")
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
# 不满足结合律的分型
|
||||
else:
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM0)
|
||||
#print(klc.end_time, klc.klc_fx_type)
|
||||
if last_top.index + bi_klc_min > klc.index:
|
||||
if last_bottom.low < klc.low:
|
||||
#print(klc.end_time, klc.fx, "中枢买点Buy 1")
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM8)
|
||||
# Found new bottom没有意义,上面UNKNOWN的时候已经是笔破坏了
|
||||
else:
|
||||
#print(klc.end_time, last_bottom.end_time, "Found a new bottom")
|
||||
if last_bottom.index + bi_klc_min < klc.index and len(bi_list) > 1:
|
||||
pre_last_bi = bi_list[-2]
|
||||
last_bi = bi_list[-1]
|
||||
if pre_last_bi.is_sure and not last_bi.is_sure and pre_last_bi.dir == Chan_BI_DIR.DOWN and False:
|
||||
#pre_last_bi.update_bi(klc)
|
||||
bi_list.remove(last_bi)
|
||||
pre_last_bi.set_next(None)
|
||||
last_bottom = klc
|
||||
last_top = pre_last_bi.start_klc
|
||||
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Top Bottom Change 2")
|
||||
klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM2)
|
||||
#print(klc.start_time, last_bi.start_klc.start_time, "New BOTTOM Found reset last bi")
|
||||
#print(klc.start_time, klc.fx, "笔买点Buy 1")
|
||||
###klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM2) # when bi is up but the fx is bottom
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM8)
|
||||
else:
|
||||
#klc.set_fx(Chan_FX_TYPE.UNKNOWN)
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
print(klc.end_time, klc.fx, "无效底分型")
|
||||
# 满足结合律的分型
|
||||
else:
|
||||
# New Temp Bottom and last top confirmed ***** confirm last up bi(last bottom and last top)
|
||||
last_bi = bi_list[-1]
|
||||
if not last_bi.is_sure:
|
||||
last_bi.set_end_klc(last_top, klc)
|
||||
bi = ChanBI(last_top, len(bi_list), Chan_BI_DIR.DOWN)
|
||||
last_bi.set_next(bi)
|
||||
bi.set_pre(last_bi)
|
||||
bi.add_klc(klc)
|
||||
bi_list.append(bi)
|
||||
last_bottom = klc
|
||||
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Bottom Change 2")
|
||||
klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM2)
|
||||
self.check_fx_pattern(klc)
|
||||
#bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#print(klc.start_time, last_top.start_time, "Normal Bottom Found, Confirm up bi 6")
|
||||
# last_top = None 初始化的时候用,其他时间不用
|
||||
else:
|
||||
if last_bottom.low > klc.low:
|
||||
last_bi = bi_list[-1]
|
||||
last_bi.set_start_klc(klc, Chan_BI_DIR.UP)
|
||||
#last_bottom.set_fx(Chan_FX_TYPE.UNKNOWN)
|
||||
last_bottom = klc
|
||||
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Bottom Change 3")
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#print(klc.start_time, klc.fx, "笔买点Buy 3")
|
||||
else:
|
||||
#klc.set_fx(Chan_FX_TYPE.BB)
|
||||
#klc.set_state('-20')
|
||||
#print(klc.start_time, klc.fx, "二类买点Buy 2")
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
# last_bottom = None 初始化的时候用,其他时间不用
|
||||
else:
|
||||
if last_top:
|
||||
# 不满足结合律的分型
|
||||
if last_top.index + bi_klc_min > klc.index:
|
||||
#klc.set_fx(Chan_FX_TYPE.PBOTTOM)
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#print(klc.start_time, klc.fx, "中枢买点Buy 1")
|
||||
else:
|
||||
# First temp bottom and last top confirmed
|
||||
last_bottom = klc
|
||||
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Bottom Change 4")
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#print(klc.start_time, klc.fx, "一类买点Buy 1")
|
||||
# Last top = None, last bottom = None, create first up bi
|
||||
else:
|
||||
# First temp bottom and no top yet
|
||||
last_bottom = klc
|
||||
bi = ChanBI(klc, len(bi_list), Chan_BI_DIR.UP)
|
||||
#klc.set_klc_fx_type(Chan_KLC_FX.BOTTOM7)
|
||||
bi_list.append(bi)
|
||||
bi_list[-1].add_klc(klc)
|
||||
klc.set_bi(bi_list[-1])
|
||||
#print(klc.start_time, klc.fx, bi_list[-1].dir, "Last Bottom Change 5")
|
||||
#print(klc.start_time, klc.fx, "笔买点Buy 4")
|
||||
self.get_above_zero_bsp(klc_list)
|
||||
#print(bi_list[-1].start_time, bi_list[-1].end_time, len(bi_list[-1].klc_list))
|
||||
return bi_list
|
||||
|
||||
def check_top_fx(self, last_bottom, klc):
|
||||
#严格笔
|
||||
#last_bottom_high = max(last_bottom.high, last_bottom.pre.high, last_bottom.next.high)
|
||||
#缠论原著笔
|
||||
last_bottom_high = last_bottom.high
|
||||
if (last_bottom_high > klc.pre.low or last_bottom_high > klc.next.low) and (klc.index - last_bottom.index < 100):
|
||||
#print(klc.end_time, "check_top_fx False")
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def check_bottom_fx(self, last_top, klc):
|
||||
#严格笔
|
||||
#last_top_low = min(last_top.low, last_top.pre.low, last_top.next.low)
|
||||
#缠论原著笔
|
||||
last_top_low = last_top.low
|
||||
if (last_top_low < klc.pre.high or last_top_low < klc.next.high) and (klc.index - last_top.index < 100):
|
||||
return False
|
||||
return True
|
||||
# 线段内的中枢
|
||||
@@ -0,0 +1,410 @@
|
||||
"""TF_DF builder mixin — 由 split_tfdf_builders 自动生成,逻辑与原 TF_DF 一致。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from pandas import DataFrame
|
||||
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
from chanlun.core.ChanBIZS import ChanBIZS
|
||||
from chanlun.core.ChanBSP import ChanBSP
|
||||
from chanlun.core.ChanEnum import (
|
||||
Chan_BI_DIR,
|
||||
Chan_BSP_DIR,
|
||||
Chan_BSP_TYPE,
|
||||
Chan_FX_TYPE,
|
||||
Chan_K_DIR,
|
||||
Chan_KLC_FX,
|
||||
Chan_KLC_STATE,
|
||||
Chan_KLINE_DIR,
|
||||
Chan_KLU_PATTERN,
|
||||
Chan_PRICE_TREND,
|
||||
Chan_SEG_DIR,
|
||||
Chan_ZS_DIR,
|
||||
)
|
||||
from chanlun.core.ChanKLC import ChanKLC
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
from chanlun.core.ChanSBI import ChanSBI
|
||||
from chanlun.core.ChanSEG import ChanSEG
|
||||
from chanlun.core.ChanZS import ChanZS, ChanZS_Big
|
||||
from chanlun.indicators.ChanMACD import ChanMACD
|
||||
|
||||
|
||||
class BspBuilderMixin:
|
||||
def get_bsp_state(self, dataframe):
|
||||
klu_list = self.get_klu_list(dataframe)
|
||||
klc_list = self.get_klc_list(klu_list)
|
||||
bi_list = self.cal_bi_list(klc_list)
|
||||
seg_list = self.get_seg_list(bi_list)
|
||||
bi_zs_list = self.cal_bi_zs(seg_list)
|
||||
bsp_list = self.find_all_bsp(bi_list, bi_zs_list)
|
||||
bsp_state_list = [0] * len(dataframe)
|
||||
klc_index = 0
|
||||
for index in range(0, len(dataframe)):
|
||||
if klc_index == len(klc_list):
|
||||
klc_index = len(klc_list) - 1
|
||||
klc = klc_list[klc_index]
|
||||
if klc.end_klu and klc.end_klu.idx == index:
|
||||
if klc.klc_fx_type == Chan_KLC_FX.TOP2:
|
||||
bi = klc.bi.pre
|
||||
if bi and bi.is_sure and bi.end_klc.bsp_type == Chan_BSP_TYPE.B3:
|
||||
# 第三类买点
|
||||
bsp_state_list[index] = -1
|
||||
#print(klc.end_time, "B3")
|
||||
else:
|
||||
bsp_state_list[index] = 0
|
||||
elif klc.klc_fx_type == Chan_KLC_FX.BOTTOM2:
|
||||
bi = klc.bi.pre
|
||||
if bi and bi.is_sure and bi.end_klc.bsp_type == Chan_BSP_TYPE.S3:
|
||||
# 第三类卖点
|
||||
bsp_state_list[index] = 1
|
||||
#print(klc.end_time, "S3")
|
||||
else:
|
||||
bsp_state_list[index] = 0
|
||||
klc_index += 1
|
||||
else:
|
||||
bsp_state_list[index] = 0
|
||||
return bsp_state_list
|
||||
|
||||
def get_above_zero_bsp(self, klc_list):
|
||||
buy_bsp_list = []
|
||||
sell_bsp_list = []
|
||||
above_zero = False
|
||||
buy_bsp = None
|
||||
sell_bsp = None
|
||||
for klc in klc_list:
|
||||
if klc.pre and klc.pre.signal < 0 and klc.signal > 0:
|
||||
above_zero = True
|
||||
if klc.pre and klc.pre.signal > 0 and klc.signal < 0:
|
||||
above_zero = False
|
||||
if above_zero and klc.klc_fx_type == Chan_KLC_FX.BOTTOM2 and klc.macd > 0:
|
||||
buy_bsp = klc
|
||||
buy_bsp_list.append(klc)
|
||||
#print(klc.end_time, "MACD 0轴上穿,回调笔底分型做多")
|
||||
if buy_bsp and klc.pre and klc.pre.macdhist > 0 and klc.macdhist < 0:
|
||||
sell_bsp = klc
|
||||
sell_bsp_list.append(klc)
|
||||
buy_bsp = None
|
||||
#print(klc.end_time, "Sell BSP Found")
|
||||
return buy_bsp_list
|
||||
|
||||
def find_all_bsp(self, bi_list, bi_zs_list):
|
||||
"""
|
||||
笔中枢的三类买卖点识别
|
||||
|
||||
三类买点:中枢形成后,一笔向上离开中枢(低点 > zg),
|
||||
随后回拉的一笔低点不跌回中枢(低点 >= zg),确认支撑有效。
|
||||
三类卖点:中枢形成后,一笔向下离开中枢(高点 < zd),
|
||||
随后反弹的一笔高点不回到中枢(高点 <= zd),确认压力有效。
|
||||
|
||||
参数:
|
||||
bi_list: 笔列表
|
||||
bi_zs_list: 笔中枢列表(二维列表,每个seg内的中枢列表)
|
||||
|
||||
返回:
|
||||
bsp_list: ChanBSP 列表,包含所有识别到的三类买卖点
|
||||
"""
|
||||
bsp_list = []
|
||||
if len(bi_list) < 4 or len(bi_zs_list) == 0:
|
||||
return bsp_list
|
||||
|
||||
for zs in bi_zs_list:
|
||||
if not zs.is_sure or len(zs.bi_list) < 3:
|
||||
continue
|
||||
#print(zs.start_time, zs.end_time, zs.dir, zs.is_sure, len(zs.bi_list))
|
||||
# 中枢结束后的第一笔(离开笔)
|
||||
last_zs_bi = zs.bi_list[-1]
|
||||
if last_zs_bi.dir == Chan_BI_DIR.UP:
|
||||
if last_zs_bi.is_sure and last_zs_bi.end_klc.high <= zs.zg or (last_zs_bi.next and last_zs_bi.next.is_sure and last_zs_bi.next.end_klc.low < zs.zd):
|
||||
leave_bi = last_zs_bi.next
|
||||
else:
|
||||
leave_bi = last_zs_bi
|
||||
else:
|
||||
if last_zs_bi.is_sure and last_zs_bi.end_klc.low >= zs.zd or (last_zs_bi.next and last_zs_bi.next.is_sure and last_zs_bi.next.end_klc.high > zs.zg):
|
||||
leave_bi = last_zs_bi.next
|
||||
else:
|
||||
leave_bi = last_zs_bi
|
||||
#print(zs.zg, zs.zd)
|
||||
if leave_bi is None or not leave_bi.is_sure:
|
||||
continue
|
||||
if (zs.dir == Chan_ZS_DIR.UP and leave_bi.dir == Chan_BI_DIR.UP and leave_bi.end_klc.high < zs.zg and leave_bi.end_klc.high > zs.zd) or (zs.dir == Chan_ZS_DIR.DOWN and leave_bi.dir == Chan_BI_DIR.DOWN and leave_bi.end_klc.low < zs.zg and leave_bi.end_klc.low > zs.zd):
|
||||
#print("--------------------", leave_bi.dir, leave_bi.end_klc.high, leave_bi.end_klc.low, zs.zg, zs.zd)
|
||||
leave_bi = leave_bi.next
|
||||
# 三类买点:向上离开中枢后回拉不破 zg
|
||||
#print("Leave bi:", leave_bi.start_time, leave_bi.end_time, leave_bi.dir, leave_bi.is_sure, leave_bi.low, leave_bi.high)
|
||||
if leave_bi.dir == Chan_BI_DIR.UP:
|
||||
first_bsp_bi_div = self.check_bi_div(zs, leave_bi)
|
||||
# 确认一类卖点:离开断能量小于进入段能量
|
||||
if first_bsp_bi_div:
|
||||
bsp = ChanBSP(
|
||||
leave_bi, len(bsp_list),
|
||||
Chan_BSP_TYPE.S1,
|
||||
Chan_BSP_DIR.SELL,
|
||||
leave_bi.sure_time,
|
||||
zs.index+1, zs, None
|
||||
)
|
||||
leave_bi.end_klc.set_bsp_type(Chan_BSP_TYPE.S1)
|
||||
bsp_list.append(bsp)
|
||||
# 回拉笔
|
||||
pullback_bi = leave_bi.next
|
||||
#print(pullback_bi.start_klc.start_time, pullback_bi.dir, pullback_bi.is_sure, pullback_bi.low, pullback_bi.high)
|
||||
if pullback_bi and pullback_bi.is_sure and pullback_bi.dir == Chan_BI_DIR.DOWN:
|
||||
if pullback_bi.low >= zs.zg:
|
||||
# 确认三类买点:回拉笔的低点不跌回中枢
|
||||
bsp = ChanBSP(
|
||||
pullback_bi, len(bsp_list),
|
||||
Chan_BSP_TYPE.B3,
|
||||
Chan_BSP_DIR.BUY,
|
||||
pullback_bi.sure_time,
|
||||
zs.index+1, zs, None
|
||||
)
|
||||
pullback_bi.end_klc.set_bsp_type(Chan_BSP_TYPE.B3)
|
||||
bsp_list.append(bsp)
|
||||
# 二类卖点
|
||||
if first_bsp_bi_div:
|
||||
second_bsp_bi = pullback_bi.next
|
||||
if second_bsp_bi and second_bsp_bi.is_sure and second_bsp_bi.end_klc.high < leave_bi.end_klc.high:
|
||||
# 确认二类卖点:一类卖点后回拉不超过一类卖点高点
|
||||
bsp = ChanBSP(
|
||||
second_bsp_bi, len(bsp_list),
|
||||
Chan_BSP_TYPE.S2,
|
||||
Chan_BSP_DIR.SELL,
|
||||
second_bsp_bi.sure_time,
|
||||
zs.index+1, zs, None
|
||||
)
|
||||
second_bsp_bi.end_klc.set_bsp_type(Chan_BSP_TYPE.B2)
|
||||
bsp_list.append(bsp)
|
||||
# 三类卖点:向下离开中枢后反弹不破 zd
|
||||
elif leave_bi.dir == Chan_BI_DIR.DOWN:
|
||||
first_bsp_bi_div = self.check_bi_div(zs, leave_bi)
|
||||
# 确认一类买点:离开段能量小于进入段
|
||||
if first_bsp_bi_div:
|
||||
bsp = ChanBSP(
|
||||
leave_bi, len(bsp_list),
|
||||
Chan_BSP_TYPE.B1,
|
||||
Chan_BSP_DIR.BUY,
|
||||
leave_bi.sure_time,
|
||||
zs.index+1, zs, None
|
||||
)
|
||||
leave_bi.end_klc.set_bsp_type(Chan_BSP_TYPE.B1)
|
||||
bsp_list.append(bsp)
|
||||
# 反弹笔
|
||||
bounce_bi = leave_bi.next
|
||||
#print(bounce_bi.start_klc.start_time, bounce_bi.dir, bounce_bi.is_sure, bounce_bi.low, bounce_bi.high)
|
||||
if bounce_bi and bounce_bi.is_sure and bounce_bi.dir == Chan_BI_DIR.UP:
|
||||
if bounce_bi.high <= zs.zd:
|
||||
# 确认三类卖点:反弹笔的高点不回到中枢
|
||||
bsp = ChanBSP(
|
||||
bounce_bi, len(bsp_list),
|
||||
Chan_BSP_TYPE.S3,
|
||||
Chan_BSP_DIR.SELL,
|
||||
bounce_bi.sure_time,
|
||||
zs.index+1, zs, None
|
||||
)
|
||||
bounce_bi.end_klc.set_bsp_type(Chan_BSP_TYPE.S3)
|
||||
bsp_list.append(bsp)
|
||||
# 二类卖点
|
||||
if first_bsp_bi_div:
|
||||
second_bsp_bi = bounce_bi.next
|
||||
if second_bsp_bi and second_bsp_bi.is_sure and second_bsp_bi.end_klc.low > leave_bi.end_klc.low:
|
||||
# 确认二类买点:一类买点后回拉不超过一类卖点高点
|
||||
bsp = ChanBSP(
|
||||
second_bsp_bi, len(bsp_list),
|
||||
Chan_BSP_TYPE.B2,
|
||||
Chan_BSP_DIR.BUY,
|
||||
second_bsp_bi.sure_time,
|
||||
zs.index+1, zs, None
|
||||
)
|
||||
second_bsp_bi.end_klc.set_bsp_type(Chan_BSP_TYPE.B2)
|
||||
bsp_list.append(bsp)
|
||||
return bsp_list
|
||||
|
||||
def check_bi_div(self, zs, leave_bi):
|
||||
enter_bi = zs.bi_list[0].pre
|
||||
macdhist_div = 0
|
||||
if enter_bi and enter_bi.dir == leave_bi.dir:
|
||||
macdhist_div = abs(leave_bi.macd_hist) - abs(enter_bi.macd_hist)
|
||||
#print(enter_bi.end_time, leave_bi.end_time, macdhist_div < 0)
|
||||
return macdhist_div < 0
|
||||
|
||||
def find_first_bsp(self, bi_list, bi_zs_list):
|
||||
"""
|
||||
笔中枢的一类买卖点识别
|
||||
|
||||
一类买点:下跌趋势中,最后一个中枢完成后,向下离开中枢的笔创新低,
|
||||
但该笔与进入中枢前的最后一笔下跌形成底背驰(力度减弱),
|
||||
即趋势力竭的转折点。
|
||||
一类卖点:上涨趋势中,最后一个中枢完成后,向上离开中枢的笔创新高,
|
||||
但该笔与进入中枢前的最后一笔上涨形成顶背驰(力度减弱),
|
||||
即趋势力竭的转折点。
|
||||
|
||||
简化判断:中枢形成后,离开中枢的笔(突破笔)本身即为一类买卖点的触发笔。
|
||||
|
||||
参数:
|
||||
bi_list: 笔列表
|
||||
bi_zs_list: 笔中枢列表(扁平列表,每个元素是一个中枢对象)
|
||||
|
||||
返回:
|
||||
bsp_list: ChanBSP 列表,包含所有识别到的一类买卖点
|
||||
"""
|
||||
bsp_list = []
|
||||
if len(bi_list) < 4 or len(bi_zs_list) == 0:
|
||||
return bsp_list
|
||||
|
||||
for zs in bi_zs_list:
|
||||
if not zs.is_sure or len(zs.bi_list) < 3:
|
||||
continue
|
||||
|
||||
# 找到中枢的最后一笔
|
||||
last_zs_bi = zs.bi_list[-1]
|
||||
|
||||
# 确定离开笔:中枢最后一笔之后的第一笔
|
||||
if last_zs_bi.dir == Chan_BI_DIR.UP:
|
||||
# 中枢最后一笔向上,如果没有真正离开中枢,取下一笔
|
||||
if last_zs_bi.is_sure and last_zs_bi.end_klc.high <= zs.zg:
|
||||
leave_bi = last_zs_bi.next
|
||||
else:
|
||||
leave_bi = last_zs_bi
|
||||
else:
|
||||
# 中枢最后一笔向下,如果没有真正离开中枢,取下一笔
|
||||
if last_zs_bi.is_sure and last_zs_bi.end_klc.low >= zs.zd:
|
||||
leave_bi = last_zs_bi.next
|
||||
else:
|
||||
leave_bi = last_zs_bi
|
||||
|
||||
if leave_bi is None or not leave_bi.is_sure:
|
||||
continue
|
||||
|
||||
# 一类买点:向下离开中枢(leave_bi向下,低点 < zd),趋势力竭
|
||||
if leave_bi.dir == Chan_BI_DIR.DOWN and leave_bi.low < zs.zd:
|
||||
# 背驰判断:比较离开笔与中枢内最后一笔同向笔的MACD柱状累积面积
|
||||
# 缠论原文:两段同向走势的MACD柱状面积比较,面积缩小即为背驰
|
||||
compare_bi = None
|
||||
for bi in reversed(zs.bi_list):
|
||||
if bi.dir == Chan_BI_DIR.DOWN and bi is not leave_bi:
|
||||
compare_bi = bi
|
||||
break
|
||||
|
||||
is_divergence = False
|
||||
if compare_bi:
|
||||
# 笔的macd_hist是该笔内所有KLU的macdhist累积面积
|
||||
leave_macd_area = abs(leave_bi.macd_hist)
|
||||
compare_macd_area = abs(compare_bi.macd_hist)
|
||||
|
||||
# 价格创新低但MACD面积缩小 = 底背驰
|
||||
if leave_bi.low <= compare_bi.low and leave_macd_area < compare_macd_area:
|
||||
is_divergence = True
|
||||
# 即使没创新低,MACD面积明显缩小也算背驰
|
||||
elif leave_macd_area < compare_macd_area * 0.5:
|
||||
is_divergence = True
|
||||
else:
|
||||
# 没有对比笔时,只要离开中枢就算一类买点
|
||||
is_divergence = True
|
||||
|
||||
if is_divergence:
|
||||
bsp = ChanBSP(
|
||||
leave_bi, len(bsp_list),
|
||||
Chan_BSP_TYPE.T1,
|
||||
Chan_BSP_DIR.BUY,
|
||||
leave_bi.sure_time,
|
||||
1, zs, None
|
||||
)
|
||||
bsp_list.append(bsp)
|
||||
|
||||
# 一类卖点:向上离开中枢(leave_bi向上,高点 > zg),趋势力竭
|
||||
elif leave_bi.dir == Chan_BI_DIR.UP and leave_bi.high > zs.zg:
|
||||
# 背驰判断:比较离开笔与中枢内最后一笔同向笔的MACD柱状累积面积
|
||||
compare_bi = None
|
||||
for bi in reversed(zs.bi_list):
|
||||
if bi.dir == Chan_BI_DIR.UP and bi is not leave_bi:
|
||||
compare_bi = bi
|
||||
break
|
||||
|
||||
is_divergence = False
|
||||
if compare_bi:
|
||||
leave_macd_area = abs(leave_bi.macd_hist)
|
||||
compare_macd_area = abs(compare_bi.macd_hist)
|
||||
|
||||
# 价格创新高但MACD面积缩小 = 顶背驰
|
||||
if leave_bi.high >= compare_bi.high and leave_macd_area < compare_macd_area:
|
||||
is_divergence = True
|
||||
# 即使没创新高,MACD面积明显缩小也算背驰
|
||||
elif leave_macd_area < compare_macd_area * 0.5:
|
||||
is_divergence = True
|
||||
else:
|
||||
is_divergence = True
|
||||
|
||||
if is_divergence:
|
||||
bsp = ChanBSP(
|
||||
leave_bi, len(bsp_list),
|
||||
Chan_BSP_TYPE.T1,
|
||||
Chan_BSP_DIR.SELL,
|
||||
leave_bi.sure_time,
|
||||
1, zs, None
|
||||
)
|
||||
bsp_list.append(bsp)
|
||||
|
||||
return bsp_list
|
||||
|
||||
|
||||
def find_second_bsp(self, bi_list, first_bsp_list):
|
||||
"""
|
||||
笔中枢的二类买卖点识别
|
||||
|
||||
二类买点:一类买点出现后,价格向上反弹一笔,再回落一笔,
|
||||
回落笔的低点不跌破一类买点的低点,确认底部成立。
|
||||
二类卖点:一类卖点出现后,价格向下回落一笔,再反弹一笔,
|
||||
反弹笔的高点不超过一类卖点的高点,确认顶部成立。
|
||||
|
||||
参数:
|
||||
bi_list: 笔列表
|
||||
first_bsp_list: 一类买卖点列表(find_first_bsp 的返回值)
|
||||
|
||||
返回:
|
||||
bsp_list: ChanBSP 列表,包含所有识别到的二类买卖点
|
||||
"""
|
||||
bsp_list = []
|
||||
if not first_bsp_list or len(bi_list) < 4:
|
||||
return bsp_list
|
||||
|
||||
for first_bsp in first_bsp_list:
|
||||
trigger_bi = first_bsp.bi # 一类买卖点的触发笔
|
||||
|
||||
if first_bsp.dir == Chan_BSP_DIR.BUY:
|
||||
# 一买之后:trigger_bi 向下 -> 反弹笔(向上) -> 回落笔(向下)
|
||||
# 回落笔的低点 > trigger_bi 的低点 => 二类买点
|
||||
bounce_bi = trigger_bi.next # 反弹笔(向上)
|
||||
if bounce_bi and bounce_bi.is_sure and bounce_bi.dir == Chan_BI_DIR.UP:
|
||||
pullback_bi = bounce_bi.next # 回落笔(向下)
|
||||
if pullback_bi and pullback_bi.is_sure and pullback_bi.dir == Chan_BI_DIR.DOWN:
|
||||
if pullback_bi.low > trigger_bi.low:
|
||||
bsp = ChanBSP(
|
||||
pullback_bi, len(bsp_list),
|
||||
Chan_BSP_TYPE.T2,
|
||||
Chan_BSP_DIR.BUY,
|
||||
pullback_bi.sure_time,
|
||||
1, first_bsp.zs, None
|
||||
)
|
||||
bsp_list.append(bsp)
|
||||
|
||||
elif first_bsp.dir == Chan_BSP_DIR.SELL:
|
||||
# 一卖之后:trigger_bi 向上 -> 回落笔(向下) -> 反弹笔(向上)
|
||||
# 反弹笔的高点 < trigger_bi 的高点 => 二类卖点
|
||||
drop_bi = trigger_bi.next # 回落笔(向下)
|
||||
if drop_bi and drop_bi.is_sure and drop_bi.dir == Chan_BI_DIR.DOWN:
|
||||
bounce_bi = drop_bi.next # 反弹笔(向上)
|
||||
if bounce_bi and bounce_bi.is_sure and bounce_bi.dir == Chan_BI_DIR.UP:
|
||||
if bounce_bi.high < trigger_bi.high:
|
||||
bsp = ChanBSP(
|
||||
bounce_bi, len(bsp_list),
|
||||
Chan_BSP_TYPE.T2,
|
||||
Chan_BSP_DIR.SELL,
|
||||
bounce_bi.sure_time,
|
||||
1, first_bsp.zs, None
|
||||
)
|
||||
bsp_list.append(bsp)
|
||||
|
||||
return bsp_list
|
||||
@@ -0,0 +1,148 @@
|
||||
"""第四类买卖点(B4/S4)接入 TF_DF。
|
||||
|
||||
判定逻辑全在 chanlun/analysis/fast_bsp.py,这里只负责把引擎的中枢/K线喂进去,
|
||||
再把结果包成 ChanFastBSP。
|
||||
|
||||
刻意不在 init_TF_DF 里默认计算:现有构造路径的开销保持不变,由调用方按需触发。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from chanlun.analysis.fast_bsp import (
|
||||
add_zone_ladder,
|
||||
attach_htf_agree,
|
||||
attach_zone_ladder,
|
||||
ensure_timestamp,
|
||||
find_fast_bsp3,
|
||||
htf_fx_timeline,
|
||||
zones_from_zs_list,
|
||||
)
|
||||
from chanlun.core.ChanEnum import Chan_BSP_DIR
|
||||
from chanlun.core.ChanFastBSP import ChanFastBSP
|
||||
|
||||
# 区间套配对:小级别出中枢与买卖点,大级别只出分型定方向。
|
||||
# 取值来自 research/HANDOFF.md §1.5,是回测里实际用过的组合。
|
||||
FAST_BSP_HTF_PAIR = {
|
||||
'1m': '5m',
|
||||
'5m': '30m',
|
||||
'15m': '1h',
|
||||
'30m': '2h',
|
||||
}
|
||||
|
||||
# 未列入配对表的周期回落到这个倍数
|
||||
FAST_BSP_HTF_FALLBACK_RATIO = 4
|
||||
|
||||
_TF_UNIT_MINUTES = {'m': 1, 'h': 60, 'd': 1440, 'w': 10080}
|
||||
|
||||
|
||||
def timeframe_minutes(tf: str) -> int | None:
|
||||
"""'30m' -> 30,'2h' -> 120。无法解析时返回 None。"""
|
||||
if not tf:
|
||||
return None
|
||||
m = re.fullmatch(r'(\d+)\s*([mhdw])', str(tf).strip().lower())
|
||||
if not m:
|
||||
return None
|
||||
return int(m.group(1)) * _TF_UNIT_MINUTES[m.group(2)]
|
||||
|
||||
|
||||
def resolve_htf(tf: str) -> tuple[str, int] | None:
|
||||
"""给小级别找配套的大级别,返回 (标签, 分钟数)。"""
|
||||
minutes = timeframe_minutes(tf)
|
||||
if minutes is None:
|
||||
return None
|
||||
paired = FAST_BSP_HTF_PAIR.get(str(tf).strip().lower())
|
||||
if paired:
|
||||
return paired, timeframe_minutes(paired)
|
||||
return f'{minutes * FAST_BSP_HTF_FALLBACK_RATIO}m', minutes * FAST_BSP_HTF_FALLBACK_RATIO
|
||||
|
||||
|
||||
class FastBspBuilderMixin:
|
||||
def build_fast_bsp_htf(self, df, timeframe=None):
|
||||
"""对同一份 df 重采样得到大级别,不额外拉数据。
|
||||
|
||||
大级别只用来取分型方向,样本太少就没有过滤意义,故重采样后不足 60 根时放弃。
|
||||
"""
|
||||
tf = timeframe or getattr(self, 'timeframe', None)
|
||||
htf = resolve_htf(tf)
|
||||
ltf_minutes = timeframe_minutes(tf)
|
||||
if htf is None or not ltf_minutes:
|
||||
return None
|
||||
label, minutes = htf
|
||||
if not minutes or len(df) * ltf_minutes < minutes * 60:
|
||||
return None
|
||||
try:
|
||||
from chanlun.pipeline.timeframe import TF_DF
|
||||
|
||||
return TF_DF(df, minutes, label)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def cal_fast_bsp(self, df=None, bi_zs_list=None, htf_chan=None, with_htf=True,
|
||||
timeframe=None, **kw):
|
||||
"""算第四类买卖点,返回 ChanFastBSP 列表。
|
||||
|
||||
bi_zs_list 传入已算好的 pure 笔中枢可免去重复计算。
|
||||
with_htf=False 时跳过大级别构建,只留 ladder_ok 这一个过滤标志。
|
||||
kw 透传给 find_fast_bsp3(scan / pullback_win / tol / require_touch 等)。
|
||||
"""
|
||||
src = df if df is not None else getattr(self, 'dataframe', None)
|
||||
if src is None or len(src) == 0:
|
||||
self.fast_bsp_list = []
|
||||
return self.fast_bsp_list
|
||||
|
||||
src = ensure_timestamp(src)
|
||||
if bi_zs_list is None:
|
||||
bi_zs_list = getattr(self, 'bi_zs_list', None)
|
||||
if not bi_zs_list:
|
||||
bi_zs_list = self.cal_bi_zs_list_pure(self.cal_bi_list(self.get_klc_list(self.cal_kl_data(src))))
|
||||
|
||||
zones = zones_from_zs_list(bi_zs_list, src)
|
||||
if zones.empty:
|
||||
self.fast_bsp_list = []
|
||||
return self.fast_bsp_list
|
||||
|
||||
zones = add_zone_ladder(zones)
|
||||
sig = find_fast_bsp3(src, zones, **kw)
|
||||
if sig.empty:
|
||||
self.fast_bsp_list = []
|
||||
return self.fast_bsp_list
|
||||
|
||||
sig = attach_zone_ladder(sig, zones)
|
||||
|
||||
if with_htf:
|
||||
if htf_chan is None:
|
||||
htf_chan = self.build_fast_bsp_htf(src, timeframe)
|
||||
sig = attach_htf_agree(sig, src, htf_fx_timeline(htf_chan) if htf_chan is not None else pd.DataFrame())
|
||||
else:
|
||||
sig['htf_dir'] = None
|
||||
sig['htf_agree'] = None
|
||||
|
||||
times = src['date'].dt.strftime('%Y-%m-%d %H:%M:%S').to_numpy()
|
||||
close = src['close'].to_numpy(dtype=float)
|
||||
|
||||
out = []
|
||||
for r in sig.itertuples(index=False):
|
||||
entry_idx = int(r.entry_idx)
|
||||
agree = getattr(r, 'htf_agree', None)
|
||||
htf_dir = getattr(r, 'htf_dir', None)
|
||||
out.append(ChanFastBSP(
|
||||
time=times[entry_idx],
|
||||
price=close[entry_idx],
|
||||
ddir=Chan_BSP_DIR.BUY if r.direction == 1 else Chan_BSP_DIR.SELL,
|
||||
entry_idx=entry_idx,
|
||||
bo_time=times[int(r.bo_idx)],
|
||||
pb_time=times[int(r.pb_idx)] if r.pb_idx == r.pb_idx else None,
|
||||
lag=r.lag,
|
||||
depth=r.depth,
|
||||
zg=r.zg,
|
||||
zd=r.zd,
|
||||
occ=r.occ,
|
||||
htf_dir=None if htf_dir is None or htf_dir != htf_dir else int(htf_dir),
|
||||
htf_agree=None if agree is None or agree != agree else bool(agree),
|
||||
ladder_ok=bool(r.ladder_ok),
|
||||
))
|
||||
self.fast_bsp_list = out
|
||||
return out
|
||||
@@ -0,0 +1,171 @@
|
||||
"""增量更新:新K只追加 KLU/KLC,笔与笔中枢在当前列表上重算。
|
||||
|
||||
不改 init_TF_DF 的整段语义。笔必须整表重扫:最后一笔 is_sure 允许收回
|
||||
(OWN_CHAN_ZS_001 上 60 天出现 7 次)。笔中枢用 cal_bi_zs_list_pure。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pandas as pd
|
||||
from pandas import DataFrame
|
||||
from chanlun.pipeline.resample import resample_to_interval
|
||||
|
||||
from chanlun.core.ChanEnum import Chan_FX_TYPE, Chan_KLC_FX, Chan_KLC_STATE
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
|
||||
|
||||
class IncrementalBuilderMixin:
|
||||
def init_stream(self, df, interval=1, timeframe=None):
|
||||
"""用历史K线初始化流式状态,之后用 append_bar / replace_last_bar。"""
|
||||
if df is None or df.empty:
|
||||
raise ValueError("DataFrame for stream is empty.")
|
||||
if "date" not in df.columns:
|
||||
raise ValueError(f"DataFrame missing 'date' column. Columns: {df.columns.tolist()}")
|
||||
self.timeframe = timeframe
|
||||
self.interval = interval
|
||||
if interval == 1:
|
||||
self.dataframe = df.copy()
|
||||
else:
|
||||
self.dataframe = resample_to_interval(df, interval)
|
||||
self.dataframe = self.add_indicators(self.dataframe)
|
||||
self.klu_list = []
|
||||
self.klc_list = []
|
||||
self.bi_list = []
|
||||
self.bi_zs_list = []
|
||||
self.seg_list = []
|
||||
self.zs_list = []
|
||||
self.bsp_list = []
|
||||
self.klc_fx_list = []
|
||||
self.big_zs_list = []
|
||||
self._klc_feed_last_klu = None
|
||||
for i in range(len(self.dataframe)):
|
||||
self._append_row_at(i, rebuild=False)
|
||||
self.rebuild_bi_zs()
|
||||
return self
|
||||
|
||||
def append_bar(self, row):
|
||||
"""追加一根已收盘K线。同一时间戳则改为替换最后一根。"""
|
||||
self._ensure_stream_state()
|
||||
item = self._normalize_row(row)
|
||||
if self.klu_list and self.klu_list[-1].time == self._row_time_str(item):
|
||||
return self.replace_last_bar(item)
|
||||
self._append_item_to_dataframe(item)
|
||||
self.dataframe = self.add_indicators(self.dataframe)
|
||||
self._append_row_at(len(self.dataframe) - 1, rebuild=True)
|
||||
return self
|
||||
|
||||
def replace_last_bar(self, row):
|
||||
"""更新最后一根K(未完成K线走新OHLC)。包含关系从 KLU 列表重放。"""
|
||||
self._ensure_stream_state()
|
||||
if not self.klu_list:
|
||||
return self.append_bar(row)
|
||||
item = self._normalize_row(row)
|
||||
idx = self.dataframe.index[-1]
|
||||
for key, val in item.items():
|
||||
self.dataframe.at[idx, key] = val
|
||||
self.dataframe = self.add_indicators(self.dataframe)
|
||||
self._apply_item_to_klu(self.klu_list[-1], self.dataframe.iloc[-1])
|
||||
self._rebuild_klc_from_klu()
|
||||
self.rebuild_bi_zs()
|
||||
return self
|
||||
|
||||
def rebuild_bi_zs(self):
|
||||
"""在当前 KLC 上重算笔 + cal_bi_zs_list_pure。会先清分型标记。"""
|
||||
self._reset_klc_bi_marks(self.klc_list)
|
||||
self.bi_list = self.cal_bi_list(self.klc_list) if self.klc_list else []
|
||||
self.bi_zs_list = self.cal_bi_zs_list_pure(self.bi_list) if self.bi_list else []
|
||||
return self.bi_zs_list
|
||||
|
||||
def _ensure_stream_state(self):
|
||||
if not hasattr(self, "klu_list") or self.klu_list is None:
|
||||
self.klu_list = []
|
||||
if not hasattr(self, "klc_list") or self.klc_list is None:
|
||||
self.klc_list = []
|
||||
if not hasattr(self, "dataframe") or self.dataframe is None:
|
||||
self.dataframe = DataFrame(
|
||||
columns=["date", "open", "high", "low", "close", "volume"]
|
||||
)
|
||||
if not hasattr(self, "_klc_feed_last_klu"):
|
||||
self._klc_feed_last_klu = self.klu_list[-1] if self.klu_list else None
|
||||
if not hasattr(self, "bi_zs_list"):
|
||||
self.bi_zs_list = []
|
||||
|
||||
def _rebuild_klc_from_klu(self):
|
||||
self.klc_list = []
|
||||
last_klu = None
|
||||
for klu in self.klu_list:
|
||||
self._push_klu_into_klc_list(self.klc_list, klu, last_klu)
|
||||
last_klu = klu
|
||||
self._klc_feed_last_klu = last_klu
|
||||
|
||||
def _append_row_at(self, idx, rebuild=True):
|
||||
item = self.dataframe.iloc[idx]
|
||||
klu = self._klu_from_item(item, idx)
|
||||
if self.klu_list:
|
||||
self.klu_list[-1].set_next(klu)
|
||||
klu.set_pre(self.klu_list[-1])
|
||||
self._push_klu_into_klc_list(self.klc_list, klu, self._klc_feed_last_klu)
|
||||
self._klc_feed_last_klu = klu
|
||||
self.klu_list.append(klu)
|
||||
if rebuild:
|
||||
self.rebuild_bi_zs()
|
||||
|
||||
def _klu_from_item(self, item, idx):
|
||||
klu = ChanKLU(
|
||||
self._item_time_str(item),
|
||||
item["open"],
|
||||
item["high"],
|
||||
item["low"],
|
||||
item["close"],
|
||||
item["volume"],
|
||||
)
|
||||
klu.set_idx(idx)
|
||||
if not hasattr(klu, "ema13"):
|
||||
klu.ema13 = 0
|
||||
if "macd" in item:
|
||||
klu.set_indicators(item)
|
||||
return klu
|
||||
|
||||
def _apply_item_to_klu(self, klu, item):
|
||||
klu.time = self._item_time_str(item)
|
||||
klu.open = item["open"]
|
||||
klu.high = item["high"]
|
||||
klu.low = item["low"]
|
||||
klu.close = item["close"]
|
||||
klu.volume = item["volume"]
|
||||
klu.range = klu.high - klu.low
|
||||
klu.body = abs(klu.close - klu.open)
|
||||
if "macd" in item:
|
||||
klu.set_indicators(item)
|
||||
|
||||
def _reset_klc_bi_marks(self, klc_list):
|
||||
for klc in klc_list:
|
||||
klc.fx = Chan_FX_TYPE.UNKNOWN
|
||||
klc.klc_fx_type = Chan_KLC_FX.UNKNOWN
|
||||
klc.klc_state = Chan_KLC_STATE.UNKNOWN
|
||||
klc.bi = None
|
||||
klc.fx_confirmed = False
|
||||
|
||||
def _item_time_str(self, item):
|
||||
date = item["date"]
|
||||
if hasattr(date, "to_pydatetime"):
|
||||
date = date.to_pydatetime()
|
||||
if isinstance(date, datetime):
|
||||
return date.strftime("%Y-%m-%d %H:%M:%S")
|
||||
return str(date)
|
||||
|
||||
def _row_time_str(self, item):
|
||||
return self._item_time_str(item)
|
||||
|
||||
def _normalize_row(self, row):
|
||||
if isinstance(row, pd.Series):
|
||||
return row
|
||||
return pd.Series(row)
|
||||
|
||||
def _append_item_to_dataframe(self, item):
|
||||
row_df = DataFrame([item])
|
||||
if self.dataframe is None or self.dataframe.empty:
|
||||
self.dataframe = row_df
|
||||
else:
|
||||
self.dataframe = pd.concat([self.dataframe, row_df], ignore_index=True)
|
||||
@@ -0,0 +1,141 @@
|
||||
"""TF_DF builder mixin — 由 split_tfdf_builders 自动生成,逻辑与原 TF_DF 一致。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from chanlun.indicators import ta
|
||||
from pandas import DataFrame
|
||||
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
from chanlun.core.ChanBIZS import ChanBIZS
|
||||
from chanlun.core.ChanBSP import ChanBSP
|
||||
from chanlun.core.ChanEnum import (
|
||||
Chan_BI_DIR,
|
||||
Chan_BSP_DIR,
|
||||
Chan_BSP_TYPE,
|
||||
Chan_FX_TYPE,
|
||||
Chan_K_DIR,
|
||||
Chan_KLC_FX,
|
||||
Chan_KLC_STATE,
|
||||
Chan_KLINE_DIR,
|
||||
Chan_KLU_PATTERN,
|
||||
Chan_PRICE_TREND,
|
||||
Chan_SEG_DIR,
|
||||
Chan_ZS_DIR,
|
||||
)
|
||||
from chanlun.core.ChanKLC import ChanKLC
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
from chanlun.core.ChanSBI import ChanSBI
|
||||
from chanlun.core.ChanSEG import ChanSEG
|
||||
from chanlun.core.ChanZS import ChanZS, ChanZS_Big
|
||||
from chanlun.indicators.ChanMACD import ChanMACD
|
||||
|
||||
|
||||
class IndicatorsBuilderMixin:
|
||||
def get_ema52(self, index=-1):
|
||||
if self.klu_list:
|
||||
ema52_value = self.klu_list[index].ema52
|
||||
# 处理NaN值
|
||||
if pd.isna(ema52_value) or ema52_value is None:
|
||||
return None
|
||||
return float(ema52_value)
|
||||
return None
|
||||
|
||||
def get_ema24(self, index=-1):
|
||||
if self.klu_list:
|
||||
ema24_value = self.klu_list[index].ema24
|
||||
# 处理NaN值
|
||||
if pd.isna(ema24_value) or ema24_value is None:
|
||||
return None
|
||||
return float(ema24_value)
|
||||
return None
|
||||
|
||||
def add_indicators(self, df):
|
||||
"""算指标并一次性挂到 df 上。
|
||||
|
||||
这里不逐列 `df['x'] = ...`:那样每一列都触发一次 BlockManager 插入,
|
||||
30 多列的开销比全部 TA 计算本身还大(2001 行实测 TA 合计 2.5ms,
|
||||
逐列赋值 3.6ms)。增量路径每根都要走一遍,这笔开销是白付的。
|
||||
"""
|
||||
fast = 12
|
||||
slow = 26
|
||||
period = 9
|
||||
macd = ta.MACD(df, fastperiod=fast, slowperiod=slow, signalperiod=period)
|
||||
bb365 = ta.BBANDS(df, timeperiod=365, nbdevup=3.0, nbdevdn=3.0, matype=0)
|
||||
bb120 = ta.BBANDS(df, timeperiod=120, nbdevup=3.0, nbdevdn=3.0, matype=0)
|
||||
bb30 = ta.BBANDS(df, timeperiod=41, nbdevup=2.3, nbdevdn=2.3, matype=0)
|
||||
bb302 = ta.BBANDS(df, timeperiod=41, nbdevup=2.0, nbdevdn=2.0, matype=0)
|
||||
bb30 = ta.BBANDS(df, timeperiod=20, nbdevup=2.0, nbdevdn=2.0, matype=0)
|
||||
bb302 = ta.BBANDS(df, timeperiod=20, nbdevup=2.0, nbdevdn=2.0, matype=0)
|
||||
bb2633 = ta.BBANDS(df, timeperiod=26, nbdevup=3.0, nbdevdn=3.0, matype=0)
|
||||
# 计算布林带中轨(移动平均线)
|
||||
bb30_middle = ta.SMA(df, timeperiod=90)
|
||||
|
||||
# 手动计算布林带 %B 指标 (BBP)
|
||||
# %B = (Price - Lower Band) / (Upper Band - Lower Band)
|
||||
bbp365 = (df['close'] - bb365['lowerband']) / (bb365['upperband'] - bb365['lowerband'])
|
||||
bbp120 = (df['close'] - bb120['lowerband']) / (bb120['upperband'] - bb120['lowerband'])
|
||||
bbp30 = (df['close'] - bb30['lowerband']) / (bb30['upperband'] - bb30['lowerband'])
|
||||
bbp302 = (df['close'] - bb302['lowerband']) / (bb302['upperband'] - bb302['lowerband'])
|
||||
bbp2633 = (df['close'] - bb2633['lowerband']) / (bb2633['upperband'] - bb2633['lowerband'])
|
||||
cols = {
|
||||
'bb2633upper': bb2633['upperband'],
|
||||
'bb2633lower': bb2633['lowerband'],
|
||||
'bbp2633': bbp2633,
|
||||
'bb2633middle': bb2633['middleband'],
|
||||
'atr': ta.ATR(df, timeperiod=14),
|
||||
'bbup365': bb365['upperband'],
|
||||
'bblow365': bb365['lowerband'],
|
||||
'bbp365': bbp365,
|
||||
'bbup120': bb120['upperband'],
|
||||
'bblow120': bb120['lowerband'],
|
||||
'bbp120': bbp120,
|
||||
'bbup30': bb30['upperband'],
|
||||
'bblow30': bb30['lowerband'],
|
||||
'bbmiddle30': bb30_middle,
|
||||
'bbp30': bbp30,
|
||||
'bbup302': bb302['upperband'],
|
||||
'bblow302': bb302['lowerband'],
|
||||
'bbp302': bbp302,
|
||||
'macd': macd['macd'],
|
||||
'macdsignal': macd['macdsignal'],
|
||||
'macdhist': macd['macdhist'],
|
||||
}
|
||||
for _p, _n in ((5, 'ema5'), (10, 'ema10'), (24, 'ema24'), (52, 'ema52'),
|
||||
(104, 'ema104'), (156, 'ema156'), (208, 'ema208'),
|
||||
(26, 'ema26'), (13, 'ema13'), (7, 'ema7')):
|
||||
cols[_n] = ta.EMA(df, timeperiod=_p)
|
||||
cols['rsi'] = ta.RSI(df, timeperiod=14)
|
||||
cols['volume_ratio'] = self.cal_volume_ratio(df)
|
||||
|
||||
# 重复调用(增量路径每根都会)时先摘掉旧列,否则 concat 出重名列。
|
||||
# 摘掉再接回末尾,列序与逐列覆盖的结果一致。
|
||||
new = pd.DataFrame(cols, index=df.index)
|
||||
dup = [c for c in new.columns if c in df.columns]
|
||||
if dup:
|
||||
df = df.drop(columns=dup)
|
||||
return pd.concat([df, new], axis=1)
|
||||
|
||||
def get_ema_state(self, dataframe):
|
||||
klu_list = self.get_klu_list(dataframe)
|
||||
klc_list = self.get_klc_list(klu_list)
|
||||
bi_list = self.cal_bi_list(klc_list)
|
||||
klu_state_list = []
|
||||
for klu in klu_list:
|
||||
if klu.near0_return == 1:
|
||||
klu_state_list.append("1")
|
||||
elif klu.near0_return == 9:
|
||||
klu_state_list.append("-1")
|
||||
elif klu.candle_dir == Chan_K_DIR.BULL:
|
||||
klu_state_list.append("2")
|
||||
elif klu.candle_dir == Chan_K_DIR.BEAR:
|
||||
klu_state_list.append("-2")
|
||||
else:
|
||||
klu_state_list.append("0")
|
||||
return klu_state_list
|
||||
|
||||
def get_decimal(self, value):
|
||||
return Decimal("{:.2f}".format(value))
|
||||
@@ -0,0 +1,573 @@
|
||||
"""TF_DF builder mixin — 由 split_tfdf_builders 自动生成,逻辑与原 TF_DF 一致。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from pandas import DataFrame
|
||||
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
from chanlun.core.ChanBIZS import ChanBIZS
|
||||
from chanlun.core.ChanBSP import ChanBSP
|
||||
from chanlun.core.ChanEnum import (
|
||||
Chan_BI_DIR,
|
||||
Chan_BSP_DIR,
|
||||
Chan_BSP_TYPE,
|
||||
Chan_FX_TYPE,
|
||||
Chan_K_DIR,
|
||||
Chan_KLC_FX,
|
||||
Chan_KLC_STATE,
|
||||
Chan_KLINE_DIR,
|
||||
Chan_KLU_PATTERN,
|
||||
Chan_PRICE_TREND,
|
||||
Chan_SEG_DIR,
|
||||
Chan_ZS_DIR,
|
||||
)
|
||||
from chanlun.core.ChanKLC import ChanKLC
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
from chanlun.core.ChanSBI import ChanSBI
|
||||
from chanlun.core.ChanSEG import ChanSEG
|
||||
from chanlun.core.ChanZS import ChanZS, ChanZS_Big
|
||||
from chanlun.indicators.ChanMACD import ChanMACD
|
||||
|
||||
|
||||
class KlineBuilderMixin:
|
||||
def get_klu_state(self, dataframe):
|
||||
klc_list = self.get_klc_list(self.get_klu_list(dataframe))
|
||||
bi_list = self.cal_bi_list(klc_list)
|
||||
klu_state_list = []
|
||||
klc_index = 0
|
||||
for index in range(0, len(dataframe)):
|
||||
if klc_index == len(klc_list):
|
||||
klc_index = len(klc_list) - 1
|
||||
klc = klc_list[klc_index]
|
||||
if klc.end_klu and klc.end_klu.idx == index:
|
||||
if klc.klc_state == Chan_KLC_STATE.S10:
|
||||
klu_state_list.append("10")
|
||||
#print(klc.end_time, klc.klc_fx_type)
|
||||
elif klc.klc_state == Chan_KLC_STATE.S_10:
|
||||
klu_state_list.append("-10")
|
||||
#print(klc.end_time, klc.klc_fx_type)
|
||||
elif klc.klc_state == Chan_KLC_STATE.S11:
|
||||
klu_state_list.append("11")
|
||||
#print(klc.end_time, klc.klc_fx_type)
|
||||
elif klc.klc_state == Chan_KLC_STATE.S_11:
|
||||
klu_state_list.append("-11")
|
||||
#print(klc.end_time, klc.klc_fx_type)
|
||||
else:
|
||||
klu_state_list.append("00")
|
||||
klc_index += 1
|
||||
else:
|
||||
klu_state_list.append("00")
|
||||
print(klu_state_list[:20])
|
||||
return klu_state_list
|
||||
|
||||
|
||||
def check_fx1(self, klc):
|
||||
if klc.pre and klc.next:
|
||||
if klc.high > klc.pre.high and klc.high > klc.next.high and klc.low > klc.pre.low and klc.low > klc.next.low:
|
||||
if klc.pre.pre and klc.next.next:
|
||||
if klc.high > klc.pre.pre.high and klc.high > klc.next.next.high:
|
||||
#if (klc.close > klc.ema52 or klc.next.close > klc.next.ema52) and klc.macd > 0:
|
||||
klc.set_fx(Chan_FX_TYPE.TOP)
|
||||
#print(klc.start_time, klc.end_time,klc.next.start_time, klc.next.end_time, klc.macd, klc.state, klc.fx, "TOP")
|
||||
return Chan_FX_TYPE.TOP
|
||||
elif klc.low < klc.pre.low and klc.low < klc.next.low and klc.high < klc.pre.high and klc.high < klc.next.high:
|
||||
#if (klc.close < klc.ema52 or klc.next.close < klc.next.ema52) and klc.macd < 0:
|
||||
if klc.pre.pre and klc.next.next:
|
||||
if klc.low < klc.pre.pre.low and klc.low < klc.next.next.low:
|
||||
klc.set_fx(Chan_FX_TYPE.BOTTOM)
|
||||
#print(klc.start_time, klc.end_time,klc.next.start_time, klc.next.end_time, klc.macd, klc.state, klc.fx, "BOTTOM")
|
||||
return Chan_FX_TYPE.BOTTOM
|
||||
return Chan_FX_TYPE.UNKNOWN
|
||||
|
||||
def check_fx(self, klc):
|
||||
# 右K未完成(仍在包含合并)时不分型:否则确认笔会随 next 扩区间被 check_*_fx 收回
|
||||
if klc.pre and klc.next and klc.next.end_klu is not None:
|
||||
if klc.high > klc.pre.high and klc.high > klc.next.high and klc.low > klc.pre.low and klc.low > klc.next.low:
|
||||
#if (klc.close > klc.ema52 or klc.next.close > klc.next.ema52) and klc.macd > 0:
|
||||
klc.set_fx(Chan_FX_TYPE.TOP)
|
||||
#print(klc.start_time, klc.end_time,klc.next.start_time, klc.next.end_time, klc.macd, klc.state, klc.fx, "TOP")
|
||||
return Chan_FX_TYPE.TOP
|
||||
elif klc.low < klc.pre.low and klc.low < klc.next.low and klc.high < klc.pre.high and klc.high < klc.next.high:
|
||||
#if (klc.close < klc.ema52 or klc.next.close < klc.next.ema52) and klc.macd < 0:
|
||||
klc.set_fx(Chan_FX_TYPE.BOTTOM)
|
||||
#print(klc.start_time, klc.end_time,klc.next.start_time, klc.next.end_time, klc.macd, klc.state, klc.fx, "BOTTOM")
|
||||
return Chan_FX_TYPE.BOTTOM
|
||||
return Chan_FX_TYPE.UNKNOWN
|
||||
|
||||
def check_fx3(self, klc):
|
||||
# 右K未完成(仍在包含合并)时不分型:否则确认笔会随 next 扩区间被 check_*_fx 收回
|
||||
if klc.pre and klc.next and klc.next.end_klu is not None:
|
||||
next_klu = klc.next.end_klu.next
|
||||
if klc.high > klc.pre.high and klc.high > klc.next.high and klc.low > klc.pre.low and klc.low > klc.next.low and klc.high > next_klu.high:
|
||||
#if (klc.close > klc.ema52 or klc.next.close > klc.next.ema52) and klc.macd > 0:
|
||||
klc.set_fx(Chan_FX_TYPE.TOP)
|
||||
#print(klc.start_time, klc.end_time,klc.next.start_time, klc.next.end_time, klc.macd, klc.state, klc.fx, "TOP")
|
||||
return Chan_FX_TYPE.TOP
|
||||
elif klc.low < klc.pre.low and klc.low < klc.next.low and klc.high < klc.pre.high and klc.high < klc.next.high and klc.low < next_klu.low:
|
||||
#if (klc.close < klc.ema52 or klc.next.close < klc.next.ema52) and klc.macd < 0:
|
||||
klc.set_fx(Chan_FX_TYPE.BOTTOM)
|
||||
#print(klc.start_time, klc.end_time,klc.next.start_time, klc.next.end_time, klc.macd, klc.state, klc.fx, "BOTTOM")
|
||||
return Chan_FX_TYPE.BOTTOM
|
||||
return Chan_FX_TYPE.UNKNOWN
|
||||
def check_fx2(self, klc):
|
||||
if klc.pre and klc.next:
|
||||
if klc.high > klc.pre.close and klc.close > klc.next.close and klc.close > klc.pre.close and klc.close > klc.next.close:
|
||||
#if (klc.close > klc.ema52 or klc.next.close > klc.next.ema52) and klc.macd > 0:
|
||||
klc.set_fx(Chan_FX_TYPE.TOP)
|
||||
#print(klc.start_time, klc.end_time,klc.next.start_time, klc.next.end_time, klc.macd, klc.state, klc.fx, "TOP")
|
||||
return Chan_FX_TYPE.TOP
|
||||
elif klc.low < klc.pre.close and klc.close < klc.next.close and klc.close < klc.pre.close and klc.close < klc.next.close:
|
||||
#if (klc.close < klc.ema52 or klc.next.close < klc.next.ema52) and klc.macd < 0:
|
||||
klc.set_fx(Chan_FX_TYPE.BOTTOM)
|
||||
#print(klc.start_time, klc.end_time,klc.next.start_time, klc.next.end_time, klc.macd, klc.state, klc.fx, "BOTTOM")
|
||||
return Chan_FX_TYPE.BOTTOM
|
||||
return Chan_FX_TYPE.UNKNOWN
|
||||
|
||||
def check_fx_pattern(self, klc):
|
||||
"""给分型前后三根 KLC 的裸 K 打 pattern 标记。
|
||||
|
||||
原本还会把 `klu.to_string()` 拼成一个字符串——那是给下面那行注释掉的
|
||||
print 用的,拼完就丢。它在 cal_bi_list 的内层,2000 根上要跑近三万次
|
||||
f-string + 六万次 enum 格式化,是纯废动作,已删。
|
||||
|
||||
`klu.pattern` 只被 cal_klu_pattern 自己的双 K / 三 K 判定读,
|
||||
不出这个模块,也不进 web 序列化。所以 lean 下整个调用可跳。
|
||||
"""
|
||||
if getattr(self, 'lean', False):
|
||||
return
|
||||
klu_list = klc.pre.klu_list + klc.klu_list + klc.next.klu_list
|
||||
self.cal_klu_pattern(klu_list)
|
||||
|
||||
def cal_volume_ratio(self, dataframe, window=10):
|
||||
"""当根量 / 前 window 根均量。前 window-1 根无基准,填 1.0。
|
||||
|
||||
原写法先 `dataframe.copy()` 再挂两列——为算一列 rolling 复制了整张
|
||||
四十列的表。直接在 Series 上算,结果逐值相同。
|
||||
"""
|
||||
vol = dataframe['volume']
|
||||
return (vol / vol.rolling(window=window).mean()).fillna(1.0).rename('volume_ratio')
|
||||
|
||||
def cal_kl_data(self, dataframe:DataFrame):
|
||||
"""按行构造 KLU 链。
|
||||
|
||||
这里刻意不用 `dataframe.iloc[i]`:那会为每一根新建一个几十列的 Series,
|
||||
随后 set_indicators 再在其上做几十次逐键查找。实测这两件事合计占 TF_DF
|
||||
构建耗时的 96%。改为先把用到的列取成 ndarray,循环里只做整数下标访问。
|
||||
"""
|
||||
n = len(dataframe)
|
||||
if n == 0:
|
||||
return []
|
||||
|
||||
times = self._format_times(dataframe['date'])
|
||||
o_a = dataframe['open'].to_numpy(dtype=float)
|
||||
h_a = dataframe['high'].to_numpy(dtype=float)
|
||||
l_a = dataframe['low'].to_numpy(dtype=float)
|
||||
c_a = dataframe['close'].to_numpy(dtype=float)
|
||||
v_a = dataframe['volume'].to_numpy(dtype=float)
|
||||
|
||||
has_ind = 'macd' in dataframe.columns
|
||||
ind_cols = {}
|
||||
if has_ind:
|
||||
for _attr, col in ChanKLU.INDICATOR_FIELDS:
|
||||
if col in dataframe.columns:
|
||||
ind_cols[col] = dataframe[col].to_numpy(dtype=float)
|
||||
|
||||
klu_list = []
|
||||
last_klu = None
|
||||
for i in range(n):
|
||||
klu = ChanKLU(times[i], o_a[i], h_a[i], l_a[i], c_a[i], v_a[i])
|
||||
klu.set_idx(i)
|
||||
klu_list.append(klu)
|
||||
if last_klu:
|
||||
last_klu.set_next(klu)
|
||||
klu.set_pre(last_klu)
|
||||
last_klu = klu
|
||||
if has_ind:
|
||||
klu.set_indicators_from(ind_cols, i)
|
||||
return klu_list
|
||||
|
||||
@staticmethod
|
||||
def _format_times(col):
|
||||
"""向量化 strftime。非 datetime 列(少见)退回逐个格式化。"""
|
||||
fmt = '%Y-%m-%d %H:%M:%S'
|
||||
try:
|
||||
return col.dt.strftime(fmt).to_numpy()
|
||||
except AttributeError:
|
||||
return np.array([d.strftime(fmt) for d in col], dtype=object)
|
||||
|
||||
def get_kl_data(self, dataframe:DataFrame):
|
||||
return self.cal_kl_data(dataframe)
|
||||
|
||||
def _push_klu_into_klc_list(self, klc_list, klu, last_klu):
|
||||
"""把一根 KLU 并入包含K线列表。与 get_klc_list 的几何规则相同。"""
|
||||
if len(klc_list) > 0:
|
||||
last_klc = klc_list[-1]
|
||||
if klu.exception:
|
||||
ddir = Chan_KLINE_DIR.DOWN
|
||||
if last_klc.high < klu.high:
|
||||
ddir = Chan_KLINE_DIR.UP
|
||||
klc = ChanKLC(klu, index=len(klc_list), ddir=ddir)
|
||||
klc.high = klu.close if klu.close > klu.open else klu.open
|
||||
klc.low = klu.open if klu.close > klu.open else klu.close
|
||||
klc_list.append(klc)
|
||||
last_klc.set_next(klc)
|
||||
klc.set_pre(last_klc)
|
||||
last_klc.set_end_klu(last_klu)
|
||||
klc.set_pre_fx()
|
||||
else:
|
||||
included = last_klc.check_klu_included(klu)
|
||||
if not included:
|
||||
ddir = Chan_KLINE_DIR.DOWN
|
||||
if last_klc.high < klu.high:
|
||||
ddir = Chan_KLINE_DIR.UP
|
||||
klc = ChanKLC(klu, index=len(klc_list), ddir=ddir)
|
||||
klc_list.append(klc)
|
||||
last_klc.set_next(klc)
|
||||
klc.set_pre(last_klc)
|
||||
last_klc.set_end_klu(last_klu)
|
||||
klc.set_pre_fx()
|
||||
else:
|
||||
last_klc.add_klu(klu)
|
||||
else:
|
||||
ddir = Chan_KLINE_DIR.UP
|
||||
if klu.open > klu.close:
|
||||
ddir = Chan_KLINE_DIR.DOWN
|
||||
klc = ChanKLC(klu, 0, ddir)
|
||||
klc_list.append(klc)
|
||||
|
||||
def get_klc_list(self, klu_list):
|
||||
klc_list = []
|
||||
# ChanMACD.__init__ 已调用 cal_macd_state,切勿再调一次(会重复堆积 seg/unittf)。
|
||||
# lean 模式跳过整套 MACD 状态机:它只服务于 bsp/背驰/web 展示,笔与中枢不依赖它。
|
||||
if getattr(self, 'lean', False):
|
||||
self._last_chan_macd = None
|
||||
else:
|
||||
macd = ChanMACD(klu_list)
|
||||
klu_list = macd.klu_list
|
||||
self._last_chan_macd = macd
|
||||
|
||||
last_klu = None
|
||||
for klu in klu_list:
|
||||
self._push_klu_into_klc_list(klc_list, klu, last_klu)
|
||||
last_klu = klu
|
||||
# cal_trend 只产出 klc.trend,而全仓只有它自己(经 prev_klcs 读自身序列
|
||||
# 状态)、一个 __str__ 和 web 的 klc_trend 图层消费它——笔与中枢不读。
|
||||
# 增量路径的 klc 其 trend 恒为 UNKNOWN 却与批量构建逐字段相同,是实证。
|
||||
# 所以 lean 下可跳;web 走非 lean,图层不受影响。
|
||||
if not getattr(self, 'lean', False):
|
||||
klc_list = self.cal_trend(klc_list)
|
||||
return klc_list
|
||||
|
||||
|
||||
def get_klu_list(self, dataframe):
|
||||
klu_list = self.get_kl_data(dataframe)
|
||||
#klu_list = self.cal_klu_pattern(klu_list)
|
||||
return klu_list
|
||||
|
||||
def cal_klu_pattern(self, klu_list):
|
||||
"""
|
||||
计算裸K的pattern - 识别反转形态
|
||||
"""
|
||||
if not klu_list or len(klu_list) < 3:
|
||||
return klu_list
|
||||
|
||||
for i, klu in enumerate(klu_list):
|
||||
# 单根K线反转模式识别
|
||||
self._detect_single_reversal_pattern(klu)
|
||||
|
||||
# 双根K线形态识别
|
||||
if i >= 1:
|
||||
self._detect_double_pattern(klu_list[i-1], klu)
|
||||
|
||||
# 三根K线形态识别
|
||||
if i >= 2:
|
||||
self._detect_triple_pattern(klu_list[i-2], klu_list[i-1], klu)
|
||||
|
||||
#if klu.pattern != Chan_KLU_PATTERN.UNKNOWN:
|
||||
#print(klu.time, klu.pattern, klu.lower_shadow_ratio, klu.upper_shadow_ratio, klu.body_ratio, klu.lower_shadow_ratio/klu.body_ratio, klu.upper_shadow_ratio/klu.body_ratio)
|
||||
return klu_list
|
||||
|
||||
|
||||
def _detect_single_reversal_pattern(self, klu):
|
||||
"""检测单根K线反转模式"""
|
||||
body = abs(klu.close - klu.open)
|
||||
upper_shadow = klu.high - max(klu.close, klu.open)
|
||||
lower_shadow = min(klu.close, klu.open) - klu.low
|
||||
total_range = klu.high - klu.low
|
||||
|
||||
# 避免除零
|
||||
if total_range == 0:
|
||||
return
|
||||
|
||||
body_ratio = body / total_range
|
||||
upper_ratio = upper_shadow / total_range
|
||||
lower_ratio = lower_shadow / total_range
|
||||
#print(klu.time, upper_ratio, lower_ratio, body_ratio, upper_ratio/body_ratio, lower_ratio/body_ratio)
|
||||
# 避免body_ratio为0时的除零错误
|
||||
if body_ratio == 0:
|
||||
return
|
||||
# 锤子线/上吊线 - 反转信号
|
||||
if lower_ratio / body_ratio >= 2:
|
||||
# 锤子线:底部反转,需要前面一段
|
||||
if klu.close > klu.open and klu.pre:
|
||||
klu.set_pattern(Chan_KLU_PATTERN.HAMMER) # 底部反转
|
||||
# 上吊线:顶部反转,需要前一根是上涨趋势
|
||||
elif klu.close < klu.open and klu.pre:
|
||||
klu.set_pattern(Chan_KLU_PATTERN.HANGING_MAN) # 顶部反转
|
||||
|
||||
# 倒锤子线/射击之星 - 反转信号
|
||||
elif upper_ratio / body_ratio >= 2:
|
||||
# 倒锤子线:底部反转,需要前一根是下跌趋势
|
||||
if klu.close > klu.open and klu.pre:
|
||||
klu.set_pattern(Chan_KLU_PATTERN.INVERTED_HAMMER) # 底部反转
|
||||
# 射击之星:顶部反转,需要前一根是上涨趋势
|
||||
elif klu.close < klu.open and klu.pre:
|
||||
klu.set_pattern(Chan_KLU_PATTERN.SHOOTING_STAR) # 顶部反转
|
||||
|
||||
# 十字星 - 反转信号
|
||||
elif body_ratio <= 0.1:
|
||||
if upper_ratio > 0.4 and lower_ratio > 0.4:
|
||||
klu.set_pattern(Chan_KLU_PATTERN.LONG_LEGGED_DOJI) # 强烈反转信号
|
||||
elif upper_ratio > 0.4 and lower_ratio <= 0.1:
|
||||
# 墓碑十字星:顶部反转,需要前一根是上涨趋势
|
||||
if klu.pre and klu.pre.close > klu.pre.open:
|
||||
klu.set_pattern(Chan_KLU_PATTERN.GRAVESTONE_DOJI) # 顶部反转
|
||||
elif lower_ratio > 0.4 and upper_ratio <= 0.1:
|
||||
# 蜻蜓十字星:底部反转,需要前一根是下跌趋势
|
||||
if klu.pre and klu.pre.close < klu.pre.open:
|
||||
klu.set_pattern(Chan_KLU_PATTERN.DRAGONFLY_DOJI) # 底部反转
|
||||
else:
|
||||
klu.set_pattern(Chan_KLU_PATTERN.DOJI) # 一般反转信号
|
||||
|
||||
|
||||
def _detect_double_pattern(self, prev_klu, curr_klu):
|
||||
"""检测两根K线形成的形态
|
||||
包括:吞没形态(看涨/看跌)、乌云盖顶、曙光初现
|
||||
"""
|
||||
# 如果前一根K线已经有形态,不再识别双K线形态
|
||||
if prev_klu.pattern != Chan_KLU_PATTERN.UNKNOWN:
|
||||
return
|
||||
|
||||
# 计算K线实体
|
||||
prev_body = abs(prev_klu.close - prev_klu.open)
|
||||
curr_body = abs(curr_klu.close - curr_klu.open)
|
||||
|
||||
# 判断K线颜色(阴阳)
|
||||
prev_bullish = prev_klu.close > prev_klu.open
|
||||
curr_bullish = curr_klu.close > curr_klu.open
|
||||
|
||||
# 检查是否存在长期趋势(至少需要5根K线的趋势)
|
||||
def check_long_trend(klu, bullish_trend=True, min_bars=5):
|
||||
"""检查是否存在长期趋势
|
||||
bullish_trend=True: 检查上涨趋势
|
||||
bullish_trend=False: 检查下跌趋势
|
||||
min_bars: 最少需要多少根K线形成趋势
|
||||
"""
|
||||
if not klu or not klu.pre:
|
||||
return False
|
||||
return True
|
||||
|
||||
# 使用EMA指标判断长期趋势
|
||||
if klu.ema52 > 0:
|
||||
if bullish_trend and klu.close < klu.ema52:
|
||||
return False
|
||||
if not bullish_trend and klu.close > klu.ema52:
|
||||
return False
|
||||
|
||||
# 检查连续的K线方向
|
||||
count = 0
|
||||
current = klu.pre
|
||||
|
||||
while current and count < min_bars:
|
||||
if not current.pre:
|
||||
break
|
||||
|
||||
if bullish_trend:
|
||||
# 上涨趋势:当前收盘价高于前一根收盘价
|
||||
if current.close <= current.pre.close:
|
||||
break
|
||||
else:
|
||||
# 下跌趋势:当前收盘价低于前一根收盘价
|
||||
if current.close >= current.pre.close:
|
||||
break
|
||||
|
||||
count += 1
|
||||
current = current.pre
|
||||
|
||||
return count >= min_bars
|
||||
|
||||
# 1. 看涨吞没形态:前阴后阳,后者完全吞没前者
|
||||
# 要求前面有明显的下跌趋势
|
||||
if not prev_bullish and curr_bullish and \
|
||||
abs(curr_klu.open - prev_klu.close) < 10 and \
|
||||
curr_klu.close > prev_klu.open and \
|
||||
check_long_trend(prev_klu, bullish_trend=False, min_bars=5):
|
||||
curr_klu.set_pattern(Chan_KLU_PATTERN.BULLISH_ENGULFING)
|
||||
return
|
||||
|
||||
# 2. 看跌吞没形态:前阳后阴,后者完全吞没前者
|
||||
# 要求前面有明显的上涨趋势
|
||||
if prev_bullish and not curr_bullish and \
|
||||
abs(curr_klu.open - prev_klu.close) < 10 and \
|
||||
curr_klu.close < prev_klu.open and \
|
||||
check_long_trend(prev_klu, bullish_trend=True, min_bars=5):
|
||||
curr_klu.set_pattern(Chan_KLU_PATTERN.BEARISH_ENGULFING)
|
||||
return
|
||||
|
||||
# 3. 乌云盖顶:前阳后阴,后者开盘价高于前者最高价,收盘价在前者实体中部以下
|
||||
# 要求前面有明显的上涨趋势
|
||||
if prev_bullish and not curr_bullish and \
|
||||
curr_klu.open > prev_klu.high and \
|
||||
curr_klu.close < (prev_klu.open + prev_klu.close) / 2 and \
|
||||
curr_klu.close > prev_klu.open and \
|
||||
check_long_trend(prev_klu, bullish_trend=True, min_bars=5):
|
||||
curr_klu.set_pattern(Chan_KLU_PATTERN.DARK_CLOUD_COVER)
|
||||
return
|
||||
|
||||
# 4. 曙光初现:前阴后阳,后者开盘价低于前者最低价,收盘价在前者实体中部以上
|
||||
# 要求前面有明显的下跌趋势
|
||||
if not prev_bullish and curr_bullish and \
|
||||
curr_klu.open < prev_klu.low and \
|
||||
curr_klu.close > (prev_klu.open + prev_klu.close) / 2 and \
|
||||
curr_klu.close < prev_klu.open and \
|
||||
check_long_trend(prev_klu, bullish_trend=False, min_bars=5):
|
||||
curr_klu.set_pattern(Chan_KLU_PATTERN.PIERCING_LINE)
|
||||
return
|
||||
|
||||
# 平顶和平底移至三根K线形态中判断
|
||||
|
||||
|
||||
def _detect_triple_pattern(self, first_klu, second_klu, third_klu):
|
||||
"""检测三根K线形成的形态
|
||||
包括:早晨之星、黄昏之星、平顶、平底
|
||||
"""
|
||||
# 如果前两根K线已经有形态,不再识别三K线形态
|
||||
if first_klu.pattern != Chan_KLU_PATTERN.UNKNOWN or \
|
||||
second_klu.pattern != Chan_KLU_PATTERN.UNKNOWN:
|
||||
return
|
||||
|
||||
# 判断K线颜色(阴阳)
|
||||
first_bullish = first_klu.close > first_klu.open
|
||||
second_bullish = second_klu.close > second_klu.open
|
||||
third_bullish = third_klu.close > third_klu.open
|
||||
|
||||
# 计算实体大小
|
||||
first_body = abs(first_klu.close - first_klu.open)
|
||||
second_body = abs(second_klu.close - second_klu.open)
|
||||
third_body = abs(third_klu.close - third_klu.open)
|
||||
|
||||
# 检查是否存在长期趋势(至少需要5根K线的趋势)
|
||||
def check_long_trend(klu, bullish_trend=True, min_bars=5):
|
||||
"""检查是否存在长期趋势
|
||||
bullish_trend=True: 检查上涨趋势
|
||||
bullish_trend=False: 检查下跌趋势
|
||||
min_bars: 最少需要多少根K线形成趋势
|
||||
"""
|
||||
if not klu or not klu.pre:
|
||||
return False
|
||||
|
||||
# 使用EMA指标判断长期趋势
|
||||
if klu.ema52 > 0:
|
||||
if bullish_trend and klu.close < klu.ema52:
|
||||
return False
|
||||
if not bullish_trend and klu.close > klu.ema52:
|
||||
return False
|
||||
|
||||
# 检查连续的K线方向
|
||||
count = 0
|
||||
current = klu.pre
|
||||
|
||||
while current and count < min_bars:
|
||||
if not current.pre:
|
||||
break
|
||||
|
||||
if bullish_trend:
|
||||
# 上涨趋势:当前收盘价高于前一根收盘价
|
||||
if current.close <= current.pre.close:
|
||||
break
|
||||
else:
|
||||
# 下跌趋势:当前收盘价低于前一根收盘价
|
||||
if current.close >= current.pre.close:
|
||||
break
|
||||
|
||||
count += 1
|
||||
current = current.pre
|
||||
|
||||
return count >= min_bars
|
||||
|
||||
# 1. 早晨之星:第一根阴线,第二根十字星或小实体,第三根阳线
|
||||
# 要求前面有明显的下跌趋势
|
||||
if not first_bullish and third_bullish and \
|
||||
second_body < first_body * 0.3 and \
|
||||
third_body > first_body * 0.5 and \
|
||||
max(second_klu.open, second_klu.close) < first_klu.close and \
|
||||
min(second_klu.open, second_klu.close) < third_klu.open and \
|
||||
third_klu.close > (first_klu.open + first_klu.close) / 2 and \
|
||||
check_long_trend(first_klu, bullish_trend=False, min_bars=7):
|
||||
third_klu.set_pattern(Chan_KLU_PATTERN.MORNING_STAR)
|
||||
return
|
||||
|
||||
# 2. 黄昏之星:第一根阳线,第二根十字星或小实体,第三根阴线
|
||||
# 要求前面有明显的上涨趋势
|
||||
if first_bullish and not third_bullish and \
|
||||
second_body < first_body * 0.3 and \
|
||||
third_body > first_body * 0.5 and \
|
||||
min(second_klu.open, second_klu.close) > first_klu.close and \
|
||||
max(second_klu.open, second_klu.close) > third_klu.open and \
|
||||
third_klu.close < (first_klu.open + first_klu.close) / 2 and \
|
||||
check_long_trend(first_klu, bullish_trend=True, min_bars=7):
|
||||
third_klu.set_pattern(Chan_KLU_PATTERN.EVENING_STAR)
|
||||
return
|
||||
|
||||
# 3. 平顶:三根K线的最高点几乎相同(上升趋势中更有意义)
|
||||
# 要求前面有明显的上涨趋势
|
||||
if (abs(first_klu.high - second_klu.high) / first_klu.high < 0.0002 and
|
||||
abs(second_klu.high - third_klu.high) / second_klu.high < 0.0002 and
|
||||
check_long_trend(first_klu, bullish_trend=True, min_bars=7)):
|
||||
# 额外确认:价格接近阻力位或关键技术指标
|
||||
is_near_resistance = False
|
||||
|
||||
# 检查是否接近EMA52阻力位
|
||||
if first_klu.ema52 > 0:
|
||||
resistance_level = first_klu.ema52
|
||||
if abs(first_klu.high - resistance_level) / resistance_level < 0.01:
|
||||
is_near_resistance = True
|
||||
|
||||
# 检查是否有成交量确认(成交量减少表示上涨动能减弱)
|
||||
volume_confirmation = False
|
||||
if (first_klu.volume > 0 and second_klu.volume > 0 and third_klu.volume > 0 and
|
||||
third_klu.volume < second_klu.volume and second_klu.volume < first_klu.volume):
|
||||
volume_confirmation = True
|
||||
|
||||
if is_near_resistance or volume_confirmation:
|
||||
third_klu.set_pattern(Chan_KLU_PATTERN.TWEEZER_TOP)
|
||||
return
|
||||
|
||||
# 4. 平底:三根K线的最低点几乎相同(下降趋势中更有意义)
|
||||
# 要求前面有明显的下跌趋势
|
||||
if (abs(first_klu.low - second_klu.low) / first_klu.low < 0.0002 and
|
||||
abs(second_klu.low - third_klu.low) / second_klu.low < 0.0002 and
|
||||
check_long_trend(first_klu, bullish_trend=False, min_bars=7)):
|
||||
# 额外确认:价格接近支撑位或关键技术指标
|
||||
is_near_support = False
|
||||
|
||||
# 检查是否接近EMA52支撑位
|
||||
if first_klu.ema52 > 0:
|
||||
support_level = first_klu.ema52
|
||||
if abs(first_klu.low - support_level) / support_level < 0.01:
|
||||
is_near_support = True
|
||||
|
||||
# 检查是否有成交量确认(成交量减少表示下跌动能减弱)
|
||||
volume_confirmation = False
|
||||
if (first_klu.volume > 0 and second_klu.volume > 0 and third_klu.volume > 0 and
|
||||
third_klu.volume < second_klu.volume and second_klu.volume < first_klu.volume):
|
||||
volume_confirmation = True
|
||||
|
||||
if is_near_support or volume_confirmation:
|
||||
third_klu.set_pattern(Chan_KLU_PATTERN.TWEEZER_BOTTOM)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
"""TF_DF builder mixin — 由 split_tfdf_builders 自动生成,逻辑与原 TF_DF 一致。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from pandas import DataFrame
|
||||
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
from chanlun.core.ChanBIZS import ChanBIZS
|
||||
from chanlun.core.ChanBSP import ChanBSP
|
||||
from chanlun.core.ChanEnum import (
|
||||
Chan_BI_DIR,
|
||||
Chan_BSP_DIR,
|
||||
Chan_BSP_TYPE,
|
||||
Chan_FX_TYPE,
|
||||
Chan_K_DIR,
|
||||
Chan_KLC_FX,
|
||||
Chan_KLC_STATE,
|
||||
Chan_KLINE_DIR,
|
||||
Chan_KLU_PATTERN,
|
||||
Chan_PRICE_TREND,
|
||||
Chan_SEG_DIR,
|
||||
Chan_ZS_DIR,
|
||||
)
|
||||
from chanlun.core.ChanKLC import ChanKLC
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
from chanlun.core.ChanSBI import ChanSBI
|
||||
from chanlun.core.ChanSEG import ChanSEG
|
||||
from chanlun.core.ChanZS import ChanZS, ChanZS_Big
|
||||
from chanlun.indicators.ChanMACD import ChanMACD
|
||||
|
||||
|
||||
class SegBuilderMixin:
|
||||
def get_seg_list(self, bi_list):
|
||||
seg_list = []
|
||||
up_bi_list = []
|
||||
down_bi_list = []
|
||||
last_up_bi = None
|
||||
last_down_bi = None
|
||||
last_up_sbi = None
|
||||
last_down_sbi = None
|
||||
last_seg = None
|
||||
up_sbi_list = []
|
||||
down_sbi_list = []
|
||||
look_for_bottom = False
|
||||
look_for_top = False
|
||||
for bi in bi_list:
|
||||
#print(len(up_sbi_list), len(down_sbi_list))
|
||||
if len(seg_list) > 0:
|
||||
# Last seg is up
|
||||
if last_seg.dir == Chan_SEG_DIR.UP:
|
||||
if bi.dir == Chan_BI_DIR.DOWN:
|
||||
if len(down_sbi_list) > 1:
|
||||
# Check down sbi inclusion
|
||||
included = last_down_sbi.check_bi_included(bi)
|
||||
if not included:
|
||||
down_sbi = ChanSBI(bi, len(down_sbi_list), bi.dir)
|
||||
last_down_sbi.set_next(down_sbi)
|
||||
last_down_sbi.set_end_bi(last_down_bi)
|
||||
down_sbi.set_pre(last_down_sbi)
|
||||
down_sbi_list.append(down_sbi)
|
||||
fx = last_down_sbi.check_fx()
|
||||
# Found top
|
||||
if fx == Chan_FX_TYPE.TOP:
|
||||
if look_for_top:
|
||||
seg_list[-2].set_sure(bi)
|
||||
look_for_top = False
|
||||
#print(bi.start_time, look_for_top, "UP 1")
|
||||
# Has gap and search for bottom fx
|
||||
if last_down_sbi.has_fx_gap:
|
||||
look_for_bottom = True
|
||||
last_seg.pre_set_end_bi(bi_list[last_down_sbi.start_bi.index - 1])
|
||||
seg = ChanSEG(last_down_sbi.start_bi, len(seg_list), Chan_SEG_DIR.DOWN, bi)
|
||||
seg_list.append(seg)
|
||||
last_seg.set_next(seg)
|
||||
seg.set_pre(last_seg)
|
||||
last_seg = seg
|
||||
up_sbi_list = []
|
||||
last_up_sbi = ChanSBI(last_up_bi, len(up_sbi_list), last_up_bi.dir)
|
||||
up_sbi_list.append(last_up_sbi)
|
||||
#up_sbi_list.append(last_up_sbi)
|
||||
#print(last_up_bi.start_time, last_up_sbi.start_bi.start_time, "Reset up sbi list 1")
|
||||
#print(bi.start_time, look_for_top, "UP 2")
|
||||
# No gap end SEG
|
||||
else:
|
||||
if look_for_bottom:
|
||||
look_for_bottom = False
|
||||
last_seg.set_start_bi(last_down_sbi.start_bi)
|
||||
seg_list[-2].set_end_bi(bi_list[last_down_sbi.start_bi.index - 1], bi)
|
||||
up_sbi_list = []
|
||||
last_up_sbi = ChanSBI(last_up_bi, len(up_sbi_list), last_up_bi.dir)
|
||||
up_sbi_list.append(last_up_sbi)
|
||||
last_seg.add_bi(bi)
|
||||
#up_sbi_list.append(last_up_sbi)
|
||||
#print(last_up_bi.start_time, last_up_sbi.start_bi.start_time, "Reset up sbi list 2")
|
||||
#print(bi.start_time, look_for_top, "UP 3")
|
||||
else:
|
||||
last_seg.set_end_bi(bi_list[last_down_sbi.start_bi.index - 1], bi)
|
||||
seg = ChanSEG(last_down_sbi.start_bi, len(seg_list), Chan_SEG_DIR.DOWN, bi)
|
||||
seg_list.append(seg)
|
||||
last_seg.set_next(seg)
|
||||
seg.set_pre(last_seg)
|
||||
last_seg = seg
|
||||
#print(last_down_sbi.end_bi.start_time, "Normal UP SEG", last_up_sbi.start_bi.start_time, bi.start_time)
|
||||
#l_up_sbi = up_sbi_list[-1]
|
||||
up_sbi_list = []
|
||||
last_up_sbi = ChanSBI(last_up_bi, len(up_sbi_list), last_up_bi.dir)
|
||||
up_sbi_list.append(last_up_sbi)
|
||||
#up_sbi_list.append(last_up_sbi)
|
||||
#print(last_up_bi.start_time, last_up_sbi.start_bi.start_time, "Reset up sbi list 3")
|
||||
last_down_sbi = down_sbi
|
||||
last_seg.add_bi(bi)
|
||||
else:
|
||||
if len(down_sbi_list) == 1:
|
||||
included = last_down_sbi.check_bi_included(bi)
|
||||
if not included:
|
||||
down_sbi = ChanSBI(bi, len(down_sbi_list), bi.dir)
|
||||
last_down_sbi.set_next(down_sbi)
|
||||
last_down_sbi.set_end_bi(last_down_bi)
|
||||
down_sbi.set_pre(last_down_sbi)
|
||||
down_sbi_list.append(down_sbi)
|
||||
last_down_sbi = down_sbi
|
||||
#print(bi.start_time, look_for_top, "UP 4")
|
||||
last_seg.add_bi(bi)
|
||||
|
||||
else:
|
||||
last_down_sbi = ChanSBI(bi, len(down_sbi_list), bi.dir)
|
||||
down_sbi_list.append(last_down_sbi)
|
||||
last_seg.add_bi(bi)
|
||||
#print(bi.start_time, look_for_top, "UP 5")
|
||||
else:
|
||||
if last_up_sbi:
|
||||
included = last_up_sbi.check_bi_included(bi)
|
||||
if not included:
|
||||
up_sbi = ChanSBI(bi, len(up_sbi_list), bi.dir)
|
||||
last_up_sbi.set_next(up_sbi)
|
||||
last_up_sbi.set_end_bi(last_up_bi)
|
||||
up_sbi.set_pre(last_up_sbi)
|
||||
up_sbi_list.append(up_sbi)
|
||||
last_up_sbi = up_sbi
|
||||
#print(bi.start_time, look_for_top, "UP 6")
|
||||
last_seg.add_bi(bi)
|
||||
|
||||
# Last seg is down
|
||||
else:
|
||||
if bi.dir == Chan_BI_DIR.UP:
|
||||
if len(up_sbi_list) > 1:
|
||||
# Check down sbi inclusion
|
||||
included = last_up_sbi.check_bi_included(bi)
|
||||
if not included:
|
||||
up_sbi = ChanSBI(bi, len(up_sbi_list), bi.dir)
|
||||
last_up_sbi.set_next(up_sbi)
|
||||
last_up_sbi.set_end_bi(last_up_bi)
|
||||
up_sbi.set_pre(last_up_sbi)
|
||||
up_sbi_list.append(up_sbi)
|
||||
fx = last_up_sbi.check_fx()
|
||||
# Found bottom
|
||||
if fx == Chan_FX_TYPE.BOTTOM:
|
||||
if look_for_bottom:
|
||||
seg_list[-2].set_sure(bi)
|
||||
look_for_bottom = False
|
||||
#print(bi.start_time, look_for_top, "DOWN 1")
|
||||
# Has gap and search for bottom fx
|
||||
if last_up_sbi.has_fx_gap:
|
||||
look_for_top = True
|
||||
last_seg.pre_set_end_bi(bi_list[last_up_sbi.start_bi.index - 1])
|
||||
seg = ChanSEG(last_up_sbi.start_bi, len(seg_list), Chan_SEG_DIR.UP, bi)
|
||||
seg_list.append(seg)
|
||||
last_seg.set_next(seg)
|
||||
seg.set_pre(last_seg)
|
||||
last_seg = seg
|
||||
down_sbi_list = []
|
||||
last_down_sbi = ChanSBI(last_down_bi, len(down_sbi_list), last_down_bi.dir)
|
||||
down_sbi_list.append(last_down_sbi)
|
||||
#down_sbi_list.append(last_down_sbi)
|
||||
#print(last_down_bi.start_time, last_down_sbi.start_bi.start_time, "Reset down sbi list 1")
|
||||
#print(bi.start_time, look_for_top, "DOWN 2")
|
||||
# No gap end SEG
|
||||
else:
|
||||
if look_for_top:
|
||||
look_for_top = False
|
||||
last_seg.set_start_bi(last_up_sbi.start_bi)
|
||||
seg_list[-2].set_end_bi(bi_list[last_up_sbi.start_bi.index - 1], bi)
|
||||
down_sbi_list = []
|
||||
last_down_sbi = ChanSBI(last_down_bi, len(down_sbi_list), last_down_bi.dir)
|
||||
down_sbi_list.append(last_down_sbi)
|
||||
last_seg.add_bi(bi)
|
||||
#down_sbi_list.append(last_down_sbi)
|
||||
#print(last_down_bi.start_time, last_down_sbi.start_bi.start_time, "Reset down sbi list 2")
|
||||
#print(bi.start_time, look_for_top, "DOWN 3")
|
||||
else:
|
||||
last_seg.set_end_bi(bi_list[last_up_sbi.start_bi.index - 1], bi)
|
||||
seg = ChanSEG(last_up_sbi.start_bi, len(seg_list), Chan_SEG_DIR.UP, bi)
|
||||
#print(last_up_sbi.start_bi.start_time)
|
||||
last_seg.set_next(seg)
|
||||
seg.set_pre(last_seg)
|
||||
seg_list.append(seg)
|
||||
last_seg = seg
|
||||
#print(last_up_sbi.end_bi.start_time, "Normal DOWN SEG", last_down_sbi.start_bi.start_time, bi.start_time)
|
||||
down_sbi_list = []
|
||||
last_down_sbi = ChanSBI(last_down_bi, len(down_sbi_list), last_down_bi.dir)
|
||||
down_sbi_list.append(last_down_sbi)
|
||||
#down_sbi_list.append(last_down_sbi)
|
||||
#print(last_down_bi.start_time, last_down_sbi.start_bi.start_time, "Reset down sbi list 3")
|
||||
last_up_sbi = up_sbi
|
||||
last_seg.add_bi(bi)
|
||||
else:
|
||||
if len(up_sbi_list) == 1:
|
||||
#last_up_sbi = up_sbi_list[-1]
|
||||
included = last_up_sbi.check_bi_included(bi)
|
||||
if not included:
|
||||
up_sbi = ChanSBI(bi, len(up_sbi_list), bi.dir)
|
||||
last_up_sbi.set_next(up_sbi)
|
||||
last_up_sbi.set_end_bi(last_up_bi)
|
||||
up_sbi.set_pre(last_up_sbi)
|
||||
up_sbi_list.append(up_sbi)
|
||||
last_up_sbi = up_sbi
|
||||
last_seg.add_bi(bi)
|
||||
#print(bi.start_time, look_for_top, "DOWN 4")
|
||||
else:
|
||||
last_up_sbi = ChanSBI(bi, len(up_sbi_list), bi.dir)
|
||||
up_sbi_list.append(last_up_sbi)
|
||||
last_seg.add_bi(bi)
|
||||
#print(bi.start_time, look_for_top, "DOWN 5")
|
||||
else:
|
||||
if last_down_sbi:
|
||||
included = last_down_sbi.check_bi_included(bi)
|
||||
if not included:
|
||||
down_sbi = ChanSBI(bi, len(down_sbi_list), bi.dir)
|
||||
last_down_sbi.set_next(down_sbi)
|
||||
last_down_sbi.set_end_bi(last_down_bi)
|
||||
down_sbi.set_pre(last_down_sbi)
|
||||
down_sbi_list.append(down_sbi)
|
||||
last_down_sbi = down_sbi
|
||||
last_seg.add_bi(bi)
|
||||
#print(bi.start_time, look_for_top, look_for_bottom, "DOWN 6")
|
||||
# len(seg_list) = 0
|
||||
else:
|
||||
if bi.check_overlap():
|
||||
if bi.dir == Chan_BI_DIR.UP:
|
||||
seg = ChanSEG(bi, len(seg_list), Chan_SEG_DIR.UP, bi)
|
||||
last_up_bi = bi
|
||||
last_up_sbi = ChanSBI(bi, len(up_sbi_list), bi.dir)
|
||||
seg_list.append(seg)
|
||||
last_seg = seg
|
||||
#print(bi.start_time, 'Create first UP SEG')
|
||||
else:
|
||||
seg = ChanSEG(bi, len(seg_list), Chan_SEG_DIR.DOWN, bi)
|
||||
last_down_bi = bi
|
||||
last_down_sbi = ChanSBI(bi, len(down_sbi_list), bi.dir)
|
||||
seg_list.append(seg)
|
||||
last_seg = seg
|
||||
#print(bi.start_time, 'Create first DOWN SEG')
|
||||
if bi.dir == Chan_BI_DIR.UP:
|
||||
last_up_bi = bi
|
||||
up_bi_list.append(bi)
|
||||
else:
|
||||
last_down_bi = bi
|
||||
down_bi_list.append(bi)
|
||||
"""
|
||||
if len(seg_list) > 1:
|
||||
seg = seg_list[-1]
|
||||
last_seg = seg_list[-2]
|
||||
last_seg_bi = last_seg.bi_list[-3]
|
||||
bi_index = seg.start_bi.index
|
||||
for i in range(bi_index, len(bi_list) - 1):
|
||||
# last seg is down
|
||||
if seg.dir == Chan_SEG_DIR.UP:
|
||||
if bi_list[i].dir == Chan_BI_DIR.UP:
|
||||
last_seg_peak = last_seg_bi.high
|
||||
if bi_list[i].high > last_seg_peak:
|
||||
# The confirmed
|
||||
print("Last UP seg is broken, create a new seg. 1")
|
||||
seg.pre_set_end_bi(bi_list[i])
|
||||
seg = ChanSEG(bi_list[i+1], len(seg_list), Chan_SEG_DIR.DOWN, bi)
|
||||
seg_list.append(seg)
|
||||
last_seg = seg_list[-2]
|
||||
if len(last_seg.bi_list) > 3:
|
||||
last_seg_bi = last_seg.bi_list[-3]
|
||||
|
||||
else:
|
||||
if bi_list[i].dir == Chan_BI_DIR.DOWN:
|
||||
last_seg_peak = last_seg_bi.low
|
||||
if bi_list[i].low < last_seg_peak:
|
||||
print("Last DOWN seg is broken, create a new seg. 1")
|
||||
seg.pre_set_end_bi(bi_list[i])
|
||||
seg = ChanSEG(bi_list[i+1], len(seg_list), Chan_SEG_DIR.UP, bi)
|
||||
seg_list.append(seg)
|
||||
last_seg = seg_list[-2]
|
||||
if len(last_seg.bi_list) > 3:
|
||||
last_seg_bi = last_seg.bi_list[-3]
|
||||
else:
|
||||
if len(seg_list) == 1:
|
||||
last_seg = seg_list[-1]
|
||||
bi_index = last_seg.bi_list[0].index
|
||||
for i in range(bi_index, len(bi_list) - 1):
|
||||
if i > bi_index + 2:
|
||||
last_seg_peak = bi_list[i-2].high
|
||||
# last seg is down
|
||||
if last_seg.dir == Chan_SEG_DIR.DOWN:
|
||||
if bi_list[i].dir == Chan_BI_DIR.UP:
|
||||
if bi_list[i].high > last_seg_peak:
|
||||
print("Last seg is broken, create a new seg. 2")
|
||||
last_seg.pre_set_end_bi(bi_list[i-1])
|
||||
seg = ChanSEG(bi_list[i], len(seg_list), Chan_SEG_DIR.UP, bi)
|
||||
seg_list.append(seg)
|
||||
last_seg = seg
|
||||
last_seg_bi = bi_list[i]
|
||||
break
|
||||
"""
|
||||
#self.cal_bi_zs(seg_list)
|
||||
return seg_list
|
||||
@@ -0,0 +1,702 @@
|
||||
"""TF_DF builder mixin — 由 split_tfdf_builders 自动生成,逻辑与原 TF_DF 一致。"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
from decimal import Decimal
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from pandas import DataFrame
|
||||
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
from chanlun.core.ChanBIZS import ChanBIZS
|
||||
from chanlun.core.ChanBSP import ChanBSP
|
||||
from chanlun.core.ChanEnum import (
|
||||
Chan_BI_DIR,
|
||||
Chan_BSP_DIR,
|
||||
Chan_BSP_TYPE,
|
||||
Chan_FX_TYPE,
|
||||
Chan_K_DIR,
|
||||
Chan_KLC_FX,
|
||||
Chan_KLC_STATE,
|
||||
Chan_KLINE_DIR,
|
||||
Chan_KLU_PATTERN,
|
||||
Chan_PRICE_TREND,
|
||||
Chan_SEG_DIR,
|
||||
Chan_ZS_DIR,
|
||||
)
|
||||
from chanlun.core.ChanKLC import ChanKLC
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
from chanlun.core.ChanSBI import ChanSBI
|
||||
from chanlun.core.ChanSEG import ChanSEG
|
||||
from chanlun.core.ChanZS import ChanZS, ChanZS_Big
|
||||
from chanlun.indicators.ChanMACD import ChanMACD
|
||||
|
||||
|
||||
class ZsBuilderMixin:
|
||||
def get_zs_state(self, df):
|
||||
bi_list = self.cal_bi_list(self.get_klc_list(self.get_kl_data(df)))
|
||||
seg_list = self.get_seg_list(bi_list)
|
||||
zs_list = self.calculate_zs(seg_list)
|
||||
for zs in zs_list:
|
||||
last_zs = zs
|
||||
return zs_list
|
||||
|
||||
def cal_bi_zs(self, seg_list):
|
||||
bi_zs_list = []
|
||||
for seg in seg_list:
|
||||
zs_list = seg.cal_bi_zs()
|
||||
if len(zs_list) > 0:
|
||||
bi_zs_list = list(bi_zs_list) + list(zs_list)
|
||||
return bi_zs_list
|
||||
# 跨段不相连的中枢
|
||||
|
||||
def cal_bi_zs_list(self, bi_list):
|
||||
"""
|
||||
根据缠论笔中枢定义计算中枢(参照 get_zs_list 线段中枢判断规则)
|
||||
从第4根笔开始(索引3),每3根笔为一组检查
|
||||
上涨中枢:后中枢 zd > 前中枢 zg(不重叠上移)
|
||||
下跌中枢:后中枢 zg < 前中枢 zd(不重叠下移)
|
||||
中枢可按两笔一组继续扩展到5根、7根...
|
||||
"""
|
||||
bi_zs_list = []
|
||||
if len(bi_list) < 3:
|
||||
return bi_zs_list
|
||||
|
||||
last_zs = None
|
||||
start_idx = 3
|
||||
|
||||
while start_idx < len(bi_list):
|
||||
if start_idx + 2 >= len(bi_list):
|
||||
break
|
||||
|
||||
bi1 = bi_list[start_idx]
|
||||
bi2 = bi_list[start_idx + 1]
|
||||
bi3 = bi_list[start_idx + 2]
|
||||
|
||||
if not (bi1.is_sure and bi2.is_sure and bi3.is_sure):
|
||||
start_idx += 1
|
||||
continue
|
||||
|
||||
zg = min(bi1.high, bi2.high, bi3.high)
|
||||
zd = max(bi1.low, bi2.low, bi3.low)
|
||||
|
||||
if zg <= zd:
|
||||
start_idx += 1
|
||||
continue
|
||||
|
||||
valid = False
|
||||
if last_zs is None:
|
||||
if bi1.dir == Chan_BI_DIR.DOWN:
|
||||
zs_dir = Chan_ZS_DIR.UP
|
||||
valid = (bi2.dir == Chan_BI_DIR.UP and bi3.dir == Chan_BI_DIR.DOWN)
|
||||
else:
|
||||
zs_dir = Chan_ZS_DIR.DOWN
|
||||
valid = (bi2.dir == Chan_BI_DIR.DOWN and bi3.dir == Chan_BI_DIR.UP)
|
||||
else:
|
||||
is_up_zs = zg > last_zs.zg
|
||||
is_down_zs = zd < last_zs.zd
|
||||
|
||||
if is_up_zs:
|
||||
zs_dir = Chan_ZS_DIR.UP
|
||||
valid = (bi1.dir == Chan_BI_DIR.DOWN and bi2.dir == Chan_BI_DIR.UP and bi3.dir == Chan_BI_DIR.DOWN)
|
||||
elif is_down_zs:
|
||||
zs_dir = Chan_ZS_DIR.DOWN
|
||||
valid = (bi1.dir == Chan_BI_DIR.UP and bi2.dir == Chan_BI_DIR.DOWN and bi3.dir == Chan_BI_DIR.UP)
|
||||
|
||||
if not valid:
|
||||
start_idx += 1
|
||||
continue
|
||||
gg = max(bi1.high, bi2.high, bi3.high)
|
||||
dd = min(bi1.low, bi2.low, bi3.low)
|
||||
zs = ChanBIZS(bi1, len(bi_zs_list), zs_dir)
|
||||
zs.set_zg(zg)
|
||||
zs.set_zd(zd)
|
||||
zs.set_gg(gg)
|
||||
zs.set_dd(dd)
|
||||
zs.is_sure = False
|
||||
zs.bi_list = [bi1, bi2, bi3]
|
||||
|
||||
added_after_leave = []
|
||||
leave_index = start_idx + 4
|
||||
while leave_index < len(bi_list):
|
||||
b = bi_list[leave_index]
|
||||
if not b.is_sure:
|
||||
break
|
||||
if b.high >= zs.zd and b.low <= zs.zg:
|
||||
added_after_leave.append(b.pre)
|
||||
added_after_leave.append(b)
|
||||
else:
|
||||
break
|
||||
leave_index += 2
|
||||
|
||||
if added_after_leave:
|
||||
bis_for_zs = list(zs.bi_list) + list(added_after_leave)
|
||||
bi_highs = [bi.high for bi in bis_for_zs]
|
||||
bi_lows = [bi.low for bi in bis_for_zs]
|
||||
zs.set_gg(max(bi_highs))
|
||||
zs.set_dd(min(bi_lows))
|
||||
zs.bi_list = bis_for_zs
|
||||
bi = bis_for_zs[-1]
|
||||
if bi.is_sure:
|
||||
zs.set_end_bi(bi, bi.sure_time)
|
||||
|
||||
start_idx = start_idx + len(added_after_leave)
|
||||
else:
|
||||
zs.set_end_bi(bi3, bi3.sure_time)
|
||||
|
||||
if last_zs:
|
||||
last_zs.set_next(zs)
|
||||
zs.set_pre(last_zs)
|
||||
|
||||
bi_zs_list.append(zs)
|
||||
last_zs = zs
|
||||
|
||||
start_idx += 4
|
||||
|
||||
if last_zs:
|
||||
last_zs.is_sure = bi_list[-1].is_sure
|
||||
|
||||
if last_zs and not last_zs.is_sure:
|
||||
if last_zs.bi_list and len(last_zs.bi_list) > 0:
|
||||
last_bi_of_zs = last_zs.bi_list[-1]
|
||||
last_bi_idx = -1
|
||||
for i, bi in enumerate(bi_list):
|
||||
if bi == last_bi_of_zs:
|
||||
last_bi_idx = i
|
||||
break
|
||||
|
||||
has_leave = False
|
||||
if last_bi_idx >= 0 and last_bi_idx + 1 < len(bi_list):
|
||||
for i in range(last_bi_idx + 1, len(bi_list)):
|
||||
bi = bi_list[i]
|
||||
if bi.is_sure:
|
||||
leave = (bi.low > last_zs.zg and bi.high > last_zs.zg) or \
|
||||
(bi.high < last_zs.zd and bi.low < last_zs.zd)
|
||||
if leave:
|
||||
has_leave = True
|
||||
break
|
||||
|
||||
if has_leave:
|
||||
if last_bi_of_zs.is_sure:
|
||||
last_zs.set_end_bi(last_bi_of_zs, last_bi_of_zs.sure_time)
|
||||
return bi_zs_list
|
||||
|
||||
def get_bi_zs_list(self, bi_list):
|
||||
"""
|
||||
根据缠论笔中枢定义计算中枢(完全参照 get_seg_zs_list 线段中枢判断规则)
|
||||
从第4根笔开始(索引3),每3根笔为一组检查
|
||||
上涨中枢:后中枢 zd > 前中枢 zg(不重叠上移)
|
||||
下跌中枢:后中枢 zg < 前中枢 zd(不重叠下移)
|
||||
盘整/扩张:后中枢与前中枢整体区间有交集 → 合并扩展
|
||||
中枢可按两笔一组继续扩展到5根、7根...
|
||||
"""
|
||||
bi_zs_list = []
|
||||
if len(bi_list) < 3:
|
||||
return bi_zs_list
|
||||
|
||||
last_zs = None
|
||||
start_idx = 3
|
||||
|
||||
while start_idx < len(bi_list):
|
||||
if start_idx + 2 >= len(bi_list):
|
||||
break
|
||||
|
||||
bi1 = bi_list[start_idx]
|
||||
bi2 = bi_list[start_idx + 1]
|
||||
bi3 = bi_list[start_idx + 2]
|
||||
|
||||
if not (bi1.is_sure and bi2.is_sure and bi3.is_sure):
|
||||
start_idx += 1
|
||||
continue
|
||||
|
||||
zg = min(bi1.high, bi2.high, bi3.high)
|
||||
zd = max(bi1.low, bi2.low, bi3.low)
|
||||
|
||||
if zg <= zd:
|
||||
start_idx += 1
|
||||
continue
|
||||
|
||||
valid = False
|
||||
if last_zs is None:
|
||||
if bi1.dir == Chan_BI_DIR.DOWN:
|
||||
zs_dir = Chan_ZS_DIR.UP
|
||||
valid = (bi2.dir == Chan_BI_DIR.UP and bi3.dir == Chan_BI_DIR.DOWN)
|
||||
else:
|
||||
zs_dir = Chan_ZS_DIR.DOWN
|
||||
valid = (bi2.dir == Chan_BI_DIR.DOWN and bi3.dir == Chan_BI_DIR.UP)
|
||||
else:
|
||||
is_up_zs = zd > last_zs.zg
|
||||
is_down_zs = zg < last_zs.zd
|
||||
|
||||
if is_up_zs:
|
||||
zs_dir = Chan_ZS_DIR.UP
|
||||
valid = (bi1.dir == Chan_BI_DIR.DOWN and bi2.dir == Chan_BI_DIR.UP and bi3.dir == Chan_BI_DIR.DOWN)
|
||||
elif is_down_zs:
|
||||
zs_dir = Chan_ZS_DIR.DOWN
|
||||
valid = (bi1.dir == Chan_BI_DIR.UP and bi2.dir == Chan_BI_DIR.DOWN and bi3.dir == Chan_BI_DIR.UP)
|
||||
|
||||
create_new_zs = False
|
||||
if not valid:
|
||||
# 如果新中枢和前一个中枢的中枢区间有重叠,不形成新中枢,合并扩展
|
||||
if last_zs is not None:
|
||||
is_in_last_zs = (zd > last_zs.zd and zd < last_zs.zg) or \
|
||||
(zg < last_zs.zg and zg > last_zs.zd) or \
|
||||
(zg > last_zs.zg and zd < last_zs.zd) or \
|
||||
(zg < last_zs.zg and zd > last_zs.zd)
|
||||
if is_in_last_zs:
|
||||
# 扩展当前中枢:将 bi1-bi3 加入 last_zs
|
||||
for bi in [bi1, bi2, bi3]:
|
||||
if bi not in last_zs.bi_list:
|
||||
last_zs.add_bi(bi)
|
||||
create_new_zs = False
|
||||
else:
|
||||
start_idx += 1
|
||||
continue
|
||||
else:
|
||||
start_idx += 1
|
||||
continue
|
||||
else:
|
||||
create_new_zs = True
|
||||
|
||||
# 新中枢形成时确认前一个中枢
|
||||
if last_zs and create_new_zs:
|
||||
last_bi = last_zs.bi_list[-1]
|
||||
if last_bi and last_bi.is_sure:
|
||||
last_zs.is_sure = True
|
||||
last_zs.set_end_bi(last_bi, last_bi.sure_time)
|
||||
|
||||
zs = last_zs
|
||||
if create_new_zs:
|
||||
gg = max(bi1.high, bi2.high, bi3.high)
|
||||
dd = min(bi1.low, bi2.low, bi3.low)
|
||||
zs = ChanBIZS(bi1, len(bi_zs_list), zs_dir)
|
||||
zs.set_zg(zg)
|
||||
zs.set_zd(zd)
|
||||
zs.set_gg(gg)
|
||||
zs.set_dd(dd)
|
||||
zs.is_sure = False
|
||||
zs.bi_list = [bi1, bi2, bi3]
|
||||
|
||||
# 离开后回抽扩展检查
|
||||
added_after_leave = []
|
||||
leave_index = start_idx + 4
|
||||
while leave_index < len(bi_list):
|
||||
b = bi_list[leave_index]
|
||||
if not b.is_sure:
|
||||
break
|
||||
if b.high >= zs.zd and b.low <= zs.zg:
|
||||
added_after_leave.append(b.pre)
|
||||
added_after_leave.append(b)
|
||||
else:
|
||||
break
|
||||
leave_index += 2
|
||||
|
||||
if added_after_leave:
|
||||
bis_for_zs = list(zs.bi_list) + list(added_after_leave)
|
||||
bi_highs = [bi.high for bi in bis_for_zs]
|
||||
bi_lows = [bi.low for bi in bis_for_zs]
|
||||
zs.set_gg(max(bi_highs))
|
||||
zs.set_dd(min(bi_lows))
|
||||
zs.bi_list = bis_for_zs
|
||||
bi = bis_for_zs[-1]
|
||||
if bi.is_sure:
|
||||
zs.set_end_bi(bi, bi.sure_time)
|
||||
start_idx = start_idx + len(added_after_leave)
|
||||
else:
|
||||
if create_new_zs:
|
||||
zs.set_end_bi(bi3, bi3.sure_time)
|
||||
|
||||
if create_new_zs:
|
||||
if last_zs:
|
||||
last_zs.set_next(zs)
|
||||
zs.set_pre(last_zs)
|
||||
bi_zs_list.append(zs)
|
||||
last_zs = zs
|
||||
|
||||
start_idx += 4
|
||||
|
||||
# 最后一个中枢:根据 bi_list 最后一笔确认状态
|
||||
if last_zs:
|
||||
last_zs.is_sure = bi_list[-1].is_sure
|
||||
|
||||
if last_zs and not last_zs.is_sure:
|
||||
if last_zs.bi_list and len(last_zs.bi_list) > 0:
|
||||
last_bi_of_zs = last_zs.bi_list[-1]
|
||||
last_bi_idx = -1
|
||||
for i, bi in enumerate(bi_list):
|
||||
if bi == last_bi_of_zs:
|
||||
last_bi_idx = i
|
||||
break
|
||||
|
||||
has_leave = False
|
||||
if last_bi_idx >= 0 and last_bi_idx + 1 < len(bi_list):
|
||||
for i in range(last_bi_idx + 1, len(bi_list)):
|
||||
bi = bi_list[i]
|
||||
if bi.is_sure:
|
||||
leave = (bi.low > last_zs.zg and bi.high > last_zs.zg) or \
|
||||
(bi.high < last_zs.zd and bi.low < last_zs.zd)
|
||||
if leave:
|
||||
has_leave = True
|
||||
break
|
||||
|
||||
if has_leave:
|
||||
if last_bi_of_zs.is_sure:
|
||||
last_zs.set_end_bi(last_bi_of_zs, last_bi_of_zs.sure_time)
|
||||
|
||||
return bi_zs_list
|
||||
|
||||
|
||||
def cal_bi_zs_list_pure(self, bi_list):
|
||||
bi_zs_list = []
|
||||
if len(bi_list) < 3:
|
||||
return bi_zs_list
|
||||
|
||||
def get_zs_range(bis):
|
||||
bis_list = bis[0:3]
|
||||
zg = min(bi.high for bi in bis_list)
|
||||
zd = max(bi.low for bi in bis_list)
|
||||
dd = min(bi.low for bi in bis_list)
|
||||
gg = max(bi.high for bi in bis_list)
|
||||
return zg, zd, dd, gg
|
||||
|
||||
def is_bi_overlap_range(bi, zg, zd):
|
||||
return bi.high >= zd and bi.low <= zg
|
||||
|
||||
def check_zs_position_filter(last_zs, zg, zd, bis):
|
||||
if last_zs is None:
|
||||
return True
|
||||
if zg <= last_zs.zd:
|
||||
return bis[0].dir == Chan_BI_DIR.UP and bis[-1].dir == Chan_BI_DIR.UP
|
||||
if zd >= last_zs.zg:
|
||||
return bis[0].dir == Chan_BI_DIR.DOWN and bis[-1].dir == Chan_BI_DIR.DOWN
|
||||
return True
|
||||
|
||||
def set_zs_bi_list(zs, bis):
|
||||
zs.bi_list = list(bis)
|
||||
for bi in zs.bi_list:
|
||||
bi.set_bi_zs(zs)
|
||||
#zs.set_gg(max(bi.high for bi in zs.bi_list))
|
||||
#zs.set_dd(min(bi.low for bi in zs.bi_list))
|
||||
zs.classify_zs()
|
||||
|
||||
last_zs = None
|
||||
start_idx = 0
|
||||
while start_idx + 2 < len(bi_list):
|
||||
bi1 = bi_list[start_idx]
|
||||
bi2 = bi_list[start_idx + 1]
|
||||
bi3 = bi_list[start_idx + 2]
|
||||
|
||||
if not (bi1.is_sure and bi2.is_sure and bi3.is_sure):
|
||||
start_idx += 1
|
||||
continue
|
||||
|
||||
if not (bi1.dir != bi2.dir and bi1.dir == bi3.dir):
|
||||
start_idx += 1
|
||||
continue
|
||||
|
||||
zg, zd, dd, gg = get_zs_range([bi1, bi2, bi3])
|
||||
if zg <= zd:
|
||||
start_idx += 1
|
||||
continue
|
||||
|
||||
bis_for_zs = [bi1, bi2, bi3]
|
||||
extend_idx = start_idx + 3
|
||||
while extend_idx + 1 < len(bi_list):
|
||||
leave_bi = bi_list[extend_idx]
|
||||
back_bi = bi_list[extend_idx + 1]
|
||||
if not (leave_bi.is_sure and back_bi.is_sure):
|
||||
break
|
||||
if not is_bi_overlap_range(back_bi, zg, zd):
|
||||
break
|
||||
bis_for_zs.append(leave_bi)
|
||||
bis_for_zs.append(back_bi)
|
||||
extend_idx += 2
|
||||
|
||||
if not check_zs_position_filter(last_zs, zg, zd, bis_for_zs):
|
||||
start_idx += 1
|
||||
continue
|
||||
|
||||
zs_dir = Chan_ZS_DIR.UP if bi1.dir == Chan_BI_DIR.DOWN else Chan_ZS_DIR.DOWN
|
||||
zs = ChanBIZS(bi1, len(bi_zs_list), zs_dir)
|
||||
zs.set_zg(zg)
|
||||
zs.set_zd(zd)
|
||||
zs.set_dd(dd)
|
||||
zs.set_gg(gg)
|
||||
|
||||
set_zs_bi_list(zs, bis_for_zs)
|
||||
zs.set_end_bi(bis_for_zs[-1], bis_for_zs[-1].sure_time)
|
||||
|
||||
if last_zs:
|
||||
last_zs.set_next(zs)
|
||||
zs.set_pre(last_zs)
|
||||
|
||||
bi_zs_list.append(zs)
|
||||
last_zs = zs
|
||||
start_idx = start_idx + len(bis_for_zs)
|
||||
|
||||
# 与 cal_bi_zs_list 一致:最后一笔未确认时末中枢标为未完成;若其后已出现确认的离开笔,仍按离开前最后一笔确认中枢结束
|
||||
if last_zs:
|
||||
last_zs.is_sure = bi_list[-1].is_sure
|
||||
|
||||
if last_zs and not last_zs.is_sure:
|
||||
if last_zs.bi_list and len(last_zs.bi_list) > 0:
|
||||
last_bi_of_zs = last_zs.bi_list[-1]
|
||||
last_bi_idx = -1
|
||||
for i, bi in enumerate(bi_list):
|
||||
if bi == last_bi_of_zs:
|
||||
last_bi_idx = i
|
||||
break
|
||||
|
||||
has_leave = False
|
||||
if last_bi_idx >= 0 and last_bi_idx + 1 < len(bi_list):
|
||||
for i in range(last_bi_idx + 1, len(bi_list)):
|
||||
bi = bi_list[i]
|
||||
if bi.is_sure:
|
||||
leave = (bi.low > last_zs.zg and bi.high > last_zs.zg) or \
|
||||
(bi.high < last_zs.zd and bi.low < last_zs.zd)
|
||||
if leave:
|
||||
has_leave = True
|
||||
break
|
||||
|
||||
if has_leave:
|
||||
if last_bi_of_zs.is_sure:
|
||||
last_zs.set_end_bi(last_bi_of_zs, last_bi_of_zs.sure_time)
|
||||
|
||||
return bi_zs_list
|
||||
|
||||
def get_zs_list(self, bi_list, seg_list):
|
||||
"""兼容历史 API:线段中枢列表。"""
|
||||
return self.get_seg_zs_list(seg_list)
|
||||
|
||||
def calculate_seg_zs(self, seg_list):
|
||||
return self.get_seg_zs_list(seg_list)
|
||||
|
||||
def get_seg_zs_list(self, seg_list):
|
||||
"""
|
||||
根据缠论线段中枢定义计算中枢
|
||||
从第4根线段开始(索引3),每3根线段为一组检查
|
||||
上涨中枢:后中枢 zd > 前中枢 zg(不重叠上移)
|
||||
下跌中枢:后中枢 zg < 前中枢 zd(不重叠下移)
|
||||
盘整/扩张:后中枢与前中枢整体区间(GG/DD)有交集
|
||||
中枢可按两段一组继续扩展到5根、7根...
|
||||
"""
|
||||
zs_list = []
|
||||
if len(seg_list) < 3:
|
||||
return zs_list
|
||||
|
||||
last_zs = None
|
||||
|
||||
# 从第4根线段开始(索引3),每3根为一组
|
||||
start_idx = 3
|
||||
|
||||
while start_idx < len(seg_list):
|
||||
# 取连续3个线段
|
||||
if start_idx + 2 >= len(seg_list):
|
||||
break
|
||||
|
||||
seg1 = seg_list[start_idx]
|
||||
seg2 = seg_list[start_idx + 1]
|
||||
seg3 = seg_list[start_idx + 2]
|
||||
|
||||
# 三个线段都必须是已确认的
|
||||
if not (seg1.is_sure and seg2.is_sure and seg3.is_sure):
|
||||
start_idx += 1
|
||||
continue
|
||||
|
||||
# 计算这3个线段的中枢区间
|
||||
zg = min(seg1.high, seg2.high, seg3.high)
|
||||
zd = max(seg1.low, seg2.low, seg3.low)
|
||||
|
||||
if zg <= zd:
|
||||
start_idx += 1
|
||||
#print(seg1.start_bi.start_klc.end_time, "not valid", zg, zd)
|
||||
continue
|
||||
|
||||
# 判断中枢类型(按注释定义)
|
||||
# 上涨中枢:后中枢 zd > 前中枢 zg(不重叠上移)
|
||||
# 下跌中枢:后中枢 zg < 前中枢 zd(不重叠下移)
|
||||
# 盘整/扩张:后中枢与前中枢区间有交集
|
||||
if last_zs is None:
|
||||
# 第一个中枢仅按线段形态判定方向
|
||||
if seg1.dir == Chan_SEG_DIR.DOWN:
|
||||
# 下跌+上涨+下跌,对应上涨中枢
|
||||
zs_dir = Chan_ZS_DIR.UP
|
||||
valid = (seg2.dir == Chan_SEG_DIR.UP and seg3.dir == Chan_SEG_DIR.DOWN)
|
||||
else:
|
||||
# 上涨+下跌+上涨,对应下跌中枢
|
||||
zs_dir = Chan_ZS_DIR.DOWN
|
||||
valid = (seg2.dir == Chan_SEG_DIR.DOWN and seg3.dir == Chan_SEG_DIR.UP)
|
||||
else:
|
||||
is_up_zs = zd > last_zs.zg
|
||||
is_down_zs = zg < last_zs.zd
|
||||
|
||||
if is_up_zs:
|
||||
# 不重叠上移
|
||||
zs_dir = Chan_ZS_DIR.UP
|
||||
valid = (seg1.dir == Chan_SEG_DIR.DOWN and seg2.dir == Chan_SEG_DIR.UP and seg3.dir == Chan_SEG_DIR.DOWN)
|
||||
elif is_down_zs:
|
||||
# 不重叠下移
|
||||
zs_dir = Chan_ZS_DIR.DOWN
|
||||
valid = (seg1.dir == Chan_SEG_DIR.UP and seg2.dir == Chan_SEG_DIR.DOWN and seg3.dir == Chan_SEG_DIR.UP)
|
||||
create_new_zs = False
|
||||
# 验证是否有效
|
||||
if not valid:
|
||||
# 如果新中枢和前一个中枢的中枢区间有重叠,不行成新中枢需要合并两个中枢
|
||||
is_in_last_zs = (zd > last_zs.zd and zd < last_zs.zg) or (zg < last_zs.zg and zg > last_zs.zd) or (zg > last_zs.zg and zd < last_zs.zd) or (zg < last_zs.zg and zd > last_zs.zd)
|
||||
if is_in_last_zs:
|
||||
#print(seg1.start_time, "New zs is in last zs, not valid")
|
||||
last_zs.extend_zs(seg_list[last_zs.seg_list[-1].index:(seg3.index + 1)])
|
||||
create_new_zs = False
|
||||
else:
|
||||
start_idx += 1
|
||||
continue
|
||||
else:
|
||||
create_new_zs = True
|
||||
if last_zs and create_new_zs:
|
||||
last_seg = last_zs.seg_list[-1]
|
||||
last_bi = last_seg.end_bi
|
||||
if last_bi:
|
||||
last_zs.is_sure = True
|
||||
last_zs.set_end_klc(last_bi.end_klc, last_bi.sure_time, 0, last_seg)
|
||||
last_zs.set_end_seg(last_seg)
|
||||
zs = last_zs
|
||||
if create_new_zs:
|
||||
# 创建新中枢
|
||||
gg = max(seg1.high, seg2.high, seg3.high)
|
||||
dd = min(seg1.low, seg2.low, seg3.low)
|
||||
|
||||
zs = ChanZS(seg1, len(zs_list), zs_dir)
|
||||
zs.set_zg(zg)
|
||||
zs.set_zd(zd)
|
||||
zs.set_gg(gg)
|
||||
zs.set_dd(dd)
|
||||
zs.is_sure = False
|
||||
zs.seg_list = [seg1, seg2, seg3]
|
||||
# 若第二线段与 [zd,zg] 重叠(如离开后回抽回到前中枢)则并入扩展
|
||||
added_after_leave = []
|
||||
leave_index = start_idx + 4
|
||||
is_break = False
|
||||
while leave_index < len(seg_list):
|
||||
s = seg_list[leave_index]
|
||||
if not s.is_sure:
|
||||
break
|
||||
sh = max(s.start_bi.high, s.end_bi.high) if s.end_bi else s.start_bi.high
|
||||
sl = min(s.start_bi.low, s.end_bi.low) if s.end_bi else s.start_bi.low
|
||||
if sh >= zs.zd and sl <= zs.zg:
|
||||
added_after_leave.append(s.pre)
|
||||
added_after_leave.append(s)
|
||||
leave_index += 2
|
||||
else:
|
||||
next_seg = s.next
|
||||
if next_seg and next_seg.is_sure:
|
||||
if next_seg.dir == Chan_SEG_DIR.UP:
|
||||
if next_seg.high <= zs.zg and next_seg.low >= zs.zd:
|
||||
leave_index += 2
|
||||
continue
|
||||
else:
|
||||
is_break = True
|
||||
else:
|
||||
if next_seg.low >= zs.zd and next_seg.low <= zs.zg:
|
||||
leave_index += 2
|
||||
continue
|
||||
else:
|
||||
is_break = True
|
||||
else:
|
||||
break
|
||||
if is_break:
|
||||
break
|
||||
if added_after_leave:
|
||||
#print(len(added_after_leave))
|
||||
segs_for_zs = list(zs.seg_list) + list(added_after_leave)
|
||||
seg_highs = [s.high for s in segs_for_zs]
|
||||
seg_lows = [s.low for s in segs_for_zs]
|
||||
zs.set_gg(max(seg_highs))
|
||||
zs.set_dd(min(seg_lows))
|
||||
zs.seg_list = segs_for_zs
|
||||
seg = segs_for_zs[-1]
|
||||
#if seg.end_bi:
|
||||
#zs.set_end_klc(seg.end_bi.end_klc, seg.sure_time, 0, seg)
|
||||
#zs.set_end_seg(seg)
|
||||
#zs.is_sure = True
|
||||
start_idx = start_idx + len(added_after_leave)
|
||||
if last_zs and last_zs.index != zs.index:
|
||||
last_zs.set_next(zs)
|
||||
zs.set_pre(last_zs)
|
||||
|
||||
zs_list.append(zs)
|
||||
last_zs = zs
|
||||
|
||||
# 移动到下一组
|
||||
start_idx += 4
|
||||
if last_zs:
|
||||
last_zs.is_sure = seg_list[-1].is_sure
|
||||
"""
|
||||
# 处理最后一个未确认的中枢 - 不自动扩展,保持未完成状态
|
||||
if last_zs and not last_zs.is_sure:
|
||||
# 获取中枢最后一个线段的索引
|
||||
if last_zs.seg_list and len(last_zs.seg_list) > 0:
|
||||
last_seg_of_zs = last_zs.seg_list[-1]
|
||||
# 找到这个线段在seg_list中的索引
|
||||
last_seg_idx = -1
|
||||
for i, seg in enumerate(seg_list):
|
||||
if seg == last_seg_of_zs:
|
||||
last_seg_idx = i
|
||||
break
|
||||
|
||||
# 从中枢最后一个线段之后检查是否有离开
|
||||
has_leave = False
|
||||
if last_seg_idx >= 0 and last_seg_idx + 1 < len(seg_list):
|
||||
for i in range(last_seg_idx + 1, len(seg_list)):
|
||||
seg = seg_list[i]
|
||||
if seg.is_sure:
|
||||
# 检查是否离开中枢
|
||||
leave = (seg.low > last_zs.zg and seg.high > last_zs.zg) or \
|
||||
(seg.high < last_zs.zd and seg.low < last_zs.zd)
|
||||
if leave:
|
||||
has_leave = True
|
||||
break
|
||||
|
||||
if not has_leave:
|
||||
# 没有离开,保持未完成状态
|
||||
pass
|
||||
else:
|
||||
# 有离开,确认中枢
|
||||
if last_seg_of_zs.end_bi:
|
||||
#print(last_seg_of_zs.start_time, "last_seg_of_zs.end_time", last_seg_of_zs.end_time)
|
||||
last_zs.set_end_klc(last_seg_of_zs.end_bi.end_klc, last_seg_of_zs.sure_time, 0, last_seg_of_zs)
|
||||
last_zs.set_end_seg(last_seg_of_zs)
|
||||
last_zs.is_sure = True
|
||||
"""
|
||||
return zs_list
|
||||
|
||||
|
||||
def get_big_zs_list(self, zs_list):
|
||||
"""
|
||||
中枢扩张:将区间重叠的连续中枢合并为大级别中枢,便于显示更大级别的震荡区间。
|
||||
重叠定义:两中枢 [zd,zg] 有交集,即 (zs_i.zg >= zs_j.zd and zs_i.zd <= zs_j.zg)。
|
||||
"""
|
||||
big_list = []
|
||||
if len(zs_list) < 2:
|
||||
return big_list
|
||||
i = 0
|
||||
while i < len(zs_list):
|
||||
group = [zs_list[i]]
|
||||
j = i + 1
|
||||
while j < len(zs_list):
|
||||
cur = zs_list[j]
|
||||
# 与当前组内任一中枢有重叠即算扩张(通常只需与组内最后一个比)
|
||||
last_in_group = group[-1]
|
||||
overlap = (last_in_group.zg >= cur.zd and last_in_group.zd <= cur.zg)
|
||||
if overlap:
|
||||
group.append(cur)
|
||||
j += 1
|
||||
else:
|
||||
break
|
||||
if len(group) >= 2:
|
||||
big = ChanZS_Big(group)
|
||||
big.index = len(big_list)
|
||||
big_list.append(big)
|
||||
i = j if len(group) >= 2 else i + 1
|
||||
return big_list
|
||||
|
||||
@@ -9,21 +9,20 @@ warnings.filterwarnings(
|
||||
|
||||
from datetime import timedelta
|
||||
from pandas import DataFrame
|
||||
from ChanEnum import Chan_FX_TYPE, Chan_KLINE_DIR, Chan_BI_DIR, Chan_SEG_DIR, Chan_ZS_DIR, Chan_BSP_DIR, Chan_BSP_TYPE, Chan_KLC_FX, Chan_MACD_STATE, Chan_PRICE_TREND, Chan_KLU_PATTERN
|
||||
from ChanKLU import ChanKLU
|
||||
from ChanKLC import ChanKLC
|
||||
from ChanBI import ChanBI
|
||||
from ChanSBI import ChanSBI
|
||||
from ChanSEG import ChanSEG
|
||||
from ChanZS import ChanZS
|
||||
from ChanBSP import ChanBSP
|
||||
import talib.abstract as ta
|
||||
from chanlun.core.ChanEnum import Chan_FX_TYPE, Chan_KLINE_DIR, Chan_BI_DIR, Chan_SEG_DIR, Chan_ZS_DIR, Chan_BSP_DIR, Chan_BSP_TYPE, Chan_KLC_FX, Chan_MACD_STATE, Chan_PRICE_TREND, Chan_KLU_PATTERN
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
from chanlun.core.ChanKLC import ChanKLC
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
from chanlun.core.ChanSBI import ChanSBI
|
||||
from chanlun.core.ChanSEG import ChanSEG
|
||||
from chanlun.core.ChanZS import ChanZS
|
||||
from chanlun.core.ChanBSP import ChanBSP
|
||||
import pandas as pd
|
||||
from technical.util import resample_to_interval
|
||||
from decimal import Decimal
|
||||
import numpy as np
|
||||
from ChanMACD import ChanMACD
|
||||
from TF_DF import TF_DF
|
||||
from chanlun.indicators.ChanMACD import ChanMACD
|
||||
from chanlun.pipeline.timeframe import TF_DF
|
||||
from chanlun.analysis.ChanZone import StructureZone, StructureZoneConfig, analyze_structure_zones
|
||||
|
||||
class ChanLun():
|
||||
def __init__(self):
|
||||
@@ -125,7 +124,18 @@ class ChanLun():
|
||||
|
||||
|
||||
|
||||
|
||||
def get_bsp_state(self, dataframe):
|
||||
return self.tf_df.get_bsp_state(dataframe)
|
||||
|
||||
def get_structure_zones(self, current_price=None, config=None):
|
||||
if config is None:
|
||||
config = StructureZoneConfig()
|
||||
return analyze_structure_zones(
|
||||
self.tf_df_dict,
|
||||
self.ema_symbols,
|
||||
current_price=current_price,
|
||||
config=config,
|
||||
)
|
||||
# TF_DF methods ------------------------------------------
|
||||
def get_ema_state(self, dataframe):
|
||||
return self.tf_df.get_ema_state(dataframe)
|
||||
@@ -159,6 +169,8 @@ class ChanLun():
|
||||
return self.tf_df.find_second_bsp(bi_list, first_bsp_list)
|
||||
def find_all_bsp(self, bi_list, bi_zs_list):
|
||||
return self.tf_df.find_all_bsp(bi_list, bi_zs_list)
|
||||
def cal_fast_bsp(self, df=None, bi_zs_list=None, htf_chan=None, with_htf=True, timeframe=None, **kw):
|
||||
return self.tf_df.cal_fast_bsp(df, bi_zs_list, htf_chan, with_htf, timeframe, **kw)
|
||||
def get_zs_list(self, bi_list, seg_list):
|
||||
return self.tf_df.get_zs_list(bi_list, seg_list)
|
||||
def cal_bi_zs(self, seg_list):
|
||||
@@ -166,6 +178,17 @@ class ChanLun():
|
||||
def cal_bi_zs_list(self, bi_list):
|
||||
#return self.tf_df.cal_bi_zs(bi_list)
|
||||
return self.tf_df.cal_bi_zs_list(bi_list)
|
||||
def cal_bi_zs_list_pure(self, bi_list):
|
||||
return self.tf_df.cal_bi_zs_list_pure(bi_list)
|
||||
def init_stream(self, dataframe, interval=1, timeframe=None):
|
||||
self.tf_df.init_stream(dataframe, interval, timeframe)
|
||||
return self.tf_df
|
||||
def append_bar(self, row):
|
||||
return self.tf_df.append_bar(row)
|
||||
def replace_last_bar(self, row):
|
||||
return self.tf_df.replace_last_bar(row)
|
||||
def get_bi_zs_list(self, bi_list):
|
||||
return self.tf_df.get_bi_zs_list(bi_list)
|
||||
def get_decimal(self, value):
|
||||
return Decimal("{:.2f}".format(value))
|
||||
def get_klc_list(self, klu_list):
|
||||
@@ -0,0 +1,52 @@
|
||||
"""OHLCV resampling — replaces `technical.util.resample_to_interval`.
|
||||
|
||||
That was the only symbol this project imported from `technical`, which in turn
|
||||
pulled in the freqtrade dependency chain. Behaviour is preserved exactly,
|
||||
including the left-labelled bins (rows are candle *open* times) and the
|
||||
`dropna()` that drops empty intervals.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pandas as pd
|
||||
|
||||
__all__ = ["TICKER_INTERVAL_MINUTES", "resample_to_interval"]
|
||||
|
||||
TICKER_INTERVAL_MINUTES: dict[str, int] = {
|
||||
"1m": 1,
|
||||
"5m": 5,
|
||||
"15m": 15,
|
||||
"30m": 30,
|
||||
"1h": 60,
|
||||
"60m": 60,
|
||||
"2h": 120,
|
||||
"4h": 240,
|
||||
"6h": 360,
|
||||
"12h": 720,
|
||||
"1d": 1440,
|
||||
"1w": 10080,
|
||||
}
|
||||
|
||||
_OHLC_AGG = {
|
||||
"open": "first",
|
||||
"high": "max",
|
||||
"low": "min",
|
||||
"close": "last",
|
||||
"volume": "sum",
|
||||
}
|
||||
|
||||
|
||||
def resample_to_interval(dataframe: pd.DataFrame, interval: int | str) -> pd.DataFrame:
|
||||
"""Resample OHLCV rows to `interval` minutes (or a timeframe string).
|
||||
|
||||
Merging the result back onto a finer frame requires care to avoid lookahead
|
||||
bias; this function only resamples.
|
||||
"""
|
||||
if isinstance(interval, str):
|
||||
interval = TICKER_INTERVAL_MINUTES[interval]
|
||||
|
||||
df = dataframe.copy()
|
||||
df = df.set_index(pd.DatetimeIndex(df["date"]))
|
||||
df = df.resample(f"{interval}min", label="left").agg(_OHLC_AGG).dropna()
|
||||
df.reset_index(inplace=True)
|
||||
return df
|
||||
@@ -0,0 +1,97 @@
|
||||
from datetime import timedelta
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from pandas import DataFrame
|
||||
from chanlun.pipeline.resample import resample_to_interval
|
||||
|
||||
from chanlun.core.ChanBI import ChanBI
|
||||
from chanlun.core.ChanBIZS import ChanBIZS
|
||||
from chanlun.core.ChanBSP import ChanBSP
|
||||
from chanlun.core.ChanEnum import (
|
||||
Chan_BI_DIR,
|
||||
Chan_BSP_DIR,
|
||||
Chan_BSP_TYPE,
|
||||
Chan_FX_TYPE,
|
||||
Chan_K_DIR,
|
||||
Chan_KLC_FX,
|
||||
Chan_KLC_STATE,
|
||||
Chan_KLINE_DIR,
|
||||
Chan_KLU_PATTERN,
|
||||
Chan_PRICE_TREND,
|
||||
Chan_SEG_DIR,
|
||||
Chan_ZS_DIR,
|
||||
)
|
||||
from chanlun.core.ChanKLC import ChanKLC
|
||||
from chanlun.core.ChanKLU import ChanKLU
|
||||
from chanlun.core.ChanSBI import ChanSBI
|
||||
from chanlun.core.ChanSEG import ChanSEG
|
||||
from chanlun.core.ChanZS import ChanZS, ChanZS_Big
|
||||
from chanlun.indicators.ChanMACD import ChanMACD
|
||||
from chanlun.pipeline.builders.bi import BiBuilderMixin
|
||||
from chanlun.pipeline.builders.bsp import BspBuilderMixin
|
||||
from chanlun.pipeline.builders.fast_bsp import FastBspBuilderMixin
|
||||
from chanlun.pipeline.builders.incremental import IncrementalBuilderMixin
|
||||
from chanlun.pipeline.builders.indicators import IndicatorsBuilderMixin
|
||||
from chanlun.pipeline.builders.kline import KlineBuilderMixin
|
||||
from chanlun.pipeline.builders.seg import SegBuilderMixin
|
||||
from chanlun.pipeline.builders.zs import ZsBuilderMixin
|
||||
|
||||
class TF_DF(IndicatorsBuilderMixin, KlineBuilderMixin, BiBuilderMixin, SegBuilderMixin, ZsBuilderMixin, BspBuilderMixin, FastBspBuilderMixin, IncrementalBuilderMixin):
|
||||
def __init__(self, df=None, interval=0, timeframe=None, lean=False):
|
||||
"""lean=True 只构建到中枢,跳过线段/走势中枢/MACD 状态机。
|
||||
|
||||
研究与实盘只吃 bi_list → 中枢 → fast_bsp 这条链;线段、zs、big_zs 和整套
|
||||
MACD 背驰状态机是 web 展示与 bsp_list 才用的。实测这些占全量构建的约四成。
|
||||
注意 lean 下 bsp_list/seg_list/chanmacd 均为空,**不要给 web 用**。
|
||||
"""
|
||||
self.lean = lean
|
||||
if df is not None:
|
||||
self.init_TF_DF(df, interval, timeframe, lean=lean)
|
||||
def init_TF_DF(self, df, interval, timeframe, lean=False):
|
||||
self.lean = lean
|
||||
self.timeframe = timeframe
|
||||
self.interval = interval
|
||||
# 检查 DataFrame 是否为空或没有 date 列
|
||||
if df is None or df.empty:
|
||||
raise ValueError(f"DataFrame for {timeframe} is empty. Please download data first.")
|
||||
if 'date' not in df.columns:
|
||||
raise ValueError(f"DataFrame for {timeframe} missing 'date' column. Columns: {df.columns.tolist()}")
|
||||
# interval=1 时不需要重采样
|
||||
if interval == 1:
|
||||
self.dataframe = df.copy()
|
||||
else:
|
||||
self.dataframe = resample_to_interval(df, interval)
|
||||
#print(self.timeframe, len(self.dataframe))
|
||||
self.dataframe = self.add_indicators(self.dataframe)
|
||||
self.klu_list = []
|
||||
self.klc_list = []
|
||||
self.bi_list = []
|
||||
self.zs_list = []
|
||||
self.bi_zs_list = []
|
||||
self.bsp_list = []
|
||||
self.fast_bsp_list = []
|
||||
self.seg_list = []
|
||||
self.klc_fx_list = []
|
||||
self.klu_list = self.cal_kl_data(self.dataframe)
|
||||
self.klc_list = self.get_klc_list(self.klu_list)
|
||||
self.bi_list = self.cal_bi_list(self.klc_list)
|
||||
self.bi_zs_list = self.cal_bi_zs_list_pure(self.bi_list)
|
||||
if self.lean:
|
||||
self.big_zs_list = []
|
||||
self.chanmacd = None
|
||||
return
|
||||
self.seg_list = self.get_seg_list(self.bi_list)
|
||||
self.zs_list = self.get_zs_list(self.bi_list, self.seg_list)
|
||||
self.big_zs_list = self.get_big_zs_list(self.zs_list)
|
||||
# get_klc_list 内已算过 ChanMACD,直接复用
|
||||
self.chanmacd = getattr(self, '_last_chan_macd', None)
|
||||
if self.chanmacd is None:
|
||||
self.chanmacd = ChanMACD(self.klu_list)
|
||||
self.klu_list = self.chanmacd.klu_list
|
||||
|
||||
|
||||
def get_current_klc(self):
|
||||
if len(self.klc_list) > 0:
|
||||
return self.klc_list[-2]
|
||||
return None
|
||||
@@ -0,0 +1 @@
|
||||
from __future__ import annotations
|
||||
@@ -0,0 +1,141 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
_CHAN = Path(__file__).resolve().parents[2]
|
||||
if str(_CHAN) not in sys.path:
|
||||
sys.path.insert(0, str(_CHAN))
|
||||
|
||||
from chanlun.pipeline.timeframe import TF_DF # noqa: E402
|
||||
|
||||
|
||||
def _zigzag_df(n=160, step=8):
|
||||
dates = pd.date_range("2024-01-01", periods=n, freq="5min")
|
||||
rows = []
|
||||
price = 100.0
|
||||
for i, date in enumerate(dates):
|
||||
up = (i // step) % 2 == 0
|
||||
if up:
|
||||
o = price
|
||||
c = price + 1.5
|
||||
h = c + 0.3
|
||||
l = o - 0.2
|
||||
else:
|
||||
o = price
|
||||
c = price - 1.5
|
||||
h = o + 0.2
|
||||
l = c - 0.3
|
||||
price = c
|
||||
rows.append(
|
||||
{
|
||||
"date": date,
|
||||
"open": o,
|
||||
"high": h,
|
||||
"low": l,
|
||||
"close": c,
|
||||
"volume": 1.0,
|
||||
}
|
||||
)
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def _sure_bi_key(bi):
|
||||
return (str(bi.start_time), bi.dir.name, round(float(bi.high), 6), round(float(bi.low), 6))
|
||||
|
||||
|
||||
def _zs_key(zs):
|
||||
return (
|
||||
str(zs.start_time),
|
||||
round(float(zs.zg), 6),
|
||||
round(float(zs.zd), 6),
|
||||
len(zs.bi_list),
|
||||
)
|
||||
|
||||
|
||||
class TestIncremental(unittest.TestCase):
|
||||
def test_init_stream_matches_batch_push(self):
|
||||
df = _zigzag_df()
|
||||
stream = TF_DF()
|
||||
stream.init_stream(df, 1, "5m")
|
||||
|
||||
batch = TF_DF()
|
||||
indexed = batch.add_indicators(df.copy())
|
||||
klu = batch.cal_kl_data(indexed)
|
||||
klc = []
|
||||
last = None
|
||||
for k in klu:
|
||||
batch._push_klu_into_klc_list(klc, k, last)
|
||||
last = k
|
||||
batch.klc_list = klc
|
||||
batch.rebuild_bi_zs()
|
||||
|
||||
self.assertEqual(len(stream.klu_list), len(klu))
|
||||
self.assertEqual(len(stream.klc_list), len(klc))
|
||||
self.assertEqual(
|
||||
[_sure_bi_key(b) for b in stream.bi_list if b.is_sure],
|
||||
[_sure_bi_key(b) for b in batch.bi_list if b.is_sure],
|
||||
)
|
||||
self.assertEqual(
|
||||
[_zs_key(z) for z in stream.bi_zs_list],
|
||||
[_zs_key(z) for z in batch.bi_zs_list],
|
||||
)
|
||||
|
||||
def test_append_bar_matches_init_stream(self):
|
||||
df = _zigzag_df()
|
||||
stream = TF_DF()
|
||||
stream.init_stream(df, 1, "5m")
|
||||
|
||||
inc = TF_DF()
|
||||
for _, row in df.iterrows():
|
||||
inc.append_bar(row)
|
||||
|
||||
self.assertEqual(len(inc.klu_list), len(stream.klu_list))
|
||||
self.assertEqual(len(inc.klc_list), len(stream.klc_list))
|
||||
self.assertEqual(
|
||||
[_sure_bi_key(b) for b in inc.bi_list if b.is_sure],
|
||||
[_sure_bi_key(b) for b in stream.bi_list if b.is_sure],
|
||||
)
|
||||
self.assertEqual(
|
||||
[_zs_key(z) for z in inc.bi_zs_list],
|
||||
[_zs_key(z) for z in stream.bi_zs_list],
|
||||
)
|
||||
|
||||
def test_replace_last_bar_keeps_count(self):
|
||||
df = _zigzag_df(n=80)
|
||||
tf = TF_DF()
|
||||
tf.init_stream(df, 1, "5m")
|
||||
n_klu = len(tf.klu_list)
|
||||
last = df.iloc[-1].copy()
|
||||
last["close"] = float(last["close"]) + 0.01
|
||||
last["high"] = max(float(last["high"]), float(last["close"]))
|
||||
tf.replace_last_bar(last)
|
||||
self.assertEqual(len(tf.klu_list), n_klu)
|
||||
self.assertGreater(len(tf.klc_list), 0)
|
||||
|
||||
def test_check_fx_skips_forming_right_wing(self):
|
||||
from types import SimpleNamespace
|
||||
|
||||
from chanlun.core.ChanEnum import Chan_FX_TYPE
|
||||
|
||||
tf = TF_DF()
|
||||
pre = SimpleNamespace(high=10, low=8)
|
||||
nxt_open = SimpleNamespace(high=11, low=7, end_klu=None)
|
||||
nxt_done = SimpleNamespace(high=11, low=7, end_klu=object())
|
||||
center = SimpleNamespace(
|
||||
pre=pre,
|
||||
next=nxt_open,
|
||||
high=12,
|
||||
low=9,
|
||||
set_fx=lambda *_a, **_k: None,
|
||||
)
|
||||
self.assertEqual(tf.check_fx(center), Chan_FX_TYPE.UNKNOWN)
|
||||
center.next = nxt_done
|
||||
self.assertEqual(tf.check_fx(center), Chan_FX_TYPE.TOP)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Pin chanlun.indicators.ta to TA-Lib's output, bar for bar.
|
||||
|
||||
These indicators feed the Chan structure builders, so a one-bar shift in the
|
||||
warm-up or a different smoothing seed silently changes every downstream
|
||||
bi/seg/zs. Equality against the reference implementation is the only check
|
||||
that catches that.
|
||||
|
||||
Skipped when talib is unavailable — which is the point of the replacement, so
|
||||
the suite still has to pass without it. Run in an environment that has talib
|
||||
whenever chanlun/indicators/ta.py changes.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
|
||||
|
||||
from chanlun.indicators import ta # noqa: E402
|
||||
from chanlun.pipeline.resample import resample_to_interval # noqa: E402
|
||||
|
||||
try:
|
||||
import talib.abstract as reference
|
||||
except ImportError: # pragma: no cover
|
||||
reference = None
|
||||
|
||||
requires_talib = unittest.skipIf(reference is None, "talib not installed")
|
||||
|
||||
|
||||
def make_ohlcv(n: int = 900, seed: int = 7) -> pd.DataFrame:
|
||||
"""Random walk with enough range for BBANDS(365) and EMA(208) to warm up."""
|
||||
rng = np.random.default_rng(seed)
|
||||
close = 100.0 + np.cumsum(rng.normal(0.0, 1.0, n))
|
||||
spread = np.abs(rng.normal(0.0, 0.6, n)) + 0.05
|
||||
high = close + spread
|
||||
low = close - spread
|
||||
open_ = np.concatenate([[close[0]], close[:-1]])
|
||||
return pd.DataFrame(
|
||||
{
|
||||
"date": pd.date_range("2024-01-01", periods=n, freq="1min", tz="UTC"),
|
||||
"open": open_,
|
||||
"high": np.maximum.reduce([high, open_, close]),
|
||||
"low": np.minimum.reduce([low, open_, close]),
|
||||
"close": close,
|
||||
"volume": rng.uniform(1.0, 100.0, n),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
class TAEquivalence(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.df = make_ohlcv()
|
||||
|
||||
def assertSameSeries(self, got, expected, label: str) -> None:
|
||||
g = np.asarray(got, dtype=float)
|
||||
e = np.asarray(expected, dtype=float)
|
||||
self.assertEqual(g.shape, e.shape, f"{label}: shape")
|
||||
np.testing.assert_array_equal(
|
||||
np.isnan(g), np.isnan(e), err_msg=f"{label}: NaN warm-up differs"
|
||||
)
|
||||
mask = ~np.isnan(e)
|
||||
np.testing.assert_allclose(
|
||||
g[mask], e[mask], rtol=1e-9, atol=1e-8, err_msg=f"{label}: values differ"
|
||||
)
|
||||
|
||||
@requires_talib
|
||||
def test_sma(self) -> None:
|
||||
for period in (5, 20, 90, 250):
|
||||
self.assertSameSeries(
|
||||
ta.SMA(self.df, timeperiod=period),
|
||||
reference.SMA(self.df, timeperiod=period),
|
||||
f"SMA({period})",
|
||||
)
|
||||
|
||||
@requires_talib
|
||||
def test_ma(self) -> None:
|
||||
for period in (5, 10, 250):
|
||||
self.assertSameSeries(
|
||||
ta.MA(self.df, timeperiod=period),
|
||||
reference.MA(self.df, timeperiod=period),
|
||||
f"MA({period})",
|
||||
)
|
||||
|
||||
@requires_talib
|
||||
def test_ema(self) -> None:
|
||||
for period in (5, 7, 10, 13, 24, 26, 30, 52, 104, 156, 208):
|
||||
self.assertSameSeries(
|
||||
ta.EMA(self.df, timeperiod=period),
|
||||
reference.EMA(self.df, timeperiod=period),
|
||||
f"EMA({period})",
|
||||
)
|
||||
|
||||
@requires_talib
|
||||
def test_rsi(self) -> None:
|
||||
for period in (7, 14, 21):
|
||||
self.assertSameSeries(
|
||||
ta.RSI(self.df, timeperiod=period),
|
||||
reference.RSI(self.df, timeperiod=period),
|
||||
f"RSI({period})",
|
||||
)
|
||||
|
||||
@requires_talib
|
||||
def test_atr(self) -> None:
|
||||
for period in (7, 14, 30):
|
||||
self.assertSameSeries(
|
||||
ta.ATR(self.df, timeperiod=period),
|
||||
reference.ATR(self.df, timeperiod=period),
|
||||
f"ATR({period})",
|
||||
)
|
||||
|
||||
@requires_talib
|
||||
def test_macd(self) -> None:
|
||||
for fast, slow, signal in ((12, 26, 9), (26, 52, 9), (5, 35, 5)):
|
||||
got = ta.MACD(self.df, fastperiod=fast, slowperiod=slow, signalperiod=signal)
|
||||
exp = reference.MACD(self.df, fastperiod=fast, slowperiod=slow, signalperiod=signal)
|
||||
for col in ("macd", "macdsignal", "macdhist"):
|
||||
self.assertSameSeries(got[col], exp[col], f"MACD({fast},{slow},{signal}).{col}")
|
||||
|
||||
@requires_talib
|
||||
def test_bbands(self) -> None:
|
||||
cases = (
|
||||
(365, 3.0, 3.0),
|
||||
(120, 3.0, 3.0),
|
||||
(41, 2.3, 2.3),
|
||||
(41, 2.0, 2.0),
|
||||
(26, 3.0, 3.0),
|
||||
(20, 2.0, 2.0),
|
||||
(14, 2.0, 2.0),
|
||||
)
|
||||
for period, up, dn in cases:
|
||||
got = ta.BBANDS(self.df, timeperiod=period, nbdevup=up, nbdevdn=dn, matype=0)
|
||||
exp = reference.BBANDS(self.df, timeperiod=period, nbdevup=up, nbdevdn=dn, matype=0)
|
||||
for col in ("upperband", "middleband", "lowerband"):
|
||||
self.assertSameSeries(got[col], exp[col], f"BBANDS({period},{up},{dn}).{col}")
|
||||
|
||||
@requires_talib
|
||||
def test_bbands_is_more_accurate_than_talib_on_tiny_windows(self) -> None:
|
||||
"""A deliberate divergence, documented so nobody "fixes" it back.
|
||||
|
||||
TA-Lib derives the variance from sumsq/n - mean**2, which cancels
|
||||
catastrophically when the window is short and prices are far from zero;
|
||||
at timeperiod=2 it drifts ~1e-6. Rolling std is accurate there, so the
|
||||
two disagree. No timeperiod below 14 is used in this codebase, and the
|
||||
periods that are used agree to ~1e-10 (covered by test_bbands).
|
||||
"""
|
||||
got = ta.BBANDS(self.df, timeperiod=2, nbdevup=1.0, nbdevdn=1.0, matype=0)["upperband"]
|
||||
exp = reference.BBANDS(self.df, timeperiod=2, nbdevup=1.0, nbdevdn=1.0, matype=0)["upperband"]
|
||||
|
||||
window = self.df["close"].rolling(2)
|
||||
truth = window.mean() + window.std(ddof=0)
|
||||
ours = np.nanmax(np.abs((got - truth).to_numpy()))
|
||||
theirs = np.nanmax(np.abs((exp - truth).to_numpy()))
|
||||
self.assertLess(ours, 1e-9)
|
||||
self.assertLess(ours, theirs)
|
||||
|
||||
@requires_talib
|
||||
def test_matches_on_real_price_scale(self) -> None:
|
||||
"""Guard against tolerances that only hold near 100."""
|
||||
df = self.df.copy()
|
||||
for col in ("open", "high", "low", "close"):
|
||||
df[col] *= 900.0
|
||||
self.assertSameSeries(
|
||||
ta.ATR(df, timeperiod=14), reference.ATR(df, timeperiod=14), "ATR@scale"
|
||||
)
|
||||
self.assertSameSeries(
|
||||
ta.RSI(df, timeperiod=14), reference.RSI(df, timeperiod=14), "RSI@scale"
|
||||
)
|
||||
|
||||
|
||||
class ResampleEquivalence(unittest.TestCase):
|
||||
@unittest.skipIf(
|
||||
__import__("importlib").util.find_spec("technical") is None,
|
||||
"technical not installed",
|
||||
)
|
||||
def test_matches_technical(self) -> None:
|
||||
from technical.util import resample_to_interval as ref_resample
|
||||
|
||||
df = make_ohlcv(600)
|
||||
for interval in (5, 15, 60, "5m", "1h"):
|
||||
got = resample_to_interval(df, interval)
|
||||
exp = ref_resample(df, interval)
|
||||
pd.testing.assert_frame_equal(got, exp, check_exact=False, rtol=1e-12)
|
||||
|
||||
def test_shapes_without_reference(self) -> None:
|
||||
df = make_ohlcv(120)
|
||||
out = resample_to_interval(df, 5)
|
||||
self.assertEqual(list(out.columns), ["date", "open", "high", "low", "close", "volume"])
|
||||
self.assertLessEqual(len(out), 120 // 5 + 1)
|
||||
self.assertTrue((out["high"] >= out["low"]).all())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,84 +0,0 @@
|
||||
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.btc_chan.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"SOL/USDT:USDT",
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800,
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8882,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.btc_perpetual.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short": true,
|
||||
"timeframe": "1m",
|
||||
"process_only_new_candles": false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "YOUR_BINANCE_API_KEY",
|
||||
"secret": "YOUR_BINANCE_API_SECRET",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "YOUR_TELEGRAM_BOT_TOKEN",
|
||||
"chat_id": "YOUR_TELEGRAM_CHAT_ID"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8820,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "change_me_to_a_random_secret_key",
|
||||
"ws_token": "change_me_to_a_random_ws_token",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "BTC_Perpetual_Bot",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chan.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT",
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800,
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8800,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_btc_15.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8811,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_btc_15.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8813,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_btc_60.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8814,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_btc_k.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8815,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_btc_k.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short": true,
|
||||
"timeframe": "1m",
|
||||
"process_only_new_candles": false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8815,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_btc_15.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8820,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_btc_15.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8820,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_eth_60.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"ETH/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8813,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_btc_15.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "5m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "other",
|
||||
"use_order_book": false,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "other",
|
||||
"use_order_book": false,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8813,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_sol.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8811,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,151 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 2,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.95,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_sol_optimized.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short": true,
|
||||
"timeframe": "5m",
|
||||
"process_only_new_candles": false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 2,
|
||||
"exit": 2,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "other",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "",
|
||||
"secret": "",
|
||||
"ccxt_config": {
|
||||
"options": {"defaultType": "swap"}
|
||||
},
|
||||
"ccxt_async_config": {
|
||||
"enableRateLimit": true,
|
||||
"rateLimit": 1000,
|
||||
"timeout": 30000
|
||||
},
|
||||
"pair_whitelist": [
|
||||
"SOL/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": []
|
||||
},
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "",
|
||||
"chat_id": ""
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": false,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8080,
|
||||
"verbosity": "error",
|
||||
"jwt_secret_key": "",
|
||||
"username": "",
|
||||
"password": ""
|
||||
},
|
||||
"discord": {
|
||||
"enabled": false,
|
||||
"webhook": "",
|
||||
"webhook_avatar": "",
|
||||
"poll_delay_seconds": 10
|
||||
},
|
||||
"notification_settings": {
|
||||
"status": "on",
|
||||
"status_inactive_after": 7,
|
||||
"timeframe_condition_change": "on",
|
||||
"telegram": { },
|
||||
"discord": { },
|
||||
"notify_all": true
|
||||
},
|
||||
"bot_name": "SOL_Chan_Optimized",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 5
|
||||
},
|
||||
"edge": {
|
||||
"enabled": false,
|
||||
"process_throttle_secs": 3600,
|
||||
"calculate_since_number_of_days": 7,
|
||||
"allowed_risk": 0.01,
|
||||
"stoploss_range_min": -0.01,
|
||||
"stoploss_range_max": -0.007,
|
||||
"stoploss_range_step": 0.001,
|
||||
"minimum_winrate": 0.60,
|
||||
"minimum_expectancy": 0.20,
|
||||
"min_trade_number": 10,
|
||||
"max_trade_duration_minute": 1440,
|
||||
"remove_pumps": false
|
||||
},
|
||||
"order_types": {
|
||||
"entry": "limit",
|
||||
"exit": "market",
|
||||
"emergency_exit": "market",
|
||||
"force_exit": "market",
|
||||
"force_entry": "market",
|
||||
"stoploss": "market",
|
||||
"stoploss_on_exchange": false,
|
||||
"stoploss_on_exchange_interval": 60
|
||||
},
|
||||
"order_time_in_force": {
|
||||
"entry": "GTC",
|
||||
"exit": "GTC"
|
||||
},
|
||||
"strategy_path": "./user_data/Chan/strategies/",
|
||||
"strategy": "ChanLun_SOL_Optimized",
|
||||
"minimal_roi": {
|
||||
"0": 0.012,
|
||||
"120": 0.010,
|
||||
"240": 0.007,
|
||||
"360": 0.005
|
||||
},
|
||||
"stoploss": -0.007,
|
||||
"trailing_stop": true,
|
||||
"trailing_stop_positive": 0.003,
|
||||
"trailing_stop_positive_offset": 0.005,
|
||||
"trailing_only_offset_is_reached": true,
|
||||
"use_custom_stoploss": true,
|
||||
"max_open_trades_per_pair": 1,
|
||||
"dry_run_wallet_refresh_time": 5,
|
||||
"caches": {
|
||||
"dataframe": {
|
||||
"enabled": true,
|
||||
"refresh_period": 60
|
||||
},
|
||||
"strategy": {
|
||||
"enabled": true,
|
||||
"refresh_period": 300
|
||||
}
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"config": {
|
||||
"pairs": ["SOL/USDT:USDT"]
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_sol.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : true,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"SOL/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"freqai": {
|
||||
"enabled": true,
|
||||
"purge_old_models": true,
|
||||
"train_period_days": 30,
|
||||
"backtest_period_days": 7,
|
||||
"identifier": "chanLun1",
|
||||
"live_retrain_hours": 1,
|
||||
"expiration_hours": 48,
|
||||
"fit_live_predictions_candles": 0,
|
||||
"data_kitchen_thread_count": 4,
|
||||
"save_backtest_models": true,
|
||||
"save_metadata": true,
|
||||
"feature_parameters": {
|
||||
"include_timeframes": [
|
||||
"1m",
|
||||
"5m",
|
||||
"15m"
|
||||
],
|
||||
"include_corr_pairlist": [
|
||||
"BTC/USDT:USDT",
|
||||
"ETH/USDT:USDT"
|
||||
],
|
||||
"label_period_candles": 24,
|
||||
"include_shifted_candles": 2,
|
||||
"indicator_periods_candles": [10, 20, 30],
|
||||
"allow_duplicate_train": true
|
||||
},
|
||||
"data_split_parameters": {
|
||||
"test_size": 0.25
|
||||
},
|
||||
"model_training_parameters": {
|
||||
"n_estimators": 100,
|
||||
"learning_rate": 0.1,
|
||||
"max_depth": 5,
|
||||
"subsample": 0.8,
|
||||
"colsample_bytree": 0.8,
|
||||
"use_label_for_weight": true,
|
||||
"booster": "gbtree",
|
||||
"num_class": 2
|
||||
}
|
||||
},
|
||||
"freqaimodel": "XGBoostClassifier",
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8811,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 3,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.btc_chan.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "30m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "ocQUqAPSD9PDhIL2lTMlMan0wMFwvvu5Fv8eYF3wUM8yPytm2jBgz51cgiHXw7J6",
|
||||
"secret": "yHIc6FOnSoOI2FvygpRKKku4FKaZGI5DSwC83Ip4wRfUcxszennF6hy2vhbVuLYJ",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT",
|
||||
"ETH/USDT:USDT",
|
||||
"SOL/USDT:USDT",
|
||||
"WIF/USDT:USDT",
|
||||
"1000PEPE/USDT:USDT",
|
||||
"DOGS/USDT:USDT",
|
||||
"ORDI/USDT:USDT",
|
||||
"AAVE/USDT:USDT",
|
||||
"REEF/USDT:USDT",
|
||||
"1000SATS/USDT:USDT",
|
||||
"SUI/USDT:USDT",
|
||||
"1INCH/USDT:USDT",
|
||||
"DOGE/USDT:USDT",
|
||||
"TON/USDT:USDT",
|
||||
"UNI/USDT:USDT",
|
||||
"XRP/USDT:USDT",
|
||||
"SUN/USDT:USDT",
|
||||
"NOT/USDT:USDT",
|
||||
"RARE/USDT:USDT",
|
||||
"RDNT/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "VolumePairList",
|
||||
"number_assets": 10,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8088,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "5m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT",
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "5985766683:AAEx2Nm_4y2IC0Tj4Hhz7djVRJRso0JKaj0",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8088,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.btc_chan.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"SOL/USDT:USDT",
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800,
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": false,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8888,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"strategy": "ChanStrategy",
|
||||
"db_url": "sqlite:///tradesv3.btc_chan.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"SOL/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": false,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8818,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chan.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"SOL/USDT:USDT",
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800,
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8815,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDC",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chan.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "hyperliquid",
|
||||
"walletAddress": "0xA834b6d3Fa1D8A55ea8e502685ef5cbD2b2D3343",
|
||||
"privateKey": "0xa399cea4c01be67c16b88e1d2121ed6e72bab6b4e8d81684ed03ce78f8b4f827",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"PURR/USDC:USDC",
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800,
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8815,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chan_sol_30.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"SOL/USDT:USDT",
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800,
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8818,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chan.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT",
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800,
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8801,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 3,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"db_url": "sqlite:///tradesv3.deepseek_trader.sqlite",
|
||||
"dry_run": true,
|
||||
"dry_run_wallet": 10000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 0,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT",
|
||||
"ETH/USDT:USDT",
|
||||
"SOL/USDT:USDT",
|
||||
"WIF/USDT:USDT",
|
||||
"1000PEPE/USDT:USDT",
|
||||
"DOGS/USDT:USDT",
|
||||
"ORDI/USDT:USDT",
|
||||
"AAVE/USDT:USDT",
|
||||
"REEF/USDT:USDT",
|
||||
"1000SATS/USDT:USDT",
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 10,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "5985766683:AAEx2Nm_4y2IC0Tj4Hhz7djVRJRso0JKaj0",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8001,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": true,
|
||||
"internals": {
|
||||
"process_throttle_secs": 15
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.ema26_ema52_cross.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"SOL/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8820,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.ema_pattern.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1h",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8888,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 2,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.elliottwave_btc.sqlite",
|
||||
"dry_run_wallet": 10000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"unfilledtimeout": {
|
||||
"entry": 5,
|
||||
"exit": 5,
|
||||
"exit_timeout_count": 3,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "",
|
||||
"secret": "",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "",
|
||||
"chat_id": ""
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": false,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8080,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "freqtrade_secret",
|
||||
"ws_token": "freqtrade_ws",
|
||||
"username": "freqtrade",
|
||||
"password": "freqtrade"
|
||||
},
|
||||
"bot_name": "ElliottWaveBTC"
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.freqai_sol.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short": true,
|
||||
"timeframe": "5m",
|
||||
"process_only_new_candles": true,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "",
|
||||
"secret": "",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"SOL/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList"
|
||||
}
|
||||
],
|
||||
"freqai": {
|
||||
"enabled": true,
|
||||
"purge_old_models": 2,
|
||||
"train_period_days": 10,
|
||||
"backtest_period_days": 7,
|
||||
"live_retrain_hours": 1,
|
||||
"identifier": "sol_futures_lgbm_v1",
|
||||
"feature_parameters": {
|
||||
"include_timeframes": [
|
||||
"5m",
|
||||
"15m"
|
||||
],
|
||||
"include_corr_pairlist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"label_period_candles": 12,
|
||||
"include_shifted_candles": 1,
|
||||
"DI_threshold": 0.9,
|
||||
"weight_factor": 0.9,
|
||||
"principal_component_analysis": false,
|
||||
"use_SVM_to_remove_outliers": true,
|
||||
"indicator_periods_candles": [
|
||||
14
|
||||
],
|
||||
"plot_feature_importances": 0
|
||||
},
|
||||
"data_split_parameters": {
|
||||
"test_size": 0.15,
|
||||
"random_state": 42
|
||||
},
|
||||
"model_training_parameters": {
|
||||
"n_estimators": 300,
|
||||
"learning_rate": 0.05,
|
||||
"max_depth": 5,
|
||||
"num_leaves": 31,
|
||||
"min_child_samples": 20,
|
||||
"subsample": 0.8,
|
||||
"colsample_bytree": 0.8,
|
||||
"reg_alpha": 0.1,
|
||||
"reg_lambda": 0.1,
|
||||
"n_jobs": 1,
|
||||
"verbosity": -1
|
||||
}
|
||||
},
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "",
|
||||
"chat_id": ""
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8822,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqai_sol",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 5
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.heikinashi_btc.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "1m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": true,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8814,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.ema26_ema52_cross.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"timeframe": "1m",
|
||||
"can_short" : true,
|
||||
"process_only_new_candles" : true,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "other",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "other",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"BTC/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8821,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.sol5m.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short": true,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "other",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing": {
|
||||
"price_side": "other",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"SOL/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "0.0.0.0",
|
||||
"listen_port": 8822,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "SOL5m",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 5
|
||||
}
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
{
|
||||
"$schema": "https://schema.freqtrade.io/schema.json",
|
||||
"max_open_trades": 1,
|
||||
"stake_currency": "USDT",
|
||||
"stake_amount": "unlimited",
|
||||
"tradable_balance_ratio": 0.99,
|
||||
"fiat_display_currency": "USD",
|
||||
"dry_run": true,
|
||||
"db_url": "sqlite:///tradesv3.chanlun_btc_15.sqlite",
|
||||
"dry_run_wallet": 1000,
|
||||
"cancel_open_orders_on_exit": true,
|
||||
"trading_mode": "futures",
|
||||
"margin_mode": "isolated",
|
||||
"can_short" : true,
|
||||
"timeframe" : "15m",
|
||||
"process_only_new_candles" : false,
|
||||
"unfilledtimeout": {
|
||||
"entry": 1,
|
||||
"exit": 1,
|
||||
"exit_timeout_count": 5,
|
||||
"unit": "minutes"
|
||||
},
|
||||
"entry_pricing": {
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1,
|
||||
"price_last_balance": 0.0,
|
||||
"check_depth_of_market": {
|
||||
"enabled": false,
|
||||
"bids_to_ask_delta": 1
|
||||
}
|
||||
},
|
||||
"exit_pricing":{
|
||||
"price_side": "same",
|
||||
"use_order_book": true,
|
||||
"order_book_top": 1
|
||||
},
|
||||
"exchange": {
|
||||
"name": "binance",
|
||||
"key": "hvoXanRExQvcN4tyGFvEnsSF4gqxXp6ZJnBu5lnhvlVuHaDbj2PhLBQGCLkkyeI8",
|
||||
"secret": "3UKA2oyDj7OoXrausmnaLwLlNfXmlNf2imBdmQqqKHArcJfk6X9xjaUF19wzu82l",
|
||||
"ccxt_config": {},
|
||||
"ccxt_async_config": {},
|
||||
"pair_whitelist": [
|
||||
"WIF/USDT:USDT"
|
||||
],
|
||||
"pair_blacklist": [
|
||||
"BNB/.*"
|
||||
]
|
||||
},
|
||||
"pairlists": [
|
||||
{
|
||||
"method": "StaticPairList",
|
||||
"number_assets": 1,
|
||||
"sort_key": "quoteVolume",
|
||||
"min_value": 0,
|
||||
"refresh_period": 1800
|
||||
}
|
||||
],
|
||||
"telegram": {
|
||||
"enabled": false,
|
||||
"token": "7677670958:AAFL_jgZvNUTPR3R3vWieREX_tDVi9w2C1Y",
|
||||
"chat_id": "580807463"
|
||||
},
|
||||
"api_server": {
|
||||
"enabled": true,
|
||||
"listen_ip_address": "127.0.0.1",
|
||||
"listen_port": 8811,
|
||||
"verbosity": "error",
|
||||
"enable_openapi": false,
|
||||
"jwt_secret_key": "14d3510740e2c39a973a8895f1aa2704d98d08b86170260085709fa5ea48251d",
|
||||
"ws_token": "dtKKDnafBrX4icq_ZCw7acJTahTK4h_yvg",
|
||||
"CORS_origins": [],
|
||||
"username": "freqtrader",
|
||||
"password": "FreqTrade007"
|
||||
},
|
||||
"bot_name": "freqtrade",
|
||||
"initial_state": "running",
|
||||
"force_entry_enable": false,
|
||||
"internals": {
|
||||
"process_throttle_secs": 2
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -1,20 +0,0 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
ENV PYTHONUNBUFFERED=1 \
|
||||
PIP_NO_CACHE_DIR=1
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY requirements.txt /app/requirements.txt
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . /app
|
||||
|
||||
ENV CONFIG_PATH=/app/config.json \
|
||||
UVICORN_HOST=0.0.0.0 \
|
||||
UVICORN_PORT=9009
|
||||
|
||||
EXPOSE 9009
|
||||
|
||||
CMD ["python", "-m", "main"]
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
{
|
||||
"exchange": "binance",
|
||||
"symbols": [
|
||||
"BTC/USDT:USDT",
|
||||
"ETH/USDT:USDT",
|
||||
"SOL/USDT:USDT",
|
||||
"WIF/USDT:USDT",
|
||||
"AAVE/USDT:USDT",
|
||||
"SUI/USDT:USDT",
|
||||
"1INCH/USDT:USDT",
|
||||
"DOGE/USDT:USDT",
|
||||
"UNI/USDT:USDT"
|
||||
],
|
||||
"start_time": "2024-01-01T00:00:00Z",
|
||||
"timeframes": ["1m", "1h", "1d", "1w"],
|
||||
"data_dir": "./data"
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
services:
|
||||
data_provider:
|
||||
build: .
|
||||
container_name: data-provider
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
CONFIG_PATH: /app/config.json
|
||||
UVICORN_HOST: 0.0.0.0
|
||||
UVICORN_PORT: "9009"
|
||||
volumes:
|
||||
- ./config.json:/app/config.json:ro
|
||||
- ./data:/app/data
|
||||
ports:
|
||||
- "9009:9009"
|
||||
|
||||
@@ -1,947 +0,0 @@
|
||||
"""
|
||||
Chan 数据服务:用 ccxt 从交易所拉取 K 线,内存缓存 + CSV 落盘;
|
||||
后台线程定期增量刷新,断线时记录 resume_since 以免漏 K;
|
||||
配置中的基础周期(如 1m/1h)可合成 DERIVED_TIMEFRAME_PLAN 中的衍生周期。
|
||||
"""
|
||||
import asyncio
|
||||
import csv
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Dict, Iterable, List, Optional
|
||||
|
||||
import ccxt # type: ignore
|
||||
import pandas as pd # type: ignore
|
||||
from fastapi import FastAPI, HTTPException, Query, WebSocket, WebSocketDisconnect
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
import uvicorn
|
||||
from technical.util import resample_to_interval
|
||||
|
||||
# docker compose logs --tail=200
|
||||
# docker compose down && docker compose build --no-cache && docker compose up -d
|
||||
|
||||
# 基础周期枚举顺序(用于衍生周期展示顺序);仅允许集合内周期作为交易所直接拉取的 tf
|
||||
TIMEFRAME_ORDER = ["1m", "1h", "1d", "1w"]
|
||||
ALLOWED_TIMEFRAMES = set(TIMEFRAME_ORDER)
|
||||
# 各基础周期一根 K 线的毫秒长度(用于历史分页与断线回退)
|
||||
TIMEFRAME_TO_MS: Dict[str, int] = {
|
||||
"1m": 60_000,
|
||||
"1h": 3_600_000,
|
||||
"1d": 86_400_000,
|
||||
"1w": 604_800_000,
|
||||
}
|
||||
# 每个基础周期可派生出的合成周期列表(由该基础周期 K 线 resample 得到)
|
||||
DERIVED_TIMEFRAME_PLAN: Dict[str, List[str]] = {
|
||||
"1m": ["2m", "3m", "4m", "5m", "10m", "15m", "20m", "25m", "30m", "45m"],
|
||||
"1h": ["2h", "3h", "4h", "5h", "6h", "7h", "8h", "9h", "10", "11h", "12h", "16h", "20h"],
|
||||
"1d": ["2d", "3d", "4d", "5d", "6d"],
|
||||
"1w": ["2w", "3w"],
|
||||
}
|
||||
CSV_FIELDNAMES = ["timestamp", "datetime", "open", "high", "low", "close", "volume"]
|
||||
DEFAULT_LIMIT = 500
|
||||
RECENT_CANDLE_LIMIT = 10
|
||||
RECENT_FETCH_INTERVAL = 5 # 后台刷新循环休眠秒数
|
||||
PERSIST_INTERVAL = 600 # 全量落盘周期(秒)
|
||||
WS_UPDATE_CANDLE_COUNT = 2 # WebSocket 增量推送最近 K 线根数
|
||||
|
||||
|
||||
logger = logging.getLogger("data_provider")
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
||||
)
|
||||
|
||||
|
||||
def to_utc_iso(timestamp_ms: int) -> str:
|
||||
"""将毫秒时间戳格式化为 UTC ISO 字符串(末尾 Z)。"""
|
||||
dt = datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone.utc)
|
||||
return dt.isoformat().replace("+00:00", "Z")
|
||||
|
||||
|
||||
def parse_timestamp(value: Optional[object]) -> Optional[int]:
|
||||
"""解析查询参数中的时间为 UTC 毫秒时间戳;支持数字或 ISO 字符串。"""
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
return int(value)
|
||||
if isinstance(value, str):
|
||||
text = value.strip()
|
||||
if not text:
|
||||
return None
|
||||
if text.isdigit():
|
||||
return int(text)
|
||||
if text.endswith("Z"):
|
||||
text = text[:-1] + "+00:00"
|
||||
try:
|
||||
dt = datetime.fromisoformat(text)
|
||||
except ValueError as exc: # pragma: no cover - informative logging
|
||||
raise ValueError(f"无法解析时间字符串: {value}") from exc
|
||||
if dt.tzinfo is None:
|
||||
dt = dt.replace(tzinfo=timezone.utc)
|
||||
else:
|
||||
dt = dt.astimezone(timezone.utc)
|
||||
return int(dt.timestamp() * 1000)
|
||||
raise ValueError(f"不支持的时间格式: {value}")
|
||||
|
||||
|
||||
def candle_to_dict(candle: Iterable[float]) -> Dict[str, float]:
|
||||
"""ccxt OHLCV 单根 [ts, o, h, l, c, v] 转为内部字典结构。"""
|
||||
ts = int(candle[0])
|
||||
return {
|
||||
"timestamp": ts,
|
||||
"datetime": to_utc_iso(ts),
|
||||
"open": float(candle[1]),
|
||||
"high": float(candle[2]),
|
||||
"low": float(candle[3]),
|
||||
"close": float(candle[4]),
|
||||
"volume": float(candle[5]),
|
||||
}
|
||||
|
||||
|
||||
def timeframe_to_minutes(tf: str) -> Optional[int]:
|
||||
"""将如 15m、2h 转为「分钟数」,供 resample 与衍生周期计算。"""
|
||||
if not tf:
|
||||
return None
|
||||
unit = tf[-1]
|
||||
try:
|
||||
value = int(tf[:-1])
|
||||
except ValueError:
|
||||
return None
|
||||
multiplier = {
|
||||
"m": 1,
|
||||
"h": 60,
|
||||
"d": 1_440,
|
||||
"w": 10_080,
|
||||
}.get(unit)
|
||||
if multiplier is None:
|
||||
return None
|
||||
return value * multiplier
|
||||
|
||||
|
||||
class WebSocketManager:
|
||||
"""管理 WebSocket 连接及订阅,线程安全地广播 K 线更新。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._subscriptions: Dict[tuple, set] = {}
|
||||
self._async_lock = asyncio.Lock()
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
|
||||
def set_loop(self, loop: asyncio.AbstractEventLoop) -> None:
|
||||
self._loop = loop
|
||||
|
||||
async def connect(self, ws: WebSocket) -> None:
|
||||
await ws.accept()
|
||||
logger.info("WebSocket 客户端已连接")
|
||||
|
||||
async def disconnect(self, ws: WebSocket) -> None:
|
||||
async with self._async_lock:
|
||||
for key in list(self._subscriptions):
|
||||
self._subscriptions[key].discard(ws)
|
||||
if not self._subscriptions[key]:
|
||||
del self._subscriptions[key]
|
||||
logger.info("WebSocket 客户端已断开")
|
||||
|
||||
async def subscribe(self, ws: WebSocket, symbol: str, timeframe: str) -> None:
|
||||
key = (symbol, timeframe)
|
||||
async with self._async_lock:
|
||||
self._subscriptions.setdefault(key, set()).add(ws)
|
||||
logger.info("WebSocket 订阅: %s %s", symbol, timeframe)
|
||||
|
||||
async def unsubscribe(self, ws: WebSocket, symbol: str, timeframe: str) -> None:
|
||||
key = (symbol, timeframe)
|
||||
async with self._async_lock:
|
||||
if key in self._subscriptions:
|
||||
self._subscriptions[key].discard(ws)
|
||||
if not self._subscriptions[key]:
|
||||
del self._subscriptions[key]
|
||||
|
||||
def has_subscribers(self, symbol: str, timeframe: str) -> bool:
|
||||
"""非异步快速检查(供同步线程调用)。"""
|
||||
return bool(self._subscriptions.get((symbol, timeframe)))
|
||||
|
||||
async def broadcast(
|
||||
self, symbol: str, timeframe: str, candles: List[Dict], msg_type: str = "kline",
|
||||
) -> None:
|
||||
key = (symbol, timeframe)
|
||||
async with self._async_lock:
|
||||
subscribers = list(self._subscriptions.get(key, set()))
|
||||
if not subscribers:
|
||||
return
|
||||
message = json.dumps(
|
||||
{"type": msg_type, "symbol": symbol, "timeframe": timeframe, "data": candles},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
dead: list = []
|
||||
for ws in subscribers:
|
||||
try:
|
||||
await ws.send_text(message)
|
||||
except Exception:
|
||||
dead.append(ws)
|
||||
if dead:
|
||||
async with self._async_lock:
|
||||
for ws in dead:
|
||||
self._subscriptions.get(key, set()).discard(ws)
|
||||
|
||||
def broadcast_from_thread(
|
||||
self, symbol: str, timeframe: str, candles: List[Dict], msg_type: str = "kline",
|
||||
) -> None:
|
||||
"""供同步后台线程调用,将广播提交到 asyncio 事件循环。"""
|
||||
if self._loop is None or self._loop.is_closed():
|
||||
return
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self.broadcast(symbol, timeframe, candles, msg_type),
|
||||
self._loop,
|
||||
)
|
||||
|
||||
|
||||
class DataProvider:
|
||||
"""封装交易所连接、本地 CSV、内存缓存、断线恢复与衍生周期聚合。"""
|
||||
|
||||
def __init__(self, config_path: Path) -> None:
|
||||
self.config_path = config_path
|
||||
self.config = self._load_config()
|
||||
self.exchange_name: str = self.config["exchange"]
|
||||
self.symbols: List[str] = self._load_symbols(self.config)
|
||||
self.timeframes: List[str] = self._validate_timeframes(self.config.get("timeframes"))
|
||||
self.data_dir = Path(self.config.get("data_dir", "./data")).expanduser()
|
||||
start = parse_timestamp(self.config.get("start_time"))
|
||||
if start is None:
|
||||
raise ValueError("配置文件必须包含 start_time 字段")
|
||||
self.start_time_ms: int = start
|
||||
self.exchange = self._init_exchange()
|
||||
self.data: Dict[str, Dict[str, List[Dict[str, float]]]] = {
|
||||
symbol: {tf: [] for tf in self.timeframes} for symbol in self.symbols
|
||||
}
|
||||
# 衍生周期 -> 用于合成的交易所基础周期(每个衍生只对应一个 base)
|
||||
self.derived_map: Dict[str, str] = {}
|
||||
for base_tf in self.timeframes:
|
||||
for derived_tf in DERIVED_TIMEFRAME_PLAN.get(base_tf, []):
|
||||
self.derived_map.setdefault(derived_tf, base_tf)
|
||||
# 衍生周期展示顺序:按 TIMEFRAME_ORDER 中的基础周期依次展开
|
||||
derived_order: List[str] = []
|
||||
for base_tf in TIMEFRAME_ORDER:
|
||||
if base_tf not in self.timeframes:
|
||||
continue
|
||||
for derived_tf in DERIVED_TIMEFRAME_PLAN.get(base_tf, []):
|
||||
if derived_tf in self.derived_map and derived_tf not in derived_order:
|
||||
derived_order.append(derived_tf)
|
||||
self.available_timeframes: List[str] = list(self.timeframes) + derived_order
|
||||
self._lock = threading.RLock()
|
||||
self._ready = threading.Event()
|
||||
self._stop_event = threading.Event()
|
||||
self._fetch_thread: Optional[threading.Thread] = None
|
||||
self._persist_thread: Optional[threading.Thread] = None
|
||||
# 记录断线后需要从哪个 since 重新拉取(symbol -> timeframe -> since_ms)
|
||||
self._resume_since: Dict[str, Dict[str, int]] = {}
|
||||
# 恢复点持久化文件
|
||||
self._resume_file: Path = self.data_dir / "resume_since.json"
|
||||
# 尝试加载历史恢复点
|
||||
self._load_resume_since()
|
||||
self._update_callbacks: List = []
|
||||
|
||||
def _load_config(self) -> Dict[str, object]:
|
||||
"""读取 JSON 配置文件。"""
|
||||
if not self.config_path.exists():
|
||||
raise FileNotFoundError(f"未找到配置文件: {self.config_path}")
|
||||
with self.config_path.open("r", encoding="utf-8") as fp:
|
||||
return json.load(fp)
|
||||
|
||||
def _load_symbols(self, config: Dict[str, object]) -> List[str]:
|
||||
"""从 symbols 列表、逗号分隔字符串或单字段 symbol 解析交易对,去重保序。"""
|
||||
raw_symbols: List[str] = []
|
||||
symbols_value = config.get("symbols")
|
||||
if isinstance(symbols_value, list):
|
||||
raw_symbols = [str(item).strip() for item in symbols_value if isinstance(item, str) and item.strip()]
|
||||
elif isinstance(symbols_value, str) and symbols_value.strip():
|
||||
raw_symbols = [item.strip() for item in symbols_value.split(",") if item.strip()]
|
||||
symbol_single = config.get("symbol")
|
||||
if not raw_symbols and isinstance(symbol_single, str) and symbol_single.strip():
|
||||
raw_symbols = [symbol_single.strip()]
|
||||
if not raw_symbols:
|
||||
raise ValueError("配置文件必须提供 symbols(列表或逗号分隔字符串)或 symbol 字段")
|
||||
unique: List[str] = []
|
||||
for item in raw_symbols:
|
||||
if item not in unique:
|
||||
unique.append(item)
|
||||
return unique
|
||||
|
||||
def _validate_timeframes(self, configured: Optional[Iterable[str]]) -> List[str]:
|
||||
"""校验周期在允许集合内;未配置则默认 TIMEFRAME_ORDER 全部;顺序优先按 TIMEFRAME_ORDER。"""
|
||||
if not configured:
|
||||
return list(TIMEFRAME_ORDER)
|
||||
invalid = [tf for tf in configured if tf not in ALLOWED_TIMEFRAMES]
|
||||
if invalid:
|
||||
raise ValueError(f"不支持的时间周期: {invalid}. 允许值: {sorted(ALLOWED_TIMEFRAMES)}")
|
||||
unique = []
|
||||
seen = set()
|
||||
for tf in TIMEFRAME_ORDER:
|
||||
if tf in configured and tf not in seen:
|
||||
unique.append(tf)
|
||||
seen.add(tf)
|
||||
for tf in configured:
|
||||
if tf not in seen:
|
||||
unique.append(tf)
|
||||
seen.add(tf)
|
||||
return unique
|
||||
|
||||
def _init_exchange(self):
|
||||
"""实例化 ccxt 交易所,币安期货默认 defaultType=future,并 load_markets。"""
|
||||
if not hasattr(ccxt, self.exchange_name):
|
||||
raise ValueError(f"不支持的交易所: {self.exchange_name}")
|
||||
exchange_class = getattr(ccxt, self.exchange_name)
|
||||
exchange = exchange_class({"enableRateLimit": True})
|
||||
if exchange.id == "binance":
|
||||
exchange.options.setdefault("defaultType", "future")
|
||||
exchange.load_markets()
|
||||
logger.info("已初始化交易所 %s", exchange.id)
|
||||
return exchange
|
||||
|
||||
def _data_file_path(self, symbol: str, timeframe: str) -> Path:
|
||||
"""单交易对单周期的 CSV 路径:data_dir/tf/exchange_symbol_tf.csv。"""
|
||||
symbol_safe = symbol.replace("/", "_").replace(":", "_")
|
||||
return self.data_dir / timeframe / f"{self.exchange.id}_{symbol_safe}_{timeframe}.csv"
|
||||
|
||||
def _load_local(self, symbol: str, timeframe: str) -> List[Dict[str, float]]:
|
||||
"""启动时从磁盘加载已有 K 线,损坏行跳过,按时间排序。"""
|
||||
path = self._data_file_path(symbol, timeframe)
|
||||
if not path.exists():
|
||||
return []
|
||||
loaded: List[Dict[str, float]] = []
|
||||
with path.open("r", encoding="utf-8", newline="") as fp:
|
||||
reader = csv.DictReader(fp)
|
||||
for row in reader:
|
||||
try:
|
||||
loaded.append(
|
||||
{
|
||||
"timestamp": int(row["timestamp"]),
|
||||
"datetime": row.get("datetime") or to_utc_iso(int(row["timestamp"])),
|
||||
"open": float(row["open"]),
|
||||
"high": float(row["high"]),
|
||||
"low": float(row["low"]),
|
||||
"close": float(row["close"]),
|
||||
"volume": float(row["volume"]),
|
||||
}
|
||||
)
|
||||
except (KeyError, ValueError):
|
||||
logger.warning("忽略损坏的行: %s", row)
|
||||
loaded.sort(key=lambda item: item["timestamp"])
|
||||
logger.info("交易对 %s 时间周期 %s 加载本地K线数量: %s", symbol, timeframe, len(loaded))
|
||||
return loaded
|
||||
|
||||
def _merge_candles(
|
||||
self,
|
||||
timeframe: str,
|
||||
base: List[Dict[str, float]],
|
||||
new_candles: Iterable[Iterable[float]],
|
||||
) -> List[Dict[str, float]]:
|
||||
"""按 timestamp 去重合并,新数据覆盖同时间戳旧数据。"""
|
||||
merged = {entry["timestamp"]: entry for entry in base}
|
||||
for candle in new_candles:
|
||||
entry = candle_to_dict(candle)
|
||||
merged[entry["timestamp"]] = entry
|
||||
ordered = list(sorted(merged.values(), key=lambda item: item["timestamp"]))
|
||||
logger.debug("时间周期 %s 合并后K线数量: %s", timeframe, len(ordered))
|
||||
return ordered
|
||||
|
||||
def _write_to_disk(self, symbol: str, timeframe: str, data: List[Dict[str, float]]) -> None:
|
||||
"""先写临时文件再 replace,避免写入中断导致 CSV 损坏。"""
|
||||
path = self._data_file_path(symbol, timeframe)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_path = path.with_suffix(path.suffix + ".tmp")
|
||||
try:
|
||||
with tmp_path.open("w", encoding="utf-8", newline="") as fp:
|
||||
writer = csv.DictWriter(fp, fieldnames=CSV_FIELDNAMES)
|
||||
writer.writeheader()
|
||||
writer.writerows(data)
|
||||
os.replace(tmp_path, path)
|
||||
finally:
|
||||
if tmp_path.exists():
|
||||
try:
|
||||
tmp_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
logger.info("交易对 %s 时间周期 %s 已写入磁盘 (%s 根K线)", symbol, timeframe, len(data))
|
||||
|
||||
def _fetch_history(self, symbol: str, timeframe: str, since_ms: int) -> List[List[float]]:
|
||||
"""从 since_ms 分页拉取直到接近当前时间;遇限频则 sleep 重试。"""
|
||||
results: List[List[float]] = []
|
||||
limit = 1500
|
||||
now_ms = self.exchange.milliseconds()
|
||||
tf_ms = TIMEFRAME_TO_MS[timeframe]
|
||||
fetch_since = since_ms
|
||||
max_rounds = 5000
|
||||
rounds = 0
|
||||
while fetch_since < now_ms and rounds < max_rounds:
|
||||
rounds += 1
|
||||
try:
|
||||
candles = self.exchange.fetch_ohlcv(
|
||||
symbol,
|
||||
timeframe=timeframe,
|
||||
since=fetch_since,
|
||||
limit=limit,
|
||||
)
|
||||
except ccxt.RateLimitExceeded as exc:
|
||||
logger.warning("触发频率限制,等待: %s", exc)
|
||||
time.sleep(self.exchange.rateLimit / 1000 if self.exchange.rateLimit else 1)
|
||||
continue
|
||||
except ccxt.BaseError as exc:
|
||||
logger.error("拉取历史K线失败 (%s, %s): %s", timeframe, fetch_since, exc)
|
||||
time.sleep(5)
|
||||
continue
|
||||
if not candles:
|
||||
break
|
||||
results.extend(candles)
|
||||
last_ts = candles[-1][0]
|
||||
fetch_since = last_ts + tf_ms
|
||||
if last_ts >= now_ms - tf_ms:
|
||||
break
|
||||
time.sleep(self.exchange.rateLimit / 1000 if self.exchange.rateLimit else 0.2)
|
||||
logger.info("交易对 %s 时间周期 %s 拉取历史K线数量: %s", symbol, timeframe, len(results))
|
||||
return results
|
||||
|
||||
def initialize(self) -> None:
|
||||
"""阻塞式启动:加载本地、从倒数第二根或配置起点补历史、写盘并 set _ready。"""
|
||||
logger.info("开始初始化数据提供商")
|
||||
for symbol in self.symbols:
|
||||
for timeframe in self.timeframes:
|
||||
existing = self._load_local(symbol, timeframe)
|
||||
tf_ms = TIMEFRAME_TO_MS[timeframe]
|
||||
last_ts = existing[-1]["timestamp"] if existing else None
|
||||
if last_ts is not None:
|
||||
if len(existing) >= 2:
|
||||
# 从倒数第二根起拉,避免最后一根未收盘重复/缺口
|
||||
fetch_since = existing[-2]["timestamp"]
|
||||
else:
|
||||
fetch_since = max(0, last_ts - tf_ms)
|
||||
else:
|
||||
fetch_since = self.start_time_ms
|
||||
logger.debug(
|
||||
"初始化拉取参数",
|
||||
extra={
|
||||
"symbol": symbol,
|
||||
"timeframe": timeframe,
|
||||
"existing_last": last_ts,
|
||||
"fetch_since": fetch_since,
|
||||
"tf_ms": tf_ms,
|
||||
},
|
||||
)
|
||||
history = self._fetch_history(symbol, timeframe, fetch_since)
|
||||
merged = self._merge_candles(timeframe, existing, history)
|
||||
with self._lock:
|
||||
self.data.setdefault(symbol, {})[timeframe] = merged
|
||||
self._write_to_disk(symbol, timeframe, merged)
|
||||
self._ready.set()
|
||||
logger.info("数据初始化完成")
|
||||
|
||||
def resample_df(self, df: pd.DataFrame, interval: int) -> pd.DataFrame:
|
||||
"""将基础周期 DataFrame 聚合为 interval 分钟周期(freqtrade technical.util)。"""
|
||||
return resample_to_interval(df, interval)
|
||||
|
||||
def _save_resume_since(self) -> None:
|
||||
"""将断线恢复点持久化到 resume_since.json(原子替换)。"""
|
||||
path = self._resume_file
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp_path = path.with_suffix(path.suffix + ".tmp")
|
||||
with self._lock:
|
||||
snapshot = {
|
||||
symbol: {tf: int(since) for tf, since in tf_map.items()}
|
||||
for symbol, tf_map in self._resume_since.items()
|
||||
}
|
||||
try:
|
||||
with tmp_path.open("w", encoding="utf-8") as fp:
|
||||
json.dump(snapshot, fp, ensure_ascii=False, separators=(",", ":"))
|
||||
os.replace(tmp_path, path)
|
||||
finally:
|
||||
if tmp_path.exists():
|
||||
try:
|
||||
tmp_path.unlink()
|
||||
except OSError:
|
||||
pass
|
||||
logger.debug("恢复点已保存到磁盘: %s", path)
|
||||
|
||||
def _load_resume_since(self) -> None:
|
||||
"""启动时加载恢复点;与内存合并时取更早的 since,避免漏拉。"""
|
||||
path = self._resume_file
|
||||
if not path.exists():
|
||||
return
|
||||
try:
|
||||
with path.open("r", encoding="utf-8") as fp:
|
||||
raw = json.load(fp)
|
||||
except Exception as exc:
|
||||
logger.warning("恢复点文件读取失败,忽略: %s (%s)", path, exc)
|
||||
return
|
||||
if not isinstance(raw, dict):
|
||||
logger.warning("恢复点文件格式错误,忽略: %s", path)
|
||||
return
|
||||
loaded: Dict[str, Dict[str, int]] = {}
|
||||
for symbol, tf_map in raw.items():
|
||||
if not isinstance(tf_map, dict):
|
||||
continue
|
||||
per_symbol: Dict[str, int] = {}
|
||||
for timeframe, since in tf_map.items():
|
||||
try:
|
||||
per_symbol[str(timeframe)] = int(since)
|
||||
except Exception:
|
||||
continue
|
||||
if per_symbol:
|
||||
loaded[str(symbol)] = per_symbol
|
||||
if not loaded:
|
||||
return
|
||||
with self._lock:
|
||||
# 合并为更早的 since,避免遗漏
|
||||
for symbol, tf_map in loaded.items():
|
||||
cur = self._resume_since.setdefault(symbol, {})
|
||||
for timeframe, since in tf_map.items():
|
||||
prev = cur.get(timeframe)
|
||||
if prev is None or since < prev:
|
||||
cur[timeframe] = since
|
||||
logger.info("已加载恢复点: %s", path)
|
||||
|
||||
def _get_resume_since(self, symbol: str, timeframe: str) -> Optional[int]:
|
||||
"""若曾断线,返回应从哪一毫秒起补拉该 symbol/tf。"""
|
||||
with self._lock:
|
||||
return self._resume_since.get(symbol, {}).get(timeframe)
|
||||
|
||||
def _set_resume_since(self, symbol: str, timeframe: str, since_ms: int) -> None:
|
||||
"""断线时写入恢复点(取更早的 since 以免漏数据),并持久化到磁盘。"""
|
||||
with self._lock:
|
||||
per_symbol = self._resume_since.setdefault(symbol, {})
|
||||
prev = per_symbol.get(timeframe)
|
||||
# 取更早的 since,避免跳过数据
|
||||
if prev is None or since_ms < prev:
|
||||
per_symbol[timeframe] = since_ms
|
||||
logger.warning(
|
||||
"记录断线恢复点: %s %s since=%s (%s)",
|
||||
symbol,
|
||||
timeframe,
|
||||
since_ms,
|
||||
to_utc_iso(since_ms),
|
||||
)
|
||||
# 同步写盘
|
||||
self._save_resume_since()
|
||||
|
||||
def _clear_resume_since(self, symbol: str, timeframe: str) -> None:
|
||||
"""补数成功后清除该 symbol/tf 的恢复点。"""
|
||||
with self._lock:
|
||||
if symbol in self._resume_since and timeframe in self._resume_since[symbol]:
|
||||
del self._resume_since[symbol][timeframe]
|
||||
if not self._resume_since[symbol]:
|
||||
del self._resume_since[symbol]
|
||||
logger.info("清除断线恢复点: %s %s", symbol, timeframe)
|
||||
# 同步写盘
|
||||
self._save_resume_since()
|
||||
|
||||
def on_update(self, callback) -> None:
|
||||
"""注册数据更新回调(签名: callback(symbol, timeframe))。"""
|
||||
self._update_callbacks.append(callback)
|
||||
|
||||
def _notify_update(self, symbol: str, timeframe: str) -> None:
|
||||
"""通知所有回调:某 symbol/timeframe 数据已更新。"""
|
||||
for cb in self._update_callbacks:
|
||||
try:
|
||||
cb(symbol, timeframe)
|
||||
except Exception as exc:
|
||||
logger.error("数据更新回调异常: %s", exc)
|
||||
|
||||
def start_background_workers(self) -> None:
|
||||
"""启动增量刷新线程与周期性落盘线程。"""
|
||||
if self._fetch_thread and self._fetch_thread.is_alive():
|
||||
return
|
||||
self._stop_event.clear()
|
||||
self._fetch_thread = threading.Thread(target=self._refresh_loop, name="refresh-loop", daemon=True)
|
||||
self._persist_thread = threading.Thread(target=self._persist_loop, name="persist-loop", daemon=True)
|
||||
self._fetch_thread.start()
|
||||
self._persist_thread.start()
|
||||
logger.info("后台线程已启动")
|
||||
|
||||
def stop(self) -> None:
|
||||
"""停止后台线程(应用关闭时 lifespan finally 调用)。"""
|
||||
self._stop_event.set()
|
||||
if self._fetch_thread:
|
||||
self._fetch_thread.join(timeout=5)
|
||||
if self._persist_thread:
|
||||
self._persist_thread.join(timeout=5)
|
||||
logger.info("数据提供商已停止")
|
||||
|
||||
def _refresh_loop(self) -> None:
|
||||
"""轮询各 symbol/tf:有恢复点则先补历史,否则 fetch 最近 RECENT_CANDLE_LIMIT 根。"""
|
||||
while not self._stop_event.is_set():
|
||||
for symbol in self.symbols:
|
||||
for timeframe in self.timeframes:
|
||||
try:
|
||||
# 若存在断线恢复点,则优先从该 since 补齐历史数据
|
||||
resume_since = self._get_resume_since(symbol, timeframe)
|
||||
if resume_since is not None:
|
||||
logger.info(
|
||||
"开始断线后补数: %s %s since=%s (%s)",
|
||||
symbol,
|
||||
timeframe,
|
||||
resume_since,
|
||||
to_utc_iso(resume_since),
|
||||
)
|
||||
history = self._fetch_history(symbol, timeframe, resume_since)
|
||||
with self._lock:
|
||||
current = self.data.setdefault(symbol, {}).get(timeframe, [])
|
||||
merged = self._merge_candles(timeframe, current, history)
|
||||
self.data[symbol][timeframe] = merged
|
||||
self._notify_update(symbol, timeframe)
|
||||
self._clear_resume_since(symbol, timeframe)
|
||||
else:
|
||||
# 正常增量获取最近若干根K线
|
||||
candles = self.exchange.fetch_ohlcv(
|
||||
symbol,
|
||||
timeframe=timeframe,
|
||||
limit=RECENT_CANDLE_LIMIT,
|
||||
)
|
||||
if not candles:
|
||||
continue
|
||||
with self._lock:
|
||||
current = self.data.setdefault(symbol, {}).get(timeframe, [])
|
||||
merged = self._merge_candles(timeframe, current, candles)
|
||||
self.data[symbol][timeframe] = merged
|
||||
self._notify_update(symbol, timeframe)
|
||||
except ccxt.BaseError as exc:
|
||||
logger.error("更新最新K线失败 (%s %s): %s", symbol, timeframe, exc)
|
||||
# 记录应当从何时恢复拉取,避免重连后从当前时间开始导致丢K
|
||||
with self._lock:
|
||||
current = self.data.get(symbol, {}).get(timeframe, [])
|
||||
if current:
|
||||
last_ts = int(current[-1]["timestamp"])
|
||||
else:
|
||||
last_ts = self.start_time_ms
|
||||
tf_ms = TIMEFRAME_TO_MS[timeframe]
|
||||
# 回退一个周期,确保包含可能未完全收盘的K线,去重由 _merge_candles 处理
|
||||
since_ms = max(self.start_time_ms, last_ts - tf_ms)
|
||||
self._set_resume_since(symbol, timeframe, since_ms)
|
||||
time.sleep(2)
|
||||
continue
|
||||
if self._stop_event.wait(RECENT_FETCH_INTERVAL):
|
||||
break
|
||||
|
||||
def _persist_loop(self) -> None:
|
||||
"""每隔 PERSIST_INTERVAL 秒把内存快照写 CSV 并保存恢复点。"""
|
||||
while not self._stop_event.wait(PERSIST_INTERVAL):
|
||||
self._persist_all()
|
||||
|
||||
def _persist_all(self) -> None:
|
||||
"""在锁内复制 data 后落盘,避免长时间持锁。"""
|
||||
if not self._ready.is_set():
|
||||
return
|
||||
with self._lock:
|
||||
snapshot = {
|
||||
symbol: {tf: list(data) for tf, data in tf_map.items()}
|
||||
for symbol, tf_map in self.data.items()
|
||||
}
|
||||
for symbol, tf_map in snapshot.items():
|
||||
for timeframe, data in tf_map.items():
|
||||
self._write_to_disk(symbol, timeframe, data)
|
||||
# 周期性也保存一次恢复点,保证一致性
|
||||
self._save_resume_since()
|
||||
|
||||
def is_ready(self) -> bool:
|
||||
return self._ready.is_set()
|
||||
|
||||
def wait_ready(self, timeout: Optional[float] = None) -> bool:
|
||||
return self._ready.wait(timeout)
|
||||
|
||||
def get_available_timeframes(self) -> List[str]:
|
||||
return list(self.available_timeframes)
|
||||
|
||||
def get_derived_timeframes(self) -> List[str]:
|
||||
return list(self.derived_map.keys())
|
||||
|
||||
def _get_base_klines(
|
||||
self,
|
||||
symbol: str,
|
||||
timeframe: str,
|
||||
start_ms: Optional[int],
|
||||
end_ms: Optional[int],
|
||||
limit: Optional[int],
|
||||
) -> List[Dict[str, float]]:
|
||||
"""从内存读取已缓存的基础周期 K 线并按时间/limit 裁剪。"""
|
||||
with self._lock:
|
||||
candles = list(self.data.get(symbol, {}).get(timeframe, []))
|
||||
if start_ms is not None:
|
||||
candles = [row for row in candles if row["timestamp"] >= start_ms]
|
||||
if end_ms is not None:
|
||||
candles = [row for row in candles if row["timestamp"] <= end_ms]
|
||||
if limit:
|
||||
candles = candles[-limit:]
|
||||
return candles
|
||||
|
||||
def get_klines(
|
||||
self,
|
||||
symbol: str,
|
||||
timeframe: str,
|
||||
start_time: Optional[object] = None,
|
||||
end_time: Optional[object] = None,
|
||||
limit: Optional[int] = None,
|
||||
) -> List[Dict[str, float]]:
|
||||
"""对外查询:基础周期直接返回;衍生周期从 derived_map 取 base,resample 后对齐时间戳再裁剪。"""
|
||||
if symbol not in self.symbols:
|
||||
raise HTTPException(status_code=404, detail=f"symbol {symbol} 不可用")
|
||||
self.wait_ready()
|
||||
start_ms = parse_timestamp(start_time)
|
||||
end_ms = parse_timestamp(end_time)
|
||||
if timeframe in self.timeframes:
|
||||
return self._get_base_klines(symbol, timeframe, start_ms, end_ms, limit)
|
||||
base_tf = self.derived_map.get(timeframe)
|
||||
if not base_tf:
|
||||
raise HTTPException(status_code=404, detail=f"{symbol} 时间周期 {timeframe} 不可用")
|
||||
target_minutes = timeframe_to_minutes(timeframe)
|
||||
if target_minutes is None:
|
||||
raise HTTPException(status_code=400, detail=f"不支持的时间周期: {timeframe}")
|
||||
target_ms = target_minutes * 60_000
|
||||
# 起点前移一根目标周期长度,保证首根合成 K 边界完整
|
||||
adjusted_start = None if start_ms is None else max(0, start_ms - target_ms)
|
||||
base_candles = self._get_base_klines(symbol, base_tf, adjusted_start, end_ms, None)
|
||||
if not base_candles:
|
||||
return []
|
||||
df = pd.DataFrame(base_candles)
|
||||
if df.empty:
|
||||
return []
|
||||
df = df.drop_duplicates(subset=["timestamp"], keep="last").sort_values("timestamp")
|
||||
df["date"] = pd.to_datetime(df["timestamp"], unit="ms", utc=True)
|
||||
# resample_to_interval 按「分钟」目标周期聚合 OHLCV
|
||||
resampled = self.resample_df(df, target_minutes)
|
||||
if resampled is None or resampled.empty:
|
||||
return []
|
||||
# 统一得到毫秒 timestamp 列(resample 可能返回 date 或 DatetimeIndex)
|
||||
if "timestamp" in resampled.columns:
|
||||
resampled_df = resampled.copy()
|
||||
else:
|
||||
resampled_df = resampled.copy()
|
||||
if "date" in resampled_df.columns:
|
||||
dates = pd.to_datetime(resampled_df["date"], utc=True, errors="coerce")
|
||||
resampled_df["timestamp"] = (dates.astype("int64", copy=False) // 1_000_000).astype("int64")
|
||||
elif isinstance(resampled_df.index, pd.DatetimeIndex):
|
||||
idx = resampled_df.index
|
||||
if idx.tz is None:
|
||||
idx = idx.tz_localize("UTC")
|
||||
else:
|
||||
idx = idx.tz_convert("UTC")
|
||||
resampled_df["timestamp"] = (idx.astype("int64", copy=False) // 1_000_000).astype("int64")
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail=f"聚合结果缺少 timestamp 列 ({timeframe})")
|
||||
resampled_df = resampled_df.dropna(subset=["timestamp"]).sort_values("timestamp")
|
||||
if start_ms is not None:
|
||||
resampled_df = resampled_df[resampled_df["timestamp"] >= start_ms]
|
||||
if end_ms is not None:
|
||||
resampled_df = resampled_df[resampled_df["timestamp"] <= end_ms]
|
||||
if resampled_df.empty:
|
||||
return []
|
||||
resampled_df["datetime"] = resampled_df["timestamp"].apply(to_utc_iso)
|
||||
for column in ["open", "high", "low", "close", "volume"]:
|
||||
if column not in resampled_df.columns:
|
||||
resampled_df[column] = 0.0
|
||||
resampled_df = resampled_df[["timestamp", "datetime", "open", "high", "low", "close", "volume"]]
|
||||
result = resampled_df.to_dict("records")
|
||||
if limit:
|
||||
result = result[-limit:]
|
||||
logger.debug(
|
||||
"衍生周期返回",
|
||||
extra={
|
||||
"symbol": symbol,
|
||||
"timeframe": timeframe,
|
||||
"base_timeframe": base_tf,
|
||||
"count": len(result),
|
||||
},
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def create_app(provider: DataProvider) -> FastAPI:
|
||||
"""构造 FastAPI 应用:lifespan 内同步 initialize 并启动后台拉数;WebSocket 实时推送。"""
|
||||
ws_manager = WebSocketManager()
|
||||
|
||||
def _on_data_update(symbol: str, base_tf: str) -> None:
|
||||
"""后台刷新线程回调:广播基础及衍生周期更新给 WebSocket 订阅者。"""
|
||||
with provider._lock:
|
||||
base_data = list(provider.data.get(symbol, {}).get(base_tf, []))
|
||||
recent = base_data[-WS_UPDATE_CANDLE_COUNT:] if base_data else []
|
||||
if recent:
|
||||
ws_manager.broadcast_from_thread(symbol, base_tf, recent)
|
||||
for derived_tf, src_base in provider.derived_map.items():
|
||||
if src_base != base_tf or not ws_manager.has_subscribers(symbol, derived_tf):
|
||||
continue
|
||||
try:
|
||||
target_min = timeframe_to_minutes(derived_tf)
|
||||
if target_min is None:
|
||||
continue
|
||||
now_ms = int(time.time() * 1000)
|
||||
window_ms = target_min * 60_000 * (WS_UPDATE_CANDLE_COUNT + 2)
|
||||
derived = provider.get_klines(
|
||||
symbol, derived_tf, start_time=now_ms - window_ms, limit=WS_UPDATE_CANDLE_COUNT,
|
||||
)
|
||||
if derived:
|
||||
ws_manager.broadcast_from_thread(symbol, derived_tf, derived)
|
||||
except Exception as exc:
|
||||
logger.debug("衍生周期广播失败 %s %s: %s", symbol, derived_tf, exc)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
loop = asyncio.get_running_loop()
|
||||
ws_manager.set_loop(loop)
|
||||
provider.on_update(_on_data_update)
|
||||
await loop.run_in_executor(None, provider.initialize)
|
||||
provider.start_background_workers()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
provider.stop()
|
||||
|
||||
app = FastAPI(title="Chan 数据提供商", version="1.0.0", lifespan=lifespan)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
@app.get("/health")
|
||||
async def health() -> Dict[str, object]:
|
||||
"""存活检查:交易所、交易对、基础/衍生周期、是否已完成冷启动。"""
|
||||
return {
|
||||
"status": "ok",
|
||||
"exchange": provider.exchange_name,
|
||||
"symbols": provider.symbols,
|
||||
"base_timeframes": provider.timeframes,
|
||||
"derived_timeframes": provider.get_derived_timeframes(),
|
||||
"timeframes": provider.get_available_timeframes(),
|
||||
"ready": provider.is_ready(),
|
||||
}
|
||||
|
||||
@app.get("/timeframes")
|
||||
async def list_timeframes() -> Dict[str, List[str]]:
|
||||
"""返回配置的基础周期与可合成的衍生周期列表。"""
|
||||
provider.wait_ready()
|
||||
return {
|
||||
"base_timeframes": provider.timeframes,
|
||||
"derived_timeframes": provider.get_derived_timeframes(),
|
||||
"timeframes": provider.get_available_timeframes(),
|
||||
}
|
||||
|
||||
@app.get("/api/candles")
|
||||
async def api_candles(
|
||||
symbol: str = Query(..., description="如 BTC/USDT"),
|
||||
tf: str = Query("1m", description="时间周期"),
|
||||
start: Optional[int] = Query(None, description="开始时间戳(ms)"),
|
||||
end: Optional[int] = Query(None, description="结束时间戳(ms)"),
|
||||
limit: Optional[int] = Query(None, description="可选,限制返回数量"),
|
||||
):
|
||||
"""按交易对与时间周期返回 OHLCV;tf 支持配置的基础周期及衍生合成周期。"""
|
||||
data = provider.get_klines(symbol=symbol, timeframe=tf, start_time=start, end_time=end, limit=limit)
|
||||
return data
|
||||
|
||||
@app.get("/")
|
||||
async def root() -> Dict[str, object]:
|
||||
"""根路径:服务名、交易所、交易对与可用周期(含 ready 标志)。"""
|
||||
return {
|
||||
"service": "Data Provider",
|
||||
"exchange": provider.exchange_name,
|
||||
"symbols": provider.symbols,
|
||||
"base_timeframes": provider.timeframes,
|
||||
"derived_timeframes": provider.get_derived_timeframes(),
|
||||
"timeframes": provider.get_available_timeframes(),
|
||||
"ready": provider.is_ready(),
|
||||
}
|
||||
|
||||
@app.websocket("/ws")
|
||||
async def websocket_endpoint(ws: WebSocket):
|
||||
"""WebSocket 实时 K 线推送。
|
||||
|
||||
客户端发送 JSON:
|
||||
{"action": "subscribe", "symbol": "BTC/USDT:USDT", "timeframe": "1m"}
|
||||
{"action": "unsubscribe", "symbol": "BTC/USDT:USDT", "timeframe": "1m"}
|
||||
{"action": "ping"}
|
||||
服务端推送:
|
||||
{"type": "subscribed", "symbol": "...", "timeframe": "..."}
|
||||
{"type": "snapshot", "symbol": "...", "timeframe": "...", "data": [...]}
|
||||
{"type": "kline", "symbol": "...", "timeframe": "...", "data": [...]}
|
||||
{"type": "pong"}
|
||||
{"type": "error", "message": "..."}
|
||||
"""
|
||||
await ws_manager.connect(ws)
|
||||
try:
|
||||
while True:
|
||||
raw = await ws.receive_text()
|
||||
try:
|
||||
msg = json.loads(raw)
|
||||
except json.JSONDecodeError:
|
||||
await ws.send_text(json.dumps({"type": "error", "message": "invalid JSON"}))
|
||||
continue
|
||||
|
||||
action = msg.get("action", "")
|
||||
symbol = str(msg.get("symbol", "")).strip()
|
||||
timeframe = str(msg.get("timeframe", "")).strip()
|
||||
|
||||
if action == "ping":
|
||||
await ws.send_text(json.dumps({"type": "pong"}))
|
||||
|
||||
elif action == "subscribe":
|
||||
if not symbol or not timeframe:
|
||||
await ws.send_text(json.dumps(
|
||||
{"type": "error", "message": "需要 symbol 和 timeframe 字段"}
|
||||
))
|
||||
continue
|
||||
await ws_manager.subscribe(ws, symbol, timeframe)
|
||||
await ws.send_text(json.dumps(
|
||||
{"type": "subscribed", "symbol": symbol, "timeframe": timeframe},
|
||||
ensure_ascii=False,
|
||||
))
|
||||
try:
|
||||
snapshot = provider.get_klines(symbol, timeframe, limit=DEFAULT_LIMIT)
|
||||
if snapshot:
|
||||
await ws.send_text(json.dumps(
|
||||
{"type": "snapshot", "symbol": symbol, "timeframe": timeframe, "data": snapshot},
|
||||
ensure_ascii=False,
|
||||
))
|
||||
except Exception as exc:
|
||||
await ws.send_text(json.dumps({"type": "error", "message": str(exc)}))
|
||||
|
||||
elif action == "unsubscribe":
|
||||
await ws_manager.unsubscribe(ws, symbol, timeframe)
|
||||
await ws.send_text(json.dumps(
|
||||
{"type": "unsubscribed", "symbol": symbol, "timeframe": timeframe},
|
||||
ensure_ascii=False,
|
||||
))
|
||||
|
||||
else:
|
||||
await ws.send_text(json.dumps({"type": "error", "message": f"未知 action: {action}"}))
|
||||
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
await ws_manager.disconnect(ws)
|
||||
|
||||
return app
|
||||
|
||||
|
||||
def build_app() -> FastAPI:
|
||||
"""默认入口:从环境变量 CONFIG_PATH(或 config.json)加载配置并创建 FastAPI app。"""
|
||||
config_path = Path(os.getenv("CONFIG_PATH", "config.json"))
|
||||
provider = DataProvider(config_path)
|
||||
return create_app(provider)
|
||||
|
||||
|
||||
app = build_app()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""直接运行本模块时启动 uvicorn(监听 UVICORN_HOST / UVICORN_PORT)。"""
|
||||
host = os.getenv("UVICORN_HOST", "0.0.0.0")
|
||||
port = int(os.getenv("UVICORN_PORT", "9009"))
|
||||
|
||||
uvicorn.run(app, host=host, port=port, log_level=os.getenv("UVICORN_LOG_LEVEL", "info"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
ccxt>=4.0.0,<5.0.0
|
||||
fastapi>=0.110.0,<1.0.0
|
||||
uvicorn[standard]>=0.23.0,<1.0.0
|
||||
pandas>=2.0.0,<3.0.0
|
||||
technical==1.5.0
|
||||
@@ -1,82 +0,0 @@
|
||||
#!/bin/bash
|
||||
# 缠论分析系统生产环境部署脚本
|
||||
|
||||
# 显示执行的命令
|
||||
set -x
|
||||
|
||||
# 确保脚本在错误时停止
|
||||
set -e
|
||||
|
||||
# 项目根目录
|
||||
PROJECT_DIR=$(pwd)
|
||||
echo "项目将部署在: $PROJECT_DIR"
|
||||
|
||||
# 创建虚拟环境
|
||||
echo "创建Python虚拟环境..."
|
||||
python3 -m venv venv
|
||||
source venv/bin/activate
|
||||
|
||||
# 安装依赖
|
||||
echo "安装依赖包..."
|
||||
pip install --upgrade pip
|
||||
pip install flask pandas matplotlib ccxt pytz talib-binary gunicorn
|
||||
|
||||
# 安装任何额外的系统依赖
|
||||
# sudo apt-get update
|
||||
# sudo apt-get install -y python3-dev
|
||||
|
||||
# 检查目录结构
|
||||
echo "检查目录结构..."
|
||||
mkdir -p web/templates
|
||||
|
||||
# 创建日志目录
|
||||
mkdir -p logs
|
||||
|
||||
# 创建启动脚本
|
||||
echo "创建启动脚本..."
|
||||
cat > start_service.sh << 'EOF'
|
||||
#!/bin/bash
|
||||
# 缠论分析系统启动脚本
|
||||
|
||||
# 项目根目录
|
||||
PROJECT_DIR=$(pwd)
|
||||
cd $PROJECT_DIR
|
||||
|
||||
# 激活虚拟环境
|
||||
source venv/bin/activate
|
||||
|
||||
# 启动服务
|
||||
cd web
|
||||
echo "启动缠论分析系统服务..."
|
||||
gunicorn app:app --bind=0.0.0.0:8123 --workers=4 --timeout=120 --log-level=info --log-file=logs/chanlun.log --daemon
|
||||
|
||||
echo "服务已启动,端口8123"
|
||||
echo "日志文件位置: $PROJECT_DIR/web/logs/chanlun.log"
|
||||
EOF
|
||||
|
||||
# 创建停止脚本
|
||||
echo "创建停止脚本..."
|
||||
cat > stop_service.sh << 'EOF'
|
||||
#!/bin/bash
|
||||
# 停止缠论分析系统服务
|
||||
|
||||
echo "停止缠论分析系统服务..."
|
||||
pkill -f "gunicorn app:app"
|
||||
echo "服务已停止"
|
||||
EOF
|
||||
|
||||
# 添加执行权限
|
||||
chmod +x start_service.sh
|
||||
chmod +x stop_service.sh
|
||||
|
||||
# 修改app.py中的调试模式(生产环境应关闭调试模式)
|
||||
if [ -f web/app.py ]; then
|
||||
echo "配置app.py为生产环境模式..."
|
||||
sed -i 's/app.run(debug=True, host='\''0.0.0.0'\'', port=8123)/# 在生产环境中,使用gunicorn启动服务\n# app.run(debug=False, host='\''0.0.0.0'\'', port=8124)/' user_data/Chan/web/app.py
|
||||
else
|
||||
echo "警告: 未找到app.py文件"
|
||||
fi
|
||||
|
||||
echo "部署完成!"
|
||||
echo "使用 ./start_service.sh 启动服务"
|
||||
echo "使用 ./stop_service.sh 停止服务"
|
||||
@@ -1,162 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
分型强度检测使用示例
|
||||
该文件展示如何使用ChanKLC类中新增的分型强度检测功能
|
||||
"""
|
||||
|
||||
from ChanKLC import ChanKLC
|
||||
from ChanEnum import Chan_FX_TYPE
|
||||
import ChanKLU
|
||||
|
||||
|
||||
def demo_fx_strength_detection():
|
||||
"""
|
||||
演示分型强度检测功能
|
||||
"""
|
||||
print("=== 分型强度检测功能演示 ===\n")
|
||||
|
||||
# 假设我们有一个已经确定为分型的KLC对象
|
||||
# 这里仅为演示,实际使用中KLC对象应该通过正常流程创建
|
||||
|
||||
print("1. 分型强度计算方法:")
|
||||
print(" - calculate_fx_strength(): 返回0-100的强度分数")
|
||||
print(" - get_fx_strength_level(): 返回强度等级描述")
|
||||
print(" - is_strong_fx(threshold): 判断是否为强分型")
|
||||
print()
|
||||
|
||||
print("2. 强度评分维度 (总分100分):")
|
||||
print(" - 价格差异强度: 40分 (与相邻K线的价格差异)")
|
||||
print(" - 突破历史点位: 20分 (是否突破重要高低点)")
|
||||
print(" - 成交量确认: 15分 (分型形成时的成交量)")
|
||||
print(" - RSI背离确认: 15分 (价格与RSI的背离)")
|
||||
print(" - MACD背离确认: 10分 (价格与MACD的背离)")
|
||||
print()
|
||||
|
||||
print("3. 强度等级分类:")
|
||||
print(" - 极强: 80-100分")
|
||||
print(" - 强: 60-79分")
|
||||
print(" - 中等: 40-59分")
|
||||
print(" - 弱: 20-39分")
|
||||
print(" - 极弱: 0-19分")
|
||||
print()
|
||||
|
||||
print("4. 在特征数据中的应用:")
|
||||
print(" 分型强度会自动集成到get_feature_data()方法返回的特征中:")
|
||||
print(" - klc_fx_strength: 强度分数")
|
||||
print(" - klc_fx_strength_level: 强度等级")
|
||||
print(" - klc_is_strong_fx: 是否为强分型(布尔值)")
|
||||
print(" - klc_fx_strength_extreme: 是否为极强分型")
|
||||
print(" - klc_fx_strength_strong: 是否为强分型")
|
||||
print(" - klc_fx_strength_medium: 是否为中等分型")
|
||||
print(" - klc_fx_strength_weak: 是否为弱分型")
|
||||
print(" - klc_fx_strength_very_weak: 是否为极弱分型")
|
||||
print()
|
||||
|
||||
|
||||
def analyze_fx_strength(klc):
|
||||
"""
|
||||
分析单个KLC的分型强度
|
||||
|
||||
Args:
|
||||
klc: ChanKLC对象
|
||||
"""
|
||||
if klc.fx == Chan_FX_TYPE.UNKNOWN:
|
||||
print(f"时间: {klc.start_time} - 无分型")
|
||||
return
|
||||
|
||||
fx_type = "顶分型" if klc.fx == Chan_FX_TYPE.TOP else "底分型"
|
||||
strength = klc.calculate_fx_strength()
|
||||
strength_level = klc.get_fx_strength_level()
|
||||
is_strong = klc.is_strong_fx()
|
||||
|
||||
print(f"时间: {klc.start_time}")
|
||||
print(f"分型类型: {fx_type}")
|
||||
print(f"强度分数: {strength}")
|
||||
print(f"强度等级: {strength_level}")
|
||||
print(f"是否强分型: {'是' if is_strong else '否'}")
|
||||
print("-" * 30)
|
||||
|
||||
|
||||
def filter_strong_fractals(klc_list, min_strength=60):
|
||||
"""
|
||||
筛选强分型
|
||||
|
||||
Args:
|
||||
klc_list: KLC对象列表
|
||||
min_strength: 最小强度阈值
|
||||
|
||||
Returns:
|
||||
强分型列表
|
||||
"""
|
||||
strong_fractals = []
|
||||
|
||||
for klc in klc_list:
|
||||
if klc.fx != Chan_FX_TYPE.UNKNOWN and klc.is_strong_fx(min_strength):
|
||||
strong_fractals.append(klc)
|
||||
|
||||
return strong_fractals
|
||||
|
||||
|
||||
def get_fractal_statistics(klc_list):
|
||||
"""
|
||||
获取分型强度统计信息
|
||||
|
||||
Args:
|
||||
klc_list: KLC对象列表
|
||||
|
||||
Returns:
|
||||
统计信息字典
|
||||
"""
|
||||
stats = {
|
||||
'total_fractals': 0,
|
||||
'top_fractals': 0,
|
||||
'bottom_fractals': 0,
|
||||
'extreme_strength': 0, # 极强
|
||||
'strong_strength': 0, # 强
|
||||
'medium_strength': 0, # 中等
|
||||
'weak_strength': 0, # 弱
|
||||
'very_weak_strength': 0,# 极弱
|
||||
'avg_strength': 0
|
||||
}
|
||||
|
||||
strengths = []
|
||||
|
||||
for klc in klc_list:
|
||||
if klc.fx != Chan_FX_TYPE.UNKNOWN:
|
||||
stats['total_fractals'] += 1
|
||||
|
||||
if klc.fx == Chan_FX_TYPE.TOP:
|
||||
stats['top_fractals'] += 1
|
||||
else:
|
||||
stats['bottom_fractals'] += 1
|
||||
|
||||
strength = klc.calculate_fx_strength()
|
||||
strengths.append(strength)
|
||||
|
||||
if strength >= 80:
|
||||
stats['extreme_strength'] += 1
|
||||
elif strength >= 60:
|
||||
stats['strong_strength'] += 1
|
||||
elif strength >= 40:
|
||||
stats['medium_strength'] += 1
|
||||
elif strength >= 20:
|
||||
stats['weak_strength'] += 1
|
||||
else:
|
||||
stats['very_weak_strength'] += 1
|
||||
|
||||
if strengths:
|
||||
stats['avg_strength'] = sum(strengths) / len(strengths)
|
||||
|
||||
return stats
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
demo_fx_strength_detection()
|
||||
|
||||
print("=== 使用建议 ===")
|
||||
print("1. 在交易策略中,可以只关注强度>=60的分型")
|
||||
print("2. 极强分型(>=80分)通常是重要的转折点")
|
||||
print("3. 结合成交量和技术指标背离的分型更可靠")
|
||||
print("4. 可以用分型强度来设置止损和止盈位置")
|
||||
print("5. 分型强度可以作为机器学习模型的重要特征")
|
||||
@@ -1,4 +0,0 @@
|
||||
#!/bin/bash
|
||||
cd /path/to/your/project/user_data/Chan/web
|
||||
source /path/to/your/virtualenv/bin/activate # 如果使用虚拟环境
|
||||
exec gunicorn app:app -b 0.0.0.0:8123 --workers=4 --timeout 120
|
||||
@@ -0,0 +1,245 @@
|
||||
"""Bitget v2 合约 REST 的最小客户端,只覆盖实盘执行要用的几个端点。
|
||||
|
||||
## 为什么不用 Hummingbot 下单
|
||||
|
||||
Hummingbot 的 Bitget 连接器只暴露 LIMIT / LIMIT_MAKER / MARKET,没有触发单。
|
||||
于是 `PositionExecutor` 的止损只能在本地控制循环里盯价、触发时才发市价单——
|
||||
**进程一死仓位就是裸的**。
|
||||
|
||||
而交易所本身完全支持:`place-order` 有 `presetStopLossPrice`,下单时就把止损
|
||||
挂到服务端。所以整个结构变成两个调用,止损从入场那一刻起就不依赖我们的进程
|
||||
存活。绕过连接器不是图省事,是为了消掉一整类故障。
|
||||
|
||||
## 止盈为什么不用 presetStopSurplusPrice
|
||||
|
||||
它触发后按**市价**执行。而成本模型里止盈是 maker——那 60% 的出场不吃滑点、
|
||||
按 maker 费率计(见 `lib/shadow_budget.LEG_IS_TAKER`)。用 preset 会让这部分
|
||||
变成 taker,预算模型就不成立了。所以止盈单独挂 `post_only` 的 reduce-only
|
||||
限价单。
|
||||
|
||||
止损反过来:必须是市价。stop-limit 在急跌里可能不成交,损失远大于省下的费。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
BASE = "https://api.bitget.com"
|
||||
PRODUCT = "usdt-futures"
|
||||
MARGIN_COIN = "USDT"
|
||||
|
||||
|
||||
class BitgetError(RuntimeError):
|
||||
def __init__(self, code: str, msg: str, path: str):
|
||||
super().__init__(f"{path} → [{code}] {msg}")
|
||||
self.code, self.msg = code, msg
|
||||
|
||||
|
||||
class Bitget:
|
||||
def __init__(self, key: str = "", secret: str = "", passphrase: str = "",
|
||||
dry: bool = False):
|
||||
self.key = key or os.environ.get("BITGET_API_KEY", "")
|
||||
self.secret = secret or os.environ.get("BITGET_API_SECRET", "")
|
||||
# 两个名字都收:另外两项是 BITGET_API_KEY / BITGET_API_SECRET,
|
||||
# 这一项却没有 API_,很容易顺手写成 BITGET_API_PASSPHRASE。写错的
|
||||
# 后果是"密钥像是填了"但签名一直失败,排查起来很绕
|
||||
self.passphrase = (passphrase
|
||||
or os.environ.get("BITGET_PASSPHRASE", "")
|
||||
or os.environ.get("BITGET_API_PASSPHRASE", ""))
|
||||
self.dry = dry
|
||||
self._sess = None
|
||||
|
||||
def _sign(self, ts: str, method: str, path: str, body: str) -> str:
|
||||
msg = f"{ts}{method.upper()}{path}{body}"
|
||||
return base64.b64encode(hmac.new(
|
||||
self.secret.encode(), msg.encode(), hashlib.sha256).digest()
|
||||
).decode()
|
||||
|
||||
async def _req(self, method: str, path: str, params: dict | None = None,
|
||||
body: dict | None = None) -> dict:
|
||||
import aiohttp
|
||||
if self._sess is None:
|
||||
self._sess = aiohttp.ClientSession(
|
||||
timeout=aiohttp.ClientTimeout(total=15))
|
||||
qs = ""
|
||||
if params:
|
||||
qs = "?" + "&".join(f"{k}={v}" for k, v in sorted(params.items()))
|
||||
payload = json.dumps(body) if body else ""
|
||||
ts = str(int(time.time() * 1000))
|
||||
headers = {
|
||||
"ACCESS-KEY": self.key,
|
||||
"ACCESS-SIGN": self._sign(ts, method, path + qs, payload),
|
||||
"ACCESS-PASSPHRASE": self.passphrase,
|
||||
"ACCESS-TIMESTAMP": ts,
|
||||
"Content-Type": "application/json",
|
||||
"locale": "en-US",
|
||||
}
|
||||
async with self._sess.request(method, BASE + path + qs,
|
||||
headers=headers,
|
||||
data=payload or None) as r:
|
||||
d = await r.json()
|
||||
if str(d.get("code")) != "00000":
|
||||
raise BitgetError(str(d.get("code")), str(d.get("msg")), path)
|
||||
return d.get("data")
|
||||
|
||||
async def close(self) -> None:
|
||||
if self._sess is not None:
|
||||
await self._sess.close()
|
||||
self._sess = None
|
||||
|
||||
# ── 只读 ──────────────────────────────────────────────────────
|
||||
async def contracts(self) -> dict:
|
||||
"""合约规则。用于数量步长与价格 tick。"""
|
||||
d = await self._req("GET", "/api/v2/mix/market/contracts",
|
||||
{"productType": PRODUCT})
|
||||
return {c["symbol"]: c for c in d}
|
||||
|
||||
async def positions(self) -> list:
|
||||
d = await self._req("GET", "/api/v2/mix/position/all-position",
|
||||
{"productType": PRODUCT,
|
||||
"marginCoin": MARGIN_COIN})
|
||||
return [p for p in (d or []) if float(p.get("total") or 0) != 0]
|
||||
|
||||
async def history_positions(self, start_ms: int | None = None,
|
||||
limit: int = 100) -> list:
|
||||
"""已平仓位,用来取**已实现盈亏**。
|
||||
|
||||
为什么必须问交易所而不是自己算:止损与止盈都挂在交易所侧成交,本进程
|
||||
看不到成交价;而且要算准还得含手续费与资金费。这个端点的 `netProfit`
|
||||
已经是 `pnl + totalFunding + openFee + closeFee`,正是日亏损上限该用
|
||||
的数。自己按标记价估会把费用漏掉,方向还总是偏乐观。
|
||||
|
||||
返回形状按文档是 `data.list`,但也见过直接给数组的写法,两种都收。
|
||||
时间字段文档写 `ctime/utime`,官方 TS 类型写 `cTime/uTime`,同样都读。
|
||||
"""
|
||||
p: dict = {"productType": PRODUCT, "limit": str(limit)}
|
||||
if start_ms:
|
||||
p["startTime"] = str(int(start_ms))
|
||||
d = await self._req("GET", "/api/v2/mix/position/history-position", p)
|
||||
if isinstance(d, dict):
|
||||
return list(d.get("list") or [])
|
||||
return list(d or [])
|
||||
|
||||
async def fee_rate(self, symbol: str) -> dict:
|
||||
"""账户在该合约上的**实际**费率档。
|
||||
|
||||
这一项决定 ATR 门控阈值(约 5 + 1.1×taker_bp),进而决定可交易币池。
|
||||
接口的合约默认档是 VIP0,不是账户档,必须问这个端点。
|
||||
"""
|
||||
return await self._req("GET", "/api/v2/mix/market/query-position-lever",
|
||||
{"symbol": symbol, "productType": PRODUCT})
|
||||
|
||||
async def account(self) -> dict:
|
||||
return await self._req("GET", "/api/v2/mix/account/account",
|
||||
{"symbol": "BTCUSDT", "productType": PRODUCT,
|
||||
"marginCoin": MARGIN_COIN})
|
||||
|
||||
# ── 写 ────────────────────────────────────────────────────────
|
||||
async def set_leverage(self, symbol: str, lev: int,
|
||||
hold_side: str | None = None) -> dict:
|
||||
body = {"symbol": symbol, "productType": PRODUCT,
|
||||
"marginCoin": MARGIN_COIN, "leverage": str(lev)}
|
||||
if hold_side:
|
||||
body["holdSide"] = hold_side
|
||||
return await self._req("POST", "/api/v2/mix/account/set-leverage",
|
||||
body=body)
|
||||
|
||||
async def set_margin_mode(self, symbol: str,
|
||||
mode: str = "isolated") -> dict:
|
||||
return await self._req("POST", "/api/v2/mix/account/set-margin-mode",
|
||||
body={"symbol": symbol, "productType": PRODUCT,
|
||||
"marginCoin": MARGIN_COIN,
|
||||
"marginMode": mode})
|
||||
|
||||
async def set_position_mode(self, mode: str = "one_way_mode") -> dict:
|
||||
"""单向 / 双向持仓。**按 productType 生效,不是按 symbol。**
|
||||
|
||||
必须显式设,因为它决定下单体的语法,两者不匹配会被整体拒单:
|
||||
|
||||
单向:side=buy/sell,**不带** tradeSide;平仓用 reduceOnly=YES
|
||||
双向:side + tradeSide=open/close;reduceOnly 在这个模式下无效
|
||||
|
||||
实盘上曾因为带着 tradeSide 打到单向账户,连续 8 次下单全被 40774 拒掉
|
||||
(4 个信号 × 2 条腿),而链路其余部分完全正常。
|
||||
|
||||
我们永不同时持有两个方向,所以单向是对的模式;且 reduceOnly 只在单向
|
||||
下可用,而出场腿依赖它防止反手开出反向仓。
|
||||
|
||||
交易所侧有持仓或挂单时切换会失败——所以调用点放在 reconcile 之后。
|
||||
"""
|
||||
return await self._req("POST", "/api/v2/mix/account/set-position-mode",
|
||||
body={"productType": PRODUCT, "posMode": mode})
|
||||
|
||||
async def entry_with_stop(self, symbol: str, side: str, size: str,
|
||||
stop_px: str, client_oid: str) -> dict:
|
||||
"""市价入场,**同时**把止损挂到服务端。
|
||||
|
||||
`presetStopLossPrice` 触发后按市价执行,这正是成本模型要的(止损是
|
||||
taker)。`clientOid` 给交易所级幂等——重发同一个 oid 会被拒,比本地
|
||||
去重可靠,因为「已发出但没收到回复」这种情况本地判不了。
|
||||
|
||||
**不带 `tradeSide`**:账户是单向持仓,带了会被 40774 整体拒单。
|
||||
"""
|
||||
body = {"symbol": symbol, "productType": PRODUCT,
|
||||
"marginMode": "isolated", "marginCoin": MARGIN_COIN,
|
||||
"size": size, "side": side,
|
||||
"orderType": "market", "clientOid": client_oid,
|
||||
"presetStopLossPrice": stop_px}
|
||||
if self.dry:
|
||||
print(f" [dry] 入场+止损 {body}", flush=True)
|
||||
return {"orderId": "dry", "clientOid": client_oid}
|
||||
return await self._req("POST", "/api/v2/mix/order/place-order",
|
||||
body=body)
|
||||
|
||||
async def tp_limit(self, symbol: str, side: str, size: str, px: str,
|
||||
client_oid: str) -> dict:
|
||||
"""挂 maker 止盈。
|
||||
|
||||
`side` 传的是**平仓方向**(多头止盈是 sell)。`post_only` 保证是 maker:
|
||||
成本模型里止盈那 60% 按 maker 费率计且不吃滑点,用 taker 会破坏预算。
|
||||
|
||||
单向持仓下平仓的写法是 `side` 取反 + `reduceOnly=YES`,**不带**
|
||||
`tradeSide`。`reduceOnly` 也正好只在单向模式下有效,它防止反手开出
|
||||
一个反向仓。
|
||||
"""
|
||||
body = {"symbol": symbol, "productType": PRODUCT,
|
||||
"marginMode": "isolated", "marginCoin": MARGIN_COIN,
|
||||
"size": size, "side": side,
|
||||
"orderType": "limit", "price": px, "force": "post_only",
|
||||
"reduceOnly": "YES", "clientOid": client_oid}
|
||||
if self.dry:
|
||||
print(f" [dry] 止盈限价 {body}", flush=True)
|
||||
return {"orderId": "dry", "clientOid": client_oid}
|
||||
return await self._req("POST", "/api/v2/mix/order/place-order",
|
||||
body=body)
|
||||
|
||||
async def close_market(self, symbol: str, hold_side: str,
|
||||
size: str, client_oid: str) -> dict:
|
||||
"""市价平(超时腿与对账用)。
|
||||
|
||||
同 tp_limit:单向持仓下是 `side` 取反 + `reduceOnly`,不带 `tradeSide`。
|
||||
"""
|
||||
side = "sell" if hold_side == "long" else "buy"
|
||||
body = {"symbol": symbol, "productType": PRODUCT,
|
||||
"marginMode": "isolated", "marginCoin": MARGIN_COIN,
|
||||
"size": size, "side": side,
|
||||
"orderType": "market", "reduceOnly": "YES",
|
||||
"clientOid": client_oid}
|
||||
if self.dry:
|
||||
print(f" [dry] 市价平 {body}", flush=True)
|
||||
return {"orderId": "dry"}
|
||||
return await self._req("POST", "/api/v2/mix/order/place-order",
|
||||
body=body)
|
||||
|
||||
async def cancel_all(self, symbol: str) -> dict:
|
||||
body = {"symbol": symbol, "productType": PRODUCT,
|
||||
"marginCoin": MARGIN_COIN}
|
||||
if self.dry:
|
||||
print(f" [dry] 撤全部挂单 {symbol}", flush=True)
|
||||
return {}
|
||||
return await self._req("POST", "/api/v2/mix/order/cancel-all-orders",
|
||||
body=body)
|
||||
@@ -0,0 +1,170 @@
|
||||
# 小额实盘执行器 · 部署
|
||||
|
||||
## 为什么是两台机
|
||||
|
||||
Bitget 的 API key 绑了 IP 白名单,只能从 AWS 那台发单;信号是新加坡那台采集器
|
||||
算出来的。于是分工固定成:
|
||||
|
||||
```
|
||||
新加坡(采集/研究机) AWS(生产机)
|
||||
shadow_hb.py 算信号 ship_signals.py 拉总线
|
||||
└→ ~/chan-live/state/ └→ /var/lib/chan-live/state/
|
||||
signals_live.jsonl ──ssh tail──→ signals_live.jsonl
|
||||
live_exec.py 读总线 → Bitget REST
|
||||
```
|
||||
|
||||
**生产机上不装采集侧的任何东西**(Docker / Hummingbot / pandas / chanlun)。
|
||||
理由不是洁癖,是四条具体代价:
|
||||
|
||||
1. `live_state.json` 原先落在 `research/out/`,而那个目录 `shadow_hb.py` 会在
|
||||
CSV 表头变化时自动 rename 归档、研究脚本会写、人也会手工清数据。那个文件装
|
||||
的是 `MAX_DAY_LOSS` 累计与已处理信号键,**被清掉不报错,只是两道闸静默
|
||||
失效**。现在改到 `/var/lib/chan-live`。
|
||||
2. 采集器十币清空 300~560ms,直接叠在信号到达执行器的延迟上。
|
||||
3. 研究侧的探针 OOM 过一次(14.9 GB、负载 12)。当时若有仓位在场,执行器会被
|
||||
一起杀掉,只剩交易所侧止损兜着。
|
||||
4. 依赖面:执行器只需标准库 + `aiohttp`。原先为读两个常量 import 研究侧的
|
||||
`step43`,把 numpy/pandas/pyarrow 全拖进实盘进程。
|
||||
|
||||
`install.sh` 里有一条断言会真的挡住第 4 条回归。
|
||||
|
||||
## 机器要求
|
||||
|
||||
CPU 无所谓(执行器几乎不算东西,信号 6.8 个/天)。要的是:
|
||||
|
||||
- 出口 IP 固定,且已加进 Bitget 该 key 的白名单
|
||||
- `chrony` 能同步。**这一条是硬要求**:`LIVE_STALE_S` 那道闸靠两机时钟一致才
|
||||
有意义,采集机时钟快 5 分钟就等于把闸放宽 5 分钟,一个早已失效的参考价会被
|
||||
当成新鲜的照做
|
||||
- 能 ssh 到采集机(拉总线用)
|
||||
|
||||
## 一、生产机(AWS)
|
||||
|
||||
```bash
|
||||
# 1. 取代码。只需要 live/ 这一个子树,但整仓克隆更省事
|
||||
git clone -b chan <repo> /tmp/chan && cd /tmp/chan
|
||||
sudo ./live/deploy/install.sh
|
||||
# 或让它自己克隆:sudo REPO=<repo> ./live/deploy/install.sh
|
||||
|
||||
# 2. 填密钥与参数
|
||||
sudo vi /etc/chan-live/live.env
|
||||
```
|
||||
|
||||
`live.env` 里必须改的四项:`BITGET_API_KEY` / `SECRET` / `PASSPHRASE` /
|
||||
`SHIP_FROM`。密钥权限**只勾只读 + 交易,不要勾提币**。
|
||||
|
||||
```bash
|
||||
# 3. 装拉总线用的 ssh key
|
||||
sudo -u chan ssh-keygen -t ed25519 -N '' \
|
||||
-f /var/lib/chan-live/home/.ssh/id_ed25519
|
||||
sudo cat /var/lib/chan-live/home/.ssh/id_ed25519.pub
|
||||
# 把这一行加到采集机的 ~/.ssh/authorized_keys
|
||||
|
||||
# 4. 空跑验全链(不下真单)
|
||||
sudo ./live/deploy/dryrun.sh
|
||||
```
|
||||
|
||||
`dryrun.sh` 验的是那些"上线才暴露、且暴露方式是花钱"的环节:密钥能不能用、
|
||||
IP 白名单对不对、chrony 同步没有、ssh 通不通、对端总线有没有信号、数量与价位
|
||||
取整合不合交易所规则。**不要跳过。**
|
||||
|
||||
```bash
|
||||
# 5. 真跑
|
||||
sudo systemctl enable --now chan-live-ship chan-live-exec
|
||||
./live/deploy/status.sh
|
||||
```
|
||||
|
||||
## 二、采集机(新加坡)
|
||||
|
||||
采集器要重启一次才会开始往总线写——`signal_bus.emit` 是后加的,跑着的进程没有
|
||||
加载。重启会丢已采的几分钟,数据本身不受影响(CSV 是追加的)。
|
||||
|
||||
```bash
|
||||
cd <repo> && git pull
|
||||
docker stop shadow && docker rm shadow
|
||||
SHADOW_SITE=sg-tencent SYMS=BTC,ETH,SOL,BNB,XRP,DOGE,ADA,AVAX,LINK,LTC \
|
||||
bash research/live/deploy/start.sh
|
||||
```
|
||||
|
||||
`start.sh` 会把 `$HOME/chan-live/state` 挂进容器成 `/bus`,总线落在
|
||||
`$HOME/chan-live/state/signals_live.jsonl`。**总线刻意放在仓库外**,因为它是
|
||||
交给另一台机的交接点,而仓库会被 git 动。
|
||||
|
||||
确认在写:
|
||||
|
||||
```bash
|
||||
ls -la ~/chan-live/state/
|
||||
# 等一个信号(6.8 个/天,可能要等几小时)
|
||||
tail -f ~/chan-live/state/signals_live.jsonl
|
||||
```
|
||||
|
||||
## 日常
|
||||
|
||||
```bash
|
||||
./live/deploy/status.sh # 一屏体检
|
||||
journalctl -u chan-live-exec -f # 执行器日志
|
||||
journalctl -u chan-live-ship -f # 搬运日志
|
||||
```
|
||||
|
||||
**怎么判健康:** 信号 6.8 个/天,所以"很久没有新信号"是正常的,不能当健康
|
||||
指标。要看的是 `chan-live-ship` 的心跳(每 5 分钟一条),里面报 ssh 在线时长与
|
||||
重连次数。管道死了但进程还活着是这里最危险的状态——`ServerAliveInterval=15`
|
||||
负责让它变成一次可见的断开。
|
||||
|
||||
**Telegram** 在 `live.env` 里填 `TG_TOKEN` / `TG_CHAT` 就开。启动时会推一条
|
||||
"执行器启动",兼作通道自检——配错了当场就知道,而不是等几小时后第一个真信号
|
||||
来时才发现。之后每小时一条在线(`TG_HB_MIN`,默认 60),带建仓数、当日盈亏
|
||||
和搬运 ssh 新鲜度——执行器活着不代表上游还在投信号。推开仓、平仓(带已实现
|
||||
盈亏)、被硬约束挡住、报错、对账平仓、跨日结算;不推信号过期跳过(常态)和
|
||||
5 分钟日志心跳。约 55 条/天上限。
|
||||
|
||||
## 停机与回滚
|
||||
|
||||
```bash
|
||||
# 停新开仓,但保留在场仓位的管理(48 分钟超时平仓在执行器进程里)
|
||||
sudo systemctl stop chan-live-ship
|
||||
|
||||
# 全停。执行器收到 SIGTERM 会**撤挂单 + 市价平掉在场仓位**再退出
|
||||
# (内部平仓上限 60s,systemd 给了 90s 停机窗口)
|
||||
sudo systemctl stop chan-live-exec
|
||||
|
||||
# 代码回滚
|
||||
cd /opt/chan && sudo git reset --hard <sha> && sudo systemctl restart chan-live-exec
|
||||
```
|
||||
|
||||
⚠️ **状态目录 `/var/lib/chan-live` 不要跟着回滚。** 它存的是当日计数与已处理
|
||||
信号键;清掉等于日上限归零、且可能重开已经做过的仓。
|
||||
|
||||
## 故障处理
|
||||
|
||||
| 症状 | 大概率原因 |
|
||||
|---|---|
|
||||
| 启动即 `40018` / 签名错 | 出口 IP 不在白名单,或密钥抄错。`curl https://api.ipify.org` 对一下 |
|
||||
| 搬运日志 `Permission denied (publickey)` | 第 3 步的 pubkey 没加到采集机 |
|
||||
| 搬运在线但一直没信号 | 采集机没重启过(`signal_bus.emit` 没加载),或对端总线路径不对 |
|
||||
| Telegram 在线报「读不到搬运」 | 搬运没起,或还是没落 `ship_alive.json` 的旧版本,两边一起重启 |
|
||||
| Telegram 在线报「ssh 已断开」 | 采集机 ssh 断了,搬运在重连。看 `chan-live-ship` 日志 |
|
||||
| 日志 `⛔ 时间倒流 Xs` | 两机时钟不同步,**staleness 闸已不可信**。查两边 `chronyc tracking` |
|
||||
| 信号收到但都被跳过 | `age > LIVE_STALE_S`。看是搬运慢还是时钟偏;也可能是重连重放的旧信号(这种跳过是对的) |
|
||||
| `systemctl status` 显示 start-limit-hit | 5 分钟内重启 5 次,systemd 停手了。先看 journal 找真因,再 `systemctl reset-failed` |
|
||||
| 执行器起不来,报缺 numpy/pandas | 有人给生产侧加了研究侧的 import。`install.sh` 的依赖断言就是挡这个 |
|
||||
|
||||
## 已知的退化边界
|
||||
|
||||
- **进程死掉不会变成裸仓。** 止损与止盈都挂在交易所侧(`presetStopLossPrice`
|
||||
与 post-only reduce-only 限价单),只有 48 分钟超时平仓在本进程。所以进程死
|
||||
掉的后果是持仓超过 48 根,不是失去保护。
|
||||
- **崩溃与主动停机的处理不同,是刻意的。** 崩溃后 systemd 几秒内重启,
|
||||
`reconcile` 接着撤挂单 + 平掉遗留仓位,空窗期由交易所侧止损兜着。主动
|
||||
`systemctl stop` 则在退出前就平掉——因为停机后没人重启,仓位会一直挂到止损
|
||||
或止盈,超时腿丢了就不是回测那个出场结构了。
|
||||
- **断线超过 20s 就等于漏掉那期间的信号。** 重连会把总线重放上来,但旧信号会被
|
||||
staleness 闸挡掉。这是对的——参考成交价是次根开盘价,过了就不是回测那个价。
|
||||
- **重启时会平掉交易所上已有的仓位**(`reconcile`)。接管要重建入场价、ATR、
|
||||
剩余半仓状态和已过根数,任一项猜错就跑成另一个收益结构,所以选择平掉。
|
||||
- **日亏损上限依赖 `watch()` 循环**。止损与止盈在交易所侧成交,本进程收不到
|
||||
通知,所以有个 10s 轮询去 `history-position` 取 `netProfit`(含手续费与资金
|
||||
费)记回闸。这个循环停了,`pnl_day` 会恒为 0,`MAX_DAY_LOSS` 静默失效。
|
||||
心跳里会打 `当日 PnL x/-20`,值一直是 0.00 而又确实有平仓,就是它出了问题。
|
||||
- **平仓后 `MAX_OPEN` 名额由 `watch()` 释放**,不是立刻。最坏延迟 10s。若
|
||||
历史记录还没落库,会等下一轮,日志里打"历史未就绪,下轮再结算"。
|
||||
@@ -0,0 +1,49 @@
|
||||
[Unit]
|
||||
Description=chan 小额实盘执行器(读信号总线,直接调 Bitget REST)
|
||||
# 搬运挂了执行器仍要活着——它得继续管在场仓位的 48 分钟超时平仓。
|
||||
# 所以这里只写 Wants(弱依赖),不写 Requires
|
||||
Wants=network-online.target chan-live-ship.service
|
||||
After=network-online.target chan-live-ship.service
|
||||
# 频繁重启说明有真问题,别让它无限打交易所。5 分钟内起 5 次就停下等人。
|
||||
# 注意这两项在 systemd 229+ 属于 [Unit],写在 [Service] 里会被忽略
|
||||
StartLimitIntervalSec=300
|
||||
StartLimitBurst=5
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=chan
|
||||
Group=chan
|
||||
WorkingDirectory=/opt/chan
|
||||
# 密钥与参数在这个文件里,权限必须 600。用 EnvironmentFile 而不是
|
||||
# Environment=,后者会出现在 `systemctl show` 的输出里
|
||||
EnvironmentFile=/etc/chan-live/live.env
|
||||
ExecStart=/opt/chan/.venv/bin/python /opt/chan/live/live_exec.py
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
# 收到 stop 时给足时间:执行器接到 SIGTERM 会撤挂单 + 平掉在场仓位再退出
|
||||
# (live_exec.shutdown(),内部平仓上限 60s)。默认的 90s 停机窗口留了余量。
|
||||
# 不需要 KillSignal=SIGINT——SIGTERM 已在代码里显式挂了处理器
|
||||
TimeoutStopSec=90
|
||||
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=chan-live-exec
|
||||
|
||||
# ── 收紧权限 ──────────────────────────────────────────────────────
|
||||
# 生产进程只需要读 /opt/chan 和读写状态目录,别的一概不给。这几条很廉价,
|
||||
# 但真出了远程代码执行,爆炸半径小很多——而这个进程手里有交易权限的密钥
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
ReadWritePaths=/var/lib/chan-live
|
||||
ProtectKernelTunables=true
|
||||
ProtectKernelModules=true
|
||||
ProtectControlGroups=true
|
||||
RestrictSUIDSGID=true
|
||||
LockPersonality=true
|
||||
MemoryMax=512M
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,40 @@
|
||||
[Unit]
|
||||
Description=chan 信号搬运(把采集机的总线拉到本机)
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
StartLimitIntervalSec=300
|
||||
StartLimitBurst=10
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=chan
|
||||
Group=chan
|
||||
WorkingDirectory=/opt/chan
|
||||
EnvironmentFile=/etc/chan-live/live.env
|
||||
# SHIP_FROM 在 live.env 里给,形如 sg-collector 或 user@1.2.3.4
|
||||
ExecStart=/opt/chan/.venv/bin/python /opt/chan/live/ship_signals.py \
|
||||
--from ${SHIP_FROM} --remote-bus ${SHIP_REMOTE_BUS}
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=chan-live-ship
|
||||
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=strict
|
||||
# chan 用户的家目录放在 /var/lib/chan-live/home,只装拉总线用的那一把 ssh
|
||||
# key。这样 ProtectHome=true 挡住 /home 与 /root 的同时,ssh 仍能读到
|
||||
# ~/.ssh(它在 /var/lib 下,不受 ProtectHome 影响),也能写 known_hosts
|
||||
ProtectHome=true
|
||||
Environment=HOME=/var/lib/chan-live/home
|
||||
ReadWritePaths=/var/lib/chan-live
|
||||
ProtectKernelTunables=true
|
||||
ProtectKernelModules=true
|
||||
RestrictSUIDSGID=true
|
||||
LockPersonality=true
|
||||
MemoryMax=256M
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Executable
+106
@@ -0,0 +1,106 @@
|
||||
#!/usr/bin/env bash
|
||||
# 空跑验全链:真连交易所读规则/持仓,**不下任何真单**。
|
||||
#
|
||||
# 上真单之前必须过这一步。它验的是那些"上线才会暴露、且暴露方式是花钱"的
|
||||
# 环节:密钥能不能用、IP 白名单对不对、时钟同不同步、搬运通不通、
|
||||
# 数量与价位取整合不合交易所规则。
|
||||
set -euo pipefail
|
||||
|
||||
APP=/opt/chan
|
||||
CONF=/etc/chan-live/live.env
|
||||
STATE=/var/lib/chan-live
|
||||
USER_NAME=chan
|
||||
SECS="${SECS:-90}"
|
||||
|
||||
die() { echo "⛔ $*" >&2; exit 1; }
|
||||
ok() { echo " ✓ $*"; }
|
||||
|
||||
[[ $EUID -eq 0 ]] || die "要 root:sudo $0"
|
||||
[[ -f "$CONF" ]] || die "缺 $CONF,先跑 install.sh"
|
||||
|
||||
set -a; . "$CONF"; set +a
|
||||
|
||||
echo "── 1. 配置自检 ──"
|
||||
for v in BITGET_API_KEY BITGET_API_SECRET BITGET_PASSPHRASE SHIP_FROM; do
|
||||
[[ -n "${!v:-}" ]] || die "$CONF 里 $v 还是空的"
|
||||
done
|
||||
ok "密钥三项与 SHIP_FROM 都已填"
|
||||
[[ "$LIVE_HOME" != /opt/chan* ]] || die "LIVE_HOME 不能指到仓库里(会被 git 清掉)"
|
||||
ok "LIVE_HOME=$LIVE_HOME 在仓库外"
|
||||
|
||||
echo "── 2. 时钟 ──"
|
||||
# staleness 闸靠两机时钟一致才有意义。这里只能验本机;跨机偏差由
|
||||
# ship_signals 在收到信号时报「时间倒流」
|
||||
if command -v chronyc >/dev/null; then
|
||||
chronyc tracking | grep -E "Reference ID|System time|Leap status" | sed 's/^/ /'
|
||||
src="$(chronyc tracking | awk '/Reference ID/{print $NF}')"
|
||||
[[ "$src" != "()" && -n "$src" ]] || die "chrony 还没同步上,等一会再跑"
|
||||
ok "chrony 已同步"
|
||||
else
|
||||
die "没装 chrony。staleness 闸不可信,先 apt install chrony"
|
||||
fi
|
||||
|
||||
echo "── 3. 出口 IP 是否在白名单内 ──"
|
||||
myip="$(curl -s --max-time 10 https://api.ipify.org || true)"
|
||||
[[ -n "$myip" ]] && echo " 本机出口 IP:$myip" || echo " ⚠ 取不到出口 IP"
|
||||
echo " 对照 Bitget 后台该 key 的 IP 白名单,不一致下面会报 40018 之类"
|
||||
|
||||
echo "── 4. 能否 ssh 到采集机 ──"
|
||||
# 不能用 ssh <host> 'echo ok' 来试:采集机那侧的 authorized_keys 用了强制命令
|
||||
# (把这把 key 锁成只能跑 tail,拿不到 shell),任何请求都会变成 tail -F,
|
||||
# 而它**永不返回**——ConnectTimeout 只管建连不管命令时长,测试会永久挂住。
|
||||
# 所以照 ship_signals 的真实用法读流:tail -c +0 会先把整个文件吐出来,
|
||||
# 数一下就等于对端总线的条数,之后它挂着等新内容,由 timeout 收掉。
|
||||
rb="${SHIP_REMOTE_BUS:-\$HOME/chan-live/state/signals_live.jsonl}"
|
||||
err="$(mktemp)"; outf="$(mktemp)"
|
||||
# timeout 要套在 sudo **里面**:套外面时 SIGTERM 只到 sudo,未必传给 ssh,
|
||||
# 于是该被收掉的 tail 会继续挂着
|
||||
sudo -u "$USER_NAME" timeout 12 ssh -T -o BatchMode=yes -o ConnectTimeout=10 \
|
||||
"$SHIP_FROM" "tail -c +0 -F $rb" >"$outf" 2>"$err" || true
|
||||
n="$(wc -l < "$outf")"
|
||||
if grep -qi "Host key verification failed" "$err"; then
|
||||
fp="(在采集机上跑 ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub 拿)"
|
||||
rm -f "$err" "$outf"
|
||||
die "主机指纹没确认过。这不是 key 的问题,装 key 也修不了。
|
||||
$USER_NAME 的 known_hosts 是空的,而 BatchMode=yes 不允许交互确认。
|
||||
**不要**用 StrictHostKeyChecking=no 糊过去,那等于放弃中间人防护。
|
||||
正确做法:在采集机上读出权威指纹 $fp,
|
||||
再在这台上写入并核对:
|
||||
sudo -u $USER_NAME ssh-keyscan -t ed25519 <采集机IP> \\
|
||||
| sudo -u $USER_NAME tee -a $STATE/home/.ssh/known_hosts
|
||||
sudo -u $USER_NAME ssh-keygen -lf $STATE/home/.ssh/known_hosts"
|
||||
elif grep -qiE "Permission denied|publickey" "$err"; then
|
||||
rm -f "$err" "$outf"
|
||||
die "认证被拒。指纹是通的,是 key 没装到采集机上:
|
||||
sudo -u $USER_NAME ssh-keygen -t ed25519 -N '' -f $STATE/home/.ssh/id_ed25519
|
||||
再把 $STATE/home/.ssh/id_ed25519.pub 加到采集机的 authorized_keys"
|
||||
elif [[ -s "$err" ]] && ! grep -q "^" "$outf" 2>/dev/null; then
|
||||
msg="$(head -3 "$err")"; rm -f "$err" "$outf"
|
||||
die "ssh $SHIP_FROM 不通:$msg"
|
||||
else
|
||||
ok "ssh $SHIP_FROM 通"
|
||||
echo " 对端总线现有 $n 条信号"
|
||||
[[ "$n" -gt 0 ]] || echo " ⚠ 对端总线是空的。信号 6.8 个/天,刚重启过就是空的很正常;但要确认采集机接了总线"
|
||||
rm -f "$err" "$outf"
|
||||
fi
|
||||
|
||||
echo "── 5. 执行器空跑 ${SECS}s(真连交易所,不下单)──"
|
||||
# --dry-run 下只读不写:下单一律只打印。合约规则那个端点是**公开**的、不验签,
|
||||
# 所以空跑里专门补了一次带签名的 account() —— 否则这一步会"通过"却根本没测到
|
||||
# 密钥与 IP 白名单,等第一个真信号来时才暴露,而那时信号正在过期
|
||||
# 让 chan 自己 source 配置($CONF 是 640 root:chan,它读得到)。
|
||||
# 不用 `env "$(grep ...)"` 那种拼法:值里有空格就会被切开
|
||||
set +e
|
||||
sudo -u "$USER_NAME" bash -c \
|
||||
"set -a; . '$CONF'; set +a; exec timeout $SECS \
|
||||
'$APP/.venv/bin/python' '$APP/live/live_exec.py' --dry-run"
|
||||
rc=$?
|
||||
set -e
|
||||
# timeout 到点是 124,属于预期
|
||||
[[ $rc -eq 124 || $rc -eq 0 ]] || die "空跑退出码 $rc,看上面报错"
|
||||
ok "空跑没有报错退出"
|
||||
|
||||
echo
|
||||
echo "空跑过了。真跑:"
|
||||
echo " sudo systemctl enable --now chan-live-ship chan-live-exec"
|
||||
echo " $APP/live/deploy/status.sh"
|
||||
Executable
+203
@@ -0,0 +1,203 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在生产机(有 Bitget API key 白名单的那台)上装实盘执行器。
|
||||
#
|
||||
# 只装执行侧:标准库 + aiohttp。**不装** Docker / Hummingbot / pandas /
|
||||
# chanlun 引擎——那些是采集与研究侧的依赖,理由见 live/live_exec.py 文件头。
|
||||
#
|
||||
# sudo ./install.sh # 从当前 checkout 安装
|
||||
# sudo REPO=git@host:jack/chan.git ./install.sh # 或指定远程克隆
|
||||
#
|
||||
# 幂等:重复跑只会更新代码与依赖,不动 /etc/chan-live/live.env 和状态目录。
|
||||
set -euo pipefail
|
||||
|
||||
APP=/opt/chan
|
||||
STATE=/var/lib/chan-live
|
||||
CONF=/etc/chan-live
|
||||
USER_NAME=chan
|
||||
BRANCH="${BRANCH:-chan}"
|
||||
REPO="${REPO:-}"
|
||||
|
||||
die() { echo "⛔ $*" >&2; exit 1; }
|
||||
say() { echo " $*"; }
|
||||
|
||||
[[ $EUID -eq 0 ]] || die "要 root:sudo $0"
|
||||
|
||||
# ── --sync-env:把模板新增的项追加到已有配置 ────────────────────────
|
||||
# 独立成一个模式而不是塞进安装流程:追加会改一个装着密钥的文件,这种事应当
|
||||
# 由你显式发起。只追加缺的项(连它上面的注释一起),**不动**已有任何一行。
|
||||
if [[ "${1:-}" == "--sync-env" ]]; then
|
||||
EX="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/live.env.example"
|
||||
[[ -f "$EX" ]] || die "找不到模板 $EX"
|
||||
[[ -f "$CONF/live.env" ]] || die "$CONF/live.env 还不存在,先跑一次 sudo $0"
|
||||
cp -a "$CONF/live.env" "$CONF/live.env.bak.$(date +%Y%m%d%H%M%S)"
|
||||
python3 - "$EX" "$CONF/live.env" <<'PY'
|
||||
import re
|
||||
import sys
|
||||
|
||||
ex_path, live_path = sys.argv[1], sys.argv[2]
|
||||
ex = open(ex_path, encoding="utf-8").read().splitlines()
|
||||
live = open(live_path, encoding="utf-8").read()
|
||||
KEY = re.compile(r"^([A-Z_][A-Z0-9_]*)=")
|
||||
have = set(KEY.match(x).group(1) for x in live.splitlines() if KEY.match(x))
|
||||
|
||||
add, block = [], []
|
||||
for line in ex:
|
||||
if KEY.match(line):
|
||||
k = KEY.match(line).group(1)
|
||||
if k not in have:
|
||||
add += block + [line]
|
||||
block = []
|
||||
elif line.startswith("#") or (not line.strip() and block):
|
||||
block.append(line)
|
||||
else:
|
||||
block = []
|
||||
|
||||
if not add:
|
||||
print(" 配置已是最新,无需追加")
|
||||
raise SystemExit(0)
|
||||
with open(live_path, "a", encoding="utf-8") as f:
|
||||
f.write("\n\n# ── 以下由 install.sh --sync-env 追加 ──\n")
|
||||
f.write("\n".join(add) + "\n")
|
||||
n = sum(1 for x in add if KEY.match(x))
|
||||
print(f" 追加了 {n} 项:" +
|
||||
" ".join(KEY.match(x).group(1) for x in add if KEY.match(x)))
|
||||
PY
|
||||
say "原文件已备份为 $CONF/live.env.bak.*"
|
||||
say "追加的项多半是空值,逐项填完再重启:sudo systemctl restart chan-live-exec"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# ── 1. 系统依赖 ────────────────────────────────────────────────────
|
||||
say "装系统包"
|
||||
if command -v apt-get >/dev/null; then
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update -qq
|
||||
# chrony 不是可选项:staleness 闸靠两机时钟一致才有意义,
|
||||
# 采集机时钟快 5 分钟就等于把闸放宽 5 分钟(见 ship_signals.py)
|
||||
apt-get install -y -qq python3-venv python3-pip git chrony openssh-client
|
||||
elif command -v dnf >/dev/null; then
|
||||
dnf install -y -q python3 python3-pip git chrony openssh-clients
|
||||
else
|
||||
die "只认 apt/dnf,其他发行版请手工装 python3-venv git chrony"
|
||||
fi
|
||||
systemctl enable --now chrony 2>/dev/null || systemctl enable --now chronyd
|
||||
|
||||
# ── 2. 专用用户与目录 ──────────────────────────────────────────────
|
||||
if ! id -u "$USER_NAME" >/dev/null 2>&1; then
|
||||
say "建系统用户 $USER_NAME(无登录 shell)"
|
||||
useradd --system --home-dir "$STATE/home" --create-home \
|
||||
--shell /usr/sbin/nologin "$USER_NAME"
|
||||
fi
|
||||
install -d -o "$USER_NAME" -g "$USER_NAME" -m 750 "$STATE" "$STATE/state" "$STATE/home"
|
||||
install -d -o "$USER_NAME" -g "$USER_NAME" -m 700 "$STATE/home/.ssh"
|
||||
install -d -o root -g "$USER_NAME" -m 750 "$CONF"
|
||||
|
||||
# ── 3. 代码 ────────────────────────────────────────────────────────
|
||||
if [[ -n "$REPO" ]]; then
|
||||
if [[ -d "$APP/.git" ]]; then
|
||||
say "更新已有 checkout"
|
||||
git -C "$APP" fetch --quiet origin "$BRANCH"
|
||||
git -C "$APP" checkout --quiet "$BRANCH"
|
||||
git -C "$APP" reset --hard --quiet "origin/$BRANCH"
|
||||
else
|
||||
say "克隆 $REPO"
|
||||
rm -rf "$APP"; git clone --quiet --branch "$BRANCH" "$REPO" "$APP"
|
||||
fi
|
||||
else
|
||||
SRC="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
[[ -f "$SRC/live/live_exec.py" ]] || die "$SRC 不像仓库根(缺 live/live_exec.py)"
|
||||
if [[ "$SRC" != "$APP" ]]; then
|
||||
say "从 $SRC 同步代码到 $APP"
|
||||
install -d "$APP"
|
||||
# 只同步生产要的那一个子树。研究侧的 research/ 不上生产机:
|
||||
# 它带 pandas/pyarrow/hummingbot,而且探针 OOM 过一次(14.9GB)
|
||||
cp -a "$SRC/live" "$APP/"
|
||||
fi
|
||||
fi
|
||||
chown -R root:root "$APP/live"
|
||||
find "$APP/live" -type f -exec chmod 644 {} + ; chmod 755 "$APP/live" "$APP/live/deploy"
|
||||
chmod 755 "$APP"/live/deploy/*.sh
|
||||
|
||||
# ── 4. venv ───────────────────────────────────────────────────────
|
||||
say "建 venv 并装依赖(应当只有 aiohttp)"
|
||||
[[ -d "$APP/.venv" ]] || python3 -m venv "$APP/.venv"
|
||||
"$APP/.venv/bin/pip" install --quiet --upgrade pip
|
||||
"$APP/.venv/bin/pip" install --quiet -r "$APP/live/requirements.txt"
|
||||
|
||||
# 断言生产进程没被拖进重量级依赖。这条会真挡住——曾经为读两个常量
|
||||
# import 研究侧的 step43,把 numpy/pandas/pyarrow 全拉进实盘进程
|
||||
say "验依赖面"
|
||||
"$APP/.venv/bin/python" - <<'PY' || die "生产进程拖进了重量级依赖,看上面输出"
|
||||
import sys
|
||||
sys.path.insert(0, "/opt/chan/live")
|
||||
import live_exec
|
||||
live_exec.assert_decomposable()
|
||||
heavy = [m for m in ("numpy", "pandas", "pyarrow", "hummingbot", "scipy")
|
||||
if m in sys.modules]
|
||||
if heavy:
|
||||
print(f" ⛔ 启动路径加载了 {heavy}")
|
||||
raise SystemExit(1)
|
||||
print(f" ✓ 只有标准库 + aiohttp · 出场结构 "
|
||||
f"{live_exec.SL_ATR}/{live_exec.SCALE_ATR}/{live_exec.RUNNER_ATR} ATR "
|
||||
f"/{live_exec.MAXB} 根")
|
||||
PY
|
||||
|
||||
# ── 5. 配置模板 ────────────────────────────────────────────────────
|
||||
if [[ ! -f "$CONF/live.env" ]]; then
|
||||
say "写配置模板 $CONF/live.env(密钥要你手工填)"
|
||||
install -o root -g "$USER_NAME" -m 640 \
|
||||
"$APP/live/deploy/live.env.example" "$CONF/live.env"
|
||||
NEED_FILL=1
|
||||
else
|
||||
say "$CONF/live.env 已存在,不覆盖(里面是密钥)"
|
||||
# 但要报出模板新增的项。不报的话,以后往 example 里加配置,已有部署会
|
||||
# **永远拿不到且毫无提示**——静默漂移,等到出事才发现某个开关根本没生效
|
||||
keys() { grep -oE '^[A-Z_][A-Z0-9_]*=' "$1" | tr -d '=' | sort -u; }
|
||||
MISSING="$(comm -23 <(keys "$APP/live/deploy/live.env.example") \
|
||||
<(keys "$CONF/live.env") | tr '\n' ' ')"
|
||||
if [[ -n "${MISSING// }" ]]; then
|
||||
say "⚠ 模板比你的配置多了这些项:$MISSING"
|
||||
say " 逐项看说明:$APP/live/deploy/live.env.example"
|
||||
say " 要把缺的那几行连注释一起追加过去,跑:"
|
||||
say " sudo $APP/live/deploy/install.sh --sync-env"
|
||||
NEED_FILL=1
|
||||
fi
|
||||
OBSOLETE="$(comm -13 <(keys "$APP/live/deploy/live.env.example") \
|
||||
<(keys "$CONF/live.env") | tr '\n' ' ')"
|
||||
[[ -n "${OBSOLETE// }" ]] && \
|
||||
say " 另有模板里已没有的项(可能已废弃):$OBSOLETE"
|
||||
fi
|
||||
|
||||
# ── 6. systemd ────────────────────────────────────────────────────
|
||||
say "装 systemd 单元"
|
||||
install -m 644 "$APP"/live/deploy/chan-live-*.service /etc/systemd/system/
|
||||
systemctl daemon-reload
|
||||
|
||||
echo
|
||||
echo "装好了。接下来按顺序做(**不要**跳过空跑那步):"
|
||||
echo
|
||||
if [[ -n "${NEED_FILL:-}" ]]; then
|
||||
echo " 1. 填密钥与参数:sudo vi $CONF/live.env"
|
||||
echo " BITGET_API_KEY / SECRET / PASSPHRASE 用只读+交易权限,"
|
||||
echo " **不要开提币权限**。SHIP_FROM 填采集机的 ssh 目标。"
|
||||
echo
|
||||
fi
|
||||
echo " 2. 装拉总线用的 ssh key:"
|
||||
echo " sudo -u $USER_NAME ssh-keygen -t ed25519 -N '' -f $STATE/home/.ssh/id_ed25519"
|
||||
echo " # 把 $STATE/home/.ssh/id_ed25519.pub 加到采集机的 authorized_keys"
|
||||
echo
|
||||
echo " 还要写 known_hosts,否则报 Host key verification failed —— 服务跑"
|
||||
echo " 起来会撞同一个墙,因为 BatchMode=yes 不允许交互确认:"
|
||||
echo " sudo -u $USER_NAME ssh-keyscan -t ed25519 <采集机IP> \\"
|
||||
echo " | sudo -u $USER_NAME tee -a $STATE/home/.ssh/known_hosts"
|
||||
echo " sudo -u $USER_NAME ssh-keygen -lf $STATE/home/.ssh/known_hosts"
|
||||
echo " # 把指纹跟采集机上 ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub"
|
||||
echo " # 的输出比一遍。**不要**图省事用 StrictHostKeyChecking=no,"
|
||||
echo " # 那等于放弃中间人防护,而这条链路上跑的是下单信号"
|
||||
echo
|
||||
echo " 3. 空跑验全链(不下真单,跑够看到一次心跳再停):"
|
||||
echo " sudo $APP/live/deploy/dryrun.sh"
|
||||
echo
|
||||
echo " 4. 真跑:"
|
||||
echo " sudo systemctl enable --now chan-live-ship chan-live-exec"
|
||||
echo " $APP/live/deploy/status.sh"
|
||||
@@ -0,0 +1,71 @@
|
||||
# 生产配置。装到 /etc/chan-live/live.env,权限 640 root:chan。
|
||||
# **不要提交填好的版本**——这里有交易权限的密钥。
|
||||
#
|
||||
# 改完要重启:sudo systemctl restart chan-live-exec
|
||||
|
||||
# ── Bitget 密钥 ───────────────────────────────────────────────────
|
||||
# 权限只勾「只读」+「交易」,**不要勾提币**。
|
||||
# IP 白名单填这台机的公网出口 IP(curl -s https://api.ipify.org 看)。
|
||||
# 这也是执行器必须跑在这台机上的唯一原因——密钥绑了这个 IP。
|
||||
BITGET_API_KEY=
|
||||
BITGET_API_SECRET=
|
||||
BITGET_PASSPHRASE=
|
||||
|
||||
# ── 信号来源(采集机)─────────────────────────────────────────────
|
||||
# ssh 目标。可以是 ~/.ssh/config 里的别名,或 user@ip
|
||||
SHIP_FROM=sg-collector
|
||||
# 采集机上总线文件的路径(在对端 shell 里展开,可用 ~)
|
||||
SHIP_REMOTE_BUS=~/chan-live/state/signals_live.jsonl
|
||||
|
||||
# ── 状态与总线 ────────────────────────────────────────────────────
|
||||
# 生产状态的根。**不要指到仓库里**:git checkout/clean 会动仓库,而这里存的
|
||||
# 是日亏损累计与在场仓位,被清掉等于 MAX_DAY_LOSS / MAX_OPEN 两道闸失忆。
|
||||
# systemd 单元里 ReadWritePaths 也是这个路径,改了要一起改
|
||||
LIVE_HOME=/var/lib/chan-live
|
||||
SIGNAL_BUS=/var/lib/chan-live/state/signals_live.jsonl
|
||||
|
||||
# ── 仓位 ─────────────────────────────────────────────────────────
|
||||
# 每笔名义额(USDT)。杠杆**不改**手续费与滑点(都按名义额收),所以抬名义额
|
||||
# 有真实成本;抬它的唯一理由是压掉步长取整:实测最差币的偏差
|
||||
# 100U → 6.7%(SOL)、500U → 1.8%、1000U → 0.6%
|
||||
LIVE_NOTIONAL=500
|
||||
# 杠杆只影响占用保证金,不影响名义敞口/手续费/滑点/盈亏绝对值。
|
||||
# 名义 500 在 10x 下占 50 USDT 保证金;止损在 2 ATR ≈ 0.2%,而 10x 强平约需
|
||||
# 逆向 10% = 100 个 ATR,差 50 倍。交易所侧记得设**逐仓**
|
||||
LIVE_LEVERAGE=10
|
||||
|
||||
# ── 硬约束:封的是「代价不随仓位缩小」的那几类故障 ─────────────────
|
||||
# 并发仓位数。信号 6.8 笔/天、持仓 48 分钟 → 期望并发 0.23 笔,3 已很宽。
|
||||
# 超了说明有 bug,不是行情好
|
||||
LIVE_MAX_OPEN=3
|
||||
# 日开仓上限。专门封「循环里的 bug 反复开仓」——单笔小但笔数无界
|
||||
LIVE_MAX_DAY=15
|
||||
# 日亏损上限(USDT)。一笔止损约 1 USDT,15 笔全亏 15 USDT
|
||||
LIVE_MAX_DAY_LOSS=20
|
||||
# 信号超过这么久就不做。参考成交价是次根开盘价,过期后跑的不是回测那个价。
|
||||
# ⚠️ 这道闸依赖两机时钟一致,chrony 必须在跑(install.sh 会装)
|
||||
LIVE_STALE_S=20
|
||||
|
||||
# 交易的币池。要与采集机一致,否则会收到不做的币的信号(会被忽略但徒增噪声)
|
||||
SYMS=BTC,ETH,SOL,BNB,XRP,DOGE,ADA,AVAX,LINK,LTC
|
||||
|
||||
# 盯交易所侧出场的轮询间隔(秒)。**别关掉这个循环**:止损与止盈在交易所侧
|
||||
# 成交,本进程收不到通知,缺了它 pnl_day 恒为 0,MAX_DAY_LOSS 就是死的
|
||||
LIVE_WATCH_S=10
|
||||
|
||||
# ── Telegram 通知 ─────────────────────────────────────────────────
|
||||
# 拿 token:Telegram 里找 @BotFather → /newbot
|
||||
# 拿 chat id:给 bot 随便发一句,再开
|
||||
# https://api.telegram.org/bot<TOKEN>/getUpdates 看 result[0].message.chat.id
|
||||
#
|
||||
# 留空则完全不推(不报错)。推的内容:开仓、平仓(带已实现盈亏)、被硬约束
|
||||
# 挡住、报错、对账平仓、跨日结算、启动与停机、整点在线。
|
||||
# **不推**信号过期跳过(常态,搬运重连会重放旧信号)和 5 分钟日志心跳。
|
||||
# 量级约 55 条/天上限(含 24 条在线)。
|
||||
TG_TOKEN=
|
||||
TG_CHAT=
|
||||
# 前缀,用来和采集机推的手工信号区分开——两边可以共用同一个 bot 和对话
|
||||
TG_TAG=实盘
|
||||
# 整点在线的间隔(分钟)。0 关掉。60 = 每天 24 条,和成交推送量级相当。
|
||||
# 这条必须带上游新鲜度:执行器活着不代表链路活着
|
||||
TG_HB_MIN=60
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user