Coinbase Advanced Trading Bot in Python

This guide shows how to build a Coinbase Advanced trading bot in Python with LumiBot, for both AI agent trading and algorithmic trading. LumiBot connects to Coinbase Advanced through CCXT, the open source library that talks to more than 100 crypto exchanges. You will create a Coinbase Advanced account and API key, connect it, and run two examples: a simple algorithmic trading bot and an agentic trading bot where an AI agent makes the calls.

What BotSpot MCP adds

Use Claude, ChatGPT, Codex, Cursor, VS Code or another MCP-compatible assistant? Connect the free BotSpot MCP for:

  • Skills: build LumiBot strategies.

  • Free data: news, economics and SEC filings.

  • Backtests: run tests and read charts.

  • Cloud hosting: low-cost scheduled bots.

  • Community: share bots and discuss trades.

  • Marketplace: discover and publish strategies.

  • Broker linking: connect accounts through BotSpot.

Connect your AI assistant

Coinbase Advanced at a glance

CCXT exchange id

coinbase

Markets

Spot, Perpetual swaps, Dated futures

Testnet (sandbox)

No

Credentials

API key, API secret

Live data streams

prices, order book, trades, your orders

CCXT request spacing

about 34 ms between requests

Official site

https://www.coinbase.com

API docs

https://docs.cdp.coinbase.com/coinbase-app/introduction/welcome

Fees

https://support.coinbase.com/customer/portal/articles/2109597-buy-sell-bank-transfer-fees

What is Coinbase Advanced?

Coinbase is a large crypto exchange. LumiBot trades through Coinbase Advanced, Coinbase’s platform for more experienced traders, using the Advanced Trade API for spot crypto.

Sign up for Coinbase Advanced

  1. Create a Coinbase account with your email, confirm the email code, set a password and add your phone number.

  2. Verify your identity. Coinbase asks for your legal name as it appears on your ID and has you upload the ID.

  3. Set up 2-step verification. Then sign in to the Coinbase Developer Platform (CDP) at https://portal.cdp.coinbase.com with the same Coinbase account.

Open a Coinbase Advanced account

Create a Coinbase Advanced API key

  1. In the CDP portal, open API Keys and select the Secret API Keys tab.

  2. Click Create API key and enter a nickname.

  3. Expand API restrictions and Advanced Settings. Add your bot’s IP address to the IP allowlist (Coinbase recommends it), and pick the portfolio the key should trade.

  4. Set the permissions (see below) and change the signature algorithm to ECDSA. ECDSA gives you a private key in the PEM format LumiBot expects.

  5. Click Create API key. Copy the key name (it looks like organizations/<org-id>/apiKeys/<key-id>) and the full private key from the window right away. The key file is no longer downloaded for you unless you click Download API key.

  6. Set COINBASE_API_KEY_NAME to the key name and COINBASE_PRIVATE_KEY to the whole private key, from -----BEGIN EC PRIVATE KEY----- to -----END EC PRIVATE KEY-----.

Which permissions to turn on: Turn on View and Trade. Coinbase’s Advanced Trade docs show that reading accounts, orders and fills needs View, and placing and canceling orders needs Trade. Leave Transfer off. Coinbase warns that anyone who gets a key with the Transfer permission can send all the crypto out of your account.

Warning

Never turn on withdrawals for a Coinbase Advanced trading bot key. Bind the key to your server’s IP address when Coinbase Advanced lets you, keep the secret out of your code and out of Git, and delete the key if it ever leaks.

Connect Coinbase Advanced to LumiBot

The simplest way: put these lines in a .env file next to your strategy. LumiBot loads the file, sees TRADING_BROKER=coinbase and connects to Coinbase Advanced for you, so your strategy needs no broker code.

TRADING_BROKER=coinbase
COINBASE_API_KEY_NAME=your_apiKey
COINBASE_PRIVATE_KEY=your_secret

LumiBot reads exactly the fields CCXT needs for Coinbase Advanced (apiKey, secret). If one is missing, LumiBot stops at start-up and names the variable you still need.

You can also build the broker in code. This is handy when one script talks to more than one exchange, or when you need extra CCXT options. The keys in the config are CCXT’s own credential names for Coinbase Advanced:

import os

COINBASE_CONFIG = {
    "exchange_id": "coinbase",
    "apiKey": os.environ.get("COINBASE_API_KEY_NAME"),
    "secret": os.environ.get("COINBASE_PRIVATE_KEY"),
    "sandbox": False,  # live connection
}

