Repository navigation
fix: order / close / cancel safety (12 fixes) - #97
Merged
Merged
Conversation
…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>
|
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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.
cancelAllOrderson Ondo / Arcus / QFEX / TxFlow / RISExORDER_PARTIAL/ORDER_REJECTED/ORDER_PENDINGwith the per-order outcomegetOpenOrdersreturned[], socancel-all,cancel <symbol>andflattenexited 0 with nothing cancelledNO_SIGNER_AVAILABLE/AGENT_EXPIRED. Views that read orders with balances (portfolio, MCP, stream, dashboard) showopenOrders: nullwith the reasonPRICE_STALE;trade checkfailsrisk_limitsfor an opening ordercancel-all/flattenfailed on them--dex <dex> trade cancel <symbol>flatten/sendTx52001 / 52002 / 62007MARGIN_INSUFFICIENTscale-tp/scale-in --levelsINVALID_PARAMS)JSON contract changes: listed in the CHANGELOG under "JSON contract changes" with migration notes. The ones most likely to affect scripts:
closed/residual) are plain decimals without padding: compare as numbers.ok: false.[];portfolioopenOrdersisnumber | nullwithopenOrdersError.risk status/risk checkfail withPRICE_STALEwhen 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 (defaultonFailure: "abort"). To close anyway, set"onFailure": "skip"on thecancel_allstep. 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 testpasses (338 files / 7317 tests)tsc --noEmitandtypecheck:testpassTesting standard (docs/TESTING.md §7)
test.skip/.onlyTwo 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
CHANGELOG.md[Unreleased]: every open fix PR adds entries (keep both sides).ws-feeds.tsdoRestPolland imports: keep both fix(dashboard): origin/host check, HL channels, stale handling, Pacifica deltas, keepalive, backoff #84'srestFallbackTimerguard and this PR'sopenOrdersForView.hyperliquid.tsgetOpenOrders: fix(dashboard): origin/host check, HL channels, stale handling, Pacifica deltas, keepalive, backoff #84 extractedhlOpenOrderRows(), which filters only spot. This PR'shlIsOutcomeCoinexclusion must move into it, or the HIP-4 fix is silently undone. Re-run the hyperliquid-info tests after resolving.🤖 Generated with Claude Code