openpit 0.8.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
// 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://openpit.dev and the OWNERS file for details.

use super::PreTradeLock;
use crate::core::account_outcome::AccountAdjustmentOutcome;

/// Opaque capability object representing reserved state.
///
/// `PreTradeReservation` is the result of successful pre-trade execution. It owns the
/// commit/rollback capability for the mutations prepared by policies, and it
/// also carries the [`PreTradeLock`] produced while those mutations were built.
///
/// The lock is part of the reservation contract. It is the policy context that
/// describes what was actually locked and which values must survive beyond the
/// synchronous pre-trade phase. This matters when later reconciliation depends
/// on execution-report details, especially partial fills and final reports.
///
/// If a policy needs trade execution report fill details to finalize reserved
/// state, the caller must persist [`PreTradeReservation::lock`] together with the order
/// and keep it until the last execution report for that order has been
/// processed. A final order state alone is not sufficient if the policy also
/// needs fill-by-fill data to determine how much of the reservation was truly
/// consumed and how much must be released.
///
/// Example: a policy may reserve quote notional using a pre-trade worst price.
/// When fills arrive, the engine may need that stored reservation context to
/// compute the unused remainder and unlock it correctly. If the lock is lost,
/// post-trade code no longer has the authoritative context produced by
/// pre-trade validation.
///
/// If dropped without explicit finalization, rollback is executed automatically.
///
/// # Finalization
///
/// Both [`commit`](Self::commit) and [`rollback`](Self::rollback) are void:
/// the state they finalize was applied eagerly, so there is nothing left for
/// the owner to decide or compensate. A mutation finalizer that fails anyway is
/// never ignored - the engine raises a kill switch instead, and the owner learns
/// about it when its next pre-trade request is rejected with
/// [`RejectCode::SystemUnavailable`](super::RejectCode::SystemUnavailable). See
/// the finalizer contract on [`Mutation`](crate::Mutation) for the reach of
/// that block.
///
/// # Lifecycle guidance
///
/// - Keep the `PreTradeReservation` alive until the order is actually sent.
/// - Call [`PreTradeReservation::commit`] only after the venue accepted the order and
///   the reservation must become durable engine state.
/// - Call [`PreTradeReservation::rollback`] if submission fails and reserved state must
///   be reverted immediately.
/// - After commit, persist [`PreTradeReservation::lock`] if later execution-report
///   processing depends on reservation-time policy context.
///
/// # Examples
///
/// ```rust
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use openpit::param::{Asset, Price, Quantity, Side};
/// use openpit::{Engine, Instrument, OrderOperation};
/// use openpit::param::TradeAmount;
///
/// use openpit::pretrade::policies::OrderValidationPolicy;
/// let engine = Engine::builder::<OrderOperation, (), ()>()
///     .no_sync()
///     .pre_trade(OrderValidationPolicy::new())
///     .build()?;
/// let order = OrderOperation {
///     instrument: Instrument::new(
///         Asset::new("AAPL")?,
///         Asset::new("USD")?,
///     ),
///     account_id: openpit::param::AccountId::from_u64(99224416),
///     side: Side::Buy,
///     trade_amount: TradeAmount::Quantity(
///         Quantity::from_str("10")?
///     ),
///     price: Some(Price::from_str("185")?),
/// };
/// let mut reservation = engine.start_pre_trade(order)?.execute()?;
/// let lock = reservation.lock().clone();
///
/// // Send order to venue. On success commit, on failure rollback.
/// reservation.commit(); // or reservation.rollback()
///
/// // If later reconciliation needs reservation context, persist `lock`
/// // together with the accepted order until the final execution report.
/// let _ = lock;
/// # Ok(())
/// # }
/// ```
pub struct PreTradeReservation {
    account_adjustments: Vec<AccountAdjustmentOutcome>,
    lock: PreTradeLock,
    inner: Option<Box<dyn ReservationHandle>>,
}

/// Internal capability interface used by [`PreTradeReservation`] and by
/// [`DropCopyOperation`](super::DropCopyOperation), which follows the same
/// finalization contract.
///
/// Provides only finalization: commit or rollback. Lock context and account
/// adjustments are passed directly to [`PreTradeReservation::from_handle`] so
/// they are not stored twice.
pub(crate) trait ReservationHandle {
    /// Finalizes the reservation by applying commit mutations.
    fn commit(self: Box<Self>);
    /// Finalizes the reservation by applying rollback mutations.
    fn rollback(self: Box<Self>);
}

