api-integration.pine
Copy
// Pine Script API Integration Examples
// @version=6
// ===== MULTI-TIMEFRAME DATA REQUESTS =====
indicator("API Integration Examples", shorttitle="API", overlay=true)
// Higher timeframe data requests
htf_4h = "4H"
htf_1d = "1D"
htf_1w = "1W"
// Request security data from different timeframes
htf_4h_close = request.security(syminfo.tickerid, htf_4h, close)
htf_4h_sma20 = request.security(syminfo.tickerid, htf_4h, ta.sma(close, 20))
htf_4h_volume = request.security(syminfo.tickerid, htf_4h, volume)
htf_1d_high = request.security(syminfo.tickerid, htf_1d, high)
htf_1d_low = request.security(syminfo.tickerid, htf_1d, low)
htf_1d_open = request.security(syminfo.tickerid, htf_1d, open)
htf_1w_rsi = request.security(syminfo.tickerid, htf_1w, ta.rsi(close, 14))
// Plot higher timeframe data
plot(htf_4h_sma20, "4H SMA20", color.blue, 2)
plot(htf_1d_high, "Daily High", color.red, 1, plot.style_stepline)
plot(htf_1d_low, "Daily Low", color.green, 1, plot.style_stepline)
// ===== MULTIPLE SYMBOL DATA REQUESTS =====
// Compare with other symbols
spy_symbol = "SPY"
qqq_symbol = "QQQ"
vix_symbol = "VIX"
// Get data from other symbols
spy_close = request.security(spy_symbol, timeframe.period, close)
qqq_close = request.security(qqq_symbol, timeframe.period, close)
vix_close = request.security(vix_symbol, timeframe.period, close)
// Calculate relative performance
spy_performance = (spy_close / spy_close[20] - 1) * 100
current_performance = (close / close[20] - 1) * 100
relative_performance = current_performance - spy_performance
// Plot relative performance
plot(relative_performance, "Relative to SPY", color=relative_performance > 0 ? color.green : color.red)
// ===== ECONOMIC DATA INTEGRATION =====
// Simulate economic calendar integration (in practice, you'd need external data)
// This example shows how you might structure such integration
// Function to simulate getting economic data
getEconomicData(indicator_name) =>
// In real implementation, this would call external API
// For demo, we'll simulate with random-ish values based on time
base_value = math.sin(time / 86400000) * 100 // Daily cycle
noise = (bar_index % 7) * 10 - 30 // Weekly variation
base_value + noise
// Simulated economic indicators
gdp_growth = getEconomicData("GDP")
unemployment_rate = math.abs(getEconomicData("UNEMPLOYMENT")) / 10 + 3
inflation_rate = math.abs(getEconomicData("INFLATION")) / 20 + 2
// Display economic data in table
var table econ_table = table.new(position.top_right, 2, 4, bgcolor=color.white, border_width=1)
if barstate.islast
table.cell(econ_table, 0, 0, "Economic Data", text_color=color.white, bgcolor=color.navy)
table.cell(econ_table, 1, 0, "Value", text_color=color.white, bgcolor=color.navy)
table.cell(econ_table, 0, 1, "GDP Growth", text_color=color.black)
table.cell(econ_table, 1, 1, str.tostring(gdp_growth, "#.#") + "%",
text_color=gdp_growth > 0 ? color.green : color.red)
table.cell(econ_table, 0, 2, "Unemployment", text_color=color.black)
table.cell(econ_table, 1, 2, str.tostring(unemployment_rate, "#.#") + "%", text_color=color.black)
table.cell(econ_table, 0, 3, "Inflation", text_color=color.black)
table.cell(econ_table, 1, 3, str.tostring(inflation_rate, "#.#") + "%",
text_color=inflation_rate > 3 ? color.red : color.green)
// ===== SECTOR/INDUSTRY DATA =====
// Get sector ETF data for comparison
xlf_symbol = "XLF" // Financial sector
xlt_symbol = "XLT" // Technology sector
xle_symbol = "XLE" // Energy sector
xlf_close = request.security(xlf_symbol, timeframe.period, close)
xlt_close = request.security(xlt_symbol, timeframe.period, close)
xle_close = request.security(xle_symbol, timeframe.period, close)
// Calculate sector relative strength
xlf_strength = (xlf_close / ta.sma(xlf_close, 50) - 1) * 100
xlt_strength = (xlt_close / ta.sma(xlt_close, 50) - 1) * 100
xle_strength = (xle_close / ta.sma(xle_close, 50) - 1) * 100
// Find strongest sector
strongest_sector = xlf_strength > xlt_strength and xlf_strength > xle_strength ? "Financial" :
xlt_strength > xle_strength ? "Technology" : "Energy"
// ===== CRYPTOCURRENCY DATA INTEGRATION =====
// Get crypto data (when analyzing crypto or for correlation)
btc_symbol = "BTCUSD"
eth_symbol = "ETHUSD"
btc_close = request.security(btc_symbol, timeframe.period, close)
eth_close = request.security(eth_symbol, timeframe.period, close)
// Calculate crypto fear & greed index (simplified simulation)
btc_volatility = ta.stdev(ta.change(btc_close), 14)
btc_rsi = ta.rsi(btc_close, 14)
crypto_fear_greed = (100 - btc_rsi) * 0.7 + (btc_volatility / btc_close * 10000) * 0.3
fear_greed_level = crypto_fear_greed > 75 ? "Extreme Fear" :
crypto_fear_greed > 55 ? "Fear" :
crypto_fear_greed > 45 ? "Neutral" :
crypto_fear_greed > 25 ? "Greed" : "Extreme Greed"
// ===== CURRENCY AND COMMODITIES DATA =====
// Get major currency and commodity data
dxy_symbol = "DXY" // Dollar Index
gold_symbol = "GOLD" // Gold
oil_symbol = "USOIL" // Oil
eur_symbol = "EURUSD" // EUR/USD
dxy_close = request.security(dxy_symbol, timeframe.period, close)
gold_close = request.security(gold_symbol, timeframe.period, close)
oil_close = request.security(oil_symbol, timeframe.period, close)
eur_close = request.security(eur_symbol, timeframe.period, close)
// Calculate currency/commodity trends
dxy_trend = ta.sma(dxy_close, 20) > ta.sma(dxy_close, 50) ? "Strong USD" : "Weak USD"
gold_trend = gold_close > ta.sma(gold_close, 50) ? "Gold Up" : "Gold Down"
oil_trend = oil_close > ta.sma(oil_close, 20) ? "Oil Up" : "Oil Down"
// ===== VOLATILITY DATA =====
// VIX and other volatility indices
vix_close_detailed = request.security("VIX", timeframe.period, close)
vvix_close = request.security("VVIX", timeframe.period, close) // VIX of VIX
// Volatility regime classification
vol_regime = vix_close_detailed < 15 ? "Low Vol" :
vix_close_detailed < 25 ? "Normal Vol" :
vix_close_detailed < 35 ? "High Vol" : "Crisis Vol"
vol_trend = vix_close_detailed > ta.sma(vix_close_detailed, 10) ? "Rising" : "Falling"
// ===== BOND MARKET DATA =====
// Treasury yields
ten_year_symbol = "US10Y"
two_year_symbol = "US02Y"
thirty_year_symbol = "US30Y"
ten_year_yield = request.security(ten_year_symbol, timeframe.period, close)
two_year_yield = request.security(two_year_symbol, timeframe.period, close)
thirty_year_yield = request.security(thirty_year_symbol, timeframe.period, close)
// Yield curve analysis
yield_curve_slope = ten_year_yield - two_year_yield
curve_steepness = thirty_year_yield - two_year_yield
yield_curve_shape = yield_curve_slope < -0.5 ? "Inverted" :
yield_curve_slope < 0.5 ? "Flat" :
yield_curve_slope < 2.0 ? "Normal" : "Steep"
// ===== COMPREHENSIVE MARKET DATA TABLE =====
var table market_table = table.new(position.bottom_right, 3, 12, bgcolor=color.white, border_width=1)
if barstate.islast
// Headers
table.cell(market_table, 0, 0, "Market Data", text_color=color.white, bgcolor=color.navy)
table.cell(market_table, 1, 0, "Value", text_color=color.white, bgcolor=color.navy)
table.cell(market_table, 2, 0, "Status", text_color=color.white, bgcolor=color.navy)
// VIX
table.cell(market_table, 0, 1, "VIX", text_color=color.black)
table.cell(market_table, 1, 1, str.tostring(vix_close_detailed, "#.#"), text_color=color.black)
table.cell(market_table, 2, 1, vol_regime,
text_color=vol_regime == "Low Vol" ? color.green :
vol_regime == "Crisis Vol" ? color.red : color.gray)
// DXY
table.cell(market_table, 0, 2, "DXY", text_color=color.black)
table.cell(market_table, 1, 2, str.tostring(dxy_close, "#.##"), text_color=color.black)
table.cell(market_table, 2, 2, dxy_trend,
text_color=dxy_trend == "Strong USD" ? color.green : color.red)
// Gold
table.cell(market_table, 0, 3, "Gold", text_color=color.black)
table.cell(market_table, 1, 3, str.tostring(gold_close, "#"), text_color=color.black)
table.cell(market_table, 2, 3, gold_trend,
text_color=gold_trend == "Gold Up" ? color.green : color.red)
// Oil
table.cell(market_table, 0, 4, "Oil", text_color=color.black)
table.cell(market_table, 1, 4, str.tostring(oil_close, "#.#"), text_color=color.black)
table.cell(market_table, 2, 4, oil_trend,
text_color=oil_trend == "Oil Up" ? color.green : color.red)
// 10Y Yield
table.cell(market_table, 0, 5, "10Y Yield", text_color=color.black)
table.cell(market_table, 1, 5, str.tostring(ten_year_yield, "#.##") + "%", text_color=color.black)
table.cell(market_table, 2, 5, yield_curve_shape,
text_color=yield_curve_shape == "Inverted" ? color.red : color.green)
// BTC
table.cell(market_table, 0, 6, "Bitcoin", text_color=color.black)
table.cell(market_table, 1, 6, str.tostring(btc_close, "#"), text_color=color.black)
table.cell(market_table, 2, 6, fear_greed_level,
text_color=str.contains(fear_greed_level, "Fear") ? color.red :
str.contains(fear_greed_level, "Greed") ? color.green : color.gray)
// Sector Leadership
table.cell(market_table, 0, 7, "Lead Sector", text_color=color.black)
table.cell(market_table, 1, 7, strongest_sector, text_color=color.blue)
table.cell(market_table, 2, 7, "Outperform", text_color=color.blue)
// Relative Performance
table.cell(market_table, 0, 8, "vs SPY", text_color=color.black)
table.cell(market_table, 1, 8, str.tostring(relative_performance, "+#.#") + "%",
text_color=relative_performance > 0 ? color.green : color.red)
table.cell(market_table, 2, 8, relative_performance > 0 ? "Outperform" : "Underperform",
text_color=relative_performance > 0 ? color.green : color.red)
// Market Breadth (simulated)
market_breadth = (spy_strength + xlf_strength + xlt_strength) / 3
breadth_status = market_breadth > 2 ? "Strong" :
market_breadth > -2 ? "Neutral" : "Weak"
table.cell(market_table, 0, 9, "Breadth", text_color=color.black)
table.cell(market_table, 1, 9, str.tostring(market_breadth, "#.#"), text_color=color.black)
table.cell(market_table, 2, 9, breadth_status,
text_color=breadth_status == "Strong" ? color.green :
breadth_status == "Weak" ? color.red : color.gray)
// Current Symbol Analysis
current_vs_sectors = (current_performance + spy_performance + xlf_strength) / 3
symbol_rank = current_vs_sectors > 5 ? "Leader" :
current_vs_sectors > -5 ? "Average" : "Laggard"
table.cell(market_table, 0, 10, syminfo.ticker + " Rank", text_color=color.black)
table.cell(market_table, 1, 10, symbol_rank,
text_color=symbol_rank == "Leader" ? color.green :
symbol_rank == "Laggard" ? color.red : color.gray)
table.cell(market_table, 2, 10, str.tostring(current_vs_sectors, "#.#") + "%", text_color=color.black)
// Market Session
session_info = hour >= 9 and hour < 16 ? "Market Open" : "After Hours"
table.cell(market_table, 0, 11, "Session", text_color=color.black)
table.cell(market_table, 1, 11, session_info,
text_color=session_info == "Market Open" ? color.green : color.gray)
table.cell(market_table, 2, 11, str.format("{0,time,HH:mm}", timenow), text_color=color.black)
// ===== CORRELATION ANALYSIS =====
// Calculate rolling correlations between symbols
correlation_length = 20
// Price change correlations
spy_returns = ta.change(spy_close) / spy_close[1]
current_returns = ta.change(close) / close[1]
vix_returns = ta.change(vix_close_detailed) / vix_close_detailed[1]
// Simple correlation calculation (Pearson)
calculateCorrelation(x, y, length) =>
x_mean = ta.sma(x, length)
y_mean = ta.sma(y, length)
numerator = ta.sma((x - x_mean) * (y - y_mean), length)
denominator = math.sqrt(ta.sma(math.pow(x - x_mean, 2), length) *
ta.sma(math.pow(y - y_mean, 2), length))
numerator / denominator
spy_correlation = calculateCorrelation(current_returns, spy_returns, correlation_length)
vix_correlation = calculateCorrelation(current_returns, vix_returns, correlation_length)
// Plot correlations
plot(spy_correlation, "SPY Correlation", color.blue, display=display.data_window)
plot(vix_correlation, "VIX Correlation", color.red, display=display.data_window)
// ===== ALERT INTEGRATION WITH EXTERNAL DATA =====
// Market condition alerts
risk_on = vix_close_detailed < 20 and dxy_close < ta.sma(dxy_close, 20) and
ten_year_yield < ta.sma(ten_year_yield, 10)
risk_off = vix_close_detailed > 25 and (yield_curve_slope < 0 or gold_close > ta.sma(gold_close, 20))
alertcondition(risk_on and not risk_on[1],
title="Risk-On Environment",
message="🟢 RISK-ON: VIX low, USD weak, yields falling - favorable for risk assets")
alertcondition(risk_off and not risk_off[1],
title="Risk-Off Environment",
message="🔴 RISK-OFF: VIX high, yield curve issues, safe haven bid - risk asset caution")
// Unusual market conditions
unusual_condition = math.abs(relative_performance) > 10 or
math.abs(spy_correlation) > 0.8 or
vix_close_detailed > 40
alertcondition(unusual_condition and not unusual_condition[1],
title="Unusual Market Condition",
message="⚠️ UNUSUAL: {{ticker}} showing extreme readings vs market benchmarks")
// ===== EXTERNAL API WEBHOOK SIMULATION =====
// Simulate webhook data structure for external integration
createWebhookPayload() =>
payload = '{"symbol":"' + syminfo.ticker +
'","price":' + str.tostring(close) +
',"vix":' + str.tostring(vix_close_detailed) +
',"spy_correlation":' + str.tostring(spy_correlation) +
',"relative_performance":' + str.tostring(relative_performance) +
',"vol_regime":"' + vol_regime +
'","sector_leader":"' + strongest_sector +
'","timestamp":"' + str.format("{0,time,yyyy-MM-dd HH:mm:ss}", timenow) + '"}'
payload
// Trigger webhook on significant events
webhook_trigger = ta.change(vol_regime) != 0 or math.abs(ta.change(relative_performance)) > 5
if webhook_trigger
webhook_data = createWebhookPayload()
// In practice, this would be sent to external webhook URL
// For display purposes, we'll show in a label
if barstate.islast
webhook_label = label.new(
x=bar_index, y=low - ta.atr(14),
text="Webhook: " + str.substring(webhook_data, 0, 50) + "...",
color=color.yellow, textcolor=color.black,
style=label.style_label_up, size=size.small
)
Show all 331 lines