from lumibot.brokers import Ccxt

broker = Ccxt(COINBASE_CONFIG)
# then: MyStrategy(broker=broker, ...)

Either way, LumiBot turns on CCXT’s built-in rate limiting for you.

Testing on Coinbase Advanced

Coinbase Advanced has no sandbox for the Advanced Trade API in CCXT, so test with a very small amount. With environment variables, leave COINBASE_SANDBOX unset. In a code config, set "sandbox": False.

Algorithmic trading example: a simple Coinbase Advanced bot

This bot buys about 50 USD of BTC on Coinbase Advanced once and then holds it. It is a starting point to check that your keys, balances and orders work. If the exchange’s minimum order is larger, raise the amount. Coinbase Advanced accepts only limit orders through CCXT, so the example places a limit order just above the last price.

from lumibot.entities import Asset
from lumibot.strategies import Strategy


class CoinbaseBuyOnce(Strategy):
    """Buy a small amount of BTC once, then hold it."""

    def initialize(self):
        self.sleeptime = "1H"
        self.set_market("24/7")  # crypto trades all day, every day

    def on_trading_iteration(self):
        coin = Asset("BTC", asset_type=Asset.AssetType.CRYPTO)
        if self.get_position(coin) is not None:
            return  # already holding BTC
        price = self.get_last_price(coin, quote=self.quote_asset)
        if price:
            quantity = round(50 / price, 6)  # about 50 USD worth
            # This exchange takes only limit orders through CCXT.
            order = self.create_order(coin, quantity, "buy", limit_price=price * 1.002, quote=self.quote_asset)
            self.submit_order(order)


if __name__ == "__main__":
    # LumiBot reads TRADING_BROKER and the keys from your .env file.
    strategy = CoinbaseBuyOnce(quote_asset=Asset("USD", asset_type=Asset.AssetType.CRYPTO))
    strategy.run_live()

Agentic trading example: an AI agent that trades on Coinbase Advanced

Agentic trading means an AI agent reads the market and decides what to do. In this example one LumiBot agent looks at prices and your Coinbase Advanced account, then places the orders itself. There is no Python logic in between: you set the rules in plain English in the prompt, such as what it may trade and how big each order can be. This follows the same pattern as LumiBot’s AI trading team examples.

from lumibot.entities import Asset
from lumibot.strategies import Strategy


class CoinbaseAITrader(Strategy):
    """One AI agent researches the market and places the trades itself."""

    def initialize(self):
        self.sleeptime = "4H"
        self.set_market("24/7")
        self.agents.create(
            name="trader",
            model="openai/gpt-6-luna",
            reasoning_effort="high",
            allow_trading=True,
            system_prompt=(
                "You manage a small crypto account on Coinbase Advanced. "
                "You may trade BTC and ETH against USD (asset_type 'crypto', quote_symbol 'USD'), or hold cash. "
                "Before every order, call account_portfolio, account_positions and "
                "market_last_price for that exact symbol in the same run. "
                "Keep each order under 10% of the account value. "
                "Explain each decision in one short paragraph."
            ),
        )

    def on_trading_iteration(self):
        self.agents["trader"].run(
            task_prompt="Review recent BTC/USD and ETH/USD prices and your current holdings, then decide whether to buy, sell or hold.",
            context={"exchange": "Coinbase Advanced", "quote": "USD", "date": self.get_datetime().isoformat()},
        )


if __name__ == "__main__":
    # LumiBot reads TRADING_BROKER and the keys from your .env file.
    strategy = CoinbaseAITrader(quote_asset=Asset("USD", asset_type=Asset.AssetType.CRYPTO))
    strategy.run_live()

The agent needs a model key such as OPENAI_API_KEY in your environment. See the AI agents quickstart for models, tools and memory.

What you can trade on Coinbase Advanced

Market

Listed by CCXT

Spot

Yes

Margin

No

Perpetual swaps

Yes

Dated futures

Yes

Options

No

CCXT lists these order features for Coinbase Advanced: stop orders, editing open orders, canceling orders.

For perpetual contracts, use the full CCXT symbol so the settlement currency is clear, for example BTC/USDT:USDT. See the CCXT guide for contract quantities, position modes and leverage.

Perpetual futures example on Coinbase Advanced

