API Reference

πŸš€ New to GMGN.ai? Create your account with our referral link to support GmGnAPI’s development β†’ Sign up on GMGN.ai
πŸ’¬ Need help? Join the Chipa Discord Β· ⚑ Go no-code with ChipaEditor

Complete reference documentation for all GmGnAPI classes, methods, and data models.

GmGnClient

Basic WebSocket client for connecting to GMGN.ai’s real-time data streams. Provides core functionality with automatic reconnection and event handling.

class GmGnClient(
    websocket_url: str = "wss://gmgn.ai/ws",
    access_token: Optional[str] = None,
    max_reconnect_attempts: int = 10,
    reconnect_delay: float = 1.0,
    heartbeat_interval: float = 30.0
)

Constructor parameters

ParameterTypeDefaultDescription
websocket_urlstr"wss://gmgn.ai/ws"WebSocket endpoint URL
access_tokenOptional[str]NoneAuthentication token for protected channels
max_reconnect_attemptsint10Maximum number of reconnection attempts
reconnect_delayfloat1.0Initial delay between reconnection attempts (seconds)
heartbeat_intervalfloat30.0Heartbeat ping interval (seconds)

Methods

async subscribe_new_pools(chain: str = "sol") -> None

Subscribe to real-time new liquidity pool notifications.

await client.subscribe_new_pools(chain="sol")

async subscribe_token_updates(tokens: List[str], chain: str = "sol") -> None

Subscribe to price and volume updates for specific tokens.

tokens = ["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"]
await client.subscribe_token_updates(tokens, chain="sol")

async subscribe_wallet_trades(wallets: List[str], chain: str = "sol") -> None

Subscribe to trading activity from specific wallet addresses.

wallets = ["wallet_address_here"]
await client.subscribe_wallet_trades(wallets, chain="sol")

async listen() -> None

Start listening for WebSocket messages and dispatch events.

await client.listen()  # Runs until connection closes

async connect() -> None

Establish WebSocket connection manually.

async disconnect() -> None

Close WebSocket connection gracefully.

Event decorators

DecoratorFires when
@client.on_new_poolA new pool notification arrives
@client.on_token_updateA token price/volume update arrives
@client.on_wallet_tradeWallet trading activity arrives
@client.on_errorA connection or data error occurs
@client.on_connectThe connection is established
@client.on_disconnectThe connection drops
@client.on_new_pool
async def handle_new_pool(pool_data: NewPoolInfo):
    print(f"New pool: {pool_data.chain}")

@client.on_token_update
async def handle_update(update: PairUpdateData):
    print(f"Price: ${update.price_usd}")

GmGnEnhancedClient

Advanced WebSocket client with filtering, monitoring, data export, and alerting capabilities. Extends GmGnClient with enterprise-grade features for production use.

class GmGnEnhancedClient(GmGnClient):
    def __init__(
        self,
        token_filter: Optional[TokenFilter] = None,
        export_config: Optional[DataExportConfig] = None,
        alert_config: Optional[AlertConfig] = None,
        enable_statistics: bool = True,
        **kwargs
    )

Additional parameters

ParameterTypeDescription
token_filterOptional[TokenFilter]Filter configuration for token screening
export_configOptional[DataExportConfig]Data export settings (JSON, CSV, database)
alert_configOptional[AlertConfig]Alert and notification configuration
enable_statisticsboolEnable real-time statistics collection

Enhanced methods

get_statistics() -> MonitoringStats

Get current monitoring statistics and metrics.

stats = client.get_statistics()
print(f"Messages: {stats.total_messages}")
print(f"Uptime: {stats.connection_uptime}s")

async export_data(format: str = "json", file_path: Optional[str] = None) -> str

Export collected data to the specified format.

file_path = await client.export_data("csv", "data.csv")
print(f"Data exported to: {file_path}")

update_filter(new_filter: TokenFilter) -> None

Update token filtering criteria dynamically.

add_alert_condition(condition: Dict[str, Any]) -> None

Add a new alert condition at runtime.

Enhanced events

DecoratorFires when
@client.on_filtered_poolA pool passes all filter criteria
@client.on_alert_triggeredAlert conditions are met
@client.on_statistics_updatePeriodic statistics updates (every 60 seconds)

Data Models

Pydantic data models for type-safe data handling and validation.

NewPoolInfo

Information about new liquidity pools.

  • c: str β€” Chain identifier
  • p: List[PoolData] β€” Pool data list
  • rg: Optional[str] β€” Region

PoolData

Individual pool information.

  • a: str β€” Pool address
  • ex: str β€” Exchange name
  • ba: str β€” Base token address
  • qa: str β€” Quote token address
  • bti: Optional[TokenInfo] β€” Base token info

TokenInfo

Detailed token information.

  • s: Optional[str] β€” Symbol
  • n: Optional[str] β€” Name
  • mc: Optional[int] β€” Market cap
  • v24h: Optional[float] β€” 24h volume
  • p: Optional[float] β€” Price

PairUpdateData

Trading pair price/volume updates.

  • pair_address: str
  • token_address: str
  • price_usd: Optional[Decimal]
  • volume_24h_usd: Optional[Decimal]
  • chain: str

WalletTradeData

Wallet trading activity.

  • wallet_address: str
  • chain: str
  • trades: List[TradeData]
  • total_volume_24h_usd: Optional[Decimal]

TradeData

Individual trade information.

  • transaction_hash: str
  • trade_type: Literal["buy", "sell"]
  • amount_usd: Decimal
  • timestamp: datetime

Configuration Models

TokenFilter

Configure token filtering criteria:

from decimal import Decimal
from gmgnapi import TokenFilter

filter_config = TokenFilter(
    min_market_cap=Decimal("100000"),     # $100K minimum
    max_market_cap=Decimal("10000000"),   # $10M maximum
    min_liquidity=Decimal("50000"),       # $50K minimum liquidity
    min_volume_24h=Decimal("10000"),      # $10K 24h volume
    exchanges=["raydium", "orca"],        # Specific exchanges
    max_risk_score=0.3                    # Low risk only
)

See the Filters Guide for every parameter.

DataExportConfig

Configure data export settings:

from gmgnapi import DataExportConfig

export_config = DataExportConfig(
    enabled=True,
    format="json",                        # "json", "csv", "parquet"
    file_path="./data/pools.json",
    max_file_size_mb=100,
    rotation_interval_hours=24,
    compress=True,
    include_metadata=True
)

AlertConfig

Configure alerts and notifications:

from gmgnapi import AlertConfig

alert_config = AlertConfig(
    enabled=True,
    webhook_url="https://hooks.slack.com/...",
    email="alerts@example.com",
    conditions=[
        {
            "field": "market_cap",
            "operator": ">",
            "value": 1000000
        },
        {
            "field": "volume_24h",
            "operator": ">",
            "value": 500000
        }
    ],
    rate_limit_seconds=60
)

Exceptions

ExceptionRaised when
GmGnAPIErrorBase exception class for all GmGnAPI errors
ConnectionErrorWebSocket connection fails
AuthenticationErrorAuthentication fails for protected channels
ValidationErrorReceived data fails validation
SubscriptionErrorSubscription to a channel fails

Exception handling example

from gmgnapi import GmGnClient, GmGnAPIError, AuthenticationError

try:
    async with GmGnClient() as client:
        await client.subscribe_wallet_trades(["wallet_address"])
        await client.listen()
except AuthenticationError as e:
    print(f"Authentication failed: {e}")
except GmGnAPIError as e:
    print(f"API error: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")

More Resources