openpit 0.5.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
// 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.

//! Account-adjustment path for [`SpotFundsPolicy`].

use crate::core::account_outcome::{OutcomeAmount, PnlOutcomeAmount};
use crate::core::sync_mode::SyncMode;
use crate::core::{
    AccountControl, AccountOutcomeEntry, HasAccountAdjustmentBalance,
    HasAccountAdjustmentBalanceAverageEntryPrice, HasAccountAdjustmentBalanceLowerBound,
    HasAccountAdjustmentBalanceRealizedPnl, HasAccountAdjustmentBalanceUpperBound,
    HasAccountAdjustmentHeld, HasAccountAdjustmentHeldLowerBound,
    HasAccountAdjustmentHeldUpperBound, HasAccountAdjustmentIncoming,
    HasAccountAdjustmentIncomingLowerBound, HasAccountAdjustmentIncomingUpperBound,
    HasBalanceAsset,
};
use crate::marketdata::MarketDataSync;
use crate::param::AccountId;
use crate::pretrade::holdings::{AdjustmentTarget, Holdings};
use crate::pretrade::policy::missing_required_field_account_adjustment_reject;
use crate::pretrade::{RejectScope, Rejects};
use crate::Mutations;

use super::rejects::{
    account_adjustment_bounds_exceeded_reject, adj_field, arithmetic_overflow_reject,
};
use super::rollback::{AdjustmentRollback, AvgRestore, PnlRestore};
use super::views::AdjustmentRequestView;
use super::SpotFundsPolicy;

/// Payload computed while mutating a holdings slot during an account
/// adjustment: the new holdings plus the named rollback payload.
///
/// Quantity deltas feed the concurrency-safe inverse-delta rollback. The prior
/// average and prior realized PnL are carried as absolute snapshots so rollback
/// can restore them when the adjustment force-set those fields, since neither
/// the weighted-average cost nor a forced realized value (which may overwrite an
/// untracked `None`) is delta-reversible. The realized-PnL delta is still
/// computed, but only to surface the delta/absolute outcome pair to the caller.
struct AdjustmentSlotUpdate {
    new: Holdings,
    rollback: AdjustmentRollback,
}

