openpit 0.2.0

Embeddable pre-trade risk SDK
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
469
470
// Copyright The Pit Project Owners. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Please see https://github.com/openpitkit and the OWNERS file for details.

use std::fmt::{Display, Formatter};

/// Reject scope returned by policies.
///
/// # Examples
///
/// ```
/// use openpit::pretrade::RejectScope;
///
/// let scope = RejectScope::Order;
/// match scope {
///     RejectScope::Order => { /* retry is safe; engine remains operational */ }
///     RejectScope::Account => { /* halt trading until situation is resolved */ }
/// }
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RejectScope {
    /// Reject only the current order.
    Order,
    /// Account-level reject signal.
    ///
    /// Engine reports it; application decides whether to stop trading.
    Account,
}

/// Standardized reject code for blocked orders.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RejectCode {
    /// A mandatory order field was not provided.
    MissingRequiredField,
    /// A field format is syntactically invalid.
    InvalidFieldFormat,
    /// A field value is outside accepted domain values.
    InvalidFieldValue,
    /// The order type is not supported.
    UnsupportedOrderType,
    /// The time-in-force value is not supported.
    UnsupportedTimeInForce,
    /// A requested order attribute is unsupported.
    UnsupportedOrderAttribute,
    /// Client order ID is already in use.
    DuplicateClientOrderId,
    /// Order arrival is outside the allowed entry window.
    TooLateToEnter,
    /// Venue session is closed for trading.
    ExchangeClosed,
    /// Instrument identifier is not recognized.
    UnknownInstrument,
    /// Account identifier is not recognized.
    UnknownAccount,
    /// Venue identifier is not recognized.
    UnknownVenue,
    /// Clearing account is not recognized.
    UnknownClearingAccount,
    /// Collateral asset is not recognized.
    UnknownCollateralAsset,
    /// Available cash is not sufficient for this order.
    InsufficientFunds,
    /// Margin is insufficient for this order.
    InsufficientMargin,
    /// Position inventory is insufficient for this order.
    InsufficientPosition,
    /// Credit limit is exceeded.
    CreditLimitExceeded,
    /// A generic risk limit is exceeded.
    RiskLimitExceeded,
    /// Multiple size limits are exceeded by one order.
    OrderExceedsLimit,
    /// Quantity limit is exceeded.
    OrderQtyExceedsLimit,
    /// Notional limit is exceeded.
    OrderNotionalExceedsLimit,
    /// Position limit is exceeded.
    PositionLimitExceeded,
    /// Concentration limit is exceeded.
    ConcentrationLimitExceeded,
    /// Leverage limit is exceeded.
    LeverageLimitExceeded,
    /// Rate limit for order submissions is exceeded.
    RateLimitExceeded,
    /// PnL-based kill switch is currently triggered.
    PnlKillSwitchTriggered,
    /// Account is blocked from trading.
    AccountBlocked,
    /// Account is not authorized to place this order.
    AccountNotAuthorized,
    /// Compliance rule forbids this order.
    ComplianceRestriction,
    /// Instrument is restricted for this account or venue.
    InstrumentRestricted,
    /// Jurisdictional restriction forbids this order.
    JurisdictionRestriction,
    /// Wash-trade prevention blocked this order.
    WashTradePrevention,
    /// Self-match prevention blocked this order.
    SelfMatchPrevention,
    /// Short-sale restriction blocked this order.
    ShortSaleRestriction,
    /// Required risk configuration is missing.
    RiskConfigurationMissing,
    /// Required reference data is unavailable.
    ReferenceDataUnavailable,
    /// Order value could not be calculated.
    OrderValueCalculationFailed,
    /// Risk system is temporarily unavailable.
    SystemUnavailable,
    /// Reject reason does not fit a more specific code.
    Other,
}

