rustyschwab-types 0.2.0

Unofficial wire types for the Charles Schwab Trader and Market Data APIs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
//! Common types shared across multiple API modules.
//!
//! This module contains shared enumerations and structures used throughout
//! the Schwab API, including:
//!
//! - Asset types: [`AssetType`](crate::common::AssetType) on the Trader API
//!   (positions, order legs, transactions) and
//!   [`AssetMainType`](crate::common::AssetMainType) on Market Data
//! - [`AccountsInstrument`](crate::common::AccountsInstrument), the
//!   instrument shape positions and order legs share
//! - [`schwab_timestamp`](crate::common::schwab_timestamp), the one
//!   timestamp spelling the Trader API's time-window query parameters accept
//! - Response headers
//! - Pagination info

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_with::skip_serializing_none;
use std::collections::HashMap;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ResponseHeaders {
    #[serde(rename = "Schwab-Client-CorrelId")]
    pub schwab_client_correlid: Option<String>,
    #[serde(rename = "Schwab-Resource-Version")]
    pub schwab_resource_version: Option<String>,
}

/// Instrument class as the Trader API spells `assetType` on positions,
/// order legs, and transaction items.
///
/// This is the spec's complete `assetType` enumeration; the per-instrument
/// base schemas list only the first eight, and the remaining three appear
/// in transaction instruments. See [`Wire`] for `Unknown`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum AssetType {
    #[default]
    Equity,
    Option,
    Index,
    MutualFund,
    CashEquivalent,
    FixedIncome,
    Currency,
    CollectiveInvestment,
    Future,
    Forex,
    Product,
    #[serde(other)]
    #[cfg_attr(feature = "schemars", schemars(skip))]
    Unknown,
}

/// An enum that appears on both requests and broker responses.
///
/// Responses decode a value this release does not know as `Unknown`, so one
/// new spelling from Schwab cannot fail a whole order list or account. A
/// request can never carry `Unknown`: the variant is absent from the JSON
/// schemas, and [`OrderRequest::validate`](crate::trading::OrderRequest::validate)
/// and the other request validators reject it.
pub trait Wire {
    /// Whether this is the `Unknown` catch-all rather than a value Schwab
    /// documents.
    fn is_unknown(&self) -> bool;
}

/// Implements [`Wire`] for enums whose catch-all variant is `Unknown`.
macro_rules! wire_enum {
    ($($ty:ty),+ $(,)?) => {$(
        impl $crate::common::Wire for $ty {
            fn is_unknown(&self) -> bool {
                matches!(self, Self::Unknown)
            }
        }
    )+};
}
pub(crate) use wire_enum;

wire_enum!(AssetType);

/// Reject `Unknown` in a request field, naming the field.
pub(crate) fn known<T: Wire>(
    field: &str,
    value: Option<&T>,
) -> Result<(), crate::validation::ValidationError> {
    match value {
        Some(v) if v.is_unknown() => Err(crate::validation::ValidationError::new(
            crate::validation::ValidationErrorKind::Unsupported,
            Some(field),
            format!("{field} is not a value Schwab accepts"),
        )),
        _ => Ok(()),
    }
}

/// Instrument class as Market Data spells `assetMainType` on quotes and
/// stream envelopes and `assetType` on instruments. A different value set
/// from the Trader API's [`AssetType`].
///
/// `Unknown` is both Schwab's own `UNKNOWN` and any value added after this
/// release, so decoding never fails on it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum AssetMainType {
    Bond,
    Equity,
    Etf,
    Extended,
    Forex,
    Future,
    FutureOption,
    Fundamental,
    Index,
    Indicator,
    MutualFund,
    Option,
    #[serde(other)]
    Unknown,
}

