Aller au contenu

GMX V2

Connector for GMX V2 perpetual futures on Arbitrum and Avalanche.

Overview

GMX V2 is a decentralized perpetuals exchange that supports leveraged long and short positions on major crypto assets. The Almanak SDK integrates GMX V2 through the intent system, supporting PERP_OPEN and PERP_CLOSE operations.

Market Format

GMX V2 markets use a slash separator: "BTC/USD", "ETH/USD", "LINK/USD".

Intent.perp_open(
    market="ETH/USD",       # Slash separator, not dash
    collateral_token="USDC",
    collateral_amount=Decimal("1000"),
    size_usd=Decimal("5000"),
    is_long=True,
    leverage=Decimal("5"),
    protocol="gmx_v2",
)

Supported Operations

Intent Description
Intent.perp_open() Open a leveraged long or short position
Intent.perp_close() Close an existing position (full or partial)

Keeper Execution Model

GMX V2 uses a two-step execution model:

  1. Order creation: Your transaction submits an order to the GMX exchange router. This is the transaction the SDK signs and submits.
  2. Keeper execution: A GMX keeper bot picks up the order and executes the actual position change in a separate transaction.

Important implications for strategies:

  • on_intent_executed(success=True) fires when the order creation TX confirms (step 1), not when the keeper executes the position (step 2).
  • There is a delay (typically a few seconds) between order creation and keeper execution.
  • get_all_positions() may not reflect the new position immediately after on_intent_executed fires. Poll position state before relying on it.

Minimum Position Size

GMX V2 enforces a minimum position size of approximately $11 net of fees. Orders below this threshold are silently rejected by the keeper with no on-chain error. The order creation TX will still succeed, but the keeper will not execute the position.

Collateral Tokens

Collateral tokens vary by chain:

Chain Supported Collateral
Arbitrum USDC, USDT
Avalanche USDC, USDT

Collateral token approvals are handled automatically by the intent compiler.

Known Limitations

  • Keeper delay: Position state is not immediately available after order creation. Allow a few seconds before querying positions.
  • Silent rejections: Orders below the minimum size are rejected without an on-chain error. Verify position creation by checking position state after the keeper delay.
  • Price impact: Large positions relative to pool open interest may experience significant price impact. GMX V2 uses a price impact model that charges more for positions that increase imbalance.

API Reference

almanak.framework.connectors.gmx_v2

GMX v2 Connector.

This module provides an adapter for interacting with GMX v2 perpetuals protocol, supporting position management, order execution, and event parsing.

GMX v2 is a decentralized perpetual exchange supporting: - Long and short positions with leverage - Multiple collateral types - Limit and market orders - Position sizing and management

Supported chains: - Arbitrum - Avalanche

Example

from almanak.framework.connectors.gmx_v2 import GMXv2Adapter, GMXv2Config

config = GMXv2Config( chain="arbitrum", wallet_address="0x...", ) adapter = GMXv2Adapter(config)

Open a position

result = adapter.open_position( market="ETH/USD", collateral_token="USDC", collateral_amount=Decimal("1000"), size_delta_usd=Decimal("5000"), is_long=True, )

GMXv2Adapter

GMXv2Adapter(
    config: GMXv2Config,
    token_resolver: TokenResolver | None = None,
)

Adapter for GMX v2 perpetuals protocol.

This adapter provides methods for: - Opening and closing positions - Increasing and decreasing position size - Managing limit orders and stop losses - Querying position and market data - Parsing transaction receipts

Example

config = GMXv2Config( chain="arbitrum", wallet_address="0x...", ) adapter = GMXv2Adapter(config)

Open a long position

result = adapter.open_position( market="ETH/USD", collateral_token="USDC", collateral_amount=Decimal("1000"), size_delta_usd=Decimal("5000"), is_long=True, )

Check position

position = adapter.get_position( market="ETH/USD", collateral_token="USDC", is_long=True, )

Close position

result = adapter.close_position( market="ETH/USD", collateral_token="USDC", is_long=True, size_delta_usd=position.size_in_usd, )

Initialize the adapter.

参数:

名称 类型 描述 默认
config GMXv2Config

GMX v2 adapter configuration

必需
token_resolver TokenResolver | None

Optional TokenResolver instance. If None, uses singleton.

None

open_position

open_position(
    market: str,
    collateral_token: str,
    collateral_amount: Decimal,
    size_delta_usd: Decimal,
    is_long: bool,
    acceptable_price: Decimal | None = None,
    trigger_price: Decimal | None = None,
) -> OrderResult

