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


Salesforce the worlds #1 customer relationship management (CRM) platform has just announced record fourth quarter and full fiscal 2022 results exceeding expectations. The pandemic-led shift to hybrid work has kept up a strong demand for its cloud-based software. Total fourth quarter revenue was $7.33 billion, an increase of 26% year over year, and 27% in constant currency.
Salesforce’s subscription and support revenue for the fourth quarter also rose 24.7% to $6.83 Billion. “We had another phenomenal quarter and full-year of financial results,” said Marc Benioff, Chair and Co-CEO of Salesforce. With our customers’ success driving our financial success, we’re generating disciplined, profitable growth at scale quarter after quarter,” said Bret Taylor, Co-CEO of Salesforce. “Our Customer 360 platform has never been more strategic or relevant in driving the growth and resilience of our customers around the world.” Salesforce has also been working to integrate Slack after its $27.7 billion purchase of the instant messaging platform, as well as adding products in a bid to sell more tools to existing customers. Analysts see a lot of room to increase sales of the company’s flagship software that lets businesses manage and interact with customers.
Salesforce believes the software market can grow double digits over the next several years, as companies across the globe continue to have conversations about facilitating hybrid and remote work models. Salesforce has not slowed down Slack’s roadmap, with the platform launching Slack Huddles and Clips in the second half of 2021. Salesforce said it expects $1.5 billion in sales form Slack in its fiscal year 2023.
Salesforce’s stock price has been on a downhill ride in the past several months, falling more than 30% from it’s November record high of over $310. Shares have recently increased over 4% and are currently trading at $209.65. Salesforce (CRM) Salesforce.com Inc. is the 51 st largest company in the world with total market cap of $205.75 billion Gavin Patterson the Chief Revenue Office said the global sanctions against Russia arising out of the war with Ukraine will have “minimal impact” on Salesforce’s business and haven’t forced the company to take any actions.
You can trade Salesforce.com Inc. (CRM) and many other stocks from the NYSE, NASDAQ, HKEX and the ASX with GO Markets as a Share CFD. Sources: Reuters, Yahoo Finance, itnews


In the midst of the Russian, Ukraine crisis, there are huge ramifications that affect us all in the global market. Energy is a critically important export. Russian oil and gas exports make up a fifth of Russia's economy and half of its earnings from exports.
The country is the European Union's biggest oil trading partner, according to the latest data from Eurostat. Russia also ranks 5 th in the world for oil consumption, accounting for about 3.7% of the world's total consumption of 97,103,871 barrels per day. They are also ranked 3 rd in oil production, which is the most important factor when it comes to costs, sitting close to the oil powerhouses of United States and Saudi Arabia.
They are also some way ahead of China, who sits in 4 th lagging behind Russia by a wide margin of 6 million barrels per day (Fig.1). As you can imagine any disruption to any country in this list on a normal day, would trigger a price movement. So a war and subsequent sanctions on a country who controls so much consumption and production of the precious liquid would make more than a ripple.
Global benchmark April Brent crude climbed $3.06, or 3.1%, to end at $100.99 a barrel. The contract, which expired at the end of the session, settled at its highest since September 2014, posting a gain of 10.7% for the month. West Texas Intermediate crude for April delivery on the New York Mercantile Exchange rose $4.13, or 4.5%, to settle at $95.72 a barrel.
The front-month contract finished at the highest since August 2014, up 8.6% for the month, according to Dow Jones Market Data. Latest Price Action Over the last few days, we have seen Oil prices finished higher each closing day, a sharp increase over night of 9.72% to start today’s session at $106.33 (Fig.2). Fig. 2 WTI Oil followed suit and had a jump of 11.5%, a sharp increase over night to start today’s session at $106.75 (Fig.3).
Fig. 3 The Wall Street Journal reported that the U.S. and other major oil-consuming countries were weighing the release of 70 million barrels of oil from emergency stockpiles in response to surging crude prices. This is to try to stabilize the oil prices and make up the supply that Russia would normally deliver pre sanctions. It’s important to tread carefully when trading assets such as these commodities, which are driven by Geopolitics, unforeseen supply and demand levels and corporate institutions around the world who have their own agendas in mind when thinking of their bottom line.
Profits. Sources: QUARTZ, worldometers.info, The Wall Street Journal, Tradingview.


