Strategy · Pine Script v5 · On the chart

Hercules Strategy Rewrite

by g-moe· code credited to goodgains

Hercules Strategy Rewrite is an automated backtesting strategy that generates entry signals using engulfing candlestick patterns, tick thresholds, and support or resistance level breakouts.

View on GitHub

GitHub stars3on the repository
Pine versionv5runs as is
Lines of code523
Settings40inputs
LicenceNone statedfile: MPL-2.0
Last update5 months ago27 May 2026

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

523 lines of Pine Script v5 from Tradingview/hercules-strategy-rewrite.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

hercules-strategy-rewrite.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © goodgains


//@version=5
strategy("Hercules Strategy Rewrite", overlay=true, max_lines_count = 500, max_labels_count = 500, max_boxes_count = 500, default_qty_value=100, initial_capital=100000, default_qty_type=strategy.percent_of_equity)

// @keywords: hercules-strategy, lightning-signal, engulfing-filter, risk-reward-target, take-profit, stop-loss, support-resistance-break, prior-day-range, daily-open-filter, time-range-filter, ma-filter, trading-session, position-boxes, max-daily-gain, max-daily-loss, inverse-signals, long-short-lock, pip-tracking, profit-box, loss-box

// trade settings
min_ticks = input.int(500, title='Lightning                  ', tooltip='On Tradingview for FOREX 1 Pip = 10 Ticks', group = 'Trade Settings', inline = '2')
tradeType = input.string('BOTH', title='What trades should be taken ?   ', options=['LONG', 'SHORT', 'BOTH'], group = 'Trade Settings', inline = '3')
trading_session = input.session("0900-1600", title = 'Trading Session', group = 'Trade Settings', inline = '4')
inverse_settings = input.bool(false, title = 'Inverse Signals', group = 'Trade Settings', inline = '1')
long_to_short_lock = input.bool(false, title = 'Next Trade Cannot Be Same Side', group = 'Trade Settings', inline = '1')


// filter settings
engulf_only = input.bool(true, title='Engulfing Candles Only', group = 'Filter Settings', inline = '1')

use_prev_candle = input(false, title='Previous Candle Filter    ', group = 'Filter Settings', inline = '2')
prev_tf = input.timeframe('', title=' ', group = 'Filter Settings', inline = '2')

use_ma = input.bool(title='MA Filter', defval=false, group='Filter Settings', inline = '3')
ma_type = input.string(title=' ', defval='SMA', options=['SMA', 'EMA', 'SMMA (RMA)', 'WMA', 'VWMA'],  group='Filter Settings', inline = '3')
ma_source = input.source(title=' ', defval=close, group='Filter Settings', inline = '3')
ma_length = input.int(defval=50, title=' ', minval=1,  group='Filter Settings', inline = '3')

prev_day_range = input.string('Outside', title = 'Prior Days Range           ', options = ['Outside', 'Inside', 'None'], group = 'Filter Settings', inline = '4')

use_day_open = input.bool(false, title = 'Daily Open Filter        ', group = 'Filter Settings', inline = '5')
day_open = input.session("0930-0931", title = ' ', group = 'Filter Settings', inline = '5')

use_range_time = input.bool(false, title = 'Time Range Filter       ', group = 'Filter Settings', inline = '6')
range_time = input.session("0930-1030", title = ' ', group = 'Filter Settings', inline = '7')
range_timedraw = input.session("0930-1600", title = ' ', group = 'Filter Settings', inline = '7')

use_support_resistance = input.bool(false, title = 'Support/Resistance Break', group = 'Filter Settings', inline = '8')
left_bars = input.int(15, title = "S/R Left Bars", group = 'Filter Settings', inline = '9')
right_bars = input.int(15, title = "S/R Right Bars", group = 'Filter Settings', inline = '9')
sr_volumethres = input.int(20, minval = 0, maxval = 100, title = 'S/R Volume Threshold', group = 'Filter Settings', inline = '10')


// risk management settings
use_rr_tp = input.bool(true, title = 'R:R Auto-Calculation', group = 'Risk Management', inline = '1')
rr_tp = input.float(2.0, title='', minval=0.0, group = 'Risk Management', inline = '1')

