Skip to main content

Crate kiteconnect

Crate kiteconnect 

Source
Expand description

§kiteconnect-rs

crates.io docs.rs

A Rust client for the Kite Connect API by Zerodha.

  • Typed REST calls: Covers Kite Connect v3 endpoints with typed request parameters and responses.
  • Lazy Call<T> requests: Every endpoint returns a Call<T> that sends nothing until awaited, with .raw(), .request(), and .response() escape hatches.
  • WebSocket ticker: Connects to wss://ws.kite.trade in a background Tokio task, reconnects with exponential backoff, and restores subscriptions.
  • Redacted secrets: Redacts tokens, API secrets, and secret query or form fields from Debug output and strips query strings from error paths.

Version 1.0 is a rewrite and does not share an API with 0.2.x.

§Install

cargo add kiteconnect
cargo add tokio --features macros,rt-multi-thread

Or in Cargo.toml:

[dependencies]
kiteconnect = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

§Log in and read holdings

Kite Connect login is a browser redirect. Open login_url(), log in, and take the request_token from the redirect URL. Then exchange it with your API secret:

use kiteconnect::{ApiSecret, KiteConnect};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut kite = KiteConnect::builder("your_api_key").build()?;
    println!("Log in at {}", kite.login_url());

    let api_secret = ApiSecret::new(std::env::var("KITE_API_SECRET")?)?;
    let session = kite
        .generate_session("request_token_from_redirect", &api_secret)
        .await?;
    kite.set_access_token(session.access_token);

    for holding in kite.holdings().await? {
        println!(
            "{} {} @ {}",
            holding.tradingsymbol, holding.quantity, holding.last_price
        );
    }
    Ok(())
}

If you already have an access token, set it on the builder with .access_token(AccessToken::new(token)?).

§Call<T>

Every endpoint method returns a Call<T>. It sends nothing until you use it:

let holdings = kite.holdings().await?; // typed: Vec<Holding>
let data = kite.holdings().raw().await?; // `data` as serde_json::Value, no typed decoding
println!("{:?}", kite.holdings().request()); // the request, not sent (secrets redacted)

.response() sends the request and returns the HTTP status, content type, and body as is. kite.call(Request::get("/path")) reaches an endpoint the crate does not wrap.

§Ticker

use kiteconnect::{AccessToken, KiteConnect, Mode, TickerEvent};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let kite = KiteConnect::builder("your_api_key")
        .access_token(AccessToken::new(std::env::var("KITE_ACCESS_TOKEN")?)?)
        .build()?;
    let (ticker, mut events) = kite.ticker().spawn()?;
    ticker.subscribe(&[408065], Mode::Full)?;

    while let Some(event) = events.recv().await {
        match event {
            TickerEvent::Ticks(ticks) => {
                for tick in ticks {
                    println!("{} {:?}", tick.instrument_token, tick.last_price);
                }
            }
            TickerEvent::OrderUpdate(order) => println!("{} {}", order.order_id, order.status),
            TickerEvent::Closed(reason) => {
                eprintln!("ticker stopped: {reason}");
                break;
            }
            _ => {}
        }
    }
    Ok(())
}

The ticker runs in its own Tokio task and connects to wss://ws.kite.trade. After a dropped connection it reconnects with exponential backoff (at most 30 seconds) and subscribes again to the current set. A handshake that Kite rejects with HTTP 400, 401, or 403 ends the ticker instead. KiteTicker is a cloneable handle, so several tasks can change subscriptions while one task reads events. The event channel is bounded: a slow reader pauses socket reads, so no tick or order update is dropped. Closed is always the last event.

§Errors

Every call returns kiteconnect::Result<T>. A Kite error envelope becomes Error::Api, with Kite’s error_type, message, and HTTP status.

match kite.orders().await {
    Ok(orders) => println!("{} orders", orders.len()),
    Err(err) if err.is_session_expired() => {
        // TokenException: renew with `renew_access_token`, or log in again.
    }
    Err(kiteconnect::Error::Api(api)) => eprintln!("{}: {}", api.kind, api.message),
    Err(err) => return Err(err),
}

