Skip to main content

hypercall_settlement/
planning.rs

1use rust_decimal::Decimal;
2
3use crate::{
4    settle_position, PositionExpiredMessage, SettlementInput, SettlementInstrument,
5    SettlementOutput,
6};
7
8/// Engine position selected for settlement.
9#[derive(Debug, Clone, PartialEq, Eq)]
10pub struct SettlementPosition {
11    pub wallet: hypercall_types::WalletAddress,
12    pub position_size: Decimal,
13    pub entry_price: Decimal,
14}
15
16/// Build settlement outputs for all non-zero positions in one instrument.
17pub fn plan_position_settlements(
18    instrument: &SettlementInstrument,
19    reference_price: Decimal,
20    positions: &[SettlementPosition],
21) -> Vec<(SettlementPosition, SettlementOutput)> {
22    positions
23        .iter()
24        .filter(|position| position.position_size != Decimal::ZERO)
25        .map(|position| {
26            let output = settle_position(&SettlementInput {
27                option_type: instrument.option_type,
28                strike: instrument.strike,
29                reference_price,
30                position_size: position.position_size,
31                entry_price: position.entry_price,
32            });
33            (position.clone(), output)
34        })
35        .collect()
36}
37
38/// Build the canonical position-expired event for a settlement output.
39pub fn build_position_expired_message(
40    instrument: &SettlementInstrument,
41    position: &SettlementPosition,
42    output: &SettlementOutput,
43    margin_mode: hypercall_types::MarginMode,
44    timestamp: u64,
45) -> PositionExpiredMessage {
46    PositionExpiredMessage {
47        wallet_address: position.wallet,
48        margin_mode,
49        symbol: instrument.symbol.clone(),
50        position_size: position.position_size,
51        settlement_price: output.intrinsic_value,
52        settlement_value: output.settlement_value,
53        settlement_entry_price: Some(position.entry_price),
54        cost_basis: Some(output.cost_basis),
55        net_pnl: Some(output.net_pnl),
56        timestamp,
57    }
58}