Bar Color Long / Short For ThinkOrSwim

@samer800 i just think the main signal, like the cyan and magenta bar color, i did it a market replay with it, very good system.
check the below

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at
#// © CR-JE
#indicator(title='Bar Color Long / Short Indicator With Advised SL Rev 4', shorttitle='SI', overlay=true)
# Converted by Sam4Cok@Samer800    - 09/2023
#// Stop Loss Finder
input length = 90;#(title='Length', defval=90, minval=1)
input smoothing = AverageType.WILDERS;
input Multiplier = 1.5;#, 'Multiplier')
input BarColorsOrangeBlue = no;#(title='Bar Colors Orange-Blue and Signal Arrows ON/OFF', defval=false)
input BarColorsLongShort = yes;#(title='Bar Colors Long-Short ON?OFF', defval=true)
input BarColorsRedYellowGreen = no;#(title='Bar Colors Red Yellow Green ON/OFF', defval=false)
input ShowArrows = yes;#(title='Arrow Colors Black/White', defval=true)
input VerticalLines = no;#(title='Bg Colors ON/OFF', defval=false)
input showStopLossLines = no;#(title='Advised SL ON/OFF', defval=false)

def na = Double.NaN;
def h = high;
def l = low;
def show_bar_colors = BarColorsOrangeBlue;
def show_bar_colorsLSonly = BarColorsLongShort;
def show_bar_colorsLS = BarColorsRedYellowGreen;
def Arrow_colors = ShowArrows;
def BG_colors = VerticalLines;
def Advised_SL = showStopLossLines;
defineGlobalColor("blue", CreateColor(33,150,243));
defineGlobalColor("orange", CreateColor(255,152,0));
script max_custom {
input x = close;
input y = close;
    def max_custom = if x > y then x else y;
    plot out = max_custom;
}
def tr = TrueRange(high, close, low);
def a = MovingAverage(smoothing, tr, length) * Multiplier;
def x  = a + h;
def x2 = l - a;

#/ Custom risk calculation (resembling RSI)
def customRiskPeriod = 14;
def priceDelta = close - close[1];
def avgGain = Average(max_custom(priceDelta, 0), customRiskPeriod);
def avgLoss = Average(max_custom(-priceDelta, 0), customRiskPeriod);
def customRS = avgGain / avgLoss;
def customRisk = 100 - (100 / (1 + customRS));

#// Define risk levels
def lowRisk = 30;
def mediumRisk = 50;
def highRisk = 70;

#// Custom sentiment calculation (resembling EMA, MACD, and ROC)
def src = close;
def shortPeriod = 9;
def longPeriod = 21;

def customShort = reference VWAP();
def customLong = WMA(src, longPeriod);
def customSignal = if customShort > customLong then 1 else -1;

def priceDelta2 = (src - src[1]) / src[1] * 100;
def customROC = Average(priceDelta2, shortPeriod);
def rocSignal = if customROC > 0 then 1 else -1;

def sentimentScore = (customSignal + rocSignal) / 2;
def sentimentPositive = sentimentScore > 0;

#// Bollinger Bands Percent calculation
def length1 = 20;
def mult = 2;
def basis = Average(close, length1);
def dev = mult * StDev(close, length1);
def upper = basis + dev;
def lower = basis - dev;
def bbPercent = (close - lower) / (upper - lower);

#// Combine custom risk, sentiment score, and BB Percent for the new signal
def combinedSignal = customRisk + sentimentScore * 10 + bbPercent * 10;

#// EMA10 calculation
def ema10 = ExpAverage(close, 10);
def ema20 = ExpAverage(close, 20);
def sma50 = ExpAverage(close, 50);

#// Long and Short
def long = sentimentPositive and (open > ema10 or close > ema10) and (ema10 > ema20) and (sma50 >= sma50[1]);
def short = !sentimentPositive and (open < ema10 or close < ema10) and (ema10 < ema20) and (sma50 <= sma50[1]);

#// Close Open Confirmation
def confirmOpenL = close >= open;
def confirmOpenS = close <= open;

#/ Signal once Long & Short
def isLong;# = false
def isShort;# = false

#//Long
def buy = !isLong[1] and long and confirmOpenL;

#//Short
def sell = !isShort[1] and short and confirmOpenS;

if (long) {
    isLong = yes;
    isShort = no;
} else
if (short) {
    isLong = no;
    isShort = yes;
} else {
    isLong = isLong[1];
    isShort = isShort[1];
}

AddVerticalLine(buy and BG_colors, "Buy", Color.CYAN);
AddVerticalLine(sell and BG_colors, "Sell", Color.MAGENTA);

AssignPriceColor(if show_bar_colors then
                 if long then GlobalColor("orange") else
                 if short then GlobalColor("blue") else Color.GRAY else
                 if show_bar_colorsLS then
                 if long then Color.GREEN else
                 if short then Color.RED else Color.YELLOW else
                 if show_bar_colorsLSonly then
                 if buy then Color.CYAN else
                 if sell then Color.MAGENTA else Color.CURRENT else Color.CURRENT);

