bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 45쪽 중 21쪽
Market increase (open / add to position)
### Long
```typescript
await sdk.executeExpressOrder(
{
kind: "increase",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "market",
size: 100n * 10n ** 30n, // $100
collateralToken: "USDC",
collateralToPay: { amount: 10_000_000n, token: "USDC" }, // 10 USDC
mode: "express",
from: account,
},
signer
);
```
### Short
```typescript
await sdk.executeExpressOrder(
{
kind: "increase",
symbol: "ETH/USD [WETH-USDC]",
direction: "short",
orderType: "market",
size: 100n * 10n ** 30n,
collateralToken: "USDC",
collateralToPay: { amount: 10_000_000n, token: "USDC" },
mode: "express",
from: account,
},
signer
);
```
## Limit increase
Set `triggerPrice` for the entry price. The order stays open until the price is reached.
`triggerPrice` is passed to the SDK as a 30-decimal USD price. If you inspect the created order on-chain, the stored value is converted to contract price format:
```typescript
contractPrice = triggerPrice / 10n ** BigInt(indexTokenDecimals);
```
For example, DOGE has 8 decimals, so a `$0.04` trigger price is passed to the SDK as `40000000000000000000000000000n` but appears in raw order data as `400000000000000000000n`.
```typescript
const result = await sdk.executeExpressOrder(
{
kind: "increase",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "limit",
size: 10n * 10n ** 30n,
triggerPrice: 2000n * 10n ** 30n, // $2,000 entry
collateralToken: "USDC",
collateralToPay: { amount: 1_000_000n, token: "USDC" },
mode: "express",
from: account,
},
signer
);
// The order is created on-chain; verify it appears in your orders list
const orders = await sdk.fetchOrders({ address: account });
```
## Market decrease (close / reduce position)
The API calculates the effective decrease size during prepare. It can convert a requested partial decrease into a full close when leaving the residual open would violate the close checks described below.
### Partial close
```typescript
// Get current position size
const positions = await sdk.fetchPositionsInfo({ address: account });
const ethLong = positions.find((p) => p.isLong && p.indexName?.includes("ETH/USD"));
const currentSize = BigInt(ethLong.sizeInUsd);
await sdk.executeExpressOrder(
{
kind: "decrease",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "market",
size: currentSize / 2n, // Close half
collateralToken: "USDC",
receiveToken: "USDC",
mode: "express",
from: account,
},
signer
);
```
### Full close
```typescript
await sdk.executeExpressOrder(
{
kind: "decrease",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "market",
size: currentSize, // Close entire position
collateralToken: "USDC",
receiveToken: "USDC",
mode: "express",
from: account,
},
signer
);
```
Inspect `prepared.estimates.sizeDeltaUsd` when you use the three-step flow. It contains the effective size after close validation and can be the full position size even when you requested less. The API snaps to a full close when the remaining position would be less than `1` USD. For a losing position whose remaining collateral would not satisfy leverage requirements, it also snaps when the residual would be below the minimum collateral or minimum position size.
### keepLeverage
When decreasing, `keepLeverage` controls whether collateral is withdrawn proportionally:
```typescript
// keepLeverage: true — removes collateral proportionally, preserving leverage ratio
await sdk.executeExpressOrder(
{
kind: "decrease",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "market",
size: currentSize / 5n,
keepLeverage: true,
collateralToken: "USDC",
receiveToken: "USDC",
mode: "express",
from: account,
},
signer
);
// keepLeverage: false — keeps collateral, reducing leverage
```
### receiveToken
Choose which token to receive when closing:
```typescript
await sdk.executeExpressOrder(
{
kind: "decrease",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "market",
size: currentSize,
collateralToken: "USDC",
receiveToken: "ETH", // Receive ETH instead of USDC
mode: "express",
from: account,
},
signer
);
```
## Conditional decrease (stop-loss / take-profit)
### Stop-loss
```typescript
const result = await sdk.executeExpressOrder(
{
kind: "decrease",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "stop-loss",
size: 10n * 10n ** 30n,
triggerPrice: 1800n * 10n ** 30n, // Trigger at $1,800
collateralToken: "USDC",
receiveToken: "USDC",
mode: "express",
from: account,
},
signer
);
```
### Take-profit
```typescript
const result = await sdk.executeExpressOrder(
{
kind: "decrease",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "take-profit",
size: 10n * 10n ** 30n,
triggerPrice: 5000n * 10n ** 30n, // Trigger at $5,000
collateralToken: "USDC",
receiveToken: "USDC",
mode: "express",
from: account,
},
signer
);
```
## TP/SL with position entry
Attach take-profit and stop-loss orders when opening a position using `tpsl`:
```typescript
// Get current mark price for TP/SL calculation
const tickers = await sdk.fetchMarketsTickers({ symbols: ["ETH/USD [WETH-USDC]"] });
const markPrice = BigInt(tickers[0].maxPrice);
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,
tpsl: [
{ type: "take-profit", triggerPrice: markPrice * 105n / 100n, size: 10n * 10n ** 30n },
{ type: "stop-loss", triggerPrice: markPrice * 95n / 100n, size: 10n * 10n ** 30n },
],
},
signer
);
```
`tpsl` supports partial-size TP/SL — omit `size` to use the full position size. `tpsl` is only valid on `increase` orders with `market` or `limit` order types. It cannot be used with `twap`, `decrease`, or `swap` orders.
## Swap orders
```typescript
await sdk.executeExpressOrder(
{
kind: "swap",
symbol: "ETH/USD [WETH-USDC]",
orderType: "market",
size: 1_000_000n, // 1 USDC (token decimals)
collateralToPay: { amount: 1_000_000n, token: "USDC" },
receiveToken: "ETH",
mode: "express",
from: account,
},
signer
);
```
## TWAP orders
Split a large order into multiple parts executed over time:
```typescript
await sdk.executeExpressOrder(
{
kind: "increase",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "twap",
size: 20n * 10n ** 30n, // $20 total
collateralToken: "USDC",
collateralToPay: { amount: 3_000_000n, token: "USDC" },
twapConfig: { duration: 600, parts: 2 }, // 2 parts over 10 minutes
mode: "express",
from: account,
},
signer
);
```
`twapConfig.parts` must be a safe integer between 2 and 30 inclusive. `twapConfig.duration` must be greater than 0, and `twapConfig` is only valid when `orderType` is `"twap"`. TWAP cannot be combined with `tpsl`.
The API applies full-close adjustment before it splits a decrease into parts, so each part is derived from the effective `OrderEstimates.sizeDeltaUsd`. It also copies the requested `uiFeeReceiver` to every part and prepends request and TWAP grouping metadata to each part's `dataList`.
## Edit orders
Change the trigger price (or size) of an existing limit/conditional order:
```typescript
const orders = await sdk.fetchOrders({ address: account });
const orderId = orders[0].key;
const prepared = await sdk.prepareEditOrder({
orderIds: [orderId],
newTriggerPrice: 2500n * 10n ** 30n, // New trigger: $2,500
mode: "express",
from: account,
});
const signature = await sdk.signOrder(prepared, signer);
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,
},
});
```
`prepareEditOrder` accepts `newSize`, `newTriggerPrice`, `newAcceptablePrice`, `newAutoCancel`, and `executionFeeTopUp`.
## Cancel orders
### Cancel specific orders
```typescript
const orders = await sdk.fetchOrders({ address: account });
const orderId = orders[0].key;
const prepared = await sdk.prepareCancelOrder({
orderIds: [orderId],
mode: "express",
from: account,
});
const signature = await sdk.signOrder(prepared, signer);
await sdk.submitOrder({
mode: prepared.mode,
requestId: prepared.requestId,
signature,
from: account,
idempotencyKey: prepared.idempotencyKey,
eip712Data: {
batchParams: prepared.payload.batchParams,
relayParams: prepared.payload.relayParams,
},
});
```
### Cancel all orders
```typescript
const prepared = await sdk.prepareCancelOrder({
all: true,
mode: "express",
from: account,
});
const signature = await sdk.signOrder(prepared, signer);
await sdk.submitOrder({
mode: prepared.mode,
requestId: prepared.requestId,
signature,
from: account,
idempotencyKey: prepared.idempotencyKey,
eip712Data: {
batchParams: prepared.payload.batchParams,
relayParams: prepared.payload.relayParams,
},
});
```
## Classic mode (on-chain transactions)
Classic mode returns raw transaction calldata instead of typed data. You sign and broadcast the transaction yourself — no relay is involved.
:::note
The SDK v2 Classic Trading path doesn't use the delegated subaccount routers. The prepared `ExchangeRouter` transaction calls `sendTokens()`, which makes the underlying `Router` pull ERC-20 collateral from the transaction sender. A transaction broadcast by a subaccount therefore uses that subaccount's balance and allowance; an allowance granted by the main account doesn't apply. Use the Express Trading subaccount flow when a delegated signer must create an order that spends the main account's collateral.
:::
```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: "classic",
from: account,
});
// prepared.payloadType === "transaction"
// prepared.payload.to — contract address
// prepared.payload.data — calldata
// prepared.payload.value — ETH value (execution fee)
// Send with your wallet / viem / ethers:
const txHash = await signer.sendTransaction({
to: prepared.payload.to,
data: prepared.payload.data,
value: BigInt(prepared.payload.value ?? 0),
});
```
`PrivateKeySigner.sendTransaction` requires `rpcUrl` in the constructor:
```typescript
const signer = new PrivateKeySigner("0xYOUR_PRIVATE_KEY", {
rpcUrl: "https://arb1.arbitrum.io/rpc",
chain: getViemChain(42161),
});
```
## Slippage and execution fee buffer
### Slippage
Controls the acceptable price deviation in basis points (default varies by order type). Higher slippage widens the acceptable price range without affecting size or fee estimates.
```typescript
const prepared = await sdk.prepareOrder({
kind: "increase",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "market",
size: 10n * 10n ** 30n,
collateralToPay: { amount: 1_000_000n, token: "USDC" },
slippage: 30, // 0.3% (in basis points)
mode: "express",
from: account,
});
```
### Execution fee buffer
Adds a buffer to the execution fee in basis points. Higher buffer reduces the chance of order failure due to gas spikes.
```typescript
const prepared = await sdk.prepareOrder({
kind: "increase",
symbol: "ETH/USD [WETH-USDC]",
direction: "long",
orderType: "market",
size: 10n * 10n ** 30n,
collateralToPay: { amount: 1_000_000n, token: "USDC" },
executionFeeBufferBps: 5000, // 50% buffer
mode: "express",
from: account,
});
```
## One-click trading (subaccounts)
Subaccounts let you sign orders with a delegated key, avoiding wallet popups for each trade. The SDK can generate and manage this key, or you can supply an independently generated signer. The main account authorizes delegated access, while the subaccount signs each order.
### Quick setup
```typescript
// Generate a local subaccount signer, refresh its on-chain status, and sign
// a SubaccountApproval only if the current on-chain authorization is not enough.
const subaccountAddress = await sdk.activateSubaccount(signer, {
expiresInSeconds: 86400, // 24 hours
maxAllowedCount: 100, // Max 100 actions
});
console.log(sdk.subaccountAddress); // "0x..."
console.log(sdk.subaccountStatus?.remainingActions);
console.log(sdk.hasActiveSubaccount); // true
console.log(sdk.subaccountApprovalMessage?.signature);
// Non-empty signature: the next subaccount order will submit this approval.
// "0x": the subaccount is already active on-chain and no new owner approval is needed.
```
### Submit orders with subaccount
Once activated, `executeExpressOrder` automatically attaches the current subaccount approval and uses the subaccount signer for the order:
```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, // Main account address
},
signer // Main signer identifies the account; SDK signs with subaccount internally
);
```
If the order submitted a fresh approval, wait until the order is created or executed, then refresh the subaccount state before preparing another subaccount order:
```typescript
let status = await sdk.fetchOrderStatus({
requestId: result.requestId,
});
while (!["created", "executed", "cancelled", "relay_failed", "relay_reverted"].includes(status.status)) {
await new Promise((r) => setTimeout(r, 2000));
status = await sdk.fetchOrderStatus({ requestId: result.requestId });
}
if (status.status === "created" || status.status === "executed") {
await sdk.refreshSubaccountState(account);
}
console.log(sdk.subaccountApprovalMessage?.signature); // "0x" after the approval is usable on-chain
```
### Manual subaccount flow
For more control, use the explicit prepare, sign, and submit flow. If the SDK has active subaccount state, `prepareOrder()` attaches the current subaccount address and approval, `signOrder()` uses the subaccount signer, and `submitOrder()` forwards the approval that belongs to the prepared request:
```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,
});
const signature = await sdk.signOrder(prepared, signer);
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,
},
});
```
### Use an externally managed subaccount
An independently generated subaccount doesn't need to come from `generateSubaccount()` or the GMX Interface. If it is already authorized on-chain for `SUBACCOUNT_ORDER_ACTION`, create an empty approval with `getEmptySubaccountApproval()`. Its `"0x"` signature tells the relay router to use the existing on-chain authorization rather than apply a new owner-signed approval.
Pass both `subaccountAddress` and `subaccountApproval` to `prepareOrder()`. Passing only `subaccountAddress` doesn't bind the main account to a subaccount approval hash, so the prepared typed data contains the zero address in `message.account`.
The high-level `sdk.signOrder()` helper selects a subaccount signer only when the same `GmxApiSdk` instance generated and stored that signer. For an external signer, use `signPreparedOrder()`, pass the main account as `accountAddress`, and include the same `subaccountApproval` in the submit request:
```typescript
const chainId = 42161;
const subaccountSigner = new PrivateKeySigner("0xYOUR_SUBACCOUNT_PRIVATE_KEY");
const subaccountAddress = subaccountSigner.address;
const subaccountApproval = getEmptySubaccountApproval(chainId, subaccountAddress);
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, // Main account address
subaccountAddress,
subaccountApproval,
});
const signature = await signPreparedOrder(
prepared,
subaccountSigner,
chainId,
account, // Main account address
);
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,
subaccountApproval,
},
});
```
Before using an empty approval, confirm that the subaccount is active, its expiry is in the future, and its remaining action count is greater than zero. Generate and store externally managed keys within your own custody boundary instead of extracting the browser-local key from the GMX Interface. See [Delegated trading integration](../../api/contracts/delegated-trading.md) for authorization, key custody, monitoring, and revocation guidance.
### Step-by-step setup
```typescript
// 1. Generate subaccount (deterministic from main signer)
const subAddr = await sdk.generateSubaccount(signer);
// 2. Refresh SDK-managed on-chain status
const status = await sdk.refreshSubaccountState(signer.address);
// 3. Activate with custom limits
await sdk.activateSubaccount(signer, {
expiresInSeconds: 86400,
maxAllowedCount: (status?.currentActionsCount ?? 0n) + 50n,
});
// 4. Refresh after an approval-bearing order is created or executed
await sdk.refreshSubaccountState(signer.address);
// 5. Clear when done or when the connected wallet account changes
sdk.clearSubaccount();
```
## Collateral management
Deposit or withdraw collateral on an existing position using `prepareCollateral`:
```typescript
const prepared = await sdk.prepareCollateral({
operation: "deposit", // or "withdraw"
positionKey: "0x...", // Position key from fetchPositionsInfo
amount: 5_000_000n, // 5 USDC (token decimals)
mode: "express",
from: account,
});
const signature = await sdk.signOrder(prepared, signer);
await sdk.submitOrder({
mode: prepared.mode,
requestId: prepared.requestId,
signature,
from: account,
idempotencyKey: prepared.idempotencyKey,
eip712Data: {
batchParams: prepared.payload.batchParams,
relayParams: prepared.payload.relayParams,
},
});
```
`prepareCollateral` also accepts optional `slippage`, `executionFeeBufferBps`, and `gasPaymentToken` parameters.
## GMX Account operations
GMX Account helpers are available in `@gmx-io/sdk/v2`. Same-chain operations return or submit wallet transactions on the settlement chain. Cross-chain deposits prepare source-chain transactions. Cross-chain withdrawals prepare typed data and submit through the relayer API.
### Setup
```typescript
const sdk = new GmxApiSdk({ chainId: ARBITRUM });
const signer = new PrivateKeySigner(process.env.PRIVATE_KEY as `0x${string}`, {
rpcUrl: process.env.ARBITRUM_RPC_URL,
chain: getViemChain(ARBITRUM),
});
const sourceSigner = new PrivateKeySigner(process.env.PRIVATE_KEY as `0x${string}`, {
rpcUrl: process.env.BASE_RPC_URL,
chain: getViemChain(SOURCE_BASE_MAINNET),
});
const account = signer.address;
const tokenGroups = getMultichainTokenGroups();
const arbitrumUsdc = resolveStargatePool(tokenGroups, { chainId: ARBITRUM, tokenSymbol: "USDC" });
const baseUsdc = resolveStargatePool(tokenGroups, { chainId: SOURCE_BASE_MAINNET, tokenSymbol: "USDC" });
if (!arbitrumUsdc || !baseUsdc) {
throw new Error("USDC is not configured for the selected chains");
}
```
### Same-chain deposit and w프로젝트로 돌아가기