impl RejectCode {
    /// Returns the stable string representation of this code.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::MissingRequiredField => "MissingRequiredField",
            Self::InvalidFieldFormat => "InvalidFieldFormat",
            Self::InvalidFieldValue => "InvalidFieldValue",
            Self::UnsupportedOrderType => "UnsupportedOrderType",
            Self::UnsupportedTimeInForce => "UnsupportedTimeInForce",
            Self::UnsupportedOrderAttribute => "UnsupportedOrderAttribute",
            Self::DuplicateClientOrderId => "DuplicateClientOrderId",
            Self::TooLateToEnter => "TooLateToEnter",
            Self::ExchangeClosed => "ExchangeClosed",
            Self::UnknownInstrument => "UnknownInstrument",
            Self::UnknownAccount => "UnknownAccount",
            Self::UnknownVenue => "UnknownVenue",
            Self::UnknownClearingAccount => "UnknownClearingAccount",
            Self::UnknownCollateralAsset => "UnknownCollateralAsset",
            Self::InsufficientFunds => "InsufficientFunds",
            Self::InsufficientMargin => "InsufficientMargin",
            Self::InsufficientPosition => "InsufficientPosition",
            Self::CreditLimitExceeded => "CreditLimitExceeded",
            Self::RiskLimitExceeded => "RiskLimitExceeded",
            Self::OrderExceedsLimit => "OrderExceedsLimit",
            Self::OrderQtyExceedsLimit => "OrderQtyExceedsLimit",
            Self::OrderNotionalExceedsLimit => "OrderNotionalExceedsLimit",
            Self::PositionLimitExceeded => "PositionLimitExceeded",
            Self::ConcentrationLimitExceeded => "ConcentrationLimitExceeded",
            Self::LeverageLimitExceeded => "LeverageLimitExceeded",
            Self::RateLimitExceeded => "RateLimitExceeded",
            Self::PnlKillSwitchTriggered => "PnlKillSwitchTriggered",
            Self::AccountBlocked => "AccountBlocked",
            Self::AccountNotAuthorized => "AccountNotAuthorized",
            Self::ComplianceRestriction => "ComplianceRestriction",
            Self::InstrumentRestricted => "InstrumentRestricted",
            Self::JurisdictionRestriction => "JurisdictionRestriction",
            Self::WashTradePrevention => "WashTradePrevention",
            Self::SelfMatchPrevention => "SelfMatchPrevention",
            Self::ShortSaleRestriction => "ShortSaleRestriction",
            Self::RiskConfigurationMissing => "RiskConfigurationMissing",
            Self::ReferenceDataUnavailable => "ReferenceDataUnavailable",
            Self::OrderValueCalculationFailed => "OrderValueCalculationFailed",
            Self::SystemUnavailable => "SystemUnavailable",
            Self::Other => "Other",
        }
    }
}

impl Display for RejectCode {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Single rejection record returned by checks.
///
/// # Examples
///
/// ```
/// use openpit::pretrade::{Reject, RejectCode, RejectScope};
///
/// let reject = Reject::new(
///     "RateLimitPolicy",
///     RejectScope::Order,
///     RejectCode::RateLimitExceeded,
///     "rate limit exceeded",
///     "submitted 3 orders in 1s window, max allowed: 2",
/// );
/// assert_eq!(reject.code, RejectCode::RateLimitExceeded);
/// assert_eq!(reject.reason, "rate limit exceeded");
/// assert_eq!(reject.details, "submitted 3 orders in 1s window, max allowed: 2");
/// assert_eq!(reject.policy, "RateLimitPolicy");
/// ```
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reject {
    /// Stable machine-readable reject code.
    pub code: RejectCode,
    /// Human-readable reject reason.
    pub reason: String,
    /// Case-specific reject details.
    pub details: String,
    /// Policy name that produced the reject.
    pub policy: &'static str,
    /// Reject scope.
    pub scope: RejectScope,
}

impl Display for Reject {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            formatter,
            "[{}] {}: {}",
            self.policy, self.reason, self.details
        )
    }
}

impl std::error::Error for Reject {}