/// The instrument on a position or an order leg (`AccountsInstrument` in
/// the Trader API spec).
///
/// The fields Schwab documents for every asset type are typed, plus the
/// option and fixed-income extensions; anything else lands in `extra`.
#[skip_serializing_none]
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
// A position or leg Schwab sends without a field must not fail the list.
#[serde(rename_all = "camelCase", default)]
#[non_exhaustive]
pub struct AccountsInstrument {
    pub asset_type: AssetType,
    pub symbol: String,
    pub cusip: Option<String>,
    pub description: Option<String>,
    pub instrument_id: Option<i64>,
    pub net_change: Option<f64>,
    /// Subtype whose value set depends on `asset_type` (`SWEEP_VEHICLE`
    /// for cash equivalents, `VANILLA` for options, …).
    #[serde(rename = "type")]
    pub type_: Option<String>,
    /// Options only. `None` when Schwab reports `UNKNOWN`.
    #[serde(default, deserialize_with = "lenient")]
    pub put_call: Option<PutCall>,
    /// Options only.
    pub underlying_symbol: Option<String>,
    /// Options only.
    pub option_multiplier: Option<i64>,
    /// Fixed income only.
    pub maturity_date: Option<String>,
    /// Fixed income only.
    pub factor: Option<f64>,
    /// Fixed income only.
    pub variable_rate: Option<f64>,
    #[serde(flatten)]
    pub extra: HashMap<String, serde_json::Value>,
}

/// Instrument subclass as Market Data spells `assetSubType` beside
/// [`AssetMainType`]: the equity subtypes (`COE` common stock, `PRF`
/// preferred, `ADR`/`GDR` depositary receipts, `CEF`, `ETF`, `ETN`, `UIT`,
/// `WAR` warrant, `RGT` right) and the mutual-fund ones (`OEF`, `CEF`,
/// `MMF`). Values outside the list decode as `Unknown`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
#[non_exhaustive]
pub enum AssetSubType {
    Adr,
    Cef,
    Coe,
    Etf,
    Etn,
    Gdr,
    Mmf,
    Oef,
    Prf,
    Rgt,
    Uit,
    War,
    #[serde(other)]
    Unknown,
}

/// Option contract right, as Schwab spells it in `putCall` fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PutCall {
    Put,
    Call,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PageInfo {
    pub page_size: i32,
    pub page_number: i32,
    pub total_pages: i32,
    pub total_items: i32,
}

/// Rewrite every float in `value` that holds an exact integer (`100.0`) as
/// that integer, so it decodes into an integer field; other numbers are
/// untouched (an integer still decodes into a float field). Only values
/// within ±2^53, where a float is exact, are rewritten.
pub fn normalize_integral_numbers(value: &mut serde_json::Value) {
    use serde_json::Value;
    const EXACT: f64 = 9_007_199_254_740_992.0;
    match value {
        Value::Number(number) if number.is_f64() => {
            if let Some(float) = number.as_f64()
                && float.fract() == 0.0
                && float.abs() <= EXACT
            {
                *value = Value::from(float as i64);
            }
        }
        Value::Array(items) => items.iter_mut().for_each(normalize_integral_numbers),
        Value::Object(fields) => fields.values_mut().for_each(normalize_integral_numbers),
        _ => {}
    }
}

/// Broker identifiers may be JSON integers or strings. Normalize losslessly.
pub fn optional_id<'de, D: serde::Deserializer<'de>>(de: D) -> Result<Option<String>, D::Error> {
    let value = Option::<serde_json::Value>::deserialize(de)?;
    match value {
        None => Ok(None),
        Some(serde_json::Value::String(s)) => Ok(Some(s)),
        Some(serde_json::Value::Number(n)) if n.is_u64() || n.is_i64() => Ok(Some(n.to_string())),
        _ => Err(serde::de::Error::custom(
            "Expected an integer or string identifier",
        )),
    }
}

/// Decode an optional enum on a broker response, reading values outside
/// the enum (Schwab's `UNKNOWN`, or a value added after this release) as
/// `None` instead of failing the whole payload. Pair with
/// `#[serde(default)]` so a missing field is `None` too.
pub fn lenient<'de, D, T>(de: D) -> Result<Option<T>, D::Error>
where
    D: serde::Deserializer<'de>,
    T: DeserializeOwned,
{
    let value = Option::<serde_json::Value>::deserialize(de)?;
    Ok(value.and_then(|v| serde_json::from_value(v).ok()))
}

