Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 5 additions & 1 deletion docs/guide/orders.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
100 changes: 89 additions & 11 deletions src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,13 @@ fn parse_order_price(raw: &str) -> Result<f64, String> {
.ok_or_else(|| "price must be a finite, non-negative number".to_string())
}

fn parse_order_quantity(raw: &str) -> Result<i64, String> {
raw.parse::<i64>()
.ok()
.filter(|quantity| *quantity > 0)
.ok_or_else(|| "quantity must be a positive integer".to_string())
}

fn parse_order_tag(raw: &str) -> Result<String, String> {
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());
Expand Down Expand Up @@ -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<f64>,
/// 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<f64>,
/// Quantity disclosed to the market for equity orders.
#[arg(long)]
#[arg(long, value_parser = clap::value_parser!(i64).range(0..))]
pub disclosed_quantity: Option<i64>,
/// DAY, IOC, TTL.
#[arg(long, ignore_case = true, value_parser = clap::builder::PossibleValuesParser::new(VALIDITIES).map(|value| value.to_ascii_uppercase()))]
pub validity: Option<String>,
/// 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<i64>,
/// 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<i64>,
/// Quantity per iceberg leg.
#[arg(long)]
#[arg(long, value_parser = parse_order_quantity)]
pub iceberg_quantity: Option<i64>,
/// Auction number for auction variety orders.
#[arg(long)]
#[arg(long, required_if_eq("variety", "auction"))]
pub auction_number: Option<String>,
/// -1 for auto protection, or 0-100 percent.
#[arg(long, value_parser = clap::value_parser!(i64).range(-1..=100), allow_hyphen_values = true)]
Expand Down Expand Up @@ -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<String>,
/// New quantity.
#[arg(long)]
#[arg(long, value_parser = parse_order_quantity)]
pub quantity: Option<i64>,
/// New limit price.
#[arg(long, value_parser = parse_order_price)]
Expand All @@ -607,13 +614,13 @@ pub struct OrderModifyArgs {
#[arg(long, value_parser = parse_order_price)]
pub trigger_price: Option<f64>,
/// New disclosed quantity.
#[arg(long)]
#[arg(long, value_parser = clap::value_parser!(i64).range(0..))]
pub disclosed_quantity: Option<i64>,
/// New order validity.
#[arg(long, ignore_case = true, value_parser = clap::builder::PossibleValuesParser::new(VALIDITIES).map(|value| value.to_ascii_uppercase()))]
pub validity: Option<String>,
/// 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<i64>,
/// -1 for automatic protection, or 0 to 100 percent.
#[arg(long, value_parser = clap::value_parser!(i64).range(-1..=100), allow_hyphen_values = true)]
Expand Down Expand Up @@ -995,6 +1002,77 @@ mod tests {
}
}

fn parse_place(extra: &str) -> Result<Cli, clap::Error> {
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"] {
Expand Down
3 changes: 2 additions & 1 deletion src/commands/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -51,6 +51,7 @@ pub async fn handle(rt: &Runtime, command: OrdersCommands) -> Result<Output> {
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(
Expand Down
141 changes: 139 additions & 2 deletions src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,28 @@ pub fn wire_value<T: DeserializeOwned>(value: &str) -> kiteconnect::Result<T> {
.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<f64>| 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<OrderParams> {
Expand Down Expand Up @@ -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<String> {
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<f64>) -> GttWriteArgs {
GttWriteArgs {
Expand Down
Loading
Loading