Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Some useful TradingView Pinescript indicators from me
#1
These indicators have been converted by me and are not available in the public indicators database of tradingview

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator(title="RD.COmbo", shorttitle="RD-Combo", overlay=false,
max_bars_back=2000, // Sufficient history for calculations, especially ForecastOsc
precision=2         // Adjust precision for plots if needed
)

// --- Input Parameters ---
bool DoAlertForEntry = input.bool(false, "Do Alert For Entry")
bool DoAlertForExit = input.bool(false, "Do Alert For Exit")
// HistorySize in MQL4 primarily limits the `start` loop iteration.
// In Pine Script, plots automatically handle historical data.
// We keep it as an input but it doesn't directly restrict plots.
int HistorySize_input = input.int(1000, "History Size", minval=100)
int ColorThreshold = input.int(5, "Color Threshold", minval=0, maxval=5)
float NoiseFilterRVI = input.float(0.03, "RVI Exit Threshold", minval=0.0, step=0.01) // MQL4 uses 0.2 in condition, but input is 0.03. Using input.
bool DebugLogger = input.bool(false, "Debug Logger (Console)")
bool DebugLoggerData = input.bool(false, "Debug Logger Data (Console)")

// --- Global variables for Signal State & Alerts ---
// `var` keyword ensures these variables retain their values across bars.
var int signalstate = 0 // 1 = Long, -1 = Short, 0 = Neutral
var bool didentryalert_pine = false
var bool didexitalert_pine = false

// --- ForecastOscillator Calculation Helper Functions ---

// Helper function to calculate the weighted sum for `wt`
f_calc_wt(src, len) =>
    float sum_val = 0.0
    // Iterate from the current bar's position `len - i` to access past `src` values.
    // MQL4 `Close[shift+length-i]` corresponds to `src[len - i]` for current bar `shift=0`.
    for i = 1 to len
        float tmp_coeff = i - (float(len) + 1.0) / 3.0
        sum_val += tmp_coeff * src[len - i]
    sum_val * 6.0 / (float(len) * (float(len) + 1.0))

// ForecastOscillator logic
f_forecast_osc_series(src_series, regress, t3, b) =>
    float b2 = b * b
    float b3 = b2 * b
    float c1 = -b3
    float c2 = (3 * (b2 + b3))
    float c3 = -3 * (2 * b2 + b + b3)
    float c4 = (1 + 3 * b + b3 + 3 * b2)
    float n = 1 + 0.5 * (float(t3) - 1)
    float w1 = 2 / (n + 1)
    float w2 = 1 - w1

    // Calculate wt for the current bar
    float wt = f_calc_wt(src_series, regress)

    // Ensure `wt` is not too close to zero to avoid division by zero
    float forecastosc = (src_series - wt) / (math.abs(wt) < 1e-10 ? 1e-10 : wt) * 100

    // T3 smoothing chain - these variables must persist across bars
    var float e1 = na
    var float e2 = na
    var float e3 = na
    var float e4 = na
    var float e5 = na
    var float e6 = na
   
    // Using nz() to handle initial `na` values
    e1 := w1 * forecastosc + w2 * nz(e1[1])
    e2 := w1 * e1 + w2 * nz(e2[1])
    e3 := w1 * e2 + w2 * nz(e3[1])
    e4 := w1 * e3 + w2 * nz(e4[1])
    e5 := w1 * e4 + w2 * nz(e5[1])
    e6 := w1 * e5 + w2 * nz(e6[1])
   
    float t3_fosc = c1 * e6 + c2 * e5 + c3 * e4 + c4 * e3
   
    [forecastosc, t3_fosc] // Return both series

// --- Pre-calculate Forecast Oscillator values ---
// Call the function on the 'close' series with MQL4's default parameters (15, 3, 0.7)
[Osc, Osct3] = f_forecast_osc_series(close, 15, 3, 0.7)


// --- Combo Indicator Logic (Translated from MQL4's Combo function) ---

// Calculate all necessary indicator values for the current bar.
// MQL4's `lookupidx` corresponds to `[0]` for the current bar in Pine.
float ma5 = ta.wma(close, 5)
float ma20 = ta.wma(close, 20)
float ma100 = ta.wma(close, 100)
float ma200 = ta.wma(close, 200)

float cci = ta.cci(close, 5)

// --- MANUAL RVI CALCULATION (REPLACEMENT FOR ta.rvi) ---
// RVI Main (period 1 from MQL4) = (Close - Open) / (High - Low)
float rvi_numerator_raw = close - open
float rvi_denominator_raw = high - low
float rvimain = rvi_denominator_raw != 0 ? rvi_numerator_raw / rvi_denominator_raw : 0.0

// RVI Signal (period 1 from MQL4 implies a 4-period SMA of the main RVI)
float rvisignal = ta.sma(rvimain, 4)
// --- END MANUAL RVI CALCULATION ---


// --- MANUAL ADX/DI CALCULATION (REPLACEMENT FOR ta.adx, ta.plus_di, ta.minus_di) ---
f_calculate_adx_di(len) =>
    // True Range
    tr1 = high - low
    tr2 = math.abs(high - close[1])
    tr3 = math.abs(low - close[1])
    tr = math.max(tr1, tr2, tr3)

    // Directional Movement
    up = high - high[1]
    down = low[1] - low

    plusDM = up > down and up > 0 ? up : 0
    minusDM = down > up and down > 0 ? down : 0

    // Smoothed True Range and Directional Movements using RMA (Wilders Smoothing)
    // ta.rma is the Pine Script equivalent of Wilders Smoothing
    smoothTR = ta.rma(tr, len)
    smoothPlusDM = ta.rma(plusDM, len)
    smoothMinusDM = ta.rma(minusDM, len)

    // Calculate DI+ and DI-
    plusDI = smoothTR != 0 ? smoothPlusDM / smoothTR * 100 : 0
    minusDI = smoothTR != 0 ? smoothMinusDM / smoothTR * 100 : 0

    // Calculate DX
    sumDI = plusDI + minusDI
    dx = sumDI != 0 ? math.abs(plusDI - minusDI) / sumDI * 100 : 0

    // Calculate ADX (smoothed DX)
    adx = ta.rma(dx, len)
   
    [adx, plusDI, minusDI]

// Apply the manual ADX/DI calculation for period 14
[adxmain, adxplus, adxminus] = f_calculate_adx_di(14)

// For previous bar values, we can simply use the `[1]` operator on the calculated series
float adxmain2 = adxmain[1]
float adxplus2 = adxplus[1]
float adxminus2 = adxminus[1]
// --- END MANUAL ADX/DI CALCULATION ---

// Forecast Oscillator values for current bar (already calculated as series `Osc` and `Osct3`)
float fcblue = Osc
float fcred = Osct3

// Initialize signal components
int maval = 0
int ccival = 0
int rvival = 0
int adxval = 0
int fcval = 0

// MA signal
if ma5 > ma20
    maval := 1
else if ma5 < ma20
    maval := -1

// CCI signal
if cci > 0
    ccival := 1
else if cci < 0
    ccival := -1
// Else ccival remains 0

// Forecast Oscillator signal
if fcblue > 0 and fcred > 0 and fcblue > fcred
    fcval := 1
else if fcblue < 0 and fcred < 0 and fcblue < fcred
    fcval := -1
// Else fcval remains 0

// RVI signal
if rvimain > 0 and rvisignal > 0 and rvimain - rvisignal > 0
    rvival := 1
else if rvimain < 0 and rvisignal < 0 and rvimain - rvisignal < 0
    rvival := -1
// Else rvival remains 0

// ADX signal
if adxmain > adxmain2 and adxplus > adxplus2 and adxmain > 20 and adxplus > 20
    adxval := 1