#// Added large arrow up and down for buy and sell signals
plot buyArr = if buy and Arrow_colors then low else na;#, style=shape.arrowup, location=location.belowbar, color=ShapeColor, size=size.large)
plot SellArr = if sell and Arrow_colors then high else na;#, style=shape.arrowdown, location=location.abovebar, color=ShapeColor, size=size.large)
buyArr.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
sellArr.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
buyArr.SetDefaultColor(Color.WHITE);
sellArr.SetDefaultColor(Color.ORANGE);

def bar = BarNumber();
def profit = if Advised_SL and close[1] then if buy then x else profit[1] else na;
def loss = if Advised_SL and close[1] then if sell then x2 else loss[1] else na;
def barstart = if buy then bar else barstart[1];
def barCond = bar > highestAll(barstart)-1;

plot profitLine = if barCond then profit else na;
plot lossLine = if barCond then loss else na;
profitLine.SetDefaultColor(Color.GREEN);
lossLine.SetDefaultColor(Color.RED);
profitLine.SetStyle(Curve.MEDIUM_DASH);
lossLine.SetStyle(Curve.MEDIUM_DASH);

#-- END of CODE
 
check the below

CSS:
#// This source code is subject to the terms of the Mozilla Public License 2.0 at
#// © CR-JE
#indicator(title='Bar Color Long / Short Indicator With Advised SL Rev 4', shorttitle='SI', overlay=true)
# Converted by Sam4Cok@Samer800    - 09/2023
#// Stop Loss Finder
input length = 90;#(title='Length', defval=90, minval=1)
input smoothing = AverageType.WILDERS;
input Multiplier = 1.5;#, 'Multiplier')
input BarColorsOrangeBlue = no;#(title='Bar Colors Orange-Blue and Signal Arrows ON/OFF', defval=false)
input BarColorsLongShort = yes;#(title='Bar Colors Long-Short ON?OFF', defval=true)
input BarColorsRedYellowGreen = no;#(title='Bar Colors Red Yellow Green ON/OFF', defval=false)
input ShowArrows = yes;#(title='Arrow Colors Black/White', defval=true)
input VerticalLines = no;#(title='Bg Colors ON/OFF', defval=false)
input showStopLossLines = no;#(title='Advised SL ON/OFF', defval=false)

def na = Double.NaN;
def h = high;
def l = low;
def show_bar_colors = BarColorsOrangeBlue;
def show_bar_colorsLSonly = BarColorsLongShort;
def show_bar_colorsLS = BarColorsRedYellowGreen;
def Arrow_colors = ShowArrows;
def BG_colors = VerticalLines;
def Advised_SL = showStopLossLines;
defineGlobalColor("blue", CreateColor(33,150,243));
defineGlobalColor("orange", CreateColor(255,152,0));
script max_custom {
input x = close;
input y = close;
    def max_custom = if x > y then x else y;
    plot out = max_custom;
}
def tr = TrueRange(high, close, low);
def a = MovingAverage(smoothing, tr, length) * Multiplier;
def x  = a + h;
def x2 = l - a;

#/ Custom risk calculation (resembling RSI)
def customRiskPeriod = 14;
def priceDelta = close - close[1];
def avgGain = Average(max_custom(priceDelta, 0), customRiskPeriod);
def avgLoss = Average(max_custom(-priceDelta, 0), customRiskPeriod);
def customRS = avgGain / avgLoss;
def customRisk = 100 - (100 / (1 + customRS));

#// Define risk levels
def lowRisk = 30;
def mediumRisk = 50;
def highRisk = 70;

#// Custom sentiment calculation (resembling EMA, MACD, and ROC)
def src = close;
def shortPeriod = 9;
def longPeriod = 21;

def customShort = reference VWAP();
def customLong = WMA(src, longPeriod);
def customSignal = if customShort > customLong then 1 else -1;

def priceDelta2 = (src - src[1]) / src[1] * 100;
def customROC = Average(priceDelta2, shortPeriod);
def rocSignal = if customROC > 0 then 1 else -1;

def sentimentScore = (customSignal + rocSignal) / 2;
def sentimentPositive = sentimentScore > 0;

#// Bollinger Bands Percent calculation
def length1 = 20;
def mult = 2;
def basis = Average(close, length1);
def dev = mult * StDev(close, length1);
def upper = basis + dev;
def lower = basis - dev;
def bbPercent = (close - lower) / (upper - lower);

#// Combine custom risk, sentiment score, and BB Percent for the new signal
def combinedSignal = customRisk + sentimentScore * 10 + bbPercent * 10;

#// EMA10 calculation
def ema10 = ExpAverage(close, 10);
def ema20 = ExpAverage(close, 20);
def sma50 = ExpAverage(close, 50);

