Struct KiteConnect

Source
pub struct KiteConnect { /* private fields */ }
Expand description

Main client for interacting with the KiteConnect API

This struct provides async methods for all KiteConnect REST API endpoints. It handles authentication, request formatting, and response parsing automatically.

§Thread Safety

KiteConnect implements Clone + Send + Sync, making it safe to use across multiple threads and async tasks. The underlying HTTP client uses connection pooling for optimal performance.

§Example

use kiteconnect_async_wasm::connect::KiteConnect;

// Create a new client
let mut client = KiteConnect::new("your_api_key", "");

// Set access token (usually done via generate_session)
client.set_access_token("your_access_token");

// Use the API
let holdings = client.holdings().await?;
println!("Holdings: {:?}", holdings);

§Cloning for Concurrent Use

use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

// Clone for use in different tasks
let client1 = client.clone();
let client2 = client.clone();

// Fetch data concurrently
let (holdings, positions) = tokio::try_join!(
    client1.holdings(),
    client2.positions()
)?;

Implementations§

Source§

impl KiteConnect

Source

pub fn login_url(&self) -> String

Generates the KiteConnect login URL for user authentication

This URL should be opened in a browser to allow the user to log in to their Zerodha account. After successful login, the user will be redirected to your redirect URL with a request_token parameter.

§Returns

A login URL string that can be opened in a browser

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("your_api_key", "");
let login_url = client.login_url();

println!("Please visit: {}", login_url);
// User visits URL, logs in, and is redirected with request_token
§Authentication Flow
  1. Generate login URL with this method
  2. Direct user to the URL in a browser
  3. User completes login and is redirected with request_token parameter
  4. Use generate_session() with the request token to get access token
Source

pub async fn generate_session( &mut self, request_token: &str, api_secret: &str, ) -> Result<JsonValue>

Generates an access token using the request token from login

This method completes the authentication flow by exchanging the request token (obtained after user login) for an access token that can be used for API calls. The access token is automatically stored in the client instance.

§Arguments
  • request_token - The request token received after user login
  • api_secret - Your KiteConnect API secret
§Returns

A Result<JsonValue> containing the session information including access token

§Errors

Returns an error if:

  • The request token is invalid or expired
  • The API secret is incorrect
  • Network request fails
  • Response parsing fails
§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let mut client = KiteConnect::new("your_api_key", "");

// After user completes login and you receive the request_token
let session_data = client
    .generate_session("request_token_from_callback", "your_api_secret")
    .await?;

println!("Session created: {:?}", session_data);
// Access token is now automatically set in the client
§Authentication Flow
  1. Call login_url() to get login URL
  2. User visits URL and completes login
  3. User is redirected with request_token parameter
  4. Call this method with the request token and API secret
  5. Access token is automatically set for subsequent API calls
Source

pub async fn invalidate_access_token( &self, access_token: &str, ) -> Result<JsonValue>

Invalidates the access token

This call invalidates the access_token and destroys the API session. After this, the user should be sent through a new login flow before further interactions. This does not log the user out of the official Kite web or mobile applications.

§Arguments
  • access_token - The access token to invalidate
§Returns

A Result<JsonValue> containing the success response

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("your_api_key", "access_token");

let result = client.invalidate_access_token("access_token").await?;
println!("Session invalidated: {:?}", result);
Source

pub async fn renew_access_token( &mut self, access_token: &str, api_secret: &str, ) -> Result<JsonValue>

Request for new access token

Source

pub async fn invalidate_refresh_token( &self, refresh_token: &str, ) -> Result<Response>

Invalidates the refresh token

Source

pub async fn generate_session_typed( &mut self, request_token: &str, api_secret: &str, ) -> KiteResult<SessionData>

Generates session with typed response

Returns strongly typed session data instead of JsonValue. This is the preferred method for new applications.

§Arguments
  • request_token - The request token received after user login
  • api_secret - Your KiteConnect API secret
§Returns

A KiteResult<SessionData> containing typed session information

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let mut client = KiteConnect::new("your_api_key", "");

let session = client.generate_session_typed("request_token", "api_secret").await?;
println!("Access token: {}", session.access_token);
println!("User ID: {}", session.user_id);
Source

pub async fn profile_typed(&self) -> KiteResult<UserProfile>

Get user profile with typed response

Returns strongly typed user profile data instead of JsonValue.

§Returns

A KiteResult<UserProfile> containing typed user profile information

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let profile = client.profile_typed().await?;
println!("User: {} ({})", profile.user_name, profile.email);
Source

pub async fn invalidate_access_token_typed( &self, access_token: &str, ) -> KiteResult<bool>

Invalidates access token with typed response

Returns strongly typed logout response instead of JsonValue. This is the preferred method for new applications.

§Arguments
  • access_token - The access token to invalidate
§Returns

A KiteResult<bool> indicating success (true) or failure

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let success = client.invalidate_access_token_typed("access_token").await?;
println!("Session invalidated: {}", success);
Source§

impl KiteConnect

Source

pub async fn get_gtts(&self, gtt_id: Option<&str>) -> Result<JsonValue>

