volumeleaders-client 0.1.2

Browser-session API client for VolumeLeaders data
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Executive summary endpoints for `/ExecutiveSummary/GetExhaustionScores`,
//! `/ExecutiveSummary/GetWelcomeTrades`,
//! `/ExecutiveSummary/GetWelcomeTradeClusters`, and
//! `/Trades/GetAllSnapshots` APIs.

use std::collections::HashMap;

use serde::Serialize;
use tracing::instrument;

use crate::client::Client;
use crate::datatables::{
    DataTablesColumn, DataTablesRequest, DataTablesResponse, fetch_limit,
    impl_datatables_request_methods,
};
use crate::error::Result;
use crate::models::{ExhaustionScore, Trade, TradeCluster};

/// Browser endpoint path for `/ExecutiveSummary/GetExhaustionScores`.
pub(crate) const EXECUTIVE_SUMMARY_GET_EXHAUSTION_SCORES_PATH: &str =
    "/ExecutiveSummary/GetExhaustionScores";

/// Browser endpoint path for `/ExecutiveSummary/GetWelcomeTrades`.
pub(crate) const EXECUTIVE_SUMMARY_GET_WELCOME_TRADES_PATH: &str =
    "/ExecutiveSummary/GetWelcomeTrades";

/// Browser endpoint path for `/ExecutiveSummary/GetWelcomeTradeClusters`.
pub(crate) const EXECUTIVE_SUMMARY_GET_WELCOME_TRADE_CLUSTERS_PATH: &str =
    "/ExecutiveSummary/GetWelcomeTradeClusters";

/// Browser endpoint path for `/Trades/GetAllSnapshots`.
pub(crate) const TRADES_GET_ALL_SNAPSHOTS_PATH: &str = "/Trades/GetAllSnapshots";

/// JSON request payload for `/ExecutiveSummary/GetExhaustionScores`.
#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct ExhaustionScoresRequest {
    /// Date string for the exhaustion scores query (e.g. `"2026-05-01"`).
    pub date: String,
}

/// Request parameters for `/ExecutiveSummary/GetWelcomeTrades`.
///
/// Wraps a [`DataTablesRequest`] with pre-configured column definitions
/// matching the VolumeLeaders welcome trades table.
#[derive(Clone, Debug)]
pub struct WelcomeTradesRequest(pub(crate) DataTablesRequest);

impl_datatables_request_methods!(WelcomeTradesRequest);

impl WelcomeTradesRequest {
    /// Create a welcome trades request with default column definitions.
    #[must_use]
    pub fn new() -> Self {
        Self(DataTablesRequest {
            columns: welcome_trades_columns(),
            ..DataTablesRequest::default()
        })
    }

    /// Return raw key-value pairs for form submission.
    pub(crate) fn to_pairs(&self) -> Vec<(String, String)> {
        self.0.to_pairs()
    }
}

impl Default for WelcomeTradesRequest {
    fn default() -> Self {
        Self::new()
    }
}

/// Request parameters for `/ExecutiveSummary/GetWelcomeTradeClusters`.
///
/// Wraps a [`DataTablesRequest`] with pre-configured column definitions
/// matching the VolumeLeaders welcome trade clusters table.
#[derive(Clone, Debug)]
pub struct WelcomeTradeClustersRequest(pub(crate) DataTablesRequest);

impl_datatables_request_methods!(WelcomeTradeClustersRequest);

impl WelcomeTradeClustersRequest {
    /// Create a welcome trade clusters request with default column definitions.
    #[must_use]
    pub fn new() -> Self {
        Self(DataTablesRequest {
            columns: welcome_trade_clusters_columns(),
            ..DataTablesRequest::default()
        })
    }

    /// Return raw key-value pairs for form submission.
    pub(crate) fn to_pairs(&self) -> Vec<(String, String)> {
        self.0.to_pairs()
    }
}

