Install
$ agentstack add skill-himanshuj16-algo-trading-skills-broker-account-margin-call-handling ✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ✓ Network access No
- ✓ Filesystem access No
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Verified badge
Passed review? Show it. Paste this badge into your README, it links to the public security report.
Reliability & compatibility
Declared compatibility
Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.
We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.
How agent discovery & health will work →About
When to Use
Invoke this whenever an algorithmic trading bot operates on a margin account (Reg T, Portfolio Margin, or futures margin). When adverse market moves push maintenance margin requirements toward or past account equity, brokers liquidate positions at market prices, and they choose which ones. Acting first — cancelling resting orders, blocking new leverage, and unwinding on your own schedule with liquidity limits — is the difference between a controlled reduction and a forced one.
Use it to run three gates: a tiered house ratio as early warning, a broker-cushion check that catches deficiency the house ratio can miss, and a pre-trade veto on orders that would consume margin you do not have.
When NOT to Use
- As a substitute for the broker's own numbers. The engine grades a snapshot you
supply. If your feed is stale, the grade is stale. Poll excess_liquidity and available_funds from the broker; do not derive them from NLV.
- As a guaranteed way to beat the broker to liquidation. IBKR does not make margin
calls — it liquidates in real time, without prior notice, and may do so without the account ever displaying a margin warning. If you are already at BREACH you may have no window at all. The pre-breach tiers are where this skill earns its keep.
- To size liquidations under Portfolio Margin or SPAN without re-pricing. The planner
assumes margin is separable per position. Under portfolio-level regimes, closing one leg of a hedge can raise total margin — see Workflow step 5.
- On a cash account, or for exchange margin-shortfall penalty accounting, which is a
separate settlement-side concern.
Prerequisites
- Broker real-time account data:
net_liquidation_value,initial_margin,
maintenance_margin, and critically excess_liquidity and available_funds.
- A pre-trade margin impact source. Estimating it is the weak link — get it from the
broker. At IBKR that is an Order.whatIf = true submission, whose OrderState returns initMarginChange and maintMarginChange.
- An open-order cancellation interface.
- Per-position
average_daily_volume. It is a required field, not an optional one: it
caps how much of a position the plan will sell, and a guessed value defeats the cap.
- An execution path for liquidation slices (TWAP/VWAP or equivalent).
Workflow
- Evaluate account health with
evaluate_margin_health(snapshot). It escalates on
the worse of two signals:
- the house ratio $M = \text{maintenance margin} / \text{NLV}$, against your configured
tiers, and
- **
excess_liquidity Full step-by-step procedure with broker-specific detail: seereferences/workflows.md`.
> Broker triggers, cushion definitions and regulatory reference points: see references/standards.md. > Printable pre-flight checklist: see assets/checklist.md.
Common Pitfalls
- Trusting the house ratio alone.
maintenance_margin / NLVuses NLV; the broker's
cushion uses Equity with Loan Value, which excludes non-margin-eligible value and can be much lower. An account can read 70% and healthy while excess_liquidity is already negative and liquidation is underway.
- Letting NaN through a threshold chain. Every comparison against NaN is False, so a
NaN ratio falls past >= breach, >= critical and >= warning into the healthy branch. A broken feed must fail closed.
- Checking new orders against maintenance margin. Positions are opened against initial
margin, which is roughly double under Reg T.
- Flooring NLV to avoid dividing by zero. It manufactures a finite ratio from an
undefined one and, if the deficit is computed from the floored value, understates the deficit by exactly the amount of negative equity.
- Exempting "de-leveraging" orders without checking they de-leverage. A bypass flag
that is trusted unconditionally lets a margin-increasing order through every gate.
- Unordered thresholds. Setting warning above critical makes the WARNING tier
unreachable — the account jumps straight to CRITICAL and the early gate never fires.
- Passive waiting for broker liquidation, taking market-order slippage on positions
someone else chose.
- Illiquidity spirals: dumping an illiquid asset at once, crushing the bid, lowering
NLV, and triggering a secondary call.
- Ignoring tail risk: unwinding long equity first while naked short options stay open
through a volatility spike.
- Ignoring the clock. Where the broker force-closes intraday products on a schedule
(Zerodha squares off MIS positions around 15:20 IST), being margin-healthy is not enough.
Verification
- Run the unit suite and confirm every test passes:
python -m unittest discover -s skills/broker-account-margin-call-handling/scripts
- Feed a snapshot with a healthy ratio but negative
excess_liquidityand confirm the
state is MARGIN_CALL_BREACH with broker_deficiency set — this is the failure mode most likely to be missed in production.
- Feed NaN in each snapshot field in turn and confirm
MarginDataErrorevery time; a
NORMAL result from any of them is a fail-open bug.
- Check each tier at its exact boundary (85.0%, 95.0%, 100.0%), not just mid-band.
- Submit a snapshot with $M = 0.88$ and confirm
WARNING. - Submit an order whose
initial_margin_impactexceedsavailable_fundsand confirm the
veto, even when the maintenance projection alone would have passed.
- Replay a historical drawdown that actually breached, and confirm the tiers would have
fired early enough to matter given your broker's liquidation behaviour.
Related Skills
kill-switch-and-drawdown-circuit-breakersoptions-margin-span-calculation-globalcorrelation-aware-exposure-limitsmargin-utilization-circuit-breaker
Source & license
This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: HimanshuJ16
- Source: HimanshuJ16/Algo-Trading-Skills
- License: Apache-2.0
- Homepage: https://skills.himanshujangir.com
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet, be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.