Get all GTT orders or details of a specific GTT

Retrieves all Good Till Triggered (GTT) orders or details of a specific GTT order. GTT orders are conditional orders that get executed when certain trigger conditions are met.

§Arguments
  • gtt_id - Optional GTT ID. If None, returns all GTT orders
§Returns

A Result<JsonValue> containing GTT orders data

§Errors

Returns an error if the API request fails or the user is not authenticated.

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

// Get all GTT orders
let all_gtts = client.get_gtts(None).await?;
println!("All GTTs: {:?}", all_gtts);

// Get specific GTT
let gtt_details = client.get_gtts(Some("123456")).await?;
println!("GTT details: {:?}", gtt_details);
Source

pub async fn place_gtt( &self, trigger_type: &str, tradingsymbol: &str, exchange: &str, trigger_values: &[f64], last_price: f64, orders: &[JsonValue], ) -> Result<JsonValue>

Place a GTT order

Creates a new Good Till Triggered order that will be executed when the specified trigger conditions are met.

§Arguments
  • trigger_type - Type of trigger (“single” or “two-leg”)
  • tradingsymbol - Trading symbol of the instrument
  • exchange - Exchange where the instrument is traded
  • trigger_values - Trigger price values
  • last_price - Current market price of the instrument
  • orders - List of orders to be placed when triggered
§Returns

A Result<JsonValue> containing GTT order creation response

§Errors

Returns an error if the GTT placement fails or parameters are invalid

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let gtt = client.place_gtt(
    "single",
    "RELIANCE",
    "NSE",
    &[2500.0], // Trigger when price hits 2500
    2450.0,    // Current price
    &[serde_json::json!({
        "transaction_type": "SELL",
        "quantity": 10,
        "order_type": "LIMIT",
        "product": "CNC",
        "price": 2500.0
    })]
).await?;

println!("GTT placed: {:?}", gtt);
Source

pub async fn modify_gtt( &self, gtt_id: &str, trigger_type: &str, tradingsymbol: &str, exchange: &str, trigger_values: &[f64], last_price: f64, orders: &[JsonValue], ) -> Result<JsonValue>

Modify a GTT order

Updates an existing GTT order with new trigger conditions or orders.

§Arguments
  • gtt_id - GTT order ID to modify
  • trigger_type - Type of trigger (“single” or “two-leg”)
  • tradingsymbol - Trading symbol of the instrument
  • exchange - Exchange where the instrument is traded
  • trigger_values - New trigger price values
  • last_price - Current market price of the instrument
  • orders - Updated list of orders to be placed when triggered
§Returns

A Result<JsonValue> containing GTT order modification response

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let result = client.modify_gtt(
    "123456",  // GTT ID
    "single",
    "RELIANCE",
    "NSE",
    &[2600.0], // New trigger price
    2450.0,    // Current price
    &[serde_json::json!({
        "transaction_type": "SELL",
        "quantity": 20,  // Updated quantity
        "order_type": "LIMIT",
        "product": "CNC",
        "price": 2600.0
    })]
).await?;

println!("GTT modified: {:?}", result);
Source

pub async fn delete_gtt(&self, gtt_id: &str) -> Result<JsonValue>

Delete a GTT order

Cancels an existing GTT order. Once deleted, the GTT will no longer monitor for trigger conditions.

§Arguments
  • gtt_id - GTT order ID to delete
§Returns

A Result<JsonValue> containing deletion confirmation

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let result = client.delete_gtt("123456").await?;
println!("GTT deleted: {:?}", result);
Source§

impl KiteConnect

Source

pub async fn trigger_range( &self, transaction_type: &str, instruments: Vec<&str>, ) -> Result<JsonValue>

Get the trigger range for a list of instruments

Source

pub async fn instruments(&self, exchange: Option<&str>) -> Result<JsonValue>

Get instruments list

Source

pub async fn mf_instruments(&self) -> Result<JsonValue>

Get mutual fund instruments list

Source

pub async fn historical_data( &self, instrument_token: &str, from_date: &str, to_date: &str, interval: &str, continuous: &str, ) -> Result<JsonValue>

Retrieves historical candlestick data for an instrument

Returns historical OHLCV (Open, High, Low, Close, Volume) data for a given instrument within the specified date range and interval. This is useful for backtesting, analysis, and charting applications.

§Arguments
  • instrument_token - The instrument token (numeric ID) of the instrument
  • from_date - Start date in YYYY-MM-DD format
  • to_date - End date in YYYY-MM-DD format
  • interval - Time interval for candlesticks (“minute”, “day”, “3minute”, “5minute”, “10minute”, “15minute”, “30minute”, “60minute”)
  • continuous - Whether to include pre-market and post-market data (“1” for true, “0” for false)
§Returns

A Result<JsonValue> containing historical data with fields like:

  • data - Array of candlestick data points
    • date - ISO datetime string
    • open - Opening price
    • high - Highest price
    • low - Lowest price
    • close - Closing price
    • volume - Trading volume
§Errors

