# Distribution Testing In ThinkOrSwim

#### Huffmac90

##### Member
I'm curious has anyone attempted a difference in distributions method for the creation of indicators? (Binomial distribution for standard market activity and Poisson distribution for outliers; then use a chi squared distribution for corrections/confidence)

#### mcdon030

##### Member
yes. I have a few rsquared, pearson, etc. if you want the latest 2^3 full factorial, you can have it. it only needs a few more things to finish and start playing with it in TOS.

#### mcdon030

##### Member
Please understand my statistical aptitude equals excel sheets and consulting the oracle "google" - I’m paying for being lazy in my younger years. My intent was to shorten time between exporting files and readjusting as it's a little tedious. I’ll have a professional correct my work soon. In the event you make headway before then, I would appreciate any feedback. My apologies for the messy scripting.

note: I didn’t include the strategy, but it should get you started...

Code:
``````##    Mcdon incomplete/untested
## 2^3 full factorial lean six sigma DOE
## A B C D=AB E=AC F=BC G=ABC
## - - - + + + -
## + - - - - + +
## - + - - + - +
## + + - + - - -
## - - + + - - +
##+ - + - + - -
##- + + - - + -
## + + + + + + +
script stats {
input sig1 = 0.0;
input siga = 0.0;
input sig1v =0.0;
def sig1_ = if isnan(sig1) then 0 else sig1;
def siga_ = if isnan(siga) then 0 else siga;
## save value
def sig1v_ =if sig1_ then sig1_ else sig1v_[1];
def sigplus =if sig1_ && siga_ then sig1_ else 0;
def sigminus =if sig1_ && !siga_ then sig1_ else 0;
## Calculating the Significance of Main Effects (Solving for Means)
def sgplusTotalsum =totalsum(if sig1_ && siga_ then 1 else 0 );
def sgminusTotalsum =totalsum(if sig1_ && !siga_ then 1 else 0 );
def sgplussumv =totalsum(if sigplus then sig1v else 0 );
def sgminussumv =totalsum(if sigminus then sig1v else 0 );
def sgplusmean = sgplussumv/sgplusTotalsum;
def sgminusmean = sgminussumv/sgminusTotalsum;
def totalmean =(sgplussumv+sgminussumv ) /(sgplusTotalsum+sgminusTotalsum);
## total sum of Squares
def sumofsqur =totalsum(if sig1_ then power(sig1v,2) else 0);
##Total Effect = Difference =
def meandif =sg1plusmean-sg1minusmean;
###Calculating the Significance of Main Effects (Solving for Standard Deviation)
def sgplusvariance ==sg1plussumv-sg1plusmean ;
def sgminusvariance == sg1minussumv-sg1minusmean ;
def plussumsqrt = power(sgplusvariance,2); ## sumsqr as well
def minussumsqrt = power(sgminusvariance,2);## sumsqr as well
def plusdivide =plussumsqrt /(sg1plusTotalsum-1);
def minusdivide =minussumsqrt /(sg1minusTotalsum-1);
def plusstdev =sqrt(plusdivide);
def minustdev =sqrt(plusdivide);
##Total Effect = Difference =
def stdevdif =plusstdev-minustdev;
##Calculating the Significance of Main Effects (Solving for Signal-to-Noise)
def plusStN = log(sgplusmean/plusstdev);
def minusStN = log(sgminusmean/minustdev);
##Total Effect = Difference =
plot StNdif = plusStN-minusStN;
}
##ANOVA Table
## Df = Degrees of freedom MS = Mean Sum of Squares
## SS = Sum of Squares F = F-test characteristic
## Alpha = F-test probability
#############
############# inputs
def stcA = STCs and afterentrycount>=1 and LGhbrydcrs[1];
def stcB = STCs and afterentrycount>=1 and close[-1] crosses below LGhybridFLT;
def stcC = STCs and afterentrycount>=1 and (GAMoneyFlowIndex[-1] < GAMoneyFlowIndex and LGhybridfullD[-1]> over_bought);
#### Calculating the Grand Average
def grandav = stats(STCs, exitpricSTC - entryPricBTO[1],winloss).totalmean;
## Factor Sum of Squares
##(Linear Contrast Effect)^2/((1/n low level)+ (1/n high level)); n = number of data point
## SS = Sum of Squares
def Aav = power(stats(STCs, stcA,winloss).meandif,2)/.5;
def Bav = power(stats(STCs, stcB,winloss).meandif,2)/.5;
def Cav = power(stats(STCs, stcC,winloss).meandif,2)/.5;
def Dav = power(stats(STCs, stcA && stcB ,winloss).meandif,2)/.5; #AB
def Eav = power(stats(STCs, stcA && stcC ,winloss).meandif,2)/.5; #AC
def Fav = power(stats(STCs, stcB && stcC ,winloss).meandif,2)/.5; #BC
def Gav = power(stats(STCs,stcA && stcB && stcC ,winloss).meandif,2)/.5; #ABC
sumofsquares
## Factor Sum of Squares
def totalsumsqr =power(stats(STCs, exitpricSTC - entryPricBTO[1],winloss).sumofsqur;
def df =1;
##MS = Mean Sum of Squares
def Ams =Aav /df;
def Bms =Bav /df;
def Cms =Cav /df;
def Dms =Dav /df;
def Ems =Eav /df;
def Fms =Fav /df;
def Gms =Gav /df;
## F = F-test characteristic
def Af =Ams /Gms;
def Bf =Bms /Gms;
def Cf =Cms /Gms;
def Df =Dms /Gms;
def Ef =Ems /Gms;
def Ff =Fms /Gms;
##   Alpha = F-test probability
def
def
def
## confidence

def
def
#######################################################################
#######################################################################
######## mcdon simple frequency no issues
script stats {
input sum =0.0;
input mean =0.0;
def variance =sum- mean ;
def sumsqrt = power(variance,2);
def divide =sumsqrt /(sum-1);
plot dev =sqrt(divide);
def StN = log( mean/dev ); #sig to noise
}
def stcsums1 = TotalSum(if IsNaN(stc1s) then 0 else stc1s);
def stcsums2 = TotalSum(if IsNaN(stc2s) then 0 else stc2s);
def stcsums3 = TotalSum(if IsNaN(stc3s) then 0 else stc3s);
def stcsums4 = TotalSum(if IsNaN(stc4s) then 0 else stc4s);
def totalssum =stcsums1 +stcsums2 +stcsums3 +stcsums4;
def sStd1 = stats(totalssum,stcsums1);
def sNs1 = stats(totalssum,stcsums1).StN;
def stcsumf1 = TotalSum(if IsNaN(stc1f) then 0 else stc1f);
def stcsumf2 = TotalSum(if IsNaN(stc2f) then 0 else stc2f);
def stcsumf3 = TotalSum(if IsNaN(stc3f) then 0 else stc3f);
def stcsumf4 = TotalSum(if IsNaN(stc4f) then 0 else stc4f);
def totalfsum =stcsumf1 +stcsumf2 +stcsumf3 +stcsumf4;
" Su1 : ( " + aspercent(stcsums1/totalssum*1)+ " )"
+" std1 : ( " + (sStd1)+ " )"+" sSN1 : ( " + (sNs1 )+ " )"
+" Su2 : ( " + aspercent(stcsums2/totalssum*1)+ " )"
+" Su3 : ( " + aspercent(stcsums3/totalssum*1)+ " )"
+" Su4 : ( " + aspercent(stcsums4/totalssum*1)+ " )"
+" fa1 : ( " + aspercent(stcsumf1/totalfsum*1)+ " )"
+" fa2 : ( " + aspercent(stcsumf2/totalfsum*1)+ " )"
+" fa3 : ( " + aspercent(stcsumf3/totalfsum*1)+ " )"
+" fa4 : ( " + aspercent(stcsumf4/totalfsum*1)+ " )"
,  if winratio>.75 then color.green else Color.WHITE);

############################  incomplete but Pearson works
script stats {
input signalin = 0.0;
input signalx = 0.0;
input signaly = 0.0;
input signalinx = 0.0;
input signaliny = 0.0;
######################## lock
def signalin_ = if isnan(signalin) then 0 else signalin;
def signalx_ = if isnan(signalx) then 0 else signalx;
def signaly_ = if isnan(signaly) then 0 else signaly;
## save value
##3 x value at y
def signalxv =if signalin_ then signalinx else signalxv[1];
def signalyv =if signaly_ then signaliny else signalyv[1];
#########################
def totalsum =totalsum(if signalin_ then 1 else 0 );
def sigXsum = totalsum(if signaly_ then signalxv else 0 );
def sigYsum = totalsum(if signaly_ then signalyv -signalyv[1] else 0 );
def sigXmean = sigXsum /totalsum;
def sigYmean = sigYsum /totalsum;
def newmean = totalsum-totalsum(if signaly_ then signalyv -signalyv[1] else 0 )/totalsum;
def sigXYsum = totalsum( if signaly_ then sigXsum* sigYsum else 0 );
def sigX2sum = Totalsum( if signaly_ then power(sigXsum,2) else 0 );
def sigY2sum = Totalsum( if signaly_ then power(sigYsum,2) else 0 );
def sumofallsquares =sigY2sum+sigY2sum;
def sumxxx = sigYsum /totalsum ;
plot SigPearson =((totalsum*sigXYsum)-(sigXsum*sigYsum))/(SQRT((totalsum*sigX2sum-power(sigXsum,2))*(totalsum*sigY2sum-power(sigYsum,2))));
#########################
######################## nothing below has been tested or reviewed
### ttest = (((sigYsum+totalsum)/2)-((sigYsum+totalsum)/2)-0)/sqrt(
def square =sqr(totalsum -SigPearson );
## def stdev =(1/2)*square ;
def sqrt =sqrt( square );
def Rsquared = power(SigPearson,2);
###def mean =(sigX2sum/totalsum +sigY2sum/totalsum ) ; ## this works
def mean =( sigXsum+ sigYsum)/totalsum ; ## this works
##def stdev= sqrt(power((sigYsum-mean),2))/(totalsum-1);
def stdev= sqrt(power((sigXsum-mean),2)+power((sigYsum-mean),2))/(totalsum-1); ## this works
def SN = log(mean/stdev);
def MSF =  mean/1;
### it works def mean =  sigXYsum/totalsum ;
### def stdev = sqrt(
def var1 = power(SigPearson ,2 )*sigYsum;
def var2 = power(SigPearson,2 )*sigXsum;
def correlation = var1 /var2;
def Rsquared2 = power(mean ,2);
def variance = (sigXsum-mean);
def variance2 = (sigYsum-mean);
def Fdist = variance /variance2;
def covarab = (sigXYsum/totalsum) -(sigxsum/totalsum) *(sigYsum/totalsum);
def varb = sqr(sigYsum *(sigYsum/totalsum))/totalsum;
def beta = covarab/varb;
def Zscorevalue = ((sigYsum-mean )/stdev );
def a = ((totalsum*sigXYsum)-(sigXsum*sigYsum))/SQRT(totalsum*sigX2sum-power(sigXsum,2)) ;
def conf = 1-a;
def nreturnssquare = Totalsum( if signaly_ then power(log(sigYsum),2) else 0 );
}``````

Last edited by a moderator:

#### 2sureshk

##### Member
Please understand my statistical aptitude equals excel sheets and consulting the oracle "google" - I’m paying for being lazy in my younger years. My intent was to shorten time between exporting files and readjusting as it's a little tedious. I’ll have a professional correct my work soon. In the event you make headway before then, I would appreciate any feedback. My apologies for the messy scripting.

note: I didn’t include the strategy, but it should get you started...

## Mcdon incomplete/untested
## 2^3 full factorial lean six sigma DOE
## A B C D=AB E=AC F=BC G=ABC
## - - - + + + -
## + - - - - + +
## - + - - + - +
## + + - + - - -
## - - + + - - +
##+ - + - + - -
##- + + - - + -
## + + + + + + +
script stats {
input sig1 = 0.0;
input siga = 0.0;
input sig1v =0.0;
def sig1_ = if isnan(sig1) then 0 else sig1;
def siga_ = if isnan(siga) then 0 else siga;
## save value
def sig1v_ =if sig1_ then sig1_ else sig1v_[1];
def sigplus =if sig1_ && siga_ then sig1_ else 0;
def sigminus =if sig1_ && !siga_ then sig1_ else 0;
## Calculating the Significance of Main Effects (Solving for Means)
def sgplusTotalsum =totalsum(if sig1_ && siga_ then 1 else 0 );
def sgminusTotalsum =totalsum(if sig1_ && !siga_ then 1 else 0 );
def sgplussumv =totalsum(if sigplus then sig1v else 0 );
def sgminussumv =totalsum(if sigminus then sig1v else 0 );
def sgplusmean = sgplussumv/sgplusTotalsum;
def sgminusmean = sgminussumv/sgminusTotalsum;
def totalmean =(sgplussumv+sgminussumv ) /(sgplusTotalsum+sgminusTotalsum);
## total sum of Squares
def sumofsqur =totalsum(if sig1_ then power(sig1v,2) else 0);
##Total Effect = Difference =
def meandif =sg1plusmean-sg1minusmean;
###Calculating the Significance of Main Effects (Solving for Standard Deviation)
def sgplusvariance ==sg1plussumv-sg1plusmean ;
def sgminusvariance == sg1minussumv-sg1minusmean ;
def plussumsqrt = power(sgplusvariance,2); ## sumsqr as well
def minussumsqrt = power(sgminusvariance,2);## sumsqr as well
def plusdivide =plussumsqrt /(sg1plusTotalsum-1);
def minusdivide =minussumsqrt /(sg1minusTotalsum-1);
def plusstdev =sqrt(plusdivide);
def minustdev =sqrt(plusdivide);
##Total Effect = Difference =
def stdevdif =plusstdev-minustdev;
##Calculating the Significance of Main Effects (Solving for Signal-to-Noise)
def plusStN = log(sgplusmean/plusstdev);
def minusStN = log(sgminusmean/minustdev);
##Total Effect = Difference =
plot StNdif = plusStN-minusStN;
}
##ANOVA Table
## Df = Degrees of freedom MS = Mean Sum of Squares
## SS = Sum of Squares F = F-test characteristic
## Alpha = F-test probability
#############
############# inputs
def stcA = STCs and afterentrycount>=1 and LGhbrydcrs[1];
def stcB = STCs and afterentrycount>=1 and close[-1] crosses below LGhybridFLT;
def stcC = STCs and afterentrycount>=1 and (GAMoneyFlowIndex[-1] < GAMoneyFlowIndex and LGhybridfullD[-1]> over_bought);
#### Calculating the Grand Average
def grandav = stats(STCs, exitpricSTC - entryPricBTO[1],winloss).totalmean;
## Factor Sum of Squares
##(Linear Contrast Effect)^2/((1/n low level)+ (1/n high level)); n = number of data point
## SS = Sum of Squares
def Aav = power(stats(STCs, stcA,winloss).meandif,2)/.5;
def Bav = power(stats(STCs, stcB,winloss).meandif,2)/.5;
def Cav = power(stats(STCs, stcC,winloss).meandif,2)/.5;
def Dav = power(stats(STCs, stcA && stcB ,winloss).meandif,2)/.5; #AB
def Eav = power(stats(STCs, stcA && stcC ,winloss).meandif,2)/.5; #AC
def Fav = power(stats(STCs, stcB && stcC ,winloss).meandif,2)/.5; #BC
def Gav = power(stats(STCs,stcA && stcB && stcC ,winloss).meandif,2)/.5; #ABC
sumofsquares
## Factor Sum of Squares
def totalsumsqr =power(stats(STCs, exitpricSTC - entryPricBTO[1],winloss).sumofsqur;
def df =1;
##MS = Mean Sum of Squares
def Ams =Aav /df;
def Bms =Bav /df;
def Cms =Cav /df;
def Dms =Dav /df;
def Ems =Eav /df;
def Fms =Fav /df;
def Gms =Gav /df;
## F = F-test characteristic
def Af =Ams /Gms;
def Bf =Bms /Gms;
def Cf =Cms /Gms;
def Df =Dms /Gms;
def Ef =Ems /Gms;
def Ff =Fms /Gms;
## Alpha = F-test probability
def
def
def
## confidence

def
def
#######################################################################
#######################################################################
######## mcdon simple frequency no issues
script stats {
input sum =0.0;
input mean =0.0;
def variance =sum- mean ;
def sumsqrt = power(variance,2);
def divide =sumsqrt /(sum-1);
plot dev =sqrt(divide);
def StN = log( mean/dev ); #sig to noise
}
def stcsums1 = TotalSum(if IsNaN(stc1s) then 0 else stc1s);
def stcsums2 = TotalSum(if IsNaN(stc2s) then 0 else stc2s);
def stcsums3 = TotalSum(if IsNaN(stc3s) then 0 else stc3s);
def stcsums4 = TotalSum(if IsNaN(stc4s) then 0 else stc4s);
def totalssum =stcsums1 +stcsums2 +stcsums3 +stcsums4;
def sStd1 = stats(totalssum,stcsums1);
def sNs1 = stats(totalssum,stcsums1).StN;
def stcsumf1 = TotalSum(if IsNaN(stc1f) then 0 else stc1f);
def stcsumf2 = TotalSum(if IsNaN(stc2f) then 0 else stc2f);
def stcsumf3 = TotalSum(if IsNaN(stc3f) then 0 else stc3f);
def stcsumf4 = TotalSum(if IsNaN(stc4f) then 0 else stc4f);
def totalfsum =stcsumf1 +stcsumf2 +stcsumf3 +stcsumf4;
" Su1 : ( " + aspercent(stcsums1/totalssum*1)+ " )"
+" std1 : ( " + (sStd1)+ " )"+" sSN1 : ( " + (sNs1 )+ " )"
+" Su2 : ( " + aspercent(stcsums2/totalssum*1)+ " )"
+" Su3 : ( " + aspercent(stcsums3/totalssum*1)+ " )"
+" Su4 : ( " + aspercent(stcsums4/totalssum*1)+ " )"
+" fa1 : ( " + aspercent(stcsumf1/totalfsum*1)+ " )"
+" fa2 : ( " + aspercent(stcsumf2/totalfsum*1)+ " )"
+" fa3 : ( " + aspercent(stcsumf3/totalfsum*1)+ " )"
+" fa4 : ( " + aspercent(stcsumf4/totalfsum*1)+ " )"
, if winratio>.75 then color.green else Color.WHITE);

############################ incomplete but Pearson works
script stats {
input signalin = 0.0;
input signalx = 0.0;
input signaly = 0.0;
input signalinx = 0.0;
input signaliny = 0.0;
######################## lock
def signalin_ = if isnan(signalin) then 0 else signalin;
def signalx_ = if isnan(signalx) then 0 else signalx;
def signaly_ = if isnan(signaly) then 0 else signaly;
## save value
##3 x value at y
def signalxv =if signalin_ then signalinx else signalxv[1];
def signalyv =if signaly_ then signaliny else signalyv[1];
#########################
def totalsum =totalsum(if signalin_ then 1 else 0 );
def sigXsum = totalsum(if signaly_ then signalxv else 0 );
def sigYsum = totalsum(if signaly_ then signalyv -signalyv[1] else 0 );
def sigXmean = sigXsum /totalsum;
def sigYmean = sigYsum /totalsum;
def newmean = totalsum-totalsum(if signaly_ then signalyv -signalyv[1] else 0 )/totalsum;
def sigXYsum = totalsum( if signaly_ then sigXsum* sigYsum else 0 );
def sigX2sum = Totalsum( if signaly_ then power(sigXsum,2) else 0 );
def sigY2sum = Totalsum( if signaly_ then power(sigYsum,2) else 0 );
def sumofallsquares =sigY2sum+sigY2sum;
def sumxxx = sigYsum /totalsum ;
plot SigPearson =((totalsum*sigXYsum)-(sigXsum*sigYsum))/(SQRT((totalsum*sigX2sum-power(sigXsum,2))*(totalsum*sigY2sum-power(sigYsum,2))));
#########################
######################## nothing below has been tested or reviewed
### ttest = (((sigYsum+totalsum)/2)-((sigYsum+totalsum)/2)-0)/sqrt(
def square =sqr(totalsum -SigPearson );
## def stdev =(1/2)*square ;
def sqrt =sqrt( square );
def Rsquared = power(SigPearson,2);
###def mean =(sigX2sum/totalsum +sigY2sum/totalsum ) ; ## this works
def mean =( sigXsum+ sigYsum)/totalsum ; ## this works
##def stdev= sqrt(power((sigYsum-mean),2))/(totalsum-1);
def stdev= sqrt(power((sigXsum-mean),2)+power((sigYsum-mean),2))/(totalsum-1); ## this works
def SN = log(mean/stdev);
def MSF = mean/1;
### it works def mean = sigXYsum/totalsum ;
### def stdev = sqrt(
def var1 = power(SigPearson ,2 )*sigYsum;
def var2 = power(SigPearson,2 )*sigXsum;
def correlation = var1 /var2;
def Rsquared2 = power(mean ,2);
def variance = (sigXsum-mean);
def variance2 = (sigYsum-mean);
def Fdist = variance /variance2;
def covarab = (sigXYsum/totalsum) -(sigxsum/totalsum) *(sigYsum/totalsum);
def varb = sqr(sigYsum *(sigYsum/totalsum))/totalsum;
def beta = covarab/varb;
def Zscorevalue = ((sigYsum-mean )/stdev );
def a = ((totalsum*sigXYsum)-(sigXsum*sigYsum))/SQRT(totalsum*sigX2sum-power(sigXsum,2)) ;
def conf = 1-a;
def nreturnssquare = Totalsum( if signaly_ then power(log(sigYsum),2) else 0 );
}
Is this a TOS script? Please share the strategy idea if it is okay with you to learn

thx
SK

#### mcdon030

##### Member
Is this a TOS script? Please share the strategy idea if it is okay with you to learn

thx
SK
It will take me a little while to appropriately annotate authors to each script I compiled as the compilation was the kitchen sink, but give me a few days. And yes, it is a TOS script

#### ezrollin

##### Member
I've been wondering if there was a script that shows accumulation buying areas and distribution selling areas for swings?

#### mcdon030

##### Member
chart : https://tos.mx/hkVIFWi
the chart has a pivot strategy which ive been working on.

Code:
``````### Name: Mcdon030_kitchen_sink_tests _Version 2
## date:  2/8/2020
## notes: below
###########################################################################################################
############################################ forward fold mcdon030 ############################################
script ff {
input v1 = 0.0 ;
input v2 = 0.0;
def bn = BarNumber();
def lv1bar = HighestAll(if v1 then bn else 0);
def lbar = HighestAll(if IsNaN(close) then 0 else bn);
def va1 = fold id = 1 to lbar with t = 0 while t == 0 do if GetValue(v1, -id) then id else 0;
plot fva1 =  GetValue(v2, -va1);
}
###########################################################################################################
############################################ count mcdon030 ############################################
script cnt{
input v = 0.0;
def cnt = if v then 0 else cnt[1]+1;
plot cnt_ = cnt;
}

###########################################################################################################
############################################ inputs  ############################################
input over_bought = 79; ## daily at 79
input over_sold = 21; ## daily at 21
input KPeriod = 7;  ## daily at 7
input DPeriod = 4; ## daily at 4
input priceH = high;
input priceL = low;
input priceC = close;
input price = close;
input gamma = 0.03; ## daily at .05
input slowing_period = 3; ## daily at 3
input sigma = 6; ## daily at 6
input offset = 0.85;
input opentime=0930;
input closetime=1600;
def bn = BarNumber();
def lbar = HighestAll(if !isnan(close) then bn else 0);
def entryPrice = EntryPrice();
def pl = FPL();
###########################################################################################################
def AP=getaggregationperiod();
def daily=if AP>=aggregationPeriod.DAY then 1 else 0;
def isopen=if daily then 1 else if secondsFromTime(opentime)>=0 and secondstillTime(closetime)>=0 then 1 else 0;
###########################################################################################################
############################################  mcdon alma stoch orginial alma author: mobius ############################################
script StochALMA {
input KPeriod = 10;
input DPeriod = 10;
input priceH = high;
input priceL = low;
input priceC = close;
input slowing_period = 3;
input sigma = 6;
input offset = 0.85;
def lowest_k = Lowest(priceL, KPeriod);
def c1 = priceC - lowest_k;
def c2 = Highest(priceH, KPeriod) - lowest_k;
def FastK = if c2 != 0 then c1 / c2 * 100 else 0;
def mF = (offset * (slowing_period - 1));
def sF = slowing_period / sigma;
def SumVectorDataF = fold y = 0 to slowing_period with WS do WS + Exp(-(Sqr(y - mF)) / (2 * Sqr(sF))) * GetValue(FastK, (slowing_period - 1) - y);
def SumVectorF = fold z = 0 to slowing_period with CW do CW + Exp(-(Sqr(z - mF)) / (2 * Sqr(sF)));
def Fullk = SumVectorDataF / SumVectorF;
def mS = (offset * (DPeriod  - 1));
def sS = DPeriod / sigma;
def SumVectorDataS = fold yy = 0 to DPeriod  with WSy do WSy + Exp(-(Sqr(yy - mS)) / (2 * Sqr(sS))) * GetValue(Fullk, (DPeriod - 1) - yy);
def SumVectorS = fold zy = 0 to DPeriod  with CWy do CWy + Exp(-(Sqr(zy - mS)) / (2 * Sqr(sS)));
def FULLD = SumVectorDataS / SumVectorS;
plot StochALMA =  Fullk;
plot FullDPlot =  FULLD;
}
###########################################################################################################
############################################  mobius stochastic Gaussian ############################################
script StochasticGA {
input nK = 10;
input nD = 3;
input RangeLength = 20;
def w = (2 * Double.Pi / (RangeLength / 2));
def beta = (1 - Cos(w)) / (Power(1.414, 2.0 / RangeLength) - 1);
def alpha = (-beta + Sqrt(beta * beta + 2 * beta));
def h = Power(alpha, 4) * high + 4 * (1 - alpha) * high[1] - 6 * Power(1 - alpha, 2) * high[2]
+ 4 * Power(1 - alpha, 3) * high[3] - Power(1 - alpha, 4) * high[4];
def c = Power(alpha, 4) * close + 4 * (1 - alpha) * close [1] - 6 * Power(1 - alpha, 2) * close[2]
+ 4 * Power(1 - alpha, 3) * close [3] - Power(1 - alpha, 4) * close [4];
def l = Power(alpha, 4) * low + 4 * (1 - alpha) * low [1] - 6 * Power(1 - alpha, 2) * low[2]
+ 4 * Power(1 - alpha, 3) * low[3] - Power(1 - alpha, 4) * low[4];
def Data = 100 * ((c - Lowest(l, nK)) / (Highest(h, nK) - Lowest(l, nK)));
def K = Inertia(Data, nK);
plot D = ExpAverage(K, nD);
}
def fullk;
def fulld;
input choose = {default alma, gauss};
switch (choose ) {
case alma:
fullk =  StochALMA(KPeriod, DPeriod, priceH, priceL, priceC, slowing_period, sigma, offset);
fulld =  StochALMA(KPeriod, DPeriod, priceH, priceL, priceC, slowing_period, sigma, offset).fulldplot; ## daily used fulld
case gauss:
fullk =  StochasticGA(KPeriod, DPeriod,slowing_period).k;
fulld = StochasticGA(KPeriod, DPeriod,slowing_period).d;
}
###########################################################################################################
############################################ languere atr ############################################
script Gma {
input price = close;
input gamma = 0.2;
rec L00 = (1 - gamma) * price + gamma * L00[1];
rec L11 = -gamma * L00 + L00[1] + gamma * L11[1];
rec L22 = -gamma * L11 + L11[1] + gamma * L22[1];
rec L33 = -gamma * L22 + L22[1] + gamma * L33[1];
def FIlt2 = (L00 + 2 * L11 + 2 * L22 + L33) / 6;
def FIR2 = (price + 2 * price[1] + 2 * price[2] + price[3]) / 6;
plot Plot3 = FIlt2;
plot Plot4 = FIR2;
}

def Plot3 = gma(price, gamma ).Plot3 ;
def Plot4 = gma(price, gamma ).FIR2 ;
def htrigg =  if Plot4 <= Plot3 and Plot4[1] >= Plot3[1]  then 1 else Double.NaN;
def ltrigg =  if Plot4 >= Plot3 and Plot4[1] <= Plot3[1] then 1 else Double.NaN;
def htr = If(!IsNaN(htrigg), 1, 0);
def ltr = If(!IsNaN(ltrigg), 1, 0);
def htrbn = if htr then bn else htrbn[1];
def ltrbn = if htr then bn else htrbn[1];
def lowestbn = lowestall(min(lowestall(htrbn),lowestall(ltrbn)));
def upcnt = cnt(htr);
def dncnt = cnt(ltr);
####
# ALMA (Arnaud Legoux Moving Average)
# ALMA is based on a shifted Gaussian distribution
# Mobius
# Chat Room Request
script ALMA {
input Data = close;
input Window = 9;
input Sigma = 6;
input Offset = 0.85;
def m = (Offset * (Window - 1));
def s = Window/Sigma;
def SumVectorData = fold y = 0 to Window with WS do WS + Exp(-(sqr(y-m))/(2*sqr(s))) * getvalue(Data, (Window-1)-y);
def SumVector = fold z = 0 to Window with CW do CW + Exp(-(sqr(z-m))/(2*sqr(s)));
plot ALMA = SumVectorData / SumVector;
}

###########################################################################################################
############################################ money flow index  ############################################
###  originial author: mobius
script gprice {
input data = close;
def n = 4;
input betaDev = 0;#Floor(n / 2);
def w = (2 * Double.Pi / n);
def beta = (1 - Cos(w)) / (Power(1.414, 2.0 / betaDev) - 1 );
def alpha = (-beta + Sqrt(beta * beta + 2 * beta));
def omega = Power(alpha, 4)     * data +
4 * (1 – alpha)    * omega[1] –
6 * Power(1 - alpha, 2) * omega[2] +
4 * Power(1 - alpha, 3) * omega[3] -
Power(1 - alpha, 4) * omega[4];
plot G = omega;
}
input length = 14;
input movingavglength = 1;
def gh =gprice(high,length);
def gc =gprice(close,length);
def gl=gprice(low,length);
def gv =gprice(volume,length);
def MoneyFlowIndex ;
input MFchoose = {default standard, ALMA,gauss};
switch (MFchoose ) {
case standard:
MoneyFlowIndex = Average(MoneyFlow(high, close, low, volume, length), movingavglength);## daily used standard
case ALMA:
MoneyFlowIndex = alma(MoneyFlow(high, close, low, volume, length),movingavglength, sigma, offset);
case gauss:
MoneyFlowIndex = Average(MoneyFlow(gh, gc,gl,gv, length), movingavglength);
}
###########################################################################################################
############################################ BTO  ############################################

def BTO;
input BTO_choose = {MF_Stoch, default  LagATR,lagcnt, all};
switch (BTO_choose  ) {
case MF_Stoch:
BTO =  isopen && MoneyFlowIndex > MoneyFlowIndex[-1] and fulld < over_sold;
case LagATR:
BTO = isopen && bn>=lowestbn &&  ltr;
case lagcnt:
BTO = isopen && dncnt[1]>=5 && bn>=lowestbn &&  ltr;
case all:
BTO =isopen && bn>=lowestbn && ltr && MoneyFlowIndex > MoneyFlowIndex[-1] and fulld < over_sold;
}
def BTOs = if isnan(BTO ) then 0 else BTO;
def entryPriceBTO = if BTOs then close else entryPriceBTO[1] ;
def entryPricestop = if IsNaN(entryPrice[1]) and !IsNaN(entryPrice) then low else entryPricestop[1] ;
###########################################################################################################
############################################ STC  ############################################
def STC;
input STC_choose = {standard, LagATR,default standandATR};
switch (STC_choose ) {
case standard:
STC = isopen &&( close[-1] crosses below entryPriceBTO or  MoneyFlowIndex[-1] < MoneyFlowIndex and fullk > over_bought);
case LagATR:
STC =isopen && close[-1] crosses below Plot3;
case standandATR:
STC = isopen &&
(close[-1] crosses below entryPricestop
or (close[-1] crosses  Plot3)
or htr
or  (MoneyFlowIndex[-1] < MoneyFlowIndex and fulld[-1] > over_bought));
}
def STCs = if isnan(STC) then 0 else STC ;
def exitpriceSTC = if STCs then close else exitpriceSTC[1];
###########################################################################################################
############################################ trade limit price etc ############################################
def afterEntryCount = if IsNaN(entryPrice[1]) and !IsNaN(entryPrice)
then 1
else if !IsNaN(entryPrice)
then afterEntryCount[1] + 1
else Double.NaN;
def BTOopen = if BTO
then 1
else if STC[1]
then 0
else BTOopen[1];
def limitbuy = if !BTOopen and BTOopen[1]
then 0
else if BTOopen and !BTOopen[1]
def BTOsig = limitbuy==1 and BTOopen and !BTOopen[1];
AddOrder(OrderType.SELL_TO_CLOSE,STCsig[-1]&& afterEntryCount>=1,tickcolor = GetColor(2), arrowcolor = GetColor(2), name = "kitchen_lx");
###########################################################################################################
############################################ stats  ############################################
### mcdon   : distribution
script stats {
input sum =0.0;
input mean =0.0;
def variance =sum- mean ;
def sumsqrt = power(variance,2);
def divide =sumsqrt /(sum-1);
plot dev =sqrt(divide);
def StN = log( mean/dev ); #sig to noise
}
def successtrade =  STCs and afterentrycount>=1 and  exitpriceSTC > entryPriceBTO;
def failuretrade =  STCs and afterentrycount>=1 and  exitpriceSTC < entryPriceBTO;
def WinRatio = (TotalTargetReached / (TotalTargetReached + TotalTargetfailures )   * 1);
def total = TotalSum(IsNaN(entryPrice[1]) and !IsNaN(entryPrice));
def winloss = if STCsig  then exitpriceSTC - entryPriceBTO[1] else winloss[1];
def stc1f =  STCsig and  close[-1] crosses below entryPricestop and  winloss<0;
def stc2f =  STCsig and close[-1] crosses  Plot3 and  winloss<0;
def stc3f =  STCsig and htr and  winloss<0;
def stc4f =  STCsig and (MoneyFlowIndex[-1] < MoneyFlowIndex and fulld[-1]> over_bought) and  winloss<0;
def stc1s =  STCsig and  close[-1] crosses below entryPricestop and  winloss>0;
def stc2s =  STCsig and close[-1] crosses  Plot3 and   winloss>0;
def stc3s =  STCsig and htr and   winloss>0;
def stc4s =  STCsig and (MoneyFlowIndex[-1] < MoneyFlowIndex and fulld[-1] > over_bought) and   winloss>0;
def stcsums1 = TotalSum(if IsNaN(stc1s) then 0 else stc1s);
def stcsums2 = TotalSum(if IsNaN(stc2s) then 0 else stc2s);
def stcsums3 = TotalSum(if IsNaN(stc3s) then 0 else stc3s);
def stcsums4 = TotalSum(if IsNaN(stc4s) then 0 else stc4s);
def totalssum =stcsums1 +stcsums2 +stcsums3 +stcsums4;
def sStd1 = stats(totalssum,stcsums1);
def sNs1 = stats(totalssum,stcsums1).StN;
def stcsumf1 = TotalSum(if IsNaN(stc1f) then 0 else stc1f);
def stcsumf2 = TotalSum(if IsNaN(stc2f) then 0 else stc2f);
def stcsumf3 = TotalSum(if IsNaN(stc3f) then 0 else stc3f);
def stcsumf4 = TotalSum(if IsNaN(stc4f) then 0 else stc4f);
def totalfsum =stcsumf1 +stcsumf2 +stcsumf3 +stcsumf4;

###########################################################################################################
############################################ labels  ############################################
" P/L : (" +asDollars(pl) +
" ) Total Trade: (" +total
+" ) SuccessRAte: ( " + AsPercent(WinRatio) + " )",
if winratio>=.70 then color.green else Color.WHITE);
" Signal Inputs: "
+ " MFchoose ( " + MFchoose  + " )"+ "  MF Length ( " + length  + " )"
+ "  Stoch: ( " + choose  + " )"
+"  Kperiod: ( " + KPeriod  + " )"
+ "  Dperiod: ( " + DPeriod  + " )"
+ "  BTO: ( " +BTO_choose+ " )"
+ "  STC: ( " +STC_choose+ " )"
,  Color.WHITE);

" Su1 : ( " + aspercent(stcsums1/totalssum*1)+ " )"
+" std1 : ( " + (sStd1)+ " )"+" sSN1 : ( " + (sNs1 )+ " )"
+" Su2 : ( " + aspercent(stcsums2/totalssum*1)+ " )"
+" Su3 : ( " + aspercent(stcsums3/totalssum*1)+ " )"
+" Su4 : ( " + aspercent(stcsums4/totalssum*1)+ " )"
+" fa1 : ( " + aspercent(stcsumf1/totalfsum*1)+ " )"
+" fa2 : ( " + aspercent(stcsumf2/totalfsum*1)+ " )"
+" fa3 : ( " + aspercent(stcsumf3/totalfsum*1)+ " )"
+" fa4 : ( " + aspercent(stcsumf4/totalfsum*1)+ " )"
,  if winratio>.70 then color.green else Color.WHITE);``````

#### mcdon030

##### Member
I've been wondering if there was a script that shows accumulation buying areas and distribution selling areas for swings?

check the chart I just posted. it count swings from higher high and lower low using an ATR posted here. additionally, the pivot creates a zz which i believe is more advanced than what TOS has. It has second and third order pivots and identifies Double Tops and bottoms.

#### ProcrastinatingPerfection

##### Member
Does anyone have the rules for trading this. I want to try it trading the SPY with options.

#### mcdon030

##### Member
Does anyone have the rules for trading this. I want to try it trading the SPY with options.
The topic of this discussion is distribution testing to create indicators. Some of my posts are more geared toward distribution testing to combine preexisting indicators to optimize settings and create rules - meaning, rules haven't been created yet. Additionally, there are 21 settings to the script I posted and the script is incomplete at this time.

That said, I left some setting comments as a starting point so you could start there. Those settings derive from accurate and professionally tested data analysis which I'm trying to build into TOS.

#### mcdon030

##### Member
not yet. I would like to optimize long signals first. I noticed one issue, it has been updated: https://tos.mx/Zhklm0W

You should review the script itself. Comments are there to understand how to run each test, variables, etc. If you find anything of note, which would be success rate >=%70 and A, B or C being >=%80, then please respond.

For example, once you find those numbers, test multiple futures, etfs, etc. If you see the same results, it's worth looking into it.

#### codydog

##### Active member
Hi mcd- Great work - very useful tool, thanks! I really like the entrylvl/stop and am wondering if you think when price trades through it, it acts like a reverse signal.

When I used to use tos' FloatingPL script, I found quite often that the report function showed that most executions were at prices a mere human could never achieve. I was saddened many times as my p&l never came close to what tos thought it should be!

I hesitate to fiddle with your script, but am wondering if you would consider converting it to a study(from a strategy), and use arrows to show where the script would enter buy/sell signals.

Thanks again for the work and share.

#### mcdon030

##### Member
@codydog

I am aware of that issue and have already created one. it aligns perfectly with the strategy https://tos.mx/xymrHrP

Additionally, I updated with an additional input test the relationships between signal A and B to C. Selecting STCDchoose with nosigwin and nosigloss is important as you can judge which signal correlates. I would suggest reading some lean sig sigma material on DOE 3 factor 2 level testing

Code:
``````def stcCn;
def stcCd;
input STCDchoose = { default standard, nosigwin,nosigloss};
switch (STCDchoose) {
case standard:
stcCn=if  STCs and BTOsC and afterentrycount>=1then 1 else 0;
stcCd =1;
case  nosigwin:
stcCn =if STCs and  exitpriceSTC > entryPriceBTO and afterentrycount>=1 then 1 else 0;
stcCd =2;
case nosigloss:
stcCn =if STCs and  exitpriceSTC < entryPriceBTO and afterentrycount>=1 then 1 else 0;
stcCd =3;
}``````

#### codydog

##### Active member
Hi mcd,

Thanks!

I made a tiny change, and not very elegant - to make the arrows more visible in the study,

input boffset = 1;
plot bullentry = if BTOsig then low - boffset * ticksize() else double.nan;
plot bullexit = if STCsig then high + boffset * ticksize() else double.nan;

Also added a yes/no for the labels (in white) to save some screen space, but thats just personal preference.

#### mcdon030

##### Member
excellent; thanks. Any help is appreciated.

##### Well-known member
VIP
If you find anything of note, which would be success rate >=%70 and A, B or C being >=%80, then please respond.

mcdon030, Checked out your script after finishing my morning trades. Wow! SFIX on a 5-day 15 minute chart has 93% success rate but no data for A,B,C. On 180-day 15 min chart, success rate is down to 74% but A and B are both above 90%. C and D are above 90% on 5-day 3 min chart. I'm sure going to be watching this next week. Thank you for sharing!

#### mcdon030

##### Member
mcdon030, Checked out your script after finishing my morning trades. Wow! SFIX on a 5-day 15 minute chart has 93% success rate but no data for A,B,C. On 180-day 15 min chart, success rate is down to 74% but A and B are both above 90%. C and D are above 90% on 5-day 3 min chart. I'm sure going to be watching this next week. Thank you for sharing!
thank you for sharing. It helps . When there is no data, it means one or two of the three(A,B,C) don't have values or more need more values to calculate. The indicator itself is really not what I think is important - It's perfecting signals and/or combining different indicators to create trade rules with confidence. Sharpe has very similar math, but I've read there is some downside. I hope this compliments current metrics, such as Sharpe, CAG,ROR, etc, but it's definitely a faster way to analyze than downloading cvs reports, uploading that report, review and do it all over again.

Plus I have no patients so a workable ANOVA Model is more valuable to me.

## The Market Trading Game Changer

Join 2,500+ subscribers inside the useThinkScript VIP Membership Club
• Exclusive indicators
• Proven strategies & setups
• Private Discord community
• Exclusive members-only content
• 1 full year of unlimited support

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?