Starting from scratch to write your first indicator - Advanced version

CN
2 hours ago

In the last session, we talked about how to write the first indicator from 0 to 1, how to calculate a line, how to label signals, and how to write alerts. Many friends said that they finally understood the code after watching it. Today we are going to keep it simple and just add one more layer of judgment — last time we alerted when the price crossed above MA20, this time we upgrade to alerting only when the price is above MA60 and crosses above MA20. This one additional filtering condition can help you filter out 80% of false signals.

Let me clarify that all the content today is a tutorial on indicator writing and does not constitute any investment advice. Those who didn't watch the last session don't need to worry; today's content is not difficult, just a little more advanced than the basic version. Follow my thought process, and I guarantee you will understand.

Many people using indicators have this trouble, right? You add the condition of crossing above the 20-day moving average, but it triggers dozens of times a day, and just when you chase in, you're stuck, and when you sell, it rises. The problem lies in having only one triggering condition, with no filter. Today we are going to teach you how to add a "gatekeeper" to the signals, for example, using trends, RSI, Bollinger Bands, or volume to filter, making the signals more accurate, so you won’t be bothered by alerts every day.

Let’s quickly review the core of the last session. Whether you are a new or old student, you must remember: any indicator can be broken down into four steps — first calculate the value, then define the signal, then plot it on the chart, and finally add alerts. Today we will not overturn this framework, we will only add one condition at the "define signal" step, which is very easy to understand.

Double Moving Average Advanced: MA20 for Rhythm, MA60 for Direction

Let’s start with the simplest double moving average. In the last class, we only looked at MA20, where we alerted when the price crossed above it, but here comes the issue: if the overall trend is downward, simply crossing above MA20 may only be a small rebound, and you end up catching the wrong side. At this time, adding a MA60 as a "large direction filter" changes everything.

MA20 is close to the price, allowing us to see the short-term rise and fall rhythm; MA60 moves slower, helping us keep hold of the big direction. The logic is very simple: we only chase short-term rising signals when the big trend is upwards, meaning we will alert when the price is above MA60 and crosses above MA20.

First, let’s plot these two moving averages; the code is very easy to understand: the name before the equal sign can be anything you want, just name it a or b; the computational function is after the equal sign. ma20 = ma(close, 20) calculates the 20-day moving average using the closing price, and ma60 = ma(close, 60) calculates the 60-day moving average. Then we color the moving averages: if the price is above MA20, it shows green; if below, red; if the price is above MA60, it shows blue; if below, gray, so it’s easy to see the trend at a glance.

There is a particularly easy point to confuse, so remember: "above" and "just crossed above" are not the same. close > ma60 means the price is currently above the 60-day moving average, which is a continuous state, suitable for filtering; while crossup(close, ma20) means the price has just crossed above MA20 from below, which is an instantaneous event, suitable for triggering alerts.

Combining these two conditions gives us crossup(close, ma20) and close > ma60, translating into plain language as "the price has just crossed above the 20-day moving average, and the big trend is upwards." You see, with this filter, all those small rebound signals in a downtrend are filtered out, leaving only trend-following signals, which increases accuracy significantly.

RSI+EMA: Adding Momentum Confirmation to Golden Crosses

After discussing the double moving averages, let’s talk about how RSI can be used in conjunction with EMA. Many beginners only remember RSI as 70 being overbought and 30 being oversold, but in advanced strategies, we don't have to stick to those levels so rigidly. When RSI is greater than 50, it indicates that bullish momentum is above the middle line, which is particularly useful for confirmation signals.

For example, with the commonly used EMA golden cross, many times the golden cross occurs, but the market is still weak and doesn’t rise. At this point, adding a condition of RSI greater than 50 can filter out those false golden crosses with insufficient momentum. The code is simple; first, calculate the 5-day EMA and the 60-day EMA, then calculate the 14-day RSI, and then write the signal condition as crossup(ema5, ema60) and rsi(close, 14) > 50.

This means that not only must a golden cross occur, but it must also meet the condition of sufficient bullish momentum for the signal to be reliable.

Here’s a little tip: changing the moving average period is very simple. For example, if you want to use EMA10 instead of EMA5, just change the 5 in the parentheses to 10, and remember to change the previous variable name to ema10, otherwise, it will throw an error. If you make a mistake, it’s okay; our platform has an AI assistant that can help you find errors and correct your code. This feature is currently temporarily free of charge, so you can use it more when writing indicators.

