AI Agents

Automated Crypto Portfolio Management with AI: A Complete System

Stop manually rebalancing your crypto portfolio. This guide shows you how to build a complete AI-powered portfolio management system that automatically tracks, rebalances, and reports your holdings.

A
AI Agents HubΒ·2025-04-15Β·5 min readΒ·907 words

Builder of AI agents, crypto trading bots, and open-source automation tools. Sharing practical guides on how to build, deploy, and profit from AI and DeFi technology.

The Problem with Manual Portfolio Management

Most crypto investors check prices obsessively, make emotional decisions at market peaks/troughs, and never have a coherent strategy. They underperform because of:

  • Emotional trading β€” Panic selling, FOMO buying
  • Drift β€” Portfolio weights diverge from target allocation
  • Missed opportunities β€” Can't monitor 24/7
  • Tax inefficiency β€” Suboptimal timing of trades

An automated portfolio management system removes all of these.

Architecture of the System

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚              Portfolio Manager Bot                   β”‚
β”‚                                                      β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”‚
β”‚  β”‚ Portfolio  β”‚  β”‚Rebalancing β”‚  β”‚ Reporting  β”‚   β”‚
β”‚  β”‚ Tracker    β”‚  β”‚ Engine     β”‚  β”‚ Module     β”‚   β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜   β”‚
β”‚                                                      β”‚
β”‚  Data Sources: 10+ exchanges + DeFi protocols       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Step 1: Portfolio Tracking

import ccxt from 'ccxt'
import { ethers } from 'ethers'

interface Position {
  asset: string
  amount: number
  value_usd: number
  allocation_pct: number
  source: 'cex' | 'defi' | 'wallet'
}

class PortfolioTracker {
  private exchanges: ccxt.Exchange[]
  private provider: ethers.JsonRpcProvider

  async getFullPortfolio(): Promise<Position[]> {
    const positions: Position[] = []

    // 1. CEX balances
    for (const exchange of this.exchanges) {
      const balances = await exchange.fetchBalance()
      for (const [asset, balance] of Object.entries(balances.total)) {
        if ((balance as number) > 0) {
          const price = await this.getPrice(asset)
          positions.push({
            asset,
            amount: balance as number,
            value_usd: (balance as number) * price,
            allocation_pct: 0, // calculated after
            source: 'cex'
          })
        }
      }
    }

    // 2. On-chain wallet balances
    const walletPositions = await this.getWalletBalances()
    positions.push(...walletPositions)

    // Calculate allocations
    const totalValue = positions.reduce((sum, p) => sum + p.value_usd, 0)
    positions.forEach(p => {
      p.allocation_pct = (p.value_usd / totalValue) * 100
    })

    return positions
  }

  private async getPrice(asset: string): Promise<number> {
    // Use CoinGecko or similar
    const response = await fetch(
      `https://api.coingecko.com/api/v3/simple/price?ids=${asset.toLowerCase()}&vs_currencies=usd`
    )
    const data = await response.json()
    return data[asset.toLowerCase()]?.usd || 0
  }
}

Step 2: AI-Powered Rebalancing Engine

import OpenAI from 'openai'

interface AllocationTarget {
  asset: string
  target_pct: number
  rationale: string
}

class AIRebalancingEngine {
  private client = new OpenAI()

  async generateTargetAllocation(
    currentPortfolio: Position[],
    marketContext: string,
    riskTolerance: 'conservative' | 'moderate' | 'aggressive'
  ): Promise<AllocationTarget[]> {
    
    const prompt = `
You are a professional crypto portfolio manager. 

Current portfolio:
${JSON.stringify(currentPortfolio, null, 2)}

Market context:
${marketContext}

Risk tolerance: ${riskTolerance}

Generate an optimal target allocation. Consider:
- Current market conditions
- Risk/reward for each asset
- Diversification
- Correlation between assets

Return JSON array: [{asset, target_pct, rationale}]
Total allocations must sum to 100%.
`

    const response = await this.client.chat.completions.create({
      model: 'gpt-4o',
      messages: [{ role: 'user', content: prompt }],
      response_format: { type: 'json_object' }
    })

    const result = JSON.parse(response.choices[0].message.content!)
    return result.allocations
  }