impl Default for WelcomeTradeClustersRequest {
    fn default() -> Self {
        Self::new()
    }
}

/// Return the DataTables column definitions for the welcome trades table.
///
/// Column order, `Data`/`Name` field values, and `Searchable`/`Orderable`
/// flags match the Go source (`WelcomeTradesColumns`) exactly.
#[must_use]
pub fn welcome_trades_columns() -> Vec<DataTablesColumn> {
    vec![
        DataTablesColumn::new("Ticker", "Ticker", true, true),
        DataTablesColumn::new("TradeRank", "R", true, true),
        DataTablesColumn::new("DollarsMultiplier", "RS", true, true),
        DataTablesColumn::new("CumulativeDistribution", "PCT", true, true),
        DataTablesColumn::new("LastComparibleTradeDate", "Charts", true, false),
    ]
}

/// Return the DataTables column definitions for the welcome trade clusters
/// table.
///
/// Column order, `Data`/`Name` field values, and `Searchable`/`Orderable`
/// flags match the Go source (`WelcomeTradeClustersColumns`) exactly.
#[must_use]
pub fn welcome_trade_clusters_columns() -> Vec<DataTablesColumn> {
    vec![
        DataTablesColumn::new("Ticker", "Ticker", true, true),
        DataTablesColumn::new("TradeClusterRank", "R", true, true),
        DataTablesColumn::new("DollarsMultiplier", "RS", true, true),
        DataTablesColumn::new("CumulativeDistribution", "PCT", true, true),
        DataTablesColumn::new("LastComparibleTradeClusterDate", "Charts", true, false),
    ]
}

/// Parse the semicolon-delimited ticker snapshot string returned by
/// `/Trades/GetAllSnapshots` into a ticker-to-price map.
///
/// Each item has the form `TICKER:PRICE` separated by semicolons.
/// Empty items (from trailing semicolons) are silently skipped.
///
/// # Errors
///
/// Returns an error if an item is missing the `:` separator or the price
/// portion cannot be parsed as `f64`.
pub fn parse_snapshots(raw: &str) -> Result<HashMap<String, f64>> {
    let mut snapshots = HashMap::new();
    for item in raw.split(';') {
        let item = item.trim();
        if item.is_empty() {
            continue;
        }
        let (ticker, price_str) = item.split_once(':').ok_or_else(|| {
            crate::error::ClientError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("parse snapshot {item:?}: missing separator"),
            ))
        })?;
        let ticker = ticker.trim();
        if ticker.is_empty() {
            return Err(crate::error::ClientError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("parse snapshot {item:?}: missing ticker"),
            )));
        }
        let price: f64 = price_str.trim().parse().map_err(|e| {
            crate::error::ClientError::Io(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("parse snapshot price for {ticker:?}: {e}"),
            ))
        })?;
        snapshots.insert(ticker.to_string(), price);
    }
    Ok(snapshots)
}

impl Client {
    /// Post a JSON request to `/ExecutiveSummary/GetExhaustionScores` and
    /// return the exhaustion score data.
    #[instrument(skip_all)]
    pub async fn get_exhaustion_scores(
        &self,
        request: &ExhaustionScoresRequest,
    ) -> Result<ExhaustionScore> {
        let body = self
            .post_json(EXECUTIVE_SUMMARY_GET_EXHAUSTION_SCORES_PATH, request)
            .await?;
        Ok(serde_json::from_str(&body)?)
    }

    /// Post a DataTables request to `/ExecutiveSummary/GetWelcomeTrades` and
    /// return the typed response envelope.
    #[instrument(skip_all)]
    pub async fn get_welcome_trades(
        &self,
        request: &WelcomeTradesRequest,
    ) -> Result<DataTablesResponse<Trade>> {
        let body = self
            .post_form(
                EXECUTIVE_SUMMARY_GET_WELCOME_TRADES_PATH,
                request.to_pairs(),
            )
            .await?;
        Ok(serde_json::from_str(&body)?)
    }