Open a new position or increase existing position.

参数:

名称 类型 描述 默认
market str

Market identifier (e.g., "ETH/USD") or market address

必需
collateral_token str

Token symbol or address for collateral

必需
collateral_amount Decimal

Amount of collateral in token decimals

必需
size_delta_usd Decimal

Position size in USD (will be scaled to 30 decimals)

必需
is_long bool

True for long, False for short

必需
acceptable_price Decimal | None

Maximum (long) or minimum (short) execution price

None
trigger_price Decimal | None

Trigger price for limit orders

None

返回:

类型 描述
OrderResult

OrderResult with order details

close_position

close_position(
    market: str,
    collateral_token: str,
    is_long: bool,
    size_delta_usd: Decimal | None = None,
    receive_token: str | None = None,
    acceptable_price: Decimal | None = None,
    trigger_price: Decimal | None = None,
) -> OrderResult

Close a position or decrease position size.

参数:

名称 类型 描述 默认
market str

Market identifier or address

必需
collateral_token str

Token symbol or address for collateral

必需
is_long bool

Position direction

必需
size_delta_usd Decimal | None

Amount to close in USD (None = close entire position)

None
receive_token str | None

Token to receive (defaults to collateral_token)

None
acceptable_price Decimal | None

Minimum (long) or maximum (short) execution price

None
trigger_price Decimal | None

Trigger price for limit orders

None

返回:

类型 描述
OrderResult

OrderResult with order details

increase_position

increase_position(
    market: str,
    collateral_token: str,
    is_long: bool,
    collateral_delta: Decimal,
    size_delta_usd: Decimal,
    acceptable_price: Decimal | None = None,
    trigger_price: Decimal | None = None,
) -> OrderResult

Increase an existing position.

This is an alias for open_position with an existing position.

参数:

名称 类型 描述 默认
market str

Market identifier or address

必需
collateral_token str

Token symbol or address

必需
is_long bool

Position direction

必需
collateral_delta Decimal

Additional collateral to add

必需
size_delta_usd Decimal

Additional size in USD

必需
acceptable_price Decimal | None

Maximum (long) or minimum (short) execution price

None
trigger_price Decimal | None

Trigger price for limit orders

None

返回:

类型 描述
OrderResult

OrderResult with order details

decrease_position

decrease_position(
    market: str,
    collateral_token: str,
    is_long: bool,
    size_delta_usd: Decimal,
    collateral_delta: Decimal = Decimal("0"),
    receive_token: str | None = None,
    acceptable_price: Decimal | None = None,
    trigger_price: Decimal | None = None,
) -> OrderResult

Decrease an existing position.

This is similar to close_position but for partial closes.

参数:

名称 类型 描述 默认
market str

Market identifier or address

必需
collateral_token str

Token symbol or address

必需
is_long bool

Position direction

必需
size_delta_usd Decimal

Size to reduce in USD

必需
collateral_delta Decimal

Collateral to withdraw

Decimal('0')
receive_token str | None

Token to receive

None
acceptable_price Decimal | None

Minimum (long) or maximum (short) execution price

None
trigger_price Decimal | None

Trigger price for limit orders

None

返回:

类型 描述
OrderResult

OrderResult with order details

get_position

get_position(
    market: str, collateral_token: str, is_long: bool
) -> GMXv2Position | None

Get position details.

参数:

名称 类型 描述 默认
market str

Market identifier or address

必需
collateral_token str

Token symbol or address

必需
is_long bool

Position direction

必需

返回:

类型 描述
GMXv2Position | None

Position details or None if not found

get_all_positions

get_all_positions() -> list[GMXv2Position]

Get all open positions.

返回:

类型 描述
list[GMXv2Position]

List of all open positions

cancel_order

cancel_order(order_key: str) -> OrderResult

Cancel a pending order.

参数:

名称 类型 描述 默认
order_key str

Order key to cancel

必需

返回:

类型 描述
OrderResult

OrderResult indicating success/failure

get_order

get_order(order_key: str) -> GMXv2Order | None

Get order details.

参数:

名称 类型 描述 默认
order_key str

Order key to look up

必需

返回:

类型 描述
GMXv2Order | None

Order details or None if not found

get_all_orders

get_all_orders() -> list[GMXv2Order]

Get all pending orders.

返回:

类型 描述
list[GMXv2Order]

List of all pending orders

set_position

set_position(position: GMXv2Position) -> None

Set a position for testing.

参数:

名称 类型 描述 默认
position GMXv2Position

Position to set

必需

clear_positions

clear_positions() -> None

Clear all positions.

clear_orders

clear_orders() -> None

Clear all orders.

clear_all

clear_all() -> None

Clear all state.

GMXv2Config dataclass

GMXv2Config(
    chain: str,
    wallet_address: str,
    default_slippage_bps: int = 50,
    execution_fee: int | None = None,
    referral_code: bytes = b"\x00" * 32,
)

Configuration for GMXv2Adapter.

属性:

名称 类型 描述
chain str

Target blockchain (arbitrum or avalanche)

wallet_address str

Address executing transactions

default_slippage_bps int

Default slippage tolerance in basis points (default 50 = 0.5%)

execution_fee int | None

Execution fee in native token wei (auto-set per chain)

referral_code bytes

Optional referral code for fee discounts

__post_init__

__post_init__() -> None

Validate configuration and set defaults.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

GMXv2Order dataclass

GMXv2Order(
    order_key: str,
    market: str,
    initial_collateral_token: str,
    order_type: GMXv2OrderType,
    is_long: bool,
    size_delta_usd: Decimal,
    initial_collateral_delta_amount: Decimal,
    trigger_price: Decimal | None = None,
    acceptable_price: Decimal | None = None,
    execution_fee: int = 0,
    callback_gas_limit: int = 0,
    is_frozen: bool = False,
    created_at: datetime = (lambda: datetime.now(UTC))(),
    updated_at: datetime = (lambda: datetime.now(UTC))(),
)

Represents a GMX v2 order.

属性:

名称 类型 描述
order_key str

Unique identifier for the order

market str

Market address

initial_collateral_token str

Collateral token for the order

order_type GMXv2OrderType

Type of order

is_long bool

Position direction

size_delta_usd Decimal

Size change in USD (30 decimals)

initial_collateral_delta_amount Decimal

Collateral amount change

trigger_price Decimal | None

Trigger price for limit/stop orders

acceptable_price Decimal | None

Maximum/minimum acceptable execution price

execution_fee int

Fee paid to keeper

callback_gas_limit int

Gas limit for callback execution

is_frozen bool

Whether order is frozen

created_at datetime

Order creation timestamp

updated_at datetime

Last update timestamp

is_increase property

is_increase: bool

Check if order increases position size.

is_decrease property

is_decrease: bool

Check if order decreases position size.

is_market_order property

is_market_order: bool

Check if order is a market order.

is_limit_order property

is_limit_order: bool

Check if order is a limit order.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

from_dict classmethod

from_dict(data: dict[str, Any]) -> GMXv2Order

Create from dictionary.

GMXv2OrderType

Bases: Enum

GMX v2 order types.

to_int

to_int() -> int

Convert to GMX v2 order type integer.

GMXv2Position dataclass

GMXv2Position(
    position_key: str,
    market: str,
    collateral_token: str,
    size_in_usd: Decimal,
    size_in_tokens: Decimal,
    collateral_amount: Decimal,
    entry_price: Decimal,
    is_long: bool,
    realized_pnl: Decimal = Decimal("0"),
    unrealized_pnl: Decimal = Decimal("0"),
    leverage: Decimal = Decimal("1"),
    liquidation_price: Decimal | None = None,
    funding_fee_amount: Decimal = Decimal("0"),
    borrowing_fee_amount: Decimal = Decimal("0"),
    last_updated: datetime = (lambda: datetime.now(UTC))(),
)

Represents an open GMX v2 position.

属性:

名称 类型 描述
position_key str

Unique identifier for the position

market str

Market address

collateral_token str

Token used as collateral

size_in_usd Decimal

Position size in USD (30 decimals)

size_in_tokens Decimal

Position size in index tokens (token decimals)

collateral_amount Decimal

Collateral amount in token decimals

entry_price Decimal

Average entry price (30 decimals)

is_long bool

True for long, False for short

realized_pnl Decimal

Realized PnL (30 decimals)

unrealized_pnl Decimal

Unrealized PnL (30 decimals)

leverage Decimal

Current leverage (size / collateral)

liquidation_price Decimal | None

Price at which position gets liquidated

funding_fee_amount Decimal

Accumulated funding fees

borrowing_fee_amount Decimal

Accumulated borrowing fees

last_updated datetime

Timestamp of last update

side property

side: GMXv2PositionSide

Get position side.

total_fees property

total_fees: Decimal

Get total accumulated fees.

net_pnl property

net_pnl: Decimal

