GetBalance() Method

Retrieve SOL balances for any Solana wallet address in your trading applications

Read-Only
No gas fees
Instant
Real-time data
Legacy
Stable & reliable
Simple
One-line usage

Overview

The GetBalance() method is a fundamental tool in the AxiomTradeAPI that allows you to retrieve the SOL (Solana native token) balance for any Solana wallet address. This method is essential for building trading bots, portfolio trackers, and balance monitoring systems.

This is a legacy method maintained for backward compatibility. For new implementations, consider using get_sol_balance() which provides the same functionality with a more modern interface.

Key Features

  • Check SOL balance for any Solana wallet instantly
  • Returns balance in both SOL and lamports formats
  • Automatic authentication and session management
  • No transaction fees - read-only operation
  • Perfect for pre-trade balance verification

Trading Bots

Verify sufficient balance before executing trades

Portfolio Tracking

Monitor balances across multiple wallets

Payment Systems

Verify payment receipt and wallet funding

Risk Management

Implement safety checks for automated systems

Method Signature

python
def GetBalance(self, wallet_address: str) -> Dict[str, Union[float, int]]

Parameters

ParameterTypeRequiredDescription
wallet_addressstrYesA valid Solana wallet address (base58 encoded public key)

Return Value

Returns a dictionary with the following structure:

python
{
    "sol": float,        # Balance in SOL (e.g., 1.5 SOL)
    "lamports": int,     # Balance in lamports (1 SOL = 1,000,000,000 lamports)
    "slot": int          # Blockchain slot (always 0 for this method)
}

Returns None if the request fails or the wallet address is invalid.

Prerequisites

1. Install the Package

bash
pip install axiomtradeapi

2. Authentication Setup

You need valid Axiom Trade credentials. Set up authentication using one of these methods:

Method A: Environment Variables (Recommended)

bash
export AXIOM_ACCESS_TOKEN='your_access_token'
export AXIOM_REFRESH_TOKEN='your_refresh_token'

Or create a .env file:

bash
AXIOM_ACCESS_TOKEN=your_access_token
AXIOM_REFRESH_TOKEN=your_refresh_token

Method B: Direct Login

python
from axiomtradeapi import AxiomTradeClient

client = AxiomTradeClient()
client.login(email, base64_password, otp_code)

Basic Usage

Example 1: Simple Balance Check

python
from axiomtradeapi import AxiomTradeClient

# Initialize client
client = AxiomTradeClient()

# Get balance for a wallet
wallet_address = "BJBgjyDZx5FSsyJf6bFKVXuJV7DZY9PCSMSi5d9tcEVh"
balance = client.GetBalance(wallet_address)

if balance:
    print(f"Wallet Balance: {balance['sol']} SOL")
    print(f"Lamports: {balance['lamports']}")
else:
    print("Failed to retrieve balance")

Output:

Wallet Balance: 2.543891234 SOL
Lamports: 2543891234

Example 2: Check Your Own Wallet

python
from axiomtradeapi import AxiomTradeClient
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Initialize client with authentication
client = AxiomTradeClient()

# Your wallet address
my_wallet = os.getenv("WALLET_ADDRESS")
balance = client.GetBalance(my_wallet)

if balance:
    print(f"💰 Your Balance: {balance['sol']} SOL")
    print(f"📊 In Lamports: {balance['lamports']:,}")
else:
    print("❌ Could not fetch balance")

Example 3: Pre-Trade Balance Verification

python
from axiomtradeapi import AxiomTradeClient

def can_afford_trade(wallet_address: str, required_sol: float) -> bool:
    """Check if wallet has enough SOL for a trade"""
    client = AxiomTradeClient()
    balance = client.GetBalance(wallet_address)
    
    if balance:
        return balance['sol'] >= required_sol
    return False

# Usage
my_wallet = "YourWalletAddressHere"
trade_amount = 0.5  # SOL