    /// Fetch up to `limit` welcome trades by paginating
    /// `/ExecutiveSummary/GetWelcomeTrades`.
    #[instrument(skip_all)]
    pub async fn get_welcome_trades_limit(
        &self,
        request: &WelcomeTradesRequest,
        limit: usize,
    ) -> Result<Vec<Trade>> {
        fetch_limit(
            self,
            EXECUTIVE_SUMMARY_GET_WELCOME_TRADES_PATH,
            request.0.clone(),
            limit,
        )
        .await
    }

    /// Post a DataTables request to
    /// `/ExecutiveSummary/GetWelcomeTradeClusters` and return the typed
    /// response envelope.
    #[instrument(skip_all)]
    pub async fn get_welcome_trade_clusters(
        &self,
        request: &WelcomeTradeClustersRequest,
    ) -> Result<DataTablesResponse<TradeCluster>> {
        let body = self
            .post_form(
                EXECUTIVE_SUMMARY_GET_WELCOME_TRADE_CLUSTERS_PATH,
                request.to_pairs(),
            )
            .await?;
        Ok(serde_json::from_str(&body)?)
    }

    /// Fetch up to `limit` welcome trade clusters by paginating
    /// `/ExecutiveSummary/GetWelcomeTradeClusters`.
    #[instrument(skip_all)]
    pub async fn get_welcome_trade_clusters_limit(
        &self,
        request: &WelcomeTradeClustersRequest,
        limit: usize,
    ) -> Result<Vec<TradeCluster>> {
        fetch_limit(
            self,
            EXECUTIVE_SUMMARY_GET_WELCOME_TRADE_CLUSTERS_PATH,
            request.0.clone(),
            limit,
        )
        .await
    }

    /// Post a JSON null request to `/Trades/GetAllSnapshots` and return
    /// ticker snapshot prices keyed by ticker symbol.
    #[instrument(skip_all)]
    pub async fn get_all_snapshots(&self) -> Result<HashMap<String, f64>> {
        let raw = self.get_all_snapshots_string().await?;
        parse_snapshots(&raw)
    }

