Andean Oscillator For ThinkOrSwim

samer800

Moderator - Expert
VIP
Lifetime
The Andean Oscillator is a technical tool designed to analyze market trends using bands, which are visual guides for price movement. For beginners, it’s helpful to first google the basics of trading with bands to ensure you have a solid foundation before diving into this indicator.

This oscillator provides several insights, but its primary focus is on two components: the bull component (green line) and the bear component (blue line). These lines represent bullish (upward) and bearish (downward) price trends, respectively.
  • Bull Component (Green Line): A rising green line signals increasing bullish momentum, suggesting prices are trending upward.
  • Bear Component (Blue Line): A rising blue line indicates growing bearish momentum, suggesting prices are trending downward.

Key Signals:​

  1. Bull > Bear: When the green line is above the blue line, the market is in an uptrend, and higher highs may be expected.
  2. Bear > Bull: When the blue line is above the green line, the market is in a downtrend, and lower lows are more likely.
This tool simplifies trend analysis, helping traders make more informed decisions about potential price movements.

ilvwaGK.png


you may find full details on the indicator below.
https://alpaca.markets/learn/andean...ed-on-an-online-algorithm-for-trend-analysis/

TV original code
https://www.tradingview.com/script/x9qYvBYN-Andean-Oscillator/

CSS:
#https://alpaca.markets/learn/andean-oscillator-a-new-technical-indicator-based-on-an-online-algorithm-for-trend-analysis/
#https://www.tradingview.com/script/x9qYvBYN-Andean-Oscillator/
#/indicator("Andean Oscillator")
# Converted and mod by Sam4Cok@Samer800 - 07/2022

declare lower;
#//Settings
input length = 50;
input sig_length = 9; #'Signal Length')
input ShowCloud = yes;
input BullBearLines = yes;
input SignalLine = yes;
input showHist   = yes;

########## Colors ########
DefineGlobalColor("Sky1" , CreateColor(0, 221, 255));
DefineGlobalColor("Sky2" , CreateColor(4, 188, 217));
DefineGlobalColor("Sky4" , CreateColor(4, 127, 145));
DefineGlobalColor("Sky5" , CreateColor(4, 103, 117));
DefineGlobalColor("Magenta1" , CreateColor(216, 0, 255));
DefineGlobalColor("Magenta2" , CreateColor(187, 4, 219));
DefineGlobalColor("Magenta4" , CreateColor(123, 3, 143));
DefineGlobalColor("Magenta5" , CreateColor(100, 2, 117));

DefineGlobalColor("Blue"   , CreateColor(17, 118, 242));
DefineGlobalColor("Lime"   , CreateColor(1, 255, 0));
############
script nz {
    input data  = 1;
    input repl  = 0;
    def ret_val = if IsNaN(data) then repl else data;
    plot return = ret_val;
}
def na = Double.NaN;

#//Exponential Envelopes
def alpha = 2 / (length + 1);

def C = close;
def O = open;

def up1 = nz(Max(Max(C, O) , Max(up1[1] - (up1[1] - C) * alpha, C)));
def up2 = nz(Max(Max(C * C, O * O), Max(up2[1] - (up2[1] - C * C) * alpha, C * C)));

def dn1 = nz(Min(Min(C, O) , Min(dn1[1] + (C - dn1[1]) * alpha, C)));
def dn2 = nz(Min(Min(C * C, O * O), Min(dn2[1] + (C * C - dn2[1]) * alpha, C * C)));

#//Components
def bull = Sqrt(dn2 - dn1 * dn1);
def bear = Sqrt(up2 - up1 * up1);
def signal = ExpAverage(Max(bull, bear), sig_length);

def ExUp  = bull > bear and bull > signal and bull > bull[1];
def ExUp1 = bull > bear and bull > signal and bull < bull[1];
def Up    = bull > bear and bull < signal and bull > bull[1];
def Up11  = bull > bear and bull < signal and bull < bull[1];
def ExDn  = bear > bull and bear > signal and bear > bear[1];
def ExDn1 = bear > bull and bear > signal and bear < bear[1];
def Dn    = bear > bull and bear < signal and bear > bear[1];
def Dn11  = bear > bull and bear < signal and bear < bear[1];
#//Plots
plot bullLine = if BullBearLines then bull else na; #'Bullish Component'
bullLine.SetDefaultColor(GlobalColor("Lime"));
bullLine.SetLineWeight(2);
bullLine.HideTitle();

plot bearLine = if BullBearLines then bear else na; #'Bearish Component'
bearLine.SetDefaultColor(GlobalColor("Blue"));
bearLine.SetLineWeight(2);
bearLine.HideTitle();

plot SigLine = if SignalLine then signal else na;#'Signal'
SigLine.AssignValueColor(if ExUp  then GlobalColor("Sky1") else
                         if ExUp1 then GlobalColor("Sky2") else
                         if up    then GlobalColor("Sky4") else
                         if up11  then GlobalColor("Sky5") else
                         if ExDn  then GlobalColor("Magenta1") else
                         if ExDn1 then GlobalColor("Magenta2") else
                         if Dn    then GlobalColor("Magenta4") else
                         if Dn11  then GlobalColor("Magenta5") else color.GRAY);
SigLine.SetLineWeight(3);
SigLine.HideTitle();