/// Deserialize a request decimal exactly.
///
/// Accepts a plain decimal string (`"150.25"`) or a JSON integer. A JSON
/// fraction is accepted as its shortest round-trip spelling, but it may
/// already have lost precision in the parser, so callers should send
/// strings. Rejected rather than reinterpreted: digit separators (`"1_000"`,
/// which `rust_decimal` would read as 1000), surrounding whitespace, exponent
/// notation, and more digits than a `Decimal` holds (which it would round).
pub mod exact_decimal {
    use rust_decimal::Decimal;
    use serde::de::{self, Deserializer, Visitor};
    use std::fmt;

    pub fn parse(s: &str) -> Result<Decimal, String> {
        let plain = !s.is_empty()
            && s.bytes()
                .all(|b| b.is_ascii_digit() || b == b'.' || b == b'-' || b == b'+');
        if !plain {
            return Err(format!("{s:?} is not a plain decimal number"));
        }
        Decimal::from_str_exact(s).map_err(|e| format!("{s:?} is not an exact decimal: {e}"))
    }

    struct Exact;

    impl Visitor<'_> for Exact {
        type Value = Decimal;

        fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("a decimal number as a string, such as \"150.25\"")
        }

        fn visit_str<E: de::Error>(self, s: &str) -> Result<Decimal, E> {
            parse(s).map_err(E::custom)
        }

        fn visit_i64<E: de::Error>(self, n: i64) -> Result<Decimal, E> {
            Ok(Decimal::from(n))
        }

        fn visit_u64<E: de::Error>(self, n: u64) -> Result<Decimal, E> {
            Ok(Decimal::from(n))
        }

        fn visit_f64<E: de::Error>(self, n: f64) -> Result<Decimal, E> {
            if !n.is_finite() {
                return Err(E::custom("decimal must be finite"));
            }
            // `{}` on f64 is the shortest round-trip spelling, never exponent form.
            parse(&n.to_string()).map_err(E::custom)
        }
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Decimal, D::Error> {
        de.deserialize_any(Exact)
    }

    /// Serialize as a JSON number, the form Schwab's order examples always
    /// use for `quantity` (prices appear as strings as well, so they stay
    /// strings). Whole values go out as integers; a value the shortest
    /// float spelling would not carry exactly is refused.
    pub fn serialize_number<S: serde::Serializer>(
        value: &Decimal,
        s: S,
    ) -> Result<S::Ok, S::Error> {
        use rust_decimal::prelude::ToPrimitive;
        use serde::ser::Error;
        if value.fract().is_zero()
            && let Some(n) = value.to_i64()
        {
            return s.serialize_i64(n);
        }
        match value.to_f64() {
            Some(n) if parse(&n.to_string()).is_ok_and(|back| back == *value) => s.serialize_f64(n),
            _ => Err(S::Error::custom(format!(
                "{value} has more precision than a JSON number carries"
            ))),
        }
    }

    /// Serialize as an exact decimal string (`"150.25"`), the form the SDK
    /// sends prices in. Explicit, so a dependency enabling rust_decimal's
    /// `serde-float` feature cannot turn prices into floats (and change
    /// every intent digest over them).
    pub fn serialize_string<S: serde::Serializer>(
        value: &Decimal,
        s: S,
    ) -> Result<S::Ok, S::Error> {
        s.collect_str(value)
    }

    /// The same rules for an optional field; pair with `#[serde(default)]`.
    pub mod option {
        use rust_decimal::Decimal;
        use serde::{Deserialize, Deserializer, Serializer};

        pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Option<Decimal>, D::Error> {
            #[derive(Deserialize)]
            struct Wrap(#[serde(deserialize_with = "super::deserialize")] Decimal);
            Ok(Option::<Wrap>::deserialize(de)?.map(|Wrap(d)| d))
        }

        pub fn serialize_number<S: Serializer>(
            value: &Option<Decimal>,
            s: S,
        ) -> Result<S::Ok, S::Error> {
            match value {
                Some(value) => super::serialize_number(value, s),
                None => s.serialize_none(),
            }
        }

        pub fn serialize_string<S: Serializer>(
            value: &Option<Decimal>,
            s: S,
        ) -> Result<S::Ok, S::Error> {
            match value {
                Some(value) => super::serialize_string(value, s),
                None => s.serialize_none(),
            }
        }
    }
}

