use crate::{Call, KiteConnect, Request};
use chrono::NaiveDateTime;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct UserMeta {
pub demat_consent: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct FullUserMeta {
pub poa: Option<String>,
pub silo: String,
#[serde(default)]
pub account_blocks: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct Bank {
pub name: String,
pub branch: String,
pub account: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct UserProfile {
pub user_id: String,
pub user_name: String,
pub user_shortname: String,
pub avatar_url: Option<String>,
pub user_type: String,
pub email: String,
pub broker: String,
pub meta: UserMeta,
#[serde(default)]
pub products: Vec<String>,
#[serde(default)]
pub order_types: Vec<String>,
#[serde(default)]
pub exchanges: Vec<String>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct FullUserProfile {
pub user_id: String,
pub user_name: String,
pub user_shortname: String,
pub avatar_url: Option<String>,
pub user_type: String,
pub email: String,
pub broker: String,
pub phone: String,
pub twofa_type: String,
#[serde(default)]
pub bank_accounts: Vec<Bank>,
#[serde(default)]
pub dp_ids: Vec<String>,
#[serde(default)]
pub products: Vec<String>,
#[serde(default)]
pub order_types: Vec<String>,
#[serde(default)]
pub exchanges: Vec<String>,
pub pan: String,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default, with = "crate::time::optional_datetime")]
pub password_timestamp: Option<NaiveDateTime>,
#[serde(default, with = "crate::time::optional_datetime")]
pub twofa_timestamp: Option<NaiveDateTime>,
pub meta: FullUserMeta,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[non_exhaustive]
pub struct AvailableMargins {
pub adhoc_margin: f64,
pub cash: f64,
pub collateral: f64,
pub intraday_payin: f64,
pub live_balance: Option<f64>,
pub opening_balance: f64,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[non_exhaustive]
pub struct UsedMargins {
pub debits: f64,
pub exposure: f64,
pub m2m_realised: f64,
pub m2m_unrealised: f64,
pub option_premium: f64,
pub payout: f64,
pub span: f64,
pub holding_sales: f64,
pub turnover: f64,
pub liquid_collateral: f64,
pub stock_collateral: f64,
pub delivery: f64,
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[non_exhaustive]
pub struct Margins {
pub enabled: bool,
pub net: f64,
pub available: AvailableMargins,
pub utilised: UsedMargins,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[non_exhaustive]
pub struct AllMargins {
pub equity: Margins,
pub commodity: Option<Margins>,
}
impl KiteConnect {
pub fn profile(&self) -> Call<UserProfile> {
Call::new(self.clone(), Request::get("/user/profile"))
}
pub fn full_profile(&self) -> Call<FullUserProfile> {
Call::new(self.clone(), Request::get("/user/profile/full"))
}
pub fn margins(&self) -> Call<AllMargins> {
Call::new(self.clone(), Request::get("/user/margins"))
}
pub fn segment_margins(&self, segment: &str) -> Call<Margins> {
Call::new(
self.clone(),
Request::get(format!("/user/margins/{segment}")),
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use httpmock::prelude::*;
use serde_json::{Value, json};
fn data(fixture: &str) -> Value {
serde_json::from_str::<Value>(fixture).unwrap()["data"].clone()
}
#[test]
fn profile_fixtures_decode_nested_types() {
let profile: UserProfile =
serde_json::from_value(data(include_str!("../mock_responses/profile.json"))).unwrap();
assert_eq!(profile.user_id, "AB1234");
assert_eq!(profile.user_shortname, "AxAx");
assert_eq!(profile.avatar_url, None);
assert_eq!(profile.meta.demat_consent, "physical");
let full: FullUserProfile =
serde_json::from_value(data(include_str!("../mock_responses/full_profile.json")))
.unwrap();
assert_eq!(full.phone, "*9999");
assert_eq!(full.bank_accounts[0].name, "HDFC BANK");
assert_eq!(full.bank_accounts[0].branch, "");
assert_eq!(full.bank_accounts[1].account, "*9999");
assert_eq!(full.meta.poa.as_deref(), Some("physical"));
assert_eq!(full.meta.silo, "x");
assert_eq!(full.meta.account_blocks.len(), 0);
assert_eq!(
full.password_timestamp.unwrap().to_string(),
"1970-01-01 00:00:00"
);
assert_eq!(
full.twofa_timestamp.unwrap().to_string(),
"1970-01-01 00:00:00"
);
}
#[test]
fn margin_fixtures_decode_required_totals() {
let all: AllMargins =
serde_json::from_value(data(include_str!("../mock_responses/margins.json"))).unwrap();
assert_eq!(
all.equity.net.to_bits(),
f64::to_bits(99_725.050_000_000_02)
);
assert_eq!(all.equity.available.cash.to_bits(), f64::to_bits(245_431.6));
assert_eq!(all.equity.utilised.span.to_bits(), f64::to_bits(101_989.0));
assert_eq!(
all.commodity.as_ref().unwrap().net.to_bits(),
f64::to_bits(100_661.7)
);
let equity: Margins =
serde_json::from_value(data(include_str!("../mock_responses/margins_equity.json")))
.unwrap();
assert_eq!(
equity.available.opening_balance.to_bits(),
f64::to_bits(245_431.6)
);
assert_eq!(equity.utilised.debits.to_bits(), f64::to_bits(145_706.55));
let commodity: Margins = serde_json::from_value(data(include_str!(
"../mock_responses/margin_commodity.json"
)))
.unwrap();
assert_eq!(commodity.available.live_balance, Some(96426.33));
assert_eq!(commodity.utilised.exposure.to_bits(), f64::to_bits(117.35));
let mut missing = data(include_str!("../mock_responses/margins_equity.json"));
missing.as_object_mut().unwrap().remove("net");
assert!(serde_json::from_value::<Margins>(missing).is_err());
let mut missing = data(include_str!("../mock_responses/margins_equity.json"));
missing["available"].as_object_mut().unwrap().remove("cash");
assert!(serde_json::from_value::<Margins>(missing).is_err());
assert!(serde_json::from_value::<UserProfile>(json!({})).is_err());
}
#[tokio::test]
async fn profile_http_contract() {
let server = MockServer::start_async().await;
let mock = server
.mock_async(|when, then| {
when.method(GET)
.path("/user/profile")
.query_param_count(".*", ".*", 0)
.header_missing("content-type");
then.body(include_str!("../mock_responses/profile.json"));
})
.await;
let client = KiteConnect::builder("key")
.base_url(server.base_url())
.build()
.unwrap();
assert_eq!(client.profile().await.unwrap().user_id, "AB1234");
mock.assert_async().await;
}
#[tokio::test]
async fn full_profile_http_contract() {
let server = MockServer::start_async().await;
let mock = server
.mock_async(|when, then| {
when.method(GET)
.path("/user/profile/full")
.query_param_count(".*", ".*", 0)
.header_missing("content-type");
then.body(include_str!("../mock_responses/full_profile.json"));
})
.await;
let client = KiteConnect::builder("key")
.base_url(server.base_url())
.build()
.unwrap();
assert_eq!(client.full_profile().await.unwrap().twofa_type, "totp");
mock.assert_async().await;
}
#[tokio::test]
async fn margins_http_contract() {
let server = MockServer::start_async().await;
let mock = server
.mock_async(|when, then| {
when.method(GET)
.path("/user/margins")
.query_param_count(".*", ".*", 0)
.header_missing("content-type");
then.body(include_str!("../mock_responses/margins.json"));
})
.await;
let client = KiteConnect::builder("key")
.base_url(server.base_url())
.build()
.unwrap();
assert_eq!(
client
.margins()
.await
.unwrap()
.commodity
.unwrap()
.net
.to_bits(),
f64::to_bits(100_661.7)
);
mock.assert_async().await;
}
#[tokio::test]
async fn segment_margins_http_contract() {
let server = MockServer::start_async().await;
let mock = server
.mock_async(|when, then| {
when.method(GET)
.path("/user/margins/equity")
.query_param_count(".*", ".*", 0)
.header_missing("content-type");
then.body(include_str!("../mock_responses/margins_equity.json"));
})
.await;
let client = KiteConnect::builder("key")
.base_url(server.base_url())
.build()
.unwrap();
assert_eq!(
client
.segment_margins("equity")
.await
.unwrap()
.utilised
.debits
.to_bits(),
f64::to_bits(145_706.55)
);
mock.assert_async().await;
}
}