quantoxide 0.6.2

Rust framework for developing, backtesting, and deploying Bitcoin futures trading strategies.
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
use std::{fmt, num::NonZeroU64, sync::Arc};

use tokio::sync::broadcast;
use uuid::Uuid;

use lnm_sdk::rest::v3::{
    RestClient,
    models::{
        Account, ClientId, CrossLeverage, CrossOrder, CrossPosition, Leverage, OrderQuantity,
        Price, Trade, TradeExecution, TradeSide, TradeSize,
    },
};

use super::{
    super::super::core::TradingState,
    error::{ExecutorActionError, ExecutorActionResult},
    state::{LiveTradeExecutorStatus, live_trading_session::LiveTradingSession},
};

/// Represents an executor action sent to the exchange API.
#[derive(Debug, Clone)]
pub enum LiveTradeExecutorAction {
    /// Opens a new isolated margin order.
    IsolatedOrder {
        /// Order side.
        side: TradeSide,
        /// Order size.
        size: TradeSize,
        /// Isolated order leverage.
        leverage: Leverage,
        /// Optional stop-loss price.
        stoploss: Option<Price>,
        /// Optional take-profit price.
        takeprofit: Option<Price>,
        /// Optional client-provided order identifier.
        client_id: Option<ClientId>,
    },
    /// Updates the stop-loss price for an isolated trade.
    IsolatedTradeUpdateStoploss {
        /// Trade identifier.
        id: Uuid,
        /// New stop-loss price.
        stoploss: Price,
    },
    /// Adds margin to an isolated trade.
    IsolatedTradeAddMargin {
        /// Trade identifier.
        id: Uuid,
        /// Margin amount in satoshis.
        amount: NonZeroU64,
    },
    /// Withdraws margin from an isolated trade.
    IsolatedTradeCashIn {
        /// Trade identifier.
        id: Uuid,
        /// Cash-in amount in satoshis.
        amount: NonZeroU64,
    },
    /// Closes an isolated order or trade.
    IsolatedOrderClose {
        /// Order or trade identifier.
        id: Uuid,
    },
    /// Cancels all open isolated orders.
    IsolatedOrderCancelAll,
    /// Closes all open isolated orders and trades.
    IsolatedOrderCloseAll,
    /// Deposits funds into the cross-margin account.
    CrossDeposit {
        /// Deposit amount in satoshis.
        amount: NonZeroU64,
    },
    /// Withdraws funds from the cross-margin account.
    CrossWithdraw {
        /// Withdrawal amount in satoshis.
        amount: NonZeroU64,
    },
    /// Sets cross-margin leverage.
    CrossSetLeverage {
        /// New cross-margin leverage.
        leverage: CrossLeverage,
    },
    /// Places a cross-margin order.
    CrossOrder {
        /// Order side.
        side: TradeSide,
        /// Order quantity.
        quantity: OrderQuantity,
        /// Optional client-provided order identifier.
        client_id: Option<ClientId>,
    },
    /// Cancels all open cross-margin orders.
    CrossOrderCancelAll,
    /// Closes the current cross-margin position.
    CrossOrderClosePosition,
}

impl fmt::Display for LiveTradeExecutorAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::IsolatedOrder {
                side,
                size,
                leverage,
                stoploss,
                takeprofit,
                client_id,
            } => {
                let fmt_price_opt = |price_opt: &Option<Price>| {
                    price_opt
                        .map(|price| format!("{:.1}", price))
                        .unwrap_or_else(|| "N/A".to_string())
                };

                let client_id_str = client_id.as_ref().map(|id| id.as_str()).unwrap_or("N/A");

                write!(
                    f,
                    "Isolated Order:\n  side: {}\n  size: {}\n  leverage: {}\n  stoploss: {}\n  takeprofit: {}\n  client_id: {}",
                    side,
                    size,
                    leverage,
                    fmt_price_opt(stoploss),
                    fmt_price_opt(takeprofit),
                    client_id_str
                )
            }
            Self::IsolatedTradeUpdateStoploss { id, stoploss } => {
                write!(
                    f,
                    "Isolated Trade Stoploss Update:\n  id: {}\n  stoploss: {:.1}",
                    id, stoploss
                )
            }
            Self::IsolatedTradeAddMargin { id, amount } => {
                write!(
                    f,
                    "Isolated Trade Add Margin:\n  id: {}\n  amount: {}",
                    id, amount
                )
            }
            Self::IsolatedTradeCashIn { id, amount } => {
                write!(
                    f,
                    "Isolated Trade Cash In:\n  id: {}\n  amount: {}",
                    id, amount
                )
            }
            Self::IsolatedOrderClose { id } => {
                write!(f, "Isolated Order Close:\n  id: {}", id)
            }
            Self::IsolatedOrderCancelAll => write!(f, "Cancel All Isolated Orders"),
            Self::IsolatedOrderCloseAll => write!(f, "Close All Isolated Orders"),
            Self::CrossDeposit { amount } => {
                write!(f, "Cross Deposit:\n  amount: {}", amount)
            }
            Self::CrossWithdraw { amount } => {
                write!(f, "Cross Withdraw:\n  amount: {}", amount)
            }
            Self::CrossSetLeverage { leverage } => {
                write!(f, "Cross Set Leverage:\n  leverage: {}", leverage)
            }
            Self::CrossOrder {
                side,
                quantity,
                client_id,
            } => {
                let client_id_str = client_id.as_ref().map(|id| id.as_str()).unwrap_or("N/A");

                write!(
                    f,
                    "Cross Order:\n  side: {}\n  quantity: {}\n  client_id: {}",
                    side, quantity, client_id_str
                )
            }
            Self::CrossOrderCancelAll => write!(f, "Cancel All Cross Orders"),
            Self::CrossOrderClosePosition => write!(f, "Cross Order Close Position"),
        }
    }
}

