Struct HistoricalDataRequest

Source
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 intervals
  • Day: 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 data
  • false: 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

Source

pub fn new( instrument_token: u32, from: NaiveDateTime, to: NaiveDateTime, interval: Interval, ) -> Self

Create a new historical data request

Source

pub fn continuous(self, continuous: bool) -> Self

Enable continuous data for futures

Source

pub fn with_oi(self, oi: bool) -> Self

Include open interest data

Source

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 valid
  • Err(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());
Source

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 token
  • from - Start date and time
  • to - End date and time
  • interval - Time interval
§Returns
  • Ok(HistoricalDataRequest) if validation passes
  • Err(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,
)?;
Source

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());
Source

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());
Source

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());
Source

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

Source

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 calls
  • continue_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)
Source

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

Source§

fn clone(&self) -> HistoricalDataRequest

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for HistoricalDataRequest

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for HistoricalDataRequest

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for HistoricalDataRequest

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,