Get net PnL after fees.

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

from_dict classmethod

from_dict(data: dict[str, Any]) -> GMXv2Position

Create from dictionary.

GMXv2PositionSide

Bases: Enum

Position side (long/short).

GMXv2Event dataclass

GMXv2Event(
    event_type: GMXv2EventType,
    event_name: str,
    log_index: int,
    transaction_hash: str,
    block_number: int,
    contract_address: str,
    data: dict[str, Any],
    raw_topics: list[str] = list(),
    raw_data: str = "",
    timestamp: datetime = (lambda: datetime.now(UTC))(),
)

Parsed GMX v2 event.

属性:

名称 类型 描述
event_type GMXv2EventType

Type of event

event_name str

Name of event (e.g., "PositionIncrease")

log_index int

Index of log in transaction

transaction_hash str

Transaction hash

block_number int

Block number

contract_address str

Contract that emitted event

data dict[str, Any]

Parsed event data

raw_topics list[str]

Raw event topics

raw_data str

Raw event data

timestamp datetime

Event timestamp

to_dict

to_dict() -> dict[str, Any]

Convert to dictionary.

from_dict classmethod

from_dict(data: dict[str, Any]) -> GMXv2Event

Create from dictionary.

GMXv2EventType

Bases: Enum

GMX v2 event types.

GMXv2ReceiptParser

GMXv2ReceiptParser(**kwargs: Any)

Parser for GMX v2 transaction receipts.

This parser extracts and decodes GMX v2 events from transaction receipts, providing structured data for position updates, order fills, and other protocol events.

SUPPORTED_EXTRACTIONS declares the extraction fields this parser can provide. Used by ResultEnricher to warn when expected fields are unsupported.

Example

parser = GMXv2ReceiptParser()

Parse a receipt dict (from web3.py)

result = parser.parse_receipt(receipt)

if result.success: for event in result.events: print(f"Event: {event.event_name}")

for increase in result.position_increases:
    print(f"Position increased: size=${increase.size_in_usd}")

Initialize the parser.

参数:

名称 类型 描述 默认
**kwargs Any

Additional arguments (ignored for compatibility)

{}

parse_receipt

parse_receipt(receipt: dict[str, Any]) -> ParseResult

Parse a transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict containing 'logs', 'transactionHash', 'blockNumber', etc.

必需

返回:

类型 描述
ParseResult

ParseResult with extracted events and data

parse_logs

parse_logs(logs: list[dict[str, Any]]) -> list[GMXv2Event]

Parse a list of logs.

参数:

名称 类型 描述 默认
logs list[dict[str, Any]]

List of log dicts

必需

返回:

类型 描述
list[GMXv2Event]

List of parsed events

is_gmx_event

is_gmx_event(topic: str | bytes) -> bool

Check if a topic is a known GMX v2 event.

参数:

名称 类型 描述 默认
topic str | bytes

Event topic (supports bytes, hex string with/without 0x, any case)

必需

返回:

类型 描述
bool

True if topic is a known GMX v2 event

get_event_type

get_event_type(topic: str | bytes) -> GMXv2EventType

Get the event type for a topic.

参数:

名称 类型 描述 默认
topic str | bytes

Event topic (supports bytes, hex string with/without 0x, any case)

必需

返回:

类型 描述
GMXv2EventType

Event type or UNKNOWN

extract_swap_amounts

extract_swap_amounts(receipt: dict[str, Any]) -> Any

Extract swap amounts from transaction receipt.

GMX V2 swaps are executed through orders, not traditional swap events. For GMX orders: - amount_in = initial_collateral_delta_amount (collateral deposited) - amount_out = size_delta_usd (position size in USD, scaled by 1e30) - effective_price represents the leverage ratio

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
Any

SwapAmounts dataclass if swap order found, None otherwise

extract_position_id

extract_position_id(receipt: dict[str, Any]) -> str | None

Extract position ID (key) from transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
str | None

Position key if found, None otherwise

extract_size_delta

extract_size_delta(
    receipt: dict[str, Any],
) -> Decimal | None

Extract size delta (in USD) from transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
Decimal | None

Size delta in USD if found, None otherwise

extract_collateral

extract_collateral(
    receipt: dict[str, Any],
) -> Decimal | None

Extract collateral amount from transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
Decimal | None

Collateral amount if found, None otherwise

extract_entry_price

extract_entry_price(
    receipt: dict[str, Any],
) -> Decimal | None

Extract entry price from transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
Decimal | None

Entry price in USD if found, None otherwise

