Indicator · Pine Script v6 · Own pane

Swing Trading Indicator

by armaandamani· code credited to Damani1234

A separate-pane indicator built for crypto swing and day trading with an external bot.

View on GitHub

Repaints

GitHub stars1on the repository
Pine versionv6current
Lines of code275
Settings0inputs
LicenceNone statedfile: MPL-2.0
Last update1 year ago11 Jul 2025

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 indicator, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart, then adjust the settings with the gear icon next to its name.

Source Code

275 lines of Pine Script v6 from src/TATradingAlgo.pinescript, published under MPL-2.0 (file header). Keep the author's credit and licence lines when you reuse it.

TATradingAlgo.pinescript
// This Pine Script™ code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © Damani1234

//@version=6
indicator("Swing Trading Indicator", overlay = false)

// 1) General Variables (Strategy + 3Commas credentials)

// 3Commas credentials
SECRET   = ("__")
BOT_UUID = ("__")
// FEE = __
// FEE_FACTOR = (1 - FEE)
varip float remainingEquity  = __


// Entry percentages
BASE_PERCENTAGE_BULLISH = 35.0
BASE_PERCENTAGE_BEARISH = 15.0
BOLLINGERPOSSIZE      = 50.0
INCREMENT             = 5

// 2) Internal variables to track sub-positions
varip bearishEntryPrices = array.new_float() // approximate fill price
varip bearishEntrySizes  = array.new_float() // # of contacts
varip bullishEntryPrices = array.new_float() // approximate fill price
varip bullishEntrySizes  = array.new_float() // # of contracts
varip float bollingerPrice   = na
varip float bollingerSize    = na
varip x   = 0
varip y   = 0

// Managing repeats
varip bool bollingerBuyAlertFired = false
varip bool bollingerSellAlertFired = true


// 3) INDICATORS

src  = close

// Stochastic RSI
SMOOTH_K     = 6
SMOOTH_D     = 6
LENGTH_RSI   = 28
LENGTH_STOCH = 28

rsiVal      = ta.rsi(src, LENGTH_RSI)
k           = ta.sma(ta.stoch(rsiVal, rsiVal, rsiVal, LENGTH_STOCH), SMOOTH_K)
d           = ta.sma(k, SMOOTH_D)

