PROTECTED SOURCE SCRIPT
BTC Arbitrage Detector

套利检测器 — 技术原理与 Webhook 实时监控指南
许可证:Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
作者:加密社
适用市场:加密货币(如 BTC/USDT)、外汇(如 EUR/USD)
一、核心目标
本指标旨在实时监测同一交易品种在多个交易所或经纪商之间的价格极差(Price Spread),并通过统计方法识别当前价差是否处于“异常”状态。当价差显著扩大时,可能意味着存在套利机会、流动性断裂或数据源异常,用户可据此采取相应操作。
二、关键技术原理
1. 多源数据聚合
指标通过 request.security() 函数并行请求多个交易所的实时价格与成交量数据。例如,当图表品种为 BTCUSD 且类型为 crypto 时,自动从以下 19 家交易所获取数据:
BITSTAMP, COINBASE, BINANCE, KRAKEN, OKX, BYBIT, KUCOIN, MEXC, BITGET...
对于外汇品种(如 EURUSD),则切换至 OANDA, PEPPERSTONE, IBKR, SAXO 等 13 家外汇经纪商。
注意:若某交易所不支持该品种(如 GEMINI 无 ETH/BTC),系统会自动忽略无效符号(ignore_invalid_symbol = true),确保脚本稳定运行。
2. 价差计算与滑动窗口
价差定义:在每个 K 线周期,取所有有效交易所的最新价格,计算其最大值与最小值之差(即 range())。
历史窗口:默认使用最近 1000 根 K 线的价差序列(可通过输入参数调整),构成动态参考分布。用户也可启用“完整数据集”以使用全部历史数据(需注意资源限制)。
3. 百分位分级机制
对当前价差在其历史分布中的位置进行百分位排名(percentrank),并按以下阈值划分等级:
异常(Unusual):> 98% 分位(默认)
高(High):> 75% 分位
典型(Typical):> 25% 分位
低(Low):≤ 25% 分位
该分级基于非参数统计,无需假设价差服从正态分布,适应性强。
4. 自适应平滑算法(AMA)
为减少噪声干扰,指标提供两种平滑选项:
固定 EMA:对原始价差序列应用指数移动平均(默认周期 9)
自适应移动平均(AMA):将当前价差的百分位排名作为“效率比率”(Efficiency Ratio),动态调整平滑系数。当价差突变(高百分位)时响应更快,平稳期则更平滑。
5. 交互式仪表盘
仪表盘展示每家交易所的:
最新价格 / 成交量
平均价格 / 成交量(基于用户设定的平均周期,默认 20)
可选显示与主图资产的绝对差值(如 Binance 价格比主图高 $ 120)
支持按任意列升序/降序排序,快速定位最高/最低报价源
三、如何利用 Webhook 实现异常价差实时告警
TradingView 的 Alert + Webhook 功能可将指标信号推送至外部服务(如 Telegram、Discord、自建服务器),实现 7×24 小时监控。
步骤 1:修改脚本,添加 Alert 条件
原脚本为纯指标(indicator),不支持 alertcondition()。需在脚本末尾添加以下代码:
Pine Script®
注意:{{plot0}} 和 {{plot1}} 会自动替换为第一个和第二个 plot() 的当前值(即 spreadPercentRank 和 currentSpread)。
步骤 2:在 TradingView 创建告警
打开图表,加载修改后的指标
点击指标名称 → “添加告警”(Add Alert)
触发条件选择 “异常价差触发”
在“操作”中选择 Webhook URL
填入你的 Webhook 地址(例如:your-server.com/arbitrage-alert)
勾选 “仅当条件首次为真时触发”(避免重复通知)
保存
Arbitrage Detector — Technical Principles and Webhook Real-Time Monitoring Guide
License: Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
Author: Crypto Community
Applicable Markets: Cryptocurrencies (e.g., BTC/USDT), Forex (e.g., EUR/USD)
1. Core Objective
This indicator is designed to monitor the price spread—the difference between the highest and lowest quoted prices—of the same trading instrument across multiple exchanges or brokers in real time. Using statistical methods, it evaluates whether the current spread falls into an "anomalous" regime. A significantly widened spread may signal potential arbitrage opportunities, liquidity fragmentation, or data feed anomalies, enabling users to take timely action.
2. Key Technical Principles
2.1 Multi-Source Data Aggregation
The script uses Pine Script’s request.security() function to fetch real-time price and volume data from multiple venues simultaneously. For example:
When the chart symbol is BTCUSD and its type is crypto, the script automatically pulls data from 19 major cryptocurrency exchanges:
BITSTAMP, COINBASE, BINANCE, KRAKEN, OKX, BYBIT, KUCOIN, MEXC, BITGET, GEMINI, CRYPTOCOM, WHITEBIT, BTSE, HTX, GATE, etc.
For forex pairs like EURUSD, it switches to 13 leading brokers:
OANDA, PEPPERSTONE, IBKR, SAXO, TICKMILL, FXCM, FOREX.COM, CAPITAL.COM, etc.
Note: If a venue does not support the symbol (e.g., GEMINI lacks ETH/BTC), the script safely skips it using ignore_invalid_symbol = true, ensuring robust execution.
2.2 Spread Calculation and Sliding Window
Spread Definition: At each confirmed bar, the script collects all valid latest prices and computes their range (max – min).
Historical Reference Window: By default, it maintains a rolling window of the last 1,000 spread values to form a dynamic empirical distribution. Users can adjust this length or enable “Full Dataset” mode to use all available historical data (subject to TradingView’s runtime limits).
2.3 Percentile-Based Classification
The current spread is ranked against its historical distribution using percentrank(). It is then classified into one of four tiers based on user-defined thresholds:
Unusual: >98th percentile (default)
High: >75th percentile
Typical: >25th percentile
Low: ≤25th percentile
This non-parametric approach makes no assumptions about the underlying distribution of spreads, offering strong adaptability across volatile and stable market regimes.
2.4 Adaptive Smoothing Algorithm (AMA)
To reduce noise while preserving responsiveness, two smoothing options are provided:
Fixed EMA: Applies a standard exponential moving average (default period: 9) to the raw spread series.
Adaptive Moving Average (AMA): Uses the current spread’s percentile rank as an “efficiency ratio” to dynamically adjust the smoothing factor. During sharp divergences (high percentile), the AMA reacts quickly; during calm periods, it becomes smoother.
2.5 Interactive Dashboard
The on-chart dashboard displays, for each venue:
Latest price and volume
Average price and volume (over a user-defined lookback period, default: 20 bars)
Optional absolute delta vs. the chart’s primary symbol (e.g., “Binance price is $ 120 higher than chart”)
Sortable columns (ascending/descending) by price or volume to instantly identify outliers
3. Setting Up Webhook Alerts for Real-Time Anomaly Notifications
TradingView’s Alert + Webhook system allows you to push signals to external services (e.g., Telegram, Discord, or a custom server) for 24/7 monitoring.
Step 1: Modify the Script to Add Alert Conditions
Since the original script is declared as an indicator(), it cannot trigger alerts by default. Append the following code at the end of the script (after the calc_bars_count line):
pinescript
编辑
// Add at the very end of the script
var float spreadPercentRank = na
spreadPercentRank := spreads.percentrank(spreads.size() - 1)
// Define alert condition: spread exceeds "Unusual" threshold
bool unusualCondition = spreadPercentRank > unusualPercentilInput
// Create alert condition with dynamic message
alertcondition(unusualCondition, title="Unusual Spread Detected",
message="【{{ticker}}】Unusual cross-exchange spread detected! Percentile: {{plot0}}%, Spread: {{plot1}}")
Note: {{plot0}} and {{plot1}} will be replaced at runtime with the values of the first and second plot() calls in the script—corresponding to spreadPercentRank and currentSpread, respectively.
Step 2: Create an Alert in TradingView
Apply the modified indicator to your chart.
Click the indicator name in the legend → “Add Alert”.
Under Condition, select “Unusual Spread Detected”.
In the Actions section, choose “Webhook URL”.
Enter your webhook endpoint (e.g., your-server.com/arbitrage-alert).
Check “Once Per Bar” or “Once Per Condition” to avoid repeated notifications.
Save the alert.
许可证:Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
作者:加密社
适用市场:加密货币(如 BTC/USDT)、外汇(如 EUR/USD)
一、核心目标
本指标旨在实时监测同一交易品种在多个交易所或经纪商之间的价格极差(Price Spread),并通过统计方法识别当前价差是否处于“异常”状态。当价差显著扩大时,可能意味着存在套利机会、流动性断裂或数据源异常,用户可据此采取相应操作。
二、关键技术原理
1. 多源数据聚合
指标通过 request.security() 函数并行请求多个交易所的实时价格与成交量数据。例如,当图表品种为 BTCUSD 且类型为 crypto 时,自动从以下 19 家交易所获取数据:
BITSTAMP, COINBASE, BINANCE, KRAKEN, OKX, BYBIT, KUCOIN, MEXC, BITGET...
对于外汇品种(如 EURUSD),则切换至 OANDA, PEPPERSTONE, IBKR, SAXO 等 13 家外汇经纪商。
注意:若某交易所不支持该品种(如 GEMINI 无 ETH/BTC),系统会自动忽略无效符号(ignore_invalid_symbol = true),确保脚本稳定运行。
2. 价差计算与滑动窗口
价差定义:在每个 K 线周期,取所有有效交易所的最新价格,计算其最大值与最小值之差(即 range())。
历史窗口:默认使用最近 1000 根 K 线的价差序列(可通过输入参数调整),构成动态参考分布。用户也可启用“完整数据集”以使用全部历史数据(需注意资源限制)。
3. 百分位分级机制
对当前价差在其历史分布中的位置进行百分位排名(percentrank),并按以下阈值划分等级:
异常(Unusual):> 98% 分位(默认)
高(High):> 75% 分位
典型(Typical):> 25% 分位
低(Low):≤ 25% 分位
该分级基于非参数统计,无需假设价差服从正态分布,适应性强。
4. 自适应平滑算法(AMA)
为减少噪声干扰,指标提供两种平滑选项:
固定 EMA:对原始价差序列应用指数移动平均(默认周期 9)
自适应移动平均(AMA):将当前价差的百分位排名作为“效率比率”(Efficiency Ratio),动态调整平滑系数。当价差突变(高百分位)时响应更快,平稳期则更平滑。
5. 交互式仪表盘
仪表盘展示每家交易所的:
最新价格 / 成交量
平均价格 / 成交量(基于用户设定的平均周期,默认 20)
可选显示与主图资产的绝对差值(如 Binance 价格比主图高 $ 120)
支持按任意列升序/降序排序,快速定位最高/最低报价源
三、如何利用 Webhook 实现异常价差实时告警
TradingView 的 Alert + Webhook 功能可将指标信号推送至外部服务(如 Telegram、Discord、自建服务器),实现 7×24 小时监控。
步骤 1:修改脚本,添加 Alert 条件
原脚本为纯指标(indicator),不支持 alertcondition()。需在脚本末尾添加以下代码:
// 在脚本最后添加(calc_bars_count 行之后)
var float spreadPercentRank = na
spreadPercentRank := spreads.percentrank(spreads.size() - 1)
// 定义异常价差条件(例如 >98% 分位)
unusualCondition = spreadPercentRank > unusualPercentilInput
// 创建告警条件
alertcondition(unusualCondition, title="异常价差触发", message="【{{ticker}}】出现异常跨交易所价差!当前百分位:{{plot0}}%,价差:{{plot1}}")
注意:{{plot0}} 和 {{plot1}} 会自动替换为第一个和第二个 plot() 的当前值(即 spreadPercentRank 和 currentSpread)。
步骤 2:在 TradingView 创建告警
打开图表,加载修改后的指标
点击指标名称 → “添加告警”(Add Alert)
触发条件选择 “异常价差触发”
在“操作”中选择 Webhook URL
填入你的 Webhook 地址(例如:your-server.com/arbitrage-alert)
勾选 “仅当条件首次为真时触发”(避免重复通知)
保存
Arbitrage Detector — Technical Principles and Webhook Real-Time Monitoring Guide
License: Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)
Author: Crypto Community
Applicable Markets: Cryptocurrencies (e.g., BTC/USDT), Forex (e.g., EUR/USD)
1. Core Objective
This indicator is designed to monitor the price spread—the difference between the highest and lowest quoted prices—of the same trading instrument across multiple exchanges or brokers in real time. Using statistical methods, it evaluates whether the current spread falls into an "anomalous" regime. A significantly widened spread may signal potential arbitrage opportunities, liquidity fragmentation, or data feed anomalies, enabling users to take timely action.
2. Key Technical Principles
2.1 Multi-Source Data Aggregation
The script uses Pine Script’s request.security() function to fetch real-time price and volume data from multiple venues simultaneously. For example:
When the chart symbol is BTCUSD and its type is crypto, the script automatically pulls data from 19 major cryptocurrency exchanges:
BITSTAMP, COINBASE, BINANCE, KRAKEN, OKX, BYBIT, KUCOIN, MEXC, BITGET, GEMINI, CRYPTOCOM, WHITEBIT, BTSE, HTX, GATE, etc.
For forex pairs like EURUSD, it switches to 13 leading brokers:
OANDA, PEPPERSTONE, IBKR, SAXO, TICKMILL, FXCM, FOREX.COM, CAPITAL.COM, etc.
Note: If a venue does not support the symbol (e.g., GEMINI lacks ETH/BTC), the script safely skips it using ignore_invalid_symbol = true, ensuring robust execution.
2.2 Spread Calculation and Sliding Window
Spread Definition: At each confirmed bar, the script collects all valid latest prices and computes their range (max – min).
Historical Reference Window: By default, it maintains a rolling window of the last 1,000 spread values to form a dynamic empirical distribution. Users can adjust this length or enable “Full Dataset” mode to use all available historical data (subject to TradingView’s runtime limits).
2.3 Percentile-Based Classification
The current spread is ranked against its historical distribution using percentrank(). It is then classified into one of four tiers based on user-defined thresholds:
Unusual: >98th percentile (default)
High: >75th percentile
Typical: >25th percentile
Low: ≤25th percentile
This non-parametric approach makes no assumptions about the underlying distribution of spreads, offering strong adaptability across volatile and stable market regimes.
2.4 Adaptive Smoothing Algorithm (AMA)
To reduce noise while preserving responsiveness, two smoothing options are provided:
Fixed EMA: Applies a standard exponential moving average (default period: 9) to the raw spread series.
Adaptive Moving Average (AMA): Uses the current spread’s percentile rank as an “efficiency ratio” to dynamically adjust the smoothing factor. During sharp divergences (high percentile), the AMA reacts quickly; during calm periods, it becomes smoother.
2.5 Interactive Dashboard
The on-chart dashboard displays, for each venue:
Latest price and volume
Average price and volume (over a user-defined lookback period, default: 20 bars)
Optional absolute delta vs. the chart’s primary symbol (e.g., “Binance price is $ 120 higher than chart”)
Sortable columns (ascending/descending) by price or volume to instantly identify outliers
3. Setting Up Webhook Alerts for Real-Time Anomaly Notifications
TradingView’s Alert + Webhook system allows you to push signals to external services (e.g., Telegram, Discord, or a custom server) for 24/7 monitoring.
Step 1: Modify the Script to Add Alert Conditions
Since the original script is declared as an indicator(), it cannot trigger alerts by default. Append the following code at the end of the script (after the calc_bars_count line):
pinescript
编辑
// Add at the very end of the script
var float spreadPercentRank = na
spreadPercentRank := spreads.percentrank(spreads.size() - 1)
// Define alert condition: spread exceeds "Unusual" threshold
bool unusualCondition = spreadPercentRank > unusualPercentilInput
// Create alert condition with dynamic message
alertcondition(unusualCondition, title="Unusual Spread Detected",
message="【{{ticker}}】Unusual cross-exchange spread detected! Percentile: {{plot0}}%, Spread: {{plot1}}")
Note: {{plot0}} and {{plot1}} will be replaced at runtime with the values of the first and second plot() calls in the script—corresponding to spreadPercentRank and currentSpread, respectively.
Step 2: Create an Alert in TradingView
Apply the modified indicator to your chart.
Click the indicator name in the legend → “Add Alert”.
Under Condition, select “Unusual Spread Detected”.
In the Actions section, choose “Webhook URL”.
Enter your webhook endpoint (e.g., your-server.com/arbitrage-alert).
Check “Once Per Bar” or “Once Per Condition” to avoid repeated notifications.
Save the alert.
Mã được bảo vệ
Tập lệnh này được đăng dưới dạng mã nguồn đóng. Tuy nhiên, bạn có thể sử dụng tự do và không giới hạn – tìm hiểu thêm tại đây.
Thông báo miễn trừ trách nhiệm
Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.
Mã được bảo vệ
Tập lệnh này được đăng dưới dạng mã nguồn đóng. Tuy nhiên, bạn có thể sử dụng tự do và không giới hạn – tìm hiểu thêm tại đây.
Thông báo miễn trừ trách nhiệm
Thông tin và các ấn phẩm này không nhằm mục đích, và không cấu thành, lời khuyên hoặc khuyến nghị về tài chính, đầu tư, giao dịch hay các loại khác do TradingView cung cấp hoặc xác nhận. Đọc thêm tại Điều khoản Sử dụng.