using System; using System.Collections.Generic; using System.Text; using System.Drawing; using WealthLab; using WealthLab.Indicators; using System.Linq;namespace WealthLab.Strategies { public class Signature { public int Bar; public string Sig; public double ROC; public Signature( int Bar, string Sig, double ROC ){ this.Bar = Bar; this.Sig = Sig; this.ROC = ROC;} } public class TASC201502 : WealthScript { private StrategyParameter paramTop; private StrategyParameter paramRoc; public TASC201502() { paramTop = CreateParameter("Top N",10,1,10,1); paramRoc = CreateParameter("ROC period",1,1,10,1); } protected override void Execute() { int roc = paramRoc.ValueInt; const char tab = '\u0009'; int halfData = Bars.Count / 2; // For in-sample and out-of-sample int oosBar = Bars.Count - halfData; int segmentCount = 5; double segmentDivisor = 100d / (double)segmentCount; List<Signature> lstSig1 = new List<Signature>(); if (Bars.Count < roc ) { DrawLabel(PricePane, "Insufficient data"); Abort(); } for(int bar = GetTradingLoopStartBar(10); bar < Bars.Count; bar++) { List<string> lstSig = new List<string>(); double open = Open[bar], high = High[bar], low = Low[bar], close = Close[bar]; double averageRange = ATR.Series(Bars,10)[bar]; double candleRange = high - low; double rangeMultiplier = candleRange / averageRange; candleRange = candleRange /= 100d; rangeMultiplier = rangeMultiplier > 1 ? 1.0 : rangeMultiplier; double HO = Math.Round((((high - open) / candleRange) * rangeMultiplier) / segmentDivisor); double HC = Math.Round((((high - close) / candleRange) * rangeMultiplier) / segmentDivisor); double OL = Math.Round((((open - low) / candleRange) * rangeMultiplier) / segmentDivisor); //Candle signature = HO-HC-OL var sig = HO+":"+HC+":"+OL; if( bar < oosBar ) lstSig1.Add(new Signature(bar,sig,ROC.Series(Close,roc)[bar+1])); else { if (IsLastPositionActive) { SellAtClose(bar,LastPosition); } else { var listSignaturesOOS = lstSig1.OrderBy(p => p.ROC).Reverse().Take(paramTop.ValueInt).ToList(); foreach(var s in listSignaturesOOS ) { if( sig == s.Sig ) { int count = lstSig1.Count( t => t.Sig == sig ); AnnotateBar(s.Sig,bar,true,Color.Blue); BuyAtClose(bar); break; } } } } } var listSignaturesIS = lstSig1.OrderBy(p => p.ROC).Reverse().Take(paramTop.ValueInt).ToList(); DrawLabel(PricePane, "Most frequent signatures from in-sample period containing 50% data: " + "\n\r"); DrawLabel(PricePane, "Signature:" + tab + "Count:" + tab + "% Change next bar:"); foreach(var s in listSignaturesIS ) { int count = lstSig1.Count( t => t.Sig == s.Sig ); DrawLabel(PricePane, s.Sig + tab + tab + count + tab + Bars.FormatValue(s.ROC)); AnnotateBar(s.Sig,s.Bar,true,Color.Black); } AnnotateBar("Out of sample starts",oosBar,true,Color.Red); for( int bar = 0; bar < oosBar; bar++ ) SetBackgroundColor(bar,Color.FromArgb(30,Color.Blue)); } } }