else if adxmain > adxmain2 and adxminus > adxminus2 and adxmain > 20 and adxminus > 20
    adxval := -1
// Else adxval remains 0

// Calculate the total combined signal strength
float val = maval + ccival + fcval + rvival + adxval

// --- Exit Signal Logic ---
// Note: MQL4 used a constant `0.2` for RVI exit threshold, but `NoiseFilterRVI` input was 0.03.
// We are using the `NoiseFilterRVI` input for consistency.
if signalstate != 0
    if signalstate == 1 and (rvimain < 0 or (rvisignal - rvimain) > NoiseFilterRVI)
        signalstate := 0 // Exit long
    if signalstate == -1 and (rvimain > 0 or (rvimain - rvisignal) > NoiseFilterRVI)
        signalstate := 0 // Exit short

// --- Debugging Output (to Pine Script console) ---
if DebugLogger or DebugLoggerData
    // Check for sufficient historical bars before logging to avoid errors with `[1]` etc.
    if bar_index >= math.max(14, 200) // At least 200 bars for MAs, 14 for ADX. Min 31+regress=46 for FO.
        if DebugLoggerData
            log.info("--------------------------------------------------------------------------")
            log.info("Time: {0}, Bar: {1}, MA 5/20/100/200: {2}/{3}/{4}/{5}",
                 timenow, bar_index, ma5, ma20, ma100, ma200)
            log.info("Time: {0}, Bar: {1}, CCI: {2}, RVI: {3}/{4}",
                 timenow, bar_index, cci, rvimain, rvisignal)
            log.info("Time: {0}, Bar: {1}, ADX(now): {2}/{3}/{4}",
                 timenow, bar_index, adxmain, adxplus, adxminus)
            log.info("Time: {0}, Bar: {1}, ADX(prev): {2}/{3}/{4}",
                 timenow, bar_index, adxmain2, adxplus2, adxminus2)
            log.info("Time: {0}, Bar: {1}, Forecast blue/red: {2}/{3}",
                 timenow, bar_index, fcblue, fcred)

        log.info("Time: {0}, Bar: {1}, MAtrend({2}) + CCI({3}) + FC({4}) + RVItrend({5}) + ADXtrend({6}) => {7} # trade state = {8}",
             timenow, bar_index, maval, ccival, fcval, rvival, adxval, val, signalstate)


// --- Determine Plot Values ---
// These are the buffers from MQL4 (Neutral, Short, Long, Signal)
float NeutralBuffer_val = 0.0
float LongSignalBuffer_val = 0.0
float ShortSignalBuffer_val = 0.0

if val >= ColorThreshold
    LongSignalBuffer_val := val
    signalstate := 1 // Set signalstate to long if conditions met
else if val <= -ColorThreshold
    ShortSignalBuffer_val := val
    signalstate := -1 // Set signalstate to short if conditions met
else
    NeutralBuffer_val := val // Neutral, between thresholds
    // If we're neutral, but previously in a signal, it might be an exit condition.
    // The `signalstate` is managed by the exit logic above.
    // So if the current `val` is neutral, but `signalstate` was set by an exit condition, it remains 0.
    // If `val` is neutral and there was no exit, `signalstate` also becomes 0.
    if math.abs(val) < ColorThreshold and signalstate != 0
        signalstate := 0 // If signal goes neutral and no specific RVI exit occurred, also reset.


// SignalBuffer: MQL4 uses `2 * signalstate`
float SignalBuffer_val = 2 * signalstate

// --- Plotting ---
// Removed minval and maxval as they are not recognized in your environment.
// The indicator will now auto-scale based on the values plotted.
plot(NeutralBuffer_val, title="Neutral", color=color.rgb(128, 128, 128), style=plot.style_columns, linewidth=2, histbase=0) // Gray
plot(ShortSignalBuffer_val, title="Short Signal", color=color.rgb(255, 69, 0), style=plot.style_columns, linewidth=2, histbase=0) // OrangeRed
plot(LongSignalBuffer_val, title="Long Signal", color=color.rgb(124, 252, 0), style=plot.style_columns, linewidth=2, histbase=0) // LawnGreen

plot(SignalBuffer_val, title="Signal Line", color=color.rgb(255, 215, 0), style=plot.style_line, linewidth=1) // Gold

// Plotting MQL4 levels (4 and -4) - these will still help visually define a range.
hline(4, "Level +4", color.rgb(100, 100, 100), linestyle=hline.style_dashed)
hline(-4, "Level -4", color.rgb(100, 100, 100), linestyle=hline.style_dashed)


// --- Alerting Logic ---
// MQL4: `SignalBuffer[0]!=0 && SignalBuffer[1]==0` for entry
// Pine: `SignalBuffer_val != 0 and SignalBuffer_val[1] == 0` for entry
if DoAlertForEntry and SignalBuffer_val != 0 and nz(SignalBuffer_val[1]) == 0
    if not didentryalert_pine
        alert("RD signals trade entry on " + syminfo.ticker + "/" + timeframe.period, alert.freq_once_per_bar)
        didentryalert_pine := true
else
    didentryalert_pine := false // Reset alert flag when no entry signal

// MQL4: `SignalBuffer[0]==0 && SignalBuffer[1]!=0` for exit
// Pine: `SignalBuffer_val == 0 and SignalBuffer_val[1] != 0` for exit
if DoAlertForExit and SignalBuffer_val == 0 and nz(SignalBuffer_val[1]) != 0
    if not didexitalert_pine
        alert("RD signals trade exit on " + syminfo.ticker + "/" + timeframe.period, alert.freq_once_per_bar)
        didexitalert_pine := true
else
    didexitalert_pine := false // Reset alert flag when no exit signal

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator(title="Weekly Pivot", shorttitle="WeeklyPivot", overlay=true)

//--- Global variables for pivot values (will retain their value across bars)
var float P_val  = na
var float S1_val = na
var float R1_val = na
var float S2_val = na
var float R2_val = na
var float S3_val = na
var float R3_val = na

//--- Global variables for labels (will hold label IDs)
var label P_label  = na
var label S1_label = na
var label R1_label = na
var label S2_label = na
var label R2_label = na
var label S3_label = na
var label R3_label = na

// --- Input for font size (from MQL4's fontsize)
var int fontsize_input = input.int(10, "Label Font Size", minval=6, maxval=24)

// --- Detect start of a new week (typically Monday, first bar of the week)
// `ta.change(time("W"))` returns true on the first bar of a new weekly period.
new_week = ta.change(time("W"))

// --- Get previous week's data
// request.security is used to fetch historical High, Low, and Close from the *completed* previous week.
// `[1]` refers to the previous weekly bar.
// `lookahead=barmerge.lookahead_on` ensures we get the value from the *closed* previous week.
[prev_w_high, prev_w_low, prev_w_close] = request.security(syminfo.tickerid, "W", [high[1], low[1], close[1]], lookahead=barmerge.lookahead_on)

