avin_core 0.4.0

Core of the 'avin' library
Documentation
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
/*****************************************************************************
 * URL:         http://avin.info
 * AUTHOR:      Alex Avin
 * E-MAIL:      mr.alexavin@gmail.com
 * LICENSE:     MIT
 ****************************************************************************/

use bitcode::{Decode, Encode};
use chrono::{DateTime, TimeDelta, Utc};

use crate::{Direction, Iid, Order, PostedStopOrder};

/// List for selecting the trade type.
///
/// # ru
/// Перечисление для выбора типа трейда.
#[derive(Debug, Clone, PartialEq, Encode, Decode)]
pub enum TradeKind {
    Long,
    Short,
}
impl TradeKind {
    pub fn to_str(&self) -> &'static str {
        match self {
            TradeKind::Long => "L",
            TradeKind::Short => "S",
        }
    }
}
impl std::fmt::Display for TradeKind {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            TradeKind::Long => write!(f, "Long"),
            TradeKind::Short => write!(f, "Short"),
        }
    }
}

/// Group of orders and operations with one position.
///
/// # ru
/// Отдельные ордера и операции по ним объединяются в трейд. Трейд
/// считается открытым, когда совершается первая сделка по бумаге. Этот
/// трейд будет закрыт, когда на счету будет ноль бумаг. Трейд суммирует
/// все операции между открытием и закрытием позиции.
///
/// Статус трейда реализован идиоматичным для Rust путем - через
/// отдельные типы. Этим не очень удобно пользоваться, зато компилятор
/// следит за корректностью работы с трейдами. Например нельзя добавить
/// стоп или тейк к закрытому трейду. Получить результат трейда можно
/// только когда он закрыт и тп.
///
/// В реализации трейдов возможны изменения, поэтому подробной
/// документации по методам пока нет.
#[derive(Debug, PartialEq, Encode, Decode)]
pub enum Trade {
    New(NewTrade),
    Opened(OpenedTrade),
    Closed(ClosedTrade),
}
impl Trade {
    #[allow(clippy::new_ret_no_self)]
    pub fn new(
        ts_nanos: i64,
        strategy: &str,
        kind: TradeKind,
        iid: Iid,
    ) -> NewTrade {
        NewTrade {
            ts_nanos,
            strategy: strategy.to_string(),
            kind,
            iid,
        }
    }

    pub fn as_new(self) -> Option<NewTrade> {
        match self {
            Trade::New(t) => Some(t),
            Trade::Opened(_) => None,
            Trade::Closed(_) => None,
        }
    }
    pub fn as_opened(self) -> Option<OpenedTrade> {
        match self {
            Trade::New(_) => None,
            Trade::Opened(t) => Some(t),
            Trade::Closed(_) => None,
        }
    }
    pub fn as_closed(self) -> Option<ClosedTrade> {
        match self {
            Trade::New(_) => None,
            Trade::Opened(_) => None,
            Trade::Closed(t) => Some(t),
        }
    }

    pub fn is_new(&self) -> bool {
        matches!(self, Trade::New(_))
    }
    pub fn is_opened(&self) -> bool {
        matches!(self, Trade::Opened(_))
    }
    pub fn is_closed(&self) -> bool {
        matches!(self, Trade::Closed(_))
    }
}
impl std::fmt::Display for Trade {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::New(t) => write!(f, "{t}"),
            Self::Opened(t) => write!(f, "{t}"),
            Self::Closed(t) => write!(f, "{t}"),
        }
    }
}

#[derive(Debug, PartialEq, Encode, Decode)]
pub struct NewTrade {
    pub ts_nanos: i64,
    pub strategy: String,
    pub kind: TradeKind,
    pub iid: Iid,
}
impl NewTrade {
    pub fn open(self, filled_order: Order) -> OpenedTrade {
        if !filled_order.is_filled() {
            panic!("order shoud be filled")
        }
        OpenedTrade {
            ts_nanos: self.ts_nanos,
            strategy: self.strategy,
            kind: self.kind,
            iid: self.iid,
            orders: vec![filled_order],

            stop_loss: None,
            take_profit: None,
        }
    }
}
impl std::fmt::Display for NewTrade {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "NewTrade={} {} {} {}",
            self.ts_nanos, self.strategy, self.kind, self.iid
        )
    }
}