Returns an error if:

  • The instrument token is invalid
  • The date range is invalid or too large
  • The interval is not supported
  • Network request fails
  • User is not authenticated
§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

// Get daily data for RELIANCE for the last month
let historical_data = client.historical_data(
    "738561",           // RELIANCE instrument token
    "2023-11-01",       // From date
    "2023-11-30",       // To date
    "day",              // Daily interval
    "0"                 // No continuous data
).await?;

println!("Historical data: {:?}", historical_data);

// Access candlestick data
if let Some(data) = historical_data["data"].as_array() {
    for candle in data {
        println!("Date: {}, Close: {}, Volume: {}",
            candle["date"], candle["close"], candle["volume"]);
    }
}
§Notes
  • Historical data is subject to availability and may have limitations based on your subscription
  • Large date ranges may be split into multiple requests automatically
  • Intraday data older than a certain period may not be available
  • Weekend and holiday data will not be included in the response
Source

pub async fn quote(&self, instruments: Vec<&str>) -> Result<JsonValue>

Retrieve quote and market depth for list of instruments

Gets real-time quote data including bid/ask prices, market depth, and other market data for the specified instruments.

§Arguments
  • instruments - List of instrument identifiers (exchange:tradingsymbol or instrument_token)
§Returns

A Result<JsonValue> containing quote data with fields like:

  • last_price - Last traded price
  • ohlc - Open, High, Low, Close data
  • market_depth - Bid/Ask data with quantities
  • volume - Trading volume
§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let instruments = vec!["NSE:RELIANCE", "BSE:SENSEX"];
let quotes = client.quote(instruments).await?;

println!("Quotes: {:?}", quotes);
Source

pub async fn ohlc(&self, instruments: Vec<&str>) -> Result<JsonValue>

Retrieve OHLC (Open, High, Low, Close) data for instruments

Gets OHLC data for the current trading day for the specified instruments.

§Arguments
  • instruments - List of instrument identifiers
§Returns

A Result<JsonValue> containing OHLC data

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let instruments = vec!["NSE:RELIANCE", "NSE:TCS"];
let ohlc_data = client.ohlc(instruments).await?;

println!("OHLC Data: {:?}", ohlc_data);
Source

pub async fn ltp(&self, instruments: Vec<&str>) -> Result<JsonValue>

Retrieve Last Traded Price (LTP) for instruments

Gets the last traded price for the specified instruments. This is a lightweight alternative to the full quote API.

§Arguments
  • instruments - List of instrument identifiers
§Returns

A Result<JsonValue> containing last traded prices

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let instruments = vec!["NSE:RELIANCE", "NSE:TCS"];
let ltp_data = client.ltp(instruments).await?;

println!("LTP Data: {:?}", ltp_data);
Source

pub async fn instruments_margins(&self, segment: &str) -> Result<JsonValue>

Retrieve margin requirements for specific trading segments

Gets margin requirements and charges for different trading segments like equity, commodity, currency, etc.

§Arguments
  • segment - Trading segment (“equity”, “commodity”, “currency”)
§Returns

A Result<JsonValue> containing margin requirements data

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let equity_margins = client.instruments_margins("equity").await?;
println!("Equity margins: {:?}", equity_margins);
Source

pub async fn quote_typed( &self, instruments: Vec<&str>, ) -> KiteResult<Vec<Quote>>

Get real-time quotes with typed response

Returns strongly typed quote data instead of JsonValue.

§Arguments
  • instruments - List of instrument identifiers
§Returns

A KiteResult<Vec<Quote>> containing typed quote data

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let instruments = vec!["NSE:RELIANCE", "BSE:SENSEX"];
let quotes = client.quote_typed(instruments).await?;
for quote in quotes {
    println!("Symbol: {}, LTP: {}", quote.trading_symbol, quote.last_price);
}
Source

pub async fn ohlc_typed(&self, instruments: Vec<&str>) -> KiteResult<Vec<OHLC>>

Get OHLC data with typed response

Returns strongly typed OHLC data instead of JsonValue.

§Arguments
  • instruments - List of instrument identifiers
§Returns

A KiteResult<Vec<OHLC>> containing typed OHLC data

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let instruments = vec!["NSE:RELIANCE", "NSE:TCS"];
let ohlc_data = client.ohlc_typed(instruments).await?;
for ohlc in ohlc_data {
    println!("Open: {}, High: {}, Low: {}, Close: {}",
        ohlc.open, ohlc.high, ohlc.low, ohlc.close);
}
Source

pub async fn ltp_typed(&self, instruments: Vec<&str>) -> KiteResult<Vec<LTP>>

Get Last Traded Price (LTP) with typed response

Returns strongly typed LTP data instead of JsonValue.

§Arguments
  • instruments - List of instrument identifiers
§Returns

A KiteResult<Vec<LTP>> containing typed LTP data

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let instruments = vec!["NSE:RELIANCE", "NSE:TCS"];
let ltp_data = client.ltp_typed(instruments).await?;
for ltp in ltp_data {
    println!("Token: {}, LTP: {}", ltp.instrument_token, ltp.last_price);
}
Source

