1use crate::{ExecutionEventPort, PortExecutionService, RiskPort, VenuePort};
10mod validation;
11use qx_core::{Order, OrderStatus};
12use qx_zhenlu::AlgoChildSlice;
13use serde::{Deserialize, Serialize};
14use validation::{same_child_identity, validate_checkpoint, validate_input};
15
16pub const ALGO_EXECUTION_STATE_SCHEMA_VERSION: u32 = 1;
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
19#[serde(rename_all = "snake_case")]
20pub enum AlgoExecutionStatus {
21 Ready,
22 Running,
23 CancelRequested,
24 Completed,
25 Cancelled,
26 Failed,
27 ReconcileRequired,
28}
29
30#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
31#[serde(tag = "kind", rename_all = "snake_case")]
32pub enum AlgoExecutionStep {
33 NotDue {
34 next_scheduled_ts: u64,
35 },
36 Submitted {
37 client_order_id: u64,
38 status: OrderStatus,
39 },
40 WaitingForChildren {
41 open_orders: usize,
42 filled_raw: i128,
43 },
44 CancellationSubmitted {
45 client_order_id: u64,
46 },
47 Completed {
48 filled_raw: i128,
49 unfilled_raw: i128,
50 },
51 Cancelled {
52 filled_raw: i128,
53 unfilled_raw: i128,
54 },
55 Failed {
56 reason: String,
57 },
58 ReconcileRequired {
59 reason: String,
60 },
61}
62
63#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
67#[serde(deny_unknown_fields)]
68pub struct AlgoExecutionState {
69 pub schema_version: u32,
70 pub parent_id: String,
71 pub parent_order: Order,
72 pub plan: Vec<AlgoChildSlice>,
73 pub child_order_id_base: u64,
74 pub next_slice_position: usize,
75 pub child_order_ids: Vec<u64>,
76 #[serde(default, skip_serializing_if = "Option::is_none")]
79 pub last_step_ts: Option<u64>,
80 pub status: AlgoExecutionStatus,
81 pub cancel_requested: bool,
82 #[serde(default, skip_serializing_if = "Option::is_none")]
83 pub failure: Option<String>,
84}
85
86#[derive(Clone, Debug, PartialEq, Eq)]
89pub struct AlgoParentOrder {
90 pub parent_id: String,
91 pub parent_order: Order,
92 pub plan: Vec<AlgoChildSlice>,
93 pub child_order_id_base: u64,
94}
95
96impl AlgoExecutionState {
97 pub fn new(input: AlgoParentOrder) -> Result<Self, String> {
98 validate_input(&input)?;
99 let state = Self {
100 schema_version: ALGO_EXECUTION_STATE_SCHEMA_VERSION,
101 parent_id: input.parent_id,
102 parent_order: input.parent_order,
103 plan: input.plan,
104 child_order_id_base: input.child_order_id_base,
105 next_slice_position: 0,
106 child_order_ids: Vec::new(),
107 last_step_ts: None,
108 status: AlgoExecutionStatus::Ready,
109 cancel_requested: false,
110 failure: None,
111 };
112 validate_checkpoint(&state)?;
113 Ok(state)
114 }
115
116 pub fn request_cancel(&mut self) -> Result<(), String> {
117 validate_checkpoint(self)?;
118 match self.status {
119 AlgoExecutionStatus::Completed
120 | AlgoExecutionStatus::Cancelled
121 | AlgoExecutionStatus::Failed
122 | AlgoExecutionStatus::ReconcileRequired => {
123 return Err(format!("算法父单终态不可取消: {:?}", self.status));
124 }
125 _ => {}
126 }
127 self.cancel_requested = true;
128 self.status = AlgoExecutionStatus::CancelRequested;
129 Ok(())
130 }
131
132 pub fn to_json(&self) -> Result<String, String> {
133 validate_checkpoint(self)?;
134 serde_json::to_string(self).map_err(|error| format!("算法执行状态序列化失败: {error}"))
135 }
136
137 pub fn from_json(payload: &str) -> Result<Self, String> {
138 let state: Self = serde_json::from_str(payload)
139 .map_err(|error| format!("算法执行状态 JSON 无效: {error}"))?;
140 validate_checkpoint(&state)?;
141 Ok(state)
142 }
143
144 pub fn step<V, P, R>(
148 &mut self,
149 now: u64,
150 gateway: &mut PortExecutionService<'_, V, P>,
151 risk: &R,
152 ) -> Result<AlgoExecutionStep, String>
153 where
154 V: VenuePort,
155 P: ExecutionEventPort,
156 R: RiskPort,
157 {
158 validate_checkpoint(self)?;
159 if gateway.now != now {
160 return Err(format!(
161 "算法调度时间与执行网关时间不一致: scheduler={now} gateway={}",
162 gateway.now
163 ));
164 }
165 if let Some(last) = self.last_step_ts {
166 if now < last {
167 return Err(format!(
168 "算法执行时钟不得回退: previous={last} current={now}"
169 ));
170 }
171 }
172 self.last_step_ts = Some(now);
173 if let Some(result) = self.terminal_step(gateway)? {
174 return Ok(result);
175 }
176 if self.cancel_requested {
177 return self.cancel_one(gateway);
178 }
179 if self.next_slice_position < self.plan.len() {
180 let slice = &self.plan[self.next_slice_position];
181 if now < slice.scheduled_ts {
182 return Ok(AlgoExecutionStep::NotDue {
183 next_scheduled_ts: slice.scheduled_ts,
184 });
185 }
186 return self.submit_one(gateway, risk);
187 }
188 self.finish_or_wait(gateway)
189 }
190
191 fn submit_one<V, P, R>(
192 &mut self,
193 gateway: &mut PortExecutionService<'_, V, P>,
194 risk: &R,
195 ) -> Result<AlgoExecutionStep, String>
196 where
197 V: VenuePort,
198 P: ExecutionEventPort,
199 R: RiskPort,
200 {
201 let position = self.next_slice_position;
202 let slice = self.plan[position].clone();
203 let client_order_id = self.child_client_id(position)?;
204 let child_order = self.child_order(&slice, client_order_id);
205
206 if let Some(existing) = gateway.order(client_order_id) {
207 if !same_child_identity(&existing, &child_order) {
208 return self.require_reconcile(format!(
209 "child client id 已被不同订单占用: parent={} child_index={} client_order_id={client_order_id}",
210 self.parent_id, slice.child_index
211 ));
212 }
213 match existing.status {
214 OrderStatus::PendingSubmit => {
215 gateway.submit_with_risk_and_correlation(
216 child_order,
217 risk,
218 self.child_correlation(&slice),
219 )?;
220 }
221 OrderStatus::Unknown | OrderStatus::Submitted | OrderStatus::CancelPending => {
222 return self.require_reconcile(format!(
223 "恢复时子单状态 {:?} 需要对账,禁止重发: client_order_id={client_order_id}",
224 existing.status
225 ));
226 }
227 _ => {
228 self.child_order_ids.push(client_order_id);
229 self.next_slice_position += 1;
230 self.status = AlgoExecutionStatus::Running;
231 return Ok(AlgoExecutionStep::Submitted {
232 client_order_id,
233 status: existing.status,
234 });
235 }
236 }
237 } else if let Err(error) = gateway.submit_with_risk_and_correlation(
238 child_order,
239 risk,
240 self.child_correlation(&slice),
241 ) {
242 if gateway
243 .order(client_order_id)
244 .is_some_and(|order| order.status == OrderStatus::Unknown)
245 {
246 return self.require_reconcile(format!(
247 "子单提交结果未知,必须先对账: client_order_id={client_order_id}: {error}"
248 ));
249 }
250 self.status = AlgoExecutionStatus::Failed;
251 self.failure = Some(error.clone());
252 return Ok(AlgoExecutionStep::Failed { reason: error });
253 }
254
255 let Some(order) = gateway.order(client_order_id) else {
256 return self.require_reconcile(format!(
257 "Venue 已返回但 OMS 查不到子单: client_order_id={client_order_id}"
258 ));
259 };
260 if order.status == OrderStatus::Unknown {
261 return self.require_reconcile(format!(
262 "子单提交后进入待对账: client_order_id={client_order_id}"
263 ));
264 }
265 self.child_order_ids.push(client_order_id);
266 self.next_slice_position += 1;
267 self.status = AlgoExecutionStatus::Running;
268 Ok(AlgoExecutionStep::Submitted {
269 client_order_id,
270 status: order.status,
271 })
272 }
273
274 fn cancel_one<V, P>(
275 &mut self,
276 gateway: &mut PortExecutionService<'_, V, P>,
277 ) -> Result<AlgoExecutionStep, String>
278 where
279 V: VenuePort,
280 P: ExecutionEventPort,
281 {
282 for client_order_id in self.child_order_ids.iter().copied() {
283 let Some(order) = gateway.order(client_order_id) else {
284 return self.require_reconcile(format!(
285 "撤单前 OMS 查不到算法子单: client_order_id={client_order_id}"
286 ));
287 };
288 match order.status {
289 OrderStatus::Accepted | OrderStatus::Working | OrderStatus::PartiallyFilled => {
290 if let Err(error) = gateway.cancel(client_order_id) {
291 if gateway
292 .order(client_order_id)
293 .is_some_and(|order| order.status == OrderStatus::Unknown)
294 {
295 return self.require_reconcile(format!(
296 "子单撤销结果未知,必须先对账: client_order_id={client_order_id}: {error}"
297 ));
298 }
299 return Err(error);
300 }
301 return Ok(AlgoExecutionStep::CancellationSubmitted { client_order_id });
302 }
303 OrderStatus::Unknown | OrderStatus::Submitted | OrderStatus::CancelPending => {
304 return self.require_reconcile(format!(
305 "撤单遇到 {:?} 子单,需要先对账: client_order_id={client_order_id}",
306 order.status
307 ));
308 }
309 OrderStatus::PendingSubmit
310 | OrderStatus::Filled
311 | OrderStatus::Cancelled
312 | OrderStatus::Rejected
313 | OrderStatus::Expired => {}
314 }
315 }
316 let (filled_raw, unfilled_raw) = self.fill_totals(gateway)?;
317 self.status = AlgoExecutionStatus::Cancelled;
318 Ok(AlgoExecutionStep::Cancelled {
319 filled_raw,
320 unfilled_raw,
321 })
322 }
323
324 fn finish_or_wait<V, P>(
325 &mut self,
326 gateway: &PortExecutionService<'_, V, P>,
327 ) -> Result<AlgoExecutionStep, String>
328 where
329 V: VenuePort,
330 P: ExecutionEventPort,
331 {
332 let mut open_orders = 0;
333 for client_order_id in &self.child_order_ids {
334 let Some(order) = gateway.order(*client_order_id) else {
335 return self.require_reconcile(format!(
336 "算法执行状态引用了缺失子单: client_order_id={client_order_id}"
337 ));
338 };
339 match order.status {
340 OrderStatus::Unknown | OrderStatus::Submitted | OrderStatus::CancelPending => {
341 return self.require_reconcile(format!(
342 "算法子单处于 {:?},必须先对账: client_order_id={client_order_id}",
343 order.status
344 ));
345 }
346 OrderStatus::Accepted | OrderStatus::Working | OrderStatus::PartiallyFilled => {
347 open_orders += 1;
348 }
349 OrderStatus::PendingSubmit
350 | OrderStatus::Filled
351 | OrderStatus::Cancelled
352 | OrderStatus::Rejected
353 | OrderStatus::Expired => {}
354 }
355 }
356 let (filled_raw, unfilled_raw) = self.fill_totals(gateway)?;
357 if open_orders > 0 {
358 return Ok(AlgoExecutionStep::WaitingForChildren {
359 open_orders,
360 filled_raw,
361 });
362 }
363 self.status = AlgoExecutionStatus::Completed;
364 Ok(AlgoExecutionStep::Completed {
365 filled_raw,
366 unfilled_raw,
367 })
368 }
369
370 fn terminal_step<V, P>(
371 &mut self,
372 gateway: &PortExecutionService<'_, V, P>,
373 ) -> Result<Option<AlgoExecutionStep>, String>
374 where
375 V: VenuePort,
376 P: ExecutionEventPort,
377 {
378 let result = match self.status {
379 AlgoExecutionStatus::Completed => {
380 let (filled_raw, unfilled_raw) = self.fill_totals(gateway)?;
381 Some(AlgoExecutionStep::Completed {
382 filled_raw,
383 unfilled_raw,
384 })
385 }
386 AlgoExecutionStatus::Cancelled => {
387 let (filled_raw, unfilled_raw) = self.fill_totals(gateway)?;
388 Some(AlgoExecutionStep::Cancelled {
389 filled_raw,
390 unfilled_raw,
391 })
392 }
393 AlgoExecutionStatus::Failed => Some(AlgoExecutionStep::Failed {
394 reason: self
395 .failure
396 .clone()
397 .unwrap_or_else(|| "算法执行失败".into()),
398 }),
399 AlgoExecutionStatus::ReconcileRequired => Some(AlgoExecutionStep::ReconcileRequired {
400 reason: self.failure.clone().unwrap_or_else(|| "需要对账".into()),
401 }),
402 _ => None,
403 };
404 Ok(result)
405 }
406
407 fn fill_totals<V, P>(
408 &self,
409 gateway: &PortExecutionService<'_, V, P>,
410 ) -> Result<(i128, i128), String>
411 where
412 V: VenuePort,
413 P: ExecutionEventPort,
414 {
415 let filled_raw = self.child_order_ids.iter().try_fold(0_i128, |sum, id| {
416 let order = gateway
417 .order(*id)
418 .ok_or_else(|| format!("算法子单缺失: client_order_id={id}"))?;
419 sum.checked_add(order.filled.raw())
420 .ok_or_else(|| "算法父单累计成交数量溢出".to_string())
421 })?;
422 if filled_raw > self.parent_order.qty.raw() {
423 return Err(format!(
424 "算法子单累计成交超过父单: parent={} filled={} qty={}",
425 self.parent_id,
426 filled_raw,
427 self.parent_order.qty.raw()
428 ));
429 }
430 Ok((filled_raw, self.parent_order.qty.raw() - filled_raw))
431 }
432
433 fn child_order(&self, slice: &AlgoChildSlice, client_order_id: u64) -> Order {
434 let mut child = self.parent_order.clone();
435 child.client_id = client_order_id;
436 child.qty = qx_core::Quantity::from_raw(slice.quantity_raw);
437 child.filled = qx_core::Quantity::ZERO;
438 child.status = OrderStatus::PendingSubmit;
439 child
440 }
441
442 fn child_client_id(&self, position: usize) -> Result<u64, String> {
443 self.child_order_id_base
444 .checked_add(position as u64)
445 .ok_or_else(|| "算法子单 client id 溢出".into())
446 }
447
448 fn child_correlation(&self, slice: &AlgoChildSlice) -> String {
449 format!("algo:{}:child:{}", self.parent_id, slice.child_index)
450 }
451
452 fn require_reconcile(&mut self, reason: String) -> Result<AlgoExecutionStep, String> {
453 self.status = AlgoExecutionStatus::ReconcileRequired;
454 self.failure = Some(reason.clone());
455 Ok(AlgoExecutionStep::ReconcileRequired { reason })
456 }
457}
458
459#[cfg(test)]
460mod tests;