plot SigHist = if ShowHist then signal else na;#'Signal'
SigHist.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
SigHist.SetLineWeight(2);
SigHist.AssignValueColor(if ExUp  then GlobalColor("Sky1") else
                         if ExUp1 then GlobalColor("Sky2") else
                         if up    then GlobalColor("Sky4") else
                         if up11  then GlobalColor("Sky5") else
                         if ExDn  then GlobalColor("Magenta1") else
                         if ExDn1 then GlobalColor("Magenta2") else
                         if Dn    then GlobalColor("Magenta4") else
                         if Dn11  then GlobalColor("Magenta5") else color.GRAY);

AddCloud(if ShowCloud then bullLine else na,  bearLine,  Color.DARK_GREEN,  Color.DARK_RED);
#//----END----------------------------------------

New update ----

lcKPWDK.png


converted it to Andean-MACD ..

CODE:

CSS:
#https://alpaca.markets/learn/andean-oscillator-a-new-technical-indicator-based-on-an-online-algorithm-for-trend-analysis/
#https://www.tradingview.com/script/x9qYvBYN-Andean-Oscillator/
#/indicator("Andean Oscillator")
# Converted and mod by Sam4Cok@Samer800 - 07/2022.
# V1.5 included Histogram option, label, Background & bug fix. 08/2022.

declare lower;
#//Settings
input label = Yes;
input length = 50;
input sig_length = 9; #'Signal Length')
input ShowCloud = yes;
input showHist  = yes;

########## Colors ########
DefineGlobalColor("Green1" , CreateColor(1, 255, 0));
DefineGlobalColor("Green2" , CreateColor(4, 181, 4));
DefineGlobalColor("Green3" , CreateColor(3, 145, 3));
DefineGlobalColor("Green4" , CreateColor(2, 117, 2));
DefineGlobalColor("Red1" , CreateColor(255, 5, 5));
DefineGlobalColor("Red2" , CreateColor(184, 6, 6));
DefineGlobalColor("Red3" , CreateColor(145, 3, 3));
DefineGlobalColor("Red4" , CreateColor(117, 2, 2));

############
script nz {
    input data  = Close;
    input repl  = 0;
    def ret_val = if IsNaN(data) then repl else data;
    plot return = ret_val;
}
def na = Double.NaN;

#//Exponential Envelopes
def alpha = 2 / (length + 1);

def up1;
def up2;
def dn1;
def dn2;
up1 = if isNaN(up1[1]) then 0 else nz(Max(Max(close, open), up1[1] - (up1[1] - close) * alpha), close);
up2 = if isNaN(up2[1]) then 0 else nz(Max(Max(Sqr(close), Sqr(open)), up2[1] - (up2[1] - Sqr(close)) * alpha), Sqr(Close));

dn1 = if isNaN(dn1[1]) then 0 else nz(Min(Min(close, open), dn1[1] + (close - dn1[1]) * alpha), close);
dn2 = if isNaN(dn2[1]) then 0 else nz(Min(Min(Sqr(close), Sqr(open)), dn2[1] + (Sqr(close) - dn2[1]) * alpha), Sqr(close));

#//Components
def bull = Sqrt(dn2 - dn1 * dn1);
def bear = Sqrt(up2 - up1 * up1);

def Signal = ExpAverage(Max(bull, bear), sig_length);
def sigBull = ExpAverage(bull, sig_length);
def sigBear = ExpAverage(bear, sig_length);

def differ = sigBull - sigBear;

def ExUp  = bull > bear and bull > Signal and differ > differ[1] and differ >= 0;
def ExUp1 = bull > bear and bull > Signal and differ < differ[1] and differ >= 0;
def Up    = bull > bear and bull < Signal and differ > differ[1] and differ >= 0;
def Up11  = bull > bear and bull < Signal and differ < differ[1] and differ >= 0;
def ExDn  = bear > bull and bear > Signal and differ < differ[1] and differ < 0;
def ExDn1 = bear > bull and bear > Signal and differ > differ[1] and differ < 0;
def Dn    = bear > bull and bear < Signal and differ < differ[1] and differ < 0;
def Dn11  = bear > bull and bear < Signal and differ > differ[1] and differ < 0;
#//Plots

plot SigLine = Signal;#'Signal'
SigLine.SetHiding(showHist);
SigLine.SetDefaultColor(Color.YELLOW);

plot bullLine = bull; #'Bullish Component'
bullLine.SetDefaultColor(Color.GREEN);
bullLine.SetLineWeight(2);
bullLine.SetHiding(showHist);
bullLine.HideTitle();

plot bearLine = bear; #'Bearish Component'
bearLine.SetDefaultColor(Color.RED);
bearLine.SetLineWeight(2);
bearLine.SetHiding(showHist);
bearLine.HideTitle();

plot ZeroLine = 0;
ZeroLine.SetDefaultColor(Color.GRAY);
ZeroLine.SetStyle(Curve.SHORT_DASH);
ZeroLine.SetHiding(!showHist);

plot diff = differ;
diff.SetDefaultColor(GetColor(5));
diff.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
diff.SetLineWeight(3);
diff.SetHiding(!showHist);
diff.AssignValueColor(if ExUp  then GlobalColor("Green1") else
                      if ExUp1 then GlobalColor("Green2") else
                      if Up    then GlobalColor("Green3") else
                      if Up11  then GlobalColor("Green4") else
                      if ExDn  then GlobalColor("Red1") else
                      if ExDn1 then GlobalColor("Red2") else
                      if Dn    then GlobalColor("Red3") else
                      if Dn11  then GlobalColor("Red4") else CreateColor(255, 241, 118));
