Skip to main content

kiteconnect/
portfolio.rs

1use crate::{Call, Exchange, KiteConnect, Product, RawResponse, Request, Result, TransactionType};
2use chrono::{NaiveDate, NaiveDateTime};
3use serde::{Deserialize, Deserializer, Serialize, de::Error as _};
4
5/// Holding returned by GET /portfolio/holdings.
6#[derive(Debug, Clone, Deserialize, Serialize)]
7#[non_exhaustive]
8pub struct Holding {
9    /// Trading symbol of the instrument.
10    pub tradingsymbol: String,
11    /// Exchange the instrument trades on.
12    pub exchange: String,
13    /// Numeric instrument token.
14    pub instrument_token: u32,
15    /// ISIN of the instrument.
16    pub isin: String,
17    /// Product type of the holding.
18    pub product: String,
19    /// Price reported for the holding.
20    pub price: f64,
21    /// Quantity of the holding in use.
22    #[serde(deserialize_with = "whole_number")]
23    pub used_quantity: i64,
24    /// Quantity held.
25    #[serde(deserialize_with = "whole_number")]
26    pub quantity: i64,
27    /// Quantity bought and pending settlement (T1).
28    #[serde(deserialize_with = "whole_number")]
29    pub t1_quantity: i64,
30    /// Realised (settled) quantity.
31    #[serde(deserialize_with = "whole_number")]
32    pub realised_quantity: i64,
33    /// Quantity authorised for sale.
34    #[serde(deserialize_with = "whole_number")]
35    pub authorised_quantity: i64,
36    /// Date and time of the sale authorisation, if any.
37    #[serde(default, with = "crate::time::optional_datetime")]
38    pub authorised_date: Option<NaiveDateTime>,
39    /// Quantity at the start of the day.
40    #[serde(deserialize_with = "whole_number")]
41    pub opening_quantity: i64,
42    /// Quantity pledged as collateral.
43    #[serde(deserialize_with = "whole_number")]
44    pub collateral_quantity: i64,
45    /// Type of collateral.
46    pub collateral_type: String,
47    /// Whether the holding has a discrepancy.
48    pub discrepancy: bool,
49    /// Average buy price.
50    pub average_price: f64,
51    /// Last traded price.
52    pub last_price: f64,
53    /// Previous close price.
54    pub close_price: f64,
55    /// Profit and loss.
56    pub pnl: f64,
57    /// Change in last price from the previous close.
58    pub day_change: Option<f64>,
59    /// Day change as a percentage.
60    pub day_change_percentage: f64,
61    /// MTF (margin trading facility) details, if any.
62    pub mtf: Option<MtfHolding>,
63}
64
65/// `MtfHolding` returned by GET /portfolio/holdings.
66#[derive(Debug, Clone, Deserialize, Serialize)]
67#[non_exhaustive]
68pub struct MtfHolding {
69    /// Quantity held under MTF.
70    #[serde(deserialize_with = "whole_number")]
71    pub quantity: i64,
72    /// MTF quantity in use.
73    #[serde(deserialize_with = "whole_number")]
74    pub used_quantity: i64,
75    /// Average price of the MTF holding.
76    pub average_price: f64,
77    /// Value of the MTF holding.
78    pub value: f64,
79    /// Initial margin for the MTF holding.
80    pub initial_margin: f64,
81}
82
83/// `HoldingCompact` returned by GET /portfolio/holdings/compact.
84#[derive(Debug, Clone, Deserialize, Serialize)]
85#[non_exhaustive]
86pub struct HoldingCompact {
87    /// Exchange the instrument trades on.
88    pub exchange: String,
89    /// Trading symbol of the instrument.
90    pub tradingsymbol: String,
91    /// Numeric instrument token.
92    pub instrument_token: u32,
93    /// Quantity bought and pending settlement (T1).
94    pub t1_quantity: i64,
95    /// Quantity held.
96    pub quantity: i64,
97    /// Exchanges the instrument is listed on.
98    #[serde(default)]
99    pub exchanges: Vec<String>,
100}
101
102/// `HoldingSummary` returned by GET /portfolio/holdings/summary.
103#[derive(Debug, Clone, Deserialize, Serialize)]
104#[non_exhaustive]
105pub struct HoldingSummary {
106    /// Total profit and loss across holdings.
107    pub total_pnl: f64,
108    /// Total profit and loss as a percentage.
109    pub total_pnl_percent: f64,
110    /// Profit and loss for the day.
111    pub today_pnl: f64,
112    /// Profit and loss for the day as a percentage.
113    pub today_pnl_percent: f64,
114    /// Total invested amount.
115    pub invested_amount: f64,
116    /// Current value of all holdings.
117    pub current_value: f64,
118}
119
120/// Position returned by GET /portfolio/positions.
121#[derive(Debug, Clone, Deserialize, Serialize)]
122#[non_exhaustive]
123pub struct Position {
124    /// Trading symbol of the instrument.
125    pub tradingsymbol: String,
126    /// Exchange the instrument trades on.
127    pub exchange: String,
128    /// Numeric instrument token.
129    pub instrument_token: u32,
130    /// Product type of the position.
131    pub product: String,
132    /// Net quantity of the position.
133    pub quantity: i64,
134    /// Quantity carried over from the previous day.
135    pub overnight_quantity: i64,
136    /// Contract multiplier.
137    pub multiplier: f64,
138    /// Average buy price.
139    pub average_price: f64,
140    /// Previous close price.
141    pub close_price: f64,
142    /// Last traded price.
143    pub last_price: f64,
144    /// Value of the position.
145    pub value: f64,
146    /// Profit and loss.
147    pub pnl: f64,
148    /// Mark-to-market profit and loss.
149    pub m2m: f64,
150    /// Unrealised profit and loss.
151    pub unrealised: f64,
152    /// Realised profit and loss.
153    pub realised: f64,
154    /// Total quantity bought.
155    pub buy_quantity: i64,
156    /// Average buy price.
157    pub buy_price: f64,
158    /// Total buy value.
159    pub buy_value: f64,
160    /// Mark-to-market profit and loss on buys.
161    pub buy_m2m: f64,
162    /// Total quantity sold.
163    pub sell_quantity: i64,
164    /// Average sell price.
165    pub sell_price: f64,
166    /// Total sell value.
167    pub sell_value: f64,
168    /// Mark-to-market profit and loss on sells.
169    pub sell_m2m: f64,
170    /// Quantity bought during the day.
171    pub day_buy_quantity: i64,
172    /// Average buy price for the day.
173    pub day_buy_price: f64,
174    /// Buy value for the day.
175    pub day_buy_value: f64,
176    /// Quantity sold during the day.
177    pub day_sell_quantity: i64,
178    /// Average sell price for the day.
179    pub day_sell_price: f64,
180    /// Sell value for the day.
181    pub day_sell_value: f64,
182}
183
184/// Positions returned by GET /portfolio/positions.
185#[derive(Debug, Clone, Deserialize, Serialize)]
186#[non_exhaustive]
187pub struct Positions {
188    /// Net positions.
189    #[serde(default)]
190    pub net: Vec<Position>,
191    /// Day positions.
192    #[serde(default)]
193    pub day: Vec<Position>,
194}
195
196/// `AuctionInstrument` returned by GET /portfolio/holdings/auctions.
197#[derive(Debug, Clone, Deserialize, Serialize)]
198#[non_exhaustive]
199pub struct AuctionInstrument {
200    /// Trading symbol of the instrument.
201    pub tradingsymbol: String,
202    /// Exchange the instrument trades on.
203    pub exchange: String,
204    /// Numeric instrument token.
205    pub instrument_token: u32,
206    /// ISIN of the instrument.
207    pub isin: String,
208    /// Product type of the holding.
209    pub product: String,
210    /// Price reported for the holding.
211    pub price: f64,
212    /// Quantity held.
213    pub quantity: i64,
214    /// Quantity bought and pending settlement (T1).
215    pub t1_quantity: i64,
216    /// Realised (settled) quantity.
217    pub realised_quantity: i64,
218    /// Quantity authorised for sale.
219    pub authorised_quantity: i64,
220    /// Date and time of the sale authorisation, if any.
221    #[serde(default, with = "crate::time::optional_datetime")]
222    pub authorised_date: Option<NaiveDateTime>,
223    /// Quantity at the start of the day.
224    pub opening_quantity: i64,
225    /// Quantity pledged as collateral.
226    pub collateral_quantity: i64,
227    /// Type of collateral.
228    pub collateral_type: String,
229    /// Whether the holding has a discrepancy.
230    pub discrepancy: bool,
231    /// Average buy price.
232    pub average_price: f64,
233    /// Last traded price.
234    pub last_price: f64,
235    /// Previous close price.
236    pub close_price: f64,
237    /// Profit and loss.
238    pub pnl: f64,
239    /// Change in last price from the previous close.
240    pub day_change: f64,
241    /// Day change as a percentage.
242    pub day_change_percentage: f64,
243    /// Auction number.
244    pub auction_number: String,
245}
246
247/// `PositionType` sent to the Kite portfolio endpoints.
248#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
249#[non_exhaustive]
250#[serde(rename_all = "lowercase")]
251pub enum PositionType {
252    /// Wire value `day`.
253    Day,
254    /// Wire value `overnight`.
255    Overnight,
256}
257
258impl std::fmt::Display for PositionType {
259    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
260        f.write_str(match self {
261            Self::Day => "day",
262            Self::Overnight => "overnight",
263        })
264    }
265}
266
267/// `HoldingAuthType` sent to the Kite portfolio endpoints.
268#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
269#[non_exhaustive]
270#[serde(rename_all = "lowercase")]
271pub enum HoldingAuthType {
272    /// Wire value `equity`.
273    Equity,
274    /// Wire value `mf`.
275    Mf,
276}
277
278impl std::fmt::Display for HoldingAuthType {
279    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
280        f.write_str(match self {
281            Self::Equity => "equity",
282            Self::Mf => "mf",
283        })
284    }
285}
286
287/// `HoldingAuthTransferType` sent to the Kite portfolio endpoints.
288#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
289#[non_exhaustive]
290#[serde(rename_all = "lowercase")]
291pub enum HoldingAuthTransferType {
292    /// Wire value `pre`.
293    Pre,
294    /// Wire value `post`.
295    Post,
296    /// Wire value `off`.
297    Off,
298    /// Wire value `gift`.
299    Gift,
300}
301
302impl std::fmt::Display for HoldingAuthTransferType {
303    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304        f.write_str(match self {
305            Self::Pre => "pre",
306            Self::Post => "post",
307            Self::Off => "off",
308            Self::Gift => "gift",
309        })
310    }
311}
312
313/// Parameters for PUT /portfolio/positions.
314#[derive(Debug, Clone)]
315#[non_exhaustive]
316pub struct ConvertPositionParams {
317    /// Exchange of the position.
318    pub exchange: Exchange,
319    /// Trading symbol of the instrument.
320    pub tradingsymbol: String,
321    /// Current product of the position.
322    pub old_product: Product,
323    /// Product to convert the position to.
324    pub new_product: Product,
325    /// Position type (day or overnight).
326    pub position_type: PositionType,
327    /// Transaction type (buy or sell).
328    pub transaction_type: TransactionType,
329    /// Quantity to convert.
330    pub quantity: i64,
331}
332
333impl ConvertPositionParams {
334    /// Creates parameters for converting a position.
335    pub fn new(
336        exchange: Exchange,
337        tradingsymbol: impl Into<String>,
338        old_product: Product,
339        new_product: Product,
340        position_type: PositionType,
341        transaction_type: TransactionType,
342        quantity: i64,
343    ) -> Self {
344        Self {
345            exchange,
346            tradingsymbol: tradingsymbol.into(),
347            old_product,
348            new_product,
349            position_type,
350            transaction_type,
351            quantity,
352        }
353    }
354}
355
356/// Instrument and quantity sent to POST /portfolio/holdings/authorise.
357#[derive(Debug, Clone)]
358#[non_exhaustive]
359pub struct HoldingsAuthInstruments {
360    /// ISIN of the instrument.
361    pub isin: String,
362    /// Quantity to authorise.
363    pub quantity: f64,
364}
365
366impl HoldingsAuthInstruments {
367    /// Creates an instrument entry from an ISIN and quantity.
368    pub fn new(isin: impl Into<String>, quantity: f64) -> Self {
369        Self {
370            isin: isin.into(),
371            quantity,
372        }
373    }
374}
375
376/// Parameters for POST /portfolio/holdings/authorise.
377#[derive(Debug, Clone, Default)]
378#[non_exhaustive]
379#[must_use]
380pub struct HoldingAuthParams {
381    /// Authorisation type (sent as `type`).
382    pub auth_type: Option<HoldingAuthType>,
383    /// Transfer type of the authorisation.
384    pub transfer_type: Option<HoldingAuthTransferType>,
385    /// Execution date of the transfer.
386    pub exec_date: Option<NaiveDate>,
387    /// Instruments to authorise.
388    pub instruments: Vec<HoldingsAuthInstruments>,
389}
390
391impl HoldingAuthParams {
392    /// Creates empty parameters.
393    pub fn new() -> Self {
394        Self::default()
395    }
396    /// Sets the authorisation type.
397    pub fn auth_type(mut self, value: HoldingAuthType) -> Self {
398        self.auth_type = Some(value);
399        self
400    }
401    /// Sets the transfer type.
402    pub fn transfer_type(mut self, value: HoldingAuthTransferType) -> Self {
403        self.transfer_type = Some(value);
404        self
405    }
406    /// Sets the execution date.
407    pub fn exec_date(mut self, value: NaiveDate) -> Self {
408        self.exec_date = Some(value);
409        self
410    }
411    /// Sets the instruments to authorise.
412    pub fn instruments(mut self, value: Vec<HoldingsAuthInstruments>) -> Self {
413        self.instruments = value;
414        self
415    }
416}
417
418/// Authorization request and redirect from POST /portfolio/holdings/authorise.
419#[derive(Debug, Clone, Deserialize, Serialize)]
420#[non_exhaustive]
421pub struct HoldingsAuthResp {
422    /// Authorisation request ID.
423    pub request_id: String,
424    /// URL to send the user to for authorisation (built locally, not in the response).
425    #[serde(skip_deserializing)]
426    pub redirect_url: String,
427}
428
429impl KiteConnect {
430    /// `GET /portfolio/holdings`.
431    pub fn holdings(&self) -> Call<Vec<Holding>> {
432        Call::new(self.clone(), Request::get("/portfolio/holdings"))
433    }
434    /// `GET /portfolio/holdings/summary`.
435    pub fn holdings_summary(&self) -> Call<HoldingSummary> {
436        Call::new(self.clone(), Request::get("/portfolio/holdings/summary"))
437    }
438    /// `GET /portfolio/holdings/compact`.
439    pub fn holdings_compact(&self) -> Call<Vec<HoldingCompact>> {
440        Call::new(self.clone(), Request::get("/portfolio/holdings/compact"))
441    }
442    /// `GET /portfolio/positions`.
443    pub fn positions(&self) -> Call<Positions> {
444        Call::new(self.clone(), Request::get("/portfolio/positions"))
445    }
446    /// `GET /portfolio/holdings/auctions`.
447    pub fn auction_instruments(&self) -> Call<Vec<AuctionInstrument>> {
448        Call::new(self.clone(), Request::get("/portfolio/holdings/auctions"))
449    }
450    /// `PUT /portfolio/positions`.
451    pub fn convert_position(&self, params: ConvertPositionParams) -> Call<bool> {
452        let form: Vec<(String, String)> = vec![
453            ("exchange".into(), params.exchange.to_string()),
454            ("tradingsymbol".into(), params.tradingsymbol),
455            ("old_product".into(), params.old_product.to_string()),
456            ("new_product".into(), params.new_product.to_string()),
457            ("position_type".into(), params.position_type.to_string()),
458            (
459                "transaction_type".into(),
460                params.transaction_type.to_string(),
461            ),
462            ("quantity".into(), params.quantity.to_string()),
463        ];
464        Call::with_decoder(
465            self.clone(),
466            Request::put("/portfolio/positions").form(form),
467            crate::call::success_bool,
468        )
469    }
470    /// `POST /portfolio/holdings/authorise`.
471    pub fn initiate_holdings_auth(&self, params: HoldingAuthParams) -> Call<HoldingsAuthResp> {
472        let mut form: Vec<(&'static str, String)> = Vec::new();
473        if let Some(value) = params.auth_type {
474            form.push(("type", value.to_string()));
475        }
476        if let Some(value) = params.transfer_type {
477            form.push(("transfer_type", value.to_string()));
478        }
479        if let Some(value) = params.exec_date {
480            form.push(("exec_date", value.to_string()));
481        }
482        for instrument in params.instruments {
483            form.push(("isin", instrument.isin));
484            form.push(("quantity", format!("{:.6}", instrument.quantity)));
485        }
486        Call::with_decoder(
487            self.clone(),
488            Request::post("/portfolio/holdings/authorise").form(form),
489            decode_holdings_auth,
490        )
491    }
492}
493
494fn decode_holdings_auth(
495    client: &KiteConnect,
496    response: &RawResponse,
497    path: &str,
498) -> Result<HoldingsAuthResp> {
499    let mut auth: HoldingsAuthResp = crate::call::decode(client, response, path)?;
500    auth.redirect_url = format!(
501        "https://kite.zerodha.com/connect/portfolio/authorise/holdings/{}/{}",
502        client.api_key(),
503        auth.request_id
504    );
505    Ok(auth)
506}
507
508/// Decodes an integer that some backends send as a whole float, such as `-0.0`.
509fn whole_number<'de, D: Deserializer<'de>>(deserializer: D) -> std::result::Result<i64, D::Error> {
510    let number = serde_json::Number::deserialize(deserializer)?;
511    if let Some(value) = number.as_i64() {
512        return Ok(value);
513    }
514    match number.as_f64() {
515        #[expect(
516            clippy::cast_possible_truncation,
517            reason = "the value is whole and within the exact f64 integer range"
518        )]
519        Some(value) if value.fract() == 0.0 && value.abs() <= 9_007_199_254_740_992.0 => {
520            Ok(value as i64)
521        }
522        _ => Err(D::Error::custom(format!(
523            "expected a whole number, got {number}"
524        ))),
525    }
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531    use httpmock::{
532        Method::{GET, POST, PUT},
533        MockServer,
534    };
535    use serde_json::{Value, json};
536
537    const HOLDINGS: &str = include_str!("../mock_responses/holdings.json");
538    const SUMMARY: &str = include_str!("../mock_responses/holdings_summary.json");
539    const COMPACT: &str = include_str!("../mock_responses/holdings_compact.json");
540    const POSITIONS: &str = include_str!("../mock_responses/positions.json");
541    const AUCTIONS: &str = include_str!("../mock_responses/auctions_list.json");
542    const AUTH: &str = include_str!("../mock_responses/holdings_auth.json");
543    const CONVERT: &str = include_str!("../mock_responses/convert_position.json");
544
545    fn data(fixture: &str) -> Value {
546        serde_json::from_str::<Value>(fixture).unwrap()["data"].clone()
547    }
548
549    fn client(server: &MockServer) -> KiteConnect {
550        KiteConnect::builder("test-api-key")
551            .base_url(server.base_url())
552            .build()
553            .unwrap()
554    }
555
556    #[test]
557    fn fixtures_decode_literal_values() {
558        let holdings: Vec<Holding> = serde_json::from_value(data(HOLDINGS)).unwrap();
559        assert_eq!(holdings.len(), 2);
560        assert_eq!(holdings[0].tradingsymbol, "AARON");
561        assert_eq!(holdings[0].instrument_token, 263_681);
562        assert_eq!(holdings[0].last_price.to_bits(), f64::to_bits(352.95));
563        assert_eq!(
564            holdings[0].authorised_date,
565            Some(
566                NaiveDate::from_ymd_opt(2025, 1, 17)
567                    .unwrap()
568                    .and_hms_opt(0, 0, 0)
569                    .unwrap()
570            )
571        );
572        let mtf = holdings[0].mtf.as_ref().unwrap();
573        assert_eq!(mtf.quantity, 1000);
574        assert_eq!(mtf.value.to_bits(), f64::to_bits(100_000.0));
575        assert_eq!(mtf.average_price.to_bits(), f64::to_bits(100.0));
576        let summary: HoldingSummary = serde_json::from_value(data(SUMMARY)).unwrap();
577        assert_eq!(
578            summary.invested_amount.to_bits(),
579            f64::to_bits(41_044.404_05)
580        );
581        assert_eq!(
582            summary.current_value.to_bits(),
583            f64::to_bits(47_842.640_000_000_01)
584        );
585        let compact: Vec<HoldingCompact> = serde_json::from_value(data(COMPACT)).unwrap();
586        assert_eq!(compact.len(), 21);
587        assert_eq!(compact[0].tradingsymbol, "63MOONS");
588        assert_eq!(compact[0].instrument_token, 3_038_209);
589        assert_eq!(compact[0].quantity, 1);
590        assert_eq!(compact[0].exchanges.len(), 0);
591        let positions: Positions = serde_json::from_value(data(POSITIONS)).unwrap();
592        assert_eq!(positions.net[0].tradingsymbol, "LEADMINI17DECFUT");
593        assert_eq!(positions.net[0].quantity, 1);
594        assert_eq!(
595            positions.net[0].buy_value.to_bits(),
596            f64::to_bits(161_050.0)
597        );
598        assert_eq!(positions.day[0].instrument_token, 53_505_799);
599        let auctions: Vec<AuctionInstrument> = serde_json::from_value(data(AUCTIONS)).unwrap();
600        assert_eq!(auctions.len(), 3);
601        assert_eq!(auctions[0].tradingsymbol, "ASHOKLEY");
602        assert_eq!(auctions[0].auction_number, "20");
603        assert_eq!(auctions[0].average_price.to_bits(), f64::to_bits(131.95));
604        let auth: HoldingsAuthResp = serde_json::from_value(data(AUTH)).unwrap();
605        assert_eq!(auth.request_id, "na8QgCeQm05UHG6NL9sAGRzdfSF64UdB");
606    }
607
608    #[test]
609    fn required_numbers_fail_and_optional_fields_accept_absence() {
610        let mut holding = data(HOLDINGS)[0].clone();
611        holding.as_object_mut().unwrap().remove("price");
612        assert!(serde_json::from_value::<Holding>(holding).is_err());
613        let mut summary = data(SUMMARY);
614        summary.as_object_mut().unwrap().remove("current_value");
615        assert!(serde_json::from_value::<HoldingSummary>(summary).is_err());
616        for empty in [Value::Null, json!("")] {
617            let mut holding = data(HOLDINGS)[0].clone();
618            holding["authorised_date"] = empty;
619            holding.as_object_mut().unwrap().remove("mtf");
620            holding["product"] = json!("FUTURE_PRODUCT");
621            let holding: Holding = serde_json::from_value(holding).unwrap();
622            assert!(holding.authorised_date.is_none());
623            assert!(holding.mtf.is_none());
624            assert_eq!(holding.product, "FUTURE_PRODUCT");
625        }
626    }
627
628    #[test]
629    fn holding_quantities_accept_whole_floats_and_reject_fractions() {
630        let mut holding = data(HOLDINGS)[0].clone();
631        holding["used_quantity"] = json!(-0.0);
632        holding["quantity"] = json!(2.0);
633        holding["mtf"]["used_quantity"] = json!(-0.0);
634        let holding: Holding = serde_json::from_value(holding).unwrap();
635        assert_eq!(holding.used_quantity, 0);
636        assert_eq!(holding.quantity, 2);
637        assert_eq!(holding.mtf.unwrap().used_quantity, 0);
638        let mut holding = data(HOLDINGS)[0].clone();
639        holding["quantity"] = json!(1.5);
640        assert!(serde_json::from_value::<Holding>(holding).is_err());
641    }
642
643    #[test]
644    fn input_enums_match_wire_values() {
645        for (value, wire) in [
646            (PositionType::Day, "day"),
647            (PositionType::Overnight, "overnight"),
648        ] {
649            assert_eq!(serde_json::to_value(value).unwrap(), json!(wire));
650            assert_eq!(value.to_string(), wire);
651        }
652        for (value, wire) in [
653            (HoldingAuthType::Equity, "equity"),
654            (HoldingAuthType::Mf, "mf"),
655        ] {
656            assert_eq!(serde_json::to_value(value).unwrap(), json!(wire));
657            assert_eq!(value.to_string(), wire);
658        }
659        for (value, wire) in [
660            (HoldingAuthTransferType::Pre, "pre"),
661            (HoldingAuthTransferType::Post, "post"),
662            (HoldingAuthTransferType::Off, "off"),
663            (HoldingAuthTransferType::Gift, "gift"),
664        ] {
665            assert_eq!(serde_json::to_value(value).unwrap(), json!(wire));
666            assert_eq!(value.to_string(), wire);
667        }
668        assert!(serde_json::from_value::<PositionType>(json!("invalid")).is_err());
669    }
670
671    #[tokio::test]
672    async fn holdings_checks_route_and_decodes() {
673        let server = MockServer::start_async().await;
674        let mock = server
675            .mock_async(|when, then| {
676                when.method(GET).path("/portfolio/holdings");
677                then.status(200)
678                    .header("content-type", "application/json")
679                    .body(HOLDINGS);
680            })
681            .await;
682        let result = client(&server).holdings().await.unwrap();
683        assert_eq!(result[0].tradingsymbol, "AARON");
684        mock.assert_calls_async(1).await;
685    }
686
687    #[tokio::test]
688    async fn holdings_summary_checks_route_and_decodes() {
689        let server = MockServer::start_async().await;
690        let mock = server
691            .mock_async(|when, then| {
692                when.method(GET).path("/portfolio/holdings/summary");
693                then.status(200)
694                    .header("content-type", "application/json")
695                    .body(SUMMARY);
696            })
697            .await;
698        let result = client(&server).holdings_summary().await.unwrap();
699        assert_eq!(
700            result.invested_amount.to_bits(),
701            f64::to_bits(41_044.404_05)
702        );
703        mock.assert_calls_async(1).await;
704    }
705
706    #[tokio::test]
707    async fn holdings_compact_checks_route_and_decodes() {
708        let server = MockServer::start_async().await;
709        let mock = server
710            .mock_async(|when, then| {
711                when.method(GET).path("/portfolio/holdings/compact");
712                then.status(200)
713                    .header("content-type", "application/json")
714                    .body(COMPACT);
715            })
716            .await;
717        let result = client(&server).holdings_compact().await.unwrap();
718        assert_eq!(result[0].instrument_token, 3_038_209);
719        mock.assert_calls_async(1).await;
720    }
721
722    #[tokio::test]
723    async fn positions_checks_route_and_decodes() {
724        let server = MockServer::start_async().await;
725        let mock = server
726            .mock_async(|when, then| {
727                when.method(GET).path("/portfolio/positions");
728                then.status(200)
729                    .header("content-type", "application/json")
730                    .body(POSITIONS);
731            })
732            .await;
733        let result = client(&server).positions().await.unwrap();
734        assert_eq!(result.net[0].quantity, 1);
735        mock.assert_calls_async(1).await;
736    }
737
738    #[tokio::test]
739    async fn auction_instruments_checks_route_and_decodes() {
740        let server = MockServer::start_async().await;
741        let mock = server
742            .mock_async(|when, then| {
743                when.method(GET).path("/portfolio/holdings/auctions");
744                then.status(200)
745                    .header("content-type", "application/json")
746                    .body(AUCTIONS);
747            })
748            .await;
749        let result = client(&server).auction_instruments().await.unwrap();
750        assert_eq!(result[0].auction_number, "20");
751        mock.assert_calls_async(1).await;
752    }
753
754    #[tokio::test]
755    async fn convert_position_checks_form_and_success() {
756        let server = MockServer::start_async().await;
757        let mock = server.mock_async(|when, then| {
758            when.method(PUT).path("/portfolio/positions")
759                .body("exchange=NSE&tradingsymbol=INFY&old_product=MIS&new_product=CNC&position_type=day&transaction_type=BUY&quantity=1");
760            then.status(200).header("content-type", "application/json").body(CONVERT);
761        }).await;
762        let params = ConvertPositionParams::new(
763            Exchange::Nse,
764            "INFY",
765            Product::Mis,
766            Product::Cnc,
767            PositionType::Day,
768            TransactionType::Buy,
769            1,
770        );
771        assert!(client(&server).convert_position(params).await.unwrap());
772        mock.assert_calls_async(1).await;
773    }
774
775    #[tokio::test]
776    async fn holdings_auth_checks_repeated_form_and_computed_redirect() {
777        let server = MockServer::start_async().await;
778        let mock = server.mock_async(|when, then| {
779            when.method(POST).path("/portfolio/holdings/authorise")
780                .body("type=equity&transfer_type=pre&exec_date=2025-01-17&isin=INE721Z01010&quantity=1.000000&isin=INE062A01020&quantity=2.500000");
781            then.status(200).header("content-type", "application/json").body(AUTH);
782        }).await;
783        let params = HoldingAuthParams::new()
784            .auth_type(HoldingAuthType::Equity)
785            .transfer_type(HoldingAuthTransferType::Pre)
786            .exec_date(NaiveDate::from_ymd_opt(2025, 1, 17).unwrap())
787            .instruments(vec![
788                HoldingsAuthInstruments::new("INE721Z01010", 1.0),
789                HoldingsAuthInstruments::new("INE062A01020", 2.5),
790            ]);
791        let auth = client(&server)
792            .initiate_holdings_auth(params.clone())
793            .await
794            .unwrap();
795        assert_eq!(auth.request_id, "na8QgCeQm05UHG6NL9sAGRzdfSF64UdB");
796        assert_eq!(
797            auth.redirect_url,
798            "https://kite.zerodha.com/connect/portfolio/authorise/holdings/test-api-key/na8QgCeQm05UHG6NL9sAGRzdfSF64UdB"
799        );
800        assert_eq!(
801            client(&server)
802                .initiate_holdings_auth(params)
803                .raw()
804                .await
805                .unwrap(),
806            data(AUTH)
807        );
808        mock.assert_calls_async(2).await;
809    }
810
811    #[tokio::test]
812    async fn holdings_auth_omits_optional_form_fields() {
813        let server = MockServer::start_async().await;
814        let mock = server
815            .mock_async(|when, then| {
816                when.method(POST)
817                    .path("/portfolio/holdings/authorise")
818                    .body("");
819                then.status(200)
820                    .header("content-type", "application/json")
821                    .body(AUTH);
822            })
823            .await;
824        let auth = client(&server)
825            .initiate_holdings_auth(HoldingAuthParams::new())
826            .await
827            .unwrap();
828        assert_eq!(auth.request_id, "na8QgCeQm05UHG6NL9sAGRzdfSF64UdB");
829        mock.assert_calls_async(1).await;
830    }
831}