Getting Started

Getting Started with AxiomTradeAPI-py

This tutorial takes you from zero to a working Solana trading application in about 30 minutes — querying balances, monitoring new tokens in real time, and building a simple trading bot.

What You’ll Learn

By the end of this guide you’ll be able to:

  • Install and configure AxiomTradeAPI-py
  • Connect to the Axiom Trade API
  • Query wallet balances and monitor portfolios
  • Set up real-time token monitoring
  • Build a first automated trading bot
  • Apply basic error handling and security practices

Prerequisites

  • Python 3.8+ (3.10+ recommended), 4GB+ RAM, a stable internet connection
  • Basic Python knowledge: variables, functions, dictionaries/lists, and a little async/await (explained as we go)
  • A code editor, a terminal, and an Axiom Trade account

Step 1: Install and Set Up a Project

mkdir solana-trading-bot
cd solana-trading-bot

python -m venv trading-env
source trading-env/bin/activate   # macOS/Linux
trading-env\Scripts\activate      # Windows

pip install axiomtradeapi python-dotenv

See the full Installation guide for Docker, from-source, and optional-extras setups. A typical project looks like:

solana-trading-bot/
├── .env                 # environment variables (never commit this)
├── config.py            # configuration settings
├── portfolio_tracker.py # portfolio monitoring example
├── token_monitor.py     # real-time token monitoring
├── simple_bot.py         # your first trading bot
└── utils.py             # helper functions

Step 2: Authentication Setup

Advanced features like WebSocket subscriptions require authentication tokens:

  1. Visit Axiom Trade and sign in
  2. Open developer tools (F12) → Application/Storage tab
  3. Find the auth-access-token and auth-refresh-token cookies and copy their values

Create a .env file (never commit this to version control):

AXIOM_AUTH_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
AXIOM_REFRESH_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...

Then a config.py:

import os
from dotenv import load_dotenv

load_dotenv()

class Config:
    """Configuration settings for our trading application"""

    AUTH_TOKEN = os.getenv('AXIOM_AUTH_TOKEN')
    REFRESH_TOKEN = os.getenv('AXIOM_REFRESH_TOKEN')

    MAX_POSITION_SIZE = 1.0  # Maximum SOL per trade
    RISK_PER_TRADE = 0.02    # 2% risk per trade

    PORTFOLIO_CHECK_INTERVAL = 60  # seconds

    TEST_WALLETS = [
        "BJBgjyDZx5FSsyJf6bFKVXuJV7DZY9PCSMSi5d9tcEVh",
        "Cpxu7gFhu3fDX1eG5ZVyiFoPmgxpLWiu5LhByNenVbPb",
    ]

if not Config.AUTH_TOKEN:
    print("Warning: No AUTH_TOKEN found. Some features will be limited.")

See Authentication for the full range of authentication methods, including automatic token refresh.

Step 3: Your First Balance Query

Create portfolio_tracker.py:

import logging
from axiomtradeapi import AxiomTradeClient
from config import Config

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class PortfolioTracker:
    """Simple portfolio tracking for Solana wallets"""

    def __init__(self):
        self.client = AxiomTradeClient(log_level=logging.INFO)
        logger.info("Portfolio tracker initialized")

    def check_single_wallet(self, wallet_address):
        try:
            balance = self.client.GetBalance(wallet_address)
            print(f"Wallet: {wallet_address}")
            print(f"  SOL Balance: {balance['sol']:.6f}")
            print(f"  Lamports: {balance['lamports']:,}")
            print(f"  Slot: {balance['slot']}")
            return balance
        except Exception as e:
            logger.error(f"Error checking wallet balance: {e}")
            return None

    def check_multiple_wallets(self, wallet_addresses):
        try:
            balances = self.client.GetBatchedBalance(wallet_addresses)
            total_sol = 0
            active_wallets = 0

            for address, balance_data in balances.items():
                if balance_data:
                    total_sol += balance_data['sol']
                    active_wallets += 1
                    print(f"  {address[:8]}...{address[-8:]}: {balance_data['sol']:.6f} SOL")
                else:
                    print(f"  {address[:8]}...{address[-8:]}: error")

            print(f"Total wallets: {len(wallet_addresses)}, active: {active_wallets}, total SOL: {total_sol:.6f}")
            return balances
        except Exception as e:
            logger.error(f"Error checking portfolio: {e}")
            return None

