Skip to Content
Symmio Trading-SDK — the SDK surface for builders on Arbitrum
ReactSolvers hooksInstant Open

Instant Open hooks

React hooks over the core Instant Open flow. The three-function split (prepare / submit / auto) applies here too — pick based on how much control you want.

The page is split into two groups:

  • Reads — pending queue reads (useInstantOpens, useInstantOpenQuoteId).
  • Writes — the three-function open path (useInstantOpenAuto, useInstantOpen), the LIMIT-order variant (useLimitOpenAuto), plus the composed orchestrator (useInstantOpenWithTpSl).

Import

import { useInstantOpen, useInstantOpenAuto, useLimitOpenAuto, useInstantOpenWithTpSl, useInstantOpens, useInstantOpenQuoteId, } from "@symmio/trading-react";

Reads

useInstantOpens

Paginated list of the solver’s pending instant-opens for a SubAccount. useManagedQuotes consumes this internally.

const pending = useInstantOpens({ account: subAccount, offset: 0n, size: 20n });

useInstantOpenQuoteId

Resolve the on-chain quoteId for a given tempQuoteId. useManagedQuotes and the notification handlers use this to link rows.

const quoteId = useInstantOpenQuoteId({ tempQuoteId: -1001 });

Writes

useInstantOpenAuto

The default — one-line orchestrator. Runs prepareInstantOpenParams inline (fetches market metadata, mark price, locked params, fee rates), then signs and POSTs. It does not add an account-balance read or balance check before signing; the frontend decides whether to check the balance before requesting submission.

const open = useInstantOpenAuto(); <Button disabled={open.isPending} onClick={() => open.mutate({ from: sessionKey, subAccountAddress: subAccount, market: { id: 1 }, positionType: PositionType.LONG, initialMargin: "100", leverage: 5, slippage: 1, }) } > {open.isPending ? "Opening…" : "Open"} </Button>;

Latency: prepare fetches run inline, so click → sign gap includes the network hop. Fine for most flows; see useInstantOpen below for the low-latency variant.

Fee-inclusive funding (lowcap only) — replace initialMargin with fund: { mode: "full-balance", balance } to deploy the selected funding amount into the position’s VA; the SDK sizes the quantity so its locks + open-side fees + settlement fit inside the balance (close fees are charged at close from the position, not funded here). Funding is a one-of: pass exactly one of the two. See Full-balance funding for the sizing semantics.

