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::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::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
impl KiteConnect
Sourcepub fn new(api_key: &str, access_token: &str) -> Self
pub fn new(api_key: &str, access_token: &str) -> Self
Creates a new KiteConnect client instance
§Arguments
api_key- Your KiteConnect API keyaccess_token- Access token (can be empty string if usinggenerate_session)
§Example
use kiteconnect::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");Sourcepub fn set_session_expiry_hook(&mut self, method: fn())
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::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);Sourcepub fn session_expiry_hook(&self) -> Option<fn()>
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
Sourcepub fn set_access_token(&mut self, access_token: &str)
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::connect::KiteConnect;
let mut client = KiteConnect::new("api_key", "");
client.set_access_token("your_access_token");Sourcepub fn access_token(&self) -> &str
pub fn access_token(&self) -> &str
Gets the access token for this instance
Sourcepub fn login_url(&self) -> String
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::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
- Generate login URL with this method
- Direct user to the URL in a browser
- User completes login and is redirected with
request_token - Use
generate_session()with the request token to get access token
Sourcepub async fn generate_session(
&mut self,
request_token: &str,
api_secret: &str,
) -> Result<JsonValue>
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 loginapi_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::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
- Call
login_url()to get login URL - User visits URL and completes login
- User is redirected with
request_tokenparameter - Call this method with the request token and API secret
- Access token is automatically set for subsequent API calls
Sourcepub async fn invalidate_access_token(
&self,
access_token: &str,
) -> Result<Response>
pub async fn invalidate_access_token( &self, access_token: &str, ) -> Result<Response>
Invalidates the access token
Sourcepub async fn renew_access_token(
&mut self,
access_token: &str,
api_secret: &str,
) -> Result<JsonValue>
pub async fn renew_access_token( &mut self, access_token: &str, api_secret: &str, ) -> Result<JsonValue>
Request for new access token
Sourcepub async fn invalidate_refresh_token(
&self,
refresh_token: &str,
) -> Result<Response>
pub async fn invalidate_refresh_token( &self, refresh_token: &str, ) -> Result<Response>
Invalidates the refresh token
Sourcepub async fn margins(&self, segment: Option<String>) -> Result<JsonValue>
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 tradingutilised- Currently utilized marginnet- Net available marginenabled- Whether the segment is enabled
§Errors
Returns an error if the API request fails or the user is not authenticated.
§Example
use kiteconnect::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"]);Sourcepub async fn holdings(&self) -> Result<JsonValue>
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 instrumentquantity- Total quantity heldaverage_price- Average buying pricelast_price- Current market pricepnl- Profit and lossproduct- Product type (CNC, MIS, etc.)
§Errors
Returns an error if the API request fails or the user is not authenticated.
§Example
use kiteconnect::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"]);
}
}Sourcepub async fn positions(&self) -> Result<JsonValue>
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 instrumentquantity- Net position quantitybuy_quantity- Total buy quantitysell_quantity- Total sell quantityaverage_price- Average position pricepnl- Realized and unrealized P&Lproduct- Product type (MIS, CNC, NRML)
§Errors
Returns an error if the API request fails or the user is not authenticated.
§Example
use kiteconnect::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"]);
}
}
}Sourcepub 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>
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
Sourcepub 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>
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
Sourcepub async fn cancel_order(
&self,
order_id: &str,
variety: &str,
parent_order_id: Option<&str>,
) -> Result<JsonValue>
pub async fn cancel_order( &self, order_id: &str, variety: &str, parent_order_id: Option<&str>, ) -> Result<JsonValue>
Cancel an order
Sourcepub async fn exit_order(
&self,
order_id: &str,
variety: &str,
parent_order_id: Option<&str>,
) -> Result<JsonValue>
pub async fn exit_order( &self, order_id: &str, variety: &str, parent_order_id: Option<&str>, ) -> Result<JsonValue>
Exit a BO/CO order
Sourcepub async fn orders(&self) -> Result<JsonValue>
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 identifiertradingsymbol- Trading symbolquantity- Order quantityprice- Order pricestatus- 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::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"]);
}
}Sourcepub async fn order_history(&self, order_id: &str) -> Result<JsonValue>
pub async fn order_history(&self, order_id: &str) -> Result<JsonValue>
Get the list of order history
Sourcepub async fn order_trades(&self, order_id: &str) -> Result<JsonValue>
pub async fn order_trades(&self, order_id: &str) -> Result<JsonValue>
Get all trades for a specific order
Sourcepub 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>
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
Sourcepub async fn mf_orders(&self, order_id: Option<&str>) -> Result<JsonValue>
pub async fn mf_orders(&self, order_id: Option<&str>) -> Result<JsonValue>
Get all mutual fund orders or individual order info
Sourcepub async fn trigger_range(
&self,
transaction_type: &str,
instruments: Vec<&str>,
) -> Result<JsonValue>
pub async fn trigger_range( &self, transaction_type: &str, instruments: Vec<&str>, ) -> Result<JsonValue>
Get the trigger range for a list of instruments
Sourcepub async fn instruments(&self, exchange: Option<&str>) -> Result<JsonValue>
pub async fn instruments(&self, exchange: Option<&str>) -> Result<JsonValue>
Get instruments list
Sourcepub async fn mf_instruments(&self) -> Result<JsonValue>
pub async fn mf_instruments(&self) -> Result<JsonValue>
Get mutual fund instruments list
Trait Implementations§
Source§impl Clone for KiteConnect
impl Clone for KiteConnect
Source§fn clone(&self) -> KiteConnect
fn clone(&self) -> KiteConnect
1.0.0 · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more