Split intraday fills across execution quotes
This commit is contained in:
@@ -20,10 +20,16 @@ pub struct BrokerExecutionReport {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
struct ExecutionFill {
|
||||
struct ExecutionLeg {
|
||||
price: f64,
|
||||
quantity: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ExecutionFill {
|
||||
quantity: u32,
|
||||
next_cursor: NaiveDateTime,
|
||||
legs: Vec<ExecutionLeg>,
|
||||
unfilled_reason: Option<&'static str>,
|
||||
}
|
||||
|
||||
@@ -968,7 +974,6 @@ where
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let cash_before = portfolio.cash();
|
||||
let fill = self.resolve_execution_fill(
|
||||
date,
|
||||
symbol,
|
||||
@@ -985,32 +990,87 @@ where
|
||||
None,
|
||||
None,
|
||||
);
|
||||
let (filled_qty, execution_price) = if let Some(fill) = fill {
|
||||
let (filled_qty, execution_legs) = if let Some(fill) = fill {
|
||||
execution_cursors.insert(symbol.to_string(), fill.next_cursor);
|
||||
if self.uses_serial_execution_cursor(reason) {
|
||||
*global_execution_cursor = Some(fill.next_cursor);
|
||||
}
|
||||
partial_fill_reason =
|
||||
merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason);
|
||||
(fill.quantity, fill.price)
|
||||
(fill.quantity, fill.legs)
|
||||
} else {
|
||||
(filled_qty, self.sell_price(snapshot))
|
||||
(
|
||||
filled_qty,
|
||||
vec![ExecutionLeg {
|
||||
price: self.sell_price(snapshot),
|
||||
quantity: filled_qty,
|
||||
}],
|
||||
)
|
||||
};
|
||||
let gross_amount = execution_price * filled_qty as f64;
|
||||
let cost = self.cost_model.calculate_with_order_state(
|
||||
date,
|
||||
OrderSide::Sell,
|
||||
gross_amount,
|
||||
Some(order_id),
|
||||
commission_state,
|
||||
);
|
||||
let net_cash = gross_amount - cost.total();
|
||||
if execution_legs.len() > 1 {
|
||||
report.diagnostics.push(format!(
|
||||
"order_split_fill symbol={symbol} side=sell order_id={order_id} fills={}",
|
||||
execution_legs.len()
|
||||
));
|
||||
}
|
||||
for leg in &execution_legs {
|
||||
let leg_cash_before = portfolio.cash();
|
||||
let gross_amount = leg.price * leg.quantity as f64;
|
||||
let cost = self.cost_model.calculate_with_order_state(
|
||||
date,
|
||||
OrderSide::Sell,
|
||||
gross_amount,
|
||||
Some(order_id),
|
||||
commission_state,
|
||||
);
|
||||
let net_cash = gross_amount - cost.total();
|
||||
let realized_pnl = portfolio
|
||||
.position_mut(symbol)
|
||||
.sell(leg.quantity, leg.price)
|
||||
.map_err(BacktestError::Execution)?;
|
||||
portfolio.apply_cash_delta(net_cash);
|
||||
|
||||
let realized_pnl = portfolio
|
||||
.position_mut(symbol)
|
||||
.sell(filled_qty, execution_price)
|
||||
.map_err(BacktestError::Execution)?;
|
||||
portfolio.apply_cash_delta(net_cash);
|
||||
report.fill_events.push(FillEvent {
|
||||
date,
|
||||
order_id: Some(order_id),
|
||||
symbol: symbol.to_string(),
|
||||
side: OrderSide::Sell,
|
||||
quantity: leg.quantity,
|
||||
price: leg.price,
|
||||
gross_amount,
|
||||
commission: cost.commission,
|
||||
stamp_tax: cost.stamp_tax,
|
||||
net_cash_flow: net_cash,
|
||||
reason: reason.to_string(),
|
||||
});
|
||||
report.position_events.push(PositionEvent {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
delta_quantity: -(leg.quantity as i32),
|
||||
quantity_after: portfolio
|
||||
.position(symbol)
|
||||
.map(|pos| pos.quantity)
|
||||
.unwrap_or(0),
|
||||
average_cost: portfolio
|
||||
.position(symbol)
|
||||
.map(|pos| pos.average_cost)
|
||||
.unwrap_or(0.0),
|
||||
realized_pnl_delta: realized_pnl,
|
||||
reason: reason.to_string(),
|
||||
});
|
||||
report.account_events.push(AccountEvent {
|
||||
date,
|
||||
cash_before: leg_cash_before,
|
||||
cash_after: portfolio.cash(),
|
||||
total_equity: self.total_equity_at(
|
||||
date,
|
||||
portfolio,
|
||||
data,
|
||||
self.account_mark_price_field(),
|
||||
)?,
|
||||
note: format!("sell {symbol} {reason}"),
|
||||
});
|
||||
}
|
||||
portfolio.prune_flat_positions();
|
||||
*intraday_turnover.entry(symbol.to_string()).or_default() += filled_qty;
|
||||
|
||||
@@ -1041,46 +1101,6 @@ where
|
||||
status,
|
||||
reason: order_reason,
|
||||
});
|
||||
report.fill_events.push(FillEvent {
|
||||
date,
|
||||
order_id: Some(order_id),
|
||||
symbol: symbol.to_string(),
|
||||
side: OrderSide::Sell,
|
||||
quantity: filled_qty,
|
||||
price: execution_price,
|
||||
gross_amount,
|
||||
commission: cost.commission,
|
||||
stamp_tax: cost.stamp_tax,
|
||||
net_cash_flow: net_cash,
|
||||
reason: reason.to_string(),
|
||||
});
|
||||
report.position_events.push(PositionEvent {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
delta_quantity: -(filled_qty as i32),
|
||||
quantity_after: portfolio
|
||||
.position(symbol)
|
||||
.map(|pos| pos.quantity)
|
||||
.unwrap_or(0),
|
||||
average_cost: portfolio
|
||||
.position(symbol)
|
||||
.map(|pos| pos.average_cost)
|
||||
.unwrap_or(0.0),
|
||||
realized_pnl_delta: realized_pnl,
|
||||
reason: reason.to_string(),
|
||||
});
|
||||
report.account_events.push(AccountEvent {
|
||||
date,
|
||||
cash_before,
|
||||
cash_after: portfolio.cash(),
|
||||
total_equity: self.total_equity_at(
|
||||
date,
|
||||
portfolio,
|
||||
data,
|
||||
self.account_mark_price_field(),
|
||||
)?,
|
||||
note: format!("sell {symbol} {reason}"),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1355,14 +1375,14 @@ where
|
||||
Some(portfolio.cash()),
|
||||
value_budget.map(|budget| budget + 400.0),
|
||||
);
|
||||
let (filled_qty, execution_price) = if let Some(fill) = fill {
|
||||
let (filled_qty, execution_legs) = if let Some(fill) = fill {
|
||||
execution_cursors.insert(symbol.to_string(), fill.next_cursor);
|
||||
if self.uses_serial_execution_cursor(reason) {
|
||||
*global_execution_cursor = Some(fill.next_cursor);
|
||||
}
|
||||
partial_fill_reason =
|
||||
merge_partial_fill_reason(partial_fill_reason, fill.unfilled_reason);
|
||||
(fill.quantity, fill.price)
|
||||
(fill.quantity, fill.legs)
|
||||
} else {
|
||||
let execution_price = self.snapshot_execution_price(snapshot, OrderSide::Buy);
|
||||
let filled_qty = self.affordable_buy_quantity(
|
||||
@@ -1386,7 +1406,13 @@ where
|
||||
),
|
||||
);
|
||||
}
|
||||
(filled_qty, execution_price)
|
||||
(
|
||||
filled_qty,
|
||||
vec![ExecutionLeg {
|
||||
price: execution_price,
|
||||
quantity: filled_qty,
|
||||
}],
|
||||
)
|
||||
};
|
||||
if filled_qty == 0 {
|
||||
report.order_events.push(OrderEvent {
|
||||
@@ -1407,21 +1433,70 @@ where
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let cash_before = portfolio.cash();
|
||||
let gross_amount = execution_price * filled_qty as f64;
|
||||
let cost = self.cost_model.calculate_with_order_state(
|
||||
date,
|
||||
OrderSide::Buy,
|
||||
gross_amount,
|
||||
Some(order_id),
|
||||
commission_state,
|
||||
);
|
||||
let cash_out = gross_amount + cost.total();
|
||||
if execution_legs.len() > 1 {
|
||||
report.diagnostics.push(format!(
|
||||
"order_split_fill symbol={symbol} side=buy order_id={order_id} fills={}",
|
||||
execution_legs.len()
|
||||
));
|
||||
}
|
||||
for leg in &execution_legs {
|
||||
let leg_cash_before = portfolio.cash();
|
||||
let gross_amount = leg.price * leg.quantity as f64;
|
||||
let cost = self.cost_model.calculate_with_order_state(
|
||||
date,
|
||||
OrderSide::Buy,
|
||||
gross_amount,
|
||||
Some(order_id),
|
||||
commission_state,
|
||||
);
|
||||
let cash_out = gross_amount + cost.total();
|
||||
|
||||
portfolio.apply_cash_delta(-cash_out);
|
||||
portfolio
|
||||
.position_mut(symbol)
|
||||
.buy(date, filled_qty, execution_price);
|
||||
portfolio.apply_cash_delta(-cash_out);
|
||||
portfolio
|
||||
.position_mut(symbol)
|
||||
.buy(date, leg.quantity, leg.price);
|
||||
|
||||
report.fill_events.push(FillEvent {
|
||||
date,
|
||||
order_id: Some(order_id),
|
||||
symbol: symbol.to_string(),
|
||||
side: OrderSide::Buy,
|
||||
quantity: leg.quantity,
|
||||
price: leg.price,
|
||||
gross_amount,
|
||||
commission: cost.commission,
|
||||
stamp_tax: cost.stamp_tax,
|
||||
net_cash_flow: -cash_out,
|
||||
reason: reason.to_string(),
|
||||
});
|
||||
report.position_events.push(PositionEvent {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
delta_quantity: leg.quantity as i32,
|
||||
quantity_after: portfolio
|
||||
.position(symbol)
|
||||
.map(|pos| pos.quantity)
|
||||
.unwrap_or(0),
|
||||
average_cost: portfolio
|
||||
.position(symbol)
|
||||
.map(|pos| pos.average_cost)
|
||||
.unwrap_or(0.0),
|
||||
realized_pnl_delta: 0.0,
|
||||
reason: reason.to_string(),
|
||||
});
|
||||
report.account_events.push(AccountEvent {
|
||||
date,
|
||||
cash_before: leg_cash_before,
|
||||
cash_after: portfolio.cash(),
|
||||
total_equity: self.total_equity_at(
|
||||
date,
|
||||
portfolio,
|
||||
data,
|
||||
self.account_mark_price_field(),
|
||||
)?,
|
||||
note: format!("buy {symbol} {reason}"),
|
||||
});
|
||||
}
|
||||
*intraday_turnover.entry(symbol.to_string()).or_default() += filled_qty;
|
||||
|
||||
let status = if filled_qty < requested_qty {
|
||||
@@ -1451,46 +1526,6 @@ where
|
||||
status,
|
||||
reason: order_reason,
|
||||
});
|
||||
report.fill_events.push(FillEvent {
|
||||
date,
|
||||
order_id: Some(order_id),
|
||||
symbol: symbol.to_string(),
|
||||
side: OrderSide::Buy,
|
||||
quantity: filled_qty,
|
||||
price: execution_price,
|
||||
gross_amount,
|
||||
commission: cost.commission,
|
||||
stamp_tax: cost.stamp_tax,
|
||||
net_cash_flow: -cash_out,
|
||||
reason: reason.to_string(),
|
||||
});
|
||||
report.position_events.push(PositionEvent {
|
||||
date,
|
||||
symbol: symbol.to_string(),
|
||||
delta_quantity: filled_qty as i32,
|
||||
quantity_after: portfolio
|
||||
.position(symbol)
|
||||
.map(|pos| pos.quantity)
|
||||
.unwrap_or(0),
|
||||
average_cost: portfolio
|
||||
.position(symbol)
|
||||
.map(|pos| pos.average_cost)
|
||||
.unwrap_or(0.0),
|
||||
realized_pnl_delta: 0.0,
|
||||
reason: reason.to_string(),
|
||||
});
|
||||
report.account_events.push(AccountEvent {
|
||||
date,
|
||||
cash_before,
|
||||
cash_after: portfolio.cash(),
|
||||
total_equity: self.total_equity_at(
|
||||
date,
|
||||
portfolio,
|
||||
data,
|
||||
self.account_mark_price_field(),
|
||||
)?,
|
||||
note: format!("buy {symbol} {reason}"),
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -1734,9 +1769,12 @@ where
|
||||
.map(|start_time| date.and_time(start_time) + Duration::seconds(1))
|
||||
.unwrap_or_else(|| date.and_hms_opt(0, 0, 1).expect("valid midnight"));
|
||||
return Some(ExecutionFill {
|
||||
price: execution_price,
|
||||
quantity,
|
||||
next_cursor,
|
||||
legs: vec![ExecutionLeg {
|
||||
price: execution_price,
|
||||
quantity,
|
||||
}],
|
||||
unfilled_reason: self.buy_reduction_reason(
|
||||
cash_limit.unwrap_or(f64::INFINITY),
|
||||
gross_limit,
|
||||
@@ -1793,6 +1831,7 @@ where
|
||||
let mut filled_qty = 0_u32;
|
||||
let mut gross_amount = 0.0_f64;
|
||||
let mut last_timestamp = None;
|
||||
let mut legs = Vec::new();
|
||||
let mut budget_block_reason = None;
|
||||
let mut saw_quote_after_cursor = false;
|
||||
|
||||
@@ -1865,6 +1904,10 @@ where
|
||||
gross_amount += quote_price * take_qty as f64;
|
||||
filled_qty += take_qty;
|
||||
last_timestamp = Some(quote.timestamp);
|
||||
legs.push(ExecutionLeg {
|
||||
price: quote_price,
|
||||
quantity: take_qty,
|
||||
});
|
||||
|
||||
if filled_qty >= requested_qty {
|
||||
break;
|
||||
@@ -1876,9 +1919,9 @@ where
|
||||
}
|
||||
|
||||
Some(ExecutionFill {
|
||||
price: gross_amount / filled_qty as f64,
|
||||
quantity: filled_qty,
|
||||
next_cursor: last_timestamp.unwrap() + Duration::seconds(1),
|
||||
legs,
|
||||
unfilled_reason: if filled_qty < requested_qty {
|
||||
budget_block_reason.or(if saw_quote_after_cursor {
|
||||
Some("intraday quote liquidity exhausted")
|
||||
|
||||
Reference in New Issue
Block a user