Last week, Russia took a step that not many people thought it would take – they invaded Ukraine. Even though the tensions have been building in the region since the annexation of Crimea in February 2014, not many people thought Vladimir Putin would take the step to invade a sovereign nation. Five days on from the start of the invasion, we have already seen countries around the world condemn Russia’s actions and announce tough sanctions against the largest country in the world.
None of those have yet made any difference to their actions, as they continue their invasion. However, their actions have already impacted their economy - and it will most likely get worse. Swift action from the West Over the weekend, the United States, European Union, United Kingdom and other countries agreed to remove a number of Russian banks from The Society for Worldwide Interbank Financial Telecommunication (SWIFT) system, an international payment system which is used by financial institutions around the world. "We commit to ensuring that selected Russian banks are removed from the SWIFT messaging system.
This will ensure that these banks are disconnected from the international financial system and harm their ability to operate globally," the European Commission said in a statement following the announcement. The latest move will have a drastic impact on the Russian economy, which is the 11 th largest in the world according to the World Bank data. It is worth pointing out that only one other country has ever been cut off from the SWIFT system – Iran.
The move resulted in Iran losing half of its oil export revenues and 30% of foreign trade. The central bank reacts On Monday, the Bank of Russia announced its key interest rate from 9.5% to 20% to protect the Ruble, as the pressure mounts on the Russian economy following the latest round of sanctions. ''External conditions for the Russian economy have drastically changed. The increase of the key rate will ensure a rise in deposit rates to levels needed to compensate for the increased depreciation and inflation risks.
This is needed to support financial and price stability and protect the savings of citizens from depreciation,'' the Central Bank said in a statement on their website. ''Further key rate decisions will be made taking into account risks posed by external and domestic conditions and the reaction of financial markets, as well as actual and expected inflation movements relative to the target and economic developments over forecast period,'' the statement continued. The Central Bank of Russian Federation interest changes since July 2020 Financial markets Last week we saw the Moscow stock exchange, the MOEX index, plummet by 45% - to a new record low. The index recovered some of the losses last Friday when it was up by 20%.
On Monday, it was announced that the exchange will not open and the Russian Central Bank said that the operating hours of the exchange would be announced on 1 March 2022 before 9:00 Moscow time. MOEX Russia Index The Ruble The Russian currency has been in free fall since the conflict began – reaching the lowest level ever against the US Dollar. US Dollar was trading at around 76 level at the beginning of February vs. the Russian Ruble.
USD/RUB was trading 107.7000 level on Monday – up by around 27%. USD/RUB With the conflict showing no signs of getting resolved any time soon, we will most likely see more impact on the Russian and world economy in the coming weeks and months. Sources: The World Bank, TradingView, Global Rates, The Central Bank of Russian Federation


All prices in this article will be in USD unless otherwise stated. Rio Tinto Group is an Anglo-Australian multinational and the world's second-largest metals and mining corporation, behind BHP, producing iron ore, copper, diamonds, gold and uranium. Rio Tinto made history last week by posting the second biggest profit in Australian corporate history, the biggest belonging to BHP.
They have decided to reward their shareholders with Australia’s biggest ever dividend worth $16.8 billion, which is roughly $23 billion AUD. The $21.4 billion of underlying earnings for 2021 was the biggest in all of Rio Tinto’s 149 year history. The achievement has allowed a dividend payment of $4.79 per share.
The final and special dividends took Rio Tinto’s total dividends for the year to a record-breaking $10.40 per share. The total dividends paid by Rio Tinto for the year is almost doubled the previous year’s $5.57. The greatest profit recorded by an Australian company was BHP.
They set this record in 2011 with a recorded $21.68 billion in underlying profit. Comparing both companies, BHP’s record profit was when the Australian dollar was much stronger than today. This means the profit announced by Rio Tinto would be much bigger than BHP, in Australian dollars, $22.5 billion vs $23 billion AUD.
This does not take into account inflation. Rio Tinto’s great result was largely attributed to its most important commodity, iron ore. However, the decade high prices for copper and aluminium have also bolstered their profits.
The shareholder returns unleashed by Rio Tinto over the past four years rank as the four biggest in the company’s history, meaning shareholders in the miner are enjoying a golden era of returns. The “golden era” was initially built on the proceeds of asset divestments, however, Australian mining companies have been fortunate due to rival mining companies in Brazil suffering massive dam failures in 2019. Australia was able to capitalise on the weak iron ore supply in the aftermath.
The strong operating environment for mining companies like Rio Tinto has only continued since the onset of the COVID-19 pandemic. The pandemic had prompted governments to announce stimulus spending on infrastructure which drove strong demand for the raw materials which were produced by the likes of Rio Tinto and BHP. Most of Rio’s record setting dividend will be paid to shareholders outside of Australia; the company’s biggest shareholder is Chinese state-owned entity Chinalco while most investors own the stock through the London Stock Exchange.
All in all, the mining industry is currently experiencing a strong year. Rio Tinto, being one of the biggest players, has set the benchmark for other companies in the industry. The strong start to the year is a good indication as to where the industry is going.
If you would like to take this opportunity to invest in Rio Tinto Group and don’t already have a trading account, you can register for a Shares or Shares CFD account at GO Markets. Sources: ASX, Wikipedia, AFR.


