Skip to content

fix: order / close / cancel safety (12 fixes) - #97

Merged
Hiksang merged 14 commits into
mainfrom
fix/order-close-safety
Nov 15, 2026
Merged

Hiksang merged 14 commits into
mainfrom
fix/order-close-safety

Conversation

@Hiksang

@Hiksang Hiksang commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

What does this PR do?

Fixes cases where a close, cancel or risk check reported success while orders or a position stayed open. Each commit fixes one bug.

Bug What happened Now
Partial close residual The residual was floored to the decimals the size printed. HL / Lighter / Aster print 10.0 as "10", so a 0.7 residual became 0: logged as closed, nothing quarantined Floored to the market lot step. An unknown lot is reported as a residual with a note
Legacy cancelAllOrders on Ondo / Arcus / QFEX / TxFlow / RISEx Returned normally with failed or unproven cancels, so bots, grids and plans treated it as done and could restart on live orders Throws ORDER_PARTIAL / ORDER_REJECTED / ORDER_PENDING with the per-order outcome
Lighter read-only adapter getOpenOrders returned [], so cancel-all, cancel <symbol> and flatten exited 0 with nothing cancelled Refuses with NO_SIGNER_AVAILABLE / AGENT_EXPIRED. Views that read orders with balances (portfolio, MCP, stream, dashboard) show openOrders: null with the reason
Risk gate An Aster mark of "N/A" made exposure NaN, and a mark of "0" / "" / null counted as $0, so orders passed the limits PRICE_STALE; trade check fails risk_limits for an opening order
HL HIP-4 outcome orders Listed as perp orders; cancel-all / flatten failed on them Left out of perp open orders; outcome commands read them
Client-side TWAP Slices were off the lot grid (Aster refused every one), and a refused run exited 0 Slices on the lot grid; a refused run is an error
--dex <dex> trade cancel <symbol> Cancelled 0 orders and reported success Cancels that market's orders
QFEX flatten Stopped at the first orphan cancel that threw Tries every orphan and reports each result
Lighter /sendTx 52001 / 52002 / 62007 Reported as outcome unknown (quarantine) Definite rejections; 21507 / 21508 are MARGIN_INSUFFICIENT
RISEx cancel-all One failed read marked the whole market failed (and listed orders twice); a failed permit lost the other markets' results Each order settled once; a failed permit fails only its market
RISEx reduce-only markets Refused market / IOC / FOK orders too Only resting non-reduce-only orders are refused (venue docs, E0706)
scale-tp / scale-in --levels "x50" parsed as NaN and passed the sum check Each percent is validated (INVALID_PARAMS)

JSON contract changes: listed in the CHANGELOG under "JSON contract changes" with migration notes. The ones most likely to affect scripts:

  • Close sizes (closed / residual) are plain decimals without padding: compare as numbers.
  • A refused TWAP is ok: false.
  • Lighter open orders on a read-only adapter fail instead of returning []; portfolio openOrders is number | null with openOrdersError.
  • risk status / risk check fail with PRICE_STALE when a position's notional is unknown.

Behaviour change to note: a plan [cancel_all, close_position] on Ondo / Arcus / QFEX / TxFlow / RISEx now stops before the close when the cancel fails or is unproven (default onFailure: "abort"). To close anyway, set "onFailure": "skip" on the cancel_all step. This is intended and documented in the CHANGELOG.

Size: 13 commits, 45 files, +1013 / −168. The owner chose to keep this group as one PR.

Checklist

  • pnpm test passes (338 files / 7317 tests)
  • tsc --noEmit and typecheck:test pass
  • No secrets, API keys, or private keys included
  • Breaking change? See JSON contract changes

Testing standard (docs/TESTING.md §7)

  • One behaviour per test; no test.skip / .only
  • New tests fail before their fix (the risk mark-"0" test was checked against the pre-fix code)
  • Write paths changed: close, cancel and TWAP. Unit-tested with mocked venues only

Two independent reviews. The second found 1 HIGH (a mark of "0" bypassed the risk gate) and 2 LOW; all three are fixed here. The fix for the HIGH item has not had a third review.

Live ↔ Unit Test Cross-Validation

