撤单替换逻辑
Cancel Replace Logic
题目详情
量化交易系统的订单管理逻辑必须可靠处理订单生命周期,防止意外重复成交和管理风险。关键操作是取消替换:原子地取消现有活跃订单并同时提交新订单。
任务:实现取消替换处理器类,原子处理订单的取消替换。维护订单状态机,确保取消替换操作在新订单提交前完成旧订单取消。
英文原题
In quantitative trading systems, order management logic must reliably handle the lifecycle of orders to prevent unintended duplicate executions and manage risk. A critical operation is the cancel-replace, which atomically cancels an existing active order and submits a new one. Implementing this state transition correctly ensures accurate tracking of live, filled, and canceled orders within an exchange simulator or execution gateway.
Task
Implement an OrderManager class that maintains the state
解析
问题分析
撤单替换(Cancel-Replace)允许修改已提交订单的价格或数量而不丢失队列位置。交易所通常将 Cancel-Replace 作为原子操作:如果撤单成功则立即提交新单,否则保持原订单不变。
解法
class CancelReplaceHandler {
std::unordered_map<uint64_t, Order> active_orders_;
public:
enum Result { REPLACED, REJECTED_NOT_FOUND, REJECTED_ALREADY_FILLED };
Result cancelReplace(uint64_t old_id, const Order& new_order) {
auto it = active_orders_.find(old_id);
if (it == active_orders_.end()) return REJECTED_NOT_FOUND;
if (it->second.status == Order::FILLED) return REJECTED_ALREADY_FILLED;
active_orders_.erase(it);
active_orders_[new_order.id] = new_order;
return REPLACED;
}
};复杂度与边界
- 时间复杂度:O(1) 哈希查找
- 边界条件:(1) 原订单已成交→拒绝 (2) 新订单 ID 不能与现有订单冲突 (3) 交易所可能在替换期间有竞态窗口
英文解析
Analysis
Cancel-Replace allows modifying a submitted order's price or quantity without losing queue position. Exchanges typically treat Cancel-Replace as atomic: if cancellation succeeds, the new order is immediately submitted; otherwise the original order remains unchanged.
Solution
class CancelReplaceHandler {
std::unordered_map<uint64_t, Order> active_orders_;
public:
enum Result { REPLACED, REJECTED_NOT_FOUND, REJECTED_ALREADY_FILLED };
Result cancelReplace(uint64_t old_id, const Order& new_order) {
auto it = active_orders_.find(old_id);
if (it == active_orders_.end()) return REJECTED_NOT_FOUND;
if (it->second.status == Order::FILLED) return REJECTED_ALREADY_FILLED;
active_orders_.erase(it);
active_orders_[new_order.id] = new_order;
return REPLACED;
}
};Complexity & Edge Cases
- Time complexity: O(1) hash lookup
- Edge cases: (1) Original order already filled: reject (2) New order ID must not conflict with existing orders (3) Exchange may have a race window during replacement
Key Considerations
- Atomic semantics: Cancel-replace is semantically atomic — if original order fills before replace arrives, replace is rejected (not partially applied)
- Quantity change rules: Reducing quantity on cancel-replace preserves original priority; increasing quantity may reset priority depending on exchange rules
- Price change priority: Changing price on cancel-replace always resets time priority at new price level; this is equivalent to cancel + new order at new price
- Race condition: Original order may partially fill between replace submission and exchange processing; must handle reject due to original order no longer being open