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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
use crate::{
Timed,
statistic::metric::drawdown::{
Drawdown, DrawdownGenerator,
max::{MaxDrawdown, MaxDrawdownGenerator},
mean::{MeanDrawdown, MeanDrawdownGenerator},
},
};
use chrono::{DateTime, Utc};
use rustrade_execution::balance::{AssetBalance, Balance};
use rustrade_integration::collection::snapshot::Snapshot;
use serde::{Deserialize, Serialize};
/// TearSheet summarising the trading session changes for an Asset.
#[derive(Debug, Clone, PartialEq, PartialOrd, Deserialize, Serialize)]
pub struct TearSheetAsset {
pub balance_end: Option<Balance>,
pub drawdown: Option<Drawdown>,
pub drawdown_mean: Option<MeanDrawdown>,
pub drawdown_max: Option<MaxDrawdown>,
}
/// Generator for an [`TearSheetAsset`].
#[derive(Debug, Clone, PartialEq, PartialOrd, Default, Deserialize, Serialize)]
pub struct TearSheetAssetGenerator {
pub balance_now: Option<Balance>,
pub drawdown: DrawdownGenerator,
pub drawdown_mean: MeanDrawdownGenerator,
pub drawdown_max: MaxDrawdownGenerator,
}
impl TearSheetAssetGenerator {
/// Initialise a [`TearSheetAssetGenerator`] from an initial `AssetState`.
pub fn init(initial: &Timed<Balance>) -> Self {
Self {
balance_now: Some(initial.value),
drawdown: DrawdownGenerator::init(Timed::new(initial.value.total, initial.time)),
drawdown_mean: MeanDrawdownGenerator::default(),
drawdown_max: MaxDrawdownGenerator::default(),
}
}
/// Update the [`TearSheetAssetGenerator`] from the next [`Snapshot`] [`AssetBalance`].
pub fn update_from_balance<AssetKey>(&mut self, balance: Snapshot<&AssetBalance<AssetKey>>) {
self.update_from_balance_parts(balance.value().balance, balance.value().time_exchange);
}
/// Update the [`TearSheetAssetGenerator`] from a [`Balance`] and its exchange timestamp.
///
/// The asset-key-free core of [`Self::update_from_balance`]; the generator tracks only `total`
/// drawdown and so never needs the asset identity. Lets callers that hold a balance without an
/// owned asset key (e.g. WS partial updates) avoid constructing a throwaway [`AssetBalance`].
///
/// `time_exchange` is expected to be non-decreasing across calls; the underlying
/// [`DrawdownGenerator`] tracks peak state and does not itself guard against out-of-order
/// timestamps (the engine applies a staleness gate before calling this). `pub(crate)`: an
/// internal helper for [`Self::update_from_balance`] and the engine's balance-apply path.
pub(crate) fn update_from_balance_parts(
&mut self,
balance: Balance,
time_exchange: DateTime<Utc>,
) {
self.balance_now = Some(balance);
if let Some(next_drawdown) = self
.drawdown
.update(Timed::new(balance.total, time_exchange))
{
self.drawdown_mean.update(&next_drawdown);
self.drawdown_max.update(&next_drawdown);
}
}
/// Generate the latest [`TearSheetAsset`].
pub fn generate(&mut self) -> TearSheetAsset {
let current_drawdown = self.drawdown.generate();
if let Some(drawdown) = ¤t_drawdown {
self.drawdown_mean.update(drawdown);
self.drawdown_max.update(drawdown);
}
TearSheetAsset {
balance_end: self.balance_now,
drawdown: current_drawdown,
drawdown_mean: self.drawdown_mean.generate(),
drawdown_max: self.drawdown_max.generate(),
}
}
/// Reset the internal state, using a new starting `Timed<Balance>` as seed.
pub fn reset(&mut self, balance_start: &Timed<Balance>) {
*self = Self::init(balance_start);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::time_plus_days;
use chrono::{DateTime, Utc};
use rust_decimal_macros::dec;
use rustrade_instrument::asset::AssetIndex;
fn balance(balance: Balance, time: DateTime<Utc>) -> AssetBalance<AssetIndex> {
AssetBalance {
asset: AssetIndex(0),
balance,
time_exchange: time,
}
}
fn duration_ms(start: DateTime<Utc>, end: DateTime<Utc>) -> i64 {
end.signed_duration_since(start).num_milliseconds()
}
#[test]
fn test_tear_sheet_asset_generator() {
struct TestCase {
input: AssetBalance<AssetIndex>,
expected: TearSheetAssetGenerator,
}
let base_time = DateTime::<Utc>::MIN_UTC;
let mut generator = TearSheetAssetGenerator::init(&Timed::new(
Balance::new(dec!(1.0), dec!(1.0)),
base_time,
));
let cases = vec![
// TC0: Balance increased from 1.0 peak, so no expected drawdowns
TestCase {
input: balance(
Balance::new(dec!(2.0), dec!(2.0)),
time_plus_days(base_time, 1),
),
expected: TearSheetAssetGenerator {
balance_now: Some(Balance::new(dec!(2.0), dec!(2.0))),
drawdown: DrawdownGenerator::init(Timed::new(
dec!(2.0),
time_plus_days(base_time, 1),
)),
drawdown_mean: MeanDrawdownGenerator::default(),
drawdown_max: MaxDrawdownGenerator::default(),
},
},
// TC1: Balance decreased, so expect a current drawdown only
TestCase {
input: balance(
Balance::new(dec!(1.5), dec!(1.5)),
time_plus_days(base_time, 2),
),
expected: TearSheetAssetGenerator {
balance_now: Some(Balance::new(dec!(1.5), dec!(1.5))),
drawdown: DrawdownGenerator {
peak: Some(dec!(2.0)),
drawdown_max: dec!(0.25), // (2.0 - 1.5) / 2.0,
time_peak: Some(time_plus_days(base_time, 1)),
time_now: time_plus_days(base_time, 2),
},
drawdown_mean: MeanDrawdownGenerator::default(),
drawdown_max: MaxDrawdownGenerator::default(),
},
},
// TC2: Further decrease - larger drawdown
TestCase {
input: balance(
Balance::new(dec!(1.0), dec!(1.0)),
time_plus_days(base_time, 3),
),
expected: TearSheetAssetGenerator {
balance_now: Some(Balance::new(dec!(1.0), dec!(1.0))),
drawdown: DrawdownGenerator {
peak: Some(dec!(2.0)),
drawdown_max: dec!(0.5), // (2.0 - 1.0) / 2.0
time_peak: Some(time_plus_days(base_time, 1)),
time_now: time_plus_days(base_time, 3),
},
drawdown_mean: MeanDrawdownGenerator::default(),
drawdown_max: MaxDrawdownGenerator::default(),
},
},
// TC3: Recovery above previous peak - should complete drawdown period
TestCase {
input: balance(
Balance::new(dec!(2.5), dec!(2.5)),
time_plus_days(base_time, 4),
),
expected: TearSheetAssetGenerator {
balance_now: Some(Balance::new(dec!(2.5), dec!(2.5))),
drawdown: DrawdownGenerator::init(Timed::new(
dec!(2.5),
time_plus_days(base_time, 4),
)),
drawdown_mean: MeanDrawdownGenerator {
count: 1,
mean_drawdown: Some(MeanDrawdown {
mean_drawdown: dec!(0.5), // Only one drawdown period completed
mean_drawdown_ms: duration_ms(
time_plus_days(base_time, 1),
time_plus_days(base_time, 4),
),
}),
},
drawdown_max: MaxDrawdownGenerator {
max: Some(MaxDrawdown(Drawdown {
value: dec!(0.5),
time_start: time_plus_days(base_time, 1),
time_end: time_plus_days(base_time, 4),
})),
},
},
},
// TC4: Small drawdown after new peak (2.5 -> 2.4)
TestCase {
input: balance(
Balance::new(dec!(2.4), dec!(2.4)),
time_plus_days(base_time, 5),
),
expected: TearSheetAssetGenerator {
balance_now: Some(Balance::new(dec!(2.4), dec!(2.4))),
drawdown: DrawdownGenerator {
peak: Some(dec!(2.5)),
drawdown_max: dec!(0.04), // (2.5 - 2.4) / 2.5
time_peak: Some(time_plus_days(base_time, 4)),
time_now: time_plus_days(base_time, 5),
},
drawdown_mean: MeanDrawdownGenerator {
count: 1,
mean_drawdown: Some(MeanDrawdown {
mean_drawdown: dec!(0.5), // Only one drawdown period completed
mean_drawdown_ms: duration_ms(
time_plus_days(base_time, 1),
time_plus_days(base_time, 4),
),
}),
},
drawdown_max: MaxDrawdownGenerator {
max: Some(MaxDrawdown(Drawdown {
value: dec!(0.5),
time_start: time_plus_days(base_time, 1),
time_end: time_plus_days(base_time, 4),
})),
},
},
},
// TC5: Equal to previous value - drawdown continues
TestCase {
input: balance(
Balance::new(dec!(2.4), dec!(2.4)),
time_plus_days(base_time, 6),
),
expected: TearSheetAssetGenerator {
balance_now: Some(Balance::new(dec!(2.4), dec!(2.4))),
drawdown: DrawdownGenerator {
peak: Some(dec!(2.5)),
drawdown_max: dec!(0.04), // (2.5 - 2.4) / 2.5
time_peak: Some(time_plus_days(base_time, 4)),
time_now: time_plus_days(base_time, 6),
},
drawdown_mean: MeanDrawdownGenerator {
count: 1,
mean_drawdown: Some(MeanDrawdown {
mean_drawdown: dec!(0.5), // Only one drawdown period completed
mean_drawdown_ms: duration_ms(
time_plus_days(base_time, 1),
time_plus_days(base_time, 4),
),
}),
},
drawdown_max: MaxDrawdownGenerator {
max: Some(MaxDrawdown(Drawdown {
value: dec!(0.5),
time_start: time_plus_days(base_time, 1),
time_end: time_plus_days(base_time, 4),
})),
},
},
},
// TC6: Tiny change, but still in drawdown - retain max drawdown from current period
TestCase {
input: balance(
Balance::new(dec!(2.41), dec!(2.41)),
time_plus_days(base_time, 7),
),
expected: TearSheetAssetGenerator {
balance_now: Some(Balance::new(dec!(2.41), dec!(2.41))),
drawdown: DrawdownGenerator {
peak: Some(dec!(2.5)),
drawdown_max: dec!(0.04), // (2.5 - 2.4) / 2.5
time_peak: Some(time_plus_days(base_time, 4)),
time_now: time_plus_days(base_time, 7),
},
drawdown_mean: MeanDrawdownGenerator {
count: 1,
mean_drawdown: Some(MeanDrawdown {
mean_drawdown: dec!(0.5), // Only one drawdown period completed
mean_drawdown_ms: duration_ms(
time_plus_days(base_time, 1),
time_plus_days(base_time, 4),
),
}),
},
drawdown_max: MaxDrawdownGenerator {
max: Some(MaxDrawdown(Drawdown {
value: dec!(0.5),
time_start: time_plus_days(base_time, 1),
time_end: time_plus_days(base_time, 4),
})),
},
},
},
// TC7: recovery above previous peak - should complete drawdown period
TestCase {
input: balance(
Balance::new(dec!(3.0), dec!(3.0)),
time_plus_days(base_time, 8),
),
expected: TearSheetAssetGenerator {
balance_now: Some(Balance::new(dec!(3.0), dec!(3.0))),
drawdown: DrawdownGenerator::init(Timed::new(
dec!(3.0),
time_plus_days(base_time, 8),
)),
drawdown_mean: MeanDrawdownGenerator {
count: 2,
mean_drawdown: Some(MeanDrawdown {
mean_drawdown: dec!(0.27), // (0.5 + 0.04) / 2
mean_drawdown_ms: (duration_ms(
time_plus_days(base_time, 1),
time_plus_days(base_time, 4),
) + duration_ms(
time_plus_days(base_time, 4),
time_plus_days(base_time, 8),
)) / 2,
}),
},
drawdown_max: MaxDrawdownGenerator {
max: Some(MaxDrawdown(Drawdown {
value: dec!(0.5),
time_start: time_plus_days(base_time, 1),
time_end: time_plus_days(base_time, 4),
})),
},
},
},
];
for (index, test) in cases.into_iter().enumerate() {
generator.update_from_balance(Snapshot(&test.input));
assert_eq!(generator, test.expected, "TC{index} failed");
}
}
}