-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathchan.py
2775 lines (2319 loc) · 95.2 KB
/
chan.py
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
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
MIT License
Copyright (c) 2024 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.
"""
# -*- coding: utf-8 -*-
# @Time : 2024/10/15 16:45
# @Author : YuYuKunKun
# @File : chan.py
import json
import math
import mmap
import time
import struct
import asyncio
import datetime
import traceback
from enum import Enum
from random import randint, choice
from pathlib import Path
from threading import Thread
from functools import wraps, lru_cache
from typing import List, Self, Optional, Tuple, final, Dict, Any, Set, Final, SupportsInt, Union
from abc import ABCMeta, abstractmethod
import requests
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Request, Query
from termcolor import colored
from collections import defaultdict
# __all__ = ["Line", "Bar", "Bi", "Duan", "ZhongShu", "FenXing", "BaseAnalyzer"]
SupportsHL = Union["Line", "Bar", "Bi", "Duan", "ZhongShu", "FenXing", "Interval", "Pillar"]
def timer(func):
@wraps(func)
def wrapper_timer(*args, **kwargs):
tic = time.perf_counter()
value = func(*args, **kwargs)
toc = time.perf_counter()
elapsed_time = toc - tic
print(f"Elapsed time: {elapsed_time:0.4f} seconds")
return value
return wrapper_timer
def ts2int(timestamp: str):
return int(time.mktime(datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S").timetuple()))
def int2ts(timestamp: int):
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(timestamp)))
class Freq(Enum):
# 60 180 300 900 1800 3600 7200 14400 21600 43200 86400 259200
S1: int = 1
S3: int = 3
S5: int = 5
S12: int = 12
m1: int = 60 * 1
m3: int = 60 * 3 # 180
m5: int = 60 * 5 # 300
m15: int = 60 * 15 # 900
m30: int = 60 * 30 # 1800
H1: int = 60 * 60 * 1 # 3600
H2: int = 60 * 60 * 2 # 7200
H4: int = 60 * 60 * 4 # 14400
H6: int = 60 * 60 * 6 # 21600
H12: int = 60 * 60 * 12 # 43200
D1: int = 60 * 60 * 24 # 86400
D3: int = 60 * 60 * 24 * 3 # 259200
def __int__(self):
return self.value
class Pillar:
__slots__ = "high", "low"
def __init__(self, high: float, low: float):
assert high > low
self.high = high
self.low = low
class Shape(Enum):
D = "底分型"
G = "顶分型"
S = "上升分型"
X = "下降分型"
T = "喇叭口型"
def __str__(self):
return self.name
def __repr__(self):
return self.name
class Direction(Enum):
Up = "向上" # 上涨
Down = "向下" # 下跌
JumpUp = "缺口向上" # 向上跳空
JumpDown = "缺口向下" # 向下跳空
NextUp = "连接向上" # 高点与后一低点相同
NextDown = "连接向下" # 低点与后一高点相同
Left = "左包右" # 顺序包含
Right = "右包左" # 逆序包含
def __str__(self):
return self.name
def __repr__(self):
return self.name
def __int__(self):
match self:
case Direction.Up:
return 1
case Direction.Down:
return -1
case Direction.JumpUp:
return 2
case Direction.JumpDown:
return -2
case Direction.NextUp:
return 3
case Direction.NextDown:
return -3
case Direction.Left:
return 7
case Direction.Right:
return 9
def reversal(self) -> Self:
match self:
case Direction.Up:
return Direction.Down
case Direction.Down:
return Direction.Up
case Direction.JumpUp:
return Direction.JumpDown
case Direction.JumpDown:
return Direction.JumpUp
case Direction.NextUp:
return Direction.NextDown
case Direction.NextDown:
return Direction.NextUp
case Direction.Left:
return Direction.Right
case Direction.Right:
return Direction.Left
def is_down(self) -> bool:
match self:
case Direction.Down | Direction.JumpDown | Direction.NextDown:
return True
case _:
return False
def is_up(self) -> bool:
match self:
case Direction.Up | Direction.JumpUp | Direction.NextUp:
return True
case _:
return False
def is_jump(self) -> bool:
match self:
case Direction.JumpDown | Direction.JumpUp:
return True
case _:
return False
def is_include(self) -> bool:
match self:
case Direction.Left | Direction.Right:
return True
case _:
return False
def is_next(self):
match self:
case Direction.NextUp | Direction.NextDown:
return True
case _:
return False
@staticmethod
def generator(obj: int, directions):
i: int = obj
while i >= 0:
yield choice(directions)
i -= 1
class ChanException(Exception):
"""exception"""
...
def _print(*args, **kwords):
result = []
for i in args:
if i in ("小阳", True, Shape.D, "底分型") or "小阳" in str(i):
result.append(colored(i, "green"))
elif i in ("老阳", False, Shape.G, "顶分型") or "老阳" in str(i):
result.append(colored(i, "red"))
elif i in ("少阴",) or "少阴" in str(i):
result.append("\33[07m" + colored(i, "yellow"))
elif i in ("老阴",) or "老阴" in str(i):
result.append("\33[01m" + colored(i, "blue"))
elif "PUSH" in str(i):
result.append(colored(i, "red"))
elif "POP" in str(i):
result.append(colored(i, "green"))
elif "ANALYSIS" in str(i):
result.append(colored(i, "blue"))
else:
result.append(i)
result = tuple(result)
print(*result, **kwords)
def dp(*args, **kwords):
if not 1:
_print(*args, **kwords)
def bdp(*args, **kwargs):
if not 1:
dp(*args, **kwargs)
def ddp(*args, **kwargs):
if not 0:
dp(*args, **kwargs)
def zsdp(*args, **kwargs):
if not 1:
dp(*args, **kwargs)
@lru_cache(maxsize=128)
def double_relation(left: SupportsHL, right: SupportsHL) -> Direction:
"""
两个带有[low, high]对象的所有关系
"""
relation = None
assert left is not right, ChanException("相同对象无法比较", left, right)
if (left.low <= right.low) and (left.high >= right.high):
relation = Direction.Left # "左包右" # 顺序
elif (left.low >= right.low) and (left.high <= right.high):
relation = Direction.Right # "右包左" # 逆序
elif (left.low < right.low) and (left.high < right.high):
relation = Direction.Up # "上涨"
if left.high < right.low:
relation = Direction.JumpUp # "跳涨"
if left.high == right.low:
relation = Direction.NextUp
elif (left.low > right.low) and (left.high > right.high):
relation = Direction.Down # "下跌"
if left.low > right.high:
relation = Direction.JumpDown # "跳跌"
if left.low == right.high:
relation = Direction.NextDown
return relation
def triple_relation(left: SupportsHL, mid: SupportsHL, right: SupportsHL, use_right: bool = False, ignore: bool = False) -> tuple[Optional[Shape], tuple[Direction, Direction], Optional[Pillar]]:
"""
三棵缠论k线的所有关系#, 允许逆序包含存在。
顶分型: 中间高点为三棵最高点。
底分型: 中间低点为三棵最低点。
上升分型: 高点从左至右依次升高
下降分型: 低点从左至右依次降低
喇叭口型: 高低点从左至右依次更高更低
"""
if any((left == mid, mid == right, left == right)):
raise ChanException("相同对象无法比较")
zg = min(left.high, mid.high, right.high)
zd = max(left.low, mid.low, right.low)
if zg > zd:
pillar = Pillar(high=zg, low=zd)
else:
pillar = None
shape = None
lm = double_relation(left, mid)
mr = double_relation(mid, right)
# lr = double_relation(left, right)
match (lm, mr):
case (Direction.Left, _):
if ignore:
... # print("顺序包含 lm", left, mid)
else:
raise ChanException("顺序包含 lm", left, mid)
case (_, Direction.Left):
if ignore:
... # print("顺序包含 mr", mid, right)
else:
raise ChanException("顺序包含 mr", mid, right)
case (Direction.Up | Direction.JumpUp | Direction.NextUp, Direction.Up | Direction.JumpUp | Direction.NextUp):
shape = Shape.S
case (Direction.Up | Direction.JumpUp | Direction.NextUp, Direction.Down | Direction.JumpDown | Direction.NextDown):
shape = Shape.G
case (Direction.Up | Direction.JumpUp | Direction.NextUp, Direction.Right) if use_right:
shape = Shape.S
case (Direction.Down | Direction.JumpDown | Direction.NextDown, Direction.Up | Direction.JumpUp | Direction.NextUp):
shape = Shape.D
case (Direction.Down | Direction.JumpDown | Direction.NextDown, Direction.Down | Direction.JumpDown | Direction.NextDown):
shape = Shape.X
case (Direction.Down | Direction.JumpDown | Direction.NextDown, Direction.Right) if use_right:
shape = Shape.X
case (Direction.Right, Direction.Up | Direction.JumpUp | Direction.NextUp) if use_right:
shape = Shape.D
case (Direction.Right, Direction.Down | Direction.JumpDown | Direction.NextDown) if use_right:
shape = Shape.G
case (Direction.Right, Direction.Right) if use_right:
shape = Shape.T
case _:
print("未匹配的关系", use_right, lm, mr)
if shape is None:
... # print(colored("triple_relation: ", "red"), shape, (lm, mr), left, mid, right)
return shape, (lm, mr), pillar
class Command:
APPEND: Final[str] = "APPEND"
MODIFY: Final[str] = "MODIFY"
REMOVE: Final[str] = "REMOVE"
def __init__(self, cmd: str, info: str) -> None:
self.cmd = cmd
self.info = info
def __str__(self):
# return f"{self.cmd.upper()}({self.info})"
return f"{self.cmd.upper()}"
@classmethod
def Append(cls, stamp: str) -> Self:
return Command(cls.APPEND, stamp)
@classmethod
def Modify(cls, stamp: str) -> Self:
return Command(cls.MODIFY, stamp)
@classmethod
def Remove(cls, stamp: str) -> Self:
return Command(cls.REMOVE, stamp)
@final
class BSPoint:
__slots__ = "info", "tp", "dt", "price", "valid", "creation_offset", "fix_offset", "stamp"
def __init__(self, info: str, tp: str, dt: datetime, price: float, valid: bool, creation_offset: int, fix_offset: int, stamp: str) -> None:
self.info = info
self.tp = tp
self.dt = dt
self.price = price
self.valid = valid
self.creation_offset = creation_offset
self.fix_offset = fix_offset
self.stamp = stamp
class ZShuCondition(Enum):
"""中枢的三种情况"""
New: str = "新生"
Continue: str = "延续"
Expand: str = "扩张"
@final
class ChanConfig:
__slots__ = (
"ANALYZER_CALC_BI",
"ANALYZER_CALC_BI_ZS",
"ANALYZER_CALC_XD",
"ANALYZER_CALC_XD_ZS",
"ANALYZER_SHON_TV",
"BI_LASTorFIRST",
"BI_FENGXING",
"BI_JUMP",
"BI_JUMP_SCALE",
"BI_LENGTH",
"MACD_FAST_PERIOD",
"MACD_SIGNAL_PERIOD",
"MACD_SLOW_PERIOD",
"ANALYZER_CALC_MACD",
)
def __init__(self):
self.BI_LENGTH = 5 # 成BI最低长度
self.BI_JUMP = True # 跳空是否判定为 NewBar
self.BI_JUMP_SCALE = 0.15 # 当跳空是否判定为 NewBar时, 此值大于0时按照缺口所占比例判定是否为NewBar,等于0时直接判定为NerBar
self.BI_LASTorFIRST = True # 一笔终点存在多个终点时 True: last, False: first
self.BI_FENGXING = False # True: 一笔起始分型高低包含整支笔对象则不成笔, False: 只判断分型中间数据是否包含
self.ANALYZER_CALC_BI = True # 是否计算BI
self.ANALYZER_CALC_XD = True # 是否计算XD
self.ANALYZER_CALC_BI_ZS = True # 是否计算BI中枢
self.ANALYZER_CALC_XD_ZS = True # 是否计算XD中枢
self.ANALYZER_CALC_MACD = True # 是否计算MACD
self.ANALYZER_SHON_TV = True
self.MACD_FAST_PERIOD = 12.0
self.MACD_SLOW_PERIOD = 26.0
self.MACD_SIGNAL_PERIOD = 9.0
@final
class MACD:
def __init__(self, fast_ema: float, slow_ema: float, dif: float, dea: float, fastperiod: float = 12.0, slowperiod: float = 26.0, signalperiod: float = 9.0):
self.fast_ema = fast_ema
self.slow_ema = slow_ema
self.DIF = dif
self.DEA = dea
self.fastperiod = fastperiod
self.slowperiod = slowperiod
self.signalperiod = signalperiod
@classmethod
def calc(cls, pre: "Bar", bar: "Bar") -> Self:
value = bar.close
# 计算快线EMA
k_fast = 2.0 / (pre.macd.fastperiod + 1.0)
_fast_ema = value * k_fast + pre.macd.fast_ema * (1.0 - k_fast)
# 计算慢线EMA
k_slow = 2.0 / (pre.macd.slowperiod + 1.0)
_slow_ema = value * k_slow + pre.macd.slow_ema * (1.0 - k_slow)
# 计算DIF
_dif = _fast_ema - _slow_ema
# 计算DEA
k_dea = 2.0 / (pre.macd.signalperiod + 1.0)
_dea = _dif * k_dea + pre.macd.DEA * (1.0 - k_dea)
macd = MACD(_fast_ema, _slow_ema, _dif, _dea, fastperiod=pre.macd.fastperiod, slowperiod=pre.macd.slowperiod, signalperiod=pre.macd.signalperiod)
bar.macd = macd
return macd
@property
def bar(self) -> float:
"""MACD柱状图"""
return (self.DIF - self.DEA) * 2
class Observer(metaclass=ABCMeta):
thread = None
queue = asyncio.Queue()
loop = asyncio.get_event_loop()
TIME = 0.01
@abstractmethod
def notify(self, obj: Any, cmd: Command): ...
class Bar:
__slots__ = "index", "dt", "open", "high", "low", "close", "volume", "direction", "__stamp", "macd", "shape", "_raw_start_index", "raw_end_index"
def __init__(self, dt: datetime, o: float, high: float, low: float, c: float, v: float, i: int, stamp: str):
self.index: int = i
self.dt: datetime = dt
self.open: float = o
self.high: float = high
self.low: float = low
self.close: float = c
self.volume: float = v
if self.open > self.close:
self.direction = Direction.Down
else:
self.direction = Direction.Up
self.__stamp = stamp
self.macd = MACD(c, c, 0.0, 0.0)
self.shape: Optional[Shape] = None
self._raw_start_index: int = i
self.raw_end_index: int = i
@property
def stamp(self) -> str:
return self.__stamp
@property
def speck(self) -> float:
if self.shape is Shape.G:
return self.high
elif self.shape is Shape.S:
return self.high
elif self.shape is Shape.D:
return self.low
elif self.shape is Shape.X:
return self.low
else:
print("NewBar.speck: shape is None")
return self.high
def __str__(self):
return f"{self.__class__.__name__}<{self.__stamp}>({self.dt}, {self.high}, {self.low}, index={self.index})"
def __repr__(self):
return f"{self.__class__.__name__}<{self.__stamp}>({self.dt}, {self.high}, {self.low}, index={self.index})"
def __bytes__(self):
return struct.pack(
">6d",
int(self.dt.timestamp()),
round(self.open, 8),
round(self.high, 8),
round(self.low, 8),
round(self.close, 8),
round(self.volume, 8),
)
def to_new_bar(self, pre) -> Self:
if self.stamp == "NewBar":
return self
return Bar.creat_new_bar_from_raw(self, pre)
@classmethod
def creat_new_bar_from_raw(cls, bar: Self, pre: Optional[Self] = None):
return cls.creat_new_bar(bar.dt, bar.high, bar.low, bar.direction, bar.volume, bar.index, pre=pre)
@classmethod
def creat_new_bar(
cls,
dt: datetime,
high: float,
low: float,
direction: Direction,
volume: float,
raw_index: int,
pre: Optional[Self] = None,
):
assert high >= low
if direction == Direction.Down:
close = low
_open = high
else:
close = high
_open = low
if direction is Direction.Up:
shape = Shape.S
else:
shape = Shape.X
index = 0
nb = Bar(dt=dt, o=_open, high=high, low=low, c=close, v=volume, i=index, stamp="NewBar")
nb._raw_start_index = raw_index
nb.raw_end_index = raw_index
nb.shape = shape
if pre is not None:
nb.index = pre.index + 1
if double_relation(pre, nb).is_include():
raise ChanException(f"\n {double_relation(pre, nb)}\n {pre},\n {nb}")
return nb
@classmethod
def creat_raw_bar(cls, dt: datetime, o: float, h: float, low: float, c: float, v: float, i: int) -> Self:
return cls(dt, o, h, low, c, v, i, "RawBar")
@classmethod
def bars_save_as_dat(cls, path: str, bars: List):
with open(path, "wb") as f:
for bar in bars:
f.write(bytes(bar))
print(f"Saved {len(bars)} bars to {path}")
@classmethod
def from_be_bytes(cls, buf: bytes, stamp: str = "RawBar") -> Self:
timestamp, open_, high, low, close, vol = struct.unpack(">6d", buf[: struct.calcsize(">6d")])
return cls(
dt=datetime.datetime.fromtimestamp(timestamp),
o=open_,
high=high,
low=low,
c=close,
v=vol,
i=0,
stamp=stamp,
)
@classmethod
def from_csv_file(cls, path: str, stamp: str = "RawBar") -> List[Self]:
raws: List = []
with open(path, "r") as f:
stamps = f.readline().split(",")
ts = stamps.index("timestamp")
o = stamps.index("open")
h = stamps.index("high")
low = stamps.index("low")
c = stamps.index("close")
v = stamps.index("volume")
i = 0
for line in f.readlines():
info = line.split(",")
rb = Bar(datetime.datetime.strptime(info[ts], "%Y-%m-%d %H:%M:%S"), float(info[o]), float(info[h]), float(info[low]), float(info[c]), float(info[v]), i, stamp)
raws.append(rb)
i += 1
return raws
@classmethod
def generate(cls, bar: "Bar", direction: Direction, seconds: int, half: bool = False) -> Self:
offset = datetime.timedelta(seconds=seconds)
dt: datetime = bar.dt + offset
volume: float = 998
raw_index: int = bar._raw_start_index + 1
high: float = 0
low: float = 0
d = bar.high - bar.low
match direction:
case Direction.Up:
i = d * 0.5 if half else randint(int(d * 0.1279), int(d * 0.883))
low: float = bar.low + i
high: float = bar.high + i
case Direction.Down:
i = d * 0.5 if half else randint(int(d * 0.1279), int(d * 0.883))
low: float = bar.low - i
high: float = bar.high - i
case Direction.JumpUp:
i = d * 1.5 if half else randint(int(d * 1.1279), int(d * 1.883))
low: float = bar.low + i
high: float = bar.high + i
case Direction.JumpDown:
i = d * 1.5 if half else randint(int(d * 1.1279), int(d * 1.883))
low: float = bar.low - i
high: float = bar.high - i
case Direction.NextUp:
i = bar.high - bar.low
high: float = bar.high + i
low: float = bar.high
case Direction.NextDown:
i = bar.high - bar.low
high: float = bar.low
low: float = bar.low - i
nb = Bar.creat_new_bar(dt, high, low, Direction.Up if direction.is_up() else Direction.Down, volume, raw_index, bar)
nb.index = bar.index + 1
assert double_relation(bar, nb) is direction, (direction, double_relation(bar, nb))
return nb
@classmethod
def merger(cls, pre: Optional[Self], bar: Self, next_raw_bar: Self) -> Optional[Self]:
if not double_relation(bar, next_raw_bar).is_include():
nb = next_raw_bar.to_new_bar(bar)
nb.index = bar.index + 1
return nb
if next_raw_bar.index - 1 != bar.raw_end_index:
raise ChanException(f"NewBar.merger: 不可追加不连续元素 bar.raw_end_index: {bar.raw_end_index}, next_raw_bar.index: {next_raw_bar.index}.")
direction = Direction.Up
if pre is not None:
if double_relation(pre, bar).is_down():
direction = Direction.Down
func = max
if direction is Direction.Down:
func = min
bar.high = func(bar.high, next_raw_bar.high)
bar.low = func(bar.low, next_raw_bar.low)
bar.open = bar.high if bar.direction is Direction.Down else bar.low
bar.close = bar.low if bar.direction is Direction.Down else bar.high
bar.raw_end_index = next_raw_bar.index
if pre is not None:
bar.index = pre.index + 1
return None
class FenXing:
__slots__ = "index", "left", "mid", "right"
def __init__(self, left: Bar, mid: Bar, right: Bar, index: int = 0):
self.left = left
self.mid = mid
self.right = right
self.index = index
@property
def dt(self) -> datetime.datetime:
return self.mid.dt
@property
def shape(self) -> Shape:
return self.mid.shape
@property
def speck(self) -> float:
return self.mid.speck
@property
def high(self) -> float:
return max(self.left.high, self.mid.high)
@property
def low(self) -> float:
return min(self.left.low, self.mid.low)
def __str__(self):
return f"FenXing({self.shape}, {self.speck}, {self.dt})"
def __repr__(self):
return f"FenXing({self.shape}, {self.speck}, {self.dt})"
def get_shape(self) -> Shape:
shape, (_, _), _ = triple_relation(self.left, self.mid, self.right)
return shape
def get_relations(self) -> (Direction, Direction):
_, (lm, mr), _ = triple_relation(self.left, self.mid, self.right)
return lm, mr
@staticmethod
def get_fenxing(bars: List[Bar], mid: Bar) -> "FenXing":
index = bars.index(mid)
return FenXing(bars[index - 1], mid, bars[index + 1])
@staticmethod
def append(fxs, fx):
if fxs and fxs[-1].shape is fx.shape:
raise ChanException("分型相同无法添加", fxs[-1], fx)
i = 0
if fxs:
i = fxs[-1].index + 1
fx.index = i
fxs.append(fx)
@staticmethod
def pop(fxs, fx):
if fxs and fxs[-1] is not fx:
raise ChanException("分型相同无法删除", fxs[-1], fx)
return fxs.pop()
class Line(metaclass=ABCMeta):
__slots__ = "pre", "next", "index", "__start", "__end", "__stamp", "__elements"
def __init__(self, start: FenXing, end: FenXing, index: int, elements: List | Set, stamp: str = "Line"):
self.index: int = index
self.pre: Optional[Self] = None
self.next: Optional[Self] = None
self.__start = start
self.__end = end
self.__stamp = stamp
self.__elements = elements
def __len__(self):
return len(self.elements)
def __iter__(self):
return iter(self.elements)
def __hash__(self):
return hash(f"{self.stamp} {self.start.mid}")
def __eq__(self, other):
return type(other) is self and self.stamp == other.stamp and self.start == other.start and self.end == other.end and self.elements == other.elements and self.index == other.index
@property
@final
def stamp(self) -> str:
return self.__stamp
@property
@final
def elements(self) -> List[Self]:
return self.__elements
@elements.setter
def elements(self, elements: List[Self]):
self.__elements = elements
@property
def start(self) -> FenXing:
return self.__start
@property
def end(self) -> FenXing:
return self.__end
@end.setter
@final
def end(self, end: FenXing):
self.__end = end
@property
@final
def direction(self) -> Direction:
if self.start.shape is Shape.G and self.end.shape is Shape.D:
return Direction.Down
elif self.start.shape is Shape.D and self.end.shape is Shape.G:
return Direction.Up
else:
raise ChanException(f"{self.stamp}.direction: {self.start.shape}, {self.end.shape}, {self.stamp}")
@property
def high(self) -> float:
if self.direction == Direction.Down:
return self.start.speck
else:
return self.end.speck
@property
def low(self) -> float:
if self.direction == Direction.Up:
return self.start.speck
else:
return self.end.speck
@property
def open(self) -> float:
if self.direction == Direction.Down:
return self.high
else:
return self.low
@property
def close(self) -> float:
if self.direction == Direction.Up:
return self.high
else:
return self.low
def calc_angle(self) -> float:
# 计算线段的角度
dx = self.end.mid.index - self.start.mid.index # self.end.dt.timestamp() - self.start.dt.timestamp() # self.end.dt - self.start.dt # 时间差
dy = self.end.speck - self.start.speck # 价格差
if dx == 0:
return 90.0 if dy > 0 else -90.0
angle = math.degrees(math.atan2(dy, dx))
return angle
def calc_speed(self) -> float:
# 计算线段的速度
dx = self.end.mid.index - self.start.mid.index # self.end.dt - self.start.dt # 时间差
dy = self.end.speck - self.start.speck # 价格差
return dy / dx
def calc_measure(self) -> float:
# 计算线段测度
dx = self.end.mid.index - self.start.mid.index # self.end.dt.timestamp() - self.start.dt.timestamp() # 时间差
dy = abs(self.end.speck - self.start.speck) # 价格差的绝对值
return math.sqrt(dx * dx + dy * dy) # 返回线段的欧几里得长度作为测度
def calc_amplitude(self) -> float:
# 计算线段振幅比例
amplitude = self.end.speck - self.start.speck
return amplitude / self.start.speck if self.start.speck != 0 else 0
def calc_macd(self) -> Dict[str, float]:
result = {"up": 0.0, "down": 0.0, "sum": 0.0}
for element in self.elements:
if hasattr(element, "macd"):
macd = element.macd
key = "up" if macd.bar > 0 else "down"
result[key] = result[key] + macd.bar
else:
macd = element.calc_macd()
result["up"] = result["up"] + macd["up"]
result["down"] = result["down"] + macd["down"]
result["sum"] = abs(result["up"]) + abs(result["down"])
return result
def is_previous(self, line: "Line") -> bool:
return line.end is self.start
def is_next(self, line: "Line") -> bool:
return self.end is line.start
def get_line(self) -> "Line":
return Line(self.start, self.end, self.index, self.elements, self.stamp)
def get_bars(self, bars: list) -> List[Bar]:
return bars[bars.index(self.start.mid) : bars.index(self.end.mid) + 1]
@classmethod
def append(cls, lines: List["Line"], line: "Line"):
if lines and not lines[-1].is_next(line):
raise ChanException("Line.append 不连续", lines[-1], line)
if lines:
line.index = lines[-1].index + 1
line.pre = lines[-1]
if len(lines) > 1:
lines[-2].next = lines[-1]
lines.append(line)
@classmethod
def pop(cls, lines: List["Line"], line: "Line") -> Optional["Line"]:
if not lines:
return
if lines[-1] is line:
drop = lines.pop()
return drop
raise ChanException("Line.pop 弹出数据不在列表中")
@classmethod
@final
def create(cls, obj: List | "Line", stamp: str) -> "Line":
if type(obj) is list:
lines: List["Line"] = obj[:]
return Line(lines[0].start, lines[-1].end, 0, lines, stamp)
line: "Line" = obj
return Line(line.start, line.end, 0, [line], stamp)
class Interval:
__slots__ = "index", "elements", "__high", "__low"
def __init__(self, elements: List, high: float, low: float):
self.elements = elements
self.__high = high
self.__low = low
self.index = 0
def __str__(self):
return f"Interval({self.index}, {len(self)}, {self.__high}, {self.__low})"
def __len__(self):
return len(self.elements)
def __iter__(self):
return iter(self.elements)
@property
def high(self) -> int | float:
return self.__high
@property
def low(self) -> int | float:
return self.__low
@property
def start(self) -> FenXing:
return self.elements[0].start