Strategy · Pine Script v5 · On the chart

Mini-Project

by Core-Four· code credited to NewTrade101

Mini-Project is a multi-indicator trading strategy that overlays technical indicators directly on the price chart.

View on GitHub

GitHub stars2on the repository
Pine versionv5runs as is
Lines of code327
Settings24inputs
LicenceNone statedfile: MPL-2.0
Last update3 years ago16 Mar 2023

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

327 lines of Pine Script v5 from main.pine, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

main.pine
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © NewTrade101
//@version=5
//indicator('Mini-Project', shorttitle='Mini', overlay=true)
strategy('Mini-Project', shorttitle='Mini' ,overlay=true, margin_long=100, margin_short=100)
//---------------------------------------------------------Input----------------------------------------------------------


//Linear-Regression (LR) Input
lr_bool= input.bool(false,title = "Linear-Regression", group = "----------SetUp----------",tooltip = "This Uses Linear Regresion")
lr_len = input.int(300, title='Linear-Regression - Length',minval=0,maxval=1001,group = "----------Linear-Regression (LR) Setting----------",tooltip = "This Uses Linear Regresion")
lr_plot = input.bool(false,title = "Plot Linear-Regression", group = "----------Linear-Regression (LR) Setting----------",tooltip = "This Uses Linear Regresion")

//RSI Input
//rsi_plot =input.bool(false,title = "Plot RSI", group = "SetUp")
rsi_len = input.int(14,title = "RSI Length",minval = 1,maxval = 51,group = "----------RSI Setting----------",tooltip = "RSI Ralitive Strength Index")
rsi_bool =input.bool(false,title = "RSI", group = "----------SetUp----------",tooltip = "RSI Ralitive Strength Index")
rsi_low =input.int(30,minval=5,maxval=95,title = "RSI-Buy Line",group ="----------RSI Setting----------" ,tooltip = "RSI Ralitive Strength Index")
rsi_high =input.int(70,minval=5,maxval=95,title = "RSI-Sell Line",group ="----------RSI Setting----------" ,tooltip = "RSI Ralitive Strength Index")

//MACD
macd_bool = input.bool(false,title = "MACD",group = "----------SetUp----------",tooltip = "MACD ")
macd_fastlen=input.int(12,title = "MACD Fast Length",minval = 1,maxval = 201,group = "----------MACD Setting----------",tooltip = "MACD ")
macd_slowlen=input.int(26,title = "MACD Slow Length",minval = 1,maxval = 201,group = "----------MACD Setting----------",tooltip = "MACD ")

//SAR
sar_start=input.float(0.01,title = "Start",group = "----------SAR Setting----------",tooltip = "SAR is used here")
sar_incriment=input.float(0.0034,title = "Incriment",group = "----------SAR Setting----------",tooltip = "SAR is used here")
sar_bool =input.bool(false,title = "SAR", group = "----------SetUp----------",tooltip = "SAR is used here")
sar_plot = input.bool(false,title = "Plot SAR ", group = "----------SAR Setting----------",tooltip = "SAR is used here")

//Super -Trend
sp_atr= input.int(2,title = "Super-Trend ATR",group = "----------Super-Trend Setting----------",tooltip = "Super-Trend is used here")
sp_fact = input.float(5,title = "Super-Trend Factor",group = "----------Super-Trend Setting----------",tooltip = "Super-Trend is used here")
sp_bool = input.bool(false,title = "Super-Trend",group = "----------SetUp----------",tooltip = "Super-Trend is used here")
sp_plot= input.bool(false,title = "Plot Suprt-Trend",group = "----------Super-Trend Setting----------",tooltip = "Super-Trend is used here")

//---------------------------------------------------------Input----------------------------------------------------------



//---------------------------------------------------------Super-Trend----------------------------------------------------------

[supertrend,direction] = ta.supertrend(sp_fact,sp_atr)


plot(sp_bool == true and sp_plot==true ? supertrend : na)


sp_buy= ta.crossover(close,supertrend)
sp_sell= ta.crossunder(close,supertrend)


//---------------------------------------------------------Super-Trend----------------------------------------------------------




//---------------------------------------------------------SAR----------------------------------------------------------

my_sar = ta.sar(sar_start,sar_incriment,0.2)
plot(sar_bool==true and sar_plot == true? my_sar : na)


sar_buy = ta.crossover(close,my_sar)
sar_sell = ta.crossunder(close,my_sar)

//---------------------------------------------------------SAR----------------------------------------------------------



//---------------------------------------------------------MACD----------------------------------------------------------


[macdline,signalline,macdhist] = ta.macd(close,macd_fastlen,macd_slowlen,9)

macd_buy=ta.crossover(macdline,signalline)
macd_sell = ta.crossunder(macdline,signalline)

//plot(macdline)
//plot(signalline)


