kiteconnect 1.0.1

Kite Connect API client for Rust: REST calls with typed responses and the WebSocket ticker
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
use crate::{Call, Exchange, KiteConnect, Product, Request, TransactionType};
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
use serde_json::json;

/// One trigger value, limit price and quantity for the Kite GTT endpoints.
#[derive(Debug, Clone, Copy)]
#[non_exhaustive]
pub struct GttTriggerParams {
    /// Price at which the leg triggers.
    pub trigger_value: f64,
    /// Limit price of the order placed on trigger.
    pub limit_price: f64,
    /// Quantity of the order placed on trigger.
    pub quantity: i64,
}

impl GttTriggerParams {
    /// Build a trigger leg for the Kite GTT endpoints.
    #[must_use]
    pub fn new(trigger_value: f64, limit_price: f64, quantity: i64) -> Self {
        Self {
            trigger_value,
            limit_price,
            quantity,
        }
    }
}

/// Single or paired trigger legs for the Kite GTT endpoints.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum GttTrigger {
    /// One trigger leg (`single`).
    Single(GttTriggerParams),
    /// Two trigger legs (`two-leg`).
    TwoLeg {
        /// Lower trigger leg.
        lower: GttTriggerParams,
        /// Upper trigger leg.
        upper: GttTriggerParams,
    },
    /// One trailing trigger leg (`trailing-single`).
    TrailingSingle {
        /// Trigger leg.
        leg: GttTriggerParams,
        /// Trailing distance in points.
        trailing_points: f64,
    },
    /// Two trailing trigger legs (`trailing-two-leg`).
    TrailingTwoLeg {
        /// Lower trigger leg.
        lower: GttTriggerParams,
        /// Upper trigger leg.
        upper: GttTriggerParams,
        /// Trailing distance in points.
        trailing_points: f64,
    },
}

/// Form parameters for `POST /gtt/triggers` and `PUT /gtt/triggers/{id}`.
#[derive(Debug, Clone)]
#[non_exhaustive]
#[must_use]
pub struct GttParams {
    /// Trading symbol of the instrument.
    pub tradingsymbol: String,
    /// Exchange of the instrument.
    pub exchange: Exchange,
    /// Last traded price of the instrument.
    pub last_price: f64,
    /// Transaction type of the orders.
    pub transaction_type: TransactionType,
    /// Product of the limit orders.
    pub product: Product,
    /// Trigger legs.
    pub trigger: GttTrigger,
}

impl GttParams {
    /// Build a GTT whose limit orders use the CNC product.
    pub fn new(
        tradingsymbol: impl Into<String>,
        exchange: Exchange,
        last_price: f64,
        transaction_type: TransactionType,
        trigger: GttTrigger,
    ) -> Self {
        Self {
            tradingsymbol: tradingsymbol.into(),
            exchange,
            last_price,
            transaction_type,
            product: Product::Cnc,
            trigger,
        }
    }

    /// Set the product of every limit order.
    pub fn product(mut self, product: Product) -> Self {
        self.product = product;
        self
    }

    fn into_form(self) -> [(&'static str, String); 3] {
        let (trigger_type, legs, trailing_points) = match self.trigger {
            GttTrigger::Single(leg) => ("single", vec![leg], None),
            GttTrigger::TwoLeg { lower, upper } => ("two-leg", vec![lower, upper], None),
            GttTrigger::TrailingSingle {
                leg,
                trailing_points,
            } => ("trailing-single", vec![leg], Some(trailing_points)),
            GttTrigger::TrailingTwoLeg {
                lower,
                upper,
                trailing_points,
            } => (
                "trailing-two-leg",
                vec![lower, upper],
                Some(trailing_points),
            ),
        };
        let mut condition = json!({
            "exchange": self.exchange,
            "tradingsymbol": self.tradingsymbol,
            "last_price": self.last_price,
            "trigger_values": legs.iter().map(|leg| leg.trigger_value).collect::<Vec<_>>()
        });
        if let Some(points) = trailing_points {
            condition["trailing_points"] = json!([points]);
        }
        let orders: Vec<_> = legs
            .iter()
            .map(|leg| {
                json!({
                    "exchange": self.exchange,
                    "tradingsymbol": self.tradingsymbol,
                    "transaction_type": self.transaction_type,
                    "quantity": leg.quantity,
                    "price": leg.limit_price,
                    "order_type": "LIMIT",
                    "product": self.product,
                })
            })
            .collect();
        [
            ("type", trigger_type.to_string()),
            ("condition", condition.to_string()),
            ("orders", json!(orders).to_string()),
        ]
    }
}

/// Trigger ID returned by POST, PUT and DELETE /gtt/triggers.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GttResponse {
    /// Id of the trigger.
    pub trigger_id: i64,
}

