Accessing Seconds from 1min Chart

CDJay

CDJay

Member
VIP
@Welkin


Hi Welkin,

There are so many threads on UTS that it's easy to miss some, which I did with this one until tonight. I love the idea of your code, because I've wanted to be able to get to-the-second data for a while.

I want to make sure I understand this graphic, so please tell me if anything I saying here is incorrect.

1) The top chart is one minute, while the bottom chart is set to ticks, whose aggregation you change throughout the trading day.
2) The bottom chart appears to the white line at the end of the top chart, with each segment a second.
3) This minute of TSLA was a down tick, which the bottom chart also shows by having more sell volume than buy volume.
4) Do 8:36 and 8:37 show buying volume? Since they do not appear to be enough to lead to a price rise, as the previous minute's bar was down, what would we look for visually to determine buying volume is coming versus selling volume? Does the green cloud (or red at the applicable time) have to be twice as tall, three times, four times, or more?

5) I don't understand your middle study? What is it showing you?

Finally, I hope the procedure goes well for your brother.

Thank you for your help.

Regards,
Jason
 
Last edited by a moderator:
Welkin

Welkin

Active member
VIP
Important correction to the OnBalanceVol aspect. This was an issue on the very low tick aggregations and shouldn't have been an issue with higher ticks and higher volatility where the candles have more structure. Noticed this while observing the globex session for a while at 5 ticks. When the close was equal to the prior close on the tick chart it was causing the volume to be added to the bearish side. This is now corrected.

Code:
#[email protected]
#Attempt at Volume Projection and Buy/Sell Strength on low TICK charts
#Thanks to YungTraderFromMontana and evanevans for the ideas
#v9.6.2020
declare lower;

def NA = Double.NaN;
input Sentiment = {default None, Inertia, HeikenAshiTrend, AboveBelowMovAvg, AboveBelowHighVolTriggeredVWAP};
input strengthType = {CandleStrength, default OnBalanceVol};
input showCumulativeStr = no;
input showCumulativeStrDiff = yes;
input aggregationInSeconds = 60;
def aggtomin = aggregationInSeconds / 60;
input toggleProjection = {enabled, default disabled};
input elapsedPercentSmoothValue = 5;
input elapsedProjectionDivisor = 2;
input showVerticalExceedPrevCvol = yes;
input showVerticalCycleEndCvol = yes;

def start = 0000;
def end = 1600;
def o = open;
def h = high;
def l = low;
def c = close;
def v = volume;
def t = tick_count;
def bull = c > c[1];
def bear = c < c[1];
def neutral = c == o;
def min = Floor(SecondsFromTime(start) / aggregationInSeconds);
def till = SecondsTillTime(end) / aggregationInSeconds;
def test = min != min[1];
def vc = if test and !test[1] then v else if !test then vc[1] + v else vc[1];

def b = ((c - l) / (h - l)) * v;
def s = ((h - c) / (h - l)) * v;
def cb;
def cs;
switch (strengthType){
case CandleStrength:
    cb = if test and !test[1] then b else if !test then cb[1] + b else cb[1];
    cs = if test and !test[1] then s else if !test then cs[1] + s else cs[1];
case OnBalanceVol:
    cb = if test and !test[1] and bull then v else if test and !test[1] and !bull then 0 else if !test and bull then cb[1] + v else cb[1];
    cs = if test and !test[1] and bear then v else if test and !test[1] and !bear then 0 else if !test and bear then cs[1] + v else cs[1];
}

#def tickcount = if test and !test[1] then t else if !test then tickcount[1] + t else tickcount[1];
#def prevtickcount = if test and !test[1] then tickcount[1] else prevtickcount[1];
#def tickperminute = prevtickcount/aggtomin;
#AddLabel(1, prevtickcount, COlor.Magenta);
#AddLabel(1,tickcount,Color.MAGENTA);
#AddLabel(1,tickperminute+" TPM",Color.MAGENTA);

def secondselapsed = (AbsValue(till - Ceil(till)) * aggregationInSeconds);
def secondsleft = aggregationInSeconds - secondselapsed;
def multipliertest = aggregationInSeconds / secondselapsed;
def multiplier  = if IsInfinite(multipliertest) then NA else multipliertest;
def percntelapsed = Round(((secondselapsed / aggregationInSeconds) * 100), 0);
def cl = if test then 1 else cl[1] + 1;
def ch = if test then cl[1] else ch[1];
def prevcumulativehigh = if test and !test[1] then vc[1] else prevcumulativehigh[1];
def cvolpassprev = vc >= prevcumulativehigh and vc[1] < prevcumulativehigh;
def highestprevchigh = HighestAll(prevcumulativehigh);
def projectioncalc = vc * multiplier;

######################
#Inertia
input inertiaLength = 20;
input inertiaPrice = close;
def inertia = Inertia(inertiaPrice, inertiaLength);

######################
#Heiken Ashi
def HAopen;
def HAhigh;
def HAlow;
def HAclose;
HAopen = CompoundValue(1, (HAopen[1] + HAclose[1]) / 2, (o[1] + c[1]) / 2);
HAhigh = Max(Max(h, HAopen), HAclose[1]);
HAlow = Min(Min(l, HAopen), HAclose[1]);
HAclose = ohlc4;

######################
#Above Below Moving Average
input movAvgPrice = close;
input movAvgType = AverageType.EXPONENTIAL;
input movAvg1Length = 20;
input movAvg2Length = 30;
input movAvg3Length = 40;
input movAvg4Length = 50;
def MA1 = MovingAverage(movAvgType, movAvgPrice, movAvg1Length);
def MA2 = MovingAverage(movAvgType, movAvgPrice, movAvg2Length);
def MA3 = MovingAverage(movAvgType, movAvgPrice, movAvg3Length);
def MA4 = MovingAverage(movAvgType, movAvgPrice, movAvg4Length);
def MA12test = MA1 > MA2;
def MA23test = MA2 > MA3;
#def MA34test = MA3 > MA4;

######################
#Sigma Vol Filters
input avgVolLength = 20;
input volAverageType = AverageType.SIMPLE;
input Sigma2 = 2.0;
input Sigma3 = 3.0;
def VolAvg = MovingAverage(volAverageType, v, avgVolLength);
def sDev = StDev(data = v, length = avgVolLength);
def VolSigma2 = VolAvg + Sigma2 * sDev;
def VolSigma3 = VolAvg + Sigma3 * sDev;

######################
#VWAP
def vconf = if v > VolSigma3 then 1 else if v > VolSigma2 then 1 else 0;
def VolumeSum = if vconf then v else CompoundValue(1, VolumeSum[1] + v, v);
def VolumeVwapSum = if vconf then v * vwap else CompoundValue(1, VolumeVwapSum[1] + v * vwap, v * vwap);
def volumeVwap2Sum = if vconf then v * Sqr(vwap) else CompoundValue(1, volumeVwap2Sum[1] + v * Sqr(vwap), v * Sqr(vwap));
def VW = if !IsNaN(c) then VolumeVwapSum / VolumeSum else VW[1];

######################

plot cvolpassprevsig = if cvolpassprev then vc else NA;
plot CVol = vc;
plot prevchigh = prevcumulativehigh;
plot cycleavg = Round(TotalSum(if test and !test[1] then ch[1] else 0) / min, 1);
plot cyclehigh = ch;
plot cyclelength = cl;

plot projection;
switch (toggleProjection){
case enabled:
    projection = if (projectioncalc >= highestprevchigh) and (percntelapsed < elapsedPercentSmoothValue) then projectioncalc / elapsedProjectionDivisor else projectioncalc;
case disabled:
    projection = NA;
}
cycleavg.Hide();
cyclehigh.Hide();
cyclelength.Hide();

plot bsdiff = prevchigh + (cb - cs);
bsdiff.SetHiding(!showCumulativeStrDiff);
def bsdiffaboveztest = bsdiff > prevchigh;
bsdiff.AssignValueColor(if bsdiffaboveztest and bsdiff > bsdiff[1] then Color.GREEN else if bsdiffaboveztest and bsdiff <= bsdiff[1] then Color.DARK_GREEN else if !bsdiffaboveztest and bsdiff < bsdiff[1] then Color.RED else Color.DARK_RED);
plot cbuy = cb;
cbuy.SetHiding(!showCumulativeStr);
plot csell = cs;
csell.SetHiding(!showCumulativeStr);

def Pos;
def Neg;
switch (Sentiment){
case None:
    Pos = NA;
    Neg = NA;
case Inertia:
    Pos = inertia > inertia[1];
    Neg = !Pos;
case HeikenAshiTrend:
    Pos = HAclose > HAopen;
    Neg = !Pos;
case AboveBelowMovAvg:
    Pos = MA12test and MA23test;
    Neg = !Pos;
case AboveBelowHighVolTriggeredVWAP:
    Pos = close > VW;
    Neg = !Pos;
}


#Vertical Lines
AddVerticalLine(showVerticalExceedPrevCvol and !IsNaN(cvolpassprevsig), "                 " + secondselapsed + "s / " + aggregationInSeconds + " | " + percntelapsed + "%", Color.CYAN);
AddVerticalLine(showVerticalCycleEndCvol and test, "Lngth " + cyclelength[1] + "  CVol " + prevcumulativehigh + "  B/S " + Round((cb[1] / vc[1]) * 100, 0) + "/" + +Round((cs[1] / vc[1]) * 100, 0) + "%", Color.GRAY, Curve.FIRM);

#Labels

input showCycleLengthLabel = yes;
input showPrevCycleLengthLabel = yes;
input showCycleAvgLengthLabel = no;
input showTotalCyclesLabel = no;
input showSecsElapsedLabel = yes;
input showCumulativeVolLabel = yes;
input showBuyStrLabel = yes;
input showSellStrLabel = yes;
input showPrevCVolLabel = yes;
input showRelToPrevCVolLabel = yes;
input showProjectedVolLabel = yes;
input showProjMultiplierLabel = no;


AddLabel(showCycleLengthLabel, "Cycle Length: " + cyclelength[1], Color.GRAY);
AddLabel(showPrevCycleLengthLabel, "Prev Cycle Length: " + cyclehigh, Color.GRAY);
AddLabel(showCycleAvgLengthLabel, "Cycle Avg Length: " + cycleavg, Color.GRAY);
AddLabel(showTotalCyclesLabel, "Cycles Since Start: " + min, Color.GRAY);
AddLabel(showSecsElapsedLabel, "Secs " + secondselapsed + "/" + aggregationInSeconds + "   " + percntelapsed + "%", Color.YELLOW);
AddLabel(showCumulativeVolLabel, "CVol: " + vc, Color.WHITE);
AddLabel(1, "BuyStr: " + Round(cb, 0) + " / " + Round((cb / vc) * 100, 2) + "%", Color.GREEN);
AddLabel(1, "SellStr: " + Round(cs, 0) + " / " + Round((cs / vc) * 100, 2) + "%", Color.RED);
AddLabel(showPrevCVolLabel, "Prev CVol: " + prevcumulativehigh, Color.WHITE);
AddLabel(showRelToPrevCVolLabel, "x" + Round(vc / prevcumulativehigh, 2) + " Prev CVol", Color.WHITE);
AddLabel(showProjectedVolLabel and toggleProjection == toggleProjection.enabled, "Proj Vol: " + Round(projection, 0), Color.DARK_ORANGE);
AddLabel(showProjMultiplierLabel and toggleProjection == toggleProjection.enabled, "Proj Multiplier x" + Round(multiplier, 2), Color.DARK_ORANGE);

CVol.SetDefaultColor(Color.DARK_GRAY);
CVol.AssignValueColor(if toggleProjection == toggleProjection.disabled and Pos then Color.GREEN else if Neg then Color.RED else Color.GRAY);
CVol.SetLineWeight(2);
prevchigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
prevchigh.SetDefaultColor(Color.YELLOW);
projection.SetDefaultColor(Color.DARK_ORANGE);
projection.AssignValueColor(if Pos then Color.GREEN else if Neg then Color.RED else Color.GRAY);
projection.SetLineWeight(2);
cvolpassprevsig.SetPaintingStrategy(PaintingStrategy.POINTS);
cvolpassprevsig.SetLineWeight(3);

AddCloud(if showCumulativeStr then cbuy else NA, csell, Color.GREEN, Color.RED);
AddCloud(if showCumulativeStrDiff then bsdiff else NA, prevchigh, Color.GREEN, Color.RED);
AddCloud(projection, CVol, CreateColor(0, 100, 200), CreateColor(0, 100, 200));
AddCloud(CVol, 0, Color.DARK_GRAY, Color.DARK_GRAY);
AddCloud(CVol, prevchigh, Color.YELLOW, Color.BLACK);
 
Last edited:
YungTraderFromMontana

YungTraderFromMontana

Well-known member
Love A/D... I've played around with it for a while and use a modified aspect of the formula every day. You (and others) will probably find this useful:
http://tos.mx/vc5Mjo8
the ADL formula was modified a bit, volume isn't included in the calculation, and the highs and lows in the formula were replaced to use higher aggregation values with a small twist. Whichever value is the highest or lowest, the current bar's high/low or previous bar's high/low. It is then multiplied by 100. this sets a floor/ceiling of -100/+100, and a threshold of 90(default but adjustable) is set. When the close comes at or above the +/-90 threshold vertical lines begin plotting, signaling either a potential break higher or met with strong resistance causing a reversal. Can usually capture some nice moves with this, especially when paired with standard deviation bands for mean reversion strats.

As for AD on tick charts it is as you said, it would require an accumulation of data of a certain length of time or it would require higher tick charts to get rid of the gaps due to the small amount of bar data that can be sampled. On low tick charts the bars are very low spread and have a lack of bar structure. The formulas that rely on OHLCs don't do so well because of this and is why we gotta bump up the tick aggregation until we have better samples of data for the formula to operate on. The 'candlestrength' aspect and some of the earlier sentiment options on the vol projection script have/had this issue...



I'm not sure... I want to start introducing market internals to the mix. Things like $ADD/$VOLD/$TICK and the VIX...

Appreciate the well wishes, currently my brother is scheduled for surgery tomorrow for a cystoscopy... he has a blockage in his left kidney and they are going to try and find out whats going on. Hopefully its just some kidney stones...


I see that, should try putting some bollinger or std dev bands on it and see what kind of signals it gives.
Best of luck to your brother🙏
 
Welkin

Welkin

Active member
VIP
Hi Welkin,

There are so many threads on UTS that it's easy to miss some, which I did with this one until tonight. I love the idea of your code, because I've wanted to be able to get to-the-second data for a while.

I want to make sure I understand this graphic, so please tell me if anything I saying here is incorrect.

1) The top chart is one minute, while the bottom chart is set to ticks, whose aggregation you change throughout the trading day.
2) The bottom chart appears to the white line at the end of the top chart, with each segment a second.
3) This minute of TSLA was a down tick, which the bottom chart also shows by having more sell volume than buy volume.
4) Do 8:36 and 8:37 show buying volume? Since they do not appear to be enough to lead to a price rise, as the previous minute's bar was down, what would we look for visually to determine buying volume is coming versus selling volume? Does the green cloud (or red at the applicable time) have to be twice as tall, three times, four times, or more?

5) I don't understand your middle study? What is it showing you?

Finally, I hope the procedure goes well for your brother.

Thank you for your help.

Regards,
Jason
1. Correct, depending on the volatility of the ticker you're looking at it should be adjusted. If there is a ton of activity and each minute takes up the entire window you should increase the tick aggregation. If the opposite is true then lower it until you find a good balance.
2. The indicator is set to 60 seconds so each minute on the x axis is marked off at 1 minute intervals. It was scrolled to the start of the day showing what happened a few minutes after market open. Probably should have zoomed in on the upper chart... Wasn't really trying to present anything with this image only show those in the thread who've been testing it the new OnBalanceVol difference aspect.
4. It wasn't enough to push it much higher, I think this is due the price range of the prior bars already knocked out a lot of the orders in the price ladder, giving it room to climb a little more with less effort, but there wasn't enough buyers to support it, buyers started taking profit and the sellers were able to further wrestle control and it started tanking lower.

I created a screenshot to better illustrate what you should be looking for. All the candles in the gray box are what are visible in the lower study.

5. The middle study is actually my advanced vol study, you can find it in this thread along with explanations.
The study for the red and green clouds floating above the candles has yet to be posted, I plan on adding it later on. It uses the same formula found in a lot of other volume studies in an attempt to measure buying and selling volume but it isn't true buy/sell volume as ToS does not provide us with that data. It is explained a little more in the mentioned thread. If you want to play around with it here it is:
Code:
#[email protected]
#Summative Volume Strength Clouds
declare lower;

def NA = Double.NaN;
input length = 5;

def o = open;
def h = high;
def l = low;
def c = close;
def v = volume;
def bvolsum = Sum(((c - l) / (h - l)) * v, length);
def svolsum = Sum(((h - c) / (h - l)) * v, length);
AddCloud(bvolsum, svolsum, Color.GREEN, Color.RED,1);
Also, thank you, I hope the procedure goes smooth as well!
 
Last edited:
CDJay

CDJay

Member
VIP
Can anyone tell what I'm doing wrong, because my screens look like someone gave me the crayons, while Welkin's looks great?

My top chart is a one minute chart with three studies of two moving averages and the VWAP — which I'll probably eliminate once I get the VolumeBySecond working — yet it's still showing volume below. My lower chart is a tick chart set to today and 25 ticks, and its only study is Welkin's VolumeBySecond in the lower area, but I still have the chart and volume, while I'm having difficulty enlarging the volume by tick below.

Thanks,
Jason

By the way, apparently drag and drop doesn't work for images. How do I post an image?
 
Welkin

Welkin

Active member
VIP
Can anyone tell what I'm doing wrong, because my screens look like someone gave me the crayons, while Welkin's looks great?

My top chart is a one minute chart with three studies of two moving averages and the VWAP — which I'll probably eliminate once I get the VolumeBySecond working — yet it's still showing volume below. My lower chart is a tick chart set to today and 25 ticks, and its only study is Welkin's VolumeBySecond in the lower area, but I still have the chart and volume, while I'm having difficulty enlarging the volume by tick below.

Thanks,
Jason

By the way, apparently drag and drop doesn't work for images. How do I post an image?
In the chart settings on the lower grid disable price subgraph and check overlap volume
edit: for posting screenshots I use an app called greenshot, which I can set to go to an editor to draw on or directly upload it to an image sharing service of my choice. the URL is automatically copied and I only have to paste it when I click the insert image button and paste the imgur url when making a reply.
 
Last edited:
Welkin

Welkin

Active member
VIP
Can anyone tell what I'm doing wrong, because my screens look like someone gave me the crayons, while Welkin's looks great?

My top chart is a one minute chart with three studies of two moving averages and the VWAP — which I'll probably eliminate once I get the VolumeBySecond working — yet it's still showing volume below. My lower chart is a tick chart set to today and 25 ticks, and its only study is Welkin's VolumeBySecond in the lower area, but I still have the chart and volume, while I'm having difficulty enlarging the volume by tick below.

Thanks,
Jason

By the way, apparently drag and drop doesn't work for images. How do I post an image?
also here is a shared grid stripped down to the minimum... just save it so you can load it again later
http://tos.mx/YQwdp9C
 
CDJay

CDJay

Member
VIP
Now that I'm getting it to look better, I like what you created Welkin, but I have a couple of questions or suggestions.

1) Every time I cycle through my watchlist, it seems like the entire day's ticks show up in the bottom grid; I'm able to get to the most current by clicking the plus button multiple times. If I go to the next ticker, I have to repeat the process. Are there some checkboxes I need to click to prevent this? Or is this something that can be coded to make it always resize and go to the latest windows?

2) Is there any way to create alerts or custom labels for the watchlist when green volume is occurring? So if I'm in Stock 1 of my watchlish, but Stock 7 started percolating, could it be written that Stock 7 would have a label pop up in a custom column telling me to look at the stock?
 
Last edited:
rad14733

rad14733

Active member
VIP
Now that I'm getting it to look better, I like what you create Welkin, but I have a couple of questions or suggestions.

1) Every time I cycle through my watchlist, it seems like the entire day's ticks show up in the bottom grid; I'm able to get to the most current by clicking the plus button multiple times. If I go to the next ticker, I have to repeat the process. Are there some checkboxes I need to click to prevent this? Or is this something that can be coded to make it always resize and go to the latest windows?
Try going to Chart Settings > Time Axis > Scale and make sure the Keep Time Zoom is checked...
 
MattATM

MattATM

Active member
VIP
Try going to Chart Settings > Time Axis > Scale and make sure the Keep Time Zoom is checked...
Back earlier in this thread I was talking about scaling to make ticks proportional to a target... But @rad14733 suggestion is way easier for just keeping a good view ;)
 
Welkin

Welkin

Active member
VIP
Now that I'm getting it to look better, I like what you created Welkin, but I have a couple of questions or suggestions.

1) Every time I cycle through my watchlist, it seems like the entire day's ticks show up in the bottom grid; I'm able to get to the most current by clicking the plus button multiple times. If I go to the next ticker, I have to repeat the process. Are there some checkboxes I need to click to prevent this? Or is this something that can be coded to make it always resize and go to the latest windows?

2) Is there any way to create alerts or custom labels for the watchlist when green volume is occurring? So if I'm in Stock 1 of my watchlish, but Stock 7 started percolating, could it be written that Stock 7 would have a label pop up in a custom column telling me to look at the stock?
Sorry, can't scan at the tick level for watchlists, they still need to be based on the normal aggregations available in your scanner (1min+). When cumulative volume is increasing every cycle it is the equivalent of scanning for the current volume bar exceeding the previous for that time frame, or an increase in relative volume. 'Green Volume' coming in simply means a bullish bar on the 1 min. When volatility picks up ATR is also rising as well in that time period. Nuances like these can be incorporated into your existing scans at the 1 min time frame, but remember if your scans involve too many factors the refresh rate for your custom watchlists will be slower, so you might have trouble capitalizing on it at the tick level. This tool's main purpose is for better precision entries to help lower risk while observing your existing scans/strategy/indicators/price action/etc. that are alerting you.
 
MattATM

MattATM

Active member
VIP
I see that, should try putting some bollinger or std dev bands on it and see what kind of signals it gives.
YUP there are no deviations if "Normalized" so I used an average CMFV (Didn't want acc/dist to big)



http://tos.mx/Swhklk1

It gives a nice preview; the issue of not knowing if volume is there to hold S/R or make nice move persists. Only thing I can think of is show a correlation between some sort of acc/dist, OBV and ? something else.
 
MattATM

MattATM

Active member
VIP
2) Is there any way to create alerts or custom labels for the watchlist when green volume is occurring? So if I'm in Stock 1 of my watchlish, but Stock 7 started percolating, could it be written that Stock 7 would have a label pop up in a custom column telling me to look at the stock?
Bro I don't completely understand what I did or what this is yet, so to early for me to think of more gadgets...
Any thought about what to make the comparison to to understand WHY? volume is there???
 
Welkin

Welkin

Active member
VIP
@MattATM Having looked back at this move that you reference, it stopped at precisely 3x daily ATR from the open. Also, it was almost precisely a 150% move down from the prev days lowest point based on the previous day's range. On the monthly volume profile on a daily chart it was very close to the value area high before the break higher on 8/26. Could be some other things but I think it was several these factors on the higher time frames that all converged together and played a role in its support.

edit: another thing, $TICKs were at the most extreme down to almost -1700, once that let off, $VOLD, $ADD, and the -VIX all started to stall then ease up

 
Last edited:
D

Dupre

New member
VIP
@Welkin Are you ever in the Discord room? If so, do you go by the same username?
 
Welkin

Welkin

Active member
VIP
@Welkin Are you ever in the Discord room? If so, do you go by the same username?
Yes, haven't spoken much but I do lurk there and a few other stock servers just to see whats going on. Every time I sign in my pm's are flooded with crypto scam bullshit 🤣 but if you wish to talk my disc id is welkin #6725 if you want to send me a message.
 
StockT8er

StockT8er

Member
VIP
I converted your study to a Strategy, hope you don't mind. Works pretty well. Still working on Bubble to work right
Setup the time as Range - TODAY 100 Ticks or Range DAY 100 Ticks

Code:
#[email protected]
#Attempt at Volume Projection and Buy/Sell Strength on low TICK charts
#Thanks to YungTraderFromMontana and evanevans for the ideas
#v9.6.2020


# Positioning --------------------------------------------------------

input usetimefilter = Yes;
input rthopen = 0932;
input rthclose = 1555;
def RTH = if usetimefilter == yes then if SecondsFromTime(rthopen) >= 0 and
               SecondsTillTime(rthclose) >= 0
            then 1
            else 0 else 1;

input StopLoss = Yes;
input stoplosspercent = .08;

input fastLength = 9;
input slowLength = 26;
input MACDLength = 3;
input averageType = AverageType.EXPONENTIAL;
def Diff = MACD(fastLength, slowLength, MACDLength, averageType).Diff;
def DiffCondition = (if Diff >= 0 then if Diff > Diff[1] then 1 else 2 else if Diff < Diff[1] then 3 else 4);

def NA = Double.NaN;
input Sentiment = {default None, Inertia, HeikenAshiTrend, AboveBelowMovAvg, AboveBelowHighVolTriggeredVWAP};
input strengthType = {CandleStrength, default OnBalanceVol};
input showCumulativeStr = no;
input showCumulativeStrDiff = yes;
input aggregationInSeconds = 60;
def aggtomin = aggregationInSeconds / 60;
input toggleProjection = {enabled, default disabled};
input elapsedPercentSmoothValue = 5;
input elapsedProjectionDivisor = 2;
input showVerticalExceedPrevCvol = yes;
input showVerticalCycleEndCvol = yes;

def start = 0000;
def end = 1600;
def o = open;
def h = high;
def l = low;
def c = close;
def v = volume;
def t = tick_count;
def bull = c > c[1];
def bear = c < c[1];
def neutral = c == o;
def min = Floor(SecondsFromTime(start) / aggregationInSeconds);
def till = SecondsTillTime(end) / aggregationInSeconds;
def test = min != min[1];
def vc = if test and !test[1] then v else if !test then vc[1] + v else vc[1];

def b = ((c - l) / (h - l)) * v;
def s = ((h - c) / (h - l)) * v;
def cb;
def cs;
switch (strengthType){
case CandleStrength:
    cb = if test and !test[1] then b else if !test then cb[1] + b else cb[1];
    cs = if test and !test[1] then s else if !test then cs[1] + s else cs[1];
case OnBalanceVol:
    cb = if test and !test[1] and bull then v else if test and !test[1] and !bull then 0 else if !test and bull then cb[1] + v else cb[1];
    cs = if test and !test[1] and bear then v else if test and !test[1] and !bear then 0 else if !test and bear then cs[1] + v else cs[1];
}

def tickcount = if test and !test[1] then t else if !test then tickcount[1] + t else tickcount[1];
def prevtickcount = if test and !test[1] then tickcount[1] else prevtickcount[1];
def tickperminute = prevtickcount/aggtomin;
#AddLabel(1, prevtickcount, COlor.Magenta);
#AddLabel(1,tickcount,Color.MAGENTA);
#AddLabel(1,tickperminute+" TPM",Color.MAGENTA);

def secondselapsed = (AbsValue(till - Ceil(till)) * aggregationInSeconds);
def secondsleft = aggregationInSeconds - secondselapsed;
def multipliertest = aggregationInSeconds / secondselapsed;
def multiplier  = if IsInfinite(multipliertest) then NA else multipliertest;
def percntelapsed = Round(((secondselapsed / aggregationInSeconds) * 100), 0);
def cl = if test then 1 else cl[1] + 1;
def ch = if test then cl[1] else ch[1];
def prevcumulativehigh = if test and !test[1] then vc[1] else prevcumulativehigh[1];
def cvolpassprev = vc >= prevcumulativehigh and vc[1] < prevcumulativehigh;
def highestprevchigh = HighestAll(prevcumulativehigh);
def projectioncalc = vc * multiplier;

######################
#Inertia
input inertiaLength = 20;
input inertiaPrice = close;
def inertia = Inertia(inertiaPrice, inertiaLength);

######################
#Heiken Ashi
def HAopen;
def HAhigh;
def HAlow;
def HAclose;
HAopen = CompoundValue(1, (HAopen[1] + HAclose[1]) / 2, (o[1] + c[1]) / 2);
HAhigh = Max(Max(h, HAopen), HAclose[1]);
HAlow = Min(Min(l, HAopen), HAclose[1]);
HAclose = ohlc4;

######################
#Above Below Moving Average
input movAvgPrice = close;
input movAvgType = AverageType.EXPONENTIAL;
input movAvg1Length = 20;
input movAvg2Length = 30;
input movAvg3Length = 40;
input movAvg4Length = 50;
def MA1 = MovingAverage(movAvgType, movAvgPrice, movAvg1Length);
def MA2 = MovingAverage(movAvgType, movAvgPrice, movAvg2Length);
def MA3 = MovingAverage(movAvgType, movAvgPrice, movAvg3Length);
def MA4 = MovingAverage(movAvgType, movAvgPrice, movAvg4Length);
def MA12test = MA1 > MA2;
def MA23test = MA2 > MA3;
def MA34test = MA3 > MA4;

######################
#Sigma Vol Filters
input avgVolLength = 20;
input volAverageType = AverageType.SIMPLE;
input Sigma2 = 2.0;
input Sigma3 = 3.0;
def VolAvg = MovingAverage(volAverageType, v, avgVolLength);
def sDev = StDev(data = v, length = avgVolLength);
def VolSigma2 = VolAvg + Sigma2 * sDev;
def VolSigma3 = VolAvg + Sigma3 * sDev;

######################
#VWAP
def vconf = if v > VolSigma3 then 1 else if v > VolSigma2 then 1 else 0;
def VolumeSum = if vconf then v else CompoundValue(1, VolumeSum[1] + v, v);
def VolumeVwapSum = if vconf then v * vwap else CompoundValue(1, VolumeVwapSum[1] + v * vwap, v * vwap);
def volumeVwap2Sum = if vconf then v * Sqr(vwap) else CompoundValue(1, volumeVwap2Sum[1] + v * Sqr(vwap), v * Sqr(vwap));
def VW = if !IsNaN(c) then VolumeVwapSum / VolumeSum else VW[1];

######################

def cvolpassprevsig = if cvolpassprev then vc else NA;
#def CVol = vc;
def prevchigh = prevcumulativehigh;
def cycleavg = Round(TotalSum(if test and !test[1] then ch[1] else 0) / min, 1);
def cyclehigh = ch;
def cyclelength = cl;

def projection;
switch (toggleProjection){
case enabled:
    projection = if (projectioncalc >= highestprevchigh) and (percntelapsed < elapsedPercentSmoothValue) then projectioncalc / elapsedProjectionDivisor else projectioncalc;
case disabled:
    projection = NA;
}
#ycleavg.Hide();
#cyclehigh.Hide();
#cyclelength.Hide();

def bsdiff = prevchigh + (cb - cs);
#bsdiff.SetHiding(!showCumulativeStrDiff);
def bsdiffaboveztest = bsdiff > prevchigh;
#bsdiff.AssignValueColor(if bsdiffaboveztest and bsdiff > bsdiff[1] then Color.GREEN else if bsdiffaboveztest and bsdiff <= bsdiff[1] then Color.DARK_GREEN else if !bsdiffaboveztest and bsdiff < bsdiff[1] then Color.RED else Color.DARK_RED);
def cbuy = cb;
#cbuy.SetHiding(!showCumulativeStr);
def csell = cs;
#csell.SetHiding(!showCumulativeStr);

def Pos;
def Neg;
switch (Sentiment){
case None:
    Pos = NA;
    Neg = NA;
case Inertia:
    Pos = inertia > inertia[1];
    Neg = !Pos;
case HeikenAshiTrend:
    Pos = HAclose > HAopen;
    Neg = !Pos;
case AboveBelowMovAvg:
    Pos = MA12test and MA23test;
    Neg = !Pos;
case AboveBelowHighVolTriggeredVWAP:
    Pos = close > VW;
    Neg = !Pos;
}

# PrevDayClose -------------------------------------------------------

input stopbuyPrevClose = No;
input aggregationPeriod = AggregationPeriod.DAY;
def showOnlyLastPeriod = yes;
def prevPrice = open(period = aggregationPeriod)[-1];
def price3 = open(period = aggregationPeriod);
def DailyOpen = if showOnlyLastPeriod and !IsNaN(prevPrice) then Double.NaN else price3;

def length3 = 1;
def displace3 = -1;
def PrevDayClose;

if showOnlyLastPeriod and !IsNaN(close(period = aggregationPeriod)[-1]) {
    PrevDayClose = Double.NaN;
} else {
    PrevDayClose = Highest(close(period = aggregationPeriod)[-displace3], length3);
}
def pclose = if stopbuyPrevClose == yes then if PrevDayClose < close then 1 else 0 else 1;

def BuyStr = Round(cb, 0);
def SellStr = Round(cs, 0);
#def BuyStr = (cb / vc);
#def SellStr = (cs / vc);
def VDiff = Round(((BuyStr - SellStr) / BuyStr) * 100, 2);

def entryPrice = EntryPrice();
def pstoploss = entryPrice * (stoplosspercent / 100);
def pStopSell = entryPrice - pstoploss > close;

def StopSell = if StopLoss == 1 then pStopSell else 0;
def EOD =  RTH == 1 > SecondsTillTime(2000);
def BuyorderPrice = open[-1] + ((close[-1] - open[-1]) / 2);
def SellorderPrice = open[-1] - ((open[-1] - close[-1]) / 2);

# Buy_Signals --------------------------------------------------------

def BuySignal1 = VDiff>2;
def SellSignal1 = VDiff<-2;
def BuySignal2 = bsdiffaboveztest and bsdiff > bsdiff[1];
def SellSignal2 = !bsdiffaboveztest and bsdiff < bsdiff[1];
def BuySignal = BuySignal1 and BuySignal2 and Diff > Diff[1];
def SellSignal = SellSignal1 and SellSignal2 and Diff < Diff[1] and DiffCondition == 3;

AddOrder(OrderType.BUY_TO_OPEN, RTH and BuySignal[-1], price = buyorderprice, tickcolor = GetColor(0), arrowcolor = GetColor(0), name = "CDS_LE_G");

AddOrder(OrderType.SELL_TO_CLOSE, SellSignal[-1], price = sellorderprice, tickcolor = GetColor(1), arrowcolor = GetColor(1), name = "CDS_SE");

AddOrder(OrderType.SELL_TO_CLOSE, StopSell[-1], price = sellorderprice, tickcolor = GetColor(7), arrowcolor = GetColor(7), name = "CDS_SL");

AddOrder(OrderType.SELL_TO_CLOSE, EOD, price = sellorderprice, tickcolor = GetColor(9), arrowcolor = GetColor(9), name = "CDS_EOD");

#input showBreakoutSignals = no;
def begin = rthopen;
# Entry Calculations.  Note: Only parses on a Strategy Chart
def entry = EntryPrice();

input showSignal = no;
plot Buy_Signal = RTH and BuySignal[0];
Buy_Signal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_UP);
Buy_Signal.SetDefaultColor(Color.CYAN);
Buy_Signal.SetLineWeight(4);
Buy_Signal.HideTitle();
Buy_Signal.SetHiding(!showSignal);

plot Sell_Signal =  RTH and SellSignal[0];
Sell_Signal.SetPaintingStrategy(PaintingStrategy.BOOLEAN_ARROW_DOWN);
Sell_Signal.SetDefaultColor(Color.MAGENTA);
Sell_Signal.SetLineWeight(4);
Sell_Signal.HideTitle();
Sell_Signal.SetHiding(!showSignal);

#Vertical Lines
#AddVerticalLine(showVerticalExceedPrevCvol and !IsNaN(cvolpassprevsig), "                 " + secondselapsed + "s / " + aggregationInSeconds + " | " + percntelapsed + "%", Color.CYAN);
#AddVerticalLine(showVerticalCycleEndCvol and test, "Lngth " + cyclelength[1] + "  CVol " + prevcumulativehigh + "  B/S " + Round((cb[1] / vc[1]) * 100, 0) + "/" + +Round((cs[1] / vc[1]) * 100, 0) + "%", Color.GRAY, Curve.FIRM);

#Labels

input showCycleLengthLabel = yes;
input showPrevCycleLengthLabel = yes;
input showCycleAvgLengthLabel = no;
input showTotalCyclesLabel = no;
input showSecsElapsedLabel = yes;
input showCumulativeVolLabel = yes;
input showBuyStrLabel = yes;
input showSellStrLabel = yes;
input showPrevCVolLabel = yes;
input showRelToPrevCVolLabel = yes;
input showProjectedVolLabel = yes;
input showProjMultiplierLabel = no;


AddLabel(showCycleLengthLabel, "Cycle Length: " + cyclelength[1], Color.GRAY);
AddLabel(showPrevCycleLengthLabel, "Prev Cycle Length: " + cyclehigh, Color.GRAY);
AddLabel(showCycleAvgLengthLabel, "Cycle Avg Length: " + cycleavg, Color.GRAY);
AddLabel(showTotalCyclesLabel, "Cycles Since Start: " + min, Color.GRAY);
AddLabel(showSecsElapsedLabel, "Secs " + secondselapsed + "/" + aggregationInSeconds + "   " + percntelapsed + "%", Color.YELLOW);
AddLabel(showCumulativeVolLabel, "CVol: " + vc, Color.WHITE);
AddLabel(1, "BuyStr: " + Round(cb, 0) + " / " + Round((cb / vc) * 100, 2) + "%", Color.GREEN);
AddLabel(1, "SellStr: " + Round(cs, 0) + " / " + Round((cs / vc) * 100, 2) + "%", Color.RED);
AddLabel(showPrevCVolLabel, "Prev CVol: " + prevcumulativehigh, Color.WHITE);
AddLabel(showRelToPrevCVolLabel, "x" + Round(vc / prevcumulativehigh, 2) + " Prev CVol", Color.WHITE);
AddLabel(showProjectedVolLabel and toggleProjection == toggleProjection.enabled, "Proj Vol: " + Round(projection, 0), Color.DARK_ORANGE);
AddLabel(showProjMultiplierLabel and toggleProjection == toggleProjection.enabled, "Proj Multiplier x" + Round(multiplier, 2), Color.DARK_ORANGE);

AddChartBubble(!IsNaN(close) and IsNaN(close[-1]), high,
        if RTH and  VDiff < 0 then
        " * S E L L _ A L E R T * " + " * Strenght " + VDiff + "% " else
        if VDiff > 0 then
         " * B U Y _ A L E R T * " + " * Strenght " + VDiff + "% " else
        " * H O L D * ",
        if VDiff+10 >0 then Color.GREEN  else
        if VDiff>0 then Color.DARK_GREEN else
        if VDiff-10<0 then Color.RED else
        if VDiff<0 then Color.DARK_RED else
        Color.YELLOW);

#CVol.SetDefaultColor(Color.DARK_GRAY);
#CVol.AssignValueColor(if toggleProjection == toggleProjection.disabled and Pos then Color.GREEN else if Neg then Color.RED else Color.GRAY);
#CVol.SetLineWeight(2);
#prevchigh.SetPaintingStrategy(PaintingStrategy.HORIZONTAL);
#prevchigh.SetDefaultColor(Color.YELLOW);
#projection.SetDefaultColor(Color.DARK_ORANGE);
#projection.AssignValueColor(if Pos then Color.GREEN else if Neg then Color.RED else Color.GRAY);
#projection.SetLineWeight(2);
#cvolpassprevsig.SetPaintingStrategy(PaintingStrategy.POINTS);
#cvolpassprevsig.SetLineWeight(3);

#AddCloud(if showCumulativeStr then cbuy else NA, csell, Color.GREEN, Color.RED);
#AddCloud(if showCumulativeStrDiff then bsdiff else NA, prevchigh, Color.GREEN, Color.RED);
#AddCloud(projection,   CVol,   CreateColor(0, 100, 200),   CreateColor(0, 100, 200));
#AddCloud(CVol,   0,   Color.DARK_GRAY,   Color.DARK_GRAY);
#AddCloud(CVol,   prevchigh,   Color.YELLOW,   Color.BLACK);
 
Last edited:
CDJay

CDJay

Member
VIP
@StockT8er, I didn't know much about TOS strategies, so I just read up on them, bu am still unclear. What do you find beneficial about using this as a strategy versus study?
 
BenTen

BenTen

Administrative
Staff
VIP
@CDJay The point of having a backtesting strategy is to figure out whether a study can generate profitable signals or not and over which period of time. I hope that makes sense.
 

Similar threads

Top