    /// Post a JSON null request to `/Trades/GetAllSnapshots` and return the
    /// raw semicolon-delimited ticker snapshot string.
    #[instrument(skip_all)]
    pub async fn get_all_snapshots_string(&self) -> Result<String> {
        let body = self.post_json(TRADES_GET_ALL_SNAPSHOTS_PATH, &()).await?;
        Ok(serde_json::from_str(&body)?)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::client::ClientConfig;
    use crate::session::{
        COOKIE_DOMAIN, Cookie, FORMS_AUTH_COOKIE_NAME, SESSION_COOKIE_NAME, Session,
    };

    fn test_session() -> Session {
        Session::new(
            vec![
                Cookie::new(SESSION_COOKIE_NAME, "session-123", COOKIE_DOMAIN),
                Cookie::new(FORMS_AUTH_COOKIE_NAME, "auth-456", COOKIE_DOMAIN),
            ],
            "xsrf-789",
        )
    }

    fn test_client(server: &mockito::Server) -> Client {
        Client::with_config(
            test_session(),
            ClientConfig {
                base_url: server.url(),
                ..ClientConfig::default()
            },
        )
        .unwrap()
    }

    // -- column definition tests --

    #[test]
    fn welcome_trades_columns_returns_5_columns() {
        let columns = welcome_trades_columns();
        assert_eq!(columns.len(), 5);
    }

    #[test]
    fn welcome_trades_columns_match_go_source() {
        let columns = welcome_trades_columns();

        assert_eq!(columns[0].data, "Ticker");
        assert_eq!(columns[0].name, "Ticker");
        assert!(columns[0].orderable);

        assert_eq!(columns[1].data, "TradeRank");
        assert_eq!(columns[1].name, "R");
        assert!(columns[1].orderable);

        assert_eq!(columns[4].data, "LastComparibleTradeDate");
        assert_eq!(columns[4].name, "Charts");
        assert!(!columns[4].orderable);
    }

    #[test]
    fn welcome_trade_clusters_columns_returns_5_columns() {
        let columns = welcome_trade_clusters_columns();
        assert_eq!(columns.len(), 5);
    }

    #[test]
    fn welcome_trade_clusters_columns_match_go_source() {
        let columns = welcome_trade_clusters_columns();

        assert_eq!(columns[0].data, "Ticker");
        assert_eq!(columns[0].name, "Ticker");
        assert!(columns[0].orderable);

        assert_eq!(columns[1].data, "TradeClusterRank");
        assert_eq!(columns[1].name, "R");
        assert!(columns[1].orderable);

        assert_eq!(columns[4].data, "LastComparibleTradeClusterDate");
        assert_eq!(columns[4].name, "Charts");
        assert!(!columns[4].orderable);
    }

    // -- parse_snapshots tests --

    #[test]
    fn parse_snapshots_parses_ticker_prices() {
        let raw = "A:114.52;AA:62.67;";
        let snapshots = parse_snapshots(raw).unwrap();
        assert!((snapshots["A"] - 114.52).abs() < 0.0001);
        assert!((snapshots["AA"] - 62.67).abs() < 0.0001);
    }

    #[test]
    fn parse_snapshots_skips_empty_items() {
        let raw = "SPY:450.00;;QQQ:380.50;";
        let snapshots = parse_snapshots(raw).unwrap();
        assert_eq!(snapshots.len(), 2);
        assert!((snapshots["SPY"] - 450.0).abs() < 0.0001);
    }

    #[test]
    fn parse_snapshots_reports_missing_separator() {
        let err = parse_snapshots("A:114.52;broken").unwrap_err();
        assert!(err.to_string().contains("missing separator"));
    }

    #[test]
    fn parse_snapshots_reports_missing_ticker() {
        let err = parse_snapshots(":123.45").unwrap_err();
        assert!(err.to_string().contains("missing ticker"));
    }

    #[test]
    fn parse_snapshots_reports_invalid_price() {
        let err = parse_snapshots("AMD:notanumber").unwrap_err();
        assert!(err.to_string().contains("parse snapshot price"));
    }

    // -- endpoint tests --

    #[tokio::test]
    async fn get_exhaustion_scores_returns_parsed_response() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("POST", EXECUTIVE_SUMMARY_GET_EXHAUSTION_SCORES_PATH)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{
                    "DateKey": 20260501,
                    "ExhaustionScoreRank": 4,
                    "ExhaustionScoreRank30Day": 8,
                    "ExhaustionScoreRank90Day": 11,
                    "ExhaustionScoreRank365Day": 22
                }"#,
            )
            .create_async()
            .await;
        let client = test_client(&server);

        let score = client
            .get_exhaustion_scores(&ExhaustionScoresRequest {
                date: "2026-05-01".to_string(),
            })
            .await
            .unwrap();

        assert_eq!(score.date_key, Some(20_260_501));
        assert_eq!(score.exhaustion_score_rank, Some(4));
        assert_eq!(score.exhaustion_score_rank_30_day, Some(8));
        assert_eq!(score.exhaustion_score_rank_90_day, Some(11));
        assert_eq!(score.exhaustion_score_rank_365_day, Some(22));
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn get_welcome_trades_returns_fixture_response() {
        let mut server = mockito::Server::new_async().await;
        let fixture = crate::test_support::read_fixture("welcome_trades_response.json");
        let mock = server
            .mock("POST", EXECUTIVE_SUMMARY_GET_WELCOME_TRADES_PATH)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&fixture)
            .create_async()
            .await;
        let client = test_client(&server);

        let response = client
            .get_welcome_trades(&WelcomeTradesRequest::new())
            .await
            .unwrap();