/// JSON schema for a request decimal: a string of digits with an optional
/// fraction, the only spelling [`exact_decimal`] guarantees is exact.
#[cfg(feature = "schemars")]
#[derive(Debug)]
pub struct DecimalString;

#[cfg(feature = "schemars")]
impl schemars::JsonSchema for DecimalString {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "DecimalString".into()
    }

    fn inline_schema() -> bool {
        true
    }

    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": "string",
            "pattern": "^[0-9]+(\\.[0-9]+)?$",
            "description": "Exact decimal as a string, e.g. \"150.25\"; never a JSON number."
        })
    }
}

/// JSON schema for an order quantity: Schwab's wire form is a JSON number
/// ([`exact_decimal::serialize_number`]), and a decimal string reads the same.
#[cfg(feature = "schemars")]
#[derive(Debug)]
pub struct QuantityNumber;

#[cfg(feature = "schemars")]
impl schemars::JsonSchema for QuantityNumber {
    fn schema_name() -> std::borrow::Cow<'static, str> {
        "QuantityNumber".into()
    }

    fn inline_schema() -> bool {
        true
    }

    fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
        schemars::json_schema!({
            "type": ["number", "string"],
            "pattern": "^[0-9]+(\\.[0-9]+)?$",
            "description": "Shares, contracts or fund units: a JSON number such as 10, \
                            or a decimal string such as \"10\"."
        })
    }
}

/// Format a timestamp for the Trader API's time-window query parameters
/// (`fromEnteredTime`, `toEnteredTime`, `startDate`, `endDate`).
///
/// Schwab documents exactly one shape, `yyyy-MM-dd'T'HH:mm:ss.SSSZ`: UTC,
/// a literal `Z`, and exactly three fractional digits. RFC 3339 spellings
/// that omit the fraction or carry more digits are not the documented form,
/// so the crate never emits them.
///
/// ```
/// use chrono::{TimeZone, Utc};
/// use rustyschwab_types::common::schwab_timestamp;
///
/// let at = Utc.with_ymd_and_hms(2025, 1, 15, 9, 30, 0).unwrap();
/// assert_eq!(schwab_timestamp(at), "2025-01-15T09:30:00.000Z");
/// ```
pub fn schwab_timestamp(at: DateTime<Utc>) -> String {
    at.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()
}

/// Parse a time as Schwab reports it on orders and transactions
/// (`2025-01-15T14:31:22+0000`, with or without a fraction), or as RFC 3339.
pub fn parse_schwab_time(text: &str) -> Result<DateTime<Utc>, chrono::ParseError> {
    DateTime::parse_from_str(text, "%Y-%m-%dT%H:%M:%S%z")
        .or_else(|_| DateTime::parse_from_str(text, "%Y-%m-%dT%H:%M:%S%.f%z"))
        .or_else(|_| DateTime::parse_from_rfc3339(text))
        .map(|at| at.with_timezone(&Utc))
}

/// `serialize_with` adapter for [`schwab_timestamp`].
pub(crate) fn serialize_timestamp<S: serde::Serializer>(
    at: &DateTime<Utc>,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    serializer.serialize_str(&schwab_timestamp(*at))
}

/// [`serialize_timestamp`] for an optional field.
pub(crate) fn serialize_optional_timestamp<S: serde::Serializer>(
    at: &Option<DateTime<Utc>>,
    serializer: S,
) -> Result<S::Ok, S::Error> {
    match at {
        Some(at) => serialize_timestamp(at, serializer),
        None => serializer.serialize_none(),
    }
}