Strategy · Pine Script v5 · On the chart

Automatic Grid Bot Strategy

by hasnocool· code credited to lovealgotrading

Automatic Grid Bot Strategy simulates a grid trading system directly on the main price chart.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code618
Settings24inputs
LicenceGPL-3.0
Last update2 years ago18 Sep 2024

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

618 lines of Pine Script v5 from AUTOMATIC GRID BOT STRATEGY [ilovealgotrading].pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

AUTOMATIC GRID BOT STRATEGY [ilovealgotrading].pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © lovealgotrading
// First of all I want to say thank you to © thequantscience. 
//@version=5
strategy(
     title = 'AUTOMATIC GRID BOT STRATEGY [lovealgotrading]', 
     overlay = true,
     commission_type = strategy.commission.percent, 
     commission_value = 0.075, 
     pyramiding = 20,
     default_qty_type = strategy.percent_of_equity,
     close_entries_rule = 'ANY',
     initial_capital = 1000
     )
/////////////////////////////// ALGORITHM BACKTEST SOURCE CODE ////////////////////////////////////
startDate  = input.time(defval=timestamp('1 nov 2022 13:30 +0000'), title='Start_Date', group = " ############# ⏰ BACKTEST DATE ⏰ ############ " )
endDate = input.time(defval=timestamp('20 oct  2030 13:30 +0000'), title='End_Date', group = " ############# ⏰ BACKTEST DATE ⏰ ############ " )
inDateRange  = time > startDate  and time < endDate
high_price = input.price(
      defval = 0.00, 
      title = 'Range High price: ',
      group = " ############## ➡️ HIGH GRID PRICE  ⬅️ ############ ", 
      confirm = true,
      tooltip = "Top grid price."
      )
low_price = input.price(
      defval = 0.00, 
      title = 'Range Low price: ',
      group = " ############## ➡️ LOW GRID PRICE  ⬅️ ############# ", 
      confirm = true,
      tooltip = "Bottom grid price."
      )
// ###########################################################################################
trade_direction = input.string(title='Trade Direction', group = " ##############🎯 TRADE DIRECTION 🎯############# ", options=['LONG', 'SHORT', 'BOTH'], defval='BOTH')
// ###########################################################################################
use_stop = input.bool(defval = false , title = "Use StopLoss", group = " ############# ⛔️ Strategy STOP Settings ⛔️ ############ ")
close_bot_after_stop = input.bool(defval = false , title = "Close Bot After Stop Loss",tooltip = "Dont open new positions after stop loss", group = " ############# ⛔️ Strategy STOP Settings ⛔️ ############ ")
stop_close_all = ""
if stop_close_all[1] != "" and close_bot_after_stop
    stop_close_all := "DONT"
use_stop_default = input.bool(defval = true , title = "Use StopLoss Where HIGH and LOW GRID PRICE", group = " ############# ⛔️ Strategy STOP Settings ⛔️ ############ ")
high_price_stop = input.price(
      defval = 99999, 
      title = 'High STOP Price: ',
      group =  " ############# ⛔️ Strategy STOP Settings ⛔️ ############ ", 
      confirm = false,
      tooltip = "Top STOP price."
      )
low_price_stop = input.price(
      defval = 0.00, 
      title = 'Low STOP Price: ',
      group =  " ############# ⛔️ Strategy STOP Settings ⛔️ ############ ", 
      confirm = false,
      tooltip = "Bottom STOP price."
      )
if use_stop_default 
    high_price_stop := high_price
    low_price_stop := low_price
