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


For years, gold has been considered a store of value. As a physical commodity, it cannot be printed like money, and its value is not impacted by interest rate decisions made by a government. Because gold has historically maintained its value over time, it serves as a form of insurance against adverse economic events.
When an adverse event occurs that lingers for a while, investors tend to pile their funds into gold, which drives up its price due to increased demand. There have been many instances in our history, where war has ignited investment into gold. One particular moment in the 21 st century which signaled a strong movement into gold as a safe haven was the unfortunate event which occurred on 9/11.
Another was the Global Financial Crisis in 2008. In both instances gold’s price sored and it returned higher profits than any other financial asset. It’s important to understand at this stage, even though gold has these unique characteristics, it is not a long-term solution for a portfolio hedge or as a safe heaven.
Negative news tends to come after more negative news, which changes investor behaviors and tends to worry investors who in turn would sell their positions in gold, thus sending the price down to original levels or even lower. Some Key Points Safe haven investments offer protection from market downswings. Precious metals, currencies, and stocks from particular sectors have been identified as safe havens in the past.
Safe havens in one period of market volatility may react differently in another, so there is no consistent safe haven other than portfolio diversity. Latest Price Action Prior to Russia’s intentions of an invasion into Ukraine and fears of war, which is creating upheaval in the political landscape in Europe and around the world, gold was steadily rising in a sideways movement. However this past week you would have noticed a sharp price action jump 3% from $1892.00 to $1973.00 USD (see below), a price that we haven’t seen since 1 st of January 2021 and there is a strong feeling that it could push past this figure as Russia ramps up its invasion into eastern Ukraine.
If this happens, we could start to see higher highs as a result, as investors are spooked by the potential turmoil and destabilization. Gold or XAUUSD, can be accessible in different forms. You can purchase gold bullion in a number of ways: through an online dealer, or even a local dealer or collector.
A pawn shop may also sell gold. You are advised to note gold's spot price – the price per ounce right now in the market – as you're buying, so that you can make a fair deal. You could also find access to gold in the following ways: Gold Futures, ETFs that own gold, Mining Stocks, ETFs that own mining stocks, or you if you wish to trade it, you could use CFDs, where you can trade the value of the shiny metal when it goes up or down.
Visit our website here to get started with a CFD trading account and start taking advantage of opportunities. Sources: www.bankrate.com, Investopedia, Tradingview.

For the last 2 years, Gold has been bouncing in a range between $1700 and $2070 and is currently testing the major support level around $1700 as seen below. The price has used the yellow highlighted as an area for support zone and a rejection zone. Over the last 2 years clear rejections have occurred every time the price has reached around $1700’s.
These candlestick rejections indicate a high probability of something similar potentially happening. We find further confluence of this analysis by looking at the weekly time frame, where Gold has broken above the trend line, and has now come back to retest it. This can often result in a bounce off the trendline, creating the start of a new uptrend.
If Gold continues to remain above the trendline and can hold the monthly support, it may indicate that it is in the early stages of a potential reversal. This may lead to another move toward the $2000’s.