#// Long and Short
def long = sentimentPositive and (open > ema10 or close > ema10) and (ema10 > ema20) and (sma50 >= sma50[1]);
def short = !sentimentPositive and (open < ema10 or close < ema10) and (ema10 < ema20) and (sma50 <= sma50[1]);

#// Close Open Confirmation
def confirmOpenL = close >= open;
def confirmOpenS = close <= open;

#/ Signal once Long & Short
def isLong;# = false
def isShort;# = false

#//Long
def buy = !isLong[1] and long and confirmOpenL;

#//Short
def sell = !isShort[1] and short and confirmOpenS;

if (long) {
    isLong = yes;
    isShort = no;
} else
if (short) {
    isLong = no;
    isShort = yes;
} else {
    isLong = isLong[1];
    isShort = isShort[1];
}

AddVerticalLine(buy and BG_colors, "Buy", Color.CYAN);
AddVerticalLine(sell and BG_colors, "Sell", Color.MAGENTA);

AssignPriceColor(if show_bar_colors then
                 if long then GlobalColor("orange") else
                 if short then GlobalColor("blue") else Color.GRAY else
                 if show_bar_colorsLS then
                 if long then Color.GREEN else
                 if short then Color.RED else Color.YELLOW else
                 if show_bar_colorsLSonly then
                 if buy then Color.CYAN else
                 if sell then Color.MAGENTA else Color.CURRENT else Color.CURRENT);

#// Added large arrow up and down for buy and sell signals
plot buyArr = if buy and Arrow_colors then low else na;#, style=shape.arrowup, location=location.belowbar, color=ShapeColor, size=size.large)
plot SellArr = if sell and Arrow_colors then high else na;#, style=shape.arrowdown, location=location.abovebar, color=ShapeColor, size=size.large)
buyArr.SetPaintingStrategy(PaintingStrategy.ARROW_UP);
sellArr.SetPaintingStrategy(PaintingStrategy.ARROW_DOWN);
buyArr.SetDefaultColor(Color.WHITE);
sellArr.SetDefaultColor(Color.ORANGE);

def bar = BarNumber();
def profit = if Advised_SL and close[1] then if buy then x else profit[1] else na;
def loss = if Advised_SL and close[1] then if sell then x2 else loss[1] else na;
def barstart = if buy then bar else barstart[1];
def barCond = bar > highestAll(barstart)-1;

plot profitLine = if barCond then profit else na;
plot lossLine = if barCond then loss else na;
profitLine.SetDefaultColor(Color.GREEN);
lossLine.SetDefaultColor(Color.RED);
profitLine.SetStyle(Curve.MEDIUM_DASH);
lossLine.SetStyle(Curve.MEDIUM_DASH);

#-- END of CODE
@samer800 thank you some much!! you are amazing!!
 
@samer800 Can you add an input so we could pick different moving, including Ema, Hull etc.. Seems like a lot of code. Could you remove these two inputs Vertival break line and Vertical line period? Really think this is just great, with only the bars turning green or red above or below the Moving average. The other Inputs are overkill. Thanks. as well.


# SwingTrading_R1V3
# R1V1 2011.06.11.23:00 KumoBob
# A very simple method of SwingTrading with Moving average
# R1V2 2011.06.13.09:00 KumoBob
# Added more periods to AverageMode
# R1V3 2011.06.13.15:00 KumoBob
# Added hints and other bells an whistles

declare upper;
#Hint: Three methods are available and provide a very simple method of SwingTrading with Moving Averages. \nThis orignated when I wanted to see what would happen if two moving averages were used on a daily basis with the buy and sell signal always being the highest and lowest of the two averages.\nIt seems to be a fairly good method, but other indicators such as PPS will most likely out perform this method.
#Hint FastMovingAverage: Length of FAST average\nDefault = 5
#Hint SlowMovingAverage: Length of SLOW average\nDefault = 13
#Hint Method: Choose to signal when Price crosses the Fast MA\nor\nChoose to signal when the Fast MA crosses the Slow MA\nor\n "Buy at the Lowest MA and Sell at the Highest MA when Price crosses these curves
#Hint AverageMode: Choose to average by bar or a selectable time period\nThe choices are DAY, 2 DAYS, 3 DAYS, 4 DAYS, WEEK, and MONTH \nDefault = Day
#Hint BubblesOn: Bubbles identify the curve's average length\nDefault = Yes
#Hint ShowPoints: Shows the exact point the signal occured\nDefault = Yes
#Hint ShowArrows: Shows the signal with an arrow\nDefault = Yes
#Hint ShowPlot: Choose to show the curves or hide them
#Hint VerticalDayBreakLinesOn: Choose to place Vertical Lines at Day, Week or Month intervals\nDefault = No
#Hint VerticalLinePeriod: Specifies the interval to plot vertical lines\nDefault = Day
#Hint PriceColorOn: Allows the signal to be seen as Red and Green price bars\nDefault = No
input FastMovingAverage = 5;
input SlowMovingAverage = 13;
Input Method = {"At Fast MA", "MA Cross",Default "Buy at Min MA Sell at Max MA"};
input AverageMode = {"Bar",default DAY, "2 DAYS", "3 DAYS", "4 DAYS", WEEK, MONTH};