// ###########################################################################################
dolar = input.int(defval = 100, title = "$ Per Position", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
// ###########################################################################################
Long_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
Long_Exit_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
Long_Stop_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
Short_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
Short_Exit_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
Short_Stop_message = input("", group = " ############# 🤖 ALGO TRADE ALERTS 🤖 ############ ")
// ###########################################################################################
float qty_new = dolar / close 
if close > 5000 
    qty_new :=  math.round(dolar / close, 3)
else if close < 5000 and close > 200
    qty_new :=  math.round(dolar / close, 2)
else if close < 200 and close > 50
    qty_new :=  math.round(dolar / close, 1)
else if close < 50
    qty_new :=  math.round(dolar / close, 0)
// ###########################################################################################
ten_grid = input.bool(
     defval = false,
     title = "10 grid levels",
     group = " ############ GRID CONFIGURATION ############ ",
     tooltip = "10 grid levels",
     confirm = true
     )
tewnty_grid = input.bool(
     defval = true,
     title = "20 grid levels",
     group = " ############ GRID CONFIGURATION ############ ",
     tooltip = "20 grid levels",
     confirm = true
     )
// ###########################################################################################
show_stop_res = input.bool(true, title = "Show Stop Price",group = " ############# 📈 Graphics Settings 📈 ########### ")
show_grid_level_bg = input.bool(true, title = "Show Grid Levels BG",group = " ############# 📈 Graphics Settings 📈 ########### ")
// ###########################################################################################
grid_range = high_price - low_price
percent_change = ((high_price - low_price) / low_price) * (1.00 / 9.00)
var float grid_1 = 0
var float grid_2 = 0
var float grid_3 = 0
var float grid_4 = 0
var float grid_5 = 0
var float grid_6 = 0
var float grid_7 = 0
var float grid_8 = 0
var float grid_9 = 0
var float grid_10 = 0
var float grid_11 = 0
var float grid_12 = 0
var float grid_13 = 0
var float grid_14 = 0
var float grid_15 = 0
var float grid_16 = 0
var float grid_17 = 0
var float grid_18 = 0
var float grid_19 = 0
var float grid_20 = 0
var float factor = 0 
long_1 = false
long_2 = false
long_3 = false
long_4 = false
long_5 = false
long_6 = false
long_7 = false
long_8 = false
long_9 = false
long_10 = false
short_1 = false
short_2 = false
short_3 = false
short_4 = false
short_5 = false
short_6 = false
short_7 = false
short_8 = false
short_9 = false
short_10 = false
if ten_grid == true
    percent_change := ((high_price - low_price) / low_price) * (1.00 / 9.00)
    factor := grid_range / 9
    grid_1 := (high_price) 
    grid_2 := (high_price - (factor * 1)) 
    grid_3 := (high_price - (factor * 2)) 
    grid_4 := (high_price - (factor * 3)) 
    grid_5 := (high_price - (factor * 4)) 
    grid_6 := (high_price - (factor * 5)) 
    grid_7 := (high_price - (factor * 6)) 
    grid_8 := (high_price - (factor * 7)) 
    grid_9 := (high_price - (factor * 8))
    grid_10 := (low_price)
    long_1 := ta.crossunder(close, ((grid_5+grid_6)/2)) 
    long_2 := ta.crossunder(close, ((grid_6+grid_7)/2)) 
    long_3 := ta.crossunder(close, ((grid_7+grid_8)/2)) 
    long_4 := ta.crossunder(close, ((grid_8+grid_9)/2)) 
    long_5 := ta.crossunder(close, ((grid_9+grid_10)/2)) 
    short_1 := ta.crossover(close, ((grid_6+grid_5)/2))
    short_2 := ta.crossover(close, ((grid_5+grid_4)/2))
    short_3 := ta.crossover(close, ((grid_4+grid_3)/2))
    short_4 := ta.crossover(close, ((grid_3+grid_2)/2))
    short_5 := ta.crossover(close, ((grid_2+grid_1)/2))
if tewnty_grid == true
    percent_change := ((high_price - low_price) / low_price) * (1.00 / 19.00)
    factor := grid_range / 19
    grid_1 := (high_price) 
    grid_2 := (high_price - (factor * 1)) 
    grid_3 := (high_price - (factor * 2)) 
    grid_4 := (high_price - (factor * 3)) 
    grid_5 := (high_price - (factor * 4)) 
    grid_6 := (high_price - (factor * 5)) 
    grid_7 := (high_price - (factor * 6)) 
    grid_8 := (high_price - (factor * 7)) 
    grid_9 := (high_price - (factor * 8)) 
    grid_10 := (high_price - (factor * 9)) 
    grid_11 := (high_price - (factor * 10)) 
    grid_12 := (high_price - (factor * 11)) 
    grid_13 := (high_price - (factor * 12)) 
    grid_14 := (high_price - (factor * 13)) 
    grid_15 := (high_price - (factor * 14)) 
    grid_16 := (high_price - (factor * 15)) 
    grid_17 := (high_price - (factor * 16)) 
    grid_18 := (high_price - (factor * 17)) 
    grid_19 := (high_price - (factor * 18))
    grid_20 := (low_price)
    long_1 := close < ((grid_10+grid_11)/2)
    long_2 := close < ((grid_11+grid_12)/2)
    long_3 := close < ((grid_12+grid_13)/2)
    long_4 := close < ((grid_13+grid_14)/2)
    long_5 := close < ((grid_14+grid_15)/2) 
    long_6 := close < ((grid_15+grid_16)/2) 
    long_7 := close < ((grid_16+grid_17)/2) 
    long_8 := close < ((grid_17+grid_18)/2) 
    long_9 := close < ((grid_18+grid_19)/2) 
    long_10 := close < ((grid_19+grid_20)/2) 
    short_10 := close >((grid_1+grid_2)/2)
    short_9 := close >((grid_2+grid_3)/2)
    short_8 := close >((grid_3+grid_4)/2)
    short_7 := close >((grid_4+grid_5)/2)
    short_6 := close >((grid_5+grid_6)/2)
    short_5 := close >((grid_6+grid_7)/2)
    short_4 := close >((grid_7+grid_8)/2)
    short_3 := close >((grid_8+grid_9)/2)
    short_2 := close >((grid_9+grid_10)/2)
    short_1 := close > ((grid_10+grid_11)/2)
// ###########################################################################################
// ###########################################################################################
if ten_grid and ( trade_direction == 'LONG' or trade_direction == 'BOTH')
    if long_1 and strategy.opentrades == 0  and inDateRange  and stop_close_all == ""
        strategy.entry(id = "L_1",  direction =   strategy.long,alert_message = Long_message,  qty = qty_new   )
         
    if strategy.opentrades == 1 
        strategy.exit(id = "E_1",from_entry = "L_1", qty_percent = 100,alert_message =Long_Exit_message,stop = 0, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
           
    if long_2 and strategy.opentrades == 1  and inDateRange    and stop_close_all == ""
        strategy.entry(id = "L_2",   direction =   strategy.long,alert_message = Long_message,  qty = qty_new  )
                   
    if strategy.opentrades == 2
        strategy.exit(id = "E_2",from_entry = "L_2", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
           
    if long_3 and strategy.opentrades == 2  and inDateRange  and stop_close_all == ""
        strategy.entry(id = "L_3",  direction =   strategy.long,alert_message = Long_message, qty = qty_new  )
                    
    if strategy.opentrades == 3
        strategy.exit(id = "E_3",from_entry = "L_3", qty_percent = 100,alert_message =Long_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
            
    if long_4 and strategy.opentrades == 3  and inDateRange    and stop_close_all == ""
        strategy.entry(id = "L_4",  direction =   strategy.long,alert_message = Long_message, qty = qty_new  )
                    
            
    if strategy.opentrades == 4
        strategy.exit(id = "E_4",from_entry = "L_4", qty_percent = 100,alert_message =Long_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
            
    if long_5 and strategy.opentrades == 4  and inDateRange  and stop_close_all == ""
        strategy.entry(id = "L_5",   direction =   strategy.long,alert_message = Long_message,  qty = qty_new  )
                   
    if strategy.opentrades == 5
        strategy.exit(id = "E_5",from_entry = "L_5", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
    
// ###########################################################################################
if ten_grid and ( trade_direction == 'SHORT' or trade_direction == 'BOTH')
    if short_1 and strategy.opentrades == 0  and inDateRange   and stop_close_all == ""
        strategy.entry(id = "S_1",  direction =  strategy.short,alert_message = Short_message, qty = qty_new   )
                        
    if strategy.opentrades == 1
        strategy.exit(id = "ES_1",from_entry = "S_1", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
            
    if short_2 and strategy.opentrades == 1  and inDateRange   and stop_close_all == ""
        strategy.entry(id = "S_2",direction =  strategy.short,alert_message = Short_message,  qty = qty_new   )
                    
        
    if strategy.opentrades == 2
        strategy.exit(id = "ES_2",from_entry = "S_2", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
            
    if short_3 and strategy.opentrades == 2  and inDateRange   and stop_close_all == ""
        strategy.entry(id = "S_3",   direction =  strategy.short,alert_message = Short_message,  qty = qty_new   )
                               
    if strategy.opentrades == 3 
        strategy.exit(id = "ES_3",from_entry = "S_3", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
            
    if short_4 and strategy.opentrades == 3  and inDateRange   and stop_close_all == ""
        strategy.entry(id = "S_4",   direction =  strategy.short,alert_message = Short_message, qty = qty_new    )
                        
            
    if strategy.opentrades == 4 
        strategy.exit(id = "ES_4",from_entry = "S_4", qty_percent = 100,alert_message =Short_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
            
    if short_5 and strategy.opentrades == 4  and inDateRange   and stop_close_all == ""
        strategy.entry(id = "S_5",  direction =  strategy.short,alert_message = Short_message,  qty = qty_new   )
                    
    if strategy.opentrades == 5 
        strategy.exit(id = "ES_5",from_entry = "S_5", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
    
// ###########################################################################################
// ###########################################################################################
long_exit_price = str.tostring(math.round_to_mintick(close*(1+percent_change)))
short_exit_price = str.tostring(math.round_to_mintick(close*(1-percent_change))) 
if  tewnty_grid and close > low_price and ( trade_direction == 'LONG' or trade_direction == 'BOTH')
    if long_1 and strategy.opentrades == 0  and inDateRange  and stop_close_all == ""
        strategy.entry(id = "L_1",  direction =  strategy.long,alert_message = Long_message,  qty = qty_new    )
         
    if strategy.opentrades == 1 
        strategy.exit(id = "E_1",from_entry = "L_1", qty_percent = 100,alert_message = Long_Exit_message,stop = 0, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
           
    if long_2 and strategy.opentrades == 1  and inDateRange   and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
        strategy.entry(id = "L_2",   direction =  strategy.long,alert_message = Long_message,  qty = qty_new   )
                   
    if strategy.opentrades == 2
        strategy.exit(id = "E_2",from_entry = "L_2", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
           
    if long_3 and strategy.opentrades == 2  and inDateRange   and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
        strategy.entry(id = "L_3",  direction =  strategy.long,alert_message = Long_message, qty = qty_new   )
                    
    if strategy.opentrades == 3
        strategy.exit(id = "E_3",from_entry = "L_3", qty_percent = 100,alert_message =Long_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
            
    if long_4 and strategy.opentrades == 3  and inDateRange   and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
        strategy.entry(id = "L_4",  direction =  strategy.long,alert_message = Long_message, qty = qty_new   )
                    
            
    if strategy.opentrades == 4
        strategy.exit(id = "E_4",from_entry = "L_4", qty_percent = 100,alert_message =Long_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
            
    if long_5 and strategy.opentrades == 4  and inDateRange   and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
        strategy.entry(id = "L_5",   direction =  strategy.long,alert_message = Long_message,  qty = qty_new   )
                   
    if strategy.opentrades == 5
        strategy.exit(id = "E_5",from_entry = "L_5", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
    
    if long_6 and strategy.opentrades == 5  and inDateRange   and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
        strategy.entry(id = "L_6",   direction =  strategy.long,alert_message = Long_message,  qty = qty_new   )
                   
    if strategy.opentrades == 6
        strategy.exit(id = "E_6",from_entry = "L_6", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
    
    if long_7 and strategy.opentrades == 6  and inDateRange   and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
        strategy.entry(id = "L_7",   direction =  strategy.long,alert_message = Long_message,  qty = qty_new   )
                   
    if strategy.opentrades == 7
        strategy.exit(id = "E_7",from_entry = "L_7", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
    
    if long_8 and strategy.opentrades == 7  and inDateRange   and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
        strategy.entry(id = "L_8",   direction =  strategy.long,alert_message = Long_message,  qty = qty_new   )
                   
    if strategy.opentrades == 8
        strategy.exit(id = "E_8",from_entry = "L_8", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
    
    if long_9 and strategy.opentrades == 8  and inDateRange   and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
        strategy.entry(id = "L_9",   direction =  strategy.long,alert_message = Long_message,  qty = qty_new   )
                   
    if strategy.opentrades == 9
        strategy.exit(id = "E_9",from_entry = "L_9", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
                     
    if long_10 and strategy.opentrades == 9  and inDateRange   and close < strategy.opentrades.entry_price(strategy.opentrades - 1) * (1-percent_change) and stop_close_all == ""
        strategy.entry(id = "L_10",   direction =  strategy.long,alert_message = Long_message,  qty = qty_new   )
                   
    if strategy.opentrades == 10
        strategy.exit(id = "E_10",from_entry = "L_10", qty_percent = 100,alert_message =Long_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change))
// ##### STOP LOSS CODES  #####
if  use_stop and   low < low_price_stop and strategy.position_size > 0
    strategy.close_all(alert_message =Long_Stop_message, immediately = true)
    stop_close_all := "DONT"
// ###########################################################################################
if tewnty_grid and close < high_price and ( trade_direction == 'SHORT' or trade_direction == 'BOTH')
    if short_1 and strategy.opentrades == 0  and inDateRange   and stop_close_all == ""
        strategy.entry(id = "S_1",  direction =  strategy.short,alert_message = Short_message, qty = qty_new    )
                    
    if strategy.opentrades == 1
        strategy.exit(id = "ES_1",from_entry = "S_1", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
            
    if short_2 and strategy.opentrades == 1  and inDateRange   and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
        strategy.entry(id = "S_2",direction =  strategy.short,alert_message = Short_message,  qty = qty_new    )
                                   
    if strategy.opentrades == 2
        strategy.exit(id = "ES_2",from_entry = "S_2", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
            
    if short_3 and strategy.opentrades == 2  and inDateRange   and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
        strategy.entry(id = "S_3",   direction =  strategy.short,alert_message = Short_message,  qty = qty_new    )
                    
            
    if strategy.opentrades == 3 
        strategy.exit(id = "ES_3",from_entry = "S_3", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
            
    if short_4 and strategy.opentrades == 3  and inDateRange   and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
        strategy.entry(id = "S_4",   direction =  strategy.short,alert_message = Short_message, qty = qty_new     )
                        
            
    if strategy.opentrades == 4 
        strategy.exit(id = "ES_4",from_entry = "S_4", qty_percent = 100,alert_message =Short_Exit_message,limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
            
    if short_5 and strategy.opentrades == 4  and inDateRange   and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
        strategy.entry(id = "S_5",  direction =  strategy.short,alert_message = Short_message,  qty = qty_new    )
                    
    if strategy.opentrades == 5 
        strategy.exit(id = "ES_5",from_entry = "S_5", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
    
    
    if short_6 and strategy.opentrades == 5  and inDateRange   and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
        strategy.entry(id = "S_6",  direction =  strategy.short,alert_message = Short_message,  qty = qty_new    )
                    
    if strategy.opentrades == 6 
        strategy.exit(id = "ES_6",from_entry = "S_6", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
        
    if short_7 and strategy.opentrades == 6  and inDateRange   and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
        strategy.entry(id = "S_7",  direction =  strategy.short,alert_message = Short_message,  qty = qty_new    )             
    if strategy.opentrades == 7 
        strategy.exit(id = "ES_7",from_entry = "S_7", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
       
    if short_8 and strategy.opentrades == 7  and inDateRange   and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
        strategy.entry(id = "S_8",  direction =  strategy.short,alert_message = Short_message,  qty = qty_new    )             
    if strategy.opentrades == 8 
        strategy.exit(id = "ES_8",from_entry = "S_8", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
    
    if short_9 and strategy.opentrades == 8  and inDateRange   and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
        strategy.entry(id = "S_9",  direction =  strategy.short,alert_message = Short_message,  qty = qty_new    )             
    if strategy.opentrades == 9 
        strategy.exit(id = "ES_9",from_entry = "S_9", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
    
    if short_10 and strategy.opentrades == 9  and inDateRange   and close > strategy.opentrades.entry_price(strategy.opentrades - 1) * (1+percent_change) and stop_close_all == ""
        strategy.entry(id = "S_10",  direction =  strategy.short,alert_message = Short_message,  qty = qty_new    )             
    if strategy.opentrades == 10
        strategy.exit(id = "ES_10",from_entry = "S_10", qty_percent = 100,alert_message =Short_Exit_message, limit = strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change))
// ###########################################################################################
if  use_stop and  high > high_price_stop and strategy.position_size < 0
    strategy.close_all(alert_message =Short_Stop_message, immediately = true)
    stop_close_all := "DONT"
bgcolor(stop_close_all == "DONT" and stop_close_all[1] != "DONT" ? color.rgb(255, 42, 42) : na )
//// ########################################################################
// Plot Functions
plot(strategy.position_size < 0 ? strategy.opentrades.entry_price(strategy.opentrades - 1)*(1-percent_change) : na , color= color.rgb(247, 85, 85), linewidth= 1, style=plot.style_cross)
plot(strategy.position_size > 0 ? strategy.opentrades.entry_price(strategy.opentrades - 1)*(1+percent_change) : na , color= color.rgb(136, 247, 85), linewidth= 1, style=plot.style_cross)
plot(inDateRange ? high_price_stop : na, color= color.rgb(255, 37, 37), linewidth =4 )
plot(inDateRange ? low_price_stop : na, color= color.rgb(255, 34, 37), linewidth =4 )
plot(inDateRange ? high_price : na, color= color.rgb(0, 0, 0), linewidth =3 )
plot(inDateRange ? low_price : na, color= color.rgb(255, 255, 255), linewidth =3 )
plot(inDateRange ? (high_price + low_price) / 2 : na , color= color.rgb(0, 68, 255), linewidth = 2 )
// ###########################################################################################
var float new_ten_grid_1 = na 
var float new_ten_grid_2 = na 
var float new_ten_grid_3 = na 
var float new_ten_grid_4 = na 
var float new_ten_grid_5 = na 
var float new_ten_grid_6 = na 
var float new_ten_grid_7 = na 
var float new_ten_grid_8 = na 
var float new_ten_grid_9 = na 
var float new_ten_grid_10 = na 
if ten_grid == true and show_grid_level_bg and inDateRange 
    new_ten_grid_1 := grid_1
    new_ten_grid_2 := grid_2
    new_ten_grid_3 := grid_3
    new_ten_grid_4 := grid_4
    new_ten_grid_5 := grid_5
    new_ten_grid_6 := grid_6
    new_ten_grid_7 := grid_7
    new_ten_grid_8 := grid_8
    new_ten_grid_9 := grid_9
    new_ten_grid_10 := grid_10
else if ten_grid == false
    new_ten_grid_1 := na
    new_ten_grid_2 := na
    new_ten_grid_3 := na
    new_ten_grid_4 := na
    new_ten_grid_5 := na
    new_ten_grid_6 := na
    new_ten_grid_7 := na
    new_ten_grid_8 := na
    new_ten_grid_9 := na
    new_ten_grid_10 := na
fill(plot(inDateRange ? new_ten_grid_1 : na , color = color.new(color.green, 90)), 
     plot(inDateRange ? new_ten_grid_2 : na , color = color.new(color.green, 90)), 
         color = color.new(color.green, 90))
fill(plot(inDateRange ?  new_ten_grid_2 : na , color = color.new(color.green, 85)), 
     plot(inDateRange ? new_ten_grid_3 : na , color = color.new(color.green, 85)), 
         color = color.new(color.green, 85))
fill(plot(inDateRange ? new_ten_grid_3 : na , color = color.new(color.green, 80)), 
     plot(inDateRange ? new_ten_grid_4 : na , color = color.new(color.green, 80)), 
         color = color.new(color.green, 80))
fill(plot(inDateRange ? new_ten_grid_4 : na , color = color.new(color.green, 70)), 
     plot(inDateRange ? new_ten_grid_5 : na , color = color.new(color.green, 70)), 
         color = color.new(color.green, 70))
fill(plot(inDateRange ?  new_ten_grid_5 : na , color = color.new(color.green, 60)), 
     plot(inDateRange ? new_ten_grid_6 : na, color = color.new(color.green, 60)), 
         color = color.new(color.green, 60))
fill(plot(inDateRange ? new_ten_grid_6 : na, color = color.new(color.red, 60)), 
     plot(inDateRange ? new_ten_grid_7 : na, color = color.new(color.red, 60)), 
         color = color.new(color.red, 60))
fill(plot(inDateRange ? new_ten_grid_7 : na, color = color.new(color.red, 70)), 
     plot(inDateRange ? new_ten_grid_8 : na, color = color.new(color.red, 70)), 
         color = color.new(color.red, 70))
fill(plot(inDateRange ? new_ten_grid_8 : na, color = color.new(color.red, 80)), 
     plot(inDateRange ? new_ten_grid_9 : na, color = color.new(color.red, 80)), 
         color = color.new(color.red, 80))
fill(plot(inDateRange ? new_ten_grid_9 : na, color = color.new(color.red, 85)), 
     plot(inDateRange ? new_ten_grid_10 : na, color = color.new(color.red, 85)), 
         color = color.new(color.red, 85))
// // ###########################################################################################
var float new_twenty_grid_1 = na 
var float new_twenty_grid_2 = na 
var float new_twenty_grid_3 = na 
var float new_twenty_grid_4 = na 
var float new_twenty_grid_5 = na 
var float new_twenty_grid_6 = na 
var float new_twenty_grid_7 = na 
var float new_twenty_grid_8 = na 
var float new_twenty_grid_9 = na 
var float new_twenty_grid_10 = na 
var float new_twenty_grid_11 = na 
var float new_twenty_grid_12 = na 
var float new_twenty_grid_13 = na 
var float new_twenty_grid_14 = na 
var float new_twenty_grid_15 = na 
var float new_twenty_grid_16 = na 
var float new_twenty_grid_17 = na 
var float new_twenty_grid_18 = na 
var float new_twenty_grid_19 = na 
var float new_twenty_grid_20 = na 
if tewnty_grid == true and show_grid_level_bg and inDateRange 
    new_twenty_grid_1 := grid_1
    new_twenty_grid_2 := grid_2
    new_twenty_grid_3 := grid_3
    new_twenty_grid_4 := grid_4
    new_twenty_grid_5 := grid_5
    new_twenty_grid_6 := grid_6
    new_twenty_grid_7 := grid_7
    new_twenty_grid_8 := grid_8
    new_twenty_grid_9 := grid_9
    new_twenty_grid_10 := grid_10
    new_twenty_grid_11 := grid_11
    new_twenty_grid_12 := grid_12
    new_twenty_grid_13 := grid_13
    new_twenty_grid_14 := grid_14
    new_twenty_grid_15 := grid_15
    new_twenty_grid_16 := grid_16
    new_twenty_grid_17 := grid_17
    new_twenty_grid_18 := grid_18
    new_twenty_grid_19 := grid_19
    new_twenty_grid_20 := grid_20
else if tewnty_grid == false
    new_twenty_grid_1 := na
    new_twenty_grid_2 := na
    new_twenty_grid_3 := na
    new_twenty_grid_4 := na
    new_twenty_grid_5 := na
    new_twenty_grid_6 := na
    new_twenty_grid_7 := na
    new_twenty_grid_8 := na
    new_twenty_grid_9 := na
    new_twenty_grid_10 := na
    new_twenty_grid_11 := na
    new_twenty_grid_12 := na
    new_twenty_grid_13 := na
    new_twenty_grid_14 := na
    new_twenty_grid_15 := na
    new_twenty_grid_16 := na
    new_twenty_grid_17 := na
    new_twenty_grid_18 := na
    new_twenty_grid_19 := na
    new_twenty_grid_20 := na
fill(plot(inDateRange ? new_twenty_grid_1 : na , color = color.new(color.green, 90)), 
     plot(inDateRange ? new_twenty_grid_2 : na , color = color.new(color.green, 90)), 
         color = color.new(color.green, 90))
fill(plot(inDateRange ? new_twenty_grid_2 : na , color = color.new(color.green, 85)), 
     plot(inDateRange ? new_twenty_grid_3 : na , color = color.new(color.green, 85)), 
         color = color.new(color.green, 85))
fill(plot(inDateRange ? new_twenty_grid_3 : na , color = color.new(color.green, 80)), 
     plot(inDateRange ? new_twenty_grid_4 : na , color = color.new(color.green, 80)), 
         color = color.new(color.green, 80))
fill(plot(inDateRange ? new_twenty_grid_4 : na , color = color.new(color.green, 70)), 
     plot(inDateRange ? new_twenty_grid_5 : na , color = color.new(color.green, 70)), 
         color = color.new(color.green, 70))
fill(plot(inDateRange ? new_twenty_grid_5 : na , color = color.new(color.green, 60)), 
     plot(inDateRange ? new_twenty_grid_6 : na , color = color.new(color.green, 60)), 
         color = color.new(color.green, 60))
fill(plot(inDateRange ? new_twenty_grid_6 : na , color = color.new(color.green, 60)), 
     plot(inDateRange ? new_twenty_grid_7 : na , color = color.new(color.green, 60)), 
         color = color.new(color.green, 60))
fill(plot(inDateRange ? new_twenty_grid_7 : na , color = color.new(color.green, 70)), 
     plot(inDateRange ? new_twenty_grid_8 : na , color = color.new(color.green, 70)), 
         color = color.new(color.green, 70))
fill(plot(inDateRange ? new_twenty_grid_8 : na , color = color.new(color.green, 80)), 
     plot(inDateRange ? new_twenty_grid_9 : na , color = color.new(color.green, 80)), 
         color = color.new(color.green, 80))
fill(plot(inDateRange ? new_twenty_grid_9 : na , color = color.new(color.green, 85)), 
     plot(inDateRange ? new_twenty_grid_10 : na , color = color.new(color.green, 85)), 
         color = color.new(color.green, 85))
fill(plot(inDateRange ? new_twenty_grid_10 : na , color = color.new(color.red, 90)), 
     plot(inDateRange ? new_twenty_grid_11 : na , color = color.new(color.red, 90)), 
         color = color.new(color.red, 90))
fill(plot(inDateRange ? new_twenty_grid_11 : na , color = color.new(color.red, 85)), 
     plot(inDateRange ? new_twenty_grid_12 : na , color = color.new(color.red, 85)), 
         color = color.new(color.red, 85))
fill(plot(inDateRange ? new_twenty_grid_12 : na , color = color.new(color.red, 80)), 
     plot(inDateRange ? new_twenty_grid_13 : na , color = color.new(color.red, 80)), 
         color = color.new(color.red, 80))
fill(plot(inDateRange ? new_twenty_grid_13 : na , color = color.new(color.red, 70)), 
     plot(inDateRange ? new_twenty_grid_14 : na , color = color.new(color.red, 70)), 
         color = color.new(color.red, 70))
fill(plot(inDateRange ? new_twenty_grid_14 : na , color = color.new(color.red, 60)), 
     plot(inDateRange ? new_twenty_grid_15 : na , color = color.new(color.red, 60)), 
         color = color.new(color.red, 60))
fill(plot(inDateRange ? new_twenty_grid_15 : na , color = color.new(color.red, 60)), 
     plot(inDateRange ? new_twenty_grid_16 : na , color = color.new(color.red, 60)), 
         color = color.new(color.red, 60))
fill(plot(inDateRange ? new_twenty_grid_16 : na , color = color.new(color.red, 70)), 
     plot(inDateRange ? new_twenty_grid_17 : na , color = color.new(color.red, 70)), 
         color = color.new(color.red, 70))
fill(plot(inDateRange ? new_twenty_grid_17 : na , color = color.new(color.red, 80)), 
     plot(inDateRange ? new_twenty_grid_18 : na , color = color.new(color.red, 80)), 
         color = color.new(color.red, 80))
fill(plot(inDateRange ? new_twenty_grid_18 : na , color = color.new(color.red, 85)), 
     plot(inDateRange ? new_twenty_grid_19 : na , color = color.new(color.red, 85)), 
         color = color.new(color.red, 85))
fill(plot(inDateRange ? new_twenty_grid_19 : na , color = color.new(color.red, 85)), 
     plot(inDateRange ? new_twenty_grid_20 : na , color = color.new(color.red, 85)), 
         color = color.new(color.red, 85))
// // ###########################################################################################
//###############################################################################################
//------------------------------Table
//###############################################################################################
showDashboard     = input.bool(true, "Show Table", group=" ############# 🔳 TABLE Settings 🔳 ############ ")
locationDashboard = input.string("Top Right", "Table Location", ["Top Right", "Middle Right", "Bottom Right", "Top Center", "Middle Center", "Bottom Center", "Top Left", "Middle Left", "Bottom Left"], group=" ############# 🔳 TABLE Settings 🔳 ############ ")
sizeDashboard     = input.string("Normal", "Table Size", ["Large", "Normal", "Small", "Tiny"], group=" ############# 🔳 TABLE Settings 🔳 ############ ")
var dashboard_loc  = locationDashboard == "Top Right" ? position.top_right : locationDashboard == "Middle Right" ? position.middle_right : locationDashboard == "Bottom Right" ? position.bottom_right : locationDashboard == "Top Center" ? position.top_center : locationDashboard == "Middle Center" ? position.middle_center : locationDashboard == "Bottom Center" ? position.bottom_center : locationDashboard == "Top Left" ? position.top_left : locationDashboard == "Middle Left" ? position.middle_left : position.bottom_left
var dashboard_size = sizeDashboard == "Large" ? size.large : sizeDashboard == "Normal" ? size.normal : sizeDashboard == "Small" ? size.small : size.tiny
if showDashboard
    var myTable =  table.new(position = dashboard_loc, columns = 5, rows = 2,bgcolor = color.white, border_width = 1, frame_color = color.rgb(25, 150, 25), frame_width = 3, border_color = color.rgb(25, 150, 25)) 
    table.cell(table_id = myTable, column = 0, row = 0, text = "Open positions"      , text_color = color.white, bgcolor = color.orange, text_size=dashboard_size)
    table.cell(table_id = myTable, column = 1, row = 0, text = "Open profit"         , text_color = color.white, bgcolor = color.orange, text_size=dashboard_size)
    table.cell(table_id = myTable, column = 2, row = 0, text = "Total trades"        , text_color = color.white, bgcolor = color.orange, text_size=dashboard_size)
    table.cell(table_id = myTable, column = 3, row = 0, text = "Total profit"        , text_color = color.white, bgcolor = color.orange, text_size=dashboard_size)
    table.cell(table_id = myTable, column = 4, row = 0, text = "Current equity"      , text_color = color.white, bgcolor = color.orange, text_size=dashboard_size)
    table.cell(table_id = myTable, column = 0, row = 1, text =       str.tostring(strategy.opentrades)                                                                                      , text_font_family = font.family_monospace, text_size=dashboard_size)
    table.cell(table_id = myTable, column = 1, row = 1, text = "$" + str.tostring(math.round(strategy.openprofit, 1)) , bgcolor = strategy.openprofit >= 0 ? color.green : color.red  , text_font_family = font.family_monospace, text_size=dashboard_size)
    table.cell(table_id = myTable, column = 2, row = 1, text =       str.tostring(strategy.closedtrades)                                                                                    , text_font_family = font.family_monospace, text_size=dashboard_size)
    table.cell(table_id = myTable, column = 3, row = 1, text = "$" + str.tostring(math.round(strategy.netprofit, 1)) , bgcolor = strategy.netprofit  >= 0 ? color.green : color.red  , text_font_family = font.family_monospace, text_size=dashboard_size)
    table.cell(table_id = myTable, column = 4, row = 1, text = "$" + str.tostring(math.round(strategy.equity, 1)) , bgcolor = strategy.equity     >= 0 ? color.green : color.red  , text_font_family = font.family_monospace, text_size=dashboard_size)
Expand (778 lines)

Overview

Automatic Grid Bot Strategy sets upper and lower price range boundaries and splits the defined range into grid levels to trade long, short, or both directions simultaneously. Users can configure dollar position sizing, custom alert messages, and optional upper and lower stop-loss boundaries. The script plots visual grid levels and displays a real-time status dashboard on the chart.

Details

Published by

hasnocool on GitHub

Code credit

lovealgotrading, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Support & resistance, Mean reversion, Screeners & dashboards

Markets

Crypto, Forex

Timeframes

Any timeframe

Risk Notes

  • The strategy can add several entries in the same direction
  • The strategy enters trades without a stop loss

Topics

analysisbtcusdtcryptocurrencydatapandaspythonsimulationtradingtradingview

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Start_Datetimetimestamp('1 nov 2022 13:30 +0000')startDate
End_Datetimetimestamp('20 oct 2030 13:30 +0000')endDate
Range High price: price0.00high_price
Range Low price: price0.00low_price
Trade DirectionstringBOTHtrade_direction
Use StopLossboolfalseuse_stop
Close Bot After Stop Lossboolfalseclose_bot_after_stop
Use StopLoss Where HIGH and LOW GRID PRICEbooltrueuse_stop_default
High STOP Price: price99999high_price_stop
Low STOP Price: price0.00low_price_stop
$ Per Positionint100dolar
Long_messagestringLong_message
Show all 24 settings
SettingTypeDefaultVariable
Long_Exit_messagestringLong_Exit_message
Long_Stop_messagestringLong_Stop_message
Short_messagestringShort_message
Short_Exit_messagestringShort_Exit_message
Short_Stop_messagestringShort_Stop_message
10 grid levelsboolfalseten_grid
20 grid levelsbooltruetewnty_grid
Show Stop Pricebooltrueshow_stop_res
Show Grid Levels BGbooltrueshow_grid_level_bg
Show TablebooltrueshowDashboard
Table LocationstringTop RightlocationDashboard
Table SizestringNormalsizeDashboard
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

330 stars

This strategy divides a fixed price range between an upper and a lower limit into equally spaced grid levels and plots them on the price chart. It marks a buy when price crosses down through a grid and a sell when price crosses up through a grid, using either

Strategy v5 Support & resistanceMean reversion Repaints
Updated 2 months ago · None stated GitHub repository of Grid Bot Simulator [Alorse]

This strategy builds a spot grid between user-set high and low prices and draws it on the price chart. It splits that range into ten levels and places up to five long limit orders at the lower levels, sizing each from current equity. Orders already below price

Strategy v6 Support & resistanceMean reversion Repaints
Updated 6 weeks ago · None stated GitHub repository of Grid Spot Trading Algorithm [The Quant Science]

FairValueGap E003

by ruckard
13 stars

Calculates the distance between the current price and the opposite end of the latest fair value gap, entering trades on the expectation that price will partially fill the gap. It incorporates risk management with customizable stop loss, take profit based on ri

Strategy v5 SMC / ICT / price actionSupport & resistance
Updated 1 year ago · None stated GitHub repository of FairValueGap E003

Wyckoff Phase

by muammeryldrm42
7 stars

This strategy identifies Wyckoff consolidation ranges directly on the price chart to trade potential spring and upthrust events. It calculates highest highs and lowest lows over a customizable lookback period, filtering setups by average volume spikes and ATR

Strategy v5 SMC / ICT / price actionSupport & resistance
Updated 3 months ago · MIT GitHub repository of Wyckoff Phase
7 stars

This strategy plots RSI on the price chart and enters a long when RSI falls below the oversold level or a short when it rises above the overbought level, only while flat. It exits with a take profit and stop loss measured in pips from the current close. Inputs

Strategy v6 Oscillators & momentumScalping
Updated 3 months ago · None stated GitHub repository of XAUUSD 1-Minute Scalping Strategy

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers