9 Commits

Author SHA1 Message Date
boris
d9de9715ef chore: 更新 fidc-backtest-engine - 2026-05-08 2026-05-08 19:57:49 -07:00
boris
65742d4d5e chore: 更新 fidc-backtest-engine - 2026-05-08 2026-05-08 07:34:04 -07:00
boris
a47c7c3e49 chore: 更新 fidc-backtest-engine - 2026-05-07 2026-05-07 17:12:49 -07:00
boris
adc2f12ddf chore: 更新 fidc-backtest-engine - 2026-05-07 2026-05-07 03:49:26 -07:00
boris
e06a1e88e5 完善AI策略手册防未来函数规则 2026-04-30 09:24:05 -07:00
boris
ce49301b98 修复平台策略次日开盘未来函数 2026-04-30 00:53:45 -07:00
boris
e5439956eb 修复平台表达式嵌套三元执行 2026-04-30 03:57:43 +08:00
boris
8e4e0cd86f 完善平台表达式因子执行能力 2026-04-28 23:22:21 +08:00
boris
c73649012f 扩展策略指标因子与滚动函数 2026-04-28 21:01:43 +08:00
9 changed files with 2098 additions and 219 deletions

View File

@@ -0,0 +1,17 @@
//! 把 DSP 运行时 schema 序列化为 JSON 输出到 stdout。
//!
//! 用法(在 fidc-backtest-engine 仓库根):
//! cargo run -p fidc-core --bin dump_platform_runtime_schema \
//! > ../omniquant/src/generated/platformRuntimeSchema.json
//!
//! 这是 omniquant 前端编译期校验表达式标识符的事实源;任何对
//! reserved_scope_names / is_runtime_helper / register_fn 清单的修改,记得
//! 重新跑这个命令并把生成文件提交到 omniquant。
use fidc_core::runtime_schema_json;
fn main() {
let schema = runtime_schema_json();
let output = serde_json::to_string_pretty(&schema).expect("serialize schema");
println!("{output}");
}

View File