//---------------------------------------------------------MACD----------------------------------------------------------

//---------------------------------------------------------RSI----------------------------------------------------------

my_rsi= ta.rsi(close,rsi_len)
rsi_buy= ta.crossover(my_rsi,rsi_low)
rsi_sell= ta.crossunder(my_rsi,rsi_high)

//---------------------------------------------------------RSI----------------------------------------------------------


//---------------------------------------------------------Linear-Regression----------------------------------------------------------

a = ta.linreg(high, lr_len, 0)
b = ta.linreg(low, lr_len, 0)
c = -ta.dev(low, lr_len) + b
d = ta.dev(high, lr_len) + a

plot(lr_plot == true ? a:na,title="Linear-Regression -UperBand")
plot(lr_plot==true ? b :na,title="Linear-Regression -LowerBand")
plot(lr_plot==true ? c :na, color=c > c[1] ? color.green : color.red,title="Linear-Regression -Middle UperBand")
plot(lr_plot==true ? d :na, color=d > d[1] ? color.green : color.red,title="Linear-Regression -Middle LowerBand")

lr_buy = ta.crossover(close,c)
lr_sell = ta.crossunder(close,d)
//---------------------------------------------------------Linear-Regression----------------------------------------------------------






//---------------------------------------------------------Plot-Trade-----------------------------------------------------------------


//---------------------------------------------------------Deth-Cross-----------------------------------------------------------------
dc_ema1 = ta.ema(close,50)
dc_ema2 = ta.ema(close,200)

buy = ta.crossover(dc_ema1,dc_ema2)
sell =ta.crossunder(dc_ema1,dc_ema2)


//---------------------------------------------------------Deth-Cross-----------------------------------------------------------------

// # ========================================================================= #
// #                   |   StopLoss  |
// # ========================================================================= #
if(lr_bool)
    rsi_bool := false
    macd_bool:=false
    sar_bool:=false
    sp_bool:=false
    buy := lr_buy
    sell := lr_sell

if(rsi_bool)
    lr_bool:=false
    macd_bool:=false
    sar_bool:=false
    sp_bool:=false
    buy := rsi_buy
    sell := rsi_sell

if(macd_bool)
    lr_bool:=false
    rsi_bool:=false
    sar_bool:=false
    sp_bool:=false
    buy := macd_buy
    sell := macd_sell

if(sar_bool)
    lr_bool:=false
    rsi_bool:=false
    macd_bool:=false
    sp_bool:=false
    buy := sar_buy
    sell := sar_sell

if(sp_bool)
    lr_bool:=false
    rsi_bool:=false
    macd_bool:=false
    sar_bool:=false
    buy := sp_buy
    sell := sp_sell

//  ----- Inputs: stoploss %, takeProfit %
stopLossPercentage = input.float(defval=1, title='StopLoss %', minval=0.01, step=1,maxval=20,group="StopLoss") / 1000
takeProfit = input.float(defval=3, title='Take Profit %', minval=0.01, step=1,maxval=20,group="StopLoss") / 1000
//  ----- Exit and Entry Conditions
isLong = buy
LongExit = buy or sell

//  ----- Calculate Stoploss and Take Profit values
SL = strategy.position_avg_price * (1 - stopLossPercentage)
TP = strategy.position_avg_price * (1 + takeProfit)
cpb = strategy.position_avg_price
//  ----- Strategy Enter, and exit when conditions are met
strategy.entry("Enter Long", strategy.long, when=isLong)
if strategy.position_size > 0 
    strategy.close("Exit Long", LongExit)
    strategy.exit(id="Exit Long", stop=SL, limit=TP)



//  ----- Plot Stoploss and TakeProfit lines
BSL=plot(strategy.position_size > 0 ? SL : na, style=plot.style_linebr, color=color.red, linewidth=2, title="StopLoss")
BTP=plot(strategy.position_size > 0 ? TP : na, style=plot.style_linebr, color=color.green, linewidth=2, title="TakeProfit")
BCP=plot(strategy.position_size > 0 ? cpb : na, style=plot.style_linebr, color=color.white, linewidth=2, title="Curent Prise Buy")
fill(BCP, BSL, color.new(color.red, 90))
fill(BCP, BTP, color.new(color.green, 90))
//---------------------------------------------------------------------------------------------------------------------


//  ----- Exit and Entry Conditions
isSell = sell
SellExit = buy or sell

//  ----- Calculate Stoploss and Take Profit values
SL1 = strategy.position_avg_price / (1 - stopLossPercentage)
TP1 = strategy.position_avg_price / (1 + takeProfit)
cp = strategy.position_avg_price
//  ----- Strategy Enter, and exit when conditions are met
strategy.entry("Enter Short", strategy.short, when=isSell)
if strategy.position_size < 0 
    strategy.close("Exit Short", SellExit)
    strategy.exit(id="Exit Short", stop=SL1, limit=TP1)