Not run against live venues or testnets. Close, cancel-all and TWAP should get a testnet QA pass before release. During the work, the integration suite was run once by mistake against public mainnet read APIs (no signing, no orders).

Merge conflicts to expect

🤖 Generated with Claude Code

Hiksang and others added 13 commits November 12, 2026 01:37
…he size's printed decimals

closePerpVerified floored the residual of a partial close to the decimals of the size string
(trade close / close-all / flatten / reduce and MCP trade_close passed the same value). HL /
Lighter / Aster print a 10.0 position as "10": a 0.7 residual floored to 0, the close was logged
as a success and nothing was quarantined while 0.7 stayed open.

The decimals now come from the market lot (stepSize, else lotStepOf), read only once a residual
exists: a full close sends no extra request and needs no market list (RISEx leaves a mark "0"
market out of it, Ondo lists LISTED markets). An unknown lot is reported as residual + note.
The `decimals` option is removed: every caller derived it from a printed size (plan rollback,
grid --close-on-stop, the arb auto / funding-arb / funding-arb-v2 / funding-auto entry
rollbacks), so a 0-decimal entry still floored 0.7 to 0. trimFirstLegToHedge floors the excess
to the lot as well (10 vs 9.3 trims 0.7; an unknown lot throws → quarantine). The residual is
floored with floorToStep (a "0.5" lot sends 0.5, not 0.7), and closed / residual are rounded to
the lot (the size's decimals on a full close), so no float noise ("6.700000000186") is printed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…cancel failed or is unproven

Ondo / Arcus / QFEX / TxFlow / RISEx returned cancelAllV2's result from the legacy
cancelAllOrders even with failed / pending entries. Its callers (bot engine cleanup and restart,
grid stop, plan cancel_all, funding-arb cleanup) read only a throw as a failure, so a refused or
unproven cancel was reported done and a strategy could restart on top of live orders.

requireAllCancelled (trading-v2.ts) applies the HL / Lighter / Pacifica contract: any failed or
pending cancel is one error carrying the per-order outcome (ORDER_PARTIAL / ORDER_REJECTED /
ORDER_PENDING).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…n, never an empty list

getOpenOrders returned [] when the adapter was read-only (no agent API key, an expired agent,
no account index): /accountActiveOrders needs an auth token signed with the API key, so the list
is unknown. trade cancel-all, cancel <symbol> and flatten's cancel step exited 0 with nothing
cancelled. The read now refuses through ensureSigner (NO_SIGNER_AVAILABLE / AGENT_EXPIRED).

account orders and MCP get_open_orders report that error instead of "No open orders". The views
that read orders together with balance and positions (portfolio, MCP portfolio, perp stream, the
dashboard REST poll) use openOrdersForView, which turns only NO_SIGNER_AVAILABLE / AGENT_EXPIRED
into orders null + reason: the venue keeps its balance and positions, openOrders is null with
openOrdersError, MCP totalOpenOrders counts the known venues and lists openOrdersUnknown, and the
stream skips its order diff (no false cancel events). A portfolio venue that could not be read
at all reports openOrders null with the error (was 0). Cancel paths still fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…puted

Aster reports an unknown mark as "N/A" (positionRisk read failed). assessRisk multiplied it
into a NaN total exposure, every "> limit" comparison was false, and enforceOrderRisk let the
order through. A mark of "0" / "" / null (RISEx "0" = none, passed through as the position mark) is
finite and counted the position as $0 exposure. assessRisk now throws PRICE_STALE for both, naming the position (risk status / risk check
fail the same way instead of reporting NaN metrics). trade-validator caught the throw as "Risk
check skipped (no limits configured)", passed: it now fails risk_limits with the reason for an
opening order and passes with a warning for a reduce-only one (the gate exempts reduce-only).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
frontendOpenOrders lists outcome orders (coin "#<encoding>") with the perp orders, and
hlIsSpotCoin excluded only "@" / "/" coins: account orders showed them as perps, and cancel-all /
flatten tried to cancel them through the perp asset map (SYMBOL_NOT_FOUND → ORDER_PARTIAL).

getOpenOrders now drops "#<n>" coins (hlIsOutcomeCoin); the outcome adapter, which relied on the
perp list containing them, reads getOutcomeOpenOrders from the same response.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…s an error

runTWAP sent String(total / slices) unrounded ("0.0033333333333333335"); Aster sends the quantity
verbatim, so every slice was a definite refusal. After aborting on too many errors it returned
the state, and trade twap printed jsonOk / exit 0.

Each slice is now an equal share of what is left, floored to lotStepOf (the remainder carried to
later slices); a sub-lot slice or unknown lot is SIZE_TOO_SMALL before sending. Refused slices
that leave a lot untraded end the run with ORDER_PARTIAL / ORDER_REJECTED (job state error). A
refusal before the first slice marks the job error as well (it later read done), and a
reduce-only run on a market missing from the market list points to `trade close`.

Tests: the abort test now expects the error; mock markets gain the lot step TWAP reads.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…orders

trade cancel <symbol> found the open orders with symbolMatch ("xyz:TSLA" for "TSLA" under
--dex xyz), then LegacyTradingV2.cancelAllV2 scoped them by exact symbol: 0 cancelled, reported
as success. cancelAllV2 now scopes with symbolMatch too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…thers

orphanedReduceOnly cancelled the orders left on flat QFEX symbols without a try: the first
ORDER_NOT_FOUND (the venue had removed the stop itself) escaped, the remaining orphans were never
tried, and flatten's cancel / close results were replaced by that bare error. A thrown cancel is
now recorded (refusal → failed, else pending, the cancelAllV2 rule) and the loop continues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…07 / 21508 are margin

lighterSendTxCodeIsDefinite treated only 20000–28999 as definite, so the account-level refusals
docs.lighter.xyz lists (52001 unauthorized API use, 52002 Standard trading limit — close / reduce
only, 62007 maker-only key) became ORDER_PENDING (outcome unknown, quarantine) although nothing
executed. They are now definite rejections with the venue's message; 21507 / 21508 (below
maintenance / initial margin) map to MARGIN_INSUFFICIENT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… only its market

