/
Ehlers.cs
1298 lines (1093 loc) · 56.5 KB
/
Ehlers.cs
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
//==============================================================================
// Project: TuringTrader, simulator core v2
// Name: Ehlers
// Description: Indicators from John F. Ehlers
// History: 2023iv01, FUB, created
//------------------------------------------------------------------------------
// Copyright: (c) 2011-2023, Bertram Enterprises LLC dba TuringTrader.
// https://www.turingtrader.org
// License: This file is part of TuringTrader, an open-source backtesting
// engine/ trading simulator.
// TuringTrader is free software: you can redistribute it and/or
// modify it under the terms of the GNU Affero General Public
// License as published by the Free Software Foundation, either
// version 3 of the License, or (at your option) any later version.
// TuringTrader is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public
// License along with TuringTrader. If not, see
// https://www.gnu.org/licenses/agpl-3.0.
//==============================================================================
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using static TuringTrader.SimulatorV2.Indicators.Trend;
namespace TuringTrader.SimulatorV2.Indicators
{
/// <summary>
/// Collection of indicators from John F. Ehlers's
/// book 'Rocket Science for Traders.'
/// </summary>
public static class Ehlers_RocketScienceForTraders
{
#region Detrend
/// <summary>
/// Detrend input signal with a Hilbert Transformer, according
/// to John F. Ehlers's book 'Rocket Science for Traders'.
/// Note that the detrender's frequency response is not flat.
/// To remedy this, Ehlers typically corrects the output by a
/// factor of 0.075 * Period + 0.54.
/// </summary>
/// <param name="series"></param>
/// <returns></returns>
public static TimeSeriesFloat Detrend(this TimeSeriesFloat series)
{
var name = string.Format("{0}.Detrend", series.Name);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var src = series.Data;
var dst = new List<BarType<double>>();
var lookback = new LookbackGroup();
var input = lookback.NewLookback(0.0);
for (int idx = 0; idx < src.Count; idx++)
{
lookback.Advance();
input.Value = src[idx].Value;
var detrender = (0.0962 * input + 0.5769 * input[2]
- 0.5769 * input[4] - 0.0962 * input[6])
* (0.075 * input[1] + 0.54);
dst.Add(new BarType<double>(
src[idx].Date, detrender));
}
return dst;
}));
return new TimeSeriesFloat(series.Owner, name, data);
});
}
#endregion
#region Distance
/// <summary>
/// Distance indicator, according to John F. Ehlers's
/// book 'Rocket Science for Traders'. Ehlers uses this
/// indicator as coefficients for an Ehlers Filter.
/// </summary>
/// <param name="series"></param>
/// <param name="n"></param>
/// <returns></returns>
public static TimeSeriesFloat Distance(this TimeSeriesFloat series, int n)
{
var name = string.Format("{0}.Distance({1})", series.Name, n);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var src = series.Data;
var dst = new List<BarType<double>>();
var lookback = new LookbackGroup();
var input = lookback.NewLookback(0.0);
for (int idx = 0; idx < src.Count; idx++)
{
lookback.Advance();
input.Value = src[idx].Value;
// this logic taken from
// Ehlers's book, see fig 18.6., page 193.
var distance = Enumerable.Range(1, n - 1)
.Sum(t => Math.Pow(input[0] - input[t], 2.0));
dst.Add(new BarType<double>(
src[idx].Date, distance));
}
return dst;
}));
return new TimeSeriesFloat(series.Owner, name, data);
});
}
#endregion
#region DominantCyclePeriod
/// <summary>
/// Calculate the dominant cycle period. The method is based
/// on John F. Ehlers's book 'Rocket Science for Traders' and
/// uses complex arithmetic and a homodyne discriminator.
/// </summary>
/// <param name="series">input series</param>
/// <returns>variance time series</returns>
public static TimeSeriesFloat DominantCyclePeriod(this TimeSeriesFloat series)
{
var name = string.Format("{0}.DominantCyclePeriod()", series.Name);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var src = series.Data;
var dst = new List<BarType<double>>();
var lookback = new LookbackGroup();
var Price = lookback.NewLookback(src[0].Value);
var Smooth = lookback.NewLookback(src[0].Value);
var Detrender = lookback.NewLookback(0);
var I1 = lookback.NewLookback(0);
var Q1 = lookback.NewLookback(0);
var jI = lookback.NewLookback(0);
var jQ = lookback.NewLookback(0);
var I2 = lookback.NewLookback(0);
var Q2 = lookback.NewLookback(0);
var Re = lookback.NewLookback(0);
var Im = lookback.NewLookback(0);
var Period = lookback.NewLookback(0);
var SmoothPeriod = lookback.NewLookback(0);
for (int idx = 0; idx < src.Count; idx++)
{
// advance all lookbacks
lookback.Advance();
// note the complicated feedback through the
// period value, which makes porting to
// TuringTrader's indicators tricky
Price.Value = src[idx].Value;
// this code is taken (almost) verbatim from
// Ehlers's book, see fig 7.2., page 68ff.
Smooth.Value = (4.0 * Price + 3.0 * Price[1]
+ 2.0 * Price[2] + Price[3])
/ 10.0;
Detrender.Value = (0.0962 * Smooth + 0.5769 * Smooth[2]
- 0.5769 * Smooth[4] - 0.0962 * Smooth[6])
* (0.075 * Period[1] + 0.54);
//--- compute in-phase and quadrature components
Q1.Value = (0.0962 * Detrender + 0.5769 * Detrender[2]
- 0.5769 * Detrender[4] - 0.0962 * Detrender[6])
* (0.075 * Period[1] + 0.54);
I1.Value = Detrender[3];
//--- advance the phase of I1 and Q1 by 90 degrees
jI.Value = (0.0962 * I1 + 0.5769 * I1[2]
- 0.5769 * I1[4] - 0.0962 * I1[6])
* (0.075 * Period[1] + 0.54);
jQ.Value = (0.0962 * Q1 + 0.5769 * Q1[2]
- 0.5769 * Q1[4] - 0.0962 * Q1[6])
* (0.075 * Period[1] + 0.54);
//--- phasor addition for 3-bar averaging
I2.Value = I1 - jQ;
Q2.Value = Q1 + jI;
//--- smooth the i and q components before applying the discriminator
I2.Value = 0.2 * I2 + 0.8 * I2[1];
Q2.Value = 0.2 * Q2 + 0.8 * Q2[1];
//--- homodyne discriminator
Re.Value = I2 * I2[1] + Q2 * Q2[1];
Im.Value = I2 * Q2[1] - Q2 * I2[1];
Re.Value = 0.2 * Re + 0.8 * Re[1];
Im.Value = 0.2 * Im + 0.8 * Im[1];
Period.Value = 2.0 * Math.PI / Math.Atan2(Im, Re);
if (Period > 1.5 * Period[1]) Period.Value = 1.5 * Period[1];
if (Period < 0.67 * Period[1]) Period.Value = 0.67 * Period[1];
if (Period < 6.0) Period.Value = 6.0;
if (Period > 50.0) Period.Value = 50.0;
Period.Value = 0.2 * Period + 0.8 * Period[1];
SmoothPeriod.Value = 0.33 * Period + 0.67 * SmoothPeriod[1]; // 0.33 = 2/(5 + 1) = EMA(5)
dst.Add(new BarType<double>(
src[idx].Date, SmoothPeriod[0]));
}
return dst;
}));
return new TimeSeriesFloat(series.Owner, name, data);
});
}
#endregion
#region SignalToNoiseRatio
/// <summary>
/// Calculate the signal-to-noise ratio. The method is based
/// on John F. Ehlers's book 'Rocket Science for Traders'.
/// </summary>
/// <param name="series">input series</param>
/// <returns>variance time series</returns>
public static TimeSeriesFloat SignalToNoiseRatio(this TimeSeriesAsset series)
{
var name = string.Format("{0}.SignalToNoiseRatio()", series.Name);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var src = series.Data;
var dst = new List<BarType<double>>();
var typ = series.TypicalPrice().Data; // Ehlers is using (H+L)/2 instead
var dcp = series.TypicalPrice().DominantCyclePeriod().Data;
var lookback = new LookbackGroup();
var Price = lookback.NewLookback(0);
var Smooth = lookback.NewLookback(0);
var SmoothPeriod = lookback.NewLookback(0);
var Q3 = lookback.NewLookback(0);
var I3 = lookback.NewLookback(0);
var Signal = lookback.NewLookback(0);
var Noise = lookback.NewLookback(0);
var SNR = lookback.NewLookback(0);
for (int idx = 0; idx < src.Count; idx++)
{
lookback.Advance();
var H = src[idx].Value.High;
var L = src[idx].Value.Low;
Price.Value = typ[idx].Value;
Smooth.Value = (4 * Price + 3 * Price[1] + 2 * Price[2] + Price[3]) / 10;
// a lot of code removed here, using
// DominantCyclePeriod indicator instead
SmoothPeriod.Value = dcp[idx].Value;
// this code is taken (almost) verbatim from
// Ehlers's book, see fig 8.5., page 87ff.
Q3.Value = 0.5 * (Smooth - Smooth[2])
* (0.1759 * SmoothPeriod + 0.4607);
var smoothPeriod_2 = (int)Math.Floor(SmoothPeriod / 2);
I3.Value = Enumerable.Range(0, smoothPeriod_2)
.Sum(t => Q3[t])
* 1.57 / Math.Max(1, smoothPeriod_2);
Signal.Value = I3 * I3 + Q3 * Q3;
Noise.Value = 0.1 * (H - L) * (H - L) * 0.25 + 0.9 * Noise[1];
if (Noise != 0 && Signal != 0)
SNR.Value = 0.33 * (10 * Math.Log(Signal / Noise) / Math.Log(10))
+ 0.67 * SNR[1];
dst.Add(new BarType<double>(
src[idx].Date, SNR[0]));
}
return dst;
}));
return new TimeSeriesFloat(series.Owner, name, data);
});
}
#endregion
#region SinewaveIndicator
/// <summary>
/// Calculate the Sinewave Indicator. The method is based
/// on John F. Ehlers's book 'Rocket Science for Traders'.
/// </summary>
/// <param name="series">input series</param>
/// <returns>Sinewave indicator container</returns>
public static SinewaveIndicatorT SinewaveIndicator(this TimeSeriesFloat series)
{
var name = string.Format("{0}.SinewaveIndicator()", series.Name);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var src = series.Data;
var dcp = series.DominantCyclePeriod().Data;
var dstPhase = new List<BarType<double>>();
var dstSine = new List<BarType<double>>();
var dstLead = new List<BarType<double>>();
var lookback = new LookbackGroup();
var Price = lookback.NewLookback(0);
var SmoothPeriod = lookback.NewLookback(0);
var SmoothPrice = lookback.NewLookback(0);
var RealPart = lookback.NewLookback();
var ImagPart = lookback.NewLookback();
var DCPhase = lookback.NewLookback();
for (int idx = 0; idx < src.Count; idx++)
{
lookback.Advance();
Price.Value = src[idx].Value;
// a lot of code removed here, using
// DominantCyclePeriod indicator instead
SmoothPeriod.Value = dcp[idx].Value;
// this code is taken (almost) verbatim from
// Ehlers's book, see fig 9.3., page 101ff.
//--- compute dominant cycle phase
SmoothPrice.Value = (4 * Price + 3 * Price[1]
+ 2 * Price[2] + Price[3]) / 10;
var DCPeriod = (int)Math.Floor(SmoothPeriod + 0.5);
RealPart.Value = Enumerable.Range(0, DCPeriod)
.Sum(t => Math.Cos(2 * Math.PI / DCPeriod * t) * SmoothPrice[t]);
ImagPart.Value = Enumerable.Range(0, DCPeriod)
.Sum(t => Math.Sin(2 * Math.PI / DCPeriod * t) * SmoothPrice[t]);
DCPhase.Value = 180 / Math.PI * Math.Atan2(ImagPart, RealPart) + 90;
//--- compensate for one bar lag of the weighted moving average
DCPhase.Value = DCPhase + 360 / SmoothPeriod;
// coerce phase between -45 and +315 degrees
if (DCPhase.Value < -45) DCPhase.Value = DCPhase + 360;
if (DCPhase.Value > 315) DCPhase.Value = DCPhase - 360;
var sine = Math.Sin(Math.PI / 180 * DCPhase);
var lead = Math.Sin(Math.PI / 180 * (DCPhase + 45));
dstPhase.Add(new BarType<double>(
src[idx].Date, DCPhase));
dstSine.Add(new BarType<double>(
src[idx].Date, sine));
dstLead.Add(new BarType<double>(
src[idx].Date, lead));
}
return (object)Tuple.Create(dstPhase, dstSine, dstLead);
}));
return new SinewaveIndicatorT(
new TimeSeriesFloat(
series.Owner, name + ".Phase",
data,
(data) => ((Tuple<List<BarType<double>>, List<BarType<double>>, List<BarType<double>>>)data).Item1),
new TimeSeriesFloat(
series.Owner, name + ".Sine",
data,
(data) => ((Tuple<List<BarType<double>>, List<BarType<double>>, List<BarType<double>>>)data).Item2),
new TimeSeriesFloat(
series.Owner, name + ".LeadSine",
data,
(data) => ((Tuple<List<BarType<double>>, List<BarType<double>>, List<BarType<double>>>)data).Item3));
});
}
/// <summary>
/// Container for Sinewave indicator result.
/// </summary>
public class SinewaveIndicatorT
{
/// <summary>
/// Dominant cycle phase. Will hover near 0 in downtrends and
/// near 180 degrees in uptrends
/// </summary>
public TimeSeriesFloat Phase;
/// <summary>
/// Dominant cycle's sine wave output.
/// </summary>
public TimeSeriesFloat Sine;
/// <summary>
/// Dominant cycle's leading sine wave output.
/// </summary>
public TimeSeriesFloat LeadSine;
/// <summary>
/// Create new container.
/// </summary>
/// <param name="phase"></param>
/// <param name="sine"></param>
/// <param name="leadsine"></param>
public SinewaveIndicatorT(TimeSeriesFloat phase, TimeSeriesFloat sine, TimeSeriesFloat leadsine)
{
Phase = phase;
Sine = sine;
LeadSine = leadsine;
}
}
#endregion
#region InstantaneousTrendline
/// <summary>
/// Calculate the Instantaneous Trendline. The method is based
/// on John F. Ehlers's book 'Rocket Science for Traders'.
/// </summary>
/// <param name="series">input series</param>
/// <param name="cycPart">cycle period adjustment, default = 1.0</param>
/// <returns>variance time series</returns>
public static TimeSeriesFloat InstantaneousTrendline(this TimeSeriesFloat series, double cycPart = 1.0)
{
var name = string.Format("{0}.InstantaneousTrendline({1})", series.Name, cycPart);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var src = series.Data;
var dst = new List<BarType<double>>();
var dcp = series.DominantCyclePeriod().Data;
var lookback = new LookbackGroup();
var Price = lookback.NewLookback(0);
var Smooth = lookback.NewLookback(0);
var SmoothPeriod = lookback.NewLookback(0);
var ITrend = lookback.NewLookback(0);
var Trendline = lookback.NewLookback(0);
for (int idx = 0; idx < src.Count; idx++)
{
lookback.Advance();
Price.Value = src[idx].Value;
// a lot of code removed here, using
// DominantCyclePeriod indicator instead
SmoothPeriod.Value = dcp[idx].Value;
// this code is taken (almost) verbatim from
// Ehlers's book, see fig 10.1., page 109ff.
//--- compute trendline as a simple average over
// the measured dominant cycle period
var DCPeriod = (int)Math.Floor(cycPart * SmoothPeriod + 0.5);
if (DCPeriod > 0)
ITrend.Value = Enumerable.Range(0, DCPeriod)
.Average(t => Price[t]);
Trendline.Value = (4 * ITrend + 3 * ITrend[1]
+ 2 * ITrend[2] + ITrend[3]) / 10;
dst.Add(new BarType<double>(
src[idx].Date, Trendline));
}
return dst;
}));
return new TimeSeriesFloat(series.Owner, name, data);
});
}
#endregion
#region MarketMode
/// <summary>
/// Calculate the market mode. The method is based
/// on John F. Ehlers's book 'Rocket Science for Traders'.
/// </summary>
/// <param name="series">input series</param>
/// <param name="breakCycle">price deviation from trend line to break cycle mode (default = 0.015 = 1.5%)</param>
/// <returns>variance time series</returns>
public static TimeSeriesFloat MarketMode(this TimeSeriesFloat series, double breakCycle = 0.015)
{
var name = string.Format("{0}.MarketMode({1})", series.Name, breakCycle);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var srcSeries = series.Data;
var srcPeriod = series.DominantCyclePeriod().Data;
var srcPhase = series.SinewaveIndicator().Phase.Data;
var srcSine = series.SinewaveIndicator().Sine.Data;
var srcLeadSine = series.SinewaveIndicator().LeadSine.Data;
var srcTrendline = series.InstantaneousTrendline().Data;
var dst = new List<BarType<double>>();
var lbg = new LookbackGroup();
var Price = lbg.NewLookback(0);
var SmoothPrice = lbg.NewLookback(0);
var SmoothPeriod = lbg.NewLookback(0);
var ITrend = lbg.NewLookback(0);
var Trendline = lbg.NewLookback(0);
var Trend = lbg.NewLookback();
var DaysInTrend = lbg.NewLookback();
var DCPhase = lbg.NewLookback();
var Sine = lbg.NewLookback();
var LeadSine = lbg.NewLookback();
for (int idx = 0; idx < srcSeries.Count; idx++)
{
lbg.Advance();
Price.Value = srcSeries[idx].Value;
// a lot of code removed here, using
// DominantCyclePeriod indicator instead
SmoothPeriod.Value = srcPeriod[idx].Value;
// code removed here, using
// Sinewave indicator instead
SmoothPrice.Value = (4 * Price + 3 * Price[1]
+ 2 * Price[2] + Price[3]) / 10;
DCPhase.Value = srcPhase[idx].Value;
Sine.Value = srcSine[idx].Value;
LeadSine.Value = srcLeadSine[idx].Value;
// more code removed here, using
// InstantaneousTrendline indicator instead
Trendline.Value = srcTrendline[idx].Value;
// this code is taken (almost) verbatim from
// Ehlers's book, see fig 11.1., page 114ff.
//--- assume trend mode
Trend.Value = 1;
//--- measure days in trend from last crossing of the
// sinewave indicator lines
if ((Sine > LeadSine && Sine[1] <= LeadSine[1])
|| (Sine < LeadSine && Sine[1] >= LeadSine[1]))
{
DaysInTrend.Value = 0;
Trend.Value = 0;
}
DaysInTrend.Value = DaysInTrend + 1;
if (DaysInTrend < 0.5 * SmoothPeriod) Trend.Value = 0;
//--- cycle mode if delta phase is +/- 50% of
// dominant cycle change of phase
if (SmoothPeriod != 0
&& DCPhase - DCPhase[1] > 0.67 * 360 / SmoothPeriod
&& DCPhase - DCPhase[1] < 1.5 * 360 / SmoothPeriod)
Trend.Value = 0;
//--- trend mode if prices are widely separated
// from the trend line
if (Math.Abs((SmoothPrice - Trendline) / Trendline) > breakCycle)
Trend.Value = 1;
dst.Add(new BarType<double>(
srcSeries[idx].Date, Trend));
}
return dst;
}));
return new TimeSeriesFloat(series.Owner, name, data);
});
}
#endregion
#region EhlersFilter
/// <summary>
/// Calculate Ehlers Filter, as described in
/// John F. Ehlers's book 'Rocket Science for Traders'.
/// Also see <see href="https://mesasoftware.com/papers/EhlersFilters.pdf"/>
/// </summary>
/// <param name="series">source series</param>
/// <param name="coefficients">coefficient series</param>
/// <param name="n">filter length</param>
/// <returns>Ehlers Filter time series</returns>
public static TimeSeriesFloat EhlersFilter(this TimeSeriesFloat series, TimeSeriesFloat coefficients, int n)
{
var name = string.Format("{0}.EhlersFilter({1},{2})", series.Name, coefficients.Name, n);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var src = series.Data;
var flt = coefficients.Data;
var dst = new List<BarType<double>>();
var lookback = new LookbackGroup();
var input = lookback.NewLookback(src[0].Value);
var filter = lookback.NewLookback(flt[0].Value);
for (int idx = 0; idx < src.Count; idx++)
{
lookback.Advance();
input.Value = src[idx].Value;
filter.Value = flt[idx].Value;
var output = Enumerable.Range(0, n)
.Sum(t => input[t] * filter[t])
/ Enumerable.Range(0, n)
.Sum(t => filter[t]);
dst.Add(new BarType<double>(
src[idx].Date, output));
}
return dst;
}));
return new TimeSeriesFloat(series.Owner, name, data);
});
}
#endregion
#region DistanceCoefficientEhlersFilter
/// <summary>
///
/// </summary>
/// <param name="series"></param>
/// <param name="n"></param>
/// <returns></returns>
public static TimeSeriesFloat DistanceCoefficientEhlersFilter(this TimeSeriesFloat series, int n)
// see Ehlers's book, see fig 18.6., page 193.
=> series.EhlersFilter(series.Distance(n), n);
#endregion
#region OptimumPredictor
/// <summary>
/// Calculate Optimum Predictor, as described in
/// John F. Ehlers's book 'Rocket Science for Traders'.
/// </summary>
/// <param name="series">source series</param>
/// <returns>Optimum Predictor time series</returns>
public static OptimumPredictorT OptimumPredictor(this TimeSeriesFloat series)
{
var name = string.Format("{0}.OptimumPredictor", series.Name);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var src = series.Data;
var dcp = series.DominantCyclePeriod().Data;
var predict = new List<BarType<double>>();
var signal = new List<BarType<double>>();
var lookback = new LookbackGroup();
var Price = lookback.NewLookback(0);
var Smooth = lookback.NewLookback(0);
var SmoothPeriod = lookback.NewLookback(0);
var Detrender2 = lookback.NewLookback(0);
var Smooth2 = lookback.NewLookback(0);
var DetrendEMA = lookback.NewLookback(0);
var Predict = lookback.NewLookback(0);
for (int idx = 0; idx < src.Count; idx++)
{
lookback.Advance();
Price.Value = src[idx].Value;
Smooth.Value = (4 * Price + 3 * Price[1] + 2 * Price[2] + Price[3]) / 10;
// a lot of code removed here, using
// DominantCyclePeriod indicator instead
SmoothPeriod.Value = dcp[idx].Value;
// this code is taken (almost) verbatim from
// Ehlers's book, see fig 20.2., page 209ff.
//--- optimum predictor
Detrender2.Value = 0.5 * Smooth - 0.5 * Smooth[2];
Smooth2.Value = (4 * Detrender2 + 3 * Detrender2[1]
+ 2 * Detrender2[2] + Detrender2[3]) / 10;
// FIXME: Ehlers uses Period here, which is hidden
// inside the DominantCyclePeriod indicator.
// This will likely introduce some lag.
var alpha = 1 - Math.Exp(-6.28 / SmoothPeriod);
DetrendEMA.Value = alpha * Smooth2
+ (1 - alpha) * DetrendEMA[1];
Predict.Value = 1.4 * (Smooth2 - DetrendEMA);
predict.Add(new BarType<double>(
src[idx].Date, Predict));
signal.Add(new BarType<double>(
src[idx].Date, Smooth2));
}
return (object)Tuple.Create(predict, signal);
}));
return new OptimumPredictorT(
new TimeSeriesFloat(
series.Owner, name + ".Predict",
data,
(data) => ((Tuple<List<BarType<double>>, List<BarType<double>>>)data).Item1),
new TimeSeriesFloat(
series.Owner, name + ".Signal",
data,
(data) => ((Tuple<List<BarType<double>>, List<BarType<double>>>)data).Item2));
});
}
/// <summary>
/// Container for Optimum Predictor indicator
/// </summary>
public class OptimumPredictorT
{
/// <summary>
/// Optimum predictor output
/// </summary>
public TimeSeriesFloat Predict;
/// <summary>
/// Optimum predictor signal line
/// </summary>
public TimeSeriesFloat Signal;
/// <summary>
/// Create Optimum Predictor container.
/// </summary>
/// <param name="predict"></param>
/// <param name="signal"></param>
public OptimumPredictorT(TimeSeriesFloat predict, TimeSeriesFloat signal)
{
Predict = predict;
Signal = signal;
}
};
#endregion
#region PredictiveMovingAverage
/// <summary>
/// Calculate predictive moving average as described in
/// John F. Ehlers's book 'Rocket Science for Traders'.
/// </summary>
/// <param name="series"></param>
/// <param name="n"></param>
/// <returns></returns>
public static PredictiveMovingAverageT PredictiveMovingAverage(this TimeSeriesFloat series, int n = 7)
{
var name = string.Format("{0}.PredictiveMovingAverage({1})", series.Name, n);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
// see Ehlers's book, see fig 20.4., page 212ff.
var wma1 = series.WMA(7);
var wma2 = wma1.WMA(7);
var predict = wma1.Mul(2).Sub(wma2);
var trigger = predict.WMA(4);
return new PredictiveMovingAverageT(predict, trigger);
});
}
/// <summary>
/// Container class for result of PredictiveMovingAverage
/// </summary>
public class PredictiveMovingAverageT
{
/// <summary>
/// Trigger line.
/// </summary>
public TimeSeriesFloat Trigger;
/// <summary>
/// Predictive moving average.
/// </summary>
public TimeSeriesFloat Predict;
/// <summary>
/// Create new container.
/// </summary>
/// <param name="predict"></param>
/// <param name="trigger"></param>
public PredictiveMovingAverageT(TimeSeriesFloat predict, TimeSeriesFloat trigger)
{
Trigger = trigger;
Predict = predict;
}
}
#endregion
#region AdaptiveRSI
/// <summary>
/// Calculate adaptive RSI. The method is based
/// on John F. Ehlers's book 'Rocket Science for Traders'.
/// </summary>
/// <param name="series">input series</param>
/// <param name="CycPart"></param>
/// <returns>variance time series</returns>
public static TimeSeriesFloat AdaptiveRSI(this TimeSeriesFloat series, double CycPart = 0.5)
{
var name = string.Format("{0}.AdaptiveRSI({1})", series.Name, CycPart);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var src = series.Data;
var dst = new List<BarType<double>>();
var dcp = series.DominantCyclePeriod().Data;
var lookback = new LookbackGroup();
var Close = lookback.NewLookback(0);
var RSI = lookback.NewLookback(0);
for (int idx = 0; idx < src.Count; idx++)
{
lookback.Advance();
Close.Value = src[idx].Value;
// a lot of code removed here, using
// DominantCyclePeriod indicator instead
var SmoothPeriod = dcp[idx].Value;
// this code is adapted from
// Ehlers's book, see fig 22.1., page 230ff.
var CU = Enumerable.Range(0, (int)Math.Floor(CycPart * SmoothPeriod))
.Sum(t => Math.Max(0.0, Close[t] - Close[t + 1]));
var CD = Enumerable.Range(0, (int)Math.Floor(CycPart * SmoothPeriod))
.Sum(t => Math.Max(0.0, Close[t + 1] - Close[t]));
if (CU + CD != 0) RSI.Value = 100 * CU / (CU + CD);
dst.Add(new BarType<double>(
src[idx].Date, RSI[0]));
}
return dst;
}));
return new TimeSeriesFloat(series.Owner, name, data);
});
}
#endregion
#region AdaptiveStochastic
/// <summary>
/// Calculate adaptive Stochastic. The method is based
/// on John F. Ehlers's book 'Rocket Science for Traders'.
/// </summary>
/// <param name="series">input series</param>
/// <param name="CycPart"></param>
/// <returns>variance time series</returns>
public static TimeSeriesFloat AdaptiveStochastic(this TimeSeriesAsset series, double CycPart = 0.5)
{
var name = string.Format("{0}.AdaptiveStochastic({1})", series.Name, CycPart);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{
var src = series.Data;
var dst = new List<BarType<double>>();
var dcp = series.TypicalPrice().DominantCyclePeriod().Data;
var lookback = new LookbackGroup();
var Close = lookback.NewLookback(0);
var H = lookback.NewLookback(0);
var L = lookback.NewLookback(0);
var HH = lookback.NewLookback(0);
var LL = lookback.NewLookback(0);
var Stochastic = lookback.NewLookback(0);
for (int idx = 0; idx < src.Count; idx++)
{
lookback.Advance();
Close.Value = src[idx].Value.Close;
H.Value = src[idx].Value.High;
L.Value = src[idx].Value.Low;
// a lot of code removed here, using
// DominantCyclePeriod indicator instead
var SmoothPeriod = dcp[idx].Value;
// this code is adapted from
// Ehlers's book, see fig 22.2., page 233ff.
var r = (int)Math.Floor(CycPart * SmoothPeriod);
if (r > 0)
{
HH.Value = Enumerable.Range(0, r).Max(t => H[t]);
LL.Value = Enumerable.Range(0, r).Min(t => L[t]);
}
if (HH - LL != 0) Stochastic.Value = (Close - LL) / (HH - LL);
dst.Add(new BarType<double>(
src[idx].Date, 100 * Stochastic));
}
return dst;
}));
return new TimeSeriesFloat(series.Owner, name, data);
});
}
#endregion
#region AdaptiveCCI
/// <summary>
/// Calculate adaptive CCI. The method is based
/// on John F. Ehlers's book 'Rocket Science for Traders'.
/// </summary>
/// <param name="series">input series</param>
/// <param name="CycPart"></param>
/// <returns>variance time series</returns>
public static TimeSeriesFloat AdaptiveCCI(this TimeSeriesAsset series, double CycPart = 1.0)
{
var name = string.Format("{0}.AdaptiveCCI({1})", series.Name, CycPart);
return series.Owner.ObjectCache.Fetch(
name,
() =>
{
var data = series.Owner.DataCache.Fetch(
name,
() => Task.Run(() =>
{