input BubblesOn = Yes;
input ShowPlot = Yes;
input ShowPoints = Yes;
input ShowArrows = Yes;
Input PriceColorOn = No;

def Mode;
switch (Method){
case "At Fast MA":
Mode = 1;
case "MA Cross":
Mode = 2;
case "Buy at Min MA Sell at Max MA":
Mode = 3;
}

Input VerticalDayBreakLinesOn = No;
input VerticalLinePeriod = {default DAY, WEEK, MONTH};



def PeriodChoice;
switch (AverageMode){
case "Day":
PeriodChoice = 1;
case "2 DAYS":
PeriodChoice = 2;
case "3 DAYS":
PeriodChoice = 3;
case "4 DAYS":
PeriodChoice = 4;
case WEEK:
PeriodChoice = 7;
case MONTH:
PeriodChoice = 30;
case "Bar":
PeriodChoice = 0;
}


def BarMA1 = Average(close () , FastMovingAverage );
Def Day1MA1 = Average(close (period = "DAY" ), FastMovingAverage );
Def Day2MA1 = Average(close (period = "2 DAYS"), FastMovingAverage );
Def Day3MA1 = Average(close (period = "3 DAYS"), FastMovingAverage );
Def Day4MA1 = Average(close (period = "4 DAYS"), FastMovingAverage );
Def Day7MA1 = Average(close (period = "WEEK" ), FastMovingAverage);
Def Day30MA1 = Average(close (period = "MONTH") , FastMovingAverage);

def BarMA2 = Average(close () , SlowMovingAverage);
Def Day1MA2 = Average(close (period = "DAY" ), SlowMovingAverage);
Def Day2MA2 = Average(close (period = "2 DAYS"), SlowMovingAverage);
Def Day3MA2 = Average(close (period = "3 DAYS"), SlowMovingAverage);
Def Day4MA2 = Average(close (period = "4 DAYS"), SlowMovingAverage);
Def Day7MA2 = Average(close (period = "WEEK" ), SlowMovingAverage);
Def Day30MA2 = Average(close (period = "MONTH") , SlowMovingAverage);


def FMA =
If PeriodChoice == 1 then Day1MA1 else
If PeriodChoice == 2 then Day2MA1 else
If PeriodChoice == 3 then Day3MA1 else
If PeriodChoice == 4 then Day4MA1 else
If PeriodChoice == 7 then Day7MA1 else
If PeriodChoice == 30 then Day30MA1 else BarMA1;
plot FastMA = if !ShowPlot then Double.NaN else FMA;

FastMA.AssignValueColor(if Close > FMA then Color.Green else if Close < FMA then Color.Red else Color.Yellow); AddChartBubble(FastMA && BubblesOn && !IsNaN(close) and IsNaN(close[-1]), FastMA, concat("", FastMovingAverage ), if Close > FMA then Color.Green else if Close < FMA then Color.Red else Color.Yellow); def SMA = If PeriodChoice == 1 then Day1MA2 else If PeriodChoice == 2 then Day2MA2 else If PeriodChoice == 3 then Day3MA2 else If PeriodChoice == 4 then Day4MA2 else If PeriodChoice == 7 then Day7MA2 else If PeriodChoice == 30 then Day30MA2 else BarMA2; plot SlowMA = if !ShowPlot then Double.NaN else SMA; SlowMA.AssignValueColor(if Close > SMA then Color.Green else if Close < SMA then Color.Red else Color.Yellow); AddChartBubble(SlowMA && BubblesOn && !IsNaN(close) and IsNaN(close[-1]), SlowMA, concat("", SlowMovingAverage), if Close > SMA then Color.Green else if Close < SMA then Color.Red else Color.Yellow); ####################

def Max = Max(FMA, SMA); def Min = Min(FMA, SMA); def Position = if Close > Max(FMA, SMA) then 2 else if Close < Min(FMA, SMA) then -2 else 0; rec Trend = If Mode == 3 then if Position[1] == 2 && Position[0] <= 0 then -2 else if Position[1] == -2 && Position[0] >= 0 then 2 else
if Position[1] == 0 && Position[0] == 2 then 2 else
if Position[1] == 0 && Position[0] == -2 then -2 else Trend[1]
else If Mode == 1 then if Close > FMA then 2 else -2
else if FMA > SMA then 2 else -2;

AssignPriceColor(if !PriceColorOn then Color.Current else If Trend > 0 then Color.Green else Color.Red);