impl PreTradeReservation {
    /// Finalizes by applying commit mutations.
    ///
    /// The reservation owns its commit/rollback capability exactly once.
    /// After `commit` returns, the reservation is consumed and any further
    /// finalization call other than [`Self::rollback`] (which is a no-op
    /// after consumption) is a programmer error.
    ///
    /// Void by contract: a commit callback that fails does not fail this call,
    /// it arms the engine kill switch. See the finalizer contract on
    /// [`Mutation`](crate::Mutation).
    ///
    /// # Panics
    ///
    /// Panics with `"pre-trade reservation already consumed"` if `commit`
    /// is called when the reservation has already been finalized. This
    /// happens when:
    ///
    /// - `commit` is called twice on the same reservation;
    /// - `commit` is called after [`Self::rollback`] has consumed the
    ///   reservation;
    /// - `commit` is called on a reservation whose
    ///   [`Drop`](std::ops::Drop) glue has already run the implicit
    ///   rollback (only reachable from raw FFI paths that retain a
    ///   pointer past the Rust scope).
    ///
    /// The panic is the API contract: each reservation must be finalized
    /// at most once and the caller is responsible for tracking ownership.
    pub fn commit(&mut self) {
        self.inner
            .take()
            .expect("pre-trade reservation already consumed")
            .commit();
    }

    /// Finalizes by applying rollback mutations.
    ///
    /// Unlike [`Self::commit`], calling `rollback` after the reservation
    /// has already been finalized is a no-op rather than a panic. This
    /// asymmetry is intentional: the destructor implicitly performs the
    /// same rollback when a reservation is dropped without explicit
    /// finalization, and a subsequent explicit `rollback` call by the
    /// owner must be safe so callers can defensively roll back without
    /// tracking whether they have already done so.
    ///
    /// Void by contract: a rollback callback that fails does not fail this
    /// call, it arms the engine kill switch. See the finalizer contract on
    /// [`Mutation`](crate::Mutation).
    ///
    /// # Panics
    ///
    /// This method does not panic on its own. Panics can only originate
    /// from inside individual rollback mutation closures registered by
    /// policies (for example, a deliberate `unreachable!` in a closure).
    /// The reservation API itself imposes no panic on double-rollback or
    /// rollback-after-commit; both are silent no-ops.
    ///
    /// A misbehaving policy mutation closure can still unwind.
    pub fn rollback(&mut self) {
        if let Some(inner) = self.inner.take() {
            inner.rollback();
        }
    }

    /// Returns the lock context attached to the reservation.
    ///
    /// Persist this value if post-trade reconciliation for the accepted order
    /// needs reservation-time policy context, such as fill-sensitive unlocking
    /// of the remaining reserved amount.
    pub fn lock(&self) -> &PreTradeLock {
        &self.lock
    }

    /// Returns account position modifications grouped by [`super::PolicyGroupId`].
    ///
    /// Contains zero or more entries. Policies that share a group tag contribute
    /// to the same entry; policies that report nothing do not create an entry.
    /// Order within a group follows policy registration order.
    pub fn account_adjustments(&self) -> &[AccountAdjustmentOutcome] {
        &self.account_adjustments
    }

    pub(crate) fn from_handle(
        inner: Box<dyn ReservationHandle>,
        lock: PreTradeLock,
        account_adjustments: Vec<AccountAdjustmentOutcome>,
    ) -> Self {
        Self {
            account_adjustments,
            lock,
            inner: Some(inner),
        }
    }
}

impl Drop for PreTradeReservation {
    fn drop(&mut self) {
        if let Some(inner) = self.inner.take() {
            inner.rollback();
        }
    }
}

#[cfg(test)]
mod tests {
    use std::cell::RefCell;
    use std::rc::Rc;

    use super::{PreTradeLock, PreTradeReservation, ReservationHandle};
    use crate::core::mutation::MutationFailureKillSwitch;
    use crate::core::DEFAULT_POLICY_GROUP_ID;
    use crate::param::Price;
    use crate::pretrade::handle::ReservationHandleImpl;
    use crate::{Mutation, Mutations};

    fn noop_action() {}

    #[test]
    fn drop_without_explicit_finalize_rolls_back() {
        let calls = Rc::new(RefCell::new(Vec::new()));
        let mut mutations = Mutations::with_capacity(2);
        let r1 = Rc::clone(&calls);
        mutations.push(Mutation::new(noop_action, move || {
            r1.borrow_mut().push("m1");
        }));
        let r2 = Rc::clone(&calls);
        mutations.push(Mutation::new(noop_action, move || {
            r2.borrow_mut().push("m2");
        }));

        let reservation = PreTradeReservation::from_handle(
            Box::new(ReservationHandleImpl::new(
                mutations,
                MutationFailureKillSwitch::inert(),
            )),
            PreTradeLock::default(),
            Vec::new(),
        );

        drop(reservation);

        assert_eq!(&*calls.borrow(), &["m2", "m1"]);
    }

