Crate bts

Crate bts 

Source
Expand description

§BTS: BackTest Strategy for Trading Algorithms

BTS is a high-performance Rust library for backtesting trading strategies on candlestick (OHLCV) data. It is designed for speed, flexibility, and accuracy, making it ideal for both retail traders and algorithmic trading developers.

§Why BTS?

  • Optimized for Performance: Uses O(1) operations on orders/positions, and parallel processing for optimization tasks.
  • Technical Analysis Ready: Seamlessly integrates with the ta crate for 100+ indicators (EMA, MACD, RSI, etc.).
  • Risk Management: Supports stop-loss, take-profit, and trailing stops with configurable rules.
  • Realistic Simulations: Models slippage, fees, and latency for accurate backtesting.
  • Extensible: Add custom indicators, strategies, or data sources with minimal effort.

§Core Components

ComponentDescription
CandleRepresents OHLCV (Open, High, Low, Close, Volume) data for a single time period.
OrderMarket, limit, or conditional orders (e.g., stop-loss, take-profit).
PositionOpen trades with configurable exit rules (e.g., trailing stops).
WalletTracks balance, locked funds, unrealized P&L, and fees.
MetricsCalculates performance metrics: P&L, drawdown, Sharpe ratio, win rate, and more.
OptimizerCalculates bests parameters (indicators, RR, etc…).
BacktestThe engine that simulates strategy execution over historical data.

§Features

§1. Technical Indicators

  • Compatible with the ta crate for 100+ additional indicators.

§2. Order Types & Exit Rules

Order TypeDescription
Market OrderExecutes immediately at the current price.
Limit OrderExecutes only at a specified price or better.
Take-ProfitCloses the position when a target price is reached.
Stop-LossCloses the position to limit losses.
Trailing StopDynamically adjusts the stop price based on market movements.
Take-Profit + Stop-LossCombines both rules for risk management.

§3. Performance Metrics

MetricDescription
Max DrawdownLargest peak-to-trough decline in account balance (%).
Profit FactorRatio of gross profits to gross losses.
Sharpe RatioRisk-adjusted return (higher = better).
Win RatePercentage of winning trades.
Sortino RatioLike Sharpe ratio, but focuses only on downside volatility.

§4. Optimization Tools

  • Parallel Brute-Force: Optimize strategy parameters (e.g., EMA periods) using multi-threading.

§Getting Started

§1. Add BTS to your project:

[dependencies]
bts = "*"
ta = "*"  # Optional: For technical analysis indicators

§2. Run a Simple Backtest:

use bts::prelude::*;
use chrono::DateTime;

fn main() {
    let candle = CandleBuilder::builder()
        .open(100.0)
        .high(110.0)
        .low(95.0)
        .close(105.0)
        .volume(1.0)
        .bid(0.5)
        .open_time(DateTime::default())
        .close_time(DateTime::default())
        .build()
        .unwrap();

    // Initialize backtest with \$10,000
    let mut backtest = Backtest::new(vec![candle], 10_000.0, None).unwrap();

    // Execute a market buy order
    backtest
        .run(|bt, _candle| {
            let order: Order = (OrderType::Market(102.0), 1.0, OrderSide::Buy).into();
            bt.place_order(order).unwrap();

            // Close the position at \$104.0
            if let Some(position) = bt.positions().last().cloned() {
                bt.close_position(&position, 104.0, true).unwrap();
            }

            Ok(())
        })
        .unwrap();

    // Print performance metrics
    #[cfg(feature = "metrics")]
    {
        let metrics = Metrics::from(&backtest);
        println!("{}", metrics);
    }
}

§Output:

=== Backtest Metrics ===
Initial Balance: 10000.00
Final Balance: 10018.00
Max Drawdown: 0.20%
Profit Factor: 2.00
Sharpe Ratio: 1.50
Win Rate: 100.00%

§Use Cases

  • Retail Traders: Test manual strategies before risking real capital.
  • Algo Developers: Build and optimize automated trading systems.
  • Quant Researchers: Backtest statistical arbitrage or machine learning models.
  • Educational: Teach trading concepts with a hands-on tool.

§Integrations

CratePurpose
taTechnical analysis indicators (EMA, RSI, MACD, etc.).
rayonParallel processing for optimization.
serdeSerialize/deserialize backtest results.
plottersVisualize equity curves and indicators.

§Error Handling

BTS uses custom error types to handle:

  • Insufficient balance.
  • Invalid order types.
  • Missing data (e.g., candles, positions).

Example:

use bts::prelude::*;
use chrono::DateTime;

fn main() {
    let candle = CandleBuilder::builder()
        .open(100.0)
        .high(110.0)
        .low(95.0)
        .close(105.0)
        .volume(1.0)
        .bid(0.5)
        .open_time(DateTime::default())
        .close_time(DateTime::default())
        .build()
        .unwrap();

    // Initialize backtest with \$10,000
    let mut backtest = Backtest::new(vec![candle], 10_000.0, None).unwrap();

    // Execute a market buy order
    backtest
        .run(|bt, _candle| {
            let order: Order = (OrderType::Market(102.0), 1.0, OrderSide::Buy).into();
            match bt.place_order(order) {
               Ok(_) => println!("Order in the pool!"),
               Err(_) => eprintln!("Error to place an order")
            }
            Ok(())
        })
        .unwrap();
}

§Contributing

Contributions are welcome! See CONTRIBUTING.md.

§License

MIT

Modules§

engine
Core trading engine components: orders, positions, wallet, and backtest logic. Core trading engine components.
errors
Error types for the library. Error types for the BTS library.
metrics
Performance metrics: drawdown, Sharpe ratio, win rate, etc. Performance metrics for backtesting.
optimizer
Strategy parameter optimization. Strategy parameter optimization.
prelude
Re-exports of commonly used types and traits for convenience.

Traits§

PercentCalculus
Trait for performing percentage-based calculations.