Strategy · Pine Script v5 · On the chart

BEST Strategy Template with Custom SL-TP Size

by hasnocool

This strategy script provides a framework for backtesting custom trading rules with flexible risk and order management.

View on GitHub

GitHub stars106on the repository
Pine versionv5runs as is
Lines of code254
Settings20inputs
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

254 lines of Pine Script v5 from BEST Strategy Template w- Custom SL-TP Size - Educational.pine, published under GPL-3.0. Keep the author's credit and licence lines when you reuse it.

BEST Strategy Template w- Custom SL-TP Size - Educational.pine
//@version=5
VERSION = "V1"
SCRIPT_NAME = "BEST Strategy Template Custom SL/TP Qty " + VERSION
// # ========================================================================= #
// #                   |   STRATEGY  |
// # ========================================================================= #
// These values are used both in the strategy() header and in the script's relevant inputs as default values so they match.
// Unless these values match in the script's Inputs and the TV backtesting Properties, results between them cannot be compared.
InitCapital = 1000000
InitPosition = 100.0
InitCommission = 0.075
InitPyramidMax = 1
CalcOnorderFills = false
ProcessOrdersOnClose = true
CalcOnEveryTick = false
CloseEntriesRule = "FIFO"
strategy(title=SCRIPT_NAME, shorttitle=SCRIPT_NAME, 
 overlay=true, pyramiding=InitPyramidMax, initial_capital=InitCapital, default_qty_type=strategy.fixed, process_orders_on_close=ProcessOrdersOnClose,
 default_qty_value=InitPosition, commission_type=strategy.commission.percent, commission_value=InitCommission, calc_on_order_fills=CalcOnorderFills, 
 calc_on_every_tick=CalcOnEveryTick, close_entries_rule = CloseEntriesRule,
 precision=6, max_lines_count=500, max_labels_count=500)
// # ========================================================================= #
// # ========================================================================= #
// #                   |   Input fields |
// # ========================================================================= #
// # ========================================================================= #
// # ========================================================================= #
// # ========================================================================= #
// #                   ||   Alerts  ||
// # ========================================================================= #
// # ========================================================================= #
i_alert_txt_entry_long = input.text_area(defval = "", title = "Long Entry Message", group = "Alerts")
i_alert_txt_entry_short = input.text_area(defval = "", title = "Short Entry Message", group = "Alerts")
i_alert_txt_exit_long = input.text_area(defval = "", title = "Long Exit Message", group = "Alerts")
i_alert_txt_exit_short = input.text_area(defval = "", title = "Short Exit Message", group = "Alerts")
// # ========================================================================= #
// # ========================================================================= #
// #                   ||   Dates Range Filtering  ||
// # ========================================================================= #
// # ========================================================================= #
DateFilter = input(false, "Date Range Filtering", group="Date")
// ————— Syntax coming from https://www.tradingview.com/blog/en/new-parameter-for-date-input-added-to-pine-21812/
i_startTime = input.time(defval = timestamp("01 Jan 2019 13:30 +0000"), title = "Start Time", group="Date")
i_endTime = input.time(defval = timestamp("30 Dec 2021 23:30 +0000"), title = "End Time", group="Date")
TradeDateIsAllowed() => DateFilter ? time >= i_startTime and time <= i_endTime : true
// # ========================================================================= #
// #                   |   General  |
// # ========================================================================= #
show_consecutive = input.bool(defval = true , title = "Show consecutive signals?", group="General")
OpenDirection    = input.string(defval="ALL", title="Direction", options=["ALL", "LONG", "SHORT"], group="General")
clrBars          = input.bool(true, title="Colour Candles to Trade Order state", group="General")
nb_contracts     = input.int(100, title = "Default Nb Contracts per Trade", group="General")
// # ========================================================================= #
// #                   |  Donchian Trend Ribbon |
// # ========================================================================= #
dlen = input.int(defval = 20, title = "Period", minval = 10, group = "Donchian Channel")
// # ========================================================================= #
// #                   | Stop Loss |
// # ========================================================================= #
use_sl         = input.bool(false, title = "Use Stop Loss?", group = "Initial Stop Loss")
sl_input_pips = input.float(30, minval = 0, title = "Stop Loss (pips)", group = "Initial Stop Loss")
sl_qty        = input.float(100, minval = 0, maxval = 100, title = "Close X% at SL", group = "Initial Stop Loss") 
// # ========================================================================= #
// #                   | Take Profit |
// # ========================================================================= #
use_tp         = input.bool(false, title = "Use Take Profit?", group = "Take Profit")
tp_input_pips = input.float(30, minval = 0, title = "Take Profit (pips)", group = "Take Profit")
tp_qty        = input.float(50, minval = 0, maxval = 100, title = "Close X% at TP", group = "Take Profit") 
// # ========================================================================= #
// #                   | Stop Loss / Take Profit |
// # ========================================================================= #
//sl_tp_qty        = input.float(50, minval = 0, maxval = 100, title = "Close X% at SL/TP", group = "SL/TP Exit Size")
// # ========================================================================= #
// #                   | Trailing Stop Loss |
// # ========================================================================= #
use_trailing  = input.bool(false, title = "Use Trailing Stop Loss?", group = "Trailing Stop Loss")
tsl_input_pips = input.float(10, minval = 0, title = "Trailing Stop Loss (pips)", group = "Trailing Stop Loss")
// # ========================================================================= #
// #                   |  Donchian Trend Ribbon |
// # ========================================================================= #
dchannel(len)=>
    float hh = ta.highest(len)
    float ll = ta.lowest(len)
    
    int trend = 0
    trend := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(trend[1])
    
