Installation

GmGnAPI is available on PyPI and can be installed using pip:

pip install gmgnapi

Development Installation

For development or to get the latest features:

git clone https://github.com/theshadow76/GmGnAPI.git
cd GmGnAPI
pip install -e .

GMGN Account Setup

Requirements

Python Version

Python 3.8 or higher

python --version

Dependencies

  • websockets >= 12.0
  • pydantic >= 2.0
  • aiofiles >= 23.0

Optional

  • pandas (for data analysis)
  • numpy (for numerical operations)
  • aiohttp (for webhook alerts)
# Install with optional dependencies
pip install gmgnapi[all]

# Or install specific optional dependencies
pip install gmgnapi[pandas,analysis]

Quick Start

Here's the fastest way to start receiving real-time data:

import asyncio
from gmgnapi import GmGnClient

async def main():
    # Create client instance
    async with GmGnClient() as client:
        # Subscribe to new liquidity pools
        await client.subscribe_new_pools(chain="sol")
        
        # Define event handler
        @client.on_new_pool
        async def handle_new_pool(pool_data):
            print(f"🆕 New pool detected!")
            for pool in pool_data.pools:
                if pool.bti:  # Base token info available
                    print(f"  Token: {pool.bti.s} ({pool.bti.n})")
                    print(f"  Market Cap: ${pool.bti.mc:,.2f}")
                    print(f"  Exchange: {pool.ex}")
                    print("-" * 40)
        
        # Start listening for messages
        print("🔥 Starting GMGN data stream...")
        await client.listen()

# Run the async function
if __name__ == "__main__":
    asyncio.run(main())

That's it!

Save this as quick_start.py and run it with python quick_start.py. You should start seeing real-time pool data!

Authentication

Some GMGN.ai channels require authentication. You can provide your access token in several ways:

1. Environment Variable (Recommended)

# Set environment variable
export GMGN_ACCESS_TOKEN="your_access_token_here"
# Client will automatically use the environment variable
async with GmGnClient() as client:
    await client.subscribe_wallet_trades()  # Requires auth

2. Direct Parameter

async with GmGnClient(access_token="your_token") as client:
    await client.subscribe_wallet_trades()

3. Configuration File

# config.json
{
    "access_token": "your_access_token_here",
    "default_chain": "sol"
}

# In your code
import json
with open('config.json') as f:
    config = json.load(f)

async with GmGnClient(access_token=config['access_token']) as client:
    # Your code here

Security Note

Never commit access tokens to version control. Use environment variables or secure configuration management.

Basic Usage Patterns

Available Subscriptions

New Pools

subscribe_new_pools()

Real-time new liquidity pool notifications

Token Updates

subscribe_token_updates()

Price and volume changes for specific tokens

Wallet Trades

subscribe_wallet_trades()

Trading activity from specific wallets

Multiple Subscriptions

async def multi_subscription_example():
    async with GmGnClient() as client:
        # Subscribe to multiple data streams
        await client.subscribe_new_pools(chain="sol")
        await client.subscribe_token_updates(tokens=["EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"])
        
        # Handle different event types
        @client.on_new_pool
        async def handle_pools(data):
            print(f"📊 New pool: {len(data.pools)} pools")
        
        @client.on_token_update
        async def handle_updates(data):
            print(f"💰 Token update: ${data.price_usd}")
        
        @client.on_error
        async def handle_error(error):
            print(f"❌ Error: {error}")
        
        await client.listen()

Chain Selection

# Solana (default)
await client.subscribe_new_pools(chain="sol")

# Ethereum
await client.subscribe_new_pools(chain="eth")

# Binance Smart Chain
await client.subscribe_new_pools(chain="bsc")

# Polygon
await client.subscribe_new_pools(chain="polygon")

Error Handling

GmGnAPI includes comprehensive error handling and automatic reconnection:

import logging
from gmgnapi import GmGnClient, GmGnAPIError

# Set up logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def robust_client_example():
    try:
        async with GmGnClient() as client:
            # Error event handler
            @client.on_error
            async def handle_error(error):
                logger.error(f"WebSocket error: {error}")
                # Custom error handling logic here
            
            # Connection event handlers
            @client.on_connect
            async def handle_connect():
                logger.info("✅ Connected to GMGN WebSocket")
            
            @client.on_disconnect
            async def handle_disconnect():
                logger.warning("⚠️ Disconnected from GMGN WebSocket")
            
            @client.on_reconnect
            async def handle_reconnect():
                logger.info("🔄 Reconnected to GMGN WebSocket")
            
            await client.subscribe_new_pools()
            await client.listen()
            
    except GmGnAPIError as e:
        logger.error(f"GMGN API Error: {e}")
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
        raise

Common Error Types

ConnectionError

Network connectivity issues - automatically retried with exponential backoff

AuthenticationError

Invalid or missing access token for authenticated channels

ValidationError

Invalid data received from the API - check your subscription parameters

Next Steps

Pro Tips

  • Use the enhanced client (GmGnEnhancedClient) for production applications
  • Enable logging to debug connection issues
  • Consider implementing data persistence for important events
  • Monitor your application's memory usage with long-running connections
  • Join our GitHub Discussions for community support