impl<Sync, MarketDataSyncMode> SpotFundsPolicy<Sync, MarketDataSyncMode>
where
    Sync: SyncMode,
    Sync::StorageLockingPolicyFactory: crate::storage::LockingPolicyFactory,
    MarketDataSyncMode: MarketDataSync,
{
    pub(super) fn read_adjustment_request<AccountAdjustment>(
        &self,
        adjustment: &AccountAdjustment,
    ) -> Result<AdjustmentRequestView, Rejects>
    where
        AccountAdjustment: HasBalanceAsset
            + HasAccountAdjustmentBalance
            + HasAccountAdjustmentBalanceAverageEntryPrice
            + HasAccountAdjustmentBalanceRealizedPnl
            + HasAccountAdjustmentBalanceLowerBound
            + HasAccountAdjustmentBalanceUpperBound
            + HasAccountAdjustmentHeld
            + HasAccountAdjustmentHeldLowerBound
            + HasAccountAdjustmentHeldUpperBound
            + HasAccountAdjustmentIncoming
            + HasAccountAdjustmentIncomingLowerBound
            + HasAccountAdjustmentIncomingUpperBound,
    {
        let asset = adjustment
            .balance_asset()
            .map_err(|e| {
                Rejects::from(missing_required_field_account_adjustment_reject(
                    self,
                    "balance asset",
                    &e,
                ))
            })?
            .clone();
        let balance = adj_field(self, "balance", adjustment.balance())?;
        let balance_average_entry_price = adj_field(
            self,
            "balance average entry price",
            adjustment.balance_average_entry_price(),
        )?;
        let balance_realized_pnl = adj_field(
            self,
            "balance realized pnl",
            adjustment.balance_realized_pnl(),
        )?;
        let balance_lower = adj_field(self, "balance lower bound", adjustment.balance_lower())?;
        let balance_upper = adj_field(self, "balance upper bound", adjustment.balance_upper())?;
        let held = adj_field(self, "held", adjustment.held())?;
        let held_lower = adj_field(self, "held lower bound", adjustment.held_lower())?;
        let held_upper = adj_field(self, "held upper bound", adjustment.held_upper())?;
        let incoming = adj_field(self, "incoming", adjustment.incoming())?;
        let incoming_lower = adj_field(self, "incoming lower bound", adjustment.incoming_lower())?;
        let incoming_upper = adj_field(self, "incoming upper bound", adjustment.incoming_upper())?;
        Ok(AdjustmentRequestView {
            asset,
            balance,
            balance_average_entry_price,
            balance_realized_pnl,
            balance_lower,
            balance_upper,
            held,
            held_lower,
            held_upper,
            incoming,
            incoming_lower,
            incoming_upper,
        })
    }

    pub(super) fn apply_account_adjustment_impl<AccountAdjustment>(
        &self,
        account_control: Option<AccountControl<<Sync as SyncMode>::StorageLockingPolicyFactory>>,
        account_id: AccountId,
        adjustment: &AccountAdjustment,
        mutations: &mut Mutations,
    ) -> Result<Vec<AccountOutcomeEntry>, Rejects>
    where
        AccountAdjustment: HasBalanceAsset
            + HasAccountAdjustmentBalance
            + HasAccountAdjustmentBalanceAverageEntryPrice
            + HasAccountAdjustmentBalanceRealizedPnl
            + HasAccountAdjustmentBalanceLowerBound
            + HasAccountAdjustmentBalanceUpperBound
            + HasAccountAdjustmentHeld
            + HasAccountAdjustmentHeldLowerBound
            + HasAccountAdjustmentHeldUpperBound
            + HasAccountAdjustmentIncoming
            + HasAccountAdjustmentIncomingLowerBound
            + HasAccountAdjustmentIncomingUpperBound,
        <<Sync as SyncMode>::StorageLockingPolicyFactory as crate::storage::LockingPolicyFactory>::Policy: 'static,
    {
        let request = self.read_adjustment_request(adjustment)?;
        if request.balance.is_none()
            && request.balance_average_entry_price.is_none()
            && request.balance_realized_pnl.is_none()
            && request.held.is_none()
            && request.incoming.is_none()
        {
            return Ok(Vec::new());
        }

        let key = (account_id, request.asset.clone());
        let update =
            self.holdings.with_mut_or_insert(
            key.clone(),
            Holdings::zero,
            |slot, _is_new| -> Result<AdjustmentSlotUpdate, Rejects> {
                let current = *slot;
                // Snapshot the prior average entry price and realized PnL so
                // rollback can restore each absolutely when this adjustment
                // force-sets it. Neither is delta-reversible: the weighted-
                // average cost is path-dependent, and a forced realized value can
                // overwrite a prior untracked `None` that no delta could restore.
                let prior_avg = current.avg_entry_price();
                let prior_realized = current.realized_pnl();
                let mut new = current;

                if let Some(amount) = request.balance {
                    new = new
                        .apply_adjustment(AdjustmentTarget::Available, amount)
                        .map_err(|_| {
                            Rejects::from(arithmetic_overflow_reject(
                                Self::NAME,
                                RejectScope::Account,
                                format!(
                                    "account adjustment overflow: account {account_id}, \
                                     asset {asset}, field balance, current {val}, applied {amount}",
                                    asset = request.asset,
                                    val = new.available(),
                                ),
                            ))
                        })?;
                    if !new.available_within_bounds(request.balance_lower, request.balance_upper) {
                        return Err(Rejects::from(account_adjustment_bounds_exceeded_reject(
                            Self::NAME,
                            account_id,
                            &request.asset,
                            "balance",
                            new.available(),
                            request.balance_lower,
                            request.balance_upper,
                        )));
                    }
                }

                if let Some(amount) = request.held {
                    new = new
                        .apply_adjustment(AdjustmentTarget::Held, amount)
                        .map_err(|_| {
                            Rejects::from(arithmetic_overflow_reject(
                                Self::NAME,
                                RejectScope::Account,
                                format!(
                                    "account adjustment overflow: account {account_id}, \
                                     asset {asset}, field held, current {val}, applied {amount}",
                                    asset = request.asset,
                                    val = new.held(),
                                ),
                            ))
                        })?;
                    if !new.held_within_bounds(request.held_lower, request.held_upper) {
                        return Err(Rejects::from(account_adjustment_bounds_exceeded_reject(
                            Self::NAME,
                            account_id,
                            &request.asset,
                            "held",
                            new.held(),
                            request.held_lower,
                            request.held_upper,
                        )));
                    }
                }

                if let Some(amount) = request.incoming {
                    new = new
                        .apply_adjustment(AdjustmentTarget::Incoming, amount)
                        .map_err(|_| {
                            Rejects::from(arithmetic_overflow_reject(
                                Self::NAME,
                                RejectScope::Account,
                                format!(
                                    "account adjustment overflow: account {account_id}, \
                                     asset {asset}, field incoming, current {val}, applied {amount}",
                                    asset = request.asset,
                                    val = new.incoming(),
                                ),
                            ))
                        })?;
                    if !new.incoming_within_bounds(request.incoming_lower, request.incoming_upper) {
                        return Err(Rejects::from(account_adjustment_bounds_exceeded_reject(
                            Self::NAME,
                            account_id,
                            &request.asset,
                            "incoming",
                            new.incoming(),
                            request.incoming_lower,
                            request.incoming_upper,
                        )));
                    }
                }

                // A balance operation may carry the position's average entry
                // price and/or force-set realized PnL even without a quantity
                // change. Set each absolutely when present and leave the prior
                // value otherwise.
                if let Some(avg) = request.balance_average_entry_price {
                    new = new.with_avg_entry_price(Some(avg));
                }
                if let Some(realized) = request.balance_realized_pnl {
                    new = new.with_realized_pnl(realized);
                }

                let avg_may_change = request.balance_average_entry_price.is_some()
                    || ((request.balance.is_some() || request.held.is_some())
                        && current.avg_entry_price().is_some());
                let clear_avg_on_flat = if avg_may_change {
                    let net_owned = new.available().checked_add(new.held()).map_err(|_| {
                        Rejects::from(arithmetic_overflow_reject(
                            Self::NAME,
                            RejectScope::Account,
                            format!(
                                "account adjustment net-position overflow: account {account_id}, \
                                 asset {asset}",
                                asset = request.asset,
                            ),
                        ))
                    })?;
                    net_owned.is_zero()
                } else {
                    false
                };
                if clear_avg_on_flat {
                    new = new.with_avg_entry_price(None);
                }
                let restore_avg_on_rollback =
                    request.balance_average_entry_price.is_some()
                        || (clear_avg_on_flat && current.avg_entry_price().is_some());

                // Compute per-field deltas with checked arithmetic before writing
                // the slot. This serves two purposes:
                //   1. Outcome reporting: delta = actual applied change per field.
                //   2. Rollback: the inverse delta is later applied to whatever
                //      the slot holds at rollback time (safe for FullSync).
                // For Delta adjustments overflow here is practically impossible
                // (new was derived from current via checked_add); for Absolute
                // adjustments with extreme opposing values it can fail, and we
                // reject before writing so no partial state escapes.
                let available_delta = new
                    .available()
                    .checked_sub(current.available())
                    .map_err(|_| {
                        Rejects::from(arithmetic_overflow_reject(
                            Self::NAME,
                            RejectScope::Account,
                            format!(
                                "account adjustment delta overflow: account {account_id}, \
                                 asset {asset}, field balance",
                                asset = request.asset,
                            ),
                        ))
                    })?;
                let held_delta = new
                    .held()
                    .checked_sub(current.held())
                    .map_err(|_| {
                        Rejects::from(arithmetic_overflow_reject(
                            Self::NAME,
                            RejectScope::Account,
                            format!(
                                "account adjustment delta overflow: account {account_id}, \
                                 asset {asset}, field held",
                                asset = request.asset,
                            ),
                        ))
                    })?;
                let incoming_delta = new
                    .incoming()
                    .checked_sub(current.incoming())
                    .map_err(|_| {
                        Rejects::from(arithmetic_overflow_reject(
                            Self::NAME,
                            RejectScope::Account,
                            format!(
                                "account adjustment delta overflow: account {account_id}, \
                                 asset {asset}, field incoming",
                                asset = request.asset,
                            ),
                        ))
                    })?;
                // Realized-PnL delta is computed only to surface the
                // delta/absolute outcome pair (rollback restores realized PnL
                // from `prior_realized`, not from this delta). It exists only
                // when this adjustment force-set a tracked value; if the prior
                // value was untracked, the forced absolute value is reported as
                // the delta from the untracked state.
                let realized_pnl_delta = match (
                    request.balance_realized_pnl,
                    new.realized_pnl(),
                    current.realized_pnl(),
                ) {
                    (Some(_), Some(new_realized), Some(current_realized)) => {
                        Some(new_realized.checked_sub(current_realized).map_err(|_| {
                            Rejects::from(arithmetic_overflow_reject(
                                Self::NAME,
                                RejectScope::Account,
                                format!(
                                    "account adjustment delta overflow: account {account_id}, \
                                     asset {asset}, field realized pnl",
                                    asset = request.asset,
                                ),
                            ))
                        })?)
                    }
                    (Some(_), Some(new_realized), None) => Some(new_realized),
                    _ => None,
                };

                *slot = new; // synchronous write, see register_*_rollback comments
                Ok(AdjustmentSlotUpdate {
                    new,
                    rollback: AdjustmentRollback {
                        available_delta,
                        held_delta,
                        incoming_delta,
                        realized_pnl_delta,
                        prior_avg: restore_avg_on_rollback.then_some(AvgRestore(prior_avg)),
                        prior_realized: request
                            .balance_realized_pnl
                            .is_some()
                            .then_some(PnlRestore(prior_realized)),
                    },
                })
            },
        )?;
        let new = update.new;
        let rollback = update.rollback;
        if new.is_zero() {
            self.holdings.remove_if_zero(&key);
        }
        self.register_adjustment_rollback(mutations, account_control, key, rollback);

        let balance_outcome = request.balance.map(|_| OutcomeAmount {
            delta: rollback.available_delta,
            absolute: new.available(),
        });
        let held_outcome = request.held.map(|_| OutcomeAmount {
            delta: rollback.held_delta,
            absolute: new.held(),
        });
        let incoming_outcome = request.incoming.map(|_| OutcomeAmount {
            delta: rollback.incoming_delta,
            absolute: new.incoming(),
        });
        // Surface the current average alongside balance changes and explicit
        // average force-sets. Realized PnL is surfaced only when the adjustment
        // force-set it, as a delta/absolute pair.
        let average_entry_price = (request.balance.is_some()
            || request.balance_average_entry_price.is_some())
        .then_some(new.avg_entry_price())
        .flatten();
        let realized_pnl = match (request.balance_realized_pnl, rollback.realized_pnl_delta) {
            (Some(_), Some(delta)) => new
                .realized_pnl()
                .map(|absolute| PnlOutcomeAmount { delta, absolute }),
            _ => None,
        };

        Ok(vec![AccountOutcomeEntry {
            asset: request.asset,
            balance: balance_outcome,
            held: held_outcome,
            incoming: incoming_outcome,
            realized_pnl,
            average_entry_price,
        }])
    }
}