Ultimate-Swing-Trading-System

Ultimate-Swing-Trading-System
Ultimate-Swing-Trading-System

//www.aflcode.com
_SECTION_BEGIN("");
SetBarsRequired(200,0);
GraphXSpace = 5;
SetChartOptions(0,chartShowArrows|chartShowDates);
k =  Optimize("K",Param("K",1,0.25,5,0.25),0.25,5,0.25);
Per= Optimize("atr",Param("atr",2,3,20,1),3,20,1);
HACLOSE=(O+H+L+C)/4;
HaOpen = AMA( Ref( HaClose,  -1 ),  1.0 );
HaHigh = Max( H,  Max( HaClose,  HaOpen ) );
HaLow = Min( L,  Min( HaClose,  HaOpen ) );
j=Haclose;
//=========================Indicator===========================================
f=ATR(10);
rfsctor = WMA(H-L, Per);
revers = k * rfsctor;
Trend = 1;  
NW[0] = 0; 
for(i = 1; i < BarCount; i++)
{
 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];
   }
  } 
 }
 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];
   }
  }
 }
}

//===============system================
Plot(NW, "", IIf(Trend == 1, 27, 4), 4);
Buy=Cover=Cross(j,nw);
Sell=Short=Cross(nw,j);
SellPrice=ValueWhen(Sell,C,1);
BuyPrice=ValueWhen(Buy,C,1);
Long=Flip(Buy,Sell);
Shrt=Flip(Sell,Buy );
_SECTION_END();

_SECTION_BEGIN("Elder Impulse Indicator");
// User-defined parameter for EMA periods
EMA_prds = Param("EMA_periods", 6, 1, 30, 1);
// Compute EMA and MACD Histogram
DayEMA  = EMA(Close, EMA_prds);
Histogram = MACD() - Signal();
// Determine if we have an Impulse UP, DOWN or None
Impulse_Up  = DayEMA > Ref(DayEMA, -1) AND Histogram > Ref(Histogram, -1);
Impulse_Down = DayEMA < Ref(DayEMA, -1) AND Histogram < Ref(Histogram, -1);   
Impulse_None = (NOT Impulse_UP) AND (NOT Impulse_Down);

// Compute Weekly MACD and determine whether rising or falling
// Note: uses "non-standard"  parameters!
TimeFrameSet(inWeekly);
MACD_val = MACD(5, 8);
Signal_val = Signal(5, 8, 5);
Hist_in_w = MACD_val - Signal_val;

wh_rising  = Hist_in_w > Ref(Hist_in_w, -1);
wh_falling  = Hist_in_w < Ref(Hist_in_w, -1);

TimeFrameRestore();

// Now get Monthly MACD Histogram....
TimeFrameSet(inMonthly);
MACD_val  = MACD(5, 8);
Signal_val  = Signal(5, 8, 5);
Hist_in_m  = MACD_val - Signal_val;