/// Rejection metadata returned by GET /gtt/triggers.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GttMeta {
    /// Reason the trigger was rejected, if any.
    pub rejection_reason: Option<String>,
}

/// Trigger condition returned by GET /gtt/triggers.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GttCondition {
    /// Exchange of the instrument.
    pub exchange: String,
    /// Trading symbol of the instrument.
    pub tradingsymbol: String,
    /// Last traded price when the trigger was set.
    pub last_price: f64,
    #[serde(default)]
    /// Trigger prices, one per leg.
    pub trigger_values: Vec<f64>,
    /// Instrument token, if returned.
    pub instrument_token: Option<u32>,
    #[serde(default)]
    /// Trailing distance in points, if any.
    pub trailing_points: Vec<f64>,
}

/// Order execution status returned by GET /gtt/triggers.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GttOrderResult {
    /// Order status.
    pub status: String,
    /// Id of the placed order, if any.
    pub order_id: Option<String>,
    /// Reason the order was rejected, if any.
    pub rejection_reason: Option<String>,
}

/// Triggered order details returned by GET /gtt/triggers.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GttResult {
    /// Account id.
    pub account_id: String,
    /// Exchange of the instrument.
    pub exchange: String,
    /// Trading symbol of the instrument.
    pub tradingsymbol: String,
    /// Order validity.
    pub validity: String,
    /// Product type.
    pub product: String,
    /// Order type.
    pub order_type: String,
    /// Transaction type.
    pub transaction_type: String,
    /// Order quantity.
    pub quantity: f64,
    /// Order price.
    pub price: f64,
    /// Order metadata, if any.
    pub meta: Option<String>,
    #[serde(default, with = "crate::time::optional_datetime")]
    /// Time of the result, if available.
    pub timestamp: Option<NaiveDateTime>,
    /// Price at which the trigger fired.
    pub triggered_at: f64,
    /// Status of the placed order, if any.
    pub order_result: Option<GttOrderResult>,
}

/// Order leg returned by GET /gtt/triggers.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct GttOrder {
    /// Exchange of the instrument.
    pub exchange: String,
    /// Trading symbol of the instrument.
    pub tradingsymbol: String,
    /// Product type.
    pub product: String,
    /// Order type.
    pub order_type: String,
    /// Transaction type.
    pub transaction_type: String,
    /// Order quantity.
    pub quantity: f64,
    /// Order price.
    pub price: f64,
    /// Result of the triggered order, if any.
    pub result: Option<GttResult>,
}

/// Trigger returned by GET /gtt/triggers and /gtt/triggers/{id}.
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct Gtt {
    /// Trigger id.
    pub id: i64,
    /// Owner's user id.
    pub user_id: String,
    /// Id of the parent trigger, if any.
    pub parent_trigger: Option<i64>,
    #[serde(rename = "type")]
    /// Trigger type, such as `single` or `two-leg`.
    pub trigger_type: String,
    #[serde(default, with = "crate::time::optional_datetime")]
    /// Creation time, if returned.
    pub created_at: Option<NaiveDateTime>,
    #[serde(default, with = "crate::time::optional_datetime")]
    /// Last update time, if returned.
    pub updated_at: Option<NaiveDateTime>,
    #[serde(default, with = "crate::time::optional_datetime")]
    /// Expiry time, if returned.
    pub expires_at: Option<NaiveDateTime>,
    /// Trigger status.
    pub status: String,
    /// Trigger condition.
    pub condition: GttCondition,
    #[serde(default)]
    /// Orders placed when the trigger fires.
    pub orders: Vec<GttOrder>,
    /// Rejection metadata, if any.
    pub meta: Option<GttMeta>,
}

