uniVocity / univocity-trader

open-source trading framework for java, supports backtesting and live trading with exchanges
578 stars 140 forks source link

VWMA #133

Open intothemoonlite opened 2 years ago

intothemoonlite commented 2 years ago

@jbax I'm trying to add the VWMA indicator but I'm not able to get it to work just yet. My code is below:

public class VolumeWeightedMovingAverage extends SingleValueIndicator {

  private double value = 0;
  private int length = 0;
  private final CircularList price;
  private final CircularList volume;

  public VolumeWeightedMovingAverage(int length, TimeInterval interval) {
    this(length, interval, c -> c.close);
  }

  public VolumeWeightedMovingAverage(int length, TimeInterval timeInterval, ToDoubleFunction<Candle> valueGetter) {
    super(timeInterval, valueGetter);
    this.length = length;
    price = new CircularList(length);
    volume = new CircularList(length);
  }

  @Override
  protected Indicator[] children() {
    return new Indicator[0];
  }

  @Override
  protected boolean process(Candle candle, double value, boolean updating) {
    if (updating) {
      price.update(candle.close);
      volume.update(candle.volume);
    } else {
      price.add(candle.close);
      volume.add(candle.volume);
    }
    this.value = this.calculate(updating);
    return true;
  }

  private double calculate(boolean updating) {
    if (getAccumulationCount() <= this.length) {
      return 0;
    }

    double top = 0;
    double bottom = 0;
    int index = 0;
    for (double px : price.values) {
      top += price.get(index) * volume.get(index);
      bottom += volume.get(index);
      index++;
    }
    return top/bottom;
  }

  @Override
  public double getValue() {
    return this.value;
  }

  @Override
  public String signalDescription() {
    return super.signalDescription();
  }
}

I see there are various classes to extend for implementation but not too sure what to use for this indicator.