// --- Main Calculation: Calculate pivots only on the first bar of a new week ---
if new_week
    // The current bar's open is the open of the new week.
    current_week_open = open

    // Calculate Pivot Points based on the MQL4 formula:
    // P = (Previous Week High + Previous Week Low + Current Week Open + Previous Week Close) / 4
    P_val  := (prev_w_high + prev_w_low + current_week_open + prev_w_close) / 4
    R1_val := (2 * P_val) - prev_w_low
    S1_val := (2 * P_val) - prev_w_high
    R2_val := P_val + (prev_w_high - prev_w_low)
    S2_val := P_val - (prev_w_high - prev_w_low)
    R3_val := (2 * P_val) + (prev_w_high - (2 * prev_w_low))
    S3_val := (2 * P_val) - ((2 * prev_w_high) - prev_w_low)

    // --- Create/Update Labels for Pivot Levels ---
    // If labels don't exist yet (first run of script, or after reset), create them.
    // Otherwise, update their position and value.
    if na(P_label) // Check if the main pivot label is 'na' to know if all labels need creating
        // Create labels with transparent background (`color.new(color.white, 100)`)
        P_label  := label.new(x=time, y=P_val, text="Weekly Pivot Point", xloc=xloc.bar_time, yloc=yloc.price,
                             color=color.new(color.white, 100), textcolor=color.rgb(255, 0, 255), size=size.small, style=label.style_label_left) // Magenta
        S1_label := label.new(x=time, y=S1_val, text="wS 1", xloc=xloc.bar_time, yloc=yloc.price,
                              color=color.new(color.white, 100), textcolor=color.rgb(65, 105, 225), size=size.small, style=label.style_label_left) // RoyalBlue
        R1_label := label.new(x=time, y=R1_val, text="wR 1", xloc=xloc.bar_time, yloc=yloc.price,
                              color=color.new(color.white, 100), textcolor=color.rgb(220, 20, 60), size=size.small, style=label.style_label_left) // Crimson
        S2_label := label.new(x=time, y=S2_val, text="wS 2", xloc=xloc.bar_time, yloc=yloc.price,
                              color=color.new(color.white, 100), textcolor=color.rgb(65, 105, 225), size=size.small, style=label.style_label_left) // RoyalBlue
        R2_label := label.new(x=time, y=R2_val, text="wR 2", xloc=xloc.bar_time, yloc=yloc.price,
                              color=color.new(color.white, 100), textcolor=color.rgb(220, 20, 60), size=size.small, style=label.style_label_left) // Crimson
        S3_label := label.new(x=time, y=S3_val, text="wS 3", xloc=xloc.bar_time, yloc=yloc.price,
                              color=color.new(color.white, 100), textcolor=color.rgb(46, 139, 87), size=size.small, style=label.style_label_left) // SeaGreen
        R3_label := label.new(x=time, y=R3_val, text="wR 3", xloc=xloc.bar_time, yloc=yloc.price,
                              color=color.new(color.white, 100), textcolor=color.rgb(46, 139, 87), size=size.small, style=label.style_label_left) // SeaGreen
   
    // Update labels (for existing ones, and for newly created ones on the same bar)
    label.set_xy(P_label, x=time, y=P_val)
    label.set_xy(S1_label, x=time, y=S1_val)
    label.set_xy(R1_label, x=time, y=R1_val)
    label.set_xy(S2_label, x=time, y=S2_val)
    label.set_xy(R2_label, x=time, y=R2_val)
    label.set_xy(S3_label, x=time, y=S3_val)
    label.set_xy(R3_label, x=time, y=R3_val)

    // Update label text if you want to include values (MQL4 only used fixed text)
    // For example: `label.set_text(P_label, "Weekly Pivot Point: " + str.tostring(P_val))`
    // But sticking to MQL4 original, fixed text is used.

    // Update font size (MQL4 only sets this on init, but we can make it dynamic here if desired)
    // For a constant font size, it's better to pass it directly to label.new and avoid updating every week.
    // However, if we added an input for fontsize, we would set it here.
    // Example: label.set_size(P_label, f_get_label_size(fontsize_input))
    // For now, size.small is hardcoded based on MQL4's fontsize=10.

// --- Plotting the Pivot Lines ---
// The `P_val`, `S1_val`, etc. variables retain their last calculated value thanks to `var`.
// This makes them horizontal lines spanning the entire week until a new calculation occurs.

plot(P_val,  title="Weekly Pivot Point", color=color.rgb(255, 0, 255), linewidth=2, style=plot.style_line) // Magenta
plot(S1_val, title="W_S 1",              color=color.rgb(65, 105, 225), linewidth=2, style=plot.style_line) // RoyalBlue
plot(R1_val, title="W_R 1",              color=color.rgb(220, 20, 60),  linewidth=2, style=plot.style_line) // Crimson
plot(S2_val, title="W_S 2",              color=color.rgb(65, 105, 225), linewidth=2, style=plot.style_line) // RoyalBlue
plot(R2_val, title="W_R 2",              color=color.rgb(220, 20, 60),  linewidth=2, style=plot.style_line) // Crimson
plot(S3_val, title="W_S 3",              color=color.rgb(46, 139, 87),  linewidth=2, style=plot.style_line) // SeaGreen
plot(R3_val, title="W_R 3",              color=color.rgb(46, 139, 87),  linewidth=2, style=plot.style_line) // SeaGreen

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator(title="Weighted WCCI", shorttitle="Weighted WCCI", overlay=false)

//--- Input Parameters ---
TCCIp       = input.int(7, "Turbo CCI Period", minval=1)
CCIp        = input.int(13, "CCI Period", minval=1)
overbslevel = input.float(200.0, "Overbought/Oversold Level")
triglevel   = input.float(50.0, "Trigger Level")
weight      = input.float(1.0, "Weight")

//--- Pine Script Buffers (variables for plotting) ---
var float ExtMapBuffer1 = na // Turbo CCI (Red)
var float ExtMapBuffer2 = na // CCI (DodgerBlue)
var float ExtMapBuffer3 = na // CCI Histogram (CadetBlue)
var float ExtMapBuffer4 = na // Overbought Level (Red)
var float ExtMapBuffer5 = na // Oversold Level (Red)
var float ExtMapBuffer6 = na // Trigger Level (RoyalBlue)
var float ExtMapBuffer7 = na // Negative Trigger Level (RoyalBlue)
var float ExtMapBuffer8 = na // Zero Level (PaleGreen)

//--- Global variables for trend tracking (mimicking MQL4's trend_counter and trend string) ---
var int trend_counter = 0
var string trend = "ZERO"

//--- Main Calculation ---
// MQL4's iCCI(NULL,0,Period,PRICE_TYPICAL,shift) translates to ta.cci(hlc3, Period)[shift]
// MQL4's iATR(NULL,0,Period,shift) translates to ta.atr(Period)[shift]

// Calculate CCI and Turbo CCI for the current bar (shift = 0 in MQL4)
float currentCCI  = ta.cci(hlc3, CCIp)
float currentTCCI = ta.cci(hlc3, TCCIp)

// Calculate ATR for the current bar (shift = 0 in MQL4)
float atr7  = ta.atr(7)
float atr49 = ta.atr(49)

float Kw = 0.0

if weight == 0
    Kw := 0.0
else
    Kw := weight * (atr7 / atr49)
    currentCCI  := currentCCI * Kw
    currentTCCI := currentTCCI * Kw

// Clamp values as per MQL4 logic
if currentTCCI > overbslevel + 50
    currentTCCI := overbslevel + 50
if currentCCI > overbslevel + 50
    currentCCI := overbslevel + 50
if currentCCI < -overbslevel - 50
    currentCCI := -overbslevel - 50
if currentTCCI < -overbslevel - 50
    currentTCCI := -overbslevel - 50

// Assign values to plotting variables
ExtMapBuffer1 := currentTCCI
ExtMapBuffer2 := currentCCI
ExtMapBuffer3 := currentCCI // Used for histogram
ExtMapBuffer4 := overbslevel
ExtMapBuffer5 := -overbslevel
ExtMapBuffer6 := triglevel
ExtMapBuffer7 := -triglevel
ExtMapBuffer8 := 0.0