plot diffLine = differ;
diffLine.SetHiding(!showHist);
diffLine.AssignValueColor( if diff >= 0 then GlobalColor("Green1") else
                             GlobalColor("Red1"));

AddCloud(if ShowCloud and !showHist then bull else na, bear  , Color.DARK_GREEN, Color.DARK_RED);
AddCloud(if ShowCloud and !showHist then bear else na, Signal, Color.RED, Color.DARK_GREEN);
AddCloud(if ShowCloud and !showHist then bull else na, Signal, Color.GREEN, Color.DARK_RED);

AddCloud(if ShowCloud then if ExUp then Double.POSITIVE_INFINITY else
         if ExDn then Double.NEGATIVE_INFINITY else na else na,
         if ExUp then Double.NEGATIVE_INFINITY else
         if ExDn then Double.POSITIVE_INFINITY else na,
          GlobalColor("Green3"), GlobalColor("Red3"));
addlabel(Label and ExUp, "Xtrm Up",  GlobalColor(“Green1”));
addlabel(Label and ExUp1,"Up",       GlobalColor(“Green2”));
addlabel(Label and Up,   "Weak Up",  GlobalColor(“Green3”));
addlabel(Label and Up11, "X Weak Up",GlobalColor(“Green4”));
addlabel(Label and ExDn, "Xtrm Dwn", GlobalColor(“Red1”));
addlabel(Label and ExDn1,"Dwn",      GlobalColor(“Red2”));
addlabel(Label and Dn,   "Weak Dwn", GlobalColor(“Red3”));
addlabel(Label and Dn11, "X weak dwn", GlobalColor(“Red4”));

#//----END----------------------------------------
 
Last edited by a moderator:

Join useThinkScript to post your question to a community of 21,000+ developers and traders.

ilvwaGK.png


you may find full details on the indicator below.
https://alpaca.markets/learn/andean...ed-on-an-online-algorithm-for-trend-analysis/

TV original code
https://www.tradingview.com/script/x9qYvBYN-Andean-Oscillator/

CSS:
#https://alpaca.markets/learn/andean-oscillator-a-new-technical-indicator-based-on-an-online-algorithm-for-trend-analysis/
#https://www.tradingview.com/script/x9qYvBYN-Andean-Oscillator/
#/indicator("Andean Oscillator")
# Converted and mod by Sam4Cok@Samer800 - 07/2022

declare lower;
#//Settings
input length = 50;
input sig_length = 9; #'Signal Length')
input ShowCloud = yes;
input BullBearLines = yes;
input SignalLine = yes;
input showHist   = yes;

########## Colors ########
DefineGlobalColor("Sky1" , CreateColor(0, 221, 255));
DefineGlobalColor("Sky2" , CreateColor(4, 188, 217));
DefineGlobalColor("Sky4" , CreateColor(4, 127, 145));
DefineGlobalColor("Sky5" , CreateColor(4, 103, 117));
DefineGlobalColor("Magenta1" , CreateColor(216, 0, 255));
DefineGlobalColor("Magenta2" , CreateColor(187, 4, 219));
DefineGlobalColor("Magenta4" , CreateColor(123, 3, 143));
DefineGlobalColor("Magenta5" , CreateColor(100, 2, 117));

DefineGlobalColor("Blue"   , CreateColor(17, 118, 242));
DefineGlobalColor("Lime"   , CreateColor(1, 255, 0));
############
script nz {
    input data  = 1;
    input repl  = 0;
    def ret_val = if IsNaN(data) then repl else data;
    plot return = ret_val;
}
def na = Double.NaN;

#//Exponential Envelopes
def alpha = 2 / (length + 1);

def C = close;
def O = open;

def up1 = nz(Max(Max(C, O) , Max(up1[1] - (up1[1] - C) * alpha, C)));
def up2 = nz(Max(Max(C * C, O * O), Max(up2[1] - (up2[1] - C * C) * alpha, C * C)));

def dn1 = nz(Min(Min(C, O) , Min(dn1[1] + (C - dn1[1]) * alpha, C)));
def dn2 = nz(Min(Min(C * C, O * O), Min(dn2[1] + (C * C - dn2[1]) * alpha, C * C)));

#//Components
def bull = Sqrt(dn2 - dn1 * dn1);
def bear = Sqrt(up2 - up1 * up1);
def signal = ExpAverage(Max(bull, bear), sig_length);

def ExUp  = bull > bear and bull > signal and bull > bull[1];
def ExUp1 = bull > bear and bull > signal and bull < bull[1];
def Up    = bull > bear and bull < signal and bull > bull[1];
def Up11  = bull > bear and bull < signal and bull < bull[1];
def ExDn  = bear > bull and bear > signal and bear > bear[1];
def ExDn1 = bear > bull and bear > signal and bear < bear[1];
def Dn    = bear > bull and bear < signal and bear > bear[1];
def Dn11  = bear > bull and bear < signal and bear < bear[1];
#//Plots
plot bullLine = if BullBearLines then bull else na; #'Bullish Component'
bullLine.SetDefaultColor(GlobalColor("Lime"));
bullLine.SetLineWeight(2);
bullLine.HideTitle();

plot bearLine = if BullBearLines then bear else na; #'Bearish Component'
bearLine.SetDefaultColor(GlobalColor("Blue"));
bearLine.SetLineWeight(2);
bearLine.HideTitle();

