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 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 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 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
  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<Response>

Invalidates the access token

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 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 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 mf_orders(&self, order_id: Option<&str>) -> Result<JsonValue>

Get all mutual fund orders or individual order info

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

Trait Implementations§

Source§

impl Clone for KiteConnect

Source§

fn clone(&self) -> KiteConnect

Returns a copy 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 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

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.

§

impl<T> Instrument for T

§

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

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

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.

§

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

§

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
§

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.
§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

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