// --- Trend Logic (for comment only) ---
// Pine Script executes on every bar, so we handle previous bar state with `[1]` or `var` variables.
// The MQL4 `shift==0` logic applies to the current bar.
if barstate.islast
    // Let's replicate the MQL4 logic as closely as possible for the `trend` string and `trend_counter`.
    // It is important to note that MQL4's `trend` variable is a global.
    // In Pine, `var` ensures persistence across bars.

    if currentCCI > 0
        if trend[1] == "UP" // Using [1] to get the value from the *previous* bar
            trend_counter := trend_counter[1] + 1
        else
            trend_counter := 1
            trend := "UP"
    else if currentCCI < 0 // Assuming MQL4 implied `currentCCI < 0` for "DOWN"
        if trend[1] == "DOWN"
            trend_counter := trend_counter[1] + 1
        else
            trend_counter := 1
            trend := "DOWN"
    else // currentCCI == 0 or very close
        trend_counter := 1
        trend := "ZERO"

    // The MQL4 'Comment' function for status bar text is removed for Pine compatibility
    // You can see the `trend` and `trend_counter` values in the Data Window when hovering over the indicator.


//--- Plotting ---
// Plot 0: Turbo CCI
// Changed color.red to color.rgb(255, 0, 0)
plot(ExtMapBuffer1, title="Turbo CCI", color=color.rgb(255, 0, 0), style=plot.style_line, linewidth=1)

// Plot 1: CCI
// Changed color.dodgerBlue to color.rgb(30, 144, 255)
plot(ExtMapBuffer2, title="CCI", color=color.rgb(30, 144, 255), style=plot.style_line, linewidth=3)

// Plot 2: CCI Histogram
// Changed color.cadetBlue to color.rgb(95, 158, 160)
plot(ExtMapBuffer3, title="CCI Histogram", color=color.rgb(95, 158, 160), style=plot.style_columns)

// Plot 3: Overbought Level (Red)
// Changed color.red to color.rgb(255, 0, 0)
plot(ExtMapBuffer4, title="Overbought Level", color=color.rgb(255, 0, 0), style=plot.style_line, linewidth=1, show_last=5000)

// Plot 4: Oversold Level (Red)
// Changed color.red to color.rgb(255, 0, 0)
plot(ExtMapBuffer5, title="Oversold Level", color=color.rgb(255, 0, 0), style=plot.style_line, linewidth=1, show_last=5000)

// Plot 5: Trigger Level (RoyalBlue)
// Changed color.royalBlue to color.rgb(65, 105, 225)
plot(ExtMapBuffer6, title="Trigger Level (+)", color=color.rgb(65, 105, 225), style=plot.style_line, linewidth=1, show_last=5000)

// Plot 6: Negative Trigger Level (RoyalBlue)
// Changed color.royalBlue to color.rgb(65, 105, 225)
plot(ExtMapBuffer7, title="Trigger Level (-)", color=color.rgb(65, 105, 225), style=plot.style_line, linewidth=1, show_last=5000)

// Plot 7: Zero Level (PaleGreen)
// Changed color.paleGreen to color.rgb(152, 251, 152)
plot(ExtMapBuffer8, title="Zero Level", color=color.rgb(152, 251, 152), style=plot.style_line, linewidth=1, show_last=5000)

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("SwamiRSI_v1", shorttitle="SwamiRSI_v1", overlay=false)

//--- Input Parameters ---
var int g_visualMode  = input.int(0, "Visual Mode (0=original, 1=trend)", minval=0, maxval=1)
var int g_priceType   = input.int(0, "Applied Price (0=Close, 1=Open, 2=High, 3=Low, 4=Median, 5=Typical; 6=Weighted)", minval=0, maxval=6)
var int g_startLength = input.int(12, "RSI Start Period", minval=1)
var int g_endLength   = input.int(48, "RSI End Period", minval=1)
var int g_sampleLength = input.int(48, "Sample RSI Period (0=off)", minval=0)
var int g_smooth      = input.int(5, "Smoothing Period", minval=1)
var color g_upTrendColor  = input.color(color.lime, "UpTrend Color")
var color g_dnTrendColor  = input.color(color.red, "DownTrend Color")
var color g_flatColor     = input.color(color.yellow, "Flat Color (if CLR_NONE, 2 Color Mix)")
var int g_scaleMode   = input.int(1, "Scale Mode (0=J.Ehlers, 1=0...100)", minval=0, maxval=1)
var int g_swamiBars   = input.int(100, "Swami Bars (-1=off, 0=all Bars, >0=any number)")

// --- Helper Functions ---

// Get applied price based on input
f_get_price(priceType) =>
    switch priceType
        0 => close
        1 => open
        2 => high
        3 => low
        4 => (high + low) / 2
        5 => (high + low + close) / 3
        6 => (open + high + low + close) / 4
        => close // Default to close if invalid type

// Custom EMA function to mimic MQL4 behavior more closely
// It stores previous EMA value in a separate buffer for state management across bars
// `ema_array`: an array that stores the previous EMA value for each 'index' (used by MQL4's ema[][2])
// `price_val`: the current price value for the EMA calculation
// `period`: the EMA period
// `idx`: the index within the ema_array to store the value (corresponds to MQL4's `index` argument)
f_ema(ema_array, price_val, period, idx) =>
    prev_ema_val = array.get(ema_array, idx)
    current_ema_val = if bar_index == 0 or na(prev_ema_val)
        price_val
    else
        prev_ema_val + 1.0 / period * (price_val - prev_ema_val)
    array.set(ema_array, idx, current_ema_val)
    current_ema_val

// Custom _RSI calculation (mimics MQL4 logic)
// `index`: corresponds to the 'i' in the MQL4 loop, used for array indexing
// `change`: current price change (price[0] - price[1])
// `period`: RSI period (StartLength + index)
// `ema_array`: array to pass to the f_ema function
// `swamisize`: from MQL4's swamisize global
f_custom_rsi(index, change, period, ema_array, swamisize) =>
    totChg = math.abs(change)

    // MQL4's EMA function uses `ema[index][0]` and `ema[index][1]`, and `prevtime[index]`
    // Here, we use indices for `ema_array`:
    // NetChgAvg uses `index` (0 to swamisize-1)
    // TotChgAvg uses `index + swamisize`
    // Final RSI EMA uses `index + 2*swamisize`
    netChgAvg = f_ema(ema_array, change, period, index)
    totChgAvg = f_ema(ema_array, totChg, period, index + swamisize)

    chgRatio = if totChgAvg != 0
        netChgAvg / totChgAvg
    else
        0.0

    rsiVal = f_ema(ema_array, 2 * chgRatio + 0.5, g_smooth, index + 2 * swamisize)

    math.max(0, math.min(1, rsiVal)) // Clamp between 0 and 1

// --- Global Variables (converted from MQL4's global arrays) ---
var float[] g_ema = na // Will be initialized on first bar
var int[] g_trend = na   // Will be initialized on first bar

var float g_fuzzWidth = na
var float g_maxValue = na
var float g_minValue = na

var int g_swamisize = na
var float g_priceCurrent = na
var float g_pricePrevious = na

// --- For Box Management ---
// We need a global array to store all created boxes so we can delete them.
var box[] all_swami_boxes = array.new_box(0)

// --- Main Calculation ---
g_priceCurrent := f_get_price(g_priceType)
g_pricePrevious := f_get_price(g_priceType)[1] // Price of the previous bar

