twelve_data_client/apis/time_series_api.rs
1/*
2 * Twelve Data API
3 *
4 * ## Overview Welcome to Twelve Data developer docs — your gateway to comprehensive financial market data through a powerful and easy-to-use API. Twelve Data provides access to financial markets across over 50 global countries, covering more than 1 million public instruments, including stocks, forex, ETFs, mutual funds, commodities, and cryptocurrencies. ## Quickstart To get started, you'll need to sign up for an API key. Once you have your API key, you can start making requests to the API. ### Step 1: Create Twelve Data account Sign up on the Twelve Data website to create your account [here](https://twelvedata.com/register). This gives you access to the API dashboard and your API key. ### Step 2: Get your API key After signing in, navigate to your [dashboard](https://twelvedata.com/account/api-keys) to find your unique API key. This key is required to authenticate all API and WebSocket requests. ### Step 3: Make your first request Try a simple API call with cURL to fetch the latest price for Apple (AAPL): ``` curl \"https://api.twelvedata.com/price?symbol=AAPL&apikey=your_api_key\" ``` ### Step 4: Make a request from Python or Javascript Use our client libraries or standard HTTP clients to make API calls programmatically. Here’s an example in [Python](https://github.com/twelvedata/twelvedata-python) and JavaScript: #### Python (using official Twelve Data SDK): ```python from twelvedata import TDClient # Initialize client with your API key td = TDClient(apikey=\"your_api_key\") # Get latest price for Apple price = td.price(symbol=\"AAPL\").as_json() print(price) ``` #### JavaScript (Node.js): ```javascript const fetch = require('node-fetch'); fetch('https://api.twelvedata.com/price?symbol=AAPL&apikey=your_api_key') .then(response => response.json()) .then(data => console.log(data)); ``` ### Step 5: Perform correlation analysis between Tesla and Microsoft prices Fetch historical price data for Tesla (TSLA) and Microsoft (MSFT) and calculate the correlation of their closing prices: ```python from twelvedata import TDClient import pandas as pd # Initialize client with your API key td = TDClient(apikey=\"your_api_key\") # Fetch historical price data for Tesla tsla_ts = td.time_series( symbol=\"TSLA\", interval=\"1day\", outputsize=100 ).as_pandas() # Fetch historical price data for Microsoft msft_ts = td.time_series( symbol=\"MSFT\", interval=\"1day\", outputsize=100 ).as_pandas() # Align data on datetime index combined = pd.concat( [tsla_ts['close'].astype(float), msft_ts['close'].astype(float)], axis=1, keys=[\"TSLA\", \"MSFT\"] ).dropna() # Calculate correlation correlation = combined[\"TSLA\"].corr(combined[\"MSFT\"]) print(f\"Correlation of closing prices between TSLA and MSFT: {correlation:.2f}\") ``` ### Authentication Authenticate your requests using one of these methods: #### Query parameter method ``` GET https://api.twelvedata.com/endpoint?symbol=AAPL&apikey=your_api_key ``` #### HTTP header method (recommended) ``` Authorization: apikey your_api_key ``` ##### API key useful information <ul> <li> Demo API key (<code>apikey=demo</code>) available for demo requests</li> <li> Personal API key required for full access</li> <li> Premium endpoints and data require higher-tier plans (testable with <a href=\"https://twelvedata.com/exchanges\">trial symbols</a>)</li> </ul> ### API endpoints Service | Base URL | ---------|----------| REST API | `https://api.twelvedata.com` | WebSocket | `wss://ws.twelvedata.com` | ### Parameter guidelines <ul> <li><b>Separator:</b> Use <code>&</code> to separate multiple parameters</li> <li><b>Case sensitivity:</b> Parameter names are case-insensitive</li> <ul><li><code>symbol=AAPL</code> = <code>symbol=aapl</code></li></ul> <li><b>Multiple values:</b> Separate with commas where supported</li> </ul> ### Response handling #### Default format All responses return JSON format by default unless otherwise specified. #### Null values <b>Important:</b> Some response fields may contain `null` values when data is unavailable for specific metrics. This is expected behavior, not an error. ##### Best Practices: <ul> <li>Always implement <code>null</code> value handling in your application</li> <li>Use defensive programming techniques for data processing</li> <li>Consider fallback values or error handling for critical metrics</li> </ul> #### Error handling Structure your code to gracefully handle: <ul> <li>Network timeouts</li> <li>Rate limiting responses</li> <li>Invalid parameter errors</li> <li>Data unavailability periods</li> </ul> ##### Best practices <ul> <li><b>Rate limits:</b> Adhere to your plan’s rate limits to avoid throttling. Check your dashboard for details.</li> <li><b>Error handling:</b> Implement retry logic for transient errors (e.g., <code>429 Too Many Requests</code>).</li> <li><b>Caching:</b> Cache responses for frequently accessed data to reduce API calls and improve performance.</li> <li><b>Secure storage:</b> Store your API key securely and never expose it in client-side code or public repositories.</li> </ul> ## Errors Twelve Data API employs a standardized error response format, delivering a JSON object with `code`, `message`, and `status` keys for clear and consistent error communication. ### Codes Below is a table of possible error codes, their HTTP status, meanings, and resolution steps: Code | status | Meaning | Resolution | --- | --- | --- | --- | **400** | Bad Request | Invalid or incorrect parameter(s) provided. | Check the `message` in the response for details. Refer to the API Documentation to correct the input. | **401** | Unauthorized | Invalid or incorrect API key. | Verify your API key is correct. Sign up for a key <a href=\"https://twelvedata.com/account/api-keys\">here</a>. | **403** | Forbidden | API key lacks permissions for the requested resource (upgrade required). | Upgrade your plan <a href=\"https://twelvedata.com/pricing\">here</a>. | **404** | Not Found | Requested data could not be found. | Adjust parameters to be less strict as they may be too restrictive. | **414** | Parameter Too Long | Input parameter array exceeds the allowed length. | Follow the `message` guidance to adjust the parameter length. | **429** | Too Many Requests | API request limit reached for your key. | Wait briefly or upgrade your plan <a href=\"https://twelvedata.com/pricing\">here</a>. | **500** | Internal Server Error | Server-side issue occurred; retry later. | Contact support <a href=\"https://twelvedata.com/contact\">here</a> for assistance. | ### Example error response Consider the following invalid request: ``` https://api.twelvedata.com/time_series?symbol=AAPL&interval=0.99min&apikey=your_api_key ``` Due to the incorrect `interval` value, the API returns: ```json { \"code\": 400, \"message\": \"Invalid **interval** provided: 0.99min. Supported intervals: 1min, 5min, 15min, 30min, 45min, 1h, 2h, 4h, 8h, 1day, 1week, 1month\", \"status\": \"error\" } ``` Refer to the API Documentation for valid parameter values to resolve such errors. ## Libraries Twelve Data provides a growing ecosystem of libraries and integrations to help you build faster and smarter in your preferred environment. Official libraries are actively maintained by the Twelve Data team, while selected community-built libraries offer additional flexibility. A full list is available on our [GitHub profile](https://github.com/search?q=twelvedata). ### Official SDKs <ul> <li><b>Python:</b> <a href=\"https://github.com/twelvedata/twelvedata-python\">twelvedata-python</a></li> <li><b>R:</b> <a href=\"https://github.com/twelvedata/twelvedata-r-sdk\">twelvedata-r-sdk</a></li> </ul> ### AI integrations <ul> <li><b>Twelve Data MCP Server:</b> <a href=\"https://github.com/twelvedata/mcp\">Repository</a> — Model Context Protocol (MCP) server that provides seamless integration with AI assistants and language models, enabling direct access to Twelve Data's financial market data within conversational interfaces and AI workflows.</li> </ul> ### Spreadsheet add-ons <ul> <li><b>Excel:</b> <a href=\"https://twelvedata.com/excel\">Excel Add-in</a></li> <li><b>Google Sheets:</b> <a href=\"https://twelvedata.com/google-sheets\">Google Sheets Add-on</a></li> </ul> ### Community libraries The community has developed libraries in several popular languages. You can explore more community libraries on [GitHub](https://github.com/search?q=twelvedata). <ul> <li><b>C#:</b> <a href=\"https://github.com/pseudomarkets/TwelveDataSharp\">TwelveDataSharp</a></li> <li><b>JavaScript:</b> <a href=\"https://github.com/evzaboun/twelvedata\">twelvedata</a></li> <li><b>PHP:</b> <a href=\"https://github.com/ingelby/twelvedata\">twelvedata</a></li> <li><b>Go:</b> <a href=\"https://github.com/soulgarden/twelvedata\">twelvedata</a></li> <li><b>TypeScript:</b> <a href=\"https://github.com/Clyde-Goodall/twelve-data-wrapper\">twelve-data-wrapper</a></li> </ul> ### Other Twelve Data repositories <ul> <li><b>searchindex</b> <i>(Go)</i>: <a href=\"https://github.com/twelvedata/searchindex\">Repository</a> — In-memory search index by strings</li> <li><b>ws-tools</b> <i>(Python)</i>: <a href=\"https://github.com/twelvedata/ws-tools\">Repository</a> — Utility tools for WebSocket stream handling</li> </ul> ### API specification <ul> <li><b>OpenAPI / Swagger:</b> Access the <a href=\"https://api.twelvedata.com/doc/swagger/openapi.json\">complete API specification</a> in OpenAPI format. You can use this file to automatically generate client libraries in your preferred programming language, explore the API interactively via Swagger tools, or integrate Twelve Data seamlessly into your AI and LLM workflows.</li> </ul>
5 *
6 * The version of the OpenAPI document: 0.0.1
7 *
8 * Generated by: https://openapi-generator.tech
9 */
10
11use super::{configuration, ContentType, Error};
12use crate::{apis::ResponseContent, models};
13use reqwest;
14use serde::{de::Error as _, Deserialize, Serialize};
15
16/// struct for passing parameters to the method [`get_time_series`]
17#[derive(Clone, Debug, Default, Serialize, Deserialize)]
18pub struct GetTimeSeriesParams {
19 /// Interval between two consecutive points in time series
20 pub interval: String,
21 /// Symbol ticker of the instrument. E.g. `AAPL`, `EUR/USD`, `ETH/BTC`, ...
22 pub symbol: Option<String>,
23 /// Filter by international securities identification number (ISIN)
24 pub isin: Option<String>,
25 /// The FIGI of an instrument for which data is requested
26 pub figi: Option<String>,
27 /// The CUSIP of an instrument for which data is requested. CUSIP access is activating in the <a href=\"https://twelvedata.com/account/add-ons\">Add-ons</a> section
28 pub cusip: Option<String>,
29 /// Number of data points to retrieve. Supports values in the range from `1` to `5000`. Default `30` when no date parameters are set, otherwise set to maximum
30 pub outputsize: Option<i64>,
31 /// Exchange where instrument is traded
32 pub exchange: Option<String>,
33 /// Market Identifier Code (MIC) under ISO 10383 standard
34 pub mic_code: Option<String>,
35 /// The country where the instrument is traded, e.g., `United States` or `US`
36 pub country: Option<String>,
37 /// The asset class to which the instrument belongs
38 pub r#type: Option<String>,
39 /// Timezone at which output datetime will be displayed. Supports: <ul> <li>1. <code>Exchange</code> for local exchange time</li> <li>2. <code>UTC</code> for datetime at universal UTC standard</li> <li>3. Timezone name according to the IANA Time Zone Database. E.g. <code>America/New_York</code>, <code>Asia/Singapore</code>. Full list of timezones can be found <a href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" target=\"blank\">here</a></li> </ul> <i>Take note that the IANA Timezone name is case-sensitive</i>
40 pub timezone: Option<String>,
41 /// Can be used separately and together with `end_date`. Format `2006-01-02` or `2006-01-02T15:04:05` Default location: <ul> <li>Forex and Cryptocurrencies - <code>UTC</code></li> <li>Stocks - where exchange is located (e.g. for AAPL it will be <code>America/New_York</code>)</li> </ul> Both parameters take into account if <code>timezone</code> parameter is provided.<br/> If <code>timezone</code> is given then, <code>start_date</code> and <code>end_date</code> will be used in the specified location Examples: <ul> <li>1. <code>&symbol=AAPL&start_date=2019-08-09T15:50:00&…</code><br/> Returns all records starting from 2019-08-09T15:50:00 New York time up to current date</li> <li>2. <code>&symbol=EUR/USD&timezone=Asia/Singapore&start_date=2019-08-09T15:50:00&…</code><br/> Returns all records starting from 2019-08-09T15:50:00 Singapore time up to current date</li> <li>3. <code>&symbol=ETH/BTC&timezone=Europe/Zurich&start_date=2019-08-09T15:50:00&end_date=2019-08-09T15:55:00&...</code><br/> Returns all records starting from 2019-08-09T15:50:00 Zurich time up to 2019-08-09T15:55:00</li> </ul>
42 pub start_date: Option<String>,
43 /// The ending date and time for data selection, see `start_date` description for details.
44 pub end_date: Option<String>,
45 /// Specifies the exact date to get the data for. Could be the exact date, e.g. `2021-10-27`, or in human language `today` or `yesterday`
46 pub date: Option<String>,
47 /// Sorting order of the output
48 pub order: Option<String>,
49 /// Returns quotes that include pre-market and post-market data. Only for `Pro` and above plans. Available at the `1min`, `5min`, `15min`, and `30min` intervals for US equities. Open, high, low, close values are supplied without volume
50 pub prepost: Option<bool>,
51 /// The format of the response data
52 pub format: Option<String>,
53 /// The separator used in the CSV response data
54 pub delimiter: Option<String>,
55 /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive. By default, the number of decimal places is automatically determined based on the values provided
56 pub dp: Option<i64>,
57 /// A boolean parameter to include the previous closing price in the time_series data. If true, adds previous bar close price value to the current object
58 pub previous_close: Option<bool>,
59 /// Adjusting mode for prices
60 pub adjust: Option<String>,
61}
62
63impl GetTimeSeriesParams {
64 /// Create a new builder for this parameter struct
65 pub fn builder() -> GetTimeSeriesParamsBuilder {
66 GetTimeSeriesParamsBuilder::default()
67 }
68}
69
70/// Builder for [`GetTimeSeriesParams`]
71#[derive(Clone, Debug, Default)]
72pub struct GetTimeSeriesParamsBuilder {
73 /// Interval between two consecutive points in time series
74 interval: String,
75 /// Symbol ticker of the instrument. E.g. `AAPL`, `EUR/USD`, `ETH/BTC`, ...
76 symbol: Option<String>,
77 /// Filter by international securities identification number (ISIN)
78 isin: Option<String>,
79 /// The FIGI of an instrument for which data is requested
80 figi: Option<String>,
81 /// The CUSIP of an instrument for which data is requested. CUSIP access is activating in the <a href=\"https://twelvedata.com/account/add-ons\">Add-ons</a> section
82 cusip: Option<String>,
83 /// Number of data points to retrieve. Supports values in the range from `1` to `5000`. Default `30` when no date parameters are set, otherwise set to maximum
84 outputsize: Option<i64>,
85 /// Exchange where instrument is traded
86 exchange: Option<String>,
87 /// Market Identifier Code (MIC) under ISO 10383 standard
88 mic_code: Option<String>,
89 /// The country where the instrument is traded, e.g., `United States` or `US`
90 country: Option<String>,
91 /// The asset class to which the instrument belongs
92 r#type: Option<String>,
93 /// Timezone at which output datetime will be displayed. Supports: <ul> <li>1. <code>Exchange</code> for local exchange time</li> <li>2. <code>UTC</code> for datetime at universal UTC standard</li> <li>3. Timezone name according to the IANA Time Zone Database. E.g. <code>America/New_York</code>, <code>Asia/Singapore</code>. Full list of timezones can be found <a href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" target=\"blank\">here</a></li> </ul> <i>Take note that the IANA Timezone name is case-sensitive</i>
94 timezone: Option<String>,
95 /// Can be used separately and together with `end_date`. Format `2006-01-02` or `2006-01-02T15:04:05` Default location: <ul> <li>Forex and Cryptocurrencies - <code>UTC</code></li> <li>Stocks - where exchange is located (e.g. for AAPL it will be <code>America/New_York</code>)</li> </ul> Both parameters take into account if <code>timezone</code> parameter is provided.<br/> If <code>timezone</code> is given then, <code>start_date</code> and <code>end_date</code> will be used in the specified location Examples: <ul> <li>1. <code>&symbol=AAPL&start_date=2019-08-09T15:50:00&…</code><br/> Returns all records starting from 2019-08-09T15:50:00 New York time up to current date</li> <li>2. <code>&symbol=EUR/USD&timezone=Asia/Singapore&start_date=2019-08-09T15:50:00&…</code><br/> Returns all records starting from 2019-08-09T15:50:00 Singapore time up to current date</li> <li>3. <code>&symbol=ETH/BTC&timezone=Europe/Zurich&start_date=2019-08-09T15:50:00&end_date=2019-08-09T15:55:00&...</code><br/> Returns all records starting from 2019-08-09T15:50:00 Zurich time up to 2019-08-09T15:55:00</li> </ul>
96 start_date: Option<String>,
97 /// The ending date and time for data selection, see `start_date` description for details.
98 end_date: Option<String>,
99 /// Specifies the exact date to get the data for. Could be the exact date, e.g. `2021-10-27`, or in human language `today` or `yesterday`
100 date: Option<String>,
101 /// Sorting order of the output
102 order: Option<String>,
103 /// Returns quotes that include pre-market and post-market data. Only for `Pro` and above plans. Available at the `1min`, `5min`, `15min`, and `30min` intervals for US equities. Open, high, low, close values are supplied without volume
104 prepost: Option<bool>,
105 /// The format of the response data
106 format: Option<String>,
107 /// The separator used in the CSV response data
108 delimiter: Option<String>,
109 /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive. By default, the number of decimal places is automatically determined based on the values provided
110 dp: Option<i64>,
111 /// A boolean parameter to include the previous closing price in the time_series data. If true, adds previous bar close price value to the current object
112 previous_close: Option<bool>,
113 /// Adjusting mode for prices
114 adjust: Option<String>,
115}
116
117impl GetTimeSeriesParamsBuilder {
118 /// Interval between two consecutive points in time series
119 pub fn interval(mut self, interval: impl Into<String>) -> Self {
120 self.interval = interval.into();
121 self
122 }
123 /// Symbol ticker of the instrument. E.g. `AAPL`, `EUR/USD`, `ETH/BTC`, ...
124 pub fn symbol(mut self, symbol: impl Into<String>) -> Self {
125 self.symbol = Some(symbol.into());
126 self
127 }
128 /// Filter by international securities identification number (ISIN)
129 pub fn isin(mut self, isin: impl Into<String>) -> Self {
130 self.isin = Some(isin.into());
131 self
132 }
133 /// The FIGI of an instrument for which data is requested
134 pub fn figi(mut self, figi: impl Into<String>) -> Self {
135 self.figi = Some(figi.into());
136 self
137 }
138 /// The CUSIP of an instrument for which data is requested. CUSIP access is activating in the <a href=\"https://twelvedata.com/account/add-ons\">Add-ons</a> section
139 pub fn cusip(mut self, cusip: impl Into<String>) -> Self {
140 self.cusip = Some(cusip.into());
141 self
142 }
143 /// Number of data points to retrieve. Supports values in the range from `1` to `5000`. Default `30` when no date parameters are set, otherwise set to maximum
144 pub fn outputsize(mut self, outputsize: i64) -> Self {
145 self.outputsize = Some(outputsize);
146 self
147 }
148 /// Exchange where instrument is traded
149 pub fn exchange(mut self, exchange: impl Into<String>) -> Self {
150 self.exchange = Some(exchange.into());
151 self
152 }
153 /// Market Identifier Code (MIC) under ISO 10383 standard
154 pub fn mic_code(mut self, mic_code: impl Into<String>) -> Self {
155 self.mic_code = Some(mic_code.into());
156 self
157 }
158 /// The country where the instrument is traded, e.g., `United States` or `US`
159 pub fn country(mut self, country: impl Into<String>) -> Self {
160 self.country = Some(country.into());
161 self
162 }
163 /// The asset class to which the instrument belongs
164 pub fn r#type(mut self, r#type: impl Into<String>) -> Self {
165 self.r#type = Some(r#type.into());
166 self
167 }
168 /// Timezone at which output datetime will be displayed. Supports: <ul> <li>1. <code>Exchange</code> for local exchange time</li> <li>2. <code>UTC</code> for datetime at universal UTC standard</li> <li>3. Timezone name according to the IANA Time Zone Database. E.g. <code>America/New_York</code>, <code>Asia/Singapore</code>. Full list of timezones can be found <a href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" target=\"blank\">here</a></li> </ul> <i>Take note that the IANA Timezone name is case-sensitive</i>
169 pub fn timezone(mut self, timezone: impl Into<String>) -> Self {
170 self.timezone = Some(timezone.into());
171 self
172 }
173 /// Can be used separately and together with `end_date`. Format `2006-01-02` or `2006-01-02T15:04:05` Default location: <ul> <li>Forex and Cryptocurrencies - <code>UTC</code></li> <li>Stocks - where exchange is located (e.g. for AAPL it will be <code>America/New_York</code>)</li> </ul> Both parameters take into account if <code>timezone</code> parameter is provided.<br/> If <code>timezone</code> is given then, <code>start_date</code> and <code>end_date</code> will be used in the specified location Examples: <ul> <li>1. <code>&symbol=AAPL&start_date=2019-08-09T15:50:00&…</code><br/> Returns all records starting from 2019-08-09T15:50:00 New York time up to current date</li> <li>2. <code>&symbol=EUR/USD&timezone=Asia/Singapore&start_date=2019-08-09T15:50:00&…</code><br/> Returns all records starting from 2019-08-09T15:50:00 Singapore time up to current date</li> <li>3. <code>&symbol=ETH/BTC&timezone=Europe/Zurich&start_date=2019-08-09T15:50:00&end_date=2019-08-09T15:55:00&...</code><br/> Returns all records starting from 2019-08-09T15:50:00 Zurich time up to 2019-08-09T15:55:00</li> </ul>
174 pub fn start_date(mut self, start_date: impl Into<String>) -> Self {
175 self.start_date = Some(start_date.into());
176 self
177 }
178 /// The ending date and time for data selection, see `start_date` description for details.
179 pub fn end_date(mut self, end_date: impl Into<String>) -> Self {
180 self.end_date = Some(end_date.into());
181 self
182 }
183 /// Specifies the exact date to get the data for. Could be the exact date, e.g. `2021-10-27`, or in human language `today` or `yesterday`
184 pub fn date(mut self, date: impl Into<String>) -> Self {
185 self.date = Some(date.into());
186 self
187 }
188 /// Sorting order of the output
189 pub fn order(mut self, order: impl Into<String>) -> Self {
190 self.order = Some(order.into());
191 self
192 }
193 /// Returns quotes that include pre-market and post-market data. Only for `Pro` and above plans. Available at the `1min`, `5min`, `15min`, and `30min` intervals for US equities. Open, high, low, close values are supplied without volume
194 pub fn prepost(mut self, prepost: bool) -> Self {
195 self.prepost = Some(prepost);
196 self
197 }
198 /// The format of the response data
199 pub fn format(mut self, format: impl Into<String>) -> Self {
200 self.format = Some(format.into());
201 self
202 }
203 /// The separator used in the CSV response data
204 pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
205 self.delimiter = Some(delimiter.into());
206 self
207 }
208 /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive. By default, the number of decimal places is automatically determined based on the values provided
209 pub fn dp(mut self, dp: i64) -> Self {
210 self.dp = Some(dp);
211 self
212 }
213 /// A boolean parameter to include the previous closing price in the time_series data. If true, adds previous bar close price value to the current object
214 pub fn previous_close(mut self, previous_close: bool) -> Self {
215 self.previous_close = Some(previous_close);
216 self
217 }
218 /// Adjusting mode for prices
219 pub fn adjust(mut self, adjust: impl Into<String>) -> Self {
220 self.adjust = Some(adjust.into());
221 self
222 }
223
224 /// Build the parameter struct
225 pub fn build(self) -> GetTimeSeriesParams {
226 GetTimeSeriesParams {
227 interval: self.interval,
228 symbol: self.symbol,
229 isin: self.isin,
230 figi: self.figi,
231 cusip: self.cusip,
232 outputsize: self.outputsize,
233 exchange: self.exchange,
234 mic_code: self.mic_code,
235 country: self.country,
236 r#type: self.r#type,
237 timezone: self.timezone,
238 start_date: self.start_date,
239 end_date: self.end_date,
240 date: self.date,
241 order: self.order,
242 prepost: self.prepost,
243 format: self.format,
244 delimiter: self.delimiter,
245 dp: self.dp,
246 previous_close: self.previous_close,
247 adjust: self.adjust,
248 }
249 }
250}
251
252/// struct for passing parameters to the method [`get_time_series_cross`]
253#[derive(Clone, Debug, Default, Serialize, Deserialize)]
254pub struct GetTimeSeriesCrossParams {
255 /// Base currency symbol
256 pub base: String,
257 /// Quote currency symbol
258 pub quote: String,
259 /// Interval between two consecutive points in time series
260 pub interval: String,
261 /// Base instrument type according to the `/instrument_type` endpoint
262 pub base_type: Option<String>,
263 /// Base exchange
264 pub base_exchange: Option<String>,
265 /// Base MIC code
266 pub base_mic_code: Option<String>,
267 /// Quote instrument type according to the `/instrument_type` endpoint
268 pub quote_type: Option<String>,
269 /// Quote exchange
270 pub quote_exchange: Option<String>,
271 /// Quote MIC code
272 pub quote_mic_code: Option<String>,
273 /// Number of data points to retrieve. Supports values in the range from `1` to `5000`. Default `30` when no date parameters are set, otherwise set to maximum
274 pub outputsize: Option<i64>,
275 /// Format of the response data
276 pub format: Option<String>,
277 /// Delimiter used in CSV file
278 pub delimiter: Option<String>,
279 /// Only for `Pro` and above plans. Available at the `1min`, `5min`, `15min`, and `30min` intervals for US equities. Open, high, low, close values are supplied without volume.
280 pub prepost: Option<bool>,
281 /// Start date for the time series data
282 pub start_date: Option<String>,
283 /// End date for the time series data
284 pub end_date: Option<String>,
285 /// Specifies if there should be an adjustment
286 pub adjust: Option<bool>,
287 /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive.
288 pub dp: Option<i64>,
289 /// Timezone at which output datetime will be displayed. Supports: <ul> <li>1. <code>Exchange</code> for local exchange time</li> <li>2. <code>UTC</code> for datetime at universal UTC standard</li> <li>3. Timezone name according to the IANA Time Zone Database. E.g. <code>America/New_York</code>, <code>Asia/Singapore</code>. Full list of timezones can be found <a href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" target=\"blank\">here</a>.</li> </ul> <i>Take note that the IANA Timezone name is case-sensitive</i>
290 pub timezone: Option<String>,
291}
292
293impl GetTimeSeriesCrossParams {
294 /// Create a new builder for this parameter struct
295 pub fn builder() -> GetTimeSeriesCrossParamsBuilder {
296 GetTimeSeriesCrossParamsBuilder::default()
297 }
298}
299
300/// Builder for [`GetTimeSeriesCrossParams`]
301#[derive(Clone, Debug, Default)]
302pub struct GetTimeSeriesCrossParamsBuilder {
303 /// Base currency symbol
304 base: String,
305 /// Quote currency symbol
306 quote: String,
307 /// Interval between two consecutive points in time series
308 interval: String,
309 /// Base instrument type according to the `/instrument_type` endpoint
310 base_type: Option<String>,
311 /// Base exchange
312 base_exchange: Option<String>,
313 /// Base MIC code
314 base_mic_code: Option<String>,
315 /// Quote instrument type according to the `/instrument_type` endpoint
316 quote_type: Option<String>,
317 /// Quote exchange
318 quote_exchange: Option<String>,
319 /// Quote MIC code
320 quote_mic_code: Option<String>,
321 /// Number of data points to retrieve. Supports values in the range from `1` to `5000`. Default `30` when no date parameters are set, otherwise set to maximum
322 outputsize: Option<i64>,
323 /// Format of the response data
324 format: Option<String>,
325 /// Delimiter used in CSV file
326 delimiter: Option<String>,
327 /// Only for `Pro` and above plans. Available at the `1min`, `5min`, `15min`, and `30min` intervals for US equities. Open, high, low, close values are supplied without volume.
328 prepost: Option<bool>,
329 /// Start date for the time series data
330 start_date: Option<String>,
331 /// End date for the time series data
332 end_date: Option<String>,
333 /// Specifies if there should be an adjustment
334 adjust: Option<bool>,
335 /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive.
336 dp: Option<i64>,
337 /// Timezone at which output datetime will be displayed. Supports: <ul> <li>1. <code>Exchange</code> for local exchange time</li> <li>2. <code>UTC</code> for datetime at universal UTC standard</li> <li>3. Timezone name according to the IANA Time Zone Database. E.g. <code>America/New_York</code>, <code>Asia/Singapore</code>. Full list of timezones can be found <a href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" target=\"blank\">here</a>.</li> </ul> <i>Take note that the IANA Timezone name is case-sensitive</i>
338 timezone: Option<String>,
339}
340
341impl GetTimeSeriesCrossParamsBuilder {
342 /// Base currency symbol
343 pub fn base(mut self, base: impl Into<String>) -> Self {
344 self.base = base.into();
345 self
346 }
347 /// Quote currency symbol
348 pub fn quote(mut self, quote: impl Into<String>) -> Self {
349 self.quote = quote.into();
350 self
351 }
352 /// Interval between two consecutive points in time series
353 pub fn interval(mut self, interval: impl Into<String>) -> Self {
354 self.interval = interval.into();
355 self
356 }
357 /// Base instrument type according to the `/instrument_type` endpoint
358 pub fn base_type(mut self, base_type: impl Into<String>) -> Self {
359 self.base_type = Some(base_type.into());
360 self
361 }
362 /// Base exchange
363 pub fn base_exchange(mut self, base_exchange: impl Into<String>) -> Self {
364 self.base_exchange = Some(base_exchange.into());
365 self
366 }
367 /// Base MIC code
368 pub fn base_mic_code(mut self, base_mic_code: impl Into<String>) -> Self {
369 self.base_mic_code = Some(base_mic_code.into());
370 self
371 }
372 /// Quote instrument type according to the `/instrument_type` endpoint
373 pub fn quote_type(mut self, quote_type: impl Into<String>) -> Self {
374 self.quote_type = Some(quote_type.into());
375 self
376 }
377 /// Quote exchange
378 pub fn quote_exchange(mut self, quote_exchange: impl Into<String>) -> Self {
379 self.quote_exchange = Some(quote_exchange.into());
380 self
381 }
382 /// Quote MIC code
383 pub fn quote_mic_code(mut self, quote_mic_code: impl Into<String>) -> Self {
384 self.quote_mic_code = Some(quote_mic_code.into());
385 self
386 }
387 /// Number of data points to retrieve. Supports values in the range from `1` to `5000`. Default `30` when no date parameters are set, otherwise set to maximum
388 pub fn outputsize(mut self, outputsize: i64) -> Self {
389 self.outputsize = Some(outputsize);
390 self
391 }
392 /// Format of the response data
393 pub fn format(mut self, format: impl Into<String>) -> Self {
394 self.format = Some(format.into());
395 self
396 }
397 /// Delimiter used in CSV file
398 pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
399 self.delimiter = Some(delimiter.into());
400 self
401 }
402 /// Only for `Pro` and above plans. Available at the `1min`, `5min`, `15min`, and `30min` intervals for US equities. Open, high, low, close values are supplied without volume.
403 pub fn prepost(mut self, prepost: bool) -> Self {
404 self.prepost = Some(prepost);
405 self
406 }
407 /// Start date for the time series data
408 pub fn start_date(mut self, start_date: impl Into<String>) -> Self {
409 self.start_date = Some(start_date.into());
410 self
411 }
412 /// End date for the time series data
413 pub fn end_date(mut self, end_date: impl Into<String>) -> Self {
414 self.end_date = Some(end_date.into());
415 self
416 }
417 /// Specifies if there should be an adjustment
418 pub fn adjust(mut self, adjust: bool) -> Self {
419 self.adjust = Some(adjust);
420 self
421 }
422 /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive.
423 pub fn dp(mut self, dp: i64) -> Self {
424 self.dp = Some(dp);
425 self
426 }
427 /// Timezone at which output datetime will be displayed. Supports: <ul> <li>1. <code>Exchange</code> for local exchange time</li> <li>2. <code>UTC</code> for datetime at universal UTC standard</li> <li>3. Timezone name according to the IANA Time Zone Database. E.g. <code>America/New_York</code>, <code>Asia/Singapore</code>. Full list of timezones can be found <a href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" target=\"blank\">here</a>.</li> </ul> <i>Take note that the IANA Timezone name is case-sensitive</i>
428 pub fn timezone(mut self, timezone: impl Into<String>) -> Self {
429 self.timezone = Some(timezone.into());
430 self
431 }
432
433 /// Build the parameter struct
434 pub fn build(self) -> GetTimeSeriesCrossParams {
435 GetTimeSeriesCrossParams {
436 base: self.base,
437 quote: self.quote,
438 interval: self.interval,
439 base_type: self.base_type,
440 base_exchange: self.base_exchange,
441 base_mic_code: self.base_mic_code,
442 quote_type: self.quote_type,
443 quote_exchange: self.quote_exchange,
444 quote_mic_code: self.quote_mic_code,
445 outputsize: self.outputsize,
446 format: self.format,
447 delimiter: self.delimiter,
448 prepost: self.prepost,
449 start_date: self.start_date,
450 end_date: self.end_date,
451 adjust: self.adjust,
452 dp: self.dp,
453 timezone: self.timezone,
454 }
455 }
456}
457
458/// struct for typed errors of method [`get_time_series`]
459#[derive(Debug, Clone, Serialize, Deserialize)]
460#[serde(untagged)]
461pub enum GetTimeSeriesError {
462 UnknownValue(serde_json::Value),
463}
464
465/// struct for typed errors of method [`get_time_series_cross`]
466#[derive(Debug, Clone, Serialize, Deserialize)]
467#[serde(untagged)]
468pub enum GetTimeSeriesCrossError {
469 UnknownValue(serde_json::Value),
470}
471
472/// The time series endpoint provides detailed historical data for a specified financial instrument. It returns two main components: metadata, which includes essential information about the instrument, and a time series dataset. The time series consists of chronological entries with Open, High, Low, and Close prices, and for applicable instruments, it also includes trading volume. This endpoint is ideal for retrieving comprehensive historical price data for analysis or visualization purposes.
473pub async fn get_time_series(
474 configuration: &configuration::Configuration,
475 params: GetTimeSeriesParams,
476) -> Result<models::GetTimeSeriesResponse, Error<GetTimeSeriesError>> {
477 // Extract parameters from params struct
478 let p_query_interval = params.interval;
479 let p_query_symbol = params.symbol;
480 let p_query_isin = params.isin;
481 let p_query_figi = params.figi;
482 let p_query_cusip = params.cusip;
483 let p_query_outputsize = params.outputsize;
484 let p_query_exchange = params.exchange;
485 let p_query_mic_code = params.mic_code;
486 let p_query_country = params.country;
487 let p_query_type = params.r#type;
488 let p_query_timezone = params.timezone;
489 let p_query_start_date = params.start_date;
490 let p_query_end_date = params.end_date;
491 let p_query_date = params.date;
492 let p_query_order = params.order;
493 let p_query_prepost = params.prepost;
494 let p_query_format = params.format;
495 let p_query_delimiter = params.delimiter;
496 let p_query_dp = params.dp;
497 let p_query_previous_close = params.previous_close;
498 let p_query_adjust = params.adjust;
499
500 let uri_str = format!("{}/time_series", configuration.base_path);
501 let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
502
503 if let Some(ref param_value) = p_query_symbol {
504 req_builder = req_builder.query(&[("symbol", ¶m_value.to_string())]);
505 }
506 if let Some(ref param_value) = p_query_isin {
507 req_builder = req_builder.query(&[("isin", ¶m_value.to_string())]);
508 }
509 if let Some(ref param_value) = p_query_figi {
510 req_builder = req_builder.query(&[("figi", ¶m_value.to_string())]);
511 }
512 if let Some(ref param_value) = p_query_cusip {
513 req_builder = req_builder.query(&[("cusip", ¶m_value.to_string())]);
514 }
515 req_builder = req_builder.query(&[("interval", &p_query_interval.to_string())]);
516 if let Some(ref param_value) = p_query_outputsize {
517 req_builder = req_builder.query(&[("outputsize", ¶m_value.to_string())]);
518 }
519 if let Some(ref param_value) = p_query_exchange {
520 req_builder = req_builder.query(&[("exchange", ¶m_value.to_string())]);
521 }
522 if let Some(ref param_value) = p_query_mic_code {
523 req_builder = req_builder.query(&[("mic_code", ¶m_value.to_string())]);
524 }
525 if let Some(ref param_value) = p_query_country {
526 req_builder = req_builder.query(&[("country", ¶m_value.to_string())]);
527 }
528 if let Some(ref param_value) = p_query_type {
529 req_builder = req_builder.query(&[("type", ¶m_value.to_string())]);
530 }
531 if let Some(ref param_value) = p_query_timezone {
532 req_builder = req_builder.query(&[("timezone", ¶m_value.to_string())]);
533 }
534 if let Some(ref param_value) = p_query_start_date {
535 req_builder = req_builder.query(&[("start_date", ¶m_value.to_string())]);
536 }
537 if let Some(ref param_value) = p_query_end_date {
538 req_builder = req_builder.query(&[("end_date", ¶m_value.to_string())]);
539 }
540 if let Some(ref param_value) = p_query_date {
541 req_builder = req_builder.query(&[("date", ¶m_value.to_string())]);
542 }
543 if let Some(ref param_value) = p_query_order {
544 req_builder = req_builder.query(&[("order", ¶m_value.to_string())]);
545 }
546 if let Some(ref param_value) = p_query_prepost {
547 req_builder = req_builder.query(&[("prepost", ¶m_value.to_string())]);
548 }
549 if let Some(ref param_value) = p_query_format {
550 req_builder = req_builder.query(&[("format", ¶m_value.to_string())]);
551 }
552 if let Some(ref param_value) = p_query_delimiter {
553 req_builder = req_builder.query(&[("delimiter", ¶m_value.to_string())]);
554 }
555 if let Some(ref param_value) = p_query_dp {
556 req_builder = req_builder.query(&[("dp", ¶m_value.to_string())]);
557 }
558 if let Some(ref param_value) = p_query_previous_close {
559 req_builder = req_builder.query(&[("previous_close", ¶m_value.to_string())]);
560 }
561 if let Some(ref param_value) = p_query_adjust {
562 req_builder = req_builder.query(&[("adjust", ¶m_value.to_string())]);
563 }
564 if let Some(ref user_agent) = configuration.user_agent {
565 req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
566 }
567 if let Some(ref apikey) = configuration.api_key {
568 let key = apikey.key.clone();
569 let value = match apikey.prefix {
570 Some(ref prefix) => format!("{} {}", prefix, key),
571 None => key,
572 };
573 req_builder = req_builder.header("Authorization", value);
574 };
575
576 let req = req_builder.build()?;
577 let resp = configuration.client.execute(req).await?;
578
579 let status = resp.status();
580 let content_type = resp
581 .headers()
582 .get("content-type")
583 .and_then(|v| v.to_str().ok())
584 .unwrap_or("application/octet-stream");
585 let content_type = super::ContentType::from(content_type);
586
587 if !status.is_client_error() && !status.is_server_error() {
588 let content = resp.text().await?;
589 match content_type {
590 ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
591 ContentType::Text => return Ok(models::GetTimeSeriesResponse::Text(content)),
592 ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetTimeSeriesResponse`")))),
593 }
594 } else {
595 let content = resp.text().await?;
596 let entity: Option<GetTimeSeriesError> = serde_json::from_str(&content).ok();
597 Err(Error::ResponseError(ResponseContent {
598 status,
599 content,
600 entity,
601 }))
602 }
603}
604
605/// The Time Series Cross endpoint calculates and returns historical cross-rate data for exotic forex pairs, cryptocurrencies, or stocks (e.g., Apple Inc. price in Indian Rupees) on the fly. It provides metadata about the requested symbol and a time series array with Open, High, Low, and Close prices, sorted descending by time, enabling analysis of price history and market trends.
606pub async fn get_time_series_cross(
607 configuration: &configuration::Configuration,
608 params: GetTimeSeriesCrossParams,
609) -> Result<models::GetTimeSeriesCrossResponse, Error<GetTimeSeriesCrossError>> {
610 // Extract parameters from params struct
611 let p_query_base = params.base;
612 let p_query_quote = params.quote;
613 let p_query_interval = params.interval;
614 let p_query_base_type = params.base_type;
615 let p_query_base_exchange = params.base_exchange;
616 let p_query_base_mic_code = params.base_mic_code;
617 let p_query_quote_type = params.quote_type;
618 let p_query_quote_exchange = params.quote_exchange;
619 let p_query_quote_mic_code = params.quote_mic_code;
620 let p_query_outputsize = params.outputsize;
621 let p_query_format = params.format;
622 let p_query_delimiter = params.delimiter;
623 let p_query_prepost = params.prepost;
624 let p_query_start_date = params.start_date;
625 let p_query_end_date = params.end_date;
626 let p_query_adjust = params.adjust;
627 let p_query_dp = params.dp;
628 let p_query_timezone = params.timezone;
629
630 let uri_str = format!("{}/time_series/cross", configuration.base_path);
631 let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
632
633 req_builder = req_builder.query(&[("base", &p_query_base.to_string())]);
634 if let Some(ref param_value) = p_query_base_type {
635 req_builder = req_builder.query(&[("base_type", ¶m_value.to_string())]);
636 }
637 if let Some(ref param_value) = p_query_base_exchange {
638 req_builder = req_builder.query(&[("base_exchange", ¶m_value.to_string())]);
639 }
640 if let Some(ref param_value) = p_query_base_mic_code {
641 req_builder = req_builder.query(&[("base_mic_code", ¶m_value.to_string())]);
642 }
643 req_builder = req_builder.query(&[("quote", &p_query_quote.to_string())]);
644 if let Some(ref param_value) = p_query_quote_type {
645 req_builder = req_builder.query(&[("quote_type", ¶m_value.to_string())]);
646 }
647 if let Some(ref param_value) = p_query_quote_exchange {
648 req_builder = req_builder.query(&[("quote_exchange", ¶m_value.to_string())]);
649 }
650 if let Some(ref param_value) = p_query_quote_mic_code {
651 req_builder = req_builder.query(&[("quote_mic_code", ¶m_value.to_string())]);
652 }
653 req_builder = req_builder.query(&[("interval", &p_query_interval.to_string())]);
654 if let Some(ref param_value) = p_query_outputsize {
655 req_builder = req_builder.query(&[("outputsize", ¶m_value.to_string())]);
656 }
657 if let Some(ref param_value) = p_query_format {
658 req_builder = req_builder.query(&[("format", ¶m_value.to_string())]);
659 }
660 if let Some(ref param_value) = p_query_delimiter {
661 req_builder = req_builder.query(&[("delimiter", ¶m_value.to_string())]);
662 }
663 if let Some(ref param_value) = p_query_prepost {
664 req_builder = req_builder.query(&[("prepost", ¶m_value.to_string())]);
665 }
666 if let Some(ref param_value) = p_query_start_date {
667 req_builder = req_builder.query(&[("start_date", ¶m_value.to_string())]);
668 }
669 if let Some(ref param_value) = p_query_end_date {
670 req_builder = req_builder.query(&[("end_date", ¶m_value.to_string())]);
671 }
672 if let Some(ref param_value) = p_query_adjust {
673 req_builder = req_builder.query(&[("adjust", ¶m_value.to_string())]);
674 }
675 if let Some(ref param_value) = p_query_dp {
676 req_builder = req_builder.query(&[("dp", ¶m_value.to_string())]);
677 }
678 if let Some(ref param_value) = p_query_timezone {
679 req_builder = req_builder.query(&[("timezone", ¶m_value.to_string())]);
680 }
681 if let Some(ref user_agent) = configuration.user_agent {
682 req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
683 }
684 if let Some(ref apikey) = configuration.api_key {
685 let key = apikey.key.clone();
686 let value = match apikey.prefix {
687 Some(ref prefix) => format!("{} {}", prefix, key),
688 None => key,
689 };
690 req_builder = req_builder.header("Authorization", value);
691 };
692
693 let req = req_builder.build()?;
694 let resp = configuration.client.execute(req).await?;
695
696 let status = resp.status();
697 let content_type = resp
698 .headers()
699 .get("content-type")
700 .and_then(|v| v.to_str().ok())
701 .unwrap_or("application/octet-stream");
702 let content_type = super::ContentType::from(content_type);
703
704 if !status.is_client_error() && !status.is_server_error() {
705 let content = resp.text().await?;
706 match content_type {
707 ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
708 ContentType::Text => return Ok(models::GetTimeSeriesCrossResponse::Text(content)),
709 ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::GetTimeSeriesCrossResponse`")))),
710 }
711 } else {
712 let content = resp.text().await?;
713 let entity: Option<GetTimeSeriesCrossError> = serde_json::from_str(&content).ok();
714 Err(Error::ResponseError(ResponseContent {
715 status,
716 content,
717 entity,
718 }))
719 }
720}