The first quarter of 2020 was marred by unpredicted events that rattled the financial markets: Tensions between US and Iran; The extreme weather conditions across the globe as a result of climate change; The novel coronavirus; and An oil price war between Saudi Arabia, the oil kingdom, and Russia. A Trio of Crises Faced by an unprecedented health crisis that caused an abrupt slowdown of activities, forced by governments and an oil crisis derived from a simultaneous demand and supply shock, the world is currently bracing for an economic recession. The markets tumbled like dominoes hit by various headwinds at once.
The freefall in the markets has forced central bankers and governments to implement various stimulus packages, emergency rate cuts and engage in significant bond-buying. Confidence has taken a massive hit as the world faces unprecedented quarantines measures! Volatility Index (VIX) A look at the CBOE Volatility Index shows how investors are reacting to the impact of the coronavirus on markets and the economy.
Also known as Wall Street’s fear gauge, the index is a real-time market index that represents the market expectation of 30-day forward-looking volatility. The Index, on average, has been around the 20 levels but increased to decades high at 82.69 on the 16 th of March 2020. The sharp rise is the reflection of fears and anxieties prevailing in the financial markets.
Source: Bloomberg Stock Market Busts and Circuit Breakers Circuit breakers were first introduced in the 1980s to curb panic selling. For the US exchanges, the S&P500 is used as the pricing reference to measure a market decline and there are currently three levels to the circuit breakers: Level 1 (7%) Trading will halt for 15 minutes if the drop occurs before 3:25 p.m. At or after 3:25 p.m.—trading shall continue unless there is a Level 3 halt.
Level 2 (13%) Trading will halt for 15 minutes if the drop occurs before 3:25 p.m. At or after 3:25 p.m.—trading shall continue unless there is a Level 3 halt. Level 3 (20%) At any time during the trading day—trading shall halt for the remainder of the trading day.
There were four circuit breakers in one month which is a record number ever since circuit breakers were first introduced! The novel coronavirus has created such uncertainty around the globe, which has caused plunges in global equities. Despite the VIX easing to 65.54, further wild swings seem certain in the next couple of weeks.
Source: Bloomberg Rescue Packages In such plunging markets, the focus has been on the rescue packages. Some world leaders were complacent at the beginning, however, we are now seeing highly coordinated intervention measures flooding the markets in an attempt to cushion the effect of the COVID-19 on the global economy. Central banks issued emergency rate cuts as well as other policy tools like quantitative easing (QE).
Major countries like Australia and New Zealand were forced to join the QE wagon to support their respective economies. Governments issued various massive stimulus packages to relieve consumers and businesses from the coronavirus fallout. The US stands out with a $2 trillion stimulus package, the biggest in history.
The rescue packages have not necessarily addressed the full extent of the economic pain which yet to be seen in the coming months, but have provided some relief to wounded economies. Stock Market – A Degree of Calm In the first quarter of 2020, it is evident that the 11-year bull run in the stock markets was over. Major equity indices dropped in bear market territory in what was the worst week since the global financial crisis.
Source: Bloomberg The stock market went on a roller coaster ride as investors pulled out of riskier assets. The degree of calm is driven by various interventions in the financial markets. But, the worst of the virus is not yet over and it may not yet be a lasting rebound.
It could well be a dead cat bounce. Notwithstanding, there are not enough signs to predict whether the stock market has found a floor or is yet to find a bottom. There are too many uncertainties to start pricing-in a recovery.
FX – The King Dollar? The currency market is on the same wild run as other markets. The immediate attention falls on the King dollar.
In the early stage of the outbreak, the US seemed relatively unfaed by the virus and the greenback gathered strength as a safe-haven compared to the rest of the world. As panic gripped markets, dollar funding pressures drove the US dollar index to a 3-year high above the 102 level. Source: Bloomberg Even though the greenback has somewhat retreated as policymakers stepped in to enhance flows, the US dollar index remains in elevated levels just below 100.
A significantly bigger stimulus package compared to its peers are fuelling hopes that the US economy would probably recover faster than other major economies. Gold – The Safe Haven The price movement of the precious metal also depicts the turmoil in the markets. At the start of the year, the US dollar and Gold were moving in tandem due to the prevailing uncertainties.
QE, low-interest rates, trade frictions, geopolitical tensions, global debt and growth uncertainties, gold hoarding by central banks have driven the gold price to a high of $1,680.47. Gold was liquidated due to the wider and rapid spread of the coronavirus across the globe. The precious metal is viewed as a highly liquid asset and investors were in a need of cash due to margin calls and other liquidity requirements.
The greenback and the US dollar have therefore started to diverge from each other. COVID-19-induced liquidity issues caused the yellow metal to plunge to a low of $1,471.24. Source: Bloomberg Once investors were reassured that central bankers are injecting money into the financial system, investors resumed the buying of gold as a safe-haven.
At the same time, gold is facing disruptions in the physical markets due to the shutdown of gold refineries leading to a shortage of gold. A combination of positive fundamentals, weaker US dollar and rescue packages lifted the XAUUSD pair back above the psychological level of $1,600. Source: Bloomberg The economic backdrop is creating a bullish environment for the precious metal.
Amid high volatility, Gold traders are likely going to keep monitoring any updates on the virus, liquidity in the financial markets, and the strength of the US dollar for fresh trading impetus. Volatility Means Opportunities Human lives and the global economy are at risk. The coronavirus has heavily impacted the way the world operates.
Even though the worst of the health crisis is not over yet, and many countries are bracing for another brutal quarter ahead, the health crisis will ease and end at some point. It is not all gloomy in the investment space despite the sharpest falls in history. The panic-driven volatility might present investment opportunities.
Investors will likely be in search of bargains by buying at rock-bottom prices once the number of coronavirus cases starts to slow down. An oil storage problem, higher storage costs, faltering demand and a significant rise in production are creating a perfect storm for the oil market.


The Euro has fallen to 20-year lows as it deals with increasing energy prices and increased bond yields as recession fears rise again. Across both the UK and Europe inflation has been especially high even compared other countries such as Australia and the USA and in response, the EUR has taken a large hit. The recent spike in energy prices has brought back fears into the market that inflation has not yet peaked and will continue to rise.
Two potential opportunities are on the EURCAD and the EURUSD. Firstly, on the EURCAD the price is sitting just above its long term supports and its lowest levels since 2015. With seemingly no fundamental reason for the price to bounce in the short to medium term, it is possible the price sells through the 1.30 CAD level and falls further to the 1.21/1.20 level.
The 50-week moving average is almost in a free fall as the currency continues to sell. In addition, the RSI, whilst in oversold territory, is forming a descending triangle. This indicates that sellers may be gearing up again to begin another move down below the 30 RSI level.
Whilst the EUR continues to be smashed there is always the potential that the market will see value and see a rally in the pair. Therefore, it is important to have risk management tools in place such as a stop loss. A stop loss could be set above 1.32 which would represent a potential risk reward of almost 2.5:1.
The EURUSD is following is showing an even more aggressive sell off. The EUR has fallen to 20-year lows vs the USD. The worrying sign is that the price has faced very little resistance since it began diving in January 2022.
Every long-term support has been sold through with without much of a pullback. With the 1.00 USD level expected to be a tougher level to sell through, short opportunities still exist. The next level of support is around 0.95/0.96 USD which is the next logical target for a short entry.
However, once it reaches this level, it may prove very difficult to fall lower as it would me mean breaching 50 year low prices.


