Strategy · Pine Script v4 · On the chart

(IK) Grid Script

by hasnocool· code credited to tapRoot_coding - Ian Kuzmik

This strategy overlays an automated grid trading system directly onto the price chart.

View on GitHub

GitHub stars106on the repository
Pine versionv4older, still runs
Lines of code89
Settings7inputs
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

89 lines of Pine Script v4 from (IK) Grid Script.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

(IK) Grid Script.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © tapRoot_coding - Ian Kuzmik
//@version=4
strategy("(IK) Grid Script", overlay=true, pyramiding=14, close_entries_rule="ANY", default_qty_type=strategy.cash, initial_capital=100.0, currency="USD", commission_type=strategy.commission.percent, commission_value=0.1)
// == INPUT == 
i_autoBounds    = input(group="Grid Bounds", title="Use Auto Bounds?", defval=false, type=input.bool)                             // calculate upper and lower bound of the grid automatically? This will theorhetically be less profitable, but will certainly require less attention
i_boundSrc      = input(group="Grid Bounds", title="(Auto) Bound Source", defval="Hi & Low", options=["Hi & Low", "Average"])     // should bounds of the auto grid be calculated from recent High & Low, or from a Simple Moving Average
i_boundLookback = input(group="Grid Bounds", title="(Auto) Bound Lookback", defval=250, type=input.integer, maxval=500, minval=0) // when calculating auto grid bounds, how far back should we look for a High & Low, or what should the length be of our sma 
i_boundDev      = input(group="Grid Bounds", title="(Auto) Bound Deviation", defval=0.10, type=input.float, maxval=1, minval=-1)  // if sourcing auto bounds from High & Low, this percentage will (positive) widen or (negative) narrow the bound limits. If sourcing from Average, this is the deviation (up and down) from the sma, and CANNOT be negative. 
i_upperBound    = input(group="Grid Bounds", title="(Manual) Upper Boundry", defval=0.285, type=input.float)                      // for manual grid bounds only. The upperbound price of your grid
i_lowerBound    = input(group="Grid Bounds", title="(Manual) Lower Boundry", defval=0.225, type=input.float)                      // for manual grid bounds only. The lowerbound price of your grid. 
i_gridQty       = input(group="Grid Lines",  title="Grid Line Quantity", defval=8, maxval=15, minval=3, type=input.integer)       // how many grid lines are in your grid
// == FUNCTIONS ==
// for auto grid only. return the upperbound if _up == true, or the lowerbound if _up == false
f_getGridBounds(_bs, _bl, _bd, _up) => 
    if _bs == "Hi & Low" 
        _up ? highest(close, _bl) * (1 + _bd) : lowest(close, _bl)  * (1 - _bd)
    else
        avg = sma(close, _bl)
        _up ? avg * (1 + _bd) : avg * (1 - _bd)
// using the lowerbound, grid width, and grid line quantity, build an array of prices (grid lines) from the bottom up
f_buildGrid(_lb, _gw, _gq) =>
    gridArr = array.new_float(0)
    for i=0 to _gq-1
        array.push(gridArr, _lb+(_gw*i))
    gridArr 
// return an array that contains the closest grid lines above and below current price (not counting the line price is currently on). This is solely for plotting purposes
f_getNearGridLines(_gridArr, _price) =>
    arr = array.new_int(3)
    for i = 0 to array.size(_gridArr)-1
        if array.get(_gridArr, i) > _price
            array.set(arr, 0, i == array.size(_gridArr)-1 ? i : i+1)
            array.set(arr, 1, i == 0 ? i : i-1)
            break
    arr
    