/// Update events emitted by the live trade executor including executor actions, status changes,
/// trading state, and closed trades.
#[derive(Clone)]
pub enum LiveTradeExecutorUpdate {
    /// An executor action was sent to the exchange.
    Action(LiveTradeExecutorAction),
    /// The executor status changed.
    Status(LiveTradeExecutorStatus),
    /// The trading state was updated.
    TradingState(TradingState),
    /// A trade was closed.
    ClosedTrade(Trade),
}

impl From<LiveTradeExecutorAction> for LiveTradeExecutorUpdate {
    fn from(value: LiveTradeExecutorAction) -> Self {
        Self::Action(value)
    }
}

impl From<LiveTradeExecutorStatus> for LiveTradeExecutorUpdate {
    fn from(value: LiveTradeExecutorStatus) -> Self {
        LiveTradeExecutorUpdate::Status(value)
    }
}

impl From<LiveTradingSession> for LiveTradeExecutorUpdate {
    fn from(value: LiveTradingSession) -> Self {
        LiveTradeExecutorUpdate::TradingState(value.into())
    }
}

pub(super) type LiveTradeExecutorTransmitter = broadcast::Sender<LiveTradeExecutorUpdate>;

/// Receiver for subscribing to [`LiveTradeExecutorUpdate`]s including executor actions, status
/// changes, trading state, and closed trades.
pub type LiveTradeExecutorReceiver = broadcast::Receiver<LiveTradeExecutorUpdate>;

#[derive(Clone)]
pub(in crate::trade) struct WrappedRestClient {
    api_rest: Arc<RestClient>,
    update_tx: LiveTradeExecutorTransmitter,
}

impl WrappedRestClient {
    pub fn new(api_rest: Arc<RestClient>, update_tx: LiveTradeExecutorTransmitter) -> Self {
        Self {
            api_rest,
            update_tx,
        }
    }

