[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6GQS0N7KDP2JYKBQ85A5AH5":3,"skill-same:01M6GQS0N7KDP2JYKBQ85A5AH5":103},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":39,"linkOnly":40,"markdownContent":41,"markdownBody":42,"frontMatter":43,"refName":55,"commitSha":56,"skillDirectory":57,"forksCount":58,"repositoryHtmlUrl":59,"repositoryHomepageUrl":6,"ownerHtmlUrl":60,"ownerBlogUrl":61,"ownerDescription":62,"updatedAt":63,"install":64,"resources":76},"01M6GQS0N7KDP2JYKBQ85A5AH5","gmx-trading",null,"Trade perpetuals and swap tokens on GMX V2 — a decentralized exchange with oracle-based pricing on Arbitrum, Avalanche, and Botanix. Supports market\u002Flimit\u002Fstop orders, leverage up to 100x, and programmable position management via TypeScript SDK or REST API.","jiayaoqijia\u002Fcryptoskill","jiayaoqijia","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F1453879?v=4","01M6GMYTX7Q7S504VC6E756ENR","YQ","01M6GMYV1QKJ1CC75MTTGT9PR0",81,"MIT","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fdefi\u002Fgmx-official-trading\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38],"gmx trading","trading","arbitrum","true","limit","io","avalanche","decentralized","leverage","tokens","perpetuals","typescript","orders","stop","Market","up","api","defi","pricing","oracle","2026-11-10 10:12:30",false,"---\nname: gmx-trading\ndescription: \"Trade perpetuals and swap tokens on GMX V2 — a decentralized exchange with oracle-based pricing on Arbitrum, Avalanche, and Botanix. Supports market\u002Flimit\u002Fstop orders, leverage up to 100x, and programmable position management via TypeScript SDK or REST API.\"\nlicense: MIT\nmetadata:\n  author: gmx-io\n  version: \"0.2.1\"\n  chains: \"arbitrum, avalanche, botanix\"\n  openclaw:\n    tags: [gmx, perpetuals, trading, swap, defi, arbitrum, avalanche, leverage, derivatives]\n    official: true\n    source: \"https:\u002F\u002Fgithub.com\u002Fgmx-io\u002Fgmx-ai\"\n---\n\n# GMX Trading Skill\n\n## Overview\n\nGMX V2 is a decentralized perpetual and spot exchange using oracle-based pricing (Chainlink Data Streams) instead of AMM curves. Traders get CEX-like execution with onchain settlement.\n\n**Supported chains:**\n| Chain | Chain ID | Native Token |\n|-------|----------|-------------|\n| Arbitrum | 42161 | ETH |\n| Avalanche | 43114 | AVAX |\n| Botanix | 3637 | BTC |\n\n**Two integration paths:**\n- **SDK** (`@gmx-io\u002Fsdk`) — Full read + write: fetch markets, create orders, manage positions\n- **REST API** — Read-only: prices, markets, positions, trade history\n\n**Trading modes:**\n- **Classic** — User signs each transaction directly\n- **Express** — Gelato relay pays gas, user signs EIP-712 message (frontend only)\n- **Express + One-Click** — Subaccount delegates signing for instant execution (frontend only)\n\n## SDK Quick Start\n\nInstall the SDK:\n\n```bash\nnpm install @gmx-io\u002Fsdk viem\n```\n\n> **Import note:** The SDK's ESM build has broken imports (missing file extensions). Use CommonJS require or configure your bundler to resolve extensionless imports. In Node.js scripts, use `const { GmxSdk } = require(\"@gmx-io\u002Fsdk\")`.\n\nCreate an SDK instance:\n\n```typescript\nconst { GmxSdk } = require(\"@gmx-io\u002Fsdk\");\n\nconst sdk = new GmxSdk({\n  chainId: 42161,\n  rpcUrl: \"https:\u002F\u002Farb1.arbitrum.io\u002Frpc\",\n  oracleUrl: \"https:\u002F\u002Farbitrum-api.gmxinfra.io\",\n  subsquidUrl: \"https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-arbitrum:prod\u002Fapi\u002Fgraphql\",\n});\n```\n\n**Chain configuration:**\n\n| Chain | chainId | oracleUrl | subsquidUrl |\n|-------|---------|-----------|-------------|\n| Arbitrum | 42161 | `https:\u002F\u002Farbitrum-api.gmxinfra.io` | `https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-arbitrum:prod\u002Fapi\u002Fgraphql` |\n| Avalanche | 43114 | `https:\u002F\u002Favalanche-api.gmxinfra.io` | `https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-avalanche:prod\u002Fapi\u002Fgraphql` |\n| Botanix | 3637 | `https:\u002F\u002Fbotanix-api.gmxinfra.io` | `https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-botanix:prod\u002Fapi\u002Fgraphql` |\n\n**Set up a wallet for write operations:**\n\n```typescript\nconst { createWalletClient, http } = require(\"viem\");\nconst { privateKeyToAccount } = require(\"viem\u002Faccounts\");\nconst { arbitrum } = require(\"viem\u002Fchains\");\n\nconst account = privateKeyToAccount(process.env.PRIVATE_KEY);\nconst walletClient = createWalletClient({\n  account,\n  chain: arbitrum,\n  transport: http(\"https:\u002F\u002Farb1.arbitrum.io\u002Frpc\"),\n});\n\nconst sdk = new GmxSdk({\n  chainId: 42161,\n  rpcUrl: \"https:\u002F\u002Farb1.arbitrum.io\u002Frpc\",\n  oracleUrl: \"https:\u002F\u002Farbitrum-api.gmxinfra.io\",\n  subsquidUrl: \"https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-arbitrum:prod\u002Fapi\u002Fgraphql\",\n  account: account.address,\n  walletClient,\n});\n```\n\n**Lightweight alternative (read-only, no RPC needed):**\n\n```typescript\nconst { GmxApiSdk } = require(\"@gmx-io\u002Fsdk\u002Fv2\");\n\nconst apiSdk = new GmxApiSdk({ chainId: 42161 });\nconst markets = await apiSdk.fetchMarketsInfo(); \u002F\u002F Returns array-like of MarketInfo objects\n\u002F\u002F Access: markets[0].marketTokenAddress, markets[0].indexTokenAddress, etc.\n```\n\n## Order Helpers\n\nThe SDK provides convenience methods that handle amount calculation and transaction submission automatically.\n\n> **Important:** Never hardcode market or token addresses. Always fetch them dynamically — addresses differ per chain and can change between deployments.\n\n### Step 1: Resolve market and token addresses\n\n```typescript\n\u002F\u002F Fetch all markets and tokens\nconst { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();\n\n\u002F\u002F Find ETH\u002FUSD market by index token symbol\n\u002F\u002F Note: On Arbitrum, perpetual markets use \"WETH\" as the index token symbol.\n\u002F\u002F Markets with symbol \"ETH\" are spot-only swap pools.\nconst ethUsdMarket = Object.values(marketsInfoData).find(\n  (m) => tokensData[m.indexTokenAddress]?.symbol === \"WETH\" && !m.isSpotOnly\n);\n\n\u002F\u002F Get token addresses from market\nconst marketAddress = ethUsdMarket.marketTokenAddress;\nconst longToken = ethUsdMarket.longTokenAddress;   \u002F\u002F e.g., WETH\nconst shortToken = ethUsdMarket.shortTokenAddress;  \u002F\u002F e.g., USDC\n\n\u002F\u002F Find a token by symbol\nconst usdcAddress = Object.values(tokensData).find((t) => t.symbol === \"USDC\")?.address;\n```\n\n### Step 2: Place orders\n\n**Open a long position:**\n\n```typescript\nawait sdk.orders.long({\n  marketAddress,                         \u002F\u002F from step 1\n  payTokenAddress: usdcAddress,          \u002F\u002F token you're paying with\n  collateralTokenAddress: longToken,     \u002F\u002F WETH as collateral for longs\n  payAmount: 100000000n,                 \u002F\u002F 100 USDC (6 decimals)\n  leverage: 50000n,                      \u002F\u002F 5x leverage (basis points)\n  allowedSlippageBps: 100,               \u002F\u002F 1% slippage\n});\n```\n\n**Open a short position:**\n\n```typescript\nawait sdk.orders.short({\n  marketAddress,\n  payTokenAddress: usdcAddress,\n  collateralTokenAddress: shortToken,    \u002F\u002F USDC as collateral for shorts\n  payAmount: 100000000n,\n  leverage: 50000n,\n});\n```\n\n**Swap tokens:**\n\n```typescript\nconst arbAddress = Object.values(tokensData).find((t) => t.symbol === \"ARB\")?.address;\nconst linkAddress = Object.values(tokensData).find((t) => t.symbol === \"LINK\")?.address;\n\nawait sdk.orders.swap({\n  fromTokenAddress: arbAddress,\n  toTokenAddress: linkAddress,\n  fromAmount: 1000000000000000000n, \u002F\u002F 1 ARB (18 decimals)\n  allowedSlippageBps: 100,\n});\n```\n\n**Limit orders** — add `limitPrice` for positions or `triggerPrice` for swaps:\n\n```typescript\nawait sdk.orders.long({\n  marketAddress,\n  payTokenAddress: usdcAddress,\n  collateralTokenAddress: longToken,\n  payAmount: 100000000n,\n  leverage: 50000n,\n  limitPrice: 3000000000000000000000000000000000n, \u002F\u002F $3000 (30 decimals)\n});\n```\n\n**Key parameters:**\n- `leverage` — In basis points: `10000n` = 1x, `50000n` = 5x, `1000000n` = 100x\n- `allowedSlippageBps` — Default `100` (1%). Range: 1-500\n- `payAmount` — Pay this much collateral. Alternative: use `sizeAmount` to specify position size\n- `fromAmount` \u002F `toAmount` — For swaps, specify input or desired output amount\n\n### Step 3: Close a position\n\nThere is no convenience `close()` method. Closing requires computing decrease amounts via `getDecreasePositionAmounts()` from `@gmx-io\u002Fsdk\u002Futils\u002Ftrade`, then calling `createDecreaseOrder()`.\n\n> **Important:** Always re-fetch `marketsInfoData` and `tokensData` right before closing. These contain oracle prices that go stale within seconds — using old data produces an `acceptablePrice` the keeper will reject.\n\n```typescript\nconst { getDecreasePositionAmounts } = require(\"@gmx-io\u002Fsdk\u002Futils\u002Ftrade\");\n\n\u002F\u002F 1. Fetch FRESH market data (prices go stale quickly)\nconst { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();\n\n\u002F\u002F 2. Get the position to close\nconst positionsInfo = await sdk.positions.getPositionsInfo({\n  marketsInfoData, tokensData, showPnlInLeverage: false,\n});\nconst position = Object.values(positionsInfo).find(\n  (p) => p.marketAddress === marketAddress && p.isLong === true\n);\n\n\u002F\u002F 3. Compute decrease amounts\nconst marketInfo = marketsInfoData[position.marketAddress];\nconst collateralToken = tokensData[position.collateralTokenAddress];\nconst { minCollateralUsd, minPositionSizeUsd } = await sdk.positions.getPositionsConstants();\nconst uiFeeFactor = await sdk.utils.getUiFeeFactor();\n\nconst decreaseAmounts = getDecreasePositionAmounts({\n  marketInfo,\n  collateralToken,\n  isLong: position.isLong,\n  position,\n  closeSizeUsd: position.sizeInUsd,   \u002F\u002F Full close. Use a smaller value for partial close.\n  keepLeverage: false,\n  userReferralInfo: undefined,\n  minCollateralUsd,\n  minPositionSizeUsd,\n  uiFeeFactor,\n  isSetAcceptablePriceImpactEnabled: false,\n});\n\n\u002F\u002F 4. Submit the decrease order\nawait sdk.orders.createDecreaseOrder({\n  marketInfo,\n  marketsInfoData,\n  tokensData,\n  isLong: position.isLong,\n  allowedSlippage: 300,    \u002F\u002F 3% — use higher slippage for decrease to avoid keeper rejection\n  decreaseAmounts,\n  collateralToken,\n});\n```\n\n## SDK Modules\n\n| Module | Key Methods | Description |\n|--------|------------|-------------|\n| `sdk.markets` | `getMarkets()`, `getMarketsInfo()`, `getDailyVolumes()` | Market data and liquidity info |\n| `sdk.tokens` | `getTokensData()`, `getTokensBalances()` | Token metadata, prices, balances |\n| `sdk.positions` | `getPositions()`, `getPositionsInfo()`, `getPositionsConstants()` | Open position data |\n| `sdk.orders` | `long()`, `short()`, `swap()`, `getOrders()`, `cancelOrders()` | Order creation and management |\n| `sdk.trades` | `getTradeHistory()` | Historical trade actions |\n| `sdk.utils` | `getGasLimits()`, `getGasPrice()`, `getExecutionFee()`, `getUiFeeFactor()` | Gas and fee estimation |\n| `sdk.oracle` | `getTickers()`, `getMarkets()`, `getTokens()` | Direct oracle data access |\n\n**Typical read flow:**\n\n```typescript\nconst { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();\nconst positionsInfo = await sdk.positions.getPositionsInfo({\n  marketsInfoData, tokensData, showPnlInLeverage: false,\n});\nconst { ordersInfoData } = await sdk.orders.getOrders({\n  marketsInfoData, tokensData,\n});\n```\n\n### Convenience vs Low-level Methods\n\nThe SDK has two tiers for order creation:\n\n**Convenience methods** — handle amount calculation, execution fee, and tx submission automatically. Use these for opening positions and swaps:\n\n| Method | Purpose | Key Params |\n|--------|---------|-----------|\n| `sdk.orders.long()` | Open long position | `marketAddress`, `payTokenAddress`, `collateralTokenAddress`, `payAmount`, `leverage` |\n| `sdk.orders.short()` | Open short position | Same as `long()` |\n| `sdk.orders.swap()` | Swap tokens | `fromTokenAddress`, `toTokenAddress`, `fromAmount` |\n| `sdk.orders.cancelOrders()` | Cancel pending orders | `orderKeys: string[]` |\n\n**Low-level methods** — require you to pre-compute amounts, provide full market\u002Ftoken objects, and handle execution fees. Required for closing positions (no convenience `close()` method exists):\n\n| Method | Purpose | Required Setup |\n|--------|---------|---------------|\n| `sdk.orders.createIncreaseOrder()` | Open position (full control) | `IncreasePositionAmounts`, `marketInfo`, `tokensData` |\n| `sdk.orders.createDecreaseOrder()` | Close\u002Freduce position | `DecreasePositionAmounts` via `getDecreasePositionAmounts()` |\n| `sdk.orders.createSwapOrder()` | Swap (full control) | `SwapAmounts`, swap path |\n\n> **Key gap:** There is no `sdk.orders.close()`. To close a position, use `getDecreasePositionAmounts()` from `@gmx-io\u002Fsdk\u002Futils\u002Ftrade` + `createDecreaseOrder()`. See [Step 3: Close a position](#step-3-close-a-position) for the full pattern.\n\n## Order Types\n\n| Type | Enum | Behavior |\n|------|------|----------|\n| Market | `MarketSwap(0)`, `MarketIncrease(2)`, `MarketDecrease(4)` | Execute immediately at current oracle price |\n| Limit | `LimitSwap(1)`, `LimitIncrease(3)`, `LimitDecrease(5)` | Execute when oracle price reaches trigger price |\n| Stop Increase | `StopIncrease(8)` | Open position when price moves past trigger (breakout entry) |\n| Stop-Loss | `StopLossDecrease(6)` | Auto-close position to limit losses |\n| Liquidation | `Liquidation(7)` | System-triggered when position falls below maintenance margin |\n\n**Trigger conditions:**\n- Long Limit: oracle price \u003C= trigger price (buy the dip)\n- Long Stop-Loss: oracle price \u003C= trigger price (exit on drop)\n- Long Take-Profit (LimitDecrease): oracle price >= trigger price (exit on rise)\n- Short Limit: oracle price >= trigger price (sell the rally)\n- Short Stop-Loss: oracle price >= trigger price (exit on rise)\n- Short Take-Profit (LimitDecrease): oracle price \u003C= trigger price (exit on drop)\n\n**Auto-cancel limits:** Maximum concurrent auto-cancel orders per position: 11 on Arbitrum, 6 on Avalanche and Botanix.\n\n**Sidecar orders:** Stop-loss and take-profit orders can be attached to increase orders via `createSltpEntries`, `cancelSltpEntries`, and `updateSltpEntries` parameters in `createIncreaseOrder()`.\n\n**TWAP orders:** Split a large order into 2–30 parts executed over a configurable duration. TWAP utilities (`getTwapDurationInSeconds`, `getIsValidTwapParams`) are exported from `@gmx-io\u002Fsdk\u002Futils\u002Ftwap` but full TWAP order creation is only available via the frontend UI.\n\n## Fees\n\n**Position fees:**\n- Opening\u002Fclosing: **0.04%** if the trade balances long\u002Fshort OI, **0.06%** if it imbalances\n- Applied to position size (notional value)\n\n**Swap fees:**\n- Standard pairs: **0.05%** (balancing) \u002F **0.07%** (imbalancing)\n- Stablecoin pairs: **0.005%** (balancing) \u002F **0.02%** (imbalancing)\n\n**Funding rate:**\n- Adaptive rate that flows from the larger open interest side to the smaller side\n- Rebalances long\u002Fshort exposure over time\n- Accrues continuously, settled on position changes\n\n**Borrowing rate:**\n- Kink model: low rate below utilization threshold, steep above\n- Approximately 45–55% APR at 75% utilization\n- Paid by all positions proportional to size\n\n**Execution fee:**\n- Covers keeper gas cost for executing the order onchain\n- Paid upfront in native token (ETH\u002FAVAX\u002FBTC)\n- Surplus refunded after execution\n- Use `sdk.utils.getExecutionFee()` to estimate\n\n## REST API\n\n### Oracle Endpoints\n\nBase URL: `https:\u002F\u002F{network}-api.gmxinfra.io`\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Fprices\u002Ftickers` | GET | Current min\u002Fmax prices for all tokens |\n| `\u002Fprices\u002Fcandles` | GET | OHLC price candles (`?tokenSymbol=ETH&period=1h`) |\n| `\u002Fsigned_prices\u002Flatest` | GET | Signed oracle prices for order execution |\n| `\u002Ftokens` | GET | Token list with addresses and decimals |\n| `\u002Fmarkets` | GET | Market configuration (index\u002Flong\u002Fshort tokens) |\n| `\u002Fmarkets\u002Finfo` | GET | Extended market info with pool sizes and utilization |\n\nAll endpoints are served from the Oracle base URL above. The legacy `gmx-api-{network}.gmx.io` domain is no longer available.\n\n### GraphQL (Subsquid)\n\nBase URL: `https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-{network}:prod\u002Fapi\u002Fgraphql`\n\nExample — fetch recent trade actions:\n\n```graphql\nquery {\n  tradeActions(\n    where: { account_eq: \"0x...\" }\n    orderBy: timestamp_DESC\n    limit: 10\n  ) {\n    id\n    eventName\n    orderType\n    sizeDeltaUsd\n    timestamp\n    transactionHash\n  }\n}\n```\n\n### Fallback URLs\n\n| Chain | Primary | Fallback 1 | Fallback 2 |\n|-------|---------|------------|------------|\n| Arbitrum | `arbitrum-api.gmxinfra.io` | `arbitrum-api-fallback.gmxinfra.io` | `arbitrum-api-fallback.gmxinfra2.io` |\n| Avalanche | `avalanche-api.gmxinfra.io` | `avalanche-api-fallback.gmxinfra.io` | `avalanche-api-fallback.gmxinfra2.io` |\n| Botanix | `botanix-api.gmxinfra.io` | `botanix-api-fallback.gmxinfra.io` | `botanix-api-fallback.gmxinfra2.io` |\n\n## Key Concepts\n\n**Oracle-based pricing:** GMX does not use an AMM. Prices come from Chainlink Data Streams, giving traders zero-slippage execution at the oracle price (subject to price impact from pool utilization).\n\n**Two-phase execution:** Orders follow a create → execute pattern. The user submits an order transaction, then a keeper executes it with fresh oracle prices. This typically takes 1–5 seconds.\n\n**BigInt amounts:** All amounts use BigInt. Prices are scaled to 30 decimals (`1 USD = 10^30`). Token amounts use their native decimals (e.g., USDC = 6, ETH = 18).\n\n**Stale data:** `marketsInfoData` and `tokensData` contain oracle prices at fetch time. These go stale within seconds. Always re-fetch fresh data before operations that depend on current prices — especially `createDecreaseOrder()`, which computes `acceptablePrice` from the data you provide. Using stale prices causes keeper rejection.\n\n**Multicall batching:** The SDK batches RPC calls automatically. Production chains use `batchSize: 1024 * 1024` bytes per multicall with no waiting. This is configured per-chain in `BATCH_CONFIGS`.\n\n**GMX Account:** Cross-chain trading from Ethereum, Base, or BNB Chain via LayerZero\u002FStargate bridge. Users can trade on Arbitrum\u002FAvalanche without bridging manually.\n\n**Subaccounts:** Delegate trading to a subaccount address for one-click trading. The subaccount can execute orders without requiring the main wallet signature each time.\n\n## Full Example: Open → Monitor → Close\n\nEnd-to-end flow that opens a long position, monitors it, and closes it.\n\n```typescript\nconst { GmxSdk } = require(\"@gmx-io\u002Fsdk\");\nconst { getDecreasePositionAmounts } = require(\"@gmx-io\u002Fsdk\u002Futils\u002Ftrade\");\nconst { createWalletClient, http } = require(\"viem\");\nconst { privateKeyToAccount } = require(\"viem\u002Faccounts\");\nconst { arbitrum } = require(\"viem\u002Fchains\");\n\n\u002F\u002F ─── Setup ───────────────────────────────────────────────────────────────────\n\nconst account = privateKeyToAccount(process.env.PRIVATE_KEY);\nconst sdk = new GmxSdk({\n  chainId: 42161,\n  rpcUrl: \"https:\u002F\u002Farb1.arbitrum.io\u002Frpc\",\n  oracleUrl: \"https:\u002F\u002Farbitrum-api.gmxinfra.io\",\n  subsquidUrl: \"https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-arbitrum:prod\u002Fapi\u002Fgraphql\",\n  account: account.address,\n  walletClient: createWalletClient({\n    account, chain: arbitrum, transport: http(\"https:\u002F\u002Farb1.arbitrum.io\u002Frpc\"),\n  }),\n});\n\n\u002F\u002F ─── 1. Resolve addresses ───────────────────────────────────────────────────\n\nconst { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();\n\nconst ethMarket = Object.values(marketsInfoData).find(\n  (m) => tokensData[m.indexTokenAddress]?.symbol === \"WETH\" && !m.isSpotOnly\n);\nconst marketAddress = ethMarket.marketTokenAddress;\nconst usdcAddress = Object.values(tokensData).find((t) => t.symbol === \"USDC\").address;\n\n\u002F\u002F ─── 2. Open long ───────────────────────────────────────────────────────────\n\nawait sdk.orders.long({\n  marketAddress,\n  payTokenAddress: usdcAddress,\n  collateralTokenAddress: usdcAddress,\n  payAmount: 10_000000n,   \u002F\u002F 10 USDC\n  leverage: 30000n,        \u002F\u002F 3x\n  allowedSlippageBps: 100,\n  skipSimulation: true,\n});\n\n\u002F\u002F ─── 3. Wait for position to appear (keeper executes in 1-30s) ──────────────\n\nlet position;\nfor (let i = 0; i \u003C 40; i++) {\n  await new Promise((r) => setTimeout(r, 3000));\n  const info = await sdk.positions.getPositionsInfo({\n    marketsInfoData, tokensData, showPnlInLeverage: false,\n  });\n  position = Object.values(info).find(\n    (p) => p.marketAddress === marketAddress && p.isLong === true\n  );\n  if (position) break;\n}\nif (!position) throw new Error(\"Position did not appear within 120s\");\n\nconsole.log(\"Position opened:\", {\n  sizeUsd: position.sizeInUsd.toString(),\n  leverage: position.leverage.toString(),\n  entryPrice: position.entryPrice.toString(),\n});\n\n\u002F\u002F ─── 4. Close position (re-fetch fresh data first!) ─────────────────────────\n\nconst fresh = await sdk.markets.getMarketsInfo();\nconst freshPositions = await sdk.positions.getPositionsInfo({\n  marketsInfoData: fresh.marketsInfoData,\n  tokensData: fresh.tokensData,\n  showPnlInLeverage: false,\n});\nconst pos = Object.values(freshPositions).find(\n  (p) => p.marketAddress === marketAddress && p.isLong === true\n);\n\nconst marketInfo = fresh.marketsInfoData[pos.marketAddress];\nconst collateralToken = fresh.tokensData[pos.collateralTokenAddress];\nconst { minCollateralUsd, minPositionSizeUsd } = await sdk.positions.getPositionsConstants();\nconst uiFeeFactor = await sdk.utils.getUiFeeFactor();\n\nconst decreaseAmounts = getDecreasePositionAmounts({\n  marketInfo, collateralToken, isLong: pos.isLong, position: pos,\n  closeSizeUsd: pos.sizeInUsd, keepLeverage: false,\n  userReferralInfo: undefined, minCollateralUsd, minPositionSizeUsd, uiFeeFactor,\n  isSetAcceptablePriceImpactEnabled: false,\n});\n\nawait sdk.orders.createDecreaseOrder({\n  marketInfo, marketsInfoData: fresh.marketsInfoData, tokensData: fresh.tokensData,\n  isLong: pos.isLong, allowedSlippage: 300, decreaseAmounts, collateralToken,\n});\n\nconsole.log(\"Close order submitted — keeper will execute in 1-30s\");\n```\n\n## Limitations\n\n- **GM pool deposits\u002Fwithdrawals:** See the [gmx-liquidity](..\u002Fgmx-official-liquidity\u002FSKILL.md) skill for contract-level operations. SDK convenience methods not yet available.\n- **GLV vault operations:** See the [gmx-liquidity](..\u002Fgmx-official-liquidity\u002FSKILL.md) skill for contract-level operations. SDK convenience methods not yet available.\n- **Express orders:** Frontend-only via Gelato relay. Not exposed in the SDK.\n- **TWAP orders:** Utility functions available (`@gmx-io\u002Fsdk\u002Futils\u002Ftwap`) but no SDK method to create TWAP orders programmatically.\n- **Order updates:** Orders cannot be modified. Cancel and recreate instead (`sdk.orders.cancelOrders()`).\n- **Trade simulation:** The `skipSimulation` parameter exists but simulation is deprecated. Set `skipSimulation: true`.\n\n## References\n\n- [SDK Reference](references\u002Fsdk-reference.md) — Full module and method documentation\n- [API Endpoints](references\u002Fapi-endpoints.md) — Oracle, OpenAPI, and GraphQL endpoint details\n- [Contract Addresses](references\u002Fcontract-addresses.md) — Deployed contracts per chain\n- [Order Types](references\u002Forder-types.md) — Detailed order type behavior and trigger logic\n- [GMX Documentation](https:\u002F\u002Fdocs.gmx.io) — Official protocol documentation\n- [GMX App](https:\u002F\u002Fapp.gmx.io) — Trading interface\n- [`@gmx-io\u002Fsdk` on npm](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@gmx-io\u002Fsdk) — SDK package\n- [gmx-io\u002Fgmx-interface](https:\u002F\u002Fgithub.com\u002Fgmx-io\u002Fgmx-interface) — Frontend source code\n","# GMX Trading Skill\n\n## Overview\n\nGMX V2 is a decentralized perpetual and spot exchange using oracle-based pricing (Chainlink Data Streams) instead of AMM curves. Traders get CEX-like execution with onchain settlement.\n\n**Supported chains:**\n| Chain | Chain ID | Native Token |\n|-------|----------|-------------|\n| Arbitrum | 42161 | ETH |\n| Avalanche | 43114 | AVAX |\n| Botanix | 3637 | BTC |\n\n**Two integration paths:**\n- **SDK** (`@gmx-io\u002Fsdk`) — Full read + write: fetch markets, create orders, manage positions\n- **REST API** — Read-only: prices, markets, positions, trade history\n\n**Trading modes:**\n- **Classic** — User signs each transaction directly\n- **Express** — Gelato relay pays gas, user signs EIP-712 message (frontend only)\n- **Express + One-Click** — Subaccount delegates signing for instant execution (frontend only)\n\n## SDK Quick Start\n\nInstall the SDK:\n\n```bash\nnpm install @gmx-io\u002Fsdk viem\n```\n\n> **Import note:** The SDK's ESM build has broken imports (missing file extensions). Use CommonJS require or configure your bundler to resolve extensionless imports. In Node.js scripts, use `const { GmxSdk } = require(\"@gmx-io\u002Fsdk\")`.\n\nCreate an SDK instance:\n\n```typescript\nconst { GmxSdk } = require(\"@gmx-io\u002Fsdk\");\n\nconst sdk = new GmxSdk({\n  chainId: 42161,\n  rpcUrl: \"https:\u002F\u002Farb1.arbitrum.io\u002Frpc\",\n  oracleUrl: \"https:\u002F\u002Farbitrum-api.gmxinfra.io\",\n  subsquidUrl: \"https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-arbitrum:prod\u002Fapi\u002Fgraphql\",\n});\n```\n\n**Chain configuration:**\n\n| Chain | chainId | oracleUrl | subsquidUrl |\n|-------|---------|-----------|-------------|\n| Arbitrum | 42161 | `https:\u002F\u002Farbitrum-api.gmxinfra.io` | `https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-arbitrum:prod\u002Fapi\u002Fgraphql` |\n| Avalanche | 43114 | `https:\u002F\u002Favalanche-api.gmxinfra.io` | `https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-avalanche:prod\u002Fapi\u002Fgraphql` |\n| Botanix | 3637 | `https:\u002F\u002Fbotanix-api.gmxinfra.io` | `https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-botanix:prod\u002Fapi\u002Fgraphql` |\n\n**Set up a wallet for write operations:**\n\n```typescript\nconst { createWalletClient, http } = require(\"viem\");\nconst { privateKeyToAccount } = require(\"viem\u002Faccounts\");\nconst { arbitrum } = require(\"viem\u002Fchains\");\n\nconst account = privateKeyToAccount(process.env.PRIVATE_KEY);\nconst walletClient = createWalletClient({\n  account,\n  chain: arbitrum,\n  transport: http(\"https:\u002F\u002Farb1.arbitrum.io\u002Frpc\"),\n});\n\nconst sdk = new GmxSdk({\n  chainId: 42161,\n  rpcUrl: \"https:\u002F\u002Farb1.arbitrum.io\u002Frpc\",\n  oracleUrl: \"https:\u002F\u002Farbitrum-api.gmxinfra.io\",\n  subsquidUrl: \"https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-arbitrum:prod\u002Fapi\u002Fgraphql\",\n  account: account.address,\n  walletClient,\n});\n```\n\n**Lightweight alternative (read-only, no RPC needed):**\n\n```typescript\nconst { GmxApiSdk } = require(\"@gmx-io\u002Fsdk\u002Fv2\");\n\nconst apiSdk = new GmxApiSdk({ chainId: 42161 });\nconst markets = await apiSdk.fetchMarketsInfo(); \u002F\u002F Returns array-like of MarketInfo objects\n\u002F\u002F Access: markets[0].marketTokenAddress, markets[0].indexTokenAddress, etc.\n```\n\n## Order Helpers\n\nThe SDK provides convenience methods that handle amount calculation and transaction submission automatically.\n\n> **Important:** Never hardcode market or token addresses. Always fetch them dynamically — addresses differ per chain and can change between deployments.\n\n### Step 1: Resolve market and token addresses\n\n```typescript\n\u002F\u002F Fetch all markets and tokens\nconst { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();\n\n\u002F\u002F Find ETH\u002FUSD market by index token symbol\n\u002F\u002F Note: On Arbitrum, perpetual markets use \"WETH\" as the index token symbol.\n\u002F\u002F Markets with symbol \"ETH\" are spot-only swap pools.\nconst ethUsdMarket = Object.values(marketsInfoData).find(\n  (m) => tokensData[m.indexTokenAddress]?.symbol === \"WETH\" && !m.isSpotOnly\n);\n\n\u002F\u002F Get token addresses from market\nconst marketAddress = ethUsdMarket.marketTokenAddress;\nconst longToken = ethUsdMarket.longTokenAddress;   \u002F\u002F e.g., WETH\nconst shortToken = ethUsdMarket.shortTokenAddress;  \u002F\u002F e.g., USDC\n\n\u002F\u002F Find a token by symbol\nconst usdcAddress = Object.values(tokensData).find((t) => t.symbol === \"USDC\")?.address;\n```\n\n### Step 2: Place orders\n\n**Open a long position:**\n\n```typescript\nawait sdk.orders.long({\n  marketAddress,                         \u002F\u002F from step 1\n  payTokenAddress: usdcAddress,          \u002F\u002F token you're paying with\n  collateralTokenAddress: longToken,     \u002F\u002F WETH as collateral for longs\n  payAmount: 100000000n,                 \u002F\u002F 100 USDC (6 decimals)\n  leverage: 50000n,                      \u002F\u002F 5x leverage (basis points)\n  allowedSlippageBps: 100,               \u002F\u002F 1% slippage\n});\n```\n\n**Open a short position:**\n\n```typescript\nawait sdk.orders.short({\n  marketAddress,\n  payTokenAddress: usdcAddress,\n  collateralTokenAddress: shortToken,    \u002F\u002F USDC as collateral for shorts\n  payAmount: 100000000n,\n  leverage: 50000n,\n});\n```\n\n**Swap tokens:**\n\n```typescript\nconst arbAddress = Object.values(tokensData).find((t) => t.symbol === \"ARB\")?.address;\nconst linkAddress = Object.values(tokensData).find((t) => t.symbol === \"LINK\")?.address;\n\nawait sdk.orders.swap({\n  fromTokenAddress: arbAddress,\n  toTokenAddress: linkAddress,\n  fromAmount: 1000000000000000000n, \u002F\u002F 1 ARB (18 decimals)\n  allowedSlippageBps: 100,\n});\n```\n\n**Limit orders** — add `limitPrice` for positions or `triggerPrice` for swaps:\n\n```typescript\nawait sdk.orders.long({\n  marketAddress,\n  payTokenAddress: usdcAddress,\n  collateralTokenAddress: longToken,\n  payAmount: 100000000n,\n  leverage: 50000n,\n  limitPrice: 3000000000000000000000000000000000n, \u002F\u002F $3000 (30 decimals)\n});\n```\n\n**Key parameters:**\n- `leverage` — In basis points: `10000n` = 1x, `50000n` = 5x, `1000000n` = 100x\n- `allowedSlippageBps` — Default `100` (1%). Range: 1-500\n- `payAmount` — Pay this much collateral. Alternative: use `sizeAmount` to specify position size\n- `fromAmount` \u002F `toAmount` — For swaps, specify input or desired output amount\n\n### Step 3: Close a position\n\nThere is no convenience `close()` method. Closing requires computing decrease amounts via `getDecreasePositionAmounts()` from `@gmx-io\u002Fsdk\u002Futils\u002Ftrade`, then calling `createDecreaseOrder()`.\n\n> **Important:** Always re-fetch `marketsInfoData` and `tokensData` right before closing. These contain oracle prices that go stale within seconds — using old data produces an `acceptablePrice` the keeper will reject.\n\n```typescript\nconst { getDecreasePositionAmounts } = require(\"@gmx-io\u002Fsdk\u002Futils\u002Ftrade\");\n\n\u002F\u002F 1. Fetch FRESH market data (prices go stale quickly)\nconst { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();\n\n\u002F\u002F 2. Get the position to close\nconst positionsInfo = await sdk.positions.getPositionsInfo({\n  marketsInfoData, tokensData, showPnlInLeverage: false,\n});\nconst position = Object.values(positionsInfo).find(\n  (p) => p.marketAddress === marketAddress && p.isLong === true\n);\n\n\u002F\u002F 3. Compute decrease amounts\nconst marketInfo = marketsInfoData[position.marketAddress];\nconst collateralToken = tokensData[position.collateralTokenAddress];\nconst { minCollateralUsd, minPositionSizeUsd } = await sdk.positions.getPositionsConstants();\nconst uiFeeFactor = await sdk.utils.getUiFeeFactor();\n\nconst decreaseAmounts = getDecreasePositionAmounts({\n  marketInfo,\n  collateralToken,\n  isLong: position.isLong,\n  position,\n  closeSizeUsd: position.sizeInUsd,   \u002F\u002F Full close. Use a smaller value for partial close.\n  keepLeverage: false,\n  userReferralInfo: undefined,\n  minCollateralUsd,\n  minPositionSizeUsd,\n  uiFeeFactor,\n  isSetAcceptablePriceImpactEnabled: false,\n});\n\n\u002F\u002F 4. Submit the decrease order\nawait sdk.orders.createDecreaseOrder({\n  marketInfo,\n  marketsInfoData,\n  tokensData,\n  isLong: position.isLong,\n  allowedSlippage: 300,    \u002F\u002F 3% — use higher slippage for decrease to avoid keeper rejection\n  decreaseAmounts,\n  collateralToken,\n});\n```\n\n## SDK Modules\n\n| Module | Key Methods | Description |\n|--------|------------|-------------|\n| `sdk.markets` | `getMarkets()`, `getMarketsInfo()`, `getDailyVolumes()` | Market data and liquidity info |\n| `sdk.tokens` | `getTokensData()`, `getTokensBalances()` | Token metadata, prices, balances |\n| `sdk.positions` | `getPositions()`, `getPositionsInfo()`, `getPositionsConstants()` | Open position data |\n| `sdk.orders` | `long()`, `short()`, `swap()`, `getOrders()`, `cancelOrders()` | Order creation and management |\n| `sdk.trades` | `getTradeHistory()` | Historical trade actions |\n| `sdk.utils` | `getGasLimits()`, `getGasPrice()`, `getExecutionFee()`, `getUiFeeFactor()` | Gas and fee estimation |\n| `sdk.oracle` | `getTickers()`, `getMarkets()`, `getTokens()` | Direct oracle data access |\n\n**Typical read flow:**\n\n```typescript\nconst { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();\nconst positionsInfo = await sdk.positions.getPositionsInfo({\n  marketsInfoData, tokensData, showPnlInLeverage: false,\n});\nconst { ordersInfoData } = await sdk.orders.getOrders({\n  marketsInfoData, tokensData,\n});\n```\n\n### Convenience vs Low-level Methods\n\nThe SDK has two tiers for order creation:\n\n**Convenience methods** — handle amount calculation, execution fee, and tx submission automatically. Use these for opening positions and swaps:\n\n| Method | Purpose | Key Params |\n|--------|---------|-----------|\n| `sdk.orders.long()` | Open long position | `marketAddress`, `payTokenAddress`, `collateralTokenAddress`, `payAmount`, `leverage` |\n| `sdk.orders.short()` | Open short position | Same as `long()` |\n| `sdk.orders.swap()` | Swap tokens | `fromTokenAddress`, `toTokenAddress`, `fromAmount` |\n| `sdk.orders.cancelOrders()` | Cancel pending orders | `orderKeys: string[]` |\n\n**Low-level methods** — require you to pre-compute amounts, provide full market\u002Ftoken objects, and handle execution fees. Required for closing positions (no convenience `close()` method exists):\n\n| Method | Purpose | Required Setup |\n|--------|---------|---------------|\n| `sdk.orders.createIncreaseOrder()` | Open position (full control) | `IncreasePositionAmounts`, `marketInfo`, `tokensData` |\n| `sdk.orders.createDecreaseOrder()` | Close\u002Freduce position | `DecreasePositionAmounts` via `getDecreasePositionAmounts()` |\n| `sdk.orders.createSwapOrder()` | Swap (full control) | `SwapAmounts`, swap path |\n\n> **Key gap:** There is no `sdk.orders.close()`. To close a position, use `getDecreasePositionAmounts()` from `@gmx-io\u002Fsdk\u002Futils\u002Ftrade` + `createDecreaseOrder()`. See [Step 3: Close a position](#step-3-close-a-position) for the full pattern.\n\n## Order Types\n\n| Type | Enum | Behavior |\n|------|------|----------|\n| Market | `MarketSwap(0)`, `MarketIncrease(2)`, `MarketDecrease(4)` | Execute immediately at current oracle price |\n| Limit | `LimitSwap(1)`, `LimitIncrease(3)`, `LimitDecrease(5)` | Execute when oracle price reaches trigger price |\n| Stop Increase | `StopIncrease(8)` | Open position when price moves past trigger (breakout entry) |\n| Stop-Loss | `StopLossDecrease(6)` | Auto-close position to limit losses |\n| Liquidation | `Liquidation(7)` | System-triggered when position falls below maintenance margin |\n\n**Trigger conditions:**\n- Long Limit: oracle price \u003C= trigger price (buy the dip)\n- Long Stop-Loss: oracle price \u003C= trigger price (exit on drop)\n- Long Take-Profit (LimitDecrease): oracle price >= trigger price (exit on rise)\n- Short Limit: oracle price >= trigger price (sell the rally)\n- Short Stop-Loss: oracle price >= trigger price (exit on rise)\n- Short Take-Profit (LimitDecrease): oracle price \u003C= trigger price (exit on drop)\n\n**Auto-cancel limits:** Maximum concurrent auto-cancel orders per position: 11 on Arbitrum, 6 on Avalanche and Botanix.\n\n**Sidecar orders:** Stop-loss and take-profit orders can be attached to increase orders via `createSltpEntries`, `cancelSltpEntries`, and `updateSltpEntries` parameters in `createIncreaseOrder()`.\n\n**TWAP orders:** Split a large order into 2–30 parts executed over a configurable duration. TWAP utilities (`getTwapDurationInSeconds`, `getIsValidTwapParams`) are exported from `@gmx-io\u002Fsdk\u002Futils\u002Ftwap` but full TWAP order creation is only available via the frontend UI.\n\n## Fees\n\n**Position fees:**\n- Opening\u002Fclosing: **0.04%** if the trade balances long\u002Fshort OI, **0.06%** if it imbalances\n- Applied to position size (notional value)\n\n**Swap fees:**\n- Standard pairs: **0.05%** (balancing) \u002F **0.07%** (imbalancing)\n- Stablecoin pairs: **0.005%** (balancing) \u002F **0.02%** (imbalancing)\n\n**Funding rate:**\n- Adaptive rate that flows from the larger open interest side to the smaller side\n- Rebalances long\u002Fshort exposure over time\n- Accrues continuously, settled on position changes\n\n**Borrowing rate:**\n- Kink model: low rate below utilization threshold, steep above\n- Approximately 45–55% APR at 75% utilization\n- Paid by all positions proportional to size\n\n**Execution fee:**\n- Covers keeper gas cost for executing the order onchain\n- Paid upfront in native token (ETH\u002FAVAX\u002FBTC)\n- Surplus refunded after execution\n- Use `sdk.utils.getExecutionFee()` to estimate\n\n## REST API\n\n### Oracle Endpoints\n\nBase URL: `https:\u002F\u002F{network}-api.gmxinfra.io`\n\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `\u002Fprices\u002Ftickers` | GET | Current min\u002Fmax prices for all tokens |\n| `\u002Fprices\u002Fcandles` | GET | OHLC price candles (`?tokenSymbol=ETH&period=1h`) |\n| `\u002Fsigned_prices\u002Flatest` | GET | Signed oracle prices for order execution |\n| `\u002Ftokens` | GET | Token list with addresses and decimals |\n| `\u002Fmarkets` | GET | Market configuration (index\u002Flong\u002Fshort tokens) |\n| `\u002Fmarkets\u002Finfo` | GET | Extended market info with pool sizes and utilization |\n\nAll endpoints are served from the Oracle base URL above. The legacy `gmx-api-{network}.gmx.io` domain is no longer available.\n\n### GraphQL (Subsquid)\n\nBase URL: `https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-{network}:prod\u002Fapi\u002Fgraphql`\n\nExample — fetch recent trade actions:\n\n```graphql\nquery {\n  tradeActions(\n    where: { account_eq: \"0x...\" }\n    orderBy: timestamp_DESC\n    limit: 10\n  ) {\n    id\n    eventName\n    orderType\n    sizeDeltaUsd\n    timestamp\n    transactionHash\n  }\n}\n```\n\n### Fallback URLs\n\n| Chain | Primary | Fallback 1 | Fallback 2 |\n|-------|---------|------------|------------|\n| Arbitrum | `arbitrum-api.gmxinfra.io` | `arbitrum-api-fallback.gmxinfra.io` | `arbitrum-api-fallback.gmxinfra2.io` |\n| Avalanche | `avalanche-api.gmxinfra.io` | `avalanche-api-fallback.gmxinfra.io` | `avalanche-api-fallback.gmxinfra2.io` |\n| Botanix | `botanix-api.gmxinfra.io` | `botanix-api-fallback.gmxinfra.io` | `botanix-api-fallback.gmxinfra2.io` |\n\n## Key Concepts\n\n**Oracle-based pricing:** GMX does not use an AMM. Prices come from Chainlink Data Streams, giving traders zero-slippage execution at the oracle price (subject to price impact from pool utilization).\n\n**Two-phase execution:** Orders follow a create → execute pattern. The user submits an order transaction, then a keeper executes it with fresh oracle prices. This typically takes 1–5 seconds.\n\n**BigInt amounts:** All amounts use BigInt. Prices are scaled to 30 decimals (`1 USD = 10^30`). Token amounts use their native decimals (e.g., USDC = 6, ETH = 18).\n\n**Stale data:** `marketsInfoData` and `tokensData` contain oracle prices at fetch time. These go stale within seconds. Always re-fetch fresh data before operations that depend on current prices — especially `createDecreaseOrder()`, which computes `acceptablePrice` from the data you provide. Using stale prices causes keeper rejection.\n\n**Multicall batching:** The SDK batches RPC calls automatically. Production chains use `batchSize: 1024 * 1024` bytes per multicall with no waiting. This is configured per-chain in `BATCH_CONFIGS`.\n\n**GMX Account:** Cross-chain trading from Ethereum, Base, or BNB Chain via LayerZero\u002FStargate bridge. Users can trade on Arbitrum\u002FAvalanche without bridging manually.\n\n**Subaccounts:** Delegate trading to a subaccount address for one-click trading. The subaccount can execute orders without requiring the main wallet signature each time.\n\n## Full Example: Open → Monitor → Close\n\nEnd-to-end flow that opens a long position, monitors it, and closes it.\n\n```typescript\nconst { GmxSdk } = require(\"@gmx-io\u002Fsdk\");\nconst { getDecreasePositionAmounts } = require(\"@gmx-io\u002Fsdk\u002Futils\u002Ftrade\");\nconst { createWalletClient, http } = require(\"viem\");\nconst { privateKeyToAccount } = require(\"viem\u002Faccounts\");\nconst { arbitrum } = require(\"viem\u002Fchains\");\n\n\u002F\u002F ─── Setup ───────────────────────────────────────────────────────────────────\n\nconst account = privateKeyToAccount(process.env.PRIVATE_KEY);\nconst sdk = new GmxSdk({\n  chainId: 42161,\n  rpcUrl: \"https:\u002F\u002Farb1.arbitrum.io\u002Frpc\",\n  oracleUrl: \"https:\u002F\u002Farbitrum-api.gmxinfra.io\",\n  subsquidUrl: \"https:\u002F\u002Fgmx.squids.live\u002Fgmx-synthetics-arbitrum:prod\u002Fapi\u002Fgraphql\",\n  account: account.address,\n  walletClient: createWalletClient({\n    account, chain: arbitrum, transport: http(\"https:\u002F\u002Farb1.arbitrum.io\u002Frpc\"),\n  }),\n});\n\n\u002F\u002F ─── 1. Resolve addresses ───────────────────────────────────────────────────\n\nconst { marketsInfoData, tokensData } = await sdk.markets.getMarketsInfo();\n\nconst ethMarket = Object.values(marketsInfoData).find(\n  (m) => tokensData[m.indexTokenAddress]?.symbol === \"WETH\" && !m.isSpotOnly\n);\nconst marketAddress = ethMarket.marketTokenAddress;\nconst usdcAddress = Object.values(tokensData).find((t) => t.symbol === \"USDC\").address;\n\n\u002F\u002F ─── 2. Open long ───────────────────────────────────────────────────────────\n\nawait sdk.orders.long({\n  marketAddress,\n  payTokenAddress: usdcAddress,\n  collateralTokenAddress: usdcAddress,\n  payAmount: 10_000000n,   \u002F\u002F 10 USDC\n  leverage: 30000n,        \u002F\u002F 3x\n  allowedSlippageBps: 100,\n  skipSimulation: true,\n});\n\n\u002F\u002F ─── 3. Wait for position to appear (keeper executes in 1-30s) ──────────────\n\nlet position;\nfor (let i = 0; i \u003C 40; i++) {\n  await new Promise((r) => setTimeout(r, 3000));\n  const info = await sdk.positions.getPositionsInfo({\n    marketsInfoData, tokensData, showPnlInLeverage: false,\n  });\n  position = Object.values(info).find(\n    (p) => p.marketAddress === marketAddress && p.isLong === true\n  );\n  if (position) break;\n}\nif (!position) throw new Error(\"Position did not appear within 120s\");\n\nconsole.log(\"Position opened:\", {\n  sizeUsd: position.sizeInUsd.toString(),\n  leverage: position.leverage.toString(),\n  entryPrice: position.entryPrice.toString(),\n});\n\n\u002F\u002F ─── 4. Close position (re-fetch fresh data first!) ─────────────────────────\n\nconst fresh = await sdk.markets.getMarketsInfo();\nconst freshPositions = await sdk.positions.getPositionsInfo({\n  marketsInfoData: fresh.marketsInfoData,\n  tokensData: fresh.tokensData,\n  showPnlInLeverage: false,\n});\nconst pos = Object.values(freshPositions).find(\n  (p) => p.marketAddress === marketAddress && p.isLong === true\n);\n\nconst marketInfo = fresh.marketsInfoData[pos.marketAddress];\nconst collateralToken = fresh.tokensData[pos.collateralTokenAddress];\nconst { minCollateralUsd, minPositionSizeUsd } = await sdk.positions.getPositionsConstants();\nconst uiFeeFactor = await sdk.utils.getUiFeeFactor();\n\nconst decreaseAmounts = getDecreasePositionAmounts({\n  marketInfo, collateralToken, isLong: pos.isLong, position: pos,\n  closeSizeUsd: pos.sizeInUsd, keepLeverage: false,\n  userReferralInfo: undefined, minCollateralUsd, minPositionSizeUsd, uiFeeFactor,\n  isSetAcceptablePriceImpactEnabled: false,\n});\n\nawait sdk.orders.createDecreaseOrder({\n  marketInfo, marketsInfoData: fresh.marketsInfoData, tokensData: fresh.tokensData,\n  isLong: pos.isLong, allowedSlippage: 300, decreaseAmounts, collateralToken,\n});\n\nconsole.log(\"Close order submitted — keeper will execute in 1-30s\");\n```\n\n## Limitations\n\n- **GM pool deposits\u002Fwithdrawals:** See the [gmx-liquidity](..\u002Fgmx-official-liquidity\u002FSKILL.md) skill for contract-level operations. SDK convenience methods not yet available.\n- **GLV vault operations:** See the [gmx-liquidity](..\u002Fgmx-official-liquidity\u002FSKILL.md) skill for contract-level operations. SDK convenience methods not yet available.\n- **Express orders:** Frontend-only via Gelato relay. Not exposed in the SDK.\n- **TWAP orders:** Utility functions available (`@gmx-io\u002Fsdk\u002Futils\u002Ftwap`) but no SDK method to create TWAP orders programmatically.\n- **Order updates:** Orders cannot be modified. Cancel and recreate instead (`sdk.orders.cancelOrders()`).\n- **Trade simulation:** The `skipSimulation` parameter exists but simulation is deprecated. Set `skipSimulation: true`.\n\n## References\n\n- [SDK Reference](references\u002Fsdk-reference.md) — Full module and method documentation\n- [API Endpoints](references\u002Fapi-endpoints.md) — Oracle, OpenAPI, and GraphQL endpoint details\n- [Contract Addresses](references\u002Fcontract-addresses.md) — Deployed contracts per chain\n- [Order Types](references\u002Forder-types.md) — Detailed order type behavior and trigger logic\n- [GMX Documentation](https:\u002F\u002Fdocs.gmx.io) — Official protocol documentation\n- [GMX App](https:\u002F\u002Fapp.gmx.io) — Trading interface\n- [`@gmx-io\u002Fsdk` on npm](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002F@gmx-io\u002Fsdk) — SDK package\n- [gmx-io\u002Fgmx-interface](https:\u002F\u002Fgithub.com\u002Fgmx-io\u002Fgmx-interface) — Frontend source code\n",{"name":5,"license":15,"metadata":44,"description":7},{"author":45,"chains":46,"version":47,"openclaw":48},"gmx-io","arbitrum, avalanche, botanix","0.2.1",{"tags":49,"source":53,"official":54},[50,29,20,51,36,21,25,27,52],"gmx","swap","derivatives","https:\u002F\u002Fgithub.com\u002Fgmx-io\u002Fgmx-ai",true,"main","3df1d0d67b30ff15236561f8c0f9f06d33f42dfd","skills\u002Fdefi\u002Fgmx-official-trading",17,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia","https:\u002F\u002Feth2030.com","Hardcore infra. Building @alt-research and applied cryptography.","2026-11-15 02:28:10",{"source":8,"skillName":5,"commands":65,"prompt":75,"zipAvailable":54},[66,69,72],{"tool":67,"command":68},"npx","npx skills add jiayaoqijia\u002Fcryptoskill --skill gmx-trading",{"tool":70,"command":71},"bunx","bunx skills add jiayaoqijia\u002Fcryptoskill --skill gmx-trading",{"tool":73,"command":74},"pnpm","pnpm dlx skills add jiayaoqijia\u002Fcryptoskill --skill gmx-trading","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fdefi\u002Fgmx-official-trading\u002FSKILL.md",[77,83,87,91,95,99],{"path":78,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":81,"sourceHtmlUrl":82},"references\u002Fapi-endpoints.md","REFERENCE","参考文档",4679,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fdefi\u002Fgmx-official-trading\u002Freferences\u002Fapi-endpoints.md",{"path":84,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":85,"sourceHtmlUrl":86},"references\u002Fcontract-addresses.md",6435,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fdefi\u002Fgmx-official-trading\u002Freferences\u002Fcontract-addresses.md",{"path":88,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":89,"sourceHtmlUrl":90},"references\u002Forder-types.md",6008,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fdefi\u002Fgmx-official-trading\u002Freferences\u002Forder-types.md",{"path":92,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":93,"sourceHtmlUrl":94},"references\u002Fsdk-reference.md",10489,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fdefi\u002Fgmx-official-trading\u002Freferences\u002Fsdk-reference.md",{"path":96,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":97,"sourceHtmlUrl":98},"SOURCE.md",146,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fdefi\u002Fgmx-official-trading\u002FSOURCE.md",{"path":100,"resourceType":79,"resourceTypeDesc":80,"sizeBytes":101,"sourceHtmlUrl":102},"TRUST.auto.yaml",2182,"https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fdefi\u002Fgmx-official-trading\u002FTRUST.auto.yaml",[104,113,121,129,137,145],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":108,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":112},"01M7DTKCERMV0RNX3HZJP4CZ26","troves","Deposit and withdraw from Troves DeFi yield vault strategies on Starknet. View available strategies, check positions, and manage vault deposits. Use this skill when the user mentions Troves, vault, yield vault, DeFi vault, strategy, yield farming, vault deposit, vault withdraw, earning yield through vaults, passive yield strategies, or wants to deposit into or withdraw from a yield strategy — even if they don't say \"Troves\" explicitly.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-troves\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-troves\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":117,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":112},"01M7DTK6CJSMGC8KCQHGNYFZBD","trade","Swap tokens on Starknet via Fibrous DEX aggregator. Supports per-provider selection (avnu, ekubo, or auto to race all). Use this skill when the user wants to swap, exchange, trade, convert, buy, or sell one token for another on Starknet. Also use when the user asks about token prices, exchange rates, DEX routing, best swap route, or wants to check how much they would receive for a given amount — even if they don't explicitly say \"swap\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-trade\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-trade\u002FSKILL.md",[],[],{"skillNo":122,"name":123,"nameZh":6,"description":124,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":125,"sourceHtmlUrl":126,"categories":127,"keywords":128,"publishedAt":112},"01M7DTJZ6A0X4PAW3Y8W4J9K64","staking","Stake, unstake, claim, and compound rewards for STRK, WBTC, tBTC, SolvBTC, and LBTC on Starknet. View validators, pools, and staking positions. Use this skill when the user mentions staking, delegating, validators, staking pools, rewards, compounding, unstaking, earning yield, passive income on crypto, or wants to earn on their STRK or BTC tokens — even if they don't say \"stake\" explicitly.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-staking\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-staking\u002FSKILL.md",[],[],{"skillNo":130,"name":131,"nameZh":6,"description":132,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":133,"sourceHtmlUrl":134,"categories":135,"keywords":136,"publishedAt":112},"01M7DTJSDZJKCDMW7GHRF4BRH5","send","Send STRK, ETH, or any ERC-20 token to a Starknet address. Supports simulation (dry-run) before execution. Use this skill when the user wants to send, transfer, pay, tip, or move tokens to another wallet address on Starknet. Also trigger when the user mentions sending funds to someone, making a payment, transferring assets, or moving crypto to a specific address — even if they just say \"pay 10 STRK to 0x...\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-send\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-send\u002FSKILL.md",[],[],{"skillNo":138,"name":139,"nameZh":6,"description":140,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":141,"sourceHtmlUrl":142,"categories":143,"keywords":144,"publishedAt":112},"01M7DTJG1E480D51ZQ7WKDQ26K","portfolio","View a comprehensive DeFi portfolio dashboard and optimize portfolio allocation via automated rebalancing. Use this skill when the user wants an overview, summary, dashboard, total value, net worth, portfolio rebalancing, target allocation, or wants to see all their DeFi positions across Starknet at once. Also trigger when the user asks \"what do I have\", \"show me everything\", \"how much am I worth\", \"my positions\", \"my investments\", \"rebalance my portfolio\", \"I want 50% ETH\", \"optimize my holdings\", or any request for a holistic view of their Starknet holdings — even if they don't explicitly say \"portfolio\".","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-portfolio\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-portfolio\u002FSKILL.md",[],[],{"skillNo":146,"name":147,"nameZh":6,"description":148,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":149,"sourceHtmlUrl":150,"categories":151,"keywords":152,"publishedAt":112},"01M7DTJ7M8TE9R2N36HFBZDGVD","multi-swap","Execute multiple token swaps in a single Starknet transaction via Fibrous (default). Supports per-provider selection (avnu, ekubo, or auto to race all). Supports 2-3 swap pairs bundled into one multicall. Use this skill when the user wants to swap multiple token pairs at once, do batch swaps, execute several trades simultaneously, perform parallel swaps, or do bulk trading in one transaction. Also trigger when the user mentions \"two swaps\", \"three swaps\", \"swap X and Y at the same time\", or wants to convert multiple tokens in a single call.","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-multi-swap\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fjiayaoqijia\u002Fcryptoskill\u002Fblob\u002Fmain\u002Fskills\u002Fmcp-servers\u002Fahmetenesdur-multi-swap\u002FSKILL.md",[],[]]