use_tp = input.bool(false, title = 'Alt Target        ', group = 'Risk Management', inline = '2')
tp_amount = input.float(1.00, title = '', group = 'Risk Management', inline = '2')
tp_type = input.string('Percent', title = '', options = ['Percent', 'Price'], group = 'Risk Management', inline = '2')

use_sl = input.bool(false, title = 'Alt Stop Loss      ', group = 'Risk Management', inline = '3')
sl_amount = input.float(1.00, title = '', group = 'Risk Management', inline = '3')
sl_type = input.string('Percent', title = '', options = ['Percent', 'Price'], group = 'Risk Management', inline = '3')


// max gains & max losses
trade_size = input.float(1, title = 'Trade Size', group = 'Max Gain/Loss', inline = '1')

use_max_daily_gain = input.bool(false, title = 'Max Daily Gain (pips)    ', group = 'Max Gain/Loss', inline = '2')
max_daily_gain = input.int(3000, title = '', group = 'Max Gain/Loss', inline = '2', step = 1000)

use_max_daily_loss = input.bool(false, title = 'Max Daily Loss (pips)    ', group = 'Max Gain/Loss', inline = '3')
max_daily_loss = input.int(3000, title = '', group = 'Max Gain/Loss', inline = '3', step = 1000)

use_max_weekly_gain = input.bool(false, title = 'Max Weekly Gain (pips) ', group = 'Max Gain/Loss', inline = '4')
max_weekly_gain = input.int(25000, title = '', group = 'Max Gain/Loss', inline = '4', step = 1000)

use_max_weekly_loss = input.bool(false, title = 'Max Weekly Loss (pips) ', group = 'Max Gain/Loss', inline = '5')
max_weekly_loss = input.int(25000, title = '', group = 'Max Gain/Loss', inline = '5', step = 1000)

use_max_monthly_gain = input.bool(false, title = 'Max Monthly Gain (pips)', group = 'Max Gain/Loss', inline = '6')
max_monthly_gain = input.int(100000, title = '', group = 'Max Gain/Loss', inline = '6', step = 1000)

use_max_monthly_loss = input.bool(false, title = 'Max Monthly Loss (pips)', group = 'Max Gain/Loss', inline = '7')
max_monthly_loss = input.int(100000, title = '', group = 'Max Gain/Loss', inline = '7', step = 1000)


// // error catching
// if use_rr_tp and (use_tp or use_sl)
//     runtime.error("You cannot use Auto-Calculating R:R with Alt Target or Alt Stop Loss")
// if long_to_short_lock and tradeType != 'BOTH'
//     runtime.error("You cannot require the next trade to be a different side if 'BOTH' is not enabled in 'What Trades should be taken'")
    

// position lines
line_showing = input.string('Current & Past', title = 'Position Tool', options = ['None', 'Current', 'Current & Past'], group = 'Position Line Settings', inline = '1')
css_targetline = input.color(color.new(color.green,80), title = 'Profit', group = 'Position Line Settings', inline = '2')
css_stopline = input.color(color.new(color.red,80), title = 'Loss', group = 'Position Line Settings', inline = '2')
css_toolcolor = input.color(color.white, title = 'Text', group = 'Position Line Settings', inline = '2')


// timeframe
is_trade_sess = time(timeframe.period, str.format('{0}:1234567', trading_session), 'America/New_York')


// lighting signals
green = close > open
red = close < open
dif = math.abs(close - open)
move_up = green and dif >= min_ticks * syminfo.mintick
move_dn = red and dif >= min_ticks * syminfo.mintick

bull_engulfing = close > open and close > open[1] and open[1] > close[1] and dif > min_ticks * syminfo.mintick
bear_engulfing = close < open and close < open[1] and open[1] < close[1] and dif > min_ticks * syminfo.mintick

lightning_bull = engulf_only ? bull_engulfing : move_up
lightning_bear = engulf_only ? bear_engulfing : move_dn


// prev candle calculate
prev_candle_src = request.security(syminfo.tickerid, prev_tf, green[1] ? true : false, lookahead = barmerge.lookahead_on)
prev_candle_long = use_prev_candle ? (prev_candle_src == true) : true
prev_candle_short = use_prev_candle ? (prev_candle_src == false) : true


