如何在TradingView的Pine Script中获取趋势线值并编写交叉算法?
Hey there! Great question—working with trend lines in Pine Script is definitely trickier than moving averages because trend lines are object-based rather than a continuous series of values like SMAs. Let's break this down step by step to solve your problem.
First, let's clarify why you can't use crossover(close, lineInstance) directly:
- SMAs generate a value for every single bar, so they're a continuous series you can compare directly with price.
- Trend lines are drawing objects defined by two endpoints (x/y coordinates). They only have valid price values between those two bars—outside that range, they don't exist, and trying to get their value returns
na.
Pine Script gives you the line.get_price() function to pull the price of a trend line at a specific bar index. Here's a quick example of defining a trend line and fetching its value:
// Define a trend line connecting the last two swing lows var line swingLowTrend = na if ta.lowest(low, 15) == low[8] and ta.lowest(low, 8) == low swingLowTrend := line.new(bar_index[8], low[8], bar_index, low, color=color.green, width=2) // Get the trend line's price on the current bar currentLinePrice = na if not na(swingLowTrend) currentLinePrice := line.get_price(swingLowTrend, bar_index)
Note: If the trend line hasn't been created yet, or the current bar is outside the trend line's start/end bars, currentLinePrice will be na—always handle this in your logic.
To use crossover/crossunder like you do with SMAs, you need to convert the trend line's intermittent values into a continuous series. The easiest way is to store each bar's trend line price in an array, then convert that array to a series:
// Initialize an array to track trend line prices across all bars var linePriceArray = array.new_float() // Push the current bar's trend line price to the array array.push(linePriceArray, currentLinePrice) // Keep the array length matched to the number of bars (optional cleanup) if array.size(linePriceArray) > bar_index + 1 array.shift(linePriceArray) // Convert the array to a series we can use with ta.crossover() linePriceSeries = array.get(linePriceArray, bar_index) // Now we can use standard crossover logic! crossAbove = ta.crossover(close, linePriceSeries) crossBelow = ta.crossunder(close, linePriceSeries) // Plot signals for visibility plotshape(crossAbove, location=location.belowbar, color=color.green, style=shape.labelup, text="BUY") plotshape(crossBelow, location=location.abovebar, color=color.red, style=shape.labeldown, text="SELL")
Since we converted the trend line prices to a series (linePriceSeries), accessing historical values is as simple as using bracket notation, just like with price or SMAs:
// Check if the price crossed above the trend line from the previous bar customCross = close[1] < linePriceSeries[1] and close > linePriceSeries and not na(linePriceSeries) and not na(linePriceSeries[1])
For more complex logic (like dynamically updating trend lines as new highs/lows form), combine line.set_* functions to adjust the trend line's endpoints, then repeat the value-fetching process above. Here's an example of a dynamic uptrend line:
var line dynamicUpTrend = na // Update the trend line when a new swing high forms if ta.highest(high, 12) == high if na(dynamicUpTrend) // Find the most recent swing low to use as the start point prevLowBar = ta.barssince(ta.lowest(low, 20) == low) dynamicUpTrend := line.new(bar_index - prevLowBar, low[prevLowBar], bar_index, high, color=color.blue) else // Update the trend line's end point to the new high line.set_x2(dynamicUpTrend, bar_index) line.set_y2(dynamicUpTrend, high) // Fetch the updated trend line's price for each bar dynamicLinePrice = line.get_price(dynamicUpTrend, bar_index)
- Trend lines are drawing objects, not native series—you need to manually convert their values to a series to use crossover logic.
- Always handle
navalues, as trend lines won't have valid prices outside their defined bar range. - Use
varwhen defining trend line variables to avoid re-creating the object on every bar.
内容的提问来源于stack exchange,提问作者ー PupSoZeyDe ー

