市场资讯及洞察
%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 Society for Worldwide Interbank Financial Telecommunication, legally S.W.I.F.T. SC, is a Belgian cooperative society providing services related to the execution of financial transactions and payments between banks worldwide. Its principal function is to serve as the main messaging network through which international payments are initiated.
It also sells software and services to financial institutions, mostly for use on its proprietary "SWIFTNet". Its important to understand that money is not moved through the SWIFT system but most importantly is the data attributed to the money that is moved through this medium. In other words, without SWIFT the institutions wouldn’t know who and for what reason is a transaction is being made.
For example; if you are sending money from country to country, SWIFT would inform the recipient bank that is getting the money, to expect a certain sum, from a certain bank. So its an extremely important step that will be taken away from Russia. If you do not have that information flow; you simply cannot do any international transactions.
SWIFT welcomes the public launch of the New Payments Platform (NPP) in Australia, which is set to revolutionise the way payments are made domestically. SWIFT has helped to design, build, test and deliver the NPP and will play a key role in operating the infrastructure for the NPP. The NPP’s paradigm-shifting financial architecture has been designed and constructed to fundamentally improve how consumers, businesses and governments transact with one another.
The key features of the NPP include: 24/7 instant payments and real-time line-by-line settlement via the Reserve Bank of Australia’s Fast Settlement Service PayID, the new and easy way to link a financial account with an easy-to-remember identifier such as a mobile phone number, email address or ABN for businesses Open access platform that truly empowers innovation through competition Overlay services framework that will provide new value services to Australian consumers, businesses and government Russia’s SWIFT Sanction Since the invasion of Russia, many countries have joined forces in order to impose heavy sanctions on Russia. Some of these actions are to limit, deter and coerce Russia or Vladimir Putin into changing his strong stance in the war against Ukraine. These sanctions would be felt throughout all classes of Russia’s community and its corporate arm.
One popular sanction has been to remove Russia from the SWIFT messaging system, with the intention to stop any Russian companies from doing international business, which in turn would hurt Russia’s economy and potentially turn Russian loyalists against Mr. Putin and force him into an unlikely reversal of the war. Although this is somewhat looked upon as a key destabilizing strategy by the West, there are some that feel the move is mostly symbolic.
EU bars 7 Russian banks from SWIFT, but spares those in Energy (Reuters). The European Union said on Wednesday (2 nd march) it was excluding seven Russian banks from the SWIFT messaging system, but stopped short of including those handling energy payments, in the latest sanctions imposed on Russia over its invasion of Ukraine. VTB Bank PJSC and Bank Rossiya are among the banks that face a ban from the messaging system.
The other institutions included on the EU list are Bank Otkritie, Novikombank, Promsvyazbank PJSC, Sovcombank PJSC and VEB.RF, said the officials, who asked not to be identified because the decision was private. European Union ambassadors agreed to spared the nation’s biggest lender Sberbank PJSC and a bank part-owned by Russian gas giant Gazprom PJSC. Would it work: Professor of Financial Economics at the University of Loughborough University, Alistair Milne, explains why he is sceptical of the sanction. “Russia’s exclusion from the international payments messaging system Swift, is presented as a powerful means of undermining its economy.
But for a payment’s expert such as myself, this is something of a myth.” He continues, “The reality, however, is that limiting access to Swift is less practically effective than most media coverage supposes. It is an important symbol of global repudiation of Russia’s exercise of military force, but not much more. It is other measures, such as blocking the central bank of the Russian Federation from transacting internationally, which is undermining confidence in the Rouble.” “There is no fundamental problem with transferring funds using some other secure messaging systems.
Russian banks might, for example, instead arrange payments using the SPFS system, which was established after the 2014 invasion of Crimea by the Russian central bank. This is currently used by a handful of international banks in Germany and Switzerland linked to Russian banks.” “Or they could use the CIPS network, which was created by the People’s Bank of China for the purpose of cross-border payments with indirect participants in many countries. They could even use WhatsApp to instruct the necessary transactions.” Leaving room for negotiation?
The EU has avoided the sanctioning of all Russia banks, specially those that use SWIFT in the energy industry. This might be crucial as they seem to be trying to limit Russia, but at the same time keep the door ajar to be able to negotitate energy deals, which, the West are hugely dependednt on. Another thing to note is payments for Russian energy exports, for example to Gazprom, are even less Swift-dependent.
When operators buy oil or gas from Gazprom, they make payments in either euro or US dollars into bank accounts held by the Russian energy company. So if the intention of sanctions is to block payments for Russian gas, the tool is not Swift; it is sanctions on Gazprom and its banking facilities. Perhaps this could be something that is visited in the future.
The absence of Sberbank PJSC and Gazprombank shows the continuing level of concern over the consequences for Europe from a financial isolation of Russia spilling over into the global economy, especially when it comes to energy supplies. The bloc is also worried Russia could retaliate by cutting deliveries. Sources: Reuters, Wikipedia, Loughborugh University, Bloomberg, swift.com


