pub struct HistoricalDataRequest {
pub instrument_token: u32,
pub from: NaiveDateTime,
pub to: NaiveDateTime,
pub interval: Interval,
pub continuous: Option<bool>,
pub oi: Option<bool>,
}
Expand description
Historical data request parameters (v1.0.3 enhanced)
This struct provides a structured way to request historical OHLCV data with precise datetime control and optional parameters. It replaces the previous approach of passing multiple string parameters.
§Benefits over Legacy API
- Type Safety: Compile-time validation of parameters
- Precise Timing: Hour/minute/second precision with
NaiveDateTime
- Builder Pattern: Fluent API for optional parameters
- Better IDE Support: Autocomplete and documentation
§Date/Time Handling
The API expects datetime in IST (Indian Standard Time). When using NaiveDateTime
,
ensure your timestamps represent IST. The API will treat naive datetimes as IST.
§Instrument Tokens
Instrument tokens are unique identifiers for tradable instruments. You can obtain them from the instruments API or by searching instruments by symbol.
§Examples
§Basic Daily Data Request
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;
let request = HistoricalDataRequest::new(
738561, // RELIANCE
NaiveDateTime::parse_from_str("2023-11-01 09:15:00", "%Y-%m-%d %H:%M:%S")?,
NaiveDateTime::parse_from_str("2023-11-30 15:30:00", "%Y-%m-%d %H:%M:%S")?,
Interval::Day,
);
§Intraday Data with Options
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;
let request = HistoricalDataRequest::new(
738561,
NaiveDateTime::parse_from_str("2023-11-20 09:00:00", "%Y-%m-%d %H:%M:%S")?,
NaiveDateTime::parse_from_str("2023-11-20 16:00:00", "%Y-%m-%d %H:%M:%S")?,
Interval::FiveMinute,
).continuous(true) // Enable continuous futures series (NFO/MCX futures only)
.with_oi(false); // Include OI for derivatives when true
Fields§
§instrument_token: u32
Instrument token - unique identifier for the trading instrument
This is a numeric identifier assigned to each tradable instrument. You can obtain instrument tokens from:
- The instruments API (
client.instruments()
) - Instrument search functionality
- KiteConnect documentation
Example: 738561 for RELIANCE on NSE
from: NaiveDateTime
From date and time (IST)
The start date and time for the historical data request. Must be in Indian Standard Time (IST). For daily data, you can use any time but 09:15:00 is recommended.
§Limits
- Intraday data: Limited to recent days (varies by broker)
- Daily data: Several years of history available
- Cannot be in the future
to: NaiveDateTime
To date and time (IST)
The end date and time for the historical data request.
Must be in Indian Standard Time (IST) and after from
date.
For daily data, you can use any time but 15:30:00 is recommended.
interval: Interval
Time interval for the historical data
Determines the granularity of the returned candles:
Minute
: 1-minute candles (for intraday analysis)ThreeMinute
,FiveMinute
, etc.: Various intraday intervalsDay
: Daily candles (for longer-term analysis)
Note: Shorter intervals generate more data points and may hit API rate limits faster.
continuous: Option<bool>
Continuous data flag (for futures)
When true
, provides continuous contract data for futures instruments
by stitching together data from different contract expiries. This gives
a continuous price series without gaps from contract rollovers.
true
: Continuous contract data (recommended for futures analysis)false
: Individual contract data (default)None
: Uses API default (false)
Only applicable to NFO/MCX futures contracts. Has no effect on equity/options.
oi: Option<bool>
Open interest data flag (for derivatives)
When true
, includes open interest data in the response for derivatives
instruments (futures and options). Open interest represents the total
number of outstanding contracts.
true
: Include open interest datafalse
: Exclude open interest data (smaller response)None
: Uses API default (false)
Only applicable to futures and options. Has no effect on equity instruments.
Implementations§
Source§impl HistoricalDataRequest
impl HistoricalDataRequest
Sourcepub fn new(
instrument_token: u32,
from: NaiveDateTime,
to: NaiveDateTime,
interval: Interval,
) -> Self
pub fn new( instrument_token: u32, from: NaiveDateTime, to: NaiveDateTime, interval: Interval, ) -> Self
Create a new historical data request
Sourcepub fn continuous(self, continuous: bool) -> Self
pub fn continuous(self, continuous: bool) -> Self
Enable continuous data for futures
Sourcepub fn validate_date_range(&self) -> Result<(), String>
pub fn validate_date_range(&self) -> Result<(), String>
Validate the date range against API limits for the specified interval
Checks if the requested date range exceeds the maximum allowed days for the specified interval according to KiteConnect API limits.
§Returns
Ok(())
if the date range is validErr(String)
with error description if validation fails
§Example
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;
let request = HistoricalDataRequest::new(
738561,
NaiveDateTime::parse_from_str("2023-11-01 09:15:00", "%Y-%m-%d %H:%M:%S").unwrap(),
NaiveDateTime::parse_from_str("2023-11-30 15:30:00", "%Y-%m-%d %H:%M:%S").unwrap(),
Interval::Day,
);
assert!(request.validate_date_range().is_ok());
Sourcepub fn new_validated(
instrument_token: u32,
from: NaiveDateTime,
to: NaiveDateTime,
interval: Interval,
) -> Result<Self, String>
pub fn new_validated( instrument_token: u32, from: NaiveDateTime, to: NaiveDateTime, interval: Interval, ) -> Result<Self, String>
Create a new historical data request with automatic validation
This is an alternative constructor that validates the date range against API limits before creating the request.
§Arguments
instrument_token
- Instrument tokenfrom
- Start date and timeto
- End date and timeinterval
- Time interval
§Returns
Ok(HistoricalDataRequest)
if validation passesErr(String)
if validation fails
§Example
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;
let request = HistoricalDataRequest::new_validated(
738561,
NaiveDateTime::parse_from_str("2023-11-01 09:15:00", "%Y-%m-%d %H:%M:%S").unwrap(),
NaiveDateTime::parse_from_str("2023-11-30 15:30:00", "%Y-%m-%d %H:%M:%S").unwrap(),
Interval::Day,
)?;
Sourcepub fn split_into_valid_requests(&self) -> Vec<Self>
pub fn split_into_valid_requests(&self) -> Vec<Self>
Split a large date range into multiple smaller requests that respect API limits
If the requested date range exceeds the maximum allowed for the interval, this method splits it into multiple smaller requests that can be made separately.
§Returns
Vector of HistoricalDataRequest
objects, each within API limits
§Example
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;
// Request 200 days of 5-minute data (exceeds 90-day limit)
let request = HistoricalDataRequest::new(
738561,
NaiveDateTime::parse_from_str("2023-01-01 09:15:00", "%Y-%m-%d %H:%M:%S").unwrap(),
NaiveDateTime::parse_from_str("2023-07-20 15:30:00", "%Y-%m-%d %H:%M:%S").unwrap(),
Interval::FiveMinute,
);
let sub_requests = request.split_into_valid_requests();
println!("Split into {} requests", sub_requests.len());
Sourcepub fn split_into_valid_requests_reverse(&self) -> Vec<Self>
pub fn split_into_valid_requests_reverse(&self) -> Vec<Self>
Split a large date range into multiple smaller requests in reverse chronological order
This method splits the request from newest to oldest dates, which is more efficient for early termination when data is not available for older periods.
§Returns
Vector of HistoricalDataRequest
objects in reverse chronological order (newest first)
§Example
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;
// Request 200 days of 5-minute data (exceeds 90-day limit)
let request = HistoricalDataRequest::new(
738561,
NaiveDateTime::parse_from_str("2023-01-01 09:15:00", "%Y-%m-%d %H:%M:%S").unwrap(),
NaiveDateTime::parse_from_str("2023-07-20 15:30:00", "%Y-%m-%d %H:%M:%S").unwrap(),
Interval::FiveMinute,
);
let sub_requests = request.split_into_valid_requests_reverse();
println!("Split into {} requests (newest first)", sub_requests.len());
Sourcepub fn days_span(&self) -> i64
pub fn days_span(&self) -> i64
Get the number of days in this request
§Returns
Number of days between from and to dates
§Example
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;
let request = HistoricalDataRequest::new(
738561,
NaiveDateTime::parse_from_str("2023-11-01 09:15:00", "%Y-%m-%d %H:%M:%S").unwrap(),
NaiveDateTime::parse_from_str("2023-11-30 15:30:00", "%Y-%m-%d %H:%M:%S").unwrap(),
Interval::Day,
);
println!("Request spans {} days", request.days_span());
Sourcepub fn is_within_limits(&self) -> bool
pub fn is_within_limits(&self) -> bool
Check if this request is within API limits
§Returns
true
if the request is within limits, false
otherwise
Sourcepub async fn fetch_with_chunking(
self,
client: &KiteConnect,
continue_on_error: bool,
) -> KiteResult<HistoricalData>
pub async fn fetch_with_chunking( self, client: &KiteConnect, continue_on_error: bool, ) -> KiteResult<HistoricalData>
Create a helper for fetching data with automatic chunking
This method creates a convenient interface for fetching historical data that automatically handles large date ranges by splitting them into multiple API calls. This provides the best user experience.
§Arguments
client
- The KiteConnect client to use for API callscontinue_on_error
- Whether to continue if a chunk fails (default: false)
§Returns
A Result<HistoricalData>
containing all candles from the entire date range
§Example
use kiteconnect_async_wasm::connect::KiteConnect;
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;
let client = KiteConnect::new("api_key", "access_token");
// Create request for large date range
let request = HistoricalDataRequest::new(
738561,
NaiveDateTime::parse_from_str("2023-01-01 09:15:00", "%Y-%m-%d %H:%M:%S")?,
NaiveDateTime::parse_from_str("2023-12-31 15:30:00", "%Y-%m-%d %H:%M:%S")?,
Interval::Day,
);
// Fetch with automatic chunking - single call handles everything!
let all_data = request.fetch_with_chunking(&client, false).await?;
println!("Retrieved {} candles for the entire year!", all_data.candles.len());
§Features
- Transparent: Works exactly like a single API call from user perspective
- Automatic: Detects when chunking is needed and handles it automatically
- Fast Path: Uses regular API for requests within limits (no overhead)
- Robust: Optional error recovery for failed chunks
- Progress: Logs progress for large requests (when debug enabled)
Sourcepub async fn fetch(self, client: &KiteConnect) -> KiteResult<HistoricalData>
pub async fn fetch(self, client: &KiteConnect) -> KiteResult<HistoricalData>
Convenience method for fetching data with default error handling
This is equivalent to fetch_with_chunking(client, false)
- stops on first error.
Use this for most cases where you want all data or nothing.
§Example
use kiteconnect_async_wasm::connect::KiteConnect;
use kiteconnect_async_wasm::models::market_data::HistoricalDataRequest;
use kiteconnect_async_wasm::models::common::Interval;
use chrono::NaiveDateTime;
let client = KiteConnect::new("api_key", "access_token");
let data = HistoricalDataRequest::new(
738561,
NaiveDateTime::parse_from_str("2023-01-01 09:15:00", "%Y-%m-%d %H:%M:%S")?,
NaiveDateTime::parse_from_str("2024-01-01 15:30:00", "%Y-%m-%d %H:%M:%S")?,
Interval::Day,
).fetch(&client).await?;
println!("Got {} candles", data.candles.len());
Trait Implementations§
Source§impl Clone for HistoricalDataRequest
impl Clone for HistoricalDataRequest
Source§fn clone(&self) -> HistoricalDataRequest
fn clone(&self) -> HistoricalDataRequest
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source
. Read more