// Initialize/resize arrays and set initial values on first bar
if bar_index == 0
    g_swamisize := g_endLength - g_startLength + 1
    // Corrected lines: Directly assign newly created arrays
    g_ema := array.new_float(g_swamisize * 3, na) // Initialize with 'na' values
    g_trend := array.new_int(g_swamisize, 0)     // Initialize with 0s

    if g_sampleLength > 0
        g_sampleLength := math.max(g_startLength, g_sampleLength)
        g_sampleLength := math.min(g_endLength, g_sampleLength)

    if g_scaleMode == 0 // J. Ehlers mode
        g_fuzzWidth := 1.0
        g_maxValue := float(g_endLength)
        g_minValue := float(g_startLength)
    else // 0-100 mode
        g_fuzzWidth := 100.0 / (g_endLength - g_startLength)
        g_maxValue := 100.0
        g_minValue := 0.0

// Variables for plotting
var float rsiPlot = na
var float sumRSIPlot = na

// Only calculate if enough bars are available
if bar_index >= g_endLength
    currentChange = g_priceCurrent - g_pricePrevious

    swamiSum = 0.0
    swamiRSI_values = array.new_float(g_swamisize) // Temporary array for current bar's SwamiRSI values

    for i = 0 to g_swamisize - 1
        currentRsiPeriod = g_startLength + i
       
        // Calculate the custom RSI (clamped between 0 and 1)
        rsi_value_clamped = f_custom_rsi(i, currentChange, currentRsiPeriod, g_ema, g_swamisize)

        if g_visualMode == 0 // Original mode
            array.set(swamiRSI_values, i, rsi_value_clamped)
            swamiSum += rsi_value_clamped
        else // Trend mode
            // Get the trend state from the previous bar's calculation (stored in g_trend)
            current_trend_state = array.get(g_trend, i)
           
            if rsi_value_clamped > 0.5
                current_trend_state := 1
            else if rsi_value_clamped < 0.5
                current_trend_state := 0
           
            array.set(g_trend, i, current_trend_state) // Update global trend array for next bar
            array.set(swamiRSI_values, i, float(current_trend_state))
            swamiSum += float(current_trend_state)

    if g_scaleMode == 0 // J. Ehlers mode
        if g_sampleLength > 0
            // Find the index for sampleLength
            sampleIndex = g_sampleLength - g_startLength
            rsiPlot := float(g_startLength) + (float(g_swamisize) - 1.0) * array.get(swamiRSI_values, sampleIndex)
        else
            rsiPlot := na // If SampleLength is 0, MQL4 also seems to not plot RSI
        sumRSIPlot := float(g_startLength) + (float(g_swamisize) - 1.0) * (swamiSum / float(g_swamisize))
    else // 0-100 mode
        if g_sampleLength > 0
            // Find the index for sampleLength
            sampleIndex = g_sampleLength - g_startLength
            rsiPlot := 100.0 * array.get(swamiRSI_values, sampleIndex)
        else
            rsiPlot := na // If SampleLength is 0, MQL4 also seems to not plot RSI
        sumRSIPlot := 100.0 * (swamiSum / float(g_swamisize))

    // --- Dynamic Rectangle Plotting (Swami Bars) ---
    plot_boxes = false
    if g_swamiBars == 0
        plot_boxes = true // Plot on all bars
    else if g_swamiBars > 0 and bar_index >= (last_bar_index - g_swamiBars)
        plot_boxes = true // Plot for the last 'g_swamiBars' bars

    // Clear all existing boxes at the start of the current bar's calculation
    // or if the indicator is re-initializing (barstate.isfirst)
    if barstate.islast or barstate.isfirst
        // Added check for array size before looping to prevent out-of-bounds error
        if array.size(all_swami_boxes) > 0
            // Iterate through our stored box IDs and delete them
            for i = 0 to array.size(all_swami_boxes) - 1
                box.delete(array.get(all_swami_boxes, i))
        // Clear the array after deleting objects (can always clear an empty array safely)
        array.clear(all_swami_boxes)

    if plot_boxes
        for i = 0 to g_swamisize - 1
            currentSwamiRSI = array.get(swamiRSI_values, i)
            barColor = color.new(color.white, 0) // Initialize with a dummy color and full transparency

            isFlatColorNone = (g_flatColor == color.new(color.fuchsia, 0)) // Using fuchsia as proxy for CLR_NONE

            if isFlatColorNone // This implies a 2-color mix (UpTrendColor and DnTrendColor)
                r1 = color.r(g_dnTrendColor) + currentSwamiRSI * (color.r(g_upTrendColor) - color.r(g_dnTrendColor))
                g1 = color.g(g_dnTrendColor) + currentSwamiRSI * (color.g(g_upTrendColor) - color.g(g_dnTrendColor))
                b1 = color.b(g_dnTrendColor) + currentSwamiRSI * (color.b(g_upTrendColor) - color.b(g_dnTrendColor))
                barColor := color.rgb(math.round(r1), math.round(g1), math.round(b1))
            else // 3 Color Mix with FlatColor
                if currentSwamiRSI >= 0.5
                    r1 = color.r(g_upTrendColor) + 2 * (1 - currentSwamiRSI) * (color.r(g_flatColor) - color.r(g_upTrendColor))
                    g1 = color.g(g_upTrendColor) + 2 * (1 - currentSwamiRSI) * (color.g(g_flatColor) - color.g(g_upTrendColor))
                    b1 = color.b(g_upTrendColor) + 2 * (1 - currentSwamiRSI) * (color.b(g_flatColor) - color.b(g_upTrendColor))
                    barColor := color.rgb(math.round(r1), math.round(g1), math.round(b1))
                else
                    r1 = color.r(g_dnTrendColor) + 2 * currentSwamiRSI * (color.r(g_flatColor) - color.r(g_dnTrendColor))
                    g1 = color.g(g_dnTrendColor) + 2 * currentSwamiRSI * (color.g(g_flatColor) - color.g(g_dnTrendColor))
                    b1 = color.b(g_dnTrendColor) + 2 * currentSwamiRSI * (color.b(g_flatColor) - color.b(g_dnTrendColor))
                    barColor := color.rgb(math.round(r1), math.round(g1), math.round(b1))

            currentValue = if g_scaleMode == 0
                float(i + g_startLength)
            else
                float(i) * g_fuzzWidth

            // Create the box and store its ID in our global array
            newBox = box.new(time[0], currentValue - 0.5 * g_fuzzWidth,
                             time, currentValue + 0.5 * g_fuzzWidth,
                             border_color=barColor, border_width=0, bgcolor=color.new(barColor, 50))
            array.push(all_swami_boxes, newBox) // Add the new box ID to our array
    else
        // If not plotting boxes for this bar, ensure all boxes are deleted
        if bar_index == last_bar_index and g_swamiBars == -1
            // Added check for array size before looping
            if array.size(all_swami_boxes) > 0
                for i = 0 to array.size(all_swami_boxes) - 1
                    box.delete(array.get(all_swami_boxes, i))
            array.clear(all_swami_boxes)


// --- Plotting the Lines ---
plot(rsiPlot, "SwamiRSI_Sample", color.rgb(139, 0, 139), style=plot.style_line, linewidth=2) // DarkOrchid
plot(sumRSIPlot, "SummaryRSI", color.rgb(210, 105, 30), style=plot.style_line, linewidth=2) // Chocolate

// Plot horizontal lines for min/max values
plot(g_minValue, "Min Value", color.gray, style=plot.style_stepline)
plot(g_maxValue, "Max Value", color.gray, style=plot.style_stepline)

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("Past Regression Deviated", overlay=true)

// Input parameters
var int lrLength = input.int(500, "LR Length (bars back)", minval=1)
var float stdChannel1 = input.float(1.0, "Std Channel 1 Multiplier", minval=0.0)
var float stdChannel2 = input.float(2.0, "Std Channel 2 Multiplier", minval=0.0)
var float stdChannel3 = input.float(3.0, "Std Channel 3 Multiplier", minval=0.0)

