chanlun 26.5.2

基于缠论(缠中说禅)理论的量化技术分析核心库,支持流式数据处理和多周期联立分析。
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
/*
 * MIT License
 *
 * Copyright (c) 2026 YuYuKunKun
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

use crate::algorithm::hub::中枢;
use crate::config::缠论配置;
use crate::kline::bar::K线;
use crate::kline::chan_kline::缠论K线;
use crate::structure::fractal_obj::分型;
use crate::structure::segment_feat::线段特征;
use crate::types::{分型结构, 相对方向, 缺口};
use std::rc::Rc;

/// 虚线 — 笔和线段的通用数据结构
///
/// 笔和线段共享此 struct,通过 `标识` 字段区分 ("笔"/"线段"/"扩展线段"等)
#[derive(Debug, Clone)]
pub struct 虚线 {
    pub 标识: String,
    pub 序号: i64,
    pub 级别: i64,
    pub : Rc<分型>,
    pub : Rc<分型>,
    pub 有效性: bool,
    pub 基础序列: Vec<Rc<虚线>>,
    pub 特征序列: Vec<Option<Rc<线段特征>>>,
    pub 实_中枢序列: Vec<Rc<中枢>>,
    pub 虚_中枢序列: Vec<Rc<中枢>>,
    pub 合_中枢序列: Vec<Rc<中枢>>,
    pub 确认K线: Option<Rc<缠论K线>>,
    pub 模式: String,
    pub _特征序列_显示: bool,
    pub 前一缺口: Option<缺口>,
    pub 前一结束位置: Option<Rc<虚线>>,
    pub 短路修正: bool,
}

/// MACD行为统计 — 统计MACD行为 方法的返回类型
#[derive(Debug, Clone)]
pub struct MACD行为统计 {
    pub DIF上穿0: i64,
    pub DIF下穿0: i64,
    pub DEA上穿0: i64,
    pub DEA下穿0: i64,
    pub 金叉次数: i64,
    pub 死叉次数: i64,
    pub 密集交叉区域: Vec<(usize, usize, usize)>,
}

impl 虚线 {
    pub fn new(
        序号: i64,
        标识: String,
        : Rc<分型>,
        : Rc<分型>,
        级别: i64,
        有效性: bool,
    ) -> Self {
        Self {
            序号,
            标识,
            级别,,,
            有效性,
            基础序列: Vec::new(),
            特征序列: Vec::new(),
            实_中枢序列: Vec::new(),
            虚_中枢序列: Vec::new(),
            合_中枢序列: Vec::new(),
            确认K线: None,
            模式: "文武".into(),
            _特征序列_显示: false,
            前一缺口: None,
            前一结束位置: None,
            短路修正: false,
        }
    }

    /// 笔序列(基础序列的别名)
    pub fn 笔序列(&self) -> &Vec<Rc<虚线>> {
        &self.基础序列
    }

    pub fn 图表标题(&self) -> String {
        format!(
            "{}:{}:{}:{}",
            self...标识, self...周期, self.标识, self.序号
        )
    }

    /// 方向 — 文到武的方向
    pub fn 方向(&self) -> 相对方向 {
        match (self..结构, self..结构) {
            (分型结构::, 分型结构::) => 相对方向::向下,
            (分型结构::, 分型结构::) => 相对方向::向下,
            (分型结构::, 分型结构::) => 相对方向::向下,
            (分型结构::, 分型结构::) => 相对方向::向下,
            _ => 相对方向::向上,
        }
    }

    /// 虚线高
    pub fn (&self) -> f64 {
        if self.方向() == 相对方向::向下 {
            self...} else {
            self...}
    }

    /// 虚线低
    pub fn (&self) -> f64 {
        if self.方向() == 相对方向::向下 {
            self...} else {
            self...}
    }

    /// 判断两个虚线是否首尾相连
    pub fn 之前是(&self, 之前: &虚线) -> bool {
        if self.标识 != 之前.标识 {
            return false;
        }
        Rc::as_ptr(&之前.) == Rc::as_ptr(&self.)
    }

    /// 判断两个虚线是否首尾相连
    pub fn 之后是(&self, 之后: &虚线) -> bool {
        if self.标识 != 之后.标识 {
            return false;
        }
        Rc::as_ptr(&self.) == Rc::as_ptr(&之后.)
    }

    /// 获取该虚线范围内的普K序列
    pub fn 获取普K序列(&self, 普K序列: &[Rc<K线>]) -> Vec<Rc<K线>> {
        // 使用指针查找(与 Python list.index 身份匹配行为一致),
        // 而非序号切片——因为序号可能与实际位置不一致。
        let= 普K序列
            .iter()
            .position(|k| Rc::as_ptr(k) == Rc::as_ptr(&self...标的K线));
        let= 普K序列
            .iter()
            .position(|k| Rc::as_ptr(k) == Rc::as_ptr(&self...标的K线));
        match (,) {
            (Some(s), Some(e)) if s <= e => 普K序列[s..=e].to_vec(),
            _ => {
                // 指针查找失败时回退到序号方式
                println!("[警告]虚线.获取普K序列 <指针查找失败时回退到序号方式>");
                let= self...原始起始序号 as usize;
                let= self...原始结束序号 as usize;
                if< 普K序列.len() &&< 普K序列.len() &&<={
                    普K序列[..=].to_vec()
                } else {
                    Vec::new()
                }
            }
        }
    }

    /// 获取该虚线范围内的缠K序列
    pub fn 获取缠K序列(&self, 缠K序列: &[Rc<缠论K线>]) -> Vec<Rc<缠论K线>> {
        缠论K线::截取(缠K序列, &self.., &self..).unwrap_or_default()
    }

    /// 获取_武 — 递归获取虚线的终点分型(笔直接返回武,线段递归到底层笔的武)
    pub fn 获取_武(&self) -> Rc<分型> {
        if self.标识 == "" {
            return Rc::clone(&self.);
        }
        let mut current: &虚线 = self;
        while current.标识 != "" {
            current = &*current.基础序列.last().unwrap();
        }
        Rc::clone(&current.)
    }

    /// 获取数据文本(用于保存/调试)
    pub fn 获取数据文本(&self) -> String {
        use crate::utils::format_f64_g;
        if self.标识 == "" {
            return format!(
                "{}, {}, {}, 文:({},{}), 武:({},{}), {}",
                self.标识,
                self.序号,
                self.级别,
                self..时间戳,
                format_f64_g(self..分型特征值),
                self..时间戳,
                format_f64_g(self..分型特征值),
                if self.有效性 { "True" } else { "False" },
            );
        }

        // 非笔:线段/扩展线段等,完整输出
        let (,,, 贯穿伤) = crate::algorithm::segment::线段::分割序列(self, None);
        let (特征_a, 特征_b, 特征_c) = crate::algorithm::segment::线段::特征序列状态(self);
        let 特征_bool = |b: bool| -> &str {
            if b {
                "True"
            } else {
                "False"
            }
        };

        let 前一缺口_str = match &self.前一缺口 {
            Some(g) => format!("{}", g),
            None => "None".to_string(),
        };
        let 前一结束位置_str = match &self.前一结束位置 {
            Some(d) => format!("{}", d),
            None => "None".to_string(),
        };

        // Format中枢序列 as Python-style list representations
        let 实_str = format!(
            "[{}]",
            self.实_中枢序列
                .iter()
                .map(|h| format!("{}", h))
                .collect::<Vec<_>>()
                .join(", ")
        );
        let 虚_str = format!(
            "[{}]",
            self.虚_中枢序列
                .iter()
                .map(|h| format!("{}", h))
                .collect::<Vec<_>>()
                .join(", ")
        );
        let 合_str = format!(
            "[{}]",
            self.合_中枢序列
                .iter()
                .map(|h| format!("{}", h))
                .collect::<Vec<_>>()
                .join(", ")
        );

        let 前_str = format!(
            "[{}]",.iter()
                .map(|d| format!("{}", d))
                .collect::<Vec<_>>()
                .join(", ")
        );
        let 后_str = format!(
            "[{}]",.iter()
                .map(|d| format!("{}", d))
                .collect::<Vec<_>>()
                .join(", ")
        );
        let 三_str = format!(
            "[{}]",.iter()
                .map(|d| format!("{}", d))
                .collect::<Vec<_>>()
                .join(", ")
        );

        format!(
            "{}, {}, {}, 文:({},{}), 武:({},{}), {}, {}, ({}, {}, {}), (前: {}, 后: {}, 三: {}, 伤: {}), 实: {}, 虚: {}, 合: {}, {}, {}, {}, {}",
            self.标识,
            self.序号,
            self.级别,
            self..时间戳,
            format_f64_g(self..分型特征值),
            self..时间戳,
            format_f64_g(self..分型特征值),
            if self.有效性 { "True" } else { "False" },
            self.基础序列.len(),
            特征_bool(特征_a),
            特征_bool(特征_b),
            特征_bool(特征_c),
            前_str,
            后_str,
            三_str,
            match &贯穿伤 { Some(d) => format!("{}", d), None => "None".to_string() },
            实_str,
            虚_str,
            合_str,
            self.模式,
            前一缺口_str,
            前一结束位置_str,
            if self.短路修正 { "True" } else { "False" },
        )
    }

    // ---- 关联函数(静态工厂方法) ----

    /// 创建笔
    pub fn 创建笔(: Rc<分型>, : Rc<分型>, 有效性: bool) -> Self {
        Self::new(0, "".into(),,, 1, 有效性)
    }

    /// 创建线段
    pub fn 创建线段(虚线序列: &[Rc<虚线>]) -> Self {
        let= Rc::clone(&虚线序列[0].);
        let= Rc::clone(&虚线序列[虚线序列.len() - 1].);
        let 标识 = if 虚线序列[0].标识 == "" {
            "线段".into()
        } else {
            format!("线段<{}>", 虚线序列[0].标识)
        };
        let 级别 = 虚线序列[0].级别 + 1;
        let mut= Self::new(0, 标识,,, 级别, true);.基础序列 = 虚线序列.to_vec();.模式 = "文武".into();}

    // ---- 买卖点模式匹配 ----

    /// 缠K买卖点模式 — 根据模式字符串选择匹配方法
    pub fn 缠K买卖点模式(模式: &str, 缠K: &缠论K线, 配置: &缠论配置) -> bool {
        match 模式 {
            "全量" => Self::买卖点全量匹配(缠K),
            "任意" => Self::买卖点任意匹配(缠K),
            "配置" => Self::买卖点配置匹配(缠K, 配置),
            "相对" => Self::买卖点相对匹配(缠K),
            _ => false,
        }
    }

    /// 买卖点配置匹配 — 根据配置中的指标开关组合判断
    pub fn 买卖点配置匹配(缠K: &缠论K线, 配置: &缠论配置) -> bool {
        match (
            配置.买卖点_指标匹配_MACD,
            配置.买卖点_指标匹配_KDJ,
            配置.买卖点_指标匹配_RSI,
        ) {
            (true, true, true) => 缠K.与MACD柱子匹配() && 缠K.与KDJ匹配() && 缠K.与RSI匹配(),
            (false, false, false) => false,
            (true, false, true) => 缠K.与MACD柱子匹配() && 缠K.与RSI匹配(),
            (false, true, false) => 缠K.与KDJ匹配(),
            (true, false, false) => 缠K.与MACD柱子匹配(),
            (false, true, true) => 缠K.与KDJ匹配() && 缠K.与RSI匹配(),
            (false, false, true) => 缠K.与RSI匹配(),
            (true, true, false) => 缠K.与MACD柱子匹配() && 缠K.与KDJ匹配(),
        }
    }

    /// 买卖点任意匹配 — 任一指标匹配
    pub fn 买卖点任意匹配(缠K: &缠论K线) -> bool {
        缠K.与MACD柱子匹配() || 缠K.与KDJ匹配() || 缠K.与RSI匹配()
    }

    /// 买卖点全量匹配 — 全部指标匹配
    pub fn 买卖点全量匹配(缠K: &缠论K线) -> bool {
        缠K.与MACD柱子匹配() && 缠K.与KDJ匹配() && 缠K.与RSI匹配()
    }

    /// 买卖点相对匹配 — 至少两个指标匹配
    pub fn 买卖点相对匹配(缠K: &缠论K线) -> bool {
        let 混沌槽 = [缠K.与MACD柱子匹配(), 缠K.与KDJ匹配(), 缠K.与RSI匹配()];
        混沌槽.iter().filter(|&&x| x).count() >= 2
    }

    // ---- MACD柱子均值计算 ----

    /// 计算MACD柱子均值 — 虚线范围内所有MACD柱的绝对值均值
    pub fn 计算MACD柱子均值(普K序列: &[Rc<K线>], 实线: &虚线) -> f64 {
        let K线序列 = K线::截取rc(普K序列, &实线...标的K线, &实线...标的K线);
        if K线序列.is_empty() {
            return 0.0;
        }
        let: f64 = K线序列
            .iter()
            .filter_map(|k| k.macd.as_ref())
            .map(|m| m.MACD柱.abs())
            .sum();/ K线序列.len() as f64
    }

    /// 计算MACD柱子均值_阴 — 负柱的绝对值均值
    pub fn 计算MACD柱子均值_阴(普K序列: &[Rc<K线>], 实线: &虚线) -> Option<f64> {
        let K线序列 = K线::截取rc(普K序列, &实线...标的K线, &实线...标的K线);
        let: Vec<f64> = K线序列
            .iter()
            .filter_map(|k| k.macd.as_ref())
            .filter(|m| m.MACD柱 < 0.0)
            .map(|m| m.MACD柱.abs())
            .collect();
        if.is_empty() {
            None
        } else {
            Some(.iter().sum::<f64>() /.len() as f64)
        }
    }

    /// 计算MACD柱子均值_阳 — 正柱的绝对值均值
    pub fn 计算MACD柱子均值_阳(普K序列: &[Rc<K线>], 实线: &虚线) -> Option<f64> {
        let K线序列 = K线::截取rc(普K序列, &实线...标的K线, &实线...标的K线);
        let: Vec<f64> = K线序列
            .iter()
            .filter_map(|k| k.macd.as_ref())
            .filter(|m| m.MACD柱 > 0.0)
            .map(|m| m.MACD柱.abs())
            .collect();
        if.is_empty() {
            None
        } else {
            Some(.iter().sum::<f64>() /.len() as f64)
        }
    }

    // ---- 武之MACD比较 ----

    /// 武之全量MACD均值 — 武端MACD柱是否小于均值(背驰)
    pub fn 武之全量MACD均值(普K序列: &[Rc<K线>], 实线: &虚线) -> bool {
        let 武_MACD = match &实线...标的K线.macd {
            Some(m) => m.MACD柱.abs(),
            None => return false,
        };
        武_MACD < Self::计算MACD柱子均值(普K序列, 实线)
    }

    /// 武之MACD均值 — 按方向选择阴/阳均值比对
    pub fn 武之MACD均值(普K序列: &[Rc<K线>], 实线: &虚线) -> bool {
        if 实线.方向() == 相对方向::向上 {
            Self::武之MACD均值_阳(普K序列, 实线)
        } else {
            Self::武之MACD均值_阴(普K序列, 实线)
        }
    }

    /// 武之MACD均值_阴 — 武端负柱是否小于阴均值
    pub fn 武之MACD均值_阴(普K序列: &[Rc<K线>], 实线: &虚线) -> bool {
        let 武_MACD = match &实线...标的K线.macd {
            Some(m) => m.MACD柱.abs(),
            None => return false,
        };
        match Self::计算MACD柱子均值_阴(普K序列, 实线) {
            Some(均值) => 武_MACD < 均值.abs(),
            None => false,
        }
    }

    /// 武之MACD均值_阳 — 武端正柱是否小于阳均值
    pub fn 武之MACD均值_阳(普K序列: &[Rc<K线>], 实线: &虚线) -> bool {
        let 武_MACD = match &实线...标的K线.macd {
            Some(m) => m.MACD柱.abs(),
            None => return false,
        };
        match Self::计算MACD柱子均值_阳(普K序列, 实线) {
            Some(均值) => 武_MACD < 均值,
            None => false,
        }
    }

    /// 武之MACD极值 — 武端MACD柱是否为区间极值
    pub fn 武之MACD极值(普K序列: &[Rc<K线>], 实线: &虚线) -> bool {
        let 武_MACD = match &实线...标的K线.macd {
            Some(m) => m.MACD柱,
            None => return false,
        };
        let K线序列 = K线::截取rc(普K序列, &实线...标的K线, &实线...标的K线);
        let 所有柱子: Vec<f64> = K线序列
            .iter()
            .filter_map(|k| k.macd.as_ref())
            .map(|m| m.MACD柱)
            .collect();
        if 所有柱子.is_empty() {
            return false;
        }
        if 武_MACD > 0.0 {
            let 极值 = 所有柱子.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
            极值 == 武_MACD
        } else {
            let 极值 = 所有柱子.iter().cloned().fold(f64::INFINITY, f64::min);
            极值 == 武_MACD
        }
    }

    // ---- MACD趋向背驰 ----

    /// 计算K线序列MACD趋向背驰 — 分析 MACD柱/DIF/DEA 三项背驰信号
    pub fn 计算K线序列MACD趋向背驰(
        普K序列: &[Rc<K线>], 方向: 相对方向
    ) -> [bool; 3] {
        if 普K序列.is_empty() {
            return [false, false, false];
        }
        let 最后 = &普K序列[普K序列.len() - 1];

        if 方向 == 相对方向::向上 {
            let 柱子序列: Vec<&Rc<K线>> = 普K序列
                .iter()
                .filter(|k| k.macd.as_ref().map_or(false, |m| m.MACD柱 > 0.0))
                .collect();
            if 柱子序列.is_empty() {
                return [false, false, false];
            }

            let mut 结果 = [false; 3];

            // MACD柱背驰
            let 最高柱子 = 柱子序列
                .iter()
                .max_by(|a, b| {
                    a.macd
                        .as_ref()
                        .unwrap()
                        .MACD柱
                        .partial_cmp(&b.macd.as_ref().unwrap().MACD柱)
                        .unwrap_or(std::cmp::Ordering::Equal)
                })
                .unwrap();
            let mut 柱对 = vec![Rc::clone(*最高柱子), Rc::clone(最后)];
            柱对.sort_by_key(|k| k.时间戳);
            if let (Some(m0), Some(m1)) = (柱对[0].macd.as_ref(), 柱对[1].macd.as_ref()) {
                if m0.MACD柱 > m1.MACD柱 && 柱对[0].< 柱对[1].{
                    结果[0] = true;
                }
            }

            // DIF背驰 (no sort — Python compares peak vs last directly)
            let 最高离差值 = 柱子序列
                .iter()
                .max_by(|a, b| {
                    let da = a.macd.as_ref().and_then(|m| m.DIF).unwrap_or(0.0);
                    let db = b.macd.as_ref().and_then(|m| m.DIF).unwrap_or(0.0);
                    da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
                })
                .unwrap();
            if let (Some(m0), Some(m1)) = (最高离差值.macd.as_ref(), 最后.macd.as_ref()) {
                let dif0 = m0.DIF.unwrap_or(0.0);
                let dif1 = m1.DIF.unwrap_or(0.0);
                if dif0 > dif1 && 最高离差值.< 最后.{
                    结果[1] = true;
                }
            }

            // DEA背驰 (no sort — Python compares peak vs last directly)
            let 最高信号线 = 柱子序列
                .iter()
                .max_by(|a, b| {
                    let da = a.macd.as_ref().and_then(|m| m.DEA).unwrap_or(0.0);
                    let db = b.macd.as_ref().and_then(|m| m.DEA).unwrap_or(0.0);
                    da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
                })
                .unwrap();
            if let (Some(m0), Some(m1)) = (最高信号线.macd.as_ref(), 最后.macd.as_ref()) {
                let dea0 = m0.DEA.unwrap_or(0.0);
                let dea1 = m1.DEA.unwrap_or(0.0);
                if dea0 > dea1 && 最高信号线.< 最后.{
                    结果[2] = true;
                }
            }

            结果
        } else {
            let 柱子序列: Vec<&Rc<K线>> = 普K序列
                .iter()
                .filter(|k| k.macd.as_ref().map_or(false, |m| m.MACD柱 < 0.0))
                .collect();
            if 柱子序列.is_empty() {
                return [false, false, false];
            }

            let mut 结果 = [false; 3];

            // MACD柱背驰 (负向: absolute value comparison)
            let 最高柱子 = 柱子序列
                .iter()
                .max_by(|a, b| {
                    a.macd
                        .as_ref()
                        .unwrap()
                        .MACD柱
                        .abs()
                        .partial_cmp(&b.macd.as_ref().unwrap().MACD柱.abs())
                        .unwrap_or(std::cmp::Ordering::Equal)
                })
                .unwrap();
            let mut 柱对 = vec![Rc::clone(*最高柱子), Rc::clone(最后)];
            柱对.sort_by_key(|k| k.时间戳);
            if let (Some(m0), Some(m1)) = (柱对[0].macd.as_ref(), 柱对[1].macd.as_ref()) {
                if m0.MACD柱 < m1.MACD柱 && 柱对[0].> 柱对[1].{
                    结果[0] = true;
                }
            }

            // DIF背驰 (no sort — Python compares peak vs last directly)
            let 最高离差值 = 柱子序列
                .iter()
                .max_by(|a, b| {
                    let da = a.macd.as_ref().and_then(|m| m.DIF).unwrap_or(0.0).abs();
                    let db = b.macd.as_ref().and_then(|m| m.DIF).unwrap_or(0.0).abs();
                    da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
                })
                .unwrap();
            if let (Some(m0), Some(m1)) = (最高离差值.macd.as_ref(), 最后.macd.as_ref()) {
                let dif0 = m0.DIF.unwrap_or(0.0);
                let dif1 = m1.DIF.unwrap_or(0.0);
                if dif0 < dif1 && 最高离差值.> 最后.{
                    结果[1] = true;
                }
            }

            // DEA背驰 (no sort — Python compares peak vs last directly)
            let 最高信号线 = 柱子序列
                .iter()
                .max_by(|a, b| {
                    let da = a.macd.as_ref().and_then(|m| m.DEA).unwrap_or(0.0).abs();
                    let db = b.macd.as_ref().and_then(|m| m.DEA).unwrap_or(0.0).abs();
                    da.partial_cmp(&db).unwrap_or(std::cmp::Ordering::Equal)
                })
                .unwrap();
            if let (Some(m0), Some(m1)) = (最高信号线.macd.as_ref(), 最后.macd.as_ref()) {
                let dea0 = m0.DEA.unwrap_or(0.0);
                let dea1 = m1.DEA.unwrap_or(0.0);
                if dea0 < dea1 && 最高信号线.> 最后.{
                    结果[2] = true;
                }
            }

            结果
        }
    }

    // ---- MACD柱子分段 ----

    /// 计算MACD柱子分段 — 按正负号将MACD柱子分段
    pub fn 计算MACD柱子分段(k线序列: &[Rc<K线>]) -> Vec<Vec<f64>> {
        if k线序列.is_empty() {
            return Vec::new();
        }

        let 符号 = |x: f64| -> &str {
            if x > 0.0 {
                ""
            } else {
                ""
            }
        };

        let 首_MACD = match &k线序列[0].macd {
            Some(m) => m.MACD柱,
            None => return Vec::new(),
        };
        let mut 当前符号 = 符号(首_MACD);
        let mut 当前段 = vec![首_MACD];
        let mut 结果 = Vec::new();

        for k线 in &k线序列[1..] {
            let macd = match &k线.macd {
                Some(m) => m.MACD柱,
                None => continue,
            };
            let 新符号 = 符号(macd);
            if 新符号 == 当前符号 {
                当前段.push(macd);
            } else {
                结果.push(std::mem::take(&mut 当前段));
                当前段.push(macd);
                当前符号 = 新符号;
            }
        }
        if !当前段.is_empty() {
            结果.push(当前段);
        }
        结果
    }

    // ---- 密集区域按间隔 ----

    /// 密集区域按间隔 — 找出交叉标记中的密集区域
    pub fn 密集区域按间隔(
        交叉标记: &[i32],
        最大间隔: usize,
        最少交叉数: usize,
    ) -> Vec<(usize, usize, usize)> {
        let 交叉索引: Vec<usize> = (0..交叉标记.len()).filter(|&i| 交叉标记[i] != 0).collect();
        if 交叉索引.is_empty() {
            return Vec::new();
        }

        let mut 密集区 = Vec::new();
        let mut 当前块起始 = 交叉索引[0];
        let mut 当前块交叉数 = 1;

        for i in 1..交叉索引.len() {
            let prev = 交叉索引[i - 1];
            let curr = 交叉索引[i];
            if curr - prev <= 最大间隔 {
                当前块交叉数 += 1;
            } else {
                if 当前块交叉数 >= 最少交叉数 {
                    密集区.push((当前块起始, prev, 当前块交叉数));
                }
                当前块起始 = curr;
                当前块交叉数 = 1;
            }
        }

        if 当前块交叉数 >= 最少交叉数 {
            密集区.push((当前块起始, 交叉索引[交叉索引.len() - 1], 当前块交叉数));
        }

        密集区
    }

    // ---- 统计MACD行为 ----

    /// 统计MACD行为 — 分析DIF/DEA穿零轴和金叉死叉
    pub fn 统计MACD行为(
        普K序列: &[Rc<K线>],
        最大间隔: usize,
        最少交叉数: usize,
    ) -> MACD行为统计 {
        let mut dif_up = 0;
        let mut dif_down = 0;
        let mut dea_up = 0;
        let mut dea_down = 0;

        for i in 1..普K序列.len() {
            let pre = &普K序列[i - 1].macd;
            let cur = &普K序列[i].macd;
            if pre.is_none() || cur.is_none() {
                continue;
            }
            let (pre_dif, cur_dif) = (pre.as_ref().unwrap().DIF, cur.as_ref().unwrap().DIF);
            let (pre_dea, cur_dea) = (pre.as_ref().unwrap().DEA, cur.as_ref().unwrap().DEA);

            if let (Some(pd), Some(cd)) = (pre_dif, cur_dif) {
                if pd < 0.0 && cd >= 0.0 {
                    dif_up += 1;
                }
                if pd > 0.0 && cd <= 0.0 {
                    dif_down += 1;
                }
            }
            if let (Some(pd), Some(cd)) = (pre_dea, cur_dea) {
                if pd < 0.0 && cd >= 0.0 {
                    dea_up += 1;
                }
                if pd > 0.0 && cd <= 0.0 {
                    dea_down += 1;
                }
            }
        }

        let mut golden = 0;
        let mut death = 0;
        let mut 交叉标记 = vec![0i32];

        for i in 1..普K序列.len() {
            let pre = &普K序列[i - 1].macd;
            let cur = &普K序列[i].macd;
            if pre.is_none() || cur.is_none() {
                交叉标记.push(0);
                continue;
            }
            let pre_dif = pre.as_ref().unwrap().DIF;
            let pre_dea = pre.as_ref().unwrap().DEA;
            let cur_dif = cur.as_ref().unwrap().DIF;
            let cur_dea = cur.as_ref().unwrap().DEA;

            if let (Some(pd), Some(cd), Some(pe), Some(ce)) = (pre_dif, cur_dif, pre_dea, cur_dea) {
                if pd <= pe && cd > ce {
                    golden += 1;
                    交叉标记.push(1);
                } else if pd >= pe && cd < ce {
                    death += 1;
                    交叉标记.push(-1);
                } else {
                    交叉标记.push(0);
                }
            } else {
                交叉标记.push(0);
            }
        }

        let 密集交叉区域 = Self::密集区域按间隔(&交叉标记, 最大间隔, 最少交叉数);

        MACD行为统计 {
            DIF上穿0: dif_up,
            DIF下穿0: dif_down,
            DEA上穿0: dea_up,
            DEA下穿0: dea_down,
            金叉次数: golden,
            死叉次数: death,
            密集交叉区域,
        }
    }

    // ---- 买卖意义 ----

    /// 买卖意义 — 核心买卖点判断逻辑
    ///
    /// 返回 (是否有意义, 原因字符串)
    pub fn 买卖意义(
        实线: &虚线, 观察员: &crate::business::observer::观察者
    ) -> (bool, String) {
        let 普K序列 = &观察员.普通K线序列;
        let 配置 = &观察员.配置;

        if 实线.标识 != "" && 实线.标识 != "线段" && !实线.标识.starts_with("线段<")
        {
            return (false, "标识不在范围内".into());
        }

        // KDJ指标完整性检查
        match &实线...标的K线.kdj {
            Some(kdj) if kdj.K.is_some() && kdj.D.is_some() && kdj.J.is_some() => {}
            _ => return (false, "KDJ指标不完整".into()),
        }

        let 意义 = Self::缠K买卖点模式(&配置.买卖点_指标模式, &实线.., 配置);
        let 结果 = false;

        let 背驰过: Vec<Rc<缠论K线>> = if 实线.标识 == "" {
            crate::algorithm::bi::::是否背驰过(实线, 观察员)
        } else {
            crate::algorithm::segment::线段::是否背驰过(实线, 观察员)
        };

        if 意义 {
            if 实线.标识 == "" {
                if Self::武之MACD均值(普K序列, 实线) {
                    return (true, "武之MACD均值".into());
                }
                if Self::武之MACD极值(普K序列, 实线) && !背驰过.is_empty() {
                    return (true, "背驰过且极值".into());
                } else if 实线..与MACD柱子分型匹配() {
                    return (
                        true,
                        format!(
                            "背驰过:{},极值:{},柱子分型匹配",
                            背驰过.len(),
                            if Self::武之MACD极值(普K序列, 实线) {
                                "True"
                            } else {
                                "False"
                            }
                        ),
                    );
                }
            }
            if 实线.标识 != ""
                && crate::algorithm::segment::线段::判断线段内部是否背驰(实线, 观察员)
            {
                return (true, "线段内部背驰".into());
            }
        }

        if !结果 && 意义 && 实线...与MACD柱子匹配() {
            if Self::武之MACD极值(普K序列, 实线) && 背驰过.len() > 2 {
                return (true, "没结果, 极值, 柱子分型匹配, 背驰过大于2次".into());
            }
        }

        (结果, "".into())
    }
}

impl std::fmt::Display for 虚线 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.标识 == "" {
            write!(
                f,
                "笔({}, {}, {}, {}, 周期: {}, 数量: {})",
                self.序号,
                self.方向(),
                self.,
                self.,
                self...周期,
                self...序号 - self...序号 + 1
            )
        } else {
            let 四象 = crate::algorithm::segment::线段::四象(self);
            let 缺口 = crate::algorithm::segment::线段::获取缺口(self);
            let 缺口_str = match 缺口 {
                Some(g) => format!("{}", g),
                None => "None".to_string(),
            };
            let 确认K线_str = match &self.确认K线 {
                Some(k) => format!("{}", k),
                None => "None".to_string(),
            };
            write!(
                f,
                "{}<{}, {}, {}, {}, {}, 数量: {}, 缺口: {}, {}>",
                self.标识,
                self.序号,
                四象,
                self.方向(),
                self.,
                self.,
                self.基础序列.len(),
                缺口_str,
                确认K线_str,
            )
        }
    }
}