@@ -110,6 +110,7 @@ pub struct BrokerSimulator<C, R> {
volume_limit: bool,
inactive_limit: bool,
liquidity_limit: bool,
strict_value_budget: bool,
intraday_execution_start_time: Option<NaiveTime>,
runtime_intraday_start_time: Cell<Option<NaiveTime>>,
runtime_intraday_end_time: Cell<Option<NaiveTime>>,
@@ -130,6 +131,7 @@ impl<C, R> BrokerSimulator<C, R> {
volume_limit: true,
inactive_limit: true,
liquidity_limit: true,
strict_value_budget: false,
intraday_execution_start_time: None,
runtime_intraday_start_time: Cell::new(None),
runtime_intraday_end_time: Cell::new(None),
@@ -154,6 +156,7 @@ impl<C, R> BrokerSimulator<C, R> {
volume_limit: true,
inactive_limit: true,
liquidity_limit: true,
strict_value_budget: false,
intraday_execution_start_time: None,
runtime_intraday_start_time: Cell::new(None),
runtime_intraday_end_time: Cell::new(None),
@@ -177,6 +180,11 @@ impl<C, R> BrokerSimulator<C, R> {
self
}
pub fn with_strict_value_budget(mut self, enabled: bool) -> Self {
self.strict_value_budget = enabled;
self
}
pub fn with_volume_percent(mut self, volume_percent: f64) -> Self {
self.volume_percent = volume_percent;
self
@@ -3388,6 +3396,16 @@ where
requested_qty
}
fn value_budget_gross_limit(&self, value_budget: Option<f64>) -> Option<f64> {
value_budget.map(|budget| {
if self.strict_value_budget {
budget
} else {
budget + 400.0
}
})
}
fn process_buy(
&self,
date: NaiveDate,
@@ -3559,7 +3577,7 @@ where
execution_cursors,
None,
Some(portfolio.cash()),
value_budget.map(|budget| budget + 400.0),
self.value_budget_gross_limit(value_budget),
algo_request,
limit_price,
);
@@ -3590,7 +3608,7 @@ where
let filled_qty = self.affordable_buy_quantity(
date,
portfolio.cash(),
value_budget.map(|budget| budget + 400.0),
self.value_budget_gross_limit(value_budget),
execution_price,
constrained_qty,
self.minimum_order_quantity(data, symbol),
@@ -3601,7 +3619,7 @@ where
partial_fill_reason,
self.buy_reduction_reason(
portfolio.cash(),
value_budget.map(|budget| budget + 400.0),
self.value_budget_gross_limit(value_budget),
execution_price,
constrained_qty,
filled_qty,
@@ -3660,7 +3678,7 @@ where
side: OrderSide::Buy,
requested_quantity: requested_qty,
filled_quantity: 0,
status: OrderStatus::Rejected,
status: zero_fill_status_for_reason(detail),
reason: format!("{reason}: {detail}"),
});
Self::emit_order_process_event(
@@ -3670,7 +3688,10 @@ where
order_id,
symbol,
OrderSide::Buy,
format!("status=Rejected reason={detail}"),
format!(
"status={:?} reason={detail}",
zero_fill_status_for_reason(detail)
),
);
self.clear_open_order(order_id);
return Ok(());
@@ -4255,57 +4276,43 @@ where
}
if algo_request.is_some() || self.intraday_execution_start_time.is_some() {
let execution_price = self.snapshot_execution_price(snapshot, side);
if !self.price_satisfies_limit(
side,
execution_price,
limit_price,
snapshot.effective_price_tick(),
) {
return None;
}
let execution_price =
self.execution_price_with_limit_slippage(execution_price, limit_price);
let quantity = match side {
OrderSide::Buy => self.affordable_buy_quantity(
date,
cash_limit.unwrap_or(f64::INFINITY),
gross_limit,
execution_price,
requested_qty,
minimum_order_quantity,
order_step_size,
),
OrderSide::Sell => requested_qty,
};
if quantity == 0 {
return None;
}
let next_cursor = algo_request
.and_then(|request| request.start_time)
.or(self.intraday_execution_start_time)
.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 {
quantity,
quantity: 0,
next_cursor,
legs: vec![ExecutionLeg {
price: execution_price,
quantity,
}],
unfilled_reason: self.buy_reduction_reason(
cash_limit.unwrap_or(f64::INFINITY),
gross_limit,
execution_price,
requested_qty,
quantity,
),
legs: Vec::new(),
unfilled_reason: Some(self.empty_intraday_quote_reason(
quotes,
start_cursor,
end_cursor,
)),
});
}
None
}
fn empty_intraday_quote_reason(
&self,
quotes: &[IntradayExecutionQuote],
start_cursor: Option<NaiveDateTime>,
end_cursor: Option<NaiveDateTime>,
) -> &'static str {
let saw_quote_in_window = quotes.iter().any(|quote| {
!start_cursor.is_some_and(|cursor| quote.timestamp < cursor)
&& !end_cursor.is_some_and(|cursor| quote.timestamp > cursor)
});
if saw_quote_in_window {
"intraday quote liquidity exhausted"
} else {
"no execution quotes after start"
}
}
fn select_execution_fill(
&self,
snapshot: &crate::data::DailyMarketSnapshot,
@@ -4487,7 +4494,10 @@ fn merge_partial_fill_reason(current: Option<String>, next: Option<&str>) -> Opt
fn zero_fill_status_for_reason(reason: &str) -> OrderStatus {
match reason {
"tick no volume" | "tick volume limit" => OrderStatus::Canceled,
"tick no volume"
| "tick volume limit"
| "intraday quote liquidity exhausted"
| "no execution quotes after start" => OrderStatus::Canceled,
_ => OrderStatus::Rejected,
}
}

View File

@@ -574,6 +574,18 @@ impl SymbolPriceSeries {
Some(sum / lookback as f64)
}
fn decision_prev_close_values(&self, date: NaiveDate, lookback: usize) -> Option<Vec<f64>> {
if lookback == 0 {
return None;
}
let end = self.decision_end_index(date)?;
if end < lookback {
return None;
}
let start = end - lookback;
Some(self.prev_closes[start..end].to_vec())
}
fn decision_volume_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
if lookback == 0 {
return None;
@@ -587,6 +599,23 @@ impl SymbolPriceSeries {
Some(sum / lookback as f64)
}
fn decision_volume_values(&self, date: NaiveDate, lookback: usize) -> Option<Vec<f64>> {
if lookback == 0 {
return None;
}
let end = self.previous_completed_end_index(date)?;
if end < lookback {
return None;
}
let start = end - lookback;
Some(
self.snapshots[start..end]
.iter()
.map(|snapshot| snapshot.volume as f64)
.collect(),
)
}
fn end_index(&self, date: NaiveDate) -> Option<usize> {
match self.dates.binary_search(&date) {
Ok(idx) => Some(idx + 1),
@@ -625,6 +654,7 @@ impl SymbolPriceSeries {
#[derive(Debug, Clone)]
struct BenchmarkPriceSeries {
dates: Vec<NaiveDate>,
opens: Vec<f64>,
closes: Vec<f64>,
open_prefix: Vec<f64>,
close_prefix: Vec<f64>,
@@ -641,6 +671,7 @@ impl BenchmarkPriceSeries {
let close_prefix = prefix_sums(&closes);
Self {
dates,
opens,
closes,
open_prefix,
close_prefix,
@@ -651,6 +682,23 @@ impl BenchmarkPriceSeries {
self.moving_average_for(date, lookback, PriceField::Close)
}
fn decision_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
if lookback == 0 {
return None;
}
let end = match self.dates.binary_search(&date) {
Ok(idx) => idx,
Err(0) => return None,
Err(idx) => idx,
};
if end < lookback {
return None;
}
let start = end - lookback;
let sum = self.close_prefix[end] - self.close_prefix[start];
Some(sum / lookback as f64)
}
fn moving_average_for(
&self,
date: NaiveDate,
@@ -678,13 +726,20 @@ impl BenchmarkPriceSeries {
}
fn trailing_values(&self, date: NaiveDate, lookback: usize) -> Vec<f64> {
self.trailing_values_for(date, lookback, PriceField::Close)
}
fn trailing_values_for(&self, date: NaiveDate, lookback: usize, field: PriceField) -> Vec<f64> {
let end = match self.dates.binary_search(&date) {
Ok(idx) => idx + 1,
Err(0) => return Vec::new(),
Err(idx) => idx,
};
let start = end.saturating_sub(lookback);
self.closes[start..end].to_vec()
match field {
PriceField::DayOpen | PriceField::Open => self.opens[start..end].to_vec(),
PriceField::Close | PriceField::Last => self.closes[start..end].to_vec(),
}
}
}
@@ -944,6 +999,7 @@ impl DataSet {
) -> Result<Self, DataSetError> {
let benchmark_code = collect_benchmark_code(&benchmarks)?;
let calendar = TradingCalendar::new(benchmarks.iter().map(|item| item.date).collect());
let factors = normalize_factor_snapshots(factors);
let instruments = instruments
.into_iter()
@@ -2009,6 +2065,65 @@ impl DataSet {
}
}
pub fn market_decision_numeric_values(
&self,
date: NaiveDate,
symbol: &str,
field: &str,
lookback: usize,
) -> Vec<f64> {
if lookback == 0 {
return Vec::new();
}
let field = normalize_field(field);
match field.as_str() {
"close" | "prev_close" | "stock_close" | "price" => self
.market_series_by_symbol
.get(symbol)
.and_then(|series| series.decision_prev_close_values(date, lookback))
.unwrap_or_default(),
"volume" | "stock_volume" => self
.market_series_by_symbol
.get(symbol)
.and_then(|series| series.decision_volume_values(date, lookback))
.unwrap_or_default(),
"day_open" | "dayopen" => self
.market_series_by_symbol
.get(symbol)
.map(|series| series.trailing_values(date, lookback, PriceField::DayOpen))
.unwrap_or_default(),
"open" => self
.market_series_by_symbol
.get(symbol)
.map(|series| series.trailing_values(date, lookback, PriceField::Open))
.unwrap_or_default(),
"last" | "last_price" => self
.market_series_by_symbol
.get(symbol)
.map(|series| series.trailing_values(date, lookback, PriceField::Last))
.unwrap_or_default(),
other => self.factor_numeric_values(date, symbol, other, lookback),
}
}
pub fn factor_numeric_values(
&self,
date: NaiveDate,
symbol: &str,
field: &str,
lookback: usize,
) -> Vec<f64> {
if lookback == 0 {
return Vec::new();
}
self.calendar
.trailing_days(date, lookback)
.into_iter()
.filter_map(|trading_day| self.factor(trading_day, symbol))
.filter_map(|snapshot| factor_numeric_value(snapshot, field))
.collect()
}
pub fn market_moving_average(
&self,
date: NaiveDate,
@@ -2025,11 +2140,35 @@ impl DataSet {
self.benchmark_series_cache.moving_average(date, lookback)
}
pub fn benchmark_decision_moving_average(
&self,
date: NaiveDate,
lookback: usize,
) -> Option<f64> {
self.benchmark_series_cache
.decision_moving_average(date, lookback)
}
pub fn benchmark_open_moving_average(&self, date: NaiveDate, lookback: usize) -> Option<f64> {
self.benchmark_series_cache
.moving_average_for(date, lookback, PriceField::Open)
}
pub fn benchmark_numeric_values(
&self,
date: NaiveDate,
field: &str,
lookback: usize,
) -> Vec<f64> {
let field = normalize_field(field);
match field.as_str() {
"open" | "day_open" | "dayopen" | "benchmark_open" => self
.benchmark_series_cache
.trailing_values_for(date, lookback, PriceField::Open),
_ => self.benchmark_series_cache.trailing_values(date, lookback),
}
}
pub fn market_open_moving_average(
&self,
date: NaiveDate,
@@ -2400,6 +2539,26 @@ fn factor_numeric_value(snapshot: &DailyFactorSnapshot, field: &str) -> Option<f
"pe_ttm" => Some(snapshot.pe_ttm),
"turnover_ratio" => snapshot.turnover_ratio,
"effective_turnover_ratio" => snapshot.effective_turnover_ratio,
"ths_market_value_stock" | "ths_market_value_stock_bn" => snapshot
.extra_factors
.get(field.as_str())
.copied()
.or(Some(snapshot.market_cap_bn)),
"ths_current_mv_stock" | "ths_current_mv_stock_bn" => snapshot
.extra_factors
.get(field.as_str())
.copied()
.or(Some(snapshot.free_float_cap_bn)),
"ths_turnover_ratio_stock" => snapshot
.extra_factors
.get(field.as_str())
.copied()
.or(snapshot.turnover_ratio),
"ths_vaild_turnover_stock" | "ths_valid_turnover_stock" => snapshot
.extra_factors
.get(field.as_str())
.copied()
.or(snapshot.effective_turnover_ratio),
other => snapshot.extra_factors.get(other).copied(),
}
}
@@ -2509,6 +2668,27 @@ fn normalize_field(field: &str) -> String {
.to_ascii_lowercase()
}
fn normalize_factor_snapshots(factors: Vec<DailyFactorSnapshot>) -> Vec<DailyFactorSnapshot> {
factors
.into_iter()
.map(|mut snapshot| {
snapshot.extra_factors = snapshot
.extra_factors
.into_iter()
.filter_map(|(field, value)| {
let normalized = normalize_field(&field);
if normalized.is_empty() || !value.is_finite() {
None
} else {
Some((normalized, value))
}
})
.collect();
snapshot
})
.collect()
}
fn normalize_history_frequency(frequency: &str) -> Option<String> {
let normalized = normalize_field(frequency);
match normalized.as_str() {

View File

@@ -9,6 +9,7 @@ pub mod futures;
pub mod instrument;
pub mod metrics;
pub mod platform_expr_strategy;
pub mod platform_runtime_schema;
pub mod platform_strategy_spec;
pub mod portfolio;
pub mod rules;
@@ -50,6 +51,11 @@ pub use platform_expr_strategy::{
PlatformRebalanceSchedule, PlatformScheduleFrequency, PlatformTradeAction,
PlatformUniverseActionKind,
};
pub use platform_runtime_schema::{
PLATFORM_RUNTIME_SCHEMA_VERSION, PlatformRuntimeSchema, reserved_scope_names,
rhai_builtin_functions, rhai_keywords, runtime_helper_functions, runtime_schema,
runtime_schema_json,
};
pub use platform_strategy_spec::{
DynamicRangeConfig, IndexThrottleConfig, MovingAverageFilterConfig, SkipWindowConfig,
StrategyBenchmarkSpec, StrategyEngineConfig, StrategyExecutionSpec,

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,345 @@
//! DSP 运行时变量与函数 schema 导出。
//!
//! 这是前后端共享的"事实源":把引擎里 reserved_scope_names 和 is_runtime_helper
//! 等清单按 JSON Schema 暴露出来,供 omniquant 前端在编译期做表达式标识符校验。
//!
//! 维护原则:
//! - 任何对 platform_expr_strategy.rs 中变量名 / 函数名清单的修改都必须在这里
//! 同步一份。两侧一致由 unit test `runtime_schema_matches_strategy_runtime`
//! 守住。
//! - 该 schema 的 version 字段需要与 omniquant/src/platformSchema.ts 里
//! PLATFORM_RUNTIME_SCHEMA_VERSION 保持一致。前端读到不同版本时应给出诊断。
use serde::Serialize;
use serde_json::Value;
/// 当前 schema 版本号。每次 reserved/runtime 列表的破坏性变更需要 +1。
pub const PLATFORM_RUNTIME_SCHEMA_VERSION: &str = "1";
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PlatformRuntimeSchema {
pub version: &'static str,
pub reserved_scope_names: Vec<&'static str>,
pub runtime_helper_functions: Vec<&'static str>,
pub rhai_builtin_functions: Vec<&'static str>,
pub rhai_keywords: Vec<&'static str>,
}
/// reserved scope names 列表。镜像 PlatformExprStrategy::reserved_scope_names。
pub fn reserved_scope_names() -> &'static [&'static str] {
RESERVED_SCOPE_NAMES
}
/// runtime helper functions 列表。镜像 PlatformExprStrategy::is_runtime_helper。
pub fn runtime_helper_functions() -> &'static [&'static str] {
RUNTIME_HELPER_FUNCTIONS
}
/// rhai engine 注册的内置函数列表。镜像 PlatformExprStrategy::new 中 register_fn
/// 的清单。
pub fn rhai_builtin_functions() -> &'static [&'static str] {
RHAI_BUILTIN_FUNCTIONS
}
/// rhai 控制流关键字(避免被前端校验视为未知)。
pub fn rhai_keywords() -> &'static [&'static str] {
RHAI_KEYWORDS
}
/// 构造完整 schema。
pub fn runtime_schema() -> PlatformRuntimeSchema {
PlatformRuntimeSchema {
version: PLATFORM_RUNTIME_SCHEMA_VERSION,
reserved_scope_names: RESERVED_SCOPE_NAMES.to_vec(),
runtime_helper_functions: RUNTIME_HELPER_FUNCTIONS.to_vec(),
rhai_builtin_functions: RHAI_BUILTIN_FUNCTIONS.to_vec(),
rhai_keywords: RHAI_KEYWORDS.to_vec(),
}
}
/// 把 schema 序列化为 JSON Value。给 fidc-data-center / strategy-runtime 接口使用。
pub fn runtime_schema_json() -> Value {
serde_json::to_value(runtime_schema()).expect("runtime schema serialization is infallible")
}
const RESERVED_SCOPE_NAMES: &[&str] = &[
// day-level
"signal_close",
"benchmark_close",
"signal_ma5",
"signal_ma10",
"signal_ma20",
"signal_ma30",
"benchmark_ma5",
"benchmark_ma10",
"benchmark_ma20",
"benchmark_ma30",
"benchmark_ma_short",
"benchmark_ma_long",
"cash",
"available_cash",
"frozen_cash",
"market_value",
"total_equity",
"total_value",
"portfolio_value",
"starting_cash",
"unit_net_value",
"static_unit_net_value",
"daily_pnl",
"daily_returns",
"total_returns",
"cash_liabilities",
"management_fee_rate",
"management_fees",
"current_exposure",
"position_count",
"max_positions",
"refresh_rate",
"year",
"month",
"quarter",
"day_of_month",
"day_of_year",
"week_of_year",
"weekday",
"is_month_start",
"is_month_end",
"has_open_orders",
"open_order_count",
"open_buy_order_count",
"open_sell_order_count",
"open_buy_qty",
"open_sell_qty",
"latest_open_order_id",
"latest_open_order_status",
"latest_open_order_unfilled_qty",
"has_process_events",
"process_event_count",
"current_process_kind",
"current_process_order_id",
"current_process_symbol",
"current_process_side",
"current_process_detail",
"latest_process_kind",
"latest_process_order_id",
"latest_process_symbol",
"latest_process_side",
"latest_process_detail",
"process_event_counts",
"day_factors",
// stock-level
"symbol",
"market_cap",
"free_float_cap",
"pe_ttm",
"volume",
"tick_volume",
"bid1_volume",
"ask1_volume",
"turnover_ratio",
"effective_turnover_ratio",
"open",
"high",
"low",
"close",
"last",
"last_price",
"prev_close",
"amount",
"upper_limit",
"lower_limit",
"price_tick",
"round_lot",
"paused",
"is_st",
"is_kcb",
"is_one_yuan",
"is_new_listing",
"allow_buy",
"allow_sell",
"touched_upper_limit",
"touched_lower_limit",
"hit_upper_limit",
"hit_lower_limit",
"listed_days",
"symbol_open_order_count",
"symbol_open_buy_qty",
"symbol_open_sell_qty",
"latest_symbol_open_order_id",
"latest_symbol_open_order_status",
"latest_symbol_open_order_unfilled_qty",
"stock_ma_short",
"stock_ma_mid",
"stock_ma_long",
"stock_ma5",
"stock_ma10",
"stock_ma20",
"stock_ma30",
"ma5",
"ma10",
"ma20",
"ma30",
"factors",
"order_book_id",
// position-level
"avg_cost",
"avg_price",
"current_price",
"position_prev_close",
"prev_position_close",
"holding_return",
"quantity",
"sellable_qty",
"sellable",
"closable",
"old_quantity",
"buy_quantity",
"sell_quantity",
"bought_quantity",
"sold_quantity",
"buy_avg_price",
"sell_avg_price",
"bought_value",
"sold_value",
"transaction_cost",
"position_market_value",
"equity",
"value_percent",
"unrealized_pnl",
"realized_pnl",
"pnl",
"day_trade_quantity_delta",
"profit_pct",
"trading_pnl",
"position_pnl",
"dividend_receivable",
"at_upper_limit",
"at_lower_limit",
];
const RUNTIME_HELPER_FUNCTIONS: &[&str] = &[
"factor",
"day_factor",
"rolling_mean",
"ma",
"sma",
"vma",
"rolling_sum",
"rolling_min",
"rolling_max",
"rolling_stddev",
"stddev",
"rolling_zscore",
"pct_change",
"factor_value",
"get_factor_value",
"factor_text",
"get_factor_text",
"dividend_cash",
"has_dividend",
"split_ratio",
"has_split",
"securities_margin",
"get_securities_margin_value",
"shares",
"get_shares_value",
"turnover_rate",
"get_turnover_rate_value",
"price_change_rate",
"get_price_change_rate_value",
"stock_connect",
"get_stock_connect_value",
"current_performance",
"fundamental",
"get_fundamentals_value",
"financial",
"get_financials_value",
"pit_financial",
"get_pit_financials_value",
"industry_code",
"get_industry_code",
"industry_name",
"get_industry_name",
"yield_curve",
"get_yield_curve_value",
"is_margin_stock",
"dominant_future",
"get_dominant_future",
"dominant_future_price",
"get_dominant_future_price_value",
];
const RHAI_BUILTIN_FUNCTIONS: &[&str] = &[
"round",
"floor",
"ceil",
"abs",
"min",
"max",
"sqrt",
"pow",
"log",
"exp",
"clamp",
"between",
"nz",
"safe_div",
"iff",
"contains",
"starts_with",
"ends_with",
"lower",
"upper",
"trim",
"strlen",
];
const RHAI_KEYWORDS: &[&str] = &[
"if", "else", "while", "loop", "for", "in", "break", "continue", "return", "fn", "let",
"const", "true", "false", "switch", "do",
];
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn runtime_schema_serializes_to_json_object() {
let value = runtime_schema_json();
assert!(value.is_object());
assert_eq!(value["version"], "1");
assert!(value["reservedScopeNames"].is_array());
assert!(value["runtimeHelperFunctions"].is_array());
assert!(value["rhaiBuiltinFunctions"].is_array());
assert!(value["rhaiKeywords"].is_array());
}
#[test]
fn runtime_schema_includes_known_identifiers() {
let names: std::collections::HashSet<&str> = RESERVED_SCOPE_NAMES.iter().copied().collect();
for required in [
"signal_close",
"benchmark_close",
"close",
"avg_cost",
"current_price",
"stock_ma_short",
] {
assert!(
names.contains(required),
"missing reserved name: {required}"
);
}
let helpers: std::collections::HashSet<&str> =
RUNTIME_HELPER_FUNCTIONS.iter().copied().collect();
for required in ["rolling_mean", "factor", "pct_change"] {
assert!(
helpers.contains(required),
"missing helper function: {required}"
);
}
}
}

View File

@@ -49,6 +49,8 @@ pub struct StrategyExecutionSpec {
pub slippage_model: Option<String>,
#[serde(default)]
pub slippage_value: Option<f64>,
#[serde(default)]
pub strict_value_budget: Option<bool>,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
@@ -83,6 +85,8 @@ pub struct StrategyEngineConfig {
#[serde(default)]
pub slippage_value: Option<f64>,
#[serde(default)]
pub strict_value_budget: Option<bool>,
#[serde(default)]
pub dividend_reinvestment: Option<bool>,
#[serde(default)]
pub rebalance_schedule: Option<StrategyExpressionScheduleConfig>,
@@ -224,6 +228,10 @@ pub struct StrategyExpressionTradingConfig {
#[serde(default)]
pub rotation_enabled: Option<bool>,
#[serde(default)]
pub daily_top_up: Option<bool>,
#[serde(default)]
pub retry_empty_rebalance: Option<bool>,
#[serde(default)]
pub subscription_guard_required: Option<bool>,
#[serde(default)]
pub actions: Vec<StrategyExpressionActionConfig>,
@@ -551,6 +559,24 @@ pub fn platform_expr_config_from_spec(
if let Some(enabled) = trading.rotation_enabled {
cfg.rotation_enabled = enabled;
}
if let Some(enabled) = trading.daily_top_up {
cfg.daily_top_up_enabled = enabled;
}
if let Some(enabled) = trading.retry_empty_rebalance {
cfg.retry_empty_rebalance = enabled;
}
if let Some(enabled) = spec
.engine_config
.as_ref()
.and_then(|engine| engine.strict_value_budget)
.or_else(|| {
spec.execution
.as_ref()
.and_then(|execution| execution.strict_value_budget)
})
{
cfg.strict_value_budget = enabled;
}
if let Some(required) = trading.subscription_guard_required {
cfg.subscription_guard_required = required;
}
@@ -1008,6 +1034,8 @@ mod tests {
},
"trading": {
"rotationEnabled": false,
"dailyTopUp": true,
"retryEmptyRebalance": true,
"stage": "open_auction",
"actions": [
{
@@ -1027,6 +1055,8 @@ mod tests {
assert_eq!(cfg.signal_symbol, "000852.SH");
assert_eq!(cfg.selection_limit_expr, "stocknum");
assert!(!cfg.rotation_enabled);
assert!(cfg.daily_top_up_enabled);
assert!(cfg.retry_empty_rebalance);
assert_eq!(cfg.explicit_actions.len(), 1);
assert_eq!(
cfg.explicit_action_stage,

View File

@@ -97,10 +97,11 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
"平台策略脚本采用声明式 DSL + 表达式执行模型。".to_string(),
"支持 let 变量、fn 自定义函数、when/unless/else 条件块、可用指标/因子字段映射。".to_string(),
"支持数值型和字符串型因子,字符串字段可用于行业、概念、标签、板块等分类过滤。".to_string(),
"当前默认回测数据已支持 OHLCV、市值、流通市值、换手率、有效换手率、上市天数、停牌/ST/板块、涨跌停价格、tick 触达涨跌停、常用价格/成交量均线;复杂技术指标和财务报表字段必须来自预计算因子或后续扩展函数".to_string(),
"当前默认回测数据已支持 OHLCV、市值、流通市值、换手率、有效换手率、上市天数、停牌/ST/板块、涨跌停价格、tick 触达涨跌停、常用价格/成交量均线,以及 stock_indicator_factors_v1 中已入库的通用指标因子".to_string(),
"AI 生成策略时只能输出完整 engine-script 代码,不输出 Markdown、解释、推理过程、JSON 包装或手册复述。".to_string(),
"表达式字段以运行时字段为准:市值使用 market_cap流通市值使用 free_float_cap不要在策略表达式中使用数据库原始字段 float_market_cap。".to_string(),
"60日价格均线使用 rolling_mean(\"close\", 60),不要使用 ma60、stock_ma60、signal_ma60 或 benchmark_ma60。".to_string(),
"任意窗口价格均线使用 rolling_mean(\"close\", n) 或 ma(\"close\", n),任意窗口均量使用 rolling_mean(\"volume\", n) 或 vma(n);不要使用未列出的 ma60、stock_ma60、signal_ma60 或 benchmark_ma60 变量".to_string(),
"next_bar_open 会用决策日信号生成订单,并在下一可交易开盘撮合;不得把执行日 open/high/low/close 当成下单前已知信息。".to_string(),
"自定义 fn 必须通过参数传入运行时字段;不要用 fn score() 这类零参数函数直接引用 market_cap、close、ma5 等股票字段。".to_string(),
"禁止自由 Python/JavaScript 命令式语句,最终必须输出平台 DSL。".to_string(),
],
@@ -165,6 +166,10 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
title: "诊断解释".to_string(),
detail: "结果为空或收益异常时优先展示 diagnostics、选股数量、过滤原因、缺失字段、窗口不足、涨跌停/停牌拒单、快照缓存命中情况。不要只返回 JSON要给用户自然语言结论和下一步优化建议。".to_string(),
},
ManualSection {
title: "收益合理性复核".to_string(),
detail: "展示或用于优化前,应按 finalEquity / initialCash - 1 复算总收益。若小资金回测出现极端收益、指标与资金不一致、或历史 run 来自旧引擎,应检查交易明细并用当前编译后的回测引擎重新回测,不要把异常 run 当成成功样本。".to_string(),
},
],
optimization_playbook: vec![
ManualSection {
@@ -215,7 +220,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
},
ManualSection {
title: "execution.matching_type / execution.slippage".to_string(),
detail: "设置撮合模式和滑点。支持 execution.matching_type(\"next_tick_last\" | \"next_tick_best_own\" | \"next_tick_best_counterparty\" | \"counterparty_offer\" | \"vwap\" | \"current_bar_close\" | \"next_bar_open\" | \"open_auction\")。其中 next_tick_last 使用 tick 的 last_pricenext_tick_best_own / next_tick_best_counterparty 会按 L1 买一卖一近似 平台内核 的 tick 最优价语义counterparty_offer 在存在 order_book_depth 多档盘口数据时会按真实档位逐档扫单并计算加权成交价,不存在 depth 时回退 L1 对手方报价vwap 会在盘中执行价链路上聚合多笔成交为单条 VWAP 成交open_auction 使用当日集合竞价开盘价 day_open 进行撮合,且不额外施加滑点,并按竞价成交量而不是盘口一档流动性限制成交;滑点支持 execution.slippage(\"none\") / execution.slippage(\"price_ratio\", 0.001) / execution.slippage(\"tick_size\", 1) / execution.slippage(\"limit_price\"),其中 limit_price 会在限价单成交时按挂单价模拟 平台内核 的最坏成交价。".to_string(),
detail: "设置撮合模式和滑点。支持 execution.matching_type(\"next_tick_last\" | \"next_tick_best_own\" | \"next_tick_best_counterparty\" | \"counterparty_offer\" | \"vwap\" | \"current_bar_close\" | \"next_bar_open\" | \"open_auction\")。其中 next_tick_last 使用 tick 的 last_pricenext_tick_best_own / next_tick_best_counterparty 会按 L1 买一卖一近似 平台内核 的 tick 最优价语义counterparty_offer 在存在 order_book_depth 多档盘口数据时会按真实档位逐档扫单并计算加权成交价,不存在 depth 时回退 L1 对手方报价vwap 会在盘中执行价链路上聚合多笔成交为单条 VWAP 成交;next_bar_open 使用决策日信号并在下一可交易日开盘撮合,禁止把执行日 open/high/low/close 解释为下单前已知数据;open_auction 使用当日集合竞价开盘价 day_open 进行撮合,且不额外施加滑点,并按竞价成交量而不是盘口一档流动性限制成交;滑点支持 execution.slippage(\"none\") / execution.slippage(\"price_ratio\", 0.001) / execution.slippage(\"tick_size\", 1) / execution.slippage(\"limit_price\"),其中 limit_price 会在限价单成交时按挂单价模拟 平台内核 的最坏成交价。".to_string(),
},
ManualSection {
title: "期货提交校验".to_string(),
@@ -262,7 +267,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
fields: vec![
ManualField { name: "symbol".to_string(), field_type: "string".to_string(), detail: "证券代码。".to_string() },
ManualField { name: "market_cap/free_float_cap".to_string(), field_type: "float".to_string(), detail: "总市值、流通市值。".to_string() },
ManualField { name: "turnover_ratio/effective_turnover_ratio".to_string(), field_type: "float".to_string(), detail: "换手率、有效换手率。".to_string() },
ManualField { name: "turnover/turnover_ratio/effective_turnover_ratio".to_string(), field_type: "float".to_string(), detail: "换手率、换手率标准字段、有效换手率turnover 是 turnover_ratio 的兼容别名".to_string() },
ManualField { name: "open/high/low/close/last/last_price/prev_close/amount".to_string(), field_type: "float".to_string(), detail: "开盘、最高、最低、收盘、盘中价、昨收和成交额。".to_string() },
ManualField { name: "upper_limit/lower_limit/price_tick/round_lot/minimum_order_quantity/order_step_size".to_string(), field_type: "float/int".to_string(), detail: "涨跌停、最小价位、整手、最小下单量和数量步长。KSH/BJSE 等板块可与 round_lot 不同。".to_string() },
ManualField { name: "paused/is_st/is_kcb/is_one_yuan/is_new_listing".to_string(), field_type: "bool".to_string(), detail: "可交易性与板块标志。".to_string() },
@@ -323,9 +328,11 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
ManualFunction { name: "order/order_status/order_avg_price/order_transaction_cost".to_string(), signature: "ctx.order(order_id)".to_string(), detail: "按订单 id 查询运行时订单对象,支持已结束订单和当前挂单。返回字段包括 status、filled_quantity、unfilled_quantity、avg_price、transaction_cost、symbol、side、reason可用便捷函数读取状态、成交均价和费用对齐 平台内核 Order 的核心属性。".to_string() },
ManualFunction { name: "account/portfolio_view/accounts".to_string(), signature: "ctx.account()".to_string(), detail: "返回当前股票账户/组合运行时视图,字段包括 account_type、cash、available_cash、frozen_cash、market_value、total_value、unit_net_value、daily_pnl、daily_returns、total_returns、transaction_cost、trading_pnl、position_pnl 等DSL 中同名字段可直接使用。也可用 ctx.stock_account()、ctx.account_by_type(\"STOCK\")、ctx.accounts() 按账户类型读取;当前股票回测路径不会把 FUTURE 虚假映射成 STOCK。".to_string() },
ManualFunction { name: "deposit_withdraw/finance_repay/management_fee".to_string(), signature: "account.deposit_withdraw(amount, receiving_days=0)".to_string(), detail: "策略账户资金动作。deposit_withdraw 正数入金、负数出金receiving_days 大于 0 时按交易日延迟到账并保持净值口径不把外部资金流当成收益。finance_repay 正数融资、负数还款,会同步维护 cash_liabilities。set_management_fee_rate 设置结算管理费率;普通策略可覆盖 management_fee(ctx, rate) 自定义计算器,对齐 平台内核 管理费回调能力。".to_string() },
ManualFunction { name: "rolling_mean".to_string(), signature: "rolling_mean(\"field\", lookback)".to_string(), detail: "任意字段滚动均值,支持 volume/amount/turnover_ratio、signal_open/signal_close、benchmark_open/benchmark_close 等。个股 volume 与 close 均按当前交易日前已完成交易日计算;单只股票历史窗口不足时在选股过滤和买入仓位表达式中按不通过/0 仓处理,不会中断整次回测。任意成交量窗口推荐用它,比如 rolling_mean(\"volume\", 15)".to_string() },
ManualFunction { name: "sma".to_string(), signature: "sma(\"field\", lookback)".to_string(), detail: "rolling_mean 的别名。任意价格均线窗口推荐用它,比如 sma(\"close\", 15)。".to_string() },
ManualFunction { name: "复杂技术指标".to_string(), signature: "factor_value(\"macd\", 1) 或预计算字段".to_string(), detail: "BOLL、EMA、WMA、DEMA、TEMA、KAMA、SAR、ADX、CCI、MACD、RSI、KDJ、WILLR、ATR、ROC、TRIX、MFI、Aroon、OBV、ADL、Beta、相关系数、线性回归、标准差、方差、K 线形态等目前不是默认内建函数;可先预计算成数值因子,再用 factor_value/rolling_mean 读取".to_string() },
ManualFunction { name: "rolling_mean / sma / ma".to_string(), signature: "rolling_mean(\"field\", lookback) / ma(\"close\", 20)".to_string(), detail: "任意字段滚动均值,支持 close、volumeamount、turnover_ratio、effective_turnover_ratio、signal_open/signal_close、benchmark_open/benchmark_close 和所有数值型 extra_factors。个股 close 使用当前交易日前已完成收盘序列volume 使用当前交易日前已完成成交量序列;历史窗口不足时在选股过滤和买入仓位表达式中按不通过/0 仓处理。".to_string() },
ManualFunction { name: "vma".to_string(), signature: "vma(60)".to_string(), detail: "rolling_mean(\"volume\", lookback) 的便捷别名,用于任意窗口成交量均线,例如 vma(5) < vma(60)。".to_string() },
ManualFunction { name: "rolling_sum / rolling_min / rolling_max".to_string(), signature: "rolling_sum(\"volume\", 20)".to_string(), detail: "任意数值字段滚动求和、最小值、最大值。可用于量能收缩、区间高低点、资金活跃度等过滤或排序".to_string() },
ManualFunction { name: "rolling_stddev / stddev / rolling_zscore / pct_change".to_string(), signature: "stddev(\"close\", 20) / pct_change(\"close\", 10)".to_string(), detail: "滚动标准差、最新值 Z 分数和区间涨跌幅。pct_change(field, n) 会读取 n+1 个窗口点并计算 latest / first - 1。".to_string() },
ManualFunction { name: "数据库指标因子".to_string(), signature: "factor_value(\"ths_valid_turnover_stock\", 1)".to_string(), detail: "stock_indicator_factors_v1 中的指标会进入 extra_factors可用 factor(\"字段\")、factors[\"字段\"]、factor_value(\"字段\", lookback) 或 rolling_mean(\"字段\", n) 读取。市值类指标统一提供亿元口径别名 ths_market_value_stock、ths_market_value_stock_bn、ths_current_mv_stock、ths_current_mv_stock_bn同时保留 raw 后缀原始值。".to_string() },
ManualFunction { name: "round/floor/ceil/abs/min/max/clamp".to_string(), signature: "round(x)".to_string(), detail: "常用数值函数。".to_string() },
ManualFunction { name: "safe_div".to_string(), signature: "safe_div(lhs, rhs, fallback)".to_string(), detail: "安全除法。".to_string() },
ManualFunction { name: "contains/starts_with/ends_with/lower/upper/trim/strlen".to_string(), signature: "starts_with(symbol, \"60\")".to_string(), detail: "字符串辅助函数。".to_string() },
@@ -343,7 +350,7 @@ pub fn built_in_strategy_manual() -> StrategyAiManual {
},
ManualFactorSource {
table: "扩展指标因子".to_string(),
detail: "当前可用扩展指标主要包括总市值、流通市值、换手率、有效换手率;其他财务、行业、概念、陆股通、技术指标等只有落地为可用因子后才可在策略中直接使用".to_string(),
detail: "来自 stock_indicator_factors_v1 和运行时 extra_factors。已入库指标会自动进入策略运行时字段名使用 dataset 小写下划线市值类默认换算为亿元口径raw 后缀保留原始 indicator_value".to_string(),
fields: vec![],
},
ManualFactorSource {
@@ -428,10 +435,15 @@ pub fn render_manual_markdown(manual: &StrategyAiManual) -> String {
out.push_str("- 只使用支持语句块:`market`、`benchmark`、`signal`、`rebalance.every_days(...).at([...])`、`selection.limit`、`selection.market_cap_band`、`filter.stock_ma`、`filter.stock_expr`、`ordering.rank_by`、`ordering.rank_expr`、`allocation.buy_scale`、`risk.stop_loss`、`risk.take_profit`、`risk.index_exposure`、`execution.matching_type`、`execution.slippage`、`universe.exclude`。\n");
out.push_str("- 禁止伪 DSL`filter(...)`、`rank(...)`、`select.top(...)`、`weight.equal(...)`、`sell_rule(...)`、`backtest(...)`、`risk.max_position(...)`。\n");
out.push_str("- 市值表达式字段只能用 `market_cap` 或 `free_float_cap`;不要使用数据库原始字段 `float_market_cap`。\n");
out.push_str("- 60日价格均线使用 `rolling_mean(\"close\", 60)`;不要使用 `ma60`、`stock_ma60`、`signal_ma60` 或 `benchmark_ma60`。\n");
out.push_str("- 任意窗口价格均线使用 `rolling_mean(\"close\", n)` 或 `ma(\"close\", n)`;任意窗口均量使用 `rolling_mean(\"volume\", n)` 或 `vma(n)`;不要使用未列出的 `ma60`、`stock_ma60`、`signal_ma60` 或 `benchmark_ma60` 变量\n");
out.push_str("- 自定义 `fn` 必须通过参数传入运行时字段;不要用 `fn score()` 这类零参数函数直接引用 `market_cap`、`close`、`ma5` 等股票字段。\n");
out.push_str("- `selection.market_cap_band` 必须写命名参数:`field=\"market_cap\"` 或 `field=\"free_float_cap\"`,并包含 `lower=...` 与 `upper=...`。\n");
out.push_str("- `risk.index_exposure(...)` 只能传一个表达式;`execution.matching_type(...)` 和 `execution.slippage(...)` 必须使用手册列出的合法取值。\n\n");
out.push_str(
"- `risk.index_exposure(...)` 只能传一个表达式;不要生成 `risk.exposure(...)`。\n",
);
out.push_str("- 完整三元表达式 `cond ? a : b` 可在表达式参数中使用;若当前运行环境报 `Unknown operator: '?'`,先重编译并重启回测服务,不要改写策略语义掩盖运行时漂移。\n");
out.push_str("- `next_bar_open` 的选股、排序和仓位信号来自决策日,订单在下一可交易开盘撮合;不要使用执行日价格作为下单前信号。\n");
out.push_str("- `execution.matching_type(...)` 和 `execution.slippage(...)` 必须使用手册列出的合法取值。\n\n");
out.push_str("## 语句块\n");
for item in &manual.statement_blocks {
out.push_str(&format!("- `{}`: {}\n", item.title, item.detail));
@@ -506,9 +518,9 @@ pub fn build_generation_prompt(
prompt.push_str("- 生成的代码必须能转换为 strategy_spec 并提交 POST /v1/backtests。\n");
prompt.push_str("- 不要使用手册未列出的字段、函数或外部平台 API 名称。\n\n");
prompt.push_str("只允许使用这些可编译语句market、benchmark、signal、rebalance.every_days(...).at([...])、selection.limit、selection.market_cap_band、filter.stock_ma、filter.stock_expr、ordering.rank_by、ordering.rank_expr、allocation.buy_scale、risk.stop_loss、risk.take_profit、risk.index_exposure、execution.matching_type、execution.slippage、universe.exclude。禁止输出 filter(...)、rank(...)、select.top(...)、weight.equal()、sell_rule(...)、backtest(...)、risk.max_position(...) 这类未支持伪语法。\n");
prompt.push_str("参数形态必须严格selection.market_cap_band 必须写 field=\"market_cap\" 或 field=\"free_float_cap\", lower=..., upper=...;禁止使用 float_market_cap禁止使用 ma60、stock_ma60、signal_ma60、benchmark_ma6060日价格均线写 rolling_mean(\"close\", 60);不要生成 fn score() 这类零参数函数,股票字段排序直接写在 ordering.rank_expr 内或用带参数函数;布尔字段按布尔使用,写 !is_st、!paused、!at_upper_limit、!at_lower_limit不要写 is_st == 0risk.index_exposure 只能传一个数值表达式,例如 ((signal_close < signal_ma20) ? 0.35 : 1.0)execution.matching_type 只能取 next_tick_last、next_tick_best_own、next_tick_best_counterparty、counterparty_offer、vwap、current_bar_close、next_bar_open、open_auctionexecution.slippage 必须写 execution.slippage(\"none\") 或 execution.slippage(\"price_ratio\", 0.001)。\n");
prompt.push_str("参数形态必须严格selection.market_cap_band 必须写 field=\"market_cap\" 或 field=\"free_float_cap\", lower=..., upper=...;禁止使用 float_market_cap禁止使用 ma60、stock_ma60、signal_ma60、benchmark_ma6060日价格均线写 rolling_mean(\"close\", 60) 或 ma(\"close\", 60),任意窗口均量写 rolling_mean(\"volume\", n) 或 vma(n);不要生成 fn score() 这类零参数函数,股票字段排序直接写在 ordering.rank_expr 内或用带参数函数;布尔字段按布尔使用,写 !is_st、!paused、!at_upper_limit、!at_lower_limit不要写 is_st == 0risk.index_exposure 只能传一个数值表达式,不要使用 risk.exposure完整三元表达式 cond ? a : b 可以使用,但不得输出残缺问号/冒号片段execution.matching_type 只能取 next_tick_last、next_tick_best_own、next_tick_best_counterparty、counterparty_offer、vwap、current_bar_close、next_bar_open、open_auctionnext_bar_open 只能使用决策日信号,不能把执行日价格当作下单前信息;execution.slippage 必须写 execution.slippage(\"none\") 或 execution.slippage(\"price_ratio\", 0.001)。\n");
prompt.push_str("回测成功但 tradeCount=0 或 holdingCount=0 是无效策略;第一版必须保持稳定买入覆盖率,复杂因子只能在后续优化中逐步加严。\n");
prompt.push_str("可参考但不要照抄的最小模板,回复时不要包含 ``` 代码围栏:\nstrategy(\"cn_a_smallcap_factor_rotation\") {\nmarket(\"CN_A\")\nbenchmark(\"000852.SH\")\nsignal(\"000001.SH\")\nrebalance.every_days(5).at([\"10:18\"])\nselection.limit(40)\nselection.market_cap_band(field=\"market_cap\", lower=0, upper=1000)\nfilter.stock_expr(listed_days >= 60 && !is_st && !paused && close > 2 && !at_upper_limit && !at_lower_limit)\nordering.rank_by(\"market_cap\", \"asc\")\nallocation.buy_scale(1.0)\nrisk.index_exposure((signal_close < signal_ma20) ? 0.35 : 1.0)\nrisk.stop_loss(holding_return < -0.08)\nexecution.slippage(\"price_ratio\", 0.001)\n}\n\n");
prompt.push_str("可参考但不要照抄的最小模板,回复时不要包含 ``` 代码围栏:\nstrategy(\"cn_a_smallcap_factor_rotation\") {\nmarket(\"CN_A\")\nbenchmark(\"000852.SH\")\nsignal(\"000001.SH\")\nrebalance.every_days(5).at([\"10:18\"])\nselection.limit(40)\nselection.market_cap_band(field=\"market_cap\", lower=0, upper=1000)\nfilter.stock_expr(listed_days >= 60 && !is_st && !paused && close > 2 && !at_upper_limit && !at_lower_limit)\nordering.rank_by(\"market_cap\", \"asc\")\nallocation.buy_scale(1.0)\nrisk.index_exposure(1.0)\nrisk.stop_loss(holding_return < -0.08)\nexecution.slippage(\"price_ratio\", 0.001)\n}\n\n");
prompt.push_str("用户目标:\n");
prompt.push_str(&format!("- {}\n", request.user_goal));
if !request.constraints.is_empty() {
@@ -535,6 +547,7 @@ pub fn build_optimization_prompt(
prompt.push_str("输出格式硬约束:回复第一行必须是 strategy(\"...\")、let、fn、const 或 //;回复中不得包含 Markdown、解释、思考过程、手册复述、JSON 包装或自然语言总结。\n");
prompt.push_str("长度硬约束:策略代码目标 80 行以内,只保留必要 let/fn/strategy 块;不要复制下面的手册片段、历史策略全文或字段清单。\n");
prompt.push_str("只修改与优化目标相关的少量参数或过滤条件,保留原策略的市场、基准、信号指数和核心风控;不要引入手册未列出的字段或外部平台 API 名称。\n");
prompt.push_str("优化可以调整调仓周期、持仓数、市值带、filter.stock_expr、ordering.rank_expr、allocation.buy_scale、止盈止损如上一轮无交易或质量分过低必须先放宽过滤条件并优先使用已入库指标因子、rolling_mean/ma/vma/rolling_stddev/pct_change 等支持函数。\n");
prompt.push_str("优化目标:\n");
prompt.push_str(&format!("- {}\n\n", request.objective));
prompt.push_str("当前策略代码如下,仅作为输入参考;回复时不要包含 Markdown 代码围栏:\n");

View File

@@ -10,7 +10,7 @@ use std::collections::{BTreeMap, BTreeSet};
#[test]
fn broker_executes_explicit_order_value_buy() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
let data = DataSet::from_components(
let data = DataSet::from_components_with_actions_and_quotes(
vec![Instrument {
symbol: "000002.SZ".to_string(),
name: "Test".to_string(),
@@ -72,6 +72,20 @@ fn broker_executes_explicit_order_value_buy() {
prev_close: 99.0,
volume: 1_000_000,
}],
Vec::new(),
vec![IntradayExecutionQuote {
date,
symbol: "000002.SZ".to_string(),
timestamp: date.and_hms_opt(10, 18, 3).unwrap(),
last_price: 10.0,
bid1: 9.99,
ask1: 10.01,
bid1_volume: 1,
ask1_volume: 1,
volume_delta: 1,
amount_delta: 0.0,
trading_phase: Some("continuous".to_string()),
}],
)
.expect("dataset");
let mut portfolio = PortfolioState::new(1_000_000.0);
@@ -111,7 +125,7 @@ fn broker_executes_explicit_order_value_buy() {
#[test]
fn broker_executes_order_shares_and_order_lots() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
let data = DataSet::from_components(
let data = DataSet::from_components_with_actions_and_quotes(
vec![Instrument {
symbol: "000002.SZ".to_string(),
name: "Test".to_string(),
@@ -173,6 +187,20 @@ fn broker_executes_order_shares_and_order_lots() {
prev_close: 99.0,
volume: 1_000_000,
}],
Vec::new(),
vec![IntradayExecutionQuote {
date,
symbol: "000002.SZ".to_string(),
timestamp: date.and_hms_opt(10, 18, 3).unwrap(),
last_price: 10.0,
bid1: 9.99,
ask1: 10.01,
bid1_volume: 1,
ask1_volume: 1,
volume_delta: 1,
amount_delta: 0.0,
trading_phase: Some("continuous".to_string()),
}],
)
.expect("dataset");
let mut portfolio = PortfolioState::new(1_000_000.0);
@@ -1192,6 +1220,120 @@ fn broker_applies_price_ratio_slippage_on_snapshot_fills() {
#[test]
fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
let data = DataSet::from_components_with_actions_and_quotes(
vec![Instrument {
symbol: "000002.SZ".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: "000002.SZ".to_string(),
timestamp: Some("2024-01-10 10:18:00".to_string()),
day_open: 10.0,
open: 10.0,
high: 10.1,
low: 9.9,
close: 10.0,
last_price: 10.0,
bid1: 9.99,
ask1: 10.01,
prev_close: 10.0,
volume: 100_000,
tick_volume: 100_000,
bid1_volume: 80_000,
ask1_volume: 80_000,
trading_phase: Some("continuous".to_string()),
paused: false,
upper_limit: 11.0,
lower_limit: 9.0,
price_tick: 0.01,
}],
vec![DailyFactorSnapshot {
date,
symbol: "000002.SZ".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: "000002.SZ".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: "000002.SZ".to_string(),
timestamp: date.and_hms_opt(10, 18, 3).unwrap(),
last_price: 10.0,
bid1: 9.99,
ask1: 10.01,
bid1_volume: 1,
ask1_volume: 1,
volume_delta: 1,
amount_delta: 0.0,
trading_phase: Some("continuous".to_string()),
}],
)
.expect("dataset");
let mut portfolio = PortfolioState::new(1_000_000.0);
let broker = BrokerSimulator::new_with_execution_price(
ChinaAShareCostModel::default(),
ChinaEquityRuleHooks::default(),
PriceField::Last,
)
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(10, 18, 0).unwrap())
.with_slippage_model(SlippageModel::TickSize(2.0));
let report = broker
.execute(
date,
&mut portfolio,
&data,
&StrategyDecision {
rebalance: false,
target_weights: BTreeMap::new(),
exit_symbols: BTreeSet::new(),
order_intents: vec![OrderIntent::Value {
symbol: "000002.SZ".to_string(),
value: 100_000.0,
reason: "tick_slippage".to_string(),
}],
notes: Vec::new(),
diagnostics: Vec::new(),
},
)
.expect("broker execution");
assert_eq!(report.fill_events.len(), 1);
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
}
#[test]
fn broker_rejects_intraday_last_order_without_execution_quotes() {
let date = NaiveDate::from_ymd_opt(2024, 1, 10).unwrap();
let data = DataSet::from_components(
vec![Instrument {
@@ -1263,8 +1405,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
ChinaEquityRuleHooks::default(),
PriceField::Last,
)
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(10, 18, 0).unwrap())
.with_slippage_model(SlippageModel::TickSize(2.0));
.with_intraday_execution_start_time(chrono::NaiveTime::from_hms_opt(10, 18, 0).unwrap());
let report = broker
.execute(
@@ -1278,7 +1419,7 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
order_intents: vec![OrderIntent::Value {
symbol: "000002.SZ".to_string(),
value: 100_000.0,
reason: "tick_slippage".to_string(),
reason: "missing_tick_quotes".to_string(),
}],
notes: Vec::new(),
diagnostics: Vec::new(),
@@ -1286,8 +1427,15 @@ fn broker_applies_tick_size_slippage_on_intraday_last_fills() {
)
.expect("broker execution");
assert_eq!(report.fill_events.len(), 1);
assert!((report.fill_events[0].price - 10.02).abs() < 1e-9);
assert!(report.fill_events.is_empty());
assert_eq!(report.order_events.len(), 1);
assert_eq!(report.order_events[0].status, OrderStatus::Canceled);
assert!(
report.order_events[0]
.reason
.contains("no execution quotes after start")
);
assert!(portfolio.position("000002.SZ").is_none());
}
#[test]