package top.baogutang.strategy.runners;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import top.baogutang.strategy.backtests.BacktestEngine;
import top.baogutang.strategy.backtests.BacktestResult;
import top.baogutang.strategy.backtests.CsvLoader;
import top.baogutang.strategy.commons.configs.AppProperties;
import top.baogutang.strategy.commons.enums.Timeframe;
import top.baogutang.strategy.models.Kline;
import top.baogutang.strategy.strategies.Strategy;

import java.util.*;

@Slf4j
@Component
public class BacktestCommandLineRunner implements CommandLineRunner {
    private final AppProperties props;
    private final Map<String, List<Strategy>> strategiesMap;

    public BacktestCommandLineRunner(AppProperties props,
                                     Map<String, List<Strategy>> strategiesMap) {
        this.props = props;
        this.strategiesMap = strategiesMap;
    }

    public void run(String... args) throws Exception {
        boolean backtest = false;
        for (String a : args) {
            if ("--backtest=true".equalsIgnoreCase(a)) {
                backtest = true;
                break;
            }
        }
        if (!backtest) return;

        AppProperties.SymbolConfig cfg = props.getSymbols().get(0);
        Map<Timeframe, List<Kline>> data = new HashMap<Timeframe, List<Kline>>();
        data.put(Timeframe.M15, CsvLoader.load("data/" + cfg.getInstId() + "_M15.csv", Timeframe.M15.millis));
        data.put(Timeframe.H1, CsvLoader.load("data/" + cfg.getInstId() + "_H1.csv", Timeframe.H1.millis));
        data.put(Timeframe.H4, CsvLoader.load("data/" + cfg.getInstId() + "_H4.csv", Timeframe.H4.millis));

        BacktestEngine engine = new BacktestEngine();
        List<Strategy> strategies = strategiesMap.get(cfg.getInstId());
        BacktestResult r = engine.run(strategies, data, props.getAccount().getEquity(), props.getAccount().getRiskPercent());
        log.info("Backtest %s Trades=%d WinRate=%.2f%% TotalR=%.2f MaxDD=%.2f%%%n",
                cfg.getInstId(), r.getTrades(), r.getWinRate() * 100, r.getTotalR(), r.getMaxDrawdown() * 100);
        System.exit(0);
    }
}