// Function to calculate Linear Regression coefficients (a and b)
// Returns [a, b] for y = a + b*x, where x=0 is the *oldest* bar in the window
// and x=length-1 is the *current* bar in the window.
f_linreg_coeffs(source, length) =>
    if length <= 1
        [float(na), float(na), float(na)] // Return a, b, and a flag for denominator == 0
    else
        sumY = 0.0
        sumX = 0.0
        sumXY = 0.0
        sumX2 = 0.0
        for i = 0 to length - 1
            val = source[i]
            // 'x' here represents the position within the current `length` window,
            // with 0 being the oldest bar in the window, and `length - 1` being the newest (current bar).
            x = float(length - 1 - i)
            sumY += val
            sumXY += val * x
            sumX += x
            sumX2 += x * x
       
        denominator = length * sumX2 - sumX * sumX
       
        if denominator == 0
            [float(na), float(na), float(na)]
        else
            b = (length * sumXY - sumX * sumY) / denominator
            a = (sumY - b * sumX) / length
            [a, b, 1.0] // Return coefficients and success flag

// Function to calculate Standard Deviation
// Takes source series, regression coefficients (a, b), and length
calc_stddev(source, a_coeff, b_coeff, length) =>
    sumSquaredDev = 0.0
    count = 0
   
    if na(a_coeff) or na(b_coeff)
        0.0 // Cannot calculate if coefficients are NA

    for i = 0 to length - 1
        // 'x_val' is the position within the current `length` window for this bar `i`
        // where 0 is the oldest bar and `length - 1` is the current bar.
        x_val = float(length - 1 - i)
       
        // Calculate the LR value at this specific bar using the computed 'a' and 'b'
        lr_val_at_i = a_coeff + b_coeff * x_val
       
        dev = math.abs(source[i] - lr_val_at_i)
        sumSquaredDev += dev * dev
        count += 1
   
    if count <= 1
        0.0
    else
        math.sqrt(sumSquaredDev / (count - 1))

// Declare variables to store the calculated values
var float meanBuffer = na
var float lrPrice1 = na // This corresponds to the start of the LR line (oldest point in range)
var float currentStdDev = na

// Calculate on each historical bar and the last bar
if barstate.islast or barstate.isconfirmed
    // Get the regression coefficients for the current window
    [a_lr, b_lr, success_flag] = f_linreg_coeffs(close, lrLength)

    if not na(success_flag) // Only proceed if coefficients were calculated successfully
        // meanBuffer corresponds to the LR value at the current bar (newest point in range)
        meanBuffer := a_lr + b_lr * (lrLength - 1)
       
        // lrPrice1 corresponds to the LR value at the oldest bar in the range
        lrPrice1 := a_lr
       
        // Calculate standard deviation using the obtained coefficients
        currentStdDev := calc_stddev(close, a_lr, b_lr, lrLength)
    else
        meanBuffer := na
        lrPrice1 := na
        currentStdDev := na


// Plotting
plot(meanBuffer, "Mean", color.white)
//plot(meanBuffer + (stdChannel1 * currentStdDev), "1st Std up", color.white)
//plot(meanBuffer - (stdChannel1 * currentStdDev), "1st Std down", color.white)
//plot(meanBuffer + (stdChannel2 * currentStdDev), "2nd Std up", color.white)
//plot(meanBuffer - (stdChannel2 * currentStdDev), "2nd Std down", color.white)
plot(meanBuffer + (stdChannel3 * currentStdDev), "3rd Std up", color.white)
plot(meanBuffer - (stdChannel3 * currentStdDev), "3rd Std down", color.white)

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("Monthly Pivot Points", overlay=true)

// --- Function to get monthly OHLC ---
var float last_month_high = na
var float last_month_low = na
var float last_month_close = na
var float this_month_open = na

var float P = na
var float S1 = na
var float R1 = na
var float S2 = na
var float R2 = na
var float S3 = na
var float R3 = na

var int lastMonth = na
newMonth = (month != month[1])

// Track highest/lowest of previous month
if newMonth
    last_month_close := close[1]
    this_month_open := open
    last_month_high := high[1]
    last_month_low := low[1]
    for i = 1 to 500
        if (month[i] != month)
            last_month_high := math.max(last_month_high, high[i])
            last_month_low := math.min(last_month_low, low[i])
        else
            break
    P := (last_month_high + last_month_low + this_month_open + last_month_close) / 4
    R1 := (2 * P) - last_month_low
    S1 := (2 * P) - last_month_high
    R2 := P + (last_month_high - last_month_low)
    S2 := P - (last_month_high - last_month_low)
    R3 := (2 * P) + (last_month_high - 2 * last_month_low)
    S3 := (2 * P) - ((2 * last_month_high) - last_month_low)

// Extend pivots through the month
Pline = P
S1line = S1
R1line = R1
S2line = S2
R2line = R2
S3line = S3
R3line = R3

// Plot lines
plot(Pline, title="Monthly Pivot", color=color.red, linewidth=2)
plot(S1line, title="S1", color=color.blue, linewidth=1)
plot(R1line, title="R1", color=color.green, linewidth=1)
plot(S2line, title="S2", color=color.blue, linewidth=1)
plot(R2line, title="R2", color=color.green, linewidth=1)
plot(S3line, title="S3", color=color.orange, linewidth=1)
plot(R3line, title="R3", color=color.orange, linewidth=1)

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("Mogalef Bands", overlay=true)

// === Inputs ===
lp = input.int(25, title="Linear Regression Period")
sp = input.int(30, title="StdDev Period")

// === Helper function: Linear Regression ===
linear_regression(src, len) =>
    var float slope = na
    var float intercept = na
    float sumX = 0
    float sumY = 0
    float sumXY = 0
    float sumX2 = 0

    for i = 0 to len - 1
        sumX += i
        sumY += src[i]
        sumXY += i * src[i]
        sumX2 += i * i

    divisor = (len * sumX2 - sumX * sumX)
    slope := divisor == 0 ? 0 : (len * sumXY - sumX * sumY) / divisor
    intercept := (sumY - slope * sumX) / len

    // Value at bar zero (most recent)
    intercept + slope * (len - 1)

// === Build arrays for LinReg and StdDev ===
var float[] linreg_arr = array.new_float()
var float[] stddev_arr = array.new_float()

linreg_val = linear_regression(close, lp)
array.unshift(linreg_arr, linreg_val)
if array.size(linreg_arr) > 500
    array.pop(linreg_arr)

stddev_val = ta.stdev(array.get(linreg_arr, 0), sp)
array.unshift(stddev_arr, stddev_val)
if array.size(stddev_arr) > 500
    array.pop(stddev_arr)

// === Calculate bands ===
hiband = linreg_val + stddev_val * 2
loband = linreg_val - stddev_val * 2
median = (hiband + loband) / 2

// === Apply the Mogalef override logic ===
hiband_prev = nz(hiband[1])
loband_prev = nz(loband[1])
linreg_prev = nz(linreg_val[1])

hiband := (linreg_val < hiband_prev and linreg_val > loband_prev) ? hiband_prev : hiband
loband := (linreg_val < hiband_prev and linreg_val > loband_prev) ? loband_prev : loband
median := (hiband + loband) / 2

// === Plot bands ===
plot(hiband, color=color.red, title="Upper Band", style=plot.style_line)
plot(loband, color=color.green, title="Lower Band", style=plot.style_line)
plot(median, color=color.blue, title="Median", style=plot.style_line)

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("MA Channels FiboEnv Mid", overlay=true)