  async generateRebalanceTrades(
    current: Position[],
    targets: AllocationTarget[],
    totalValue: number,
    rebalanceThreshold: number = 5 // Only rebalance if off by >5%
  ): Promise<{ asset: string; action: 'buy' | 'sell'; usd_amount: number }[]> {
    
    const trades = []

    for (const target of targets) {
      const current_pos = current.find(p => p.asset === target.asset)
      const current_pct = current_pos?.allocation_pct || 0
      const diff_pct = target.target_pct - current_pct

      if (Math.abs(diff_pct) > rebalanceThreshold) {
        trades.push({
          asset: target.asset,
          action: diff_pct > 0 ? 'buy' : 'sell',
          usd_amount: Math.abs(diff_pct / 100) * totalValue
        })
      }
    }

    return trades
  }
}

Step 3: Automated Reporting

class PortfolioReporter {
  async generateDailyReport(portfolio: Position[]): Promise<string> {
    const client = new OpenAI()
    
    const response = await client.chat.completions.create({
      model: 'gpt-4o',
      messages: [{
        role: 'user',
        content: `Generate a brief daily portfolio report (3-4 bullet points).
        
Portfolio: ${JSON.stringify(portfolio)}

Include: total value, top performers, key risks to watch, recommended actions.`
      }]
    })

    return response.choices[0].message.content!
  }

  async sendTelegram(message: string, chatId: string, botToken: string) {
    await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ chat_id: chatId, text: message })
    })
  }
}

Step 4: Putting It All Together

// Main loop - runs every 6 hours
async function portfolioManagementLoop() {
  const tracker = new PortfolioTracker(exchanges, provider)
  const engine = new AIRebalancingEngine()
  const reporter = new PortfolioReporter()

  while (true) {
    console.log('Running portfolio management cycle...')

    // 1. Get current state
    const portfolio = await tracker.getFullPortfolio()
    const totalValue = portfolio.reduce((sum, p) => sum + p.value_usd, 0)

    // 2. Get market context
    const marketContext = await getMarketContext()

    // 3. Generate optimal allocation
    const targets = await engine.generateTargetAllocation(
      portfolio, marketContext, 'moderate'
    )

    // 4. Calculate rebalancing trades
    const trades = await engine.generateRebalanceTrades(portfolio, targets, totalValue)

    // 5. Execute trades (if any)
    if (trades.length > 0) {
      console.log(`Executing ${trades.length} rebalancing trades`)
      for (const trade of trades) {
        await executeTrade(trade)
      }
    }

    // 6. Send daily report (once per day)
    const hour = new Date().getHours()
    if (hour === 8) {
      const report = await reporter.generateDailyReport(portfolio)
      await reporter.sendTelegram(report, CHAT_ID, BOT_TOKEN)
    }

    // Wait 6 hours
    await sleep(6 * 60 * 60 * 1000)
  }
}

Configuration Example

const config = {
  rebalance_threshold_pct: 5,   // Rebalance if allocation drifts by 5%
  max_trade_size_usd: 1000,      // Never execute a single trade >$1,000
  risk_tolerance: 'moderate',
  report_time: '08:00',          // Daily report at 8am
  assets_to_track: ['BTC', 'ETH', 'SOL', 'USDC'],
}

What This System Achieves

  • Consistent strategy β€” No emotional deviations
  • Optimal timing β€” Buys dips automatically (rebalancing = buy low sell high)
  • Diversification β€” Maintains target allocation across market cycles
  • Transparency β€” Daily reports tell you exactly what happened and why

Studies show disciplined rebalancing outperforms buy-and-hold in volatile markets by 1–3% annually β€” with lower drawdowns.

Get the Full System

The complete portfolio management system is available on our Tools page with exchange connectors, backtesting, and a web dashboard.

Related Articles