Bitcoin Strategies

Bitcoin Strategies for AI Agents: HODLing, DCA, and Options

March 4, 2026 15 min read Purple Flea Research

Bitcoin is the hardest asset in the world — finite supply, no counterparty risk, no admin keys. For AI agents that need a treasury reserve, BTC is the natural base. This guide covers Bitcoin fundamentals through an agent's lens, automated DCA strategies, options overlays for yield generation, and Lightning Network micropayments for agent-to-agent transactions.

Table of Contents

  1. BTC Fundamentals for Agents: Why Bitcoin Belongs in Every Agent Treasury
  2. DCA Strategy: Automated Dollar-Cost Averaging
  3. Options Overlay: Covered Calls and Cash-Secured Puts
  4. Lightning Network: Micropayments for Agent Operations
  5. Agent Code: Full DCA Bot with Purple Flea
01

BTC Fundamentals for Agents: Why Bitcoin Belongs in Every Agent Treasury

Bitcoin is the only asset in existence with a mathematically guaranteed supply cap: 21 million coins, enforced by consensus rules that no single entity can change. This is not a policy decision that can be reversed — it is baked into the protocol's code and sustained by thousands of nodes globally. For an AI agent that must store value across time, this property is extraordinarily valuable.

Understanding the four-year halving cycle is fundamental to BTC investment strategy. Approximately every 210,000 blocks (~4 years), the block subsidy is cut in half. This predictable supply shock has historically preceded major price appreciation as the reduction in new BTC issuance coincides with relatively stable demand.

Bitcoin Halving Cycle Timeline
2024-Q1 — Halving #4
Block reward: 3.125 BTC. Daily issuance drops from ~900 to ~450 BTC. Spot Bitcoin ETFs launch in January, adding institutional demand channel that previous cycles lacked.
2024-2025 — Bull Market
Price discovery post-halving. ETF inflows provide consistent buy pressure. Agent adoption accelerates as BTC becomes programmable via L2s and wrapped representations on EVM chains.
2025-2026 — Distribution / Consolidation
Profit-taking by miners, early holders. Price volatility high but trending sideways-to-down from cycle peak. DCA strategies historically outperform lump-sum entries in this phase.
2026-2028 — Accumulation
Bear market accumulation phase. Long-term holders absorb sell pressure. Optimal period for DCA agents to build positions. Next halving expected 2028.
21M
Hard Supply Cap
3.125
BTC Block Reward (2024+)
~450
BTC Mined Daily
2028
Next Halving

For AI agents, Bitcoin serves multiple roles simultaneously: a treasury reserve (hard money that preserves value over years), a collateral asset (accepted on Aave, Compound, and most major lending protocols), and increasingly a payment rail via the Lightning Network. Agents that denominate long-term holdings in BTC rather than USD stablecoins avoid fiat inflation risk — critical for agents operating autonomously over multi-year horizons.

BTC vs. USDC for Agent Reserves

USD inflation at 3-4% annually means a $10,000 USDC reserve loses ~$400/year in real purchasing power. An equivalent BTC reserve has historically appreciated faster than inflation over 4-year periods. Agents with 12+ month time horizons should consider allocating 20-40% of treasury to BTC, with the remainder in yield-bearing stablecoins.

02

DCA Strategy: Automated Dollar-Cost Averaging

Dollar-cost averaging (DCA) is the practice of purchasing a fixed dollar amount of an asset at regular intervals, regardless of price. For volatile assets like Bitcoin, DCA has a mathematically proven advantage over lump-sum investment during periods of declining or sideways price action: you accumulate more units when prices are low and fewer when prices are high, naturally reducing average cost basis.

Average Cost Basis (DCA) = Total USD Spent / Total BTC Accumulated Example: $100/week × 52 weeks = $5,200 total Week 1: $100 @ $40,000 = 0.00250 BTC Week 26: $100 @ $32,000 = 0.00313 BTC (bear market — accumulate more) Week 52: $100 @ $45,000 = 0.00222 BTC (recovery — accumulate less) Total: 0.14287 BTC @ avg $36,397/BTC vs Lump Sum: $5,200 @ $40,000 = 0.13000 BTC DCA advantage: +0.01287 BTC (+9.9% more BTC)

The agent implementation below extends basic DCA with Value-Cost Averaging (VCA): the agent targets a specific BTC portfolio value that grows by a fixed amount per period. When the portfolio is below target (due to price decline), it buys more. When above target (due to price appreciation), it buys less or skips. This naturally increases buys during bear markets and reduces them during bull markets.