#[derive(Debug, PartialEq, Encode, Decode)]
pub struct OpenedTrade {
    pub ts_nanos: i64,
    pub strategy: String,
    pub kind: TradeKind,
    pub iid: Iid,
    pub orders: Vec<Order>,

    pub stop_loss: Option<PostedStopOrder>,
    pub take_profit: Option<PostedStopOrder>,
}
impl OpenedTrade {
    pub fn add_order(&mut self, filled_order: Order) {
        if !filled_order.is_filled() {
            panic!("order shoud be filled")
        }

        self.orders.push(filled_order)
    }
    pub fn set_stop(&mut self, stop_order: PostedStopOrder) {
        self.stop_loss = Some(stop_order);
    }
    pub fn set_take(&mut self, stop_order: PostedStopOrder) {
        self.take_profit = Some(stop_order);
    }
    pub fn close(self) -> ClosedTrade {
        let trade = ClosedTrade {
            ts_nanos: self.ts_nanos,
            strategy: self.strategy,
            kind: self.kind,
            iid: self.iid,
            orders: self.orders,
            stop_loss: self.stop_loss,
            take_profit: self.take_profit,
        };

        // NOTE: проверка что трейд действительно закрыт
        // количество активов в позиции = 0
        if trade.quantity() != 0 {
            panic!("in closed trade quantity != 0");
        }
        trade
    }

    pub fn is_long(&self) -> bool {
        self.kind == TradeKind::Long
    }
    pub fn is_short(&self) -> bool {
        self.kind == TradeKind::Short
    }

    pub fn lots(&self) -> i32 {
        self.quantity() / self.iid.lot() as i32
    }
    pub fn quantity(&self) -> i32 {
        let mut total: i32 = 0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => continue,
            };
            if *order.direction() == Direction::Buy {
                total += op.quantity
            } else {
                total -= op.quantity
            }
        }

        total
    }
    pub fn buy_quantity(&self) -> i32 {
        let mut total: i32 = 0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => continue,
            };
            if *order.direction() == Direction::Buy {
                total += op.quantity
            }
        }

        total
    }
    pub fn sell_quantity(&self) -> i32 {
        let mut total: i32 = 0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => continue,
            };
            if *order.direction() == Direction::Sell {
                total += op.quantity
            }
        }

        total
    }

    pub fn value(&self) -> f64 {
        let mut total: f64 = 0.0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => continue,
            };
            if *order.direction() == Direction::Buy {
                total += op.value
            } else {
                total -= op.value
            }
        }

        total
    }
    pub fn buy_value(&self) -> f64 {
        let mut total: f64 = 0.0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => continue,
            };
            if *order.direction() == Direction::Buy {
                total += op.value
            }
        }

        total
    }
    pub fn sell_value(&self) -> f64 {
        let mut total: f64 = 0.0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => continue,
            };
            if *order.direction() == Direction::Sell {
                total += op.value
            }
        }

        total
    }

    pub fn avg(&self) -> f64 {
        if self.is_long() {
            self.buy_avg()
        } else {
            self.sell_avg()
        }
    }
    pub fn buy_avg(&self) -> f64 {
        self.buy_value() / self.buy_quantity() as f64
    }
    pub fn sell_avg(&self) -> f64 {
        self.sell_value() / self.sell_quantity() as f64
    }
}
impl std::fmt::Display for OpenedTrade {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "OpenedTrade={} {} {} {}",
            self.ts_nanos, self.strategy, self.kind, self.iid
        )
    }
}

#[derive(Debug, PartialEq, Encode, Decode)]
pub struct ClosedTrade {
    pub ts_nanos: i64,
    pub strategy: String,
    pub kind: TradeKind,
    pub iid: Iid,
    pub orders: Vec<Order>,
    pub stop_loss: Option<PostedStopOrder>,
    pub take_profit: Option<PostedStopOrder>,
}
impl ClosedTrade {
    pub fn is_long(&self) -> bool {
        self.kind == TradeKind::Long
    }
    pub fn is_short(&self) -> bool {
        self.kind == TradeKind::Short
    }
    pub fn is_win(&self) -> bool {
        todo!();
    }
    pub fn is_loss(&self) -> bool {
        todo!();
    }