    pub async fn get_trades_running(&self) -> ExecutorActionResult<Vec<Trade>> {
        self.api_rest
            .futures_isolated
            .get_running_trades()
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn get_trades_closed(&self, limit: NonZeroU64) -> ExecutorActionResult<Vec<Trade>> {
        let trade_page = self
            .api_rest
            .futures_isolated
            .get_closed_trades(None, None, Some(limit), None)
            .await
            .map_err(ExecutorActionError::RestApi)?;

        Ok(trade_page.into())
    }

    pub async fn get_user(&self) -> ExecutorActionResult<Account> {
        self.api_rest
            .account
            .get_account()
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    fn send_action_update(&self, action: LiveTradeExecutorAction) {
        let _ = self.update_tx.send(action.into());
    }

    pub async fn isolated_order(
        &self,
        side: TradeSide,
        size: TradeSize,
        leverage: Leverage,
        stoploss: Option<Price>,
        takeprofit: Option<Price>,
        client_id: Option<ClientId>,
    ) -> ExecutorActionResult<Trade> {
        self.send_action_update(LiveTradeExecutorAction::IsolatedOrder {
            side,
            size,
            leverage,
            stoploss,
            takeprofit,
            client_id: client_id.clone(),
        });

        self.api_rest
            .futures_isolated
            .new_trade(
                side,
                size,
                leverage,
                TradeExecution::Market,
                stoploss,
                takeprofit,
                client_id,
            )
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn isolated_trade_update_stoploss(
        &self,
        id: Uuid,
        stoploss: Price,
    ) -> ExecutorActionResult<Trade> {
        self.send_action_update(LiveTradeExecutorAction::IsolatedTradeUpdateStoploss {
            id,
            stoploss,
        });

        self.api_rest
            .futures_isolated
            .update_stoploss(id, Some(stoploss))
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn isolated_trade_add_margin(
        &self,
        id: Uuid,
        amount: NonZeroU64,
    ) -> ExecutorActionResult<Trade> {
        self.send_action_update(LiveTradeExecutorAction::IsolatedTradeAddMargin { id, amount });

        self.api_rest
            .futures_isolated
            .add_margin_to_trade(id, amount)
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn isolated_trade_cash_in(
        &self,
        id: Uuid,
        amount: NonZeroU64,
    ) -> ExecutorActionResult<Trade> {
        self.send_action_update(LiveTradeExecutorAction::IsolatedTradeCashIn { id, amount });

        self.api_rest
            .futures_isolated
            .cash_in_trade(id, amount)
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn isolated_order_close(&self, id: Uuid) -> ExecutorActionResult<Trade> {
        self.send_action_update(LiveTradeExecutorAction::IsolatedOrderClose { id });

        self.api_rest
            .futures_isolated
            .close_trade(id)
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn isolated_order_cancel_all(&self) -> ExecutorActionResult<Vec<Trade>> {
        self.send_action_update(LiveTradeExecutorAction::IsolatedOrderCancelAll);

        self.api_rest
            .futures_isolated
            .cancel_all_trades()
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn isolated_order_close_all(&self) -> ExecutorActionResult<Vec<Trade>> {
        self.send_action_update(LiveTradeExecutorAction::IsolatedOrderCloseAll);

        let running_trades = self
            .api_rest
            .futures_isolated
            .get_running_trades()
            .await
            .map_err(ExecutorActionError::RestApi)?;

        let mut closed_trades = Vec::new();

        for trade in running_trades {
            let closed_trade = self
                .api_rest
                .futures_isolated
                .close_trade(trade.id())
                .await
                .map_err(ExecutorActionError::RestApi)?;

            closed_trades.push(closed_trade);
        }

        Ok(closed_trades)
    }

    pub async fn cross_get_position(&self) -> ExecutorActionResult<CrossPosition> {
        self.api_rest
            .futures_cross
            .get_position()
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn cross_deposit(&self, amount: NonZeroU64) -> ExecutorActionResult<CrossPosition> {
        self.send_action_update(LiveTradeExecutorAction::CrossDeposit { amount });

        self.api_rest
            .futures_cross
            .deposit(amount)
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn cross_withdraw(&self, amount: NonZeroU64) -> ExecutorActionResult<CrossPosition> {
        self.send_action_update(LiveTradeExecutorAction::CrossWithdraw { amount });

        self.api_rest
            .futures_cross
            .withdraw(amount)
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn cross_set_leverage(
        &self,
        leverage: CrossLeverage,
    ) -> ExecutorActionResult<CrossPosition> {
        self.send_action_update(LiveTradeExecutorAction::CrossSetLeverage { leverage });

        self.api_rest
            .futures_cross
            .set_leverage(leverage)
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn cross_order(
        &self,
        side: TradeSide,
        quantity: OrderQuantity,
        client_id: Option<ClientId>,
    ) -> ExecutorActionResult<CrossOrder> {
        self.send_action_update(LiveTradeExecutorAction::CrossOrder {
            side,
            quantity,
            client_id: client_id.clone(),
        });

        self.api_rest
            .futures_cross
            .place_order(side, quantity, TradeExecution::Market, client_id)
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn cross_cancel_all_orders(&self) -> ExecutorActionResult<Vec<CrossOrder>> {
        self.send_action_update(LiveTradeExecutorAction::CrossOrderCancelAll);

        self.api_rest
            .futures_cross
            .cancel_all_orders()
            .await
            .map_err(ExecutorActionError::RestApi)
    }

    pub async fn cross_order_close_position(&self) -> ExecutorActionResult<CrossOrder> {
        self.send_action_update(LiveTradeExecutorAction::CrossOrderClosePosition);

        self.api_rest
            .futures_cross
            .close_position()
            .await
            .map_err(ExecutorActionError::RestApi)
    }
}