package top.baogutang.strategy.services;

import top.baogutang.strategy.models.Kline;

import java.util.List;

public class IndicatorService {
    public double sma(List<Kline> bars, int p) {
        if (bars.size() < p) return Double.NaN;
        double s = 0;
        for (int i = bars.size() - p; i < bars.size(); i++) s += bars.get(i).close();
        return s / p;
    }

    public double smaVolume(List<Kline> bars, int p) {
        if (bars.size() < p) return Double.NaN;
        double s = 0;
        for (int i = bars.size() - p; i < bars.size(); i++) s += bars.get(i).volume();
        return s / p;
    }

    public double atr(List<Kline> bars, int p) {
        if (bars.size() < p + 1) return Double.NaN;
        double sum = 0;
        for (int i = 1; i < bars.size(); i++) {
            Kline c = bars.get(i);
            Kline prev = bars.get(i - 1);
            double tr = Math.max(c.high() - c.low(),
                    Math.max(Math.abs(c.high() - prev.close()), Math.abs(c.low() - prev.close())));
            if (i >= bars.size() - p) sum += tr;
        }
        return sum / p;
    }

    public double lowerShadowRatio(Kline k) {
        double range = k.high() - k.low();
        if (range <= 0) return 0;
        double lower = Math.min(k.open(), k.close()) - k.low();
        return lower / range;
    }

    public double upperShadowRatio(Kline k) {
        double range = k.high() - k.low();
        if (range <= 0) return 0;
        double upper = k.high() - Math.max(k.open(), k.close());
        return upper / range;
    }
}
