marketsurge-client 0.1.0

Unofficial HTTP client library for the MarketSurge platform
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
//! Chart market data endpoints.

use serde::{Deserialize, Serialize};

use crate::client::Client;
use crate::graphql::GraphQLRequest;
use crate::types::symbols_to_owned;

// ---------------------------------------------------------------------------
// GraphQL queries
// ---------------------------------------------------------------------------

const QUERY_CHART_MARKET_DATA: &str = r#"query ChartMarketData(
  $symbols: [String!]!
  $symbolDialectType: MDSymbolDialectType!
  $where: TimeSeriesFilterInput!
  $exchangeName: String!
) {
  marketData(symbols: $symbols, symbolDialectType: $symbolDialectType) {
    id
    originRequest {
      fromDialect
      symbol
    }
    pricing {
      timeSeries(where: $where) {
        period
        dataPoints {
          startDateTime
          endDateTime
          volume { value }
          last { value }
          low { value }
          high { value }
          open { value }
        }
      }
      quote {
        tradeDateTime
        timeliness
        quoteType
        volume { value formattedValue }
        percentChange { value formattedValue }
        netChange { value formattedValue }
        last { value formattedValue }
      }
      premarketQuote {
        last { value formattedValue }
        tradeDateTime
        timeliness
        volume { value formattedValue }
        percentChange { value formattedValue }
        quoteType
        netChange { value formattedValue }
      }
      postmarketQuote {
        volume { value formattedValue }
        tradeDateTime
        timeliness
        percentChange { formattedValue value }
        netChange { value formattedValue }
        quoteType
        last { value formattedValue }
      }
      currentMarketState
    }
  }
  exchangeData(exchangeName: $exchangeName) {
    city
    countryCode
    exchangeISO
    id
    holidays(
      where: {
        startDateTime: { gt: "2021-12-02T07:00:00.000Z" }
        endDateTime: { lt: "2026-03-27T23:55:25.000Z" }
      }
    ) {
      name
      holidayType
      description
      startDateTime
      endDateTime
    }
  }
}"#;

const QUERY_CHART_MARKET_DATA_WEEKLY: &str = r#"query ChartMarketData(
  $symbols: [String!]!
  $symbolDialectType: MDSymbolDialectType!
  $where: TimeSeriesFilterInput!
) {
  marketData(symbols: $symbols, symbolDialectType: $symbolDialectType) {
    id
    originRequest {
      fromDialect
      symbol
    }
    pricing {
      timeSeries(where: $where) {
        period
        dataPoints {
          startDateTime
          endDateTime
          volume { value }
          last { value }
          low { value }
          high { value }
          open { value }
        }
      }
      quote {
        tradeDateTime
        timeliness
        quoteType
        volume { value formattedValue }
        percentChange { value formattedValue }
        netChange { value formattedValue }
        last { value formattedValue }
      }
      premarketQuote {
        last { value formattedValue }
        tradeDateTime
        timeliness
        volume { value formattedValue }
        percentChange { value formattedValue }
        quoteType
        netChange { value formattedValue }
      }
      postmarketQuote {
        volume { value formattedValue }
        tradeDateTime
        timeliness
        percentChange { formattedValue value }
        netChange { value formattedValue }
        quoteType
        last { value formattedValue }
      }
      currentMarketState
    }
  }
}"#;

// ---------------------------------------------------------------------------
// Wire variable types (serialization only)
// ---------------------------------------------------------------------------

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ChartMarketDataVariables {
    symbols: Vec<String>,
    symbol_dialect_type: String,
    #[serde(rename = "where")]
    filter: TimeSeriesFilterInput,
    exchange_name: String,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ChartMarketDataWeeklyVariables {
    symbols: Vec<String>,
    symbol_dialect_type: String,
    #[serde(rename = "where")]
    filter: TimeSeriesFilterInput,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct TimeSeriesFilterInput {
    start_date_time: EqFilter,
    end_date_time: EqFilter,
    time_series_type: EqFilter,
    include_intraday_data: bool,
}

#[derive(Serialize)]
struct EqFilter {
    eq: String,
}

// ---------------------------------------------------------------------------
// Response types
// ---------------------------------------------------------------------------

/// Top-level response from the `ChartMarketData` query.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChartMarketDataResponse {
    /// Per-symbol chart market data items.
    #[serde(default)]
    pub market_data: Vec<ChartMarketDataItem>,
    /// Exchange information (present for daily, absent for weekly).
    pub exchange_data: Option<ChartExchangeData>,
}

/// Chart market data for a single symbol.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChartMarketDataItem {
    /// Symbol identifier.
    pub id: String,
    /// Original request dialect and symbol.
    pub origin_request: Option<ChartOriginRequest>,
    /// Pricing data.
    pub pricing: Option<ChartPricing>,
}

