TradingView Data API Docs
Access 160,000+ stocks, forex, cryptocurrencies, and ETF data from around the world. Supports REST API and ultra-low latency WebSocket.
Basic Information
- Base URL:
https://tradingview-data1.p.rapidapi.com - RapidAPI Host:
tradingview-data1.p.rapidapi.com - API Version: 1.2.0
- Supported Format: JSON
Authentication
All API requests require authentication via RapidAPI. You need to include the following parameters in request headers:
x-rapidapi-host: tradingview-data1.p.rapidapi.com
x-rapidapi-key: YOUR_RAPIDAPI_KEY
Please keep your API key secure and do not commit it to public code repositories. You can get your API key on RapidAPI platformto get your API key.
Rate Limit
Different subscription plans have different rate limits:
| Plan | Monthly Quota | Rate Limit | Price |
|---|---|---|---|
| Basic | 150 requests/month | 1000 requests/hour | Free |
| Pro | 30,000 requests/month | 5 requests/second | $10/month |
| Ultra | 50,000 requests/month | 5 requests/second | $30/month |
| Mega | 200,000 requests/month | 5 requests/second | $80/month |
Error Handling
API uses standard HTTP status codes to indicate request success or failure.
Common Status Codes
| Status Code | Description | Description |
|---|---|---|
200 |
OK | Request successful |
400 |
Bad Request | Invalid request parameters or missing required parameters |
401 |
Unauthorized | Authentication failed or invalid API key |
404 |
Not Found | Requested resource not found |
429 |
Too Many Requests | Rate limit exceeded |
500 |
Internal Server Error | Internal server error |
Error Response Format
{
"success": false,
"error": {
"code": "INVALID_SYMBOL",
"message": "Symbol not found or invalid",
"details": "The symbol 'INVALID:SYMBOL' does not exist"
}
}
Health - Health Check
Used to check API server status and connection.
/health
Check API server status including connection state, active sessions, authentication status, and more.
Request Examples
curl --request GET \
--url 'https://tradingview-data1.p.rapidapi.com/health' \
--header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
--header 'x-rapidapi-key: YOUR_RAPIDAPI_KEY'
const response = await fetch('https://tradingview-data1.p.rapidapi.com/health', {
method: 'GET',
headers: {
'x-rapidapi-host': 'tradingview-data1.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY'
}
});
const data = await response.json();
console.log(data);
import requests
url = "https://tradingview-data1.p.rapidapi.com/health"
headers = {
"x-rapidapi-host": "tradingview-data1.p.rapidapi.com",
"x-rapidapi-key": "YOUR_RAPIDAPI_KEY"
}
response = requests.get(url, headers=headers)
print(response.json())
Response Examples
{
"success": true,
"data": {
"status": "ok",
"timestamp": 1734234567890,
"charts": 5,
"quoteSessions": 10,
"authenticated": true,
"reconnectAttempts": 0
}
}
Price - Price Data
Get candlestick (K-line) data with support for multiple timeframes.
/api/price/{symbol}
Get OHLCV candlestick data for specified trading symbol with customizable timeframe, history range, and chart type.
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
symbol |
string | ✓ | Trading symbol code, format: EXCHANGE:SYMBOLExample: BINANCE:BTCUSDT, NASDAQ:AAPL |
Query Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
timeframe |
string | 1 | Timeframe:1, 5, 15, 30, 60, 240, D, W, M |
|
range |
integer | 10 | Number of candles (1-300) | |
to |
integer | End timestamp (Unix timestamp) for querying historical data | ||
type |
string | Chart type:candles, bars, line |
Request Examples
curl --request GET \
--url 'https://tradingview-data1.p.rapidapi.com/api/price/BINANCE:BTCUSDT?timeframe=1&range=10' \
--header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
--header 'x-rapidapi-key: YOUR_RAPIDAPI_KEY'
const symbol = 'BINANCE:BTCUSDT';
const params = new URLSearchParams({
timeframe: '1',
range: '10'
});
const response = await fetch(`https://tradingview-data1.p.rapidapi.com/api/price/${symbol}?${params}`, {
method: 'GET',
headers: {
'x-rapidapi-host': 'tradingview-data1.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY'
}
});
const data = await response.json();
console.log(data);
import requests
symbol = "BINANCE:BTCUSDT"
url = f"https://tradingview-data1.p.rapidapi.com/api/price/{symbol}"
params = {
"timeframe": "1",
"range": "10"
}
headers = {
"x-rapidapi-host": "tradingview-data1.p.rapidapi.com",
"x-rapidapi-key": "YOUR_RAPIDAPI_KEY"
}
response = requests.get(url, params=params, headers=headers)
print(response.json())
Response Examples
{
"success": true,
"data": {
"symbol": "BINANCE:BTCUSDT",
"timeframe": "1",
"candles": [
{
"time": 1704067260,
"open": 96432.50,
"high": 96500.00,
"low": 96400.25,
"close": 96450.75,
"volume": 123.45
},
// ... More candlestick data
]
}
}
/api/price/batch
Batch get candlestick data for multiple symbols (max 10 per request).
Request Body
{
"requests": [
{
"symbol": "BINANCE:BTCUSDT",
"timeframe": "1",
"range": 10
},
{
"symbol": "NASDAQ:AAPL",
"timeframe": "D",
"range": 5
}
]
}
Request Examples
curl --request POST \
--url 'https://tradingview-data1.p.rapidapi.com/api/price/batch' \
--header 'Content-Type: application/json' \
--header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
--header 'x-rapidapi-key: YOUR_RAPIDAPI_KEY' \
--data '{
"requests": [
{
"symbol": "BINANCE:BTCUSDT",
"timeframe": "1",
"range": 10
},
{
"symbol": "NASDAQ:AAPL",
"timeframe": "D",
"range": 5
}
]
}'
const response = await fetch('https://tradingview-data1.p.rapidapi.com/api/price/batch', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-rapidapi-host': 'tradingview-data1.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY'
},
body: JSON.stringify({
requests: [
{
symbol: 'BINANCE:BTCUSDT',
timeframe: '1',
range: 10
},
{
symbol: 'NASDAQ:AAPL',
timeframe: 'D',
range: 5
}
]
})
});
const data = await response.json();
console.log(data);
import requests
url = "https://tradingview-data1.p.rapidapi.com/api/price/batch"
headers = {
"Content-Type": "application/json",
"x-rapidapi-host": "tradingview-data1.p.rapidapi.com",
"x-rapidapi-key": "YOUR_RAPIDAPI_KEY"
}
data = {
"requests": [
{
"symbol": "BINANCE:BTCUSDT",
"timeframe": "1",
"range": 10
},
{
"symbol": "NASDAQ:AAPL",
"timeframe": "D",
"range": 5
}
]
}
response = requests.post(url, json=data, headers=headers)
print(response.json())
Response Examples
{
"success": true,
"data": [
{
"symbol": "BINANCE:BTCUSDT",
"candles": [...]
},
{
"symbol": "NASDAQ:AAPL",
"candles": [...]
}
]
}
Quote - Real-time Quote
Get real-time market quote data including price, volume, bid/ask spread, and more.
/api/quote/{symbol}
Get real-time quote data for specified trading symbol.
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
symbol |
string | ✓ | Trading symbol code, format: EXCHANGE:SYMBOL |
Request Examples
curl --request GET \
--url 'https://tradingview-data1.p.rapidapi.com/api/quote/NASDAQ:AAPL' \
--header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
--header 'x-rapidapi-key: YOUR_RAPIDAPI_KEY'
const symbol = 'NASDAQ:AAPL';
const response = await fetch(`https://tradingview-data1.p.rapidapi.com/api/quote/${symbol}`, {
method: 'GET',
headers: {
'x-rapidapi-host': 'tradingview-data1.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY'
}
});
const data = await response.json();
console.log(data);
import requests
symbol = "NASDAQ:AAPL"
url = f"https://tradingview-data1.p.rapidapi.com/api/quote/{symbol}"
headers = {
"x-rapidapi-host": "tradingview-data1.p.rapidapi.com",
"x-rapidapi-key": "YOUR_RAPIDAPI_KEY"
}
response = requests.get(url, headers=headers)
print(response.json())
Response Examples
{
"success": true,
"data": {
"symbol": "NASDAQ:AAPL",
"name": "Apple Inc",
"price": 228.45,
"change": 2.83,
"change_percent": 1.25,
"volume": 52341567,
"market_cap": 3520000000000,
"open": 226.50,
"high": 229.10,
"low": 225.80,
"prev_close": 225.62,
"bid": 228.40,
"ask": 228.50,
"52w_high": 237.23,
"52w_low": 164.08
}
}
/api/quote/batch
Batch get real-time quotes for multiple symbols (max 10 per request).
Request Body
{symbols": [
"NASDAQ:AAPL",
"NYSE:TSLA",
"BINANCE:BTCUSDT"
]
}
Response Examples
{
"success": true,
"data": [
{
"symbol": "NASDAQ:AAPL",
"price": 228.45,
"change_percent": 1.25,
...
},
{
"symbol": "NYSE:TSLA",
"price": 412.30,
"change_percent": -0.85,
...
},
{
"symbol": "BINANCE:BTCUSDT",
"price": 96432.50,
"change_percent": 2.14,
...
}
]
}
Search - Market Search
Search for symbols, names, or descriptions globally by keyword.
/api/search/market/{query}
Search for stocks, cryptocurrencies, forex, and other markets.
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
query |
string | ✓ | Search keyword (company name, code, etc.) |
Query Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
type |
string | Asset type filter:stock, crypto, forex, futures etc. |
||
limit |
integer | 10 | Number of results (1-50) |
Request Examples
curl --request GET \
--url 'https://tradingview-data1.p.rapidapi.com/api/search/market/apple?type=stock&limit=5' \
--header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
--header 'x-rapidapi-key: YOUR_RAPIDAPI_KEY'
const query = 'apple';
const params = new URLSearchParams({
type: 'stock',
limit: '5'
});
const response = await fetch(`https://tradingview-data1.p.rapidapi.com/api/search/market/${query}?${params}`, {
method: 'GET',
headers: {
'x-rapidapi-host': 'tradingview-data1.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY'
}
});
const data = await response.json();
console.log(data);
import requests
query = "apple"
url = f"https://tradingview-data1.p.rapidapi.com/api/search/market/{query}"
params = {
"type": "stock",
"limit": 5
}
headers = {
"x-rapidapi-host": "tradingview-data1.p.rapidapi.com",
"x-rapidapi-key": "YOUR_RAPIDAPI_KEY"
}
response = requests.get(url, params=params, headers=headers)
print(response.json())
Response Examples
{
"success": true,
"data": {
"results": [
{
"symbol": "NASDAQ:AAPL",
"description": "Apple Inc",
"type": "stock",
"exchange": "NASDAQ",
"logo": "country/US.svg"
},
// ... More results
],
"total": 5
}
}
Technical Analysis - Technical Analysis
Get professional technical analysis signals and detailed technical indicator data.
/api/ta/{symbol}
Get technical analysis signals across multiple timeframes (Buy/Sell/Neutral).
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
symbol |
string | ✓ | Trading symbol code, format: EXCHANGE:SYMBOL |
Query Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
timeframe |
string | 1d | Timeframe:1m, 5m, 15m, 1h, 4h, 1d, 1W, 1M |
Request Examples
curl --request GET \
--url 'https://tradingview-data1.p.rapidapi.com/api/ta/NASDAQ:AAPL?timeframe=1d' \
--header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
--header 'x-rapidapi-key: YOUR_RAPIDAPI_KEY'
const symbol = 'NASDAQ:AAPL';
const params = new URLSearchParams({
timeframe: '1d'
});
const response = await fetch(`https://tradingview-data1.p.rapidapi.com/api/ta/${symbol}?${params}`, {
method: 'GET',
headers: {
'x-rapidapi-host': 'tradingview-data1.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY'
}
});
const data = await response.json();
console.log(data);
import requests
symbol = "NASDAQ:AAPL"
url = f"https://tradingview-data1.p.rapidapi.com/api/ta/{symbol}"
params = {
"timeframe": "1d"
}
headers = {
"x-rapidapi-host": "tradingview-data1.p.rapidapi.com",
"x-rapidapi-key": "YOUR_RAPIDAPI_KEY"
}
response = requests.get(url, params=params, headers=headers)
print(response.json())
Response Examples
{
"success": true,
"data": {
"symbol": "NASDAQ:AAPL",
"timeframe": "1d",
"summary": {
"recommendation": "BUY",
"buy_count": 15,
"sell_count": 3,
"neutral_count": 8
},
"oscillators": {
"recommendation": "NEUTRAL",
"values": {
"RSI": 58.34,
"STOCH": 62.12,
"CCI": 45.67,
"ADX": 28.90,
"AO": 12.34,
"Mom": 3.45,
"MACD": 1.23,
"Stoch.RSI": 55.67
}
},
"moving_averages": {
"recommendation": "BUY",
"values": {
"EMA10": 225.30,
"SMA10": 224.85,
"EMA20": 222.15,
"SMA20": 221.90,
"EMA50": 215.40,
"SMA50": 214.80,
"EMA100": 208.25,
"SMA100": 207.90,
"EMA200": 195.60,
"SMA200": 195.20
}
}
}
}
/api/ta/{symbol}/indicators
Get detailed technical indicator data including RSI, MACD, Stoch, CCI, ADX, moving averages, pivot points, and more.
Response Examples
{
"success": true,
"data": {
"symbol": "NASDAQ:AAPL",
"indicators": {
"RSI": 58.34,
"RSI[1]": 56.12,
"Stoch.K": 62.12,
"Stoch.D": 58.45,
"MACD.macd": 1.23,
"MACD.signal": 0.98,
"ADX": 28.90,
"ATR": 3.45,
"CCI20": 45.67,
"BB.upper": 232.50,
"BB.lower": 220.30,
"Ichimoku.BLine": 225.40,
"VWMA": 226.80,
"HullMA9": 227.10
},
"pivot_points": {
"classic": {
"R1": 230.45,
"R2": 232.80,
"R3": 235.60,
"PP": 228.10,
"S1": 225.30,
"S2": 222.75,
"S3": 219.95
},
"fibonacci": {
"R1": 229.50,
"R2": 231.20,
"R3": 233.40,
"PP": 228.10,
"S1": 226.70,
"S2": 225.00,
"S3": 222.80
}
}
}
}
News - Financial News
Get the latest financial news and market information.
/api/news
Get financial news list with support for filtering by symbol, language, and market type.
Query Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
symbol |
string | Filter news for specific symbol(Format:EXCHANGE:SYMBOL) |
||
lang |
string | en | News language:en, zh, ja, ko etc. |
|
limit |
integer | 20 | Number of news items (1-50) |
Request Examples
curl --request GET \
--url 'https://tradingview-data1.p.rapidapi.com/api/news?symbol=NASDAQ:AAPL&lang=en&limit=10' \
--header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
--header 'x-rapidapi-key: YOUR_RAPIDAPI_KEY'
const params = new URLSearchParams({
symbol: 'NASDAQ:AAPL',
lang: 'en',
limit: '10'
});
const response = await fetch(`https://tradingview-data1.p.rapidapi.com/api/news?${params}`, {
method: 'GET',
headers: {
'x-rapidapi-host': 'tradingview-data1.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY'
}
});
const data = await response.json();
console.log(data);
import requests
url = "https://tradingview-data1.p.rapidapi.com/api/news"
params = {
"symbol": "NASDAQ:AAPL",
"lang": "en",
"limit": 10
}
headers = {
"x-rapidapi-host": "tradingview-data1.p.rapidapi.com",
"x-rapidapi-key": "YOUR_RAPIDAPI_KEY"
}
response = requests.get(url, params=params, headers=headers)
print(response.json())
Response Examples
{
"success": true,
"data": {
"news": [
{
"id": "news_123456",
"title": "Apple Reports Record Q4 Earnings",
"provider": "Reuters",
"published": 1704067260,
"source": "reuters.com",
"urgency": 1,
"link": "https://..."
},
// ... More news
],
"total": 10
}
}
Other News Endpoints
API also provides news endpoints categorized by market type:
GET /api/news/stock- Stock market newsGET /api/news/crypto- Cryptocurrency NewsGET /api/news/forex- Forex market newsGET /api/news/futures- Futures market newsGET /api/news/bond- Bond market newsGET /api/news/etf- ETF market newsGET /api/news/economic- Economic newsGET /api/news/index- Index newsGET /api/news/{newsId}- Get news details
Leaderboard - Leaderboard
Get market leaderboard data including gainers, losers, and most active rankings.
/api/leaderboard/stocks
Get stock market leaderboard data.
Query Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
market_code |
string | ✓ | Market code(Example:america, china, japan) |
|
tab |
string | gainers | Leaderboard type:gainers (Gainers), losers (Losers), active (Active) |
|
limit |
integer | 50 | Number of results (1-100) |
Request Examples
curl --request GET \
--url 'https://tradingview-data1.p.rapidapi.com/api/leaderboard/stocks?market_code=america&tab=gainers&limit=10' \
--header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
--header 'x-rapidapi-key: YOUR_RAPIDAPI_KEY'
const params = new URLSearchParams({
market_code: 'america',
tab: 'gainers',
limit: '10'
});
const response = await fetch(`https://tradingview-data1.p.rapidapi.com/api/leaderboard/stocks?${params}`, {
method: 'GET',
headers: {
'x-rapidapi-host': 'tradingview-data1.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY'
}
});
const data = await response.json();
console.log(data);
import requests
url = "https://tradingview-data1.p.rapidapi.com/api/leaderboard/stocks"
params = {
"market_code": "america",
"tab": "gainers",
"limit": 10
}
headers = {
"x-rapidapi-host": "tradingview-data1.p.rapidapi.com",
"x-rapidapi-key": "YOUR_RAPIDAPI_KEY"
}
response = requests.get(url, params=params, headers=headers)
print(response.json())
Response Examples
{
"success": true,
"data": {
"stocks": [
{
"symbol": "NASDAQ:AAPL",
"name": "Apple Inc",
"price": 228.45,
"change": 12.34,
"change_percent": 5.72,
"volume": 52341567,
"market_cap": 3520000000000
},
// ... More stocks
],
"total": 10
}
}
Other Leaderboard Endpoints
API also provides leaderboards for other asset types:
GET /api/leaderboard/crypto- Cryptocurrency LeaderboardGET /api/leaderboard/forex- Forex LeaderboardGET /api/leaderboard/futures- Futures LeaderboardGET /api/leaderboard/indices- Indices LeaderboardGET /api/leaderboard/bonds- Bonds LeaderboardGET /api/leaderboard/corporate-bonds- Corporate Bonds LeaderboardGET /api/leaderboard/etfs- ETF Leaderboard
Calendar - Financial Calendar
Get economic calendar, earnings calendar, dividends calendar, and IPO calendar data.
/api/calendar/economic
Get economic calendar event data.
Query Parameters
| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
from |
string | Today | Start date(Format:YYYY-MM-DD) | |
to |
string | 7 days later | End date(Format:YYYY-MM-DD) | |
countries |
string | Country codes (comma-separated, e.g.:US,CN,JP) |
Response Examples
{
"success": true,
"data": {
"events": [
{
"date": "2026-01-27",
"time": "14:30:00",
"country": "US",
"event": "GDP Growth Rate",
"importance": "high",
"actual": "2.9%",
"forecast": "2.8%",
"previous": "2.7%"
},
// ... More events
],
"total": 50
}
}
Other Calendar Endpoints
GET /api/calendar/earnings- Earnings CalendarGET /api/calendar/revenue- Dividends CalendarGET /api/calendar/ipo- IPO Calendar
Metadata - Metadata
Get API configuration metadata and reference data.
Metadata Endpoints
GET /api/metadata/markets- Get all available market codesGET /api/metadata/tabs- Get all available tab configurationsGET /api/metadata/columnsets- Get column set metadata by asset typeGET /api/metadata/languages- Get supported language list
Example: Get Supported Language List
curl --request GET \
--url 'https://tradingview-data1.p.rapidapi.com/api/metadata/languages' \
--header 'x-rapidapi-host: tradingview-data1.p.rapidapi.com' \
--header 'x-rapidapi-key: YOUR_RAPIDAPI_KEY'
const response = await fetch('https://tradingview-data1.p.rapidapi.com/api/metadata/languages', {
method: 'GET',
headers: {
'x-rapidapi-host': 'tradingview-data1.p.rapidapi.com',
'x-rapidapi-key': 'YOUR_RAPIDAPI_KEY'
}
});
const data = await response.json();
console.log(data);
import requests
url = "https://tradingview-data1.p.rapidapi.com/api/metadata/languages"
headers = {
"x-rapidapi-host": "tradingview-data1.p.rapidapi.com",
"x-rapidapi-key": "YOUR_RAPIDAPI_KEY"
}
response = requests.get(url, headers=headers)
print(response.json())
Response Examples
{
"success": true,
"data": {
"languages": [
{ "code": "en", "name": "English" },
{ "code": "zh", "name": "Chinese" },
{ "code": "ja", "name": "Japanese" },
{ "code": "ko", "name": "한국어" },
{ "code": "es", "name": "Español" },
{ "code": "fr", "name": "Français" },
{ "code": "de", "name": "Deutsch" },
{ "code": "ru", "name": "Русский" }
]
}
}
Logo - Logo Proxy
Get TradingView symbol logo images.
/logo/{path}
Get TradingView logo images via proxy service. The path parameter should be obtained from currency-logoid, base-currency-logoid, or logoid fields returned by other endpoints.
Path Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
path |
string | ✓ | Logo path (Example:country/US.svg) |
Example Usage
<mg src="https://tradingview-data1.p.rapidapi.com/logo/country/US.svg" alt="Logo" />
Token - JWT Token Generation
Generate JWT tokens for WebSocket authentication. This endpoint allows you to create time-limited authentication tokens for secure WebSocket connections.
/api/token/generate
Generate a JWT token for WebSocket connections with configurable expiration times.
Request Headers
X-RapidAPI-Host: tradingview-data1.p.rapidapi.com
X-RapidAPI-Key: YOUR_RAPIDAPI_KEY
Content-Type: application/json
Example Request
curl -X POST "https://tradingview-data1.p.rapidapi.com/api/token/generate" \
-H "X-RapidAPI-Host: tradingview-data1.p.rapidapi.com" \
-H "X-RapidAPI-Key: YOUR_RAPIDAPI_KEY" \
-H "Content-Type: application/json" \
-d '{
"token-jwt-type": 2,
"userId": "user123"
}'
Response
{
"success": true,
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"expiresIn": "6 hours",
"expiresAt": 1705567890123,
"wsUrl": "wss://ws.singularitymark.sbs"
}
Response Fields
| Field | Type | Description |
|---|---|---|
success |
boolean | Indicates if token generation was successful |
token |
string | JWT token for WebSocket authentication |
expiresIn |
string | Human-readable expiration duration (e.g., "6 hours") |
expiresAt |
number | Unix timestamp in milliseconds when token expires |
wsUrl |
string | WebSocket server URL to use with this token |
You must generate a new token before the current token expires. WebSocket connections will be automatically terminated when the token expires. Monitor the expiresAt timestamp and proactively refresh your token.
WebSocket Real-time Data Stream
Use WebSocket to get ultra-low latency real-time data push.
WebSocket feature is only available in Ultra and Mega plans.
Connection Steps
- Generate JWT token using
POST /api/token/generateendpoint - Connect to WebSocket server using the token from the response
- Subscribe to trading symbols you are interested in
- Receive real-time data push
WebSocket Connection Example
// First, generate a JWT token
const tokenResponse = await fetch('https://tradingview-data1.p.rapidapi.com/api/token/generate', {
method: 'POST',
headers: {
'X-RapidAPI-Host': 'tradingview-data1.p.rapidapi.com',
'X-RapidAPI-Key': 'YOUR_RAPIDAPI_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({ 'token-jwt-type': 2 })
});
const { token, wsUrl } = await tokenResponse.json();
// Connect to WebSocket with token
const ws = new WebSocket(`${wsUrl}?token=${token}`);
ws.onopen = () => {
console.log('WebSocket connected');
// Subscribe to trading symbols
ws.send(JSON.stringify({
action: 'subscribe',
symbols: ['BINANCE:BTCUSDT', 'NASDAQ:AAPL']
}));
};
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
console.log('Real-time data:', data);
// Handle price updates
if (data.type === 'quote') {
console.log(`${data.symbol}: $${data.price} (${data.change_percent}%)`);
}
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
ws.onclose = () => {
console.log('WebSocket disconnected');
};
import websocket
import json
import requests
# First, generate a JWT token
response = requests.post(
'https://tradingview-data1.p.rapidapi.com/api/token/generate',
headers={
'X-RapidAPI-Host': 'tradingview-data1.p.rapidapi.com',
'X-RapidAPI-Key': 'YOUR_RAPIDAPI_KEY',
'Content-Type': 'application/json'
},
json={'token-jwt-type': 2}
)
token_data = response.json()
token = token_data['token']
ws_url = token_data['wsUrl']
def on_message(ws, message):
data = json.loads(message)
print(f"Real-time data: {data}")
if data.get('type') == 'quote':
symbol = data['symbol']
price = data['price']
change = data['change_percent']
print(f"{symbol}: ${price} ({change}%)")
def on_open(ws):
print("WebSocket connected")
# Subscribe to trading symbols
ws.send(json.dumps({
'action': 'subscribe',
'symbols': ['BINANCE:BTCUSDT', 'NASDAQ:AAPL']
}))
def on_error(ws, error):
print(f"WebSocket error: {error}")
def on_close(ws, close_status_code, close_msg):
print("WebSocket disconnected")
# Connect to WebSocket with token
ws = websocket.WebSocketApp(
f"{ws_url}?token={token}",
on_message=on_message,
on_open=on_open,
on_error=on_error,
on_close=on_close
)
ws.run_forever()
WebSocket Message Format
{type": "quote",
"symbol": "BINANCE:BTCUSDT",
"price": 96432.50,
"change": 1203.45,
"change_percent": 1.26,
"volume": 123456.78,
"timestamp": 1704067260
}
Best Practices
Recommended Practices
- Use batch endpoints - When you need to get data for multiple symbols, using batch endpoints can reduce the number of requests
- Cache data - For data that doesn't change frequently (such as market metadata), it's recommended to cache on the client side
- Error retry - Implement exponential backoff retry strategy to avoid frequent retries when errors occur
- WebSocket usage - For scenarios requiring real-time data, using WebSocket is more efficient than polling REST API
- Monitor quota - Regularly check your API usage to avoid exceeding quota limits
Practices to Avoid
- Frequent polling - Avoid polling the same endpoint at very high frequencies
- Ignore errors - Don't ignore error messages returned by API, they contain important debugging information
- Hardcode data - Don't hardcode configuration data like market codes, should dynamically get from metadata endpoints
- Expose API Key - Never expose your API key in client-side code
- Oversized batch requests - Comply with batch endpoint quantity limits, don't try to include too many items in a single request
Support & Help
Complete Documentation
View complete API documentation and reference on RapidAPI
View Documentation →