plot SigLine = if SignalLine then signal else na;#'Signal'
SigLine.AssignValueColor(if ExUp  then GlobalColor("Sky1") else
                         if ExUp1 then GlobalColor("Sky2") else
                         if up    then GlobalColor("Sky4") else
                         if up11  then GlobalColor("Sky5") else
                         if ExDn  then GlobalColor("Magenta1") else
                         if ExDn1 then GlobalColor("Magenta2") else
                         if Dn    then GlobalColor("Magenta4") else
                         if Dn11  then GlobalColor("Magenta5") else color.GRAY);
SigLine.SetLineWeight(3);
SigLine.HideTitle();

plot SigHist = if ShowHist then signal else na;#'Signal'
SigHist.SetPaintingStrategy(PaintingStrategy.HISTOGRAM);
SigHist.SetLineWeight(2);
SigHist.AssignValueColor(if ExUp  then GlobalColor("Sky1") else
                         if ExUp1 then GlobalColor("Sky2") else
                         if up    then GlobalColor("Sky4") else
                         if up11  then GlobalColor("Sky5") else
                         if ExDn  then GlobalColor("Magenta1") else
                         if ExDn1 then GlobalColor("Magenta2") else
                         if Dn    then GlobalColor("Magenta4") else
                         if Dn11  then GlobalColor("Magenta5") else color.GRAY);

AddCloud(if ShowCloud then bullLine else na,  bearLine,  Color.DARK_GREEN,  Color.DARK_RED);
#//----END----------------------------------------
I find that your color scheme to be confusing, I use a light to dark and then back to light more insightful for a trader, lighter colors for improving conditions and darker colors for worsening conditions

Code:
DefineGlobalColor("Sky1" , Color.Cyan);
DefineGlobalColor("Sky2" , CreateColor(50, 150, 200));
DefineGlobalColor("Sky4" , CreateColor(50, 150, 250));
DefineGlobalColor("Sky5" , Color.Blue);
DefineGlobalColor("Magenta1" , Color.Plum);
DefineGlobalColor("Magenta2" , Color.Magenta);
DefineGlobalColor("Magenta4" , CreateColor(225, 125, 225));
DefineGlobalColor("Magenta5" , CreateColor(225,175, 225));

I also added labels so that I can tell what the bar is
Code:
input label = Yes;
addlabel(Label == yes,"ExUp", GlobalColor(“Sky1”));
addlabel(Label == yes,"ExUp1", GlobalColor(“Sky2”));
addlabel(Label == yes," Up", GlobalColor(“Sky4”));
addlabel(Label == yes," Up11", GlobalColor(“Sky5”));
addlabel(Label == yes,"ExDn", GlobalColor(“Magenta1”));
addlabel(Label == yes,"ExDn1", GlobalColor(“Magenta2”));
addlabel(Label == yes,"Dn", GlobalColor(“Magenta4”));
addlabel(Label == yes,"Dn11", GlobalColor(“Magenta5”));
 
The author states:
This is an experimental signal providing script for scalper that uses 2 of open source indicators.

First one provides the signals for us called Andean Oscillator by alexgrover. We use it to create long signals when bull line crosses over signal line while being above the bear line. And reverse is true for shorts where bear line crosses over signal line while being above bull line.

Second one is used for filtering out low volatility areas thanks to great idea by HeWhoMustNotBeNamed called Relative Bandwidth Filter. We use it to filter out signals and create signals only when the Relative Bandwith Line below middle line.

The default values for both indicators changed a bit, especially used linreg values to create relatively better signals. These can be changed in settings.

Please be aware that i did not do extensive testing with this indicator in markets other than crypto so it should be used with caution.

WO6o6TU.png

Original Tradingview code
https://www.tradingview.com/script/Pc13q4HI-Relative-Andean-Scalping/

For the new ThinkOrSwim code, you must scroll down to the next post
 
Last edited by a moderator:
I'm a fan of these indicators
https://usethinkscript.com/threads/andean-oscillator-for-thinkorswim.12034/#post-103474
and I was hoping @samer800 could go for the trifecta of this series and hopefully convert the Relative Andean Scalping indicator.
https://www.tradingview.com/script/Pc13q4HI-Relative-Andean-Scalping/

Thank you for taking the time to convert these great indicators!

Code is below:


Code:
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0
// This script uses source code of Andean Oscilator by @alexgrover and Relative Bandwith Filter by @HeWhoMustNotBeNamed
// This is an experimental signal indicator and should be used with caution.
// © serkany88

//@version=5
indicator("Relative Andean Scalping", precision=3, overlay=true)

// Functions used later
f_ideal_TimesInLast(_cond, _len) =>  math.sum(_cond ? 1 : 0, _len)

//------------------------------------------------------------------------------
//Andean Settings and Calculation by @alexgrover
//-----------------------------------------------------------------------------{
and_length     = input.int(100, minval=1, title='Andean Length', group='Andean Oscilator Settings')

and_sig_length = input.int(13, title='Andean Signal Length', group='Andean Oscilator Settings')

//Andean Calculation
var alpha = 2/(and_length+1)

var up1 = 0.,var up2 = 0.
var dn1 = 0.,var dn2 = 0.

C = close
O = open

up1 := nz(math.max(C, O, up1[1] - (up1[1] - C) * alpha), C)
up2 := nz(math.max(C * C, O * O, up2[1] - (up2[1] - C * C) * alpha), C * C)