    pub fn lots(&self) -> i32 {
        self.quantity() / self.iid.lot() as i32
    }
    pub fn quantity(&self) -> i32 {
        let mut total: i32 = 0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => panic!("in closed trade all orders must be filled"),
            };
            if *order.direction() == Direction::Buy {
                total += op.quantity
            } else {
                total -= op.quantity
            }
        }

        total
    }
    pub fn buy_quantity(&self) -> i32 {
        let mut total: i32 = 0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => panic!("in closed trade all orders must be filled"),
            };
            if *order.direction() == Direction::Buy {
                total += op.quantity
            }
        }

        total
    }
    pub fn sell_quantity(&self) -> i32 {
        let mut total: i32 = 0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => panic!("in closed trade all orders must be filled"),
            };
            if *order.direction() == Direction::Sell {
                total += op.quantity
            }
        }

        total
    }

    pub fn value(&self) -> f64 {
        let mut total: f64 = 0.0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => panic!("in closed trade all orders must be filled"),
            };
            if *order.direction() == Direction::Buy {
                total += op.value
            } else {
                total -= op.value
            }
        }

        total
    }
    pub fn buy_value(&self) -> f64 {
        let mut total: f64 = 0.0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => panic!("in closed trade all orders must be filled"),
            };
            if *order.direction() == Direction::Buy {
                total += op.value
            }
        }

        total
    }
    pub fn sell_value(&self) -> f64 {
        let mut total: f64 = 0.0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => panic!("in closed trade all orders must be filled"),
            };
            if *order.direction() == Direction::Sell {
                total += op.value
            }
        }

        total
    }

    pub fn commission(&self) -> f64 {
        let mut total: f64 = 0.0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => panic!("in closed trade all orders must be filled"),
            };
            total += op.commission
        }

        total
    }
    pub fn buy_commission(&self) -> f64 {
        let mut total: f64 = 0.0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => panic!("in closed trade all orders must be filled"),
            };
            if *order.direction() == Direction::Buy {
                total += op.commission
            }
        }

        total
    }
    pub fn sell_commission(&self) -> f64 {
        let mut total: f64 = 0.0;

        for order in self.orders.iter() {
            let op = match order.operation() {
                Some(op) => op,
                None => panic!("in closed trade all orders must be filled"),
            };
            if *order.direction() == Direction::Sell {
                total += op.commission
            }
        }

        total
    }

    pub fn avg(&self) -> f64 {
        match self.kind {
            TradeKind::Long => self.buy_avg(),
            TradeKind::Short => self.sell_avg(),
        }
    }
    pub fn buy_avg(&self) -> f64 {
        self.buy_value() / self.buy_quantity() as f64
    }
    pub fn sell_avg(&self) -> f64 {
        self.sell_value() / self.sell_quantity() as f64
    }

    pub fn dt(&self) -> DateTime<Utc> {
        DateTime::from_timestamp_nanos(self.ts_nanos)
    }
    pub fn open_dt(&self) -> DateTime<Utc> {
        let o = self.orders.first().unwrap();
        match o.operation() {
            Some(operation) => operation.dt(),
            None => panic!("closed trade without operation in order"),
        }
    }
    pub fn open_ts(&self) -> i64 {
        let o = self.orders.first().unwrap();
        match o.operation() {
            Some(operation) => operation.ts_nanos,
            None => panic!("closed trade without operation in order"),
        }
    }
    pub fn close_dt(&self) -> DateTime<Utc> {
        let o = self.orders.last().unwrap();
        match o.operation() {
            Some(operation) => operation.dt(),
            None => panic!("closed trade without operation in order"),
        }
    }
    pub fn close_ts(&self) -> i64 {
        let o = self.orders.last().unwrap();
        match o.operation() {
            Some(operation) => operation.ts_nanos,
            None => panic!("closed trade without operation in order"),
        }
    }
    pub fn timedelta(&self) -> TimeDelta {
        self.close_dt() - self.open_dt()
    }
    pub fn result(&self) -> f64 {
        self.sell_value() - self.buy_value() - self.commission()
    }
    pub fn result_p(&self) -> f64 {
        self.result() / self.buy_value() * 100.0
    }
    pub fn speed(&self) -> f64 {
        // NOTE: если таймдельту перевести сразу в дни то
        // для трейдов короче одного дня там будет 0.
        // поэтому смотрю на количество минут трейда, делю на 60 и 24
        // получается например 600 / 60 / 24 = 0.42 дня.
        // Беру результат трейда в процентах и делю на это число
        // в итоге получается количество рублей в день
        // используется для сравнения эффективности трейдов с учетом
        // времени которое деньги были заняты в этом трейде.
        self.result() / (self.timedelta().num_minutes() as f64 / 60.0 / 24.0)
    }
    pub fn speed_p(&self) -> f64 {
        // NOTE: если таймдельту перевести сразу в дни то
        // для трейдов короче одного дня там будет 0.
        // поэтому смотрю на количество минут трейда, делю на 60 и 24
        // получается например 600m трейд / 60 / 24 = 0.42 дня.
        // Беру результат трейда в процентах и делю на это число
        // в итоге получается количество процентов в день
        // используется для сравнения эффективности трейдов с учетом
        // времени которое деньги были заняты в этом трейде.
        self.result_p()
            / (self.timedelta().num_minutes() as f64 / 60.0 / 24.0)
    }
}
impl std::fmt::Display for ClosedTrade {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "ClosedTrade={} {} {} {} = {}",
            self.dt(),
            self.strategy,
            self.kind,
            self.iid.ticker(),
            self.result()
        )
    }
}

