市场资讯及洞察
%20(1).jpg)
在上一篇文章中,我们已经系统介绍了 Pine Script 中的 for loop,并通过实例说明了它在固定次数遍历、区间计算等场景下的常见用法。不过,在实际策略和指标开发中,并不是所有问题都能提前确定循环次数。有些逻辑需要在“条件满足之前不断执行”,这时 while loop 就显得尤为重要。
while loop 是 Pine Script 中另一种核心循环结构,它基于条件判断来决定是否继续执行代码,而不是依赖预先设定的次数。这使它在动态计算、逐步逼近目标值、状态驱动型逻辑等场景中具有更高的灵活性。当然,也正因为这种灵活性,while loop 在使用时需要格外注意边界条件,否则可能导致脚本超时或编译错误。
本文将在 for loop 的基础上,详细介绍 Pine Script 中 while loop 的语法结构、执行机制及其与 for loop 的关键区别,并结合实际示例,帮助你理解在什么情况下应该选择 while loop,以及如何安全、高效地使用它。
while 循环语句用于创建一个由条件控制的循环,它通过一个条件表达式来控制其本地代码块的执行。只要指定的条件保持为真,循环就会持续迭代。
Pine Script 使用以下语法来定义一个 while 循环:
[variables = | :=] while condition
statements | continue | break
return_expression
其中,循环头部中的 condition 可以是字面量、变量、表达式,或返回 bool(布尔) 值的函数调用。
while 循环的头部会在每一次迭代之前对条件进行求值。因此,当脚本在某次迭代中修改了该条件时,循环头部会在下一次迭代时反映这些变化。
根据循环头部中指定的条件,while 循环的行为可以与 for 循环类似,例如持续迭代直到某个计数变量达到指定的上限。
由于 while 循环 的执行依赖于其条件始终为真,而该条件在某一次特定迭代中可能不会发生变化,因此在循环开始之前,预期的迭代次数往往是无法准确确定的。因此,while 循环通常在无法事先确定精确循环边界的场景中非常有用。
下面的脚本用于跟踪当图表的收盘价突破用户指定长度和通道宽度的 Keltner 通道时的情况。当价格突破当前 K 线的通道范围时,脚本会绘制一个方框,用来高亮显示此前所有连续收盘价仍位于该价格区间内的 K 线。该脚本使用 while 循环来分析历史 K 线的价格,并逐步调整每一个新方框的左边界,直到绘制的区域覆盖当前区间内最新的一组连续 K 线。

下面逐行解析代码:
1. 指定脚本版本。
2. 定义一个指标脚本,指标名称为while loop, 简短名称为window,第三个参数 true:表示指标绘制在主图(价格图)上。
3. 创建一个整数输入参数。默认值:20,名称:Channel length,允许范围:1 到 4999。用于后续计算 EMA 和 ATR 的周期长度。
4. 创建一个浮点数输入参数。默认值:2.0,最小值:0。用于控制通道宽度(ATR 的倍数)。
5. 使用 ta.ema() 计算指数移动平均线。输入价格:close(收盘价),周期:lengthInput,结果存入变量 ma。
6. 计算 ATR 并乘以倍数:ta.atr(lengthInput) 计算 平均真实波幅(ATR)。再乘以用户设定的宽度倍数。用于构建价格通道的上下边界。
7. 计算通道下轨:通道下轨 = EMA − ATR × 倍数。
8. 计算通道上轨。
9. 判断价格是否突破通道:当满足以下任一条件时为 true:收盘价低于通道下轨或收盘价高于通道上轨。
10. 检测“首次突破”:当前 K 线价格在通道外,上一根 K 线价格不在通道外。这表示:刚刚发生突破(避免重复画框)。
11. 创建价格窗口 Box:创建一个新的 box 对象:
左边界:bar_index
右边界:bar_index(初始宽度为 0)
上边界:channelHigh
下边界:channelLow
border_width = 2:边框宽度
bgcolor:半透明灰色背景
这个方框将用来标记“价格在通道内的历史区间”。
12. 初始化计数器:定义一个整数变量 i,用于回溯历史 K 线(close[i] 表示第 i 根之前的收盘价)。
13. while 循环:向左扩展方框:只要 第 i 根之前的收盘价仍在当前通道范围内:
close[i] >= channelLow
close[i] <= channelHigh
循环继续执行。
14. 调整方框左边界:将方框的左边界向左移动到:当前 K 线索引 – i,实现“逐根向左扩展方框”。
15. 增加回溯步数:每次循环 i 加 1
16. 绘制通道下轨。
17. 在图表上绘制通道上轨线。
K线上结果呈现如下:

本文通过一个完整的 Pine Script 示例,系统地讲解了 while 循环在 TradingView 指标中的实际应用。脚本以 EMA 与 ATR 构建 Keltner 通道为基础,当价格首次突破通道时创建一个价格窗口方框,并利用 while 循环向左逐根回溯历史 K 线,只要收盘价仍处于当前通道范围内,就不断扩展方框的左边界。相比 for 循环,while 循环不依赖预先确定的迭代次数,更适合用于回溯区间长度不确定的场景。通过这一示例,可以清楚地看到 while 循环在处理“连续条件判断”和“动态边界”问题时的优势,有助于读者在编写更灵活、逻辑更清晰的 Pine Script 脚本时,合理选择和运用循环结构。

