Documentation/Balance Queries
šŸ’°

Balance Queries

Complete guide to Solana wallet monitoring and portfolio tracking

Intermediate20 minutes

šŸš€ Quick Start: Basic Balance Query

Single Wallet Query
from axiomtradeapi import AxiomTradeClient

# Initialize the client
client = AxiomTradeClient()

# Query any Solana wallet balance
wallet_address = "BJBgjyDZx5FSsyJf6bFKVXuJV7DZY9PCSMSi5d9tcEVh"
balance = client.GetBalance(wallet_address)

print(f"šŸ’° Wallet Balance:")
print(f"   SOL: {balance['sol']}")
print(f"   Lamports: {balance['lamports']:,}")
print(f"   Slot: {balance['slot']}")
Output
šŸ’° Wallet Balance:
   SOL: 1.234567890
   Lamports: 1,234,567,890
   Slot: 344031778

⚔ High-Performance Batch Operations

Monitor up to 1,000 wallets in a single API call for optimal performance:

Batch Query Example
from axiomtradeapi import AxiomTradeClient

client = AxiomTradeClient()

# Monitor multiple wallets simultaneously
wallet_addresses = [
    "BJBgjyDZx5FSsyJf6bFKVXuJV7DZY9PCSMSi5d9tcEVh",
    "Cpxu7gFhu3fDX1eG5ZVyiFoPmgxpLWiu5LhByNenVbPb",
    "DsHk4F6QNTK6RdTmaDSKeFzGXMnQ9QxKTkDkG8XF8F4F",
    "8YLKwP3nQtVsF7X9mR2wCvBqA3n4H5kJ9L6mN1oP2qR3"
]

# Batch query - much faster than individual calls
balances = client.GetBatchedBalance(wallet_addresses)

print("šŸ“Š Portfolio Summary:")
total_sol = 0

for address, balance_data in balances.items():
    if balance_data:
        sol_amount = balance_data['sol']
        total_sol += sol_amount
        print(f"   {address[:8]}...{address[-8:]}: {sol_amount:.6f} SOL")
    else:
        print(f"   {address[:8]}...{address[-8:]}: āŒ Error")

print(f"\nšŸ’Ž Total Portfolio Value: {total_sol:.6f} SOL")
⚔

Performance Benefits

Batch operations are 50-100x faster than individual queries:

  • • Single API call for up to 1,000 wallets
  • • Reduced network overhead
  • • Lower rate limit consumption
  • • Ideal for portfolio tracking and trading bots

šŸ† Advanced: Portfolio Performance Tracker

Build a comprehensive portfolio monitoring system with historical tracking:

portfolio_tracker.py
import time
import json
from datetime import datetime
from axiomtradeapi import AxiomTradeClient

