#pragma once
#include "types.hpp"
#include "custom_strategy.hpp"
#include "risk.hpp"
#include <vector>
#include <deque>
#include <string>
#include <cstdio>
#include <cmath>
#include <fstream>
#include <sstream>
namespace quant {
struct BacktestTrade {
int64_t entry_ts = 0;
double entry_price = 0.0;
double qty = 0.0;
uint8_t side = 0;
int64_t exit_ts = 0;
double exit_price = 0.0;
double pnl = 0.0;
bool closed = false;
};
struct BacktestStats {
size_t bars = 0;
size_t trades = 0;
double initial_capital = 0.0;
double final_capital = 0.0;
double total_return_pct = 0.0;
double max_drawdown_pct = 0.0;
double sharpe = 0.0;
double win_rate = 0.0;
double avg_win = 0.0, avg_loss = 0.0;
double profit_factor = 0.0;
size_t long_trades = 0, short_trades = 0;
};
class Backtester {
public:
struct Config {
double initial_capital = 10000.0;
double fee_rate = 0.0005;
double slippage = 0.0002;
RiskConfig risk;
};
Backtester(Strategy& strategy, Config cfg) : strategy_(strategy), cfg_(std::move(cfg)) {}
BacktestStats run(const std::vector<Kline>& bars, const Symbol& symbol) {
stats_ = {};
stats_.initial_capital = cfg_.initial_capital;
stats_.final_capital = cfg_.initial_capital;
RiskManager risk(cfg_.risk, cfg_.initial_capital);
std::vector<BacktestTrade> trades;
double peak = cfg_.initial_capital;
double eq_curve_sum = 0.0, eq_curve_sq = 0.0;
std::vector<double> returns;
size_t n = bars.size();
stats_.bars = n;
size_t wins = 0, losses = 0;
double total_win = 0.0, total_loss = 0.0;
Signal pending{};
bool has_pending = false;
strategy_.set_signal_callback([&](const Signal& sig) {
pending = sig;
has_pending = true;
});
for (size_t i = 0; i < n; ++i) {
const Kline& k = bars[i];
if (has_pending && i > 0) {
double exec_price = bars[i].open * (1.0 + cfg_.slippage * ((pending.side <= 1) ? 1 : -1));
if (pending.side <= 1) {
double atr = exec_price * 0.002;
double qty = risk.calculate_position_size(atr, exec_price);
if (qty > 0 && risk.check_pre_trade(OrderRequest{}, exec_price)) {
trades.push_back({bars[i].timestamp, exec_price, qty, (uint8_t)pending.side});
}
} else {
for (auto it = trades.rbegin(); it != trades.rend(); ++it) {
if (!it->closed) {
uint8_t close_side = (pending.side == 2) ? 0 : 1;
if (close_side == it->side) {
it->exit_ts = bars[i].timestamp;
it->exit_price = exec_price;
double pnl = (it->exit_price - it->entry_price) * it->qty;
if (it->side == 1) pnl = -pnl;
double fee = (it->entry_price * it->qty + it->exit_price * it->qty) * cfg_.fee_rate;
it->pnl = pnl - fee;
it->closed = true;
stats_.final_capital += it->pnl;
++stats_.trades;
if (it->side == 0) ++stats_.long_trades; else ++stats_.short_trades;
if (it->pnl > 0) { ++wins; total_win += it->pnl; }
else { ++losses; total_loss += it->pnl; }
break;
}
}
}
}
has_pending = false;
}
strategy_.on_kline(k);
double eq = stats_.final_capital;
for (const auto& t : trades) {
if (!t.closed) {
double upnl = (k.close - t.entry_price) * t.qty;
if (t.side == 1) upnl = -upnl;
eq += upnl;
}
}
double ret = (eq - peak) / peak;
if (eq > peak) peak = eq;
if (ret < 0) stats_.max_drawdown_pct = std::max(stats_.max_drawdown_pct, -ret * 100.0);
if (i > 0) returns.push_back((eq - stats_.final_capital) / stats_.final_capital);
eq_curve_sum += eq;
eq_curve_sq += eq * eq;
}
stats_.total_return_pct = (stats_.final_capital - stats_.initial_capital) / stats_.initial_capital * 100.0;
if (stats_.trades > 0) {
stats_.win_rate = (double)wins / stats_.trades * 100.0;
stats_.avg_win = (wins > 0) ? total_win / wins : 0.0;
stats_.avg_loss = (losses > 0) ? total_loss / losses : 0.0;
stats_.profit_factor = (total_loss < 0.0) ? (total_win / -total_loss) : 0.0;
}
if (returns.size() > 2) {
double mean = 0.0, sd = 0.0;
for (double r : returns) mean += r;
mean /= returns.size();
for (double r : returns) sd += (r - mean) * (r - mean);
sd = std::sqrt(sd / returns.size());
if (sd > 0) stats_.sharpe = mean / sd * std::sqrt(252.0 * 24.0 * 4.0);
}
return stats_;
}
const BacktestStats& stats() const { return stats_; }
private:
Strategy& strategy_;
Config cfg_;
BacktestStats stats_;
};
inline std::vector<Kline> load_klines_csv(const std::string& path) {
std::vector<Kline> out;
std::ifstream f(path);
if (!f) return out;
std::string line;
std::getline(f, line);
while (std::getline(f, line)) {
if (line.empty()) continue;
std::stringstream ss(line);
std::string tok;
std::vector<std::string> parts;
while (std::getline(ss, tok, ',')) parts.push_back(tok);
if (parts.size() < 6) continue;
double ts = std::strtod(parts[0].c_str(), nullptr);
Kline k{};
k.timestamp = (int64_t)ts;
k.open = std::strtod(parts[1].c_str(), nullptr);
k.high = std::strtod(parts[2].c_str(), nullptr);
k.low = std::strtod(parts[3].c_str(), nullptr);
k.close = std::strtod(parts[4].c_str(), nullptr);
k.volume = std::strtod(parts[5].c_str(), nullptr);
out.push_back(k);
}
return out;
}
}