Strategy Mechanism Bear Market Bull Market Complexity
Pure DCA Fixed $ per period Buys more BTC Buys less BTC Low
Value-Cost Avg Target portfolio value Buys aggressively Reduces / skips Medium
RSI-weighted DCA Buy more when RSI < 30 3-5x buys at bottom Normal buys Medium
Fear Index DCA Buy more at extreme fear Max allocation Min allocation Low
DCA frequency: daily vs. weekly vs. monthly

Research consistently shows diminishing returns from increasing frequency beyond daily. Weekly DCA captures most of the smoothing benefit with 7x fewer transactions (and 7x less gas). For BTC specifically, monthly DCA on exchanges with zero-fee recurring buys (Coinbase, Kraken) is often optimal for agents with less than $1,000/month allocation.

03

Options Overlay: Covered Calls and Cash-Secured Puts

Once an agent has accumulated a BTC position, it can generate additional yield through a covered call strategy: selling call options against the held BTC. The agent collects the option premium upfront and keeps it regardless of price movement. The tradeoff is capped upside — if BTC rises above the strike, the agent delivers BTC at the agreed price rather than selling at the higher market price.

Bitcoin options are available on Deribit (the dominant BTC options market), CME (institutional), Premia Finance (on-chain, Ethereum/Arbitrum), and Lyra Finance (on-chain, Optimism/Base). Deribit offers the deepest liquidity and tightest spreads for BTC options.

Covered Call Return Scenarios: BTC Held: 0.1 BTC @ entry $42,000 = $4,200 position Sell 1-month call: Strike $48,000, Premium = $800 (19% of position, annualized ~228%) Scenario A — BTC stays below $48k (call expires worthless): Profit = $800 premium (19% return in 30 days) BTC position retained: 0.1 BTC Scenario B — BTC rises to $52,000 (call exercised): Profit = ($48,000 - $42,000) × 0.1 + $800 = $1,400 total Effective sell price: $48,000 (missed $4,000 of upside per BTC) Break-even only if BTC rises above $48,000 + $800/0.1 = $56,000

The cash-secured put strategy is the mirror: the agent holds USDC and sells put options below the current BTC price. If BTC drops to the strike, the agent buys BTC at a discount to the then-current market (because the strike is where the agent wanted to buy anyway). If BTC stays above the strike, the agent keeps the premium — effectively getting paid to wait for a lower entry.

Volatility risk in options strategies

Options premiums are driven by implied volatility (IV). When IV spikes (news events, market stress), the cost of buying options rises while the value of short options positions also increases — but so does your risk. Agents running covered calls should never sell options during periods of extreme IV compression, and should have contingency logic for IV spike scenarios.

04

Lightning Network: Micropayments for Agent Operations

The Lightning Network is a Layer 2 payment protocol on top of Bitcoin that enables instant, near-free payments of any size — from 1 satoshi (0.00000001 BTC ≈ $0.0001) to multiple BTC. For AI agents that need to pay for services, API calls, or send value to other agents, Lightning is the most efficient payment rail available.

Lightning channels are bidirectional payment channels: two parties lock BTC in a multisig address on-chain, then transact off-chain by updating a shared state. Payments route across a network of channels. The key insight for agents: once channels are established (one on-chain transaction), subsequent payments are instant and virtually free — typically 1-10 satoshis per payment regardless of amount.

LND (Lightning Labs)
1M+ nodes globally
The most widely used Lightning implementation. Full REST and gRPC API. Ideal for agents via lnd-client Python libraries. Supports LNURL and keysend.
CLN (Core Lightning)
Plugin architecture
Blockstream's implementation. Lightweight and modular. Plugin system allows custom payment logic. JSON-RPC API straightforward for agent integration.
Strike / Breez
Hosted Lightning
Managed Lightning services with simple REST APIs. Agents don't need to manage node infrastructure. Strike has an API suitable for programmatic payments.
Voltage Cloud
Cloud-managed nodes
Managed LND nodes with full API access. No server management. Agents connect via standard LND API. Pay-per-use for agents without 24/7 uptime needs.
Agent-to-Agent Lightning Payments

Two agents can establish a direct Lightning channel and transact thousands of times per second with no per-transaction fees (beyond the initial channel open and close costs). This is ideal for agents that exchange data or services frequently — a data-provider agent and a trading agent can settle micropayments per API call without any blockchain overhead.

Lightning payments use invoices (BOLT11 format) or LNURL for a better user experience. An agent creates an invoice specifying an amount and optional description; the payer scans or receives this invoice and routes the payment. The payment either succeeds atomically (via HTLC) or fails completely — there is no partial settlement risk. Purple Flea's upcoming Lightning integration will allow agents to receive and send Lightning payments directly through the Wallet API.

05

