use std::path::Path;
use color_eyre::{Result, eyre::WrapErr};
use rust_decimal::Decimal;
use serde::Deserialize;
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
#[serde(default)]
pub daemon_endpoint: String,
#[serde(default)]
pub endpoint: Option<String>,
#[serde(default)]
pub api_token_file: Option<String>,
#[serde(default)]
pub kill_switch_on_disconnect: Option<bool>,
#[serde(default)]
pub backend: Option<String>,
#[serde(default)]
pub listen_endpoint: Option<String>,
#[serde(default)]
pub risk: RiskConfig,
pub strategy: StrategyConfig,
}
#[derive(Debug, Clone, Copy, Default, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct RiskConfig {
#[serde(default)]
pub max_order_qty: Option<Decimal>,
#[serde(default)]
pub max_order_notional: Option<Decimal>,
#[serde(default)]
pub max_orders_per_minute: Option<u32>,
#[serde(default)]
pub max_open_orders: Option<u32>,
#[serde(default)]
pub max_net_qty_per_symbol: Option<Decimal>,
}
impl RiskConfig {
#[must_use]
pub const fn limits(&self) -> crate::risk::RiskLimits {
crate::risk::RiskLimits {
max_order_qty: self.max_order_qty,
max_order_notional: self.max_order_notional,
max_orders_per_minute: self.max_orders_per_minute,
max_open_orders: self.max_open_orders,
max_net_qty_per_symbol: self.max_net_qty_per_symbol,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct StrategyConfig {
#[serde(rename = "type")]
pub strategy_type: String,
#[serde(default)]
pub params: StrategyParams,
}
#[derive(Deserialize)]
struct StrategyParamsWire {
#[serde(default)]
exchange_id: Option<String>,
#[serde(default)]
label: Option<String>,
#[serde(default)]
symbol: Option<String>,
#[serde(default)]
lower_price: Option<Decimal>,
#[serde(default)]
upper_price: Option<Decimal>,
#[serde(default)]
num_levels: Option<u32>,
#[serde(default)]
qty_per_level: Option<Decimal>,
#[serde(flatten)]
extra: toml::Table,
}
impl<'de> Deserialize<'de> for StrategyParams {
fn deserialize<D: serde::Deserializer<'de>>(de: D) -> Result<Self, D::Error> {
let wire = StrategyParamsWire::deserialize(de)?;
let mut params = Self {
exchange_id: wire.exchange_id,
label: wire.label,
symbol: wire.symbol,
lower_price: wire.lower_price,
upper_price: wire.upper_price,
num_levels: wire.num_levels,
qty_per_level: wire.qty_per_level,
extra: wire.extra,
};
params.merge_known_keys();
Ok(params)
}
}
fn decimal_value(v: Decimal) -> toml::Value {
toml::Value::String(v.normalize().to_string())
}
#[derive(Debug, Clone, Default)]
pub struct StrategyParams {
pub exchange_id: Option<String>,
pub label: Option<String>,
pub symbol: Option<String>,
pub lower_price: Option<Decimal>,
pub upper_price: Option<Decimal>,
pub num_levels: Option<u32>,
pub qty_per_level: Option<Decimal>,
pub extra: toml::Table,
}
impl StrategyParams {
pub const fn table(&self) -> &toml::Table {
&self.extra
}
fn merge_known_keys(&mut self) {
let put = |table: &mut toml::Table, key: &str, value: toml::Value| {
table.entry(key).or_insert(value);
};
if let Some(v) = self.exchange_id.clone() {
put(&mut self.extra, "exchange_id", toml::Value::String(v));
}
if let Some(v) = self.label.clone() {
put(&mut self.extra, "label", toml::Value::String(v));
}
if let Some(v) = self.symbol.clone() {
put(&mut self.extra, "symbol", toml::Value::String(v));
}
if let Some(v) = self.lower_price {
put(&mut self.extra, "lower_price", decimal_value(v));
}
if let Some(v) = self.upper_price {
put(&mut self.extra, "upper_price", decimal_value(v));
}
if let Some(v) = self.num_levels {
put(&mut self.extra, "num_levels", toml::Value::Integer(i64::from(v)));
}
if let Some(v) = self.qty_per_level {
put(&mut self.extra, "qty_per_level", decimal_value(v));
}
}
pub fn venue(&self) -> &str {
self.exchange_id.as_deref().unwrap_or("mock")
}
pub fn venue_label(&self) -> &str {
self.label.as_deref().unwrap_or_default()
}
}
impl Config {
pub fn backend(&self) -> &str {
self.backend.as_deref().map(str::trim).filter(|b| !b.is_empty()).unwrap_or("api")
}
pub fn validated_backend(&self) -> Result<&str> {
match self.backend() {
backend @ ("api" | "mock") => Ok(backend),
other => {
Err(color_eyre::eyre::eyre!("unknown backend: {other} (expected 'mock' or 'api')"))
}
}
}
pub fn endpoint_or_default(&self, default: &str) -> String {
self.endpoint.clone().unwrap_or_else(|| default.to_string())
}
pub fn api_token(&self) -> Result<String> {
let Some(path) = self.api_token_file.as_deref() else {
return Ok(String::new());
};
let raw = std::fs::read_to_string(path)
.wrap_err_with(|| format!("failed to read api_token_file {path}"))?;
let token = raw.trim().to_string();
if token.is_empty() {
return Err(color_eyre::eyre::eyre!(
"api_token_file {path} is empty; refusing to start unauthenticated"
));
}
Ok(token)
}
pub fn load(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
let contents = std::fs::read_to_string(path)
.wrap_err_with(|| format!("failed to read config file: {}", path.display()))?;
let config: Self = toml::from_str(&contents)
.wrap_err_with(|| format!("failed to parse config file: {}", path.display()))?;
config
.validated_backend()
.wrap_err_with(|| format!("invalid config file: {}", path.display()))?;
if config.kill_switch_on_disconnect.is_some() {
tracing::warn!(
"config `kill_switch_on_disconnect` is deprecated and ignored; \
configure `worker.v1.KillSwitchPolicy` instead"
);
}
Ok(config)
}
}
#[cfg(test)]
mod tests {
use proptest::prelude::*;
use rust_decimal_macros::dec;
use super::*;
fn parse(params_toml: &str) -> StrategyParams {
let doc = format!(
"daemon_endpoint = \"http://127.0.0.1:8810\"\n[strategy]\ntype = \"simple_grid\"\n[strategy.params]\n{params_toml}\n"
);
let config: Config = toml::from_str(&doc).expect("config parses");
config.strategy.params
}
#[test]
fn well_known_keys_reach_the_strategy_table() {
let params = parse(
"symbol = \"BTCUSDT\"\nexchange_id = \"binance\"\nnum_levels = 7\nlower_price = \"90000\"\nqty_per_level = \"0.001\"\n",
);
let table = params.table();
assert_eq!(table.get("symbol").and_then(toml::Value::as_str), Some("BTCUSDT"));
assert_eq!(table.get("exchange_id").and_then(toml::Value::as_str), Some("binance"));
assert_eq!(table.get("num_levels").and_then(toml::Value::as_integer), Some(7));
assert_eq!(table.get("lower_price").and_then(toml::Value::as_str), Some("90000"));
assert_eq!(table.get("qty_per_level").and_then(toml::Value::as_str), Some("0.001"));
}
#[test]
fn strategy_specific_keys_survive_the_merge() {
let params = parse("symbol = \"BTCUSDT\"\nfunding_rate_threshold = \"0.0005\"\n");
assert_eq!(
params.table().get("funding_rate_threshold").and_then(toml::Value::as_str),
Some("0.0005")
);
}
#[test]
fn a_strategy_config_deserializes_from_the_merged_table() {
#[derive(serde::Deserialize)]
struct GridConfig {
symbol: String,
num_levels: u32,
qty_per_level: Decimal,
}
let params = parse(
"symbol = \"BTCUSDT\"\nexchange_id = \"mock\"\nnum_levels = 5\nqty_per_level = \"0.001\"\n",
);
let cfg: GridConfig = toml::Value::Table(params.table().clone())
.try_into()
.expect("the documented config must deserialize");
assert_eq!(cfg.symbol, "BTCUSDT");
assert_eq!(cfg.num_levels, 5);
assert_eq!(cfg.qty_per_level, dec!(0.001));
}
#[test]
fn absent_well_known_keys_stay_absent() {
let params = parse("symbol = \"BTCUSDT\"\n");
assert!(!params.table().contains_key("num_levels"));
assert!(!params.table().contains_key("lower_price"));
assert!(!params.table().contains_key("label"));
}
#[test]
fn venue_accessor_defaults_to_mock() {
assert_eq!(parse("symbol = \"X\"\n").venue(), "mock");
assert_eq!(parse("symbol = \"X\"\nexchange_id = \"htx\"\n").venue(), "htx");
}
fn full_config(doc: &str) -> Config {
let body = format!(
"daemon_endpoint = \"http://127.0.0.1:8810\"\n{doc}\n[strategy]\ntype = \"simple_grid\"\n"
);
toml::from_str(&body).expect("config parses")
}
#[test]
fn an_explicit_backend_is_used_verbatim() {
assert_eq!(full_config("backend = \"api\"\n").backend(), "api");
assert_eq!(full_config("backend = \"mock\"\n").backend(), "mock");
assert!(full_config("backend = \"api\"\n").validated_backend().is_ok());
assert!(full_config("backend = \"mock\"\n").validated_backend().is_ok());
}
#[test]
fn an_unknown_backend_is_rejected_by_validation() {
for backend in ["custom", "daemon", "API", "Mock ", ""] {
let config = full_config(&format!("backend = \"{backend}\"\n"));
if backend.trim().is_empty() {
assert!(config.validated_backend().is_ok(), "blank falls back to api");
} else {
assert!(config.validated_backend().is_err(), "{backend} must be rejected");
}
}
}
#[test]
fn an_absent_or_blank_backend_falls_back_to_api() {
assert_eq!(full_config("").backend(), "api");
assert_eq!(full_config("backend = \"\"\n").backend(), "api");
assert_eq!(full_config("backend = \" \"\n").backend(), "api", "blank is trimmed");
assert_eq!(full_config("backend = \" mock \"\n").backend(), "mock", "and so is a name");
}
#[test]
fn an_endpoint_does_not_choose_the_backend() {
let config = full_config("endpoint = \"http://api:9000\"\n");
assert_eq!(config.backend(), "api", "an endpoint is not a backend selector");
assert_eq!(config.endpoint_or_default("fallback"), "http://api:9000");
}
#[test]
fn a_removed_api_endpoint_key_is_rejected_rather_than_ignored() {
let err = toml::from_str::<Config>(
"daemon_endpoint = \"http://x:1\"\napi_endpoint = \"http://internal:9000\"\n\
[strategy]\ntype = \"simple_grid\"\n",
)
.expect_err("a removed key must not be silently dropped");
let message = err.to_string();
assert!(
message.contains("api_endpoint"),
"the error must name the offending key so the operator knows what to fix: {message}"
);
}
#[test]
fn a_misspelled_endpoint_key_is_rejected() {
let typo = ["end", "pi", "ont"].join("");
let err = toml::from_str::<Config>(&format!(
"daemon_endpoint = \"http://x:1\"\n{typo} = \"http://typo:9000\"\n\
[strategy]\ntype = \"simple_grid\"\n"
))
.expect_err("an unknown key must be reported");
assert!(err.to_string().contains(&typo), "{err}");
}
#[test]
fn an_absent_endpoint_falls_back_to_the_default() {
assert_eq!(full_config("").endpoint_or_default("http://fallback"), "http://fallback");
}
#[test]
fn an_unset_token_file_yields_an_empty_token() {
assert!(full_config("").api_token().expect("unset is not an error").is_empty());
}
#[test]
fn a_token_file_is_trimmed() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("token");
std::fs::write(&path, " secret-token\n").expect("write");
let config = full_config(&format!("api_token_file = {:?}\n", path.display().to_string()));
assert_eq!(config.api_token().expect("readable token"), "secret-token");
}
#[test]
fn an_unreadable_token_file_is_an_error() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("absent");
let config = full_config(&format!("api_token_file = {:?}\n", path.display().to_string()));
let err = config.api_token().expect_err("an unreadable token file must fail");
assert!(err.to_string().contains("api_token_file"), "got {err}");
}
#[test]
fn a_whitespace_only_token_file_is_an_error() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("token");
std::fs::write(&path, "\n\t \n").expect("write");
let config = full_config(&format!("api_token_file = {:?}\n", path.display().to_string()));
let err = config.api_token().expect_err("an empty token file must fail");
assert!(err.to_string().contains("empty"), "got {err}");
}
#[test]
fn load_reads_a_valid_config_off_disk() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("worker.toml");
std::fs::write(
&path,
"daemon_endpoint = \"http://127.0.0.1:8810\"\nkill_switch_on_disconnect = true\nlisten_endpoint = \"127.0.0.1:0\"\n[strategy]\ntype = \"ema_cross\"\n[strategy.params]\nsymbol = \"BTC/USDT\"\n",
)
.expect("write");
let config = Config::load(&path).expect("loads");
assert_eq!(config.daemon_endpoint, "http://127.0.0.1:8810");
assert_eq!(config.kill_switch_on_disconnect, Some(true));
assert_eq!(config.listen_endpoint.as_deref(), Some("127.0.0.1:0"));
assert_eq!(config.strategy.strategy_type, "ema_cross");
assert_eq!(config.strategy.params.symbol.as_deref(), Some("BTC/USDT"));
}
#[test]
fn load_reports_a_missing_file_with_its_path() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("nope.toml");
let err = Config::load(&path).expect_err("missing file");
let message = err.to_string();
assert!(message.contains("failed to read config file"), "{message}");
assert!(message.contains("nope.toml"), "{message}");
}
#[test]
fn load_reports_malformed_toml_with_its_path() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("bad.toml");
std::fs::write(&path, "this is not = = toml\n").expect("write");
let err = Config::load(&path).expect_err("malformed");
let message = err.to_string();
assert!(message.contains("failed to parse config file"), "{message}");
assert!(message.contains("bad.toml"), "{message}");
}
#[test]
fn load_rejects_a_config_missing_a_required_field() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("partial.toml");
std::fs::write(&path, "[strategy]\ntype = \"ema_cross\"\n").expect("write");
let config = Config::load(&path).expect("daemon_endpoint is optional legacy");
assert!(config.daemon_endpoint.is_empty());
assert_eq!(config.strategy.strategy_type, "ema_cross");
std::fs::write(&path, "daemon_endpoint = \"http://x\"\n").expect("write");
let err = Config::load(&path).expect_err("missing strategy");
let chain = format!("{err:?}");
assert!(chain.contains("strategy"), "{chain}");
}
#[test]
fn load_rejects_an_unknown_backend() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("bad-backend.toml");
std::fs::write(&path, "backend = \"custom\"\n[strategy]\ntype = \"simple_grid\"\n")
.expect("write");
let err = Config::load(&path).expect_err("unknown backend must fail load");
let chain = format!("{err:?}");
assert!(chain.contains("custom"), "{chain}");
}
fn config_with_risk(risk_toml: &str) -> Config {
let body = format!(
"daemon_endpoint = \"http://127.0.0.1:8810\"\n{risk_toml}\n\
[strategy]\ntype = \"simple_grid\"\n"
);
toml::from_str(&body).expect("config parses")
}
#[test]
fn an_absent_risk_section_leaves_the_gate_disabled() {
let config = full_config("");
assert!(!config.risk.limits().is_enabled());
assert!(!config.risk.limits().needs_book());
}
#[test]
fn a_documented_risk_section_parses_into_limits() {
let config = config_with_risk(
"[risk]\nmax_order_qty = \"1\"\nmax_order_notional = \"50000\"\n\
max_orders_per_minute = 120\nmax_open_orders = 200\n\
max_net_qty_per_symbol = \"5\"\n",
);
let limits = config.risk.limits();
assert!(limits.is_enabled());
assert!(limits.needs_book());
assert_eq!(limits.max_order_qty, Some(dec!(1)));
assert_eq!(limits.max_order_notional, Some(dec!(50000)));
assert_eq!(limits.max_orders_per_minute, Some(120));
assert_eq!(limits.max_open_orders, Some(200));
assert_eq!(limits.max_net_qty_per_symbol, Some(dec!(5)));
}
#[test]
fn unset_risk_limits_stay_unset() {
let config = config_with_risk("[risk]\nmax_order_qty = \"1\"\n");
let limits = config.risk.limits();
assert_eq!(limits.max_order_qty, Some(dec!(1)));
assert_eq!(limits.max_order_notional, None);
assert_eq!(limits.max_orders_per_minute, None);
assert_eq!(limits.max_open_orders, None);
assert_eq!(limits.max_net_qty_per_symbol, None);
assert!(limits.is_enabled());
assert!(!limits.needs_book());
}
#[test]
fn an_empty_risk_section_is_a_pass_through() {
let config = config_with_risk("[risk]\n");
assert!(!config.risk.limits().is_enabled());
}
#[test]
fn a_misspelled_risk_limit_is_rejected() {
let err = toml::from_str::<Config>(
"daemon_endpoint = \"http://x:1\"\n[risk]\nmax_order_size = \"1\"\n\
[strategy]\ntype = \"simple_grid\"\n",
)
.expect_err("an unknown risk key must be reported");
assert!(err.to_string().contains("max_order_size"), "{err}");
}
#[test]
fn decimals_are_merged_as_normalized_strings() {
let cases = [
(dec!(90000.00), "90000"),
(dec!(0.00100), "0.001"),
(dec!(1000), "1000"),
(dec!(-1.500), "-1.5"),
(Decimal::ZERO, "0"),
];
for (value, expected) in cases {
let params = parse(&format!("symbol = \"X\"\nlower_price = \"{value}\"\n"));
assert_eq!(
params.table().get("lower_price").and_then(toml::Value::as_str),
Some(expected),
"{value}"
);
}
}
#[test]
fn an_explicit_extra_key_wins_over_the_merged_well_known_key() {
let params = parse("symbol = \"FROM_WELL_KNOWN\"\n");
assert_eq!(
params.table().get("symbol").and_then(toml::Value::as_str),
Some("FROM_WELL_KNOWN")
);
let mut table = params.table().clone();
table.insert("symbol".into(), toml::Value::String(String::from("OVERRIDDEN")));
let merged: StrategyParams = toml::Value::Table(table).try_into().expect("re-parses");
assert_eq!(merged.table().get("symbol").and_then(toml::Value::as_str), Some("OVERRIDDEN"));
}
#[test]
fn venue_label_defaults_to_empty() {
assert_eq!(parse("symbol = \"X\"\n").venue_label(), "");
assert_eq!(parse("symbol = \"X\"\nlabel = \"sub\"\n").venue_label(), "sub");
}
#[test]
fn strategy_type_is_read_from_the_type_key() {
assert_eq!(full_config("").strategy.strategy_type, "simple_grid");
}
#[test]
fn absent_params_deserialize_to_an_empty_table() {
let config = full_config("");
assert!(config.strategy.params.table().is_empty());
assert!(config.strategy.params.symbol.is_none());
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn a_merged_decimal_always_round_trips_through_the_table(
mantissa in -1_000_000_000i64..1_000_000_000,
scale in 0u32..19,
) {
let Ok(value) = Decimal::try_from_i128_with_scale(i128::from(mantissa), scale) else {
return Ok(());
};
let params = parse(&format!("symbol = \"X\"\nqty_per_level = \"{value}\"\n"));
let rendered = params
.table()
.get("qty_per_level")
.and_then(toml::Value::as_str)
.expect("the key is merged as a string");
prop_assert_eq!(
rendered.parse::<Decimal>().expect("the rendering re-parses"),
value.normalize(), "{} rendered as {}", value, rendered );
}
#[test]
fn a_merged_level_count_is_always_an_integer(levels in 0u32..10_000) {
let params = parse(&format!("symbol = \"X\"\nnum_levels = {levels}\n"));
prop_assert_eq!(
params.table().get("num_levels").and_then(toml::Value::as_integer),
Some(i64::from(levels))
);
}
#[test]
fn an_endpoint_never_selects_a_backend(
backend in prop::sample::select(&["api", "mock", ""]),
) {
let config =
full_config(&format!("endpoint = \"http://api:9000\"\nbackend = \"{backend}\"\n"));
let expected = match backend {
"" => "api",
other => other.trim(),
};
prop_assert_eq!(config.backend(), if expected.is_empty() { "api" } else { expected });
prop_assert!(config.validated_backend().is_ok());
}
#[test]
fn only_a_blank_backend_falls_back(
backend in prop::sample::select(&["api", "", " ", "mock"]),
) {
let config = full_config(&format!("backend = \"{backend}\"\n"));
let trimmed = backend.trim();
prop_assert_eq!(config.backend(), if trimmed.is_empty() { "api" } else { trimmed });
prop_assert!(config.validated_backend().is_ok());
}
}
}