市场资讯及洞察
%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 脚本时,合理选择和运用循环结构。


Qantas Airways Limited (QAN:ASX) is the flagship carrier of Australia and the country's largest airline by fleet size. The company has had a resurgence in 2022 and the share price has rebounded from the lows of the pandemic. The “Flying Kangaroo” as it’s known throughout the industry, said that it would report an underlying pre-tax profit of up to A$1.3bn (US$815mn) in the six months to December, doubling market estimates, as strong demand for flights offsets higher fuel costs and inflation.
The improved financial performance has come from the company transferring the increased costs via increased fairs. The share price for the airline soared to $5.83, its highest level since November 2021, on the back of the strong profit forecast. Qantas’s pre-pandemic share price was sitting at $7.35 AUD and saw its financial performance suffer with 3 consecutive years of more than A$1bn losses because of pandemic restrictions and lost A$25bn of revenue during the period.
Net debt, which spiralled to almost A$6.5bn during the pandemic, is expected to fall to between A$3.2bn and A$3.4bn by the end of the year, well below the airline’s A$3.9bn target range. Alan Joyce, Chief Executive gave a promising statement on the company’s performance advising, “It’s been a really challenging time for the national carrier, but today’s announcement shows how far we’ve come. Since August, we’ve seen a big improvement in our operational performance and an acceleration in our financial performance.” The report in profits has come too late for investors to receive a final dividend this year, with the company deciding not to reverse its decision to halt dividend payments.
However, it’s not all doom and gloom for investors, as Alan Joyce has led a A$400mn share buyback this year. Share buybacks do not put cash in the hands of investors as a dividend does. However, they do support shareholders by reducing the overall share count.
This tends to boost the share price, given that under the laws of supply and demand, less supply leads to a rise in price. If you are interested in venturing into trading stocks, FX or commodities, you can create access to one of our MetaTrader 5 trading CFD platforms with GO Markets here or call our Melbourne based office on 03 8566 7680 to discuss your trading goals with our account managers and to get started. Sources: https://www.ft.com/, https://au.finance.yahoo.com/, https://www.fool.com.au/


Oracle Corporation reported its fiscal 2022 third quarter financial results after the closing bell on Wall Street today. The US software and hardware manufacturer reported revenue of $10.513 billion vs. $10.506 billion expected. Earnings per share at $1.13 per share, falling short of analyst estimate of $1.18 per share.
The company also announced a quarterly cash dividend of $0.32 per share of outstanding common stock "In Q3, Oracle delivered over 7% constant currency revenue growth—our highest quarterly organic revenue growth rate since we began our transition to the cloud," said Oracle CEO, Safra Catz following the latest results. "This strong top line growth was coupled with a solid non-GAAP constant currency operating profit growth of 4%, but the big story is that our overall revenue growth is being driven by both our rapidly growing Cloud Infrastructure and Cloud Applications businesses. Q3 Cloud Infrastructure revenue was up 47% in constant currency. Q3 Cloud Applications growth was led by Fusion ERP, which was up 35% in constant currency and NetSuite ERP which was up 29% in constant currency.
Total Cloud revenue which includes Cloud Infrastructure and Cloud Applications is now over $11 billion a year," Catz added. Oracle Corporation (ORCL) Shares of Oracle were little changed at the end of trading on Thursday, up by 0.84% at $76.70 a share. Here is how the stock has performed in the past year – 1 Month: -6.22% 3 Month: -13.53% Year-to-date: -11.98% 1 Year: +13.87% Oracle is the 49 th largest company in the world with total market cap of $204.85 billion.
You can trade Oracle Corporation (ORCL) and many other stocks from the NYSE, NASDAQ, HKEX and the ASX with GO Markets as a Share CFD. Trading Derivatives carries a high level of risk. Sources: Oracle Corporation, TradingView, MetaTrader 5, CompaniesMarketCap


Oil has continued its tumble from its March 2022 high of $131 per barrel down to $82 a barrel. The drop has been in response to weak economic figures from China and the USA which has added to the recessionary anxiety gripping the market. Furthermore, as Iran edges closer to a nuclear deal, the removal of economic sanctions on the country may be able to provide 2.5 million barrels a day to the global supply.
The drop has also coincided with a rebound in equities as the possibility that central banks may soften their aggressive interest-raising regime has entered the market. Further industry data released from the USA outlining their Crude stockpiles due later on Tuesday, may also impact the price in the short term. The recent drop has pushed the price of both Crude and WTI to 6-month lows not seen since before the Russia and Ukraine crises.
On the daily chart, both Brent and WTI are sitting on areas of support between $85-$93 and $83-$90 respectively. The price for both Brent and WTI has also dipped below the 200-day moving average indicating a medium-term bearish shift. The question remains, is this just a retracement, or a reversal of exhaustion?
Due to the prices being resting near their area of support and the RSI consolidating between 25-45, this does indicate a possible bounce. If the RSI can break above the recent consolidation/range or 45 and the general price of the commodity can bounce off its support, there may be the potential for buying opportunities. With any trade and especially those involving commodities, there are always external risks to consider that may invalidate the current trading strategy.
For instance, if inflation becomes less of an issue and central banks begin to taper their aggressiveness in fighting inflation, the price of oil may begin to slip. Therefore, this is a trade that can in which the utilisation of both technical and fundamental analysis can be done.


