feat: shareholder movements from the Stockbit session (ownership movements)

`idx ownership movements [SYMBOL]` and the MCP tool
`get_shareholder_movements` list reported changes in insiders' and major
holders' stakes, newest first, from Stockbit's
/insider/company/majorholder: IDX insider disclosures (any size, with the
trade price) and KSEI changes of holders at 5% and above (Stockbit's
estimated price). Stockbit filters by date range, holder id, action and
source; each page is 50 rows and one request, up to 10 pages, cached an
hour per page under every filter.

Rows keep exact signed share counts and the stake in basis points as
Stockbit rounds it; unknown action labels are kept as `other` rather than
dropped. JSON is {movements, more}; JSONL is one movement per line. The
command lives under `ownership` but needs no import, and `ownership`
commands now take --offline / --no-cache for it.

The per-symbol summary score is the next PR; docs/STOCKBIT.md records the
endpoint's parameters and action types as checked on 2026-11-03.

Claude-Session: https://claude.ai/code/session_01RqPPVeVDrnLoP7NUZmLRxY
This commit is contained in:
Rasyidan Akbar F. 2026-11-03 16:02:26 +07:00
commit ae0ca0c109
43 changed files with 3050 additions and 29 deletions

View file

@ -1,17 +1,18 @@
//! Fixture-backed provider for tests, enabled by the `testing` feature and
//! `IDX_USE_MOCK_PROVIDER`. Release builds do not contain it.
use super::stockbit::{corpaction, exodus};
use super::stockbit::{corpaction, exodus, movement};
use super::types::{Bar, Fundamentals, Interval, Intraday, OrderBook, Period, Quote};
use super::{
BrokerSummaryProvider, CorporateActionProvider, FundamentalsProvider, HistoryProvider,
IntradayProvider, OrderBookProvider, QuoteProvider, TradingSummaryProvider, idx, ipot, msn,
stockbit, yahoo,
IntradayProvider, OrderBookProvider, QuoteProvider, ShareholderMovementProvider,
TradingSummaryProvider, idx, ipot, msn, stockbit, yahoo,
};
use crate::broker::types::{BrokerBoard, BrokerInvestor, BrokerQuery};
use crate::config::ProviderKind;
use crate::corporate::types::{ActionKind, CorporateAction};
use crate::error::IdxError;
use crate::movements::types::{MovementPage, MovementQuery};
pub(crate) fn enabled() -> bool {
std::env::var("IDX_USE_MOCK_PROVIDER").is_ok()
@ -254,6 +255,36 @@ impl CorporateActionProvider for MockStockbitProvider {
}
}
/// `stockbit_exodus_majorholder[_<code>][_p<page>].json` (no suffix for page
/// 1); a missing fixture is an empty page, as Stockbit answers past the end.
/// The query's filters apply to the fixture's rows, as Stockbit applies them.
impl ShareholderMovementProvider for MockStockbitProvider {
fn shareholder_movements(
&self,
query: &MovementQuery,
page: u32,
) -> Result<MovementPage, IdxError> {
let subject = query.symbol.as_deref().unwrap_or("shareholder movements");
let mut name = "majorholder".to_string();
if let Some(symbol) = &query.symbol {
name.push('_');
name.push_str(&stockbit::stockbit_code(symbol)?.to_ascii_lowercase());
}
if page > 1 {
name.push_str(&format!("_p{page}"));
}
let body = match self.exodus(subject, &format!("{name}.json")) {
Err(IdxError::SymbolNotFound(_)) if query.symbol.is_some() || page > 1 => {
r#"{"data":{"is_more":false,"movement":[]}}"#.to_string()
}
other => other?,
};
let mut parsed = movement::parse_movements(&body)?;
parsed.movements.retain(|m| query.admits(m));
Ok(parsed)
}
}
impl HistoryProvider for MockStockbitProvider {
fn history(
&self,

View file

@ -89,6 +89,17 @@ pub trait CorporateActionProvider {
) -> Result<Vec<crate::corporate::types::CorporateAction>, IdxError>;
}
/// Shareholder movements: needs the user's Stockbit session.
pub trait ShareholderMovementProvider {
/// Page `page` (from 1) of `query`, whose `symbol` is resolved
/// (`BBCA.JK`) or `None` for the market.
fn shareholder_movements(
&self,
query: &crate::movements::types::MovementQuery,
page: u32,
) -> Result<crate::movements::types::MovementPage, IdxError>;
}
pub trait FundamentalsProvider {
fn fundamentals(&self, symbol: &str) -> Result<Fundamentals, IdxError>;
}
@ -364,6 +375,14 @@ pub fn corporate_action_provider() -> Box<dyn CorporateActionProvider> {
Box::new(stockbit::StockbitProvider::new())
}
pub fn shareholder_movement_provider() -> Box<dyn ShareholderMovementProvider> {
#[cfg(feature = "testing")]
if mock::enabled() {
return Box::new(mock::MockStockbitProvider);
}
Box::new(stockbit::StockbitProvider::new())
}
/// Today in WIB, the date IDX trades on.
pub(crate) fn today_wib() -> chrono::NaiveDate {
#[cfg(feature = "testing")]

View file

@ -25,12 +25,13 @@ use chrono::{Months, NaiveDate};
use serde_json::Value;
use super::auth::SessionStore;
use super::corpaction;
use super::parse::number;
use super::{USER_AGENT, pace, stockbit_code};
use super::{corpaction, movement};
use crate::api::types::{BookLevel, Interval, Ohlc, OrderBook, Period, Quote};
use crate::corporate::types::{ActionKind, CorporateAction};
use crate::error::IdxError;
use crate::movements::types::{MovementPage, MovementQuery};
const BASE_URL: &str = "https://exodus.stockbit.com";
const REFRESH_PATH: &str = "/login/refresh";
@ -140,6 +141,25 @@ impl Exodus {
corpaction::parse_corporate_actions(kind, &body)
}
/// Page `page` of shareholder movements: one stock's (`query.symbol`,
/// resolved) or the market's.
pub(crate) fn shareholder_movements(
&self,
query: &MovementQuery,
page: u32,
) -> Result<MovementPage, IdxError> {
let code = query.symbol.as_deref().map(stockbit_code).transpose()?;
let subject = query
.symbol
.clone()
.unwrap_or_else(|| "shareholder movements".to_string());
let body = self.get(
&movement::request_path(query, code.as_deref(), page),
&subject,
)?;
movement::parse_movements(&body)
}
/// The market's state, read at most every `MARKET_STATE_TTL` per process.
/// Unknown on any failure, which hides bid/offer.
fn market_status(&self) -> Option<String> {

View file

@ -20,6 +20,7 @@ pub mod browser;
pub mod corpaction;
pub mod exodus;
pub mod loopback;
pub mod movement;
mod parse;
pub mod signin;
@ -33,10 +34,11 @@ pub use parse::{parse_symbol_page, status_error, stockbit_code};
use super::types::{Bar, Fundamentals, Interval, Intraday, OrderBook, Period, Quote};
use super::{
CorporateActionProvider, FundamentalsProvider, HistoryProvider, IntradayProvider,
OrderBookProvider, QuoteProvider,
OrderBookProvider, QuoteProvider, ShareholderMovementProvider,
};
use crate::corporate::types::{ActionKind, CorporateAction};
use crate::error::IdxError;
use crate::movements::types::{MovementPage, MovementQuery};
use auth::SessionStore;
use exodus::Exodus;
@ -216,6 +218,16 @@ impl CorporateActionProvider for StockbitProvider {
}
}
impl ShareholderMovementProvider for StockbitProvider {
fn shareholder_movements(
&self,
query: &MovementQuery,
page: u32,
) -> Result<MovementPage, IdxError> {
self.require_session()?.shareholder_movements(query, page)
}
}
impl HistoryProvider for StockbitProvider {
fn history(
&self,

View file

@ -0,0 +1,328 @@
//! Shareholder movements from `GET /insider/company/majorholder`: reported
//! changes in a holder's stake, newest first, 50 rows a page.
//!
//! Two sources share the feed: IDX insider disclosures (directors,
//! commissioners and other insiders, any size; a trade price) and KSEI's
//! daily changes of holders at or above 5% (no price; Stockbit estimates
//! one). Each row (`data.movement[]`) carries `id` (the holder's id, not the
//! row's), `name`, `symbol`, `date` (`"25 Mar 26"`), `previous` / `current` /
//! `changes` (`value`: shares as `"+147,933"`, `percentage`: `"+0.0001"`),
//! `action_type` (`ACTION_TYPE_BUY`, ..._SELL, ..._TRANSFER, ..._CROSS,
//! ..._RIGHT_ISSUE, ..._PRIVATE_PLACEMENT, ..._TENDER_OFFER, ...),
//! `nationality`, `badges`, `price.raw.value`, `value.raw.value`,
//! `is_estimated_price`, `purpose` and `data_source.type`.
//!
//! Query parameters (all optional): `symbol`, `date_start` / `date_end`
//! (YYYY-MM-DD), `insider` (holder id), `action_type`, `source_type`, `page`
//! (from 1).
use chrono::NaiveDate;
use serde_json::Value;
use crate::error::IdxError;
use crate::movements::types::{
ActionFilter, MovementAction, MovementPage, MovementQuery, MovementSource, ShareholderMovement,
};
pub const PATH: &str = "/insider/company/majorholder";
/// Stockbit's `action_type` value for `filter`.
pub fn action_type(filter: ActionFilter) -> &'static str {
match filter {
ActionFilter::Buy => "ACTION_TYPE_BUY",
ActionFilter::Sell => "ACTION_TYPE_SELL",
ActionFilter::Transfer => "ACTION_TYPE_TRANSFER",
ActionFilter::Cross => "ACTION_TYPE_CROSS",
ActionFilter::CorporateAction => "ACTION_TYPE_CORPACTION",
}
}
/// Stockbit's `source_type` value for `source`.
pub fn source_type(source: MovementSource) -> &'static str {
match source {
MovementSource::Idx => "SOURCE_TYPE_IDX",
MovementSource::Ksei => "SOURCE_TYPE_KSEI",
}
}
/// The request path for `page` of `query`; `code` is the bare IDX code.
/// Every value is a date, a digit id, a code or a fixed enum name, so
/// nothing needs escaping.
pub fn request_path(query: &MovementQuery, code: Option<&str>, page: u32) -> String {
let mut path = format!("{PATH}?page={page}");
if let Some(code) = code {
path.push_str(&format!("&symbol={code}"));
}
if let Some(from) = query.from {
path.push_str(&format!("&date_start={from}"));
}
if let Some(to) = query.to {
path.push_str(&format!("&date_end={to}"));
}
if let Some(id) = &query.holder_id {
path.push_str(&format!("&insider={id}"));
}
if let Some(action) = query.action {
path.push_str(&format!("&action_type={}", action_type(action)));
}
if let Some(source) = query.source {
path.push_str(&format!("&source_type={}", source_type(source)));
}
path
}
/// One page of the feed. A row without a symbol, holder or readable date is
/// skipped; a body without `data` is a parse error.
pub fn parse_movements(body: &str) -> Result<MovementPage, IdxError> {
let value: Value = serde_json::from_str(body)
.map_err(|e| IdxError::ParseError(format!("Stockbit majorholder: {e}")))?;
let data = value
.get("data")
.filter(|data| data.is_object())
.ok_or_else(|| IdxError::ParseError("Stockbit majorholder: no data".to_string()))?;
let movements = data
.get("movement")
.and_then(Value::as_array)
.map(|rows| rows.iter().filter_map(parse_row).collect())
.unwrap_or_default();
Ok(MovementPage {
movements,
more: data
.get("is_more")
.and_then(Value::as_bool)
.unwrap_or(false),
})
}
fn parse_row(row: &Value) -> Option<ShareholderMovement> {
let symbol = text(row.get("symbol"))?.to_ascii_uppercase();
let holder = text(row.get("name"))?.to_string();
let date = NaiveDate::parse_from_str(text(row.get("date"))?, "%d %b %y").ok()?;
let shares = |key: &str| signed(row.get(key).and_then(|v| v.get("value"))).unwrap_or(0);
let bps = |key: &str| {
percent(row.get(key).and_then(|v| v.get("percentage")))
.map(|p| (p * 100.0).round() as i64)
.unwrap_or(0)
};
let raw = |key: &str| {
signed(
row.get(key)
.and_then(|v| v.get("raw"))
.and_then(|v| v.get("value")),
)
.filter(|n| *n != 0)
};
Some(ShareholderMovement {
symbol,
date,
holder,
holder_id: text(row.get("id")).unwrap_or_default().to_string(),
action: action(text(row.get("action_type")).unwrap_or_default()),
source: match text(row.get("data_source").and_then(|v| v.get("type"))) {
Some("SOURCE_TYPE_IDX") => Some(MovementSource::Idx),
Some("SOURCE_TYPE_KSEI") => Some(MovementSource::Ksei),
_ => None,
},
locality: match text(row.get("nationality")) {
Some("NATIONALITY_TYPE_LOCAL") => Some("Local".to_string()),
Some("NATIONALITY_TYPE_FOREIGN") => Some("Foreign".to_string()),
_ => None,
},
roles: row
.get("badges")
.and_then(Value::as_array)
.map(|badges| {
badges
.iter()
.filter_map(|b| text(Some(b)))
.map(role)
.collect()
})
.unwrap_or_default(),
shares_before: shares("previous"),
shares_after: shares("current"),
shares_change: shares("changes"),
percentage_before_bps: bps("previous"),
percentage_after_bps: bps("current"),
percentage_change_bps: bps("changes"),
price: raw("price"),
price_estimated: row
.get("is_estimated_price")
.and_then(Value::as_bool)
.unwrap_or(false),
value: raw("value"),
purpose: text(row.get("purpose"))
.filter(|p| *p != "-")
.map(str::to_string),
})
}
fn action(raw: &str) -> MovementAction {
match raw.strip_prefix("ACTION_TYPE_").unwrap_or(raw) {
"BUY" => MovementAction::Buy,
"SELL" => MovementAction::Sell,
"TRANSFER" => MovementAction::Transfer,
"CROSS" => MovementAction::Cross,
"RIGHT_ISSUE" => MovementAction::RightsIssue,
"PRIVATE_PLACEMENT" => MovementAction::PrivatePlacement,
"TENDER_OFFER" => MovementAction::TenderOffer,
"BONUS_STOCK" => MovementAction::BonusStock,
"DIVIDEND_STOCK" => MovementAction::StockDividend,
"DIVIDEND_CASH" => MovementAction::CashDividend,
_ => MovementAction::Other,
}
}
/// `SHAREHOLDER_BADGE_DIREKTUR` -> `director`; an unknown badge keeps its
/// own name, lowercased.
fn role(badge: &str) -> String {
match badge.strip_prefix("SHAREHOLDER_BADGE_").unwrap_or(badge) {
"DIREKTUR" => "director".to_string(),
"KOMISARIS" => "commissioner".to_string(),
other => other.to_ascii_lowercase(),
}
}
fn text(value: Option<&Value>) -> Option<&str> {
value
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
}
/// `"+147,933"`, `"-10,000,000"`, `"6982"` or a JSON number.
fn signed(value: Option<&Value>) -> Option<i64> {
match value? {
Value::Number(n) => n.as_i64().or_else(|| n.as_f64().map(|f| f.round() as i64)),
Value::String(s) => s.trim().replace(',', "").parse().ok(),
_ => None,
}
}
/// `"+0.0001"`, `"-0.16"`, `"54.94"`.
fn percent(value: Option<&Value>) -> Option<f64> {
let n = match value? {
Value::Number(n) => n.as_f64()?,
Value::String(s) => s.trim().replace(',', "").parse().ok()?,
_ => return None,
};
n.is_finite().then_some(n)
}
#[cfg(test)]
mod tests {
use super::*;
fn fixture(name: &str) -> String {
std::fs::read_to_string(format!(
"{}/tests/fixtures/stockbit_exodus_{name}.json",
env!("CARGO_MANIFEST_DIR")
))
.unwrap()
}
#[test]
fn insider_buy_reads_shares_price_and_roles() {
let page = parse_movements(&fixture("majorholder_bbca")).unwrap();
assert!(page.more);
let row = page
.movements
.iter()
.find(|m| m.holder == "HENDRA TANUMIHARDJA")
.expect("BBCA director row");
assert_eq!(row.symbol, "BBCA");
assert_eq!(row.date, NaiveDate::from_ymd_opt(2026, 3, 25).unwrap());
assert_eq!(row.action, MovementAction::Buy);
assert_eq!(row.source, Some(MovementSource::Idx));
assert_eq!(row.roles, ["director"]);
assert_eq!(
(row.shares_before, row.shares_after, row.shares_change),
(193_206, 341_139, 147_933)
);
// 0.0003% of BBCA rounds to 0 basis points; the shares stay exact.
assert_eq!(row.percentage_after_bps, 0);
assert_eq!(row.price, Some(6982));
assert_eq!(row.value, Some(1_032_868_206));
assert!(!row.price_estimated);
assert_eq!(row.locality.as_deref(), Some("Local"));
}
#[test]
fn ksei_sale_is_negative_with_an_estimated_price() {
let page = parse_movements(&fixture("majorholder")).unwrap();
let row = page
.movements
.iter()
.find(|m| m.holder == "RUDI R. SUTANTRA")
.expect("ATLA KSEI sale");
assert_eq!(row.action, MovementAction::Sell);
assert_eq!(row.source, Some(MovementSource::Ksei));
assert_eq!(row.holder_id, "1000004481");
assert_eq!(row.shares_change, -10_000_000);
assert_eq!(row.percentage_before_bps, 4081);
assert_eq!(row.percentage_change_bps, -16);
assert!(row.price_estimated);
assert!(row.roles.is_empty());
assert_eq!(row.purpose, None);
}
#[test]
fn unknown_labels_are_kept_not_dropped() {
let body = r#"{"data":{"is_more":false,"movement":[
{"id":"7","name":"X","symbol":"abcd","date":"02 Nov 26",
"action_type":"ACTION_TYPE_SOMETHING_NEW","badges":["SHAREHOLDER_BADGE_CEO"],
"data_source":{"type":"SOURCE_TYPE_NEW"},"purpose":"-",
"previous":{"value":"0","percentage":"0"},
"current":{"value":"1,000","percentage":"0.01"},
"changes":{"value":"+1,000","percentage":"+0.01"},
"price":{"raw":{"value":"0"}},"value":{"raw":{"value":"0"}}},
{"id":"8","name":"","symbol":"ABCD","date":"02 Nov 26"},
{"id":"9","name":"Y","symbol":"ABCD","date":"2026-11-02"}
]}}"#;
let page = parse_movements(body).unwrap();
assert!(!page.more);
assert_eq!(page.movements.len(), 1);
let row = &page.movements[0];
assert_eq!(row.symbol, "ABCD");
assert_eq!(row.action, MovementAction::Other);
assert_eq!(row.source, None);
assert_eq!(row.roles, ["ceo"]);
assert_eq!(
(row.price, row.value, row.purpose.as_deref()),
(None, None, None)
);
assert_eq!(row.percentage_after_bps, 1);
}
#[test]
fn empty_and_broken_bodies() {
let empty = parse_movements(r#"{"data":{"is_more":false,"movement":null}}"#).unwrap();
assert_eq!(empty, MovementPage::default());
assert!(parse_movements(r#"{"message":"unauthorized"}"#).is_err());
assert!(parse_movements("<html>").is_err());
}
#[test]
fn request_path_carries_every_filter() {
let mut query = MovementQuery::from_args(
None,
Some("2026-10-01"),
Some("2026-10-15"),
Some("14074"),
1,
)
.unwrap();
query.action = Some(ActionFilter::CorporateAction);
query.source = Some(MovementSource::Ksei);
assert_eq!(
request_path(&query, Some("BBCA"), 2),
"/insider/company/majorholder?page=2&symbol=BBCA&date_start=2026-10-01\
&date_end=2026-10-15&insider=14074&action_type=ACTION_TYPE_CORPACTION\
&source_type=SOURCE_TYPE_KSEI"
);
assert_eq!(
request_path(&MovementQuery::default(), None, 1),
"/insider/company/majorholder?page=1"
);
}
}

View file

@ -98,6 +98,10 @@ impl Idx {
crate::corporate::Corporate { idx: self }
}
pub fn movements(&self) -> crate::movements::Movements<'_> {
crate::movements::Movements { idx: self }
}
pub fn financial(&self) -> crate::financial::Financial<'_> {
crate::financial::Financial { idx: self }
}

