TradingView Binance automation starts with an alert. When a TradingView alert fires, TradingView can send its message as an HTTP POST to a URL you choose. This guide receives that TradingView webhook in a small TypeScript service, checks it, and places a Binance USD-M futures order with the Siebly Binance JavaScript SDK, the binance npm package. Orders go to Binance’s futures testnet unless you change two settings on purpose.
The service runs as a Cloudflare Worker, which can be hosted on Cloudflare’s free Workers plan, and follows the Siebly guide to the Binance SDK in Cloudflare Workers. Every request is checked before anything reaches Binance: a shared secret compared in constant time, a strict alert schema, a symbol allow-list, a quantity cap, a leverage cap, a notional cap and an idempotent client order ID. Anything that fails a check is refused. This guide covers the plumbing only, not when to trade.
Spot orders use the SDK’s MainClient with the same checks, in Place Binance Spot orders with MainClient. Run the webhook on a Node.js Express server routes Spot and USD-M alerts through one handler on a server you host yourself.
How TradingView Binance automation works
Four pieces sit between the chart and the exchange:
- TradingView alert. You write a JSON alert message with placeholders such as
{{ticker}}. When the alert fires, TradingView fills them in and POSTs the result to your webhook URL. - Cloudflare Worker. It checks the source address, the secret and the payload, and answers straight away.
- Siebly Binance SDK. After the response, the Worker uses
USDMClientto look up the client order ID, read the mark price, set leverage and submit a market order. - Binance. Futures testnet by default, demo trading as an option, and production only with an explicit flag.
A TradingView bot built this way keeps the trading decision in TradingView and the safety rules in code you control. The Worker never invents an order: it either places exactly what a valid alert asks for, within your limits, or it places nothing.
What a TradingView webhook sends
TradingView documents its webhook behaviour in How to configure webhook alerts. The facts that shape this design:
- It sends a POST with the alert message as the body. A message that is valid JSON gets an
application/jsoncontent type; anything else is sent astext/plain. - Only ports 80 and 443 are accepted, and IPv6 is not supported.
- If the server takes longer than three seconds, TradingView cancels the request.
- Requests come from four published addresses:
52.89.214.238,34.212.75.30,54.218.53.128and52.32.178.7. - Webhook alerts need two-factor authentication on the TradingView account. Which plans include webhook notifications is listed on TradingView’s pricing page.
The page describes no request signature and no way to add your own headers, so the Worker authenticates with a secret in the JSON body plus the source address list. TradingView also warns against putting login credentials or passwords in the body. The secret here is a random token used only by this Worker; the Binance API keys stay in Worker secrets and never appear in an alert.
Write the TradingView alerts message
Paste this into the alert’s message box and turn on the webhook URL in the alert’s notifications. The placeholders come from TradingView’s strategy alerts and alert placeholder documentation:
{
"secret": "YOUR_WEBHOOK_SECRET",
"ticker": "{{ticker}}",
"action": "{{strategy.order.action}}",
"contracts": "{{strategy.order.contracts}}",
"leverage": "2",
"id": "{{strategy.order.id}}-{{timenow}}"
}
{{ticker}}is the chart symbol. TradingView lists Binance USD-M perpetuals with a.Psuffix, for example BTCUSDT.P, so the allow-list below maps that name to Binance’sBTCUSDT.{{strategy.order.action}}isbuyorsell, and{{strategy.order.contracts}}is the order quantity from the strategy.idjoins the strategy’s order ID with{{timenow}}, the alert’s fire time to the nearest second. The Worker turns it into the Binance client order ID.
For a plain price or indicator alert without a strategy, type the action and quantity as fixed values instead of strategy placeholders. Keep the alert message to these six fields: the Worker rejects any other field.
Set up the Cloudflare Worker
The project uses Node.js 24, npm, Wrangler and TypeScript, the same toolchain as the Siebly guide:
{
"name": "tradingview-binance-webhook",
"private": true,
"type": "module",
"scripts": {
"dev": "wrangler dev",
"deploy": "wrangler deploy",
"typecheck": "tsc"
},
"dependencies": {
"binance": "3.6.15"
},
"devDependencies": {
"@cloudflare/workers-types": "^5.20261129.1",
"typescript": "^7.0.2",
"wrangler": "4.161.0"
}
}
wrangler.jsonc holds the non-secret settings. The compatibility date matches the Siebly guide; Cloudflare’s Node.js compatibility page states that dates from 2026-08-04 enable Node.js compatibility by default, so no compatibility flag is needed.
{
"$schema": "node_modules/wrangler/config-schema.json",
"name": "tradingview-binance-webhook",
"main": "src/index.ts",
"compatibility_date": "2026-11-01",
"vars": {
// testnet (default), demo or live. live also needs LIVE_ORDERS = "enabled".
"BINANCE_ENV": "testnet",
"LIVE_ORDERS": "disabled",
"MAX_LEVERAGE": "3",
"MAX_NOTIONAL_USDT": "200",
// TradingView's published webhook source addresses.
"ALLOWED_IPS": "52.89.214.238,34.212.75.30,54.218.53.128,52.32.178.7"
}
}
For local runs, Wrangler reads secrets from an untracked .dev.vars file. The local file clears ALLOWED_IPS, because requests from your own machine do not come from TradingView’s addresses:
# Copy to .dev.vars for wrangler dev. Never commit .dev.vars.
WEBHOOK_SECRET=replace-with-a-long-random-string
BINANCE_API_KEY=
BINANCE_API_SECRET=
# Local requests do not come from TradingView's addresses.
ALLOWED_IPS=
The Env type and the environment guard live in one file. BINANCE_ENV defaults to testnet. live works only when LIVE_ORDERS is also enabled; any other combination throws, and the request is refused:
export interface Env {
WEBHOOK_SECRET: string;
BINANCE_API_KEY: string;
BINANCE_API_SECRET: string;
BINANCE_ENV: string;
LIVE_ORDERS: string;
MAX_LEVERAGE: string;
MAX_NOTIONAL_USDT: string;
ALLOWED_IPS: string;
}
export type BinanceEnv = 'testnet' | 'demo' | 'live';
// Testnet unless live is chosen twice. Anything unexpected throws.
export function binanceEnv(env: Env): BinanceEnv {
const value = env.BINANCE_ENV || 'testnet';
if (value === 'testnet' || value === 'demo') return value;
if (value === 'live' && env.LIVE_ORDERS === 'enabled') return 'live';
throw new Error(`Refusing BINANCE_ENV="${value}" with LIVE_ORDERS="${env.LIVE_ORDERS}"`);
}
Check the webhook secret in constant time
A plain === on strings can return faster when the first characters differ, which leaks information about the secret. Workers provide crypto.subtle.timingSafeEqual(), a non-standard Web Crypto extension that compares two buffers in a way that resists timing attacks. Hashing both values with SHA-256 first gives two 32-byte buffers whatever the input, so the comparison never depends on the secret’s length:
const encoder = new TextEncoder();
// Hash both values first so the comparison always sees equal lengths,
// then compare in constant time with the Workers runtime helper.
export async function secretMatches(received: unknown, expected: string): Promise<boolean> {
if (typeof received !== 'string' || !expected) return false;
const [a, b] = await Promise.all([
crypto.subtle.digest('SHA-256', encoder.encode(received)),
crypto.subtle.digest('SHA-256', encoder.encode(expected)),
]);
return crypto.subtle.timingSafeEqual(a, b);
}
Validate the alert: allow-list, quantity and leverage caps
In this TradingView Binance setup, the allow-list is the only place a symbol can come from. Each entry sets the Binance symbol, the largest quantity one alert may order and the number of quantity decimals to accept:
// Allow-list: TradingView {{ticker}} value -> Binance USD-M symbol and limits.
// Keys are whatever your chart's alerts send; check the alert log to confirm.
export interface SymbolRule {
symbol: string;
maxQty: number;
qtyDecimals: number;
}
export const SYMBOLS: Record<string, SymbolRule> = {
'BTCUSDT.P': { symbol: 'BTCUSDT', maxQty: 0.01, qtyDecimals: 3 },
'ETHUSDT.P': { symbol: 'ETHUSDT', maxQty: 0.1, qtyDecimals: 3 },
};
The quantity caps above are placeholders for testnet; set your own per symbol. checkAlert() rejects unknown fields, unknown tickers, any action other than buy or sell, a quantity with more decimals than allowed, a quantity over the cap and a leverage outside 1 to MAX_LEVERAGE. It refuses rather than rounds, so an order is never resized without your say:
import { SYMBOLS, type SymbolRule } from './symbols';
export interface Alert {
rule: SymbolRule;
side: 'BUY' | 'SELL';
quantity: number;
leverage: number;
alertId: string;
}
export type Checked = { ok: true; alert: Alert } | { ok: false; error: string };
const KEYS = new Set(['secret', 'ticker', 'action', 'contracts', 'leverage', 'id']);
// Validate the parsed alert body. The secret is checked separately.
export function checkAlert(body: unknown, maxLeverage: number): Checked {
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
return { ok: false, error: 'body must be a JSON object' };
}
const fields = body as Record<string, unknown>;
const extra = Object.keys(fields).find((key) => !KEYS.has(key));
if (extra) return { ok: false, error: `unexpected field "${extra}"` };
const { ticker, action, contracts, leverage, id } = fields;
const rule = typeof ticker === 'string' ? SYMBOLS[ticker] : undefined;
if (!rule) return { ok: false, error: `ticker ${String(ticker)} is not on the allow-list` };
if (action !== 'buy' && action !== 'sell') return { ok: false, error: 'action must be buy or sell' };
// TradingView placeholders arrive as strings, for example "0.002".
const qtyText = String(contracts);
const pattern = new RegExp(`^\\d+(\\.\\d{1,${rule.qtyDecimals}})?$`);
const quantity = Number(qtyText);
if (!pattern.test(qtyText) || !(quantity > 0)) {
return { ok: false, error: `contracts must be a positive number with at most ${rule.qtyDecimals} decimals` };
}
if (quantity > rule.maxQty) return { ok: false, error: `quantity ${quantity} is over the ${rule.maxQty} cap` };
const lev = leverage === undefined ? 1 : Number(leverage);
if (!Number.isInteger(lev) || lev < 1 || lev > maxLeverage) {
return { ok: false, error: `leverage must be a whole number from 1 to ${maxLeverage}` };
}
if (typeof id !== 'string' || id.length === 0 || id.length > 200) {
return { ok: false, error: 'id is required' };
}
return { ok: true, alert: { rule, side: action === 'buy' ? 'BUY' : 'SELL', quantity, leverage: lev, alertId: id } };
}
// Same alert id, same client order id: a repeated delivery maps to one order.
export async function clientOrderId(alertId: string): Promise<string> {
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(alertId));
const hex = [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('');
return `tv${hex.slice(0, 30)}`;
}
clientOrderId() hashes the alert ID into a 32-character value starting with tv. Binance’s USD-M new order reference allows newClientOrderId values matching ^[\.A-Z\:/a-z0-9_-]{1,36}$, and a SHA-256 hex prefix always fits.
Testnet by default with the Binance SDK
USDMClient takes two environment options, both in the SDK source for binance 3.6.15. testnet: true sends USD-M requests to https://testnet.binancefuture.com, and demoTrading: true sends them to https://demo-fapi.binance.com. With neither, requests go to production. Testnet and demo trading each use API keys created on those platforms.
The second constructor argument sets fetchOptions.cache to no-store, as the Siebly Workers guide does, because the SDK’s HTTP layer otherwise requests a cache mode that Workers rejects. placeOrder() runs the exchange calls in a fixed order:
import { USDMClient } from 'binance';
import type { Alert } from './alert';
import type { BinanceEnv, Env } from './env';
export function createClient(env: Env, target: BinanceEnv): USDMClient {
return new USDMClient(
{
api_key: env.BINANCE_API_KEY,
api_secret: env.BINANCE_API_SECRET,
testnet: target === 'testnet',
demoTrading: target === 'demo',
},
// Matches the Siebly Workers guide: a cache mode Workers accepts.
{ fetchOptions: { cache: 'no-store' } },
);
}
// The SDK rejects with a plain object such as { code, message, body }.
function describe(error: unknown): string {
if (typeof error === 'object' && error !== null) {
const { code, message } = error as { code?: unknown; message?: unknown };
return `${String(code)} ${String(message)}`;
}
return String(error);
}
const ORDER_NOT_FOUND = -2013;
export async function placeOrder(
client: USDMClient,
alert: Alert,
orderId: string,
maxNotional: number,
): Promise<string> {
const { symbol } = alert.rule;
try {
// Idempotency: if this client order id already exists, do nothing.
try {
const existing = await client.getOrder({ symbol, origClientOrderId: orderId });
return `duplicate alert, order ${orderId} already ${existing.status}`;
} catch (error) {
if ((error as { code?: unknown }).code !== ORDER_NOT_FOUND) throw error;
}
const mark = await client.getMarkPrice({ symbol });
const notional = alert.quantity * Number(mark.markPrice);
if (!(notional <= maxNotional)) {
return `rejected: notional ${notional.toFixed(2)} USDT is over the ${maxNotional} cap`;
}
await client.setLeverage({ symbol, leverage: alert.leverage });
const order = await client.submitNewOrder({
symbol,
side: alert.side,
type: 'MARKET',
quantity: alert.quantity,
newClientOrderId: orderId,
});
return `order ${order.clientOrderId} ${order.status}`;
} catch (error) {
return `not placed, Binance rejected the request: ${describe(error)}`;
}
}
- Look up the client order ID. Binance’s Query Order endpoint finds an order by
origClientOrderIdand returns-2013(Order does not exist.) when there is none. Any other answer, including an error, stops the alert here, so a repeated delivery of the same alert cannot place a second order. - Check the notional. Quantity times the current mark price must be at or under
MAX_NOTIONAL_USDT. - Set leverage. The value already passed the cap in
checkAlert(). - Submit a market order with the client order ID.
The SDK rejects with a plain object carrying code and message, so describe() reads those fields rather than expecting an Error. A market order without positionSide is for one-way mode; on a hedge-mode account Binance rejects it, as Binance error -4061 and hedge mode explains.
The webhook handler: answer within three seconds
The handler runs every check in order and returns as soon as one fails. Once the alert is valid, it replies 202 and finishes the Binance calls in ctx.waitUntil(), which keeps the Worker running after the response for a limited time. Four exchange calls in sequence could pass TradingView’s three-second limit, and a cancelled request would leave the outcome unknown:
import { checkAlert, clientOrderId } from './alert';
import { createClient, placeOrder } from './binance';
import { binanceEnv, type Env } from './env';
import { secretMatches } from './secret';
const reply = (status: number, message: string) => Response.json({ message }, { status });
export default {
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
if (request.method !== 'POST' || new URL(request.url).pathname !== '/tradingview') {
return reply(404, 'not found');
}
const allowed = env.ALLOWED_IPS.split(',').map((ip) => ip.trim()).filter(Boolean);
const ip = request.headers.get('CF-Connecting-IP') ?? '';
if (allowed.length > 0 && !allowed.includes(ip)) return reply(403, 'source address not allowed');
let body: unknown;
try {
body = await request.json();
} catch {
return reply(400, 'body is not valid JSON');
}
const secret = (body as { secret?: unknown } | null)?.secret;
if (!(await secretMatches(secret, env.WEBHOOK_SECRET))) return reply(401, 'bad secret');
const checked = checkAlert(body, Number(env.MAX_LEVERAGE));
if (!checked.ok) return reply(422, checked.error);
let target;
try {
target = binanceEnv(env);
} catch (error) {
return reply(503, (error as Error).message);
}
const orderId = await clientOrderId(checked.alert.alertId);
const client = createClient(env, target);
// TradingView cancels requests that take over three seconds, so answer
// now and finish the order after the response.
ctx.waitUntil(
placeOrder(client, checked.alert, orderId, Number(env.MAX_NOTIONAL_USDT)).then((result) =>
console.log(`[${target}] ${orderId}: ${result}`),
),
);
return reply(202, `accepted ${orderId} for ${target}`);
},
} satisfies ExportedHandler<Env>;
| Check | Fails with |
|---|---|
| Path or method | 404 |
Source address not in ALLOWED_IPS |
403 |
| Body is not JSON | 400 |
| Secret does not match | 401 |
| Schema, allow-list or caps | 422 |
BINANCE_ENV not allowed |
503 |
| Accepted, order runs after the response | 202 |
The order result goes to the Worker log. TradingView shows only its own delivery result, in the Webhook status column of the alert log. On the free plan, Cloudflare’s Workers limits are 10 ms of CPU time and 50 subrequests per request; time spent waiting on fetch() does not count as CPU time, and this handler makes four subrequests per accepted alert. Check CPU time in the Worker’s logs after deploying.
Run the TradingView webhook locally with wrangler dev
Results below are from wrangler dev 4.161.0 with binance 3.6.15, using random throwaway API keys. npm run dev starts the Worker in workerd on http://127.0.0.1:8787 with no Cloudflare account. A TradingView-shaped payload, sent twice:
curl -s -H 'Content-Type: application/json' \
-d '{"secret":"local-test-secret-7f3a","ticker":"BTCUSDT.P","action":"buy","contracts":"0.002","leverage":"2","id":"Long-2026-12-01T01:15:00Z"}' \
http://127.0.0.1:8787/tradingview
{"message":"accepted tvad601abfb4b0bc2b142d27326f462f for testnet"}
Both deliveries map to the same client order ID. The Worker log shows the signed requests reaching Binance’s futures testnet and the real rejection for a key that testnet does not know, -2015, which Binance error -2015 covers in detail:
[wrangler:info] POST /tradingview 202 Accepted (42ms)
[wrangler:info] POST /tradingview 202 Accepted (3ms)
[testnet] tvad601abfb4b0bc2b142d27326f462f: not placed, Binance rejected the request: -2015 Invalid API-key, IP, or permissions for action
[testnet] tvad601abfb4b0bc2b142d27326f462f: not placed, Binance rejected the request: -2015 Invalid API-key, IP, or permissions for action
The SDK signs those requests inside workerd, so the same code runs locally and on Cloudflare. With BINANCE_ENV set to demo, the same path ends at Binance’s demo trading endpoint:
[demo] tvad601abfb4b0bc2b142d27326f462f: not placed, Binance rejected the request: -2015 Invalid API-key, IP, or permissions for action
Changing one field at a time in the same payload produces these responses, none of which calls Binance:
| Payload change | HTTP | Response message |
|---|---|---|
"secret": "wrong" |
401 | bad secret |
"ticker": "DOGEUSDT.P" |
422 | ticker DOGEUSDT.P is not on the allow-list |
"contracts": "0.5" |
422 | quantity 0.5 is over the 0.01 cap |
"contracts": "0.0015" |
422 | contracts must be a positive number with at most 3 decimals |
"leverage": "20" |
422 | leverage must be a whole number from 1 to 3 |
extra "price": "1" |
422 | unexpected field "price" |
"action": "long" |
422 | action must be buy or sell |
| plain text body | 400 | body is not valid JSON |
BINANCE_ENV=live without LIVE_ORDERS |
503 | Refusing BINANCE_ENV="live" with LIVE_ORDERS="disabled" |
ALLOWED_IPS set to TradingView’s addresses, request from localhost |
403 | source address not allowed |
Deploy and connect the TradingView alert
Store the credentials as Worker secrets, then deploy. Use testnet API keys while BINANCE_ENV is testnet:
npx wrangler secret put WEBHOOK_SECRET
npx wrangler secret put BINANCE_API_KEY
npx wrangler secret put BINANCE_API_SECRET
npx wrangler deploy
Wrangler prints the Worker’s workers.dev URL. In the TradingView alert, set the webhook URL to that address plus /tradingview, over HTTPS on the default port 443, and replace YOUR_WEBHOOK_SECRET in the message with the value you stored. Fire the alert and read the result with npx wrangler tail; the log line shows whether the TradingView Binance order was placed, refused or rejected.
Moving to production is a separate decision. It takes a production API key with trading permission only and no withdrawals, BINANCE_ENV set to live and LIVE_ORDERS set to enabled. API key security best practices and the SDK’s production guide cover the rest.
Place Binance Spot orders with MainClient
A Spot order follows the same path as the futures order: the same alert message, the same secret check and the same caps, with MainClient in place of USDMClient. What changes:
- The ticker picks the market. TradingView sends a Spot chart as
BTCUSDTand a USD-M perpetual asBTCUSDT.P. Each allow-list entry carries amarketofspotorusdm, so one alert format covers both. - No leverage. A Spot alert leaves the
leveragefield out, and the checker refuses one that includes it. A Spot sell uses base asset the account already holds; there is no short position. - Quantity follows the Spot filters.
quantityis in the base asset and must match the symbol’sLOT_SIZEstep:0.00001forBTCUSDTand0.0001forETHUSDT, which is why the allow-list allows 5 and 4 decimals. The Binance exchange info filters guide covers reading them. Spot also enforces a minimum notional of 5 USDT on these two symbols. - Environments.
MainClientwithtestnet: truesends requests tohttps://testnet.binance.vision, anddemoTrading: truesends them tohttps://demo-api.binance.com. As with futures, each environment needs its own API keys. - Same duplicate guard. Binance’s Spot error list defines
-2013asOrder does not exist., so a lookup byorigClientOrderIdthat returns it means the alert is new.
getSymbolPriceTicker() is a public endpoint, so the price check needs no valid key and runs before any signed request. It returns one object for one symbol and an array without a symbol, which is why the code narrows the type:
import { MainClient } from 'binance';
import type { Alert } from './alert.ts';
import type { Config } from './config.ts';
import { describe, ORDER_NOT_FOUND } from './errors.ts';
export function createSpotClient(config: Config): MainClient {
return new MainClient({
api_key: config.apiKey,
api_secret: config.apiSecret,
testnet: config.target === 'testnet',
demoTrading: config.target === 'demo',
});
}
export async function placeSpotOrder(
client: MainClient,
alert: Alert,
orderId: string,
maxNotional: number,
): Promise<string> {
const { symbol } = alert.rule;
try {
// A public call, so an oversize alert is refused before any signed request.
const ticker = await client.getSymbolPriceTicker({ symbol });
if (Array.isArray(ticker)) throw new Error('expected one price');
const notional = alert.quantity * Number(ticker.price);
if (!(notional <= maxNotional)) {
return `rejected: notional ${notional.toFixed(2)} USDT is over the ${maxNotional} cap`;
}
// Idempotency: if this client order id already exists, do nothing.
try {
const existing = await client.getOrder({ symbol, origClientOrderId: orderId });
return `duplicate alert, order ${orderId} already ${existing.status}`;
} catch (error) {
if ((error as { code?: unknown }).code !== ORDER_NOT_FOUND) throw error;
}
const order = await client.submitNewOrder({
symbol,
side: alert.side,
type: 'MARKET',
quantity: alert.quantity,
newClientOrderId: orderId,
});
return `order ${order.clientOrderId} ${order.status}`;
} catch (error) {
return `not placed, Binance rejected the request: ${describe(error)}`;
}
}
The notional is quantity times the latest price, compared with MAX_NOTIONAL_USDT. An alert over the cap returns a rejected line and never reaches the signed calls.
Run the webhook on a Node.js Express server
A Worker suits a webhook with no server to look after. An Express server fits when you already run a Node.js process, want the Spot and USD-M clients created once and kept in memory, or plan to add order update streams next to the webhook. This variant keeps the six-field alert message from the Worker and routes by ticker:
BTCUSDTgoes toplaceSpotOrder()withMainClient.BTCUSDT.Pgoes toplaceFuturesOrder()withUSDMClient.
Node.js 24 runs the .ts files directly by removing the types, and tsc 7 checks them in strict mode with erasableSyntaxOnly, so there is no build step:
{
"name": "tradingview-binance-express",
"private": true,
"type": "module",
"scripts": {
"start": "node --env-file=.env src/server.ts",
"typecheck": "tsc"
},
"dependencies": {
"binance": "3.6.15",
"express": "^5.2.1"
},
"devDependencies": {
"@types/express": "^5.0.6",
"@types/node": "^24.0.0",
"typescript": "^7.0.2"
}
}
{
"compilerOptions": {
"target": "ES2023",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"types": ["node"]
},
"include": ["src/*.ts"]
}
Copy the environment file to .env and keep that file out of version control. BINANCE_ENV, LIVE_ORDERS, the caps and the source address list work as in the Worker, plus TRUST_PROXY for deployments behind a reverse proxy:
# Random token that TradingView sends in the alert body.
WEBHOOK_SECRET=replace-with-a-long-random-token
# Keys for the environment named in BINANCE_ENV.
BINANCE_API_KEY=
BINANCE_API_SECRET=
# testnet (default), demo or live. live also needs LIVE_ORDERS=enabled.
BINANCE_ENV=testnet
LIVE_ORDERS=disabled
MAX_LEVERAGE=3
MAX_NOTIONAL_USDT=200
# TradingView's published webhook source addresses.
ALLOWED_IPS=52.89.214.238,34.212.75.30,54.218.53.128,52.32.178.7
# Number of reverse proxies in front of Express, so req.ip is the real sender.
TRUST_PROXY=0
PORT=3000
export type Target = 'testnet' | 'demo' | 'live';
export interface Config {
secret: string;
apiKey: string;
apiSecret: string;
target: Target;
maxLeverage: number;
maxNotional: number;
allowedIps: string[];
trustProxy: number;
port: number;
}
function need(env: NodeJS.ProcessEnv, name: string): string {
const value = env[name];
if (!value) throw new Error(`${name} is not set`);
return value;
}
// Testnet unless live is chosen twice. Anything unexpected stops the server at start-up.
export function readConfig(env: NodeJS.ProcessEnv = process.env): Config {
const target = env.BINANCE_ENV || 'testnet';
if (target !== 'testnet' && target !== 'demo' && target !== 'live') {
throw new Error(`Unknown BINANCE_ENV="${target}"`);
}
if (target === 'live' && env.LIVE_ORDERS !== 'enabled') {
throw new Error(`Refusing BINANCE_ENV="live" with LIVE_ORDERS="${env.LIVE_ORDERS ?? ''}"`);
}
return {
secret: need(env, 'WEBHOOK_SECRET'),
apiKey: need(env, 'BINANCE_API_KEY'),
apiSecret: need(env, 'BINANCE_API_SECRET'),
target,
maxLeverage: Number(env.MAX_LEVERAGE ?? 3),
maxNotional: Number(env.MAX_NOTIONAL_USDT ?? 200),
allowedIps: (env.ALLOWED_IPS ?? '').split(',').map((ip) => ip.trim()).filter(Boolean),
trustProxy: Number(env.TRUST_PROXY ?? 0),
port: Number(env.PORT ?? 3000),
};
}
The allow-list, the alert checker and the secret comparison are the Worker’s versions with three changes: the allow-list entries carry a market, the leverage rule applies to usdm tickers only, and the hashing uses node:crypto instead of crypto.subtle:
// Allow-list: TradingView {{ticker}} value -> Binance market, symbol and limits.
// Spot charts send BTCUSDT, USD-M perpetual charts send BTCUSDT.P.
export interface SymbolRule {
market: 'spot' | 'usdm';
symbol: string;
maxQty: number;
qtyDecimals: number;
}
export const SYMBOLS: Record<string, SymbolRule> = {
BTCUSDT: { market: 'spot', symbol: 'BTCUSDT', maxQty: 0.01, qtyDecimals: 5 },
ETHUSDT: { market: 'spot', symbol: 'ETHUSDT', maxQty: 0.1, qtyDecimals: 4 },
'BTCUSDT.P': { market: 'usdm', symbol: 'BTCUSDT', maxQty: 0.01, qtyDecimals: 3 },
'ETHUSDT.P': { market: 'usdm', symbol: 'ETHUSDT', maxQty: 0.1, qtyDecimals: 3 },
};
import { createHash } from 'node:crypto';
import { SYMBOLS, type SymbolRule } from './symbols.ts';
export interface Alert {
rule: SymbolRule;
side: 'BUY' | 'SELL';
quantity: number;
leverage: number;
alertId: string;
}
export type Checked = { ok: true; alert: Alert } | { ok: false; error: string };
const KEYS = new Set(['secret', 'ticker', 'action', 'contracts', 'leverage', 'id']);
// Validate the parsed alert body. The secret is checked separately.
export function checkAlert(body: unknown, maxLeverage: number): Checked {
if (typeof body !== 'object' || body === null || Array.isArray(body)) {
return { ok: false, error: 'body must be a JSON object' };
}
const fields = body as Record<string, unknown>;
const extra = Object.keys(fields).find((key) => !KEYS.has(key));
if (extra) return { ok: false, error: `unexpected field "${extra}"` };
const { ticker, action, contracts, leverage, id } = fields;
const rule = typeof ticker === 'string' ? SYMBOLS[ticker] : undefined;
if (!rule) return { ok: false, error: `ticker ${String(ticker)} is not on the allow-list` };
if (action !== 'buy' && action !== 'sell') return { ok: false, error: 'action must be buy or sell' };
// TradingView placeholders arrive as strings, for example "0.002".
const qtyText = String(contracts);
const pattern = new RegExp(`^\\d+(\\.\\d{1,${rule.qtyDecimals}})?$`);
const quantity = Number(qtyText);
if (!pattern.test(qtyText) || !(quantity > 0)) {
return { ok: false, error: `contracts must be a positive number with at most ${rule.qtyDecimals} decimals` };
}
if (quantity > rule.maxQty) return { ok: false, error: `quantity ${quantity} is over the ${rule.maxQty} cap` };
// Leverage exists on USD-M only. Spot alerts leave it out.
let lev = 1;
if (rule.market === 'spot') {
if (leverage !== undefined) return { ok: false, error: 'leverage applies to futures tickers only' };
} else {
lev = leverage === undefined ? 1 : Number(leverage);
if (!Number.isInteger(lev) || lev < 1 || lev > maxLeverage) {
return { ok: false, error: `leverage must be a whole number from 1 to ${maxLeverage}` };
}
}
if (typeof id !== 'string' || id.length === 0 || id.length > 200) {
return { ok: false, error: 'id is required' };
}
return { ok: true, alert: { rule, side: action === 'buy' ? 'BUY' : 'SELL', quantity, leverage: lev, alertId: id } };
}
// Same alert id, same client order id: a repeated delivery maps to one order.
export function clientOrderId(alertId: string): string {
return `tv${createHash('sha256').update(alertId).digest('hex').slice(0, 30)}`;
}
import { createHash, timingSafeEqual } from 'node:crypto';
const digest = (value: string) => createHash('sha256').update(value).digest();
// Hash both values first so the comparison always sees equal lengths,
// then compare in constant time.
export function secretMatches(received: unknown, expected: string): boolean {
if (typeof received !== 'string' || !expected) return false;
return timingSafeEqual(digest(received), digest(expected));
}
Both order modules share the error helpers. futures.ts is the Worker’s binance.ts without the Workers-only fetchOptions argument, and with the public mark price check first, as in spot.ts:
// Binance error code for "Order does not exist." on Spot and USD-M.
export const ORDER_NOT_FOUND = -2013;
// The SDK rejects with a plain object such as { code, message, body }.
export function describe(error: unknown): string {
if (typeof error === 'object' && error !== null) {
const { code, message } = error as { code?: unknown; message?: unknown };
return `${String(code)} ${String(message)}`;
}
return String(error);
}
import { USDMClient } from 'binance';
import type { Alert } from './alert.ts';
import type { Config } from './config.ts';
import { describe, ORDER_NOT_FOUND } from './errors.ts';
export function createFuturesClient(config: Config): USDMClient {
return new USDMClient({
api_key: config.apiKey,
api_secret: config.apiSecret,
testnet: config.target === 'testnet',
demoTrading: config.target === 'demo',
});
}
export async function placeFuturesOrder(
client: USDMClient,
alert: Alert,
orderId: string,
maxNotional: number,
): Promise<string> {
const { symbol } = alert.rule;
try {
const mark = await client.getMarkPrice({ symbol });
const notional = alert.quantity * Number(mark.markPrice);
if (!(notional <= maxNotional)) {
return `rejected: notional ${notional.toFixed(2)} USDT is over the ${maxNotional} cap`;
}
try {
const existing = await client.getOrder({ symbol, origClientOrderId: orderId });
return `duplicate alert, order ${orderId} already ${existing.status}`;
} catch (error) {
if ((error as { code?: unknown }).code !== ORDER_NOT_FOUND) throw error;
}
await client.setLeverage({ symbol, leverage: alert.leverage });
const order = await client.submitNewOrder({
symbol,
side: alert.side,
type: 'MARKET',
quantity: alert.quantity,
newClientOrderId: orderId,
});
return `order ${order.clientOrderId} ${order.status}`;
} catch (error) {
return `not placed, Binance rejected the request: ${describe(error)}`;
}
}
The handler runs the same checks as the Worker, answers 202 and then places the order. Express keeps running after the response, so there is no waitUntil(); the order promise logs its own result:
import express, { type NextFunction, type Request, type Response } from 'express';
import { checkAlert, clientOrderId } from './alert.ts';
import { readConfig } from './config.ts';
import { createFuturesClient, placeFuturesOrder } from './futures.ts';
import { secretMatches } from './secret.ts';
import { createSpotClient, placeSpotOrder } from './spot.ts';
const config = readConfig();
const spot = createSpotClient(config);
const futures = createFuturesClient(config);
const app = express();
app.set('trust proxy', config.trustProxy);
app.use(express.json({ limit: '10kb' }));
app.post('/tradingview', (req: Request, res: Response) => {
const reply = (status: number, message: string) => void res.status(status).json({ message });
// Node reports IPv4 clients on a dual-stack socket as ::ffff:a.b.c.d.
const ip = (req.ip ?? '').replace(/^::ffff:/, '');
if (config.allowedIps.length > 0 && !config.allowedIps.includes(ip)) {
return reply(403, 'source address not allowed');
}
// express.json() leaves req.body undefined for a text/plain alert message.
if (typeof req.body !== 'object' || req.body === null) return reply(400, 'body is not valid JSON');
if (!secretMatches(req.body.secret, config.secret)) return reply(401, 'bad secret');
const checked = checkAlert(req.body, config.maxLeverage);
if (!checked.ok) return reply(422, checked.error);
const { alert } = checked;
const orderId = clientOrderId(alert.alertId);
const market = alert.rule.market;
// Answer first: TradingView cancels requests that take over three seconds.
reply(202, `accepted ${orderId} for ${market} on ${config.target}`);
const placed =
market === 'spot'
? placeSpotOrder(spot, alert, orderId, config.maxNotional)
: placeFuturesOrder(futures, alert, orderId, config.maxNotional);
void placed.then((result) => console.log(`[${config.target} ${market}] ${orderId}: ${result}`));
});
// A body that is declared as JSON but does not parse.
app.use((error: unknown, _req: Request, res: Response, next: NextFunction) => {
if (error instanceof SyntaxError) return void res.status(400).json({ message: 'body is not valid JSON' });
next(error);
});
app.listen(config.port, () => console.log(`listening on ${config.port}, target ${config.target}`));
Run it with npm start, which is node --env-file=.env src/server.ts. A Spot alert and a USD-M alert go to the same URL:
# Spot alert, then USD-M alert, same secret, same endpoint.
curl -s -H 'Content-Type: application/json' \
-d '{"secret":"local-secret-7f3a","ticker":"BTCUSDT","action":"buy","contracts":"0.0005","id":"Long-2026-12-02T09:00:00Z"}' \
-w '\n' http://127.0.0.1:3000/tradingview
curl -s -H 'Content-Type: application/json' \
-d '{"secret":"local-secret-7f3a","ticker":"BTCUSDT.P","action":"buy","contracts":"0.002","leverage":"2","id":"Long-2026-12-02T09:00:00Z"}' \
-w '\n' http://127.0.0.1:3000/tradingview
{"message":"accepted tvc7f1a136c23cf7b8be8fc80021e9f7 for spot on testnet"}
{"message":"accepted tvc7f1a136c23cf7b8be8fc80021e9f7 for usdm on testnet"}
The server log shows each order reaching the matching Binance environment. With random throwaway keys, Binance answers -2015, the same rejection Binance error -2015 covers. Two further alerts for 0.005 BTC, which is over the 200 USDT cap on both markets, stop at the public price check:
listening on 3000, target testnet
[testnet usdm] tvb129577ad62d7653aa51ebcdde77e9: rejected: notional 298.03 USDT is over the 200 cap
[testnet spot] tvc247858b22688b6aa3fb97fdf9380d: rejected: notional 298.10 USDT is over the 200 cap
[testnet spot] tvc7f1a136c23cf7b8be8fc80021e9f7: not placed, Binance rejected the request: -2015 Invalid API-key, IP, or permissions for action.
[testnet usdm] tvc7f1a136c23cf7b8be8fc80021e9f7: not placed, Binance rejected the request: -2015 Invalid API-key, IP, or permissions for action
With BINANCE_ENV=demo, the same two alerts end at Binance’s demo trading endpoints, https://demo-api.binance.com for Spot and https://demo-fapi.binance.com for USD-M:
listening on 3000, target demo
[demo spot] tvc7f1a136c23cf7b8be8fc80021e9f7: not placed, Binance rejected the request: -2015 Invalid API-key, IP, or permissions for action.
[demo usdm] tvc7f1a136c23cf7b8be8fc80021e9f7: not placed, Binance rejected the request: -2015 Invalid API-key, IP, or permissions for action
Responses for invalid requests, none of which calls Binance:
| Request | HTTP | Response message |
|---|---|---|
"secret": "wrong" |
401 | bad secret |
"ticker": "DOGEUSDT" |
422 | ticker DOGEUSDT is not on the allow-list |
"leverage": "2" on BTCUSDT |
422 | leverage applies to futures tickers only |
"leverage": "20" on BTCUSDT.P |
422 | leverage must be a whole number from 1 to 3 |
"contracts": "0.000123456" on BTCUSDT |
422 | contracts must be a positive number with at most 5 decimals |
| plain text body | 400 | body is not valid JSON |
| JSON that does not parse | 400 | body is not valid JSON |
ALLOWED_IPS set to TradingView’s addresses, request from localhost |
403 | source address not allowed |
Behind a reverse proxy, Express sees the proxy’s address unless TRUST_PROXY names how many proxies to trust. With TRUST_PROXY=1, a request that carries X-Forwarded-For: 52.89.214.238 passes the source address check:
$ request from localhost
{"message":"source address not allowed"} (HTTP 403)
$ request from localhost with X-Forwarded-For: 52.89.214.238
{"message":"accepted tv9159d6b8f61c99fb86bee36dc727aa for spot on testnet"} (HTTP 202)
Starting with BINANCE_ENV=live and LIVE_ORDERS=disabled stops the process before it listens:
Error: Refusing BINANCE_ENV="live" with LIVE_ORDERS="disabled"
Serve the app over HTTPS on port 443 for TradingView, with a reverse proxy or a hosting platform that terminates TLS in front of port 3000. Use npm run typecheck before each deploy.
TradingView bot FAQ
Does this work for TradingView automated trading on Binance Spot?
Yes. Place Binance Spot orders with MainClient shows the Spot order call, and the Express server places Spot and USD-M orders from one webhook URL. A Worker can do the same by swapping USDMClient for MainClient and dropping the leverage step. The Binance SDK orders guide lists the Spot order calls.
Why not wait for the order before replying to TradingView?
TradingView alerts expect a quick answer: TradingView cancels a webhook request after three seconds. Replying first and placing the order in waitUntil() keeps the response fast, and the client order ID lookup protects against a repeated delivery.
Can the Worker keep a WebSocket open for order updates?
Not from a request handler. The Siebly Workers guide explains that a handler is not an always-running process; for user data streams, use a service that keeps the connection open, as covered in the Binance SDK WebSocket guide.
Where can I read more about building the rest of a bot?
Build an AI crypto trading bot in TypeScript covers deterministic risk checks and a dry-run mode in more depth, and Binance exchange info filters covers quantity and price rules per symbol. The Siebly SDKs have over 4.8 million npm downloads across 10+ SDKs; the Binance SDK tutorial and the Binance SDK documentation are the next steps.
Versions: binance 3.6.15, Node.js 24.22.1, TypeScript 7.0.2, Express 5.3.0, wrangler 4.161.0.