Bollinger Bands Advanced: Midline Marking + Upper and Lower Band Alerts

Next, let’s talk about Bollinger Bands, an indicator that many people use, but very few use correctly. Bollinger Bands are like a channel, where the midline is the centerline, the upper band is the ceiling, and the lower band is the floor, with prices mostly running within this channel.

The Bollinger Bands function has a particularly convenient feature, as it can return three values at once: the midline, upper band, and lower band, so we don’t need to calculate them separately. [mid, upper, lower] = boll(close, 20, 2) calculates all three lines at once.

Our approach today is also straightforward, focusing on three tasks: plot all three lines on the chart, mark an alert "midline" when the price crosses the midline, and send an alert when the price crosses above the upper band or below the lower band. This way, when the price touches the channel boundaries, you will know immediately, whether working in a range or breaking out, it's useful.

In a ranging market, prices generally run in the middle of the Bollinger Bands; touching the upper band leads to a pullback, and touching the lower band leads to a rebound. Using this method for high selling and low buying is particularly convenient. In a trending market, if the price breaks above the upper band, it is a signal for accelerating upward, and if it breaks below the lower band, it is a signal for accelerating downward, helping you catch major movements in time.

Backtesting: Validate Your Indicator, Don't Treat Real Trading as an Experiment

Finally, let’s talk about backtesting, which is very important. Many people write indicators and go directly to real trading, ending up losing heavily, simply because they skipped this backtesting step. Backtesting is like doing mock exams before a test; it helps you see how your trading rules have performed in the past and whether they have executed as you expected.

The method for backtesting is also very simple; add trading functions to your indicator: enter_long is for opening a long position, and exit_long is for closing a long position. Then click the backtest button, select the backtest period, and you will see figures like returns, win rate, and maximum drawdown. For instance, looking at the EMA golden cross and dead cross strategy we just wrote, if you look at it over a longer period, the returns may look good, but in the last three months during the bear market, it only triggered one signal. Although it didn't lose money, it also didn't gain much, so at this point, you know this strategy is better suited to a bull market and should adjust parameters or add other conditions in a bear market.

It’s important to remind everyone, backtesting is not a guarantee of returns. Past performance does not mean future profitability. Backtesting can only help you verify if your logic is correct; in real trading, you still need to consider practical issues such as transaction fees, slippage, and liquidity. Never rush in just because you see high backtest returns.

The 4 Pitfalls Newbies Are Most Likely to Fall Into

Today’s content is actually not difficult; the core is "one triggering condition + one filtering condition." Finally, I’ll point out four pitfalls that beginners are most likely to fall into. Avoiding these pitfalls will make the indicators you write better than 80% of others.

The first pitfall is not to write too many conditions. Two or three conditions are enough; if you write a bunch of conflicting conditions, you will either get no signals or all the signals will be wrong. The second pitfall is just writing judgments without plotting lines. You must draw reference lines like moving averages and Bollinger Bands; otherwise, when a signal comes out, you won’t know its position, and you will be confused looking at the candlestick chart. The third pitfall is having alerts too frequent. If it pops up reminders tens of times a day, you will definitely turn off notifications, rendering it pointless. Add some filtering conditions; it’s better to have fewer signals but more accurate ones. The fourth pitfall is being overly confident in backtest returns. Backtesting is just a tool, not a holy grail; it can help you avoid obvious pitfalls but cannot guarantee you will definitely make money. In real trading, you must manage risk and test with small positions.

That’s all for today’s content. You can try it out yourself, adding filtering conditions to the indicators you use often, and see if the signals become much more accurate. We’ll continue the discussion on more advanced strategies in our next live session! (Indicator beginner village every Thursday)

This article only represents the author's personal views and does not represent the position or viewpoint of this platform. This article is for information sharing only and does not constitute any investment advice to anyone.

免责声明:本文章仅代表作者个人观点,不代表本平台的立场和观点。本文章仅供信息分享,不构成对任何人的任何投资建议。用户与作者之间的任何争议,与本平台无关。如网页中刊载的文章或图片涉及侵权,请提供相关的权利证明和身份证明发送邮件到support@aicoin.com,本平台相关工作人员将会进行核查。

Share To
APP

X

Telegram

Facebook

Reddit

CopyLink