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


Coinbase Global Inc. (COIN) released its financial results for Q2 after the market close in the US on Tuesday. The company reported revenue that fell short of Wall Street expectations at $808.325 million for Q2 vs. $873.82 million expected. Coinbase reported a loss per share of -$4.98 per share vs. -$2.47 loss per share expected. ''Q2 was a test of durability for crypto companies and a complex quarter overall.
Dramatic market movements shifted user behaviour and trading volume, which impacted transaction revenue, but also highlighted the strength of our risk management program. We are focusing on our top business priorities and more tightly managing expenses.'' ''The decline in crypto asset prices significantly impacted our Q2 financial results, which were consistent with the outlook provided in May. Net revenue was $803 million, down 31% compared to Q1, driven by lower trading volume.
Total operating expenses were $1.9 billion, up 8% compared to Q1. Net loss was $1.1 billion and was heavily impacted by non-cash impairment charges. Absent non-cash impairment charges, net loss would have been $647 million.
Adjusted EBITDA was negative $151 million,'' the company wrote in a letter to shareholders. Coinbase Global Inc. (COIN) chart Share price of Coinbase was down by 10.55% on Tuesday, trading $87.49 a share. The stock fell further in after-hours following the release of the latest financial results, down by around 3%.
Here is how the stock has performed in the past year: 1 month +61.65% 3 months +20.13% Year-to-date -65.26% 1 year -67.49% Coinbase price targets Citigroup $105 DA Davidson $90 Mizuho $42 JMP Securities $205 Atlantic Equities $54 Goldman Sachs $45 JP Morgan $68 Coinbase Global Inc. is the 754 th largest company in the world with a market cap of $22.96 billion. You can trade Coinbase Global Inc. (COIN) and many other stocks from the NYSE, NASDAQ, HKEX and the ASX with GO Markets as a Share CFD. Sources: Coinbase Global Inc., TradingView, MetaTrader 5, Benzinga, CompaniesMarketCap

Fears of slowing growth and weak Chinese data have forced China to ramp up its efforts to stimulate its economy and reassure investors: Record $83 billion injection: China injected a large amount of money in its economy. $83 billion was placed in the country’s financial system to avoid a cash crunch that would add further pressure to an “already” weakening economy. Spending Plans: Amid a raft of measures, China has approved a whopping $125bn of new rail projects over the past month. China is increasing its approvals for new projects and fiscal spending to counteract the slowdown.
Tax Cuts: China has put forward plans for the private sector and small business and is turning to tax cuts as a primary defence for its slowing economy. As uncertainties around tariffs continue, China is helping private companies and small business to obtain financing and increasing consumer spending. As of writing, the GDP (YoY) came at 6.4% from 6.5%, and we expect China’s economy to weaken in the lower range of the 6% mark amid the current external and domestic challenges.
Trade tensions have shaken business and consumer confidence and have further slowed economic growth. Even though there is more optimism on trade talks and higher chances of a truce deal, we expect trade negotiations to be bumpy and lengthy. The real economic implications may become more apparent in the coming months, and this can weigh on risk sentiment.
We expect to continue observing more actions from China during the year. The weak data is also giving room for policymakers to put forward more growth-supportive measures in the near term to stimulate growth and bring stability to its economy. So far, the stimulus actions coupled with positive trade talks helped the Chinese Yuan and the Shanghai Index to climb higher.
After a bruising year, the Index rose by more than 130 points since the beginning of the year.


Beyond Meat Inc. reported their latest financial results for Q4 2021 after the closing bell on Wall Street today. The US plant-based meat substitute producer company fell short of analyst expectations for the last quarter, sending the stock price lower in the after-market hours. The company reported revenue of $100.678 million in Q4 (decrease of 1.2% year-over-year) vs. $101.044 million expected.
Loss per share reported at -$1.27 a share, way above analyst forecast -$0.70 a share. Net revenue for 2021 at $464.7 million – an increase of 14.2% year-over-year. "In 2021 we saw strong growth in our international channel net revenues, as well as sporadic yet promising signs of a resumption of growth in U.S. foodservice channel net revenues as COVID-19 variants peaked and declined. These gains, however, were dampened by what we believe to be a temporary disruption in U.S. retail growth, for our brand and the broader category.
Despite the variability and challenges of the year, we did not deviate from building the foundation for our long-term growth. The investments we made in our team, infrastructure, and capabilities across the U.S., EU, and China, as well as extensive product scaling activities for key strategic partners, weighed heavily on operating expenses and gross margin during a fourth quarter and year that were already impacted by lower than expected volumes. However, we believe these investments will be instrumental in driving our long-term growth," Ethan Brown, Beyond Meat CEO said in a statement following the latest financial results from the company. "As we begin 2022, we are pleased with the progress we are making against our long-term strategy, such as the number of tests and core menu placements recently announced by our global QSR partners.
Though we will continue to invest during 2022, we expect to substantially moderate the growth of our operating expenses as we leverage the building blocks we now have in place to serve our customers, consumers, and markets — bringing forward our exciting and expansive future one delicious serving at a time," Brown added. Beyond Meat Inc. (BYND) chart (Weekly) Shares of Beyond Meat were up by 3.38% on Thursday at $48.64. However, the stock fell sharply in the after-hours – down by around 10%.
Here is how the stock has performed in the past year – 1 Month: -13.37% 3 Month: -35.14% Year-to-date: -24.80% 1 Year: -65.91% Beyond Meat Inc. is the 2973 rd largest company in the world with total market cap of $3.10 billion. You can trade Beyond Meat Inc. (BYND) and many other stocks from the NYSE, NASDAQ, HKEX and the ASX with GO Markets as a Share CFD. Sources: Beyond Meat Inc., TradingView, MetaTrader 5, CompaniesMarketCap