/// Original request dialect and symbol.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChartOriginRequest {
    /// Source dialect (e.g. "CHARTING").
    pub from_dialect: String,
    /// Ticker symbol.
    pub symbol: String,
}

/// Pricing data including time series and quotes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChartPricing {
    /// Historical time series data.
    pub time_series: Option<ChartTimeSeries>,
    /// Regular-hours quote.
    pub quote: Option<ChartQuote>,
    /// Pre-market quote.
    pub premarket_quote: Option<ChartQuote>,
    /// Post-market quote.
    pub postmarket_quote: Option<ChartQuote>,
    /// Current market state (e.g. "POST_MARKET").
    pub current_market_state: Option<String>,
}

/// Time series with period and data points.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChartTimeSeries {
    /// Time series period (e.g. "ONE_DAY", "ONE_WEEK").
    pub period: String,
    /// Price/volume data points.
    #[serde(default)]
    pub data_points: Vec<ChartDataPoint>,
}

/// Single OHLCV data point.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChartDataPoint {
    /// Period start timestamp.
    pub start_date_time: String,
    /// Period end timestamp.
    pub end_date_time: String,
    /// Trading volume.
    pub volume: Option<ChartValue>,
    /// Last/close price.
    pub last: Option<ChartValue>,
    /// Period low price.
    pub low: Option<ChartValue>,
    /// Period high price.
    pub high: Option<ChartValue>,
    /// Period open price.
    pub open: Option<ChartValue>,
}

/// Single numeric value.
pub type ChartValue = crate::types::FloatValue;

/// Quote data with formatted display strings.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChartQuote {
    /// Trade timestamp.
    pub trade_date_time: Option<String>,
    /// Data timeliness (e.g. "REAL_TIME", "DELAYED").
    pub timeliness: Option<String>,
    /// Quote type (e.g. "REGULAR", "PRE_MARKET").
    pub quote_type: Option<String>,
    /// Volume with formatted string.
    pub volume: Option<ChartFormattedValue>,
    /// Percent change with formatted string.
    pub percent_change: Option<ChartFormattedValue>,
    /// Net change with formatted string.
    pub net_change: Option<ChartFormattedValue>,
    /// Last price with formatted string.
    pub last: Option<ChartFormattedValue>,
}

/// Numeric value with formatted display string.
pub type ChartFormattedValue = crate::types::FormattedFloat;

/// Exchange information and holidays.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChartExchangeData {
    /// City name.
    pub city: Option<String>,
    /// ISO country code.
    pub country_code: Option<String>,
    /// Exchange ISO code (e.g. "XNYS").
    #[serde(rename = "exchangeISO")]
    pub exchange_iso: Option<String>,
    /// Exchange identifier.
    pub id: Option<String>,
    /// Exchange holidays.
    #[serde(default)]
    pub holidays: Vec<ChartExchangeHoliday>,
}

/// Exchange holiday entry.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ChartExchangeHoliday {
    /// Holiday name.
    pub name: String,
    /// Holiday type (e.g. "FULL").
    pub holiday_type: Option<String>,
    /// Holiday description.
    pub description: Option<String>,
    /// Start timestamp.
    pub start_date_time: String,
    /// End timestamp.
    pub end_date_time: String,
}

// ---------------------------------------------------------------------------
// Client methods
// ---------------------------------------------------------------------------

impl Client {
    /// Fetches daily chart market data for the given symbols.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL request fails or the response
    /// cannot be deserialized.
    #[allow(clippy::too_many_arguments)]
    pub async fn chart_market_data(
        &self,
        symbols: &[&str],
        symbol_dialect_type: &str,
        start_date_time: &str,
        end_date_time: &str,
        time_series_type: &str,
        include_intraday: bool,
        exchange_name: &str,
    ) -> crate::error::Result<ChartMarketDataResponse> {
        let variables = ChartMarketDataVariables {
            symbols: symbols_to_owned(symbols),
            symbol_dialect_type: symbol_dialect_type.to_string(),
            filter: TimeSeriesFilterInput {
                start_date_time: EqFilter {
                    eq: start_date_time.to_string(),
                },
                end_date_time: EqFilter {
                    eq: end_date_time.to_string(),
                },
                time_series_type: EqFilter {
                    eq: time_series_type.to_string(),
                },
                include_intraday_data: include_intraday,
            },
            exchange_name: exchange_name.to_string(),
        };

        let request = GraphQLRequest {
            operation_name: "ChartMarketData".to_string(),
            variables,
            query: QUERY_CHART_MARKET_DATA.to_string(),
        };

        self.graphql_post(&request).await
    }