extract_leverage

extract_leverage(receipt: dict[str, Any]) -> Decimal | None

Extract leverage from transaction receipt.

Leverage is calculated as size_in_usd / (collateral_amount * collateral_token_price).

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
Decimal | None

Leverage multiplier (e.g., Decimal("10") for 10x) if found, None otherwise.

extract_realized_pnl

extract_realized_pnl(
    receipt: dict[str, Any],
) -> Decimal | None

Extract realized PnL from transaction receipt.

Only available for position decreases (closing/reducing positions).

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
Decimal | None

Realized PnL in USD if found, None otherwise

extract_exit_price

extract_exit_price(
    receipt: dict[str, Any],
) -> Decimal | None

Extract exit price from transaction receipt.

Only available for position decreases (closing/reducing positions).

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
Decimal | None

Exit price in USD if found, None otherwise

extract_fees_paid

extract_fees_paid(receipt: dict[str, Any]) -> int | None

Extract fees paid from transaction receipt.

参数:

名称 类型 描述 默认
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

必需

返回:

类型 描述
int | None

Execution fee in wei if found, None otherwise.

GMXV2SDK

GMXV2SDK(rpc_url: str, chain: str = 'arbitrum')

SDK for interacting with GMX V2 perpetuals on Arbitrum.

This SDK builds transactions for creating orders using the ExchangeRouter's multicall function which atomically: 1. Sends collateral to OrderVault (via sendWnt or sendTokens) 2. Creates the order

Initialize GMX V2 SDK.

参数:

名称 类型 描述 默认
rpc_url str

RPC endpoint URL

必需
chain str

Target chain (only 'arbitrum' supported currently)

'arbitrum'

get_market_address

get_market_address(index_token_symbol: str) -> str

Get GMX V2 market address for an index token.

参数:

名称 类型 描述 默认
index_token_symbol str

"ETH" or "BTC"

必需

返回:

类型 描述
str

Market address

get_execution_fee

get_execution_fee(
    order_type: str = "increase", multiplier: float = 1.5
) -> int

Calculate execution fee for GMX order dynamically.

GMX V2 validates: executionFee >= adjustedGasLimit * tx.gasprice where adjustedGasLimit = baseGasLimit + orderGasLimit * multiplierFactor (callbackGasLimit = 0 for our orders).

参数:

名称 类型 描述 默认
order_type str

"increase" or "decrease" to select appropriate gas limit

'increase'
multiplier float

Safety multiplier on top of the adjusted gas limit (default 1.5x for testing, use 2.0x for production)

1.5

返回:

类型 描述
int

Execution fee in wei

build_increase_order_multicall

build_increase_order_multicall(
    params: GMXV2OrderParams,
) -> GMXV2TransactionData

Build a multicall transaction to create an increase order.

This combines: 1. sendWnt or sendTokens (collateral to OrderVault) 2. createOrder

参数:

名称 类型 描述 默认
params GMXV2OrderParams

Order parameters

必需

返回:

类型 描述
GMXV2TransactionData

Transaction data ready for execution

build_decrease_order_multicall

build_decrease_order_multicall(
    params: GMXV2OrderParams,
) -> GMXV2TransactionData

Build a multicall transaction to create a decrease order.

For decrease orders, no collateral needs to be sent to OrderVault. Only the execution fee is needed, sent via sendWnt.

参数:

名称 类型 描述 默认
params GMXV2OrderParams

Order parameters

必需

返回:

类型 描述
GMXV2TransactionData

Transaction data ready for execution

DecreasePositionSwapType

Bases: IntEnum

GMX V2 Decrease Position Swap Types

GMXV2OrderParams dataclass

GMXV2OrderParams(
    from_address: str,
    market: str,
    initial_collateral_token: str,
    initial_collateral_delta_amount: int,
    size_delta_usd: int,
    is_long: bool,
    acceptable_price: int,
    execution_fee: int,
    trigger_price: int = 0,
    referral_code: bytes = b"\x00" * 32,
)

Parameters for creating a GMX V2 order.

GMXV2TransactionData dataclass

GMXV2TransactionData(
    to: str,
    value: int,
    data: str,
    gas_estimate: int,
    description: str,
)

Transaction data returned by the SDK.

OrderType

Bases: IntEnum

GMX V2 Order Types

get_gmx_v2_sdk

get_gmx_v2_sdk(
    rpc_url: str, chain: str = "arbitrum"
) -> GMXV2SDK

Factory function to create a GMX V2 SDK instance.