1st Pine Script Lesson: Coding an Indicator - Bollinger Band
Welcome to this lesson on Trading View, where we will be learning how to create a Bollinger Band indicator using Pine Script.
Bollinger Bands are a popular tool that helps measure an asset's volatility and identify potential trends in price movement. Essentially, the indicator consists of three lines: a middle line that's a simple moving average (SMA), and an upper and lower band that are two standard deviations away from the SMA. The upper band represents the overbought level, meaning the price of the asset is considered high and may be due for a correction. The lower band represents the oversold level, meaning the price is considered low and may be due for a rebound.
Pine Script is a programming language specifically used for creating custom indicators and strategies on Trading View. It's a powerful tool that allows traders to customize their technical analysis to fit their special trading needs and gain deeper insights into the markets..
In this lesson, we'll be taking a hands-on approach to learning. We'll walk through each step of creating our own Bollinger Band indicator using Pine Script, with the goal of helping you gain confidence in your ability to customize and create indicators that meet your unique trading needs. So, grab a cup of coffee and let's get started!
Step 1: Set up a new chart
Let‘s set up a new clean chart to work with for this example. You will find the menu to manage your layouts on the top right of the TradingView screen.
a) add a new layout
b) rename it to „Mizar Example“
c) select BTCUSDT from Binance
d) set the time frame to 1 hour
e) clean the screen (closing the Volume indicator)
f) save it
Step 2: Coding an indicator
Let‘s code our new indicator („Mizar-Killer-Long-Approach“)and make the possible entry moments visible on the chart. You will find the Pine Editor on the bottom left of the TradingView screen.
a) open the Pine Editor
b) use „Open“ in the Pine Editor menu bar
c) use the item: create a new indicator
d) let‘s use full screen for a better overview use the three dots on the right end of the Pine Editor menu bar and open the script in a separate new browser tab
e) rename it to “Mikilap“ by clicking on the current name
f) save it
Step 3: Coding an indicator
Let‘s start coding Our target:
1. create an own new indicator: Mikilap, which bases in general on RSI and Bollinger Band
2. define the parameter for Mikilap, to select the long entries
3. show the long entries on the chart by - putting a label below the bar - change the background color of the timeframe for the bar on the chart
Initiation/Generals
• Indicator initiation
//Indicator script initiation
indicator(title = "Mizar-Killer-Long-Approach", shorttitle = "Mikilap", overlay = true, max_labels_count = 300)
indicator = Pine keyword for an indicator script
title = Long form of the name
short title = Short form of the name as shown on the chart
overlay = true: output like labels, boxes, … are shown on the chart
false: output like plots, … are shown in a separate pane
• General variables and input
// Coin Pair with PREFIX
// Bitcoin / USDT on Binance as an example / standard value on an 60 minutes = 1-hour timeframe
string symbol_full = input.symbol(defval = "BINANCE:BTCUSDT", title = "Select Pair:", group = "General")
string time_frame = input.string(defval = "60", title = "Timeframe:", tooltip = "Value in minutes, so 1 hour = 60", group = "General")
Using the input type of a variable allows you to change this setting in the setup on the chart without changing the Pine Script code.
Framework Code on Main Level
• Framework code on the main level around the indicator calculation function
// Defintion of a Pine Script individual function to handle the Request and avoid Repainting Errors
Function_Mikilap(simple string coinpair, simple string tf_to_use) =>
int function_result = 0
// placeholder for indicator calculations
function_result
// Calling the Milky Way function to start the calculation
int indi_value = Function_Mikilap(symbol_full, time_frame)
Output on the chart - Part 1
// Output on the chart
// Part 1 - plotting a Bollinger Band for the active CoinPair on the chart
int length = input.int(defval = 21, title = "BB Length:", group = "Bollinger Band Setting")
src = input(defval = close, title="BB Source", group = "Bollinger Band Setting")
float mult = input.float(defval = 2.0, title="BB Standard-Deviation", group = "Bollinger Band Setting")
upper_band = ta.sma(src, length) + (mult * ta.stdev(src, length))
lower_band = ta.sma(src, length) - (mult * ta.stdev(src, length))
upper = plot(upper_band, "BB Upper", color=#faffaf)
lower = plot(lower_band, "BB Lower", color=#faffaf)
fill(upper, lower, title = "BB Background", color=color.rgb(245, 245, 80, 80))
Done for today!
• Let‘s save our current script and take a look if we see our Bollinger Band plotted on the chart.
• Step 1: Save (top right)
• Step 2: check in the compiling section, that there are no errors (separate pane below the code)
• Step 3: go to the Mizar Example chart and add an Indicator
How does it look now?
You will see the Bollinger Band as a yellow area around the candles. By pressing the „Settings“ button behind the name of our indicator, the menu for Mikilap will open and you can adjust all the settings we have done with input type variables.
Congrats if you‘ve made it until here! Get prepared for the next lesson, where we will continue with the indicator/entry logic.
Bollingerbandstrategy
USDCAD on a fall USDCAD since early this morning is on a consistent fall on the 15 minute chart.
AMEX:USD Dollar strength issues have continued with the latest hike in prime interest rates
trying to cool down inflation. Canadian dollar is buoyed by the rising spot price of
gold and oil which are more prominent parts of the Canadian economy than they
are in the USA> The chart shows a ride down the lower Bollinger Bands with no
signs of reversal as of yet. As a leveraged forex trade heading into the market close
I will open a good sized position scalping into 5-10 minutes before the close for the
week,
XAGUSD Spot Gold Cup and Handle Bull Trend ResumptionXAUUSD on the daily chart has a long-term cup and handle now in its final formation.
Spot gold price has risen above the lip of the cup and is in position to ascend from there
the height /depth of the cup for about another $100 on the current price based on
the pattern to occur over the width of the cup or about 6-8 months. Any gold related
instruments including miners, junior miners, ETFs like GLD, JNUG , NUGT and
gold itself on the forex markets should be in an overall uptrend. Any further degradation
in the AMEX:USD will further support Spot Gold rising.
Using the Bollinger Band oscillator or Luxalgo I will try to buy when XAUUSD is at the bottom
of the Bollinger Bands ( Red Histogram is high / Green Histogram is low ) and sell in
an opposite fashion with positions on and off to profit from the uptrend ongoing.
Bollinger Bands; Key to boost your profitThe Bollinger Bands indicator is one of the popular technical analysis tools used in Forex trading. Here are some ways you can use Bollinger Bands in Forex trading:
Identifying support and resistance levels
The Bollinger Bands indicator can help you identify support and resistance levels. If the price of a currency pair approaches the lower line of the Bollinger Bands, this may suggest that it is a support level. On the other hand, when the price approaches the upper line, it may suggest that it is a resistance level. You can then look for confirmation of these levels using other indicators or technical analysis methods to decide whether to enter a long or short position.
Identifying trends
The Bollinger Bands indicator can also help you identify trends. If the price of a currency pair exceeds the upper line of the Bollinger Bands, it means that the uptrend will continue, and if the price falls below the lower line, the downtrend will continue. Then you can look for confirmation with other indicators or technical analysis methods to decide whether to enter a long or short position.
Price fluctuation analysis
The Bollinger Bands indicator can also help you analyze price fluctuations. When the prices of a currency pair are close to the lower Bollinger Bands line, it means that the currency pair is undervalued, so you can consider buying. On the other hand, when prices are near the upper line of the Bollinger Bands, it means that the currency pair is overvalued, so you can consider selling.
Detecting periods of volatility
The Bollinger Bands indicator can also help detect periods of volatility. When the Bollinger Bands lines are narrowed, it means that the currency pair is in a period of low volatility, so this may suggest that the following trend or price movement may be sharp. On the other hand, when the lines are widened, it means that the currency pair is in a period of high volatility, so the price movement may be more stable.
In conclusion, the Bollinger Bands indicator can be a useful tool in Forex technical analysis. It can help identify support and resistance levels, identify trends, analyze.
At Manticore investments we use it in conjunction with Haiken Ashi candles and RSI in our scalping - swing strategy. This combination allows us to more effectively read the supports and resistances of the bollinger bands and whether the price will break through them or not.
GBPNZD I STRONG set up coming this week! Here's How to trade it.Welcome back! Let me know your thoughts in the comments!
** GBPNZD Analysis - Listen to video!
We recommend that you keep this pair on your watchlist and enter when the entry criteria of your strategy is met.
Please support this idea with a LIKE and COMMENT if you find it useful and Click "Follow" on our profile if you'd like these trade ideas delivered straight to your email in the future.
Thanks for your continued support!
MAHINDRA & MAHINDRA FINANCIAL SERVICES - Multiple Indicators 📊 Script: M_MFIN (MAHINDRA & MAHINDRA FINANCIAL SERVICES LIMITED)
📊 Nifty50 Stock: NO
📊 Sectoral Index: NIFTY MIDCAP / NIFTY 500 /NIFTY FINANCIAL SERVICES
📊 Sector: Financial Services - Financial Services
📊 Industry: Finance - Non Banking Financial Company (NBFC)
Key highlights: 💡⚡
📈 Script is trading at upper band of Bollinger Bands (BB) and going to give breakout of it.
📈 MACD is giving crossover.
📈 Double Moving Averages also giving crossover.
📈 Volume is increasing along with price which is volume breakout.
📈 Current RSI is around 68.
📈 One can go for Swing Trade.
⏱️ C.M.P 📑💰- 229
🟢 Target 🎯🏆 - 259
⚠️ Stoploss ☠️🚫 - 217
⚠️ Important: Always maintain your Risk & Reward Ratio.
⚠️ Purely technical based pick.
✅Like and follow to never miss a new idea!✅
Disclaimer: I am not SEBI Registered Advisor. My posts are purely for training and educational purposes.
Eat🍜 Sleep😴 TradingView📈 Repeat🔁
Happy learning with trading. Cheers!🥂
CHFJPY 200pips SHORT Idea CHFJPY is getting really weak, SUITE B already confirmed the INCOMING correction leg.
#1 ENTRY (Risk Entry, Good Reward) -: Enter SHORT when CHFJPY reaches UPPER BAND
#2 Entry (Confirmed Entry, Minimal Reward) -: Enter SHORT when CHFJPY breaks BELWO the BL after touching UB. (Not advisable on this current structure)
INVALIDATION
On #1 Entry, Set a 50pips SL from UB tap.
On #2 Entry, when price rejects back BELOW BL , the SUITE INDICATORS will print a SL zone on the chart for you, use it. (OR 50pips)
TARGETS
Target is simple here, we are looking at TP around BL on H4 or PMthH on D1
P.S I will post money making trades like this everyday and everything you see on my chart is
from the HOOD SUITE INDICATORS, everything you need is right in front on you inside the indicator.
(The key zones, Levels for manipulation, visible SL for invalidation, Alert when trade setup is ready).
No trend lines or complicated analysis, all you have to do is FOLLOW!
CADJPY 200pips High Quality SetupCADJPY just hd a massive rally to the upside and soon will be CORRECTING which is why we are looking to enter SHORT at the peak around the PMthH (Previous Month High)
#1 ENTRY (Risk Entry, Good Reward) -: Enter SHORT when price reaches PMthL
#2 Entry (Confirmed Entry, Minimal Reward) -: Enter SHORT when CJ breaks BELWO the BL after touching PMthH.
INVALIDATION
On #1 Entry, Set a 50pips SL from PMthH tap.
On #2 Entry, when price rejects back ABOVE BL , the SUITE INDICATORS will print a SL zone on the chart for you, use it. (OR 50pips)
TARGETS
If the SHORT trigger comes, we are looking to exit at the first EMA Cloud touch on D1.
P.S I will post money making trades like this everyday and everything you see on my chart is
from the HOOD SUITE INDICATORS, everything you need is right in front on you inside the indicator.
(The key zones, Levels for manipulation, visible SL for invalidation, Alert when trade setup is ready).
No trend lines or complicated analysis, all you have to do is FOLLOW!
📊Bollinger Bands In A Trending MarketBollinger Bands are a widely used chart indicator for technical analysis created by John Bollinger in the 1980s. They offer insights into price and volatility and are used in many markets, including stocks, futures, and currencies. Bollinger Bands have multiple uses, such as determining overbought and oversold levels, as a trend following tool, and for monitoring for breakouts.
📍 Strategy
Bollinger Bands measure deviation and can be helpful in diagnosing trends. By generating two sets of bands using different standard deviation parameters, traders can gauge trends and define buy and sell zones. The bands adapt dynamically to price action, widening and narrowing with volatility to create an accurate trending envelope. A touch of the upper or lower band is not a signal in and of itself, and attempting to "sell the top" or "buy the bottom" can lead to losses. Standard deviation is a statistical measure of the amount of variation or dispersion of a set of prices or returns from its average value. The higher the standard deviation, the wider the Bollinger Bands, indicating greater price volatility, and vice versa. Traders may use standard deviation to set stop-loss and take-profit levels or to help determine the risk-to-reward ratio of a trade.
📍 Calculation
First, calculate a simple moving average. Next, calculate the standard deviation over the same number of periods as the simple moving average. For the upper band, add the standard deviation to the moving average. For the lower band, subtract the standard deviation from the moving average.
Typical values used:
Short term: 10 day moving average, bands at 1.5 standard deviations. (1.5 times the standard dev. +/- the SMA)
Medium term: 20 day moving average, bands at 2 standard deviations.
Long term: 50 day moving average, bands at 2.5 standard deviations.
👤 @AlgoBuddy
📅 Daily Ideas about market update, psychology & indicators
❤️ If you appreciate our work, please like, comment and follow ❤️
IOTX/USDT looking good for a potential short! Hey guys 👋
IOTX coin is going to be the first coin of the day. Where currently sitting just below that resistance we see a good potential for a short position here. BUckle up and let's go!
If you like ideas provided by our team you can show us your support by liking and commenting.
Yours Sincerely,
Swallow Team 🔱
Disclamer:
We are not financial advisors. The content that we share on this website are for educational purposes and are our own personal opinions.
Testing a Famous Indicator 2 (& 3) Steps Beyond Moving AveragesSince trading is all about having a statistical edge (well, if you wanna make a living at it)...
How about we use an indicator with deeper insight than averages?
It’s called the Bollinger Band, and it’s what we’re testing today.
What the Heck Is a Bollinger Band?
Without getting all mathy on you (the formula is gnarly), imagine slicing up a regular bell curve in sections.
The middle section (first standard deviation) has about 68% of the data.
A broader chunk (2 standard deviations, which includes the first) has about 95%.
And the widest chunk (3 standard deviations, including the first 2) has 99.7%
Whenever price pierces one of the bands, we look to take a trade. We’ll test this in 3 ways, which we’ll dig into after laying out our basic setup…
The Trading Truth Test Setup
Market: the S&P 500 index (using SPY to trade it, assuming SPY is exactly 1/10th the S&P 500 Index price)
Timeframe: Jan 2, 2008 to March 28, 2023
Bar interval: 1 hour
Moving averages: 50 bars (simple moving averages, meaning every bar gets equal weight, unlike with exponential)
Starting Equity: $25,000
Max % of Equity Per Trade: 3%
Commissions, fees and taxes. To keep things super simple, we’re assuming these are all zero.
Our 3 Tests
Test A:
Any time a high pierces the upper band 2 standard deviations away, go short (if we’re not already in a trade).
Any time a low pierces the upper band 2 standard deviations below, go long (if we’re not already in a trade).
Take profits and losses 2 average true ranges (ATRs) away from the previous close.
Test B:
The same as Test A, except we’ll use 3 standard deviations, instead of 2.
Test C:
Any time a high pierces the 3-standard-deviations upper band, exit a long position and go short.
Any time a low pierces the 3-standard-deviations lower band, exit a short position and go long.
We’re not using ATRs to take profits and losses on this one.
The Test Results
Test A ended down at $20,810.61, down 16.8%. From equity high to equity low, this strategy had a 19.0% drawdown.
Test B ended with $22,818.73. So, we lost 8.7%, with a 9.2% peak-to-trough drawdown. Waiting for price to pierce 3 standard deviations helped reduce our loss.
Test C ended with $25,127.75, a 0.5% gain, with a 15.1% equity high-to-low drawdown.
But but but… buy and hold once again came out the winner by far, up 173.1%.
Note: I did this analysis in a spreadsheet, with exported TradingView data. If you see any errors, please let me know.
What Test Tweaks We Could Make
For Tests A and B, I’d be curious to test waiting for at least a 1-bar price reversal after a Bollinger Band is pierced.
That way, we’d have some momentum back in the trade direction before jumping in.
Test C seems to show this, since we only exit trades when a band gets pierced going in the opposite direction. Still, the results are basically breakeven, so some other rule(s) may help there.
What would you test? And what else would you like to see tested?
Comment below!
ADAUSDT Sleeping Giant: ADVANCE Next ⬆Hi Traders, Investors and Speculators of the Charts 📈📉
Ev here. Been trading crypto since 2017 and later got into stocks. I have 3 board exams on financial markets and studied economics from a top tier university for a year.
In this quick analysis on Cardano, we take a look at:
👉 Bollinger Bands Strategy : What comes next?
👉 Technical Indicator Phoenix Ascending : Where is the short term momentum, bullish or bearish?
👉 Trendline analysis : Local support zone and resistance zones in yellow
👉 Market Cycles : 4 Phases 7 & Wyckoff Method
👉 What NOT to do now
The reasoning behind labelling this post as a "long" , is because I don't believe in trying to catch the exact bottom. this very often leaves you positionless and forces traders to try and jump in whilst the price is going parabolic. With a little more patience, from here the price could easily do a +260%, which is a modest target.
_______________________
📢Follow us here on TradingView for daily updates and trade ideas on crypto , stocks and commodities 💎Hit like & Follow 👍
We thank you for your support !
CryptoCheck
Bitcoin Bullish: Phoenix Asc + BBands🐮Hi Traders, Investors and Speculators of the Charts 📈📉
Ev here. Been trading crypto since 2017 and later got into stocks. I have 3 board exams on financial markets and studied economics from a top tier university for a year.
With a three point analysis today, Bitcoin seems bullish from all perspectives. From a trendline analysis, it seems likely for a weekly close above the immediate resistance zone. From a candlestick analysis, we see a strong week for bulls. Furthermore if we take a look at the Bollinger Bands, we see weekly candle closes way above the basis of the BBands, which indicates a bullish market. And for a final conclusion, we take a look t my favorite technical indicator - the Phoenix Ascending. PA is really a great TA indicator because it contains the RSI, EMA, Momentum and the LSMA (which are all pointing to bullish pressure).
Even IF we see consolidation UNDER this zone, in other words sideways trading in a tight range right underneath the turquoise resistance zone , that would still be considered a bullish sing since it indicates that bulls are weakening the resistance zone .
_______________________
📢Follow us here on TradingView for daily updates and trade ideas on crypto , stocks and commodities 💎Hit like & Follow 👍
We thank you for your support !
CryptoCheck
Bitcoin's Support and Resistance, Navigating the Highs and LowsBitcoin is currently trading at $22,300 area with an RSI of 68.50. The 4-hour timeframe shows that the 0 fibonacci is at 19,549, the 0.5 fibonacci is at 21,105, and the 1 fibonacci is at 22,662. Additionally, the upper Bollinger band is at 22,555, the lower Bollinger band is at 18,900, and the middle Bollinger band is at 20,730. The volume oscillator is -0.70%, MACD is 266, and the stochastic oscillator is at 97. The 4-hour EMA 50 is at 21,456.
Bitcoin recently rallied by 10% to reach $22,000. This indicates a bullish sentiment for Bitcoin and the crypto market as a whole. This can be seen in the current price of Bitcoin at $22,500, which is above the 4-hour EMA 50, indicating that the short-term trend is bullish.
The FDIC is stepping in for Silicon Valley Bank, which indicates a positive move for the crypto market as it implies more institutional support for cryptocurrencies. This could lead to increased demand for Bitcoin, which may drive the price higher.
However, the recent flash spike in the Bitcoin price to $50,000 on Binance, could be a warning sign of the crypto market's volatility. The sudden spike occurred after the USD Coin peg snapped, causing a chain reaction that resulted in a temporary price surge. This event highlights the importance of risk management in cryptocurrency investing.
In conclusion, the current price of Bitcoin at $22,500 with bullish sentiment, increased institutional support, and growing adoption of cryptocurrencies are positive indicators for the future of Bitcoin. However, the recent flash spike and the volatile nature of the crypto market require investors to exercise caution and implement risk management strategies
Bitcoin's key prices can be used to identify potential entry and exit points for traders. The 4-hour timeframe lower Bollinger band at 18,900 is considered a local support level, while the 4-hour timeframe 0.5 fibonacci at 21,105 is a solid support level that could attract buyers and provide a strong base. On the other hand, the 4-hour timeframe upper Bollinger band at 22,555 is a local resistance level, and the 4-hour timeframe 1 fibonacci at 22,662 is a solid resistance level. Breaking above the resistance levels could indicate strong bullish momentum, while breaking below the support levels could signal a bearish sentiment.
It's crucial to note that these key levels are not fixed, and they may change with the market conditions. Therefore, traders should use them as a guide and combine them with other technical indicators and market analysis to make informed trading decisions. If the price breaks below the support levels, it could be a sell signal, while a break above the resistance levels could be a buy signal. Keeping an eye on these key prices can help traders to manage their risk and identify potential trading opportunities.
AUDNZDHi
AUDNZD has been examined in different dimensions:
1- Strong supply and demand levels that I identify with my own indicator and system.
2- The structure of recently formed waves
3- Current market momentum
4- The structure of classical and price patterns
In this idea, I identified the direction of the market in different ways and in the second step, I analyzed the potential of continuation or reversal. Usually, paying attention to the trend and strength of the trend can greatly increase the accuracy of the analysis.
In general, I tried to describe the continuation of the movement in the simplest possible way in the diagram.
⚠️ Disclaimer:
This is a personal opinion and you are responsible for any trading decisions.
Bitcoin - Phoenix Ascending Points $19KHi Traders, Investors and Speculators of the Charts 📈📉
According to the trend analyses that we've been watching, we didn't want to see a candle CLOSE UNDER the current support zone of $21700. From a trendline analysis, the next demand zone would only be at $18400. We can confirm this by pulling up two technical indicators : the Phoenix Ascending and the Bollinger Bands. Together, they point to harsh short term selling pressure. Bears have taken control for the immediate term, and according to the BBands, 19K is a next likely stop for the short term.
However, BTC dropping may not be a bad thing.. for altcoins . Check out this idea:
_______________________
📢Follow us here on TradingView for daily updates and trade ideas on crypto , stocks and commodities 💎Hit like & Follow 👍
We thank you for your support !
CryptoCheck
BONE Countdown has BegunHello fellow traders!
Bone will be the gas of shibarium and the governance token of shib ecosystem..
But always remeber a good analysis have multiple variables (3 scenario: 1:The Bad/ 2: The Good/ 3: The Neutral)
this analysis have only the good (for now) ..
If you liked this idea or if you have your own opinion about it, write in the comments.
Thanks for reading!