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') &nbsp;&nbsp;.then(response => response.json()) &nbsp;&nbsp;.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( &nbsp;&nbsp;&nbsp;&nbsp;symbol=\"TSLA\", &nbsp;&nbsp;&nbsp;&nbsp;interval=\"1day\", &nbsp;&nbsp;&nbsp;&nbsp;outputsize=100 ).as_pandas()  # Fetch historical price data for Microsoft msft_ts = td.time_series( &nbsp;&nbsp;&nbsp;&nbsp;symbol=\"MSFT\", &nbsp;&nbsp;&nbsp;&nbsp;interval=\"1day\", &nbsp;&nbsp;&nbsp;&nbsp;outputsize=100 ).as_pandas()  # Align data on datetime index combined = pd.concat( &nbsp;&nbsp;&nbsp;&nbsp;[tsla_ts['close'].astype(float), msft_ts['close'].astype(float)], &nbsp;&nbsp;&nbsp;&nbsp;axis=1, &nbsp;&nbsp;&nbsp;&nbsp;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 Documenta­tion to correct the input. |  **401** | Unauthor­ized | 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 { &nbsp;&nbsp;\"code\": 400, &nbsp;&nbsp;\"message\": \"Invalid **interval** provided: 0.99min. Supported intervals: 1min, 5min, 15min, 30min, 45min, 1h, 2h, 4h, 8h, 1day, 1week, 1month\", &nbsp;&nbsp;\"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
11
12use reqwest;
13use serde::{Deserialize, Serialize, de::Error as _};
14use crate::{apis::ResponseContent, models};
15use super::{Error, configuration, ContentType};
16
17/// struct for passing parameters to the method [`get_time_series`]
18#[derive(Clone, Debug, Default)]
19pub struct GetTimeSeriesParams {
20    /// Interval between two consecutive points in time series
21    pub interval: String,
22    /// Symbol ticker of the instrument. E.g. `AAPL`, `EUR/USD`, `ETH/BTC`, ...
23    pub symbol: Option<String>,
24    /// Filter by international securities identification number (ISIN)
25    pub isin: Option<String>,
26    /// The FIGI of an instrument for which data is requested
27    pub figi: Option<String>,
28    /// 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
29    pub cusip: Option<String>,
30    /// 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
31    pub outputsize: Option<i64>,
32    /// Exchange where instrument is traded
33    pub exchange: Option<String>,
34    /// Market Identifier Code (MIC) under ISO 10383 standard
35    pub mic_code: Option<String>,
36    /// The country where the instrument is traded, e.g., `United States` or `US`
37    pub country: Option<String>,
38    /// The asset class to which the instrument belongs
39    pub r#type: Option<String>,
40    /// 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>
41    pub timezone: Option<String>,
42    /// 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>
43    pub start_date: Option<String>,
44    /// The ending date and time for data selection, see `start_date` description for details.
45    pub end_date: Option<String>,
46    /// 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`
47    pub date: Option<String>,
48    /// Sorting order of the output
49    pub order: Option<String>,
50    /// 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
51    pub prepost: Option<bool>,
52    /// The format of the response data
53    pub format: Option<String>,
54    /// The separator used in the CSV response data
55    pub delimiter: Option<String>,
56    /// 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
57    pub dp: Option<i64>,
58    /// 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
59    pub previous_close: Option<bool>,
60    /// Adjusting mode for prices
61    pub adjust: Option<String>
62}
63
64impl GetTimeSeriesParams {
65    /// Create a new builder for this parameter struct
66    pub fn builder() -> GetTimeSeriesParamsBuilder {
67        GetTimeSeriesParamsBuilder::default()
68    }
69}
70
71/// Builder for [`GetTimeSeriesParams`]
72#[derive(Clone, Debug, Default)]
73pub struct GetTimeSeriesParamsBuilder {
74    /// Interval between two consecutive points in time series
75    interval: String,
76    /// Symbol ticker of the instrument. E.g. `AAPL`, `EUR/USD`, `ETH/BTC`, ...
77    symbol: Option<String>,
78    /// Filter by international securities identification number (ISIN)
79    isin: Option<String>,
80    /// The FIGI of an instrument for which data is requested
81    figi: Option<String>,
82    /// 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
83    cusip: Option<String>,
84    /// 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
85    outputsize: Option<i64>,
86    /// Exchange where instrument is traded
87    exchange: Option<String>,
88    /// Market Identifier Code (MIC) under ISO 10383 standard
89    mic_code: Option<String>,
90    /// The country where the instrument is traded, e.g., `United States` or `US`
91    country: Option<String>,
92    /// The asset class to which the instrument belongs
93    r#type: Option<String>,
94    /// 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>
95    timezone: Option<String>,
96    /// 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>
97    start_date: Option<String>,
98    /// The ending date and time for data selection, see `start_date` description for details.
99    end_date: Option<String>,
100    /// 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`
101    date: Option<String>,
102    /// Sorting order of the output
103    order: Option<String>,
104    /// 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
105    prepost: Option<bool>,
106    /// The format of the response data
107    format: Option<String>,
108    /// The separator used in the CSV response data
109    delimiter: Option<String>,
110    /// 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
111    dp: Option<i64>,
112    /// 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
113    previous_close: Option<bool>,
114    /// Adjusting mode for prices
115    adjust: Option<String>
116}
117
118impl GetTimeSeriesParamsBuilder {
119    /// Interval between two consecutive points in time series
120    pub fn interval(mut self, interval: impl Into<String>) -> Self {
121        self.interval = interval.into();
122        
123        self
124    }
125    /// Symbol ticker of the instrument. E.g. `AAPL`, `EUR/USD`, `ETH/BTC`, ...
126    pub fn symbol(mut self, symbol: impl Into<String>) -> Self {
127        self.symbol = Some(symbol.into());
128        
129        self
130    }
131    /// Filter by international securities identification number (ISIN)
132    pub fn isin(mut self, isin: impl Into<String>) -> Self {
133        self.isin = Some(isin.into());
134        
135        self
136    }
137    /// The FIGI of an instrument for which data is requested
138    pub fn figi(mut self, figi: impl Into<String>) -> Self {
139        self.figi = Some(figi.into());
140        
141        self
142    }
143    /// 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
144    pub fn cusip(mut self, cusip: impl Into<String>) -> Self {
145        self.cusip = Some(cusip.into());
146        
147        self
148    }
149    /// 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
150    pub fn outputsize(mut self, outputsize: i64) -> Self {
151        
152        self.outputsize = Some(outputsize);
153        
154        self
155    }
156    /// Exchange where instrument is traded
157    pub fn exchange(mut self, exchange: impl Into<String>) -> Self {
158        self.exchange = Some(exchange.into());
159        
160        self
161    }
162    /// Market Identifier Code (MIC) under ISO 10383 standard
163    pub fn mic_code(mut self, mic_code: impl Into<String>) -> Self {
164        self.mic_code = Some(mic_code.into());
165        
166        self
167    }
168    /// The country where the instrument is traded, e.g., `United States` or `US`
169    pub fn country(mut self, country: impl Into<String>) -> Self {
170        self.country = Some(country.into());
171        
172        self
173    }
174    /// The asset class to which the instrument belongs
175    pub fn r#type(mut self, r#type: impl Into<String>) -> Self {
176        self.r#type = Some(r#type.into());
177        
178        self
179    }
180    /// 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>
181    pub fn timezone(mut self, timezone: impl Into<String>) -> Self {
182        self.timezone = Some(timezone.into());
183        
184        self
185    }
186    /// 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>
187    pub fn start_date(mut self, start_date: impl Into<String>) -> Self {
188        self.start_date = Some(start_date.into());
189        
190        self
191    }
192    /// The ending date and time for data selection, see `start_date` description for details.
193    pub fn end_date(mut self, end_date: impl Into<String>) -> Self {
194        self.end_date = Some(end_date.into());
195        
196        self
197    }
198    /// 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`
199    pub fn date(mut self, date: impl Into<String>) -> Self {
200        self.date = Some(date.into());
201        
202        self
203    }
204    /// Sorting order of the output
205    pub fn order(mut self, order: impl Into<String>) -> Self {
206        self.order = Some(order.into());
207        
208        self
209    }
210    /// 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
211    pub fn prepost(mut self, prepost: bool) -> Self {
212        
213        self.prepost = Some(prepost);
214        
215        self
216    }
217    /// The format of the response data
218    pub fn format(mut self, format: impl Into<String>) -> Self {
219        self.format = Some(format.into());
220        
221        self
222    }
223    /// The separator used in the CSV response data
224    pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
225        self.delimiter = Some(delimiter.into());
226        
227        self
228    }
229    /// 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
230    pub fn dp(mut self, dp: i64) -> Self {
231        
232        self.dp = Some(dp);
233        
234        self
235    }
236    /// 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
237    pub fn previous_close(mut self, previous_close: bool) -> Self {
238        
239        self.previous_close = Some(previous_close);
240        
241        self
242    }
243    /// Adjusting mode for prices
244    pub fn adjust(mut self, adjust: impl Into<String>) -> Self {
245        self.adjust = Some(adjust.into());
246        
247        self
248    }
249
250    /// Build the parameter struct
251    pub fn build(self) -> GetTimeSeriesParams {
252        GetTimeSeriesParams {
253            interval: self.interval,
254            symbol: self.symbol,
255            isin: self.isin,
256            figi: self.figi,
257            cusip: self.cusip,
258            outputsize: self.outputsize,
259            exchange: self.exchange,
260            mic_code: self.mic_code,
261            country: self.country,
262            r#type: self.r#type,
263            timezone: self.timezone,
264            start_date: self.start_date,
265            end_date: self.end_date,
266            date: self.date,
267            order: self.order,
268            prepost: self.prepost,
269            format: self.format,
270            delimiter: self.delimiter,
271            dp: self.dp,
272            previous_close: self.previous_close,
273            adjust: self.adjust
274        }
275    }
276}
277
278/// struct for passing parameters to the method [`get_time_series_cross`]
279#[derive(Clone, Debug, Default)]
280pub struct GetTimeSeriesCrossParams {
281    /// Base currency symbol
282    pub base: String,
283    /// Quote currency symbol
284    pub quote: String,
285    /// Interval between two consecutive points in time series
286    pub interval: String,
287    /// Base instrument type according to the `/instrument_type` endpoint
288    pub base_type: Option<String>,
289    /// Base exchange
290    pub base_exchange: Option<String>,
291    /// Base MIC code
292    pub base_mic_code: Option<String>,
293    /// Quote instrument type according to the `/instrument_type` endpoint
294    pub quote_type: Option<String>,
295    /// Quote exchange
296    pub quote_exchange: Option<String>,
297    /// Quote MIC code
298    pub quote_mic_code: Option<String>,
299    /// 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
300    pub outputsize: Option<i64>,
301    /// Format of the response data
302    pub format: Option<String>,
303    /// Delimiter used in CSV file
304    pub delimiter: Option<String>,
305    /// 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.
306    pub prepost: Option<bool>,
307    /// Start date for the time series data
308    pub start_date: Option<String>,
309    /// End date for the time series data
310    pub end_date: Option<String>,
311    /// Specifies if there should be an adjustment
312    pub adjust: Option<bool>,
313    /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive.
314    pub dp: Option<i64>,
315    /// 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>
316    pub timezone: Option<String>
317}
318
319impl GetTimeSeriesCrossParams {
320    /// Create a new builder for this parameter struct
321    pub fn builder() -> GetTimeSeriesCrossParamsBuilder {
322        GetTimeSeriesCrossParamsBuilder::default()
323    }
324}
325
326/// Builder for [`GetTimeSeriesCrossParams`]
327#[derive(Clone, Debug, Default)]
328pub struct GetTimeSeriesCrossParamsBuilder {
329    /// Base currency symbol
330    base: String,
331    /// Quote currency symbol
332    quote: String,
333    /// Interval between two consecutive points in time series
334    interval: String,
335    /// Base instrument type according to the `/instrument_type` endpoint
336    base_type: Option<String>,
337    /// Base exchange
338    base_exchange: Option<String>,
339    /// Base MIC code
340    base_mic_code: Option<String>,
341    /// Quote instrument type according to the `/instrument_type` endpoint
342    quote_type: Option<String>,
343    /// Quote exchange
344    quote_exchange: Option<String>,
345    /// Quote MIC code
346    quote_mic_code: Option<String>,
347    /// 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
348    outputsize: Option<i64>,
349    /// Format of the response data
350    format: Option<String>,
351    /// Delimiter used in CSV file
352    delimiter: Option<String>,
353    /// 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.
354    prepost: Option<bool>,
355    /// Start date for the time series data
356    start_date: Option<String>,
357    /// End date for the time series data
358    end_date: Option<String>,
359    /// Specifies if there should be an adjustment
360    adjust: Option<bool>,
361    /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive.
362    dp: Option<i64>,
363    /// 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>
364    timezone: Option<String>
365}
366
367impl GetTimeSeriesCrossParamsBuilder {
368    /// Base currency symbol
369    pub fn base(mut self, base: impl Into<String>) -> Self {
370        self.base = base.into();
371        
372        self
373    }
374    /// Quote currency symbol
375    pub fn quote(mut self, quote: impl Into<String>) -> Self {
376        self.quote = quote.into();
377        
378        self
379    }
380    /// Interval between two consecutive points in time series
381    pub fn interval(mut self, interval: impl Into<String>) -> Self {
382        self.interval = interval.into();
383        
384        self
385    }
386    /// Base instrument type according to the `/instrument_type` endpoint
387    pub fn base_type(mut self, base_type: impl Into<String>) -> Self {
388        self.base_type = Some(base_type.into());
389        
390        self
391    }
392    /// Base exchange
393    pub fn base_exchange(mut self, base_exchange: impl Into<String>) -> Self {
394        self.base_exchange = Some(base_exchange.into());
395        
396        self
397    }
398    /// Base MIC code
399    pub fn base_mic_code(mut self, base_mic_code: impl Into<String>) -> Self {
400        self.base_mic_code = Some(base_mic_code.into());
401        
402        self
403    }
404    /// Quote instrument type according to the `/instrument_type` endpoint
405    pub fn quote_type(mut self, quote_type: impl Into<String>) -> Self {
406        self.quote_type = Some(quote_type.into());
407        
408        self
409    }
410    /// Quote exchange
411    pub fn quote_exchange(mut self, quote_exchange: impl Into<String>) -> Self {
412        self.quote_exchange = Some(quote_exchange.into());
413        
414        self
415    }
416    /// Quote MIC code
417    pub fn quote_mic_code(mut self, quote_mic_code: impl Into<String>) -> Self {
418        self.quote_mic_code = Some(quote_mic_code.into());
419        
420        self
421    }
422    /// 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
423    pub fn outputsize(mut self, outputsize: i64) -> Self {
424        
425        self.outputsize = Some(outputsize);
426        
427        self
428    }
429    /// Format of the response data
430    pub fn format(mut self, format: impl Into<String>) -> Self {
431        self.format = Some(format.into());
432        
433        self
434    }
435    /// Delimiter used in CSV file
436    pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
437        self.delimiter = Some(delimiter.into());
438        
439        self
440    }
441    /// 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.
442    pub fn prepost(mut self, prepost: bool) -> Self {
443        
444        self.prepost = Some(prepost);
445        
446        self
447    }
448    /// Start date for the time series data
449    pub fn start_date(mut self, start_date: impl Into<String>) -> Self {
450        self.start_date = Some(start_date.into());
451        
452        self
453    }
454    /// End date for the time series data
455    pub fn end_date(mut self, end_date: impl Into<String>) -> Self {
456        self.end_date = Some(end_date.into());
457        
458        self
459    }
460    /// Specifies if there should be an adjustment
461    pub fn adjust(mut self, adjust: bool) -> Self {
462        
463        self.adjust = Some(adjust);
464        
465        self
466    }
467    /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive.
468    pub fn dp(mut self, dp: i64) -> Self {
469        
470        self.dp = Some(dp);
471        
472        self
473    }
474    /// 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>
475    pub fn timezone(mut self, timezone: impl Into<String>) -> Self {
476        self.timezone = Some(timezone.into());
477        
478        self
479    }
480
481    /// Build the parameter struct
482    pub fn build(self) -> GetTimeSeriesCrossParams {
483        GetTimeSeriesCrossParams {
484            base: self.base,
485            quote: self.quote,
486            interval: self.interval,
487            base_type: self.base_type,
488            base_exchange: self.base_exchange,
489            base_mic_code: self.base_mic_code,
490            quote_type: self.quote_type,
491            quote_exchange: self.quote_exchange,
492            quote_mic_code: self.quote_mic_code,
493            outputsize: self.outputsize,
494            format: self.format,
495            delimiter: self.delimiter,
496            prepost: self.prepost,
497            start_date: self.start_date,
498            end_date: self.end_date,
499            adjust: self.adjust,
500            dp: self.dp,
501            timezone: self.timezone
502        }
503    }
504}
505
506
507/// struct for typed errors of method [`get_time_series`]
508#[derive(Debug, Clone, Serialize, Deserialize)]
509#[serde(untagged)]
510pub enum GetTimeSeriesError {
511    UnknownValue(serde_json::Value),
512}
513
514/// struct for typed errors of method [`get_time_series_cross`]
515#[derive(Debug, Clone, Serialize, Deserialize)]
516#[serde(untagged)]
517pub enum GetTimeSeriesCrossError {
518    UnknownValue(serde_json::Value),
519}
520
521
522/// 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.
523pub async fn get_time_series(configuration: &configuration::Configuration, params: GetTimeSeriesParams) -> Result<models::GetTimeSeries200Response, Error<GetTimeSeriesError>> {
524    // Extract parameters from params struct
525    let p_query_interval = params.interval;
526    let p_query_symbol = params.symbol;
527    let p_query_isin = params.isin;
528    let p_query_figi = params.figi;
529    let p_query_cusip = params.cusip;
530    let p_query_outputsize = params.outputsize;
531    let p_query_exchange = params.exchange;
532    let p_query_mic_code = params.mic_code;
533    let p_query_country = params.country;
534    let p_query_type = params.r#type;
535    let p_query_timezone = params.timezone;
536    let p_query_start_date = params.start_date;
537    let p_query_end_date = params.end_date;
538    let p_query_date = params.date;
539    let p_query_order = params.order;
540    let p_query_prepost = params.prepost;
541    let p_query_format = params.format;
542    let p_query_delimiter = params.delimiter;
543    let p_query_dp = params.dp;
544    let p_query_previous_close = params.previous_close;
545    let p_query_adjust = params.adjust;
546
547    let uri_str = format!("{}/time_series", configuration.base_path);
548    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
549
550    if let Some(ref param_value) = p_query_symbol {
551        req_builder = req_builder.query(&[("symbol", &param_value.to_string())]);
552    }
553    if let Some(ref param_value) = p_query_isin {
554        req_builder = req_builder.query(&[("isin", &param_value.to_string())]);
555    }
556    if let Some(ref param_value) = p_query_figi {
557        req_builder = req_builder.query(&[("figi", &param_value.to_string())]);
558    }
559    if let Some(ref param_value) = p_query_cusip {
560        req_builder = req_builder.query(&[("cusip", &param_value.to_string())]);
561    }
562    req_builder = req_builder.query(&[("interval", &p_query_interval.to_string())]);
563    if let Some(ref param_value) = p_query_outputsize {
564        req_builder = req_builder.query(&[("outputsize", &param_value.to_string())]);
565    }
566    if let Some(ref param_value) = p_query_exchange {
567        req_builder = req_builder.query(&[("exchange", &param_value.to_string())]);
568    }
569    if let Some(ref param_value) = p_query_mic_code {
570        req_builder = req_builder.query(&[("mic_code", &param_value.to_string())]);
571    }
572    if let Some(ref param_value) = p_query_country {
573        req_builder = req_builder.query(&[("country", &param_value.to_string())]);
574    }
575    if let Some(ref param_value) = p_query_type {
576        req_builder = req_builder.query(&[("type", &serde_json::to_string(param_value)?)]);
577    }
578    if let Some(ref param_value) = p_query_timezone {
579        req_builder = req_builder.query(&[("timezone", &param_value.to_string())]);
580    }
581    if let Some(ref param_value) = p_query_start_date {
582        req_builder = req_builder.query(&[("start_date", &param_value.to_string())]);
583    }
584    if let Some(ref param_value) = p_query_end_date {
585        req_builder = req_builder.query(&[("end_date", &param_value.to_string())]);
586    }
587    if let Some(ref param_value) = p_query_date {
588        req_builder = req_builder.query(&[("date", &param_value.to_string())]);
589    }
590    if let Some(ref param_value) = p_query_order {
591        req_builder = req_builder.query(&[("order", &serde_json::to_string(param_value)?)]);
592    }
593    if let Some(ref param_value) = p_query_prepost {
594        req_builder = req_builder.query(&[("prepost", &param_value.to_string())]);
595    }
596    if let Some(ref param_value) = p_query_format {
597        req_builder = req_builder.query(&[("format", &serde_json::to_string(param_value)?)]);
598    }
599    if let Some(ref param_value) = p_query_delimiter {
600        req_builder = req_builder.query(&[("delimiter", &param_value.to_string())]);
601    }
602    if let Some(ref param_value) = p_query_dp {
603        req_builder = req_builder.query(&[("dp", &param_value.to_string())]);
604    }
605    if let Some(ref param_value) = p_query_previous_close {
606        req_builder = req_builder.query(&[("previous_close", &param_value.to_string())]);
607    }
608    if let Some(ref param_value) = p_query_adjust {
609        req_builder = req_builder.query(&[("adjust", &serde_json::to_string(param_value)?)]);
610    }
611    if let Some(ref user_agent) = configuration.user_agent {
612        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
613    }
614    if let Some(ref apikey) = configuration.api_key {
615        let key = apikey.key.clone();
616        let value = match apikey.prefix {
617            Some(ref prefix) => format!("{} {}", prefix, key),
618            None => key,
619        };
620        req_builder = req_builder.header("Authorization", value);
621    };
622
623    let req = req_builder.build()?;
624    let resp = configuration.client.execute(req).await?;
625
626    let status = resp.status();
627    let content_type = resp
628        .headers()
629        .get("content-type")
630        .and_then(|v| v.to_str().ok())
631        .unwrap_or("application/octet-stream");
632    let content_type = super::ContentType::from(content_type);
633
634    if !status.is_client_error() && !status.is_server_error() {
635        let content = resp.text().await?;
636        match content_type {
637            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
638            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetTimeSeries200Response`"))),
639            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::GetTimeSeries200Response`")))),
640        }
641    } else {
642        let content = resp.text().await?;
643        let entity: Option<GetTimeSeriesError> = serde_json::from_str(&content).ok();
644        Err(Error::ResponseError(ResponseContent { status, content, entity }))
645    }
646}
647
648/// 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.
649pub async fn get_time_series_cross(configuration: &configuration::Configuration, params: GetTimeSeriesCrossParams) -> Result<models::GetTimeSeriesCross200Response, Error<GetTimeSeriesCrossError>> {
650    // Extract parameters from params struct
651    let p_query_base = params.base;
652    let p_query_quote = params.quote;
653    let p_query_interval = params.interval;
654    let p_query_base_type = params.base_type;
655    let p_query_base_exchange = params.base_exchange;
656    let p_query_base_mic_code = params.base_mic_code;
657    let p_query_quote_type = params.quote_type;
658    let p_query_quote_exchange = params.quote_exchange;
659    let p_query_quote_mic_code = params.quote_mic_code;
660    let p_query_outputsize = params.outputsize;
661    let p_query_format = params.format;
662    let p_query_delimiter = params.delimiter;
663    let p_query_prepost = params.prepost;
664    let p_query_start_date = params.start_date;
665    let p_query_end_date = params.end_date;
666    let p_query_adjust = params.adjust;
667    let p_query_dp = params.dp;
668    let p_query_timezone = params.timezone;
669
670    let uri_str = format!("{}/time_series/cross", configuration.base_path);
671    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
672
673    req_builder = req_builder.query(&[("base", &p_query_base.to_string())]);
674    if let Some(ref param_value) = p_query_base_type {
675        req_builder = req_builder.query(&[("base_type", &param_value.to_string())]);
676    }
677    if let Some(ref param_value) = p_query_base_exchange {
678        req_builder = req_builder.query(&[("base_exchange", &param_value.to_string())]);
679    }
680    if let Some(ref param_value) = p_query_base_mic_code {
681        req_builder = req_builder.query(&[("base_mic_code", &param_value.to_string())]);
682    }
683    req_builder = req_builder.query(&[("quote", &p_query_quote.to_string())]);
684    if let Some(ref param_value) = p_query_quote_type {
685        req_builder = req_builder.query(&[("quote_type", &param_value.to_string())]);
686    }
687    if let Some(ref param_value) = p_query_quote_exchange {
688        req_builder = req_builder.query(&[("quote_exchange", &param_value.to_string())]);
689    }
690    if let Some(ref param_value) = p_query_quote_mic_code {
691        req_builder = req_builder.query(&[("quote_mic_code", &param_value.to_string())]);
692    }
693    req_builder = req_builder.query(&[("interval", &p_query_interval.to_string())]);
694    if let Some(ref param_value) = p_query_outputsize {
695        req_builder = req_builder.query(&[("outputsize", &param_value.to_string())]);
696    }
697    if let Some(ref param_value) = p_query_format {
698        req_builder = req_builder.query(&[("format", &serde_json::to_string(param_value)?)]);
699    }
700    if let Some(ref param_value) = p_query_delimiter {
701        req_builder = req_builder.query(&[("delimiter", &param_value.to_string())]);
702    }
703    if let Some(ref param_value) = p_query_prepost {
704        req_builder = req_builder.query(&[("prepost", &param_value.to_string())]);
705    }
706    if let Some(ref param_value) = p_query_start_date {
707        req_builder = req_builder.query(&[("start_date", &param_value.to_string())]);
708    }
709    if let Some(ref param_value) = p_query_end_date {
710        req_builder = req_builder.query(&[("end_date", &param_value.to_string())]);
711    }
712    if let Some(ref param_value) = p_query_adjust {
713        req_builder = req_builder.query(&[("adjust", &param_value.to_string())]);
714    }
715    if let Some(ref param_value) = p_query_dp {
716        req_builder = req_builder.query(&[("dp", &param_value.to_string())]);
717    }
718    if let Some(ref param_value) = p_query_timezone {
719        req_builder = req_builder.query(&[("timezone", &param_value.to_string())]);
720    }
721    if let Some(ref user_agent) = configuration.user_agent {
722        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
723    }
724    if let Some(ref apikey) = configuration.api_key {
725        let key = apikey.key.clone();
726        let value = match apikey.prefix {
727            Some(ref prefix) => format!("{} {}", prefix, key),
728            None => key,
729        };
730        req_builder = req_builder.header("Authorization", value);
731    };
732
733    let req = req_builder.build()?;
734    let resp = configuration.client.execute(req).await?;
735
736    let status = resp.status();
737    let content_type = resp
738        .headers()
739        .get("content-type")
740        .and_then(|v| v.to_str().ok())
741        .unwrap_or("application/octet-stream");
742    let content_type = super::ContentType::from(content_type);
743
744    if !status.is_client_error() && !status.is_server_error() {
745        let content = resp.text().await?;
746        match content_type {
747            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
748            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetTimeSeriesCross200Response`"))),
749            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::GetTimeSeriesCross200Response`")))),
750        }
751    } else {
752        let content = resp.text().await?;
753        let entity: Option<GetTimeSeriesCrossError> = serde_json::from_str(&content).ok();
754        Err(Error::ResponseError(ResponseContent { status, content, entity }))
755    }
756}
757