plot(k, "K", color=color.new(color.blue, 0))
plot(d, "D", color=color.new(color.orange, 0))
hOB = hline(25, "Stoch Overbought", color=#787B86)
hOS = hline(10, "Stoch Oversold",   color=#787B86)
fill(hOB, hOS, color=color.new(color.blue, 85), title="Stoch Background")


// MACD (for bullish/bearish trend determination)
FAST_LEN   = 216
SLOW_LEN   = 432
SIGNAL_LEN = 144

[macdLine, macdSignal, _] = ta.macd(src, FAST_LEN, SLOW_LEN, SIGNAL_LEN)
plot(macdLine, "MACD", color=color.new(color.blue, 0))
plot(macdSignal, "Signal", color=color.new(color.orange, 0))

// MFI

MFI_LENGTH = 864
MFI_SRC = hlc3
mfi = ta.mfi(MFI_SRC, MFI_LENGTH)
plot(mfi, "MFI", color=#7E57C2)
overbought=hline(56, title="MFI Overbought", color=#787B86)
oversold=hline(45, title="MFI Oversold", color=#787B86)

// ADX

// ADX_LEN = 14
// DI_LEN  = 14

// dirmov(length) =>
//     up        = ta.change(high)
//     down      = -ta.change(low)
//     plusDM    = na(up)   ? na : (up > down and up > 0   ? up   : 0)
//     minusDM   = na(down) ? na : (down > up and down > 0 ? down : 0)
//     trTwo     = math.max(high - low, math.abs(high - nz(src[1])), math.abs(low - nz(src[1])))
//     truerange = ta.rma(trTwo, length)
//     plus      = fixnan(100 * ta.rma(plusDM,  length) / truerange)
//     minus     = fixnan(100 * ta.rma(minusDM, length) / truerange)
//     [plus, minus]

// adx(di_length, adx_length) =>
//     [plus, minus] = dirmov(di_length)
//     sum           = plus + minus
//     adx_          = 100 * ta.rma(math.abs(plus - minus) / (sum == 0 ? 1 : sum), adx_length)
//     adx_

// sig = adx(DI_LEN, ADX_LEN)
// plot(sig, color=color.red, title="ADX")


// CMF

// var float cumVol = 0.0
// cumVol += nz(volume)
// if barstate.islast and cumVol == 0
//     runtime.error("No volume data from data vendor.")

// CMF_LEN = 25
// ad      = (src == high and src == low) or (high == low) ? 0 : ((2*src - low - high)/(high - low))*volume
// mf      = math.sum(ad, CMF_LEN) / math.sum(volume, CMF_LEN)
// plot(mf, color=#43A047, title="CMF")
// hline(0, "Zero", color=#787B86, linestyle=hline.style_dashed)

// Short Bollinger Bands (for sell signals)

LENGTH = 2016
MULT = 2.5

basis = ta.ema(src, LENGTH)
dev = MULT * ta.stdev(src, LENGTH)
upper = basis + dev
lower = basis - dev
p1 = plot(upper, "Bollinger Upper", color=#F23645)

// Long Bollinger Bands (for buy signals)

LONG_LENGTH = 4032
LONG_MULT = 2.5

longBasis = ta.ema(src, LONG_LENGTH)
longDev = LONG_MULT * ta.stdev(src, LONG_LENGTH)
longUpper = longBasis + longDev
longLower = longBasis - longDev
p4 = plot(longLower, "Long Bollinger Lower", color=#089981)


// 4) Conditions / Trend Identification

trendBullish = (macdLine > macdSignal) and (mfi < 56)
trendBearish = (macdLine <= macdSignal) or (mfi > 56)
allowTrading = barstate.isrealtime
haltTrading = (macdLine <= macdSignal) and (mfi > 45)

entryConditionStoch = trendBearish ? (ta.crossover(k, d) and (k < 10)) : (ta.crossover(k, d) and (k < 20))
exitConditionStoch = trendBearish ? (ta.crossunder(k, d) and (k > 25)) : (ta.crossunder(k, d) and (k > 50))

entryConditionBollinger = ta.crossover(src, longLower)
exitConditionBollinger = ta.crossunder(src, upper)


// 5) Entry & Exit Execution

if barstate.isconfirmed

    // STOCHASTIC ENTRIES

    if allowTrading and entryConditionStoch and ((x + y) < 6) and not haltTrading
        // position size depends on bullish vs. bearish
        if trendBullish
            posSizePercentage = BASE_PERCENTAGE_BULLISH - (INCREMENT * x)
            x := x + 1

            entryDollarAmount = remainingEquity * (posSizePercentage / 100)

            numberOfContracts = math.round((entryDollarAmount / close), 5)

            remainingEquity -= entryDollarAmount

            array.push(bullishEntryPrices, close)
            array.push(bullishEntrySizes,  numberOfContracts)

            // Build the JSON 
            string contractStr = str.tostring(numberOfContracts)
            string buyJSON = '{  "secret": "'+SECRET+'",  "max_lag": "300",  "timestamp": "'+str.tostring(timenow)+'",  "trigger_price": "'+str.tostring(close)+'",  "tv_exchange": "'+syminfo.prefix+'",  "tv_instrument": "'+syminfo.ticker+'",  "action": "enter_long",  "bot_uuid": "'+BOT_UUID+'",  "order": {    "amount": "'+contractStr+'",    "currency_type": "base",    "order_type": "market"  }}'
            alert(buyJSON, alert.freq_once_per_bar_close)
            
        else
            posSizePercentage = BASE_PERCENTAGE_BEARISH - (INCREMENT * y)
            y := y + 1

            entryDollarAmount = remainingEquity * (posSizePercentage / 100)

            numberOfContracts = math.round((entryDollarAmount / close), 5)

            remainingEquity -= entryDollarAmount

            array.push(bearishEntryPrices, close)
            array.push(bearishEntrySizes, numberOfContracts)

            // Build the JSON 
            string contractStr = str.tostring(numberOfContracts)
            string buyJSON = '{  "secret": "'+SECRET+'",  "max_lag": "300",  "timestamp": "'+str.tostring(timenow)+'",  "trigger_price": "'+str.tostring(close)+'",  "tv_exchange": "'+syminfo.prefix+'",  "tv_instrument": "'+syminfo.ticker+'",  "action": "enter_long",  "bot_uuid": "'+BOT_UUID+'",  "order": {    "amount": "'+contractStr+'",    "currency_type": "base",    "order_type": "market"  }}'
            alert(buyJSON, alert.freq_once_per_bar_close)

    // BOLLINGER ENTRY

    if allowTrading and entryConditionBollinger and not bollingerBuyAlertFired
        
        entryDollarAmount = remainingEquity * (BOLLINGERPOSSIZE / 100)

        numberOfContracts = math.round((entryDollarAmount / close), 5)

        remainingEquity -= entryDollarAmount

        bollingerPrice := close
        bollingerSize := numberOfContracts

        // Build the JSON
        string contractStr = str.tostring(numberOfContracts)
        string buyJSON = '{  "secret": "'+SECRET+'",  "max_lag": "300",  "timestamp": "'+str.tostring(timenow)+'",  "trigger_price": "'+str.tostring(close)+'",  "tv_exchange": "'+syminfo.prefix+'",  "tv_instrument": "'+syminfo.ticker+'",  "action": "enter_long",  "bot_uuid": "'+BOT_UUID+'",  "order": {    "amount": "'+contractStr+'",    "currency_type": "base",    "order_type": "market"  }}'
        alert(buyJSON, alert.freq_once_per_bar_close)
        bollingerSellAlertFired := false
        bollingerBuyAlertFired := true


    // STOCHASTIC EXITS

    if allowTrading and exitConditionStoch and (array.size(bearishEntryPrices) > 0 or array.size(bullishEntryPrices) > 0)
        
        contractsInProfit = 0.0
        
        bullishSumSubPos = array.size(bullishEntryPrices)
        bearishSumSubPos = array.size(bearishEntryPrices)


        if bullishSumSubPos > 0
            for i = bullishSumSubPos - 1 to 0 by 1
                bullEPrice = array.get(bullishEntryPrices, i)
                bullESize  = array.get(bullishEntrySizes, i)

                if close > bullEPrice
                    contractsInProfit += bullESize
                    x := x - 1
                    remainingEquity += (bullESize * close)
                    array.remove(bullishEntryPrices, i)
                    array.remove(bullishEntrySizes, i)


        if bearishSumSubPos > 0
            for i = bearishSumSubPos - 1 to 0 by 1
                bearEPrice = array.get(bearishEntryPrices, i)
                bearESize  = array.get(bearishEntrySizes, i)

                if close > bearEPrice
                    contractsInProfit += bearESize
                    y := y - 1
                    remainingEquity += (bearESize * close)
                    array.remove(bearishEntryPrices, i)
                    array.remove(bearishEntrySizes, i)

        // Build the JSON
        string contractStr = str.tostring(contractsInProfit)
        string exitJSON = '{  "secret": "'+SECRET+'",  "max_lag": "300",  "timestamp": "'+str.tostring(timenow)+'",  "trigger_price": "'+str.tostring(close)+'",  "tv_exchange": "'+syminfo.prefix+'",  "tv_instrument": "'+syminfo.ticker+'",  "action": "exit_long",  "bot_uuid": "'+BOT_UUID+'",  "order": {    "amount": "'+contractStr+'",    "currency_type": "base",    "order_type": "market"  }}'
        if contractsInProfit > 0
            alert(exitJSON, alert.freq_once_per_bar_close)


    // BOLLINGER EXIT

    if allowTrading and exitConditionBollinger and not bollingerSellAlertFired

        if close > bollingerPrice

            remainingEquity += (bollingerSize * close)
            
            // Build the JSON
            contractStr  = str.tostring(bollingerSize)
            string exitJSON = '{  "secret": "'+SECRET+'",  "max_lag": "300",  "timestamp": "'+str.tostring(timenow)+'",  "trigger_price": "'+str.tostring(close)+'",  "tv_exchange": "'+syminfo.prefix+'",  "tv_instrument": "'+syminfo.ticker+'",  "action": "exit_long",  "bot_uuid": "'+BOT_UUID+'",  "order": {    "amount": "'+contractStr+'",    "currency_type": "base",    "order_type": "market"  }}'          
            alert(exitJSON, alert.freq_once_per_bar_close)
            
            // Update repeat conditions
            bollingerBuyAlertFired := false
            bollingerSellAlertFired := true

Overview

Swing Trading Indicator plots a Stochastic RSI, a MACD with very long periods for the medium-term trend, and a Money Flow Index, and also uses two Bollinger Band sets for oversold entries and exits. The code tracks several sub-positions and sizes them as a percentage of remaining equity, then sends alert messages with a quantity and price for a webhook bot. Credentials are placeholders to fill in. It uses real-time state, so alerts can differ from historical bars.

Details

Published by

armaandamani on GitHub

Code credit

Damani1234, as written in the script's header

Type

Indicator, Pine Script v6

Draws

Separate pane below the chart

Category

Oscillators & momentum, Volatility & bands, Volume

Markets

Crypto

Timeframes

H4 and above

Risk Notes

  • Signals can change on the live bar or after it closes (repainting)
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

114 stars

This indicator standardizes price inputs using z-score normalization before calculating a relative strength index (RSI). It generates trade signals when standardized price components cross over or under the standardized RSI feature. Signals can be filtered by

Indicator v4 Oscillators & momentumVolatility & bands Repaints
Updated 1 year ago · None stated GitHub repository of Preprosessed & Standardized RSI

PPO ATR Bands

by cryptorife
75 stars

PPO ATR Bands plots a percentage price oscillator in a separate pane. It compares a Hull average of typical price with a volume-weighted exponential average of Parabolic SAR, then scales three true-range bands around the slow average into matching oscillator l

Indicator v4 Oscillators & momentumMoving averages
Updated 3 years ago · GPL-3.0 GitHub repository of PPO ATR Bands

This indicator calculates the Relative Strength Index (RSI) alongside a simple moving average to generate directional momentum signals in a separate pane. It supports Break Flip and Break Continuous scanning modes for long and short setups. A wide array of opt

Indicator v5 Oscillators & momentumVolatility & bands
Updated 1 year ago · None stated GitHub repository of Momentum Setup: RSI Direction Confirmation

NFI v6

by koradiyakaushal
12 stars

This Pine v4 study ports early NostalgiaForInfinity V6 conditions onto the price chart. It computes two Bollinger setups, several EMAs and SMAs, RSI, MFI, a percent SMA spread labeled EWO, a 14-period choppiness value, and short and longer volume medians. Fixe

Indicator v4 Moving averagesVolatility & bands
Updated 5 years ago · MIT GitHub repository of NFI v6

The script calculates a variant of the Fear & Greed Index using rate of return, accumulation distribution money flow weighted by volume, and volatility from VIX. It offers display options for the raw index value or price candles scaled by the index level. Smoo

Indicator v5 Oscillators & momentumVolatility & bands Repaints
Updated 4 years ago · MPL-2.0 GitHub repository of Trading Psychology - Fear & Greed Index by DGT

More indicators

Trade Your Charts With a Regulated Broker

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

Compare brokers