rec Point = If Mode == 3 then
if Position[1] == 2 && Position[0] <= 0 then Max else if Position[1] == -2 && Position[0] >= 0 then Min else
if Position[1] == 0 && Position[0] == 2 then Max else
if Position[1] == 0 && Position[0] == -2 then Min else Point[1]
else If Mode == 1 then if Close > FMA then Close else Point[1]
else if FMA > SMA then Close else Point[1];

plot SignalPoint = If !ShowPoints then Double.NaN else Point;
SignalPoint.SetLineWeight(1);
SignalPoint.SetPaintingStrategy(PaintingStrategy.Points);
SignalPoint.AssignValueColor(If Trend > 0 then Color.Green else Color.Red);
# ARROWS ROUTINE
# ___________________________________________
def x_over = Crosses(Trend, 0);
plot up = if ShowArrows && x_over && Trend > 0 then Low else Double.NaN;
up.SetPaintingStrategy(PaintingStrategy.Arrow_up);
up.SetDefaultColor(Color.white);
plot dn = if ShowArrows && x_over && Trend < 0 then High else Double.NaN; dn.SetPaintingStrategy(PaintingStrategy.Arrow_down); dn.SetDefaultColor(Color.white); # Vertical Time Lines # ___________________________________________

def vert = VerticalLinePeriod == VerticalLinePeriod.Day and getDay() <> getDay()[1] or
VerticalLinePeriod == VerticalLinePeriod.WEEK and getWeek() <> getWeek()[1] or VerticalLinePeriod == VerticalLinePeriod.MONTH and getMonth() <> getMonth()[1];
AddVerticalLine(VerticalDayBreakLinesOn && Vert,
"",
if VerticalLinePeriod == VerticalLinePeriod.day then color.cyan else if VerticalLinePeriod == VerticalLinePeriod.week then Color.Magenta else color.Yellow);
 
@samer800 Can you add an input so we could pick different moving, including Ema, Hull etc.. Seems like a lot of code. Could you remove these two inputs Vertival break line and Vertical line period? Really think this is just great, with only the bars turning green or red above or below the Moving average. The other Inputs are overkill. Thanks. as well.


# SwingTrading_R1V3
# R1V1 2011.06.11.23:00 KumoBob
# A very simple method of SwingTrading with Moving average
# R1V2 2011.06.13.09:00 KumoBob
# Added more periods to AverageMode
# R1V3 2011.06.13.15:00 KumoBob
# Added hints and other bells an whistles

declare upper;
#Hint: Three methods are available and provide a very simple method of SwingTrading with Moving Averages. \nThis orignated when I wanted to see what would happen if two moving averages were used on a daily basis with the buy and sell signal always being the highest and lowest of the two averages.\nIt seems to be a fairly good method, but other indicators such as PPS will most likely out perform this method.
#Hint FastMovingAverage: Length of FAST average\nDefault = 5
#Hint SlowMovingAverage: Length of SLOW average\nDefault = 13
#Hint Method: Choose to signal when Price crosses the Fast MA\nor\nChoose to signal when the Fast MA crosses the Slow MA\nor\n "Buy at the Lowest MA and Sell at the Highest MA when Price crosses these curves
#Hint AverageMode: Choose to average by bar or a selectable time period\nThe choices are DAY, 2 DAYS, 3 DAYS, 4 DAYS, WEEK, and MONTH \nDefault = Day
#Hint BubblesOn: Bubbles identify the curve's average length\nDefault = Yes
#Hint ShowPoints: Shows the exact point the signal occured\nDefault = Yes
#Hint ShowArrows: Shows the signal with an arrow\nDefault = Yes
#Hint ShowPlot: Choose to show the curves or hide them
#Hint VerticalDayBreakLinesOn: Choose to place Vertical Lines at Day, Week or Month intervals\nDefault = No
#Hint VerticalLinePeriod: Specifies the interval to plot vertical lines\nDefault = Day
#Hint PriceColorOn: Allows the signal to be seen as Red and Green price bars\nDefault = No
input FastMovingAverage = 5;
input SlowMovingAverage = 13;
Input Method = {"At Fast MA", "MA Cross",Default "Buy at Min MA Sell at Max MA"};
input AverageMode = {"Bar",default DAY, "2 DAYS", "3 DAYS", "4 DAYS", WEEK, MONTH};

input BubblesOn = Yes;
input ShowPlot = Yes;
input ShowPoints = Yes;
input ShowArrows = Yes;
Input PriceColorOn = No;

def Mode;
switch (Method){
case "At Fast MA":
Mode = 1;
case "MA Cross":
Mode = 2;
case "Buy at Min MA Sell at Max MA":
Mode = 3;
}

Input VerticalDayBreakLinesOn = No;
input VerticalLinePeriod = {default DAY, WEEK, MONTH};



def PeriodChoice;
switch (AverageMode){
case "Day":
PeriodChoice = 1;
case "2 DAYS":
PeriodChoice = 2;
case "3 DAYS":
PeriodChoice = 3;
case "4 DAYS":
PeriodChoice = 4;
case WEEK:
PeriodChoice = 7;
case MONTH:
PeriodChoice = 30;
case "Bar":
PeriodChoice = 0;
}


