scuriolus 0.2.0

Scuriolus is a modular trading bot platform.
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
use std::fmt::{self, Display};

use chrono::{DateTime, Datelike as _, DurationRound as _, TimeDelta, TimeZone, Utc, Weekday};
use derive_getters::Getters;
use rust_decimal::Decimal;
use strum_macros::{Display, EnumIter};

use crate::{
    core::{CoreError, CoreResult},
    market::mexc_enums,
    trade_log,
};

/// An error related to an [`Order`].
#[derive(Debug, thiserror::Error)]
#[error("Order error: {0}")]
pub struct OrderError(pub String);

impl OrderError {
    pub fn new(msg: &str) -> Self {
        OrderError(msg.to_string())
    }
}

/// Cryptocurrency
#[derive(Debug, Clone, Copy, Display, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum Crypto {
    /// Bitcoin
    BTC,
    /// Dogecoin
    DOGE,
    /// Ethereum
    ETH,
    /// Solana
    SOL,
    /// USD Coin
    USDC,
    /// Tether
    USDT,
    /// Xelis
    XEL,
}

/// The status of an [`Order`].
#[derive(Debug, Clone, Copy, Display, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum OrderStatus {
    Open,
    PartiallyFilled,
    PartiallyCanceled,
    Filled,
    Canceled,
    Tested,
    Failed,
}

/// Represents the quantity of an [`Order`].
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Display)]
pub enum Quantity {
    /// The Quantity is in the asset currency.
    Asset(Decimal), // in BTCUSDT: BTC
    /// The Quantity is in the quote currency.
    Quote(Decimal), // in BTCUSDT: USDT
}

impl Quantity {
    // TODO order should could have both, to explicit effective price and cost
    pub fn get_amount(&self) -> Decimal {
        match self {
            Quantity::Asset(amount) => *amount,
            Quantity::Quote(amount) => *amount,
        }
    }

    /// Returns a tuple representing the quantity in either asset or quote currency.
    ///
    /// This method extracts the value stored in a `Quantity` instance and returns it
    /// as a tuple of `(Option<Amount>, Option<Amount>)`.
    ///
    /// - If the variant is `Quantity::Asset`, it returns `(Some(amount), None)`.
    /// - If the variant is `Quantity::Quote`, it returns `(None, Some(amount))`.
    ///
    /// # Example
    /// ```rust
    /// use crate::scuriolus::data::Quantity;
    /// use rust_decimal::Decimal;
    ///
    /// let qty = Quantity::Asset(Decimal::TWO);
    /// let (asset, quote) = qty.get_amounts();
    /// assert_eq!(asset, Some(Decimal::TWO));
    /// assert_eq!(quote, None);
    /// ```
    ///
    /// # Returns
    /// A tuple where:
    /// - The first element is `Some(amount)` if it's an asset quantity, otherwise `None`.
    /// - The second element is `Some(amount)` if it's a quote quantity, otherwise `None`.
    pub fn get_amounts(&self) -> (Option<Decimal>, Option<Decimal>) {
        match self {
            Quantity::Asset(amount) => (Some(*amount), None),
            Quantity::Quote(amount) => (None, Some(*amount)),
        }
    }
}

/// A trait for specific details of an [`Order`], depending on a market
pub trait SpecificOrderDetails:
    Clone
    + Default
    + fmt::Debug
    + Display
    + serde::Serialize
    + PartialEq
    + 'static
    + Send
    + Sync
    + for<'de> serde::Deserialize<'de>
{
    const NAME: &'static str;
}

/// Empty [`SpecificOrderDetails`], for testing mainly.
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, PartialEq)]
pub struct EmptySpecificOrderDetails {
    content: Option<()>,
}
impl SpecificOrderDetails for EmptySpecificOrderDetails {
    const NAME: &'static str = "EmptySpecificOrderDetails";
}

impl Display for EmptySpecificOrderDetails {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "<EmptySpecificOrderDetails>")
    }
}

/// Represents a market order.
#[derive(Debug, Clone, Getters, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(bound = "D: SpecificOrderDetails")]
pub struct Order<D: SpecificOrderDetails> {
    #[getter(skip)]
    _id: String, // "id" cannot be used because of surrealDB read system
    asset: Crypto,
    quote: Crypto,
    side: mexc_enums::OrderSide,
    order_type: mexc_enums::OrderType,
    status: OrderStatus,
    quantity: Quantity,
    price: Option<Decimal>,
    executed_qty: Decimal,
    cummulative_quote_qty: Decimal,
    details: D,
}