def main():
    tracker = PortfolioTracker()
    tracker.check_single_wallet(Config.TEST_WALLETS[0])
    tracker.check_multiple_wallets(Config.TEST_WALLETS)

if __name__ == "__main__":
    main()
python portfolio_tracker.py

See Balance Queries for batch operations and more advanced monitoring patterns.

Step 4: Real-Time Token Monitoring

Create token_monitor.py:

import asyncio
import logging
from datetime import datetime
from axiomtradeapi import AxiomTradeClient
from config import Config

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class TokenMonitor:
    """Real-time token launch monitoring"""

    def __init__(self):
        self.client = AxiomTradeClient(
            auth_token=Config.AUTH_TOKEN,
            refresh_token=Config.REFRESH_TOKEN,
            log_level=logging.INFO
        )
        self.min_market_cap = 5.0
        self.min_liquidity = 10.0
        self.tokens_found = 0
        self.qualified_tokens = 0

    async def handle_new_tokens(self, tokens):
        for token in tokens:
            self.tokens_found += 1

            market_cap = token.get('marketCapSol', 0)
            liquidity = token.get('liquiditySol', 0)
            meets_criteria = market_cap >= self.min_market_cap and liquidity >= self.min_liquidity

            if meets_criteria:
                self.qualified_tokens += 1

            print(f"New token: {token.get('tokenName', 'Unknown')} ({token.get('tokenTicker', 'N/A')})")
            print(f"  Market cap: {market_cap:.2f} SOL, liquidity: {liquidity:.2f} SOL")
            print(f"  Status: {'qualified' if meets_criteria else 'filtered'}, time: {datetime.now().strftime('%H:%M:%S')}")

    async def start_monitoring(self):
        logger.info("Starting real-time token monitoring...")
        await self.client.subscribe_new_tokens(self.handle_new_tokens)
        await self.client.ws.start()

async def main():
    if not Config.AUTH_TOKEN:
        print("No authentication token found. See the authentication guide for setup.")
        return

    monitor = TokenMonitor()
    await monitor.start_monitoring()

if __name__ == "__main__":
    asyncio.run(main())
python token_monitor.py

See WebSocket Integration for reconnection handling, filtering, and performance tuning.

Step 5: Build Your First Trading Bot

Create simple_bot.py, combining balance checks and token monitoring into a minimal bot skeleton:

import asyncio
import logging
from datetime import datetime
from axiomtradeapi import AxiomTradeClient
from config import Config

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("TradingBot")

class SimpleTradingBot:
    """A simple trading bot for educational purposes"""

    def __init__(self):
        self.client = AxiomTradeClient(
            auth_token=Config.AUTH_TOKEN,
            refresh_token=Config.REFRESH_TOKEN,
            log_level=logging.INFO
        )
        self.config = {
            'max_position_size': Config.MAX_POSITION_SIZE,
            'min_market_cap': 20.0,
            'min_liquidity': 50.0,
            'target_profit': 0.15,
            'stop_loss': -0.05,
        }
        self.active_positions = {}
        self.is_running = False

    async def start(self):
        self.is_running = True
        await asyncio.gather(
            self.token_monitoring_task(),
            self.portfolio_monitoring_task(),
        )

    async def token_monitoring_task(self):
        await self.client.subscribe_new_tokens(self.analyze_new_token)
        await self.client.ws.start()

    async def analyze_new_token(self, tokens):
        for token in tokens:
            if not self.passes_initial_filters(token):
                continue
            signal_strength = self.calculate_signal_strength(token)
            if signal_strength > 0.7:
                logger.info(f"Strong signal for {token.get('tokenName')}: {signal_strength:.2f}")
                # execute_buy_order(token, signal_strength) would go here in a real bot

    def passes_initial_filters(self, token):
        if token.get('marketCapSol', 0) < self.config['min_market_cap']:
            return False
        if token.get('liquiditySol', 0) < self.config['min_liquidity']:
            return False
        return len(self.active_positions) < 3

    def calculate_signal_strength(self, token):
        score = 0.0
        market_cap = token.get('marketCapSol', 0)
        if market_cap > 100:
            score += 0.3
        elif market_cap > 50:
            score += 0.2

        liquidity = token.get('liquiditySol', 0)
        if liquidity > 200:
            score += 0.3
        elif liquidity > 100:
            score += 0.2

        if token.get('protocol') in ('Raydium', 'Orca', 'Jupiter'):
            score += 0.2

        return score

    async def portfolio_monitoring_task(self):
        while self.is_running:
            balances = self.client.GetBatchedBalance(Config.TEST_WALLETS)
            total_sol = sum(b['sol'] for b in balances.values() if b)
            logger.info(f"Portfolio value: {total_sol:.6f} SOL")
            await asyncio.sleep(Config.PORTFOLIO_CHECK_INTERVAL)

