-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathorder_flow_ticks.py
More file actions
1311 lines (1107 loc) · 59 KB
/
order_flow_ticks.py
File metadata and controls
1311 lines (1107 loc) · 59 KB
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
"""
Order Flow Ticks
=====
Python version of Order Flow Ticks (v2.0) developed for cTrader Trading Platform
Features from Order Flow Ticks + Aggregated (C#):
- Bubbles Chart
- [Delta / Subtract / Change] Sources
- HeatMap Coloring
- Momentum Coloring [fading, positive/negative]
- Ultra Levels [positive/negative]
- Tick Spike Filter
- Spike Levels
- Spike Chart
- HeatMap Coloring
- Positive/Negative Coloring
- Misc
- Custom MAs
- Add Strength Filter to Subtract Delta
Additional Features => that will be implemented to C# version... sometime next year (2026)
- ['sum_delta' / 'delta_bs_sum'] sources to "Spike Filter" and "Bubbles Chart"
- FilterType.[SoftMax_Power / L2Norm / MinMax] filters alternatives to Bubbles Chart
- [L1Norm, SoftMax_Power] filters alternatives to Tick Spike
- FilterRatio.[Fixed / Percentage] to both
Improvements:
- Parallel processing for each bar.
- Numpy arrays, where possible.
- Vectorized operations, almost everything.
Python/C# author:
- srlcarlg
"""
from copy import deepcopy
from multiprocessing import cpu_count, Pool
import numpy as np
import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objects as go
from custom_mas import get_ma, get_stddev
from models_utils.odf_models import *
from models_utils.odf_utils import touches_bubbles, touches_spikes, rolling_percentile, l1norm, l1norm_profile, l2norm, \
power_softmax, power_softmax_profile
class OrderFlowTicks:
def __init__(self, df_ohlc: pd.DataFrame, df_ticks: pd.DataFrame, row_height: float,
strength_filter: StrengthFilter | None = None,
spike_filter: SpikeFilter | None = None,
bubbles_filter: BubblesFilter | None = None,
is_open_time: bool = True,
with_plotly_columns: bool = True):
"""
Create "Order Flow Ticks" from any OHLC chart! \n
(Candles, Renko, Range, Ticks) \n
Backtest version.
Usage
-----
>>> from order_flow_ticks import OrderFlowTicks
>>> odft = OrderFlowTicks(df_ohlc, df_ticks, row_height)
>>> # plot with plotly
>>> odft.plot(mode='delta')
>>> # get df_ohlc with all modes
>>> df = odft.all()
>>> # or get specific mode
>>> odft.normal(), odft.buy_sell(), odft.delta()
>>> # change parameters for filters
>>> from models_utils.odf_models import *
>>> params_strength = StrengthFilter(MAType.Exponential, 5, 1.5, 2)
>>> params_spike = SpikeFilter(SpikeFilterType.MA, FilterRatio.Percentage, MAType.Exponential, ...)
>>> params_bubbles = BubblesFilter(FilterType.MA, FilterRatio.Percentage, MAType.Exponential, ...)
>>> odft = OrderFlowTicks(df_ohlc, df_ticks, row_height, params_strength, params_spike, params_bubbles)
>>> # or get multiples df_ohlc dataframes from different parameters
>>> params_strength = StrengthFilter(MAType.Weighted, 5, 2, 4)
>>> odft.normal(params_strength), odft.buy_sell(params_strength), odft.delta(params_strength)
>>> # delta only
>>> params_spike = SpikeFilter(SpikeFilterType.L1Norm, FilterRatio.Percentage, MAType.Weighted, ...)
>>> params_spike.levels(max_count=2)
>>> params_bubbles = BubblesFilter(FilterType.SoftMax_Power, FilterRatio.Percentage, MAType.Triangular, ...)
>>> params_bubbles.levels(UltraBubblesLevel.High_Low, UltraBubblesBreak.Close_Only, 2)
>>> odft.delta(params_strength, params_spike, params_bubbles)
Parameters
----------
df_ohlc : dataframe
* index/datetime, open, high, low, close
* "datetime": If is not present, the index will be used.
df_ticks : dataframe
* It should have:
* datetime index or 'datetime' column
* 'close' column (ticks price)
row_height : float
Cannot be less than or equal to 0.00000...
is_open_time : bool
Specify if the index/datetime of df_ohlc is the OpenTime or CloseTime of each bar
with_plotly_columns : bool
Return 'plotly_[...]' columns used in self.plot(), if False it will not be possible to plot.
"""
if 'datetime' not in df_ohlc.columns:
df_ohlc["datetime"] = df_ohlc.index
if 'datetime' not in df_ticks.columns:
df_ticks["datetime"] = df_ticks.index
_expected = ['open', 'high', 'low', 'close']
for column in _expected:
if column not in df_ohlc.columns:
raise ValueError(f"'{column}' column from the expected {_expected} doesn't exist!")
self._row_height = row_height
self._ticks_datetime = df_ticks['datetime'].to_numpy()
self._ticks_close = df_ticks['close'].to_numpy()
self._strength_filter = strength_filter if isinstance(strength_filter, StrengthFilter) else StrengthFilter()
self._spike_filter = spike_filter if isinstance(spike_filter, SpikeFilter) else SpikeFilter()
self._bubbles_filter = bubbles_filter if isinstance(bubbles_filter, BubblesFilter) else BubblesFilter()
self._is_open_time = is_open_time
self._with_plotly_columns = with_plotly_columns
if is_open_time:
df_ohlc['end_time'] = df_ohlc['datetime'].shift(-1)
else:
df_ohlc['start_time'] = df_ohlc['datetime'].shift(1)
# drop NaN from .shift() operation
df_ohlc.dropna(inplace=True)
# For plotly
if with_plotly_columns:
df_ohlc['plotly_int_index'] = range(len(df_ohlc))
def parallel_process_dataframes(df):
num_processes = cpu_count()
with Pool(processes=num_processes) as pool:
results = pool.map(self._create, df.to_dict(orient='records'))
return results
profiles_each_bar = parallel_process_dataframes(df_ohlc)
normal_bars = (lst[0] for lst in profiles_each_bar)
buy_sell_bars = (lst[1] for lst in profiles_each_bar)
delta_bars = (lst[2] for lst in profiles_each_bar)
normal_df = pd.DataFrame.from_records(normal_bars)
buy_sell_df = pd.DataFrame.from_records(buy_sell_bars)
delta_df = pd.DataFrame.from_records(delta_bars)
for _df in [normal_df, buy_sell_df, delta_df]:
_df.index = _df['datetime']
_df.drop(columns=['datetime'], inplace=True)
delta_df['delta_change'] = delta_df['delta'] + delta_df['delta'].shift(1)
# fill NaN from .shift() operation
delta_df['delta_change'].fillna(delta_df['delta'], inplace=True)
self._df_ohlcv = df_ohlc
self._normal_df = normal_df
self._buy_sell_df = buy_sell_df
self._delta_df = delta_df
# creating new columns by vectorized operations to [spike, bubbles]-sources
from warnings import simplefilter
simplefilter(action="ignore", category=pd.errors.PerformanceWarning)
def normal(self, strength_filter: StrengthFilter | None = None):
"""
Get df_ohlc with 'Normal' mode.
"""
normal_df = self._normal_df.copy()
self._strength(normal_df, "normal_value", strength_filter)
df = pd.concat([self._df_ohlcv, normal_df], axis=1)
df.index = df['datetime']
return df
def buy_sell(self, strength_filter: StrengthFilter | None = None):
"""
Get df_ohlc with 'Buy_Sell' mode.
"""
buy_sell_df = self._buy_sell_df.copy()
self._strength(buy_sell_df, "bs_sum", strength_filter)
self._strength(buy_sell_df, "bs_subtract", strength_filter)
df = pd.concat([self._df_ohlcv, buy_sell_df], axis=1)
df.index = df['datetime']
return df
def delta(self, strength_filter: StrengthFilter | None = None, spike_filter: SpikeFilter | None = None,
bubbles_filter: BubblesFilter | None = None,):
"""
Get df_ohlc with 'Delta' mode.
"""
delta_df = self._delta_df.copy()
self._strength(delta_df, "delta", strength_filter)
self._strength(delta_df, "subtract_delta", strength_filter)
self._tick_spike(delta_df, spike_filter)
self._bubbles_chart(delta_df, self._df_ohlcv, bubbles_filter)
df = pd.concat([self._df_ohlcv, delta_df], axis=1)
df.index = df['datetime']
self._spike_levels_count(df, spike_filter)
self._bubbles_levels_count(df, bubbles_filter)
return df
def all(self):
"""
Get df_ohlc with all modes (normal, buy_sell, delta)
"""
df = pd.concat([self._df_ohlcv, self._normal_df, self._buy_sell_df, self._delta_df], axis=1)
# Drop duplicated columns (we have 3 profile_prices, keep 1)
df = df.loc[: , ~df.columns.duplicated()]
df.index = df['datetime']
return df
def plot(self, iloc_value: int | list = 15, mode: str = 'delta', view: str = 'profile',
spike_plot: SpikePlot | None = None,
chart: str = 'ohlc', renderer: str = 'default',
width: int = 1200, height: int = 800):
"""
Parameters
----------
df: pd.DataFrame
If None, the dataframe from [normal, buy_sell, delta] methods of the current ODF instance will be used
iloc_value : int
First nº rows to be plotted
mode : str
'normal', 'buy_sell', 'delta'
view : str
'divided' or 'profile'
spike_plot : SpikePlot
Spike Filter parameters
chart : str
'ohlc' or 'candle'
renderer : str
* Change 'plotply' renderer if anything goes wrong, use:
* **static**: svg, png and jpeg
* **interactive**: notebook, plotly_mimetype
* **html_interactive**: browser, iframe
* or visit plotply.py renderers wiki
width : int
for static renderer
height : int
for static renderer
"""
_profiles = ['normal', 'buy_sell', 'delta']
_views = ['profile', 'divided']
_charts = ['candle', 'ohlc']
input_values = [mode, view, chart]
input_validation = [_profiles, _views, _charts]
for value, validation in zip(input_values, input_validation):
if value not in validation:
raise ValueError(f"Only {validation} options are valid.")
k = spike_plot if isinstance(spike_plot, SpikePlot) else SpikePlot()
df = self.normal() if mode == 'normal' else \
self.buy_sell() if mode == 'buy_sell' else \
self.delta()
if type(iloc_value) is int:
df = df.iloc[:iloc_value]
else:
df = df.iloc[iloc_value[0]:iloc_value[1]]
df[f'plotly_int_index'] = range(len(df))
df_len = len(df)
prefix = 'plotly'
fig = make_subplots(rows=1, cols=1, shared_xaxes=True, vertical_spacing=0.0)
if chart == 'ohlc':
fig.add_trace(go.Ohlc(x=df[f'{prefix}_int_index'],
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close'], opacity=0.5), row=1, col=1)
else:
fig.add_trace(go.Candlestick(x=df[f'{prefix}_int_index'],
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close'], opacity=0.3), row=1, col=1)
# TODO np.arrays
# Histograms
# 'base=index' makes the trick of divided/profiles views
# Profile view needs (max_side * 2 in self._create) because
# we're moving the initial value to the left max_side (-0.245 or 0.3)
for index in range(df_len):
step = 0.245 if chart == 'candle' else 0.3
base_index = index if view == 'divided' else index - step
y_prices = df['profile_prices'].iat[index]
len_prices = len(y_prices)
if mode == 'normal':
x_column = f'{prefix}_{mode}_{chart}_histogram'
fig.add_trace(
go.Bar(y=y_prices, x=df[x_column].iat[index],
orientation='h', base=index - step,
marker=dict(
color='#00BFFF',
opacity = 0.4
)), row=1, col=1)
else:
# Spike Chart
if k.spike_chart and mode == 'delta':
spike_prefix = f'{prefix}_spike_chart_{k.spike_source}'
coloring_column = f'{spike_prefix}_{k.spike_chart_coloring}_color'
base_index = index - 0.4
fig.add_trace(
go.Bar(y=y_prices, x=[0.8 for _ in range(len_prices - 1)],
orientation='h', base=base_index,
marker=dict(
color=df[coloring_column].iat[index],
opacity=0.4
)), row=1, col=1)
else:
chart_suffix = f'{chart}_histogram' \
if view == 'divided' else \
f'profile_{chart}_histogram'
# Buy
buy_middle = 'delta_buy' if mode == 'delta' else 'buy'
x_buy_column = f'{prefix}_{buy_middle}_{chart_suffix}'
color = 'deepskyblue'
if mode == 'delta':
color = df[f'{prefix}_spike_{k.spike_source}_buy_color'].iat[index] if k.spike else 'deepskyblue'
fig.add_trace(
go.Bar(y=y_prices, x=df[x_buy_column].iat[index], marker=dict(
color=color,
opacity=0.3 if view == 'divided' else 0.4
),
orientation='h', base=base_index), row=1, col=1)
# Sell
sell_middle = 'delta_sell' if mode == 'delta' else 'sell'
x_sell_column = f'{prefix}_{sell_middle}_{chart_suffix}'
color = 'crimson'
if mode == 'delta':
color = df[f'{prefix}_spike_{k.spike_source}_sell_color'].iat[index] if k.spike else 'crimson'
fig.add_trace(
go.Bar(y=y_prices, x=df[x_sell_column].iat[index], marker=dict(
color=color,
opacity=0.3
),
orientation='h', base=base_index), row=1, col=1)
# Spike Levels
if k.spike_levels and mode == 'delta':
lvl_prefix = 'spike_levels'
levels = df[f'{lvl_prefix}_price_{k.spike_source}'].iat[index]
len_lvl = len(levels)
if len_lvl == 0:
continue
break_at = abs(index - df[f'{lvl_prefix}_break_at_{k.spike_source}'].iat[index])
base_index = index + step
# remove the y2 of all levels
# the Y size is automatically set by plotly
levels = np.delete(levels, 1, axis=1)
levels_coloring = df[f'{prefix}_{lvl_prefix}_{k.spike_source}_{k.spike_levels_coloring}_color'].iat[index]
# 2d array to 1d array is not suitable due to:
# plotly automatic space between y values
for idx in range(len_lvl):
fig.add_trace(
go.Bar(y=levels[idx], x=[break_at], marker=dict(
color=levels_coloring[idx],
opacity=0.3,
),
orientation='h', base=base_index), row=1, col=1)
# Numbers
# Some beautiful colors from plotply - colorscales wiki
# But everything will be transparent :D
color = [[0.0, "rgba(165,0,38, 0.0)"],
[0.1, "rgba(215,48,39, 0.0)"],
[0.2, "rgba(244,109,67, 0.0)"],
[0.3, "rgba(253,174,97, 0.0)"],
[0.4, "rgba(254,224,144, 0.0)"],
[0.5, "rgba(224,243,248, 0.0)"],
[0.6, "rgba(171,217,233, 0.0)"],
[0.7, "rgba(116,173,209, 0.0)"],
[0.8, "rgba(69,117,180, 0.0)"],
[1.0, "rgba(49,54,149, 0.0)"]]
for index in range(df_len):
y_prices = df['profile_prices'].iat[index]
if mode in ['normal', 'delta']:
chart_suffix = f'{chart}_numbers' if mode != 'delta' else \
f'profile_{chart}_numbers' if view == 'profile' else \
f'{chart}_numbers'
x_column = f'{prefix}_{mode}_{chart_suffix}'
z_text = df[f'{mode}_profile'].iat[index]
# workaround to display without recalculating everything
x_values = df[x_column].iat[index] if type(iloc_value) is int else \
[v - iloc_value[0] for v in df[x_column].iat[index]]
fig.add_trace(
go.Heatmap(
x=x_values,
y=y_prices,
z=z_text,
text=z_text,
colorscale=color,
showscale=False, # remove numbers from show_legend=False column
texttemplate="%{text}",
textfont={
"size": 11,
"color": 'black',
"family": "Courier New"},
), row=1, col=1)
if mode == 'delta' and k.spike_strength:
z_text = df[f'spike_profile_{k.spike_source}'].iat[index]
x_axis = [arr + 0.5 for arr in x_values]
fig.add_trace(
go.Heatmap(
x=x_axis,
y=y_prices,
z=z_text,
text=z_text,
colorscale=color,
showscale=False, # remove numbers from show_legend=False column
# texttemplate="%{text}",
texttemplate="<= %{text}",
textfont={
"size": 11,
"color": 'black',
"family": "Courier New"},
), row=1, col=1)
else:
chart_suffix = f'profile_{chart}_numbers' if view == 'profile' else f'{chart}_numbers'
# Buy
x_buy_column = f'{prefix}_buy_{chart_suffix}'
z_text = df['buy_profile'].iat[index]
x_buy_values = df[x_buy_column].iat[index] if type(iloc_value) is int else \
[v - iloc_value[0] for v in df[x_buy_column].iat[index]]
fig.add_trace(
go.Heatmap(
x=x_buy_values,
y=y_prices,
z=z_text,
text=z_text,
colorscale=color,
showscale=False, # remove numbers from show_legend=False column
texttemplate="%{text}",
textfont={
"size": 11,
"color": 'black',
"family": "Courier New"},
), row=1, col=1)
# Sell
x_sell_column = f'{prefix}_sell_{chart_suffix}'
z_text = df['sell_profile'].iat[index]
x_sell_values = df[x_sell_column].iat[index] if type(iloc_value) is int else \
[v - iloc_value[0] for v in df[x_sell_column].iat[index]]
fig.add_trace(
go.Heatmap(
x=x_sell_values,
y=y_prices,
z=z_text,
text=z_text,
colorscale=color,
showscale=False, # remove numbers from show_legend=False column
texttemplate="%{text}",
textfont={
"size": 11,
"color": 'black',
"family": "Courier New"},
), row=1, col=1)
# Delta Change = above the candle
if mode == 'delta':
df['high_y'] = df['high'] + (self._row_height * 1)
fig.add_trace(
go.Scatter(
x=df['plotly_int_index'], y=df['high_y'], text=df['delta_change'],
textposition='middle center',
textfont=dict(size=11, color='blue'),
mode='text'
), row=1, col=1)
# Mode value = below the candle
df['low_y'] = df['low'] - (self._row_height * 2)
column_below = 'normal_value' if mode == 'normal' else \
'bs_subtract' if mode == 'buy_sell' else \
'delta'
fig.add_trace(
go.Scatter(
x=df['plotly_int_index'], y=df['low_y'], text=df[column_below], textposition='middle center',
textfont=dict(size=11, color='green'),
mode='text'
), row=1, col=1)
spike_info = ""
if mode == 'delta' and (k.spike_chart or k.spike):
mode_column = {
'delta': 'delta',
'sum': 'sum_delta',
'bs_sum': 'delta_bs_sum',
}
f = self._spike_filter
ratio_text = f'/ {f.p_period} period' if f.filter_ratio == FilterRatio.Percentage else ""
spike_info = f"Source: {mode_column[k.spike_source]} <br>" \
f"Filter: {f.filter_type.name} / {f.ma_period} period <br>" \
f"Ratio: {f.filter_ratio.name} {ratio_text}"
fig.update_layout(
title=f'Order Flow Ticks: {mode}/{view} <br>' + spike_info,
height=800,
# IMPORTANT!
# Allows bars(histograms) to diverge from the center (0)
# from plotply horizontal bars chart wiki
barmode='relative', # or overlay
xaxis_rangeslider_visible=False
)
fig.update_traces(
showlegend=False
)
if renderer != 'default':
if renderer in ['svg', 'png', 'jpeg']:
fig.show(renderer=renderer, width=width, height=height)
else:
fig.show(renderer=renderer)
else:
fig.show()
def plot_bubbles(self, iloc_value: int | list = 15, delta_source: str = 'delta', coloring: str = 'heatmap',
strength: bool = False, levels: bool = False, levels_coloring: str = 'plusminus',
renderer: str = 'default',
width: int = 1200, height: int = 800):
_sources = ['delta', 'subtract', 'sum', 'change', 'bs_sum']
if delta_source not in _sources:
raise ValueError(f"Only {_sources} options are valid.")
_colors = ['heatmap', 'fading', 'plusminus']
if coloring not in _colors:
raise ValueError(f"Only {_colors} options are valid.")
df = self.delta()
if type(iloc_value) is int:
df = df.iloc[:iloc_value]
else:
df = df.iloc[iloc_value[0]:iloc_value[1]]
df[f'plotly_int_index'] = range(len(df))
fig = make_subplots(rows=1, cols=1, shared_xaxes=True, vertical_spacing=0.0)
prefix = 'plotly'
x_values = df[f'{prefix}_int_index']
y_values = df['close']
# close line
fig.add_trace(go.Scatter(x=x_values,
y=y_values,
mode='lines',
opacity=1), row=1, col=1)
# delta value
mode_column = {
'delta' : 'delta',
'subtract' : 'subtract_delta',
'sum': 'sum_delta',
'change' : 'delta_change',
'bs_sum': 'delta_bs_sum',
}
name = mode_column[delta_source]
fig.add_trace(go.Scatter(x=x_values,
y=y_values,
mode='text',
text=df[name],
textfont=dict(size=11, color='black'),
opacity=1), row=1, col=1)
# strength value
if strength:
df['close_y'] = y_values - (self._row_height / 4)
fig.add_trace(go.Scatter(x=x_values,
y=df['close_y'],
mode='text',
text=df[f'bubbles_{delta_source}_strength'],
textposition='bottom center',
textfont=dict(size=9, color='blue'),
opacity=1), row=1, col=1)
# bubbles
bubbles_prefix = f'{prefix}_bubbles'
fig.add_trace(go.Scatter(x=x_values,
y=y_values,
mode='markers',
marker=dict(
color=df[f'{bubbles_prefix}_{delta_source}_{coloring}_color'],
size=df[f'{bubbles_prefix}_{delta_source}_size'],
),
opacity=0.5), row=1, col=1)
# ultra levels
if levels:
lvl_prefix = f'bubbles_levels_{delta_source}'
for index in range(len(df)):
# TODO np.arrays
level = df[f'{lvl_prefix}_high_to_low'].iat[index]
if level == 0:
continue
break_at = abs(index - df[f'{lvl_prefix}_break_at'].iat[index])
lvl_color = df[f'{bubbles_prefix}_{delta_source}_plusminus_color'].iat[index] \
if levels_coloring == 'plusminus' else levels_coloring
for i in range(2):
fig.add_trace(
go.Bar(y=[level[i]], x=[break_at], marker=dict(
color=lvl_color,
opacity=0.3
),
orientation='h', base=index), row=1, col=1)
b = self._bubbles_filter
ratio_text = f'/ {b.p_period} period' if b.filter_ratio == FilterRatio.Percentage else ""
fig.update_layout(
title=f"Order Flow Ticks: {mode_column[delta_source]} <br>"
f"Filter: {b.filter_type.name} / {b.ma_period} period <br>"
f"Ratio: {b.filter_ratio.name} {ratio_text}",
height=800,
barmode='relative', # or overlay
xaxis_rangeslider_visible=False
)
fig.update_traces(
showlegend=False
)
if renderer != 'default':
if renderer in ['svg', 'png', 'jpeg']:
fig.show(renderer=renderer, width=width, height=height)
else:
fig.show(renderer=renderer)
else:
fig.show()
def _strength(self, df, column_name: str, s_params: StrengthFilter | None = None):
s = s_params if isinstance(s_params, StrengthFilter) else self._strength_filter
df[f'abs_{column_name}'] = abs(df[column_name])
df['strength_ma'] = get_ma(df[f'abs_{column_name}'].to_numpy(), s.ma_type, s.ma_period)
df[f'strength_{column_name}_filter'] = df[column_name] / df[f'strength_ma']
d = df[f'strength_{column_name}_filter']
df[f'strength_{column_name}'] = np.where(d >= s.ratio_2, 2,
np.where(d >= s.ratio_1, 1, 0))
df.drop(columns=[f'abs_{column_name}', f'strength_ma'], inplace=True)
return df
def _tick_spike(self, df: pd.DataFrame, t_params: SpikeFilter | None = None):
t = t_params if isinstance(t_params, SpikeFilter) else self._spike_filter
_delta_name = ['delta', 'sum', 'bs_sum']
_delta_columns = ['delta', 'sum_delta', 'delta_bs_sum']
for name, column_name in zip(_delta_name, _delta_columns):
df[f'{name}_abs'] = abs(df[column_name])
b_prefix = f'spike_{name}'
match t.filter_type:
case SpikeFilterType.MA | SpikeFilterType.StdDev:
df[f'{b_prefix}_ma'] = get_ma(df[f'{name}_abs'].to_numpy(), t.ma_type, t.ma_period)
df[f'{b_prefix}_filter'] = df[f'{b_prefix}_ma']
if t.filter_type == SpikeFilterType.StdDev:
df[f'{b_prefix}_stddev'] = get_stddev(df[f'{name}_abs'].to_numpy(), df[f'{b_prefix}_ma'], t.ma_period)
df[f'{b_prefix}_filter'] = df[f'{b_prefix}_stddev']
df.drop(columns=[f'{b_prefix}_stddev'], inplace=True)
df.drop(columns=[f'{b_prefix}_ma'], inplace=True)
case SpikeFilterType.L1Norm:
df[f'{b_prefix}_filter'] = df[f'{name}_abs'].rolling(t.ma_period).apply(l1norm, raw=True)
df[f'{b_prefix}_filter'] = df[f'{b_prefix}_filter'] * 100
case SpikeFilterType.SoftMax_Power:
df[f'{b_prefix}_filter'] = df[f'{name}_abs'].rolling(t.ma_period).apply(power_softmax, raw=True)
df[f'{b_prefix}_filter'] = df[f'{b_prefix}_filter'] * 100
# The code below simulates the "Segments loop" of OrderFlow C# method
# vectorized for speeed hehehe
abs_name = 'delta_profile_abs'
df[abs_name] = [abs(arr) for arr in df['delta_profile']]
if t.filter_type == SpikeFilterType.L1Norm:
df[abs_name] = [l1norm_profile(arr) for arr in df[abs_name]]
df[abs_name] = [np.round(arr * 100, 2) for arr in df[abs_name]]
elif t.filter_type == SpikeFilterType.SoftMax_Power:
df[abs_name] = [power_softmax_profile(arr) for arr in df[abs_name]]
df[abs_name] = [np.round(arr * 100, 2) for arr in df[abs_name]]
# The overall output seems to be the "same" for both methods, after the divide operation below.
# divide each row-profile by normalized delta
profile_name = f'spike_profile_{name}'
df[profile_name] = df[abs_name] / df[f'{b_prefix}_filter']
df[profile_name] = [np.round(arr, 2) for arr in df[profile_name]]
if t.filter_ratio == FilterRatio.Percentage:
"""
simple math, normalize the values to 0~1, just:
- calculate the sum of all elements absolute value
- divide each element by the sum
- aka L1 normalization
added MA to get the values >= 100%, as well as, percentile-like behavior of bubbles chart.
"""
pct_name = 'pct_filter'
df[pct_name] = [sum(abs(arr)) for arr in df[profile_name]]
df[pct_name] = df[pct_name] = get_ma(df[pct_name].to_numpy(), t.ma_type, t.p_period)
df[profile_name] = df[profile_name] / df[pct_name]
df[profile_name] = [np.round(arr * 100, 1) for arr in df[profile_name]]
# Spike Chart => heatmap
df[f'spike_chart_{name}'] = [np.where(arr < t.lowest, 0,
np.where(arr < t.low, 1,
np.where(arr < t.average, 2,
np.where(arr < t.high, 3,
np.where(arr >= t.ultra, 4, 4))))) for arr in df[profile_name]] \
if t.filter_ratio == FilterRatio.Fixed else \
[np.where(arr < t.lowest_pct, 0,
np.where(arr < t.low_pct, 1,
np.where(arr < t.average_pct, 2,
np.where(arr < t.high_pct, 3,
np.where(arr >= t.ultra_pct, 4, 4))))) for arr in df[profile_name]]
df[f'spike_plusminus_{name}'] = [arr > 0 for arr in df['delta_profile']]
# df[f'spike_plusminus_{name}'] = [arr.astype(int) for arr in df['spike_plusminus']]
# Spike Levels
"""
The actual spike prices.
Some trick => group the segments by two like:
[1, 2, 3, 4] => [(1,2), (2,3), (3,4)]
to match with delta_profile length.
"""
# [ [y1, y2], [y1, y2], [y1, y2], ...]
df['price_util'] = [np.array([arr[:-1], arr[1:]]).T for arr in df['profile_prices']]
# Since they have the same length, filter the 'spike_chart' values (>= average)
# [ True, False, False, ...]
df['mask_util'] = [arr >= 2 for arr in df[f'spike_chart_{name}']]
# Then filter the segments 2d array using the boolean 1d array
# [ [y1, y2], ...]
df[f'spike_levels_price_{name}'] = [arr[mask] for arr, mask in zip(df['price_util'], df['mask_util'])]
# get its strength
# [ 4, ...]
df[f'spike_levels_strength_{name}'] = [arr[mask] for arr, mask in zip(df[f'spike_chart_{name}'], df['mask_util'])]
# and its sign too
# [ True, ...]
df[f'spike_levels_sign_is_plus_{name}'] = [arr[mask] > 0 for arr, mask in
zip(df[f'spike_plusminus_{name}'], df['mask_util'])]
if not self._with_plotly_columns:
df.drop(columns=[f'{name}_abs', 'price_util', 'mask_util'], inplace=True)
continue
prefix = 'plotly_spike'
# Spike
# Instead of creating a new scatter for each spike, just color the histograms
df[f'{prefix}_{name}_buy_color'] = [np.where(arr, 'gold', 'deepskyblue') for arr in df['mask_util']]
df[f'{prefix}_{name}_sell_color'] = [np.where(arr, 'gold', 'crimson') for arr in df['mask_util']]
# Spike Chart
prefix_chart = f'{prefix}_chart_{name}'
df[f'{prefix_chart}_heatmap_color'] = [np.where(arr == 0, 'rgb(0,255,255)',
np.where(arr == 1, '#FFFFFF',
np.where(arr == 2, 'rgb(255,255,0)',
np.where(arr == 3, 'rgb(255,192,0)',
np.where(arr == 4, 'rgb(255,0,0)', 'rgb(255,0,0)'))))) \
for arr in df[f'spike_chart_{name}']]
is_plus = [arr.astype(int) for arr in df[f'spike_plusminus_{name}']]
df[f'{prefix_chart}_plusminus_color'] = [np.where(arr == 1, 'deepskyblue', 'crimson') for arr in is_plus]
# Spike Levels
prefix_lvl = f'{prefix}_levels_{name}'
df[f'{prefix_lvl}_heatmap_color'] = [np.where(arr == 0, 'rgb(0,255,255)',
np.where(arr == 1, '#FFFFFF',
np.where(arr == 2, 'rgb(255,255,0)',
np.where(arr == 3, 'rgb(255,192,0)',
np.where(arr == 4, 'rgb(255,0,0)', 'rgb(255,0,0)'))))) \
for arr in df[f'spike_levels_strength_{name}']]
is_plus = [arr.astype(int) for arr in df[f'spike_levels_sign_is_plus_{name}']]
df[f'{prefix_lvl}_plusminus_color'] = [np.where(arr == 1, 'deepskyblue', 'crimson') for arr in is_plus]
df.drop(columns=[f'{name}_abs', 'price_util', 'mask_util'], inplace=True)
return df
def _bubbles_chart(self, df: pd.DataFrame, df_ohlc: pd.DataFrame, b_params: BubblesFilter | None = None):
b = b_params if isinstance(b_params, BubblesFilter) else self._bubbles_filter
# utils for vectorized operations
df['is_up_util'] = df_ohlc['close'] > df_ohlc['open']
df['is_up_util'] = df['is_up_util'].astype(int)
df['y1_util'] = np.where(df['is_up_util'] > 0, df_ohlc['high'], df_ohlc['low'])
df['y2_util'] = np.where(df['is_up_util'] > 0, df_ohlc['low'], df_ohlc['high'])
df['close_util'] = [(y1, y2) for y1, y2 in zip(df['y1_util'], df_ohlc['close'])]
df['open_util'] = [(y1, y2) for y1, y2 in zip(df['y2_util'], df_ohlc['open'])]
df['hl_util'] = [(y1, y2) for y1, y2 in zip(df_ohlc['low'], df_ohlc['high'])]
_delta_name = ['delta', 'subtract', 'sum', 'change', 'bs_sum']
_delta_columns = ['delta', 'subtract_delta', 'sum_delta', 'delta_change', 'delta_bs_sum']
for name, column_name in zip(_delta_name, _delta_columns):
df[f'{name}_abs'] = abs(df[column_name])
b_prefix = f'bubbles_{name}'
match b.filter_type:
case FilterType.MA | FilterType.StdDev | FilterType.Both:
df[f'{b_prefix}_ma'] = get_ma(df[f'{name}_abs'].to_numpy(), b.ma_type, b.ma_period)
df[f'{b_prefix}_filter'] = df[f'{b_prefix}_ma']
if b.filter_type in [FilterType.StdDev, FilterType.Both]:
df[f'{b_prefix}_stddev'] = get_stddev(df[f'{name}_abs'].to_numpy(), df[f'{b_prefix}_ma'], b.ma_period)
if b.filter_type == FilterType.Both:
df[f'{b_prefix}_filter'] = (df[f'{name}_abs'] - df[f'{b_prefix}_ma']) / df[f'{b_prefix}_stddev']
else:
df[f'{b_prefix}_filter'] = df[f'{b_prefix}_stddev']
df.drop(columns=[f'{b_prefix}_stddev'], inplace=True)
df.drop(columns=[f'{b_prefix}_ma'], inplace=True)
case FilterType.SoftMax_Power:
df[f'{b_prefix}_filter'] = df[f'{name}_abs'].rolling(b.ma_period).apply(power_softmax, raw=True)
case FilterType.L2Norm:
df[f'{b_prefix}_filter'] = df[f'{name}_abs'].rolling(b.ma_period).apply(l2norm, raw=True)
case FilterType.MinMax:
series = df[f'{name}_abs']
roll_min = series.rolling(b.ma_period).min()
roll_max = series.rolling(b.ma_period).max()
df[f'{b_prefix}_filter'] = (series - roll_min) / (roll_max - roll_min)
# The code below simulates the "Segments loop" of OrderFlow C# method
# vectorized for speeed hehehe
# divide total x-delta by normalized x-delta (ma/stddev)
if b.filter_type in [FilterType.MA, FilterType.StdDev]:
df[f'{b_prefix}_strength'] = df[f'{name}_abs'] / df[f'{b_prefix}_filter']
else:
df[f'{b_prefix}_strength'] = df[f'{b_prefix}_filter']
df[f'{b_prefix}_strength'] = round(df[f'{b_prefix}_strength'], 2)
if b.filter_ratio == FilterRatio.Percentage:
pctile = df[f'{b_prefix}_strength'].rolling(b.p_period).apply(rolling_percentile, raw=True)
df[f'{b_prefix}_strength'] = round(pctile, 1)
# heatmap + bubbles size
d = df[f'{b_prefix}_strength']
df[f'{b_prefix}_chart'] = np.where(d < b.lowest, 0,
np.where(d < b.low, 1,
np.where(d < b.average, 2,
np.where(d < b.high, 3,
np.where(d >= b.ultra, 4, 4))))) \
if b.filter_ratio == FilterRatio.Fixed else \
np.where(d < b.lowest_pct, 0,
np.where(d < b.low_pct, 1,
np.where(d < b.average_pct, 2,
np.where(d < b.high_pct, 3,
np.where(d >= b.ultra_pct, 4, 4)))))
# fading
df[f'{b_prefix}_fading'] = df[column_name] < df[column_name].shift(1)
# positive/negative
df[f'{b_prefix}_plusminus'] = df[column_name] > 0
# ultra levels
lvl_prefix = f'bubbles_levels_{name}'
df[f'{lvl_prefix}_is_ultra'] = df[f'{b_prefix}_chart'] == 4
df[f'{lvl_prefix}_is_ultra'] = df[f'{lvl_prefix}_is_ultra'].astype(int)
# y1, y2
d = df[f'{lvl_prefix}_is_ultra']
df[f'{lvl_prefix}_high_to_low'] = np.where(d > 0, df['hl_util'], 0)
df[f'{lvl_prefix}_high_or_low_close'] = np.where(d > 0, df['close_util'], 0)
df[f'{lvl_prefix}_high_or_low_open'] = np.where(d > 0, df['open_util'], 0)
df.drop(columns=[f'{name}_abs'], inplace=True)
if not self._with_plotly_columns:
continue
plt_prefix = f'plotly_{b_prefix}'
d = df[f'{b_prefix}_chart']
df[f'{plt_prefix}_size'] = np.where(d == 0, 20,
np.where(d == 1, 35,
np.where(d == 2, 50,
np.where(d == 3, 65,
np.where(d == 4, 80, 80)))))
df[f'{plt_prefix}_heatmap_color'] = np.where(d == 0, 'rgb(0,255,255)',
np.where(d == 1, '#FFFFFF',
np.where(d == 2, 'rgb(255,255,0)',
np.where(d == 3, 'rgb(255,192,0)',
np.where(d == 4, 'rgb(255,0,0)', 'rgb(255,0,0)')))))
d = df[f'{b_prefix}_fading'].astype(int)
df[f'{plt_prefix}_fading_color'] = np.where(d == 1, 'crimson', 'deepskyblue')
d = df[f'{b_prefix}_plusminus'].astype(int)
df[f'{plt_prefix}_plusminus_color'] = np.where(d == 0, 'crimson', 'deepskyblue')
df.drop(columns=['is_up_util', 'y1_util', 'y2_util', 'open_util', 'hl_util', 'close_util'], inplace=True)
def _spike_levels_count(self, df: pd.DataFrame, t_params: SpikeFilter | None = None):
t = t_params if isinstance(t_params, SpikeFilter) else self._spike_filter
_delta_name = ['delta', 'sum', 'bs_sum']
for name in _delta_name:
# TODO np.arrays
df[f'spike_levels_break_at_{name}'] = np.NaN
current_levels = []
for i in range(len(df)):
o = df['open'].iat[i]
h = df['high'].iat[i]
l = df['low'].iat[i]
c = df['close'].iat[i]
price_levels = df[f'spike_levels_price_{name}'].iat[i]
# check touches for all active levels
for level in current_levels:
if not level.is_active:
continue
if touches_spikes(o, h, l, c, level.top, level.bottom):
level.touch_count += 1
if level.touch_count >= t.max_count:
level.is_active = False
df[f'spike_levels_break_at_{name}'].iat[level.level_idx] = i
if len(price_levels) != 0:
# at least 1 level = 2D np.array
# [ [y1, y2], [y1, y2], etc...]
for k in range(len(price_levels)):
y1 = price_levels[k][0]
y2 = price_levels[k][1]
top = max(y1, y2)
bottom = min(y1, y2)
info = LevelInfo(top, bottom, i)
current_levels.append(info)
return df
def _bubbles_levels_count(self, df: pd.DataFrame, b_params: BubblesFilter | None = None):
b = b_params if isinstance(b_params, BubblesFilter) else self._bubbles_filter
_delta_name = ['delta', 'subtract', 'change']
df_len = len(df)
for name in _delta_name:
# TODO np.arrays
lvl_prefix = f'bubbles_levels_{name}'
df[f'{lvl_prefix}_break_at'] = np.NaN
current_levels = []
for i in range(df_len):
o = df['open'].iat[i]
h = df['high'].iat[i]
l = df['low'].iat[i]
c = df['close'].iat[i]
match b.level_size:
case UltraBubblesLevel.HighOrLow_Open:
price_level = df[f'{lvl_prefix}_high_or_low_open'].iat[i]
case UltraBubblesLevel.HighOrLow_Close:
price_level = df[f'{lvl_prefix}_high_or_low_close'].iat[i]
case _:
price_level = df[f'{lvl_prefix}_high_to_low'].iat[i]
# check touches for all active levels
for level in current_levels:
if not level.is_active:
continue