如何让PineScript绘制的线段仅显示10根K线且不被新线段删除
PineScript Solution: Persistent 10-Bar Close Lines
Issues with Your Current Code
- Old Lines Get Deleted: You're reusing a single
line_objvariable and deleting it each time a new line is created, so only the most recent line remains. - Lines Extend Infinitely: The
extend=extend.rightparameter makes lines stretch to the right indefinitely.
Corrected Code
//@version=5 indicator("10-Bar Close Segments", overlay=true) // Initialize a persistent array to store all line objects var line[] lineCollection = array.new_line() // Create a new line every 10 bars (once we have enough historical data) if bar_index % 10 == 0 and bar_index >= 10 // Draw line between the close 10 bars ago and current close, no extension newLine = line.new( x1=bar_index - 10, y1=close[10], x2=bar_index, y2=close, color=color.red, width=2, extend=extend.none ) // Add the new line to our collection to keep it from being deleted array.push(lineCollection, newLine)
Key Fixes Explained
- Persistent Line Storage: Using a
vararray (lineCollection) ensures every new line is stored permanently—old lines aren't overwritten or deleted. - Limited Line Length: Setting
extend=extend.nonerestricts each line to exactly the 10-bar span betweenbar_index-10andbar_index. - Valid Data Check: The
bar_index >=10condition prevents trying to draw lines when there's no historical data forclose[10].
This code will draw a new red line every 10 bars, connecting the close of the current bar to the close 10 bars prior. All lines remain visible on the chart, each spanning exactly 10 bars with no infinite extension.
内容的提问来源于stack exchange,提问作者Foenkelito
相关产品推荐
相关产品推荐

