TrailingStop and VWAPStop Color Change

germanburrito

Active member
So I'm testing this idea, I combined the trailstop indicator as well as a vwap indicator, but I would like to see how to change the line color when the line reverses below or above close, sort of like the trailstop indicator functions.

nuJeTIz.png

Code:
# VWAPALOOZA
# By Prospectus @ http://readtheprospectus.worspress.com
#
# This Thinkscript calculates four different types of VWAP:
# OneDay (standard type), Rolling (N bar lookback), Bar
# Incremental (discrete N bar periods) and Volume Incremental
# (discrete N-shares-traded periods).
#H Kaczmarczyk added Deviation Lines & Clouds
declare upper;
#
# Check if we are on the current day:
#
def istoday = if getDay() == getLastDay() then 1 else 0;
#
# Input Rolling / Incremental period, VWAP type, and
# Averaging method ( (H+L)/2 or Close):
#
input Period = 21;
input DPeriod = 21;

def n = Period;
input VolIncrement=20000;
def v=VolIncrement;
input VWAPType = {Rolling,default BarIncremental, VolIncremental, OneDay};
def type;
switch (VWAPType){
case Rolling:
type = 1;
case BarIncremental:
type = 0;
case OneDay:
type = 2;
case VolIncremental:
type=3;
}
input AverageMethod = {CLOSE, default H_L};
def num;
switch (AverageMethod){
case CLOSE:
num = close;
case H_L:
num = (high + low) / 2;
}
#
# Define volume for today only (other days zero):
#
def todayvol = if istoday then volume else 0;
#
# Calculate the P*V term for VWAP:
#
def pv = num * todayvol;
#
# Code for BarIncremental counter:
#
rec k = if k[1] == n then 1 else k[1] + 1;
#
# Code for VolIncremental volume sum:
#
rec volsum=if volsum[1]>v then volume else volsum[1]+volume;
#
# Code for VolIncremental price*volume:
#
rec pvsum =if volsum[1]>v then num*volume else pvsum[1] + num*volume;
#
# Now define the VolIncremental to display:
#
rec volinc=if volsum[1]==0 then num else if volsum[1]>v then pvsum[1]/volsum[1] else volinc[1];
#
# Now the final VWAP calculations:
#
rec calcVWAP = if type == 2 then TotalSum(pv) / TotalSum(todayvol) else if type == 1 then sum(num*volume, n) / sum(volume, n) else if type==3 then volinc else if type==0 and k == n then sum(num*volume, n) / sum(volume, n) else calcvwap[1];
#
# Define the plot:
#
def VWAPALOOZA = calcvwap;
#
# TD Ameritrade IP Company, Inc. (c) 2009-2020
#

input trailType = {default modified, unmodified};
input ATRPeriod = 21;
input ATRFactor = 5;
input firstTrade = {default long, short};
input averageType = AverageType.WILDERS;

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);

def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);

def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

def state = {default init, long, short};
def trail;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            trail =  close - loss;
        case short:
            state = state.short;
            trail = close + loss;
        }
    } else {
        state = state.init;
        trail = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;
    }
}



def TrailingStop = trail;

plot both= (trailingstop+VWAPALOOZA)/2;

Finalized script here: https://usethinkscript.com/threads/trailingstop-and-vwapstop-color-change.5215/post-49785
 
Last edited by a moderator:

rad14733

Well-known member
VIP
@germanburrito I'm surprised you haven't coded color change yet... Here you go...

Ruby:
# VWAPALOOZA
# By Prospectus @ http://readtheprospectus.worspress.com
#
# This Thinkscript calculates four different types of VWAP:
# OneDay (standard type), Rolling (N bar lookback), Bar
# Incremental (discrete N bar periods) and Volume Incremental
# (discrete N-shares-traded periods).
#H Kaczmarczyk added Deviation Lines & Clouds
declare upper;
#
# Check if we are on the current day:
#
def istoday = if getDay() == getLastDay() then 1 else 0;
#
# Input Rolling / Incremental period, VWAP type, and
# Averaging method ( (H+L)/2 or Close):
#
input Period = 21;
input DPeriod = 21;

def n = Period;
input VolIncrement=20000;
def v=VolIncrement;
input VWAPType = {Rolling,default BarIncremental, VolIncremental, OneDay};
def type;
switch (VWAPType){
case Rolling:
type = 1;
case BarIncremental:
type = 0;
case OneDay:
type = 2;
case VolIncremental:
type=3;
}
input AverageMethod = {CLOSE, default H_L};
def num;
switch (AverageMethod){
case CLOSE:
num = close;
case H_L:
num = (high + low) / 2;
}
#
# Define volume for today only (other days zero):
#
def todayvol = if istoday then volume else 0;
#
# Calculate the P*V term for VWAP:
#
def pv = num * todayvol;
#
# Code for BarIncremental counter:
#
rec k = if k[1] == n then 1 else k[1] + 1;
#
# Code for VolIncremental volume sum:
#
rec volsum=if volsum[1]>v then volume else volsum[1]+volume;
#
# Code for VolIncremental price*volume:
#
rec pvsum =if volsum[1]>v then num*volume else pvsum[1] + num*volume;
#
# Now define the VolIncremental to display:
#
rec volinc=if volsum[1]==0 then num else if volsum[1]>v then pvsum[1]/volsum[1] else volinc[1];
#
# Now the final VWAP calculations:
#
rec calcVWAP = if type == 2 then TotalSum(pv) / TotalSum(todayvol) else if type == 1 then sum(num*volume, n) / sum(volume, n) else if type==3 then volinc else if type==0 and k == n then sum(num*volume, n) / sum(volume, n) else calcvwap[1];
#
# Define the plot:
#
def VWAPALOOZA = calcvwap;
#
# TD Ameritrade IP Company, Inc. (c) 2009-2020
#