Coinbase Advanced also lists perpetual swaps. This bot opens one small long position in BTC/USD:USD worth about 50 USD and then holds it. LumiBot treats a perpetual as asset_type="crypto_future" and sizes it in contracts, the same model as LumiBot’s Bitunix futures broker. Contract symbols can differ by exchange, so check the symbol in self.broker.api.markets before going live. In hedge mode, add position_side="long" to create_order. Coinbase Advanced accepts only limit orders through CCXT, so the example places a limit order just above the last price.

from lumibot.entities import Asset
from lumibot.strategies import Strategy


class CoinbaseOpenOneLong(Strategy):
    """Open one small long BTC perpetual position, then hold it."""

    def initialize(self):
        self.sleeptime = "1H"
        self.set_market("24/7")  # crypto trades all day, every day

    def on_trading_iteration(self):
        # The full CCXT symbol keeps the settlement currency clear.
        contract = self.broker.get_asset("BTC/USD:USD")
        if self.get_position(contract) is not None:
            return  # already holding the position
        price = self.get_last_price(contract)
        if price:
            # Each contract covers contract.multiplier BTC; size the order to about 50 USD.
            quantity = round(50 / (price * contract.multiplier), 6)
            # This exchange takes only limit orders through CCXT.
            order = self.create_order(contract, quantity, "buy", limit_price=price * 1.002)
            self.submit_order(order)


if __name__ == "__main__":
    # LumiBot reads TRADING_BROKER and the keys from your .env file.
    strategy = CoinbaseOpenOneLong(quote_asset=Asset("USD", asset_type=Asset.AssetType.CRYPTO))
    strategy.run_live()

Fees and partner IDs on Coinbase Advanced

You pay Coinbase Advanced’s normal trading fees. CCXT, the library underneath, normally tags Coinbase Advanced orders with its own partner ID. LumiBot removes that tag. LumiBot may attach its own exchange partner ID instead. That costs you nothing extra. LumiBot never adds an extra builder fee unless one is turned on, and it logs a warning when one is.

Coinbase Advanced tips

  • The private key is several lines long. Keep the line breaks: either paste it as a multi-line value in quotes, or write it on one line with \n where each line break goes. Coinbase’s docs say the newlines must be kept for the key to work.

  • Each CDP key is tied to one portfolio. If you want a bot to trade a separate portfolio, make a key for that portfolio. This also keeps bot trades apart from your manual trades.

  • New CDP keys do not use a passphrase. COINBASE_API_PASSPHRASE is only for old legacy keys, so leave it unset.

  • This page is for Coinbase Advanced (CCXT id coinbase). Coinbase Exchange and Coinbase International Exchange are separate CCXT ids (coinbaseexchange and coinbaseinternational) with their own key systems that use a passphrase.

  • CCXT 4.5.91 also lists futures and perpetual-style US contracts through Coinbase Advanced. These require an eligible derivatives account; the BTC/USD:USD example is separate from spot. International perpetuals use the separate coinbaseinternational adapter.

Frequently asked questions

Can I build a Coinbase Advanced trading bot in Python?

Yes. Install LumiBot (pip install lumibot), set your Coinbase Advanced keys and use the coinbase CCXT exchange id as shown above.

Does Coinbase Advanced have a testnet?

No testnet is set up for Coinbase Advanced in LumiBot. Start with a small amount, and in a code config set "sandbox": False.

Which API permissions does a Coinbase Advanced bot need?

Turn on View and Trade. Coinbase’s Advanced Trade docs show that reading accounts, orders and fills needs View, and placing and canceling orders needs Trade. Leave Transfer off. Coinbase warns that anyone who gets a key with the Transfer permission can send all the crypto out of your account.

Can an AI agent trade on Coinbase Advanced by itself?

Yes. The agentic example above gives one agent permission to trade. You control what it may trade and how much through its prompt.

Can I trade Coinbase Advanced perpetual futures with LumiBot?

CCXT lists perpetual swaps for this exchange. Use the full contract symbol, such as BTC/USDT:USDT.

Is LumiBot free?

Yes. LumiBot is open source on GitHub at https://github.com/Lumiwealth/lumibot. You pay only your exchange’s trading fees and, for AI agents, your model provider.

Run it in the cloud with BotSpot

Do not want to keep a computer running for your Coinbase Advanced bot? BotSpot is the hosted home for LumiBot strategies and AI trading agents: build with AI, backtest, connect a broker, and watch every trade with logs and alerts.

Try BotSpot

Sources