dchannelalt(len, maintrend)=>
    float hh = ta.highest(len)
    float ll = ta.lowest(len)
    
    int trend = 0
    trend := close > hh[1] ? 1 : close < ll[1] ? -1 : nz(trend[1])
    maintrend == 1  ? trend == 1  ? #00FF00ff :  #00FF009f :
     maintrend == -1 ? trend == -1 ? #FF0000ff :  #FF00009f :
     na
dc_maintrend = dchannel(dlen)
bull_dc = dc_maintrend == 1
bear_dc = dc_maintrend == -1
plotshape(
 series     = bull_dc and not bull_dc[1],
 title      = "Bull Donchian Channel",
 style      =  shape.diamond,
 location   =  location.bottom,
 color      = color.new(color = color.purple, transp = 0),
 size       = size.normal
 )
plotshape(
 series     = bear_dc and not bear_dc[1],
 title      = "Bear Donchian Channel",
 style      =  shape.diamond,
 location   =  location.top,
 color      = color.new(color = color.orange, transp = 0),
 size       = size.normal
 )
// # ========================================================================= #
// #                   | Consolidated Signals |
// # ========================================================================= #
T1_posUp = bull_dc
T1_posDn = bear_dc
var float count_signals = 1.
T1_conditionUP = bull_dc
T1_conditionDN = bear_dc
// # ========================================================================= #
// #                   ||   Global Trend Variables ||
// # ========================================================================= #
T1_sinceUP = ta.barssince(T1_conditionUP)
T1_sinceDN = ta.barssince(T1_conditionDN)
bull = show_consecutive ? T1_conditionUP : ta.crossunder(T1_sinceUP,T1_sinceDN)
bear = show_consecutive ? T1_conditionDN : ta.crossover(T1_sinceUP,T1_sinceDN)
T1_sinceNUP = ta.barssince(bull)
T1_sinceNDN = ta.barssince(bear)
T1_BuyTrend = T1_sinceNDN > T1_sinceNUP
T1_SellTrend = T1_sinceNDN < T1_sinceNUP
T1_SellToBuy = T1_BuyTrend and T1_SellTrend[1]
T1_BuyToSell = T1_SellTrend and T1_BuyTrend[1]
T1_ChangeTrend = T1_BuyToSell or T1_SellToBuy
if T1_ChangeTrend or strategy.position_size == 0
    count_signals := 1
plotshape(
 series     = bull and not bull[1],
 title      = "Buy Signal",
 style      = shape.triangleup,
 location   = location.bottom,
 color      = color.new(color = color.green, transp = 0),
 size       = size.normal,
 display    =  display.none 
 )
plotshape(
 series     = bear and not bear[1],
 title      = "Sell Signal",
 style      = shape.triangledown,
 location   = location.top,
 color      = color.new(color = color.red, transp = 0),
 size       = size.normal,
 display    =  display.none 
 )
// # ========================================================================= #
// #       |   Entry Price |
// # ========================================================================= #
entry_long_price  = ta.valuewhen(condition=bull and strategy.position_size[1] <= 0, source=close, occurrence=0)
entry_short_price = ta.valuewhen(condition=bear and strategy.position_size[1] >= 0, source=close, occurrence=0)
// # ========================================================================= #
// #                   |   Stop Loss |
// # ========================================================================= #
pip() => 1//syminfo.mintick * (syminfo.type == "forex" ? 10 : 1)
var float final_SL_Long  = 0.
var float final_SL_Short = 0.
final_SL_Long  := strategy.position_avg_price - (sl_input_pips * pip())
final_SL_Short := strategy.position_avg_price + (sl_input_pips * pip())
// # ========================================================================= #
// #                   |  Take Profit |
// # ========================================================================= #
var float final_TP_Long  = 0.
var float final_TP_Short = 0.
final_TP_Long  := strategy.position_avg_price + (tp_input_pips * pip())
final_TP_Short := strategy.position_avg_price - (tp_input_pips * pip())
plot(strategy.position_size > 0 and use_tp ? final_TP_Long : na, title = "TP Long", color = color.orange, linewidth=2, style=plot.style_linebr)
plot(strategy.position_size < 0 and use_tp ? final_TP_Short : na, title = "TP Short", color = color.orange, linewidth=2, style=plot.style_linebr)
// # ========================================================================= #
// #                   |   Trailing Stop Loss |
// # ========================================================================= # 
signal_candle = bear or bull
var MaxReached = 0.0  
var bool is_TP1_reached = false
if signal_candle[1]
    MaxReached := strategy.position_size > 0 ? high : low