mh_rising = Hist_in_m > Ref(Hist_in_m, -1);
mh_falling = Hist_in_m < Ref(Hist_in_m, -1);
TimeFrameRestore();
wh_rising  = TimeFrameExpand( wh_rising, inWeekly ); 
wh_falling  = TimeFrameExpand( wh_falling, inWeekly ); 
mh_rising  = TimeFrameExpand(mh_rising, inMonthly);
mh_falling  = TimeFrameExpand(mh_falling, inMonthly);
kol  = IIf( wh_rising, colorGreen,  IIf(wh_falling, colorRed, colorLightGrey));
mkol  = IIf( mh_rising, colorCustom9,  IIf(mh_falling, colorOrange, colorLightGrey));
// Plot them all!
Plot(3, "R", kol, styleOwnScale|styleArea|styleNoLabel, -12, 156); // Weekly trend
Plot(6, "R", mkol, styleOwnScale|styleArea|styleNoLabel, -0.5, 150); // Monthly Trend
_SECTION_END();
_SECTION_BEGIN("J's SRI CHAKRA - PH: 9367151067");
//{J's SRI CHAKRA} 
//{Buy} 
x1=5; x2=4; x3=3; x4=2; x5=1; x6=.5; 
//{Lowest price stock <5} 
AA=IIf(C<5,Cross(C,ValueWhen(Peak(H,x1,1) !=Ref(Peak(H,x1,1),-1),H,1)), 
//{Price between 5 AND 20} 
IIf(C>5 AND C<20,Cross(C,ValueWhen(Peak(H,x2,1) !=Ref(Peak(H,x2,1),-1),H,1)), 
//{Price between 20 AND 70} 
IIf(C>20 AND C<70,Cross(C,ValueWhen(Peak(H,x3,1) !=Ref(Peak(H,x3,1),-1),H,1)), 
//{Price between 70 AND 150} 
IIf(C>70 AND C<150,Cross(C,ValueWhen(Peak(H,x4,1) !=Ref(Peak(H,x4,1),-1),H,1)), 
//{Price between 150 AND 300} 
IIf(C>150 AND C<300,Cross(C,ValueWhen(Peak(H,x5,1) !=Ref(Peak(H,x5,1),-1),H,1)), 
//{Price over 300} 
Cross(C,ValueWhen(Peak(H,x6,1)!=Ref(Peak(H,x6,1),-1),H,1))))))); 
//{Sell } 
x1=5; x2=4; x3=3; x4=2; x5=1; x6=.5; 
//{Lowest price stock <5} 
BB=IIf(C<5,Cross(ValueWhen(Trough(L,x1,1) !=Ref(Trough(L,x1,1),-1),L,1),C), 
//{Price between 5 AND 20} 
IIf(C>5 AND C<20,Cross(ValueWhen(Trough(L,x2,1) !=Ref(Trough(L,x2,1),-1),L,1),C), 
//{Price between 20 AND 70} 
IIf(C>20 AND C<70,Cross(ValueWhen(Trough(L,x3,1) !=Ref(Trough(L,x3,1),-1),L,1),C), 
//{Price between 70 AND 150} 
IIf(C>70 AND C<150,Cross(ValueWhen(Trough(L,x4,1) !=Ref(Trough(L,x4,1),-1),L,1),C), 
//{Price between 150 AND 300} 
IIf(C>150 AND C<300,Cross(ValueWhen(Trough(L,x5,1) !=Ref(Trough(L,x5,1),-1),L,1),C), 
//{Price over 300} 
Cross(ValueWhen(Trough(L,x6,1)!=Ref(Trough(L,x6,1),-1),L,1),C)))))); 

Color=IIf(BarsSince(AA)>BarsSince(BB),colorRed,IIf(RSI()>70,colorCustom11,colorDarkGreen)); 
 ///// Trailing Stop Module ///// 
