bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 20쪽
t
Use one market and token snapshot across the whole read flow. This avoids mixing data from different polls when you render positions, active orders, and recent trades together.
```typescript
const sdk = new GmxSdk({
chainId: 42161,
rpcUrl: "https://arb1.arbitrum.io/rpc",
oracleUrl: "https://arbitrum-api.gmxinfra.io",
subsquidUrl: "https://gmx.squids.live/gmx-synthetics-arbitrum:prod/api/graphql",
});
sdk.setAccount("0x9f7198eb1b9Ccc0Eb7A07eD228d8FbC12963ea33");
const { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();
if (!marketsInfoData || !tokensData) {
throw new Error("Failed to load market snapshot");
}
const [{ positionsData }, { ordersInfoData }, trades] = await Promise.all([
sdk.positions.getPositions({
marketsData: marketsInfoData,
tokensData,
}),
sdk.orders.getOrders({
marketsInfoData,
tokensData,
}),
sdk.trades.getTradeHistory({
pageSize: 25,
pageIndex: 0,
marketsInfoData,
tokensData,
}),
]);
console.log({
positions: Object.values(positionsData ?? {}),
orders: Object.values(ordersInfoData ?? {}),
recentTrades: trades,
});
```
## Open a Market Increase order
If you want the SDK to calculate swap paths, fees, and order amounts for you, start with the quick helper methods. The helper returns a transaction hash after submission. After that, you still need to wait for the receipt and refetch positions or orders.
```typescript
const account = privateKeyToAccount("0x...your-private-key");
const walletClient = createWalletClient({
account,
chain: arbitrum,
transport: http("https://arb1.arbitrum.io/rpc"),
});
const sdk = new GmxSdk({
chainId: 42161,
rpcUrl: "https://arb1.arbitrum.io/rpc",
oracleUrl: "https://arbitrum-api.gmxinfra.io",
subsquidUrl: "https://gmx.squids.live/gmx-synthetics-arbitrum:prod/api/graphql",
walletClient,
account: account.address,
});
const txHash = await sdk.orders.long({
payAmount: 100031302n,
marketAddress: "0x70d95587d40A2caf56bd97485aB3Eec10Bee6336",
payTokenAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
collateralTokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
allowedSlippageBps: 125,
leverage: 50000n,
});
const receipt = await sdk.publicClient.waitForTransactionReceipt({ hash: txHash });
if (receipt.status !== "success") {
throw new Error("Order transaction reverted");
}
const { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();
const { ordersInfoData } = await sdk.orders.getOrders({
marketsInfoData: marketsInfoData!,
tokensData: tokensData!,
});
console.log("Submitted tx:", txHash);
console.log("Active orders:", Object.keys(ordersInfoData));
```
## Cancel active orders
Fetch the latest active orders first, then cancel by on-chain order key. This matters if your UI lets the user cancel and replace orders quickly.
```typescript
const { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();
if (!marketsInfoData || !tokensData) {
throw new Error("Failed to load market snapshot");
}
const { ordersInfoData } = await sdk.orders.getOrders({
marketsInfoData,
tokensData,
});
const orderKeys = Object.keys(ordersInfoData);
if (orderKeys.length === 0) {
throw new Error("No active orders to cancel");
}
const txHash = await sdk.orders.cancelOrders(orderKeys);
await sdk.publicClient.waitForTransactionReceipt({ hash: txHash });
const refreshed = await sdk.orders.getOrders({
marketsInfoData,
tokensData,
});
console.log("Remaining orders:", Object.keys(refreshed.ordersInfoData));
```
## Operational notes
### Data freshness and consistency
- Quick helpers fetch `marketsInfoData` and `tokensData` for you when you do not pass them in.
- If your app already has a fresh snapshot, pass the same `marketsInfoData` and `tokensData` through the whole flow. This gives you a more consistent view than mixing independent reads.
- After a write, treat reads as eventually consistent. Transaction submission, order creation, keeper execution, and indexed reads do not complete at the same time.
### Simulation behavior
- On chains with a configured `SimulationRouter`, the SDK appends a `makeExternalCalls` preflight through that router to the `ExchangeRouter.multicall`. If the optional contract is not configured, it uses the legacy simulation payload.
- Market increases simulate before submit unless you pass `skipSimulation: true`.
- Limit increases skip simulation in the current implementation.
- Market swaps simulate before submit. `Limit Swap` orders do not.
- `createDecreaseOrder()` currently sets `skipSimulation: true`. If you expose that flow, validate inputs before submit and handle chain-level failures explicitly.
### Retries and timeouts
- The default viem HTTP clients created by `GmxSdk` disable transport retries with `retryCount: 0`.
- SDK multicalls use a `40000` ms timeout.
- Add your own retry and backoff policy around read paths that can be repeated safely. Persist transaction hashes from write paths so you can recover after client restarts.
### Idempotency and race conditions
- SDK v1 order methods do not take idempotency keys or client-generated order IDs.
- Disable duplicate submit actions in your UI while a transaction is pending.
- When you cancel or replace orders, refetch active orders just before choosing `orderKeys`.
## Next steps
- Go back to [Getting Started](./readme.mdx) for constructor options and module reference.
- See [Examples](./examples.md) for smaller focused snippets.
- Use [Exports](./exports/exports.md) when you need lower-level helpers such as fee estimation, price impact, or custom trade amount calculation.
---
## Troubleshooting(V1)
Use this page when SDK v1 reads or writes do not behave the way you expect. Most production issues fall into one of five buckets: missing receipt handling, stale follow-up reads, duplicate submits, transport failures, or workflow assumptions that belong to SDK v2 or GraphQL instead.
## The SDK returned a transaction hash, but my UI is still pending
That is expected. SDK v1 order methods submit the transaction and return the hash. They do not wait for the receipt for you.
Recommended pattern:
1. Persist the transaction hash as soon as you receive it.
2. Wait for the receipt with `sdk.publicClient.waitForTransactionReceipt`.
3. Only after the receipt succeeds should you start polling positions, orders, or trade history.
If the client reloads before confirmation, recover from the saved transaction hash instead of resubmitting.
## The transaction succeeded, but the order or position is not visible yet
Treat follow-up reads as eventually consistent.
- Transaction inclusion, order creation, keeper execution, and indexed history do not complete at the same time.
- `orders.getOrders()` shows active on-chain orders, but trade history comes from Subsquid and can lag behind live chain state.
- If you need a coherent account snapshot, refresh one `marketsInfoData` and `tokensData` snapshot and reuse it across position and order reads.
## I accidentally submitted the same action twice
SDK v1 does not support idempotency keys or client order IDs.
Recommended client behavior:
1. Disable repeat submit actions while a transaction is pending.
2. Persist the last in-flight transaction hash per user action.
3. Require an explicit retry action after a failure instead of auto-resubmitting writes.
## Cancel or replace shows unexpected order state
This is usually a race between an old UI snapshot and current on-chain order keys.
- Refetch active orders immediately before calling `cancelOrders`.
- Cancel by the latest on-chain order keys, not by cached UI state from an earlier poll.
- After cancel or replace, refetch orders again instead of assuming the previous list is still valid.
## Read calls fail with timeouts or transient RPC errors
The default SDK-created viem transports set `retryCount: 0`, and SDK multicalls use a `40000` ms timeout.
Recommended client behavior:
1. Add retry and backoff around safe read paths.
2. Keep write submission separate from read retries so you do not duplicate transactions.
3. Consider supplying your own viem clients if you need a custom transport strategy.
If you inject a custom viem `publicClient`, make sure it includes `BATCH_CONFIGS` from `@gmx-io/sdk/configs/batch`. The SDK-created default clients already do this for you, but custom clients do not inherit it automatically.
Without the SDK batch config, large GMX multicalls may be fragmented into many smaller requests instead of one client-side multicall. Common symptoms include unexpectedly high RPC request counts, public RPC rate limits, and browser-side transport failures during otherwise normal read or order-helper flows.
## A limit order did not simulate before submit
That can be current behavior, not necessarily a bug.
- Market increases simulate by default unless you opt out.
- Limit increases skip simulation in the current implementation.
- Market swaps simulate by default, while `Limit Swap` orders do not.
- `createDecreaseOrder()` currently skips simulation.
If your UI exposes these flows, validate inputs before submission and surface chain-level errors clearly.
## Next steps
- Use the [Integration guide](./integration-guide.md) for exact SDK v1 workflows.
- Use [Getting Started](./readme.mdx) for constructor and module reference.
- Use [SDK Overview](../overview.md) when you need to choose between SDK v1 and SDK v2.
---
## Order Examples
This page shows how to create, edit, cancel, and track orders using `GmxApiSdk`. All examples assume Arbitrum (`chainId: 42161`).
## Setup
```typescript
const sdk = new GmxApiSdk({ chainId: 42161 });
// For signing orders — PrivateKeySigner wraps viem's privateKeyToAccount
const signer = new PrivateKeySigner("0xYOUR_PRIVATE_KEY");
const account = signer.address;
```
`IAbstractSigner` is the minimal interface the SDK needs. You can implement it with any wallet:
```typescript
const walletSigner: IAbstractSigner = {
address: "0x...",
async signTypedData(domain, types, value) {
return wallet.signTypedData({ domain, types, message: value });
},
async signMessage(message) {
return wallet.signMessage({ message });
},
// Optional - only needed for classic mode
async sendTransaction(tx) {
return wallet.sendTransaction(tx);
},
};
```
## Discovering markets and prices
Before creating orders, you need to know which markets exist and what prices to use. The `symbol` field used in order requests (e.g. `"ETH/USD [WETH-USDC]"`) comes from the market data.
### List available markets
```typescript
const markets = await sdk.fetchMarkets();
for (const m of markets) {
console.log(m.symbol); // "ETH/USD [WETH-USDC]"
console.log(m.marketTokenAddress); // "0x70d95587d40A2caf56bd97485aB3Eec10Bee6336"
console.log(m.isSpotOnly); // false (perp market) or true (spot only)
console.log(m.leverageTiers); // [{ maxLeverage, minCollateralFactor, maxPositionSize }]
console.log(m.minPositionSizeUsd); // Minimum position size (30 decimals)
console.log(m.minCollateralUsd); // Minimum collateral (30 decimals)
}
```
### Get current prices and market data
```typescript
// All markets
const tickers = await sdk.fetchMarketsTickers();
// Filter by symbol
const ethTickers = await sdk.fetchMarketsTickers({
symbols: ["ETH/USD [WETH-USDC]"],
});
// Filter by market address
const filtered = await sdk.fetchMarketsTickers({
addresses: ["0x70d95587d40A2caf56bd97485aB3Eec10Bee6336"],
});
const ticker = ethTickers[0];
console.log(ticker.symbol); // "ETH/USD [WETH-USDC]"
console.log(ticker.markPrice); // Current mark price (30 decimals)
console.log(ticker.maxPrice); // Max price
console.log(ticker.minPrice); // Min price
console.log(ticker.high24h); // 24h high
console.log(ticker.low24h); // 24h low
console.log(ticker.priceChangePercent24hBps); // 24h change in bps
console.log(ticker.longInterestUsd); // Open interest long (30 decimals)
console.log(ticker.shortInterestUsd); // Open interest short (30 decimals)
console.log(ticker.availableLiquidityLong); // Legacy pool liquidity: excludes JIT, not for sizing
console.log(ticker.availableLiquidityShort); // Legacy pool liquidity: excludes JIT, not for sizing
console.log(ticker.fundingRateLong); // Current funding rate
console.log(ticker.borrowingRateLong); // Current borrowing rate
console.log(ticker.capacityLong); // Optional JIT-aware TradingCapacity for longs: use for sizing
console.log(ticker.capacityShort); // Optional JIT-aware TradingCapacity for shorts: use for sizing
// Fetch validated capacity for one market side directly
const longCapacity = await sdk.getTradingCapacity({
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
});
console.log(longCapacity.availableLiquidity); // 30-decimal USD bigint
console.log(longCapacity.limitingFactor); // "reserve", "openInterest", "both", or "notApplicable"
console.log(longCapacity.jitDataStatus); // "available", "stale", or "unavailable"
```
### Cache market configuration and values separately
Use the split endpoints when your application can refresh slower-changing configuration independently from frequently changing market state:
```typescript
const marketConfigs = await sdk.fetchMarketsConfig();
const marketValues = await sdk.fetchMarketsValues();
const ethConfig = marketConfigs.find(
(market) =>
market.marketTokenAddress.toLowerCase() ===
"0x70d95587d40A2caf56bd97485aB3Eec10Bee6336".toLowerCase()
);
const ethValues = marketValues.find(
(market) =>
market.marketTokenAddress.toLowerCase() ===
ethConfig?.marketTokenAddress.toLowerCase()
);
console.log(ethConfig?.maxCollateralSumLongTokenLong);
console.log(ethConfig?.minFundingIncreaseRatePerSecond);
console.log(ethValues?.virtualInventoryForPositionsInTokens);
console.log(ethValues?.updatedAt); // Unix time in milliseconds, or null
```
`updatedAt` represents the least-recent component included in that values row. Apply your own freshness limit and handle `null` explicitly.
### Get token info
```typescript
// Static token catalog (symbols, decimals, addresses)
const tokens = await sdk.fetchTokens();
// Token metadata with current prices
const tokensData = await sdk.fetchTokensData();
```
### Read positions and orders
```typescript
// Current positions for an account
const positions = await sdk.fetchPositionsInfo({ address: account });
for (const p of positions) {
console.log(p.indexName); // "ETH/USD"
console.log(p.isLong); // true or false
console.log(p.sizeInUsd); // Position size (30-decimal bigint)
console.log(p.positionValueInUsd); // Position value (30-decimal bigint)
console.log(p.collateralUsd); // Collateral value
console.log(p.marketAddress); // Market address
}
// Positions with their related TP/SL orders
const positionsWithOrders = await sdk.fetchPositionsInfo({
address: account,
includeRelatedOrders: true,
});
// Active orders
const orders = await sdk.fetchOrders({ address: account });
for (const o of orders) {
console.log(o.key); // Order key (used for edit/cancel)
console.log(o.isLong);
console.log(o.sizeDeltaUsd); // Size delta (30-decimal bigint)
console.log(o.triggerPrice); // Trigger price for limit/conditional orders
console.log(o.executionFee);
}
```
### Check wallet balances and allowances
```typescript
const balances = await sdk.fetchWalletBalances({ address: account });
const allowances = await sdk.fetchAllowances({
address: account,
spender: "router",
});
// Build an ERC-20 approval if needed
const approveTx = sdk.buildApproveTransaction({
tokenAddress: "0xaf88d065e77c8cC2239327C5EDb3A432268e5831", // USDC on Arbitrum
spender: "router",
amount: 1_000_000_000n, // 1000 USDC
});
// approveTx.to, approveTx.data — send via your wallet
```
## Express orders — three-step flow
Express orders use the API relay (GMX Relay). The flow is: **prepare** → **sign** → **submit**.
### 1. Prepare
```typescript
const prepared = await sdk.prepareOrder({
kind: "increase",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "market",
size: 10n * 10n ** 30n, // $10 (30 decimals)
collateralToken: "USDC",
collateralToPay: { amount: 1_000_000n, token: "USDC" }, // 1 USDC (6 decimals)
mode: "express",
from: account,
});
// prepared.payloadType === "typed-data"
// prepared.estimates contains fee and price impact data
console.log(prepared.estimates);
// {
// sizeDeltaUsd: 10000000000000000000000000000000n,
// executionFeeAmount: ...,
// positionFeeUsd: ...,
// acceptablePrice: ...,
// swapPriceImpactDeltaUsd: ...,
// positionPriceImpactDeltaUsd: ...,
// borrowingFeeUsd: ...,
// fundingFeeUsd: ...,
// }
```
### 2. Sign
```typescript
const signature = await sdk.signOrder(prepared, signer);
```
### 3. Submit
```typescript
const submitted = await sdk.submitOrder({
mode: prepared.mode,
requestId: prepared.requestId,
signature,
from: account,
idempotencyKey: prepared.idempotencyKey,
eip712Data: {
batchParams: prepared.payload.batchParams,
relayParams: prepared.payload.relayParams,
},
});
console.log(submitted.requestId); // Use this to track the order
console.log(submitted.status); // "relay_accepted", "relay_pending", etc.
```
### Referral codes and UI fee receivers
Order prepare requests can include optional attribution fields:
```typescript
const prepared = await sdk.prepareOrder({
kind: "increase",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "market",
size: 10n * 10n ** 30n,
collateralToken: "USDC",
collateralToPay: { amount: 1_000_000n, token: "USDC" },
mode: "express",
from: account,
referralCode: "YourReferralCode",
uiFeeReceiver: "0x1234567890123456789012345678901234567890",
});
```
`referralCode` may be either the human-readable registered referral code, such as `"YourReferralCode"`, or an already encoded `bytes32` value. Human-readable codes can contain letters, digits, and underscores, and can be up to 20 characters long. The GMX API encodes human-readable codes before building the order payload.
Use `uiFeeReceiver` for custom UI fee attribution. The receiver must be a valid address and should have its UI fee factor configured on-chain. The prepared Express order keeps the same receiver address, including on every part of a TWAP order; register and claim UI fees from that original receiver. The API stores TWAP grouping metadata separately in each part's `dataList`.
## Express orders — one-call convenience
`executeExpressOrder` runs prepare + sign + submit in a single call:
```typescript
const result = await sdk.executeExpressOrder(
{
kind: "increase",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "market",
size: 10n * 10n ** 30n,
collateralToken: "USDC",
collateralToPay: { amount: 1_000_000n, token: "USDC" },
mode: "express",
from: account,
},
signer
);
console.log(result.requestId);
```
## Tracking order status
Poll `fetchOrderStatus` with the `requestId` returned from submission:
```typescript
const status = await sdk.fetchOrderStatus({
requestId: submitted.requestId,
});
console.log(status.status);
// Possible values:
// "prepared" | "relay_accepted" | "relay_pending" | "relay_submitted"
// | "created" | "executed" | "cancelled" | "relay_failed" | "relay_reverted"
// Terminal statuses: "executed", "cancelled", "relay_failed", "relay_reverted"
```
Polling loop example:
```typescript
async function waitForExecution(sdk, requestId, timeoutMs = 60_000) {
const terminal = new Set(["executed", "cancelled", "relay_failed", "relay_reverted"]);
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const status = await sdk.fetchOrderStatus({ requestId });
if (terminal.has(status.status)) return status;
await new Promise((r) => setTimeout(r, 2000));
}
throw new Error(`Order ${requestId} did not reach terminal status within ${timeoutMs}ms`);
}
const finalStatus = await waitForExecution(sdk, result.requestId);
// finalStatus.executionTxnHash — on-chain execution tx
// finalStatus.orderKeys — created order keys
// finalStatus.error — error details if failed
```
## 프로젝트로 돌아가기