577 Commits
Author SHA1 Message Date
Himanshu JangirandGitHub 925e831b1f Update funding options in FUNDING.yml 2026-09-14 10:55:46 +05:30
HimanshuJ16 00cc84366a fix: update star history links and image sources in README 2026-09-12 07:54:20 +05:30
HimanshuJ16 8fb1286169 docs: updates to README 2026-09-11 10:41:40 +05:30
HimanshuJ16 5fb2721acc docs: updates to README 2026-09-11 10:40:15 +05:30
HimanshuJ16 101ee44471 fix: update class names for consistent styling in Anatomy and Hero components 2026-09-07 14:00:05 +05:30
HimanshuJ16 eeca5b4797 fix: update max-width for GraphCanvas in catalog and domain-atlas components 2026-09-07 13:56:07 +05:30
Himanshu JangirandGitHub 27cf66a9cd Merge pull request #18 from HimanshuJ16/site-footer-author
site: footer colophon with author credit; fix theme toggle hydration
2026-09-07 13:48:59 +05:30
HimanshuJ16andClaude Fable 5.1 b3d710be47 site: footer colophon with author credit; fix theme toggle hydration
The footer's two disclaimers no longer sit in mismatched columns beside the licence;
they read as one measured block, with a final line crediting the author and the licence.
A new Author column links to GitHub, LinkedIn and the portfolio (lib/site.ts AUTHOR).

The theme toggle's accessible label depended on the resolved theme, which the server
cannot know, so every page hydrated with an attribute mismatch. It now reads
"Toggle theme" until mounted.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 13:47:29 +05:30
Himanshu JangirandGitHub 0f4f35243d Merge pull request #17 from HimanshuJ16/site-redesign
site: redesign the catalog site and prepare it for Vercel
2026-09-07 13:29:29 +05:30
HimanshuJ16andClaude Fable 5.1 26c257b901 site: redesign the catalog site and prepare it for Vercel
A full redesign of the statically exported Next.js catalog under site/, plus the
deployment metadata a public domain needs.

Experience tier (/, /skills, /domains, 404): the library's cross-reference graph
drawn on a Canvas 2D ring from a build-time asset (public/graph.json, checked against
the library at build time), an editorial "code that reads as correct" spread, a pinned
seven-section anatomy, a per-skill length spectrum, a marquee of real handoffs, smooth
scroll and a contextual cursor loaded after hydration.

Document tier (/skills/[slug], /domains/[slug]): the Markdown pipeline wraps each
level-2 section so the seven guaranteed sections are numbered structure; "When NOT to
Use" is styled as the boundary with handoff arrows; a contents rail with fixed positions;
handoff lists in both directions; code frames with a delegated copy control. No animation
library, no smooth scroll, CSS-only entrances.

System: one token set for both themes, sixteen domain hues through the .tint mechanism,
Geist / Geist Mono / Instrument Serif italic, a motion scale of two curves and four
durations. Entrances are CSS scroll-driven animations; motion (the library) is removed.
Hover-only link prefetch. A Star pill in the header with the live GitHub star count.

