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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion docs/guide/orders.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
2 changes: 1 addition & 1 deletion src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<i64>,
/// 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<i64>,
/// Auction number for auction variety orders.
Expand Down
28 changes: 25 additions & 3 deletions src/commands/orders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Output> {
Expand Down Expand Up @@ -50,8 +52,14 @@ pub async fn handle(rt: &Runtime, command: OrdersCommands) -> Result<Output> {
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(
Expand Down Expand Up @@ -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<u32> {
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")
})
}
30 changes: 29 additions & 1 deletion src/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<OrderParams> {
Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -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 [
Expand Down
53 changes: 53 additions & 0 deletions tests/cli_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Loading