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
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, Serialize, Deserialize)]
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 self
123 }
124 /// Symbol ticker of the instrument. E.g. `AAPL`, `EUR/USD`, `ETH/BTC`, ...
125 pub fn symbol(mut self, symbol: impl Into<String>) -> Self {
126 self.symbol = Some(symbol.into());
127 self
128 }
129 /// Filter by international securities identification number (ISIN)
130 pub fn isin(mut self, isin: impl Into<String>) -> Self {
131 self.isin = Some(isin.into());
132 self
133 }
134 /// The FIGI of an instrument for which data is requested
135 pub fn figi(mut self, figi: impl Into<String>) -> Self {
136 self.figi = Some(figi.into());
137 self
138 }
139 /// 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
140 pub fn cusip(mut self, cusip: impl Into<String>) -> Self {
141 self.cusip = Some(cusip.into());
142 self
143 }
144 /// 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
145 pub fn outputsize(mut self, outputsize: i64) -> Self {
146 self.outputsize = Some(outputsize);
147 self
148 }
149 /// Exchange where instrument is traded
150 pub fn exchange(mut self, exchange: impl Into<String>) -> Self {
151 self.exchange = Some(exchange.into());
152 self
153 }
154 /// Market Identifier Code (MIC) under ISO 10383 standard
155 pub fn mic_code(mut self, mic_code: impl Into<String>) -> Self {
156 self.mic_code = Some(mic_code.into());
157 self
158 }
159 /// The country where the instrument is traded, e.g., `United States` or `US`
160 pub fn country(mut self, country: impl Into<String>) -> Self {
161 self.country = Some(country.into());
162 self
163 }
164 /// The asset class to which the instrument belongs
165 pub fn r#type(mut self, r#type: impl Into<String>) -> Self {
166 self.r#type = Some(r#type.into());
167 self
168 }
169 /// 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>
170 pub fn timezone(mut self, timezone: impl Into<String>) -> Self {
171 self.timezone = Some(timezone.into());
172 self
173 }
174 /// 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>
175 pub fn start_date(mut self, start_date: impl Into<String>) -> Self {
176 self.start_date = Some(start_date.into());
177 self
178 }
179 /// The ending date and time for data selection, see `start_date` description for details.
180 pub fn end_date(mut self, end_date: impl Into<String>) -> Self {
181 self.end_date = Some(end_date.into());
182 self
183 }
184 /// 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`
185 pub fn date(mut self, date: impl Into<String>) -> Self {
186 self.date = Some(date.into());
187 self
188 }
189 /// Sorting order of the output
190 pub fn order(mut self, order: impl Into<String>) -> Self {
191 self.order = Some(order.into());
192 self
193 }
194 /// 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
195 pub fn prepost(mut self, prepost: bool) -> Self {
196 self.prepost = Some(prepost);
197 self
198 }
199 /// The format of the response data
200 pub fn format(mut self, format: impl Into<String>) -> Self {
201 self.format = Some(format.into());
202 self
203 }
204 /// The separator used in the CSV response data
205 pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
206 self.delimiter = Some(delimiter.into());
207 self
208 }
209 /// 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
210 pub fn dp(mut self, dp: i64) -> Self {
211 self.dp = Some(dp);
212 self
213 }
214 /// 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
215 pub fn previous_close(mut self, previous_close: bool) -> Self {
216 self.previous_close = Some(previous_close);
217 self
218 }
219 /// Adjusting mode for prices
220 pub fn adjust(mut self, adjust: impl Into<String>) -> Self {
221 self.adjust = Some(adjust.into());
222 self
223 }
224
225 /// Build the parameter struct
226 pub fn build(self) -> GetTimeSeriesParams {
227 GetTimeSeriesParams {
228 interval: self.interval,
229 symbol: self.symbol,
230 isin: self.isin,
231 figi: self.figi,
232 cusip: self.cusip,
233 outputsize: self.outputsize,
234 exchange: self.exchange,
235 mic_code: self.mic_code,
236 country: self.country,
237 r#type: self.r#type,
238 timezone: self.timezone,
239 start_date: self.start_date,
240 end_date: self.end_date,
241 date: self.date,
242 order: self.order,
243 prepost: self.prepost,
244 format: self.format,
245 delimiter: self.delimiter,
246 dp: self.dp,
247 previous_close: self.previous_close,
248 adjust: self.adjust
249 }
250 }
251}
252
253/// struct for passing parameters to the method [`get_time_series_cross`]
254#[derive(Clone, Debug, Default, Serialize, Deserialize)]
255pub struct GetTimeSeriesCrossParams {
256 /// Base currency symbol
257 pub base: String,
258 /// Quote currency symbol
259 pub quote: String,
260 /// Interval between two consecutive points in time series
261 pub interval: String,
262 /// Base instrument type according to the `/instrument_type` endpoint
263 pub base_type: Option<String>,
264 /// Base exchange
265 pub base_exchange: Option<String>,
266 /// Base MIC code
267 pub base_mic_code: Option<String>,
268 /// Quote instrument type according to the `/instrument_type` endpoint
269 pub quote_type: Option<String>,
270 /// Quote exchange
271 pub quote_exchange: Option<String>,
272 /// Quote MIC code
273 pub quote_mic_code: Option<String>,
274 /// 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
275 pub outputsize: Option<i64>,
276 /// Format of the response data
277 pub format: Option<String>,
278 /// Delimiter used in CSV file
279 pub delimiter: Option<String>,
280 /// 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.
281 pub prepost: Option<bool>,
282 /// Start date for the time series data
283 pub start_date: Option<String>,
284 /// End date for the time series data
285 pub end_date: Option<String>,
286 /// Specifies if there should be an adjustment
287 pub adjust: Option<bool>,
288 /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive.
289 pub dp: Option<i64>,
290 /// 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>
291 pub timezone: Option<String>
292}
293
294impl GetTimeSeriesCrossParams {
295 /// Create a new builder for this parameter struct
296 pub fn builder() -> GetTimeSeriesCrossParamsBuilder {
297 GetTimeSeriesCrossParamsBuilder::default()
298 }
299}
300
301/// Builder for [`GetTimeSeriesCrossParams`]
302#[derive(Clone, Debug, Default)]
303pub struct GetTimeSeriesCrossParamsBuilder {
304 /// Base currency symbol
305 base: String,
306 /// Quote currency symbol
307 quote: String,
308 /// Interval between two consecutive points in time series
309 interval: String,
310 /// Base instrument type according to the `/instrument_type` endpoint
311 base_type: Option<String>,
312 /// Base exchange
313 base_exchange: Option<String>,
314 /// Base MIC code
315 base_mic_code: Option<String>,
316 /// Quote instrument type according to the `/instrument_type` endpoint
317 quote_type: Option<String>,
318 /// Quote exchange
319 quote_exchange: Option<String>,
320 /// Quote MIC code
321 quote_mic_code: Option<String>,
322 /// 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
323 outputsize: Option<i64>,
324 /// Format of the response data
325 format: Option<String>,
326 /// Delimiter used in CSV file
327 delimiter: Option<String>,
328 /// 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.
329 prepost: Option<bool>,
330 /// Start date for the time series data
331 start_date: Option<String>,
332 /// End date for the time series data
333 end_date: Option<String>,
334 /// Specifies if there should be an adjustment
335 adjust: Option<bool>,
336 /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive.
337 dp: Option<i64>,
338 /// 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>
339 timezone: Option<String>
340}
341
342impl GetTimeSeriesCrossParamsBuilder {
343 /// Base currency symbol
344 pub fn base(mut self, base: impl Into<String>) -> Self {
345 self.base = base.into();
346 self
347 }
348 /// Quote currency symbol
349 pub fn quote(mut self, quote: impl Into<String>) -> Self {
350 self.quote = quote.into();
351 self
352 }
353 /// Interval between two consecutive points in time series
354 pub fn interval(mut self, interval: impl Into<String>) -> Self {
355 self.interval = interval.into();
356 self
357 }
358 /// Base instrument type according to the `/instrument_type` endpoint
359 pub fn base_type(mut self, base_type: impl Into<String>) -> Self {
360 self.base_type = Some(base_type.into());
361 self
362 }
363 /// Base exchange
364 pub fn base_exchange(mut self, base_exchange: impl Into<String>) -> Self {
365 self.base_exchange = Some(base_exchange.into());
366 self
367 }
368 /// Base MIC code
369 pub fn base_mic_code(mut self, base_mic_code: impl Into<String>) -> Self {
370 self.base_mic_code = Some(base_mic_code.into());
371 self
372 }
373 /// Quote instrument type according to the `/instrument_type` endpoint
374 pub fn quote_type(mut self, quote_type: impl Into<String>) -> Self {
375 self.quote_type = Some(quote_type.into());
376 self
377 }
378 /// Quote exchange
379 pub fn quote_exchange(mut self, quote_exchange: impl Into<String>) -> Self {
380 self.quote_exchange = Some(quote_exchange.into());
381 self
382 }
383 /// Quote MIC code
384 pub fn quote_mic_code(mut self, quote_mic_code: impl Into<String>) -> Self {
385 self.quote_mic_code = Some(quote_mic_code.into());
386 self
387 }
388 /// 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
389 pub fn outputsize(mut self, outputsize: i64) -> Self {
390 self.outputsize = Some(outputsize);
391 self
392 }
393 /// Format of the response data
394 pub fn format(mut self, format: impl Into<String>) -> Self {
395 self.format = Some(format.into());
396 self
397 }
398 /// Delimiter used in CSV file
399 pub fn delimiter(mut self, delimiter: impl Into<String>) -> Self {
400 self.delimiter = Some(delimiter.into());
401 self
402 }
403 /// 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.
404 pub fn prepost(mut self, prepost: bool) -> Self {
405 self.prepost = Some(prepost);
406 self
407 }
408 /// Start date for the time series data
409 pub fn start_date(mut self, start_date: impl Into<String>) -> Self {
410 self.start_date = Some(start_date.into());
411 self
412 }
413 /// End date for the time series data
414 pub fn end_date(mut self, end_date: impl Into<String>) -> Self {
415 self.end_date = Some(end_date.into());
416 self
417 }
418 /// Specifies if there should be an adjustment
419 pub fn adjust(mut self, adjust: bool) -> Self {
420 self.adjust = Some(adjust);
421 self
422 }
423 /// Specifies the number of decimal places for floating values. Should be in range [0, 11] inclusive.
424 pub fn dp(mut self, dp: i64) -> Self {
425 self.dp = Some(dp);
426 self
427 }
428 /// 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>
429 pub fn timezone(mut self, timezone: impl Into<String>) -> Self {
430 self.timezone = Some(timezone.into());
431 self
432 }
433
434 /// Build the parameter struct
435 pub fn build(self) -> GetTimeSeriesCrossParams {
436 GetTimeSeriesCrossParams {
437 base: self.base,
438 quote: self.quote,
439 interval: self.interval,
440 base_type: self.base_type,
441 base_exchange: self.base_exchange,
442 base_mic_code: self.base_mic_code,
443 quote_type: self.quote_type,
444 quote_exchange: self.quote_exchange,
445 quote_mic_code: self.quote_mic_code,
446 outputsize: self.outputsize,
447 format: self.format,
448 delimiter: self.delimiter,
449 prepost: self.prepost,
450 start_date: self.start_date,
451 end_date: self.end_date,
452 adjust: self.adjust,
453 dp: self.dp,
454 timezone: self.timezone
455 }
456 }
457}
458
459
460/// struct for typed errors of method [`get_time_series`]
461#[derive(Debug, Clone, Serialize, Deserialize)]
462#[serde(untagged)]
463pub enum GetTimeSeriesError {
464 UnknownValue(serde_json::Value),
465}
466
467/// struct for typed errors of method [`get_time_series_cross`]
468#[derive(Debug, Clone, Serialize, Deserialize)]
469#[serde(untagged)]
470pub enum GetTimeSeriesCrossError {
471 UnknownValue(serde_json::Value),
472}
473
474
475/// 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.
476pub async fn get_time_series(configuration: &configuration::Configuration, params: GetTimeSeriesParams) -> Result<models::GetTimeSeries200Response, 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", &serde_json::to_string(param_value)?)]);
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", &serde_json::to_string(param_value)?)]);
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", &serde_json::to_string(param_value)?)]);
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", &serde_json::to_string(param_value)?)]);
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 Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetTimeSeries200Response`"))),
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::GetTimeSeries200Response`")))),
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 { status, content, entity }))
598 }
599}
600
601/// 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.
602pub async fn get_time_series_cross(configuration: &configuration::Configuration, params: GetTimeSeriesCrossParams) -> Result<models::GetTimeSeriesCross200Response, Error<GetTimeSeriesCrossError>> {
603 // Extract parameters from params struct
604 let p_query_base = params.base;
605 let p_query_quote = params.quote;
606 let p_query_interval = params.interval;
607 let p_query_base_type = params.base_type;
608 let p_query_base_exchange = params.base_exchange;
609 let p_query_base_mic_code = params.base_mic_code;
610 let p_query_quote_type = params.quote_type;
611 let p_query_quote_exchange = params.quote_exchange;
612 let p_query_quote_mic_code = params.quote_mic_code;
613 let p_query_outputsize = params.outputsize;
614 let p_query_format = params.format;
615 let p_query_delimiter = params.delimiter;
616 let p_query_prepost = params.prepost;
617 let p_query_start_date = params.start_date;
618 let p_query_end_date = params.end_date;
619 let p_query_adjust = params.adjust;
620 let p_query_dp = params.dp;
621 let p_query_timezone = params.timezone;
622
623 let uri_str = format!("{}/time_series/cross", configuration.base_path);
624 let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);
625
626 req_builder = req_builder.query(&[("base", &p_query_base.to_string())]);
627 if let Some(ref param_value) = p_query_base_type {
628 req_builder = req_builder.query(&[("base_type", ¶m_value.to_string())]);
629 }
630 if let Some(ref param_value) = p_query_base_exchange {
631 req_builder = req_builder.query(&[("base_exchange", ¶m_value.to_string())]);
632 }
633 if let Some(ref param_value) = p_query_base_mic_code {
634 req_builder = req_builder.query(&[("base_mic_code", ¶m_value.to_string())]);
635 }
636 req_builder = req_builder.query(&[("quote", &p_query_quote.to_string())]);
637 if let Some(ref param_value) = p_query_quote_type {
638 req_builder = req_builder.query(&[("quote_type", ¶m_value.to_string())]);
639 }
640 if let Some(ref param_value) = p_query_quote_exchange {
641 req_builder = req_builder.query(&[("quote_exchange", ¶m_value.to_string())]);
642 }
643 if let Some(ref param_value) = p_query_quote_mic_code {
644 req_builder = req_builder.query(&[("quote_mic_code", ¶m_value.to_string())]);
645 }
646 req_builder = req_builder.query(&[("interval", &p_query_interval.to_string())]);
647 if let Some(ref param_value) = p_query_outputsize {
648 req_builder = req_builder.query(&[("outputsize", ¶m_value.to_string())]);
649 }
650 if let Some(ref param_value) = p_query_format {
651 req_builder = req_builder.query(&[("format", &serde_json::to_string(param_value)?)]);
652 }
653 if let Some(ref param_value) = p_query_delimiter {
654 req_builder = req_builder.query(&[("delimiter", ¶m_value.to_string())]);
655 }
656 if let Some(ref param_value) = p_query_prepost {
657 req_builder = req_builder.query(&[("prepost", ¶m_value.to_string())]);
658 }
659 if let Some(ref param_value) = p_query_start_date {
660 req_builder = req_builder.query(&[("start_date", ¶m_value.to_string())]);
661 }
662 if let Some(ref param_value) = p_query_end_date {
663 req_builder = req_builder.query(&[("end_date", ¶m_value.to_string())]);
664 }
665 if let Some(ref param_value) = p_query_adjust {
666 req_builder = req_builder.query(&[("adjust", ¶m_value.to_string())]);
667 }
668 if let Some(ref param_value) = p_query_dp {
669 req_builder = req_builder.query(&[("dp", ¶m_value.to_string())]);
670 }
671 if let Some(ref param_value) = p_query_timezone {
672 req_builder = req_builder.query(&[("timezone", ¶m_value.to_string())]);
673 }
674 if let Some(ref user_agent) = configuration.user_agent {
675 req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
676 }
677 if let Some(ref apikey) = configuration.api_key {
678 let key = apikey.key.clone();
679 let value = match apikey.prefix {
680 Some(ref prefix) => format!("{} {}", prefix, key),
681 None => key,
682 };
683 req_builder = req_builder.header("Authorization", value);
684 };
685
686 let req = req_builder.build()?;
687 let resp = configuration.client.execute(req).await?;
688
689 let status = resp.status();
690 let content_type = resp
691 .headers()
692 .get("content-type")
693 .and_then(|v| v.to_str().ok())
694 .unwrap_or("application/octet-stream");
695 let content_type = super::ContentType::from(content_type);
696
697 if !status.is_client_error() && !status.is_server_error() {
698 let content = resp.text().await?;
699 match content_type {
700 ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
701 ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `models::GetTimeSeriesCross200Response`"))),
702 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`")))),
703 }
704 } else {
705 let content = resp.text().await?;
706 let entity: Option<GetTimeSeriesCrossError> = serde_json::from_str(&content).ok();
707 Err(Error::ResponseError(ResponseContent { status, content, entity }))
708 }
709}
710