P6=Param("Trailing Stop Risk",2.5,2,3.5,0.1); 
P7=Param("Trailing Stop LookBack",14,5,25,1); 
P8=Param("Trailing Stop PrevLow Switch",0,0,1,1); 
PrevLow=IIf(P8==1, Ref(C,-TroughBars(C,5,1)) ,Null); 
Plot(PrevLow,"",colorRed); 
//Position sizing// 
MyTotalPort = Param("MyTotalPort",1000000,10000,10000000,100000); 
AcceptableRisk = Param("AcceptableRisk",0.5,0.1,3,0.1); 
BarsFromStart = BarsSince(Cross(AA,BB)AND Ref(Color,-1)==colorRed) ; 
InitialStopLoss =Ref( H - P6*ATR(P7),-BarsFromStart); 
PositionSizing = 0.01*AcceptableRisk*MyTotalPort/( C - InitialStopLoss ); 
Plot(IIf( HHV(H - P6*ATR(P7),BarsFromStart+1) <C ,HHV(H - P6*ATR(P7),BarsFromStart+1),Null) ,"",colorBlue,1); 
PlotShapes(shapeHollowDownArrow*Cross(Ref(HHV(H - P6*ATR(P7),BarsFromStart+1),-1),C),colorRed,0,H,Offset=-43); 
Title=Name()+" "+Date()+" "+EncodeColor(colorWhite)+"J's SRI CHAKRA - Ph: 9367151067"+EncodeColor(colorCustom11)+" Vol="+NumToStr(Volume ,1.2)+" "+EncodeColor(1)+"Position Sizing ( " +AcceptableRisk+ "% Risk ) = " + WriteIf(color==colorLime,NumToStr(PositionSizing ,1.0),"0")+ 
EncodeColor(colorYellow)+"\nO="+O+EncodeColor(colorCustom3)+" Pk-Tgh Exit"+EncodeColor(colorCustom3)+" ATR Trailing Exit"+EncodeColor(colorOrange)+" RSI Exit"+EncodeColor(colorCustom9)+" ADX = "+ADX()+EncodeColor(colorWhite)+"\nH="+H+"\nL="+L+"\nClose="+ C+""+"\nchange= "+NumToStr((Ref(C,-1)-Close) ,1.2) + 
" "; 
PlotShapes( AA*shapeHollowUpTriangle,colorCustom9,0,L-0.2); 
PlotShapes( BB*shapeHollowDownTriangle,colorDarkRed,0,H+0.2); 
GraphXSpace=3;
_SECTION_END();
_SECTION_BEGIN("Plot Weekly and Daily Moving average");

MaxGraph=7;

//Input Time periods for Weekly and Daily Moving Averages
WeeklyPds=20;//Weeks
DailyPds=1;//Days 
/***********************************/
//Input Price Variable ( open, high ,low, close);
Price=C;
WeeklyPrice=Price;
DailyPrice=Price;
/**********************************/
/***Colors***/
//Set to your Preference
Color=6;//Price chart
WklyAvgColor=5;//weekly AverageLine
DlyAvgColor=4;//Daily AverageLine
/**********************************/
Weekly=ValueWhen(DayOfWeek() > Ref( DayOfWeek(),1),WeeklyPrice);
WeeklyAvg=EMA(Weekly,WeeklyPds);
DailyAvg=EMA(DailyPrice,DailyPds);
Plot(EMA(C,200),"",colorCustom12,styleLine);
Plot(EMA(C,500),"",colorGold,styleLine);
Graph0=C;
Graph0Style=64;
Graph0Color=Color;

Graph1=WeeklyAvg;
Graph1Style=1+4;//Thick line
Graph1Color=WklyAvgColor;

Graph2=DailyAvg;
Graph2Style=1;
Graph2Color=DlyAvgColor;
_SECTION_END();
/****************************************

Name   : Logic All In One for Intraday 
Date   : 10th JAN 2009
Author        : j
E-Mail ID     :  j

*****************************************/
EnableTextOutput(False);
_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
Title_X = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) );
 
SetChartBkGradientFill( ParamColor("BgTop", colorWhite),ParamColor("BgBottom", colorWhite), ParamColor("Title", colorWhite));
SetChartBkColor(ParamColor("Background", colorWhite));
_SECTION_END();
//Indicators

_SECTION_BEGIN("Indicators");
RSI_Periods  = Param("RSI Periods", 2, 1, 100, 1);
MA_Periods  = Param("Periods for MAV", 50, 1, 200, 1);
Daily_Trend_MA_Pds = Param("Periods for Trend EMA", 6, 1, 100, 1);
_SECTION_END();