    #[test]
    fn drop_without_explicit_finalize_can_ignore_non_kill_switch_mutations() {
        let calls = Rc::new(RefCell::new(Vec::new()));
        let mut mutations = Mutations::with_capacity(2);
        let rollback_calls = Rc::clone(&calls);
        mutations.push(Mutation::new(noop_action, move || {
            rollback_calls.borrow_mut().push("rollback");
        }));
        mutations.push(Mutation::new(noop_action, noop_action));

        let reservation = PreTradeReservation::from_handle(
            Box::new(ReservationHandleImpl::new(
                mutations,
                MutationFailureKillSwitch::inert(),
            )),
            PreTradeLock::default(),
            Vec::new(),
        );

        drop(reservation);

        assert_eq!(&*calls.borrow(), &["rollback"]);
    }

    #[test]
    #[should_panic(expected = "pre-trade reservation already consumed")]
    fn commit_panics_for_finalized_reservation() {
        let mut reservation = PreTradeReservation {
            account_adjustments: Vec::new(),
            lock: PreTradeLock::default(),
            inner: None,
        };
        reservation.commit();
    }

    #[test]
    fn rollback_is_noop_for_finalized_reservation() {
        let mut reservation = PreTradeReservation {
            account_adjustments: Vec::new(),
            lock: PreTradeLock::default(),
            inner: None,
        };
        reservation.rollback();
    }

    #[test]
    fn commit_with_locked_reservation_handle() {
        let mut reservation = PreTradeReservation::from_handle(
            Box::new(LockedReservationHandle),
            PreTradeLock::new(),
            Vec::new(),
        );
        reservation.commit();
    }

    #[test]
    fn lock_returns_reservation_lock_with_some_price() {
        let price = Price::from_str("185").expect("price must be valid");
        let reservation = PreTradeReservation::from_handle(
            Box::new(LockedReservationHandle),
            PreTradeLock::from_entries([(DEFAULT_POLICY_GROUP_ID, price)]),
            Vec::new(),
        );

        let prices: Vec<_> = reservation
            .lock()
            .prices_of(DEFAULT_POLICY_GROUP_ID)
            .collect();
        assert_eq!(prices, vec![price]);
    }

    #[test]
    fn lock_returns_reservation_lock_with_none_price() {
        let reservation = PreTradeReservation::from_handle(
            Box::new(LockedReservationHandle),
            PreTradeLock::new(),
            Vec::new(),
        );

        assert!(reservation
            .lock()
            .prices_of(DEFAULT_POLICY_GROUP_ID)
            .next()
            .is_none());
    }

    #[test]
    fn commit_executes_commit_mutations() {
        let calls = Rc::new(RefCell::new(Vec::new()));
        let mut mutations = Mutations::with_capacity(1);
        let commit_calls = Rc::clone(&calls);
        mutations.push(Mutation::new(
            move || {
                commit_calls.borrow_mut().push("commit");
            },
            noop_action,
        ));

        let mut reservation = PreTradeReservation::from_handle(
            Box::new(ReservationHandleImpl::new(
                mutations,
                MutationFailureKillSwitch::inert(),
            )),
            PreTradeLock::default(),
            Vec::new(),
        );
        reservation.commit();

        assert_eq!(&*calls.borrow(), &["commit"]);
    }

    #[test]
    fn rollback_executes_rollback_mutations() {
        let calls = Rc::new(RefCell::new(Vec::new()));
        let mut mutations = Mutations::with_capacity(1);
        let rollback_calls = Rc::clone(&calls);
        mutations.push(Mutation::new(noop_action, move || {
            rollback_calls.borrow_mut().push("rollback");
        }));

        let mut reservation = PreTradeReservation::from_handle(
            Box::new(ReservationHandleImpl::new(
                mutations,
                MutationFailureKillSwitch::inert(),
            )),
            PreTradeLock::default(),
            Vec::new(),
        );
        reservation.rollback();

        assert_eq!(&*calls.borrow(), &["rollback"]);
    }

    struct LockedReservationHandle;

    impl ReservationHandle for LockedReservationHandle {
        fn commit(self: Box<Self>) {}

        fn rollback(self: Box<Self>) {}
    }
}