tvdata-rs 0.1.2

Async Rust client for TradingView screener queries, search, calendars, quote snapshots, and OHLCV history.
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
use bon::Builder;
use time::{Duration, OffsetDateTime};

use crate::client::TradingViewClient;
use crate::error::Result;
use crate::market_data::{InstrumentIdentity, RowDecoder, identity_columns, merge_columns};
use crate::scanner::fields::{analyst, calendar as calendar_fields};
use crate::scanner::filter::SortOrder;
use crate::scanner::{Column, Market, ScanQuery, ScanRow};

const DEFAULT_CALENDAR_LIMIT: usize = 100;
const CALENDAR_PAGE_SIZE: usize = 200;

fn default_calendar_from() -> OffsetDateTime {
    OffsetDateTime::now_utc()
}

fn default_calendar_to() -> OffsetDateTime {
    OffsetDateTime::now_utc() + Duration::days(30)
}

#[derive(Debug, Clone, PartialEq, Eq, Builder)]
pub struct CalendarWindowRequest {
    #[builder(into)]
    pub market: Market,
    #[builder(default = default_calendar_from())]
    pub from: OffsetDateTime,
    #[builder(default = default_calendar_to())]
    pub to: OffsetDateTime,
    #[builder(default = DEFAULT_CALENDAR_LIMIT)]
    pub limit: usize,
}

impl CalendarWindowRequest {
    pub fn new(market: impl Into<Market>, from: OffsetDateTime, to: OffsetDateTime) -> Self {
        Self::builder().market(market).from(from).to(to).build()
    }

    pub fn upcoming(market: impl Into<Market>, days: i64) -> Self {
        let now = OffsetDateTime::now_utc();
        Self::builder()
            .market(market)
            .from(now)
            .to(now + Duration::days(days.max(0)))
            .build()
    }

    pub fn trailing(market: impl Into<Market>, days: i64) -> Self {
        let now = OffsetDateTime::now_utc();
        Self::builder()
            .market(market)
            .from(now - Duration::days(days.max(0)))
            .to(now)
            .build()
    }

    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DividendDateKind {
    #[default]
    ExDate,
    PaymentDate,
}

#[derive(Debug, Clone, PartialEq, Eq, Builder)]
pub struct DividendCalendarRequest {
    #[builder(into)]
    pub market: Market,
    #[builder(default = default_calendar_from())]
    pub from: OffsetDateTime,
    #[builder(default = default_calendar_to())]
    pub to: OffsetDateTime,
    #[builder(default = DEFAULT_CALENDAR_LIMIT)]
    pub limit: usize,
    #[builder(default)]
    pub date_kind: DividendDateKind,
}

impl DividendCalendarRequest {
    pub fn new(market: impl Into<Market>, from: OffsetDateTime, to: OffsetDateTime) -> Self {
        Self::builder().market(market).from(from).to(to).build()
    }

    pub fn upcoming(market: impl Into<Market>, days: i64) -> Self {
        let now = OffsetDateTime::now_utc();
        Self::builder()
            .market(market)
            .from(now)
            .to(now + Duration::days(days.max(0)))
            .build()
    }

    pub fn trailing(market: impl Into<Market>, days: i64) -> Self {
        let now = OffsetDateTime::now_utc();
        Self::builder()
            .market(market)
            .from(now - Duration::days(days.max(0)))
            .to(now)
            .build()
    }

    pub fn limit(mut self, limit: usize) -> Self {
        self.limit = limit;
        self
    }

