Mizar_trading

3rd Pine Script Lesson: Open a command & send it to a Mizar Bot

Education
BINANCE:BTCUSDT   Bitcoin / TetherUS
Welcome back to our TradingView tutorial series! We have reached lesson number 3 where we will be learning how to open a command on TradingView and send it to a Mizar Bot.

If you're new here and missed the first two lessons, we highly recommend starting there as they provide a solid foundation for understanding the concepts we'll be covering today. In the first lesson, you will be learning how to create a Bollinger Band indicator using Pine Script:
In the second lesson, you will be guided through every step of coding the entry logic for your own Bollinger Band indicator using Pine Script:

In this brief tutorial, we'll walk you through the process of utilizing your custom indicator, Mikilap, to determine the ideal timing for sending a standard JSON command to a Mizar DCA bot. By the end of this lesson, you'll have the ability to fine-tune your trading strategies directly on Mizar using indicators from TradingView. So, sit back, grab a cup of coffee (or tea), and let's get started!

To establish a common starting point for everyone, please use the following code as a starting point. It incorporates the homework assignment from our Pine Script lesson number 2. By using this code as our foundation, we can collectively build upon it and delve into additional concepts together. So, sit back, grab a cup of coffee (or tea), and let's get started!

// This source code is subject to the terms of the Mozilla Public License 2.0 at mozilla.org/MPL/2.0/
// Mizar Example Code - Lesson I - Coding an indicator
// version 1.0 - April 2023
// Intellectual property © Mizar.com

// Mizar-Killer-Long-Approach ("Mikilap")

//@version=5

// Indicator script initiation
indicator(title = "Mizar-Killer-Long-Approach", shorttitle = "Mikilap", overlay = true, max_labels_count = 300)

// Coin Pair with PREFIX
// Bitcoin / USDT on Binance as 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")

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

int     length_rsi  = input.int(defval = 12, title = "RSI Length:", group = "RSI Setting")
src_rsi             = input(defval = low, title="RSI Source;", group = "RSI Setting")
int     rsi_min     = input.int(defval = 25, title = "", inline = "RSI band", group = "RSI Setting")
int     rsi_max     = input.int(defval = 45, title = " < min RSI max > ", inline = "RSI band", group = "RSI Setting")

// 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])

// Bollinger part of MIKILAP
  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

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

// RSI part of MIKILAP
src_sb = switch src_rsi
       open => open_R
       high => high_R
       low  => low_R
       => close_R
  
   rsi_val                             = ta.rsi(src_sb, length_rsi)

   bool rsi_entry = rsi_min < rsi_val and rsi_max > rsi_val and barstate_info

// Check if all criteria are met
 if bb_entry[1] and rsi_entry[1]
       function_result += 1

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

   function_result

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

// Output on the chart
// plotting a band around the lower bandwith 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))


Open a command to send to a Mizar Bot.

Let‘s continue coding


Our target: Use our own indicator: Mikilap, to define the timing to send a standard JSON command to a Mizar DCA bot.
(1) define the JSON command in a string, with variables for
- API key
- BOT id
- BASE asset (coin to trade)
(2) send the JSON command at the beginning of a new bar
(3) setup the TradingView alert to transport our JSON command via
Webhook/API to the Mizar DCA bot

Below you can see the code, which defines the individual strings to prepare the JSON command. In the following, we will explain line by line, what each individual string and command is used for.

// 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, )

//Text-strings for alerts via API / Webhook
   string api_key             = "top secret"                                  // API key from MIZAR account
   string symbol_prefix       = str.replace(symbol_full, "BINANCE:", "", 0)
   string symbol_name         = str.replace(symbol_prefix, "USDT", "", 0)
   string bot_id              = "0000"                                        // BOT id from MIZAR DCA bot

// String with JSON command as defined in format from MIZAR.COM
// BOT id, API key and the BASE asset are taken from separate variables

DCA bot identifier:
   string api_key             = "top secret"                                  
   string bot_id              = "0000" 

These both strings contain the info about your account (BOT owner) and the unique id of your bot, which should receive the JSON command.

BASE asset:
string symbol_prefix       = str.replace(symbol_full, "BINANCE:", "", 0)
   string symbol_name         = str.replace(symbol_prefix, "USDT", "", 0)

The shortcut of the base asset will be taken out of the complete string for the coin pair by cutting out the CEX identifier and the quote asset.

JSON command for opening a position:
Entry_message       = '{ "bot_id": "' + bot_id + '", "action": "' + "open-position" + '", "base_asset": "' + symbol_name + '", "quote_asset": "' + "USDT" + '", "api_key": "' + api_key + '" }'

If you want to have more info about all possible JSON commands for a DCA bot, please look into Mizar‘s docs: docs.mizar.com/mizar.../dca-bot-tradingview

  • As the JSON syntax requires quotation marks (“) as part of the command, we define the string for the entry message with single quotations ('). So please ensure to open and close these quotations before or after each operator (=, +, …).

  • Current status:
- We have the entry logic and show every possible entry on the chart => label.
- We have the JSON command ready in a combined string (Entry_message) including the BOT identifier (API key and BOT id) as well as the coin pair to buy.

  • What is missing?
- To send this message at the opening of a new bar as soon as the entry logic is true. As we know these moments already, because we are placing a label on the chart, we can use this condition for the label to send the message as well.

  • alert(): built-in function
- We recommend checking the syntax and parameters for alert() in the Pine Script Reference Manual. As we want to send only one opening command, we are using the alert.freq_once_per_bar. To prepare for more complex Pine Scripts, we have placed the alert() in a separate local scope of an if condition, which is not really needed in this script as of now.

if bb_entry[1] and rsi_entry[1]
       function_result += 1
  
   if function_result == 1
       alert(Entry_message, alert.freq_once_per_bar)


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

  • IMPORTANT REMARK:
    Do not use this indicator for real trades! This example is for educational purposes only!

  • Configuration of the TradingView alert: on the top right of the chart screen, you will find the clock, which represents the alert section

a) click on the clock to open the alert section
b) click on the „+“ to create a new alert

c) set the condition to our indicator Mikilap and the menu will change its format (configuration of the TradingView alert)

For our script nothing else is to do (you may change the expiration date and alert name), except to add the Webhook address in the Notification tab.


Congratulations on finishing the third lesson on TradingView - we hope you found it informative and engaging! You are now able to code a well-working easy Pine Script indicator, which will send signals and opening commands to your Mizar DCA bot.

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 TradingView 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.