pub async fn historical_data_typed( &self, request: HistoricalDataRequest, ) -> KiteResult<HistoricalData>

Get historical data with typed response

Returns strongly typed historical data instead of JsonValue.

§Arguments
  • request - A HistoricalDataRequest containing all the parameters for the request
§Returns

A KiteResult<HistoricalData> containing typed historical data

§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 request = HistoricalDataRequest::new(
    738561,             // RELIANCE instrument token
    NaiveDateTime::parse_from_str("2023-11-01 00:00:00", "%Y-%m-%d %H:%M:%S")?,
    NaiveDateTime::parse_from_str("2023-11-30 23:59:59", "%Y-%m-%d %H:%M:%S")?,
    Interval::Day,
).continuous(false);

let historical_data = client.historical_data_typed(request).await?;

for candle in &historical_data.candles {
    println!("Date: {}, Close: {}, Volume: {}",
        candle.date, candle.close, candle.volume);
}
Source§

impl KiteConnect

Source

pub async fn mf_orders(&self, order_id: Option<&str>) -> Result<JsonValue>

Get all mutual fund orders or individual order info

Source

pub async fn place_mf_order( &self, tradingsymbol: &str, transaction_type: &str, quantity: Option<&str>, amount: Option<&str>, tag: Option<&str>, ) -> Result<JsonValue>

Place a mutual fund order

Places a mutual fund buy or sell order. For buy orders, you can specify either quantity (units) or amount (monetary value). For sell orders, quantity is required.

§Arguments
  • tradingsymbol - Trading symbol of the mutual fund
  • transaction_type - “BUY” or “SELL”
  • quantity - Quantity (units) for the order (optional for buy orders)
  • amount - Amount in rupees for buy orders (alternative to quantity)
  • tag - Optional tag to identify orders
§Returns

A Result<JsonValue> containing order confirmation with order_id

§Errors

Returns an error if the order placement fails or parameters are invalid

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

// Buy order with amount
let buy_order = client.place_mf_order(
    "INF846K01DP8",    // MF trading symbol
    "BUY",             // Transaction type
    None,              // No quantity
    Some("1000"),      // Amount in rupees
    Some("my_tag")     // Optional tag
).await?;

println!("Order placed: {:?}", buy_order);
Source

pub async fn cancel_mf_order(&self, order_id: &str) -> Result<JsonValue>

Cancel a mutual fund order

Cancels a pending mutual fund order. Only orders in OPEN status can be cancelled.

§Arguments
  • order_id - The mutual fund order ID to cancel
§Returns

A Result<JsonValue> containing cancellation confirmation

§Errors

Returns an error if the order cannot be cancelled or doesn’t exist

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let result = client.cancel_mf_order("123456789").await?;
println!("Cancellation result: {:?}", result);
Source

pub async fn mf_sips(&self, sip_id: Option<&str>) -> Result<JsonValue>

Get mutual fund SIPs (Systematic Investment Plans)

Retrieves all active SIPs or details of a specific SIP.

§Arguments
  • sip_id - Optional SIP ID. If None, returns all SIPs
§Returns

A Result<JsonValue> containing SIP information

§Errors

Returns an error if the API request fails

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

// Get all SIPs
let all_sips = client.mf_sips(None).await?;

// Get specific SIP
let sip_details = client.mf_sips(Some("123456")).await?;
Source

pub async fn place_mf_sip( &self, tradingsymbol: &str, amount: &str, instalments: &str, frequency: &str, initial_amount: Option<&str>, instalment_day: Option<&str>, tag: Option<&str>, ) -> Result<JsonValue>

Place a mutual fund SIP (Systematic Investment Plan)

Creates a new SIP for systematic investment in mutual funds.

§Arguments
  • tradingsymbol - Trading symbol of the mutual fund
  • amount - SIP amount per installment
  • instalments - Total number of installments (max 99 for lifetime)
  • frequency - SIP frequency (“weekly”, “monthly”, “quarterly”)
  • initial_amount - Optional initial lump sum amount
  • instalment_day - Day of month for monthly SIPs (1-28) or day of week for weekly
  • tag - Optional tag to identify the SIP
§Returns

A Result<JsonValue> containing SIP creation confirmation

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let sip = client.place_mf_sip(
    "INF846K01DP8",    // MF trading symbol
    "1000",            // Amount per installment
    "12",              // 12 installments
    "monthly",         // Monthly frequency
    Some("5000"),      // Initial amount
    Some("15"),        // 15th of every month
    Some("retirement_sip") // Tag
).await?;
Source

pub async fn modify_mf_sip( &self, sip_id: &str, amount: &str, status: &str, instalments: &str, frequency: &str, instalment_day: Option<&str>, ) -> Result<JsonValue>

Modify a mutual fund SIP

Modifies an existing SIP’s parameters like amount, frequency, or status.

§Arguments
  • sip_id - The SIP ID to modify
  • amount - New SIP amount per installment
  • status - SIP status (“ACTIVE” or “PAUSED”)
  • instalments - New total number of installments
  • frequency - New SIP frequency
  • instalment_day - New day for installments
§Returns