// ma filter
ma(source, length, type) =>
    type == 'SMA' ? ta.sma(source, length) : type == 'EMA' ? ta.ema(source, length) : type == 'SMMA (RMA)' ? ta.rma(source, length) : type == 'WMA' ? ta.wma(source, length) : type == 'VWMA' ? ta.vwma(source, length) : na
ma = ma(ma_source, ma_length, ma_type)
plot(use_ma ? ma : na, color=color.yellow, title='Filter MA')

ma_long = use_ma ? close > ma : true
ma_short = use_ma ? close < ma : true


// get prior days high low
prior_high = request.security(syminfo.tickerid, 'D', high[1], lookahead=barmerge.lookahead_on)
prior_low = request.security(syminfo.tickerid, 'D', low[1], lookahead=barmerge.lookahead_on)

prior_day_cond = prev_day_range == 'Outside' and (close > prior_high or close < prior_low) ? true :
 prev_day_range == 'Inside' and (close < prior_high and close > prior_low) ? true : prev_day_range == 'None' ? true : false


// get open price
open_time = time(timeframe.period, day_open, "America/New_York")
var float open_price = na
open_price := open_time ? open : open_price[1]
var line open_line = na
// bgcolor(open_time ? color.new(color.yellow,70) : na)

if use_day_open
    if open_time
        // adjust yesterdays line
        // line.set_extend(open_line, extend.none)
        // new line
        open_line := line.new(x1 = bar_index, y1 = open_price, x2 = bar_index + 1, y2 = open_price, 
         xloc = xloc.bar_index, extend = extend.none, color = close > open_price ? color.new(#2ba12f, 0) : color.new(#ff0000, 0),
         style = line.style_solid, width = 2)
    else
        line.set_x2(open_line, bar_index)
        line.set_color(open_line, close > open_price ? color.new(#2ba12f, 0) : color.new(#ff0000, 0))

open_price_buy = close > open_price or not use_day_open
open_price_sell = close < open_price or not use_day_open


// range time filter
// array management
f_array_add_pop(array, new_value_to_add) =>
    array.unshift(array, new_value_to_add)
    array.pop(array)


// manage all lines but mid
f_manage_lines(sess_calc, sess_draw, line_array, line_color, line_style, line_width, condition, update_value) =>

    newest_line = array.get(line_array,0)

    // during session 1 calculation time
    if sess_calc
        // new lines
        if not sess_calc[1]
            line.delete(array.get(line_array, array.size(line_array) - 1))
            f_array_add_pop(line_array, line.new(x1 = time, y1 = update_value, x2 = time+2, y2 = update_value,
             xloc = xloc.bar_time, extend = extend.right, color = line_color, width = line_width,
             style = (line_style == 'Solid' ? line.style_solid : line_style == 'Dashed' ? line.style_dashed : line_style == 'Dotted' ? line.style_dotted : line.style_solid)))

        // update line values
        if sess_calc[1]
            line.set_x2(newest_line, time)
            if condition
                line.set_y1(newest_line, update_value)
                line.set_y2(newest_line, update_value)

    else
        // end lines and end extension
        if sess_draw[1]
            // highest body
            line.set_x2(newest_line, time)
            line.set_extend(newest_line, extend.none)

var sess1_highesthigh_line = array.new_line(50, na)
var sess1_lowestlow_line = array.new_line(50, na)

sess1_css_highest =     color.new(color.yellow,10)
sess1_style_highest =   'Solid'
sess1_width_highest =   1
sess1_css_lowest =     color.new(color.yellow,10)
sess1_style_lowest =   'Solid'
sess1_width_lowest =    1
is_range_time = time(timeframe.period, str.format('{0}:1234567', range_time), 'America/New_York') and use_range_time and timeframe.isintraday 
is_range_timedraw = time(timeframe.period, str.format('{0}:1234567', range_timedraw), 'America/New_York') and use_range_time and timeframe.isintraday 
f_manage_lines(is_range_time, is_range_timedraw, sess1_highesthigh_line, sess1_css_highest, sess1_style_highest, sess1_width_highest, high > line.get_y1(array.get(sess1_highesthigh_line,0)), high)
f_manage_lines(is_range_time, is_range_timedraw, sess1_lowestlow_line, sess1_css_lowest, sess1_style_lowest, sess1_width_lowest, low < line.get_y1(array.get(sess1_lowestlow_line,0)), low)

sess1_buy = (not is_range_time and is_range_timedraw and close > line.get_y2(array.get(sess1_highesthigh_line,0))) or not use_range_time
sess1_sell = (not is_range_time and is_range_timedraw and close < line.get_y2(array.get(sess1_lowestlow_line,0))) or not use_range_time


// support and resistance
resistance_value = ta.valuewhen(ta.pivothigh(high,left_bars,right_bars), high[right_bars], 0)
support_value = ta.valuewhen(ta.pivotlow(low,left_bars,right_bars), low[right_bars], 0)
var line resistance = na
var line support = na
if use_support_resistance
    if resistance_value != resistance_value[1]
        line.set_extend(resistance, extend.none)
        resistance := line.new(x1 = time[right_bars], y1 = resistance_value, x2 = time[right_bars + 1], y2 = resistance_value,
         color = color.new(#FF0000,0), extend = extend.right, xloc = xloc.bar_time)
    else
        line.set_x2(resistance, time)
    if support_value != support_value[1]
        line.set_extend(support, extend.none)
        support := line.new(x1 = time[right_bars], y1 = support_value, x2 = time[right_bars + 1], y2 = support_value,
         color = color.new(#233dee,0), extend = extend.right, xloc = xloc.bar_time)
    else
        line.set_x2(support, time)
        
sr_short = ta.ema(volume, 5)
sr_long = ta.ema(volume, 10)
sr_osc = 100 * (sr_short - sr_long) / sr_long
sr_buy = (close >= line.get_y1(resistance) and sr_osc > sr_volumethres) or not use_support_resistance
sr_sell = (close <= line.get_y1(support) and  sr_osc > sr_volumethres ) or not use_support_resistance
    


//  define vars
var bool in_trade = false
var int trade_side = 0
var int last_trade = na

var float target = 99999999.99
var float stop = 0.000000
var float entry_price = 0.00

var bool long_entry = false
var bool short_entry = false

var bool tgt_hit = false
var bool stop_hit = false

var bool long_exit = false
var bool short_exit = false

var max_daily_gain_hit = false
var max_daily_loss_hit = false
var max_weekly_gain_hit = false
var max_weekly_loss_hit = false
var max_monthly_gain_hit = false
var max_monthly_loss_hit = false
var max_gains_hit = false
var max_losses_hit = false

var float strategy_openpips = 0.00
var float strategy_newclosedpips = 0.00
var float daily_pips = 0.00
var float weekly_pips = 0.00
var float monthly_pips = 0.00
var float beginning_of_day_pips = 0.00
var float beginning_of_week_pips = 0.00
var float beginning_of_month_pips = 0.00


// define entry
long_trade_side = long_to_short_lock ? (last_trade == -1 or na(last_trade)) : trade_side != 1 
short_trade_side = long_to_short_lock ? (last_trade == 1 or na(last_trade)) : trade_side != -1 

long_conditions = is_trade_sess and lightning_bull and prev_candle_long and ma_long and sess1_buy and sr_buy and tradeType != "SHORT"
short_conditions = is_trade_sess and lightning_bear and prev_candle_short and ma_short and sess1_sell and sr_sell and tradeType != "LONG"
long_entry :=  (inverse_settings ? short_conditions : long_conditions) and prior_day_cond and open_price_buy and not
 (max_daily_gain_hit or max_weekly_gain_hit or max_monthly_gain_hit) and not
 (max_daily_loss_hit or max_weekly_loss_hit or max_monthly_loss_hit) and long_trade_side and not long_entry[1]
short_entry := (inverse_settings ? long_conditions : short_conditions) and prior_day_cond and open_price_sell and not
 (max_daily_gain_hit or max_weekly_gain_hit or max_monthly_gain_hit) and not
 (max_daily_loss_hit or max_weekly_loss_hit or max_monthly_loss_hit) and short_trade_side and not short_entry[1]

// define position
entry_price := long_entry[1] or short_entry[1] ? open :  in_trade == true ? entry_price[1] : na
trade_side := long_entry[1] ? 1 : short_entry[1] ? -1 : in_trade == false ? 0 : trade_side[1]
last_trade := (trade_side != 0 and trade_side != trade_side[1]) ? trade_side : last_trade[1]

// define targets and stops
if use_tp
    target := trade_side == 1 ? (tp_type == 'Percent' ? (entry_price + (entry_price * (tp_amount/100))) : entry_price + tp_amount ) 
     : trade_side == -1 ? (tp_type == 'Percent' ? (entry_price - (entry_price * (tp_amount/100))) : entry_price - tp_amount ) : na
else
    target := na
    
if use_sl    
    stop := trade_side == 1 ?  ( sl_type == 'Percent' ? (entry_price - (entry_price * (sl_amount/100))) : entry_price - sl_amount ) : trade_side == -1 ? ( sl_type == 'Percent' ? (entry_price + (entry_price * (sl_amount/100))) : entry_price + sl_amount ) : na
else    
    stop := na

if use_rr_tp
    target := long_entry[1] ? open + math.abs(open - low[1]) * rr_tp 
     : short_entry[1] ? open - math.abs(open - high[1]) * rr_tp
     : target[1]

    stop := long_entry[1] ? low[1]
     : short_entry[1] ? high[1]
     : stop[1]


// MAX DAILY GAIN / LOSS CALCULATIONS
pip_mult = syminfo.mintick
//open pnl
if in_trade
    if trade_side == 1
        strategy_openpips := (close - entry_price) / pip_mult * trade_size
    else if trade_side == -1
        strategy_openpips := (entry_price - close) / pip_mult * trade_size
    else
        strategy_openpips := 0
else 
    strategy_openpips := 0   


// see if max profit/loss thresholds are met
max_daily_gain_hit := dayofweek != dayofweek[1] ? false : use_max_daily_gain and daily_pips[1] + strategy_openpips >= max_daily_gain ? true : max_daily_gain_hit[1]
max_weekly_gain_hit :=  weekofyear != weekofyear[1] ? false : use_max_weekly_gain and weekly_pips[1] + strategy_openpips >= max_weekly_gain ? true : max_weekly_gain_hit[1]
max_monthly_gain_hit := month != month[1] ? false : use_max_monthly_gain and monthly_pips[1] + strategy_openpips >= max_monthly_gain ? true : max_monthly_gain_hit[1]

max_daily_loss_hit := dayofweek != dayofweek[1] ? false : use_max_daily_loss and daily_pips[1] + strategy_openpips <= -max_daily_loss ? true : max_daily_loss_hit[1]
max_weekly_loss_hit :=  weekofyear != weekofyear[1] ? false : use_max_weekly_loss and weekly_pips[1] + strategy_openpips <= -max_weekly_loss ? true : max_weekly_loss_hit[1]
max_monthly_loss_hit := month != month[1] ? false : use_max_monthly_loss and monthly_pips[1] + strategy_openpips <= -max_monthly_loss ? true : max_monthly_loss_hit[1]


// update position management
max_gains_hit := trade_side != 0 and (max_daily_gain_hit or max_weekly_gain_hit or max_monthly_gain_hit)
max_losses_hit := trade_side != 0 and (max_daily_loss_hit or max_weekly_loss_hit or max_monthly_loss_hit)
tgt_hit := trade_side == 1 and high >= target or trade_side == -1 and low <= target
stop_hit := trade_side == 1 and low <= stop or trade_side == -1 and high >= stop

long_exit := ( (tgt_hit or stop_hit or max_gains_hit or max_losses_hit or not is_trade_sess) ) and in_trade[1] == true and trade_side[1] == 1
short_exit := ( (tgt_hit or stop_hit or max_gains_hit or max_losses_hit or not is_trade_sess)) and in_trade[1] == true and trade_side[1] == -1   

in_trade := long_entry or short_entry ? true : long_exit or short_exit ?  false : in_trade[1]


// closed pnl calculations
// reversal trades pnl calculation
if trade_side[1] == 1 and trade_side == -1 
    strategy_newclosedpips := (open - entry_price) / pip_mult * trade_size
else  if trade_side[1] == -1 and trade_side == 1 
    strategy_newclosedpips := (entry_price[1] - open) / pip_mult * trade_size
else 
    strategy_newclosedpips := 0 
    
// time exits pnl calculation
if not is_trade_sess[1] and is_trade_sess[2] 
    if trade_side[1] == 1 and trade_side == 0
        strategy_newclosedpips := (open - entry_price) / pip_mult * trade_size
    if trade_side[1] == -1 and trade_side == 0
        strategy_newclosedpips := (entry_price[1] - open) / pip_mult * trade_size
else 
    strategy_newclosedpips := 0 


// all other exits pnl calculation
if long_exit[1]
    if tgt_hit[1]
        strategy_newclosedpips := (target[1] - entry_price[1]) / pip_mult * trade_size
    else if stop_hit[1]
        strategy_newclosedpips := (stop[1] - entry_price[1]) / pip_mult * trade_size
    else
        strategy_newclosedpips := (open - entry_price[1]) / pip_mult * trade_size
else if short_exit[1]
    if tgt_hit[1]
        strategy_newclosedpips := (entry_price[1] - target[1]) / pip_mult * trade_size
    else if stop_hit[1]
        strategy_newclosedpips := (entry_price[1] - stop[1]) / pip_mult * trade_size
    else
        strategy_newclosedpips := (entry_price[1] - open) / pip_mult * trade_size
else 
    strategy_newclosedpips := 0 


// // calculate pips
daily_pips := dayofweek != dayofweek[1] ? 0 : daily_pips[1] + strategy_newclosedpips
weekly_pips := weekofyear != weekofyear[1] ? 0 : weekly_pips[1] + strategy_newclosedpips
monthly_pips := month != month[1] ? 0 : monthly_pips[1] + strategy_newclosedpips


// debug pips
// bgcolor(dayofweek != dayofweek[1]  ? color.white : max_daily_gain_hit ? color.new(color.green, 70) : max_daily_loss_hit ? color.new(color.red, 70) : na)
// // bgcolor(max_daily_gain_hit == true ? color.green : na)
// barcolor(tgt_hit ? color.green : stop_hit ? color.red : na)
// plot(monthly_pips, color = color.teal)
// plot(strategy_openpips, color = color.yellow)
// plot(strategy_newclosedpips, color = color.fuchsia)
// // plot(daily_pips, color = color.teal)
// // plot(strategy_openpips, color = color.yellow)
// // plot(strategy_newclosedpips, color = color.fuchsia)


//  calculate variables for text
profit_pct = math.round(math.abs((target - entry_price) / target * 100),2)
stop_pct = math.round(math.abs((stop - entry_price) / stop * 100),2)

target_text = 'TGT: ' + str.tostring(math.round_to_mintick(target)) + ' (' + str.tostring(profit_pct) + '%)'
stoploss_text = 'SL: ' + str.tostring(math.round_to_mintick(stop)) + ' (' + str.tostring(stop_pct) + '%)'


// --TRADE POSIITION LINES-- //
var line current_entryline = na
var line current_targetline = na
var line current_stopline = na

previous_entrylines = array.new_line(50, na)
previous_targetlines = array.new_line(50, na)
previous_stoplines = array.new_line(50, na)

var box profit_box = na
var box loss_box = na

previous_profit_box = array.new_box(50,na)
previous_loss_box = array.new_box(50,na)

show_position_tool = line_showing != 'None' 
show_previous = line_showing == 'Past' or line_showing == 'Current & Past'


// --FUNCTION TO COPY LINE TO STORED ARRAY-- //
f_copy_n_store(current_line, storing_array) =>
    if show_previous
        copied_line = line.copy(current_line)
        line.set_extend(copied_line, extend.none)
        line.set_x2(copied_line, bar_index)
        f_array_add_pop(storing_array, copied_line)
    line.delete(current_line)
// --FUNCTION TO COPY LINE TO STORED ARRAY-- //


// --FUNCTION TO COPY BOX TO STORED ARRAY-- //
f_copy_n_storebox(current_box, storing_array, box_type, valign_type) =>
    if show_previous
        copied_box = box.copy(current_box)
        box.set_extend(copied_box, extend.none)
        box.set_right(copied_box, bar_index)
        box.set_text(copied_box, box_type == 1 ? target_text : stoploss_text)
        box.set_text_color(copied_box, css_toolcolor)
        box.set_text_size(copied_box, size.small)
        box.set_text_valign(copied_box, valign_type == 1 ? text.align_top : text.align_bottom)
        f_array_add_pop(storing_array, copied_box)

    box.delete(current_box)
// --FUNCTION TO COPY LINE TO STORED ARRAY-- //



// new lines
if long_entry[1] or short_entry[1] and show_position_tool
    // if we were in a trade and flipped side
    if entry_price[1] != 0
        f_copy_n_storebox(profit_box, previous_profit_box, 1,long_entry[1] ? 1 : -1)
        f_copy_n_storebox(loss_box, previous_loss_box, -1, long_entry[1] ? -1 : 1)
    profit_box := box.new(left = bar_index, top = target, right = bar_index + 1, bottom = entry_price, border_color = color.new(css_targetline, 50), border_width = 1, border_style = line.style_solid,
     extend = extend.right, bgcolor = css_targetline, text = target_text, text_size = size.small, text_color = css_toolcolor, text_halign = text.align_center, text_valign = long_entry[1] ? text.align_top : text.align_bottom)
    loss_box := box.new(left = bar_index, top = entry_price, right = bar_index + 1, bottom = stop, border_color = color.new(css_stopline, 50), border_width = 1, border_style = line.style_solid,
     extend = extend.right, bgcolor = css_stopline, text = stoploss_text, text_size = size.small, text_color = css_toolcolor, text_halign = text.align_center, text_valign =  long_entry[1] ?text.align_bottom : text.align_top)
    

// manage lines
if long_exit or short_exit
    f_copy_n_storebox(profit_box, previous_profit_box, 1, long_exit ? 1 : -1)
    f_copy_n_storebox(loss_box, previous_loss_box, -1, long_exit ? -1 : 1)
else
    box.set_right(profit_box, bar_index)
    box.set_right(loss_box, bar_index)
// --TRADE POSIITION LINES-- //


// backtest certain time
// backtest_start = input.time(defval=timestamp('01 Jan 2021 13:30 +0000'), title='Backtesting Start Time', group = 'Backtesting Settings')
// backtest_end = input.time(defval=timestamp('01 Dec 2023 19:30 +0000'), title='Backtesting End Time', group = 'Backtesting Settings')
// is_backtesting_time = time > backtest_start and time < backtest_end


// --ORDERS-- //
if not is_trade_sess
    strategy.close_all(comment = 'EOD', immediately = true)

if (strategy.position_size > 0)
    strategy.exit(id="LE", limit=target, stop=stop , comment = "TP/SL")
if (strategy.position_size < 0)
    strategy.exit(id="SS_E", limit=target, stop=stop , comment = "TP/SL")

if long_exit
    strategy.close("LE", comment = "LX")
else if short_exit
    strategy.close("SS_E", comment = "SS_X")

if long_entry 
    strategy.entry("LE", strategy.long)
else if short_entry 
    strategy.entry("SS_E", strategy.short)



// --ORDERS-- //




// basically the old way what happeneed is that orders werent cancelled and they would overlap and that is why sometimes
//  it would enter and exit same bar. It is not always the accurate inputted stop price. There might be a workaround with
//  calling strategy order cancellations, but having an indicator follow the same backtesting "engine" might be far fetched. What I did is coded it like the other
//  work we have done. All take profits/stops should occur at the price they are assigned to UNLESS it is the bar following entry
//  then it will exit at that bars open.

// so it really comes down to how you want to calculate with tradingviews backtest engine. the way it is programmed now
// is like the most recent

Overview

Hercules Strategy Rewrite offers multi-layer filtering including moving average trend checks, prior day range conditions, daily open levels, and customizable session time filters. Positions are managed with auto-calculated risk-to-reward targets, optional percentage or tick-based stop losses, and directional trade locks. It overlays trade executions and strategy graphics directly on the price chart.

Details

Published by

g-moe on GitHub

Code credit

goodgains, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Candlestick patterns, Sessions & time, Support & resistance, Trend

Markets

Forex

Timeframes

M15-H1

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Settings

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

SettingTypeDefaultVariable
Lightning                  int500min_ticks
What trades should be taken ?   stringBOTHtradeType
Trading Sessionsession0900-1600trading_session
Inverse Signalsboolfalseinverse_settings
Next Trade Cannot Be Same Sideboolfalselong_to_short_lock
Engulfing Candles Onlybooltrueengulf_only
Previous Candle Filter    boolfalseuse_prev_candle
timeframeprev_tf
MA Filterboolfalseuse_ma
stringSMAma_type
sourceclosema_source
int50ma_length
Show all 40 settings
SettingTypeDefaultVariable
Prior Days Range           stringOutsideprev_day_range
Daily Open Filter        boolfalseuse_day_open
session0930-0931day_open
Time Range Filter       boolfalseuse_range_time
session0930-1030range_time
session0930-1600range_timedraw
Support/Resistance Breakboolfalseuse_support_resistance
S/R Left Barsint15left_bars
S/R Right Barsint15right_bars
S/R Volume Thresholdint20sr_volumethres
R:R Auto-Calculationbooltrueuse_rr_tp
rr_tpfloat2.0rr_tp
Alt Target        boolfalseuse_tp
tp_amountfloat1.00tp_amount
tp_typestringPercenttp_type
Alt Stop Loss      boolfalseuse_sl
sl_amountfloat1.00sl_amount
sl_typestringPercentsl_type
Trade Sizefloat1trade_size
Max Daily Gain (pips)    boolfalseuse_max_daily_gain
max_daily_gainint3000max_daily_gain
Max Daily Loss (pips)    boolfalseuse_max_daily_loss
max_daily_lossint3000max_daily_loss
Max Weekly Gain (pips) boolfalseuse_max_weekly_gain
max_weekly_gainint25000max_weekly_gain
Max Weekly Loss (pips) boolfalseuse_max_weekly_loss
max_weekly_lossint25000max_weekly_loss
Max Monthly Gain (pips)boolfalseuse_max_monthly_gain
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

106 stars

This strategy trades the three-candle strike pattern filtered by trend direction and time sessions. It calculates market regime using linear regression and exponential or smoothed moving averages to distinguish between ranging and trending conditions. Risk man

Strategy v5 Candlestick patternsTrend
Updated 2 years ago · GPL-3.0 GitHub repository of 3 Candle Strike Strategy

ATOM 1m scalp HK

by dearvn
43 stars

This overlay strategy targets one-minute ATOM scalps. It tracks pivot highs and lows as resistance and support, compares a three-period EMA with a multi-stage smoothed close, and flags long or short when price crosses that curve in the matching direction. Dail

Strategy v5 ScalpingSupport & resistance Repaints
Updated 2 years ago · None stated GitHub repository of ATOM 1m scalp HK

1-Min Gold Taylor Technique

by eddiebelaval
7 stars

This intraday strategy implements session-based trading rules tailored for gold on short timeframes. It tracks the Asian session price range, VWAP, 20-period EMA, and previous day high and low levels to identify liquidity sweeps during London and New York trad

Strategy v6 Sessions & timeSupport & resistance
Updated 3 months ago · None stated GitHub repository of 1-Min Gold Taylor Technique

Diego's Strategy

by jerryinyang
5 stars

Diego's Strategy draws confirmed swing pivots on the price chart and connects them with dashed lines when the price move exceeds an ATR-based deviation threshold. It can plot Fibonacci retracement levels and use a chosen zone for entries, with separate Fibonac

Strategy v4 Support & resistanceTrend
Updated 2 years ago · None stated GitHub repository of Diego's Strategy

Dskyz Adaptive Futures Elite (DAFE)

by mushroom-men-Trading
2 stars

Dskyz Adaptive Futures Elite (DAFE) is an automated strategy designed for intraday trading. It generates long and short entries by pairing fast and slow moving average crossovers with candlestick pattern detection, filtered by RSI, volume, volatility, and a hi

Strategy v6 Moving averagesCandlestick patterns
Updated 9 months ago · None stated GitHub repository of Dskyz Adaptive Futures Elite (DAFE)

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