is_session_expired() is true only for TokenException. Kite rejects such a request before it acts on it, so it is safe to renew the token and send the request again. Retry nothing else, an order write least of all.

Tokens and the API secret are newtypes whose Debug output is redacted. Request and Body redact secret query and form values in Debug. Decode errors name the path without its query string.

§MSRV

Rust 1.92.

§License

The crate uses the MIT license. See LICENSE.

Re-exports§

pub use error::Error;
pub use error::Result;
pub use ticker::CloseReason;
pub use ticker::DEFAULT_TICKER_URL;
pub use ticker::KiteTicker;
pub use ticker::Mode;
pub use ticker::Tick;
pub use ticker::TickerBuilder;
pub use ticker::TickerEvent;
pub use ticker::TickerEvents;
pub use ticker::parse_binary;

Modules§

error
Error types and the secret-key redaction helpers.
ticker
Kite Connect WebSocket ticker.

Structs§

AccessToken
Access token sent as Authorization: token api_key:access_token.
Alert
Alert returned by /alerts.
AlertBasket
ATO basket returned by /alerts.
AlertBasketItem
ATO basket item returned by /alerts.
AlertHistory
Trigger entry returned by /alerts/{uuid}/history.
AlertHistoryMeta
Quote metadata returned by /alerts/{uuid}/history.
AlertOhlc
OHLC prices returned by /alerts/{uuid}/history.
AlertParams
Parameters for POST /alerts and PUT /alerts/{uuid}.
AllMargins
All segment margins from GET /user/margins.
ApiSecret
API secret for POST /session/token and POST /session/refresh_token.
AuctionInstrument
AuctionInstrument returned by GET /portfolio/holdings/auctions.
AvailableMargins
Available funds from GET /user/margins/{segment}.
Bank
Bank account from GET /user/profile/full.
BasketCreate
The basket field of a POST /alerts that creates an ATO.
BasketGtt
The gtt object inside a basket item’s order params: two percentage legs.
BasketMargins
Initial, final and per-order totals returned by POST /margins/basket.
BasketModify
The basket field of a PUT /alerts/{uuid} that changes an existing ATO’s basket: operations only, and deliberately no name, type or tags.
BasketOrderParams
The complete order parameters one basket item carries.
BasketParams
Parameters for POST /margins/basket.
Call
A Kite API request that is sent when you await it or call one of its methods.
Candle
A candle returned by GET /instruments/historical/{token}/{interval}.
Charges
Charges breakdown returned by the Kite margin and charges endpoints.
ChargesParams
Parameters for POST /charges/orders.
ConvertPositionParams
Parameters for PUT /portfolio/positions.
Depth
Market depth returned by GET /quote.
DepthItem
A depth level returned by GET /quote.
FullUserMeta
Metadata from GET /user/profile/full.
FullUserProfile
Full user profile from GET /user/profile/full.
Gst
GST breakdown returned by the Kite margin and charges endpoints.
Gtt
Trigger returned by GET /gtt/triggers and /gtt/triggers/{id}.
GttCondition
Trigger condition returned by GET /gtt/triggers.
GttMeta
Rejection metadata returned by GET /gtt/triggers.
GttOrder
Order leg returned by GET /gtt/triggers.
GttOrderResult
Order execution status returned by GET /gtt/triggers.
GttParams
Form parameters for POST /gtt/triggers and PUT /gtt/triggers/{id}.
GttResponse
Trigger ID returned by POST, PUT and DELETE /gtt/triggers.
GttResult
Triggered order details returned by GET /gtt/triggers.
GttTriggerParams
One trigger value, limit price and quantity for the Kite GTT endpoints.
Holding
Holding returned by GET /portfolio/holdings.
HoldingAuthParams
Parameters for POST /portfolio/holdings/authorise.
HoldingCompact
HoldingCompact returned by GET /portfolio/holdings/compact.
HoldingSummary
HoldingSummary returned by GET /portfolio/holdings/summary.
HoldingsAuthInstruments
Instrument and quantity sent to POST /portfolio/holdings/authorise.
HoldingsAuthResp
Authorization request and redirect from POST /portfolio/holdings/authorise.
Instrument
An instrument returned by GET /instruments or GET /instruments/{exchange}.
KiteConnect
Kite Connect REST client.
KiteConnectBuilder
Builder for KiteConnect, created by KiteConnect::builder.
MarginParams
Parameters for POST /margins/orders.
MarginPnl
Profit and loss returned by the Kite margin endpoints.
Margins
Segment margins from GET /user/margins/{segment}.
MfHolding
Response from the Kite GET /mf/holdings endpoint.
MfInstrument
Response from the Kite GET /mf/instruments CSV endpoint.
MfOrder
Response from the Kite GET /mf/orders and GET /mf/orders/{order_id} endpoints.
MfOrderParams
Form parameters for the Kite POST /mf/orders endpoint.
MfOrderResponse
Response from the Kite POST and DELETE /mf/orders endpoint.
MfSip
Response from the Kite GET /mf/sips and GET /mf/sips/{sip_id} endpoints.
MfSipModifyParams
Form parameters for the Kite PUT /mf/sips/{sip_id} endpoint.
MfSipParams
Form parameters for the Kite POST /mf/sips endpoint.
MfSipResponse
Response from the Kite POST, PUT and DELETE /mf/sips endpoint.
MfTrade
Response from the Kite GET /mf/holdings/{isin} endpoint.
MtfHolding
MtfHolding returned by GET /portfolio/holdings.
Ohlc
OHLC prices returned by the Kite quote endpoints.
Order
Order from the Kite orders, history, and order-update endpoints.
OrderCharges
Order charges returned by POST /charges/orders.
OrderChargesParam
Order in the POST /charges/orders body.
OrderChild
Child order from the Kite autoslice order endpoint.
OrderChildError
Child error from the Kite autoslice order endpoint.
OrderMarginParam
Order in the POST /margins/orders and POST /margins/basket body.
OrderMargins
Order or basket totals returned by POST /margins/orders and /margins/basket.
OrderParams
Form parameters for the Kite place and modify order endpoints.
OrderResponse
Result from the Kite place, modify, cancel, and exit order endpoints.
Position
Position returned by GET /portfolio/positions.
Positions
Positions returned by GET /portfolio/positions.
Quote
An instrument quote returned by GET /quote.
QuoteLtp
An instrument last price returned by GET /quote/ltp.
QuoteOhlc
An instrument OHLC quote returned by GET /quote/ohlc.
RawResponse
HTTP response from a successful (2xx) request, before envelope decoding.
RefreshToken
Refresh token for POST /session/refresh_token.
Request
A Kite API request: method, path, query, body and X-Kite-Version header.
Trade
Trade from the Kite trades and order-trades endpoints.
UsedMargins
Used funds from GET /user/margins/{segment}.
UserMeta
Metadata from GET /user/profile.
UserProfile
User profile from GET /user/profile.
UserSession
Session returned by POST /session/token.
UserSessionTokens
Tokens returned by POST /session/refresh_token.

