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
use getset::Getters;
use tracing::trace;

use crate::{
    account::Account,
    account_tracker::AccountTracker,
    clearing_house::ClearingHouse,
    config::Config,
    market_state::MarketState,
    risk_engine::{IsolatedMarginRiskEngine, RiskEngine},
    types::{
        Currency, Error, ExchangeOrderMeta, Filled, LimitOrder, LimitOrderUpdate, MarginCurrency,
        MarketOrder, MarketUpdate, NewOrder, OrderError, OrderId, Pending, Result, Side,
        TimestampNs,
    },
};

/// The main leveraged futures exchange for simulated trading
#[derive(Debug, Clone, Getters)]
pub struct Exchange<A, Q, UserOrderId>
where
    Q: Currency,
    Q::PairedCurrency: MarginCurrency,
    UserOrderId: Clone + std::fmt::Debug + Eq + PartialEq + std::hash::Hash,
{
    /// The exchange configuration.
    #[getset(get = "pub")]
    config: Config<Q::PairedCurrency>,

    /// The current state of the simulated market.
    #[getset(get = "pub")]
    market_state: MarketState,

    /// The main user account.
    #[getset(get = "pub", get_mut = "mut")]
    account: Account<Q::PairedCurrency, UserOrderId>,

    /// A performance tracker for the user account.
    #[getset(get = "pub")]
    account_tracker: A,

    risk_engine: IsolatedMarginRiskEngine<Q::PairedCurrency>,

    clearing_house: ClearingHouse<A, Q::PairedCurrency, UserOrderId>,

    next_order_id: u64,
}

