Connecting Coinbase Spot Crypto and Handling Historical Bars
Summary
The document describes Coinbase as a spot crypto venue available through Lumibot’s shared CCXT broker integration. It explains that current Coinbase Cloud Developer Platform credentials use a key name and private key, while a passphrase is generally relevant only to legacy HMAC credentials. It also notes that crypto markets run continuously, so a strategy should use a 24/7 market schedule and an appropriate polling interval.
For operational checks, it recommends starting with small paper or live quantities and verifying balances, orders, fills, and cancellations before increasing exposure. Its historical-data note explains that CCXT pagination advances the timestamp cursor by one full timeframe after the last candle, avoiding repeated boundary candles on exchanges with inclusive cursors. Requests either return the requested bar count or raise a short-history error. The document covers setup and data handling rather than a trading signal, and it provides no performance evidence or analysis of Coinbase execution quality.
Key ideas
- Coinbase access through the shared CCXT broker uses a CDP key name and private key for current credentials.
- Continuous crypto trading calls for a 24/7 market schedule.
- Small test quantities can help check balances, orders, fills, and cancellation behavior.
- Historical pagination advances beyond the last candle to avoid repeatedly fetching an inclusive boundary.
- A history request may fail when the exchange returns fewer bars than requested.
Tags
Full text
# brokers.ccxt.coinbase
:seo_title: Coinbase Advanced Trading Bot in Python: AI Agent and Algorithmic Trading
.. Generated by scripts/generate_ccxt_exchange_pages.py from docsrc/_data/. Edit the data, not this page.
Coinbase Advanced Trading Bot in Python
=======================================
.. meta::
:description: Build a Coinbase Advanced trading bot in Python with LumiBot and CCXT. Create Coinbase Advanced API keys, connect them, and run a regular or AI agent strategy.
:keywords: Coinbase Advanced trading bot, Coinbase Advanced API, Coinbase Advanced Python, agentic trading Coinbase Advanced, AI trading bot Coinbase Advanced, algorithmic trading Coinbase Advanced, ccxt coinbase
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.
.. include:: _snippets/botspot_mcp_callout.rst
Coinbase Advanced at a glance
-----------------------------
.. list-table::
:widths: 35 65
* - 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
-----------------------------
#. Create a Coinbase account with your email, confirm the email code, set a password and add your phone number.
#. Verify your identity. Coinbase asks for your legal name as it appears on your ID and has you upload the ID.
#. 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 <https://www.coinbase.com/signup>`_
Create a Coinbase Advanced API key
----------------------------------
#. In the CDP portal, open API Keys and select the Secret API Keys tab.
#. Click Create API key and enter a nickname.
#. 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.
#. Set the permissions (see below) and change the signature algorithm to ECDSA. ECDSA gives you a private key in the PEM format LumiBot expects.
#. 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.
#. 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.
.. code-block:: bash
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:
.. code-block:: python
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.
.. code-block:: python
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.
.. code-block:: python
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 :doc:`AI agents quickstart <agents_quickstart>` for models, tools and memory.
What you can trade on Coinbase Advanced
---------------------------------------
.. list-table::
:header-rows: 1
:widths: 40 60
* - 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 :doc:`the CCXT guide <brokers.ccxt>` 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.
.. code-block:: python
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 <https://botspot.trade/sales?showLogin=1&utm_source=documentation&utm_medium=exchange_page&utm_campaign=lumibot_ccxt&utm_content=coinbase>`_
Related guides
--------------
* :doc:`How crypto exchange setup works <brokers.ccxt>`
* :doc:`AI agents quickstart <agents_quickstart>`
* :doc:`One Trading trading bot <brokers.ccxt.onetrading>`
* :doc:`BigONE trading bot <brokers.ccxt.bigone>`
* :doc:`Binance COIN-M trading bot <brokers.ccxt.binancecoinm>`
* :doc:`Binance USDⓈ-M trading bot <brokers.ccxt.binanceusdm>`
Sources
-------
* `Coinbase Developer Platform: Coinbase App API Key Authentication <https://docs.cdp.coinbase.com/coinbase-app/authentication-authorization/api-key-authentication>`_ (read 2026-10-23)
* `Coinbase Developer Platform: CDP API key types and algorithms <https://docs.cdp.coinbase.com/get-started/authentication/overview>`_ (read 2026-10-23)
* `Coinbase Developer Platform: Advanced Trade API endpoints and key permissions <https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/rest-api>`_ (read 2026-10-23)
* `Coinbase Developer Platform: Welcome to Advanced Trade API <https://docs.cdp.coinbase.com/coinbase-app/advanced-trade-apis/overview>`_ (read 2026-10-23)
* `Coinbase Help: New customer resource guide <https://help.coinbase.com/new-customer-guide>`_ (read 2026-10-23)
* `CCXT 4.5.91 coinbase adapter source <https://github.com/ccxt/ccxt/blob/v4.5.91/python/ccxt/coinbase.py>`_ (read 2026-11-01)
* Exchange id, URLs, markets, credentials and stream support: CCXT 4.5.91 metadata, generated 2026-11-01Shown in full with attribution under the source's licence. Licence: GPL-3.0
This summary was written by Stratmill's research agent from the original; it is not a copy of the source.