Walmart tops expectations for Q2 – the stock is up Walmart Inc. (WMT) announced its Q2 financial results before the market open on Wall Street on Tuesday. World’s largest supermarket chain reported results that exceeded analyst expectations, sending the stock price higher. The company reported revenue of $152.859 billion (up by 8.4% year-over-year) vs. $150.994 billion expected.
Earnings per share reported at $1.77 per share for the quarter vs. $1.62 per share estimate. Doug McMillon, President and CEO of Walmart commented on the latest results: ''We’re pleased to see more customers choosing Walmart during this inflationary period, and we’re working hard to support them as they prioritize their spending. The actions we’ve taken to improve inventory levels in the U.S., along with a heavier mix of sales in grocery put pressure on profit margin for Q2 and our outlook for the year.
We made good progress throughout the quarter operationally to improve costs in our supply chain, and that work is ongoing. We continue to build on our strategy to expand our digital businesses, including the continued strength we see in our international markets.'' Walmart Inc. (WMT) chart The stock was up by over 6% on Tuesday, trading at $140.233 a share. Here is how the stock has performed in the past year: 1 Month +8.62% 3 Month +7.14% Year-to-date -2.74% 1 Year -6.62% Walmart price targets Deutsche Bank $142 Raymond James $140 BMO Capital $160 Cowen & Co. $150 Morgan Stanley $145 UBS $152 Credit Suisse $133 Wells Fargo $130 Walmart is the 14 th largest company in the world with a market cap of $383.98 billion.
You can trade Walmart Inc. (WMT) and many other stocks from the NYSE, NASDAQ, HKEX and the ASX with GO Markets as a Share CFD. Sources: Walmart Inc., TradingView, MetaTrader 5, Benzinga, CompaniesMarketCap


The USDJPY has been in an extremely strong upward trend since September 2021. This pair's recent price action has also been charactarised by relatively weak retracements as it has trended higher. Inflationary pressures have acted as a strong catalyst for the USD against most other currencies further aided by the Federal Reserve taking a strong stance against inflation with a series of aggressive interest rate hikes.
At the same time, the JPY has remained weak as the Central Bank of Japan has refused to intervene and shift from its dovish stance. The most recent retracement shows the potential for a good risk/reward Long trade. On the chart, it can be seen that the price has pulled back to the 23.60% Fibonacci level, which is at 132/133JPY.
This area also doubles as a support zone with the prior resistance level becoming a level of support which is another sign that the trend may continue. On the weekly chart, the characteristics of the candlesticks near the support zone also support the premise that the price may bounce. The candles have long wicks touching the support area indicating that the buyers are soaking up the supply.
They have also closed near their opening price again showing how buyers are soaking up the supply. The 4-hour chart shows a consolidation of the price forming a triangle, with the potential to break out to the upside. This may provide an alternative entry signal for the same overall strategy.
An important aspect to remember when trading this strategy is to ensure that price occurs with relatively high volume. Large volume indicates that buyers are regaining control over the price, and that sellers have become exhausted. Potential risks There are some risks with this trade.
Firstly, the pair is already quite overextended with the price at multi-decade highs. In addition, with US inflation fears potentially easing and interest rate hikes priced in already, the current price may be near its peak.