def BarMA1 = Average(close () , FastMovingAverage );
Def Day1MA1 = Average(close (period = "DAY" ), FastMovingAverage );
Def Day2MA1 = Average(close (period = "2 DAYS"), FastMovingAverage );
Def Day3MA1 = Average(close (period = "3 DAYS"), FastMovingAverage );
Def Day4MA1 = Average(close (period = "4 DAYS"), FastMovingAverage );
Def Day7MA1 = Average(close (period = "WEEK" ), FastMovingAverage);
Def Day30MA1 = Average(close (period = "MONTH") , FastMovingAverage);

def BarMA2 = Average(close () , SlowMovingAverage);
Def Day1MA2 = Average(close (period = "DAY" ), SlowMovingAverage);
Def Day2MA2 = Average(close (period = "2 DAYS"), SlowMovingAverage);
Def Day3MA2 = Average(close (period = "3 DAYS"), SlowMovingAverage);
Def Day4MA2 = Average(close (period = "4 DAYS"), SlowMovingAverage);
Def Day7MA2 = Average(close (period = "WEEK" ), SlowMovingAverage);
Def Day30MA2 = Average(close (period = "MONTH") , SlowMovingAverage);


def FMA =
If PeriodChoice == 1 then Day1MA1 else
If PeriodChoice == 2 then Day2MA1 else
If PeriodChoice == 3 then Day3MA1 else
If PeriodChoice == 4 then Day4MA1 else
If PeriodChoice == 7 then Day7MA1 else
If PeriodChoice == 30 then Day30MA1 else BarMA1;
plot FastMA = if !ShowPlot then Double.NaN else FMA;

FastMA.AssignValueColor(if Close > FMA then Color.Green else if Close < FMA then Color.Red else Color.Yellow); AddChartBubble(FastMA && BubblesOn && !IsNaN(close) and IsNaN(close[-1]), FastMA, concat("", FastMovingAverage ), if Close > FMA then Color.Green else if Close < FMA then Color.Red else Color.Yellow); def SMA = If PeriodChoice == 1 then Day1MA2 else If PeriodChoice == 2 then Day2MA2 else If PeriodChoice == 3 then Day3MA2 else If PeriodChoice == 4 then Day4MA2 else If PeriodChoice == 7 then Day7MA2 else If PeriodChoice == 30 then Day30MA2 else BarMA2; plot SlowMA = if !ShowPlot then Double.NaN else SMA; SlowMA.AssignValueColor(if Close > SMA then Color.Green else if Close < SMA then Color.Red else Color.Yellow); AddChartBubble(SlowMA && BubblesOn && !IsNaN(close) and IsNaN(close[-1]), SlowMA, concat("", SlowMovingAverage), if Close > SMA then Color.Green else if Close < SMA then Color.Red else Color.Yellow); ####################

def Max = Max(FMA, SMA); def Min = Min(FMA, SMA); def Position = if Close > Max(FMA, SMA) then 2 else if Close < Min(FMA, SMA) then -2 else 0; rec Trend = If Mode == 3 then if Position[1] == 2 && Position[0] <= 0 then -2 else if Position[1] == -2 && Position[0] >= 0 then 2 else
if Position[1] == 0 && Position[0] == 2 then 2 else
if Position[1] == 0 && Position[0] == -2 then -2 else Trend[1]
else If Mode == 1 then if Close > FMA then 2 else -2
else if FMA > SMA then 2 else -2;

AssignPriceColor(if !PriceColorOn then Color.Current else If Trend > 0 then Color.Green else Color.Red);


rec Point = If Mode == 3 then
if Position[1] == 2 && Position[0] <= 0 then Max else if Position[1] == -2 && Position[0] >= 0 then Min else
if Position[1] == 0 && Position[0] == 2 then Max else
if Position[1] == 0 && Position[0] == -2 then Min else Point[1]
else If Mode == 1 then if Close > FMA then Close else Point[1]
else if FMA > SMA then Close else Point[1];

plot SignalPoint = If !ShowPoints then Double.NaN else Point;
SignalPoint.SetLineWeight(1);
SignalPoint.SetPaintingStrategy(PaintingStrategy.Points);
SignalPoint.AssignValueColor(If Trend > 0 then Color.Green else Color.Red);
# ARROWS ROUTINE
# ___________________________________________
def x_over = Crosses(Trend, 0);
plot up = if ShowArrows && x_over && Trend > 0 then Low else Double.NaN;
up.SetPaintingStrategy(PaintingStrategy.Arrow_up);
up.SetDefaultColor(Color.white);
plot dn = if ShowArrows && x_over && Trend < 0 then High else Double.NaN; dn.SetPaintingStrategy(PaintingStrategy.Arrow_down); dn.SetDefaultColor(Color.white); # Vertical Time Lines # ___________________________________________