// === INPUT PARAMETERS ===
barsCount     = input.int(1000, title="Bars Count")
maPeriod      = input.int(55, title="MA Period")
maType        = input.string("SMA", title="MA Type", options=["SMA", "EMA", "SMMA", "LWMA"])
priceSource   = input.string("Median", title="Price Source", options=["Close", "Open", "High", "Low", "Median", "Typical", "Weighted"])
maShift       = input.int(0, title="MA Shift")

// === PRICE SOURCE ===
src = switch priceSource
    "Close" => close
    "Open" => open
    "High" => high
    "Low" => low
    "Median" => hl2
    "Typical" => (high + low + close) / 3
    "Weighted" => (high + low + close + close) / 4

// === MA FUNCTION ===
getMA(source, length) =>
    switch maType
        "SMA" => ta.sma(source, length)
        "EMA" => ta.ema(source, length)
        "SMMA" => ta.rma(source, length)
        "LWMA" => ta.wma(source, length)

// === CALCULATE RANGE OVER LAST barsCount BARS ===
var float maxDev = na
var float minDev = na

if bar_index >= barsCount + maPeriod
    maxDev := 0.0
    minDev := 0.0
    for i = 0 to barsCount
        ma_i = getMA(src[i], maPeriod)
        top = high[i] - ma_i
        bottom = low[i] - ma_i
        maxDev := math.max(maxDev, top)
        minDev := math.min(minDev, bottom)

// === FIBO OFFSETS ===
inc4 = math.abs(maxDev) > math.abs(minDev) ? maxDev : minDev
inc1 = (maxDev - minDev) * 0.118
inc2 = (maxDev - minDev) * 0.264
inc3 = (maxDev - minDev) * 0.5

// === BASE MA ===
baseMA = getMA(src[maShift], maPeriod)

// === CHANNEL LEVELS ===
fibUp100 = baseMA + inc3
fibDn23  = baseMA + inc2
fibDn38  = baseMA + inc1
fib50    = baseMA
fibUp38  = baseMA - inc1
fibUp23  = baseMA - inc2
fibDn100 = baseMA - inc3

// === PLOT ===
plot(fibUp100, title="FibMA Up 100%", color=color.purple)
plot(fibDn23,  title="FibMA Down 23.5%", color=color.purple)
plot(fibDn38,  title="FibMA Down 38.2 / Up 61.8%", color=color.purple)
plot(fib50,    title="FibMA 50%", color=color.purple)
plot(fibUp38,  title="FibMA Up 38.2 / Down 61.8%", color=color.purple)
plot(fibUp23,  title="FibMA Up 23.5%", color=color.purple)
plot(fibDn100, title="FibMA Down 100%", color=color.purple)

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("BB-HL", overlay=true)

// === INPUTS ===
per   = input.int(200, title="Period")
nDev  = input.float(2.0, title="Deviation Multiplier")

// === CALCULATIONS ===
medianPrice = hl2
ma = ta.sma(medianPrice, per)

// Compute squared deviation using max of High and Low deviation from MA
highDev = math.pow(high - ma, 2)
lowDev  = math.pow(low - ma, 2)
devMax  = math.max(highDev, lowDev)

// Rolling average of max squared deviation
devAvg = 0.0
devSum = 0.0

// Use a manual loop to simulate rolling sum of devMax
var float[] devBuffer = array.new_float()

// Update the buffer each bar
if bar_index > 0
    array.push(devBuffer, devMax)
    if array.size(devBuffer) > per
        array.shift(devBuffer)

// Compute rolling average from buffer
if array.size(devBuffer) >= per
    for i = 0 to array.size(devBuffer) - 1
        devSum := devSum + array.get(devBuffer, i)
    devAvg := devSum / per

// Standard deviation and bands
stdev = math.sqrt(devAvg)
upper = ma + nDev * stdev
lower = ma - nDev * stdev

// === PLOTS ===
plot(ma, title="MA", color=color.orange)
plot(upper, title="Upper Band", color=color.silver)
plot(lower, title="Lower Band", color=color.silver)

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("ATR Channels", overlay=true)

// === INPUTS ===
PeriodsATR   = input.int(18, title="ATR Period")
MA_Periods   = input.int(49, title="MA Period")
MA_type_opt  = input.string("SMA", title="MA Type", options=["SMA", "EMA", "WMA", "VWMA"])
Mult_Factor1 = input.float(1.6, title="Multiplier 1")
Mult_Factor2 = input.float(3.2, title="Multiplier 2")
Mult_Factor3 = input.float(4.8, title="Multiplier 3")

// === HELPER FUNCTIONS ===
get_ma(src, len) =>    MA_type_opt == "SMA"  ? ta.sma(src, len) :    MA_type_opt == "EMA"  ? ta.ema(src, len) :    MA_type_opt == "WMA"  ? ta.wma(src, len) :    MA_type_opt == "VWMA" ? ta.vwma(src, len) :    na

// === CORE CALCULATIONS ===
src = hlc3
atr = ta.atr(PeriodsATR)
ma = get_ma(src, MA_Periods)

// === CHANNEL LEVELS ===
ch1_upper = ma + Mult_Factor1 * atr
ch1_lower = ma - Mult_Factor1 * atr
ch2_upper = ma + Mult_Factor2 * atr
ch2_lower = ma - Mult_Factor2 * atr
ch3_upper = ma + Mult_Factor3 * atr
ch3_lower = ma - Mult_Factor3 * atr

// === PLOT ===
// Only the outermost bands are visible (like in your MQL4 indicator)
plot(ch3_upper, title="ATRu3", color=color.purple, linewidth=1)
plot(ch3_lower, title="ATRd3", color=color.purple, linewidth=1)

// Optional: Uncomment below to show inner bands too
//plot(ch1_upper, title="ATRu1", color=color.aqua, linewidth=1)
//plot(ch1_lower, title="ATRd1", color=color.aqua, linewidth=1)
//plot(ch2_upper, title="ATRu2", color=color.blue, linewidth=1)
//plot(ch2_lower, title="ATRd2", color=color.blue, linewidth=1)

// Optional: Plot the moving average line
//plot(ma, title="Moving Average", color=color.green)

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("TD Sequential", overlay=true)

var int numDown = 0
var int numUp = 0

pointSize = syminfo.mintick

// Recalculate TD counts
if close[1] < close[5]
    numDown += 1
else
    numDown := 0

if close[1] > close[5]
    numUp += 1
else
    numUp := 0

// Display Sell Setup (Down Count)
if (numDown > 0 and numDown < 10)
    label.new(bar_index[1], low[1] - 5 * pointSize, text=str.tostring(numDown), style=label.style_label_down, textcolor=color.red, size=size.small)
else if (numDown == 9)
    label.new(bar_index[1], low[1] - 5 * pointSize, text="9", style=label.style_label_down, textcolor=color.red, size=size.normal)
else if (close[1] < close[5] and numDown >= 10)
    label.new(bar_index[1], low[1] - 5 * pointSize, text=str.tostring(numDown), style=label.style_label_down, textcolor=color.orange, size=size.small)

// Display Buy Setup (Up Count)
if (numUp > 0 and numUp < 10)
    label.new(bar_index[1], high[1] + 10 * pointSize, text=str.tostring(numUp), style=label.style_label_up, textcolor=color.blue, size=size.small)
else if (numUp == 9)
    label.new(bar_index[1], high[1] + 10 * pointSize, text="9", style=label.style_label_up, textcolor=color.blue, size=size.normal)
else if (close[1] > close[5] and numUp >= 10)
    label.new(bar_index[1], high[1] + 10 * pointSize, text=str.tostring(numUp), style=label.style_label_up, textcolor=color.aqua, size=size.small)

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("CyAn 1 FT", overlay=false)

// === Input Parameters ===
lenth = input.int(5, title="Length")
maxbars = input.int(2000, title="Max Bars (not used in Pine)")