SetBarsRequired(100000, 100000);
// Find nearest UP and DOWN bar before current bar
Up_Day = Close > Open;
Down_Day = Close < Open;
Reference_Low = ValueWhen(Up_Day, L, 1);
Reference_High = ValueWhen(Down_Day, H, 1);
Buy_Condition = C > O AND C > Reference_High;
Sell_Condition = C < O AND C < Reference_Low;
a= Buy_Condition;
b= Sell_Condition;
state=IIf(BarsSince(a)<BarsSince(b),1,0);
s=state>Ref(state,-1);
ss=state<Ref(state,-1);
sss=state==Ref(state,-1);
col=IIf(state == 1 ,51,IIf(state ==0,4,1));
Buy_Views = WriteIf(s,"EXIT ALL SHORT POSITIONS\n AND TRADE LONG WITH STOPLOSS="+EncodeColor(colorBrightGreen)+WriteVal(L,1.2)+",",""); 
Sell_Views = WriteIf(ss,"EXIT ALL LONG POSITIONS \n AND TRADE SHORT WITH STOPLOSS="+EncodeColor(colorRed)+WriteVal(H,1.2)+",","");

// RSI and Vol ratio calculation
RSI_Value  = RSI(RSI_Periods);
MAV_Value = V/EMA(V, MA_Periods);

//Percentage change

s=C-Ref(C,-1);
t=(s/Ref(C,-1))*100;
Percentage= t;

//Percentage Change in Volume 

w = V -Ref(V,-1);
x = (w/Ref(V,-1))*100;
Volume_Ratio = x;
//Volume_Ratio = V/EMA(V,50);
//Conditions

Condition1 = Percentage > 0.5 AND Volume_Ratio > 1.5;
Condition2 = Percentage > 1 AND Volume_Ratio < -1.5;
Condition3 = Percentage < 0 AND Volume_Ratio > -1.5;
Condition4 = Percentage < 1 AND Volume_Ratio < 1.5;
Condition5 = IIf(NOT Condition1 AND NOT Condition2 AND  NOT Condition3 AND  NOT Condition4, True,False);


Fresh_Buying = WriteIf(Condition1,"Fresh Buying", "");
Short_Covering = WriteIf(Condition2,"Short Covering", "");
Fresh_Short_Building = WriteIf(Condition3,"Fresh Short Building", "");
Possible_Bottom = WriteIf(Condition4,"Possible Bottom OR Top", "");
No_Major_Move = WriteIf(Condition5, "No_Major_Move","");

//interpretation output

EnableTextOutput(True);
"\nSell Below: " + WriteVal(ValueWhen(Up_Day, L, 1), 1.2);
"Buy Above : " + WriteVal(Reference_High, 1.2);
"";
"Current RSI Value: " + WriteVal(RSI_Value, 1.2);
"Current Vol. Ratio: " + WriteVal(MAV_Value, 1.2);
"";
"Fresh Buying: " + WriteIf(Condition1,"Fresh Buying","");

EnableTextOutput(False);

Filter = Buy_Condition OR Sell_Condition;

// Trading System
PositionSize = BuyPrice * 1;
Buy  = Buy_condition;
Sell  = Sell_condition;
Buy  = ExRem( Buy, Sell );
Sell  = ExRem( Sell, Buy );

// Experimental Code BEGIN
Is_Last_Bar = BarIndex()+1 == BarCount;
printf("Last Bar: %g\n", Is_Last_Bar);
Buy_Alert = Buy AND Is_Last_Bar;
Sell_Alert = Sell AND Is_Last_Bar;
Buy_Alert_Text = WriteIf(Buy_Alert, "BUY WARNING!!!", "");
Sell_Alert_Text = WriteIf(Sell_Alert, "SELL WARNING!!!", "");
Buy_Alert_Text1 = WriteIf(Buy_Alert, "BUY", "");
Sell_Alert_Text1 = WriteIf(Sell_Alert, "SELL", "");
LastbarsignalCol  = IIf(Buy_Alert, colorGreen, IIf(Sell_Alert, colorRed, colorLightGrey));


//Buy & Sell Arrows Signal
PlotShapes(shapeCircle  * Buy_Alert, colorBrightGreen, 0, L, -15);
PlotShapes(shapeCircle * Sell_Alert, colorRed, 0, H, 15);

AlertIf( Buy, "SOUND C:\\Windows\\Media\\notify.wav", "Audio alert", 2);
AlertIf( Sell, "SOUND C:\\Windows\\Media\\tada.wav", "Audio alert", 2 );