Since the recent crisis in Europe, you would have noticed a few things in the stock market which have directly or indirectly affected your normal day to day life, as a motorist one of the first things that you would have taken note of, is the price of fuel. Only a fortnight ago petrol prices for unleaded fuel was sold for $149.99 per litre (APCO service station Cranbourne), today’s price of $186.998 (price as of 24 hours ago) marks a clear sign that prices are rising and, in most cases, have hit above $2 per litre with people predicting that it will get worst before it gets better. We will take a look at why the EV market may be positioned to take advantage of this economic pain.
EV cars have long been in the process of becoming a cleaner alternative to combustible engine vehicles. Since climate change has been at the forefront of politicians and corporations’ agendas, companies such as Tesla have managed to carve out a large portion of the market for themselves and be the leading light into the new generations of cars. Whether that be by producing the latest car in the Roadster or providing companies with “regulatory credits” which allow the companies to reach emission targets set by governance in their respective countries.
In a push to reduce carbon emissions, governments around the world have introduced incentives for automakers to develop electric vehicles in return for regulatory credits. Because Tesla only manufacturers EV cars, they get free credits and as they have a surplus amount, they can sell these credits to their competitors for them to be able to meet the latest emissions targets. That’s one way in which Tesla profits hugely from their vision as they are able to make 100% profits on these credits.
As climate change reels its head and costs of fuel soars, many believe that EVs are the best alternative to an old age problem. However for EV cars to be successfully incorporated in our communities, there has to be a few advances in infrastructure including more regular charging stations, and improved battery life, with many currently working on producing longer lasting, quicker charging and more affordable batteries. As well as this, the price of EV vehicles would need to come in line with economy combustible engine vehicles to make them more desirable.
The infrastructure for electric-vehicle charging continues to expand. In 2019, there were about 7.3 million chargers worldwide, of which about 6.5 million were private, light-duty vehicle slow chargers in homes, multi-dwelling buildings and workplaces. Convenience, cost-effectiveness and a variety of support policies (such as preferential rates, equipment purchase incentives, and rebates) are the main drivers for the prevalence of private charging.
Market Performance: Sales of electric cars topped 2.1 million globally in 2019, surpassing 2018 – already a record year – to boost the stock to 7.2 million electric cars. Electric cars, which accounted for 2.6% of global car sales and about 1% of global car stock in 2019, registered a 40% year-on-year increase. Companies leading the way in manufacturing of EV cars and companies working alongside in infrastructure, battery life development and electricity providers in the field are: TESLA Volkswagen Group BMW Hyundai/KIA Jaguar Land Rover Schneider Electric SE Siemens AG ABB Eaton Corporation ChargePoint, Inc.
Webasto Group EVBox B.V. Blink Charging, Co. EFACEC Popular mentions to Delta Electronics, Inc. (Taiwan), Leviton Manufacturing Co., Inc. (U.S.), Alfen (Netherlands), NewMotion B.V. (Netherlands), Star Charge (China), SemaConnect (U.S.), Robert Bosch GmbH (Germany), and ClipperCreek Inc. (U.S.).
Some of the key players in both car manufacturing, infrastructure and battery performance which investors are keeping a close eye on, in order to take advantage of potential opportunities within the stock market. As we can gather from the research, figures and public opinion as well as Geopolitical issues affecting prices of energy, we can conclude that a change to EV cars is not longer just a pipedream but a very potential reality, with governments aligned with corporations and the public in wanting to have a change of direction from combustible engines to electricity charged vehicles. We would be able to see a huge increase or EV cars on our roads within the next few years.
Sources: CNBC, iea.org, Google, meticulousblog.org


