March 4, 2026 ยท 5 min read

How to Automate Dollar-Cost Averaging with an AI Agent

Dollar-cost averaging is one of the most battle-tested investment strategies ever devised. Instead of trying to time the market โ€” a game that even the best human traders lose more often than they win โ€” DCA simply buys a fixed dollar amount on a fixed schedule. The result is that you automatically buy more units when prices are low and fewer when prices are high, gradually lowering your average cost basis over time.

For AI agents, DCA is the default "I don't know exactly when to buy" strategy, and it's a powerful one. It eliminates timing risk, reduces the emotional component of trading decisions, and can be implemented in under 50 lines of Python. This guide walks you through a complete DCA agent setup using the Purple Flea trading API, from basic weekly buys to advanced value-averaging and multi-asset allocation.

Why DCA Works Mathematically

The mathematical basis of DCA is a property called the harmonic mean advantage. When you invest a fixed dollar amount repeatedly, the average price you pay is always less than or equal to the arithmetic average of the prices over that period.

Consider buying $100 of BTC three times at $50,000, $40,000, and $60,000. Simple average price: $50,000. Your actual average cost basis: $100 buys 0.002 BTC, then $100 buys 0.0025 BTC, then $100 buys 0.00167 BTC. Total: 0.00617 BTC for $300, or $48,623 average โ€” nearly $1,400 below the arithmetic average price.

This advantage compounds over longer periods with higher volatility. Crypto markets, with their frequent 20-40% drawdowns and recovery cycles, are nearly ideal conditions for DCA strategies.

Setting Up Your Purple Flea Agent

Before writing any trading logic, you need a Purple Flea account, a funded wallet, and an API key. New agents can claim a free starting balance through the Purple Flea faucet โ€” this is useful for testing your DCA logic before funding with real capital.

  1. Register at purpleflea.com/quick-register
  2. Copy your API key from the dashboard
  3. Install the SDK: pip install purpleflea
  4. Fund your wallet via the faucet or by depositing USDC

Basic DCA Implementation

The following script uses the schedule library to buy $50 of BTC every Monday at 09:00 UTC. It is production-ready with error handling and logging.

import schedule
import time
import logging
import purpleflea

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
client = purpleflea.TradingClient(api_key="your_api_key")

DCA_AMOUNT_USD = 50.0
DCA_SYMBOL = "BTC-USDT"

def run_dca_buy():
    try:
        # Check available balance before buying
        balance = client.get_balance(asset="USDT")
        if balance["available"] < DCA_AMOUNT_USD:
            logging.warning(f"Insufficient balance: {balance['available']} USDT")
            return

        order = client.place_order(
            symbol=DCA_SYMBOL,
            side="buy",
            quote_amount=DCA_AMOUNT_USD,  # spend exactly $50
            order_type="market"
        )

        logging.info(
            f"DCA buy executed: {order['filled_qty']:.6f} BTC "
            f"at ${order['fill_price']:,.2f} "
            f"(${DCA_AMOUNT_USD} spent)"
        )
    except Exception as e:
        logging.error(f"DCA buy failed: {e}")

# Schedule every Monday at 09:00 UTC
schedule.every().monday.at("09:00").do(run_dca_buy)

logging.info("DCA agent started. Waiting for next scheduled run...")
while True:
    schedule.run_pending()
    time.sleep(60)

Advanced: Value Averaging

Value averaging is DCA with a twist: your buy size adapts to price conditions. When the asset is trading below its moving average (suggesting it's cheap relative to recent history), you buy more. When it's above the moving average (expensive), you buy less or even sell. The result is more aggressive accumulation during dips and capital preservation during peaks.

import purpleflea
import statistics

client = purpleflea.TradingClient(api_key="your_api_key")

BASE_AMOUNT = 50.0  # base weekly spend in USDT
MA_PERIODS = 20     # 20-week moving average

def value_average_buy():
    # Fetch weekly candles for moving average
    candles = client.get_candles(symbol="BTC-USDT", interval="1w", limit=MA_PERIODS + 1)
    closes = [c[4] for c in candles[:-1]]  # exclude current forming candle
    current_price = candles[-1][4]
    moving_avg = statistics.mean(closes)

    # Deviation ratio: 1.0 means at average, 0.8 means 20% below
    deviation = current_price / moving_avg

    # Scale buy size inversely with price deviation
    # Below MA: buy up to 2x base. Above MA: buy as little as 0.25x base
    scale = max(0.25, min(2.0, 2.0 - deviation))
    buy_amount = BASE_AMOUNT * scale

    order = client.place_order(
        symbol="BTC-USDT",
        side="buy",
        quote_amount=round(buy_amount, 2),
        order_type="market"
    )

    print(f"Price {deviation:.2%} of MA | Buying ${buy_amount:.2f} (scale: {scale:.2f}x)")
    return order

Advanced: Multi-Asset DCA Allocation

Diversifying your DCA across multiple assets reduces single-asset concentration risk. A common allocation for a crypto-focused agent is BTC 50%, ETH 30%, SOL 20%. The Purple Flea trading API handles all three assets on the same endpoint, so a multi-asset DCA loop is straightforward:

import purpleflea

client = purpleflea.TradingClient(api_key="your_api_key")

WEEKLY_BUDGET = 100.0  # total USD to deploy each week
ALLOCATIONS = {
    "BTC-USDT": 0.50,
    "ETH-USDT": 0.30,
    "SOL-USDT": 0.20,
}

def multi_asset_dca():
    results = []
    for symbol, weight in ALLOCATIONS.items():
        amount = round(WEEKLY_BUDGET * weight, 2)
        order = client.place_order(
            symbol=symbol,
            side="buy",
            quote_amount=amount,
            order_type="market"
        )
        results.append({
            "symbol": symbol,
            "spent": amount,
            "received": order["filled_qty"],
            "price": order["fill_price"]
        })
        print(f"  {symbol}: bought {order['filled_qty']:.4f} at ${order['fill_price']:,.2f}")
    return results

Tracking DCA Performance

Tracking your average cost basis across many buys is essential for evaluating your DCA agent's performance. Your average cost basis is simply total USDC spent divided by total units acquired. To calculate unrealized P&L, compare that figure against the current market price.

The Purple Flea wallet API exposes full transaction history with timestamps, amounts, and fill prices, making it straightforward to aggregate cost basis data. You can also pull this data into a Pandas DataFrame for analysis and visualization.

Common DCA Mistakes Agents Make

Getting started: Use the Purple Flea faucet to claim a free starting balance and test your DCA agent with zero capital at risk. Once you're satisfied with the behavior, fund with real capital and set the agent running on a VPS or cloud function.

DCA is not glamorous, but it is consistent. For agents that will run for months or years across bull and bear cycles, consistent accumulation at average market prices beats almost every active strategy on a risk-adjusted basis. Build the basic version, run it, measure it, and then layer in value averaging once you have real performance data to guide your parameter choices.

Explore the full API reference at /agent-dollar-cost-averaging and the trading API docs for all available order types and scheduling integrations.