impl KiteConnect {
    /// `GET /gtt/triggers`.
    pub fn gtts(&self) -> Call<Vec<Gtt>> {
        Call::new(self.clone(), Request::get("/gtt/triggers"))
    }
    /// `GET /gtt/triggers/{id}`.
    pub fn gtt(&self, trigger_id: i64) -> Call<Gtt> {
        Call::new(
            self.clone(),
            Request::get(format!("/gtt/triggers/{trigger_id}")),
        )
    }
    /// `POST /gtt/triggers`.
    pub fn place_gtt(&self, params: GttParams) -> Call<GttResponse> {
        Call::new(
            self.clone(),
            Request::post("/gtt/triggers").form(params.into_form()),
        )
    }
    /// `PUT /gtt/triggers/{id}`.
    pub fn modify_gtt(&self, trigger_id: i64, params: GttParams) -> Call<GttResponse> {
        Call::new(
            self.clone(),
            Request::put(format!("/gtt/triggers/{trigger_id}")).form(params.into_form()),
        )
    }
    /// `DELETE /gtt/triggers/{id}`.
    pub fn delete_gtt(&self, trigger_id: i64) -> Call<GttResponse> {
        Call::new(
            self.clone(),
            Request::delete(format!("/gtt/triggers/{trigger_id}")),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use httpmock::prelude::*;
    use serde_json::Value;

    fn client(server: &MockServer) -> KiteConnect {
        KiteConnect::builder("key")
            .base_url(server.base_url())
            .build()
            .unwrap()
    }
    fn params() -> GttParams {
        GttParams::new(
            "RAIN",
            Exchange::Nse,
            102.6,
            TransactionType::Sell,
            GttTrigger::TwoLeg {
                lower: GttTriggerParams::new(102.0, 101.5, 1),
                upper: GttTriggerParams::new(103.7, 104.0, 2),
            },
        )
    }
    fn wire(params: GttParams) -> (String, Value, Value) {
        let [(_, kind), (_, condition), (_, orders)] = params.into_form();
        (
            kind,
            serde_json::from_str(&condition).unwrap(),
            serde_json::from_str(&orders).unwrap(),
        )
    }
    fn fixture<T: serde::de::DeserializeOwned>(body: &str) -> T {
        let value: Value = serde_json::from_str(body).unwrap();
        serde_json::from_value(value["data"].clone()).unwrap()
    }
    fn assert_gtt(gtt: &Gtt, id: i64) {
        assert_eq!(gtt.id, id);
        assert_eq!(gtt.user_id, "XX0000");
        assert_eq!(gtt.trigger_type, "two-leg");
        assert_eq!(gtt.status, "triggered");
        assert_eq!(gtt.created_at.unwrap().to_string(), "2019-09-09 15:13:22");
        assert_eq!(gtt.updated_at.unwrap().to_string(), "2019-09-09 15:15:08");
        assert_eq!(gtt.expires_at.unwrap().to_string(), "2020-01-01 12:00:00");
        assert_eq!(gtt.parent_trigger, None);
        assert!(gtt.meta.is_none());
        assert_eq!(gtt.condition.exchange, "NSE");
        assert_eq!(gtt.condition.tradingsymbol, "RAIN");
        assert_eq!(gtt.condition.last_price.to_bits(), f64::to_bits(102.6));
        assert_eq!(gtt.condition.trigger_values, vec![102.0, 103.7]);
        assert_eq!(gtt.condition.instrument_token, Some(3_926_273));
        assert!(gtt.orders[0].result.is_none());
        assert_eq!(gtt.orders[1].quantity.to_bits(), f64::to_bits(1.0));
        assert_eq!(gtt.orders[1].price.to_bits(), f64::to_bits(1.0));
        let result = gtt.orders[1].result.as_ref().unwrap();
        assert_eq!(result.account_id, "XX0000");
        assert_eq!(result.timestamp.unwrap().to_string(), "2019-09-09 15:15:08");
        assert_eq!(result.triggered_at.to_bits(), f64::to_bits(103.7));
        let order_result = result.order_result.as_ref().unwrap();
        assert_eq!(order_result.status, "failed");
        assert_eq!(order_result.order_id.as_deref(), Some(""));
        assert_eq!(
            order_result.rejection_reason.as_deref(),
            Some(
                "Your order price is lower than the current lower circuit limit of 70.65. Place an order within the daily range."
            )
        );
    }

    #[test]
    fn fixtures_decode() {
        assert_gtt(
            &fixture(include_str!("../mock_responses/gtt_get_order.json")),
            123,
        );
        let list: Vec<Gtt> = fixture(include_str!("../mock_responses/gtt_get_orders.json"));
        assert_eq!(list.len(), 2);
        assert_eq!(list[0].id, 112_127);
        assert_eq!(list[0].status, "active");
        assert_eq!(list[0].condition.tradingsymbol, "INFY");
        assert_eq!(list[0].condition.trigger_values, vec![702.0]);
        assert!(list[0].meta.as_ref().unwrap().rejection_reason.is_none());
        assert_gtt(&list[1], 105_099);
        for body in [
            include_str!("../mock_responses/gtt_place_order.json"),
            include_str!("../mock_responses/gtt_modify_order.json"),
            include_str!("../mock_responses/gtt_delete_order.json"),
        ] {
            let response: GttResponse = fixture(body);
            assert_eq!(response.trigger_id, 123);
        }
    }

    #[test]
    fn nullable_fields_and_future_response_strings_decode() {
        let mut value: Value =
            serde_json::from_str(include_str!("../mock_responses/gtt_get_order.json")).unwrap();
        value["data"]["type"] = json!("future-type");
        value["data"]["status"] = json!("future-status");
        value["data"]["created_at"] = json!("");
        value["data"]["updated_at"] = Value::Null;
        value["data"].as_object_mut().unwrap().remove("expires_at");
        value["data"]["meta"] = json!({"rejection_reason": "rejected"});
        let gtt: Gtt = serde_json::from_value(value["data"].clone()).unwrap();
        assert_eq!(gtt.trigger_type, "future-type");
        assert_eq!(gtt.status, "future-status");
        assert!(gtt.created_at.is_none());
        assert!(gtt.updated_at.is_none());
        assert!(gtt.expires_at.is_none());
        assert_eq!(
            gtt.meta.unwrap().rejection_reason.as_deref(),
            Some("rejected")
        );
        for field in ["id", "condition"] {
            let mut missing = value["data"].clone();
            missing.as_object_mut().unwrap().remove(field);
            assert!(serde_json::from_value::<Gtt>(missing).is_err());
        }
        assert!(serde_json::from_value::<GttResponse>(json!({})).is_err());
        assert!(serde_json::from_value::<GttResponse>(json!({"trigger_id": "123"})).is_err());
    }

    #[test]
    fn typed_params_preserve_leg_order_product_and_trailing_types() {
        let (kind, condition, orders) = wire(params().product(Product::Nrml));
        assert_eq!(kind, "two-leg");
        assert_eq!(condition["trigger_values"], json!([102.0, 103.7]));
        assert_eq!(orders[0]["price"], 101.5);
        assert_eq!(orders[1]["quantity"], json!(2));
        assert_eq!(orders[0]["product"], "NRML");
        assert_eq!(orders[1]["product"], "NRML");
        assert_eq!(orders[1]["order_type"], "LIMIT");
        for (trigger, kind, values) in [
            (
                GttTrigger::Single(GttTriggerParams::new(100.0, 99.0, 1)),
                "single",
                json!([100.0]),
            ),
            (
                GttTrigger::TrailingSingle {
                    leg: GttTriggerParams::new(100.0, 99.0, 1),
                    trailing_points: 2.0,
                },
                "trailing-single",
                json!([100.0]),
            ),
            (
                GttTrigger::TrailingTwoLeg {
                    lower: GttTriggerParams::new(100.0, 99.0, 1),
                    upper: GttTriggerParams::new(110.0, 111.0, 2),
                    trailing_points: 2.0,
                },
                "trailing-two-leg",
                json!([100.0, 110.0]),
            ),
        ] {
            let (wire_kind, condition, orders) = wire(GttParams::new(
                "RAIN",
                Exchange::Nse,
                102.6,
                TransactionType::Sell,
                trigger,
            ));
            assert_eq!(wire_kind, kind);
            assert_eq!(condition["trigger_values"], values);
            assert_eq!(orders[0]["product"], "CNC");
            if kind != "single" {
                assert_eq!(condition["trailing_points"], json!([2.0]));
            }
        }
    }

    #[tokio::test]
    async fn gtts_request() {
        let server = MockServer::start_async().await;
        let mock = server
            .mock_async(|when, then| {
                when.method(GET).path("/gtt/triggers");
                then.status(200)
                    .body(include_str!("../mock_responses/gtt_get_orders.json"));
            })
            .await;
        let gtts = client(&server).gtts().await.unwrap();
        assert_eq!(gtts.len(), 2);
        assert_eq!(gtts[0].id, 112_127);
        assert_gtt(&gtts[1], 105_099);
        mock.assert_async().await;
    }
    #[tokio::test]
    async fn gtt_request() {
        let server = MockServer::start_async().await;
        let mock = server
            .mock_async(|when, then| {
                when.method(GET).path("/gtt/triggers/123");
                then.status(200)
                    .body(include_str!("../mock_responses/gtt_get_order.json"));
            })
            .await;
        assert_gtt(&client(&server).gtt(123).await.unwrap(), 123);
        mock.assert_async().await;
    }
    #[tokio::test]
    async fn place_gtt_request() {
        let server = MockServer::start_async().await;
        let mock = server.mock_async(|when, then| {
            when.method(POST).path("/gtt/triggers")
                .form_urlencoded_tuple("type", "two-leg")
                .form_urlencoded_tuple("condition", r#"{"exchange":"NSE","last_price":102.6,"tradingsymbol":"RAIN","trigger_values":[102.0,103.7]}"#)
                .form_urlencoded_tuple("orders", r#"[{"exchange":"NSE","order_type":"LIMIT","price":101.5,"product":"CNC","quantity":1,"tradingsymbol":"RAIN","transaction_type":"SELL"},{"exchange":"NSE","order_type":"LIMIT","price":104.0,"product":"CNC","quantity":2,"tradingsymbol":"RAIN","transaction_type":"SELL"}]"#);
            then.status(200).body(include_str!("../mock_responses/gtt_place_order.json"));
        }).await;
        assert_eq!(
            client(&server)
                .place_gtt(params())
                .await
                .unwrap()
                .trigger_id,
            123
        );
        mock.assert_async().await;
    }
    #[tokio::test]
    async fn modify_gtt_request() {
        let server = MockServer::start_async().await;
        let mock = server.mock_async(|when, then| {
            when.method(PUT).path("/gtt/triggers/123")
                .form_urlencoded_tuple("type", "trailing-single")
                .form_urlencoded_tuple("condition", r#"{"exchange":"NSE","last_price":102.6,"tradingsymbol":"RAIN","trailing_points":[2.0],"trigger_values":[100.0]}"#)
                .form_urlencoded_tuple("orders", r#"[{"exchange":"NSE","order_type":"LIMIT","price":99.0,"product":"MIS","quantity":1,"tradingsymbol":"RAIN","transaction_type":"BUY"}]"#);
            then.status(200).body(include_str!("../mock_responses/gtt_modify_order.json"));
        }).await;
        let params = GttParams::new(
            "RAIN",
            Exchange::Nse,
            102.6,
            TransactionType::Buy,
            GttTrigger::TrailingSingle {
                leg: GttTriggerParams::new(100.0, 99.0, 1),
                trailing_points: 2.0,
            },
        )
        .product(Product::Mis);
        assert_eq!(
            client(&server)
                .modify_gtt(123, params)
                .await
                .unwrap()
                .trigger_id,
            123
        );
        mock.assert_async().await;
    }
    #[tokio::test]
    async fn delete_gtt_request() {
        let server = MockServer::start_async().await;
        let mock = server
            .mock_async(|when, then| {
                when.method(DELETE).path("/gtt/triggers/123");
                then.status(200)
                    .body(include_str!("../mock_responses/gtt_delete_order.json"));
            })
            .await;
        assert_eq!(
            client(&server).delete_gtt(123).await.unwrap().trigger_id,
            123
        );
        mock.assert_async().await;
    }
}