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


The Kansas City Federal Reserve is set to host the 45 th Annual Symposium at Jackson Hole Lodge in Wyoming’s Grand Teton National Park. Some of the countries and world’s most important central bankers, economists, and academics will be meeting to discuss the biggest issues facing the global economy. The key issue on the agenda is of “Reassessing Constraints on the Economy and Policy.” All eyes will be on Jerome Powell, with the chairman of the Federal Reserve expected to speak on Thursday and provide an update on the proceedings of the conference.
At last year’s event Powell was caught out after stating that inflation was transitory, only to see it become a huge long-lasting issue. Therefore, he may try and correct this perception and portray a much more conservative attitude. There is also a view from some analysts that the Fed came across too dovish in the July meeting which led to the market rally.
At this stage the market has priced in a 75-bps increase at the September meeting, however this may change. With key inflation measures slowing somewhat, the question will be whether the fed continue its aggressive interest rate hikes or eases their policy to avoid a potential recession. The market will be hoping that Powell provides some clues for what the Fed plans to do after rates peak.
They will be hoping for clarity over whether the bank will hold the rates at the high levels for some time or lower them straight away to avoid a recession. Market participants should be weary that although Jackson Hole may provide some important context to the future rates, no official policies will be set. The conference will most likely have a relatively small impact on the market, it still has the potential to provide some volatility for both equities and currency if significant attitude shifts are expressed.
The USD is currently at 5 year highs and with some positive catalysts for the currency, it may continue to rise further if the Fed continues to be aggressive in its rate hikes.


JD.com Inc. (JD) announced its fourth-quarter earnings numbers on Thursday. The Chinese e-commerce company reported revenue of $43.422 billion (up by 23% year-over-year), slightly above Wall Street analysts forecast of $43.186 billion. Earnings per share reported at $0.35 per share vs. $0.28 per share expected. ''We are pleased to finish the year with a set of strong results on both the top and bottom lines as we continued to execute and deliver on our strategic priorities,'' said Sandy Xu, Chief Financial Officer of JD.com. ''During the quarter, we further optimized our operational efficiency through technology and innovation, increasing our competitiveness as well as our ability to support our business partners.
In 2022, we will continue to execute our business strategies and focus on sustainable high-quality growth across all of our business lines,'' Xu added. JD.com Inc. (JD) Share price of JD dropped following the latest financial results on Thursday, after the weakest revenue growth in six quarters. The stock was down by around 16% at $52.13 pe share.
Here is how the stock has performed in the past year – 1 Month: -31.40% 3 Month: -34.13% Year-to-date: -25.20% 1 Year: -41.77% JD.com Inc. is the 163 rd largest company in the world with total market cap of $85.95 billion. You can trade JD.com Inc. (JD) 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: JD.com, TradingView, MetaTrader 5, CompaniesMarketCap


The recent price action of the Bitcoin suggests that the leading cryptocurrency may be ready for another sell off. Since last November when the currency peaked it has seen a sharp decline with retracements along the way. With inflation and recessionary pressures prevalent short-term volatility remains high as the market determines how to price the asset.
The Jackson Hole symposium is set to begin on Thursday in the USA and may effect the price in the short term if bullish or bearish sentiment comes from the event. The Chart The long-term outlook for Bitcoin is bearish. With constant sell downs and both the 50 Day and 200 day moving average both firmly pushing towards the downside.
Furthermore, the price has not been able to sustain any significant rally and has broken through its major support at $30,000 USD. Recent Price Action The concern for BTC is that it has sold out of the channel that it had been consolidating in and has therefore rejected the upward move. Similarly, the price has followed this action, twice before with both resulting in sell offs.
These patterns appear as traps for bulls because, buyers begin to feel FOMO and then enter long only to be ‘fake out’ as sellers soak up the buying volume and then continue to push the price back down. The RSI also supports more selling as it currently sits at 38 whilst the prior sell offs reached below 20. The RSI also looks to have made a triple top as shown in the chart further indicating that sellers may be ready to drive the price down further.
The concern for buyers is that this current sell off may not be finished. The 5-hour pattern looks to be forming a bear flag/pennant. If the price can break below it may fall to the next support at $17,000/18,000 USD.
This pattern is to be expected and is just reflective of sellers taking a breath before they continue to push the price lower. The price has also fallen back below the 50-period moving average indicting short term bearish sentiment. If the short-term target of $ 17,000/18,000 USD cannot hold the next target is the $13,500 USD level.


Iron ore prices have continued to rally to a six-month high this week, due in part to reports of potential easing of China’s strict COVID-19 policy and their signs of improved steel demand. The Singapore Exchange has the iron ore futures price reaching $165 USD a tonne on Tuesday, this is the highest level since July 2021. The price increase could have been attributed to a report that concluded that Beijing was considering potentially moving away from a zero-tolerance approach to COVID-19.
If this occurs, it could potentially put an end to the stop-start nature of China’s economic activities which has been happening since the start of COVID-19 pandemic. Another report indicated that experimental opening measures could arrive in a few select cities across China as early as June, which will coincide with the beginning of their Summer. A potential sign that China’s stimulus is contributing to rebound in growth can be evident earlier this month with the release of China’s Manufacturing Purchasing Managers Index (PMI).
The PMI had increased to 50.2, which was greater than the economists’ consensus of 49.8. Some experts and economists believe that the PMI’s figures released next month of March will likely provide a better indication of the true state of China’s economy, given the effects of the Lunar New Year period in the first two months of the year. Iron ore supplies could also heavily affect its global price.
There are concerns about the supply disruptions caused by the conflict between Russia and Ukraine, given their iron ore sector accounts for 100 million tonnes and 81 million tonnes a year, respectively. Heavy rain in the south-east of Brazil earlier this year, linked to the La Nina weather pattern, has forced producers to cease operations. Brazil is the second largest iron ore producer behind Australia, producing almost 400 million tonnes compared to Australia’s 900 million tonnes.
The increase in price to iron ore and energy has driven the AUD/USD to reach a new four month high of 74.41 US cents. Commonwealth Bank (CBA) believes that the currency is currently on track to end the first quarter near 74 US cents. They have updated the fair value estimate of the Australian dollar following the release of the RBA’s commodity price index for February.
CBA’s fair value for the AUD/USD ranges between 78-90 US cents, centred on 84 US cents. All in all, the AUD/USD has a healthy positive correlation with the price of iron ore due Australia being the largest producer. Investors can research the supply and demand of iron ore to achieve a good potential indication of the strength of the AUD/USD.
If you would like to take this opportunity to trade on the AUD/USD and require a trading account, you can open a trading account with GO Markets. Source: GO Markets MT5, Tradingview, Tradingeconmics, Statista, WSJ, Science.org, AFR