        assert_eq!(response.draw, 7);
        assert_eq!(response.records_total, 2);
        assert_eq!(response.records_filtered, 2);
        assert_eq!(response.data.len(), 2);
        assert_eq!(response.data[0].ticker.as_deref(), Some("AMD"));
        assert_eq!(response.data[0].trade_rank, Some(11));
        assert_eq!(response.data[1].ticker.as_deref(), Some("NVDA"));
        assert_eq!(response.data[1].trade_rank, Some(5));
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn get_welcome_trades_limit_respects_limit() {
        let mut server = mockito::Server::new_async().await;
        let fixture = crate::test_support::read_fixture("welcome_trades_response.json");
        server
            .mock("POST", EXECUTIVE_SUMMARY_GET_WELCOME_TRADES_PATH)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&fixture)
            .create_async()
            .await;
        let client = test_client(&server);

        let trades = client
            .get_welcome_trades_limit(&WelcomeTradesRequest::new(), 1)
            .await
            .unwrap();

        assert_eq!(trades.len(), 1);
        assert_eq!(trades[0].ticker.as_deref(), Some("AMD"));
    }

    #[tokio::test]
    async fn get_welcome_trade_clusters_returns_fixture_response() {
        let mut server = mockito::Server::new_async().await;
        let fixture = crate::test_support::read_fixture("welcome_trade_clusters_response.json");
        let mock = server
            .mock("POST", EXECUTIVE_SUMMARY_GET_WELCOME_TRADE_CLUSTERS_PATH)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&fixture)
            .create_async()
            .await;
        let client = test_client(&server);

        let response = client
            .get_welcome_trade_clusters(&WelcomeTradeClustersRequest::new())
            .await
            .unwrap();

        assert_eq!(response.draw, 8);
        assert_eq!(response.records_total, 2);
        assert_eq!(response.records_filtered, 2);
        assert_eq!(response.data.len(), 2);
        assert_eq!(response.data[0].ticker.as_deref(), Some("AMD"));
        assert_eq!(response.data[0].trade_cluster_rank, Some(7));
        assert_eq!(response.data[1].ticker.as_deref(), Some("MSFT"));
        assert_eq!(response.data[1].trade_cluster_rank, Some(3));
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn get_welcome_trade_clusters_limit_respects_limit() {
        let mut server = mockito::Server::new_async().await;
        let fixture = crate::test_support::read_fixture("welcome_trade_clusters_response.json");
        server
            .mock("POST", EXECUTIVE_SUMMARY_GET_WELCOME_TRADE_CLUSTERS_PATH)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(&fixture)
            .create_async()
            .await;
        let client = test_client(&server);

        let clusters = client
            .get_welcome_trade_clusters_limit(&WelcomeTradeClustersRequest::new(), 1)
            .await
            .unwrap();

        assert_eq!(clusters.len(), 1);
        assert_eq!(clusters[0].ticker.as_deref(), Some("AMD"));
    }

    #[tokio::test]
    async fn get_all_snapshots_parses_ticker_prices() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("POST", TRADES_GET_ALL_SNAPSHOTS_PATH)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#""A:114.52;AA:62.67;""#)
            .create_async()
            .await;
        let client = test_client(&server);

        let snapshots = client.get_all_snapshots().await.unwrap();

        assert!((snapshots["A"] - 114.52).abs() < 0.0001);
        assert!((snapshots["AA"] - 62.67).abs() < 0.0001);
        mock.assert_async().await;
    }

    #[tokio::test]
    async fn get_all_snapshots_string_returns_raw_string() {
        let mut server = mockito::Server::new_async().await;
        let mock = server
            .mock("POST", TRADES_GET_ALL_SNAPSHOTS_PATH)
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#""A:114.52;AA:62.67;""#)
            .create_async()
            .await;
        let client = test_client(&server);

        let raw = client.get_all_snapshots_string().await.unwrap();

        assert_eq!(raw, "A:114.52;AA:62.67;");
        mock.assert_async().await;
    }
}