Skip to main content

orders

This module provides utilities for working with GMX orders, including type checking functions, order information processing, and order classification helpers. It handles both swap orders and position orders, including TWAP (Time-Weighted Average Price) orders.

Methods

This module exports type-check predicates, type-narrowing guards, and data-enrichment helpers for working with GMX orders. Import everything from @gmx-io/sdk/utils/orders.

Order type classification

The following predicates check which broad category an OrderType enum value belongs to. Use these to branch logic without hardcoding enum integers.

FunctionReturns true for
isMarketOrderTypeMarketSwap, MarketIncrease, MarketDecrease
isLimitOrderTypeLimitIncrease, LimitSwap, StopIncrease
isTriggerDecreaseOrderTypeLimitDecrease, StopLossDecrease
isDecreaseOrderTypeMarketDecrease, LimitDecrease, StopLossDecrease
isIncreaseOrderTypeMarketIncrease, LimitIncrease, StopIncrease
isSwapOrderTypeMarketSwap, LimitSwap
isLimitSwapOrderTypeLimitSwap only
isLiquidationOrderTypeLiquidation only
isStopLossOrderTypeStopLossDecrease only
isLimitDecreaseOrderTypeLimitDecrease only
isLimitIncreaseOrderTypeLimitIncrease only
isStopIncreaseOrderTypeStopIncrease only
note

isLimitOrderType includes StopIncrease (Stop Market Increase) in addition to LimitIncrease and LimitSwap. This matches the on-chain classification where stop market increase orders behave like limit orders — they execute when price reaches a trigger level.

import { OrderType } from "@gmx-io/sdk/utils/orders";
import {
isMarketOrderType,
isLimitOrderType,
isTriggerDecreaseOrderType,
isDecreaseOrderType,
isIncreaseOrderType,
isSwapOrderType,
isLiquidationOrderType,
} from "@gmx-io/sdk/utils/orders";

isMarketOrderType(OrderType.MarketIncrease); // true
isLimitOrderType(OrderType.LimitIncrease); // true
isLimitOrderType(OrderType.StopIncrease); // true — stop market is treated as limit
isTriggerDecreaseOrderType(OrderType.StopLossDecrease); // true
isDecreaseOrderType(OrderType.MarketDecrease); // true
isIncreaseOrderType(OrderType.LimitIncrease); // true
isSwapOrderType(OrderType.LimitSwap); // true
isLiquidationOrderType(OrderType.Liquidation); // true

isIncreaseOrderType

function isIncreaseOrderType(
orderType: OrderType
): orderType is OrderType.MarketIncrease | OrderType.LimitIncrease | OrderType.StopIncrease;

Type predicate that narrows OrderType to one of the three increase variants. Use this in conditional branches where the TypeScript compiler must know the narrowed type.

import { isIncreaseOrderType, OrderType } from "@gmx-io/sdk/utils/orders";

function handleOrder(orderType: OrderType) {
if (isIncreaseOrderType(orderType)) {
// orderType is now typed as MarketIncrease | LimitIncrease | StopIncrease
return buildIncreaseParams(orderType);
}
}

OrderInfo type guards

These functions accept an OrderInfo object (enriched order) and narrow its type to a more specific variant. OrderInfo is a union of SwapOrderInfo, PositionOrderInfo, and TwapOrderInfo.

FunctionNarrows to
isSwapOrder(orderInfo)SwapOrderInfo — has triggerRatio, initialCollateralToken, targetCollateralToken
isPositionOrder(orderInfo)PositionOrderInfo — has acceptablePrice, triggerPrice, marketInfo, indexToken
isTwapOrder(orderInfo)Extract<T, { isTwap: true }> — has orders[], twapId, numberOfParts
isTwapSwapOrder(orderInfo)TwapOrderInfo<SwapOrderInfo>
isTwapPositionOrder(orderInfo)TwapOrderInfo<PositionOrderInfo>
import {
isSwapOrder,
isPositionOrder,
isTwapOrder,
isTwapSwapOrder,
isTwapPositionOrder,
} from "@gmx-io/sdk/utils/orders";

// Route order handling by type
function handleOrderInfo(orderInfo: OrderInfo) {
if (isTwapOrder(orderInfo)) {
// orderInfo.orders — array of individual sub-orders
console.log(`TWAP has ${orderInfo.orders.length} parts`);
} else if (isSwapOrder(orderInfo)) {
console.log("Swap trigger ratio:", orderInfo.triggerRatio);
} else if (isPositionOrder(orderInfo)) {
console.log("Acceptable price:", orderInfo.acceptablePrice);
}
}

getOrderKeys

function getOrderKeys(order: OrderInfo): string[];

Returns all on-chain order keys for an order. TWAP orders have one key per sub-order; regular orders have a single key. Use this when you need to cancel or update all parts of an order without special-casing TWAP.

import { getOrderKeys } from "@gmx-io/sdk/utils/orders";