A Result<JsonValue> containing modification confirmation

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

// Increase SIP amount and change frequency
let result = client.modify_mf_sip(
    "123456",          // SIP ID
    "1500",            // New amount
    "ACTIVE",          // Status
    "24",              // New installment count
    "monthly",         // Frequency
    Some("20")         // New instalment day
).await?;
Source

pub async fn cancel_mf_sip(&self, sip_id: &str) -> Result<JsonValue>

Cancel a mutual fund SIP

Cancels an active SIP. This will stop all future installments.

§Arguments
  • sip_id - The SIP ID to cancel
§Returns

A Result<JsonValue> containing cancellation confirmation

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let result = client.cancel_mf_sip("123456").await?;
println!("SIP cancelled: {:?}", result);
Source

pub async fn mf_holdings(&self) -> Result<JsonValue>

Get mutual fund holdings

Retrieves the user’s mutual fund holdings with current values and returns.

§Returns

A Result<JsonValue> containing mutual fund holdings data

§Errors

Returns an error if the API request fails

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let holdings = client.mf_holdings().await?;
println!("MF Holdings: {:?}", holdings);

// Access specific fields
if let Some(data) = holdings["data"].as_array() {
    for holding in data {
        println!("Fund: {}, Units: {}, Current Value: {}",
            holding["tradingsymbol"],
            holding["quantity"],
            holding["last_price"]);
    }
}
Source

pub async fn mf_orders_typed( &self, order_id: Option<&str>, ) -> KiteResult<Vec<MFOrder>>

Get mutual fund orders with typed response

Returns strongly typed MF order data instead of JsonValue.

§Arguments
  • order_id - Optional order ID. If None, returns all orders
§Returns

A KiteResult<Vec<MFOrder>> for all orders or KiteResult<MFOrder> for specific order

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

// Get all MF orders
let all_orders = client.mf_orders_typed(None).await?;
for order in all_orders {
    println!("Order ID: {}, Status: {:?}", order.order_id, order.status);
}

// Get specific order
let specific_order = client.mf_order_typed("123456").await?;
println!("Order: {:?}", specific_order);
Source

pub async fn mf_order_typed(&self, order_id: &str) -> KiteResult<MFOrder>

Get single mutual fund order with typed response

Returns a single strongly typed MF order.

§Arguments
  • order_id - The order ID to fetch
§Returns

A KiteResult<MFOrder> containing the typed order data

Source

pub async fn place_mf_order_typed( &self, order_params: &MFOrderParams, ) -> KiteResult<MFOrderResponse>

Place a mutual fund order with typed response

Places a mutual fund order and returns typed response.

§Arguments
  • order_params - Typed order parameters
§Returns

A KiteResult<MFOrderResponse> containing order confirmation

§Example
use kiteconnect_async_wasm::connect::KiteConnect;
use kiteconnect_async_wasm::models::mutual_funds::MFOrderParams;
use kiteconnect_async_wasm::models::common::TransactionType;

let client = KiteConnect::new("api_key", "access_token");

let order_params = MFOrderParams {
    trading_symbol: "INF846K01DP8".to_string(),
    transaction_type: TransactionType::BUY,
    amount: Some(1000.0),
    quantity: None,
    tag: Some("my_tag".to_string()),
};

let response = client.place_mf_order_typed(&order_params).await?;
println!("Order placed with ID: {}", response.order_id);
Source

pub async fn mf_sips_typed(&self, sip_id: Option<&str>) -> KiteResult<Vec<SIP>>

Get mutual fund SIPs with typed response

Returns strongly typed SIP data instead of JsonValue.

§Arguments
  • sip_id - Optional SIP ID. If None, returns all SIPs
§Returns

A KiteResult<Vec<SIP>> for all SIPs or KiteResult<SIP> for specific SIP

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

// Get all SIPs
let all_sips = client.mf_sips_typed(None).await?;
for sip in all_sips {
    println!("SIP ID: {}, Status: {:?}", sip.sip_id, sip.status);
}
Source

pub async fn mf_sip_typed(&self, sip_id: &str) -> KiteResult<SIP>

Get single mutual fund SIP with typed response

Returns a single strongly typed SIP.

§Arguments
  • sip_id - The SIP ID to fetch
§Returns

A KiteResult<SIP> containing the typed SIP data

Source

pub async fn place_mf_sip_typed( &self, sip_params: &SIPParams, ) -> KiteResult<SIPResponse>

Place a mutual fund SIP with typed response

Creates a new SIP and returns typed response.

§Arguments
  • sip_params - Typed SIP parameters
§Returns

A KiteResult<SIPResponse> containing SIP creation confirmation

§Example
use kiteconnect_async_wasm::connect::KiteConnect;
use kiteconnect_async_wasm::models::mutual_funds::{SIPParams, SIPFrequency};

let client = KiteConnect::new("api_key", "access_token");

let sip_params = SIPParams {
    trading_symbol: "INF846K01DP8".to_string(),
    amount: 1000.0,
    instalments: Some(12),
    frequency: SIPFrequency::Monthly,
    initial_amount: Some(5000.0),
    tag: Some("retirement_sip".to_string()),
};