View file

@ -16,6 +16,7 @@ pub mod flow;
#[cfg(feature = "ownership")]
pub mod investor;
pub mod market;
pub mod movements;
#[cfg(feature = "ownership")]
pub mod ownership;
pub mod text;

View file

@ -0,0 +1,124 @@
//! Shareholder movements from the user's Stockbit session: reported changes
//! in insiders' and major holders' stakes (IDX insider disclosures and KSEI's
//! 5% holder changes), one stock's or the market's, newest first. Each page
//! is 50 rows and one request (paced 1 s apart), cached for an hour.
//!
//! These are the reports as filed. Whether they predict anything is not
//! claimed here: share plans read as a cluster of buys at one price, and a
//! row appears days after the trade (see `docs/STOCKBIT.md`).
pub mod types;
use chrono::Utc;
use crate::api::{shareholder_movement_provider, stockbit};
use crate::client::{CachePolicy, CacheSpec, Fetched, Idx, cached_fetch};
use crate::error::IdxError;
use types::{MovementList, MovementQuery};
/// The feed gains rows through the day; an hour keeps a session's repeated
/// queries cheap without hiding a day's filings for long.
const TTL_SECS: u64 = 3600;
const BUCKET: &str = "stockbit-movements";
pub struct Movements<'a> {
pub(crate) idx: &'a Idx,
}
impl Movements<'_> {
/// Up to `query.pages` pages of the feed, newest first; `more` says
/// whether rows remain past them. The result is as old as its oldest page
/// and stale if any page is.
pub fn list(
&self,
query: &MovementQuery,
policy: CachePolicy,
) -> Result<Fetched<MovementList>, IdxError> {
let mut query = query.clone();
if let Some(symbol) = &query.symbol {
let (resolved, _) = self.idx.idx_code(symbol, "shareholder movements")?;
query.symbol = Some(resolved);
}
let provider = shareholder_movement_provider();
let subject = query
.symbol
.clone()
.unwrap_or_else(|| "shareholder movements".to_string());
let mut list = Fetched {
data: MovementList::default(),
source: stockbit::SOURCE,
fetched_at: Utc::now(),
stale: false,
};
for page in 1..=query.pages.max(1) {
let key = cache_key(&query, page);
let part = cached_fetch(
&self.idx.cache,
CacheSpec {
bucket: BUCKET,
key: &key,
ttl_secs: TTL_SECS,
subject: &subject,
source: stockbit::SOURCE,
},
policy,
|| provider.shareholder_movements(&query, page),
Ok,
)?;
list.fetched_at = list.fetched_at.min(part.fetched_at);
list.stale |= part.stale;
list.data.movements.extend(part.data.movements);
list.data.more = part.data.more;
if !part.data.more {
break;
}
}
Ok(list)
}
}
/// Every filter and the page, so no two queries share an entry.
fn cache_key(query: &MovementQuery, page: u32) -> String {
let opt = |value: Option<String>| value.unwrap_or_else(|| "-".to_string());
format!(
"{}:{}:{}:{}:{}:{}:p{page}",
query.symbol.as_deref().unwrap_or("market"),
opt(query.from.map(|d| d.to_string())),
opt(query.to.map(|d| d.to_string())),
query.holder_id.as_deref().unwrap_or("-"),
query.action.map(|a| a.as_str()).unwrap_or("-"),
query.source.map(|s| s.as_str()).unwrap_or("-"),
)
}
#[cfg(test)]
mod tests {
use super::*;
use types::{ActionFilter, MovementSource};
#[test]
fn cache_keys_differ_by_every_filter() {
let base = MovementQuery::from_args(None, None, None, None, 1).unwrap();
let mut keys = vec![cache_key(&base, 1), cache_key(&base, 2)];
let mut q = base.clone();
q.symbol = Some("BBCA.JK".to_string());
keys.push(cache_key(&q, 1));
let mut q = base.clone();
q.from = chrono::NaiveDate::from_ymd_opt(2026, 10, 1);
keys.push(cache_key(&q, 1));
let mut q = base.clone();
q.to = chrono::NaiveDate::from_ymd_opt(2026, 10, 1);
keys.push(cache_key(&q, 1));
let mut q = base.clone();
q.holder_id = Some("14074".to_string());
keys.push(cache_key(&q, 1));
let mut q = base.clone();
q.action = Some(ActionFilter::Sell);
keys.push(cache_key(&q, 1));
let mut q = base;
q.source = Some(MovementSource::Ksei);
keys.push(cache_key(&q, 1));
let unique: std::collections::HashSet<_> = keys.iter().collect();
assert_eq!(unique.len(), keys.len(), "{keys:?}");
}
}