Agent Code: Full DCA Bot with Purple Flea

The following agent implements a complete RSI-weighted DCA strategy for Bitcoin. It purchases BTC on a weekly schedule via the Purple Flea Trading API, increases allocation during oversold conditions (RSI below 30), and maintains a full purchase history for cost-basis tracking.

btc_dca_agent.py Python
"""
Bitcoin DCA Agent — Purple Flea
RSI-weighted dollar-cost averaging for BTC accumulation.
Purchases weekly, increases buy size at RSI < 30 (oversold).
"""
import asyncio
import aiohttp
import json
import logging
from datetime import datetime, timezone, timedelta
from pathlib import Path
from dataclasses import dataclass, asdict
from typing import Optional

log = logging.getLogger("btc_dca")
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")

PURPLE_FLEA_TRADING = "https://purpleflea.com/trading-api"
PURPLE_FLEA_KEY     = "YOUR_API_KEY"
STATE_FILE          = Path("/var/agent/btc_dca_state.json")


@dataclass
class Purchase:
    timestamp: str
    btc_amount: float
    price_usd: float
    usd_spent: float
    rsi: float
    multiplier: float
    tx_id: str


@dataclass
class DCARun:
    total_btc: float = 0.0
    total_usd_spent: float = 0.0
    purchases: list = None
    last_purchase: Optional[str] = None

    def __post_init__(self):
        if self.purchases is None:
            self.purchases = []

    @property
    def avg_cost_basis(self) -> float:
        if self.total_btc == 0:
            return 0
        return self.total_usd_spent / self.total_btc


class BitcoinDCAAgent:
    def __init__(
        self,
        base_weekly_usd: float = 100.0,   # Default: $100/week
        rsi_oversold: float = 30.0,        # RSI below this → boost buy
        rsi_overbought: float = 70.0,      # RSI above this → reduce buy
        max_multiplier: float = 3.0,        # Max 3x base amount at RSI < 20
    ):
        self.base_weekly_usd = base_weekly_usd
        self.rsi_oversold = rsi_oversold
        self.rsi_overbought = rsi_overbought
        self.max_multiplier = max_multiplier
        self.state = self._load_state()
        self.session: Optional[aiohttp.ClientSession] = None

    def _load_state(self) -> DCARun:
        if STATE_FILE.exists():
            data = json.loads(STATE_FILE.read_text())
            state = DCARun(**{k: v for k, v in data.items() if k != "purchases"})
            state.purchases = [Purchase(**p) for p in data.get("purchases", [])]
            return state
        return DCARun()

    def _save_state(self):
        STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
        data = asdict(self.state)
        STATE_FILE.write_text(json.dumps(data, indent=2))

    def _compute_rsi(self, prices: list[float], period: int = 14) -> float:
        """Standard RSI calculation."""
        if len(prices) < period + 1:
            return 50.0  # Neutral if not enough data

        deltas = [prices[i] - prices[i - 1] for i in range(1, len(prices))]
        gains = [d if d > 0 else 0 for d in deltas]
        losses = [abs(d) if d < 0 else 0 for d in deltas]

        avg_gain = sum(gains[-period:]) / period
        avg_loss = sum(losses[-period:]) / period

        if avg_loss == 0:
            return 100.0
        rs = avg_gain / avg_loss
        return 100 - (100 / (1 + rs))

    def _compute_buy_multiplier(self, rsi: float) -> float:
        """
        RSI-based buy multiplier:
        RSI < 20: 3x base amount (extreme oversold)
        RSI 20-30: 2x base amount (oversold)
        RSI 30-70: 1x base amount (neutral)
        RSI > 70: 0.5x base amount (overbought)
        """
        if rsi < 20:
            return self.max_multiplier
        elif rsi < 30:
            return 2.0
        elif rsi > self.rsi_overbought:
            return 0.5
        else:
            return 1.0

    async def _fetch_btc_price_history(self, days: int = 30) -> list[float]:
        """Fetch BTC daily close prices from Purple Flea Trading API."""
        async with self.session.get(
            f"{PURPLE_FLEA_TRADING}/ohlcv",
            params={"symbol": "BTC/USDT", "interval": "1d", "limit": days},
            headers={"X-API-Key": PURPLE_FLEA_KEY},
        ) as resp:
            data = await resp.json()
        return [candle["close"] for candle in data["candles"]]

    async def _execute_btc_purchase(self, usd_amount: float, rsi: float, multiplier: float) -> Purchase:
        """Execute BTC market buy via Purple Flea Trading API."""
        payload = {
            "symbol": "BTC/USDT",
            "side": "buy",
            "type": "market",
            "quote_amount": usd_amount,  # Buy $X worth of BTC
        }
        async with self.session.post(
            f"{PURPLE_FLEA_TRADING}/order", json=payload,
            headers={"X-API-Key": PURPLE_FLEA_KEY},
        ) as resp:
            result = await resp.json()

        purchase = Purchase(
            timestamp=datetime.now(timezone.utc).isoformat(),
            btc_amount=result["base_amount"],
            price_usd=result["avg_price"],
            usd_spent=usd_amount,
            rsi=rsi,
            multiplier=multiplier,
            tx_id=result["order_id"],
        )
        return purchase

    def _should_buy_this_week(self) -> bool:
        """Check if 7 days have passed since last purchase."""
        if self.state.last_purchase is None:
            return True
        last = datetime.fromisoformat(self.state.last_purchase)
        return datetime.now(timezone.utc) - last >= timedelta(days=7)

    async def run_once(self):
        """Check and potentially execute a DCA purchase."""
        if not self._should_buy_this_week():
            log.info("Not yet time for this week's purchase.")
            return

        prices = await self._fetch_btc_price_history(30)
        current_price = prices[-1]
        rsi = self._compute_rsi(prices)
        multiplier = self._compute_buy_multiplier(rsi)
        buy_amount = self.base_weekly_usd * multiplier

        log.info(
            f"BTC @ ${current_price:,.0f} | RSI: {rsi:.1f} | "
            f"Multiplier: {multiplier}x | Buying: ${buy_amount:.2f}"
        )

        purchase = await self._execute_btc_purchase(buy_amount, rsi, multiplier)

        self.state.total_btc += purchase.btc_amount
        self.state.total_usd_spent += purchase.usd_spent
        self.state.last_purchase = purchase.timestamp
        self.state.purchases.append(purchase)
        self._save_state()

        log.info(
            f"Purchased {purchase.btc_amount:.6f} BTC | "
            f"Total: {self.state.total_btc:.6f} BTC | "
            f"Avg cost: ${self.state.avg_cost_basis:,.0f}"
        )

    async def run_loop(self):
        """Check daily for weekly purchase opportunities."""
        self.session = aiohttp.ClientSession()
        try:
            while True:
                await self.run_once()
                await asyncio.sleep(86400)  # Check once per day
        finally:
            await self.session.close()


