Skip to content

GMX V2

Connector for GMX V2 perpetuals protocol.

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.

Parameters:

Name Type Description Default
config GMXv2Config

GMX v2 adapter configuration

required
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.

Parameters:

Name Type Description Default
market str

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

required
collateral_token str

Token symbol or address for collateral

required
collateral_amount Decimal

Amount of collateral in token decimals

required
size_delta_usd Decimal

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

required
is_long bool

True for long, False for short

required
acceptable_price Decimal | None

Maximum (long) or minimum (short) execution price

None
trigger_price Decimal | None

Trigger price for limit orders

None

Returns:

Type Description
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.

Parameters:

Name Type Description Default
market str

Market identifier or address

required
collateral_token str

Token symbol or address for collateral

required
is_long bool

Position direction

required
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

Returns:

Type Description
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.

Parameters:

Name Type Description Default
market str

Market identifier or address

required
collateral_token str

Token symbol or address

required
is_long bool

Position direction

required
collateral_delta Decimal

Additional collateral to add

required
size_delta_usd Decimal

Additional size in USD

required
acceptable_price Decimal | None

Maximum (long) or minimum (short) execution price

None
trigger_price Decimal | None

Trigger price for limit orders

None

Returns:

Type Description
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.

Parameters:

Name Type Description Default
market str

Market identifier or address

required
collateral_token str

Token symbol or address

required
is_long bool

Position direction

required
size_delta_usd Decimal

Size to reduce in USD

required
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

Returns:

Type Description
OrderResult

OrderResult with order details

get_position

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

Get position details.

Parameters:

Name Type Description Default
market str

Market identifier or address

required
collateral_token str

Token symbol or address

required
is_long bool

Position direction

required

Returns:

Type Description
GMXv2Position | None

Position details or None if not found

get_all_positions

get_all_positions() -> list[GMXv2Position]

Get all open positions.

Returns:

Type Description
list[GMXv2Position]

List of all open positions

cancel_order

cancel_order(order_key: str) -> OrderResult

Cancel a pending order.

Parameters:

Name Type Description Default
order_key str

Order key to cancel

required

Returns:

Type Description
OrderResult

OrderResult indicating success/failure

get_order

get_order(order_key: str) -> GMXv2Order | None

Get order details.

Parameters:

Name Type Description Default
order_key str

Order key to look up

required

Returns:

Type Description
GMXv2Order | None

Order details or None if not found

get_all_orders

get_all_orders() -> list[GMXv2Order]

Get all pending orders.

Returns:

Type Description
list[GMXv2Order]

List of all pending orders

set_position

set_position(position: GMXv2Position) -> None

Set a position for testing.

Parameters:

Name Type Description Default
position GMXv2Position

Position to set

required

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.

Attributes:

Name Type Description
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.

Attributes:

Name Type Description
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.

Attributes:

Name Type Description
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.

Attributes:

Name Type Description
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.

Parameters:

Name Type Description Default
**kwargs Any

Additional arguments (ignored for compatibility)

{}

parse_receipt

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

Parse a transaction receipt.

Parameters:

Name Type Description Default
receipt dict[str, Any]

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

required

Returns:

Type Description
ParseResult

ParseResult with extracted events and data

parse_logs

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

Parse a list of logs.

Parameters:

Name Type Description Default
logs list[dict[str, Any]]

List of log dicts

required

Returns:

Type Description
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.

Parameters:

Name Type Description Default
topic str | bytes

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

required

Returns:

Type Description
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.

Parameters:

Name Type Description Default
topic str | bytes

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

required

Returns:

Type Description
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

Parameters:

Name Type Description Default
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

required

Returns:

Type Description
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.

Parameters:

Name Type Description Default
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

required

Returns:

Type Description
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.

Parameters:

Name Type Description Default
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

required

Returns:

Type Description
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.

Parameters:

Name Type Description Default
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

required

Returns:

Type Description
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.

Parameters:

Name Type Description Default
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

required

Returns:

Type Description
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).

Parameters:

Name Type Description Default
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

required

Returns:

Type Description
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).

Parameters:

Name Type Description Default
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

required

Returns:

Type Description
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).

Parameters:

Name Type Description Default
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

required

Returns:

Type Description
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.

Parameters:

Name Type Description Default
receipt dict[str, Any]

Transaction receipt dict with 'logs' field

required

Returns:

Type Description
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.

Parameters:

Name Type Description Default
rpc_url str

RPC endpoint URL

required
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.

Parameters:

Name Type Description Default
index_token_symbol str

"ETH" or "BTC"

required

Returns:

Type Description
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

Parameters:

Name Type Description Default
order_type str

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

'increase'
multiplier float

Safety multiplier (default 1.5x for testing, use 2.0x for production)

1.5

Returns:

Type Description
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

Parameters:

Name Type Description Default
params GMXV2OrderParams

Order parameters

required

Returns:

Type Description
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.

Parameters:

Name Type Description Default
params GMXV2OrderParams

Order parameters

required

Returns:

Type Description
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.