if can_afford_trade(my_wallet, trade_amount):
    print("✅ Sufficient balance for trade")
else:
    print("❌ Insufficient balance")

Advanced Examples

Build production-ready applications with these advanced patterns including portfolio tracking, balance monitoring, and trading bot integration.

🏦 Multi-Wallet Monitoring

Track balances across multiple wallets efficiently

check_multiple_wallets()

📊 Portfolio Tracker

Build complete portfolio tracking systems

PortfolioTracker class

⚠️ Balance Alert System

Set up automated low-balance alerts

BalanceAlert class

🤖 Trading Bot Integration

Safe balance management for bots

TradingBot class

View the complete guide with 8+ advanced examples, error handling patterns, and production best practices

View Full Documentation on GitHub

Error Handling

Common Issues

  • Returns None: Invalid wallet address, expired auth token, or network issues
  • Slow Response: Network congestion or API rate limiting
  • Authentication Failed: Invalid or expired credentials

Robust Error Handling Example

python
from axiomtradeapi import AxiomTradeClient
from typing import Optional, Dict

def safe_balance_check(wallet_address: str) -> Optional[Dict]:
    """Safely check balance with validation"""
    client = AxiomTradeClient()
    
    # Validate address format
    if not wallet_address or len(wallet_address) < 32:
        print(f"❌ Invalid wallet address: {wallet_address}")
        return None
    
    try:
        balance = client.GetBalance(wallet_address)
        
        if balance is None:
            print(f"❌ Failed to retrieve balance")
            return None
        
        return balance
    
    except Exception as e:
        print(f"❌ Error checking balance: {str(e)}")
        return None

# Usage
result = safe_balance_check("YourWalletAddress")
if result:
    print(f"✅ Balance: {result['sol']} SOL")

Best Practices

DO

  • • Cache balance results for frequent checks
  • • Implement retry logic for failed requests
  • • Validate wallet addresses before querying
  • • Use rate limiting for batch operations
  • • Log balance history for audit trails

DON'T

  • • Make excessive API calls without caching
  • • Assume balance check will always succeed
  • • Skip input validation
  • • Ignore rate limiting errors
  • • Store sensitive data in plain text

💡 Pro Tip: Balance Caching

For applications that check balances frequently, implement a caching strategy to reduce API calls and improve performance:

python
from datetime import datetime, timedelta

class CachedBalanceChecker:
    def __init__(self, cache_duration_seconds=60):
        self.client = AxiomTradeClient()
        self.cache = {}
        self.cache_duration = timedelta(seconds=cache_duration_seconds)
    
    def get_balance(self, wallet: str, use_cache=True):
        # Check cache first
        if use_cache and wallet in self.cache:
            cached = self.cache[wallet]
            if datetime.now() - cached['time'] < self.cache_duration:
                return cached['balance']
        
        # Fetch fresh data
        balance = self.client.GetBalance(wallet)
        if balance:
            self.cache[wallet] = {
                'balance': balance,
                'time': datetime.now()
            }
        return balance

Troubleshooting

Issue: Method Returns None

Possible causes:

  • Invalid wallet address format
  • Authentication token expired
  • Network connectivity issues
  • API service temporarily unavailable

Solution: Verify your authentication status with client.ensure_authenticated() and validate the wallet address format.

Issue: Slow Response Time

Solution: Implement timeout handling and consider using batch operations for multiple wallet checks. Add delay between requests to respect rate limits.

Issue: Balance Shows 0 for Funded Wallet

Solution: Ensure you're checking the correct network (mainnet vs devnet). Verify the wallet address is correct and has received transactions.

Still Need Help?

Our community and support team are here to help you succeed with AxiomTradeAPI

Build Your Trading Bot Today

Need help implementing GetBalance() in your trading system? Our expert team can build a custom solution for you.

Open Source

Contribute to AxiomTradeAPI

View on GitHub

Community

Join 1000+ developers

Join Discord

Custom Bots

Professional development

Get Started