def vert = VerticalLinePeriod == VerticalLinePeriod.Day and getDay() <> getDay()[1] or
VerticalLinePeriod == VerticalLinePeriod.WEEK and getWeek() <> getWeek()[1] or VerticalLinePeriod == VerticalLinePeriod.MONTH and getMonth() <> getMonth()[1];
AddVerticalLine(VerticalDayBreakLinesOn && Vert,
"",
if VerticalLinePeriod == VerticalLinePeriod.day then color.cyan else if VerticalLinePeriod == VerticalLinePeriod.week then Color.Magenta else color.Yellow);
I added mov avg option . Vertical line just set it as no from the setting.

CSS:
# SwingTrading_R1V3
# R1V1 2011.06.11.23:00 KumoBob
# A very simple method of SwingTrading with Moving average
# R1V2 2011.06.13.09:00 KumoBob
# Added more periods to AverageMode
# R1V3 2011.06.13.15:00 KumoBob
# Added hints and other bells an whistles

declare upper;
#Hint: Three methods are available and provide a very simple method of SwingTrading with Moving Averages. \nThis orignated when I wanted to see what would happen if two moving averages were used on a daily basis with the buy and sell signal always being the highest and lowest of the two averages.\nIt seems to be a fairly good method, but other indicators such as PPS will most likely out perform this method.
#Hint FastMovingAverage: Length of FAST average\nDefault = 5
#Hint SlowMovingAverage: Length of SLOW average\nDefault = 13
#Hint Method: Choose to signal when Price crosses the Fast MA\nor\nChoose to signal when the Fast MA crosses the Slow MA\nor\n "Buy at the Lowest MA and Sell at the Highest MA when Price crosses these curves
#Hint AverageMode: Choose to average by bar or a selectable time period\nThe choices are DAY, 2 DAYS, 3 DAYS, 4 DAYS, WEEK, and MONTH \nDefault = Day
#Hint BubblesOn: Bubbles identify the curve's average length\nDefault = Yes
#Hint ShowPoints: Shows the exact point the signal occured\nDefault = Yes
#Hint ShowArrows: Shows the signal with an arrow\nDefault = Yes
#Hint ShowPlot: Choose to show the curves or hide them
#Hint VerticalDayBreakLinesOn: Choose to place Vertical Lines at Day, Week or Month intervals\nDefault = No
#Hint VerticalLinePeriod: Specifies the interval to plot vertical lines\nDefault = Day
#Hint PriceColorOn: Allows the signal to be seen as Red and Green price bars\nDefault = No
input MovAvgType = AverageType.SIMPLE;
input FastMovingAverage = 5;
input SlowMovingAverage = 13;
Input Method = {"At Fast MA", "MA Cross",Default "Buy at Min MA Sell at Max MA"};
input AverageMode = {"Bar",default DAY, "2 DAYS", "3 DAYS", "4 DAYS", WEEK, MONTH};

input BubblesOn = Yes;
input ShowPlot = Yes;
input ShowPoints = Yes;
input ShowArrows = no;
Input PriceColorOn = No;

def Mode;
switch (Method){
case "At Fast MA":
Mode = 1;
case "MA Cross":
Mode = 2;
case "Buy at Min MA Sell at Max MA":
Mode = 3;
}

Input VerticalDayBreakLinesOn = No;
input VerticalLinePeriod = {default DAY, WEEK, MONTH};



def PeriodChoice;
switch (AverageMode){
case "Day":
PeriodChoice = 1;
case "2 DAYS":
PeriodChoice = 2;
case "3 DAYS":
PeriodChoice = 3;
case "4 DAYS":
PeriodChoice = 4;
case WEEK:
PeriodChoice = 7;
case MONTH:
PeriodChoice = 30;
case "Bar":
PeriodChoice = 0;
}


def BarMA1 = MovingAverage(MovAvgType, close () , FastMovingAverage );
Def Day1MA1 = MovingAverage(MovAvgType,close (period = "DAY" ), FastMovingAverage );
Def Day2MA1 = MovingAverage(MovAvgType,close (period = "2 DAYS"), FastMovingAverage );
Def Day3MA1 = MovingAverage(MovAvgType,close (period = "3 DAYS"), FastMovingAverage );
Def Day4MA1 = MovingAverage(MovAvgType,close (period = "4 DAYS"), FastMovingAverage );
Def Day7MA1 = MovingAverage(MovAvgType,close (period = "WEEK" ), FastMovingAverage);
Def Day30MA1 = MovingAverage(MovAvgType,close (period = "MONTH") , FastMovingAverage);