    /// Fetches weekly chart market data for the given symbols.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL request fails or the response
    /// cannot be deserialized.
    pub async fn chart_market_data_weekly(
        &self,
        symbols: &[&str],
        symbol_dialect_type: &str,
        start_date_time: &str,
        end_date_time: &str,
    ) -> crate::error::Result<ChartMarketDataResponse> {
        let variables = ChartMarketDataWeeklyVariables {
            symbols: symbols_to_owned(symbols),
            symbol_dialect_type: symbol_dialect_type.to_string(),
            filter: TimeSeriesFilterInput {
                start_date_time: EqFilter {
                    eq: start_date_time.to_string(),
                },
                end_date_time: EqFilter {
                    eq: end_date_time.to_string(),
                },
                time_series_type: EqFilter {
                    eq: "ONE_WEEK".to_string(),
                },
                include_intraday_data: true,
            },
        };

        let request = GraphQLRequest {
            operation_name: "ChartMarketData".to_string(),
            variables,
            query: QUERY_CHART_MARKET_DATA_WEEKLY.to_string(),
        };

        self.graphql_post(&request).await
    }
}

#[cfg(test)]
mod tests {
    use crate::test_support::{mock_test, mock_test_with_fixture};

    #[tokio::test]
    async fn chart_market_data_parses_response() {
        let (_server, client, mock) = mock_test("ChartMarketData").await;

        let resp = client
            .chart_market_data(
                &["AAPL"],
                "CHARTING",
                "2025-01-01T00:00:00.000Z",
                "2025-05-02T23:59:59.000Z",
                "ONE_DAY",
                true,
                "NYSE",
            )
            .await
            .expect("chart_market_data should succeed");

        assert_eq!(resp.market_data.len(), 1);
        let item = &resp.market_data[0];
        assert_eq!(item.id, "AAPL-CHARTING");

        let origin = item.origin_request.as_ref().expect("origin_request");
        assert_eq!(origin.symbol, "AAPL");
        assert_eq!(origin.from_dialect, "CHARTING");

        let pricing = item.pricing.as_ref().expect("pricing");
        let ts = pricing.time_series.as_ref().expect("time_series");
        assert_eq!(ts.period, "ONE_DAY");
        assert_eq!(ts.data_points.len(), 2);
        assert_eq!(ts.data_points[0].last.as_ref().unwrap().value, Some(210.45));

        let quote = pricing.quote.as_ref().expect("quote");
        assert_eq!(quote.last.as_ref().unwrap().value, Some(212.30));
        assert_eq!(
            quote.last.as_ref().unwrap().formatted_value.as_deref(),
            Some("212.30")
        );

        assert_eq!(pricing.current_market_state.as_deref(), Some("POST_MARKET"));

        let exchange = resp.exchange_data.as_ref().expect("exchange_data");
        assert_eq!(exchange.city.as_deref(), Some("New York"));
        assert_eq!(exchange.exchange_iso.as_deref(), Some("XNYS"));
        assert_eq!(exchange.holidays.len(), 1);
        assert_eq!(exchange.holidays[0].name, "Independence Day");

        mock.assert();
    }

    #[tokio::test]
    async fn chart_market_data_weekly_parses_response() {
        let (_server, client, mock) =
            mock_test_with_fixture("ChartMarketDataWeekly", "ChartMarketData").await;

        let resp = client
            .chart_market_data_weekly(
                &["AAPL"],
                "CHARTING",
                "2024-05-01T00:00:00.000Z",
                "2025-05-02T23:59:59.000Z",
            )
            .await
            .expect("chart_market_data_weekly should succeed");

        assert_eq!(resp.market_data.len(), 1);
        let item = &resp.market_data[0];
        assert_eq!(item.id, "AAPL-CHARTING");

        let pricing = item.pricing.as_ref().expect("pricing");
        let ts = pricing.time_series.as_ref().expect("time_series");
        assert_eq!(ts.period, "ONE_WEEK");
        assert_eq!(ts.data_points.len(), 1);

        assert!(resp.exchange_data.is_none());

        mock.assert();
    }

    #[cfg(not(coverage))]
    #[tokio::test]
    #[ignore]
    async fn integration_chart_market_data() {
        let client = crate::test_support::live_client().await;
        let resp = client
            .chart_market_data(
                &["AAPL"],
                "CHARTING",
                "2025-01-01T00:00:00.000Z",
                "2025-05-02T23:59:59.000Z",
                "ONE_DAY",
                true,
                "NYSE",
            )
            .await
            .expect("live chart_market_data should succeed");

        assert!(!resp.market_data.is_empty());
    }

    #[cfg(not(coverage))]
    #[tokio::test]
    #[ignore]
    async fn integration_chart_market_data_weekly() {
        let client = crate::test_support::live_client().await;
        let resp = client
            .chart_market_data_weekly(
                &["AAPL"],
                "CHARTING",
                "2024-05-01T00:00:00.000Z",
                "2025-05-02T23:59:59.000Z",
            )
            .await
            .expect("live chart_market_data_weekly should succeed");

        assert!(!resp.market_data.is_empty());
    }
}