// Check if previous day's close is above its 6-day EMA
DailyClose  =   TimeFrameCompress(Close, inDaily);
DailyEMA   =  EMA( DailyClose, Daily_Trend_MA_Pds); 
DailyClose  = TimeFrameExpand(DailyClose, inDaily, expandFirst);
DailyEma  = TimeFrameExpand(DailyEMA, inDaily, expandFirst);

// Trend detection based on 6EMA for Daily 
Daily_Trend_UP    = DailyClose > DailyEMA;
Daily_Trend_DOWN   = DailyClose < DailyEMA;
Trend_UP_Text  = WriteIf(Daily_Trend_UP, "Daily Trend UP", "");
Trend_DOWN_Text = WriteIf(Daily_Trend_DOWN, "Daily Trend DOWN", "");
Trend_Neutral_Text = WriteIf(NOT Daily_Trend_DOWN AND NOT Daily_Trend_UP, "Neutral", "");
TrendCol  = IIf(Daily_Trend_UP, colorGreen, IIf(Daily_Trend_DOWN, colorRed, colorLightGrey));


/** Debug BEGIN  */
printf("\nDaily Close: %g ", DailyClose);
printf("\nDaily Trend: %g", (DailyEMA));
/*      Debug END ****/

//Inerpretation 
Title = Title_X + "\n"  +

   EncodeColor(colorCustom11) + "RSI(" + WriteVal(RSI_Periods, 1)  + "):  " +
   EncodeColor(colorBrightGreen) + WriteVal(RSI_Value, 1.2) + "\n" + 
   EncodeColor(colorCustom11) + "Vol. Ratio: " + EncodeColor(colorDarkGreen) + WriteVal(MAV_Value, 1.2) + "\n" +
   EncodeColor(colorRed) + Trend_Down_Text + EncodeColor(colorBrightGreen) + Trend_Up_Text +
   EncodeColor(colorWhite) + Trend_Neutral_Text +  "\n" + 
          EncodeColor(colorRed) + Sell_Alert_Text + EncodeColor(colorBrightGreen) + Buy_Alert_Text + "\n" +
          EncodeColor(colorRed) + Fresh_Short_Building + EncodeColor(colorBrightGreen) + Fresh_Buying + EncodeColor(colorWhite) + Short_Covering + EncodeColor(colorWhite) + Possible_Bottom +"\n" +
          EncodeColor(colorBrightGreen)+ "Buy Above : " + WriteVal(Reference_High, 1.2)+ "\n" +
          EncodeColor(colorCustom5) + "Sell Below: " + WriteVal(ValueWhen(Up_Day, L, 1), 1.2) + "\n" +
          EncodeColor(colorCustom12) + "Trend value: " + WriteVal(DailyEMA,1) +"\n"+
          EncodeColor(colorBlue)+ Buy_Views + EncodeColor(colorBlue)+ Sell_Views;
          

//M J Povit Point

DayH = TimeFrameGetPrice("H", inDaily, -1);  // yesterdays high
DayL = TimeFrameGetPrice("L", inDaily, -1);  //    low
DayC = TimeFrameGetPrice("C", inDaily, -1);  //    close
DayO = TimeFrameGetPrice("O", inDaily);   // current day open
Dayz = TimeFrameGetPrice("C", inDaily, -6);  //  six days close
if ( True )
{
PP = (Dayc + Dayc -6 )/2;
R1  =  Dayc + (DayH - DayL)/2;
S1  =  Dayc - (DayH - DayL)/2;
R2  =  Dayc + (DayH - DayL);
S2  =  Dayc - (DayH - DayL);
}
Plot(pp, "PP",colorYellow,styleDots+styleNoLine);
Plot(R1, "R1",colorCustom12,styleDots+styleNoLine);
Plot(S1, "S1",colorCustom9,styleDots+styleNoLine);
Plot(R2, "R2",colorRed,styleDots+styleNoLine);
Plot(S2, "S2",colorBlue,styleDots+styleNoLine);