input trailType = {default modified, unmodified};
input ATRPeriod = 21;
input ATRFactor = 5;
input firstTrade = {default long, short};
input averageType = AverageType.WILDERS;

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);

def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);

def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

def state = {default init, long, short};
def trail;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            trail =  close - loss;
        case short:
            state = state.short;
            trail = close + loss;
        }
    } else {
        state = state.init;
        trail = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;
    }
}



def TrailingStop = trail;


plot both= (trailingstop+VWAPALOOZA)/2;
both.SetPaintingStrategy(paintingStrategy.LINE);
both.SetLineWeight(2);
both.DefineColor("UpTrend", Color.GREEN);
both.DefineColor("DnTrend", Color.RED);
both.AssignValueColor(if both > both[1] then both.Color("UpTrend") else both.Color("DnTrend"));
 

germanburrito

Active member
@rad14733 I couldn't figure it out, I have only been tinkering with coding for four months, I know some complex things, but at the same time I have issues with simple code, I believe I'm going thru a weird transition period in my learning lol, either way I truly appreciate it.
 

germanburrito

Active member
@germanburrito Could you post the Deviation study if it's not some paid indicator? Looks interesting.

Here you go sir https://tos.mx/ICTWZa9

Code:
#WT_LB Short Name TV
#DEVIATION
declare lower;
input Channel_Length = 10; #10
input Average_Length = 21; #10

def ap = hlc3;
def esa = ExpAverage(ap, Channel_Length);
def d = ExpAverage(AbsValue(ap - esa), Channel_Length);
def ci = (ap - esa) / (0.015 * d);
def tci = ExpAverage(ci, Average_Length);
def wt1 = tci;
def wt2 = SimpleMovingAvg(wt1, 4);
#plot zero = 0;
#zero.setDefaultColor(color.gray);

def wt1_1 = wt1;
def wt2_1 = wt2;

#plot avg = (wt1_1-wt2_1);

def dev1 = (stdevAll(wt1)+stdevAll(wt2))/2;

plot up = wt1_1+ dev1*2.0;
plot down = wt1_1- dev1*2;

def avg2 =(up-down/up+down)-20;

#plot avgA =(up/down-up+down);

def avg3 = 1.1* (up+down/up+down)-20;

plot line = (avg2+avg3)/2;
line.SetDefaultColor(Color.white);
line.SetLineWeight(2);

down.SetDefaultColor(Color.green);
down.SetLineWeight(3);

up.SetDefaultColor(Color.red);
up.SetLineWeight(3);
 

germanburrito

Active member
Here is an update to the script from above. Now includes ADX. This is my trend indicator. The labels consist of the ADX data, does not mean direction.

w3mFv41.png


Code:
declare lower;

def istoday = if GetDay() == GetLastDay() then 1 else 0;

input Period = 21;
input DPeriod = 21;

def n = Period;
input VolIncrement = 20000;
def v = VolIncrement;
input VWAPType = {Rolling, default BarIncremental, VolIncremental, OneDay};
def type;
switch (VWAPType){
case Rolling:
    type = 1;
case BarIncremental:
    type = 0;
case OneDay:
    type = 2;
case VolIncremental:
    type = 3;
}
input AverageMethod = {CLOSE, default H_L};
def num;
switch (AverageMethod){
case CLOSE:
    num = close;
case H_L:
    num = (high + low) / 2;
}
#
# Define volume for today only (other days zero):
#
def todayvol = if istoday then volume else 0;
#
# Calculate the P*V term for VWAP:
#
def pv = num * todayvol;
#
# Code for BarIncremental counter:
#
rec k = if k[1] == n then 1 else k[1] + 1;
#
# Code for VolIncremental volume sum:
#
rec volsum = if volsum[1] > v then volume else volsum[1] + volume;
#
# Code for VolIncremental price*volume:
#
rec pvsum = if volsum[1] > v then num * volume else pvsum[1] + num * volume;
#
# Now define the VolIncremental to display:
#
rec volinc = if volsum[1] == 0 then num else if volsum[1] > v then pvsum[1] / volsum[1] else volinc[1];
#
# Now the final VWAP calculations:
#
rec calcVWAP = if type == 2 then TotalSum(pv) / TotalSum(todayvol) else if type == 1 then Sum(num * volume, n) / Sum(volume, n) else if type == 3 then volinc else if type == 0 and k == n then Sum(num * volume, n) / Sum(volume, n) else calcVWAP[1];
#
# Define the plot:
#
def VWAPALOOZA = calcVWAP;
#
# TD Ameritrade IP Company, Inc. (c) 2009-2020
#