dn1 := nz(math.min(C, O, dn1[1] + (C - dn1[1]) * alpha), C)
dn2 := nz(math.min(C * C, O * O, dn2[1] + (C * C - dn2[1]) * alpha), C * C)

bull = math.sqrt(dn2 - dn1 * dn1)
bear = math.sqrt(up2 - up1 * up1)

signal = ta.ema(math.max(bull, bear), and_sig_length)
//-----------------------------------------------------------------------------}

//------------------------------------------------------------------------------
//Relative Bandwith Filter by @HeWhoMustNotBeNamed
//-----------------------------------------------------------------------------{
import HeWhoMustNotBeNamed/enhanced_ta/14 as eta

bandType = input.string("KC", title="Bands Type", group="Relative Bandwith Filter Bands", options=["BB", "KC", "DC"])
bmasource = input.source(close, title="Bands Source", group="Relative Bandwith Filter Bands")
bmatype = input.string("linreg", title="Bands Type", group="Relative Bandwith Filter Bands", options=["sma", "ema", "hma", "rma", "wma", "vwma", "swma", "linreg", "median"])
bmalength = input.int(34, title="Bands Length", group="Relative Bandwith Filter Bands")
multiplier = input.float(2.0, step=0.5, title="Bands Multiplier", group="Relative Bandwith Filter Bands")
useTrueRange = input.bool(true, title="Bands Use True Range (KC)", group="Relative Bandwith Filter Bands")
useAlternateSource = input.bool(false, title="Bands Use Alternate Source (DC)", group="Relative Bandwith Filter Bands")
bsticky = input.bool(true, title="Sticky Lines", group="Relative Bandwith Filter Bands")

atrLength = input.int(34, 'ATR Length', group='Relative Bandwith Filter ATR')

bbmatype = input.string("linreg", title="BBands Type", group="Relative Bandwith Filter BBands", options=["sma", "ema", "hma", "rma", "wma", "vwma", "linreg", "median"])
bbmalength = input.int(100, title="BBands Length", group="Relative Bandwith Filter BBands")
mmultiplier = input.float(1.0, step=0.5, title="BBands Multiplier", group="Relative Bandwith Filter BBands")

desiredCondition = input.string("Higher Bandwidth", "Desired Condition", options=["Higher Bandwidth", "Lower Bandwidth"], group="Relative Bandwith Filter")
referenceBand = input.string("Middle", options=["Upper", "Lower", "Middle"], group="Relative Bandwith Filter")

var cloudTransparency = 90
[bbmiddle, bbupper, bblower] = eta.bb(bmasource, bmatype, bmalength, multiplier, sticky=bsticky)
[kcmiddle, kcupper, kclower] = eta.kc(bmasource, bmatype, bmalength, multiplier, useTrueRange, sticky=bsticky)
[dcmiddle, dcupper, dclower] = eta.dc(bmalength, useAlternateSource, bmasource, sticky=bsticky)

upper = bandType == "BB"? bbupper : bandType == "KC"? kcupper : dcupper
lower = bandType == "BB"? bblower : bandType == "KC"? kclower : dclower
middle = bandType == "BB"? bbmiddle : bandType == "KC"? kcmiddle : dcmiddle

atr = ta.atr(atrLength)

relativeBandwidth = (upper-lower)/atr

[mmiddle, uupper, llower] = eta.bb(relativeBandwidth, bbmatype, bbmalength, mmultiplier, sticky=false)

reference = referenceBand == "Middle"? mmiddle : referenceBand == "Upper"? uupper : llower
bbsignal = relativeBandwidth > reference? 2 : 0
bbsignal := desiredCondition == "Lower Bandwidth"? math.abs(bbsignal-2) : bbsignal
//-----------------------------------------------------------------------------}

//------------------------------------------------------------------------------
//Entry Condition Signals
//-----------------------------------------------------------------------------{
longCond = relativeBandwidth < mmiddle and bull > bear and ta.crossover(bull, signal)
shortCond = relativeBandwidth < mmiddle and bear > bull and ta.crossover(bear, signal)

//Define last signal condition to update later
var bool last_signal = false

plotshape(longCond and not(last_signal), title='Long Signal', style=shape.labelup, location=location.belowbar, color=color.green, text='Long', textcolor=color.white, size=size.small)
plotshape(shortCond and not(last_signal), title='Short Signal', style=shape.labeldown, location=location.abovebar, color=color.red, text='Short', textcolor=color.white, size=size.small)

//Alerts
alertcondition(longCond and not(last_signal), "Long Signal", message='Long Signal at Price: {{close}} @ {{ticker}}')
alertcondition(shortCond and not(last_signal), "Short Signal", message='Short Signal at Price: {{close}} @ {{ticker}}')
alertcondition((longCond and not(last_signal)) or (shortCond and not(last_signal)), "Long or Short Signal", message='Signal at Price: {{close}} @ {{ticker}}')

//We check if there is any signal in last 5 bars and if there is we won't show any signal to avoid confusion and filter out some bad signals
last_signal := f_ideal_TimesInLast(longCond or shortCond, 5) >= 1
check the below:

CSS:
#// Indicator for TOS
#// This script uses source code of Andean Oscilator by @alexgrover and Relative Bandwith Filter by @HeWhoMustNotBeNamed
#// This is an experimental signal indicator and should be used with caution.
#// © serkany88
#indicator("Relative Andean Scalping", precision=3, overlay=true)
# Converted by Sam4Cok@Samer800    - 11/2024

