1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
//! # 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 popular indicators crates 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
//!
//! | Component | Description |
//! |---------------- |----------------------------------------------------------------------------------|
//! | **`Metrics`** | Calculates performance metrics: P&L, drawdown, Sharpe ratio, win rate, and more. |
//! | **`Optimizer`** | Calculates bests parameters *(indicators, RR, etc...)*. |
//! | **`Draw`** | Draw candlestick data, balance and metrics to a *SVG* or *PNG* file. |
//! | **`Backtest`** | The engine that simulates strategy execution over historical data. |
//!
//! ## Features
//!
//! ### 1. **Technical Indicators**
//! - Compatible with indicators crates like the [`ta`](https://crates.io/crates/ta) crate for 100+ additional indicators.
//!
//! ### 2. **Order Types & Exit Rules**
//!
//! | Order Type | Description |
//! |-----------------------------|---------------------------------------------------------------|
//! | **Market Order** | Executes immediately at the current price. |
//! | **Limit Order** | Executes only at a specified price or better. |
//! | **Take-Profit** | Closes the position when a target price is reached. |
//! | **Stop-Loss** | Closes the position to limit losses. |
//! | **Trailing Stop** | Dynamically adjusts the stop price based on market movements. |
//! | **Take-Profit + Stop-Loss** | Combines both rules for risk management. |
//!
//! ### 3. **Performance Metrics**
//!
//! | Metric | Description |
//! |----------------------|--------------------------------------------------------|
//! | **Max Drawdown** | Largest peak-to-trough decline in account balance (%). |
//! | **Profit Factor** | Ratio of gross profits to gross losses. |
//! | **Sharpe Ratio** | Risk-adjusted return (higher = better). |
//! | **Win Rate** | Percentage of winning trades. |
//!
//! ### 4. **Optimization Tools**
//!
//! - **Parallelize**: Optimize strategy parameters (e.g., EMA periods) using multi-threading.
//!
//! ## Getting Started
//!
//! ### 1. Add BTS to your project:
//! ```toml
//! [dependencies]
//! bts_rs = "1.0.11"
//! ta = "0.5.0" # Optional: For technical analysis indicators
//! ```
//!
//! ### 2. Run a Simple Backtest:
//! ```rust
//! use std::sync::Arc;
//!
//! use bts_rs::prelude::*;
//! use chrono::{DateTime, Duration};
//!
//! 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() + Duration::days(1))
//! .build()
//! .unwrap();
//!
//! // Initialize backtest with \$10,000
//! let mut backtest = Backtest::new(Arc::from_iter(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(candle, order).unwrap();
//! // Close the position at \$104.0
//! if let Some(position) = bt.positions().last().cloned() {
//! bt.close_position(candle, &position, 104.0, true).unwrap();
//! }
//! Ok(())
//! })
//! .unwrap();
//!
//! // Print performance metrics
//! #[cfg(feature = "metrics")]
//! {
//! let metrics = Metrics::from(&backtest);
//! println!("{}", metrics);
//! }
//! ```
//!
//! ### Output:
//!
//! ```bash
//! === Backtest Metrics ===
//! Initial Balance: 10000.00
//! Final Balance: 10018.00
//! Profit & Loss (P&L): 0.00
//! Fees paid: 0.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
//!
//! | Crate | Purpose |
//! |-------------------------------------------------|-------------------------------------------------------------------|
//! | [`rayon`](https://crates.io/crates/rayon) | Parallel processing for optimization. |
//! | [`serde`](https://crates.io/crates/serde) | Serialize/deserialize backtest results. |
//! | [`plotters`](https://crates.io/crates/plotters) | Visualize market candlesticks data, equity curves and indicators. |
//!
//! ## Error Handling
//!
//! BTS uses custom error types to handle:
//! - Insufficient balance.
//! - Invalid order types.
//! - Missing data (e.g., candles, positions) and more.
//!
//! Example:
//! ```rust
//! use std::sync::Arc;
//!
//! use bts_rs::prelude::*;
//! use chrono::{DateTime, Duration};
//!
//! 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() + Duration::days(1))
//! .build()
//! .unwrap();
//!
//! // Initialize backtest with \$10,000
//! let mut backtest = Backtest::new(Arc::from_iter(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(candle, order) {
//! Ok(_) => println!("Order in the pool!"),
//! Err(_) => eprintln!("Error to place an order")
//! }
//! Ok(())
//! })
//! .unwrap();
//! ```
//!
//! ## Contributing
//!
//! Contributions are welcome! See [`CONTRIBUTING.md`](https://github.com/raonagos/bts-rs/blob/master/CONTRIBUTING.md).
//!
//! ## License
//!
//! The project is licensed under the [`MIT`](https://github.com/raonagos/bts-rs/blob/master/LICENSE).
/// Core trading engine components: orders, positions, wallet, and backtest logic.
/// Error types for the library.
/// Utility functions and helpers.
/// Performance metrics: drawdown, Sharpe ratio, win rate, etc.
/// Strategy parameter optimization.
/// Module for visualizing backtest results and candle charts.
/// Re-exports of commonly used types and traits for convenience.
use ;
/// Trait for performing percentage-based calculations (human readable).
///
/// This trait provides methods to add, subtract, and calculate percentages
/// for numeric types, enabling common financial calculations.