//  ----- Plot Stoploss and TakeProfit lines
SS=plot(strategy.position_size < 0 ? SL1 : na, style=plot.style_linebr, color=color.red, linewidth=2, title="StopLoss Sell")

STP=plot(strategy.position_size < 0 ? TP1 : na, style=plot.style_linebr, color=color.green, linewidth=2, title="TakeProfit Sell")
CS=plot(strategy.position_size < 0 ? cp : na, style=plot.style_linebr, color=color.white, linewidth=2, title="Curent Prise Sell")
fill(SS, CS, color.new(color.red, 90))
fill(CS, STP, color.new(color.green, 90))

// # ========================================================================= #
// #                   |   StopLoss  |
// # ========================================================================= #

//--------------------------------------------------------Plot-Trade-----------------------------------------------------






// # ========================================================================= #
// #                   |   BackTester  |
// # ========================================================================= #


startBalance        = input.float(title="Starting Balance", defval=10000.0, group="g_tester", tooltip="Your starting balance for the custom inbuilt tester system")
riskPerTrade        = input.float(title="Risk Per Trade", defval=1.0, group="g_tester", tooltip="Your desired % risk per trade (as a whole number)")
drawTester          = input.bool(title="Draw Backtester", defval=true, group="g_tester", tooltip="Turn on/off inbuilt backtester display")
rr = input.float(title='R:R', defval=1.0, group="g_tester", tooltip='Risk:Reward profile')


// Save trade stop & target & position size if a valid setup is detected
var t_entry = 0.0
var t_stop = 0.0
var t_target = 0.0
var t_direction = 0

// Get indicator values
atr = ta.atr(14)

// Custom function to convert pips into whole numbers
toWhole(number) =>
    return_1 = atr < 1.0 ? number / syminfo.mintick / (10 / syminfo.pointvalue) : number
    return_1 := atr >= 1.0 and atr < 100.0 and syminfo.currency == 'JPY' ? return_1 * 100 : return_1
    return_1

// Custom function to convert whole numbers back into pips
toPips(number) =>
    return_2 = atr >= 1.0 ? number : number * syminfo.mintick * (10 / syminfo.pointvalue)
    return_2 := atr >= 1.0 and atr < 100.0 and syminfo.currency == 'JPY' ? return_2 / 100 : return_2
    return_2


// Custom function to truncate (cut) excess decimal places
truncate(_number, _decimalPlaces) =>
    _factor = math.pow(10, _decimalPlaces)
    int(_number * _factor) / _factor


// --- BEGIN TESTER CODE --- //
// Declare performance tracking variables
var balance = startBalance
var drawdown = 0.0
var maxDrawdown = 0.0
var maxBalance = 0.0
var totalPips = 0.0
var totalWins = 0
var totalLoss = 0

// Detect winning trades
if strategy.wintrades != strategy.wintrades[1]
    balance += riskPerTrade / 100 * balance * rr
    totalPips += math.abs(t_entry - t_target)
    totalWins += 1
    if balance > maxBalance
        maxBalance := balance
        maxBalance

// Detect losing trades
if strategy.losstrades != strategy.losstrades[1]
    balance -= riskPerTrade / 100 * balance
    totalPips -= math.abs(t_entry - t_stop)
    totalLoss += 1
    // Update drawdown
    drawdown := balance / maxBalance - 1
    if drawdown < maxDrawdown
        maxDrawdown := drawdown
        maxDrawdown

// Prepare stats table
var table testTable = table.new(position.top_right, 5, 2, border_width=1)
f_fillCell(_table, _column, _row, _title, _value, _bgcolor, _txtcolor) =>
    _cellText = _title + '\n' + _value
    table.cell(_table, _column, _row, _cellText, bgcolor=_bgcolor, text_color=_txtcolor)

// Draw stats table
var bgcolor = color.new(color.black, 0)
if drawTester
    if barstate.islastconfirmedhistory
        // Update table
        dollarReturn = balance - startBalance
        f_fillCell(testTable, 0, 0, 'Total Trades:', str.tostring(strategy.closedtrades), bgcolor, color.white)
        f_fillCell(testTable, 0, 1, 'Win Rate:', str.tostring(truncate(strategy.wintrades / strategy.closedtrades * 100, 2)) + '%', bgcolor, color.white)
        f_fillCell(testTable, 1, 0, 'Starting:', '$' + str.tostring(startBalance), bgcolor, color.white)
        f_fillCell(testTable, 1, 1, 'Ending:', '$' + str.tostring(truncate(balance, 2)), bgcolor, color.white)
        f_fillCell(testTable, 2, 0, 'Return:', '$' + str.tostring(truncate(dollarReturn, 2)), dollarReturn > 0 ? color.green : color.red, color.white)
        f_fillCell(testTable, 2, 1, 'Pips:', (totalPips > 0 ? '+' : '') + str.tostring(truncate(toWhole(totalPips), 2)), bgcolor, color.white)
        f_fillCell(testTable, 3, 0, 'Return:', (dollarReturn > 0 ? '+' : '') + str.tostring(truncate(dollarReturn / startBalance * 100, 2)) + '%', dollarReturn > 0 ? color.green : color.red, color.white)
        f_fillCell(testTable, 3, 1, 'Max DD:', str.tostring(truncate(maxDrawdown * 100, 2)) + '%', color.red, color.white)