#//Andean Settings and Calculation by @alexgrover
input AndeanLength   = 100;     # 'Andean Length'
input AndeanSignalLength = 13;  # 'Andean Signal Length'

def na = Double.NaN;
def last = IsNaN(close);

#//Andean Calculation
def alpha = 2 / (AndeanLength + 1);

def up1 = if !up1[1] then close else Max(close, Max(open, up1[1] - (up1[1] - close) * alpha));
def up2 = if !up2[1] then Sqr(close) else Max(Sqr(close), Max(Sqr(open), up2[1] - (up2[1] - Sqr(close)) * alpha));

def dn1 = if !dn1[1] then close else Min(close, Min(open, dn1[1] + (close - dn1[1]) * alpha));
def dn2 = if !dn2[1] then Sqr(close) else Min(Sqr(close), Min(Sqr(open), dn2[1] + (Sqr(close) - dn2[1]) * alpha));

def bull = Sqrt(dn2 - dn1 * dn1);
def bear = Sqrt(up2 - up1 * up1);

def signal = ExpAverage(Max(bull, bear), AndeanSignalLength);

#//Relative Bandwith Filter by @HeWhoMustNotBeNamed

input bandType = {default KC, BB, DC};
input BandSource = close;
input BandMovAvg = {SMA, EMA, HMA, RMA, WMA, VWMA, SWMA, default Linreg, Median};
input BandLength = 34;
input BandMultiplier = 2.0;
input KCTrueRange = yes;      # "Use True Range (KC)"
input DCAlternateSource = no; # "Use Alternate Source (DC)"
input sticky = yes;            # "Sticky"
input atrLength = 34;
input BBMovAvg = {SMA, EMA, HMA, RMA, WMA, VWMA, SWMA, default Linreg, Median};
input bbLength = 100;        # "BB Length"
input BBMultiplier = 1.0;       # "Multiplier"


#swma(source)
script swma {
    input x = close;
    def swma = x[3] * 1 / 6 + x[2] * 2 / 6 + x[1] * 2 / 6 + x[0] * 1 / 6;
    plot return = swma;
}
#vwma(source, length)
script VWMA {
    input x = close;
    input y = 15;
    def VWMA = Average(x * volume, y) / Average(volume, y);
    plot result = VWMA;
}
#ma(type, source, length) =>
script ma {
    input type   = {SMA, EMA, HMA, RMA, WMA, VWMA, SWMA, default Linreg, Median};
    input source = close;
    input length = 100;
    def ma;
    Switch (type) {
    Case SMA : ma = Average(source, length);
    Case EMA : ma = ExpAverage(source, length);
    Case HMA : ma = HullMovingAvg(source, length);
    Case RMA : ma = WildersAverage(source, length);
    Case WMA : ma = WMA(source, length);
    Case VWMA: ma = VWMA(source, length);
    Case SWMA: ma = SWMA(source);
    Case Median: ma = Median(source, length);
    Default  : ma = Inertia(source, length);
    }
    plot result = ma;
}
#getStickyRange(highsource, lowsource, upper, lower, sticky=false)=>
script getStickyRange {
    input highsource = high;
    input lowsource = low;
    input upper = high;
    input lower = low;
    input sticky = no;
    def newUpper;
    def newLower;
    def prevUpper = if newUpper[1] then newUpper[1] else upper;
    def prevLower = if newLower[1] then newLower[1] else lower;
    def highBreakout = highsource[1] >= prevUpper;
    def lowBreakout  = lowsource[1]  <= prevLower;
        newUpper = if (highBreakout or lowBreakout or !sticky) then upper else prevUpper;
        newLower = if (highBreakout or lowBreakout or !sticky) then Lower else prevLower;
    plot UpBand = newUpper;
    plot LoBand = newLower;
}
#### BB
def sDev = StDev(BandSource, BandLength);
def BBMid = ma(BandMovAvg, BandSource, BandLength);
def BBup = BBMid + BandMultiplier * sDev;
def BBlo = BBMid - BandMultiplier * sDev;
def BBupper = getStickyRange(high, low, BBup, BBlo, sticky).Upband;
def BBlower = getStickyRange(high, low, BBup, BBlo, sticky).Loband;
def BBmiddle = (BBupper + BBlower) / 2;

##### KC
def tr = if IsNaN(close[1]) then high - low else TrueRange(high, close, low);
def span = BandMultiplier * ma(BandMovAvg, if KCTrueRange then tr else (high - low), BandLength);
def KCavg = ma(BandMovAvg, BandSource, BandLength);
def KCUp = KCavg + span;
def KClo = KCavg - span;
def KCnewUpper = getStickyRange(high, low, KCUp, KClo, sticky).Upband;
def KCnewLower = getStickyRange(high, low, KCUp, KClo, sticky).Loband;
def KCupper  = KCnewUpper;
def KClower  = KCnewLower;
def KCmiddle = (KCupper + KClower) / 2 ;

##### DC
def highSource = if DCAlternateSource then BandSource else high;
def lowSource  = if DCAlternateSource then BandSource else low;
def DCupp = Highest(highSource, BandLength);
def DClow = Lowest(lowSource, BandLength);
def DCnewUpper = getStickyRange(highSource, lowSource, DCupp, DClow, sticky).UpBand;
def DCnewLower = getStickyRange(highSource, lowSource, DCupp, DClow, sticky).LoBand;
def DCmid = (DCnewUpper + DCnewLower) / 2;
def DCupper  = DCnewUpper;
def DClower  = DCnewLower;
def DCmiddle = DCmid;