let response = client.place_mf_sip_typed(&sip_params).await?;
println!("SIP created with ID: {}", response.sip_id);
Source

pub async fn mf_holdings_typed(&self) -> KiteResult<Vec<MFHolding>>

Get mutual fund holdings with typed response

Returns strongly typed MF holdings data instead of JsonValue.

§Returns

A KiteResult<Vec<MFHolding>> containing typed holdings data

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let holdings = client.mf_holdings_typed().await?;
for holding in holdings {
    println!("Fund: {}, Units: {}, Current Value: {}",
        holding.trading_symbol, holding.quantity, holding.last_price);
}
Source§

impl KiteConnect

Source

pub async fn place_order( &self, variety: &str, exchange: &str, tradingsymbol: &str, transaction_type: &str, quantity: &str, product: Option<&str>, order_type: Option<&str>, price: Option<&str>, validity: Option<&str>, disclosed_quantity: Option<&str>, trigger_price: Option<&str>, squareoff: Option<&str>, stoploss: Option<&str>, trailing_stoploss: Option<&str>, tag: Option<&str>, ) -> Result<JsonValue>

Place an order

Source

pub async fn modify_order( &self, order_id: &str, variety: &str, quantity: Option<&str>, price: Option<&str>, order_type: Option<&str>, validity: Option<&str>, disclosed_quantity: Option<&str>, trigger_price: Option<&str>, parent_order_id: Option<&str>, ) -> Result<JsonValue>

Modify an open order

Source

pub async fn cancel_order( &self, order_id: &str, variety: &str, parent_order_id: Option<&str>, ) -> Result<JsonValue>

Cancel an order

Source

pub async fn exit_order( &self, order_id: &str, variety: &str, parent_order_id: Option<&str>, ) -> Result<JsonValue>

Exit a BO/CO order

Source

pub async fn orders(&self) -> Result<JsonValue>

Retrieves a list of all orders for the current trading day

Returns all orders placed by the user for the current trading day, including pending, completed, rejected, and cancelled orders.

§Returns

A Result<JsonValue> containing orders data with fields like:

  • order_id - Unique order identifier
  • tradingsymbol - Trading symbol
  • quantity - Order quantity
  • price - Order price
  • status - Order status (OPEN, COMPLETE, CANCELLED, REJECTED)
  • order_type - Order type (MARKET, LIMIT, SL, SL-M)
  • product - Product type (MIS, CNC, NRML)
§Errors

Returns an error if the API request fails or the user is not authenticated.

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let orders = client.orders().await?;
println!("Orders: {:?}", orders);

// Check order statuses
if let Some(data) = orders["data"].as_array() {
    for order in data {
        println!("Order {}: {} - {}",
            order["order_id"],
            order["tradingsymbol"],
            order["status"]);
    }
}
Source

pub async fn order_history(&self, order_id: &str) -> Result<JsonValue>

Get the list of order history

Source

pub async fn trades(&self) -> Result<JsonValue>

Get all trades

Source

pub async fn order_trades(&self, order_id: &str) -> Result<JsonValue>

Get all trades for a specific order

Source

pub async fn convert_position( &self, exchange: &str, tradingsymbol: &str, transaction_type: &str, position_type: &str, quantity: &str, old_product: &str, new_product: &str, ) -> Result<JsonValue>

Modify an open position product type

Source

pub async fn place_order_typed( &self, variety: &str, order_params: &OrderParams, ) -> KiteResult<OrderResponse>

Place an order with typed response

Returns strongly typed order response instead of JsonValue. This is the preferred method for new applications.

§Arguments
  • variety - Order variety (“regular”, “bo”, “co”, etc.)
  • order_params - Typed order parameters struct
§Returns

A KiteResult<OrderResponse> containing the order ID

§Example
use kiteconnect_async_wasm::connect::KiteConnect;
use kiteconnect_async_wasm::models::orders::OrderParams;
use kiteconnect_async_wasm::models::common::{Exchange, Product, OrderType, TransactionType, Validity};

let client = KiteConnect::new("api_key", "access_token");

let params = OrderParams {
    trading_symbol: "INFY".to_string(),
    exchange: Exchange::NSE,
    transaction_type: TransactionType::BUY,
    quantity: 1,
    order_type: OrderType::LIMIT,
    product: Product::CNC,
    price: Some(1500.0),
    validity: Some(Validity::DAY),
    disclosed_quantity: None,
    trigger_price: None,
    squareoff: None,
    stoploss: None,
    trailing_stoploss: None,
    market_protection: None,
    iceberg_legs: None,
    iceberg_quantity: None,
    auction_number: None,
    tag: None,
};

let order_response = client.place_order_typed("regular", &params).await?;
println!("Order ID: {}", order_response.order_id);
Source

pub async fn orders_typed(&self) -> KiteResult<Vec<Order>>

Get all orders with typed response

Returns strongly typed list of orders instead of JsonValue.

§Returns