Investors are currently bracing for further volatility in the global markets as Russia’s troops have been deployed into eastern Ukraine. The heightened tensions between Russia and Ukraine reached a tipping point last week when the Kremlin had officially recognised regions in eastern Ukraine held by separatists (supported by Russia). Russia ordered troops to enter Ukraine on a peacekeeping mission.
The western countries have responded promptly, with the UK and US among the first countries to reprimand Russian actions with their first round of restrictive economic sanctions. The US had unveiled various sanctions targeting Russia, this included limits on sovereign debt and Russia’s two biggest banks, Promsvyazbank and VEB, who both support the military. A statement from The White House described these measures as the “first tranche of swift and severe costs on Russia” and said the Treasury would “determine that any institution in the financial services sector of the Russian Federation economy is a target for further sanctions.” Australia also followed the US's lead and applied sanctions on Russia aimed at the country’s elites and commercial sector, including transport, energy companies and banks.
Investors had a major focus on Energy commodities given Russia’s strong supply of gas to Europe, especially at a time of strong demand and constrained output that has plagued the region for much of the past year. Here are some thoughts from Vivek Dhar, analyst covering energy commodities for CBA, and Shane Oliver, chief economist for AMP Capital. Mr.
Dhar describes the initial US sanctions as relatively tame given they target sovereign debt, which is low for the Russian economy. Instead, Germany’s decision to suspend the certification of the Nord Stream 2 pipeline poses a more serious response to the escalating situation, given it would have eased the region’s gas shortages. “The extent of Russia’s incursion will likely see sanctions escalate in turn. A full‑scale invasion of Ukraine certainly opens the door to sanctions on Russia’s oil and gas exports,” he added, which could push the price of oil beyond $US100 per barrel.
Mr. Oliver believes there was a risk Russia could itself cut off supply of gas to Europe, “with a potential flow-on to oil demand at a time when conflict may threaten supply”, adding to anticipated inflation. Investors are worried about a stagflationary shock to Europe and, to a lesser degree, the global economy.
All in all, the crisis between Russia and Ukraine is still ongoing and there will certainly be further actions taken by countries across the world. As investors' uncertainty slowly rises, the global markets will adjust with every major update. Keeping up to date with other countries’ sanctions and reaction to the invasion can be a rewarding task as opportunities can present themselves.
If you have spotted an opportunity to invest in the global markets and don’t already have a trading account, you can register for an account at GO Markets.


Gold has seen a resurgence in the past few weeks on the back of inflationary pressure and geopolitical tensions in Ukraine and Russia. Prior to the conflict, the price of Gold was hovering around $1,800 USD per ounce. After pushing through $2000 USD per ounce the price is now moving closer to its all-time high at $2070.
The rise in other commodities such as Oil, Gas, and Coal has also added to the rise in the price of Gold as concerns of inflation are increased, the interest in Gold usually follows. An interesting comparison can be made with regards to the increasing price of Oil. Whilst both commodities can be used as hedges against the market, Gold provides a more stable option whilst Oil is the more volatile option.
Both have seen strong rises due to the conflict and whilst Oil’s has been more meteoric, Gold has been steadier, as can be seen in the chart below. Gold has also performed extremely well against Bitcoin and other cryptocurrencies during the volatility that has been caused by the conflict. There was potential for Bitcoin and Cryptocurrency to provide a hedge against the market, however Bitcoin has been outperformed by Gold at this point.
Gold vs BTC vs Oil An interesting quandary to the Gold rise is the geopolitical element. For instance, Russia’s central bank purchased more Gold in 2021 than all other central banks, except for those in India and the United Arab Emirates. This means that there may be a shortfall in supply.
Technical Analysis The long-term chart has shown a long period of consolidation ultimately forming a symmetrical triangle pattern from which the price has broken out. It saw a big rise during the beginning of the pandemic and reached a maximum price of $2075 USD per ounce. When the price broke out of the triangle, initially an increase in relative volume occurred.
In addition, the retracement of the breakout was short-lived, and buying pushed the price up relatively easily. Another symmetrical triangle formed on the four-hour chart on the breakout of the breakout. Once again there was a strong increase in volume for the intimal move before it began the price began to contract again.
These continual price contractions and triangles forming may indicate that supply is being soaked up and that buying demand is present. On the four-hour time frame, it can be observed that the short sharp periods of consolidation have continued to be formed. Importantly, the consolidations have been relatively short, with in a tight range and broken with a high level of volume.
If volatility continues to be prominent and Inflation remains a threat, Gold will likely remain relevant. It will be interesting to see what happens with the price, if it is able to push through the all-time high price of $2075 per ounce.