    pub fn date_kind(mut self, date_kind: DividendDateKind) -> Self {
        self.date_kind = date_kind;
        self
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct EarningsCalendarEntry {
    pub instrument: InstrumentIdentity,
    pub release_at: OffsetDateTime,
    pub release_time_code: Option<u32>,
    pub calendar_date: Option<OffsetDateTime>,
    pub eps_forecast_next_fq: Option<f64>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DividendCalendarEntry {
    pub instrument: InstrumentIdentity,
    pub effective_date: OffsetDateTime,
    pub ex_date: Option<OffsetDateTime>,
    pub payment_date: Option<OffsetDateTime>,
    pub amount: Option<f64>,
    pub yield_percent: Option<f64>,
}

#[derive(Debug, Clone, PartialEq)]
pub struct IpoCalendarEntry {
    pub instrument: InstrumentIdentity,
    pub offer_date: OffsetDateTime,
    pub offer_time_code: Option<u32>,
    pub announcement_date: Option<OffsetDateTime>,
    pub offer_price_usd: Option<f64>,
    pub deal_amount_usd: Option<f64>,
    pub market_cap_usd: Option<f64>,
    pub price_range_usd_min: Option<f64>,
    pub price_range_usd_max: Option<f64>,
    pub offered_shares: Option<f64>,
    pub offered_shares_primary: Option<f64>,
    pub offered_shares_secondary: Option<f64>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum WindowOrdering {
    Asc,
    Desc,
}

struct CalendarScanSpec<T, Decode, Date>
where
    Decode: Fn(&RowDecoder, &ScanRow) -> Option<T>,
    Date: Fn(&T) -> Option<OffsetDateTime>,
{
    sort_by: Column,
    ordering: WindowOrdering,
    columns: Vec<Column>,
    decode: Decode,
    event_date: Date,
}

impl TradingViewClient {
    pub(crate) async fn corporate_earnings_calendar(
        &self,
        request: &CalendarWindowRequest,
    ) -> Result<Vec<EarningsCalendarEntry>> {
        let columns = earnings_calendar_columns();
        scan_calendar_window(
            self,
            &request.market,
            request.from,
            request.to,
            request.limit,
            CalendarScanSpec {
                sort_by: analyst::EARNINGS_RELEASE_NEXT_DATE,
                ordering: WindowOrdering::Asc,
                columns,
                decode: decode_earnings_entry,
                event_date: EarningsCalendarEntry::event_date,
            },
        )
        .await
    }

    pub(crate) async fn corporate_dividend_calendar(
        &self,
        request: &DividendCalendarRequest,
    ) -> Result<Vec<DividendCalendarEntry>> {
        let columns = dividend_calendar_columns();
        let sort_by = match request.date_kind {
            DividendDateKind::ExDate => calendar_fields::EX_DIVIDEND_DATE_UPCOMING,
            DividendDateKind::PaymentDate => calendar_fields::PAYMENT_DATE_UPCOMING,
        };

        scan_calendar_window(
            self,
            &request.market,
            request.from,
            request.to,
            request.limit,
            CalendarScanSpec {
                sort_by,
                ordering: WindowOrdering::Asc,
                columns,
                decode: |decoder, row| decode_dividend_entry(decoder, row, request.date_kind),
                event_date: DividendCalendarEntry::event_date,
            },
        )
        .await
    }

    pub(crate) async fn corporate_ipo_calendar(
        &self,
        request: &CalendarWindowRequest,
    ) -> Result<Vec<IpoCalendarEntry>> {
        let columns = ipo_calendar_columns();
        scan_calendar_window(
            self,
            &request.market,
            request.from,
            request.to,
            request.limit,
            CalendarScanSpec {
                sort_by: calendar_fields::IPO_OFFER_DATE,
                ordering: WindowOrdering::Desc,
                columns,
                decode: decode_ipo_entry,
                event_date: IpoCalendarEntry::event_date,
            },
        )
        .await
    }
}

fn earnings_calendar_columns() -> Vec<Column> {
    merge_columns([
        identity_columns(),
        vec![
            analyst::EARNINGS_RELEASE_NEXT_DATE,
            analyst::EARNINGS_RELEASE_NEXT_CALENDAR_DATE,
            analyst::EARNINGS_RELEASE_NEXT_TIME,
            analyst::EPS_FORECAST_NEXT_FQ,
        ],
    ])
}

fn dividend_calendar_columns() -> Vec<Column> {
    merge_columns([
        identity_columns(),
        vec![
            calendar_fields::DIVIDEND_AMOUNT_UPCOMING,
            calendar_fields::DIVIDEND_YIELD_UPCOMING,
            calendar_fields::EX_DIVIDEND_DATE_UPCOMING,
            calendar_fields::PAYMENT_DATE_UPCOMING,
        ],
    ])
}

fn ipo_calendar_columns() -> Vec<Column> {
    merge_columns([
        identity_columns(),
        vec![
            calendar_fields::IPO_OFFER_DATE,
            calendar_fields::IPO_OFFER_TIME,
            calendar_fields::IPO_ANNOUNCEMENT_DATE,
            calendar_fields::IPO_OFFER_PRICE_USD,
            calendar_fields::IPO_DEAL_AMOUNT_USD,
            calendar_fields::IPO_MARKET_CAP_USD,
            calendar_fields::IPO_PRICE_RANGE_USD_MIN,
            calendar_fields::IPO_PRICE_RANGE_USD_MAX,
            calendar_fields::IPO_OFFERED_SHARES,
            calendar_fields::IPO_OFFERED_SHARES_PRIMARY,
            calendar_fields::IPO_OFFERED_SHARES_SECONDARY,
        ],
    ])
}

async fn scan_calendar_window<T, Decode, Date>(
    client: &TradingViewClient,
    market: &Market,
    from: OffsetDateTime,
    to: OffsetDateTime,
    limit: usize,
    spec: CalendarScanSpec<T, Decode, Date>,
) -> Result<Vec<T>>
where
    Decode: Fn(&RowDecoder, &ScanRow) -> Option<T>,
    Date: Fn(&T) -> Option<OffsetDateTime>,
{
    if limit == 0 || from > to {
        return Ok(Vec::new());
    }

    let CalendarScanSpec {
        sort_by,
        ordering,
        columns,
        decode,
        event_date,
    } = spec;
    let decoder = RowDecoder::new(&columns);
    let sort_order = match ordering {
        WindowOrdering::Asc => SortOrder::Asc,
        WindowOrdering::Desc => SortOrder::Desc,
    };
    let base_query = ScanQuery::new()
        .market(market.clone())
        .select(columns)
        .filter(sort_by.clone().not_empty())
        .sort(sort_by.sort(sort_order));

    let mut results = Vec::new();
    let mut offset = 0usize;

    loop {
        let query = base_query.clone().page(offset, CALENDAR_PAGE_SIZE)?;
        let response = client.scan(&query).await?;
        if response.rows.is_empty() {
            break;
        }

        let mut reached_window_end = false;
        for row in &response.rows {
            let Some(entry) = decode(&decoder, row) else {
                continue;
            };
            let Some(entry_date) = event_date(&entry) else {
                continue;
            };

            match ordering {
                WindowOrdering::Asc => {
                    if entry_date < from {
                        continue;
                    }
                    if entry_date > to {
                        reached_window_end = true;
                        break;
                    }
                    results.push(entry);
                    if results.len() >= limit {
                        return Ok(results);
                    }
                }
                WindowOrdering::Desc => {
                    if entry_date > to {
                        continue;
                    }
                    if entry_date < from {
                        reached_window_end = true;
                        break;
                    }
                    results.push(entry);
                }
            }
        }

        if reached_window_end {
            break;
        }

        offset += response.rows.len();
        if offset >= response.total_count || response.rows.len() < CALENDAR_PAGE_SIZE {
            break;
        }
    }

    if matches!(ordering, WindowOrdering::Desc) {
        results.reverse();
        if results.len() > limit {
            results.truncate(limit);
        }
    }

    Ok(results)
}

fn decode_earnings_entry(decoder: &RowDecoder, row: &ScanRow) -> Option<EarningsCalendarEntry> {
    Some(EarningsCalendarEntry {
        instrument: decoder.identity(row),
        release_at: decoder.timestamp(row, analyst::EARNINGS_RELEASE_NEXT_DATE.as_str())?,
        release_time_code: decoder.whole_number(row, analyst::EARNINGS_RELEASE_NEXT_TIME.as_str()),
        calendar_date: decoder
            .timestamp(row, analyst::EARNINGS_RELEASE_NEXT_CALENDAR_DATE.as_str()),
        eps_forecast_next_fq: decoder.number(row, analyst::EPS_FORECAST_NEXT_FQ.as_str()),
    })
}

fn decode_dividend_entry(
    decoder: &RowDecoder,
    row: &ScanRow,
    date_kind: DividendDateKind,
) -> Option<DividendCalendarEntry> {
    let ex_date = decoder.timestamp(row, calendar_fields::EX_DIVIDEND_DATE_UPCOMING.as_str());
    let payment_date = decoder.timestamp(row, calendar_fields::PAYMENT_DATE_UPCOMING.as_str());
    let effective_date = match date_kind {
        DividendDateKind::ExDate => ex_date,
        DividendDateKind::PaymentDate => payment_date,
    }?;

    Some(DividendCalendarEntry {
        instrument: decoder.identity(row),
        effective_date,
        ex_date,
        payment_date,
        amount: decoder.number(row, calendar_fields::DIVIDEND_AMOUNT_UPCOMING.as_str()),
        yield_percent: decoder.number(row, calendar_fields::DIVIDEND_YIELD_UPCOMING.as_str()),
    })
}

fn decode_ipo_entry(decoder: &RowDecoder, row: &ScanRow) -> Option<IpoCalendarEntry> {
    Some(IpoCalendarEntry {
        instrument: decoder.identity(row),
        offer_date: decoder.timestamp(row, calendar_fields::IPO_OFFER_DATE.as_str())?,
        offer_time_code: decoder.whole_number(row, calendar_fields::IPO_OFFER_TIME.as_str()),
        announcement_date: decoder.timestamp(row, calendar_fields::IPO_ANNOUNCEMENT_DATE.as_str()),
        offer_price_usd: decoder.number(row, calendar_fields::IPO_OFFER_PRICE_USD.as_str()),
        deal_amount_usd: decoder.number(row, calendar_fields::IPO_DEAL_AMOUNT_USD.as_str()),
        market_cap_usd: decoder.number(row, calendar_fields::IPO_MARKET_CAP_USD.as_str()),
        price_range_usd_min: decoder.number(row, calendar_fields::IPO_PRICE_RANGE_USD_MIN.as_str()),
        price_range_usd_max: decoder.number(row, calendar_fields::IPO_PRICE_RANGE_USD_MAX.as_str()),
        offered_shares: decoder.number(row, calendar_fields::IPO_OFFERED_SHARES.as_str()),
        offered_shares_primary: decoder
            .number(row, calendar_fields::IPO_OFFERED_SHARES_PRIMARY.as_str()),
        offered_shares_secondary: decoder
            .number(row, calendar_fields::IPO_OFFERED_SHARES_SECONDARY.as_str()),
    })
}

impl EarningsCalendarEntry {
    fn event_date(&self) -> Option<OffsetDateTime> {
        Some(self.release_at)
    }
}

impl DividendCalendarEntry {
    fn event_date(&self) -> Option<OffsetDateTime> {
        Some(self.effective_date)
    }
}

impl IpoCalendarEntry {
    fn event_date(&self) -> Option<OffsetDateTime> {
        Some(self.offer_date)
    }
}

#[cfg(test)]
mod tests;