TradingView Webhook Documentation
Automate your trading by sending TradingView alerts directly to your exchange accounts
Complete guide to webhook integration, supported fields, and JSON payload examples
Quick Start Guide
Sign up for Traydar
Create your free account at traydar.com/signup
Connect your exchange
Link your crypto exchange or MT4/MT5 broker account in the dashboard
Get your webhook URL
Copy your unique webhook URL from Dashboard → Webhooks
Create TradingView alert with webhook
Set up your alert in TradingView, enable webhook notifications, and paste your Traydar webhook URL
Getting Your Webhook URL
Once logged in, navigate to your dashboard and find the Webhooks section. Your unique webhook URL will look like:
Copy this URL and use it in your TradingView alerts to send trade signals directly to Traydar.
Supported Webhook Fields
| Field | Type | Required | Description |
|---|---|---|---|
| exchange | string | Conditional* | Exchange identifier (e.g., "binance", "MT5", "okx"). *Required unless accountName or accounts is provided |
| accountName | string | No | Specific exchange account name (for routing to a particular account). Exchange is automatically determined from the account. |
| accounts | string | No | Comma-separated list of account names to route the order to multiple accounts simultaneously (can be across different exchanges and brokers) |
| rule | string | No | Name of a trading rule to execute instead of direct order placement. When specified, the webhook data is passed as context to the rule engine. See Rule-Based Trading section for details. |
| script | string | No | Name of a Python script to execute. When specified, the script is triggered with the webhook data available via get_trigger_payload(). Script runs asynchronously and webhook returns immediately. See Python Scripts documentation for details. |
| script_listener | string | No | Name of a long-running Python script to send a real-time message to. The script must be currently running and have an @on_message decorator. Message is delivered instantly via Redis pub/sub. See Message Listeners documentation. |
| symbol | string | Yes | Trading pair symbol (e.g., "BTCUSDT", "USDJPY") |
| action | string | Yes | Trade direction: "buy" or "sell" |
| quantity | number or string | Yes | Order quantity. Supports:
|
| price | number | No | Limit price (omit for market orders) |
| riskai | number | No | Enable/disable RiskAI checks: 0 = disabled, 1 = enabled (default: 1). Set to 0 to bypass risk validation for this specific trade. |
| stop_loss | number | No | Stop loss price level |
| take_profit | number | No | Take profit price level |
| order_type | string | No | "market" or "limit" (auto-detected from price field) |
| leverage | number | No | Leverage multiplier (for supported exchanges) |
💡 Percentage-Based Quantities
Specify quantities as percentages instead of absolute values for dynamic position sizing based on your available balance or holdings.
BUY Orders
Percentage of available balance in quote currency.
{
"symbol": "BTCUSDT",
"action": "buy",
"quantity": "50%",
"price": 50000
}⚠️ Price field is required for percentage BUY orders
SELL Orders
Percentage of total position size.
{
"symbol": "BTCUSDT",
"action": "sell",
"quantity": "100%"
}✓ Close entire position with "100%"
Requirements & Notes:
- Valid range: 0% to 100%
- Format: String with "%" suffix (e.g., "50%")
- Compatible: Absolute quantities still work (e.g., 0.01)
- Fresh data: Balance/position fetched in real-time from exchange
- Multi-account: Each account calculates independently
Webhook Routing Logic
Traydar uses a priority-based routing system to determine which account(s) receive your webhook signal:
Priority 0: Multi-Account Routing (Highest)
If your webhook includes an accounts field with a comma-separated list of account names, Traydar will route the same order to all specified accounts simultaneously. This is the most powerful option - accounts can be across different exchanges and brokers (e.g., "Main Trading,Scalping Account,MT5 Broker").
Priority 1: Single Account Name Match
If your webhook includes an accountName field, Traydar will route the signal to that specific account. The exchange type is automatically determined from the account - no need to specify exchange separately.
Priority 2: Exchange Type Match
If no accounts or accountName is provided, Traydar will route to the first active account of the specified exchange type.
Priority 3: Fallback (Lowest)
If none of the above are provided, Traydar will route to your first active account of any type. A warning will be logged about this fallback routing.
Rule-Based Trading Logic
Define complex trading logic using rules instead of direct webhook parameters
What are Trading Rules?
Trading Rules allow you to define custom trading logic using a simple, deterministic language. Instead of sending direct order parameters in your webhooks, you can reference a rule by name and let Traydar's rule engine handle:
- Conditional routing based on market conditions or signal data
- Multi-step trading sequences with error handling
- Dynamic calculations (stop loss, position sizing, etc.)
- Parallel execution across multiple rules
- Automatic notifications via Telegram
How to Use Rules
Step 1: Create a rule in your dashboard
Step 2: Reference the rule in your webhook payload:
{
"rule": "my_trading_strategy",
"symbol": "BTCUSDT",
"action": "buy",
"quantity": 1.0,
"price": 50000
}Step 3: Traydar executes your rule with the webhook data as context
Example Rule
rule buy_with_stop_loss:
# Only process BUY signals
if action != "BUY" goto end
# Calculate stop loss (2% below entry)
set stop_price = price * 0.98
# Place market order
place_order(symbol=symbol, side="BUY", quantity=quantity, type="market")
on_error goto error
# Send success notification
send_message("Buy order placed at " + price + ". Stop: " + stop_price)
goto end
:error
send_message("Order failed: " + last_error)
goto end
:end
endBenefits: Rules are deterministic, sandboxed, and resource-light. No loops, no recursion, just straightforward conditional logic that executes in milliseconds.
Python Script Execution via Webhooks
Trigger custom Python scripts from webhooks for advanced automation and price monitoring
What is Script-Based Execution?
Instead of placing direct orders or running rules, you can trigger Python scripts from webhooks. This allows you to:
- Run complex calculations and data analysis in Python
- Access real-time exchange data (positions, balances, orders)
- Make conditional trading decisions based on custom logic
- Watch for price patterns and react automatically
- Send customized Telegram notifications
- Chain multiple trading operations together
How to Use Script Execution
Step 1: Create a Python script in your dashboard
Step 2: Reference the script name in your webhook payload:
{
"script": "my_price_alert_script",
"symbol": "BTCUSDT",
"price": 98500.50,
"custom_field": "any data you want"
}Step 3: Your script receives the webhook data and executes asynchronously
Note: When using the script parameter, the webhook returns immediately and the script runs in the background. Order placement parameters like action, quantity, etc. are ignored - your script decides what to do.
Accessing Webhook Data in Your Script
# Get the webhook payload that triggered this script
payload = get_trigger_payload()
print(f"Triggered by webhook!")
print(f"Symbol: {payload['symbol']}")
print(f"Price: {payload['price']}")
# Access any custom fields you sent
if 'custom_field' in payload:
print(f"Custom data: {payload['custom_field']}")
# Use the data to make trading decisions
if payload['price'] > 100000:
place_order(
symbol=payload['symbol'],
side="sell",
amount=0.1,
order_type="market"
)
send_message(f"BTC hit $ {payload['price']}! Sold 0.1 BTC")
else:
send_message(f"BTC at $ {payload['price']}, holding position")Example Use Cases
📊 Custom Risk Checks
Webhook triggers script that checks your portfolio risk before placing the order
🎯 Dynamic Position Sizing
Calculate position size based on account balance, volatility, and risk tolerance
📈 Multi-Leg Strategies
Execute complex strategies like spreads, hedges, or portfolio rebalancing
⚡ Real-Time Alerts
Trigger long-running price watchers that monitor markets 24/7
Script vs Rule: Use scripts for complex Python logic, data analysis, and API calls. Use rules for simple conditional logic that needs to execute in milliseconds. Scripts are more powerful but take longer to start (~1-2 seconds).
JSON Payload Examples
Example 1: MT4/MT5 Forex Trade with Stop Loss and Take Profit
{
"exchange": "MT5",
"symbol": "USDJPY",
"action": "sell",
"price": 154.872,
"quantity": 1,
"stop_loss": 155.500,
"take_profit": 154.000
}Example 2: Binance Crypto Trade
{
"exchange": "binance",
"symbol": "BTCUSDT",
"action": "sell",
"price": 86830,
"quantity": 1
}Example 3: Market Order (No Price)
{
"exchange": "binance",
"symbol": "ETHUSDT",
"action": "buy",
"quantity": 0.5
}When price is omitted, the order executes as a market order at the current market price.
Example 4: All Optional Fields
{
"exchange": "binanceusdm",
"symbol": "BTCUSDT",
"action": "buy",
"price": 85000,
"quantity": 0.1,
"stop_loss": 84000,
"take_profit": 90000,
"order_type": "limit",
"leverage": 10
}Example 5: Routing to a Specific Account with accountName
{
"accountName": "My Trading Account",
"symbol": "BTCUSDT",
"action": "buy",
"price": 86000,
"quantity": 0.05
}Use accountName to route webhooks to a specific account. The exchange type is automatically determined from the account - no need to specify exchange separately. The account name must exactly match the name you set in your Traydar dashboard.
Example 6: Routing to Multiple Accounts Simultaneously
{
"accounts": "Main Trading,Scalping Account,MT5 Broker",
"symbol": "BTCUSDT",
"action": "buy",
"price": 86000,
"quantity": 0.05
}Use accounts to send the same order to multiple accounts simultaneously. Provide a comma-separated list of account names. This is the highest priority routing method - accounts can be across different exchanges and brokers (e.g., Binance, OKX, MT4, MT5). Each account name must exactly match a name in your Traydar dashboard.
Example 7: Percentage-Based Quantities
{
"accountName": "My Trading Account",
"symbol": "BTCUSDT",
"action": "buy",
"price": 50000,
"quantity": "50%"
}Uses 50% of available USDT balance to buy BTC at $50,000. For SELL orders, use percentage of total position size (e.g., "quantity": "100%" to close entire position). Valid range: 0% to 100%.
Example 8: Bypassing RiskAI Checks
{
"exchange": "binance",
"symbol": "BTCUSDT",
"action": "buy",
"price": 86000,
"quantity": 0.1,
"riskai": 0
}Setting riskai: 0 disables RiskAI validation for this specific trade. The trade will execute without position sizing, portfolio heat, or behavioral checks. Use with caution! By default, riskai is 1 (enabled) if not specified.
Example 9: Executing a Trading Rule
{
"rule": "my_trading_strategy",
"symbol": "BTCUSDT",
"action": "buy",
"price": 86000,
"quantity": 1.0
}Instead of placing a direct order, this executes the trading rule named my_trading_strategy with the webhook data as context. The rule can add custom logic, stop losses, notifications, etc. See the Rule-Based Trading section for details.
Example 10: Triggering a Python Script
{
"script": "price_alert_handler",
"symbol": "BTCUSDT",
"price": 98500.50,
"alert_type": "resistance_break",
"timeframe": "1h"
}Triggers the Python script named price_alert_handler with the webhook payload. The script runs asynchronously and can access the data via get_trigger_payload(). Perfect for complex analysis, custom risk checks, or chaining multiple operations. See the Python Script Execution section for details.
Example 11: Sending a Message to a Long-Running Script
{
"script_listener": "btc_monitor",
"alert_type": "resistance_break",
"symbol": "BTCUSDT",
"price": 98500.50,
"volume_spike": true
}Sends a real-time message to the long-running script named btc_monitor (which must already be running). The script receives the message instantly via Redis pub/sub and can react immediately. Perfect for alerting monitoring bots or sending parameter updates to running strategies. See Message Listeners documentation.
Field Validation Rules
exchange
Valid exchange identifiers:
- Crypto:
binance,binanceusdm,binancecoinm,okx,bybit,kucoin, etc. - Forex/CFDs:
MT4,MT5
accountName
Optional. Use this to route webhooks to a specific exchange account by its name. The account name must exactly match the name you set in your Traydar dashboard. When using accountName, the exchange type is automatically determined from the account - no need to specify the exchange field separately.
accounts
Optional. Comma-separated list of account names for multi-account routing. Each name must exactly match an account in your Traydar dashboard. Orders will be sent to all listed accounts simultaneously. This is the highest priority routing method and is particularly powerful for sending the same signal across different exchanges and brokers (e.g., "Main Trading,Scalping Account,MT5 Broker" will route to 3 different accounts).
symbol
Exchange-specific format:
- Crypto: Use exchange format (e.g.,
BTCUSDT,ETHUSDT) - Forex: Use standard pairs (e.g.,
EURUSD,USDJPY,GBPUSD)
action
Must be either "buy" or "sell" (case-insensitive)
price
Positive number. If omitted, order executes as a market order. If provided, order executes as a limit order at the specified price.
quantity
Positive number representing the order size in the base currency or lots (for MT4/MT5).
riskai
Optional number to enable/disable RiskAI validation for this specific trade.
0- Disable RiskAI checks (bypasses all risk validation)1- Enable RiskAI checks (default if not specified)
Note: Setting riskai: 0 bypasses position sizing limits, portfolio heat checks, behavioral detection, and all other RiskAI protections. Use with extreme caution.
Setting Up TradingView Alerts
Step 1: Create Alert in TradingView
Open your chart in TradingView, click the alert icon (clock), and set your desired conditions for the alert to trigger.
Step 2: Enable Webhook Notifications
In the alert settings, go to the Notifications tab and check the "Webhook URL" option.
Step 3: Paste Your Traydar Webhook URL
Paste your unique Traydar webhook URL (from your dashboard) into the webhook URL field.
Step 4: Configure Alert Message (JSON Payload)
In the Message field, enter your JSON payload with the trade details:
{
"exchange": "binance",
"symbol": "BTCUSDT",
"action": "buy",
"price": 86830,
"quantity": 0.01
}Step 5: Save and Test
Click "Create" to save your alert. When the alert triggers, TradingView will send the webhook to Traydar, which will execute the trade on your connected exchange.
Common Issues & Troubleshooting
Invalid Exchange Name
Make sure the exchange name matches exactly. Use lowercase for crypto exchanges (e.g., "binance", "okx") and uppercase for MT4/MT5.
Symbol Format Errors
Each exchange has its own symbol format. For Binance, use "BTCUSDT". For MT4/MT5, use standard forex pairs like "EURUSD" or "USDJPY".
Missing Required Fields
Ensure your JSON includes all required fields: exchange, symbol, action, and quantity. The webhook will fail without these.
Invalid JSON Syntax
Use a JSON validator to check your payload. Common errors include missing commas, unquoted strings, or trailing commas.
RiskAI Protection
AI-powered risk management for every trade
Traydar includes RiskAI, an intelligent risk management system that protects your trading account from dangerous mistakes. Every webhook signal is automatically analyzed before execution, checking against multiple risk parameters to prevent account blow-ups and emotional trading errors.
Why RiskAI Matters
Most traders fail not because of bad strategy, but because of poor risk management. A single oversized position, a correlated portfolio during a market crash, or revenge trading after a loss can wipe out months of gains in minutes.
RiskAI acts as your guardian, continuously monitoring your account and blocking trades that violate your risk parameters—even when emotions tell you to ignore the rules.
Core Protection Features
🛡️ Smart Position Sizing
Automatically calculates maximum safe position size based on your account balance, risk tolerance, and market volatility.
- • Kelly Criterion: Optimal position sizing based on win rate
- • Volatility Adjustment: Auto-reduce size during high volatility
- • Max Position Limit: Never exceed configured % of account
- • Leverage Control: Prevent over-leveraged positions
📊 Portfolio Risk Analysis
Monitors total portfolio exposure, correlation between positions, and warns when risk limits are approached.
- • Portfolio Heat: Total risk across all positions
- • Correlation Detection: Identify correlated positions
- • Max Open Positions: Prevent over-diversification
- • Daily Loss Limit: Stop trading after daily limit hit
🧠 Behavioral Detection
Identifies revenge trading, overtrading, and emotional decision patterns to protect you from yourself.
- • Revenge Trading: Blocks trades within cooldown after loss
- • Rapid Trading: Flags excessive trading frequency
- • Position Size Deviation: Detects unusual bet sizing
- • Consecutive Losses: Increases scrutiny after losing streak
⚡ Real-Time Alerts
Instant Telegram notifications when risk thresholds are exceeded, with configurable enforcement modes.
- • Instant Notifications: Telegram alerts within seconds
- • Risk Score: 0-100 score for every trade attempt
- • Detailed Context: See exactly why trade was flagged
- • Alert History: Track all warnings and blocks
📈 Risk Score Calculation
Every trade receives a comprehensive risk score (0-100) based on seven weighted components, including AI-powered predictions:
AI-Powered Risk Prediction
Advanced machine learning model trained on behavioral patterns and portfolio metrics
RiskAI now includes a Machine Learning component that learns from your trading history to predict risk more accurately than rule-based systems alone. The AI model analyzes 32+ features including:
📊 What the AI Learns From
- • Your historical win rates and profit factors
- • Trading frequency and timing patterns
- • Position sizing consistency
- • Drawdown recovery behavior
- • Portfolio correlation patterns
- • Emotional trading indicators
✨ How It Helps You
- • Detects subtle risk patterns humans miss
- • Adapts to your evolving trading style
- • No price data needed - pure behavioral AI
- • Complements rule-based protections
- • Continuous learning from outcomes
- • Fails gracefully (never blocks on AI error)
🧠 How It Works
The ML model uses a algorithm trained on historical risk scores and trade outcomes. It predicts a risk score (0-100) that gets weighted at 15% in your final risk calculation, working alongside the six traditional components.
Privacy First: Your data never leaves our secure infrastructure. The model trains on aggregated behavioral metrics, not your raw trade details. If the ML system fails for any reason, it defaults to a neutral score and your trades continue with traditional risk checks intact.
Configurable Enforcement Modes
Get alerts and see risk scores, but all trades are allowed to proceed. Best for experienced traders who want visibility without automation. You'll receive Telegram notifications for every warning, but maintain full manual control.
Dangerous trades are automatically blocked before execution. Critical violations (position size exceeded, portfolio heat exceeded) prevent the trade entirely. You can configure which violations trigger blocks vs warnings. Recommended for most traders.
Turn off all risk checks (not recommended). Only use this if you have another risk management system in place. All webhook signals will be processed without RiskAI analysis.
🎯 Real-World Examples
Scenario 1: Position Size Violation
Your webhook signals a 5 BTC buy, but RiskAI calculates this is 15% of your account—exceeding your 10% max position size limit.
Result: Trade blocked with Telegram alert: "Position size (15.00%) exceeds maximum allowed (10.00%)"
Scenario 2: Revenge Trading Detection
You just closed a losing trade on BTCUSDT. 3 minutes later, your webhook triggers another BTCUSDT entry. You have a 30-minute revenge trading cooldown configured.
Result: Warning issued: "Potential revenge trading detected - trade within cooldown period after loss"
Scenario 3: Correlated Positions
You already hold positions in BTC and ETH. Your webhook now signals an entry on another crypto altcoin. RiskAI detects high correlation (0.85) across all three.
Result: Warning: "High correlation detected - portfolio risk may be concentrated"
Scenario 4: Portfolio Heat Exceeded
You have 5 open positions with combined risk of 18% of account. Your portfolio heat limit is 20%. New trade would add 5% more risk.
Result: Trade blocked: "Portfolio heat (23.00%) would exceed limit (20.00%)"
⚙️ Configurable Parameters
Customize RiskAI to match your trading style and risk tolerance. All settings are configured per-user in the RiskAI dashboard:
- • Max position size %
- • Max leverage
- • Default stop-loss %
- • Daily loss limit %
- • Portfolio heat limit
- • Max open positions
- • Max trades per hour
- • Max trades per day
- • Revenge trading cooldown
- • Max correlation threshold
- • Correlation lookback days
Pro Feature
RiskAI is available exclusively with Traydar Pro subscription. Pro members get access to the complete risk management suite including:
- • Full risk analysis on every trade
- • Configurable enforcement modes
- • Real-time Telegram alerts
- • Historical risk score tracking
- • Portfolio correlation analysis
- • Behavioral pattern detection
Ready to Automate Your Trading?
Start sending TradingView alerts to your exchange accounts in minutes
Get Started Free