External Integration 🌐
Working with External Data
Request Module
//@version=5
indicator("External Data")
// Request data from another symbol
btcData = request.security("BTCUSD", timeframe.period, close)
ethData = request.security("ETHUSD", timeframe.period, close)
// Calculate correlation
correlation = ta.correlation(btcData, ethData, 14)
plot(correlation, "BTC-ETH Correlation")
Multi-Timeframe Analysis
//@version=5
indicator("Multi-Timeframe")
// Get data from multiple timeframes
daily = request.security(syminfo.tickerid, "D", close)
weekly = request.security(syminfo.tickerid, "W", close)
monthly = request.security(syminfo.tickerid, "M", close)
// Create relative strength indicator
dailyChange = daily / daily[1]
weeklyChange = weekly / weekly[1]
monthlyChange = monthly / monthly[1]
Data Export
CSV Format Generation
//@version=5
indicator("Data Export")
// Format data for export
formatCSV() =>
timestamp = str.tostring(time)
price = str.tostring(close)
volume = str.tostring(volume)
timestamp + "," + price + "," + volume
// Create export string
var string[] exportData = array.new_string(0)
if barstate.islast
array.push(exportData, formatCSV())
Alert Integration
//@version=5
indicator("Alert Integration")
// Create structured alert message
alertMessage() =>
json = "{"
json += "\"symbol\":\"" + syminfo.ticker + "\","
json += "\"price\":" + str.tostring(close) + ","
json += "\"volume\":" + str.tostring(volume) + ","
json += "\"time\":\"" + str.tostring(time) + "\""
json += "}"
json
// Trigger alert with JSON data
if ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
alert(alertMessage(), alert.freq_once_per_bar)
External API Integration
Webhook Formatting
//@version=5
strategy("Webhook Integration")
// Create webhook payload
createWebhookPayload(action, price, quantity) =>
json = "{"
json += "\"action\":\"" + action + "\","
json += "\"symbol\":\"" + syminfo.ticker + "\","
json += "\"price\":" + str.tostring(price) + ","
json += "\"quantity\":" + str.tostring(quantity) + ","
json += "\"timestamp\":\"" + str.tostring(timenow) + "\""
json += "}"
json
// Send trade signals
if strategy.position_size != strategy.position_size[1]
alert(createWebhookPayload(
strategy.position_size > strategy.position_size[1] ? "BUY" : "SELL",
close,
math.abs(strategy.position_size - strategy.position_size[1])
))
Real-Time Integration
Broker Integration
//@version=5
strategy("Broker Integration", overlay=true)
// Define order parameters
var float defaultQuantity = 1.0
var float stopLossPercent = 2.0
var float takeProfitPercent = 4.0
// Create broker order
placeBrokerOrder(direction, entry) =>
stopPrice = direction == "long" ?
entry * (1 - stopLossPercent/100) :
entry * (1 + stopLossPercent/100)
targetPrice = direction == "long" ?
entry * (1 + takeProfitPercent/100) :
entry * (1 - takeProfitPercent/100)
json = "{"
json += "\"type\":\"LIMIT\","
json += "\"direction\":\"" + direction + "\","
json += "\"quantity\":" + str.tostring(defaultQuantity) + ","
json += "\"entry\":" + str.tostring(entry) + ","
json += "\"stop\":" + str.tostring(stopPrice) + ","
json += "\"target\":" + str.tostring(targetPrice) + ""
json += "}"
json
Data Synchronization
State Management
//@version=5
indicator("State Management")
// Track external state
var float[] externalPrices = array.new_float(0)
var string[] externalEvents = array.new_string(0)
// Synchronize with external data
syncExternalData() =>
if array.size(externalPrices) > 100
array.shift(externalPrices)
array.shift(externalEvents)
array.push(externalPrices, close)
array.push(externalEvents, barstate.isconfirmed ? "confirmed" : "pending")
Error Handling
Robust External Requests
//@version=5
indicator("Robust Integration")
// Handle external data requests
safeRequest(symbol, tf, field) =>
var float lastValue = na
value = request.security(symbol, tf, field)
if na(value)
// Use last known value or fallback
value := lastValue
else
lastValue := value
value
// Usage with error handling
try =>
btcPrice = safeRequest("BTCUSD", "D", close)
if na(btcPrice)
runtime.error("Failed to fetch BTC price")
btcPrice
catch =>
close // Fallback to current symbol
Performance Considerations
Optimizing External Calls
//@version=5
indicator("Optimized Integration")
// Cache external data
var float[] dataCache = array.new_float(0)
var int cacheSize = 100
var int updateInterval = 10
// Efficient data fetching
getExternalData() =>
shouldUpdate = bar_index % updateInterval == 0
if shouldUpdate
if array.size(dataCache) >= cacheSize
array.shift(dataCache)
array.push(dataCache, close)
array.get(dataCache, array.size(dataCache) - 1)
Integration Tips
- Use structured data formats (JSON)
- Implement robust error handling
- Cache external data when possible
- Rate limit external requests
- Validate external data
Common Issues
❌ Excessive API calls ❌ Missing error handlers ❌ Poor data synchronization ❌ Unhandled timeframe mismatches ❌ Webhook formatting errors
Next Steps
Ready to learn about performance optimization? Move on to the next chapter! 🚀