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
use crate::event::Event;

use crate::data::{MarketEvent, MarketMeta};
use crate::strategy::{Decision, SignalEvent, SignalForceExit};
use crate::execution::FillEvent;
use crate::portfolio::error::PortfolioError;
use crate::portfolio::position::PositionUpdate;
use chrono::{DateTime, Utc};
use uuid::Uuid;
use serde::{Deserialize, Serialize};

/// Logic for [`OrderEvent`] quantity allocation.
pub mod allocator;

/// Barter portfolio module specific errors.
pub mod error;

/// Core Portfolio logic containing an implementation of [`MarketUpdater`],
/// [`OrderGenerator`] and [`FillUpdater`]. Utilises the risk and allocator logic to optimise
/// [`OrderEvent`] generation.
pub mod portfolio;

/// Data structures encapsulating the state of a trading [`Position`], as well as the logic for
/// entering, updating and exiting them.
pub mod position;

/// Repositories for persisting Portfolio state.
pub mod repository;

/// Logic for evaluating the risk associated with a proposed [`OrderEvent`].
pub mod risk;

/// Updates the Portfolio from an input [`MarketEvent`].
pub trait MarketUpdater {
    /// Determines if the Portfolio has an open Position relating to the input [`MarketEvent`]. If
    /// so it updates it using the market data, and returns a [`PositionUpdate`] detailing the
    /// changes.
    fn update_from_market(
        &mut self,
        market: &MarketEvent,
    ) -> Result<Option<PositionUpdate>, PortfolioError>;
}

/// May generate an [`OrderEvent`] from an input advisory [`SignalEvent`].
pub trait OrderGenerator {
    /// May generate an [`OrderEvent`] after analysing an input advisory [`SignalEvent`].
    fn generate_order(
        &mut self,
        signal: &SignalEvent,
    ) -> Result<Option<OrderEvent>, PortfolioError>;

    /// Generates an exit [`OrderEvent`] if there is an open [`Position`] associated with the
    /// input [`SignalForceExit`]'s [`PositionId`].
    fn generate_exit_order(
        &mut self,
        signal: SignalForceExit,
    ) -> Result<Option<OrderEvent>, PortfolioError>;
}

/// Updates the Portfolio from an input [`FillEvent`].
pub trait FillUpdater {
    /// Updates the Portfolio state using the input [`FillEvent`]. The [`FillEvent`] triggers a
    /// Position entry or exit, and the Portfolio updates key fields such as current_cash and
    /// current_value accordingly.
    fn update_from_fill(
        &mut self,
        fill: &FillEvent,
    ) -> Result<Vec<Event>, PortfolioError>;
}

/// Orders are generated by the portfolio and details work to be done by an Execution handler to
/// open a trade.
#[derive(Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
pub struct OrderEvent {
    pub event_type: &'static str,
    pub trace_id: Uuid,
    pub timestamp: DateTime<Utc>,
    pub exchange: &'static str,
    pub symbol: String,
    /// Metadata propagated from source MarketEvent
    pub market_meta: MarketMeta,
    /// LONG, CloseLong, SHORT or CloseShort
    pub decision: Decision,
    /// +ve or -ve Quantity depending on Decision
    pub quantity: f64,
    /// MARKET, LIMIT etc
    pub order_type: OrderType,
}

impl OrderEvent {
    pub const ORGANIC_ORDER: &'static str = "Order";
    pub const FORCED_EXIT_ORDER: &'static str = "OrderForcedExit";

    /// Returns a OrderEventBuilder instance.
    pub fn builder() -> OrderEventBuilder {
        OrderEventBuilder::new()
    }
}

/// Type of order the portfolio wants the execution::handler to place.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, Deserialize, Serialize)]
pub enum OrderType {
    Market,
    Limit,
    Bracket,
}

impl Default for OrderType {
    fn default() -> Self {
        Self::Market
    }
}

/// Builder to construct OrderEvent instances.
#[derive(Debug, Default)]
pub struct OrderEventBuilder {
    pub event_type: Option<&'static str>,
    pub trace_id: Option<Uuid>,
    pub timestamp: Option<DateTime<Utc>>,
    pub exchange: Option<&'static str>,
    pub symbol: Option<String>,
    pub market_meta: Option<MarketMeta>,
    pub decision: Option<Decision>,
    pub quantity: Option<f64>,
    pub order_type: Option<OrderType>,
}

impl OrderEventBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn event_type(self, value: &'static str) -> Self {
        Self {
            event_type: Some(value),
            ..self
        }
    }

    pub fn trace_id(self, value: Uuid) -> Self {
        Self {
            trace_id: Some(value),
            ..self
        }
    }

    pub fn timestamp(self, value: DateTime<Utc>) -> Self {
        Self {
            timestamp: Some(value),
            ..self
        }
    }

    pub fn exchange(self, value: &'static str) -> Self {
        Self {
            exchange: Some(value),
            ..self
        }
    }

    pub fn symbol(self, value: String) -> Self {
        Self {
            symbol: Some(value),
            ..self
        }
    }

    pub fn market_meta(self, value: MarketMeta) -> Self {
        Self {
            market_meta: Some(value),
            ..self
        }
    }

    pub fn decision(self, value: Decision) -> Self {
        Self {
            decision: Some(value),
            ..self
        }
    }

    pub fn quantity(self, value: f64) -> Self {
        Self {
            quantity: Some(value),
            ..self
        }
    }

    pub fn order_type(self, value: OrderType) -> Self {
        Self {
            order_type: Some(value),
            ..self
        }
    }

    pub fn build(self) -> Result<OrderEvent, PortfolioError> {
        Ok(OrderEvent {
            event_type: self.event_type.unwrap_or(OrderEvent::ORGANIC_ORDER),
            trace_id: self.trace_id.ok_or(PortfolioError::BuilderIncomplete)?,
            timestamp: self.timestamp.ok_or(PortfolioError::BuilderIncomplete)?,
            exchange: self.exchange.ok_or(PortfolioError::BuilderIncomplete)?,
            symbol: self.symbol.ok_or(PortfolioError::BuilderIncomplete)?,
            market_meta: self.market_meta.ok_or(PortfolioError::BuilderIncomplete)?,
            decision: self.decision.ok_or(PortfolioError::BuilderIncomplete)?,
            quantity: self.quantity.ok_or(PortfolioError::BuilderIncomplete)?,
            order_type: self.order_type.ok_or(PortfolioError::BuilderIncomplete)?,
        })
    }
}

/// Communicates a String represents a unique identifier for an Engine's Portfolio [`Balance`].
pub type BalanceId = String;

/// Total and available balance at a point in time.
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug, Deserialize, Serialize)]
pub struct Balance {
    pub timestamp: DateTime<Utc>,
    pub total: f64,
    pub available: f64,
}

impl Default for Balance {
    fn default() -> Self {
        Self {
            timestamp: Utc::now(),
            total: 0.0,
            available: 0.0
        }
    }
}

impl Balance {
    /// Construct a new [`Balance`] using the provided total & available balance values.
    pub fn new(timestamp: DateTime<Utc>, total: f64, available: f64) -> Self {
        Self {
            timestamp,
            total,
            available,
        }
    }

    /// Returns the unique identifier for an Engine's [`Balance`].
    pub fn balance_id(engine_id: Uuid) -> BalanceId {
        format!("{}_balance", engine_id)
    }
}