class SolanaPortfolioTracker:
    def __init__(self, wallets_file="portfolio_wallets.json"):
        self.client = AxiomTradeClient()
        self.wallets_file = wallets_file
        self.portfolio_history = []
        
    def load_wallets(self):
        """Load wallet addresses from JSON file"""
        try:
            with open(self.wallets_file, 'r') as f:
                data = json.load(f)
                return data.get('wallets', [])
        except FileNotFoundError:
            print(f"āš ļø  {self.wallets_file} not found. Create it with your wallet addresses.")
            return []
    
    def track_portfolio(self, interval=60):
        """Track portfolio balance over time"""
        wallets = self.load_wallets()
        
        if not wallets:
            print("āŒ No wallets to track")
            return
        
        print(f"šŸ” Tracking {len(wallets)} wallets every {interval} seconds")
        print("Press Ctrl+C to stop\n")
        
        try:
            while True:
                # Get current balances
                balances = self.client.GetBatchedBalance(wallets)
                
                # Calculate metrics
                total_sol = sum(
                    b['sol'] for b in balances.values() if b
                )
                
                timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                
                # Store in history
                snapshot = {
                    'timestamp': timestamp,
                    'total_sol': total_sol,
                    'wallet_count': len([b for b in balances.values() if b])
                }
                self.portfolio_history.append(snapshot)
                
                # Display current status
                print(f"[{timestamp}]")
                print(f"   šŸ’° Total SOL: {total_sol:.6f}")
                print(f"   šŸ“Š Active Wallets: {snapshot['wallet_count']}/{len(wallets)}")
                
                # Calculate change if we have history
                if len(self.portfolio_history) > 1:
                    prev = self.portfolio_history[-2]['total_sol']
                    change = total_sol - prev
                    change_pct = (change / prev * 100) if prev > 0 else 0
                    
                    emoji = "šŸ“ˆ" if change >= 0 else "šŸ“‰"
                    print(f"   {emoji} Change: {change:+.6f} SOL ({change_pct:+.2f}%)")
                
                print()
                time.sleep(interval)
                
        except KeyboardInterrupt:
            print("\nā¹ļø  Stopping tracker...")
            self.save_history()
    
    def save_history(self):
        """Save tracking history to file"""
        filename = f"portfolio_history_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
        with open(filename, 'w') as f:
            json.dump(self.portfolio_history, f, indent=2)
        print(f"āœ… History saved to {filename}")
    
    def get_summary(self):
        """Generate portfolio summary"""
        wallets = self.load_wallets()
        balances = self.client.GetBatchedBalance(wallets)
        
        print("=" * 60)
        print("šŸ“Š PORTFOLIO SUMMARY")
        print("=" * 60)
        
        total_sol = 0
        active_count = 0
        
        for address, balance_data in balances.items():
            if balance_data:
                sol = balance_data['sol']
                total_sol += sol
                active_count += 1
                
                print(f"\n{address}")
                print(f"   Balance: {sol:.6f} SOL")
                print(f"   Lamports: {balance_data['lamports']:,}")
                print(f"   Last Slot: {balance_data['slot']}")
        
        print("\n" + "=" * 60)
        print(f"Total Wallets: {len(wallets)}")
        print(f"Active Wallets: {active_count}")
        print(f"Total Balance: {total_sol:.6f} SOL")
        print(f"Average per Wallet: {total_sol/active_count:.6f} SOL" if active_count > 0 else "Average: N/A")
        print("=" * 60)

# Example usage
if __name__ == "__main__":
    tracker = SolanaPortfolioTracker()
    
    # Get one-time summary
    tracker.get_summary()
    
    # Or start continuous tracking (60 second intervals)
    # tracker.track_portfolio(interval=60)
portfolio_wallets.json
{
  "wallets": [
    "BJBgjyDZx5FSsyJf6bFKVXuJV7DZY9PCSMSi5d9tcEVh",
    "Cpxu7gFhu3fDX1eG5ZVyiFoPmgxpLWiu5LhByNenVbPb",
    "DsHk4F6QNTK6RdTmaDSKeFzGXMnQ9QxKTkDkG8XF8F4F"
  ]
}

šŸ’” Common Use Cases

šŸ“Š

Portfolio Management

  • • Track multiple wallets in one dashboard
  • • Calculate total portfolio value
  • • Monitor balance changes over time
  • • Generate performance reports
šŸ¤–

Trading Bot Integration

  • • Check wallet balance before trades
  • • Monitor fund availability
  • • Track profit/loss in real-time
  • • Implement risk management
šŸ””

Balance Alerts

  • • Alert on low balance thresholds
  • • Notify on large transactions
  • • Monitor whale wallets
  • • Track competitor activity
šŸ“ˆ

Analytics & Reporting

  • • Historical balance tracking
  • • Performance metrics calculation
  • • Export data for analysis
  • • Visualize trends over time

✨ Best Practices

1. Use Batch Operations When Possible

Always use GetBatchedBalance() for multiple wallets instead of individual calls:

āŒ Don't do this:

for wallet in wallets:
    balance = client.GetBalance(wallet)
    # Slow, uses many API calls

āœ… Do this:

balances = client.GetBatchedBalance(wallets)
# Fast, single API call

2. Implement Error Handling

try:
    balance = client.GetBalance(wallet_address)
except ConnectionError:
    # Retry with exponential backoff
    pass
except Exception as e:
    logger.error(f"Balance query failed: {e}")

3. Cache Results Appropriately

Balance data is accurate to the latest Solana slot. For non-critical applications, consider caching for 5-10 seconds to reduce API calls.