ohtradeDocumentação
Operar ↗

Crie um aplicativo ou agente de trading

> Updated reference (English); translation pending.

ohtrade exposes public account reads and wallet-authorized actions. Your app can use its own interface, and an Agent can prepare and sign permitted actions for its owner. The signing key stays with the wallet or authorized signer.

Start at /llms.txt for the document directory, /docs/manifest.json for versions and page links, and /docs/openapi.json for the HTTP reference. Every Docs page has a Markdown alternative. The public reading resources remain accessible independently of access to trading functionality.

Pin the deployment first

Read /api/funding/config, /api/trading/config and /api/protocol/config. Match their program, cluster, genesis and settlement-token identifiers to the deployment your user approved. Account execution availability is reported at funding/config.execution.enabled; auction availability at protocol/config.enabled. Trading configuration has no universal enabled flag: an unavailable intent service returns 503. Check action availability before asking for a signature.

Use the matching SDK and IDL. Public GET endpoints can be read without a wallet signature or API key. Wallet addresses and the account activity returned by these endpoints are public information.

The fast trading path

The intent route submits a 175-byte, little-endian message signed by an owner or a currently authorized trading key:

POST /api/trading/intent
Content-Type: application/json

{
  "intent": "EXACT_175_SIGNED_BYTES_AS_BASE64",
  "signature": "ED25519_SIGNATURE_64_BYTES_AS_BASE64",
  "signer": "SIGNING_SOLANA_PUBLIC_KEY"
}

Use encodeIntent from the matching SDK. The signed fields are domain, program ID, owner, collateral pool, action, market ID, side, margin, leverage, position, price bound, nonce, signed slot, expiry slot and minimum winning exposure (minExposure).

FieldEncoding / meaning
DomainFixed 16-byte ohtrade:intent:2 domain field
Pool0 for USDC, 1 for OH
Kind0 to open, 1 to close
Side0 long, 1 short
Marginu64 micro-units; zero for a close
Leverageu32 in the signed message; zero for a close
PositionDefault public key for an open; actual position for a close
Price boundu64 with 8 decimals; zero explicitly selects no bound
Nonceu64 in the current account's replay window
Signed / expiry slotu64; default lifetime 75 slots, maximum 150
Minimum winning exposureu64 micro-units at byte offset 167; zero for close; signed minExposure for open

The program ID is part of the message. Genesis is checked through the deployment and RPC configuration, not a separate genesis field inside this signature layout. Keep slot lifetimes in slots rather than assuming a fixed number of seconds.

The server returns {id, accepted: true} after intake. The intent ID has the form owner:pool:nonce. Receipt is not a fill.

Follow execution

Subscribe to /api/trading/events?owner=PUBLIC_KEY and refresh /api/trading/snapshot?owner=PUBLIC_KEY. The SSE stream carries request, fill, rejected, cancelled and snapshot events. Fill events advance through processed, confirmed and finalized stages. Reconcile a fresh snapshot after a reconnect.

Do not send an intent ID to /api/trading/status; that endpoint belongs to prepared transactions. For an intent, keep the original message, signature, nonce and ID, then use matching execution events and account state to establish the outcome. A nonce may be consumed by a rejection as well as a successful fill.

Accounts, conventional orders and auctions

These actions use a prepare → sign → submit flow:

Action familyPrepareSubmitStatus
Account, deposit, withdrawal, staking, rent, sessions/api/funding/account/prepare/api/funding/account/submit/api/funding/account/status?id=…
Conventional open, close, Request cancellation/api/trading/prepare/api/trading/submit/api/trading/status?id=…
Buyback sell, reprice, cancel/api/protocol/prepare/api/protocol/submit/api/protocol/operation?id=…

Inspect the returned message and its actions, amounts, destinations, deployment, fee payer, rent and validity before signing. Sponsored transactions usually need the owner or permitted session signature plus the service fee payer; an explicitly chosen self-paid fallback has a different signer arrangement. Never assume a fixed signer count for every route.

Trading and auction preparations can return a quoteToken. Save this opaque receipt with the operation and return it unchanged on submit. It lets the service recover an unsigned preview removed from its bounded cache. Wallet signatures and the preparation's original validity still apply.

For a batch cancellation, sign the main transaction and every returned followUps together, then submit that exact set. An approval currently covers up to eight chunks. Follow afterBatch, awaitingSignature and presignedRemaining; prepare continue_cancel when another approval is needed.

Exact amounts and recoverable submissions

USDC and OH have 6 decimal places; quoted prices have 8. JSON amounts are decimal integer strings. For 100 OH at 0.25 USDC per OH:

{"amount":"100000000","price":"25000000"}

Use integer or bigint arithmetic. Persist the operation ID, approved terms and exact signed bytes before submitting. After an uncertain response, query the original operation and reconcile its state. Prepared transactions can be retried with their original bytes; creating a new transaction with a fresh blockhash is a new authorization decision.

historyUnavailable means the outcome remains unresolved. An unsigned preparation can expire before submission. Once signed bytes may have been broadcast, resolve the original signature. For prepared trades, neverLanded is reported only after finalized expiry and a chain-state proof. A quote's displayed expiry alone does not establish a broadcast result. Keep a confirmed failure separate from an RPC timeout.

Fees and service limits

The server pays supported sponsored network fees. The user funds refundable account rent. An intent open needs Position rent in the shared prepaid SOL balance; the conventional Request path also needs its temporary account rent and future-position commitment.

HTTP 429 includes retry information. Respect Retry-After and structured code fields rather than parsing the human message. Relay limits and sponsorship budgets are service controls; they can differ from chain account limits. A self-paid fallback should be an explicit owner choice.

The funding, trading and protocol routes use ordinary HTTPS and CORS. They do not require a server-side secret API key. Internal keeper credentials are not part of this interface. Start with read-only calls, and obtain specific owner authorization before signing a write.

Local V11 implementation

This V11 build supports fresh deployments only. Its changed account discriminators and layouts must be decoded with the matching release's sdk/idl/perp.json and SDK; legacy accounts cannot be reinterpreted or upgraded in place by this build. The intent wire version is separate from the account ABI.

Before signing, match the configured program, SDK/IDL, economics version 11 and the finalized volatility calibration hash. A 175-byte intent alone does not prove account compatibility. Persist the exact signed terms and use execution events plus account state to reconcile rejection or fill. A rejected opening must not be treated as a filled position; the Request path's collateral and rent cleanup follows its actual outcome. There is no automatic conversion of old accounts, outstanding claims or trading history.

Implementação local V11

Esta versão V11 suporta apenas implantações novas. Discriminadores e estruturas de contas alterados exigem o sdk/idl/perp.json e SDK da mesma versão; contas antigas não podem ser reinterpretadas nem atualizadas no lugar por esta versão. A versão da mensagem intent é distinta do ABI das contas.

Antes de assinar, confira programa, SDK/IDL, versão econômica 11 e hash final de calibração. Um intent de 175 bytes não prova compatibilidade de contas. Guarde os termos exatos e reconcilie eventos com o estado da conta. Abertura rejeitada não cria posição; a liberação de garantia e rent no Request depende do resultado real. Contas, créditos e histórico antigos não se convertem automaticamente.

← Anterior
Controles e encerramento do protocolo
Próximo →
Referência HTTP pública