NIO Inc. (NIO) reported its latest delivery numbers for February on Tuesday. The Chinese electric vehicle company delivered 6,131 cars last month – an increase of 9.9% year-over-year. The deliveries in February consisted of: 1,084 ES8s – the company’s six-seater or seven-seater flagship premium smart electric SUV 3,309 ES6s – the company’s five-seater high-performance premium smart electric SUV 1,738 EC6s – the company’s five-seater premium smart electric coupe SUV NIO has delivered a total of 182,853 electric vehicles as of 28 th February, 2022.
NIO Inc. (NIO) Shares of NIO were down by 4.25% at the end of the trading day on Tuesday at $21.87 per share. Here is how the stock has performed in the past year – 1 Month: -11.96% 3 Month: -44.11% Year-to-date: -30.97% 1 Year: -49.48% NIO is the 15 th largest automaker in the world with a market cap of $34.78 billion. You can trade NIO Inc. (NIO) and many other stocks from the NYSE, NASDAQ, HKEX and the ASX with GO Markets as a Share CFD.
Sources: NIO Inc., CompaniesMarketCap


Moderna Inc. (MRNA) reported it latest financial numbers before the opening bell in the US on Thursday. The pharmaceutical company reported results that beat Wall Street estimates, sending the stock price higher on the day. Total revenue reported at $7.211 billion in the fourth quarter vs. $6.798 billion expected.
Earnings per share at $11.29 per share vs. estimate of $9.96 per share. Stéphane Bancel, CEO of Moderna commented on the last year’s performance following the latest results: "In 2021, we delivered 807 million doses with approximately 25% of those doses going to low- and middle-income countries, and we will continue to scale in 2022 to help end the COVID-19 pandemic. Moderna has experienced exponential growth and we have more than doubled the size of our team over the last year with a global team of 3,000.
We also have announced plans to scale to 21 commercial subsidiaries across the world, including four new locations in Asia and six new locations in Europe. We continue to expand and advance our industry-leading mRNA pipeline with 44 programs in development. We look forward to clinical readouts from our therapeutics development candidates later in 2022 in rare genetic diseases and oncology.
We are entering 2022 with a remarkable team and strategic priorities to continue advancing mRNA vaccines and therapeutics to impact human health." Moderna Inc. (MRNA) chart (Weekly) Share price of Moderna surged by over 10% during Thursday, trading at $147.53 per share. Here is how the stock has performed in the past year – 1 Month: +0.18% 3 Month: -45.54% Year-to-date: -41.38% 1 Year: +0.34% Moderna Inc. is the 274 th largest company in the world and 21 st largest pharmaceutical company with a total market cap of $59.54 billion. You can trade Moderna Inc. (MRNA) and many other stocks from the NYSE, NASDAQ, HKEX and the ASX with GO Markets as a Share CFD.
Sources: Moderna Inc., TradingView, MetaTrader 5, CompaniesMarketCap


Mastercard Incorporated (MA) reported its latest financial results before the opening bell on Wall Street on Thursday. The US financial services company reported revenue of $5.497 billion in Q2, beating analyst estimate of $5.267 billion. Earnings per share reported at $2.56 per share vs. $2.36 per share expected. ''We had strong revenue and earnings growth again this quarter, as overall consumer spending remained robust and cross-border volumes grew 58% versus year ago,'' Michael Miebach, CEO of Mastercard said in a press release following the results. ''Increasing inflationary pressures have yet to significantly impact overall consumer spending but we will continue to monitor this closely.
We have a well-diversified business model and the demonstrated ability to deliver strong operating margins through up and down cycles,'' Miebach concluded. Mastercard Incorporated (MA) chart Shares of MasterCard were trading higher on Thursday after beating Wall Street expectations, up by around 1% at $348.50 per share. Here is how the stock has performed in the past year: 1 Month +10.56% 3 Month -7.92% Year-to-date -2.92% 1 Year -10.29% Mastercard Incorporated price targets JP Morgan $425 Wells Fargo $400 Piper Sandler $298 Mizuho $375 Truist Securities $420 Barclays $430 BMO Capital $402 Morgan Stanley $452 Mastercard Incorporated is the 19 th largest company in the world with a market cap of $338.14 billion.
You can trade Mastercard Incorporated (MA) and many other stocks from the NYSE, NASDAQ, HKEX and the ASX with GO Markets as a Share CFD. Sources: Mastercard Incorporated, TradingView, MetaTrader 5, Benzinga, CompaniesMarketCap