Skip to main content

qx_zhenlu/
algo.rs

1//! Deterministic parent-order slicing primitives shared by execution clients.
2//!
3//! This module only plans child quantities and decision timestamps. It never
4//! submits orders: every child still has to pass through the normal risk and
5//! execution gateway.
6
7use serde::{Deserialize, Serialize};
8use std::fmt;
9
10pub const MAX_ALGO_CHILDREN: usize = 10_000;
11
12#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
13#[serde(deny_unknown_fields)]
14pub struct AlgoChildSlice {
15    pub parent_id: String,
16    pub child_index: u32,
17    pub scheduled_ts: u64,
18    pub quantity_raw: i128,
19}
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(deny_unknown_fields)]
23pub struct VwapVolumeBucket {
24    pub ts: u64,
25    pub market_volume_raw: u128,
26}
27
28#[derive(Clone, Debug, PartialEq, Eq)]
29pub enum AlgoExecutionError {
30    InvalidParent,
31    InvalidRange,
32    InvalidQuantity,
33    InvalidChildCount,
34    InvalidVolumeProfile,
35    ArithmeticOverflow,
36}
37
38impl fmt::Display for AlgoExecutionError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str(match self {
41            Self::InvalidParent => "algo parent id must not be empty",
42            Self::InvalidRange => "algo schedule end must be greater than start",
43            Self::InvalidQuantity => "parent quantity must be positive",
44            Self::InvalidChildCount => "child count must be in 1..=10000 and not exceed quantity",
45            Self::InvalidVolumeProfile => {
46                "VWAP volume buckets must be ordered, positive and non-empty"
47            }
48            Self::ArithmeticOverflow => "algo schedule arithmetic overflow",
49        })
50    }
51}
52
53impl std::error::Error for AlgoExecutionError {}
54
55/// Split a parent quantity into near-equal slices distributed over the closed
56/// `[start_ts, end_ts]` interval. Remainder units go to earlier slices so the
57/// result is deterministic and exactly conserves the parent quantity.
58pub fn plan_twap(
59    parent_id: &str,
60    total_quantity_raw: i128,
61    start_ts: u64,
62    end_ts: u64,
63    child_count: usize,
64) -> Result<Vec<AlgoChildSlice>, AlgoExecutionError> {
65    validate_common(parent_id, total_quantity_raw, start_ts, end_ts, child_count)?;
66    let count = child_count as i128;
67    let base = total_quantity_raw / count;
68    let remainder = total_quantity_raw % count;
69    let span = u128::from(end_ts - start_ts);
70    let denominator = child_count.saturating_sub(1).max(1) as u128;
71    (0..child_count)
72        .map(|index| {
73            let offset = if child_count == 1 {
74                0
75            } else {
76                span.checked_mul(index as u128)
77                    .ok_or(AlgoExecutionError::ArithmeticOverflow)?
78                    / denominator
79            };
80            let scheduled_ts = u128::from(start_ts)
81                .checked_add(offset)
82                .and_then(|value| u64::try_from(value).ok())
83                .ok_or(AlgoExecutionError::ArithmeticOverflow)?;
84            Ok(AlgoChildSlice {
85                parent_id: parent_id.to_owned(),
86                child_index: index as u32,
87                scheduled_ts,
88                quantity_raw: base + if (index as i128) < remainder { 1 } else { 0 },
89            })
90        })
91        .collect()
92}
93
94/// Allocate parent quantity proportional to a frozen market-volume profile.
95/// The last bucket receives the integer rounding remainder, preserving the
96/// exact parent quantity. The profile is bounded and must contain strictly
97/// increasing timestamps and positive volumes.
98pub fn plan_vwap(
99    parent_id: &str,
100    total_quantity_raw: i128,
101    start_ts: u64,
102    end_ts: u64,
103    buckets: &[VwapVolumeBucket],
104) -> Result<Vec<AlgoChildSlice>, AlgoExecutionError> {
105    let count = buckets.len();
106    validate_common(parent_id, total_quantity_raw, start_ts, end_ts, count)?;
107    if buckets.iter().any(|bucket| bucket.market_volume_raw == 0)
108        || buckets
109            .iter()
110            .any(|bucket| bucket.ts < start_ts || bucket.ts > end_ts)
111        || buckets.windows(2).any(|pair| pair[0].ts >= pair[1].ts)
112    {
113        return Err(AlgoExecutionError::InvalidVolumeProfile);
114    }
115    let total_volume = buckets.iter().try_fold(0_u128, |sum, bucket| {
116        sum.checked_add(bucket.market_volume_raw)
117            .ok_or(AlgoExecutionError::ArithmeticOverflow)
118    })?;
119    if total_volume == 0 {
120        return Err(AlgoExecutionError::InvalidVolumeProfile);
121    }
122    let parent_qty = total_quantity_raw as u128;
123    let mut assigned = 0_u128;
124    let mut slices = Vec::with_capacity(count);
125    for (index, bucket) in buckets.iter().enumerate() {
126        let quantity = if index + 1 == count {
127            parent_qty
128                .checked_sub(assigned)
129                .ok_or(AlgoExecutionError::ArithmeticOverflow)?
130        } else {
131            mul_div_floor(parent_qty, bucket.market_volume_raw, total_volume)?
132        };
133        assigned = assigned
134            .checked_add(quantity)
135            .ok_or(AlgoExecutionError::ArithmeticOverflow)?;
136        if quantity > 0 {
137            slices.push(AlgoChildSlice {
138                parent_id: parent_id.to_owned(),
139                child_index: index as u32,
140                scheduled_ts: bucket.ts,
141                quantity_raw: i128::try_from(quantity)
142                    .map_err(|_| AlgoExecutionError::ArithmeticOverflow)?,
143            });
144        }
145    }
146    if assigned != parent_qty {
147        return Err(AlgoExecutionError::ArithmeticOverflow);
148    }
149    Ok(slices)
150}
151
152fn validate_common(
153    parent_id: &str,
154    quantity: i128,
155    start_ts: u64,
156    end_ts: u64,
157    child_count: usize,
158) -> Result<(), AlgoExecutionError> {
159    if parent_id.trim().is_empty() {
160        return Err(AlgoExecutionError::InvalidParent);
161    }
162    if end_ts <= start_ts {
163        return Err(AlgoExecutionError::InvalidRange);
164    }
165    if quantity <= 0 {
166        return Err(AlgoExecutionError::InvalidQuantity);
167    }
168    if child_count == 0 || child_count > MAX_ALGO_CHILDREN || child_count as i128 > quantity {
169        return Err(AlgoExecutionError::InvalidChildCount);
170    }
171    Ok(())
172}
173
174fn mul_div_floor(a: u128, b: u128, divisor: u128) -> Result<u128, AlgoExecutionError> {
175    if divisor == 0 {
176        return Err(AlgoExecutionError::ArithmeticOverflow);
177    }
178    let whole = (a / divisor)
179        .checked_mul(b)
180        .ok_or(AlgoExecutionError::ArithmeticOverflow)?;
181    let fraction = (a % divisor)
182        .checked_mul(b)
183        .ok_or(AlgoExecutionError::ArithmeticOverflow)?
184        / divisor;
185    whole
186        .checked_add(fraction)
187        .ok_or(AlgoExecutionError::ArithmeticOverflow)
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn twap_conserves_quantity_and_distributes_remainder_deterministically() {
196        let plan = plan_twap("parent-7", 11, 10, 40, 4).unwrap();
197        assert_eq!(
198            plan.iter()
199                .map(|slice| slice.quantity_raw)
200                .collect::<Vec<_>>(),
201            [3, 3, 3, 2]
202        );
203        assert_eq!(
204            plan.iter()
205                .map(|slice| slice.scheduled_ts)
206                .collect::<Vec<_>>(),
207            [10, 20, 30, 40]
208        );
209        assert!(plan.iter().all(|slice| slice.parent_id == "parent-7"));
210    }
211
212    #[test]
213    fn vwap_uses_volume_weights_and_assigns_rounding_remainder_to_last_child() {
214        let plan = plan_vwap(
215            "p",
216            10,
217            100,
218            300,
219            &[
220                VwapVolumeBucket {
221                    ts: 100,
222                    market_volume_raw: 1,
223                },
224                VwapVolumeBucket {
225                    ts: 200,
226                    market_volume_raw: 2,
227                },
228                VwapVolumeBucket {
229                    ts: 300,
230                    market_volume_raw: 3,
231                },
232            ],
233        )
234        .unwrap();
235        assert_eq!(
236            plan.iter()
237                .map(|slice| slice.quantity_raw)
238                .collect::<Vec<_>>(),
239            [1, 3, 6]
240        );
241        assert_eq!(
242            plan.iter().map(|slice| slice.quantity_raw).sum::<i128>(),
243            10
244        );
245    }
246
247    #[test]
248    fn vwap_rejects_unordered_or_zero_volume_profiles() {
249        let unordered = [
250            VwapVolumeBucket {
251                ts: 200,
252                market_volume_raw: 1,
253            },
254            VwapVolumeBucket {
255                ts: 100,
256                market_volume_raw: 2,
257            },
258        ];
259        assert_eq!(
260            plan_vwap("p", 3, 100, 200, &unordered),
261            Err(AlgoExecutionError::InvalidVolumeProfile)
262        );
263        let zero = [VwapVolumeBucket {
264            ts: 100,
265            market_volume_raw: 0,
266        }];
267        assert_eq!(
268            plan_vwap("p", 1, 100, 200, &zero),
269            Err(AlgoExecutionError::InvalidVolumeProfile)
270        );
271    }
272
273    #[test]
274    fn child_count_and_time_bounds_are_fail_closed() {
275        assert_eq!(
276            plan_twap("p", 2, 10, 10, 1),
277            Err(AlgoExecutionError::InvalidRange)
278        );
279        assert_eq!(
280            plan_twap("p", 1, 10, 20, 2),
281            Err(AlgoExecutionError::InvalidChildCount)
282        );
283    }
284}