A KiteResult<Vec<Order>> containing typed order information

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let orders = client.orders_typed().await?;
for order in orders {
    println!("Order {}: {} - {:?}",
        order.order_id,
        order.trading_symbol,
        order.status);
}
Source

pub async fn trades_typed(&self) -> KiteResult<Vec<Trade>>

Get all trades with typed response

Returns strongly typed list of trades instead of JsonValue.

§Returns

A KiteResult<Vec<Trade>> containing typed trade information

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let trades = client.trades_typed().await?;
for trade in trades {
    println!("Trade {}: {} @ {}",
        trade.trade_id,
        trade.quantity,
        trade.average_price);
}
Source

pub async fn order_trades_typed(&self, order_id: &str) -> KiteResult<Vec<Trade>>

Get trades for specific order with typed response

Returns strongly typed list of trades for a specific order instead of JsonValue.

§Arguments
  • order_id - The order ID to get trades for
§Returns

A KiteResult<Vec<Trade>> containing typed trade information

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let trades = client.order_trades_typed("order_id").await?;
for trade in trades {
    println!("Trade executed: {} @ {}", trade.quantity, trade.average_price);
}
Source§

impl KiteConnect

Source

pub async fn margins(&self, segment: Option<String>) -> Result<JsonValue>

Retrieves account balance and margin details

Returns margin information for trading segments including available cash, used margins, and available margins for different product types.

§Arguments
  • segment - Optional trading segment (“equity” or “commodity”). If None, returns all segments
§Returns

A Result<JsonValue> containing margin data with fields like:

  • available - Available margin for trading
  • utilised - Currently utilized margin
  • net - Net available margin
  • enabled - Whether the segment is enabled
§Errors

Returns an error if the API request fails or the user is not authenticated.

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

// Get margins for all segments
let all_margins = client.margins(None).await?;
println!("All margins: {:?}", all_margins);

// Get margins for specific segment
let equity_margins = client.margins(Some("equity".to_string())).await?;
println!("Equity available margin: {}",
    equity_margins["data"]["available"]["live_balance"]);
Source

pub async fn profile(&self) -> Result<JsonValue>

Get user profile details

Source

pub async fn holdings(&self) -> Result<JsonValue>

Retrieves the user’s holdings (stocks held in demat account)

Holdings represent stocks that are held in the user’s demat account. This includes information about quantity, average price, current market value, profit/loss, and more.

§Returns

A Result<JsonValue> containing holdings data with fields like:

  • tradingsymbol - Trading symbol of the instrument
  • quantity - Total quantity held
  • average_price - Average buying price
  • last_price - Current market price
  • pnl - Profit and loss
  • product - Product type (CNC, MIS, etc.)
§Errors

Returns an error if the API request fails or the user is not authenticated.

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let holdings = client.holdings().await?;
println!("Holdings: {:?}", holdings);

// Access specific fields
if let Some(data) = holdings["data"].as_array() {
    for holding in data {
        println!("Symbol: {}, Quantity: {}",
            holding["tradingsymbol"], holding["quantity"]);
    }
}
Source

pub async fn positions(&self) -> Result<JsonValue>

Retrieves the user’s positions (open positions for the day)

Positions represent open trading positions for the current trading day. This includes both intraday and carry-forward positions with details about profit/loss, margin requirements, and position status.

§Returns

A Result<JsonValue> containing positions data with fields like:

  • tradingsymbol - Trading symbol of the instrument
  • quantity - Net position quantity
  • buy_quantity - Total buy quantity
  • sell_quantity - Total sell quantity
  • average_price - Average position price
  • pnl - Realized and unrealized P&L
  • product - Product type (MIS, CNC, NRML)
§Errors

Returns an error if the API request fails or the user is not authenticated.

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let positions = client.positions().await?;
println!("Positions: {:?}", positions);

// Check for open positions
if let Some(day_positions) = positions["data"]["day"].as_array() {
    for position in day_positions {
        if position["quantity"].as_i64().unwrap_or(0) != 0 {
            println!("Open position: {} qty {}",
                position["tradingsymbol"], position["quantity"]);
        }
    }
}
Source

pub async fn margins_typed( &self, segment: Option<&str>, ) -> KiteResult<MarginData>

Get user margins with typed response

Returns strongly typed margin data instead of JsonValue.

§Arguments
  • segment - Optional trading segment (“equity” or “commodity”)
§Returns

A KiteResult<MarginData> containing typed margin information

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let margins = client.margins_typed(None).await?;
println!("Available equity margin: {}", margins.equity.unwrap().available.cash);
Source

pub async fn holdings_typed(&self) -> KiteResult<Vec<Holding>>

Get user holdings with typed response

Returns a vector of strongly typed holding objects instead of JsonValue.

§Returns

A KiteResult<Vec<Holding>> containing typed holdings data

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let holdings = client.holdings_typed().await?;
for holding in holdings {
    println!("Symbol: {}, Quantity: {}, P&L: {}",
        holding.trading_symbol, holding.quantity, holding.pnl);
}
Source

pub async fn positions_typed(&self) -> KiteResult<Vec<Position>>

Get user positions with typed response