const keys = getOrderKeys(orderInfo);
// Regular order: ["0xabc..."]
// TWAP order with 4 parts: ["0xabc...", "0xdef...", "0x123...", "0x456..."]

getOrderInfo

function getOrderInfo(p: {
marketsInfoData: MarketsInfoData;
tokensData: TokensData;
wrappedNativeToken: Token;
order: Order;
}): OrderInfo | undefined;

Enriches a raw Order (as returned by the contract reader) into an OrderInfo with resolved token data, market info, computed swap path stats, trigger ratios, and parsed prices. Returns undefined if required tokens or market data are missing from the supplied data maps.

Parameters

ParameterTypeDescription
marketsInfoDataMarketsInfoDataMap of market address → MarketInfo
tokensDataTokensDataMap of token address → TokenData with prices
wrappedNativeTokenTokenWrapped native token (for unwrap path resolution)
orderOrderRaw order object from contract
warning

getOrderInfo returns undefined when any required lookup fails — for example, when the initial collateral token or target collateral token is not present in tokensData, or when the market is not in marketsInfoData. Always check the return value before accessing fields.

import { getOrderInfo } from "@gmx-io/sdk/utils/orders";

const orderInfo = getOrderInfo({
marketsInfoData,
tokensData,
wrappedNativeToken,
order: rawOrder,
});

if (!orderInfo) {
// Token or market data not loaded yet — retry when data is available
return;
}

console.log("Trigger price:", orderInfo.triggerPrice);

isVisibleOrder

function isVisibleOrder(orderType: OrderType): boolean;

Returns true if the order type is one that a user would see in a position or orders list. Returns true for all market orders, limit orders, limit swap orders, and trigger decrease orders. Returns false for Liquidation (which is a keeper action, not a user order).

import { isVisibleOrder, OrderType } from "@gmx-io/sdk/utils/orders";

isVisibleOrder(OrderType.LimitIncrease); // true
isVisibleOrder(OrderType.MarketDecrease); // true
isVisibleOrder(OrderType.Liquidation); // false — liquidations are not user-visible

isOrderForPosition

function isOrderForPosition(order: OrderInfo, positionKey: string): order is PositionOrderInfo;

Returns true if the order belongs to the position identified by positionKey, and narrows the type to PositionOrderInfo. The collateral address check differs by order type: limit increase orders match on targetCollateralToken, while trigger decrease orders match on initialCollateralTokenAddress.

import { isOrderForPosition } from "@gmx-io/sdk/utils/orders";

const positionOrders = orders.filter((o) => isOrderForPosition(o, positionKey));
// positionOrders is now typed as PositionOrderInfo[]

isOrderForPositionByData

function isOrderForPositionByData(
order: OrderInfo,
params: {
account: string;
marketAddress: string;
collateralAddress: string;
isLong: boolean;
}
): order is PositionOrderInfo;

Same matching logic as isOrderForPosition but accepts explicit position data instead of a position key string. Use this when you have individual position fields rather than a composed key.

Parameters

ParameterTypeDescription
orderOrderInfoEnriched order to check
accountstringTrader account address
marketAddressstringMarket contract address
collateralAddressstringCollateral token address
isLongbooleantrue for long positions
import { isOrderForPositionByData } from "@gmx-io/sdk/utils/orders";

const isMatch = isOrderForPositionByData(orderInfo, {
account: "0x1234567890123456789012345678901234567890",
marketAddress: "0xFD70de6b91282D8017aA4E741e9Ae325CAb992d8",
collateralAddress: "0x82aF49447D8a07e3bd95BD0d56f35241523fBab1",
isLong: true,
});

getOrderTradeboxKey

function getOrderTradeboxKey(order: OrderInfo): string;

Returns a stable string key for deduplicating orders by position in UI state. Position orders (including TWAP position orders) use the format POSITION-{account}:{marketAddress}:{collateralAddress}:{isLong}. Swap orders use SWAP-{account}:{initialCollateralTokenAddress}:{targetCollateralToken.address}.

import { getOrderTradeboxKey } from "@gmx-io/sdk/utils/orders";

const key = getOrderTradeboxKey(orderInfo);
// Position order example:
// "POSITION-0x1234...5678:0xFD70...2d8:0x82aF...bab1:true"
// Swap order example:
// "SWAP-0x1234...5678:0x82aF...bab1:0xFF97...cf5"

API data fetching

fetchApiOrders

fetchApiOrders(ctx: { api: IHttp }, params: {
address: string;
}): Promise<ApiOrderInfo[]>

Fetches order data from the GMX REST API instead of on-chain multicalls. Available on chains where isApiSupported(chainId) returns true (Arbitrum, Avalanche, and Arbitrum Sepolia). The response is deserialized with deserializeBigIntsInObject.

import { GmxApiSdk } from "@gmx-io/sdk/v2";
import { fetchApiOrders } from "@gmx-io/sdk/utils/orders";

const apiSdk = new GmxApiSdk({ chainId: 42161 });
const orders = await fetchApiOrders(apiSdk.ctx, { address: "0x1234...5678" });