There are two ways to connect Coinbase to TradingView. TradingView lists Coinbase Advanced as a broker, so you can place orders from a chart by hand. To have an alert place the order, give the alert a webhook URL. A program you host receives the alert and calls Coinbase's Advanced Trade API.
That program takes about 120 lines of Python on Coinbase's official SDK. The one here trades spot pairs with market orders, and previews them until you switch orders on.
Can TradingView automate Coinbase orders?
Not by itself. TradingView's page on autotrading with strategies says: "Automated strategy trading with a brokerage account is not available on TradingView yet." The broker connection covers the orders you click.
An alert can call your server instead. The webhook doc says TradingView sends "a POST request as soon as the alert is triggered, with the alert message in the body of the request." Only ports 80 and 443 are accepted, and a request is cancelled after three seconds. The pricing page puts webhooks on paid plans, and TradingView allows them only with 2-factor authentication enabled.
Which fields does the alert carry?
Create the alert on a strategy with this message:
{
"pair": "{{ticker}}",
"action": "{{strategy.order.action}}",
"position": "{{strategy.market_position}}",
"order": "{{strategy.order.id}}",
"bar": "{{time}}"
}
In TradingView's list of placeholders, {{strategy.order.action}} is buy or sell for the executed order and {{strategy.market_position}} is the strategy's current position, one of long, flat or short. {{strategy.order.id}} is the first argument of the Pine call that created the order. {{time}} is the bar's time in UTC.
The receiver joins the five values into an id and handles each id once.
The webhook doc warns against "login credentials or passwords in the webhook body", so the secret goes in the URL. The order size stays on your server.
strategy placeholders "can only be used in strategy alerts", so an indicator alert needs action, position and order typed in.
Which API key does it need?
Advanced Trade takes keys from the Coinbase Developer Platform (CDP). Coinbase's API key guide starts at Secret API Keys, under the API Keys tab. Click Create API key, then expand API restrictions and Advanced Settings. The guide calls the IP allowlist "recommended but not required".
Select View and Trade, and leave Transfer off. Coinbase's permission list says Transfer lets an application "send and receive funds, on and off platform". The receiver reads the key's permissions at start and exits if Transfer is on.
Each key is tied to one portfolio. A sell alert sells that portfolio's whole available balance of the coin, so choose a portfolio holding only what the receiver may trade.
Set the signature algorithm to ECDSA. The guide says Coinbase App SDKs don't support Ed25519 keys, though the Python SDK's changelog lists them as added in version 1.8.3.
Key files "are no longer automatically downloaded", so click Download API key and copy the JSON file to your server.
What does the code do?
Install three packages with pip install coinbase-advanced-py flask waitress. The receiver is one file, app.py:
import hmac
import logging
import os
import queue
import sqlite3
import threading
import uuid
from contextlib import closing
from decimal import Decimal
from coinbase.rest import RESTClient
from flask import Flask, abort, request
logging.basicConfig(level=logging.INFO)
log = logging.getLogger("tv-coinbase")
TOKEN = os.environ["WEBHOOK_TOKEN"].encode()
BUY_QUOTE_SIZE = Decimal(os.environ["BUY_QUOTE_SIZE"])
PLACE_ORDERS = os.environ.get("PLACE_ORDERS") == "yes"
DB_PATH = os.environ.get("ALERT_DB", "alerts.sqlite3")
PRODUCTS = {"BTCUSD": "BTC-USD", "ETHUSD": "ETH-USD"}
FIELDS = ("pair", "action", "position", "order", "bar")
client = RESTClient(key_file=os.environ["COINBASE_KEY_FILE"], timeout=10)
grants = client.get_api_key_permissions()
if grants["can_transfer"]:
raise SystemExit("this API key can transfer funds; create one without Transfer")
if PLACE_ORDERS and not grants["can_trade"]:
raise SystemExit("PLACE_ORDERS=yes needs an API key with Trade")
log.info("portfolio %s, placing orders: %s", grants["portfolio_uuid"], PLACE_ORDERS)
with closing(sqlite3.connect(DB_PATH)) as db, db:
db.execute("CREATE TABLE IF NOT EXISTS alerts (id TEXT PRIMARY KEY)")
pending = queue.Queue()
app = Flask(__name__)
def is_new(alert_id):
try:
with closing(sqlite3.connect(DB_PATH)) as db, db:
db.execute("INSERT INTO alerts (id) VALUES (?)", (alert_id,))
except sqlite3.IntegrityError:
return False
return True
@app.post("/alert/<token>")
def receive(token):
if not hmac.compare_digest(token.encode(), TOKEN):
abort(404)
message = request.get_json(silent=True, force=True)
if not isinstance(message, dict):
abort(400)
values = [message.get(name) for name in FIELDS]
if not all(isinstance(value, str) and value for value in values):
abort(400)
pair, action, position = values[:3]
if pair not in PRODUCTS or action not in ("buy", "sell"):
abort(400)
alert_id = " ".join(values)
if not is_new(alert_id):
return {"result": "duplicate"}
pending.put((alert_id, PRODUCTS[pair], action, position))
return {"result": "queued"}
def floor_to(amount, increment):
step = Decimal(increment)
return amount // step * step
def available(currency):
cursor = None
while True:
page = client.get_accounts(limit=250, cursor=cursor)
for account in page.accounts:
if account.currency == currency:
return Decimal(account.available_balance["value"])
if not page.has_next:
return Decimal(0)
cursor = page.cursor
def handle(alert_id, product_id, action, position):
if action == "buy" and position != "long":
return log.info("%s ignored: a buy that does not open a long", alert_id)
product = client.get_public_product(product_id)
if action == "buy":
size = floor_to(BUY_QUOTE_SIZE, product.quote_increment)
minimum, field = product.quote_min_size, "quote_size"
else:
size = floor_to(available(product.base_currency_id), product.base_increment)
minimum, field = product.base_min_size, "base_size"
sizing = {field: f"{size:f}"}
if size < Decimal(minimum):
return log.warning("%s skipped: %s is under the product minimum", alert_id, sizing)
side = action.upper()
if not PLACE_ORDERS:
errs = client.preview_market_order(product_id, side, **sizing)["errs"]
return log.info("%s preview %s %s: errs=%s", alert_id, product_id, sizing, errs)
client_order_id = str(uuid.uuid5(uuid.NAMESPACE_URL, alert_id))
order = client.market_order(client_order_id, product_id, side, **sizing)
if order["success"]:
log.info("%s %s %s: order %s", alert_id, product_id, sizing, order["success_response"]["order_id"])
else:
log.error("%s rejected: %s", alert_id, order["error_response"])
def drain():
for job in iter(pending.get, None):
try:
handle(*job)
except Exception:
log.exception("%s raised", job[0])
threading.Thread(target=drain, daemon=True).start()
The URL's token goes through hmac.compare_digest, a comparison Python's docs say avoids "content-based short circuiting behaviour". A mismatch gets a 404.
TradingView labels a JSON message application/json and anything else text/plain, so force=True parses the body whatever the label. A body that isn't JSON, a missing field, an unlisted pair or an unknown action gets a 400.
The handler does one SQLite insert and one queue.put. A single worker thread makes every Coinbase call, outside TradingView's three-second limit.
The id column is a primary key, so a repeated id raises sqlite3.IntegrityError and the handler answers duplicate. The id is saved before the order goes out, so an alert that fails at Coinbase isn't sent again.
PRODUCTS maps TradingView tickers to Coinbase product ids and doubles as the allowlist. TradingView shows Coinbase's bitcoin pair as COINBASE:BTCUSD, and its example of {{ticker}} is BTCUSD. Coinbase calls it BTC-USD.
How are orders sized?
Coinbase's order guide sets the rule for market orders: "To buy a product, provide a quote_size or base_size; to sell, provide a base_size." In BTC-USD, bitcoin is the base and dollars are the quote.
A buy spends BUY_QUOTE_SIZE of the quote currency. A sell uses the whole available base balance, so a strategy's partial exit becomes a full exit at Coinbase. A buy that leaves the strategy flat only covered a short, and the receiver skips it.
The product endpoint describes base_increment as the "Minimum amount base value can be increased or decreased at once". On 13 Nov 2026, BTC-USD had a base_increment of 0.00000001 and a quote_min_size of 1. The receiver rounds sizes down to the increment and skips an order under the product's minimum.
Every order carries a client_order_id. The Create Order reference says that if it isn't unique, "the order will not be created and the order corresponding with that ID will be returned instead." The receiver derives it from the alert id with uuid5, so a replayed alert carries the same one even if the SQLite file is lost.
A refused order arrives with success false and the reason in error_response, which the worker logs.
Can I test without real orders?
Yes, in preview mode. Coinbase's sandbox doc says "All responses are static and pre-defined", so it can't check a size against your balance.
Until PLACE_ORDERS=yes is set, the receiver sends each order to Preview Order and places nothing. Coinbase's permission table lists that call under view, so a View-only key is enough at first. The receiver logs the preview's errs, the "List of potential failure reasons were this order to be submitted".
Send an alert by hand:
curl -X POST "https://alerts.example.com/alert/$WEBHOOK_TOKEN" \
-d '{"pair":"BTCUSD","action":"buy","position":"long","order":"test","bar":"1"}'
Flask answers {"result":"queued"}, and the preview appears in the log. The same body sent twice gets {"result":"duplicate"}.
When the log looks right, restart with PLACE_ORDERS=yes and a key that has View and Trade.
How do I keep it running?
Four environment variables configure it:
-
WEBHOOK_TOKEN, the secret part of the URL, such as the output of Python'ssecrets.token_hex(32). -
COINBASE_KEY_FILE, the path of the key file. -
BUY_QUOTE_SIZE, what each buy spends, in the quote currency. -
PLACE_ORDERS, unset until the previews look right.
A systemd unit keeps the process up:
[Service]
User=alerts
WorkingDirectory=/opt/alerts
EnvironmentFile=/etc/alerts.env
ExecStart=/opt/alerts/venv/bin/waitress-serve --host 127.0.0.1 --port 8000 app:app
Restart=on-failure
[Install]
WantedBy=multi-user.target
EnvironmentFile= "reads the environment variables from a text file", and Restart=on-failure restarts the process after a non-zero exit.
Flask's Waitress page says Waitress shouldn't run as root, which rules out ports 80 and 443: "a reverse proxy such as nginx or Apache httpd should be used in front". Point the proxy at 127.0.0.1:8000. Give TradingView https://alerts.example.com/alert/ plus your token as the webhook URL.
What do the errors mean?
| Log text | Why | What to do |
|---|---|---|
403 Client Error: Missing Required Scopes. Please verify your API keys include the necessary permissions. |
The key lacks a permission the call needs | Orders need Trade. Previews and balances need View |
Product BTC-USDX not supported |
A product id in PRODUCTS doesn't exist |
Use Coinbase's form, BTC-USD
|
INSUFFICIENT_FUND, or PREVIEW_INSUFFICIENT_FUND in a preview |
The balance doesn't cover the order | Fund the portfolio or lower BUY_QUOTE_SIZE
|
Cannot specify both api_key and key_file in constructor |
COINBASE_API_KEY or COINBASE_API_SECRET is set in the environment |
Unset both |
The SDK's source holds the first and last texts. The product text is Coinbase's answer to a made-up id on 13 Nov 2026. The sandbox doc names both fund reasons.
AI tools wrote this article. Its facts were checked against the official docs linked above, and its code was run against a stubbed exchange.
Trading involves risk of loss.
Top comments (0)