Deployment: canonical and OpenGraph URLs, sitemap.xml and robots.txt driven by
NEXT_PUBLIC_SITE_URL (default https://skills.himanshujangir.com); README documents the
Vercel project settings. CLAUDE.md no longer references the removed GitHub Pages workflow.

Measured (gzip, Next report): landing 123 kB First Load JS, document pages 109 kB, shared
103 kB; 501 skill pages, 16 domain pages, 520-URL sitemap.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 13:28:26 +05:30
Himanshu JangirandGitHub 25318e85a8 Merge pull request #11 from HimanshuJ16/dependabot/github_actions/actions/setup-python-7
chore(deps): bump actions/setup-python from 5 to 7
v3.0.0
2026-09-04 09:38:48 +05:30
Himanshu JangirandGitHub 9c779af5e0 Merge pull request #10 from HimanshuJ16/dependabot/github_actions/actions/checkout-7
chore(deps): bump actions/checkout from 4 to 7
2026-09-04 09:38:14 +05:30
HimanshuJ16 ed3d7d5361 fix: update dependabot configuration for clarity and accuracy in CI workflows 2026-09-04 09:35:48 +05:30
dependabot[bot]andGitHub 0992631a90 chore(deps): bump actions/setup-python from 5 to 7
Bumps [actions/setup-python](https://github.com/actions/setup-python) from 5 to 7.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/v5...v7)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-04 03:48:04 +00:00
dependabot[bot]andGitHub 79e690f5bf chore(deps): bump actions/checkout from 4 to 7
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 7.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-04 03:47:58 +00:00
HimanshuJ16 48bcc05379 Update Python version requirements across multiple skills to 3.10+
- Changed minimum Python version from 3.7+ or 3.9+ to 3.10+ in various skill documentation files to reflect the use of features introduced in Python 3.10.
- Updated prerequisites in skills related to structured logging, futures contract construction, systemd supervision, tail correlation, risk hedging, and more.
- Ensured consistency in Python version claims across all relevant skills to maintain compatibility with the latest library features.
- Added validation tests to enforce the new Python floor requirement and prevent claims below 3.10 in skill documentation.
2026-09-04 09:17:19 +05:30
HimanshuJ16 d466d60ea1 fix: update skill descriptions for clarity and accuracy across multiple files 2026-09-04 08:45:03 +05:30
HimanshuJ16 dde7936897 fix: remove a one-ULP dependency from a correlation threshold test
test_threshold_is_applied_before_rounding_under_ewma built a correlation of
exactly 0.70 and asserted that the >= 0.70 breach check fires on it. The
computed value came out as 0.7000000000000001 -- above the threshold by a
single ULP, 1.1e-16.

The weighted covariance behind it is a matrix product, so its last bit depends
on the BLAS build and the CPU's vectorisation rather than on anything the test
controls. That is why the suite passed on the 3.10 and 3.13 runners and failed
on the 3.12 one in the same CI run, and why it passed on all four interpreters
locally: the runners resolve different numpy builds.

Both cases now sit 4e-5 either side of the threshold while still rounding to
the same reported 0.7000. That is a stricter test of the property the name
claims -- a value that rounds to 0.7000 must breach or not breach on its raw
value, not its rounded one -- and the margin is ~11 orders of magnitude above
the float noise.

Swept the other 28 exact-boundary tests in the library: all are pure-Python
arithmetic on exactly-representable values, so they are bit-identical on every
machine. This was the only numpy-backed one.

Verified on CPython 3.10.20 (numpy 2.2.6), 3.11.4, 3.12.13 and 3.13.14
(numpy 2.5.2): every CI step passes on every version.
2026-09-04 01:47:26 +05:30
HimanshuJ16 11324c2885 fix: make two float-drift tests independent of the CPython sum() change
CPython 3.12 gave the built-in sum() Neumaier compensated summation for
floats. sum([0.1] * 10) is therefore 0.9999999999999999 up to Python 3.11 and
exactly 1.0 from 3.12 onward.

Two tests used that expression to manufacture a one-ULP divergence:
backtest-determinism-and-reproducibility asserted that two accumulation orders
disagree, and reproducible-ml-training-pipelines asserted that a last-ULP
difference survives canonical encoding. On 3.12 and 3.13 the drift vanished, so
both tests asserted against a value identical to 1.0 and failed -- while
silently no longer covering the divergence they exist to detect.

Both now accumulate in an explicit += loop. The loop stays naive on every
version, and it is also the operation a backtest accumulating a P&L series
actually performs, so the tests now demonstrate the real phenomenon rather than
an implementation detail of sum().

Verified on real CPython 3.10.20, 3.11.4, 3.12.13 and 3.13.14: validation, both
generated-file drift checks, the repository suite, all 501 skill suites
(20,289 tests), the agentskills.io spec check on 3.12/3.13, and the three
examples pass on every version.
2026-09-04 01:40:02 +05:30
HimanshuJ16 61aeccadb3 fix: restore Python 3.10 compatibility in three skills
The new 3.10 CI job exposed three genuine incompatibilities that the previous
single-version (3.11) pipeline could not see.

datetime.fromisoformat only accepts a trailing 'Z' from Python 3.11.
point-in-time-database-for-ml-training-data and
post-incident-forensics-for-suspected-key-compromise both advertise 'Z' as a
valid timestamp -- the latter uses it in its own error message -- yet passed
the raw string straight to fromisoformat, so on 3.10 each rejected the format
it documents. Both now normalise a trailing Z to +00:00 before parsing.

Python 3.10 and 3.11 also disagree on how a (str, Enum) member renders:
3.10 formats to the value but str()s to "Class.MEMBER", while 3.11 made both
"Class.MEMBER". DivergenceSeverity now pins __str__ to its value so str(),
format() and .value agree on every version, which is what a severity written
into a report needs.

Verified on real CPython 3.10.20 and 3.11.4: validation, both generated-file
drift checks, the repository suite, all 501 skill suites (20,289 tests) and
the three examples pass on both.
2026-09-04 01:30:38 +05:30
HimanshuJ16 327fc0dcd2 fix(ci): install skills-ref only on Python 3.11+ and call it as agentskills 2026-09-04 01:22:21 +05:30
HimanshuJ16 8527a5178b Refactor code structure for improved readability and maintainability 2026-09-04 01:16:48 +05:30
HimanshuJ16 5e1c2dbe53 fix: correct formatting of author name in plugin.json 2026-09-03 15:47:18 +05:30
HimanshuJ16andClaude Opus 5 3a12ae9050 test: rename digit-leading skill to isolate Cowork sync failure
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-03 15:36:45 +05:30
HimanshuJ16 94933e5a25 chore: remove outdated improve-skill protocol from CLAUDE.md 2026-09-03 15:33:15 +05:30
HimanshuJ16andClaude Opus 5 cd91e3ee7d chore: exclude .claude/ from the repository and plugin package
The plugin's source is "./", so everything tracked in this repo ships
inside the plugin package. Both reference marketplaces that sync
successfully on claude.ai (wshobson/agents,
mukul975/Anthropic-Cybersecurity-Skills) ship zero .claude/ files; this
repo shipped two. This removes the last content difference between them
while leaving the files on disk locally.

.claude-plugin/ is deliberately not ignored.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-03 15:25:24 +05:30
HimanshuJ16 079851ce6a @
fix: rename marketplace to avoid collision with plugin name

The marketplace and its sole plugin were both named "algo-trading-skills",
producing the identifier "algo-trading-skills@algo-trading-skills". Both
reference marketplaces that sync successfully on claude.ai (wshobson/agents,
mukul975/Anthropic-Cybersecurity-Skills) use distinct marketplace and plugin
names.

Renames the marketplace to "himanshuj16-algo-trading-skills", following the
owner-prefix convention. The plugin keeps the name "algo-trading-skills", so
the skill namespace prefix is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@
2026-09-03 15:21:12 +05:30
HimanshuJ16 2c9647f1bc feat: enhance marketplace.json with detailed plugin metadata 2026-09-03 15:15:54 +05:30
HimanshuJ16 3901419499 feat: add transfer pricing engine for multi-entity trading operations
- Implemented a new Python module for calculating intercompany pricing and profit splits based on OECD guidelines.
- Introduced classes for legal entities, intercompany transactions, DEMPE contributions, and transfer pricing settlements.
- Added methods for various transfer pricing methodologies including Cost Plus, CUP, TNMM, and Profit Split.
- Enhanced error handling for transfer pricing calculations and validations.
- Updated related documentation to reflect the new skill name for transfer pricing considerations.
2026-09-03 14:57:12 +05:30
HimanshuJ16 1882a206a6 Update generated_at timestamp in index.json 2026-09-03 14:37:33 +05:30
HimanshuJ16 64e8b01dc0 Refactor skill documentation and validation checks
- Removed unnecessary category sections from various skill markdown files.
- Updated paths in testing instructions to reflect new directory structure.
- Added "When NOT to Use" section to several skills for clarity.
- Enhanced skill validation to ensure proper structure of scripts and test suites.
- Improved error messages in validation to provide clearer guidance on issues.
- Added tests to ensure helper modules are correctly named and located.
- Updated validation logic to enforce canonical test command format in documentation.
2026-09-03 14:30:15 +05:30
HimanshuJ16andClaude Opus 5 bfa202c9f1 Fix flaky retry test in webhook-based-order-fill-notifications
The two "retry" deliveries in
test_position_is_correct_across_retries_replays_and_reordering were built
as fresh fill() calls, and fill() stamps time.time() on every call. That
made each retry a different payload, so the consumer correctly flagged it
DUPLICATE_CONTENT_MISMATCH and needs_reconcile came out 3 instead of 1.

Windows' ~15ms clock granularity returns the same time.time() for both
calls, so the digests matched and the test passed locally while failing on
the Linux CI runner. Reuse the original payload objects, which is what an
at-least-once redelivery actually is: the same bytes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-03 13:19:05 +05:30
HimanshuJ16 eb7108c285 Refactor and expand unit tests for zerodha-kite-postback-webhook-verification
- Enhanced test coverage for postback payload verification, including valid and invalid scenarios.
- Introduced detailed regression tests to prevent previously encountered defects.
- Improved handling of timestamp parsing and verification, ensuring correct timezone handling.
- Added tests for checksum computation and validation, including edge cases for empty and malformed checksums.
- Implemented idempotency tests to ensure duplicate postbacks are handled correctly.
- Refined error handling for malformed input and non-JSON bodies.
- Established a base class for shared test setup and verification logic.
2026-09-03 10:00:18 +05:30
HimanshuJ16 5249968b53 Add Richardson-extrapolated second central difference method for spot price in QuantoGreeksTest 2026-08-28 21:49:43 +05:30
HimanshuJ16 013a3b1b14 Enhance systemd service for trading bot with improved crash-loop handling and resource limits
- Added StartLimitIntervalSec and StartLimitBurst to prevent rapid restarts during broker outages.
- Configured WatchdogSec to ensure timely health checks and prevent false positives on bot health.
- Introduced MemoryHigh and MemoryMax settings to manage resource usage effectively.
- Retained existing restart behavior on failure while ensuring clean exits are handled appropriately.
2026-08-28 21:20:25 +05:30
HimanshuJ16 16799b46ae Refactor and expand unit tests for MarketRegimeCoverageEngine
- Added comprehensive tests for regime classification, coverage gates, and input validation.
- Introduced detailed checks for drawdown calculations and Sharpe ratio computations.
- Enhanced test structure to ensure stability and accuracy of regime classifications across multiple market conditions.
- Addressed previous regression issues and ensured proper handling of edge cases in input data.
2026-08-26 20:05:06 +05:30
HimanshuJ16 7e72405a9c Refactor and enhance unit tests for LeakageFreeHyperparameterTunerEngine
- Introduced new test cases for purged and embargoed index generation.
- Added validation checks for candidate pools and validation blocks.
- Improved test structure for better readability and maintainability.
- Ensured deterministic behavior in tuning orchestration and score calculations.
- Enhanced error handling for invalid configurations and non-finite scores.
- Updated expected max Sharpe calculations to align with statistical standards.
2026-08-25 08:28:09 +05:30
HimanshuJ16 a0fdc9eadf Enhance dynamic position sizing based on realized volatility
- Updated workflows documentation to clarify the procedure for preparing return series and estimating realized volatility.
- Improved the `realized_vol_sizer.py` script by adding detailed comments and enhancing the validation of return series.
- Introduced a new function `required_ewma_observations` to calculate the effective number of observations for EWMA.
- Enhanced the `VolatilityTargetingResult` class to include additional fields for better tracking of volatility scaling.
- Updated unit tests in `test_realized_vol_sizer.py` to cover new functionality and ensure robustness against edge cases.
- Added tests for handling non-finite returns, constant return series, and validation of constructor parameters.
2026-08-23 21:02:21 +05:30
HimanshuJ16 b680e6a449 Refactor and expand unit tests for custody vendor due diligence engine
- Introduced a new structure for tests, enhancing readability and maintainability.
- Added comprehensive test cases covering various scenarios including compliance, charter types, and insurance coverage.
- Implemented a factory function to create vendor profiles with customizable attributes.
- Ensured all tests validate the decision-making process of the custody vendor due diligence engine.
- Included checks for regulatory compliance, operational thresholds, and input validation.
- Updated logging configuration for better debugging during test execution.
2026-08-23 16:57:05 +05:30
HimanshuJ16 b540e442c1 Enhance cross-asset correlation regime detection:
- Update skill description to reflect K-normalized Frobenius distance calculation.
- Revise thresholds and regime classification logic for improved accuracy.
- Introduce validation checks for returns and correlation matrices to prevent data errors.
- Expand pre-flight checklist and standards documentation for clarity on calibration and data hygiene.
- Add comprehensive unit tests covering various regime scenarios and input validations.
- Improve code readability and maintainability with detailed docstrings and comments.
2026-08-23 08:54:17 +05:30
HimanshuJ16 3ed130dc07 Refactor corporate action adjuster tests: Enhance coverage for stock splits and dividends
- Introduced new test classes for split and dividend adjustments.
- Added comprehensive tests for various scenarios including 2-for-1 splits, reverse splits, and cash dividends.
- Implemented checks for edge cases such as non-trading days and duplicate bar dates.
- Ensured proper handling of corporate action errors and input validation.
- Verified that adjustments compound correctly across multiple events.
2026-08-22 13:02:48 +05:30
HimanshuJ16 269df51443 Refactor and expand unit tests for Bybit V5 API integration
- Introduced a comprehensive test suite for the Bybit V5 signing layer, including tests for HMAC-SHA256 signature generation.
- Added tests to validate the construction of signatures, ensuring correct parameter ordering and case sensitivity.
- Implemented tests to verify that signed strings match transmitted strings in requests.
- Enhanced query string rendering tests to handle various edge cases, including optional parameters and boolean values.
- Added validation tests for order body construction, ensuring proper handling of numeric values and order link IDs.
- Included tests for configuration validation, ensuring that invalid configurations are correctly rejected.
- Expanded acceptance window and server time offset tests to ensure accurate time synchronization.
- Added rate limit snapshot tests to validate header parsing and budget utilization logic.
2026-08-20 12:58:06 +05:30
HimanshuJ16 7eef45d155 Refactor margin interest tests for clarity and coverage
- Consolidated tier definitions into a helper function for reuse.
- Enhanced test cases for effective APR calculations, including edge cases for credit balances and NaN inputs.
- Added validation tests for rate schedule integrity, ensuring proper error handling for invalid configurations.
- Improved daily accrual tests to account for weekends and holidays, ensuring accurate interest calculations.
- Introduced tests for borrow collateral basis, verifying fee calculations against market values.
- Ensured robustness by rejecting invalid inputs and configurations across various test scenarios.
2026-08-14 22:44:30 +05:30
Himanshu JangirandGitHub 27fa8a95c3 Merge pull request #9 from HimanshuJ16/claude/blue-green-deployment-skill-pj9zbt
Expand documentation and test coverage across five core skills
2026-08-14 08:14:07 +05:30
Claude e063f6b494 fix(changelog-differ): resolve $ref and treat absence as a change
The differ read `type`, `properties` and `enum` directly off each schema. A `$ref`
schema carries none of those, so both sides presented as empty objects and every
check was skipped. Real broker specs (Binance, Coinbase, IBKR) describe payloads
almost entirely through references, which meant the tool reported "compatible"
for a release that deleted an entire response model.

Measured against the previous implementation, on one breaking edit at a time:

  $ref response model gutted        MISSED -> caught
  response 200 removed              MISSED -> caught
  response content-type removed     MISSED -> caught
  response field loses 'required'   MISSED -> caught
  new response enum value           MISSED -> caught
  requestBody removed               MISSED -> caught
  request content-type removed      MISSED -> caught
  optional param -> required        MISSED -> caught
  path-level parameters       AttributeError -> ok
  two empty documents               GREEN -> SchemaDiffError

Reference resolution:
- Follow local refs against the document each side came from, covering OpenAPI
  3.x `#/components/schemas/...` and Swagger 2.0 `#/definitions/...`, decoding
  ~0/~1 JSON Pointer escapes.
- Guard cycles: self-referential models (Order.parent -> Order) are ordinary and
  would otherwise recurse forever once refs resolve.
- Report external and dangling refs as UNRESOLVED_REF rather than skipping them
  silently; an unresolved ref means that region was never compared.

Absence is a change. Removed response status codes, removed request and response
content types, and a wholly removed requestBody were each invisible to loops
written as `if key in new: compare(...)`. Each now has a change type.

Direction-aware classification. The same edit breaks different parties depending
on which way it points:
- Request enums constrain what the client sends, so removing a value is breaking
  and adding one is not.
- Response enums constrain what the client handles, so adding a value is breaking
  — a new order status silently breaks an exhaustive state machine — while
  removing one is not.
- A request field moving into `required`, and a response field moving out of it,
  are both breaking. `old_required` was computed and never used.

Other correctness fixes:
- Only real HTTP methods are treated as operations. A Path Item Object legally
  carries `parameters`, `servers`, `summary`, `description` and `$ref`, and the
  differ raised AttributeError on a valid specification. Path-level parameters
  are now diffed as shared across operations.
- Normalize `type` before comparing: OpenAPI 3.1 permits type arrays where 3.0
  used `nullable: true`, so `["string"]` vs `"string"` was reported as a mutation
  that never happened and `["object","null"]` silently skipped property diffing.
- Reject documents that are not mappings or lack `paths`. An empty document from
  a failed download previously produced zero changes and a green gate.
- Added exit_code, breaking_changes and format_report so the tool can actually
  gate a build, which SKILL.md described but nothing implemented.

Documentation: corrected the unsupported "Swagger v2 or v3" and YAML claims to
match what the code does, documented the enum and requirement matrices with their
rationale, and reset the pre-ticked checklist that asserted verification the
defects above show had not happened.

Tests: 4 -> 43. Two of the previous four fixtures omitted `requestBody` and
`responses` entirely — real breaking changes that passed only because the differ
could not see them. Fixtures now deep-copy a baseline and mutate exactly one thing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UoqCTfNGdU91RQWxC3Jwyv
2026-08-14 01:19:03 +00:00
Claude add49e977c fix(broker-agnostic-adapter): stop reporting unclassifiable order statuses as live
normalize_status defaulted every unmapped broker status to OrderStatus.PENDING,
which asserts the order is live and working. Hand-written maps miss real terminal
statuses, and the shipped maps covered only four each. Verified against broker
documentation, the following all resolved to PENDING on the previous code:

  Zerodha LAPSED        -> order expired unexecuted (terminal)
  IBKR    ApiCancelled  -> cancelled via API (terminal)
  Alpaca  done_for_day  -> finished for the session
  Alpaca  replaced      -> superseded by another order
  IBKR    "FILLED"      -> FILLED, missed because IBKR alone used a
                           case-sensitive lookup while the others upper-cased

A strategy reading any of these as PENDING waits forever on a dead order or
re-sends one that already resolved. Unmapped statuses now return a new
OrderStatus.UNKNOWN and log at ERROR; UNKNOWN is neither live nor terminal
(OrderResult.is_terminal is False), so callers must re-query or reconcile.

Status maps completed from published documentation: Kite Connect's ~13 lifecycle
states, Alpaca's 12+ FIX-derived states, and IBKR's eight orderStatus values.
Lookup is case-insensitive and whitespace-trimmed for all adapters.

Factory safety:
- The registry no longer ships simulated adapters bound to production broker
  names. create("zerodha") previously returned MockZerodhaAdapter, which
  fabricates fills, so a system resolving config["broker"] would trade against
  invented prices with no error anywhere. The registry now starts empty; call
  register_simulated_adapters() to opt in for offline work.
- register() rejects classes that do not implement BaseBrokerAdapter, so
  mis-wiring fails at startup rather than on the first order.
- Added reset() for test isolation, since the registry is process-wide state.

Request validation, hoisted to the base class so a new adapter cannot omit it:
- LIMIT orders without a price were accepted and returned a fabricated fill
  price of 100.50. `if request.price` also treated Decimal("0") as absent, so a
  zero limit price was silently replaced. Both now raise.
- MARKET orders carrying a price, STOP without stop_price, and STOP_LIMIT
  missing either are rejected.
- float quantities and prices are rejected rather than coerced. A float passed
  the old checks and propagated into OrderResult, defeating the module's stated
  Decimal guarantee and surfacing later as a TypeError against a Decimal. int is
  widened losslessly.
- Decimal("NaN") previously raised decimal.InvalidOperation straight through the
  adapter boundary, the exact leaky abstraction this skill warns against;
  non-finite values now raise OrderExecutionError.

OrderResult gained client_order_id, echoed by every adapter. Without it a caller
cannot correlate a response to its request, which retry-safe submission requires.
cancel_order's contract is documented as a cancellation request whose outcome
must be confirmed via get_order_status, not as a cancellation.

Documentation: status tables in standards.md now list each broker's documented
enumeration with sources rather than the subset the code mapped, and the Upstox
row is marked unverified rather than assumed from the Zerodha pattern.

Tests: 8 -> 36. The previous suite asserted the fail-open behaviour
(normalize_status("unknown_status") == PENDING).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UoqCTfNGdU91RQWxC3Jwyv
2026-08-13 17:19:26 +00:00
Claude b1b375e8b0 fix(margin-call-handling): fail closed on unusable data and escalate on the broker's own cushion
The engine graded accounts solely on maintenance_margin / net_liquidation_value
and never read excess_liquidity or available_funds, though both were fields on
the snapshot. Interactive Brokers defines Excess Liquidity as Equity with Loan
Value minus maintenance margin, and ELV is not NLV: it excludes value that does
not count toward margin equity. An account holding non-marginable assets can
therefore show a 70% house ratio while the broker's cushion is already negative
and positions are being liquidated.

Reproduced against the previous code: with NLV 100k, maintenance margin 70k and
excess liquidity -10k, evaluate_margin_health returned NORMAL and
guard_new_order approved a new order.

Separately, every threshold comparison against NaN evaluates False, so a NaN
ratio fell through the breach, critical and warning tests into the healthy
branch. A NaN net liquidation value, a NaN maintenance margin, and a NaN
margin_impact each reported a healthy account or approved an order.

Risk evaluation:
- Escalate to BREACH whenever excess_liquidity is negative, regardless of the
  house ratio, and expose broker_deficiency on the evaluation.
- Validate every snapshot, position and order input is finite; raise the new
  MarginDataError rather than grading an account the engine cannot measure.
- Stop flooring NLV at 0.01. At non-positive equity the ratio is undefined, so
  report infinity and a distinct HALT_AND_ESCALATE action; the deficit is now
  computed from the true NLV, which the floor understated by exactly the amount
  of negative equity (150,000 reported as 99,999.99).
- Validate threshold configuration: unordered thresholds silently made the
  WARNING tier unreachable, and a de-leverage target at or above the breach
  threshold aimed the recovery at a state that is itself a breach.

Order gating:
- Add an initial-margin gate. Positions are opened against initial margin, which
  Reg T sets at 50% for a long margin equity purchase against FINRA 4210's 25%
  maintenance minimum, so a maintenance-only projection is the weaker constraint.
  guard_new_order now accepts initial_margin_impact and tests it against
  available_funds.
- is_deleveraging=True returned True unconditionally, so an order with a
  +999,999 margin impact bypassed every gate. A de-leveraging order must reduce
  margin; a positive impact is now refused.

De-leveraging:
- Validate positions and make NLV handling consistent with evaluate_margin_health;
  non-positive equity now targets a full unwind explicitly.
- average_daily_volume no longer defaults to 1,000,000. It caps how much of a
  position the plan will sell, and a default asserts liquidity the position may
  not have.
- Document that the linear per-position margin model does not hold under
  Portfolio Margin or SPAN, where closing a hedge leg can increase total margin.

Documentation:
- standards.md cited reqSecDefOptParams as IBKR's pre-trade margin check. That
  call returns option chain metadata; the mechanism is Order.whatIf=true, whose
  OrderState returns initMarginChange and maintMarginChange. Corrected, with the
  error called out.
- Correct the IBKR warning trigger (Equity with Loan Value <= maintenance margin
  x 110%, not excess liquidity below 10% of NLV) and the Zerodha row, whose real
  policy is MTM-loss and time based, including the ~15:20 IST intraday square-off
  and exchange shortfall penalties, not margin-utilisation based.
- Qualify the portfolio margin stress range: -8%/+6% high-cap broad-based, +/-10%
  other broad-based, +/-15% sector and individual equity.
- Note that IBKR does not make margin calls and liquidates without notice, so
  BREACH is a state to avoid reaching rather than one to plan to act from.
- workflows.md taught the 0.01 NLV floor as procedure; corrected.

Tests: 5 -> 29, with regression coverage for each defect above and exact-boundary
tier checks. Thresholds remain house policy, not regulation, and are labelled so.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UoqCTfNGdU91RQWxC3Jwyv
2026-08-13 17:08:19 +00:00
Claude ffee373e42 fix(borsa-istanbul): treat cancel as a request, deduplicate execution reports, reject overfills
cancel_order() set the order to CANCELED the instant the Order Cancel Request
(MsgType=F) was sent. FIX 5.0 SP2 is explicit that MsgType=F only *requests*
cancellation of the remaining quantity; the order stays live until the venue
answers with an ExecutionReport carrying ExecType=Canceled, or refuses with an
Order Cancel Reject (MsgType=9). Because the execution-report handler ignored
orders already in a terminal state, any fill landing in the cancel race window
was silently discarded, leaving local position state short of the venue's.

Reproduced against the previous code: a cancel request followed by a genuine
80-lot fill left filled_quantity at 0.

Order lifecycle:
- Add PENDING_CANCEL (OrdStatus=6). cancel_order() now sends the request and
  leaves the order working and fillable; confirm_cancel() applies ExecType=4 and
  reject_cancel() applies MsgType=9, returning the order to NEW or
  PARTIALLY_FILLED according to its fill state. confirm_cancel() also accepts
  unsolicited venue cancels.
- Refuse a duplicate cancel request rather than sending a second one.

Execution reports:
- Deduplicate on (ClOrdID, ExecID). Resend Request recovery replays application
  messages, and the previous handler double-counted every replayed fill. Keyed
  by the pair, not ExecID alone, so per-order ExecIDs cannot cross-suppress.
- Reject reports that would take cumulative quantity past order quantity and log
  at ERROR instead of absorbing the overfill into the average price.
- Validate filled_qty and exec_price are finite and positive.
- Compare against order quantity with a tolerance so float accumulation across
  partial fills cannot strand a fully-filled order in PARTIALLY_FILLED.

Order entry:
- Reject duplicate ClOrdID; the previous code silently overwrote a working
  order's record and discarded its fills.
- Reject NaN quantity, which passed the previous `quantity <= 0` check because
  NaN fails every comparison.
- Reject non-positive limit prices, Price on an OrdType=Market order, empty
  symbols, and resubmission of an already-used FIXOrder object.
- Validate port range and CompIDs on connect().
- Timestamps are timezone-aware UTC; datetime.utcnow() is naive and deprecated.
- Add TimeInForce (tag 59), which the checklist already claimed was validated.

Documentation:
- SKILL.md stated the module handled DMA/HFT session management. It has no
  network I/O, no FIX encoding and no sequence-number persistence. Add an
  explicit scope boundary and a When NOT to Use section so it cannot be mistaken
  for a gateway.
- Replace three Related Skills references to skills that do not exist; they
  evaded validation because they were not backticked.
- Correct frontmatter to the documented taxonomy and the repository's licence.
- Extend workflows.md with the cancel request/confirm/reject sequence and ExecID
  deduplication; extend the checklist to match.

references/standards.md is unchanged: its FIX 5.0 SP2 and `.E` symbology claims
were verified correct against Borsa Istanbul's published protocol documentation.

Tests: 7 -> 37, including regression tests for each defect above.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UoqCTfNGdU91RQWxC3Jwyv
2026-08-13 16:54:39 +00:00
Claude af9ba67f99 fix(blue-green-deployment): correct contradictory rollback guidance, complete SKILL.md, harden audit trail
references/standards.md instructed the reader that "Rollback is a simple pointer
swap" and mandated reversion in under 1ms. That is the exact defect the
implementation's primary safeguard exists to prevent: rollback reconciles state
backwards from the live slot and refuses when reconciliation fails. It also
justified state continuity with "Blue remains actively updating its state from
market data" -- market data does not carry the live instance's fills.

SKILL.md carried placeholder text ("Documentation for When to Use.") in six of
the seven required sections; the validator only checks that headers exist, so
this passed CI.

Documentation:
- Rewrite SKILL.md with real When to Use / When NOT to Use, workflow decision
  points, and specific pitfalls, following sibling deployment-ops conventions.
- Rewrite standards.md: correct the rollback and hot-standby claims, separate
  regulatory obligations from engineering practice, and scope each to its
  jurisdiction. Add verified RTS 6 Art. 8 (controlled deployment) and Art. 11
  (management of material changes), the two most on-point articles, which were
  absent; add SEC Rule 15c3-5 pre-trade control placement.
- Extend workflows.md with the slot lifecycle, cutover-refusal classification
  (a failed state sync is not retryable), and the kill-switch escalation.
- Extend checklist.md with authoriser sign-off, rollback-viability and audit
  export gates.
- Fix frontmatter: subdomain general -> deployment-ops, meaningful tags,
  discovery-oriented description; regenerate index.json.

Implementation:
- Add is_authorised_to_route(); the docstring told the execution layer to
  consult the deployer before every submission but exposed no API for it,
  leaving integrators to read mutable slot state outside the lock.
- Record an INITIALIZE baseline; initial_version was documented as recorded in
  deployment_history but nothing was written at construction.
- Flag forced rollbacks. The [FORCED] marker was gated on force and not
  sync_ok, so overriding the target-eligibility guard while the sync happened
  to succeed was recorded as an ordinary successful rollback.
- Close an ABA hole in the post-warmup guard: identifying the slot by
  (state, version) let a decommission plus same-version redeploy during warmup
  receive the previous attempt's stale health verdict. Use a generation token.
- Accept authorised_by on decommission_standby().

Tests: 25 -> 34. The two regression tests were verified to fail against the
pre-fix code and pass after. All API changes are additive.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UoqCTfNGdU91RQWxC3Jwyv
2026-08-13 16:42:35 +00:00
HimanshuJ16 746a971eef feat: Enhance Blue-Green Deployer with robust state management and audit trail
- Added detailed docstrings to classes and methods for better understanding.
- Introduced new states and safeguards for deployment and rollback processes.
- Improved error handling for health checks and state synchronization.
- Implemented comprehensive unit tests covering various scenarios including health check failures, state synchronization issues, and concurrency.
- Enhanced audit trail to record authorisation details for each action.
- Ensured atomicity during deployment and cutover operations to prevent race conditions.
- Refined rollback mechanism to ensure safe transitions and prevent routing to stale states.
2026-08-13 17:56:01 +05:30