async def main():
    if not Config.AUTH_TOKEN:
        print("No authentication token found. Set up your .env file for WebSocket features.")
        return

    bot = SimpleTradingBot()
    await bot.start()

if __name__ == "__main__":
    asyncio.run(main())

This is a learning skeleton, not a production bot — it does not execute real trades. See Building Trading Bots for full strategies (sniping, market making, arbitrage), risk management, and production deployment, and Buying and Selling Tokens for actually executing trades.

Step 6: Security and Error Handling

A couple of small utilities worth adding early on:

# utils.py
from functools import wraps

def require_auth(func):
    """Decorator to ensure authentication is available"""
    @wraps(func)
    def wrapper(*args, **kwargs):
        from config import Config
        if not Config.AUTH_TOKEN:
            raise ValueError("Authentication required for this operation")
        return func(*args, **kwargs)
    return wrapper

def validate_wallet_address(address):
    """Validate Solana wallet address format"""
    if not address or len(address) != 44:
        raise ValueError(f"Invalid Solana address: {address}")
    return True
import asyncio
from functools import wraps

def retry_on_failure(max_retries=3, delay=1):
    """Decorator for retrying failed async operations"""
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            for attempt in range(max_retries):
                try:
                    return await func(*args, **kwargs)
                except Exception as e:
                    if attempt == max_retries - 1:
                        raise
                    await asyncio.sleep(delay)
            return None
        return wrapper
    return decorator

See Security and Error Handling for the full guides.

Step 7: Testing Your Setup

# test_setup.py
import asyncio
import logging
from axiomtradeapi import AxiomTradeClient
from config import Config

async def run_comprehensive_test():
    tests_passed = 0
    tests_failed = 0

    try:
        client = AxiomTradeClient(log_level=logging.WARNING)
        tests_passed += 1
    except Exception as e:
        print(f"Client initialization failed: {e}")
        return

    try:
        balance = client.GetBalance(Config.TEST_WALLETS[0])
        print(f"Balance query OK: {balance['sol']} SOL")
        tests_passed += 1
    except Exception as e:
        print(f"Balance query failed: {e}")
        tests_failed += 1

    try:
        balances = client.GetBatchedBalance(Config.TEST_WALLETS)
        print(f"Batch query OK: {len(balances)} wallets")
        tests_passed += 1
    except Exception as e:
        print(f"Batch query failed: {e}")
        tests_failed += 1

    print(f"Passed: {tests_passed}, Failed: {tests_failed}")

if __name__ == "__main__":
    asyncio.run(run_comprehensive_test())
python test_setup.py

Common Issues

No module named 'axiomtradeapi'

pip install axiomtradeapi

Authentication failed

python -c "from config import Config; print('Auth token:', bool(Config.AUTH_TOKEN))"

Network timeout — check your internet connection; the SDK has built-in retry logic. For anything beyond these basics, see the full Troubleshooting guide.

Next Steps

Project ideas to try next: a portfolio tracker with alerts, a token-launch notifier, an arbitrage scanner, or a multi-wallet management dashboard.