//Average, Volitility & Percentage Scale.
av3=V/EMA(V,50);
V1= MA(V,50);
r = RSI(2); 
s=C-Ref(C,-1);
t=(s/Ref(C,-1))*100;
p=H-L;
q=(p/Ref(C,-1))*100;

//Explore Options

Filter = 1; /* all symbols and quotes accepted */
//filer = Buy OR Sell ;
AddColumn(Open,"OPEN",1);
AddColumn(High,"HIGH",1);
AddColumn(Low,"LOW",1);
AddColumn(Close,"CLOSE",1); 
AddColumn(t,"Per",1.2);
AddColumn(V,"VOLUME",1);
AddColumn(V1,"AGV VOLUME",1);
AddColumn(av3,"RATIO50",1.2);
AddColumn(r,"RSI",2);
AddTextColumn(WriteVal(Reference_High, 1.2),"BUY ABOVE",colorWhite,colorGreen);
AddTextColumn(WriteVal(ValueWhen(Up_Day, L, 1), 1.2),"SELL BELOW",colorWhite,colorRed); 
AddTextColumn(Trend_Down_Text + Trend_Up_Text,"DAILY TREND",1,colorWhite,TrendCol); 
AddTextColumn(Buy_Alert_Text + Sell_Alert_Text,"LAST BAR SIGNAL",1,colorWhite,Lastbarsignalcol); 




//=====================================================================
//background stock name (works only on Amibroker version 5.00 onwards.
//=====================================================================
_SECTION_BEGIN("Name");
GfxSetOverlayMode(1);
GfxSelectFont("Tahoma", Status("pxheight")/10 );
GfxSetTextAlign( 6 );// center alignment
//GfxSetTextColor( ColorRGB( 200, 200, 200 ) );
GfxSetTextColor( ColorHSB( 42, 42, 42 ) );
GfxSetBkMode(0); // transparent
GfxTextOut( Name(), Status("pxwidth")/2, Status("pxheight")/12 );
GfxSelectFont("Tahoma", Status("pxheight")/12 );
GfxTextOut( "SRI CHAKRA", Status("pxwidth")/2, Status("pxheight")/3 );
GfxSelectFont("Tahoma", Status("pxheight")/20 );
GfxTextOut( "sreechakraa@yahoo.co.in", Status("pxwidth")/2, Status("pxheight")/2 );
_SECTION_END();
//======================================================================================
TimeFrameSet( in15Minute ); // switch to 5 minute frame 
_SECTION_BEGIN("display");
no=12;
res=HHV(H,no);
sup=LLV(L,no);
avd=IIf(C>Ref(res,-1),1,IIf(C<Ref(sup,-3),-1,0));
avn=ValueWhen(avd!=0,avd,1);
Hsupres=IIf(avn==1,sup,res);

//Plot(supres,"Alwa",colorTan,styleStaircase);
_SECTION_END();

TimeFrameRestore(); // restore time frame to original 

TimeFrameSet( inHourly ); // switch now to hourly 
_SECTION_BEGIN("display");
no=12;
res=HHV(H,no);
sup=LLV(L,no);
avd=IIf(C>Ref(res,-1),1,IIf(C<Ref(sup,-3),-1,0));
avn=ValueWhen(avd!=0,avd,1);
Hhsupres=IIf(avn==1,sup,res);

//Plot(supress,"Alwa",colorTan,styleStaircase);
_SECTION_END();


mah_9 = EMA( C, 9 ); // 9 bar moving average from hourly data 
//mah_9 = EMA( C, 9 ); // 9 bar moving average from hourly data 

TimeFrameRestore(); // restore time frame to original 

//Plot( Close, "Price", colorWhite, styleCandle ); 

// plot expanded average 

//Plot( TimeFrameExpand( Hsupres, in15Minute), "13 bar moving average from 5 min bars", colorGreen ); 
//Plot( TimeFrameExpand( Hhsupres, inHourly), "9 bar moving average from hourly bars", colorRed );

_SECTION_BEGIN("display");
no=12;
res=HHV(H,no);
sup=LLV(L,no);
avd=IIf(C>Ref(res,-1),1,IIf(C<Ref(sup,-3),-1,0));
avn=ValueWhen(avd!=0,avd,1);
supres=IIf(avn==1,sup,res);

Plot(supres,"",colorTan,styleStaircase);
_SECTION_END();

Hsig=TimeFrameExpand(Hsupres,in15Minute);
Hhsig=TimeFrameExpand(Hhsupres,inHourly);

Buy= C>hsig AND  C>supres AND C>Hhsig;
Sell=C<hsig AND C<supres AND C<Hhsig;
Buy=ExRem(Buy,Sell);
Sell=ExRem(Sell,Buy);

PlotShapes(shapeUpArrow*Buy,colorCustom11, 0, L, -20 );
PlotShapes(shapeDownArrow*Sell,colorCustom12, 0, H, -20 );


//shape=Buy*shapeUpArrow + Sell*shapeDownArrow; PlotShapes(shape,IIf(Buy,colorBrightGreen,colorRed),0,IIf(Buy,Low,High)); 
_SECTION_END();


uptrend=C>hsig AND  C>supres AND C>Hhsig;
// downtrend=Sell=C<hsig AND C<supres AND C<Hhsig;
downtrend=C<hsig AND C<supres AND C<Hhsig;

//Buy=ExRem(Buy,Sell);
//Sell=ExRem(Sell,Buy);
//shape=Buy*shapeUpArrow + Sell*shapeDownArrow; PlotShapes(shape,IIf(Buy,colorBrightGreen,colorRed),0,IIf(Buy,Low,High)); _SECTION_END();

Plot( 5, /* defines the height of the ribbon in percent of pane width
*/"********",
IIf( uptrend, colorDarkOliveGreen, IIf( downtrend, colorRed, 0 )), /* choose color */
styleOwnScale|styleArea|styleNoLabel, -0.5, 200 );

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); 



MinBars = 200;
MinBarsOK = IIf(BarCount >= MinBars, True, False);

if (MinBarsOK) { ;


  /* **********************************

Code to automatically identify pivots

********************************** */
// -- what will be our lookback range for the hh and ll?
farback=Param("How Far back to go",200,1,50,1);
nBars = Param("Number of bars", 100, 0, 50, 1);

// -- Create 0-initialized arrays the size of barcount
aHPivs = H - H;
aLPivs = L - L;
// -- More for future use, not necessary for basic plotting
aHPivHighs = H - H;
aLPivLows = L - L;
aHPivIdxs = H - H;
aLPivIdxs = L - L;
nHPivs = 0;
nLPivs = 0;
lastHPIdx = 0;
lastLPIdx = 0;
lastHPH = 0;
lastLPL = 0;
curPivBarIdx = 0;
// -- looking back from the current bar, how many bars 
// back were the hhv and llv values of the previous 
// n bars, etc.?
aHHVBars = HHVBars(H, nBars);
aLLVBars = LLVBars(L, nBars);
aHHV = HHV(H, nBars);
aLLV = LLV(L, nBars);
// -- Would like to set this up so pivots are calculated back from
// last visible bar to make it easy to "go back" and see the pivots
// this code would find. However, the first instance of 
// _Trace output will show a value of 0
aVisBars = Status("barvisible");
nLastVisBar = LastValue(Highest(IIf(aVisBars, BarIndex(), 0)));
_TRACE("Last visible bar: " + nLastVisBar);
// -- Initialize value of curTrend
curBar = (BarCount-1);
curTrend = "";
if (aLLVBars[curBar] < 
aHHVBars[curBar]) {
curTrend = "D";
}
else {
curTrend = "U";
}
// -- Loop through bars. Search for 
// entirely array-based approach
// in future version
for (i=0; i<farback; i++) {
curBar = (BarCount - 1) - i;
// -- Have we identified a pivot? If trend is down...
if (aLLVBars[curBar] < aHHVBars[curBar]) {
// ... and had been up, this is a trend change
if (curTrend == "U") {
curTrend = "D";
// -- Capture pivot information
curPivBarIdx = curBar - aLLVBars[curBar];
aLPivs[curPivBarIdx] = 1;
aLPivLows[nLPivs] = L[curPivBarIdx];
aLPivIdxs[nLPivs] = curPivBarIdx;
nLPivs++;
}
// -- or current trend is up
} else {
if (curTrend == "D") {
curTrend = "U";
curPivBarIdx = curBar - aHHVBars[curBar];
aHPivs[curPivBarIdx] = 1;
aHPivHighs[nHPivs] = H[curPivBarIdx];
aHPivIdxs[nHPivs] = curPivBarIdx;
nHPivs++;
}
// -- If curTrend is up...else...
} 
// -- loop through bars
} 
// -- Basic attempt to add a pivot this logic may have missed
// -- OK, now I want to look at last two pivots. If the most 
// recent low pivot is after the last high, I could
// still have a high pivot that I didn't catch
// -- Start at last bar
curBar = (BarCount-1);
candIdx = 0;
candPrc = 0;
lastLPIdx = aLPivIdxs[0];
lastLPL = aLPivLows[0];
lastHPIdx = aHPivIdxs[0];
lastHPH = aHPivHighs[0];
if (lastLPIdx > lastHPIdx) {
// -- Bar and price info for candidate pivot
candIdx = curBar - aHHVBars[curBar];
candPrc = aHHV[curBar]; 
if (
lastHPH < candPrc AND
candIdx > lastLPIdx AND
candIdx < curBar) {
// -- OK, we'll add this as a pivot...
aHPivs[candIdx] = 1;
// ...and then rearrange elements in the 
// pivot information arrays
for (j=0; j<nHPivs; j++) {
aHPivHighs[nHPivs-j] = aHPivHighs[nHPivs-
(j+1)];
aHPivIdxs[nHPivs-j] = aHPivIdxs[nHPivs-(j+1)];
}
aHPivHighs[0] = candPrc ;
aHPivIdxs[0] = candIdx;
nHPivs++;
} 
} else {
// -- Bar and price info for candidate pivot
candIdx = curBar - aLLVBars[curBar];
candPrc = aLLV[curBar]; 
if (
lastLPL > candPrc AND
candIdx > lastHPIdx AND
candIdx < curBar) {
// -- OK, we'll add this as a pivot...
aLPivs[candIdx] = 1;
// ...and then rearrange elements in the 
// pivot information arrays
for (j=0; j<nLPivs; j++) {
aLPivLows[nLPivs-j] = aLPivLows[nLPivs-(j+1)];
aLPivIdxs[nLPivs-j] = aLPivIdxs[nLPivs-(j+1)];
}
aLPivLows[0] = candPrc;
aLPivIdxs[0] = candIdx;
nLPivs++;
}
}
// -- Dump inventory of high pivots for debugging
/*
for (k=0; k<nHPivs; k++) {
_TRACE("High pivot no. " + k
+ " at barindex: " + aHPivIdxs[k] + ", " 
+ WriteVal(ValueWhen(BarIndex()==aHPivIdxs[k], 
DateTime(), 1), formatDateTime)
+ ", " + aHPivHighs[k]);
}
*/
// -- OK, let's plot the pivots using arrows
PlotShapes(IIf(aHPivs==1, shapeDownTriangle, shapeNone), colorCustom12, 0, High, Offset=-20);
PlotShapes(IIf(aLPivs==1, shapeUpTriangle , shapeNone), colorCustom11, 0, Low, Offset=-20);
Sell = aHPivs == 1 ;
Buy = aLPivs == 1 ;
Filter=Buy OR Sell; 
Sell=ExRem(Sell,Buy); 
Buy=ExRem(Buy,Sell);
}
Previous
Next Post »