USDJPY ready to bounce or retrace further. The USDJPY has been recently provided great buying opportunities for traders. However, in recent days it has posted its largest drop since beginning the current upward at the beginning of January 2021.
The question remains, is this just a standard retracement or is it a symbol of a much bigger reversal. In the last few months, the USD has risen sharply as the market has responded to inflation fears and geopolitical events. With inflation levels at record levels across much of the developed world many Central Banks have shifted to a hawkish stance regarding their monetary policy with the USA being a prime example of this.
On the contrary, the Central Bank of Japan has remained dovish almost acting as a lone solider compared to other countries in this regard. Despite this, as bond yields have begun to settle down and the market has begun to price in recession fears and inflation, the YEN has become attractive again. Technical Analysis Looking at the technical elements of the chart, the price is down from the multi decade highs of 139 that it reached in the middle of July.
Importantly the price has also dropped below the most recent support level. In addition, the price has also breached the 50-day moving average. The question that remains is whether this is a simple retracement or the signs of a reversal occurring.
There are two characteristics of this price action that support the potential bounce back to the upside for this currency pair. Firstly, on the daily, chart, although the price did break through the initial first level of support it is currently holding the next stronger level down at 131/132. In addition, looking at the weekly chart, the price is showing a relatively strong bounce off the same 131/132 zone.
This multi timeframe analysis, further supports the continuation of the upward trend of the pair. The midterm buy target may be a retest of the 140 level. There is a large risk with this trade.
If the ‘Top’ is indeed ‘in’ and the pair does start to falter, then there is risk of massive selling. This is because the pair is already so overextended to the buy side. In addition, a rush to close Yen short positions may further accelerate the move back downward.
If this does occur and the 130 level breaks it may see the price fall to the 125 level. The short-term future of the pair will still likely be determined by short term economic news and activity within both Japan and the USA.


US economic data revealed last night shows that the country’s GDP has shrunk by 0.9%, although some are remaining positive that a recession may still be avoided. Despite the worrying figures, Federal Reserve Chair, Jerome Powell, outlined his belief that due to low unemployment figures of 3.6% and a strong market for jobs with 11 million job openings that there may be a 'soft landing'. Joe Biden commented, “It’s no surprise that the economy is slowing down as the Federal Reserve acts to bring down inflation.” More US CPI data is expected to be announced tonight.
In response to the GDP figure, the US indices had another green day with the Dow Jones, the Nasdaq, and the S&P500 all rising 1.03%, 1.08%, and 1.21% respectively. In terms of share price movement, Meta’s stock price dipped 5.22% as it posted its first-ever quarterly drop in revenue, signaling how interest rate hikes have been impacting growth companies. The data also followed through to the Australian market with the yield on 3-year government bonds falling to 3.1%.
The ASX200 also continued its momentum for the week as it pushed higher again on Thursday. Brent Crude Oil had a mixed day ending the day flat at $107.58. Gold continued to bounce off its support zone and climbed up 1.25% and Natural Gas fell 4.66% as it continues to pull back from its recent highs dropping 4.66%.
FOREX and Cryptocurrency The USD dropped sharply as the GDP figures were announced. It recovered briefly, before selling back down, closing towards the lowest price of the day, a total drop of 0.28%. Bitcoin and Ethereum also gained momentum as money continued to flow back into risk assets, with the latter jumping to its highest level since the middle of July.
ETHUSD closed at $1726 and Bitcoin at $23,860.


Salesforce.com Inc. (CRM) reported its fourth-quarter earnings results after the closing bell over Wall Street today – surpassing analyst expectations. World’s leading customer relationship management (CRM) company reported revenue of $7.326 billion (an increase of 26% year-over-year) vs. $7.242 billion expected. Earnings per share reported at $0.84 a share vs. $0.75 a share expected. ''We had another phenomenal quarter and full-year of financial results,'' Marc Benioff, Chair and Co-CEO of Salesforce said following the latest results. ''As we continue to see tremendous demand from customers, we’re raising our FY23 re venue guidance to $32.1 billion at the high-end of range, with non-GAAP operating margin of 20%, and operating cash flow growth of 22% year-over-year,'' Benioff continued.
Bret Taylor, Co-CEO of Salesforce, also commented on the strong financial results: ''With our customers’ success driving our financial success, we’re generating disciplined, profitable growth at scale quarter after quarter.'' ''Our Customer 360 platform has never been more strategic or relevant in driving the growth and resilience of our customers around the world.'' Salesforce.com Inc. (CRM) Share price of Salesforce was little changed at the end of the trading day on Wall Street Tuesday, down by 0.78% at $208.36 per share. Here is how the stock has performed in the past year – 1 Month: -10.01% 3 Month: -26.69% Year-to-date: -17.80% 1 Year: -2.15% Salesforce.com Inc. is the 51 st largest company in the world with total market cap of $205.75 billion. 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: Salesforce.com Inc., TradingView, MetaTrader 5, CompaniesMarketCap