diff --git a/CHANGELOG.md b/CHANGELOG.md index e3f5cf6..00d4cca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,11 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Fixed + +- `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`. + ## [0.2.3] - 2026-11-12 ### Changed diff --git a/docs/guide/orders.md b/docs/guide/orders.md index d7fa4b7..3b05498 100644 --- a/docs/guide/orders.md +++ b/docs/guide/orders.md @@ -119,7 +119,11 @@ Required flags: `--exchange`, `--tradingsymbol`, `--transaction-type`, `--order- **Parameter validation rules:** - Prices must be finite and non-negative. -- Iceberg legs (`--iceberg-legs`) must be between `2` and `50`. +- `--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`. +- `--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). When Kite accepts the order: diff --git a/src/cli.rs b/src/cli.rs index fdf8cf7..677904a 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -440,6 +440,13 @@ fn parse_order_price(raw: &str) -> Result { .ok_or_else(|| "price must be a finite, non-negative number".to_string()) } +fn parse_order_quantity(raw: &str) -> Result { + raw.parse::() + .ok() + .filter(|quantity| *quantity > 0) + .ok_or_else(|| "quantity must be a positive integer".to_string()) +} + fn parse_order_tag(raw: &str) -> Result { if raw.is_empty() || raw.len() > 20 || !raw.bytes().all(|byte| byte.is_ascii_alphanumeric()) { return Err("order tag must contain 1 to 20 ASCII letters or digits".to_string()); @@ -540,34 +547,34 @@ pub struct OrderPlaceArgs { #[arg(long, ignore_case = true, value_parser = clap::builder::PossibleValuesParser::new(ORDER_TYPES).map(|value| value.to_ascii_uppercase()))] pub order_type: String, /// Number of shares/contracts/units to transact. - #[arg(long)] + #[arg(long, value_parser = parse_order_quantity)] pub quantity: i64, /// CNC, NRML, MIS, MTF, etc. #[arg(long, ignore_case = true, value_parser = clap::builder::PossibleValuesParser::new(PRODUCTS).map(|value| value.to_ascii_uppercase()))] pub product: String, /// Limit price for LIMIT/SL orders. Omit or use 0 for MARKET orders. - #[arg(long, value_parser = parse_order_price)] + #[arg(long, value_parser = parse_order_price, required_if_eq_any([("order_type", "LIMIT"), ("order_type", "SL")]))] pub price: Option, /// Trigger price for SL/SL-M orders. - #[arg(long, value_parser = parse_order_price)] + #[arg(long, value_parser = parse_order_price, required_if_eq_any([("order_type", "SL"), ("order_type", "SL-M")]))] pub trigger_price: Option, /// Quantity disclosed to the market for equity orders. - #[arg(long)] + #[arg(long, value_parser = clap::value_parser!(i64).range(0..))] pub disclosed_quantity: Option, /// DAY, IOC, TTL. #[arg(long, ignore_case = true, value_parser = clap::builder::PossibleValuesParser::new(VALIDITIES).map(|value| value.to_ascii_uppercase()))] pub validity: Option, /// TTL validity in minutes. Used only when --validity TTL. - #[arg(long)] + #[arg(long, value_parser = clap::value_parser!(i64).range(1..), required_if_eq("validity", "TTL"))] pub validity_ttl: Option, /// Number of iceberg legs, between 2 and 50. - #[arg(long, value_parser = clap::value_parser!(i64).range(2..=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. - #[arg(long)] + #[arg(long, value_parser = parse_order_quantity)] pub iceberg_quantity: Option, /// Auction number for auction variety orders. - #[arg(long)] + #[arg(long, required_if_eq("variety", "auction"))] pub auction_number: Option, /// -1 for auto protection, or 0-100 percent. #[arg(long, value_parser = clap::value_parser!(i64).range(-1..=100), allow_hyphen_values = true)] @@ -598,7 +605,7 @@ pub struct OrderModifyArgs { #[arg(long, ignore_case = true, value_parser = clap::builder::PossibleValuesParser::new(ORDER_TYPES).map(|value| value.to_ascii_uppercase()))] pub order_type: Option, /// New quantity. - #[arg(long)] + #[arg(long, value_parser = parse_order_quantity)] pub quantity: Option, /// New limit price. #[arg(long, value_parser = parse_order_price)] @@ -607,13 +614,13 @@ pub struct OrderModifyArgs { #[arg(long, value_parser = parse_order_price)] pub trigger_price: Option, /// New disclosed quantity. - #[arg(long)] + #[arg(long, value_parser = clap::value_parser!(i64).range(0..))] pub disclosed_quantity: Option, /// New order validity. #[arg(long, ignore_case = true, value_parser = clap::builder::PossibleValuesParser::new(VALIDITIES).map(|value| value.to_ascii_uppercase()))] pub validity: Option, /// New TTL validity in minutes. Used only when --validity TTL. - #[arg(long)] + #[arg(long, value_parser = clap::value_parser!(i64).range(1..))] pub validity_ttl: Option, /// -1 for automatic protection, or 0 to 100 percent. #[arg(long, value_parser = clap::value_parser!(i64).range(-1..=100), allow_hyphen_values = true)] @@ -995,6 +1002,77 @@ mod tests { } } + fn parse_place(extra: &str) -> Result { + use clap::Parser; + Cli::try_parse_from( + "kite orders place --exchange NFO --tradingsymbol NIFTY26NOVFUT --transaction-type BUY --product NRML" + .split_whitespace() + .chain(extra.split_whitespace()), + ) + } + + #[test] + fn order_flags_required_by_the_order_type_or_variety_are_enforced() { + for (extra, missing) in [ + ("--quantity 75 --order-type LIMIT", "--price"), + ("--quantity 75 --order-type sl", "--price"), + ( + "--quantity 75 --order-type SL --price 100", + "--trigger-price", + ), + ("--quantity 75 --order-type SL-M", "--trigger-price"), + ( + "--quantity 75 --order-type MARKET --variety iceberg", + "--iceberg-legs", + ), + ( + "--quantity 75 --order-type MARKET --validity TTL", + "--validity-ttl", + ), + ( + "--quantity 75 --order-type MARKET --variety auction", + "--auction-number", + ), + ] { + let error = parse_place(extra).unwrap_err(); + assert_eq!( + error.kind(), + clap::error::ErrorKind::MissingRequiredArgument, + "{extra}" + ); + assert!(error.to_string().contains(missing), "{extra}"); + } + assert!(parse_place("--quantity 75 --order-type MARKET").is_ok()); + } + + #[test] + fn order_quantities_refuse_values_kite_cannot_accept() { + use clap::Parser; + for extra in [ + "--order-type MARKET --quantity 0", + "--order-type MARKET --quantity=-75", + "--order-type MARKET --quantity 75 --disclosed-quantity=-5", + "--order-type MARKET --quantity 75 --iceberg-quantity 0", + "--order-type MARKET --quantity 75 --validity-ttl 0", + ] { + assert_eq!( + parse_place(extra).unwrap_err().kind(), + clap::error::ErrorKind::ValueValidation, + "{extra}" + ); + } + for extra in ["--quantity 0", "--quantity=-5", "--validity-ttl 0"] { + let args = "kite orders modify --order-id 1" + .split_whitespace() + .chain(extra.split_whitespace()); + assert_eq!( + Cli::try_parse_from(args).unwrap_err().kind(), + clap::error::ErrorKind::ValueValidation, + "{extra}" + ); + } + } + #[test] fn order_prices_and_tags_refuse_invalid_wire_values() { for value in ["NaN", "inf", "-1", "-inf"] { diff --git a/src/commands/orders.rs b/src/commands/orders.rs index 1996ee3..17e72de 100644 --- a/src/commands/orders.rs +++ b/src/commands/orders.rs @@ -3,7 +3,7 @@ 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, wire_value}; +use crate::util::{order_modify_params, order_place_params, validate_order_place, wire_value}; use anyhow::{Result, bail}; use serde_json::Value; @@ -51,6 +51,7 @@ pub async fn handle(rt: &Runtime, command: OrdersCommands) -> Result { None => rt.with_session(|api| api.trades().raw()).await?, }, OrdersCommands::Place(args) => { + validate_order_place(&args)?; let variety = wire_value(&args.variety)?; let params = order_place_params(&args)?; return send_unless_dry_run( diff --git a/src/util.rs b/src/util.rs index 1596081..c88f2a1 100644 --- a/src/util.rs +++ b/src/util.rs @@ -148,6 +148,28 @@ pub fn wire_value(value: &str) -> kiteconnect::Result { .map_err(|_| kiteconnect::Error::InvalidInput("invalid order parameter")) } +/// Checks that depend on more than one flag, which clap cannot express. +/// +/// # Errors +/// Returns an error if the flags describe an order Kite cannot accept as written. +pub fn validate_order_place(args: &OrderPlaceArgs) -> Result<()> { + let positive = |value: Option| value.is_some_and(|value| value > 0.0); + if matches!(args.order_type.as_str(), "LIMIT" | "SL") && !positive(args.price) { + bail!("--price must be greater than 0 for LIMIT and SL orders"); + } + if matches!(args.order_type.as_str(), "SL" | "SL-M") && !positive(args.trigger_price) { + bail!("--trigger-price must be greater than 0 for SL and SL-M orders"); + } + if args.validity_ttl.is_some() && args.validity.as_deref() != Some("TTL") { + bail!("--validity-ttl requires --validity TTL"); + } + if args.variety != "iceberg" && (args.iceberg_legs.is_some() || args.iceberg_quantity.is_some()) + { + bail!("--iceberg-legs and --iceberg-quantity require --variety iceberg"); + } + Ok(()) +} + /// # Errors /// Returns an error if an order parameter is not a supported wire value. pub fn order_place_params(args: &OrderPlaceArgs) -> kiteconnect::Result { @@ -443,8 +465,123 @@ 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}; - use crate::cli::{ConfirmArgs, GttWriteArgs}; + use super::{csv_records, gtt_payload, parse_key_values, validate_order_place}; + use crate::cli::{Cli, Commands, ConfirmArgs, GttWriteArgs, OrdersCommands}; + use clap::Parser; + + fn place_error(extra: &[&str]) -> Option { + let mut args = vec![ + "kite", + "orders", + "place", + "--exchange", + "NFO", + "--tradingsymbol", + "NIFTY26NOVFUT", + "--transaction-type", + "BUY", + "--product", + "NRML", + "--quantity", + "75", + ]; + args.extend(extra); + let Some(Commands::Orders { + command: OrdersCommands::Place(args), + }) = Cli::try_parse_from(args).unwrap().command + else { + panic!("expected orders place") + }; + validate_order_place(&args) + .err() + .map(|error| error.to_string()) + } + + #[test] + fn order_flags_that_contradict_each_other_are_refused() { + for (extra, message) in [ + ( + &["--order-type", "LIMIT", "--price", "0"][..], + "--price must be greater than 0 for LIMIT and SL orders", + ), + ( + &[ + "--order-type", + "SL", + "--price", + "0", + "--trigger-price", + "99", + ], + "--price must be greater than 0 for LIMIT and SL orders", + ), + ( + &["--order-type", "sl-m", "--trigger-price", "0"], + "--trigger-price must be greater than 0 for SL and SL-M orders", + ), + ( + &["--order-type", "MARKET", "--validity-ttl", "5"], + "--validity-ttl requires --validity TTL", + ), + ( + &[ + "--order-type", + "MARKET", + "--validity", + "DAY", + "--validity-ttl", + "5", + ], + "--validity-ttl requires --validity TTL", + ), + ( + &["--order-type", "MARKET", "--iceberg-legs", "3"], + "--iceberg-legs and --iceberg-quantity require --variety iceberg", + ), + ( + &["--order-type", "MARKET", "--iceberg-quantity", "25"], + "--iceberg-legs and --iceberg-quantity require --variety iceberg", + ), + ] { + assert_eq!(place_error(extra).as_deref(), Some(message), "{extra:?}"); + } + } + + #[test] + fn complete_orders_pass_validation() { + for extra in [ + &["--order-type", "MARKET"][..], + &["--order-type", "MARKET", "--price", "0"], + &["--order-type", "LIMIT", "--price", "100"], + &[ + "--order-type", + "SL", + "--price", + "100", + "--trigger-price", + "99", + ], + &["--order-type", "SL-M", "--trigger-price", "99"], + &[ + "--order-type", + "MARKET", + "--validity", + "ttl", + "--validity-ttl", + "5", + ], + &[ + "--order-type", + "MARKET", + "--variety", + "ICEBERG", + "--iceberg-legs", + "3", + ], + ] { + assert_eq!(place_error(extra), None, "{extra:?}"); + } + } fn gtt_args(trigger_type: &str, trailing_points: Option) -> GttWriteArgs { GttWriteArgs { diff --git a/tests/cli_output.rs b/tests/cli_output.rs index 4882609..d61ce34 100644 --- a/tests/cli_output.rs +++ b/tests/cli_output.rs @@ -2234,6 +2234,8 @@ fn mixed_case_order_flags_send_canonical_values() { "limit", "--quantity", "1", + "--price", + "1500", ], true, ); @@ -2344,6 +2346,14 @@ fn invalid_order_and_market_arguments_fail_before_a_request() { vec!["--iceberg-legs", "1"], vec!["--iceberg-legs", "51"], vec!["--tag", "has space"], + vec!["--quantity", "0"], + vec!["--quantity=-1"], + vec!["--disclosed-quantity=-1"], + vec!["--order-type", "SL"], + vec!["--order-type", "SL-M"], + vec!["--variety", "iceberg"], + vec!["--variety", "auction"], + vec!["--validity", "TTL"], ] { let mut args = PLACE.to_vec(); if extra[0] == "--price" { @@ -2362,3 +2372,53 @@ fn invalid_order_and_market_arguments_fail_before_a_request() { assert_eq!(setup.run(binary, args, true).status.code(), Some(2)); } } + +#[test] +fn order_dry_runs_refuse_flags_that_contradict_each_other() { + let setup = Setup::new(); + let binary = Path::new(env!("CARGO_BIN_EXE_kite")); + let writes = setup.server.mock(|when, then| { + when.path_prefix("/orders"); + then.status(500); + }); + for (extra, message) in [ + ( + vec!["--price", "0"], + "error: --price must be greater than 0 for LIMIT and SL orders\n", + ), + ( + vec!["--order-type", "SL-M", "--trigger-price", "0"], + "error: --trigger-price must be greater than 0 for SL and SL-M orders\n", + ), + ( + vec!["--validity-ttl", "5"], + "error: --validity-ttl requires --validity TTL\n", + ), + ( + vec!["--iceberg-legs", "3"], + "error: --iceberg-legs and --iceberg-quantity require --variety iceberg\n", + ), + ] { + for confirm in [false, true] { + let mut args = PLACE.to_vec(); + for flag in extra.iter().filter(|value| value.starts_with("--")) { + if let Some(index) = args.iter().position(|value| value == flag) { + args.drain(index..index + 2); + } + } + args.extend(&extra); + if confirm { + args.push("--confirm"); + } + let result = setup.run(binary, &args, false); + assert_eq!(result.status.code(), Some(1), "{args:?}"); + assert_eq!(result.stdout, b"", "{args:?}"); + assert_eq!( + String::from_utf8(result.stderr).unwrap(), + message, + "{args:?}" + ); + } + } + writes.assert_calls(0); +}