Expand description
§kiteconnect-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 aCall<T>that sends nothing until awaited, with.raw(),.request(), and.response()escape hatches. - WebSocket ticker: Connects to
wss://ws.kite.tradein a background Tokio task, reconnects with exponential backoff, and restores subscriptions. - Redacted secrets: Redacts tokens, API secrets, and secret query or form fields from
Debugoutput 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-threadOr 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§
Structs§
- Access
Token - Access token sent as
Authorization: token api_key:access_token. - Alert
- Alert returned by
/alerts. - Alert
Basket - ATO basket returned by
/alerts. - Alert
Basket Item - ATO basket item returned by
/alerts. - Alert
History - Trigger entry returned by
/alerts/{uuid}/history. - Alert
History Meta - Quote metadata returned by
/alerts/{uuid}/history. - Alert
Ohlc - OHLC prices returned by
/alerts/{uuid}/history. - Alert
Params - Parameters for
POST /alertsandPUT /alerts/{uuid}. - AllMargins
- All segment margins from GET /user/margins.
- ApiSecret
- API secret for
POST /session/tokenandPOST /session/refresh_token. - Auction
Instrument AuctionInstrumentreturned by GET /portfolio/holdings/auctions.- Available
Margins - Available funds from GET /user/margins/{segment}.
- Bank
- Bank account from GET /user/profile/full.
- Basket
Create - The
basketfield of aPOST /alertsthat creates an ATO. - Basket
Gtt - The
gttobject inside a basket item’s order params: two percentage legs. - Basket
Margins - Initial, final and per-order totals returned by POST /margins/basket.
- Basket
Modify - The
basketfield of aPUT /alerts/{uuid}that changes an existing ATO’s basket: operations only, and deliberately noname,typeortags. - Basket
Order Params - The complete order parameters one basket item carries.
- Basket
Params - 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.
- Charges
Params - Parameters for
POST /charges/orders. - Convert
Position Params - Parameters for PUT /portfolio/positions.
- Depth
- Market depth returned by GET /quote.
- Depth
Item - A depth level returned by GET /quote.
- Full
User Meta - Metadata from GET /user/profile/full.
- Full
User Profile - 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.
- GttOrder
Result - Order execution status returned by GET /gtt/triggers.
- GttParams
- Form parameters for
POST /gtt/triggersandPUT /gtt/triggers/{id}. - GttResponse
- Trigger ID returned by POST, PUT and DELETE /gtt/triggers.
- GttResult
- Triggered order details returned by GET /gtt/triggers.
- GttTrigger
Params - One trigger value, limit price and quantity for the Kite GTT endpoints.
- Holding
- Holding returned by GET /portfolio/holdings.
- Holding
Auth Params - Parameters for POST /portfolio/holdings/authorise.
- Holding
Compact HoldingCompactreturned by GET /portfolio/holdings/compact.- Holding
Summary HoldingSummaryreturned by GET /portfolio/holdings/summary.- Holdings
Auth Instruments - Instrument and quantity sent to POST /portfolio/holdings/authorise.
- Holdings
Auth Resp - Authorization request and redirect from POST /portfolio/holdings/authorise.
- Instrument
- An instrument returned by GET /instruments or GET /instruments/{exchange}.
- Kite
Connect - Kite Connect REST client.
- Kite
Connect Builder - Builder for
KiteConnect, created byKiteConnect::builder. - Margin
Params - Parameters for
POST /margins/orders. - Margin
Pnl - 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/ordersandGET /mf/orders/{order_id}endpoints. - MfOrder
Params - Form parameters for the Kite POST /mf/orders endpoint.
- MfOrder
Response - Response from the Kite POST and DELETE /mf/orders endpoint.
- MfSip
- Response from the Kite
GET /mf/sipsandGET /mf/sips/{sip_id}endpoints. - MfSip
Modify Params - Form parameters for the Kite
PUT /mf/sips/{sip_id}endpoint. - MfSip
Params - Form parameters for the Kite POST /mf/sips endpoint.
- MfSip
Response - Response from the Kite POST, PUT and DELETE /mf/sips endpoint.
- MfTrade
- Response from the Kite GET /mf/holdings/{isin} endpoint.
- MtfHolding
MtfHoldingreturned by GET /portfolio/holdings.- Ohlc
- OHLC prices returned by the Kite quote endpoints.
- Order
- Order from the Kite orders, history, and order-update endpoints.
- Order
Charges - Order charges returned by POST /charges/orders.
- Order
Charges Param - Order in the
POST /charges/ordersbody. - Order
Child - Child order from the Kite autoslice order endpoint.
- Order
Child Error - Child error from the Kite autoslice order endpoint.
- Order
Margin Param - Order in the
POST /margins/ordersandPOST /margins/basketbody. - Order
Margins - Order or basket totals returned by POST /margins/orders and /margins/basket.
- Order
Params - Form parameters for the Kite place and modify order endpoints.
- Order
Response - 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.
- Quote
Ltp - An instrument last price returned by GET /quote/ltp.
- Quote
Ohlc - An instrument OHLC quote returned by GET /quote/ohlc.
- RawResponse
- HTTP response from a successful (2xx) request, before envelope decoding.
- Refresh
Token - Refresh token for
POST /session/refresh_token. - Request
- A Kite API request: method, path, query, body and
X-Kite-Versionheader. - Trade
- Trade from the Kite trades and order-trades endpoints.
- Used
Margins - Used funds from GET /user/margins/{segment}.
- User
Meta - Metadata from GET /user/profile.
- User
Profile - User profile from GET /user/profile.
- User
Session - Session returned by POST /session/token.
- User
Session Tokens - Tokens returned by
POST /session/refresh_token.
Enums§
- Alert
Operator - Comparison operator sent to
/alerts. - Alert
RhsType - Right-hand side type sent to
/alerts. - Alert
Status - Alert status sent to
/alerts. - Alert
Type - Alert type sent to
/alerts. - Basket
Item Params - The
paramsof a basket write: either typed, or a verbatim JSON object. - Basket
Operation - One entry in a basket write’s
itemsarray. - Basket
Write - The
basketan 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.
Debughides 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.
- Holding
Auth Transfer Type HoldingAuthTransferTypesent to the Kite portfolio endpoints.- Holding
Auth Type HoldingAuthTypesent to the Kite portfolio endpoints.- Order
Type - Order type for Kite order endpoints.
- Position
Type PositionTypesent to the Kite portfolio endpoints.- Product
- Product for Kite order and portfolio endpoints.
- Transaction
Type - 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.