Trend Following Regression Cloud

UnknownUnicorn13336802 · study · 50 行 · 点赞 261 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

//@version=5
indicator("Trend Following Regression Cloud", overlay=true)
 
// Function to calculate the slope of linear regression
calcSlope(source, length) =>
    sumX = 0.0
    sumY = 0.0
    sumXSqr = 0.0
    sumXY = 0.0
    for i = 0 to length - 1
        val = source[length - 1 - i]
        per = i + 1.0
        sumX += per
        sumY += val
        sumXSqr += per * per
        sumXY += val * per
    slope = (length * sumXY - sumX * sumY) / (length * sumXSqr - sumX * sumX)
    slope
 
// Define lengths
lengths = array.from(10, 20, 50, 100, 200, 300, 400, 500)
 
// Calculate slopes for each length
slopes = array.new_float()
for len in lengths
    slope = calcSlope(close, len)
    array.push(slopes, slope)
 
// Compute differences by subtracting the larger length slope from the smaller one
differences = array.new_float()
for i = 0 to array.size(slopes) - 2
    diff = (array.get(slopes, i) - array.get(slopes, i + 1))*array.get(lengths,i)
    array.push(differences, diff)
 
// Sum up the differences
totalDistance = array.sum(differences)
 
// Plotting
// Base line (you can choose any moving average or indicator as the base)
baseLine = ta.sma(close, 100)
 
// Cloud line based on totalDistance
multiplier = 0.1  // Adjust the multiplier as needed for better visualization
cloudLine = baseLine + totalDistance * multiplier
 
// Plot the baseLine and cloudLine
p1 = plot(baseLine, color=color.gray, linewidth=1, title="Base Line")
p2 = plot(cloudLine, color=color.gray, linewidth=1, title="Cloud Line")
fill(p1, p2, color=totalDistance > 0 ? color.green : color.red, title="Slope Difference Cloud")
alertcondition(ta.cross(totalDistance,0),'trend change')

← 返回列表