def BarMA2 = MovingAverage(MovAvgType,close () , SlowMovingAverage);
Def Day1MA2 = MovingAverage(MovAvgType,close (period = "DAY" ), SlowMovingAverage);
Def Day2MA2 = MovingAverage(MovAvgType,close (period = "2 DAYS"), SlowMovingAverage);
Def Day3MA2 = MovingAverage(MovAvgType,close (period = "3 DAYS"), SlowMovingAverage);
Def Day4MA2 = MovingAverage(MovAvgType,close (period = "4 DAYS"), SlowMovingAverage);
Def Day7MA2 = MovingAverage(MovAvgType,close (period = "WEEK" ), SlowMovingAverage);
Def Day30MA2 = MovingAverage(MovAvgType,close (period = "MONTH") , SlowMovingAverage);


def FMA =
If PeriodChoice == 1 then Day1MA1 else
If PeriodChoice == 2 then Day2MA1 else
If PeriodChoice == 3 then Day3MA1 else
If PeriodChoice == 4 then Day4MA1 else
If PeriodChoice == 7 then Day7MA1 else
If PeriodChoice == 30 then Day30MA1 else BarMA1;
plot FastMA = if !ShowPlot then Double.NaN else FMA;

FastMA.AssignValueColor(if Close > FMA then Color.Green else if Close < FMA then Color.Red else Color.Yellow); AddChartBubble(FastMA && BubblesOn && !IsNaN(close) and IsNaN(close[-1]), FastMA, concat("", FastMovingAverage ), if Close > FMA then Color.Green else if Close < FMA then Color.Red else Color.Yellow); def SMA = If PeriodChoice == 1 then Day1MA2 else If PeriodChoice == 2 then Day2MA2 else If PeriodChoice == 3 then Day3MA2 else If PeriodChoice == 4 then Day4MA2 else If PeriodChoice == 7 then Day7MA2 else If PeriodChoice == 30 then Day30MA2 else BarMA2; plot SlowMA = if !ShowPlot then Double.NaN else SMA; SlowMA.AssignValueColor(if Close > SMA then Color.Green else if Close < SMA then Color.Red else Color.Yellow); AddChartBubble(SlowMA && BubblesOn && !IsNaN(close) and IsNaN(close[-1]), SlowMA, concat("", SlowMovingAverage), if Close > SMA then Color.Green else if Close < SMA then Color.Red else Color.Yellow); ####################

def Max = Max(FMA, SMA); def Min = Min(FMA, SMA); def Position = if Close > Max(FMA, SMA) then 2 else if Close < Min(FMA, SMA) then -2 else 0; rec Trend = If Mode == 3 then if Position[1] == 2 && Position[0] <= 0 then -2 else if Position[1] == -2 && Position[0] >= 0 then 2 else
if Position[1] == 0 && Position[0] == 2 then 2 else
if Position[1] == 0 && Position[0] == -2 then -2 else Trend[1]
else If Mode == 1 then if Close > FMA then 2 else -2
else if FMA > SMA then 2 else -2;

AssignPriceColor(if !PriceColorOn then Color.Current else If Trend > 0 then Color.Green else Color.Red);


rec Point = If Mode == 3 then
if Position[1] == 2 && Position[0] <= 0 then Max else if Position[1] == -2 && Position[0] >= 0 then Min else
if Position[1] == 0 && Position[0] == 2 then Max else
if Position[1] == 0 && Position[0] == -2 then Min else Point[1]
else If Mode == 1 then if Close > FMA then Close else Point[1]
else if FMA > SMA then Close else Point[1];

plot SignalPoint = If !ShowPoints then Double.NaN else Point;
SignalPoint.SetLineWeight(1);
SignalPoint.SetPaintingStrategy(PaintingStrategy.Points);
SignalPoint.AssignValueColor(If Trend > 0 then Color.Green else Color.Red);
# ARROWS ROUTINE
# ___________________________________________
def x_over = Crosses(Trend, 0);
plot up = if ShowArrows && x_over && Trend > 0 then Low else Double.NaN;
up.SetPaintingStrategy(PaintingStrategy.Arrow_up);
up.SetDefaultColor(Color.white);
plot dn = if ShowArrows && x_over && Trend < 0 then High else Double.NaN; dn.SetPaintingStrategy(PaintingStrategy.Arrow_down); dn.SetDefaultColor(Color.white); # Vertical Time Lines # ___________________________________________

def vert = VerticalLinePeriod == VerticalLinePeriod.Day and getDay() <> getDay()[1] or
VerticalLinePeriod == VerticalLinePeriod.WEEK and getWeek() <> getWeek()[1] or VerticalLinePeriod == VerticalLinePeriod.MONTH and getMonth() <> getMonth()[1];
AddVerticalLine(VerticalDayBreakLinesOn && Vert,
"",
if VerticalLinePeriod == VerticalLinePeriod.day then color.cyan else if VerticalLinePeriod == VerticalLinePeriod.week then Color.Magenta else color.Yellow);
 

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

Similar threads

Not the exact question you're looking for?

Start a new thread and receive assistance from our community.

87k+ Posts
402 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