Trading terms glossary A - B - C - D - E - F - G - H - I - J - K - L - M - N - O - P - Q - R - S - T - U - V - W - X - Y - Z - W West Texas Intermediate (WTI) West Texas Intermediate (WTI, also referred to as Texas Light Sweet) is an oil benchmark that is central to oil commodity trading. It is one of the three major oil benchmarks used in trading, along with Brent crude and Dubai/Oman. Working Order A Working Order typically refers to either a stop or limit order to open.
Working Orders are used to advise your broker to execute a trade when your desired tradable asset reaches a specified price. Learn more about Working Orders

Trading terms glossary A - B - C - D - E - F - G - H - I - J - K - L - M - N - O - P - Q - R - S - T - U - V - W - X - Y - Z - V Variable costs Variable cost refers to an expense which is subject to change when a products sales volumes change. Costs will typically increase or decrease when sales drop or rise, respectively. VIX Short for the Chicago Board Options Exchange Volatility Index, the VIX is used to track S&P 500 index volatility.
It is arguably the most well-known volatility index on the market. Learn more about VIX Volatility A market’s volatility is its likelihood of making major, short-term price movements at any time. A high level of volatility can provide opportunity to make profitable trades in a short period of time.
Learn more about Volatility Volume Volume in trading refers to the amount of a particular asset being traded over a certain period of time. It's typically presented alongside price information and offers an extra dimension when examining the price history of an asset. Learn more about using Volume in trading.
Volume-weighted average price VWAP is a technical analysis tool which shows the ratio of an asset's price to its total trade volume. the VWAP provides traders with a measure of the average price a stock has traded at over a given period of time.

Trading terms glossary A - B - C - D - E - F - G - H - I - J - K - L - M - N - O - P - Q - R - S - T - U - V - W - X - Y - Z - U Unborrowable stock The stock that no one is willing to lend out to short sellers is known as an Unborrowable stock. The traditional means of short selling is impossible, when shares in a company are unborrowable.

Trading terms glossary A - B - C - D - E - F - G - H - I - J - K - L - M - N - O - P - Q - R - S - T - U - V - W - X - Y - Z - T Take profit (TP) Learn more about Trading with a Profit Target (Take Profit) Strategy. Tangible assets Tangible assets are a companies physical assets, such as real estate holdings, machinery, manufacturing or computer equipment, and raw materials of value, e.g. timber, ore, etc. Technical analysis Technical analysis is the examination and prediction of price movements in a financial market.
Analysts aim to form accurate predictions of future price movements using information such as historical data, market statistics, trader sentiments and current events impacting a given market. Tom-next Short for ‘tomorrow-next day’, Tom-next is the process of rolling a Forex position from one spot day to the next. This is also sometimes referred to as "the cost of carry" or "financing adjustment".
Trading floor Also referred to as a "trading pit", the trading floor is the area in an exchange where assets are traded. This is most commonly associated with stock and futures exchanges. Trading journal Learn more about using a Trading Journal.
Trading plan A strategy used by individual traders to evaluate assets, risk management and types of tradings. A trading plan will typically be composed of the expected term of trading, and how to accomplish the traders objectives in that time frame. Learn more about Trading Plan Trailing stop A trailing stop is modified type of stop-loss order that automatically follows positive market movements of traders asset.
If the traders position moves positively but then reverses, a trailing stop will lock in the current profit and close the traders position. Learn more about using a Trailing Stop strategy. Treasury stock Treasury stocks are a portion of a company’s shares that it keeps in its own treasury.
These shares do not pay dividends - because a company can't pay itself - and do not count towards the number of shares listed. Trend A sustained upward or downward movement of a particular market or asset. Identifying the beginning of a trend as the time to purchase/open a position, and forecasting the end of trends as the time to sell/close a position, is a key part of market analysis.
Trending shares A company's stock is considered a "trending share" when it moves significantly in comparison to its underlying index; the trend can be up or down, and can represent significant gain or loss.

