Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

56
LINES

< > BotCompany Repo | #1036469 // ATR [average true range, trading indicator]

JavaX fragment (include) [tags: use-pretranspiled]

Libraryless. Click here for Pure Java version (17707L/102K).

persistable sclass ATR extends CandleBasedIndicator<Double> {
  // For first phase
  new Average initialAverage;
  
  // For second phase
  settable SmoothedMovingAverage sma;
  
  // TR value
  settable double tr = Double.NaN;

  // ATR value
  settable double atr = Double.NaN;
  
  // ATR values collected as ticker
  gettable TickerSequence atrHistory = new TickerSequence("ATR");

  Double value() { ret atr(); }
  
  *(int *length) {}

  {
    length = 14;
    onCandleAdded((IVF1<TradingCandle>) candle -> {
      var x = candle.move();
      var u = max(x, 0.0);
      var d = neg(min(x, 0.0));
      
      // Calculate TR
      if (candles().size() < 2) ret;
      
      tr(trueRange(ll(candles().nextToLast(), candles().last())));
      
      if (initialAverage.count() < length())
        ret with initialAverage.add(tr);
        
      if (sma == null) {
        sma(new SmoothedMovingAverage(length()));
        sma().add(initialAverage!);
      } else
        sma().add(tr);

      atr(sma()!);
      long time = candle.endTime().toLong();
      atrHistory?.addIfPriceChanged(atr, time);
    });
  }
  
  TickerSequence asTicker(L<TradingCandle> candles) {
    feed(candles);
    ret atrHistory;
  }
  
  void reset :: after {
    resetFields(this, "initialAverage sma tr atr atrHistory");
  }
}

Author comment

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: 177 / 267
Version history: 7 change(s)
Referenced in: #1003674 - Standard Classes + Interfaces (LIVE continued in #1034167)
#1036488 - ROCIndicator [rate of change, trading indicator]
#1036489 - ADX [average directional movement index, trading indicator, dev.]