Mizar_trading

2nd Pine Script Lesson: Coding the Entry Logic - Bollinger Band

Education
BINANCE:BTCUSDT   Bitcoin / TetherUS
Welcome back to our Trading View tutorial series! In this second lesson, be learning how to code the entry logic for a Bollinger Band indicator using Pine Script.

If you're new here and missed the first lesson, we highly recommend starting there as it provides a solid foundation for understanding the concepts we'll be covering today:
In this hands-on lesson, we'll guide you through every step of coding the entry logic for your own Bollinger Band indicator using Pine Script. By the end of this lesson, you'll have a functional indicator that you can use to inform your trading decisions. So, sit back, grab a cup of coffee, and let's get started!

Code the entry logic

a) This is where we are calling the Mikilap function with two arguments:
- the coinpair and
- the timeframe we want to use.

// Calling the Mikilap function to start the calculation

int indi_value = Function_Mikilap(symbol_full, time_frame)


b) In the function initiation we convert the strings into simple strings.

// Definition of a Pine Script individual function to handle the Request and avoid Repainting Errors

Function_Mikilap(simple string coinpair, simple string tf_to_use) =>


c) As we are calling the function to get an integer value, we have to define an output variable as an integer and place this variable as the last line in the local scope of the function code to return the integer value.

    int function_result = 0

    // placeholder for indicator calculations

    function_result

Step 1:
Using the lower bandwidth of the Bollinger Band based on SMA (close, 21) and a standard deviation of 2.0 and try to highlight bars, where close is next to the lower band


a) Requesting the values for the coinpair with request.security()

[open_R, high_R, low_R, close_R] = request.security(coinpair, tf_to_use, [open, high, low, close]) 

We recommend using repainting functions like request or barstate only in a local scope (inside a function) and not to request complex calculated values. For saving calculation capacity it is useful to only request the classic four OHLCs and do any calculation with these four after the request.security().


b) Calculation of the lower Bollinger Bands values as we need the global info, which type of source, length, and deviation value to use for the calculation, let‘s cut & paste the input for the Bollinger Band in the general starting section of the code and as we want to look for close values „next“ to the lower bandwidth, we need to define what „next“ means; let‘s do it in another input variable, perhaps we want to play with the definition later.

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")

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")
float lower_dev = input.float(defval = 0.1, title="BB Lower Deviation in %", group = "Bollinger Band Setting")/100 

First, let‘s make it visible on the chart by re-writing the Bollinger Bandplot, which is not needed anymore.

// Calling the Mikilap function to start the calculation

int indi_value = Function_Mikilap(symbol_full, time_frame)

// Output on the chart
// Part 2 - plotting a Band around the lower bandwidth of a Bollinger Band for the active CoinPair on the chart

lower_bb            = ta.sma(src, length) - (mult*ta.stdev(src, length))
lower_bb_devup      = lower_bb + lower_bb * lower_dev
lower_bb_devdown    = lower_bb - lower_bb * lower_dev

upper = plot(lower_bb_devup, "BB Dev UP", color=#faffaf)
lower = plot(lower_bb_devdown, "BB Dev DOWN", color=#faffaf)
fill(upper, lower, title = "BB Dev Background", color=color.rgb(245, 245, 80, 80))


c) Now we use the same calculation for the coinpair inside the function and start with the selection of the source (OHLC) to use, which is activein the respective input variable.

// 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
    bool barstate_info = barstate.isconfirmed

    [open_R, high_R, low_R, close_R] = request.security(coinpair, tf_to_use,[open, high, low, close])

    src_cp = switch src
        open => open_R
        high => high_R
        low => low_R
        => close_R
    
    lower_band_cp                   = ta.sma(src_cp,length) - (mult*ta.stdev(src_cp, length))
    lower_band_cp_devup            = lower_band_cp + lower_band_cp * lower_dev
    lower_band_cp_devdown           = lower_band_cp - lower_band_cp * lower_dev

// placeholder for indicator calculations


d) As the bandwidth for the interesting close values is defined by our band, the only thing missing for the part of the Bollinger Band in our Mikilap indicator is to check if the close value of a bar is inside our band. As we are talking about closed bars, let‘s be sure that it is really closed by using barstate.isconfirmed (repainting built-in function!) and save it in a variable in the head of the function to avoid requesting this info too often.

bool barstate_info = barstate.isconfirmed

Now let‘s check if the close value of a bar is inside our band.

bool bb_entry = close_R < lower_band_cp_devup and close_R > lower_band_cp_devdown and barstate_info

And increase the output variable by 1 in case the close value is inside.

if bb_entry[1]
   function_result += 1

By using bb_entry, we are referring to the last bar next to the actual bar, because we want to enter on the opening of the bar after the criteria has been met.


e) And to make these possible entries visible, we want to place a label below the bar and show the entry price (=open value of the bar) as mouseover (tooltip). This should only happen if the active coinpair on the chart is the same coinpair, which is in the calculation of the function.

 if function_result == 1 and ticker.standard(syminfo.tickerid) == coinpair
        label LE_arrow = label.new(x = bar_index, y = low_R, text = "\n ↑ \n LE", yloc = yloc.belowbar, color = color.rgb(255,255,255,25),style = label.style_none, textcolor = color.white, tooltip = str.tostring(open_R))


Note:
You will love labels (!) and in case you are looking for text symbols that can be used as labels, look here: www.messletters.com/en/symbols/

If you need help use the Pine Script Reference Manual, which explains 99% of everything in Pine Script, here: www.tradingview.com/...script-reference/v5/


f) As our function now returns different integer values (0 or 1), we can use this info to color the background on the actual chart in case it is 1.

// Calling the Mikilap function to start the calculation

int indi_value = Function_Mikilap(symbol_full, time_frame)

color bg_color      = indi_value ? color.rgb(180,180,180,75) : color.rgb(25,25,25,100)
bgcolor(bg_color)


g) To finish this little Pine Script lesson and to achieve our initial targets, we just need to integrate the second indicator (RSI) into the function. We want to use the RSI for 0,5 days (12 hours) and use it to ensure to not go into a long entry in an oversold (< 25) or overbought (> 70) market. We will use RSI (low, 12) within 25 to 45 as the range to go for.


Your tasks:
  • define new input variables for RSI: src_rsi and length_rsi
  • define new input variables for the RSI range we want to use: rsi_minand rsi_max(please use the „inline“ format of an input type)
  • calculate the RSI (src_rsi, length_rsi) inside our Mikilap-function
  • define a boolean variable (rsi_entry) to check if the calculated RSI value is inside the range (please add as last check the barstate_info)
  • add the RSI entry check to the Bollinger Band entry check to combine them


Congratulations on finishing the second lesson on Trading View - we hope you found it informative and engaging!

We're committed to providing you with valuable insights and practical knowledge throughout this tutorial series. So, we'd love to hear from you! Please leave a comment below with your suggestions on what you'd like us to focus on in the next lesson.

Thanks for joining us on this learning journey, and we're excited to continue exploring Trading View with you!

Disclaimer

The information and publications are not meant to be, and do not constitute, financial, investment, trading, or other types of advice or recommendations supplied or endorsed by TradingView. Read more in the Terms of Use.