#[cfg(test)]
mod tests {
    use crate::*;
    use chrono::{TimeZone, Utc};

    #[test]
    fn statuses() {
        // create trade
        let iid = Manager::find_iid("moex_share_sber").unwrap();
        let dt = Utc.with_ymd_and_hms(2025, 4, 5, 14, 50, 0).unwrap();
        let ts = dt.timestamp_nanos_opt().unwrap();
        let trade =
            Trade::new(ts, "Trend T3 Posterior v1", TradeKind::Long, iid);
        assert_eq!(trade.ts_nanos, ts);
        assert_eq!(trade.strategy, "Trend T3 Posterior v1");
        assert_eq!(trade.iid.ticker(), "SBER");

        // open trade - add first filled order
        let order = LimitOrder::new(Direction::Buy, 10, 301.0);
        let mut order = order.post("broker_id=100500");
        let tr = Transaction::new(100, 301.0);
        order.add_transaction(tr);
        let ts = 0;
        let order = order.fill(ts, 3.0);
        let mut trade = trade.open(Order::Limit(LimitOrder::Filled(order)));
        assert_eq!(trade.orders.len(), 1);

        // add second filled order
        let order = LimitOrder::new(Direction::Sell, 10, 311.0);
        let mut order = order.post("broker_id=100501");
        let tr = Transaction::new(100, 311.0);
        order.add_transaction(tr);
        let ts = time_unit::TimeUnit::Days.get_unit_nanoseconds() as i64;
        let order = order.fill(ts, 3.0);
        trade.add_order(Order::Limit(LimitOrder::Filled(order)));
        assert_eq!(trade.orders.len(), 2);

        // close trade
        let trade = trade.close();
        assert_eq!(trade.result(), 994.0);
        assert!(trade.result_p() > 3.3);
        assert_eq!(trade.timedelta().num_seconds(), 86400); // сутки
        assert!(trade.speed() > 990.0);
        assert!(trade.speed_p() > 3.3);
    }
    #[test]
    #[should_panic]
    fn close_unclosed_trade() {
        // create trade
        let iid = Manager::find_iid("moex_share_sber").unwrap();
        let dt = Utc.with_ymd_and_hms(2025, 4, 5, 14, 50, 0).unwrap();
        let ts = dt.timestamp_nanos_opt().unwrap();
        let trade =
            Trade::new(ts, "Trend T3 Posterior v1", TradeKind::Long, iid);
        assert_eq!(trade.ts_nanos, ts);
        assert_eq!(trade.strategy, "Trend T3 Posterior v1");
        assert_eq!(trade.iid.ticker(), "SBER");

        // open trade - add first filled order
        let order = LimitOrder::new(Direction::Buy, 10, 301.0);
        let mut order = order.post("broker_id=100500");
        let tr = Transaction::new(100, 301.0);
        order.add_transaction(tr);
        let order = order.fill(100500, 3.0);
        let trade = trade.open(Order::Limit(LimitOrder::Filled(order)));
        assert_eq!(trade.orders.len(), 1);

        // try close opened trade - should_panic
        let _ = trade.close();
    }
}