如何在PineScript中判断均线是否显示并控制对应标签隐藏?
Sync MA Labels with Plot Visibility in PineScript
Yes, you can check if your moving average plots are visible and sync your labels to hide/show alongside them using PineScript's plot.getvisibility() function. Here's how to fix your issue:
1. Store Plot References
When creating your MA plots, assign them to variables—these act as unique IDs you can use to check visibility later:
//@version=5 indicator("MA with Synced Labels", overlay=true) // Calculate MAs ma_50 = ta.sma(close, 50) ma_200 = ta.sma(close, 200) // Save plot references plot_ma_blue = plot(ma_50, color=color.blue, title="50-period MA") plot_ma_red = plot(ma_200, color=color.red, title="200-period MA")
2. Check Visibility and Draw Labels Conditionally
Use plot.getvisibility() to fetch the checkbox state from the settings window, then only render labels when the corresponding MA is visible:
// Get visibility state of each MA is_blue_ma_visible = plot.getvisibility(plot_ma_blue) is_red_ma_visible = plot.getvisibility(plot_ma_red) // Draw labels only if the MA is enabled if is_blue_ma_visible label.new(bar_index, ma_50, str.tostring(ma_50, "#.##"), color=color.blue, textcolor=color.white) if is_red_ma_visible label.new(bar_index, ma_200, str.tostring(ma_200, "#.##"), color=color.red, textcolor=color.white)
Key Notes:
plot.getvisibility()returnstrueif the plot is checked in the indicator settings,falseotherwise. This directly gives you the checkbox state of your red MA (or any plot you reference).- This functionality requires PineScript v5—older versions don't support this function.
- After implementing this, your labels will automatically hide/show when you toggle the MA plots in the configuration window.
内容的提问来源于stack exchange,提问作者xarc
相关产品推荐
相关产品推荐