Returns structured position data instead of JsonValue.

§Returns

A KiteResult<Vec<Position>> containing typed positions data

§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let client = KiteConnect::new("api_key", "access_token");

let positions = client.positions_typed().await?;
for position in &positions {
    if position.quantity != 0 {
        println!("Open position: {} qty {}",
            position.trading_symbol, position.quantity);
    }
}
Source

pub async fn convert_position_typed( &self, request: &ConversionRequest, ) -> KiteResult<bool>

Convert positions between product types (typed)

Converts a position from one product type to another (e.g., MIS to CNC).

§Arguments
  • request - Conversion request details
§Returns

A KiteResult<bool> indicating success

§Example
use kiteconnect_async_wasm::connect::KiteConnect;
use kiteconnect_async_wasm::models::portfolio::ConversionRequest;
use kiteconnect_async_wasm::models::common::{Exchange, Product, TransactionType};

let client = KiteConnect::new("api_key", "access_token");

let conversion = ConversionRequest {
    exchange: Exchange::NSE,
    trading_symbol: "RELIANCE".to_string(),
    transaction_type: TransactionType::BUY,
    quantity: 10,
    from_product: Product::MIS,
    to_product: Product::CNC,
};

let success = client.convert_position_typed(&conversion).await?;
println!("Conversion successful: {}", success);
Source§

impl KiteConnect

Source

pub fn new(api_key: &str, access_token: &str) -> Self

Creates a new KiteConnect client instance

§Arguments
  • api_key - Your KiteConnect API key
  • access_token - Access token (can be empty string if using generate_session)
§Example
use kiteconnect_async_wasm::connect::KiteConnect;

// Create client for authentication flow
let mut client = KiteConnect::new("your_api_key", "");

// Or create with existing access token
let client = KiteConnect::new("your_api_key", "your_access_token");
Source

pub fn new_with_config(api_key: &str, config: KiteConnectConfig) -> Self

Creates a new KiteConnect client with custom configuration

§Arguments
  • api_key - Your KiteConnect API key
  • config - Configuration for the client
§Example
use kiteconnect_async_wasm::connect::{KiteConnect, KiteConnectConfig, RetryConfig};
use std::time::Duration;

let config = KiteConnectConfig {
    retry_config: RetryConfig {
        max_retries: 5,
        base_delay: Duration::from_millis(100),
        ..Default::default()
    },
    ..Default::default()
};

let mut client = KiteConnect::new_with_config("your_api_key", config);
client.set_access_token("your_access_token");
Source

pub fn set_session_expiry_hook(&mut self, method: fn())

Sets a session expiry callback hook for this instance

This hook will be called when a session expires, allowing you to handle re-authentication or cleanup logic.

§Arguments
  • method - Callback function to execute on session expiry
§Example
use kiteconnect_async_wasm::connect::KiteConnect;

fn handle_session_expiry() {
    println!("Session expired! Please re-authenticate.");
}

let mut client = KiteConnect::new("api_key", "access_token");
client.set_session_expiry_hook(handle_session_expiry);
Source

pub fn session_expiry_hook(&self) -> Option<fn()>

Gets the current session expiry hook

Returns the session expiry callback function if one has been set.

§Returns

Option<fn() -> ()> - The callback function, or None if not set

Source

pub fn set_access_token(&mut self, access_token: &str)

Sets the access token for authenticated API requests

This is typically called automatically by generate_session, but can be used manually if you have a pre-existing access token.

§Arguments
  • access_token - The access token string
§Example
use kiteconnect_async_wasm::connect::KiteConnect;

let mut client = KiteConnect::new("api_key", "");
client.set_access_token("your_access_token");
Source

pub fn access_token(&self) -> &str

Gets the access token for this instance

Source

pub fn request_count(&self) -> u64

Gets the current request count for monitoring

Source

pub async fn rate_limiter_stats(&self) -> RateLimiterStats

Get rate limiter statistics for monitoring

Source

pub fn set_rate_limiting_enabled(&mut self, enabled: bool)

Enable or disable rate limiting

Source

pub fn is_rate_limiting_enabled(&self) -> bool

Check if rate limiting is enabled

Source

pub async fn can_request_immediately(&self, endpoint: &KiteEndpoint) -> bool

Check if a request can be made without waiting

Source

pub async fn get_delay_for_request(&self, endpoint: &KiteEndpoint) -> Duration

Get the delay required before making a request

Source

pub async fn wait_for_request(&self, endpoint: &KiteEndpoint)

Wait for rate limit compliance before making a request

Trait Implementations§

Source§

impl Clone for KiteConnect

Source§

fn clone(&self) -> KiteConnect

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

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

Performs copy-assignment from source. Read more
Source§

impl Debug for KiteConnect

Source§

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

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

impl Default for KiteConnect

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl RequestHandler for KiteConnect

Implement the async request handler for KiteConnect struct

Source§

async fn send_request( &self, url: Url, method: &str, data: Option<HashMap<&str, &str>>, ) -> Result<Response>

Send an HTTP request with the specified parameters 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> ErasedDestructor for T
where T: 'static,