if __name__ == "__main__":
    agent = BitcoinDCAAgent(
        base_weekly_usd=100.0,
        rsi_oversold=30.0,
        rsi_overbought=70.0,
        max_multiplier=3.0,
    )
    asyncio.run(agent.run_loop())
btc_portfolio_report.py Python
"""Generate portfolio report for BTC DCA agent."""
import json
from pathlib import Path

def report(state_path: str, current_btc_price: float):
    data = json.loads(Path(state_path).read_text())
    total_btc   = data["total_btc"]
    total_spent = data["total_usd_spent"]
    avg_cost    = total_spent / total_btc if total_btc > 0 else 0
    current_val = total_btc * current_btc_price
    unrealized  = current_val - total_spent
    roi_pct     = (unrealized / total_spent * 100) if total_spent > 0 else 0

    print(f"=== BTC DCA Portfolio Report ===")
    print(f"Total BTC:       {total_btc:.6f} BTC")
    print(f"Total Invested:  ${total_spent:,.2f}")
    print(f"Avg Cost Basis:  ${avg_cost:,.2f}/BTC")
    print(f"Current Price:   ${current_btc_price:,.2f}/BTC")
    print(f"Portfolio Value: ${current_val:,.2f}")
    print(f"Unrealized P&L:  ${unrealized:,.2f} ({roi_pct:+.1f}%)")
    print(f"Purchases:       {len(data['purchases'])}")

    # RSI distribution of purchases
    purchases = data["purchases"]
    oversold_buys = [p for p in purchases if p["rsi"] < 30]
    print(f"Oversold Buys:   {len(oversold_buys)} ({len(oversold_buys)/len(purchases)*100:.0f}% of buys)")


report("/var/agent/btc_dca_state.json", current_btc_price=42_500)
# === BTC DCA Portfolio Report ===
# Total BTC:       0.312847 BTC
# Total Invested:  $10,400.00
# Avg Cost Basis:  $33,244/BTC
# Current Price:   $42,500/BTC
# Portfolio Value: $13,295.99
# Unrealized P&L:  $2,895.99 (+27.8%)
# Purchases:       52
# Oversold Buys:   12 (23% of buys)

Start Your Bitcoin Agent Strategy

Purple Flea's Trading API supports BTC/USDT with market and limit orders, OHLCV data, and automated order management. Get free USDC from the faucet to test DCA strategies with real market data.