use super::documents::{declare_document, DocTree, TagRule, Vocabulary};
use super::element::{attributes, elements, fn_name, rust_name};
use super::{Declared, Family};
pub use super::{fragment, json, El, Json, Value};
elements! {
market: children;
note: leaf;
quote: leaf;
trade: leaf;
book: children;
bid: leaf;
ask: leaf;
news: leaf;
position: leaf;
fill: leaf;
order: leaf;
order_update = "order-update": leaf;
cancel: leaf;
cancel_update = "cancel-update": leaf;
amend: leaf;
amend_update = "amend-update": leaf;
account: children;
holding: leaf;
open_order = "open-order": leaf;
problem: leaf;
}
attributes! {
pub trait MarketAttrs {
t; text; sym; last; bid; ask; vol; price; qty; side; headline; source; tone; avg;
by; order; mode; ref_; at; id; type_; tif; venue; grant; limit; stop; take_profit; stop_loss; effect; instrument; account; connection;
state; filled; error; src; cancel; amend; leg;
currency; status; value; buying_power; cash; equity; day_change; day_change_pct;
pl; pl_pct; client; submitted; avg_price;
}
}
pub(crate) const FAMILY: Family = Family { module: "market", roots: &["market"], declare };
pub const HOLDING_FIELDS: &[&str] = &["sym", "qty", "side", "avg", "price", "value", "pl", "plPct"];
pub const OPEN_ORDER_FIELDS: &[&str] =
&["sym", "status", "ref", "client", "order", "side", "type", "tif", "state", "submitted", "qty", "filled", "avgPrice", "limit"];
const R: &[&str] = &["market"];
const MARKET: Vocabulary = Vocabulary {
format: "market",
noun: "a market recording",
root: "market",
tags: &[
TagRule::new("market", &[]).attrs(&[]),
TagRule::new("note", R).required(&["t", "text"]).attrs(&["t", "text"]),
TagRule::new("quote", R).required(&["t", "sym"]).attrs(&["t", "sym", "last", "bid", "ask", "vol"]),
TagRule::new("trade", R).required(&["t", "sym", "price", "qty"]).attrs(&["t", "sym", "price", "qty", "side"]),
TagRule::new("book", R).required(&["t", "sym"]).attrs(&["t", "sym"]),
TagRule::new("bid", &["book"]).required(&["price", "qty"]).attrs(&["price", "qty"]),
TagRule::new("ask", &["book"]).required(&["price", "qty"]).attrs(&["price", "qty"]),
TagRule::new("news", R).required(&["t", "headline"]).attrs(&["t", "headline", "sym", "source", "tone"]),
TagRule::new("position", R).required(&["t", "sym", "qty", "avg"]).attrs(&["t", "sym", "qty", "avg"]),
TagRule::new("fill", R)
.required(&["t", "sym", "side", "price", "qty"])
.attrs(&["t", "sym", "side", "price", "qty", "by", "order", "leg", "mode", "ref", "at"]),
TagRule::new("order", R)
.required(&["t", "id", "sym", "side", "qty", "type", "tif", "venue", "mode", "by", "grant"])
.attrs(&["t", "id", "sym", "side", "qty", "type", "tif", "venue", "mode", "by", "grant", "limit", "stop", "takeProfit", "stopLoss", "effect", "instrument", "account", "connection"]),
TagRule::new("order-update", R)
.required(&["t", "order", "state", "mode"])
.attrs(&["t", "order", "state", "mode", "leg", "ref", "filled", "avg", "error", "src"]),
TagRule::new("cancel", R)
.required(&["t", "id", "venue", "mode", "ref", "by", "grant"])
.attrs(&["t", "id", "venue", "mode", "ref", "by", "grant", "order", "leg", "connection", "account"]),
TagRule::new("cancel-update", R).required(&["t", "cancel", "state", "mode"]).attrs(&["t", "cancel", "state", "mode", "error"]),
TagRule::new("amend", R)
.required(&["t", "id", "order", "sym", "side", "qty", "type", "tif", "venue", "mode", "ref", "by", "grant"])
.attrs(&["t", "id", "order", "sym", "side", "qty", "type", "tif", "venue", "mode", "ref", "by", "grant", "limit", "stop", "effect", "connection", "account"]),
TagRule::new("amend-update", R).required(&["t", "amend", "state", "mode"]).attrs(&["t", "amend", "state", "mode", "ref", "error"]),
TagRule::new("account", R).required(&["t", "venue", "mode"]).attrs(&[
"t", "venue", "mode", "connection", "currency", "status", "value", "buyingPower", "cash", "equity", "dayChange", "dayChangePct",
]),
TagRule::new("holding", &["account"]).required(&["sym", "qty"]).attrs(HOLDING_FIELDS),
TagRule::new("open-order", &["account"]).required(&["sym", "status"]).attrs(OPEN_ORDER_FIELDS),
TagRule::new("problem", &["account"]).required(&["text"]).attrs(&["text"]),
],
from_tree: market_of,
};
const DECIMALS: &[(&str, &[&str])] = &[
("quote", &["last", "bid", "ask", "vol"]),
("trade", &["price", "qty"]),
("bid", &["price", "qty"]),
("ask", &["price", "qty"]),
("position", &["qty", "avg"]),
("fill", &["price", "qty"]),
("order", &["qty", "limit", "stop", "takeProfit", "stopLoss"]),
("order-update", &["filled", "avg"]),
("amend", &["qty", "limit", "stop"]),
("account", &["value", "buyingPower", "cash", "equity", "dayChange", "dayChangePct"]),
("holding", &["qty", "avg", "price", "value", "pl", "plPct"]),
("open-order", &["qty", "filled", "avgPrice", "limit"]),
];
pub fn empty() -> Json {
Json::obj().with("records", Vec::<Json>::new())
}
fn declare(root: El) -> Result<Declared, String> {
declare_document(&root, &MARKET)
}
fn is_decimal(s: &str) -> bool {
let s = s.strip_prefix('-').unwrap_or(s);
let (whole, frac) = match s.split_once('.') {
Some((w, f)) => (w, Some(f)),
None => (s, None),
};
let digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
digits(whole) && frac.is_none_or(digits)
}
fn is_iso_time(s: &str) -> bool {
fn digits(b: &[u8], n: usize) -> bool {
b.len() >= n && b[..n].iter().all(u8::is_ascii_digit)
}
let b = s.as_bytes();
if b.len() < 17 {
return false;
}
let head = digits(b, 4) && b.get(4) == Some(&b'-') && digits(&b[5..], 2) && b.get(7) == Some(&b'-') && digits(&b[8..], 2);
if !(head && b.get(10) == Some(&b'T') && digits(&b[11..], 2) && b.get(13) == Some(&b':') && digits(&b[14..], 2)) {
return false;
}
let mut rest = &b[16..];
if rest.first() == Some(&b':') {
if !digits(&rest[1..], 2) {
return false;
}
rest = &rest[3..];
if rest.first() == Some(&b'.') {
let n = rest[1..].iter().take_while(|c| c.is_ascii_digit()).count();
if n == 0 {
return false;
}
rest = &rest[1 + n..];
}
}
rest == b"Z" || (rest.len() == 6 && matches!(rest[0], b'+' | b'-') && digits(&rest[1..], 2) && rest[3] == b':' && digits(&rest[4..], 2))
}
pub const STANDARD_MULTIPLIER: &str = "100";
const OPTION_FORM: &str = r#"<underlying> <expiry YYYY-MM-DD> <C|P> <strike>[ x<multiplier>], for example "AAPL 2026-12-18 C 200""#;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OptionContract {
pub underlying: String,
pub expiry: String,
pub right: String,
pub strike: String,
pub multiplier: String,
}
fn canonical(s: &str) -> Option<String> {
let s = s.trim();
let (whole, frac) = s.split_once('.').map_or((s, None), |(w, f)| (w, Some(f)));
let digits = |p: &str| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit());
if !digits(whole) || !frac.is_none_or(digits) {
return None;
}
let whole = whole.trim_start_matches('0');
let whole = if whole.is_empty() { "0" } else { whole };
let frac = frac.unwrap_or("").trim_end_matches('0');
Some(if frac.is_empty() { whole.to_string() } else { format!("{whole}.{frac}") })
}
fn is_date(s: &str) -> bool {
let b = s.as_bytes();
if b.len() != 10 || b[4] != b'-' || b[7] != b'-' || !b.iter().enumerate().all(|(i, c)| i == 4 || i == 7 || c.is_ascii_digit()) {
return false;
}
let (y, m, d): (u32, u32, u32) = (s[..4].parse().unwrap_or(0), s[5..7].parse().unwrap_or(0), s[8..].parse().unwrap_or(0));
let leap = (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;
let days = match m {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 if leap => 29,
2 => 28,
_ => 0,
};
(1..=days).contains(&d)
}
pub fn parse_option(sym: &str) -> Result<Option<OptionContract>, String> {
if !sym.contains(' ') {
return Ok(None);
}
let parts: Vec<&str> = sym.split(' ').collect();
if !(4..=5).contains(&parts.len()) || parts.iter().any(|p| p.is_empty()) {
return Err(format!("an option contract is {OPTION_FORM}, not {sym:?}"));
}
let (underlying, expiry, right, strike) = (parts[0], parts[1], parts[2], parts[3]);
if underlying.len() > 24 || !underlying.bytes().all(|b| b.is_ascii_alphanumeric() || b"._/-".contains(&b)) {
return Err(format!("an option's underlying is letters, digits and . _ / - (at most 24), not {underlying:?}"));
}
if !is_date(expiry) {
return Err(format!("an option's expiry is a date, YYYY-MM-DD, not {expiry:?}"));
}
if right != "C" && right != "P" {
return Err(format!("an option's right is C (a call) or P (a put), not {right:?}"));
}
let k = match canonical(strike) {
Some(k) if k.bytes().any(|b| (b'1'..=b'9').contains(&b)) => k,
_ => return Err(format!("an option's strike is decimal text above 0, not {strike:?}")),
};
if k != strike {
return Err(format!("an option's strike is written {k}, not {strike} (one spelling for each contract)"));
}
let mut multiplier = STANDARD_MULTIPLIER.to_string();
if let Some(mult) = parts.get(4) {
let n = mult.strip_prefix('x').filter(|n| !n.is_empty() && !n.starts_with('0') && n.bytes().all(|b| b.is_ascii_digit()));
let Some(n) = n else {
return Err(format!(r#"an option's multiplier is x and a whole number above 0 ("x10"), not {mult:?}"#));
};
if n == STANDARD_MULTIPLIER {
return Err(format!("a multiplier of {STANDARD_MULTIPLIER} is not written: {} is that contract", parts[..4].join(" ")));
}
multiplier = n.to_string();
}
Ok(Some(OptionContract { underlying: underlying.into(), expiry: expiry.into(), right: right.into(), strike: strike.into(), multiplier }))
}
pub fn option_symbol(underlying: &str, expiry: &str, right: &str, strike: &str, multiplier: Option<&str>) -> Result<String, String> {
let r = match right.to_ascii_lowercase().as_str() {
"c" | "call" => "C",
"p" | "put" => "P",
_ => right,
};
let k = canonical(strike).unwrap_or_else(|| strike.to_string());
let m = multiplier.map_or(STANDARD_MULTIPLIER.to_string(), |m| canonical(m).unwrap_or_else(|| m.to_string()));
let sym = if m == STANDARD_MULTIPLIER { format!("{underlying} {expiry} {r} {k}") } else { format!("{underlying} {expiry} {r} {k} x{m}") };
parse_option(&sym)?;
Ok(sym)
}
fn check(t: &DocTree) -> Result<(), String> {
let at = format!("{}()", fn_name(t.tag));
let decimals = DECIMALS.iter().find(|(tag, _)| *tag == t.tag).map_or(&[][..], |(_, d)| *d);
for (k, v) in &t.attrs {
let name = rust_name(k);
let decimal = decimals.contains(&k.as_str());
let s = match v {
Json::Str(s) => s,
Json::Num(_) if decimal => return Err(format!(r#"{at}: {name} is decimal text ("185.09"), not a number"#)),
Json::Num(_) => return Err(format!("{at}: {name} is text, not a number")),
other => return Err(format!("{at}: {name} is text, not {}", other.text())),
};
if decimal && !is_decimal(s) {
return Err(format!(r#"{at}: {name} is decimal text ("185.09"), not {s:?}"#));
}
if k == "t" && !is_iso_time(s) {
return Err(format!(r#"{at}: t is an ISO time ("2026-10-01T13:30:00.000Z"), not {s:?}"#));
}
if k == "sym" {
parse_option(s).map_err(|e| format!("{at}: sym: {e}"))?;
}
}
t.children.iter().try_for_each(check)
}
fn record_of(t: &DocTree) -> Json {
let mut out = Json::obj().with("kind", t.tag);
for (k, v) in &t.attrs {
out.set(k, v.clone());
}
match t.tag {
"book" => {
let levels = |side: &str| -> Vec<Json> {
t.children
.iter()
.filter(|c| c.tag == side)
.map(|c| Json::from(vec![c.attr_of("price").cloned().unwrap_or(Json::Null), c.attr_of("qty").cloned().unwrap_or(Json::Null)]))
.collect()
};
out.set("bids", levels("bid"));
out.set("asks", levels("ask"));
}
"account" => {
for (tag, key) in [("holding", "positions"), ("open-order", "open"), ("problem", "problems")] {
let items: Vec<Json> = t
.children
.iter()
.filter(|c| c.tag == tag)
.map(|c| if tag == "problem" { c.attr_of("text").cloned().unwrap_or(Json::Null) } else { c.record() })
.collect();
if !items.is_empty() {
out.set(key, items);
}
}
}
_ => {}
}
out
}
fn market_of(t: &DocTree) -> Result<Json, String> {
t.children.iter().try_for_each(check)?;
Ok(Json::obj().with("records", t.children.iter().map(record_of).collect::<Vec<_>>()))
}