diff --git a/CHANGELOG.md b/CHANGELOG.md index f37db41..3093533 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - `kite orders place` refuses orders that are incomplete as written, in dry runs and with `--confirm`: a LIMIT or SL order without a positive `--price`, an SL or SL-M order without a positive `--trigger-price`, `--variety iceberg` without `--iceberg-legs`, `--variety auction` without `--auction-number`, `--validity TTL` without `--validity-ttl`, and iceberg or TTL flags given without their variety or validity. It previously printed a dry run and exited 0. - `kite orders place` and `kite orders modify` refuse a zero or negative `--quantity` and a negative `--disclosed-quantity`. +- `kite orders place --variety iceberg` without `--iceberg-quantity` sends the per-leg quantity Kite web sends: the quantity split across the legs, rounded up to whole lots of the instrument. It previously sent no per-leg quantity. - An autoslice order placed from the TUI order ticket shows an error toast when Kite rejects a slice. The toast counts the failed slices and gives each one's reason. It previously showed only the first order ID as placed. This also covers orders the ticket slices by itself above the freeze quantity. - The TUI shows rupee totals to the paisa, as Kite does: the Positions P&L summary, the Overview tiles and panel totals, the Holdings title, Funds and the available margin in the header. They were rounded to whole rupees, so a P&L of +619.16 read +₹619. - SSE IPO rows show Applied only when an application is live. Any order object in Kite's reply used to mark the issue applied, even after every application had failed or been cancelled. diff --git a/docs/guide/orders.md b/docs/guide/orders.md index 3b05498..c290758 100644 --- a/docs/guide/orders.md +++ b/docs/guide/orders.md @@ -121,7 +121,7 @@ Required flags: `--exchange`, `--tradingsymbol`, `--transaction-type`, `--order- - Prices must be finite and non-negative. - `--quantity` must be a positive integer. - `LIMIT` and `SL` orders need a positive `--price`. `SL` and `SL-M` orders need a positive `--trigger-price`. -- Iceberg legs (`--iceberg-legs`) must be between `2` and `50`. `--variety iceberg` needs `--iceberg-legs`, and the iceberg flags need `--variety iceberg`. +- Iceberg legs (`--iceberg-legs`) must be between `2` and `50`. `--variety iceberg` needs `--iceberg-legs`, and the iceberg flags need `--variety iceberg`. Without `--iceberg-quantity`, the CLI sends what Kite web does: the quantity split across the legs, rounded up to whole lots of the instrument. - `--validity TTL` needs `--validity-ttl`, and `--validity-ttl` needs `--validity TTL`. - `--variety auction` needs `--auction-number`. - Order tags (`--tag`) must be `1` to `20` ASCII alphanumeric characters, following the [Kite Connect order parameters specification](https://kite.trade/docs/connect/v3/orders/#regular-order-parameters). diff --git a/src/cli.rs b/src/cli.rs index 677904a..414ca4a 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -570,7 +570,7 @@ pub struct OrderPlaceArgs { /// Number of iceberg legs, between 2 and 50. #[arg(long, value_parser = clap::value_parser!(i64).range(2..=50), required_if_eq("variety", "iceberg"))] pub iceberg_legs: Option, - /// Quantity per iceberg leg. + /// Quantity per iceberg leg. Defaults to Kite web's split: the quantity over the legs, rounded up to whole lots. #[arg(long, value_parser = parse_order_quantity)] pub iceberg_quantity: Option, /// Auction number for auction variety orders. diff --git a/src/commands/orders.rs b/src/commands/orders.rs index 17e72de..c6e4aa4 100644 --- a/src/commands/orders.rs +++ b/src/commands/orders.rs @@ -3,8 +3,10 @@ use crate::app::output::Output; use crate::app::render; use crate::app::runtime::Runtime; use crate::cli::OrdersCommands; -use crate::util::{order_modify_params, order_place_params, validate_order_place, wire_value}; -use anyhow::{Result, bail}; +use crate::util::{ + iceberg_leg_quantity, order_modify_params, order_place_params, validate_order_place, wire_value, +}; +use anyhow::{Context, Result, bail}; use serde_json::Value; pub async fn handle(rt: &Runtime, command: OrdersCommands) -> Result { @@ -50,8 +52,14 @@ pub async fn handle(rt: &Runtime, command: OrdersCommands) -> Result { Some(id) => rt.with_session(|api| api.order_trades(&id).raw()).await?, None => rt.with_session(|api| api.trades().raw()).await?, }, - OrdersCommands::Place(args) => { + OrdersCommands::Place(mut args) => { validate_order_place(&args)?; + if let Some(legs) = args.iceberg_legs + && args.iceberg_quantity.is_none() + { + let lot = lot_size(rt, &args.exchange, &args.tradingsymbol).await?; + args.iceberg_quantity = Some(iceberg_leg_quantity(args.quantity, legs, lot)); + } let variety = wire_value(&args.variety)?; let params = order_place_params(&args)?; return send_unless_dry_run( @@ -152,3 +160,17 @@ fn matches_string_field(item: &Value, field: &str, expected: Option<&str>) -> bo } }) } + +async fn lot_size(rt: &Runtime, exchange: &str, tradingsymbol: &str) -> Result { + let store = crate::instruments::load(&rt.app_uuid()?) + .await + .map_err(anyhow::Error::msg)?; + store + .by_exact_symbol(tradingsymbol) + .into_iter() + .find(|instrument| instrument.exchange.eq_ignore_ascii_case(exchange)) + .map(|instrument| instrument.lot_size) + .with_context(|| { + format!("instrument not found: {exchange}:{tradingsymbol}; pass --iceberg-quantity") + }) +} diff --git a/src/util.rs b/src/util.rs index c88f2a1..dd51b4c 100644 --- a/src/util.rs +++ b/src/util.rs @@ -170,6 +170,15 @@ pub fn validate_order_place(args: &OrderPlaceArgs) -> Result<()> { Ok(()) } +/// Kite web's quantity per iceberg leg: the order split evenly across the +/// legs, rounded up to a whole number of lots. +#[must_use] +pub fn iceberg_leg_quantity(quantity: i64, legs: i64, lot_size: u32) -> i64 { + let lot = i64::from(lot_size.max(1)); + let per_leg = legs.max(2) * lot; + (quantity + per_leg - 1) / per_leg * lot +} + /// # Errors /// Returns an error if an order parameter is not a supported wire value. pub fn order_place_params(args: &OrderPlaceArgs) -> kiteconnect::Result { @@ -465,7 +474,9 @@ fn read_one_json(inline: Option<&str>, file: Option<&Path>, name: &str) -> Resul #[cfg(test)] mod tests { - use super::{csv_records, gtt_payload, parse_key_values, validate_order_place}; + use super::{ + csv_records, gtt_payload, iceberg_leg_quantity, parse_key_values, validate_order_place, + }; use crate::cli::{Cli, Commands, ConfirmArgs, GttWriteArgs, OrdersCommands}; use clap::Parser; @@ -547,6 +558,23 @@ mod tests { } } + #[test] + fn iceberg_legs_split_like_kite_web_and_round_up_to_whole_lots() { + for (quantity, legs, lot, per_leg) in [ + (100, 4, 1, 25), + (101, 4, 1, 26), + (750, 4, 75, 225), + (750, 10, 75, 75), + (9000, 3, 0, 3000), + ] { + assert_eq!( + iceberg_leg_quantity(quantity, legs, lot), + per_leg, + "{quantity} over {legs} legs of lot {lot}" + ); + } + } + #[test] fn complete_orders_pass_validation() { for extra in [ diff --git a/tests/cli_output.rs b/tests/cli_output.rs index d61ce34..91a7a39 100644 --- a/tests/cli_output.rs +++ b/tests/cli_output.rs @@ -2422,3 +2422,56 @@ fn order_dry_runs_refuse_flags_that_contradict_each_other() { } writes.assert_calls(0); } + +#[test] +fn an_iceberg_order_without_a_leg_quantity_splits_like_kite_web() { + let setup = Setup::new(); + let binary = Path::new(env!("CARGO_BIN_EXE_kite")); + let cache = setup.cache_path(); + fs::create_dir_all(cache.parent().unwrap()).unwrap(); + let records = + [("NSE", "INFY", 1), ("NFO", "NIFTY26NOVFUT", 75)].map(|(exchange, symbol, lot)| { + json!({ + "instrument_token":1,"tradingsymbol":symbol,"name":symbol,"exchange":exchange, + "tick_size":0.05,"lot_size":lot,"instrument_type":"EQ","segment":exchange + }) + }); + fs::write(&cache, serde_json::to_vec(&records).unwrap()).unwrap(); + let writes = setup.server.mock(|when, then| { + when.path_prefix("/orders"); + then.status(500); + }); + let iceberg = |exchange: &str, symbol: &str, quantity: &str, legs: &str| { + let mut args: Vec<&str> = PLACE.to_vec(); + for (flag, value) in [ + ("--exchange", exchange), + ("--tradingsymbol", symbol), + ("--quantity", quantity), + ] { + let index = args.iter().position(|arg| *arg == flag).unwrap(); + args[index + 1] = value; + } + args.extend(["--variety", "iceberg", "--iceberg-legs", legs]); + setup.run(binary, &args, true) + }; + for (exchange, symbol, quantity, legs, per_leg) in [ + ("NSE", "INFY", "101", "4", "26"), + ("NFO", "NIFTY26NOVFUT", "750", "4", "225"), + ] { + let result = iceberg(exchange, symbol, quantity, legs); + assert_eq!(result.status.code(), Some(0), "{symbol}"); + let body: Value = serde_json::from_slice(&result.stdout).unwrap(); + assert_eq!( + body["body"]["form"]["iceberg_quantity"], per_leg, + "{symbol}: {body}" + ); + } + let missing = iceberg("NSE", "NOSUCH", "100", "4"); + assert_eq!(missing.status.code(), Some(1)); + assert!( + String::from_utf8(missing.stdout) + .unwrap() + .contains("instrument not found: NSE:NOSUCH; pass --iceberg-quantity") + ); + writes.assert_calls(0); +}