What is an Expert Advisor (EA)? Expert Advisors (EAs) are trading software that automatically run and trade based on their preprogrammed rules for initiating, managing, and exiting trades in the market. These automated trading systems are very popular among traders and are widely used on the Metatrader 4 and 5 platforms.
For most traders, EAs are primarily used for Forex, although they can be used on any market that’s available on the platform. These can be purchased prebuilt online from a developer or created to automate an existing strategy being used. There are many reasons why traders use them, and I will explain some of the main advantages and disadvantages.
Advantages of using an EA: Discipline - these programs are set to certain parameters and will manage your positions based on the programmed strategy. Using a set of yes/no triggers it will make trading decisions and act on them instantly without changing their decisions like humans would do. It will also manage risk based on your risk settings, so you do not overexpose your account.
Timesaving – there is only so much time a trader can look at the charts for trading opportunities before getting tired while the markets are open. An EA can monitor the charts 24 hours per day and open and close positions or even provide alerts which can save time. Emotionless – this plays a huge role in the decision making for traders.
When trading with real money traders tend to make emotional decisions and break their strategy from fear or greed. An EA removes this element and will stick to the original plan although manually intervention can still be done. Backtesting – you can backtest an EA to see whether the strategy has been profitable in the past on multiple markets.
Although these can give you confidence to use them, it’s important to keep in mind that past performance is not an indicator for future performance. Disadvantages of using an EA Technical failures – for an expert advisor to work, your platform needs to be open and running at all times which means if you experience technical issues such as a crash, software update, power outages, connection problems then this will effect the EA. Additional cost of VPS – this is a dedicated private server which allows you to remove some of the technical challenges when using an expert advisor.
There are benefits of lower latency and faster execution and also the peace of the mind that the EA is running on a private server which can be accessed from any location. It typically costs around A$30 per month to have this access. World events – an EA is programmed to trade based on technical parameters, which means should there be an unexpected world event or news announcement, this would have an impact on your trades as the the market moves in response to them.
Doesn’t teach how to trade – these are coded to trade certain parameters therefore unless you understand how to code, you can only watch. Although there are many EAs which make money for people who can’t trade, if they are unprofitable then it’s back to the drawing board; that could mean finding another EA or learning to trade. Here are example how an Expert Advisor looks running on MT4 platform: If you are interested to use an Expert Advisor and seeing how these can perform and the results, you can find them on MQL5.com.
This is the largest community for developers and signal providers to showcase their systems. You will find some for free and some that will need a monthly subscriptions to have access to them. You can run expert advisors on a GO Markets trading account.
If you need any help setting them up please contact our support team.


Alibaba Group Holdings Limited (BABA) reported its latest financial results before the market open on Thursday. The Chinese e-commerce giant reported revenue of $30.689 billion for the quarter vs. $30.364 billion expected. Earnings per share were reported at $1.75 per share vs. $1.60 per share expected.
Daniel Zhang, Chairman and CEO of Alibaba Group commented on the results: ''During the past quarter, we actively adapted to changes in the macro environment and remained focused on our long-term strategy by continuing to strengthen our capability for customer value creation.'' ''Following a relatively slow April and May, we saw signs of recovery across our businesses in June. We are confident in our growth opportunities in the long term given our high-quality consumer base and the resilience of our diversified business model catering to different demands of our customers,'' Zhang added. ''Despite the challenges posed by the COVID-19 resurgence, we delivered stable revenue performance year-over-year. We have narrowed losses in key strategic businesses given ongoing improvements in operating efficiency and increasing focus on cost optimization,'' said Toby Xu, CFO of Alibaba Group. ''We recently shared our plan to add Hong Kong as another primary listing venue.
By becoming primary listed on both Hong Kong and New York stock exchanges, we aim to further expand and diversify our investor base,'' Xu concluded. Alibaba Group Holdings Limited (BABA) chart Share price of Alibaba was up by around 1% on Thursday, trading at $96.93 a share. Here is how the stock has performed in the past year: 1 Month -21.79% 3 Month +14% Year-to-date -19.42% 1 Year -51.97% Alibaba price targets B of A Securities $155 Bernstein $130 Benchmark $205 JP Morgan $140 HSBC $141 Citigroup $172 Truist Securities $145 Barclays $161 Alibaba Group Holdings Limited is the 31 st largest company in the world with a market cap of $256.21 billion.
You can trade Alibaba Group Holdings Limited (BABA) and many other stocks from the NYSE, NASDAQ, HKEX and the ASX with GO Markets as a Share CFD. Sources: Alibaba Group Holdings Limited, TradingView, MarketWatch, Benzinga, CompaniesMarketCap