openpine_vm/strategy/
order.rs

1use num_enum::TryFromPrimitive;
2use openpine_macros::Enum;
3use serde::{Deserialize, Serialize};
4
5/// Trade direction used by strategies.
6#[derive(
7    Debug,
8    Hash,
9    Eq,
10    PartialEq,
11    Ord,
12    PartialOrd,
13    Copy,
14    Clone,
15    Serialize,
16    Deserialize,
17    TryFromPrimitive,
18)]
19#[repr(i32)]
20pub enum Direction {
21    /// Long position / buy direction.
22    Long = 0,
23    /// Short position / sell direction.
24    Short = 1,
25}
26
27impl Direction {
28    #[inline]
29    pub(crate) fn quantity(&self, quantity: f64) -> f64 {
30        match self {
31            Direction::Long => quantity,
32            Direction::Short => -quantity,
33        }
34    }
35
36    #[inline]
37    pub(crate) fn from_quantity(quantity: f64) -> Self {
38        match quantity {
39            q if q > 0.0 => Direction::Long,
40            q if q < 0.0 => Direction::Short,
41            _ => unreachable!(),
42        }
43    }
44
45    #[inline]
46    pub(crate) fn opposite(&self) -> Self {
47        match self {
48            Direction::Long => Direction::Short,
49            Direction::Short => Direction::Long,
50        }
51    }
52
53    #[inline]
54    pub(crate) fn value(&self) -> f64 {
55        match self {
56            Direction::Long => 1.0,
57            Direction::Short => -1.0,
58        }
59    }
60}
61
62#[derive(Debug, Hash, Eq, PartialEq, Copy, Clone, Enum, Serialize, Deserialize)]
63#[repr(i32)]
64pub(crate) enum AllowEntryIn {
65    Long,
66    Short,
67    Both,
68}
69
70impl AllowEntryIn {
71    #[inline]
72    pub(crate) fn is_allow(&self, direction: Direction) -> bool {
73        match self {
74            AllowEntryIn::Long => direction == Direction::Long,
75            AllowEntryIn::Short => direction == Direction::Short,
76            AllowEntryIn::Both => true,
77        }
78    }
79}