// == VARIABLES ==
var upperBound      = i_autoBounds ? f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, true) : i_upperBound  // upperbound of our grid
var lowerBound      = i_autoBounds ? f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, false) : i_lowerBound // lowerbound of our grid
var gridWidth       = (upperBound - lowerBound)/(i_gridQty-1)                                                       // space between lines in our grid
var gridLineArr     = f_buildGrid(lowerBound, gridWidth, i_gridQty)                                                 // an array of prices that correspond to our grid lines
var orderArr        = array.new_bool(i_gridQty, false)                                                              // a boolean array that indicates if there is an open order corresponding to each grid line
var closeLineArr    = f_getNearGridLines(gridLineArr, close)                                                        // for plotting purposes - an array of 2 indices that correspond to grid lines near price
var nearTopGridLine = array.get(closeLineArr, 0)                                                                    // for plotting purposes - the index (in our grid line array) of the closest grid line above current price                        
var nearBotGridLine = array.get(closeLineArr, 1)                                                                    // for plotting purposes - the index (in our grid line array) of the closest grid line below current price 
// == LOGIC ==
// ENTRY & EXIT
for i = 0 to (array.size(gridLineArr) - 1)
    if close < array.get(gridLineArr, i) and not array.get(orderArr, i) and i < (array.size(gridLineArr) - 1)
        buyId = i
        array.set(orderArr, buyId, true)
        strategy.entry(id=tostring(buyId), long=true, qty=(strategy.initial_capital/(i_gridQty-1))/close, comment="#"+tostring(buyId))
    if close > array.get(gridLineArr, i) and i != 0 
        if array.get(orderArr, i-1)
            sellId = i-1
            array.set(orderArr, sellId, false)
            strategy.close(id=tostring(sellId), comment="#"+tostring(sellId))
        
// MAINTAIN GRID 
// update auto grid (if active)
if i_autoBounds
    upperBound  := f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, true)
    lowerBound  := f_getGridBounds(i_boundSrc, i_boundLookback, i_boundDev, false)
    gridWidth   := (upperBound - lowerBound)/(i_gridQty-1)
    gridLineArr := f_buildGrid(lowerBound, gridWidth, i_gridQty)
// update near grid lines (for plotting purposes)
closeLineArr    := f_getNearGridLines(gridLineArr, close)
nearTopGridLine := array.get(closeLineArr, 0)
nearBotGridLine := array.get(closeLineArr, 1)
// plot grid lines
plot(array.size(gridLineArr) > 0  ? array.get(gridLineArr,0)  : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 1  ? array.get(gridLineArr,1)  : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 2  ? array.get(gridLineArr,2)  : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 3  ? array.get(gridLineArr,3)  : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 4  ? array.get(gridLineArr,4)  : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 5  ? array.get(gridLineArr,5)  : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 6  ? array.get(gridLineArr,6)  : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 7  ? array.get(gridLineArr,7)  : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 8  ? array.get(gridLineArr,8)  : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 9  ? array.get(gridLineArr,9)  : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 10 ? array.get(gridLineArr,10) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 11 ? array.get(gridLineArr,11) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 12 ? array.get(gridLineArr,12) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 13 ? array.get(gridLineArr,13) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
plot(array.size(gridLineArr) > 14 ? array.get(gridLineArr,14) : na, color=bar_index % 2 == 1 ? color.rgb(255,255,0,50) : #00000000)
// plot near grid lines
plot(array.get(gridLineArr, nearTopGridLine), color=color.rgb(255,0,255,20), style=plot.style_stepline, linewidth=2)
plot(array.get(gridLineArr, nearBotGridLine), color=color.rgb(0,0,255,20),   style=plot.style_stepline, linewidth=2)
Expand (102 lines)

Overview

(IK) Grid Script defines upper and lower boundaries either manually or dynamically using recent price extremes or a simple moving average with deviation bands. An array of evenly spaced grid levels is generated across the price channel to execute trades as price oscillates through the bands. The strategy utilizes pyramiding across multiple levels and operates without a dedicated stop loss by default.

Details

Published by

hasnocool on GitHub

Code credit

tapRoot_coding - Ian Kuzmik, as written in the script's header

Type

Strategy, Pine Script v4

Draws

On the price chart

Category

Support & resistance, Mean reversion

Markets

Crypto

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
Use Auto Bounds?boolfalsei_autoBounds
(Auto) Bound SourcestringHi & Lowi_boundSrc
(Auto) Bound Lookbackint250i_boundLookback
(Auto) Bound Deviationfloat0.10i_boundDev
(Manual) Upper Boundryfloat0.285i_upperBound
(Manual) Lower Boundryfloat0.225i_lowerBound
Grid Line Quantityint8i_gridQty
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
5 stars

This strategy enters one long trade when the bar low comes within a set point tolerance of the prior day's low and the close finishes above that level. Entries are allowed only inside a UTC session and are blocked after a Friday cutoff hour. It stays flat unti

Strategy v5 Support & resistanceMean reversion Repaints
Updated 4 months ago · MIT GitHub repository of PDL — Prior Day Level Retest (Bull)

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