Kpl Swing Trading System AFL Code

download Kpl Swing Trading System AFL Code

of 21

Transcript of Kpl Swing Trading System AFL Code

  • 8/17/2019 Kpl Swing Trading System AFL Code

    1/21

    KPL Swing (breakout trading system)

    KPL Swing (breakout trading system)

    The KPL Swing is a simple trend following mechanical trading system which automates the entry and exit.

    The trading system is extremely simple and easy to use, works across multiple

     time frames and does not require any in-depth knowledge of TA. It is somewhat similar to the turtle trading system.

    The trading or investing logic is simple.... buy new highs (strength) and sell new lows (weakness). The default entry or decision level for long positions is a close above 20 days highest high.

    The system follows a trailing stoploss for exit with profitable trades. No targets are given as no one knows how high (or low) a stock can move. Profits arewhatever the market gives. A trailing stoploss locks in the gains and removes emotions from trading.

    Respect for stoplosses is a mandatory requirement. If you cannot follow stopl

    osses, you should stay out of the market completely.

    Caveat: this indicator works best with indices and highly liquid stocks. It is not recommended for stocks with poor liquidity as freak trades often distort the value of the breakout level (high or low).

    Code for Amibroker AFL is posted at the end of this page.

    How to use indicator in Amibroker:

    Example charts: NIFTY 60min- SBI 60min - Wipro Dly - Asian Paint Dly - Tatamotors Dly - Reliance Weekly

    - Default setting: N=20. Higher values (30, 50, 100 etc) will give fewer but far more reliable trades.
    - Timeframe and charts: daytraders/ swing traders (30 min), positional traders (daily) and long term investors (weekly/ monthly).
    - Smaller the timeframe or N, higher the number of trades and whipsaws.
    - Ignore signals if market is rangebound. Eg., if market is trading within lastmonth's range, ignore signal on daily chart.
    - Entry trade: Initiate a long trade when indicator gives a BUY (stock closes for the first time above the 20 days or 20 weeks highest high).

  • 8/17/2019 Kpl Swing Trading System AFL Code

    2/21

    - Stoploss: Keep a "hard stoploss" few points below the Signal bar LOW.
    - Trend reversal: Exit trade when indicator gives a SELL (Exit long positions).<br>- Position sizing: always follow this to determine trade quantity...this will automatically limit losses to a predefined value irrespective of stock price.- Always paper trade before trading with actual cash.

    - You can use a ATR based trailing stoploss (highly recommended). This is a built-in indicator in Amibroker and will give excellent returns / fast exits. Use ATR(20).
    - You can use the same code in Scanner mode to generate Buy/ Sell signals.

    Position sizing - How much quantity to buy? Use position sizing and limit loss to Rs.500/- per trade.

    Qtty = 500/ (Purchase price - hard stoploss).

    Eg. You want to buy a stock trading at Rs.100/- with a stoploss Rs.90. The quantity you shd trade is 500/(100-90) = 50 shares. So if your stoploss gets hit,you shd exit and your max loss will be Rs.500/-.

    And finally, the code....Amibroker AFLs

    Note: the current bar is always dynamic so for intraday purposes, you shouldevaluate the signal only after the current bar is complete.

     _SECTION_BEGIN("KPL Swing");//Copyright Kamalesh Langote. Email:[email protected]. Visit http://www.vfmdirect.com/kplswing for latest code and updates//Copy & paste formula in NotePad and save file as "kplswing.afl" in C: ProgramFiles > Amibroker > Formulas > Custom folder. To use just drag and drop from Indicator list (custom) on price chartno=Param( "Swing", 20, 1, 100 );

    res=HHV(H,no);sup=LLV(L,no);avd=IIf(C>Ref(res,-1),1,IIf(C

    // line codePlot(tsl, _DEFAULT_NAME(), colorTan, styleStaircase);

    // ribbon codePlot( 2, "Ribbon",IIf(C>tsl,colorBlue,colorRed),styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );

    // arrows codeBuy=Cross(C,Ref(res,-1));Sell=Cross(Ref(sup,-1),C);shape=Buy*shapeUpArrow + Sell*shapeDownArrow;PlotShapes(shape,colorBlack,0,IIf(Buy,Low,High));

    // scanner codeBuy=Cross(C,tsl);Sell=Cross(tsl,C);

  • 8/17/2019 Kpl Swing Trading System AFL Code

    3/21

     _SECTION_END();

    Metastock users: I am no longer supporting metastock....

    ---------------------------------------------------------------------------------------------------Ichimoku Kinko Hyo trading system...!amibroker users can use the following code for the system:Code:

    //============================================================SetChartOptions(0,chartShowArrows|chartShowDates); _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) Vol " +WriteVal( V, 1.0 ) +" {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 )) ));Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );if( ParamToggle("Tooltip shows", "All Values|Only Prices" ) ){ToolTip=StrFormat("Open: %g\nHigh: %g\nLow: %g\nClose: %g (%.1f%%)\nVolume: "+NumToStr( V, 1 ), O, H, L, C, SelectedValue( ROC( C, 1 )));}

    SL = ( HHV( H, 26 ) + LLV( L, 26) )/2;TL = ( HHV( H, 9 ) + LLV( L, 9 ) )/2;DL = Ref( C, 26 );Span1 = (( SL + TL )/2);Span2 = (HHV( H, 52) + LLV(L, 52))/2;

    Plot(SL,"SL",2,styleThick); // standard, base, or kijun-sen linePlot(TL,"TL",2,styleThick); // turning, conversion, or tenkan-sen linePlot(DL,"",colorLightBlue,styleLine); // delayed, lagging, or chikou spanPlot(Span1,"",colorGreen,1,0,0,26); // senkou span A, kumo, or white clouds

  • 8/17/2019 Kpl Swing Trading System AFL Code

    4/21

    Plot(Span2,"",colorSeaGreen,1,0,0,26); // senkou span B, kumo, or white cloudsPlotOHLC(Span1,Span2,Span1,Span2,"",IIf(Span1>Span2,8,9),styleCloud|4096,0,0,26);

    //==========================================================

     _SECTION_BEGIN("SDA2 Channel Trading System");

    Derived=WMA(((H+L)/2)+(O-C),3);i=WMA(Derived,3);Upper=(Derived+StDev(Derived,7))+ATR(2)/1.5;Lower=(Derived-StDev(Derived,7))-ATR(2)/1;color=IIf(BarsSince(Cross(Lower,C))>BarsSince(Cross(C,Upper)), colorBrightGreen,colorRed);Plot(C,"",Color,64);Plot(Upper,"upper band",colorGreen);Plot(Lower,"lower band",colorDarkRed);Title=Name()+" "+Date()+" "+EncodeColor(colorBlack)+" SDA2 Channel System "+EncodeColor(colorRed)+" Vol="+NumToStr(Volume,1.0)+" "+" O="+Open+" H="+HHV(H,1)+" L="+LLV(L,1)+"Close="+ Close+""+"("+NumToStr((Close-Ref(C,-1))/Ref(C,-1)*100,1.2)+" %)";

    /* Buy or Sell Condition */

    Buy = Cross(Close,Upper);Sell = Cross(Lower,Close);Buy = ExRem(Buy,Sell);Sell = ExRem(Sell,Buy);

    Filter = Buy OR Sell;/* Exploration Parameters */AddTextColumn( FullName(), "Company Name" );AddColumn( Buy, "Buy", 1 );AddColumn( Sell, "Sell", 1 );AddColumn( C, "Close", 1.3 );AddColumn( H, "High", 1.3 );AddColumn( Lower, "Lower Band", 1.3 );

    AddColumn( Upper, "Upper Band", 1.3 );

    PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);

    PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-45);PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, H, Offset=40);PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,H, Offset=50);

    PlotShapes(IIf(Sell, shapeDownArrow, shapeNone),colorWhite, 0,H, Offset=-45);

     _SECTION_END();

    //====================================================

     _SECTION_BEGIN("MA Percentage Band");SetChartOptions(0,chartShowArrows|chartShowDates);

     _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));Plot( C, "Close", colorBlack, styleNoTitle | ParamStyle("Style") | GetPriceStyle() );

  • 8/17/2019 Kpl Swing Trading System AFL Code

    5/21

    P = ParamField("Price field",-1);Periods = Param("Periods", 200, 2, 300, 1, 10 );Percent = Param("Percentage %", 25, 1,100, 1, 10 );SelectedIndicator = ParamList( "Show", "SMA,EMA,WMA,DEMA,TEMA", 1 ); if ( SelectedIndicator == "SMA" ){Positive_Percent_Band = MA( P, Periods )+ (MA( P, Periods )*percent/100);Negative_Percent_Band = MA( P, Periods )- (MA( P, Periods )*percent/100);Plot( MA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );Plot( Positive_Percent_Band, "Positive %", ParamColor( "Color", colorCycle ), ParamStyle("Style") );Plot( Negative_Percent_Band, " Negative %", ParamColor( "Color", colorCycle ), ParamStyle("Style") );}elseif ( SelectedIndicator == "EMA" ){Positive_Percent_Band = EMA( P, Periods )+ (EMA( P, Periods )*percent/100);Negative_Percent_Band = EMA( P, Periods )- (EMA( P, Periods )*percent/100);Plot( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );Plot( Positive_Percent_Band, "Positive %", ParamColor( "Color", colorCycle ), Pa

    ramStyle("Style") );Plot( Negative_Percent_Band, " Negative %", ParamColor( "Color", colorCycle ), ParamStyle("Style") );}elseif ( SelectedIndicator == "WMA" ){Positive_Percent_Band = WMA( P, Periods )+ (WMA( P, Periods )*percent/100);Negative_Percent_Band = WMA( P, Periods )- (WMA( P, Periods )*percent/100);Plot( WMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );Plot( Positive_Percent_Band, "Positive %", ParamColor( "Color", colorCycle ), ParamStyle("Style") );

    Plot( Negative_Percent_Band, " Negative %", ParamColor( "Color", colorCycle ), ParamStyle("Style") );}elseif ( SelectedIndicator == "DEMA" ){Positive_Percent_Band = DEMA( P, Periods )+ (DEMA( P, Periods )*percent/100);Negative_Percent_Band = DEMA( P, Periods )- (DEMA( P, Periods )*percent/100);Plot( DEMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );Plot( Positive_Percent_Band, "Positive %", ParamColor( "Color", colorCycle ), ParamStyle("Style") );Plot( Negative_Percent_Band, " Negative %", ParamColor( "Color", colorCycle ), P

    aramStyle("Style") );}elseif ( SelectedIndicator == "TEMA" ){Positive_Percent_Band = TEMA( P, Periods )+ (TEMA( P, Periods )*percent/100);Negative_Percent_Band = TEMA( P, Periods )- (TEMA( P, Periods )*percent/100);Plot( TEMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );Plot( Positive_Percent_Band, "Positive %", ParamColor( "Color", colorCycle ), Pa

  • 8/17/2019 Kpl Swing Trading System AFL Code

    6/21

    ramStyle("Style") );Plot( Negative_Percent_Band, " Negative %", ParamColor( "Color", colorCycle ), ParamStyle("Style") );}

     _SECTION_END();

    //===================================================

    //Marketcalls - Counter Trend Reversal System//www.marketcalls.in

     _SECTION_BEGIN("Marketcalls - Counter Trend Reversal System");SetChartOptions(0,chartShowArrows|chartShowDates);

     _N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));

    z=(High+Low+(Close)*(2))/(4);EMAavg=((34*EMA(z,2)+21*EMA(z,3))+(13*EMA(z,5))+(8*EMA(z,8))+(5*EMA(z,13))+(3*EMA(z,21))+(2*EMA(z,34)))/(87);Plot(EMAavg,"EMAavg=",colorRed);

    Buy =C>EMAavg AND C>EMA(C,5);

    ex =C

  • 8/17/2019 Kpl Swing Trading System AFL Code

    7/21

    ( 172,172,172 )));

     _SECTION_END(); // Two adjustable parameter "Buy sensitivity" and "Buy Finetune" provided to adjust entry points.// Two adjustable parameter "Sell sensitivity" and "Sell Finetune" provided to adjust Exit points.

     _SECTION_BEGIN("KAMA System 1.0");

     

    SetChartOptions(0,chartShowArrows|chartShowDates);Title = ("KAMA SYSTEM - " + Name()+" " + Date() +" "+Interval(2) +" "+ EncodeColor(colorLime)+",Open "+Open +" ,High "+H+" ,Low "+L+" ,Close "+C+" "+"{{VALUES}}");

    //{{VALUES}}"+ O+ H+ L+C);

    //_N(Title =StrFormat("{{Name}} - {{Interval}} {{Date}} Open %g, Hi %g, Lo %g, C

    lose %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));

    // Buy adjustmentsbs=Param("BUY Sensitivity",7,2,20,1);bf=Param("BUY Finetune",2,0.1,20,0.1);

    ///uncommentf for optimization//bs=Optimize("BUY Sensitivity",7,2,20,1);//bf=Optimize("BUY Finetune",2,0.1,20,0.1);// Sell Adjustmentsss=Param("SELL Sensitivity",5,2,20,1);sf=Param("SELL Finetune",1,0.1,20,0.1);

    ///uncommentf for optimizationss=Optimize("SELL Sensitivity",5,2,20,1);sf=Optimize("SELL Finetune",1,0.1,20,0.1);

    //stock selection parametersMyCL = Param( "CL", 10, 10, 100, 10 );MyVK = Param( "VK", 30, 10, 100, 10 );MyTL = Param( "TL", 300, 100, 1000, 100 );//stock selection//TLM = EMA(C*V/100000,100) ;//include = C> MyCL AND V/1000> MyVK AND C*V/100000 > MyTL AND TLM > 0.333 * MyT

    L ;

    // commonfast = 2/(2+1);slow = 2/(30+1);//BUY partdirb=abs(Close-Ref(Close,-bs));volb=Sum(abs(Close-Ref(Close,-1)),bs);ERb=dirb/volb;scb =( ERb*(fast-slow)+slow)^2;

  • 8/17/2019 Kpl Swing Trading System AFL Code

    8/21

    xb = AMA( C, scb );flb=bf*StDev(xb-Ref(xb,-1),20);j=xb-Ref(xb,-3);

    //SELL partdirs=abs(Close-Ref(Close,-ss));vols=Sum(abs(Close-Ref(Close,-1)),ss);ERs=dirs/vols;scs =( ERs*(fast-slow)+slow)^2;xs = AMA( C, scs );fls=sf*StDev(xs-Ref(xs,-1),20);k=Ref(Xs,-3)-Xs;

    Buy=Cross(j,flb) ;Sell=Cross(k,fls);mycolor=IIf(C>xb,colorLime,colorRed);Plot( C, "Close", mycolor,styleNoTitle | styleCandle );Plot(xb,"KAMA-BUY",colorRed,1);Plot(xs,"KAMA-SELL",colorOrange,1);Buy = ExRem(Buy,Sell);Sell = ExRem(Sell,Buy);

    shape = Buy * shapeUpArrow +Sell * shapeDownArrow ;

    PlotShapes( shape, IIf( Buy, colorLime, colorRed),0, IIf( Buy, Low, High ) );

    GraphXSpace = 5;dist = 1.5*ATR(20);

    for( i = 0; i < BarCount; i++ ){if( Buy[i] ) PlotText( "Buy\n@" + C[ i ], i, L[ i ]-dist[i], colorLime );if( Sell[i] ) PlotText( "sell\n@" + C[ i ], i, L[ i ]+dist[i], colorRed );}Filter= Buy OR Sell;

    PositionScore=100/C;PositionSize = - 20;SetBarsRequired(10000, 10000);SetFormulaName("KAMA System");

     _SECTION_END();

     _SECTION_BEGIN("IIR2");// IIR2.afl//// Documentation to describe what the function does.// Second order smoother// the function statement

    function IIR2( input, f0, f1, f2 )// the function body{result[ 0 ] = input[ 0 ];result[ 1 ] = input[ 1 ];for( i = 2; i < BarCount; i++ ){result[i] = f0 * input[i] + f1 * result[i-1] + f2 * result[i-2];}// the function returns a single value and exits.

  • 8/17/2019 Kpl Swing Trading System AFL Code

    9/21

    return result;}// The routine that calls the function.SmoothedClose = IIR2(Close, 0.2, 1.4, -0.6 );//Plot( Close, "Price", 2, styleCandle );Plot( SmoothedClose, "function example", colorRed );//Figure 8.1 IIR2

     _SECTION_END();

     _SECTION_BEGIN("GSMA");SetBarsRequired(100000,0);PI = 3.1415926;

    function jIIR2( input, f0, f1, f2 ){

    result[ 0 ] = input[ 0 ];result[ 1 ] = input[ 1 ];

    for( i = 2; i < BarCount; i++ ){

    result[ i ] = f0 * input[ i ] +f1 * result[ i - 1 ] +f2 * result[ i - 2 ];

    }

    return result;}

    function GSMA( input, Period ){  N = 0;  an = 2 * PI / Period;  c0 = b0 = 1;  c1 = b1 = b2 = a1 = a2 = gamma1 = 0;  beta1 = 2.415 * ( 1- cos( an ) );  alpha = -beta1 + sqrt( beta1 ^ 2 + 2 * beta1 );  alpha1 = ( cos( an ) + sin( an ) - 1 )/cos( an );

      {  fo = alpha ^ 2;  f1 = 2 * ( 1- alpha ); f2 = -( 1 - alpha )*( 1 - alpha );  } 

    return jIIR2( input, fo,f1,f2);}period=Param("period",13,1,40,1);

    //Plot( Close, "Price", colorBlack, styleCandle );Plot( GSMA( C,period), "GSMA", colorLime );

    // Linear Regression Line with 2 Standard Deviation Channels Plotted Above andBelow// Written by Patrick Hargus, with critical hints from Marcin Gorzynski, Amibroker.com Technical Support// Designed for use with AB 4.63 beta and above, using drag and drop feature.// Permits plotting a linear regression line of any price field available on the chart for a period determined by the user.// 2 Channels, based on a standard deviation each determined by the user, are plotted above and below the linear regression line.

  • 8/17/2019 Kpl Swing Trading System AFL Code

    10/21

    // A look back feature is also provided for examining how the indicator would have appeared on a chart X periods in the past.

    P = ParamField("Price field",-1);Daysback = Param("Period for Liner Regression Line",21,1,240,1);shift = Param("Look back period",0,0,240,1);

    // =============================== Math Formula =============================================================

    x = Cum(1);lastx = LastValue( x ) - shift;aa = LastValue( Ref(LinRegIntercept( p, Daysback), -shift) );bb = LastValue( Ref(LinRegSlope( p, Daysback ), -shift) );y = Aa + bb * ( x - (Lastx - DaysBack +1 ) );

    // ==================Plot the Linear Regression Line ==========================================================

    LRColor = ParamColor("LR Color", colorCycle );

    LRStyle = ParamStyle("LR Style");

    LRLine = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y, Null );Plot( LRLine , "LinReg", LRCOLOR, LRSTYLE ); // styleDots );

    // ========================== Plot 1st SD Channel ===============================================================

    SDP = Param("Standard Deviation", 1.5, 0, 6, 0.1);SD = SDP/2;

    width = LastValue( Ref(SD*StDev(p, Daysback),-shift) ); // THIS IS WHERE THE WIDTH OF THE CHANELS IS SET

    SDU = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y+width , Null ) ;SDL = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y-width , Null ) ;

    SDColor = ParamColor("SD Color", colorCycle );SDStyle = ParamStyle("SD Style");

    Plot( SDU , "Upper Lin Reg", SDColor,SDStyle );Plot( SDL , "Lower Lin Reg", SDColor,SDStyle );

    // ========================== Plot 2d SD Channel ===============================================================

    SDP2 = Param("2d Standard Deviation", 2.0, 0, 6, 0.1);

    SD2 = SDP2/2;

    width2 = LastValue( Ref(SD2*StDev(p, Daysback),-shift) ); // THIS IS WHERE THE WIDTH OF THE CHANELS IS SETSDU2 = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y+width2 , Null ) ;SDL2 = IIf( x > (lastx - Daysback) AND BarIndex() < Lastx, y-width2 , Null ) ;

    SDColor2 = ParamColor("2 SD Color", colorCycle );SDStyle2 = ParamStyle("2 SD Style");

  • 8/17/2019 Kpl Swing Trading System AFL Code

    11/21

    Plot( SDU2 , "Upper Lin Reg", SDColor2,SDStyle2 );Plot( SDL2 , "Lower Lin Reg", SDColor2,SDStyle2 );

    // ============================ End Indicator Code ==============================================================

    //Fibonacci cluster

     _SECTION_BEGIN("Background");SetChartOptions(0,chartShowArrows|chartShowDates);SetChartBkColor(ParamColor("Outer panel",colorWhite)); // color of outer

     borderSetChartBkGradientFill( ParamColor("Inner panel upper",colorWhite),Param

    Color("Inner panel lower",colorWhite));tchoice=Param("Title Selection ",2,1,2,1);

    //Plot(C, "", IIf(O>=C, colorOrange, colorGreen), ParamStyle("Price Style",styleCandle,maskPrice));//////////////////////////////////////////////////////////////////

     _SECTION_BEGIN("Fib Retracements");fibs = ParamToggle("Plot Fibs","Off|On",1);pctH = Param ("Pivot Hi %", 0.325,0.001,2.0,0.002);HiLB = Param ("Hi LookBack",1,1,BarCount-1,1);pctL = Param ("Pivot Lo %", 0.325,0.001,2.0,0.002);

    LoLB = Param ("Lo LookBack",1,1,BarCount-1,1);Back = Param ("Extend Left = 2",1,1,500,1);Fwd = Param("Plot Forward", 0, 0, 500, 1);text = ParamToggle("Plot Text","Off|On",1);hts = Param ("Text Shift", -33.5,-50,50,0.10);style =ParamStyle("Line Style",styleLine,styleNoLabel);

    x = BarIndex();pRp = PeakBars( H, pctH, 1) == 0;yRp0 = SelectedValue(ValueWhen( pRp, H, HiLB));xRp0 = SelectedValue(ValueWhen( pRp, x, HiLB));pSp = TroughBars( L, pctL, 1) == 0;ySp0 = SelectedValue(ValueWhen( pSp, L, LoLB));xSp0 = SelectedValue(ValueWhen( pSp, x, LoLB));

    Delta = yRp0 - ySp0;

    function fib(ret){retval = (Delta * ret);Fibval = IIf(ret < 1.0AND xSp0 < xRp0, yRp0 - retval, IIf(ret < 1.0AND xSp0 > xRp0, ySp0 + retval,IIf(ret > 1.0AND xSp0 < xRp0, yRp0 - retval, IIf(ret > 1.0AND xSp0 > xRp0, ySp0 + retval, Null))));return FibVal;}

    x0 = Min(xSp0,xRp0)-Back;x1 = (BarCount -1);//////////////////////////////////////////////////////////////////r236 = fib(0.236); r236I = LastValue (r236,1);r382 = fib(0.382); r382I = LastValue (r382,1);r050 = fib(0.50); r050I = LastValue (r050,1);r618 = fib(0.618); r618I = LastValue (r618,1);r786 = fib(0.786); r786I = LastValue (r786,1);e127 = fib(1.27); e127I = LastValue (e127,1);e162 = fib(1.62); e162I = LastValue (e162,1);

  • 8/17/2019 Kpl Swing Trading System AFL Code

    12/21

    e200 = fib(2.00); e200I = LastValue (e200,1);e262 = fib(2.62); e262I = LastValue (e262,1);e424 = fib(4.24); e424I = LastValue (e424,1);//////////////////////////////////////////////////////////////////p00 = IIf(xSp0 > xRp0,ySp0,yRp0); p00I = LastValue (p00,1);p100 = IIf(xSp0 < xRp0,ySp0,yRp0); p100I = LastValue (p100,1);color00 =IIf(xSp0 > xRp0,colorLime,colorRed);color100 =IIf(xSp0 < xRp0,colorLime,colorRed);//////////////////////////////////////////////////////////////////numbars = LastValue(Cum(Status("barvisible")));fraction= IIf(StrRight(Name(),3) == "", 3.2, 3.2);//////////////////////////////////////////////////////////////////if(fibs==1){Plot(LineArray(xRp0-Fwd,yRp0,x1,yRp0,Back),"PR",32,8|styleNoRescale,Null, Null,Fwd);Plot(LineArray(xSp0-Fwd,ySp0,x1,ySp0,Back),"PS",27,8|styleNoRescale,Null, Null,Fwd);Plot(LineArray(x0-Fwd,r236,x1,r236,Back),"",45,style|styleNoRescale,Null, Null,Fwd);Plot(LineArray(x0-Fwd,r382,x1,r382,Back),"",44,style|styleNoRescale,Null, Null,Fwd);Plot(LineArray(x0-Fwd,r050,x1,r050,Back),"",41,style|styleNoRescale,Null, Null,Fwd);

    Plot(LineArray(x0-Fwd,r618,x1,r618,Back),"",43,style|styleNoRescale,Null, Null,Fwd);Plot(LineArray(x0-Fwd,r786,x1,r786,Back),"",42,style|styleNoRescale,Null, Null,Fwd);Plot(LineArray(x0-Fwd,e127,x1,e127,Back),"e127",47,style|styleNoRescale,Null, Null,Fwd);Plot(LineArray(x0-Fwd,e162,x1,e162,Back),"e162",47,style|styleNoRescale,Null, Null,Fwd);Plot(LineArray(x0-Fwd,e200,x1,e200,Back),"p200",47,style|styleNoRescale,Null, Null,Fwd);Plot(LineArray(x0-Fwd,e262,x1,e262,Back),"p262",47,style|styleNoRescale,Null, Null,Fwd);Plot(LineArray(x0-Fwd,e424,x1,e424,Back),"p424",25,style|styleNoRescale,Null, Nu

    ll,Fwd);}//////////////////////////////////////////////////////////////////if(text==1){PlotText(" 0% = " + WriteVal(p00,fraction), LastValue(BarIndex())-(numbars/hts), p00I + 0.05, color00);PlotText("23% = " + WriteVal(r236,fraction), LastValue(BarIndex())-(numbars/hts), r236I + 0.05, 45);PlotText("38% = " + WriteVal(r382,fraction), LastValue(BarIndex())-(numbars/hts), r382I + 0.05, 44);PlotText("50% = " + WriteVal(r050,fraction), LastValue(BarIndex())-(numbars/hts), r050I + 0.05, 41);

    PlotText("62% = " + WriteVal(r618,fraction), LastValue(BarIndex())-(numbars/hts), r618I + 0.05, 43);PlotText("78% = " + WriteVal(r786,fraction), LastValue(BarIndex())-(numbars/hts), r786I + 0.05, 42);PlotText("100% = " + WriteVal(p100,fraction), LastValue(BarIndex())-(numbars/hts),p100I + 0.05, color100);PlotText("127% = " + WriteVal(e127,fraction), LastValue(BarIndex())-(numbars/hts),e127I + 0.05, 47);PlotText("162% = " + WriteVal(e162,fraction), LastValue(BarIndex())-(numbars/hts),e162I + 0.05, 47);

  • 8/17/2019 Kpl Swing Trading System AFL Code

    13/21

    PlotText("200% = " + WriteVal(e200,fraction), LastValue(BarIndex())-(numbars/hts),e200I + 0.05, 47);PlotText("262% = " + WriteVal(e262,fraction), LastValue(BarIndex())-(numbars/hts),e262I + 0.05, 47);PlotText("424% = " + WriteVal(e424,fraction), LastValue(BarIndex())-(numbars/hts),e424I + 0.05, 25);}

     _SECTION_END();//////////////////////////////////////////////////////////////////if (tchoice==1 ){

     _N(Title = EncodeColor(colorBlack)+StrFormat(" {{NAME}} - {{INTERVAL}} {{DATE}} Open: %g, High: %g, Low: %g, Close: %g {{VALUES}}",O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));}//////////////////////////////////////////////////////////////////if (tchoice==2 ){Title = EncodeColor(colorBlack)+ Date() + " Tick = " + EncodeColor(5) + Interval()+EncodeColor(colorBlack) + " Open = " + EncodeColor(colorBlack) + O +EncodeColor(colorBlack) + " High = " + EncodeColor(5) + H +EncodeColor(colorBlack) + " Low = " + EncodeColor(colorRed) + L +EncodeColor(colorBlack) + " Close = " + EncodeColor(colorBlack) + C + "\n" +

    EncodeColor( colorBlack) +"_______________"+"\n"+EncodeColor( colorBlack) + "424% = " + EncodeColor(25)+ e424 +" " +"\n"+EncodeColor( colorBlack) + "262% = " + EncodeColor(47)+ e262 +" " +"\n"+EncodeColor( colorBlack) + "200% = " + EncodeColor(47)+ e200 +" " +"\n"+EncodeColor( colorBlack) + "162% = " + EncodeColor(47)+ e162 +" " +"\n"+EncodeColor( colorBlack) + "127% = " + EncodeColor(47)+ e127 +" " +"\n"+EncodeColor( colorYellow) + " Res = " + EncodeColor(32)+ p100 +" " +"\n"+

    EncodeColor( colorBlack) + " 78% = " + EncodeColor(42)+ r786 +" " +"\n"+EncodeColor( colorBlack) + " 62% = " + EncodeColor(43)+ r618 +" " +"\n"+EncodeColor( colorBlack) + " 50% = " + EncodeColor(41)+ r050 +" " +"\n"+EncodeColor( colorBlack) + " 38% = " + EncodeColor(44)+ r382 +" " +"\n"+EncodeColor( colorBlack) + " 23% = " + EncodeColor(45)+ r236+ " " +"\n"+EncodeColor( colorYellow) + " Sup = " + EncodeColor(34)+ p00 + " " ;}

    GraphXSpace=5;

     _SECTION_BEGIN("BACK COLR");SetChartBkGradientFill( ParamColor("BgTop", ColorRGB( 172,172,172 )),

    ParamColor("BgBottom", ColorRGB( 172,172,172 )),ParamColor("titleblock",ColorRGB( 172,172,172 )));

     _SECTION_END();

    TM = Param("TML",1,1,2,1); //Determine optimum direction of crossing

  • 8/17/2019 Kpl Swing Trading System AFL Code

    14/21

    P = Param("Period",14,2,50,1); //PeriodsLB = Param("LB",14,1,20,1);Ps = Param("Ps",5,1,6,1);LB = Param("LB",14,1,20,1);D = 1; //DateNum()>1000301; //Disable datenum()Blevel = Param("BL",15,00,30,1); //Use neutral thresholdsSlevel = Param("SL",70,50,100,1);

    /*uncomment following for optimizationTM = Optimize("TML",1,1,2,1); //Determine optimum direction of crossingP = Optimize("Pd",6,2,10,1); //Periods as provided by DimitrisLB = /Optimize("LB",14,1,20,1);Ps = Optimize("Ps",5,1,6,1);D = DateNum()>1000301; //Disable datenum()Blevel = Optimize("BL",12,0,20,1); //Use neutral thresholdsSlevel = Optimize("SL",70,70,100,1);*/

    Stocci=100*(CCI(P)-LLV(CCI(P),LB))/(HHV(CCI(P),LB)-LLV(CCI(P),LB));

    StoCCIma=EMA(stocci,Ps);Plot(StoCCI,"StoCCI",colorViolet,styleLine);Plot(StoCCIma,"StoCCIma",colorOrange,styleLine);Buy = IIf(TM==1,Cross(STOCCI,BLEVEL),Cross(BLEVEL,STOCCI));Sell = IIf(TM==1,Cross(Slevel,STOCCI),Cross(STOCCI,SLevel));

    Buy = D*Buy;Sell = D*Sell;Short = Sell;Cover = Buy;

    shape = Buy * shapeCircle + Sell * shapeCircle;

    PlotShapes( shape, IIf( Buy, colorLime, colorRed ), 0,IIf( Buy, Ref(StoCCI,-1)*0.9, Ref(StoCCI,-1)*1.01) );

     _SECTION_BEGIN("PPO");//Further understanding of PPO indicator visit www.Stockchart.com

    PPOShort = Param("PPO Short Period", 8, 1, 150, 1);PPOLong = Param("PPO Long Period", 17, 1, 150, 1);PPOsignal = Param("PPOsignal", 9, 1, 150, 1);PPO = (EMA(C, PPOShort ) - EMA(C, PPOLong ))/ EMA(C, PPOLong );PPOS = (EMA(ppo, PPOsignal ));Val=ppo-PPOS ;Plot( PPO , "ppo", colorGreen, styleLine| styleThick );Plot ( PPOS ,"PPO Signal", colorOrange, styleLine| styleThick );dynamic_color = IIf( Val> 0, colorGreen, colorRed );Plot( Val, "PPO Histogram", dynamic_color, styleHistogram | styleThick );

    Buy=Cross(PPO,PPOS);Sell=Cross(PPOS,PPO);

    shape = Buy * shapeHollowUpArrow + Sell * shapeHollowDownArrow;

    PlotShapes( shape, IIf( Buy, colorLime, colorRed ), 0,IIf( Buy, Ref(PPO,-1)*0.9, Ref(PPO,-1)*1.05) );

     _SECTION_END();

    //===============================================

  • 8/17/2019 Kpl Swing Trading System AFL Code

    15/21

     _SECTION_BEGIN("MA Diff");T=26;KMA=((C-MA(C,T))/MA(C,T))*100;Graph0=KMA;Graph0Style=2+4;Graph0BarColor=IIf(KMA>0,5,4);GraphXSpace=5;

     _SECTION_END();

     _SECTION_BEGIN("Price");SetChartOptions(0,chartShowArrows|chartShowDates);Plot( C, "Close", ParamColor("Color", colorRed ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );

     _SECTION_END();

    //------------------------------------------------------------------------------

     _SECTION_BEGIN("ZIG-ZAG");P = ParamField( "Price field" );change = Param("% change",5,0.1,25,0.1);

     _SECTION_END();

     _SECTION_BEGIN("EMA");P = ParamField("Price field",-1);Periods = Param("Periods", 15, 2, 300, 1, 10 );

     _SECTION_END();

     _SECTION_BEGIN("MACD Exploration");r1 = Param( "Fast avg", 12, 2, 200, 1 );r2 = Param( "Slow avg", 26, 2, 200, 1 );r3 = Param( "Signal avg", 9, 2, 200, 1 );Z=Param("zig",1,0,10,0.1);

    Cond1 = Cross(MACD(r1,r2),Signal(r1,r2,r3));

    Cond3 = Zig(C,z)>Ref(Zig(C,z),-4);Buy = Cond1 AND Cond3;

    Cond4 = Cross(Signal(r1,r2,r3),MACD(r1,r2));

    Cond6 = Zig(C,z)

  • 8/17/2019 Kpl Swing Trading System AFL Code

    16/21

    }

    //------------------------------------------------------------------------------------------------if(Status("action") == actionExplore)

    Filter = Buy OR Sell;SetOption("NoDefaultColumns", True);

    AddTextColumn(Name(), "Symbol", 77, FG, BG, 120);AddColumn(DateTime(), "Date", formatDateTime, FG, BG, 100);AddColumn(TimeNum() ,"Time",1);AddColumn( C, "Close", 1.3 );AddColumn( H, "High", 1.3 );AddColumn(V, "Volume");AddColumn(Ref(V,-1),"P-Vol");AddColumn(V/Ref(V,-1)*100,"Increase in Vol");AddColumn( Buy, "Buy", 1 );AddColumn( Sell, "Sell", 1 );

    shape = Buy * shapeHollowUpTriangle + Sell * shapeHollowDownTriangle;

    PlotShapes( shape, IIf( Buy, colorBlue, colorWhite ), 0, IIf( Buy, Low, High ) )

    ;

    GraphXSpace = 7;

    GraphXSpace = 7; _SECTION_END();

     _SECTION_BEGIN("EMA3");P = ParamField("Price field",-1);Periods = Param("Periods", 15, 2, 300, 1, 10 );

     _SECTION_END();

     _SECTION_BEGIN("Background text");C13=Param("fonts",20,10,30,1 );C14=Param("left-right",2.1,1.0,5.0,0.1 );C15=Param("up-down",12,1,20,1 );Miny = Status("axisminy");Maxy = Status("axismaxy");lvb = Status("lastvisiblebar");fvb = Status("firstvisiblebar");pxwidth = Status("pxwidth");pxheight = Status("pxheight");GfxSetBkMode(transparent=1);GfxSetOverlayMode(1);GfxSelectFont("Tahoma", Status("pxheight")/C13 );

    GfxSetTextAlign( 6 );GfxSetTextColor( ColorRGB (217,217,213));GfxTextOut( Name(), Status("pxwidth")/C14, Status("pxheight")/C15 );GfxSelectFont("Tahoma", Status("pxheight")/C13*0.5 );GfxSetTextColor( ColorRGB (103,103,103));GfxTextOut( "By", Status("pxwidth")/C14, Status("pxheight")/C15*2.5 );GfxSelectFont("Tahoma", Status("pxheight")/C13*0.5 );GfxSetTextColor( ColorRGB (103,103,103));GfxTextOut( "Nakshatra", Status("pxwidth")/C14, Status("pxheight")/C15*4 );GfxSelectFont("MS Sans Serif", 10, 500, False, False, 0);

  • 8/17/2019 Kpl Swing Trading System AFL Code

    17/21

    //Second phase starts Here//File: BHS Chart

     _SECTION_BEGIN("BHS1.02");SetChartBkColor(ParamColor("Outer panel color ",colorLightYellow));SetChartBkColor(ParamColor("BackGround Color", colorDarkGrey));pShowtradeLines = ParamToggle("Show Trade Lines", "No|Yes", 1);pShowMarkers = ParamToggle("Show Markers", "No|Yes", 1);synch=ParamToggle("Synchronize buy/short with foreign index", "No|Yes", 1);Volmin=Param("Volume minimum",5000,0,10000000,50);Volmax=Param("Volume maximum",1000000,0,10000000,50);priceRL=Param("Price Range Min",150,1,20000,1);priceRH=Param("Price Range Max",3000,1,20000,1);PercChangemin=Param("Percentage Change Min set", -25, -100, 100, 0.1);PercChangemax=Param("Percentage Change Max set", 25, -100, 100, 0.1);PerctakeProfit=Param("Take Profit Percent Set",0.6,0.3,30,0.1);PercStoploss=Param("StopLoss Percent Set",0.25,0.2,5,0.1);

    //PlotOHLC(Open,High,Low,Close,"",colorWhite,styleCandle);Bars = 0;xpdh = 90;

    {Plot_Range = (TimeNum() >= 85500 AND TimeNum()= 085500 AND TimeNum()0);

    Num_Bars = 36000 / Interval(1);

    TimeFrameSet(inDaily);TOP_ = Open;PDH_ = Ref(High,-1);PDL_ = Ref(Low,-1);PDO_ = Ref(Open,-1);

    PDC_ = Ref(Close,-1);PDM_ = (PDH_+PDL_)/2;TimeFrameRestore();

    isAll = True;isRth = TimeNum() >= 085400 AND TimeNum() = 085400 AND TimeNum()

  • 8/17/2019 Kpl Swing Trading System AFL Code

    18/21

    DayL = TimeFrameCompress( aRthLd, inDaily, compressLow );DayL = TimeFrameExpand( DayL, inDaily, expandFirst );

    FC1=((PDH-PDL)*0.433);FC2=((PDH-PDL)*0.7666);FC3=((PDH-PDL)*1.355);FC4=(FHH-FHL);

    A=IIf((FC4BG3 ,colorBrightGreen,IIf(Hac < BR3,colorRed,colorGrey50));Plot(4, "", Co,styleArea+styleOwnScale | styleNoLabel, -1, 100);RestorePriceArrays();

     _SECTION_END();

    BuyPrice=(DayL+AF);BuyTP1=(BuyPrice+(BuyPrice*(PerctakeProfit/100)));BuyTP2=(C>=BuyTP1);SellPrice=(DayH-AF);SellTP1=(SellPrice-(SellPrice*(PerctakeProfit/100)));SellTP2=(C=Volmin AND V=PercChangemin AND percchange=priceRL AND C

  • 8/17/2019 Kpl Swing Trading System AFL Code

    19/21

    BuyPriceline=LineArray(x0,LastValue(BuyPrice),x1,LastValue(BuyPrice),0);BuyStopline=LineArray(x0,LastValue(BuyStop2),x1,LastValue(BuyStop2),0);BuyTPline=LineArray(x0,LastValue(BuyTP1),x1,LastValue(BuyTP1),0);SellPriceline=LineArray(x0,LastValue(SellPrice),x1 ,LastValue(SellPrice),0);SellStopline=LineArray(x0,LastValue(SellStop2),x1, LastValue(SellStop2),0);SellTPline=LineArray(x0,LastValue(SellTP1),x1,LastValue(SellTP1),0);DayHline=LineArray(x0,LastValue(DayH),x1,LastValue (DayH),0);DayLline=LineArray(x0,LastValue(DayL),x1,LastValue (DayL),0);

    Plot(IIf(pShowtradeLines,BuyStopline,Null),"BuySto p",colorBrightGreen,styleDots|styleNoRescale| styleNoLine);Plot(IIf(pShowtradeLines,SellPriceline,Null),"Shor t Here",colorRed,styleDots|styleNoRescale);PlotShapes(IIf(pShowMarkers AND Buy, shapeHollowUpArrow, Null), colorDarkGreen,0,L,Offset=-30);

    if( Status("action") == actionIndicator )(Title = EncodeColor(colorWhite)+ "Nakshatra Super " + " - " + Name() + " - " + EncodeColor(colorYellow)+ Interval(2) + EncodeColor(colorYellow) +" - " + Date() +" - "+ EncodeColor(colorYellow) + "-Open="+WriteVal(O,1) + EncodeColor(colorYellow) + "- High= "+ WriteVal(H,1)+ EncodeColor(colorYellow) + "- Low= "+ WriteVal(L,1)+ EncodeColor(colorYellow) + "- Close= "+ WriteVal(C,1)+ Enc

    odeColor(colorYellow) + "- Vol= "+ WriteVal(V,1)+("\n")+WriteIf(Percchange, " % Change = "+(Percchange)+" ","")+" Previous DayHigh="+WriteVal(PDH,1)+", Previous DayLow="+WriteVal(PDL,1)+", Today High="+WriteVal(DayH,1)+", Todays Low="+WriteVal(DayL,1)+WriteIf(Hac>BG3,EncodeColor(colorBrightGreen)+"+Up ",WriteIf(Hac

  • 8/17/2019 Kpl Swing Trading System AFL Code

    20/21

     _SECTION_BEGIN("short signal");HaClose=(O+H+L+C)/4;HaOpen = AMA( Ref( HaClose, -1 ), 0.5 );HaHigh = Max( H, Max( HaClose, HaOpen ) );HaLow = Min( L, Min( HaClose, HaOpen ) );BG2=HHV(LLV(Low,4)+ATR(4),8);BR2=LLV(HHV(High,4)-ATR(4),8);SetBarFillColor( IIf(O NW[i-1]){NW[i] = j[i] - Revers[i];}else{NW[i] = NW[i-1];}

    }}if(Trend[i-1] == -1){if(j[i] > NW[i-1]){Trend[i] = 1;NW[i] = j[i] - Revers[i];}else{Trend[i] = -1;if((j[i] + Revers[i]) < NW[i-1])

    {NW[i] = j[i] + Revers[i];}else{NW[i] = NW[i-1];}}}}

  • 8/17/2019 Kpl Swing Trading System AFL Code

    21/21

    Plot(NW, "", IIf(Trend == 1, 6, 4), 4);

    Buy=Cross(j,nw);Short=Cross(nw,j);Sell=Cross(nw,j);Cover=Cross(j,nw);Buy=ExRem(Buy,Sell);Sell=ExRem(Sell,Buy);Short=ExRem(Short,Cover);Cover=ExRem(Cover,Short);dist = 1.5*ATR(15);for( i = 0; i < BarCount; i++ ){//if( Buy[i] ) PlotText( "Buy@" + O[ i ], i, L[ i ]-Trend[i], colorDarkBlue, colorYellow );//if( Sell[i] ) PlotText( "Sell@" +H[ i ], i-4, L[ i ]+Trend[i], colorRed, colorYellow );}

    //PlotShapes(IIf(Buy, shapeUpArrow, shapeNone),colorWhite, 0,halow,-30);//PlotShapes(IIf(Sell, shapeHollowDownTriangle, shapeNone),colorWhite, 0,hahigh,-15);//PlotShapes(IIf(Cover, shapeHollowUpTriangle, shapeNone),colorWhite, 0,halow,-1

    5);//PlotShapes(IIf(Short, shapeDownArrow, shapeNone),colorWhite, 0,hahigh,-30);

    //================================================