impl<A, Q, UserOrderId> Exchange<A, Q, UserOrderId>
where
    A: AccountTracker<Q::PairedCurrency>,
    Q: Currency,
    Q::PairedCurrency: MarginCurrency,
    UserOrderId: Clone + Eq + PartialEq + std::hash::Hash + std::fmt::Debug,
{
    /// Create a new Exchange with the desired config and whether to use candles
    /// as infomation source
    pub fn new(account_tracker: A, config: Config<Q::PairedCurrency>) -> Self {
        let market_state = MarketState::new(config.contract_specification().price_filter.clone());
        let account = Account::new(config.starting_balance(), config.initial_leverage());
        let risk_engine = IsolatedMarginRiskEngine::<Q::PairedCurrency>::new(
            config.contract_specification().clone(),
        );
        let clearing_house = ClearingHouse::new();

        Self {
            config,
            market_state,
            clearing_house,
            risk_engine,
            account,
            account_tracker,
            next_order_id: 0,
        }
    }

    /// Update the exchange state with new information
    ///
    /// ### Parameters:
    /// `timestamp_ns`: Is used in the AccountTracker `A`
    ///     and if setting order timestamps is enabled in the config.
    /// `market_update`: Newest market information
    ///
    /// ### Returns:
    /// If Ok, returns updates regarding limit orders, wether partially filled or fully.
    pub fn update_state<U>(
        &mut self,
        timestamp_ns: TimestampNs,
        market_update: U,
    ) -> Result<Vec<LimitOrderUpdate<Q, UserOrderId>>>
    where
        U: MarketUpdate<Q, UserOrderId>,
    {
        self.market_state
            .update_state(timestamp_ns, &market_update)?;
        self.account_tracker
            .update(timestamp_ns, &self.market_state, &self.account);
        if let Err(e) = self
            .risk_engine
            .check_maintenance_margin(&self.market_state, &self.account)
        {
            // TODO: liquidate position properly
            return Err(e.into());
        };

        // TODO: move into `Account`
        let mut changed_orders = Vec::new();
        for mut order in self.account.active_limit_orders.clone().values().cloned() {
            if let Some(filled_qty) = market_update.limit_order_filled(&order) {
                let qty = match order.side() {
                    Side::Buy => filled_qty,
                    Side::Sell => filled_qty.into_negative(),
                };
                self.clearing_house.settle_filled_order(
                    &mut self.account,
                    &mut self.account_tracker,
                    qty,
                    order.limit_price(),
                    self.config.contract_specification().fee_maker,
                    self.market_state.current_timestamp_ns(),
                );
                // Fill order and check if it is fully filled.
                if order.fill(order.limit_price(), filled_qty) {
                    let filled_order = order.clone().into_filled(order.limit_price(), timestamp_ns);
                    changed_orders.push(LimitOrderUpdate::FullyFilled(filled_order));
                    continue;
                }
                changed_orders.push(LimitOrderUpdate::PartiallyFilled(order.clone()));
            }
        }
        for update in changed_orders.iter() {
            match update {
                LimitOrderUpdate::FullyFilled(limit_order) => {
                    self.account
                        .remove_executed_order_from_active(limit_order.state().meta().id());
                    // TODO: we could potentially log partial fills as well...
                    self.account_tracker.log_limit_order_fill();
                }
                LimitOrderUpdate::PartiallyFilled(_) => {}
            }
        }
        Ok(changed_orders)
    }

    /// # Arguments:
    /// `order`: The order that is being submitted.
    ///
    /// # Returns:
    /// If Ok, the order with timestamp and id filled in.
    /// Else its an error.
    pub fn submit_limit_order(
        &mut self,
        order: LimitOrder<Q, UserOrderId, NewOrder>,
    ) -> Result<LimitOrder<Q, UserOrderId, Pending<Q>>> {
        trace!("submit_order: {:?}", order);

        // Basic checks
        self.config
            .contract_specification()
            .quantity_filter
            .validate_order_quantity(order.quantity())?;
        self.config
            .contract_specification()
            .price_filter
            .validate_limit_order(&order, self.market_state.mid_price())?;

        let meta = ExchangeOrderMeta::new(
            self.next_order_id(),
            self.market_state.current_timestamp_ns(),
        );
        let order = order.into_pending(meta);

        match order.side() {
            Side::Buy => {
                if order.limit_price() >= self.market_state.ask() {
                    return Err(Error::OrderError(OrderError::LimitPriceAboveAsk));
                }
            }
            Side::Sell => {
                if order.limit_price() <= self.market_state.bid() {
                    return Err(Error::OrderError(OrderError::LimitPriceBelowBid));
                }
            }
        }
        self.risk_engine.check_limit_order(&self.account, &order)?;
        self.account.append_limit_order(order.clone());
        self.account_tracker.log_limit_order_submission();

        Ok(order)
    }

    /// Submit a new `MarketOrder` to the exchange.
    ///
    /// # Arguments:
    /// `order`: The order that is being submitted.
    ///
    /// # Returns:
    /// If Ok, the order with timestamp and id filled in.
    /// Else its an error.
    pub fn submit_market_order(
        &mut self,
        order: MarketOrder<Q, UserOrderId, NewOrder>,
    ) -> Result<MarketOrder<Q, UserOrderId, Filled>> {
        // Basic checks
        self.config
            .contract_specification()
            .quantity_filter
            .validate_order_quantity(order.quantity())?;

        let meta = ExchangeOrderMeta::new(
            self.next_order_id(),
            self.market_state.current_timestamp_ns(),
        );
        let order = order.into_pending(meta);

        let fill_price = match order.side() {
            Side::Buy => self.market_state.ask(),
            Side::Sell => self.market_state.bid(),
        };
        self.risk_engine
            .check_market_order(&self.account, &order, fill_price)?;
        let quantity = match order.side() {
            Side::Buy => order.quantity(),
            Side::Sell => order.quantity().into_negative(),
        };
        // From here on, everything is infallible
        self.clearing_house.settle_filled_order(
            &mut self.account,
            &mut self.account_tracker,
            quantity,
            fill_price,
            self.config.contract_specification().fee_taker,
            self.market_state.current_timestamp_ns(),
        );
        self.account_tracker.log_market_order_fill();

        Ok(order.into_filled(fill_price, self.market_state.current_timestamp_ns()))
    }

    #[inline]
    fn next_order_id(&mut self) -> OrderId {
        self.next_order_id += 1;
        self.next_order_id - 1
    }

    /// Cancel an active limit order based on the `user_order_id`.
    ///
    /// # Arguments:
    /// `user_order_id`: The user order id of the order to cancel.
    ///
    /// # Returns:
    /// the cancelled order if successfull, error when the `user_order_id` is
    /// not found
    pub fn cancel_limit_order_by_user_id(
        &mut self,
        user_order_id: UserOrderId,
    ) -> Result<LimitOrder<Q, UserOrderId, Pending<Q>>> {
        self.account
            .cancel_order_by_user_id(user_order_id, &mut self.account_tracker)
    }

    /// Cancel an active limit order.
    ///
    /// # Arguments:
    /// `order_id`: The `id` (assigned by the exchange) of the order to cancel.
    ///
    /// # Returns:
    /// An order if successful with the given order_id.
    pub fn cancel_order(
        &mut self,
        order_id: OrderId,
    ) -> Result<LimitOrder<Q, UserOrderId, Pending<Q>>> {
        self.account
            .cancel_limit_order(order_id, &mut self.account_tracker)
    }
}