View file

@ -0,0 +1,334 @@
use chrono::NaiveDate;
use serde::{Deserialize, Serialize};
use crate::error::IdxError;
/// What a holder's row records, as Stockbit labels it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MovementAction {
Buy,
Sell,
/// Shares moved between accounts or parties, not a market trade.
Transfer,
/// A crossing: a negotiated trade between two parties.
Cross,
RightsIssue,
PrivatePlacement,
TenderOffer,
BonusStock,
StockDividend,
CashDividend,
/// A label Stockbit added after this release.
Other,
}
impl MovementAction {
pub fn as_str(self) -> &'static str {
match self {
Self::Buy => "buy",
Self::Sell => "sell",
Self::Transfer => "transfer",
Self::Cross => "cross",
Self::RightsIssue => "rights_issue",
Self::PrivatePlacement => "private_placement",
Self::TenderOffer => "tender_offer",
Self::BonusStock => "bonus_stock",
Self::StockDividend => "stock_dividend",
Self::CashDividend => "cash_dividend",
Self::Other => "other",
}
}
/// Whether `filter` (Stockbit's `action_type`) selects this action.
pub fn matches(self, filter: ActionFilter) -> bool {
match filter {
ActionFilter::Buy => self == Self::Buy,
ActionFilter::Sell => self == Self::Sell,
ActionFilter::Transfer => self == Self::Transfer,
ActionFilter::Cross => self == Self::Cross,
ActionFilter::CorporateAction => matches!(
self,
Self::RightsIssue
| Self::PrivatePlacement
| Self::TenderOffer
| Self::BonusStock
| Self::StockDividend
| Self::CashDividend
),
}
}
}
/// The action filters Stockbit's feed takes (`action_type`). Corporate
/// action covers rights issues, private placements and the like.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "kebab-case")]
pub enum ActionFilter {
Buy,
Sell,
Transfer,
Cross,
#[cfg_attr(feature = "clap", value(name = "corporate-action"))]
CorporateAction,
}
impl ActionFilter {
pub const ALL: [Self; 5] = [
Self::Buy,
Self::Sell,
Self::Transfer,
Self::Cross,
Self::CorporateAction,
];
/// The CLI's name (`--action`), also used in MCP inputs.
pub fn as_str(self) -> &'static str {
match self {
Self::Buy => "buy",
Self::Sell => "sell",
Self::Transfer => "transfer",
Self::Cross => "cross",
Self::CorporateAction => "corporate-action",
}
}
}
impl std::str::FromStr for ActionFilter {
type Err = IdxError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let wanted = value.trim().to_ascii_lowercase().replace('_', "-");
Self::ALL
.into_iter()
.find(|filter| filter.as_str() == wanted)
.ok_or_else(|| {
IdxError::InvalidInput(format!(
"unknown action '{value}'; use one of: {}",
Self::ALL.map(Self::as_str).join(", ")
))
})
}
}
/// Who reported the change: IDX insider disclosures (directors,
/// commissioners and other insiders, any size), or KSEI's daily changes of
/// holders at or above 5%.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
#[serde(rename_all = "lowercase")]
pub enum MovementSource {
Idx,
Ksei,
}
impl MovementSource {
pub fn as_str(self) -> &'static str {
match self {
Self::Idx => "idx",
Self::Ksei => "ksei",
}
}
}
impl std::str::FromStr for MovementSource {
type Err = IdxError;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.trim().to_ascii_lowercase().as_str() {
"idx" => Ok(Self::Idx),
"ksei" => Ok(Self::Ksei),
_ => Err(IdxError::InvalidInput(format!(
"unknown source '{value}'; use idx or ksei"
))),
}
}
}
/// One reported change in a holder's stake. Share counts are exact;
/// percentages are of the company's shares, in basis points as Stockbit
/// rounds them, so a small insider's stake can read 0.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ShareholderMovement {
pub symbol: String,
/// The day of the change (the trade or the register date).
pub date: NaiveDate,
pub holder: String,
/// Stockbit's id for the holder; `--holder` takes it.
pub holder_id: String,
pub action: MovementAction,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub source: Option<MovementSource>,
/// `Local` or `Foreign`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub locality: Option<String>,
/// Insider roles at the company: `director`, `commissioner`.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub roles: Vec<String>,
pub shares_before: i64,
pub shares_after: i64,
/// Signed: negative for a sale.
pub shares_change: i64,
pub percentage_before_bps: i64,
pub percentage_after_bps: i64,
pub percentage_change_bps: i64,
/// Whole IDR per share.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub price: Option<i64>,
/// The price is Stockbit's estimate (KSEI rows report no price).
pub price_estimated: bool,
/// Whole IDR: shares changed times price.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub value: Option<i64>,
/// The stated purpose, free text (`Investasi`, `Divestasi`, ...).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub purpose: Option<String>,
}
/// One page of Stockbit's feed (50 rows), newest first.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct MovementPage {
pub movements: Vec<ShareholderMovement>,
/// Whether a further page exists.
pub more: bool,
}
/// Most pages one query reads (500 rows).
pub const MAX_PAGES: u32 = 10;
/// What to list. `symbol` is resolved (`BBCA.JK`) once it reaches a
/// provider; `None` is the whole market.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct MovementQuery {
pub symbol: Option<String>,
pub from: Option<NaiveDate>,
pub to: Option<NaiveDate>,
pub holder_id: Option<String>,
pub action: Option<ActionFilter>,
pub source: Option<MovementSource>,
/// Pages to read, 1 to `MAX_PAGES`.
pub pages: u32,
}
impl MovementQuery {
/// Validates user input: dates as YYYY-MM-DD with `from` not after
/// `to`, a numeric holder id, and 1 to `MAX_PAGES` pages.
pub fn from_args(
symbol: Option<&str>,
from: Option<&str>,
to: Option<&str>,
holder_id: Option<&str>,
pages: u32,
) -> Result<Self, IdxError> {
let parse = |name: &str, value: &str| {
NaiveDate::parse_from_str(value.trim(), "%Y-%m-%d").map_err(|_| {
IdxError::InvalidInput(format!("invalid {name} '{value}'; use YYYY-MM-DD"))
})
};
let from = from.map(|v| parse("from", v)).transpose()?;
let to = to.map(|v| parse("to", v)).transpose()?;
if let (Some(from), Some(to)) = (from, to)
&& to < from
{
return Err(IdxError::InvalidInput(format!(
"to ({to}) is before from ({from})"
)));
}
let holder_id = holder_id.map(str::trim).filter(|id| !id.is_empty());
if let Some(id) = holder_id
&& !id.bytes().all(|b| b.is_ascii_digit())
{
return Err(IdxError::InvalidInput(format!(
"holder '{id}' is not a holder id; ids are digits, shown in the HOLDER ID \
column and as holder_id in JSON"
)));
}
if !(1..=MAX_PAGES).contains(&pages) {
return Err(IdxError::InvalidInput(format!(
"pages must be 1 to {MAX_PAGES}"
)));
}
Ok(Self {
symbol: symbol
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string),
from,
to,
holder_id: holder_id.map(str::to_string),
action: None,
source: None,
pages,
})
}
/// Whether `movement` passes the query's filters (what Stockbit applies
/// on its side; the mock provider uses it).
pub fn admits(&self, movement: &ShareholderMovement) -> bool {
self.from.is_none_or(|from| movement.date >= from)
&& self.to.is_none_or(|to| movement.date <= to)
&& self
.holder_id
.as_ref()
.is_none_or(|id| &movement.holder_id == id)
&& self
.action
.is_none_or(|filter| movement.action.matches(filter))
&& self
.source
.is_none_or(|source| movement.source == Some(source))
}
}
/// The rows a query read, newest first.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct MovementList {
pub movements: Vec<ShareholderMovement>,
/// More rows exist past the pages read (raise `--pages`, or narrow the
/// dates).
pub more: bool,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn query_validates_dates_holder_and_pages() {
let query =
MovementQuery::from_args(Some(" bbca "), Some("2026-10-01"), None, Some("14074"), 2)
.unwrap();
assert_eq!(query.symbol.as_deref(), Some("bbca"));
assert_eq!(query.from, NaiveDate::from_ymd_opt(2026, 10, 1));
assert_eq!(query.holder_id.as_deref(), Some("14074"));
for (from, to, holder, pages) in [
(Some("01-10-2026"), None, None, 1),
(Some("2026-10-02"), Some("2026-10-01"), None, 1),
(None, None, Some("RUDI"), 1),
(None, None, Some("1&page=9"), 1),
(None, None, None, 0),
(None, None, None, MAX_PAGES + 1),
] {
assert!(
MovementQuery::from_args(None, from, to, holder, pages).is_err(),
"{from:?} {to:?} {holder:?} {pages}"
);
}
}
#[test]
fn action_filter_names_round_trip() {
for filter in ActionFilter::ALL {
assert_eq!(filter.as_str().parse::<ActionFilter>().unwrap(), filter);
}
assert_eq!(
"corporate_action".parse::<ActionFilter>().unwrap(),
ActionFilter::CorporateAction
);
assert!("dividend".parse::<ActionFilter>().is_err());
assert!(MovementAction::RightsIssue.matches(ActionFilter::CorporateAction));
assert!(!MovementAction::Transfer.matches(ActionFilter::CorporateAction));
}
}