impl<D: SpecificOrderDetails> Order<D> {
    pub fn new(
        asset: Crypto,
        quote: Crypto,
        side: mexc_enums::OrderSide,
        order_type: mexc_enums::OrderType,
        quantity: Quantity,
        price: Option<Decimal>,
    ) -> Result<Self, OrderError> {
        match order_type {
            mexc_enums::OrderType::Limit => {
                if price.is_none() {
                    return Err(OrderError::new("Limit order should have a price"));
                }
            }
            mexc_enums::OrderType::Market => {
                if price.is_some() {
                    return Err(OrderError::new("Market order should not have a price"));
                }
            }
            mexc_enums::OrderType::LimitMaker
            | mexc_enums::OrderType::ImmediateOrCancel
            | mexc_enums::OrderType::FillOrKill => {
                return Err(OrderError::new("Unimplemented order type"))
            }
        }

        if quantity.get_amount() <= Decimal::from(0) {
            return Err(OrderError::new("Amount should be greater than 0"));
        }

        if price.is_some() && price.unwrap() <= Decimal::from(0) {
            return Err(OrderError::new("Price should be greater than 0"));
        }

        tracing::trace!(
            "Creating order: asset: {}, quote: {}, side: {:?}, type: {:?}, quantity: {}, price: {:?}",
            asset,
            quote,
            side,
            order_type,
            quantity,
            price);

        Ok(Self {
            asset,
            quote,
            side,
            order_type,
            quantity,
            price,
            status: OrderStatus::Open,
            _id: uuid::Uuid::new_v4().to_string(),
            executed_qty: Decimal::from(0),
            cummulative_quote_qty: Decimal::from(0),
            details: D::default(),
        })
    }

    pub fn id(&self) -> &String {
        &self._id
    }

    pub fn set_status(&mut self, status: OrderStatus) {
        self.status = status;
        trade_log!("Update on order {}: status now {}", self._id, status);
    }

    pub fn set_executed(&mut self, executed_qty: Decimal, cummulative_quote_qty: Decimal) {
        self.executed_qty = executed_qty;
        self.cummulative_quote_qty = cummulative_quote_qty;
        tracing::debug!(
            "Order {} executed: {} - {}",
            self._id,
            executed_qty,
            cummulative_quote_qty
        );
    }

    pub fn set_asset_quantity(&mut self, asset_quantity: Decimal) -> Result<(), OrderError> {
        if self.order_type != mexc_enums::OrderType::Market
            && self.side != mexc_enums::OrderSide::Buy
        {
            return Err(OrderError::new(
                "Asset quantity can only be modified for buy market orders",
            ));
        }
        self.quantity = Quantity::Asset(asset_quantity);
        Ok(())
    }

    pub fn quote_quantity(&self) -> Result<Decimal, OrderError> {
        match self.quantity {
            Quantity::Asset(amount) => {
                Ok(self.price.ok_or_else(|| OrderError::new("Price not set"))? * amount)
            }
            Quantity::Quote(amount) => Ok(amount),
        }
    }

    pub fn is_done(&self) -> bool {
        matches!(
            self.status,
            OrderStatus::Filled
                | OrderStatus::Canceled
                | OrderStatus::PartiallyCanceled
                | OrderStatus::Tested
                | OrderStatus::Failed
        )
    }

    pub fn set_price(&mut self, price: Decimal) -> Result<(), OrderError> {
        if self.order_type != mexc_enums::OrderType::Market && self.status != OrderStatus::Filled {
            return Err(OrderError::new(
                "Price can only be modified except for filled market orders",
            ));
        }

        self.price = Some(price);
        Ok(())
    }

    pub fn symbol(&self) -> String {
        format!("{}{}", self.asset(), self.quote())
    }

    pub fn details_mut(&mut self) -> &mut D {
        &mut self.details
    }
}

impl<D: SpecificOrderDetails> fmt::Display for Order<D> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "Buy: {}, With: {}, Side: {:?}, Type: {:?},Amount: {}, Price: {:?}, Market: {}, Status: {}, Specifc: {}", 
            self.asset, self.quote, self.side, self.order_type, self.quantity, self.price, D::NAME, self.status, self.details
        )
    }
}

/// An order draft to be sent to the market.
#[derive(Debug, Clone, Copy)]
pub struct OrderDraft {
    pub asset: Crypto,
    pub quote: Crypto,
    pub side: mexc_enums::OrderSide,
    pub order_type: mexc_enums::OrderType,
    pub amount: Quantity,
    pub price: Option<Decimal>,
}

impl From<OrderStatus> for mexc_enums::OrderStatus {
    fn from(status: OrderStatus) -> Self {
        match status {
            OrderStatus::Open => mexc_enums::OrderStatus::New,
            OrderStatus::Filled => mexc_enums::OrderStatus::Filled,
            OrderStatus::Canceled => mexc_enums::OrderStatus::Canceled,
            OrderStatus::PartiallyFilled => mexc_enums::OrderStatus::PartiallyFilled,
            OrderStatus::PartiallyCanceled => mexc_enums::OrderStatus::PartiallyCanceled,
            OrderStatus::Tested => mexc_enums::OrderStatus::Canceled,
            OrderStatus::Failed => mexc_enums::OrderStatus::Canceled,
        }
    }
}