Enums§

AlertOperator
Comparison operator sent to /alerts.
AlertRhsType
Right-hand side type sent to /alerts.
AlertStatus
Alert status sent to /alerts.
AlertType
Alert type sent to /alerts.
BasketItemParams
The params of a basket write: either typed, or a verbatim JSON object.
BasketOperation
One entry in a basket write’s items array.
BasketWrite
The basket an ATO write sends. An ATO write without one keeps the stored basket, which is how a condition is edited without touching the orders.
Body
Request body. Debug hides form values for secret keys and every JSON body.
Exchange
Exchange for Kite order and market endpoints.
GttTrigger
Single or paired trigger legs for the Kite GTT endpoints.
HoldingAuthTransferType
HoldingAuthTransferType sent to the Kite portfolio endpoints.
HoldingAuthType
HoldingAuthType sent to the Kite portfolio endpoints.
OrderType
Order type for Kite order endpoints.
PositionType
PositionType sent to the Kite portfolio endpoints.
Product
Product for Kite order and portfolio endpoints.
TransactionType
Transaction side for Kite order endpoints.
Validity
Validity for Kite order endpoints.
Variety
Order variety for Kite order endpoints.

Constants§

DEFAULT_BASE_URL
Kite Connect REST API root used when the builder sets no base URL.