alpaca-facade 0.24.9

High-level convenience facades built on top of the alpaca-rust workspace crates
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
use std::collections::HashMap;
use std::path::PathBuf;

use alpaca_data::{Client, options::preferred_feed, stocks::SnapshotsRequest};
use alpaca_facade::{
    OptionChainRequest, fetch_chain, map_live_snapshots, map_snapshot, map_snapshots,
    resolve_positions_from_optionstrat_url,
};
use alpaca_option::url;
use rust_decimal::Decimal;

fn repo_root() -> PathBuf {
    let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    manifest_dir
        .parent()
        .unwrap()
        .parent()
        .unwrap()
        .to_path_buf()
}

fn load_local_env() {
    let dotenv_path = repo_root().join(".env");
    dotenvy::from_path_override(dotenv_path)
        .expect("alpaca-rust/.env should load for live adapter tests");
}

fn assert_ny_timestamp(value: &str) {
    assert!(
        value.len() == 19,
        "timestamp should be normalized to YYYY-MM-DD HH:MM:SS, got {value}"
    );
    assert!(
        !value.contains('T'),
        "timestamp should not contain T, got {value}"
    );
    assert!(
        !value.ends_with('Z'),
        "timestamp should not end with Z, got {value}"
    );
}

fn assert_underlying_price_close(actual: Option<f64>, expected: Option<f64>) {
    let actual = actual.expect("mapped snapshot should carry underlying price");
    let expected = expected.expect("live stock price should exist");
    assert!(
        actual.is_finite() && actual > 0.0,
        "underlying price should be a positive finite number, got {actual}"
    );
    assert!(
        (actual - expected).abs() <= 1.0,
        "underlying price drift too large: actual={actual}, expected={expected}"
    );
}

async fn discover_live_snapshots(
    limit: usize,
) -> (String, HashMap<String, alpaca_data::options::Snapshot>) {
    load_local_env();
    let client = Client::builder()
        .credentials_from_env()
        .expect("credentials should load from env")
        .build()
        .expect("alpaca data client should build");

    let candidates = ["SPY", "QQQ", "AAPL"];
    for symbol in candidates {
        let response = client
            .options()
            .chain(alpaca_data::options::ChainRequest {
                underlying_symbol: symbol.to_string(),
                feed: Some(preferred_feed()),
                r#type: None,
                strike_price_gte: None,
                strike_price_lte: None,
                expiration_date: None,
                expiration_date_gte: None,
                expiration_date_lte: None,
                root_symbol: None,
                updated_since: None,
                limit: Some(limit as u32),
                page_token: None,
            })
            .await
            .expect("live option chain request should succeed");

        if response.snapshots.len() >= 2 {
            return (symbol.to_string(), response.snapshots);
        }
    }

    panic!("failed to discover enough live option snapshots");
}

async fn fetch_live_snapshots_for(
    symbol: &str,
    limit: usize,
) -> HashMap<String, alpaca_data::options::Snapshot> {
    load_local_env();
    let client = Client::builder()
        .credentials_from_env()
        .expect("credentials should load from env")
        .build()
        .expect("alpaca data client should build");

    let response = client
        .options()
        .chain(alpaca_data::options::ChainRequest {
            underlying_symbol: symbol.to_string(),
            feed: Some(preferred_feed()),
            r#type: None,
            strike_price_gte: None,
            strike_price_lte: None,
            expiration_date: None,
            expiration_date_gte: None,
            expiration_date_lte: None,
            root_symbol: None,
            updated_since: None,
            limit: Some(limit as u32),
            page_token: None,
        })
        .await
        .expect("live option chain request should succeed");

    response.snapshots
}

async fn fetch_live_stock_prices(symbols: &[&str]) -> HashMap<String, f64> {
    load_local_env();
    let client = Client::builder()
        .credentials_from_env()
        .expect("credentials should load from env")
        .build()
        .expect("alpaca data client should build");

    let snapshots = client
        .stocks()
        .snapshots(SnapshotsRequest {
            symbols: symbols.iter().map(|symbol| (*symbol).to_string()).collect(),
            feed: None,
            currency: None,
        })
        .await
        .expect("live stock snapshots request should succeed");

    snapshots
        .into_iter()
        .filter_map(|(symbol, snapshot)| {
            snapshot
                .price()
                .and_then(|value| rust_decimal::prelude::ToPrimitive::to_f64(&value))
                .map(|price| (symbol, price))
        })
        .collect()
}