Results are in – NVIDIA reports NVIDIA Corporation (NVDA) announced its second quarter results after the closing bell in the US on Wednesday. The US technology giant reported revenue that exceeded analyst expectations at $6.704 billion for the quarter vs. estimate of $6.699 billion. Earnings per share reported at $0.51 per share, narrowly beating estimate of $0.50 per share for the second quarter. ''We are navigating our supply chain transitions in a challenging macro environment and we will get through this,'' founder and CEO of NVIDIA, Jensen Huang said in a statement following the latest results. ''Accelerated computing and AI, the pioneering work of our company, are transforming industries.
Automotive is becoming a tech industry and is on track to be our next billion-dollar business. Advances in AI are driving our Data Center business while accelerating breakthroughs in fields from drug discovery to climate science to robotics.'' ''I look forward to next month’s GTC conference, where we will share new advances in RTX, as well as breakthroughs in AI and the metaverse, the next evolution of the internet. Join us,'' Huang added.
NVIDA expects revenue of around $5.9 billion for the third quarter, which is short of analyst estimate of $6.9 billion for the quarter. NVIDIA Corporation (NVDA) chart Shares of NVIDIA were little changed on Wednesday, up by 0.24% at $172.12. The stock fell in the after-hours by around 3% on future outlook.
Here is how the stock has performed in the past year: 1 month -3.19% 3 months +1.46% Year-to-date -41.44% 1 year -22.47% NVIDIA price targets Truist Securities $216 Mizuho $250 Raymond James $240 Barclays $200 Deutsche Bank $175 Citigroup $285 Keybanc $230 NVIDIA Corporation is the 13 th largest company in the world with a market cap of $429.17 billion. You can trade NVIDIA Corporation (NVDA) and many other stocks from the NYSE, NASDAQ, HKEX and the ASX with GO Markets as a Share CFD. Sources: NVIDIA Corporation, TradingView, MetaTrader 5, Benzinga, CompaniesMarketCap


The Reserve Bank of Australia, (RBA) has increased the Country’s cash rate by half a percent to combat the rising inflation in its latest cash rate change. The increase was in line with most analyst’s expectations as the RBA continues to fight inflation and bring it back into the 2-3% range. The current forecast from the RBA suggests that CPI inflation will peak near 7.75% over 2022, before falling to 4% during 2023, and then settling at 3% in 2024.
A key source of concern for the RBA was and continues to be the current spending habits of Australian households. Importantly, as the cost of goods has risen due to inflation, pressure has built on household budgets and their spending habits. This has been caused by both the supply chain issues and the increased cash rate.
Furthermore, consumer confidence has fallen, and “housing prices are declining after the large increases in recent years.” This shows how interest rate hikes are impacting the lives of Australians and their spending habits. Another important factor at play is the tightening of the job market. The unemployment rate dropped in June to 3.5%, the lowest rate in 50 years, and job vacancies and job advertisements continue to be at high levels.
However, the bank does not expect to be able to hold these levels and predict the rate of unemployment will reach 4% by the end of 2024 as a result of the current slowing economic growth. In response to the announcement, the ASX200 responded positively as investors saw the announcement as bullish, shooting up 0.38% in the 30 minutes after the announcement. Conversely, the AUDUSD dropped back below $0.70 dropping to $0.6970 in the 30 minutes immediately after the announcement.
The RBA will later this week further update the market with its monetary policy statement which will provide further clarity on its decision-making and the current sentiment.