Compare commits
1 Commits
v2026.05.1
...
v2026.5.15
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4577657c90 |
@@ -111,6 +111,7 @@ pub struct BrokerSimulator<C, R> {
|
|||||||
inactive_limit: bool,
|
inactive_limit: bool,
|
||||||
liquidity_limit: bool,
|
liquidity_limit: bool,
|
||||||
strict_value_budget: bool,
|
strict_value_budget: bool,
|
||||||
|
same_day_buy_close_mark_at_fill: bool,
|
||||||
intraday_execution_start_time: Option<NaiveTime>,
|
intraday_execution_start_time: Option<NaiveTime>,
|
||||||
runtime_intraday_start_time: Cell<Option<NaiveTime>>,
|
runtime_intraday_start_time: Cell<Option<NaiveTime>>,
|
||||||
runtime_intraday_end_time: Cell<Option<NaiveTime>>,
|
runtime_intraday_end_time: Cell<Option<NaiveTime>>,
|
||||||
@@ -132,6 +133,7 @@ impl<C, R> BrokerSimulator<C, R> {
|
|||||||
inactive_limit: true,
|
inactive_limit: true,
|
||||||
liquidity_limit: true,
|
liquidity_limit: true,
|
||||||
strict_value_budget: false,
|
strict_value_budget: false,
|
||||||
|
same_day_buy_close_mark_at_fill: false,
|
||||||
intraday_execution_start_time: None,
|
intraday_execution_start_time: None,
|
||||||
runtime_intraday_start_time: Cell::new(None),
|
runtime_intraday_start_time: Cell::new(None),
|
||||||
runtime_intraday_end_time: Cell::new(None),
|
runtime_intraday_end_time: Cell::new(None),
|
||||||
@@ -157,6 +159,7 @@ impl<C, R> BrokerSimulator<C, R> {
|
|||||||
inactive_limit: true,
|
inactive_limit: true,
|
||||||
liquidity_limit: true,
|
liquidity_limit: true,
|
||||||
strict_value_budget: false,
|
strict_value_budget: false,
|
||||||
|
same_day_buy_close_mark_at_fill: false,
|
||||||
intraday_execution_start_time: None,
|
intraday_execution_start_time: None,
|
||||||
runtime_intraday_start_time: Cell::new(None),
|
runtime_intraday_start_time: Cell::new(None),
|
||||||
runtime_intraday_end_time: Cell::new(None),
|
runtime_intraday_end_time: Cell::new(None),
|
||||||
@@ -185,6 +188,15 @@ impl<C, R> BrokerSimulator<C, R> {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_same_day_buy_close_mark_at_fill(mut self, enabled: bool) -> Self {
|
||||||
|
self.same_day_buy_close_mark_at_fill = enabled;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn same_day_buy_close_mark_at_fill(&self) -> bool {
|
||||||
|
self.same_day_buy_close_mark_at_fill
|
||||||
|
}
|
||||||
|
|
||||||
pub fn with_volume_percent(mut self, volume_percent: f64) -> Self {
|
pub fn with_volume_percent(mut self, volume_percent: f64) -> Self {
|
||||||
self.volume_percent = volume_percent;
|
self.volume_percent = volume_percent;
|
||||||
self
|
self
|
||||||
@@ -252,6 +264,34 @@ where
|
|||||||
snapshot.price(self.execution_price_field)
|
snapshot.price(self.execution_price_field)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn value_buy_sizing_price(
|
||||||
|
&self,
|
||||||
|
date: NaiveDate,
|
||||||
|
data: &DataSet,
|
||||||
|
symbol: &str,
|
||||||
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
|
) -> f64 {
|
||||||
|
let start_cursor = self
|
||||||
|
.runtime_intraday_start_time
|
||||||
|
.get()
|
||||||
|
.or(self.intraday_execution_start_time)
|
||||||
|
.map(|start_time| date.and_time(start_time));
|
||||||
|
data.execution_quotes_on(date, symbol)
|
||||||
|
.iter()
|
||||||
|
.filter(|quote| {
|
||||||
|
start_cursor
|
||||||
|
.map(|cursor| quote.timestamp >= cursor)
|
||||||
|
.unwrap_or(true)
|
||||||
|
})
|
||||||
|
.next()
|
||||||
|
.and_then(|quote| match self.execution_price_field {
|
||||||
|
PriceField::Last => (quote.last_price.is_finite() && quote.last_price > 0.0)
|
||||||
|
.then_some(quote.last_price),
|
||||||
|
_ => quote.buy_price(),
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|| self.sizing_price(snapshot))
|
||||||
|
}
|
||||||
|
|
||||||
fn snapshot_execution_price(
|
fn snapshot_execution_price(
|
||||||
&self,
|
&self,
|
||||||
snapshot: &crate::data::DailyMarketSnapshot,
|
snapshot: &crate::data::DailyMarketSnapshot,
|
||||||
@@ -2917,7 +2957,7 @@ where
|
|||||||
let round_lot = self.round_lot(data, symbol);
|
let round_lot = self.round_lot(data, symbol);
|
||||||
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
|
let minimum_order_quantity = self.minimum_order_quantity(data, symbol);
|
||||||
let order_step_size = self.order_step_size(data, symbol);
|
let order_step_size = self.order_step_size(data, symbol);
|
||||||
let price = self.sizing_price(snapshot);
|
let price = self.value_buy_sizing_price(date, data, symbol, snapshot);
|
||||||
let snapshot_requested_qty = self.value_buy_quantity(
|
let snapshot_requested_qty = self.value_buy_quantity(
|
||||||
date,
|
date,
|
||||||
value.abs(),
|
value.abs(),
|
||||||
@@ -3408,13 +3448,10 @@ where
|
|||||||
requested_qty: u32,
|
requested_qty: u32,
|
||||||
reference_price: f64,
|
reference_price: f64,
|
||||||
) -> Option<f64> {
|
) -> Option<f64> {
|
||||||
value_budget.map(|budget| {
|
if !self.strict_value_budget {
|
||||||
if self.strict_value_budget {
|
return None;
|
||||||
budget.max(reference_price * requested_qty as f64)
|
|
||||||
} else {
|
|
||||||
budget + 400.0
|
|
||||||
}
|
}
|
||||||
})
|
value_budget.map(|budget| budget.max(reference_price * requested_qty as f64))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn process_buy(
|
fn process_buy(
|
||||||
@@ -3733,7 +3770,7 @@ where
|
|||||||
.position_mut(symbol)
|
.position_mut(symbol)
|
||||||
.buy(date, leg.quantity, leg.price);
|
.buy(date, leg.quantity, leg.price);
|
||||||
if let Some(position) = portfolio.position_mut_if_exists(symbol) {
|
if let Some(position) = portfolio.position_mut_if_exists(symbol) {
|
||||||
position.record_trade_cost(cost.total());
|
position.record_buy_trade_cost(leg.quantity, cost.total());
|
||||||
}
|
}
|
||||||
|
|
||||||
report.fill_events.push(FillEvent {
|
report.fill_events.push(FillEvent {
|
||||||
@@ -4372,7 +4409,8 @@ where
|
|||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
let quote_quantity_limited = self.quote_quantity_limited(matching_type);
|
let quote_quantity_limited =
|
||||||
|
self.quote_quantity_limited_for_window(matching_type, start_cursor, end_cursor);
|
||||||
let lot = round_lot.max(1);
|
let lot = round_lot.max(1);
|
||||||
let eligible_quotes: Vec<&IntradayExecutionQuote> = quotes
|
let eligible_quotes: Vec<&IntradayExecutionQuote> = quotes
|
||||||
.iter()
|
.iter()
|
||||||
@@ -4533,6 +4571,23 @@ where
|
|||||||
self.volume_limit || self.liquidity_limit || matching_type != MatchingType::NextTickLast
|
self.volume_limit || self.liquidity_limit || matching_type != MatchingType::NextTickLast
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn quote_quantity_limited_for_window(
|
||||||
|
&self,
|
||||||
|
matching_type: MatchingType,
|
||||||
|
start_cursor: Option<NaiveDateTime>,
|
||||||
|
end_cursor: Option<NaiveDateTime>,
|
||||||
|
) -> bool {
|
||||||
|
if matching_type == MatchingType::Twap
|
||||||
|
&& !self.volume_limit
|
||||||
|
&& !self.liquidity_limit
|
||||||
|
&& start_cursor.is_some()
|
||||||
|
&& start_cursor == end_cursor
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
self.quote_quantity_limited(matching_type)
|
||||||
|
}
|
||||||
|
|
||||||
fn uses_serial_execution_cursor(&self, reason: &str) -> bool {
|
fn uses_serial_execution_cursor(&self, reason: &str) -> bool {
|
||||||
let _ = reason;
|
let _ = reason;
|
||||||
false
|
false
|
||||||
@@ -4629,4 +4684,26 @@ mod tests {
|
|||||||
assert!(volume_limited.quote_quantity_limited(MatchingType::NextTickLast));
|
assert!(volume_limited.quote_quantity_limited(MatchingType::NextTickLast));
|
||||||
assert!(liquidity_limited.quote_quantity_limited(MatchingType::NextTickLast));
|
assert!(liquidity_limited.quote_quantity_limited(MatchingType::NextTickLast));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn instantaneous_twap_without_limits_does_not_cap_quote_quantity() {
|
||||||
|
let broker = BrokerSimulator::new(ChinaAShareCostModel::default(), ChinaEquityRuleHooks)
|
||||||
|
.with_volume_limit(false)
|
||||||
|
.with_liquidity_limit(false);
|
||||||
|
let cursor = chrono::NaiveDate::from_ymd_opt(2025, 11, 3)
|
||||||
|
.unwrap()
|
||||||
|
.and_hms_opt(9, 31, 0)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert!(!broker.quote_quantity_limited_for_window(
|
||||||
|
MatchingType::Twap,
|
||||||
|
Some(cursor),
|
||||||
|
Some(cursor)
|
||||||
|
));
|
||||||
|
assert!(broker.quote_quantity_limited_for_window(
|
||||||
|
MatchingType::Twap,
|
||||||
|
Some(cursor),
|
||||||
|
Some(cursor + chrono::Duration::minutes(1))
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -654,6 +654,14 @@ impl SymbolPriceSeries {
|
|||||||
self.values_for(field).get(end - 1).copied()
|
self.values_for(field).get(end - 1).copied()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn snapshot_before(&self, date: NaiveDate) -> Option<&DailyMarketSnapshot> {
|
||||||
|
let end = self.previous_completed_end_index(date)?;
|
||||||
|
if end == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.snapshots.get(end - 1)
|
||||||
|
}
|
||||||
|
|
||||||
fn prefix_for(&self, field: PriceField) -> &[f64] {
|
fn prefix_for(&self, field: PriceField) -> &[f64] {
|
||||||
match field {
|
match field {
|
||||||
PriceField::DayOpen => &self.open_prefix,
|
PriceField::DayOpen => &self.open_prefix,
|
||||||
@@ -1828,6 +1836,12 @@ impl DataSet {
|
|||||||
.and_then(|series| series.price_on_or_before(date, field))
|
.and_then(|series| series.price_on_or_before(date, field))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn market_before(&self, date: NaiveDate, symbol: &str) -> Option<&DailyMarketSnapshot> {
|
||||||
|
self.market_series_by_symbol
|
||||||
|
.get(symbol)
|
||||||
|
.and_then(|series| series.snapshot_before(date))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn factor_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyFactorSnapshot> {
|
pub fn factor_snapshots_on(&self, date: NaiveDate) -> Vec<&DailyFactorSnapshot> {
|
||||||
self.factor_by_date
|
self.factor_by_date
|
||||||
.get(&date)
|
.get(&date)
|
||||||
|
|||||||
@@ -2127,7 +2127,12 @@ where
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
portfolio.update_prices(execution_date, &self.data, PriceField::Close)?;
|
portfolio.update_prices_with_options(
|
||||||
|
execution_date,
|
||||||
|
&self.data,
|
||||||
|
PriceField::Close,
|
||||||
|
self.broker.same_day_buy_close_mark_at_fill(),
|
||||||
|
)?;
|
||||||
|
|
||||||
let post_trade_open_orders = self.open_order_views();
|
let post_trade_open_orders = self.open_order_views();
|
||||||
let visible_order_events = result
|
let visible_order_events = result
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
|||||||
use chrono::NaiveDate;
|
use chrono::NaiveDate;
|
||||||
use indexmap::IndexMap;
|
use indexmap::IndexMap;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use std::collections::BTreeMap;
|
use std::collections::{BTreeMap, BTreeSet};
|
||||||
|
|
||||||
use crate::data::{DataSet, DataSetError, PriceField};
|
use crate::data::{DataSet, DataSetError, PriceField};
|
||||||
|
|
||||||
@@ -205,6 +205,22 @@ impl Position {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn record_buy_trade_cost(&mut self, quantity: u32, value: f64) {
|
||||||
|
if quantity == 0 || !value.is_finite() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let cost = value.max(0.0);
|
||||||
|
if cost <= 0.0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if let Some(lot) = self.lots.last_mut() {
|
||||||
|
lot.price += cost / quantity as f64;
|
||||||
|
self.recalculate_average_cost();
|
||||||
|
}
|
||||||
|
self.day_trade_cost += cost;
|
||||||
|
self.refresh_day_pnl();
|
||||||
|
}
|
||||||
|
|
||||||
pub fn set_dividend_receivable(&mut self, value: f64) {
|
pub fn set_dividend_receivable(&mut self, value: f64) {
|
||||||
self.dividend_receivable = if value.is_finite() {
|
self.dividend_receivable = if value.is_finite() {
|
||||||
value.max(0.0)
|
value.max(0.0)
|
||||||
@@ -316,6 +332,7 @@ pub struct PortfolioState {
|
|||||||
positions: IndexMap<String, Position>,
|
positions: IndexMap<String, Position>,
|
||||||
cash_receivables: Vec<CashReceivable>,
|
cash_receivables: Vec<CashReceivable>,
|
||||||
pending_cash_flows: Vec<PendingCashFlow>,
|
pending_cash_flows: Vec<PendingCashFlow>,
|
||||||
|
day_sold_symbols: BTreeSet<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -348,6 +365,7 @@ impl PortfolioState {
|
|||||||
positions: IndexMap::new(),
|
positions: IndexMap::new(),
|
||||||
cash_receivables: Vec::new(),
|
cash_receivables: Vec::new(),
|
||||||
pending_cash_flows: Vec::new(),
|
pending_cash_flows: Vec::new(),
|
||||||
|
day_sold_symbols: BTreeSet::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -402,7 +420,18 @@ impl PortfolioState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn prune_flat_positions(&mut self) {
|
pub fn prune_flat_positions(&mut self) {
|
||||||
self.positions.retain(|_, position| !position.is_flat());
|
let mut sold_symbols = Vec::new();
|
||||||
|
self.positions.retain(|symbol, position| {
|
||||||
|
if position.is_flat() {
|
||||||
|
if position.sold_quantity() > 0 {
|
||||||
|
sold_symbols.push(symbol.clone());
|
||||||
|
}
|
||||||
|
false
|
||||||
|
} else {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
});
|
||||||
|
self.day_sold_symbols.extend(sold_symbols);
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn add_cash_receivable(&mut self, receivable: CashReceivable) {
|
pub fn add_cash_receivable(&mut self, receivable: CashReceivable) {
|
||||||
@@ -538,6 +567,7 @@ impl PortfolioState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn begin_trading_day(&mut self) {
|
pub fn begin_trading_day(&mut self) {
|
||||||
|
self.day_sold_symbols.clear();
|
||||||
for position in self.positions.values_mut() {
|
for position in self.positions.values_mut() {
|
||||||
position.begin_trading_day();
|
position.begin_trading_day();
|
||||||
}
|
}
|
||||||
@@ -550,9 +580,24 @@ impl PortfolioState {
|
|||||||
data: &DataSet,
|
data: &DataSet,
|
||||||
field: PriceField,
|
field: PriceField,
|
||||||
) -> Result<(), DataSetError> {
|
) -> Result<(), DataSetError> {
|
||||||
|
self.update_prices_with_options(date, data, field, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn update_prices_with_options(
|
||||||
|
&mut self,
|
||||||
|
date: NaiveDate,
|
||||||
|
data: &DataSet,
|
||||||
|
field: PriceField,
|
||||||
|
same_day_buy_close_mark_at_fill: bool,
|
||||||
|
) -> Result<(), DataSetError> {
|
||||||
|
let day_sold_symbols = self.day_sold_symbols.clone();
|
||||||
for position in self.positions.values_mut() {
|
for position in self.positions.values_mut() {
|
||||||
if field == PriceField::Close
|
let sold_today =
|
||||||
|
position.sold_quantity() > 0 || day_sold_symbols.contains(&position.symbol);
|
||||||
|
if same_day_buy_close_mark_at_fill
|
||||||
|
&& field == PriceField::Close
|
||||||
&& position.day_buy_quantity > 0
|
&& position.day_buy_quantity > 0
|
||||||
|
&& !sold_today
|
||||||
&& position.sellable_qty(date) == 0
|
&& position.sellable_qty(date) == 0
|
||||||
&& position.last_price.is_finite()
|
&& position.last_price.is_finite()
|
||||||
&& position.last_price > 0.0
|
&& position.last_price > 0.0
|
||||||
@@ -1165,7 +1210,7 @@ mod tests {
|
|||||||
.expect("dataset");
|
.expect("dataset");
|
||||||
|
|
||||||
portfolio
|
portfolio
|
||||||
.update_prices(buy_date, &dataset, PriceField::Close)
|
.update_prices_with_options(buy_date, &dataset, PriceField::Close, true)
|
||||||
.expect("same day close");
|
.expect("same day close");
|
||||||
let position = portfolio.position(symbol).expect("position");
|
let position = portfolio.position(symbol).expect("position");
|
||||||
assert!((position.last_price - 3.01).abs() < 1e-9);
|
assert!((position.last_price - 3.01).abs() < 1e-9);
|
||||||
@@ -1178,6 +1223,27 @@ mod tests {
|
|||||||
let position = portfolio.position(symbol).expect("position");
|
let position = portfolio.position(symbol).expect("position");
|
||||||
assert!((position.last_price - 3.07).abs() < 1e-9);
|
assert!((position.last_price - 3.07).abs() < 1e-9);
|
||||||
assert!((position.market_value() - 3991.0).abs() < 1e-6);
|
assert!((position.market_value() - 3991.0).abs() < 1e-6);
|
||||||
|
|
||||||
|
let prev_date = NaiveDate::from_ymd_opt(2025, 2, 7).unwrap();
|
||||||
|
let mut roundtrip_portfolio = PortfolioState::new(20_000.0);
|
||||||
|
roundtrip_portfolio
|
||||||
|
.position_mut(symbol)
|
||||||
|
.buy(prev_date, 2000, 2.90);
|
||||||
|
roundtrip_portfolio.begin_trading_day();
|
||||||
|
roundtrip_portfolio
|
||||||
|
.position_mut(symbol)
|
||||||
|
.sell(2000, 3.01)
|
||||||
|
.expect("same day sell");
|
||||||
|
roundtrip_portfolio.prune_flat_positions();
|
||||||
|
roundtrip_portfolio
|
||||||
|
.position_mut(symbol)
|
||||||
|
.buy(buy_date, 1800, 3.01);
|
||||||
|
roundtrip_portfolio
|
||||||
|
.update_prices(buy_date, &dataset, PriceField::Close)
|
||||||
|
.expect("same day roundtrip close");
|
||||||
|
let position = roundtrip_portfolio.position(symbol).expect("position");
|
||||||
|
assert!((position.last_price - 3.06).abs() < 1e-9);
|
||||||
|
assert!((position.market_value() - 5508.0).abs() < 1e-6);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -1780,11 +1780,23 @@ impl OmniMicroCapStrategy {
|
|||||||
if !sizing_price.is_finite() || sizing_price <= 0.0 {
|
if !sizing_price.is_finite() || sizing_price <= 0.0 {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
let snapshot_requested_qty = self.round_lot_quantity(
|
let mut snapshot_requested_qty = self.round_lot_quantity(
|
||||||
((projected.cash().min(order_value)) / sizing_price).floor() as u32,
|
((projected.cash().min(order_value)) / sizing_price).floor() as u32,
|
||||||
minimum_order_quantity,
|
minimum_order_quantity,
|
||||||
order_step_size,
|
order_step_size,
|
||||||
);
|
);
|
||||||
|
while snapshot_requested_qty > 0 {
|
||||||
|
let gross_amount = sizing_price * snapshot_requested_qty as f64;
|
||||||
|
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||||
|
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
snapshot_requested_qty = self.decrement_order_quantity(
|
||||||
|
snapshot_requested_qty,
|
||||||
|
minimum_order_quantity,
|
||||||
|
order_step_size,
|
||||||
|
);
|
||||||
|
}
|
||||||
let projected_execution_price = self.projected_execution_price(market, OrderSide::Buy);
|
let projected_execution_price = self.projected_execution_price(market, OrderSide::Buy);
|
||||||
let projected_fill = self.projected_select_execution_fill(
|
let projected_fill = self.projected_select_execution_fill(
|
||||||
ctx,
|
ctx,
|
||||||
@@ -1796,14 +1808,15 @@ impl OmniMicroCapStrategy {
|
|||||||
minimum_order_quantity,
|
minimum_order_quantity,
|
||||||
order_step_size,
|
order_step_size,
|
||||||
false,
|
false,
|
||||||
Some(projected.cash()),
|
Some(projected.cash().min(order_value)),
|
||||||
Some(order_value + 400.0),
|
Some(order_value),
|
||||||
execution_state,
|
execution_state,
|
||||||
);
|
);
|
||||||
let mut quantity = snapshot_requested_qty;
|
let mut quantity = snapshot_requested_qty;
|
||||||
while quantity > 0 {
|
while quantity > 0 {
|
||||||
let gross_amount = projected_execution_price * quantity as f64;
|
let gross_amount = projected_execution_price * quantity as f64;
|
||||||
if gross_amount <= order_value + 400.0 && gross_amount <= projected.cash() + 1e-6 {
|
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||||
|
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
quantity =
|
quantity =
|
||||||
@@ -1818,7 +1831,8 @@ impl OmniMicroCapStrategy {
|
|||||||
.unwrap_or(projected_execution_price);
|
.unwrap_or(projected_execution_price);
|
||||||
while quantity > 0 {
|
while quantity > 0 {
|
||||||
let gross_amount = execution_price * quantity as f64;
|
let gross_amount = execution_price * quantity as f64;
|
||||||
if gross_amount <= projected.cash() + 1e-6 {
|
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||||
|
if cash_out <= order_value + 1e-6 && cash_out <= projected.cash() + 1e-6 {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
quantity =
|
quantity =
|
||||||
@@ -1834,7 +1848,7 @@ impl OmniMicroCapStrategy {
|
|||||||
};
|
};
|
||||||
let gross_amount = fill.price * fill.quantity as f64;
|
let gross_amount = fill.price * fill.quantity as f64;
|
||||||
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
let cash_out = gross_amount + self.buy_commission(gross_amount);
|
||||||
if gross_amount > projected.cash() + 1e-6 {
|
if cash_out > projected.cash() + 1e-6 || cash_out > order_value + 1e-6 {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
projected.apply_cash_delta(-cash_out);
|
projected.apply_cash_delta(-cash_out);
|
||||||
|
|||||||
@@ -233,8 +233,148 @@ fn broker_order_value_rounds_to_nearest_lot_when_min_lot_is_affordable() {
|
|||||||
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 3_938.13);
|
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 3_938.13);
|
||||||
|
|
||||||
assert_eq!(report.fill_events.len(), 1);
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
assert_eq!(report.fill_events[0].quantity, 200);
|
assert_eq!(report.fill_events[0].quantity, 100);
|
||||||
assert_eq!(portfolio.position(symbol).expect("position").quantity, 200);
|
assert_eq!(portfolio.position(symbol).expect("position").quantity, 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_order_value_budget_includes_buy_commission() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2025, 6, 23).unwrap();
|
||||||
|
let symbol = "605303.SH";
|
||||||
|
let data = order_value_rounding_data(date, symbol, 11.93);
|
||||||
|
|
||||||
|
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 4_776.0);
|
||||||
|
|
||||||
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
|
assert_eq!(report.fill_events[0].quantity, 300);
|
||||||
|
assert_eq!(portfolio.position(symbol).expect("position").quantity, 300);
|
||||||
|
|
||||||
|
let (portfolio, report) = execute_single_value_order(date, &data, symbol, 4_848.0);
|
||||||
|
|
||||||
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
|
assert_eq!(report.fill_events[0].quantity, 400);
|
||||||
|
assert_eq!(portfolio.position(symbol).expect("position").quantity, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn broker_delayed_limit_open_sell_uses_tick_price() {
|
||||||
|
let date = NaiveDate::from_ymd_opt(2025, 6, 27).unwrap();
|
||||||
|
let prev_date = NaiveDate::from_ymd_opt(2025, 6, 26).unwrap();
|
||||||
|
let symbol = "300635.SZ";
|
||||||
|
let data = DataSet::from_components_with_actions_and_quotes(
|
||||||
|
vec![Instrument {
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
name: "Test".to_string(),
|
||||||
|
board: "SZ".to_string(),
|
||||||
|
round_lot: 100,
|
||||||
|
listed_at: None,
|
||||||
|
delisted_at: None,
|
||||||
|
status: "active".to_string(),
|
||||||
|
}],
|
||||||
|
vec![DailyMarketSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
timestamp: Some("2025-06-27 09:31:00".to_string()),
|
||||||
|
day_open: 12.55,
|
||||||
|
open: 12.55,
|
||||||
|
high: 13.16,
|
||||||
|
low: 12.26,
|
||||||
|
close: 12.36,
|
||||||
|
last_price: 12.39,
|
||||||
|
bid1: 12.39,
|
||||||
|
ask1: 12.40,
|
||||||
|
prev_close: 13.24,
|
||||||
|
volume: 329_575,
|
||||||
|
tick_volume: 10_000,
|
||||||
|
bid1_volume: 10_000,
|
||||||
|
ask1_volume: 10_000,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
paused: false,
|
||||||
|
upper_limit: 14.56,
|
||||||
|
lower_limit: 11.92,
|
||||||
|
price_tick: 0.01,
|
||||||
|
}],
|
||||||
|
vec![DailyFactorSnapshot {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
market_cap_bn: 50.0,
|
||||||
|
free_float_cap_bn: 45.0,
|
||||||
|
pe_ttm: 15.0,
|
||||||
|
turnover_ratio: Some(2.0),
|
||||||
|
effective_turnover_ratio: Some(1.8),
|
||||||
|
extra_factors: BTreeMap::new(),
|
||||||
|
}],
|
||||||
|
vec![CandidateEligibility {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
is_st: false,
|
||||||
|
is_new_listing: false,
|
||||||
|
is_paused: false,
|
||||||
|
allow_buy: true,
|
||||||
|
allow_sell: true,
|
||||||
|
is_kcb: false,
|
||||||
|
is_one_yuan: false,
|
||||||
|
}],
|
||||||
|
vec![BenchmarkSnapshot {
|
||||||
|
date,
|
||||||
|
benchmark: "000300.SH".to_string(),
|
||||||
|
open: 100.0,
|
||||||
|
close: 100.0,
|
||||||
|
prev_close: 99.0,
|
||||||
|
volume: 1_000_000,
|
||||||
|
}],
|
||||||
|
Vec::new(),
|
||||||
|
vec![IntradayExecutionQuote {
|
||||||
|
date,
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
timestamp: date.and_hms_opt(9, 31, 0).unwrap(),
|
||||||
|
last_price: 12.39,
|
||||||
|
bid1: 12.39,
|
||||||
|
ask1: 12.40,
|
||||||
|
bid1_volume: 10_000,
|
||||||
|
ask1_volume: 10_000,
|
||||||
|
volume_delta: 10_000,
|
||||||
|
amount_delta: 123_900.0,
|
||||||
|
trading_phase: Some("continuous".to_string()),
|
||||||
|
}],
|
||||||
|
)
|
||||||
|
.expect("dataset");
|
||||||
|
let mut portfolio = PortfolioState::new(1_000.0);
|
||||||
|
portfolio.position_mut(symbol).buy(prev_date, 800, 10.92);
|
||||||
|
let broker = BrokerSimulator::new_with_execution_price(
|
||||||
|
ChinaAShareCostModel::default(),
|
||||||
|
ChinaEquityRuleHooks::default(),
|
||||||
|
PriceField::Last,
|
||||||
|
)
|
||||||
|
.with_matching_type(MatchingType::NextTickLast)
|
||||||
|
.with_intraday_execution_start_time(NaiveTime::from_hms_opt(9, 31, 0).unwrap())
|
||||||
|
.with_volume_limit(false)
|
||||||
|
.with_liquidity_limit(false);
|
||||||
|
|
||||||
|
let report = broker
|
||||||
|
.execute(
|
||||||
|
date,
|
||||||
|
&mut portfolio,
|
||||||
|
&data,
|
||||||
|
&StrategyDecision {
|
||||||
|
rebalance: false,
|
||||||
|
target_weights: BTreeMap::new(),
|
||||||
|
exit_symbols: BTreeSet::new(),
|
||||||
|
order_intents: vec![OrderIntent::TargetValue {
|
||||||
|
symbol: symbol.to_string(),
|
||||||
|
target_value: 0.0,
|
||||||
|
reason: "delayed_limit_open_sell".to_string(),
|
||||||
|
}],
|
||||||
|
notes: Vec::new(),
|
||||||
|
diagnostics: Vec::new(),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.expect("broker execution");
|
||||||
|
|
||||||
|
assert_eq!(report.fill_events.len(), 1);
|
||||||
|
assert_eq!(report.fill_events[0].quantity, 800);
|
||||||
|
assert_eq!(report.fill_events[0].price, 12.39);
|
||||||
|
assert!(portfolio.position(symbol).is_none());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -905,7 +1045,7 @@ fn broker_executes_order_percent_and_target_percent() {
|
|||||||
)
|
)
|
||||||
.expect("percent execution");
|
.expect("percent execution");
|
||||||
assert_eq!(percent_report.fill_events.len(), 1);
|
assert_eq!(percent_report.fill_events.len(), 1);
|
||||||
assert_eq!(percent_report.fill_events[0].quantity, 10_000);
|
assert_eq!(percent_report.fill_events[0].quantity, 9_900);
|
||||||
|
|
||||||
let mut target_percent_portfolio = PortfolioState::new(1_000_000.0);
|
let mut target_percent_portfolio = PortfolioState::new(1_000_000.0);
|
||||||
let target_percent_report = broker
|
let target_percent_report = broker
|
||||||
@@ -2498,7 +2638,7 @@ fn broker_executes_algo_twap_percent_across_window_quotes() {
|
|||||||
exit_symbols: BTreeSet::new(),
|
exit_symbols: BTreeSet::new(),
|
||||||
order_intents: vec![OrderIntent::AlgoPercent {
|
order_intents: vec![OrderIntent::AlgoPercent {
|
||||||
symbol: "000002.SZ".to_string(),
|
symbol: "000002.SZ".to_string(),
|
||||||
percent: 0.0036,
|
percent: 0.0037,
|
||||||
style: AlgoOrderStyle::Twap,
|
style: AlgoOrderStyle::Twap,
|
||||||
start_time: Some(NaiveTime::from_hms_opt(10, 0, 0).unwrap()),
|
start_time: Some(NaiveTime::from_hms_opt(10, 0, 0).unwrap()),
|
||||||
end_time: Some(NaiveTime::from_hms_opt(10, 30, 0).unwrap()),
|
end_time: Some(NaiveTime::from_hms_opt(10, 30, 0).unwrap()),
|
||||||
|
|||||||
Reference in New Issue
Block a user