### Bands
def upper;
def lower;
def middle;
Switch (bandType) {
Case BB :
    upper  = BBupper;
    lower  = BBlower;
    middle = BBmiddle;
Case DC :
    upper  = DCupper;
    lower  = DClower;
    middle = DCmiddle;
Default :
    upper  = KCupper;
    lower  = KClower;
    middle = KCmiddle;
}

def atrValue = WildersAverage(tr, atrLength);
def relativeBandwidth = (upper - lower) / atrValue;

#### RB BB
def RBsDev = stdev(RelativeBandwidth,BBLength);
def RBMid = ma(BBMovAvg, RelativeBandwidth, BBLength);
def BBuup = RBMid + BBMultiplier * RBsDev;
def BBllo = RBMid - BBMultiplier * RBsDev;

def BBnewuUpper = getStickyRange(high, low, BBuup, BBllo).Upband;
def BBnewlLower = getStickyRange(high, low, BBuup, BBllo).Loband;

def uupper = BBnewuUpper;
def llower = BBnewlLower;
def mmiddle = (BBnewuUpper + BBnewlLower) / 2;

#//Entry Condition Signals
def longCond  = relativeBandwidth < mmiddle and bull > bear and (bull Crosses Above signal);
def shortCond = relativeBandwidth < mmiddle and bear > bull and (bear Crosses Above signal);
def last_signal;
def cond = longCond or shortCond;

AddChartBubble(longCond and !last_signal[1], low, "L", Color.CYAN, no); # 'Long Signal'
AddChartBubble(shortCond and !last_signal[1], high, "S", Color.MAGENTA); # 'Short Signal'

    last_signal = sum(if cond then 1 else 0, 5) >=1;


#-- END of CODE
 
check the below:

CSS:
#// Indicator for TOS
#// This script uses source code of Andean Oscilator by @alexgrover and Relative Bandwith Filter by @HeWhoMustNotBeNamed
#// This is an experimental signal indicator and should be used with caution.
#// © serkany88
#indicator("Relative Andean Scalping", precision=3, overlay=true)
# Converted by Sam4Cok@Samer800    - 11/2024

#//Andean Settings and Calculation by @alexgrover
input AndeanLength   = 100;     # 'Andean Length'
input AndeanSignalLength = 13;  # 'Andean Signal Length'

def na = Double.NaN;
def last = IsNaN(close);

#//Andean Calculation
def alpha = 2 / (AndeanLength + 1);

def up1 = if !up1[1] then close else Max(close, Max(open, up1[1] - (up1[1] - close) * alpha));
def up2 = if !up2[1] then Sqr(close) else Max(Sqr(close), Max(Sqr(open), up2[1] - (up2[1] - Sqr(close)) * alpha));

def dn1 = if !dn1[1] then close else Min(close, Min(open, dn1[1] + (close - dn1[1]) * alpha));
def dn2 = if !dn2[1] then Sqr(close) else Min(Sqr(close), Min(Sqr(open), dn2[1] + (Sqr(close) - dn2[1]) * alpha));

def bull = Sqrt(dn2 - dn1 * dn1);
def bear = Sqrt(up2 - up1 * up1);

def signal = ExpAverage(Max(bull, bear), AndeanSignalLength);

#//Relative Bandwith Filter by @HeWhoMustNotBeNamed

input bandType = {default KC, BB, DC};
input BandSource = close;
input BandMovAvg = {SMA, EMA, HMA, RMA, WMA, VWMA, SWMA, default Linreg, Median};
input BandLength = 34;
input BandMultiplier = 2.0;
input KCTrueRange = yes;      # "Use True Range (KC)"
input DCAlternateSource = no; # "Use Alternate Source (DC)"
input sticky = yes;            # "Sticky"
input atrLength = 34;
input BBMovAvg = {SMA, EMA, HMA, RMA, WMA, VWMA, SWMA, default Linreg, Median};
input bbLength = 100;        # "BB Length"
input BBMultiplier = 1.0;       # "Multiplier"


#swma(source)
script swma {
    input x = close;
    def swma = x[3] * 1 / 6 + x[2] * 2 / 6 + x[1] * 2 / 6 + x[0] * 1 / 6;
    plot return = swma;
}
#vwma(source, length)
script VWMA {
    input x = close;
    input y = 15;
    def VWMA = Average(x * volume, y) / Average(volume, y);
    plot result = VWMA;
}
#ma(type, source, length) =>
script ma {
    input type   = {SMA, EMA, HMA, RMA, WMA, VWMA, SWMA, default Linreg, Median};
    input source = close;
    input length = 100;
    def ma;
    Switch (type) {
    Case SMA : ma = Average(source, length);
    Case EMA : ma = ExpAverage(source, length);
    Case HMA : ma = HullMovingAvg(source, length);
    Case RMA : ma = WildersAverage(source, length);
    Case WMA : ma = WMA(source, length);
    Case VWMA: ma = VWMA(source, length);
    Case SWMA: ma = SWMA(source);
    Case Median: ma = Median(source, length);
    Default  : ma = Inertia(source, length);
    }
    plot result = ma;
}
#getStickyRange(highsource, lowsource, upper, lower, sticky=false)=>
script getStickyRange {
    input highsource = high;
    input lowsource = low;
    input upper = high;
    input lower = low;
    input sticky = no;
    def newUpper;
    def newLower;
    def prevUpper = if newUpper[1] then newUpper[1] else upper;
    def prevLower = if newLower[1] then newLower[1] else lower;
    def highBreakout = highsource[1] >= prevUpper;
    def lowBreakout  = lowsource[1]  <= prevLower;
        newUpper = if (highBreakout or lowBreakout or !sticky) then upper else prevUpper;
        newLower = if (highBreakout or lowBreakout or !sticky) then Lower else prevLower;
    plot UpBand = newUpper;
    plot LoBand = newLower;
}
#### BB
def sDev = StDev(BandSource, BandLength);
def BBMid = ma(BandMovAvg, BandSource, BandLength);
def BBup = BBMid + BandMultiplier * sDev;
def BBlo = BBMid - BandMultiplier * sDev;
def BBupper = getStickyRange(high, low, BBup, BBlo, sticky).Upband;
def BBlower = getStickyRange(high, low, BBup, BBlo, sticky).Loband;
def BBmiddle = (BBupper + BBlower) / 2;