input trailType = {default modified, unmodified};
input ATRPeriod = 21;
input ATRFactor = 12;
input firstTrade = {default long, short};
input averageType = AverageType.WILDERS;

Assert(ATRFactor > 0, "'atr factor' must be positive: " + ATRFactor);

def HiLo = Min(high - low, 1.5 * Average(high - low, ATRPeriod));
def HRef = if low <= high[1]
    then high - close[1]
    else (high - close[1]) - 0.5 * (low - high[1]);
def LRef = if high >= low[1]
    then close[1] - low
    else (close[1] - low) - 0.5 * (low[1] - high);

def trueRange;
switch (trailType) {
case modified:
    trueRange = Max(HiLo, Max(HRef, LRef));
case unmodified:
    trueRange = TrueRange(high, close, low);
}
def loss = ATRFactor * MovingAverage(averageType, trueRange, ATRPeriod);

def state = {default init, long, short};
def trail;
switch (state[1]) {
case init:
    if (!IsNaN(loss)) {
        switch (firstTrade) {
        case long:
            state = state.long;
            trail =  close - loss;
        case short:
            state = state.short;
            trail = close + loss;
    }
    } else {
        state = state.init;
        trail = Double.NaN;
    }
case long:
    if (close > trail[1]) {
        state = state.long;
        trail = Max(trail[1], close - loss);
    } else {
        state = state.short;
        trail = close + loss;
    }
case short:
    if (close < trail[1]) {
        state = state.short;
        trail = Min(trail[1], close + loss);
    } else {
        state = state.long;
        trail =  close - loss;
    }
}



def TrailingStop = trail;

plot both = (TrailingStop + VWAPALOOZA) / 2;


both.AssignValueColor(if close > both
                           then color.green
                           else color.red);

Both.setlineweight(3);

plot L = close;

L.AssignValueColor(color.cyan);
L.SetLineWeight(3);


input length2 = 14;
input averageType2 = AverageType.WILDERS;

def ADX = DMI(length2, averageType2).ADX;

def level = 23.6;
def level2 = 45;
def level3 = 70;


def U = adx > level and adx < level2;
def U2 = adx > level2 and adx < level3;
def U3 = adx > level3 ;
def D = adx< level;



AddLabel( U, " TRENDING " , Color.YELLOW);
AddLabel( U2, " STRONG " , Color.MAGENTA);
AddLabel( U3, " EXTREMLY STRONG " , Color.CYAN);
AddLabel( D, " RESTING " , Color.LIGHT_GRAY);
 
Last edited by a moderator:

germanburrito

Active member
HI looks good what is your strategy for trading with it, what times frames are better. TY
i use this as support and resistance,
this is not the only tool i use, but it is a great tool, I have been trading for two years and i discovered that the market is in fact "fractal", so it is of the most crucial that you maintain the same settings for the higher time frames as you do for the low time frames, at least in my opinion you may explore other ideas that might fit your trading. I use 7 times frames, a monthly, weekly, daily, 4 hour, 1 hour, 30 min, 5 min, i don't use the minute because I can gauge what the minute is doing by looking at the 5 minute candle.
some traders believe that time should not affect the movement off the market, i do believe that time affects the market, that's why i am not a fan of tick charts, i want to know when a new candle begins, because that's usually when new buyers and sellers come in, a new week, new hour, new 30 minutes...... will increase the volume coming in.
this will tell you trend
now trend is the most use and abused word that I have come across in my trading
i have found that "don't fight the trend" does not hold any real substance.
you see a trend in my opinion is arbitrary, what is a trend? two candles? three? four? adx over 25? what does that mean? what time frame?
whats trending on a 5 minute chart might be consolidation on a 15 minute chart.
the TREND is only true or not to the time frame you are looking at.
with that being said i want to make sure that there is not a CLEAR RECENT break of the indicator to the upside or downside on a higher time frame, usually 4 hours, usually to the downside because most of the time stocks go up, the market is delta positive, so technically you have a higher probability longing ( i know that may be argued, i'm not here for that), to keep it simple then i try to look for a bounce on the 5 minute chart of the trend line.

so basically and approach would be green on most time frames, with the stock coming down on the 5 minute time frame to bounce on the trend line.

this is not the only tool i use, so i couldn't really tell you how i actually trade, but i hope at least this may give you some ideas, because i do believe that sharing is how you gain.


Also I do what is called a ghetto spread lol, I buy a contract wait till it goes up lets say 20 percent and then I sell a cheaper contract against it. So I'm still in the play but its way harder for me to lose money, im still in the play, with a a little bit of upside and a little bit of downside. This is also great if you dont have the account to day trade it allows you to almost day trade with any account size, you because selling a cheaper contract against your contract does not count as a day trade.
 
Last edited:

Similar threads

Top