// --- END TESTER CODE --- //


// # ========================================================================= #
// #                   |   BackTester  |
// # ========================================================================= #

Overview

Mini-Project provides modular components including Linear Regression, the Relative Strength Index (RSI), MACD, Parabolic SAR, and Supertrend. Users can toggle each indicator individually to build custom signal combinations, such as Supertrend crossover entries. Exits are governed by configurable stop loss and take profit percentages alongside risk-per-trade position settings. By default, all indicator modules are turned off, requiring users to activate their preferred setup before generating trades.

Details

Published by

Core-Four on GitHub

Code credit

NewTrade101, as written in the script's header

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

Trend, Oscillators & momentum, Volatility & bands

Markets

Stocks, Crypto, Forex

Timeframes

Any timeframe

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
Linear-Regressionboolfalselr_bool
Linear-Regression - Lengthint300lr_len
Plot Linear-Regressionboolfalselr_plot
RSI Lengthint14rsi_len
RSIboolfalsersi_bool
RSI-Buy Lineint30rsi_low
RSI-Sell Lineint70rsi_high
MACDboolfalsemacd_bool
MACD Fast Lengthint12macd_fastlen
MACD Slow Lengthint26macd_slowlen
Startfloat0.01sar_start
Incrimentfloat0.0034sar_incriment
Show all 24 settings
SettingTypeDefaultVariable
SARboolfalsesar_bool
Plot SAR boolfalsesar_plot
Super-Trend ATRint2sp_atr
Super-Trend Factorfloat5sp_fact
Super-Trendboolfalsesp_bool
Plot Suprt-Trendboolfalsesp_plot
StopLoss %float1stopLossPercentage
Take Profit %float3takeProfit
Starting Balancefloat10000.0startBalance
Risk Per Tradefloat1.0riskPerTrade
Draw BacktesterbooltruedrawTester
R:Rfloat1.0rr
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 trading strategy combines three Exponential Moving Averages (8, 14, and 50 periods by default) with Stochastic RSI and Average True Range (ATR). It enters a long position when EMA 1 is above EMA 2, EMA 2 is above EMA 3, and the Stochastic RSI %K line cros

Strategy v4 TrendOscillators & momentum
Updated 2 years ago · GPL-3.0 GitHub repository of 3 x EMA + Stochastic RSI + ATR

Momentum Rider DAILY FINAL

by greenpeas007
58 stars

This strategy combines exponential moving averages (EMA 9, 21, 50), RSI, MACD, and Supertrend indicators to enter long positions. It triggers trades using six dynamic setups based on momentum breakouts, EMA crossovers, and pullbacks. Position sizing is compute

Strategy v6 TrendOscillators & momentum Repaints
Updated 4 months ago · Custom licence GitHub repository of Momentum Rider DAILY FINAL
57 stars

This strategy identifies trend reversals through market structure changes (CHoCH) filtered by MACD momentum. It initiates long positions on bullish structure breaks when MACD is positive and above its signal line, and short positions on bearish breaks when MAC

Strategy v6 SMC / ICT / price actionOscillators & momentum Repaints
Updated 1 year ago · Apache-2.0 GitHub repository of Market Structure MACD 4H + Trailing

CombinedBinHAndClucV6

by viktors1982
36 stars

CombinedBinHAndClucV6 is a trading strategy based on the popular BinHV45 and ClucMay72018 algorithms. It calculates dual Bollinger Bands, Exponential Moving Averages, Relative Strength Index, Average True Range, and volume metrics across primary and one-hour h

Strategy v4 Volatility & bandsOscillators & momentum Repaints
Updated 2 years ago · None stated GitHub repository of CombinedBinHAndClucV6
27 stars

LuxAlgo Hybrid Gold Scalper is a price-chart strategy aimed at gold. It stacks a fast, slow, trend and 200-period bias EMA to mark trend direction, then filters strength with RSI, ADX and an intraday VWAP. Swing highs and lows are marked from pivot length. Set

Strategy v5 TrendOscillators & momentum
Updated 5 months ago · None stated GitHub repository of LuxAlgo Hybrid Gold Scalper

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