Free tools Windows power users keep installed
One-click scans. No signup required.
iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
When a trading bot reads margin usage as zero, that value may mean “unknown,” “measured in the wrong units,” or “not represented by this account-mode field”—not that the account has no margin in use. Sam Hartley’s postmortem describes four interacting defects in a Python bot and a practical fix: derive usage from held positions and re-read it immediately before each new entry. The reported figures are Hartley’s account-specific results, not independently verified benchmarks or universal exchange behavior.
What failed in Hartley’s margin guard?
Hartley describes an hourly funding-rate scan that could open as many as three positions, with a rule intended to keep total margin below 50% of account equity. The guard read zero and allowed entries because four separate problems obscured the real exposure or let the bot act on stale information.
1. Missing state became a safe-looking zero
The code used state.get("margin_used") or 0.0. That expression maps both a missing value and a genuine numeric zero to 0.0. The guard therefore could not distinguish “usage is unknown” from “usage is confirmed to be zero.” For a safety limit, that is fail-open behavior: uncertainty permits the action instead of stopping it.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
2. Notional was compared with a margin limit
Some code paths reportedly stored position notional—position size multiplied by leverage—in margin_used, then compared it with a limit expressed as account margin. Notional and margin are different quantities. Because both can look like ordinary dollar figures, this kind of unit mismatch can produce plausible-looking results rather than an obvious error.
#1 Best Overall
- My Trading Journal for Stock Market, Forex, and Crypto: Precisely track and analyze every trade. This log book is essential for improving your trading performance and decision-making skills.
- Comprehensive Day Trading Planner: Record and review 80 guided trades with 8 review sections, perfect for traders aiming to refine their strategies and maximize profits.
- Customizable Trading Setup: Tailor your trading approach by documenting your setups, analyzing results, and adjusting strategies based on market conditions.
- For All Types of Traders: Whether you're trading stocks, forex, or crypto, My Trading Journal supports your unique trading style and helps you achieve consistent success.
- Premium Quality and Durability: Made with high-quality materials, this A5-sized journal is perfect for daily use and designed to withstand the rigors of active trading.
3. The remote fields did not reflect cross-margin usage in this account
Hartley says that, in the account’s cross-margin mode, collateral was tracked at the account level while the position-level position_margin and order_margin fields were zero for open positions. In a read-only check, Hartley reports zero in both fields across three positions alongside $460.97 in cross initial margin. This describes Hartley’s account and report only; it does not establish how another exchange, API, or account configuration behaves.
4. The guard was not refreshed during the entry loop
The check reportedly ran once during a sync before candidate processing. The loop could then open multiple positions without recalculating usage. Even a correct snapshot becomes stale as soon as the bot changes the account, so checking only before a sequence of actions does not enforce a changing limit across that sequence.
Rank #2
- FOR SERIOUS TRADERS: Track every entry, exit, position size, P&L, and setup with a structured layout designed for forex, stocks, options, futures, and crypto traders who want to identify what actually works in their strategy. NEUROSCIENCE-BASED DESIGN that encourages Growth Mindset and accountability
- TRADER PSYCHOLOGY FOCUS: Built on proven cognitive science principles, each page guides you through emotion tagging, bias recognition, and post-trade reflection to rewire reactive decision-making and build the disciplined mindset top-performing traders rely on
- COMPLETE 2026 TRADING LOG BOOK: Undated 12-month layout with performance summaries and goal tracking for day traders, swing traders, and long-term investors building consistent and serious results
- PERFORMANCE METRICS THAT DRIVE GROWTH: Dedicated sections for win rate, risk-reward ratio and strategy backtesting help you turn raw data into actionable insights, so every losing trade becomes a lesson and every winning trade becomes a repeatable system
- DIGITAL MONEY MANAGEMENT FILE INCLUDED : calculate your risk/reward ratio and win rate to find out whether you have a mathematical edge on the market, or not.
Why the guard needs both a reliable value and a fresh one
A numerical threshold is useful only if the value being compared is present, expressed in compatible units, and meaningful for the account mode. It also needs to describe the account at the moment the bot is about to act. A zero returned by a field is not self-explanatory: the code must know whether it means verified zero usage or a field that does not represent the quantity the guard needs.
- Presence: Missing or unparseable usage should have an explicit policy. For an entry-safety check, a conservative policy is to block new entries until usage can be established.
- Units: Keep the measured quantity and threshold aligned. Do not compare position notional with a margin cap.
- Semantics: Confirm what a remote field means in the specific account mode and configuration, rather than inferring account-wide usage from a position-level value.
- Freshness: Recalculate mutable usage immediately before every constrained action.
- Next-action exposure: Decide whether the proposed position’s expected margin must be included before approving it.
What changed in the described fix?
Hartley says the revised calculation derives usage from active positions as capital_at_entry / leverage, with a lower bound on leverage, and recalculates that figure from the live position list inside the candidate loop before each new entry. Exchange-reported figures remain diagnostic rather than serving as the guard’s primary input in the described change.
Rank #3
- BUILT FOR YOUR MARKET, FUTURES, STOCKS, FOREX, OPTIONS & CRYPTO: 4X is a mindset and process journal, not a strategy tool tied to one instrument. The plan, the trade log, the deep dive and the weekly review work the same whether you trade ES, EURUSD, SPY or BTC. Traders use it across all five markets every day.
- THE 2026 EDITION, REBUILT FROM TRADER FEEDBACK: Same trusted system, better in every way. An extra daily page for more room to log the session. Weekly reviews now grouped with each week's trades, so no more flipping back and forth. Crisp, darker print that's easy on the eyes after hours on a screen. A Quick-Start QR that scans straight to step-by-step instructions.
- NOT A NOTEBOOK, A COMPLETE 12-WEEK SYSTEM: Start with a one-time 9-part Trading Plan (your market, setups, risk rules and discipline checklist). Then twelve identical weeks: five Daily Logs, five Deep Dive trade pages, and a two-page Weekly Review. 189 guided pages, roughly 80 trades. Guided prompts walk you through every step. You never stare at a blank page.
- RATE YOUR EXECUTION, NOT YOUR RESULT: Your platform tracks the P&L. Nothing tracks the why. Log energy, sleep and mindset before the open; grade every trade A to F on whether you followed your plan, not on whether it won; then face the pattern every weekend with START / STOP / IMPROVE / CONTINUE. That review habit is the edge. You're 42% more likely to hit a goal you've written down.
- BUILT TO LAST, ARRIVES GIFT-READY: Vegan-leather hardcover, 100gsm bleed-resistant paper, two ribbon markers and an elastic closure band. Bound to lay flat so you're not fighting the spine while you write. 189 pages, 5.75" x 8.5", carries in a bag. Ships in a premium gift box: the gift every trader in your life actually wants.
The important structural change is the location of the check: it runs where an entry is about to happen, not just once before the loop. That lets the next check see positions opened earlier in the same scan. The underlying calculation still depends on the position data and formula matching the account’s actual margin model; the post does not establish that the formula applies to every trading system or account mode.
What did the reported runs show?
Hartley reports that five identical entry signals in one scan opened five positions under the old behavior, using $933.89 of margin—described as 83.5% of the account against a 50% cap. With the revised behavior, the reported checks saw $0, $186.78, $373.56, and $560.34; the bot then blocked the fourth entry. The resulting three positions reportedly used $560.34, described as 50.1% against the 50% cap. These are figures from Hartley’s account and runs, not independently validated measurements or general benchmarks.
Rank #4
How can a test show that the fix matters?
A test can pass while failing to detect the defect if it simply recreates the guard’s intended formula rather than exercising the code that actually decides whether to enter. Hartley describes replacing such a test with one that extracts the guard block from the source and runs patched and unpatched versions against the same scenarios, then asserts that their outputs differ.
For the reported missing-value scenario, Hartley says the unpatched behavior stopped after two positions, while the patched behavior opened three and then blocked; the control assertion checks that patched and unpatched outputs are not identical. This is the author’s test description, not a test independently executed for this article. The general lesson is to include a control that would fail if the patch made no observable difference in the scenario designed to expose the bug.
Best Value
What limitation remains in the revised guard?
Hartley notes that the revised check compares current usage with the cap but does not add the proposed position’s expected margin before approving entry. It can therefore overshoot the threshold by as much as one entry’s margin. In the reported example, three slots of about 16.7% each produce 50.1% against a 50% cap; a single 30% slot could produce a 10-percentage-point overshoot if approved when current usage is already at the cap.
To enforce a hard ceiling rather than a limit on current usage, the approval condition needs to account for the candidate as well as existing positions—for example, by comparing current usage plus the candidate’s expected margin with the cap. That requires a defensible estimate of the candidate’s margin and a consistent unit for both terms.
How to verify a margin field before relying on it
- Identify the exact account mode and configuration in use, including whether margin is isolated or cross-account.
- Check the exchange’s current documentation for the field’s definition and scope; confirm whether it reports position-level or account-level usage.
- Compare the field with a read-only account view and known open positions in that same mode. Treat a mismatch as unresolved, not as evidence of zero.
- Trace every value written to the guard input and confirm its units, source, and behavior when missing or invalid.
- Test the entry path with several sequential candidates, verifying that the guard observes the updated position list before each decision and applies the intended policy to unknown usage.
- If the limit is a strict maximum, include the next candidate’s expected margin in the approval calculation and test a candidate large enough to cross the cap.
Hartley’s account of the incident and implementation is available in the original postmortem.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

