Libraryless. Click here for Pure Java version (17707L/102K).
1 | persistable sclass ATR extends CandleBasedIndicator<Double> { |
2 | // For first phase |
3 | new Average initialAverage; |
4 | |
5 | // For second phase |
6 | settable SmoothedMovingAverage sma; |
7 | |
8 | // TR value |
9 | settable double tr = Double.NaN; |
10 | |
11 | // ATR value |
12 | settable double atr = Double.NaN; |
13 | |
14 | // ATR values collected as ticker |
15 | gettable TickerSequence atrHistory = new TickerSequence("ATR"); |
16 | |
17 | Double value() { ret atr(); } |
18 | |
19 | *(int *length) {} |
20 | |
21 | { |
22 | length = 14; |
23 | onCandleAdded((IVF1<TradingCandle>) candle -> { |
24 | var x = candle.move(); |
25 | var u = max(x, 0.0); |
26 | var d = neg(min(x, 0.0)); |
27 | |
28 | // Calculate TR |
29 | if (candles().size() < 2) ret; |
30 | |
31 | tr(trueRange(ll(candles().nextToLast(), candles().last()))); |
32 | |
33 | if (initialAverage.count() < length()) |
34 | ret with initialAverage.add(tr); |
35 | |
36 | if (sma == null) { |
37 | sma(new SmoothedMovingAverage(length())); |
38 | sma().add(initialAverage!); |
39 | } else |
40 | sma().add(tr); |
41 | |
42 | atr(sma()!); |
43 | long time = candle.endTime().toLong(); |
44 | atrHistory?.addIfPriceChanged(atr, time); |
45 | }); |
46 | } |
47 | |
48 | TickerSequence asTicker(L<TradingCandle> candles) { |
49 | feed(candles); |
50 | ret atrHistory; |
51 | } |
52 | |
53 | void reset :: after { |
54 | resetFields(this, "initialAverage sma tr atr atrHistory"); |
55 | } |
56 | } |
Began life as a copy of #1036452
download show line numbers debug dex old transpilations
Travelled to 2 computer(s): mowyntqkapby, mqqgnosmbjvj
No comments. add comment
Snippet ID: | #1036469 |
Snippet name: | ATR [average true range, trading indicator] |
Eternal ID of this version: | #1036469/8 |
Text MD5: | c697306fbd387e90c2fbfdad6f6e32b6 |
Transpilation MD5: | ece4b0b45fc45c741174856d1e185b77 |
Author: | stefan |
Category: | javax / trading |
Type: | JavaX fragment (include) |
Public (visible to everyone): | Yes |
Archived (hidden from active list): | No |
Created/modified: | 2022-12-16 14:59:25 |
Source code size: | 1367 bytes / 56 lines |
Pitched / IR pitched: | No / No |
Views / Downloads: | 176 / 265 |
Version history: | 7 change(s) |
Referenced in: | [show references] |