-
Notifications
You must be signed in to change notification settings - Fork 226
/
AtrStop.Series.cs
111 lines (94 loc) · 3.2 KB
/
AtrStop.Series.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
namespace Skender.Stock.Indicators;
// ATR TRAILING STOP (SERIES)
public static partial class Indicator
{
internal static List<AtrStopResult> CalcAtrStop(
this List<QuoteD> qdList,
int lookbackPeriods,
double multiplier,
EndType endType)
{
// check parameter arguments
ValidateAtrStop(lookbackPeriods, multiplier);
// initialize
List<AtrStopResult> results = new(qdList.Count);
List<AtrResult> atrResults = qdList.CalcAtr(lookbackPeriods);
bool isBullish = true;
double? upperBand = null;
double? lowerBand = null;
// roll through quotes
for (int i = 0; i < qdList.Count; i++)
{
QuoteD q = qdList[i];
AtrStopResult r = new(q.Date);
results.Add(r);
if (i >= lookbackPeriods)
{
double? atr = atrResults[i].Atr;
QuoteD p = qdList[i - 1];
double? upperEval;
double? lowerEval;
// potential bands for CLOSE
if (endType == EndType.Close)
{
upperEval = q.Close + (multiplier * atr);
lowerEval = q.Close - (multiplier * atr);
}
// potential bands for HIGH/LOW
else
{
upperEval = q.High + (multiplier * atr);
lowerEval = q.Low - (multiplier * atr);
}
// initial values
if (i == lookbackPeriods)
{
isBullish = q.Close >= p.Close;
upperBand = upperEval;
lowerBand = lowerEval;
}
// new upper band
if (upperEval < upperBand || p.Close > upperBand)
{
upperBand = upperEval;
}
// new lower band
if (lowerEval > lowerBand || p.Close < lowerBand)
{
lowerBand = lowerEval;
}
// trailing stop
if (q.Close <= (isBullish ? lowerBand : upperBand))
{
r.AtrStop = (decimal?)upperBand;
r.BuyStop = (decimal?)upperBand;
isBullish = false;
}
else
{
r.AtrStop = (decimal?)lowerBand;
r.SellStop = (decimal?)lowerBand;
isBullish = true;
}
}
}
return results;
}
// parameter validation
private static void ValidateAtrStop(
int lookbackPeriods,
double multiplier)
{
// check parameter arguments
if (lookbackPeriods <= 1)
{
throw new ArgumentOutOfRangeException(nameof(lookbackPeriods), lookbackPeriods,
"Lookback periods must be greater than 1 for ATR Trailing Stop.");
}
if (multiplier <= 0)
{
throw new ArgumentOutOfRangeException(nameof(multiplier), multiplier,
"Multiplier must be greater than 0 for ATR Trailing Stop.");
}
}
}