#[tokio::test]
async fn map_snapshot_uses_live_alpaca_snapshot() {
    let (symbol, snapshots) = discover_live_snapshots(8).await;
    let (occ_symbol, snapshot) = snapshots
        .iter()
        .next()
        .expect("live chain should yield at least one snapshot");
    let stock_prices = fetch_live_stock_prices(&[symbol.as_str()]).await;
    let underlying_price = stock_prices.get(&symbol).copied();

    let mapped = map_snapshot(
        occ_symbol,
        snapshot,
        underlying_price,
        Some(0.04),
        Some(0.0),
    )
    .expect("live snapshot should map into core snapshot");

    assert_eq!(mapped.contract.occ_symbol, *occ_symbol);
    assert_ny_timestamp(&mapped.as_of);
    assert_eq!(mapped.underlying_price, underlying_price);
    if let (Some(bid), Some(ask), Some(mark)) =
        (mapped.quote.bid, mapped.quote.ask, mapped.quote.mark)
    {
        assert!(
            (mark - ((bid + ask) / 2.0)).abs() < 1e-9,
            "mark should be bid/ask midpoint when both sides exist"
        );
    }
}

#[tokio::test]
async fn map_snapshots_sorts_live_symbols() {
    let (symbol, snapshots) = discover_live_snapshots(8).await;
    let stock_prices = fetch_live_stock_prices(&[symbol.as_str()]).await;
    let mapped = map_snapshots(&snapshots, Some(&stock_prices), Some(0.04), Some(0.0))
        .expect("live snapshots map should convert");

    assert!(mapped.len() >= 2, "need at least two live mapped snapshots");
    for snapshot in &mapped {
        assert_ny_timestamp(&snapshot.as_of);
        assert_eq!(
            snapshot.underlying_price,
            stock_prices.get(&symbol).copied()
        );
    }
    for pair in mapped.windows(2) {
        assert!(
            pair[0].contract.occ_symbol <= pair[1].contract.occ_symbol,
            "mapped snapshots should stay sorted by occ symbol"
        );
    }
}

#[tokio::test]
async fn map_live_snapshots_fetches_underlying_prices() {
    let (symbol, snapshots) = discover_live_snapshots(8).await;
    let stock_prices = fetch_live_stock_prices(&[symbol.as_str()]).await;
    let expected_price = stock_prices.get(&symbol).copied();

    let mapped = map_live_snapshots(
        &snapshots,
        &Client::builder()
            .credentials_from_env()
            .expect("credentials should load from env")
            .build()
            .expect("alpaca data client should build"),
        None,
        Some(0.04),
        Some(0.0),
    )
    .await
    .expect("live snapshots map should enrich underlying prices");

    assert!(mapped.len() >= 2, "need at least two live mapped snapshots");
    for snapshot in &mapped {
        assert_ny_timestamp(&snapshot.as_of);
        assert_underlying_price_close(snapshot.underlying_price, expected_price);
    }
}

#[tokio::test]
async fn fetch_chain_builds_live_canonical_chain() {
    load_local_env();
    let client = Client::builder()
        .credentials_from_env()
        .expect("credentials should load from env")
        .build()
        .expect("alpaca data client should build");
    let stock_prices = fetch_live_stock_prices(&["SPY"]).await;
    let underlying_price = stock_prices.get("SPY").copied();

    let chain = fetch_chain(
        &client,
        "SPY",
        &OptionChainRequest::from_expiration_range(Some(&alpaca_time::clock::today()), None)
            .with_underlying_price(underlying_price),
        Some(0.04),
        Some(0.0),
    )
    .await
    .expect("live fetch_chain should succeed");

    assert_eq!(chain.underlying_symbol, "SPY");
    assert_ny_timestamp(&chain.as_of);
    assert!(
        !chain.snapshots.is_empty(),
        "live fetch_chain should return at least one snapshot"
    );
    for snapshot in &chain.snapshots {
        assert_eq!(snapshot.contract.underlying_symbol, "SPY");
    }
}