Dicker Data is an Australian-owned and operated, ASX-listed technology hardware, software and cloud distributor. They were founded in 1978. As a distributor, they sell exclusively to a valued partner base of over 5,500 resellers.
Dicker Data distributes a wide portfolio of products from the world’s leading technology vendors. Dicker Data have successfully navigated the end of governmental business stimulus and the impact of a global semiconductor chip shortage to post a net profit of $73.6 million, which is an increase of 29%. Sales figures increased 24% to $2.48 billion for the 2021 calendar year.
Dicker Data declared a final dividend of 15 cents (USD), 100% flanked, on total earnings of 42.6 cents per share. FY21 Results Highlights The company believes that shortages are a part of the computer business and have always planned around it. They identify the software sector to be its highest growth opportunity as dynamic workplaces, which allow employees to work from home, are currently in high demand.
They also identify that there will be a strong demand for audio-visual equipment, such as large format displays for meeting rooms, as workplaces welcome back employees to the offices. The company’s debt over the period has almost doubled to $230.2 million after they have announced debt funded deals to acquire its rival IT distributor, Exceed, for $68 million. They have also recently acquired Hills Ltd’s Security and Information Technology business for $20 million last month.
The company also has their sights on another acquisition in the future, they have been in talks with a few bankers to help finance a potential acquisition of a rival US-based IT distributor, Ingram Micro. Ingram Micro was sold to US private equity group Platinum Equity for $7.2 billion (USD) in July 2021. Prior to this, HNA Group acquired the business for around $6 billion (USD) in 2016.
Co-founder David Dicker stated that his company would have acquired Ingram Micro for $7 billion (USD) if they had been able to raise the capital. Dicker Data share value is slowly trending up since February’s acquisition. However, due to the Russia and Ukraine conflict, the ASX 200 index is currently dropping in value and this can trickle down to companies such as Dicker Data.
Overall, Dicker Data is currently in a growth state and is looking to acquire companies that would help increase the company’s value and offerings to its many clients. They aim to use debt to fund the acquisitions and then issue shares to pay down the debt once the acquisition is successful. The acquisitions have helped the company achieve a profitable year as evident in the earnings report.
With the acquisition target of Ingram Micro, this can be an exciting opportunity to track the progress from start to finish. If you would like to take this opportunity to invest in Dicker Data and don’t already have a trading account, you can register for a Shares account at GO Markets. Sources: ASX, TradingView, AFR.


A sudden rapid increase in commodity prices, propelled by supply concerns stemming from the Russia and Ukraine conflict, has brought about inflationary pressure and moved future inflation expectation. The increase has also pushed indices into a bear market and caused some volatility in global equities. Nickel, European gas and wheat have all hit record highs on Monday.
Copper, Brent crude oil, aluminium and thermal coal are currently sitting at their highest levels in years. The commodities rally has stirred up fears that inflationary pressures will persist as the price increase works its way through the supply chain and slows down economic growth. The Australian 10-year break-even rate is sitting at 2.48%, its highest level since 2014.
The US 10-year break-even rate increased to 2.86% on Tuesday, its highest level since 2005. The German 10-year break-even rate hit a record high of 2.62%. Break-even rates represent the difference between a nominal bond and an inflation-linked bond of the same maturity, implying the average rate of inflation over a given period of time.
The spike in these rates suggests that the bond market is expecting inflation to be far more persistent than central banks and strategists have been expecting. The fear of Russian energy sanctions has led to heavy selling in the global equity markets. The US Dow Jones, Nasdaq, Euro Stoxx 50 and Germany DAX index have slipped into bear markets as shown from the chart above.
The EU50 and DAX are currently down 20% since their peaks in mid-January. The spike in break-even rates comes after the surge in the price of energy as Brent crude has reached a high of $136 USD a barrel on Monday. This rapid increase in the cost of energy, namely the Brent Oil, is currently making its way through to our local petrol pumps.
As the national average petrol price has climbed to 1.839 per litre. Other commodity prices are also beginning to break into new territory and are likely to drive up the cost of goods further down the supply chain. Nickel recently hit a record high of over $60,000 USD a tonne, as supply risks sparked a short squeeze.
About 7 per cent of the world’s nickel is produced in Russia, with the metal being used to produce stainless steel. It is also a major component of lithium-ion batteries, which are used in electric vehicles. The steady surge in commodity prices and their associated inflation risk has created a dilemma for central banks across the world.
Central banks are trying to manage inflation without curbing growth. All in all, commodity prices are currently on the rise as the conflict between Russia and Ukraine continues. Their prices are now on most investors’ watchlists, as it can affect other markets such as Forex and Indices.
If you would like to take this opportunity to invest and do not yet have a trading account, you can open a GO Markets CFD trading account. Source: GO Markets MT5, TradingView, Globalpetrolprices, AFR