// === Recursive Buffers ===
var float aux_prev = 0.0
var float fish_prev = 0.0

// === Stochastic %K Calculation ===
k = ta.stoch(close, high, low, lenth)

// === Safe recursive update ===
var float aux = na
var float fish = na

if bar_index > lenth
    aux := 0.5 * ((k / 100.0 - 0.5) * 2) + 0.5 * aux_prev
    fish := 0.25 * math.log((1 + aux) / (1 - aux)) + 0.5 * fish_prev
    aux_prev := aux
    fish_prev := fish

// === Signal Line (1 bar lag) ===
signal = nz(fish[1])

// === Plotting ===
plot(aux, title="Aux", color=color.yellow, linewidth=2)
//plot(signal, title="Signal", color=color.red, linewidth=1)
hline(0.8, "Upper Level", color=color.yellow, linestyle=hline.style_dotted)
hline(-0.8, "Lower Level", color=color.yellow, linestyle=hline.style_dotted)
Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("DVI_ValueChart", overlay=false)

var float dvi = na
midpoint = (high + low + high[1] + low[1] + high[2] + low[2] + high[3] + low[3] + high[4] + low[4]) / 10

dvu = (volume * (high - low) + volume[1] * (high[1] - low[1]) + volume[2] * (high[2] - low[2]) + volume[3] * (high[3] - low[3]) + volume[4] * (high[4] - low[4])) / 5 * 0.02

dv = volume * ((close - midpoint) / midpoint)
dv := dvu != 0 ? dv / dvu : 0

dvi := na(dvi[1]) ? dv : dvi[1] + dv

plot(dvi, title="DVI_ValueChart", color=color.aqua, linewidth=1)
Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("Spud 2 (fixed)", overlay=false, max_bars_back=1000)

// Inputs
Per = input.int(15, minval=5, title="Period (must be multiple of 5)")
Pk = input.int(5, title="Pk")
Pd = input.int(3, title="Pd")
Ps = input.int(3, title="Ps")

factor = Per / 5

// Custom Stochastic Calculation on current bar using past bars only
customStoch() =>
    sumlo = 0.0
    sumhi = 0.0
    for j = 0 to Ps - 1
        barsBack = j * (Per / timeframe.multiplier)
        if barsBack <= bar_index
            clos1 = close[barsBack]
            pkLength = int(Pk * factor)
            highestHigh = ta.highest(high, pkLength)[barsBack]
            lowestLow = ta.lowest(low, pkLength)[barsBack]
            sumlo += clos1 - lowestLow
            sumhi += highestHigh - lowestLow
    sumhi <= 0 ? 100 : (sumlo / sumhi) * 100

// Linear regression on series data
lreg_series(buffer, length) =>
    if length <= 1
        na
    else
        Sx = 0.0
        Sy = 0.0
        Sxx = 0.0
        Sxy = 0.0
        for i = 0 to length - 1
            x = i * 1.0
            y = buffer[i]
            Sx += x
            Sy += y
            Sxx += x * x
            Sxy += x * y
        n = length * 1.0
        c = Sxx * n - Sx * Sx
        if c == 0
            na
        else
            beta = (n * Sxy - Sx * Sy) / c
            alpha = (Sy - beta * Sx) / n
            alpha

// Calculate SBuffer for current bar
SBuffer = customStoch()

// Calculate MaBuffer as linear regression of SBuffer over last Pd bars
MaBuffer = bar_index >= Pd - 1 ? lreg_series(SBuffer, Pd) : na

// Plot
//plot(SBuffer, color=color.gray, title="Stoch")
plot(MaBuffer, color=color.red, title="Ma")
Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("TSI", overlay=false)

First_R = input.int(5, title="First EMA Period")
Second_S = input.int(8, title="Second EMA Period")

// Momentum (MTM)
mtm = close - close[1]
abs_mtm = math.abs(mtm)

// First smoothing
ema_mtm = ta.ema(mtm, First_R)
ema_abs_mtm = ta.ema(abs_mtm, First_R)

// Second smoothing
ema2_mtm = ta.ema(ema_mtm, Second_S)
ema2_abs_mtm = ta.ema(ema_abs_mtm, Second_S)

// TSI Calculation
tsi = 100 * ema2_mtm / ema2_abs_mtm

plot(tsi, title="TSI", color=color.yellow, linewidth=2)
hline(0, "Zero Line", color=color.gray)

Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("Stochastic RSI [Ehlers]", overlay=false)

// === Input Parameters ===
rsiLength = input.int(5, title="RSI Length")
stocLength = input.int(5, title="Stochastic Length")
wmaLength = input.int(5, title="WMA Length")

// === Step 1: Calculate RSI ===
rsi = ta.rsi(close, rsiLength)

// === Step 2: Calculate Highest High and Lowest Low of RSI over Stochastic Length ===
hh = ta.highest(rsi, stocLength)
ll = ta.lowest(rsi, stocLength)

// === Step 3: Normalize RSI into Stochastic RSI ===
value1 = rsi - ll
value2 = hh - ll
value3 = value2 != 0 ? value1 / value2 : 0.0

// === Step 4: Smooth with WMA and scale ===
smoothed = ta.wma(value3, wmaLength)
stocRSI = 2.0 * (smoothed - 0.5)
trigger = stocRSI[1]

// === Plotting ===
plot(stocRSI, title="Stochastic RSI", color=color.red)
plot(trigger, title="Trigger", color=color.blue)
hline(0, color=color.gray, linestyle=hline.style_dotted)
hline(1, "Upper", color=color.gray, linestyle=hline.style_dashed)
hline(-1, "Lower", color=color.gray, linestyle=hline.style_dashed)
Code:
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("Anchored VWAP with Deviation Bands", overlay=true)

show_custom = input.bool(true, "Show Custom")
startfrom = input.time(timestamp("01 Jan 2020 00:00 +0000"), "Start From")
deviation_band_1 = input.float(1.0, "Deviation Band 1")

// Anchored region
var float cum_vp = na
var float cum_vol = na

// Reset at the anchor point
if (na(cum_vol))
    cum_vp := 0.0
    cum_vol := 0.0

is_after_start = time >= startfrom

vp = volume * hlc3

cum_vp := is_after_start ? cum_vp + vp : na
cum_vol := is_after_start ? cum_vol + volume : na

anchored_vwap = is_after_start and cum_vol != 0 ? cum_vp / cum_vol : na

// Store historical VWAP for deviation calculation
var float[] vwap_series = array.new_float()

if is_after_start
    array.unshift(vwap_series, anchored_vwap)
    if array.size(vwap_series) > bar_index
        array.pop(vwap_series)

// Calculate standard deviation from the anchored point
var float std_dev = na
if is_after_start and array.size(vwap_series) > 1
    float mean = anchored_vwap
    float sum_sq_diff = 0.0
    for i = 0 to array.size(vwap_series) - 1
        float val = array.get(vwap_series, i)
        sum_sq_diff += math.pow(val - mean, 2)
    std_dev := math.sqrt(sum_sq_diff / array.size(vwap_series))

upper_band = show_custom and not na(anchored_vwap) ? anchored_vwap + deviation_band_1 * std_dev : na
lower_band = show_custom and not na(anchored_vwap) ? anchored_vwap - deviation_band_1 * std_dev : na

plot(upper_band, color=color.red, title="Upper Band")
plot(lower_band, color=color.red, title="Lower Band")
plot(show_custom ? anchored_vwap : na, color=color.green, title="Anchored VWAP")
Reply


Messages In This Thread
Some useful TradingView Pinescript indicators from me - by qchartist - 05-30-2025, 10:37 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)