cancelAllV2's catch covered the post-cancel verification reads: one failed by-id read marked
every ref of the market failed, duplicating refs already pushed to cancelled, although the
cancel-all tx had been accepted. permit() sat outside the try, so a permit failure threw out of
the whole call and lost the other markets' results.

Each order is now settled once; after an accepted (or unknown) cancel-all the unsettled orders
are pending; a failed permit / definite send failure marks that market's orders failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rders

placeOrder refused every non-reduce-only order on a market in reduce-only mode, market orders
(LIMIT IOC) included. RISEx docs: reduce_only "only accepts resting orders (GTC/GTT) that are
marked reduce-only on this market; FOK and IOC orders are unaffected" (E0706 "Resting orders
(GTC/GTT) must be reduce-only"). Market / IOC / FOK orders are now sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
parseFloat("x50") is NaN and `Math.abs(NaN - 100) > 0.01` is false, so the sum guard accepted it:
a NaN last level was placed with the remainder of the size, a NaN earlier level threw an untyped
RangeError from BigInt. Each percent now goes through parsePositiveDecimal (INVALID_PARAMS).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Migration notes under [Unreleased] for the output changes of this group: close size format,
TWAP ok → error, Lighter read-only open orders (account orders, portfolio, MCP portfolio,
stream), risk PRICE_STALE, Lighter 52001 / 52002 / 62007 and 21507 / 21508 codes, HL outcome
rows, and plan cancel_all failures on Ondo / Arcus / QFEX / TxFlow / RISEx.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

⚠️ Large PR — 1181 changed lines across 45 files (lockfile and snapshots excluded).

If it holds more than one logical change, consider splitting it for review.

Conflicts: CHANGELOG.md (both sides kept); ws-feeds.ts REST poll (main's
obsolete-read guard and emitUpdate(false), this branch's openOrdersForView);
hyperliquid.ts (main's hlOpenOrderRows helper now takes the keep predicate,
default perp-only, so HIP-4 outcome rows stay out of perp open orders and
the dashboard feed).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@Hiksang
Hiksang merged commit f1372f9 into main Nov 15, 2026
5 checks passed
@Hiksang
Hiksang deleted the fix/order-close-safety branch November 15, 2026 09:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant