Friday, April 22, 2011

Volatility Based Position Sizing and Choppiness Index easy language code

I don't really pay much attention to this little blog anymore but I've noticed looking at the stats that two of my most popular posts deal with volatility based position sizing and Bill Dreiss's choppiness index. So in the spirit of open source, I'm releasing my code here. Hopefully it is helpful to someone out there.


Inputs: InvestmentCapital (70000),
PercentRisk(.2),
MaxPercentAllocation(50),
StopFactor(.025), {volatility based stop}
ProfitFactor(3);

Variables: DollarRisk(0), NumShares(0), Vx(0), timeofentry(0);
Variables: HMax(0), LMax(0), Period(14), Choppiness(0);

DollarRisk = InvestmentCapital*PercentRisk/100;
Vx = SquareRoot(AvgTrueRange(50));

NumShares = DollarRisk/(Close[0]*Vx*StopFactor);
SetStopShare;
SetStopLoss(Close[0]*Vx*StopFactor);
If ProfitFactor > 0 then Begin
SetStopShare;
SetProfitTarget(AbsValue(Close[0]*Vx*StopFactor*ProfitFactor));
End;

If NumShares*Close[0] > MaxPercentAllocation/100*InvestmentCapital then Begin
NumShares = 0;
End;

NumShares = Round(NumShares, 0);

HMax = MaxList(Highest(Close[1], Period));
LMax = MinList(Lowest(Close[1], Period));
If Hmax = Lmax then Hmax=Hmax+.00001;
Choppiness = 100.0 * Log(Summation(TrueRange,Period)/(HMax -LMax)) / Log(Period);