##### KC
def tr = if IsNaN(close[1]) then high - low else TrueRange(high, close, low);
def span = BandMultiplier * ma(BandMovAvg, if KCTrueRange then tr else (high - low), BandLength);
def KCavg = ma(BandMovAvg, BandSource, BandLength);
def KCUp = KCavg + span;
def KClo = KCavg - span;
def KCnewUpper = getStickyRange(high, low, KCUp, KClo, sticky).Upband;
def KCnewLower = getStickyRange(high, low, KCUp, KClo, sticky).Loband;
def KCupper  = KCnewUpper;
def KClower  = KCnewLower;
def KCmiddle = (KCupper + KClower) / 2 ;

##### DC
def highSource = if DCAlternateSource then BandSource else high;
def lowSource  = if DCAlternateSource then BandSource else low;
def DCupp = Highest(highSource, BandLength);
def DClow = Lowest(lowSource, BandLength);
def DCnewUpper = getStickyRange(highSource, lowSource, DCupp, DClow, sticky).UpBand;
def DCnewLower = getStickyRange(highSource, lowSource, DCupp, DClow, sticky).LoBand;
def DCmid = (DCnewUpper + DCnewLower) / 2;
def DCupper  = DCnewUpper;
def DClower  = DCnewLower;
def DCmiddle = DCmid;

### Bands
def upper;
def lower;
def middle;
Switch (bandType) {
Case BB :
    upper  = BBupper;
    lower  = BBlower;
    middle = BBmiddle;
Case DC :
    upper  = DCupper;
    lower  = DClower;
    middle = DCmiddle;
Default :
    upper  = KCupper;
    lower  = KClower;
    middle = KCmiddle;
}

def atrValue = WildersAverage(tr, atrLength);
def relativeBandwidth = (upper - lower) / atrValue;

#### RB BB
def RBsDev = stdev(RelativeBandwidth,BBLength);
def RBMid = ma(BBMovAvg, RelativeBandwidth, BBLength);
def BBuup = RBMid + BBMultiplier * RBsDev;
def BBllo = RBMid - BBMultiplier * RBsDev;

def BBnewuUpper = getStickyRange(high, low, BBuup, BBllo).Upband;
def BBnewlLower = getStickyRange(high, low, BBuup, BBllo).Loband;

def uupper = BBnewuUpper;
def llower = BBnewlLower;
def mmiddle = (BBnewuUpper + BBnewlLower) / 2;

#//Entry Condition Signals
def longCond  = relativeBandwidth < mmiddle and bull > bear and (bull Crosses Above signal);
def shortCond = relativeBandwidth < mmiddle and bear > bull and (bear Crosses Above signal);
def last_signal;
def cond = longCond or shortCond;

AddChartBubble(longCond and !last_signal[1], low, "L", Color.CYAN, no); # 'Long Signal'
AddChartBubble(shortCond and !last_signal[1], high, "S", Color.MAGENTA); # 'Short Signal'

    last_signal = sum(if cond then 1 else 0, 5) >=1;


#-- END of CODE
Thanks so much Samer, your work is greatly appreciated!
 

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
355 Online
Create Post

Similar threads

Similar threads

The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
  • Exclusive indicators
  • Proven strategies & setups
  • Private Discord community
  • ‘Buy The Dip’ signal alerts
  • Exclusive members-only content
  • Add-ons and resources
  • 1 full year of unlimited support

Frequently Asked Questions

What is useThinkScript?

useThinkScript is the #1 community of stock market investors using indicators and other tools to power their trading strategies. Traders of all skill levels use our forums to learn about scripting and indicators, help each other, and discover new ways to gain an edge in the markets.

How do I get started?

We get it. Our forum can be intimidating, if not overwhelming. With thousands of topics, tens of thousands of posts, our community has created an incredibly deep knowledge base for stock traders. No one can ever exhaust every resource provided on our site.

If you are new, or just looking for guidance, here are some helpful links to get you started.

What are the benefits of VIP Membership?
VIP members get exclusive access to these proven and tested premium indicators: Buy the Dip, Advanced Market Moves 2.0, Take Profit, and Volatility Trading Range. In addition, VIP members get access to over 50 VIP-only custom indicators, add-ons, and strategies, private VIP-only forums, private Discord channel to discuss trades and strategies in real-time, customer support, trade alerts, and much more. Learn all about VIP membership here.
How can I access the premium indicators?
To access the premium indicators, which are plug and play ready, sign up for VIP membership here.
Back
Top