impl From<mexc_enums::OrderStatus> for OrderStatus {
    fn from(status: mexc_enums::OrderStatus) -> Self {
        match status {
            mexc_enums::OrderStatus::New => OrderStatus::Open,
            mexc_enums::OrderStatus::Filled => OrderStatus::Filled,
            mexc_enums::OrderStatus::Canceled => OrderStatus::Canceled,
            mexc_enums::OrderStatus::PartiallyFilled => OrderStatus::PartiallyFilled,
            mexc_enums::OrderStatus::PartiallyCanceled => OrderStatus::PartiallyCanceled,
        }
    }
}

/// Avalaible Kline intervals
#[derive(
    Debug,
    Display,
    serde::Serialize,
    serde::Deserialize,
    Clone,
    Copy,
    PartialEq,
    EnumIter,
    Eq,
    PartialOrd,
    Ord,
)]
pub enum KlineInterval {
    OneMinute,
    FiveMinutes,
    FifteenMinutes,
    ThirtyMinutes,
    OneHour,
    FourHours,
    OneDay,
    OneWeek,
    OneMonth,
}

impl KlineInterval {
    pub fn next_interval_to_zoom_out(&self) -> Option<KlineInterval> {
        match self {
            KlineInterval::OneMinute => Some(KlineInterval::FiveMinutes),
            KlineInterval::FiveMinutes => Some(KlineInterval::FifteenMinutes),
            KlineInterval::FifteenMinutes => Some(KlineInterval::OneHour),
            KlineInterval::ThirtyMinutes => Some(KlineInterval::OneHour),
            KlineInterval::OneHour => Some(KlineInterval::OneDay),
            KlineInterval::FourHours => Some(KlineInterval::OneDay),
            KlineInterval::OneDay => Some(KlineInterval::OneWeek),
            KlineInterval::OneWeek => None,
            KlineInterval::OneMonth => None,
        }
    }

    pub fn time_delta(&self) -> TimeDelta {
        match self {
            KlineInterval::OneMinute => TimeDelta::minutes(1),
            KlineInterval::FiveMinutes => TimeDelta::minutes(5),
            KlineInterval::FifteenMinutes => TimeDelta::minutes(15),
            KlineInterval::ThirtyMinutes => TimeDelta::minutes(30),
            KlineInterval::OneHour => TimeDelta::hours(1),
            KlineInterval::FourHours => TimeDelta::hours(4),
            KlineInterval::OneDay => TimeDelta::days(1),
            KlineInterval::OneWeek => TimeDelta::weeks(1),
            KlineInterval::OneMonth => TimeDelta::days(30),
        }
    }

    /// Given a target date, returns the start and end date of the interval
    /// this target date belongs to.
    ///
    /// For the precision of 1 week, the start date will always be a Monday.
    /// If the date is exactly on a boundary, the interval starting on this boundary will be returned
    ///
    ///  ## Arguments
    ///
    /// * `target` - The target date to get the bounds for
    pub fn get_time_bounds(
        &self,
        target: DateTime<Utc>,
    ) -> CoreResult<(DateTime<Utc>, DateTime<Utc>)> {
        match self {
            KlineInterval::OneWeek => {
                let mut start = target.duration_trunc(KlineInterval::OneDay.time_delta())?;
                let mut end = target.duration_round_up(KlineInterval::OneDay.time_delta())?;

                while start.weekday() != Weekday::Mon {
                    start -= TimeDelta::days(1);
                }
                while end.weekday() != Weekday::Mon && end <= start {
                    end += TimeDelta::days(1);
                }

                Ok((end, start))
            }
            KlineInterval::OneMonth => {
                let start = Utc
                    .with_ymd_and_hms(target.year(), target.month(), 1, 0, 0, 0)
                    .single()
                    .ok_or(CoreError::comput_error("Error creating start date"))?;
                let end = if target.month() == 12 {
                    Utc.with_ymd_and_hms(target.year() + 1, 1, 1, 0, 0, 0)
                } else {
                    Utc.with_ymd_and_hms(target.year(), target.month() + 1, 1, 0, 0, 0)
                }
                .single()
                .ok_or(CoreError::comput_error("Error creating start date"))?;
                Ok((start, end))
            }
            _ => {
                let start = target.duration_trunc(self.time_delta())?;
                let end = target.duration_round_up(self.time_delta())?;
                if start != end {
                    Ok((start, end))
                } else {
                    Ok((start, end + self.time_delta()))
                }
            }
        }
    }

    pub fn short_string(&self) -> String {
        match self {
            KlineInterval::OneMinute => "1m",
            KlineInterval::FiveMinutes => "5m",
            KlineInterval::FifteenMinutes => "15m",
            KlineInterval::ThirtyMinutes => "30m",
            KlineInterval::OneHour => "1h",
            KlineInterval::FourHours => "4h",
            KlineInterval::OneDay => "1d",
            KlineInterval::OneWeek => "1w",
            KlineInterval::OneMonth => "1M",
        }
        .to_string()
    }
}