open.mutate({ from: sessionKey, subAccountAddress: subAccount, market: { id: 1 }, positionType: PositionType.LONG, fund: { mode: "full-balance", balance: "100" }, // deploy all $100 — no initialMargin leverage: 5, // slippage optional on lowcap — auto-derived from the dry-run estimate });

Acceptance is not a fill. Keep optimistic rows pending until the live open confirmation. The hook invalidates SDK balance and pending-open queries on acceptance. If the app owns separate query keys, refresh its displayed balance after every attempt and again on open or failure notifications. Refresh positions, virtual accounts and market capacity on the corresponding live events; preserve polling as a fallback.

operationDeadline and deadline are forwarded unchanged. Rejection bodies and missing IDs surface as normalized hook errors, retaining solver details in error.responseData.

Delegation preflight — before signing, every open hook (useInstantOpenAuto, useLimitOpenAuto, useInstantOpen, useInstantOpenWithTpSl) checks that the signing key holds the InstantLayer delegation the open needs. A session key without it fails the mutation with a SymmioRequestError whose code is INSTANT_SIGNER_NOT_DELEGATED, before anything is signed or sent; prompt the user to grant the trade set (useGrantDelegation). Pass preflightDelegation: false in the variables when your UI already gates the button on delegation, for example with useAreDelegationsActive. See Delegation preflight.

Enigma account timelocks — on v0.8.6 deployments advertising timelock approval metadata, these hooks use core’s canonical margin wrapper and non-skippable policy check. A missing account policy produces INSTANT_OPEN_TIMELOCK_POLICY_REQUIRED before signing. An Active session does not establish that this separate policy exists. The hooks never configure timelocks automatically or require delegation for the wrapper selector. Render the normalized error and direct the owner to the separately approved account-setup flow. See Enigma margin timelocks for immutable fields, expiry, legacy compatibility and the other typed errors.

useLimitOpenAuto

The LIMIT-order variant — same one-line shape as useInstantOpenAuto, but the user’s resting price is the trigger and the order writes a pending on-chain quote instead of filling immediately. Majors / Rasa only; throws UNSUPPORTED_BY_SOLVER when the resolved solver has no limit support (gate the UI with useSupportsLimitOrder). Defaults the send deadline to 15 minutes. Funding is always a typed initialMargin here — the full-balance fund mode is lowcap-only, and limit orders are majors-only.

const place = useLimitOpenAuto(); place.mutate({ from: sessionKey, subAccountAddress: subAccount, market: { id: 1 }, positionType: PositionType.LONG, initialMargin: "100", leverage: 5, price: "64000", // resting limit price });

On success it invalidates the hedger’s instant-open feed, so the order surfaces immediately as an offchain row in useLimitOrders; the anchor notification then flips it to onchain. Cancel it with useRequestToCancelQuote.

usePrepareInstantOpenParams

Live-preview the exact InstantOpenParameters a submit will sign — order (price + quantity), lockedParam, margin.amount, solverFeeCaps — by running prepareInstantOpenParams as a read. prepareInstantOpenParams neither signs nor submits, so this is safe to run on every input change; drive a “quote preview” from it and what the user sees is bit-for-bit what sendQuote receives — no separate local recomputation to drift, and the full-balance rescale + lot snap come for free.

Like useInstantOpenFees, it pre-fetches every input through its own cached queries (market metadata, mark price, locked params, on-chain fee rates, solver info, and the lowcap dry-run estimate) and passes them in as prefills, so the query function is pure. It also returns estimatedOpenPrice and estimatedOpenPriceTimestamp (epoch milliseconds). Forward the estimate to submission. The timestamp is available for frontend refresh or expiry decisions; core does not enforce an estimate age limit.

The hook has no fixed estimate polling interval. Call refetchEstimatedPrice(options?) when your frontend wants a fresh SDK-managed estimate. It forwards the estimate query’s existing refetch function and returns its query result; its promise finishes when the estimate request finishes. A changed estimate triggers the existing preview recalculation, so continue to gate submission on isReady. The existing refetch() reruns the calculation using cached inputs. If you supply estimatedOpenPrice, refresh that value yourself: supplied estimates continue to take precedence.

The optional estimatedOpenPriceWithoutShadow is diagnostic data from the same settled SDK-managed estimate as estimatedOpenPrice. It is absent when the solver omits it, while inputs are debouncing/refetching, for failed/placeholder estimates, when disabled, or when the caller supplies estimatedOpenPrice (including null). A cached no-shadow value is never paired with a caller override. This field does not enter core preparation, fees or submission and creates no additional request. Use it only for an explanation; all trading calculations continue to use the shadow-inclusive estimatedOpenPrice.

The returned estimatedOpenPrice is a decimal string when available, null when the estimate settled but was unavailable, and undefined while pending or on a non-lowcap solver. Forward it unchanged to submission, including null, so core does not fetch an unavailable estimate again. With automatic or explicit full-balance sizing, the estimate affects the final quantity and funding decision as well as margin.amount.

Preparation and fee data also contain InstantOpenEstimateMetadata: openEstimateStatus and the exact estimatedOpenPrice. Display a reference-price notice when the status is "unavailable", explain that the execution price is not guaranteed, and keep the selected slippage limit. Gate that notice on isReady so retained data from another input is not presented as current.

The preview waits for its estimate and disables automatic retries. A technical failure, including a confirmed missing estimate route, settles the estimate to null and clears any previously successful estimate and its timestamp. A solver refusal or query cancellation surfaces through error and keeps isReady false. A valid price outside tolerance still rejects. See the core fallback rules for error codes and reserve wording.

useInstantOpenAuto().data has the core InstantOpenAutoReturnType, including estimate metadata. useInstantOpenWithTpSl().data.instantOpen includes the same metadata in both provided-quantity and prepared-quantity modes. The primitive useInstantOpen retains its original result shape.

For automatic fallback, pass the raw available balance as availableBalance alongside initialMargin. The hook returns data.fundingMode ("initial-margin" or "full-balance") from core. Keep the typed input editable and show an adjustment message when the effective mode is "full-balance". Prefer this resolved funding check to comparing the typed amount against a fee-adjusted allowance. See automatic fallback for the exact rules.

A typed initialMargin above availableBalance produces a synchronous validationError, including while offline, before requesting a price estimate or other prefills. Display validationError ?? error: error and isError describe the calculation query, while validationError describes invalid input. Invalid balance funding disables dependent queries; correcting the input clears validationError and resumes preparation. Explicitly disabled hooks and empty inputs stay idle without validation. Automatic fallback applies only when the typed amount fits but its required funding exceeds the balance.

The hook also returns isReady: it is true only when required inputs, the debounced estimate, and the current preparation have settled successfully. Gate submission on isReady; previous data may remain visible while it is false. Pass the same availableBalance to the fee preview and useInstantOpenAuto / useInstantOpenWithTpSl submission. Take TP/SL quantity from the prepared order, including when fallback activates automatically.

const preview = usePrepareInstantOpenParams({ subAccountAddress, from: sessionKey, market: { id: symbolId }, positionType, initialMargin, availableBalance, // raw collateral decimal string; lowcap automatic fallback leverage, slippage, }); // Display this error before rendering the preview. const error = preview.validationError ?? preview.error; // render preview.data — the exact params the send signs // preview.data?.order.quantity, preview.data?.lockedParam.cva, preview.data?.margin.amount const open = useInstantOpenWithTpSl(); if (preview.isReady) { open.mutate({ ...variables, initialMargin, availableBalance, estimatedOpenPrice: preview.estimatedOpenPrice, }); }

Bind estimate refresh to a frontend action, for example:

<button type="button" onClick={() => void preview.refetchEstimatedPrice()}> Refresh estimate </button>

useInstantOpen

Low-latency primitive — the caller supplies the fully-resolved InstantOpenParameters bag. Pair it with a usePrepareInstantOpenParams preview staged earlier (on trade-panel mount) so the critical path is just sign + POST.

const prepare = usePrepareInstantOpenParams(uiInputs); const open = useInstantOpen(); // user clicks Open — no fetches on the critical path if (prepare.isReady && prepare.data) open.mutate(prepare.data);

useInstantOpenWithTpSl

Orchestrator that opens a position and immediately attaches TP/SL against the returned tempQuoteId. Two mutations chained under the hood:

  1. instantOpenAuto → returns tempQuoteId.
  2. setQuoteTpSl with quoteId: tempQuoteId → creates the conditional-order legs.
const open = useInstantOpenWithTpSl({ tpslState: "sdk" }); open.mutate({ tpslQuantityMode: "prepared", ...instantOpenInputs, tpsl: hasTpOrSl ? { from: sessionKey, virtualAccount: predictedVa, subAccount, symbolId, positionType, quantity, pricePrecision, tp: tpInput, sl: slInput, } : undefined, });

virtualAccount is the position’s VA, which does not exist on-chain yet — derive it with usePredictedNextVirtualAccount keyed by isolationTypeForSide(positionType) and symbolId. tpsl: undefined (both legs empty) collapses the call to a plain useInstantOpenAuto. The open and the TP/SL leg fail independently: a rejected TP/SL still resolves the mutation and surfaces data.tpslError rather than throwing away a landed open.

Pass tpslQuantityMode: "prepared" to prepare the open once and attach using the exact submitted quantity, including full-balance rescaling. A previous preview can differ from the actual submission. The default "provided" retains caller-supplied tpsl.quantity for compatibility.

Pass useInstantOpenWithTpSl({ tpslState: "external" }) when the application owns TP/SL optimism and REST reconciliation. This skips writes to the SDK TP/SL store; existing instant-open and balance refreshes remain. The default "sdk" retains the store behavior below.

data.tpslParameters contains the resolved attachment inputs, including submitted quantity and quote ID, whenever they could be constructed. It is present on attachment rejection as well as acceptance, and contains no signature. An absent or invalid attachment ID after an accepted open returns data.tpslError; the accepted open is preserved. Recovery must call only setQuoteTpSl, never the open mutation again. Do not replay an ambiguous write automatically: acceptance is separate from observed order state.

On acceptance, useTpSlStore is populated with the confirming record keyed by tempQuoteId. Resolve the on-chain ID through useInstantOpenQuoteId when the position anchors. The shared order record becomes reachable by both IDs once its alias is learned from a read or notification carrying the relationship; an on-chain-only notification cannot establish that relationship by itself. The handler’s WebSocket report can flip the record from confirming to new; matching REST rows can also settle it through the SDK’s existing reconciliation. Read current orders with useQuoteTpSl({ quoteId, account }).

The reference app uses prepared quantity and SDK-owned order state. Its submission result is a separate presentation policy: useWatchTpSlNotifications subscribes before dispatch and HTTP acceptance keeps Setting TP/SL… visible until a matching new or edit report arrives for every submitted side. Successful cancellation reports and unsuccessful reports show an error, including after a timeout. A trigger report shows TP/SL confirmed; a trigger has fired, without claiming that trade execution finished. Current-order REST reads remain unchanged, but cannot independently complete this submission message or turn an absent row into a failure.

For an at-open result, the reference app uses useInstantOpenQuoteId with the submitted deployment and solver, polling every two seconds until anchoring. It retains the temporary ID, including negative IDs, and checks reports against the resolved ID too. Reports arriving before the HTTP response or ID resolution are retained for this submission; unrelated pre-resolution reports are bounded to the latest 128 entries. The two listeners in the existing-position editor share the SDK’s pooled socket: one updates current orders, the other controls the submission message. The at-open result does not mount an additional current-order query.

If a report is still missing 90 seconds after acceptance, the reference app shows TP/SL not confirmed yet — check current orders without an automatic retry. Late reports can still replace that warning. A fresh submission starts a new waiting window; context changes discard old feedback and completions. This matches reports by position and submitted side, not a backend mutation ID. Overlapping writes and delayed reports from earlier mutations remain unsupported; this UI does not introduce a correlation or replay guarantee.

An explicit SET_TPSL_REJECTED response offers a user-triggered Retry TP/SL only action through useSetQuoteTpSl, using the returned tpslParameters. A malformed response or transport failure shows unconfirmed protection and asks the user to check current orders; it does not enable a blind retry. A fresh empty read cannot prove that an ambiguous request will not complete later. Switching wallet, session, account, deployment or solver discards the old form’s recovery controls.

external is intended for consumers that already own optimism and reconciliation; selecting it in the reference app would remove its existing state owner without a replacement. Acceptance and recovery messaging above does not change the SDK store’s existing notification/read policy.

See TP/SL for the store + reconciliation model.

  • Core Instant Open — the three-function split explained.
  • TP/SL — useInstantOpenWithTpSl composes over these.
  • Unified Quotes — useManagedQuotes reconciles the pending list with on-chain reads + notifications.
Last updated on