/// Collection of rejects returned by [`Request::execute`].
///
/// Implements `Deref` to `[Reject]` for direct element access.
///
/// [`Request::execute`]: crate::pretrade::Request::execute
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rejects(Vec<Reject>);

impl Rejects {
    pub(crate) fn new(rejects: Vec<Reject>) -> Self {
        Self(rejects)
    }
}

impl std::ops::Deref for Rejects {
    type Target = Vec<Reject>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl Display for Rejects {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
        for (i, reject) in self.0.iter().enumerate() {
            if i > 0 {
                write!(formatter, "; ")?;
            }
            Display::fmt(reject, formatter)?;
        }
        Ok(())
    }
}

impl std::error::Error for Rejects {}

impl Reject {
    /// Creates a reject with human-readable reason and details.
    pub fn new(
        policy: &'static str,
        scope: RejectScope,
        code: RejectCode,
        reason: impl Into<String>,
        details: impl Into<String>,
    ) -> Self {
        Self {
            code,
            reason: reason.into(),
            details: details.into(),
            policy,
            scope,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::RejectCode;

    #[test]
    fn reject_code_as_str_and_display_are_stable_for_all_values() {
        let cases = [
            (RejectCode::MissingRequiredField, "MissingRequiredField"),
            (RejectCode::InvalidFieldFormat, "InvalidFieldFormat"),
            (RejectCode::InvalidFieldValue, "InvalidFieldValue"),
            (RejectCode::UnsupportedOrderType, "UnsupportedOrderType"),
            (RejectCode::UnsupportedTimeInForce, "UnsupportedTimeInForce"),
            (
                RejectCode::UnsupportedOrderAttribute,
                "UnsupportedOrderAttribute",
            ),
            (RejectCode::DuplicateClientOrderId, "DuplicateClientOrderId"),
            (RejectCode::TooLateToEnter, "TooLateToEnter"),
            (RejectCode::ExchangeClosed, "ExchangeClosed"),
            (RejectCode::UnknownInstrument, "UnknownInstrument"),
            (RejectCode::UnknownAccount, "UnknownAccount"),
            (RejectCode::UnknownVenue, "UnknownVenue"),
            (RejectCode::UnknownClearingAccount, "UnknownClearingAccount"),
            (RejectCode::UnknownCollateralAsset, "UnknownCollateralAsset"),
            (RejectCode::InsufficientFunds, "InsufficientFunds"),
            (RejectCode::InsufficientMargin, "InsufficientMargin"),
            (RejectCode::InsufficientPosition, "InsufficientPosition"),
            (RejectCode::CreditLimitExceeded, "CreditLimitExceeded"),
            (RejectCode::RiskLimitExceeded, "RiskLimitExceeded"),
            (RejectCode::OrderExceedsLimit, "OrderExceedsLimit"),
            (RejectCode::OrderQtyExceedsLimit, "OrderQtyExceedsLimit"),
            (
                RejectCode::OrderNotionalExceedsLimit,
                "OrderNotionalExceedsLimit",
            ),
            (RejectCode::PositionLimitExceeded, "PositionLimitExceeded"),
            (
                RejectCode::ConcentrationLimitExceeded,
                "ConcentrationLimitExceeded",
            ),
            (RejectCode::LeverageLimitExceeded, "LeverageLimitExceeded"),
            (RejectCode::RateLimitExceeded, "RateLimitExceeded"),
            (RejectCode::PnlKillSwitchTriggered, "PnlKillSwitchTriggered"),
            (RejectCode::AccountBlocked, "AccountBlocked"),
            (RejectCode::AccountNotAuthorized, "AccountNotAuthorized"),
            (RejectCode::ComplianceRestriction, "ComplianceRestriction"),
            (RejectCode::InstrumentRestricted, "InstrumentRestricted"),
            (
                RejectCode::JurisdictionRestriction,
                "JurisdictionRestriction",
            ),
            (RejectCode::WashTradePrevention, "WashTradePrevention"),
            (RejectCode::SelfMatchPrevention, "SelfMatchPrevention"),
            (RejectCode::ShortSaleRestriction, "ShortSaleRestriction"),
            (
                RejectCode::RiskConfigurationMissing,
                "RiskConfigurationMissing",
            ),
            (
                RejectCode::ReferenceDataUnavailable,
                "ReferenceDataUnavailable",
            ),
            (
                RejectCode::OrderValueCalculationFailed,
                "OrderValueCalculationFailed",
            ),
            (RejectCode::SystemUnavailable, "SystemUnavailable"),
            (RejectCode::Other, "Other"),
        ];

        for (code, expected_name) in cases {
            assert_eq!(code.as_str(), expected_name);
            assert_eq!(code.to_string(), expected_name);
        }
    }

    #[test]
    fn reject_display_formats_policy_reason_and_details() {
        let reject = super::Reject::new(
            "TestPolicy",
            super::RejectScope::Order,
            RejectCode::Other,
            "something went wrong",
            "extra info",
        );
        assert_eq!(
            reject.to_string(),
            "[TestPolicy] something went wrong: extra info"
        );
    }

    #[test]
    fn rejects_deref_gives_slice_access() {
        let rejects = super::Rejects::new(vec![super::Reject::new(
            "P",
            super::RejectScope::Order,
            RejectCode::Other,
            "r",
            "d",
        )]);
        assert_eq!(rejects.len(), 1);
        assert_eq!(rejects[0].policy, "P");
    }

    #[test]
    fn rejects_display_single() {
        let rejects = super::Rejects::new(vec![super::Reject::new(
            "P",
            super::RejectScope::Order,
            RejectCode::Other,
            "reason",
            "details",
        )]);
        assert_eq!(rejects.to_string(), "[P] reason: details");
    }

    #[test]
    fn rejects_display_multiple_joined_with_separator() {
        let rejects = super::Rejects::new(vec![
            super::Reject::new(
                "P1",
                super::RejectScope::Order,
                RejectCode::Other,
                "r1",
                "d1",
            ),
            super::Reject::new(
                "P2",
                super::RejectScope::Account,
                RejectCode::Other,
                "r2",
                "d2",
            ),
        ]);
        assert_eq!(rejects.to_string(), "[P1] r1: d1; [P2] r2: d2");
    }

    #[test]
    fn rejects_display_empty_produces_empty_string() {
        let rejects = super::Rejects::new(vec![]);
        assert_eq!(rejects.to_string(), "");
    }

    #[test]
    fn rejects_display_propagates_error_from_reject_fmt() {
        use std::fmt;
        use std::fmt::Write;

        struct ImmediateFailWriter;
        impl Write for ImmediateFailWriter {
            fn write_str(&mut self, _: &str) -> fmt::Result {
                Err(fmt::Error)
            }
        }

        let rejects = super::Rejects::new(vec![super::Reject::new(
            "P",
            super::RejectScope::Order,
            RejectCode::Other,
            "r",
            "d",
        )]);
        assert!(fmt::write(&mut ImmediateFailWriter, format_args!("{rejects}")).is_err());
    }

    #[test]
    fn rejects_display_propagates_write_error() {
        use std::fmt;
        use std::fmt::Write;

        struct FailOnSeparator;
        impl Write for FailOnSeparator {
            fn write_str(&mut self, s: &str) -> fmt::Result {
                if s == "; " {
                    Err(fmt::Error)
                } else {
                    Ok(())
                }
            }
        }

        let rejects = super::Rejects::new(vec![
            super::Reject::new("P", super::RejectScope::Order, RejectCode::Other, "r", "d"),
            super::Reject::new("P", super::RejectScope::Order, RejectCode::Other, "r", "d"),
        ]);
        assert!(fmt::write(&mut FailOnSeparator, format_args!("{rejects}")).is_err());
    }
}