MaxReached := strategy.position_size > 0
 ? math.max(nz(MaxReached, high), high)
 : strategy.position_size < 0 ? math.min(nz(MaxReached, low), low) : na
if (strategy.position_size > 0 and MaxReached >= final_TP_Long) 
 or (strategy.position_size < 0 and MaxReached <= final_TP_Short)
    is_TP1_reached := true
if use_trailing and is_TP1_reached and use_sl
    if strategy.position_size > 0
        stopValue = MaxReached - (tsl_input_pips * pip())
        final_SL_Long := math.max(stopValue, final_SL_Long[1])
    else if strategy.position_size < 0
        stopValue = MaxReached + (tsl_input_pips * pip())
        final_SL_Short := math.min(stopValue, final_SL_Short[1])
plot(strategy.position_size > 0 and use_sl ? final_SL_Long : na, title = "SL Long", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
plot(strategy.position_size < 0 and use_sl ? final_SL_Short : na, title = "SL Short", color = color.fuchsia, linewidth=2, style=plot.style_linebr)
// # ========================================================================= #
// #                   | Strategy Calls |
// # ========================================================================= #
open_all        = OpenDirection == "ALL"
open_all_longs  = OpenDirection != "SHORT"
open_all_shorts = OpenDirection != "LONG"
//final_sl_qty = nb_contracts * (1 - (1 - sl_qty))
//final_tp_qty = nb_contracts * (1 - (1 - tp_qty))
// Go long
longCondition = bull// and not bull[1]
if (longCondition and open_all_longs and TradeDateIsAllowed())// and not (strategy.position_size[1] > 0))
    strategy.entry("Long", strategy.long, alert_message = i_alert_txt_entry_long, qty = nb_contracts)
    alert(i_alert_txt_entry_long, alert.freq_once_per_bar_close)
        
// Go Short
shortCondition = bear// and not bear[1]
if (shortCondition and open_all_shorts and TradeDateIsAllowed())// and not (strategy.position_size[1] < 0))
    strategy.entry("Short", strategy.short, alert_message = i_alert_txt_entry_short, qty = nb_contracts)
    alert(i_alert_txt_entry_short, alert.freq_once_per_bar_close)
var bool both_sl_tp_100 = false
if use_sl and use_tp and sl_qty == 100 and tp_qty == 100
    both_sl_tp_100 := true
if (strategy.position_size[1] > 0)
    if both_sl_tp_100
        strategy.exit(id = "Exit Long SL",  from_entry = "Long", stop = final_SL_Long, limit = final_TP_Long, comment_loss = "Long Exit SL", alert_loss = "Long Exit SL", comment_profit = "Long Exit TP", alert_profit = "Long Exit TP")
    else
        if use_sl and low <= final_SL_Long
            strategy.exit(id = "Exit Long SL",  from_entry = "Long", stop  = use_sl ? final_SL_Long : na, comment_loss = "Long Exit SL", qty_percent   = sl_qty, alert_loss = "Long Exit SL") 
        if use_tp and high >= final_TP_Long
            strategy.exit(id = "Exit Long TP",  from_entry = "Long", limit = use_tp ? final_TP_Long : na, comment_profit = "Long Exit TP", qty_percent = tp_qty, alert_profit = "Long Exit tp")     
if (strategy.position_size[1] < 0)
    if both_sl_tp_100
        strategy.exit(id = "Exit Short SL",  from_entry = "Short", stop = final_SL_Short, limit = final_TP_Short, comment_loss = "Short Exit SL", alert_loss = "Short Exit SL", comment_profit = "Short Exit TP", alert_profit = "Short Exit TP")
    else
        if use_sl and high >= final_SL_Short
            strategy.exit(id = "Exit Short SL",  from_entry = "Short", stop  = use_sl ? final_SL_Short : na, qty_percent = sl_qty, comment_loss = "Short Exit SL", alert_loss = "Short Exit SL") 
        if use_tp and low <= final_TP_Short
            strategy.exit(id = "Exit Short TP",  from_entry = "Short", limit = use_tp ? final_TP_Short : na, qty_percent = tp_qty, comment_profit = "Short Exit TP", alert_profit = "Short Exit TP")  
// # ========================================================================= #
// #                   |   Bars Coloring |
// # ========================================================================= #
// Colour code the candles
bclr = not clrBars ? na : strategy.position_size == 0 ? #dbd5d5 : 
 T1_BuyTrend  ? color.lime :
 T1_SellTrend ? color.red : color.gray
barcolor(bclr, title="Trade State Bar Colouring")
// # ========================================================================= #
// #                   |   Reset Variables |
// # ========================================================================= #
if strategy.position_size == 0 or T1_ChangeTrend
    is_TP1_reached := false
Expand (339 lines)

Overview

BEST Strategy Template with Custom SL-TP Size allows traders to configure fixed pip-based stop loss, take profit, and trailing stop levels, complete with custom partial exit percentages. Additional features include date range filtering, optional consecutive signal display, customizable alert text messages for entries and exits, and candle coloring according to current trade order states. It overlays on the main price chart. Stop loss management is toggled off by default.

Details

Published by

hasnocool on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

  • 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
Long Entry Messagetexti_alert_txt_entry_long
Short Entry Messagetexti_alert_txt_entry_short
Long Exit Messagetexti_alert_txt_exit_long
Short Exit Messagetexti_alert_txt_exit_short
Date Range FilteringboolfalseDateFilter
Start Timetimetimestamp("01 Jan 2019 13:30 +0000")i_startTime
End Timetimetimestamp("30 Dec 2021 23:30 +0000")i_endTime
Show consecutive signals?booltrueshow_consecutive
DirectionstringALLOpenDirection
Colour Candles to Trade Order statebooltrueclrBars
Default Nb Contracts per Tradeint100nb_contracts
Periodint20dlen
Show all 20 settings
SettingTypeDefaultVariable
Use Stop Loss?boolfalseuse_sl
Stop Loss (pips)float30sl_input_pips
Close X% at SLfloat100sl_qty
Use Take Profit?boolfalseuse_tp
Take Profit (pips)float30tp_input_pips
Close X% at TPfloat50tp_qty
Use Trailing Stop Loss?boolfalseuse_trailing
Trailing Stop Loss (pips)float10tsl_input_pips
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

Doge SMA

by hackingthemarkets
474 stars

Doge SMA is a long-only moving-average crossover strategy drawn on the price chart. It calculates a fast and a slow simple moving average of close and enters a long position when the fast average crosses above the slow average, but only inside a user-defined s

Strategy v4 TrendMoving averages
Updated 4 years ago · None stated GitHub repository of Doge SMA
440 stars

This script is an empty strategy template for Pine Script developers. It declares a version 4 strategy named Basic Strategy Boilerplate with the short title Strategy Boilerplate and sets overlay to true so any future plots would appear on the price chart. It d

Strategy v4
Updated 7 years ago · GPL-3.0 GitHub repository of Basic Strategy Boilerplate

This strategy calculates and plots a fast Exponential Moving Average (EMA) and a slow EMA directly on the main price chart. It enters long trades when the fast EMA crosses above the slow EMA and exits when the fast EMA crosses below the slow EMA. Inputs allow

Strategy v6 TrendMoving averages
Updated today · AGPL-3.0 GitHub repository of Forven S01508 — Simple EMA20/50 Cross
330 stars

2 EMA/SMA + RSI Strategy [Alorse] combines three configurable moving averages with a short-period Relative Strength Index filter. It plots fast, slow, and trend moving averages on the price chart. Long entries trigger when the fast moving average is above the

Strategy v4 TrendOscillators & momentum
Updated 2 months ago · None stated GitHub repository of 2 EMA/SMA + RSI Strategy [Alorse]

Acrypto - Weighted Strategy

by AlbertoCuadra
318 stars

This strategy plots on the price chart and opens long or short positions when a weighted score from MACD, Stochastic RSI, RSI, Supertrend and a moving-average crossover exceeds a user-set trigger. Each component has its own weight and candle delay. Entries can

Strategy v5 TrendOscillators & momentum
Updated 3 years ago · Custom licence GitHub repository of Acrypto - Weighted Strategy

This overlay strategy offers two selectable entry modes: a Bollinger squeeze on typical price and a simple moving-average cross. It filters trades by weekday, session, date range, and an optional news window, and can restrict direction or invert the side. Risk

Strategy v5 Volatility & bandsMoving averages
Updated today · None stated GitHub repository of Boilerplate Configurable Strategy [Yosiet]

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