#[tokio::test]
async fn resolve_positions_from_optionstrat_url_uses_live_snapshots() {
    let (underlying_symbol, snapshots) = discover_live_snapshots(8).await;
    let stock_prices = fetch_live_stock_prices(&[underlying_symbol.as_str()]).await;
    let underlying_price = stock_prices.get(&underlying_symbol).copied();
    let mut symbols = snapshots.keys().cloned().collect::<Vec<_>>();
    symbols.sort();
    let selected = symbols.into_iter().take(2).collect::<Vec<_>>();
    assert_eq!(selected.len(), 2, "live chain should provide two contracts");

    let url_value = url::build_optionstrat_url(&alpaca_option::OptionStratUrlInput {
        underlying_display_symbol: underlying_symbol.clone(),
        legs: selected
            .iter()
            .enumerate()
            .map(|(index, occ_symbol)| alpaca_option::OptionStratLegInput {
                occ_symbol: occ_symbol.clone(),
                quantity: if index == 0 { 1 } else { -1 },
                premium_per_contract: Some(if index == 0 { 1.0 } else { 2.0 }),
                ..Default::default()
            })
            .collect::<Vec<_>>(),
        stocks: Vec::new(),
    })
    .expect("live optionstrat url should build");

    load_local_env();
    let client = Client::builder()
        .credentials_from_env()
        .expect("credentials should load from env")
        .build()
        .expect("alpaca data client should build");

    let resolved = resolve_positions_from_optionstrat_url(&url_value, &client)
        .await
        .expect("live optionstrat positions should resolve");

    assert_eq!(resolved.underlying_display_symbol, underlying_symbol);
    assert_eq!(resolved.legs.len(), 2);
    assert_eq!(resolved.positions.len(), 2);
    assert_eq!(resolved.positions[0].avg_cost, Decimal::new(100, 2));
    assert_eq!(resolved.positions[1].avg_cost, Decimal::new(200, 2));
    assert!(
        resolved
            .positions
            .iter()
            .all(|position| position.snapshot_ref().is_some())
    );
    for position in &resolved.positions {
        let snapshot = position.snapshot_ref().unwrap();
        assert_ny_timestamp(&snapshot.as_of);
        assert_underlying_price_close(snapshot.underlying_price, underlying_price);
    }
}

#[tokio::test]
async fn brk_b_live_chain_and_optionstrat_roundtrip_work() {
    let snapshots = fetch_live_snapshots_for("BRK.B", 8).await;
    let stock_prices = fetch_live_stock_prices(&["BRK.B"]).await;
    let underlying_price = stock_prices.get("BRK.B").copied();
    assert!(
        snapshots.len() >= 2,
        "BRK.B live chain should yield at least two snapshots, got {}",
        snapshots.len()
    );

    let mut symbols = snapshots.keys().cloned().collect::<Vec<_>>();
    symbols.sort();
    let selected = symbols.into_iter().take(2).collect::<Vec<_>>();
    assert_eq!(
        selected.len(),
        2,
        "BRK.B live chain should provide two contracts"
    );
    assert!(
        selected.iter().all(|symbol| symbol.starts_with("BRKB")),
        "BRK.B chain contracts should use BRKB OCC prefix: {:?}",
        selected
    );

    let url_value = url::build_optionstrat_url(&alpaca_option::OptionStratUrlInput {
        underlying_display_symbol: "BRK.B".to_string(),
        legs: selected
            .iter()
            .enumerate()
            .map(|(index, occ_symbol)| alpaca_option::OptionStratLegInput {
                occ_symbol: occ_symbol.clone(),
                quantity: if index == 0 { 1 } else { -1 },
                premium_per_contract: Some(if index == 0 { 1.0 } else { 2.0 }),
                ..Default::default()
            })
            .collect::<Vec<_>>(),
        stocks: Vec::new(),
    })
    .expect("BRK.B optionstrat url should build");
    assert!(
        url_value.contains("/BRK%2FB/"),
        "BRK.B optionstrat url should encode the dot symbol: {url_value}"
    );

    load_local_env();
    let client = Client::builder()
        .credentials_from_env()
        .expect("credentials should load from env")
        .build()
        .expect("alpaca data client should build");

    let resolved = resolve_positions_from_optionstrat_url(&url_value, &client)
        .await
        .expect("BRK.B optionstrat url should resolve against live snapshots");

    assert_eq!(resolved.underlying_display_symbol, "BRK.B");
    assert_eq!(resolved.legs.len(), 2);
    assert_eq!(resolved.positions.len(), 2);
    for position in &resolved.positions {
        assert_eq!(position.contract_info().underlying_symbol, "BRKB");
        assert!(
            position.snapshot_ref().is_some(),
            "resolved position should carry live snapshot"
        );
        let snapshot = position.snapshot_ref().unwrap();
        assert_ny_timestamp(&snapshot.as_of);
        assert_underlying_price_close(snapshot.underlying_price, underlying_price);
    }
}

#[tokio::test]
async fn map_snapshots_accepts_brk_b_display_symbol_prices() {
    let snapshots = fetch_live_snapshots_for("BRK.B", 8).await;
    let stock_prices = fetch_live_stock_prices(&["BRK.B"]).await;
    let underlying_price = stock_prices
        .get("BRK.B")
        .copied()
        .expect("BRK.B stock price should exist");

    let mapped = map_snapshots(&snapshots, Some(&stock_prices), Some(0.04), Some(0.0))
        .expect("BRK.B live snapshots should map");

    assert!(
        !mapped.is_empty(),
        "BRK.B mapped snapshots should not be empty"
    );
    for snapshot in &mapped {
        assert_eq!(snapshot.contract.underlying_symbol, "BRKB");
        assert_eq!(snapshot.underlying_price, Some(underlying_price));
        assert_ny_timestamp(&snapshot.as_of);
    }
}