Trading terms glossary A - B - C - D - E - F - G - H - I - J - K - L - M - N - O - P - Q - R - S - T - U - V - W - X - Y - Z - S Scalp "Scalping" is the process of opening and closing a position very quickly, with the goal of profiting from small price movements. SEC The SEC is the US Securities and Exchange Commission. It is the government agency which regulates markets United States to protect investors.
It also oversees mergers and acquisitions of companies. Sectors A sectors is a division within an economy or market, used for analysing and comparing companies with activities and interests. Share buyback A share buyback is when a company buys back its own shares back from private investors.
Once shares are bought back by the company they are considered cancelled, but can be redistribution in the future. Share buybacks are sometimes done as a tax-efficient way to return money to shareholders. Learn more about Share Buybacks Share price The share or stock price is the amount it costs to buy a single share of a company.
This price is determined by the market and fluctuates. Share prices typically increase when a company is regarded as having a promising future, or when it reports better than expected earnings, and will fall when reporting missed expectations. Share prices may also fall following news or events expected to impact the company negatively.
Shares (stocks, cash equities) A shares is a unit of ownership in a company, usually traded on the stock market. They are also referred to as cash equities or stocks. Short Short describes a trade that will incur profit if the asset being traded decreases in price.
This is also referred to as going short, shorting or short-selling. Learn more about Short Trading Short squeeze When an asset starts to move up in price, this can cause traders holding short positions to rush to cover their positions and minimize potential losses. Learn more about Short Squeeze Short-selling The act of selling an asset that you do not currently own.
The hope of short-selling is that the asset will decrease in value, at which point the trader can close their trade for a profit. In contrast to this, if a shorted asset rises in value, closing the position results in a loss for the trader. Slippage Slippage is when the price an order is executes at does not match the price at which it was made.
Smart order router (Smart order routing) Smart order routing is an automated online trading process that looks for trading liquidity, and is used as an indicator in certain trading strategies. SNB Abbreviation for the Swiss National Bank, the central bank for Switzerland. Spot Price The spot price refers to the price of an asset at any given time, available for immediate purchase/delivery at that moment.
Spread Spread refers to the difference in price between the bid(buy) and offer(sell) price for a tradable asset. Stock exchange A stock exchange is a centralised location where a publicly traded companies shares are traded. Stock exchanges tradable assets are limited to stocks, bonds and exchange traded products.
There are many major stock exchanges operating in different countries, e.g. the New York Stock Exchange and Nasdaq in the United States, the Japan Exchange Group, Honk Kong Stock Exchange, London Stock Exchange, Swiss Exchange, and more. Stock index A stock index is a group of shares used to paint a general picture of a particular sector, exchange or economy. Stock indexes are typically made from a certain number of the top shares from a given exchange, e.g. the ASX200 is based on the 200 largest stocks listed on the Australian Stock Exchange.
Stock symbol A stock symbol is an abbreviation used to identify the shares of a publicly traded companies. e.g. the stock symbol of Apple Inc. on the Nasdaq is NASDAQ:AAPL. Stop Loss Order A stop loss is a limit order which triggers a trade at a predetermined price. Stop loss orders are useful for closing positions in response to a sudden unfavorable market movement, e.g. in the event the value of an asset suddenly crashes, a stop loss order can automatically sell the asset when it reaches a specified price to limit losses, rather than continuing to hold the asset while it continues to fall in value.
Strike Price The strike price is the agreed price for an underlying asset, this price forms the basis of an options contract. Support level Support level refers to a price price which a given asset may have difficulty falling below, due to a majority of traders looking to buy around this price. Swaps Learn more about Swaps.

Trading terms glossary A - B - C - D - E - F - G - H - I - J - K - L - M - N - O - P - Q - R - S - T - U - V - W - X - Y - Z - R Rally A rally refers to the price of an asset undergoing sustained upward momentum over a period of time. Range Range is the difference between a market’s lowest and highest point over a specified period of time. If a market has a wide range during a given period this is an indication of high volatility, and may be utilized in certain trading strategies.
Rate-of-return ROR, Rate-of-return, is the profit or loss of an investment over a given period. ROR is expressed as a percentage, with a positive ROR reflecting that an investment has returned a profit, while a negative ROR means a loss. Ratio spread Ratio spread options trading strategy where a trader will hold an unequal number of buy and sell positions on a single underlying asset at the same time.
Reserves Reserves are the liquid assets set aside for future use by a trader. Reserves can be held in the form of commodities, such as gold, but usually traders will keep cash as it is more immediately accessible. Resistance level Resistance level is the price at which an assets upward price trajectory is hindered by an overwhelming demand to sell the asset.
When an asset appears to be nearing a resistance level, traders may close their position in order to take profit, rather than risk the price falling to a lower price. Reversal (Trend reversal) A reversal is a change of direction in the price movement of an asset, e.g. when an upward trend becomes a downward trend, or vice versa. Rights issue When a company offers existing shareholders the opportunity to buy additional shares for a discounted price, this is referred to as a Rights issue.
The discounted price will usually only be available for a brief period, before returning to the normal price. Learn more about Rights issues Risk management Risk management refers to a variety of processes or strategies, the ultimate goal of which is to identify the potential risk of investments and mitigate potential losses. Risks In trading, "risk" refers to any potential event or circumstance in which and investment can lose money.
Regulatory News Service (UK) The RNS is responsible for disseminating information on behalf of UK publicly listed companies. The RNS operates as part of the London Stock Exchange (LSE) and provides companies with information to help them to meet their regulatory disclosure obligations. ROCE (Return on capital employed) ROCE refers to a long-term profitability ratio which measures how effectively capital is used by a company, e.g. profit generated for each each dollar used.
Rollover A rollover refers to keeping a position open beyond its expiry date. Relative Strength Index (RSI) RSI is a tool used in technical analysis to gauge whether an asset is potentially overbought or oversold, and to predict if a rally or correction may be imminent. Learn more about RSI.