Multi time frame with Trendline

Multi time frame with Trendline
Multi time frame with Trendline

//www.aflcode.com
_SECTION_BEGIN("Multi time frame with Trendline");
// Specially designed for use in day trading and to save chart space. This chart will displays 2 sets
// of candlestick bars. One for the time interval set for your chart- for example 1 Minute. 
// The higher timeframe candlestick bars are created by using gfx low-level graphics AND will display  
// according to the parameters you set- for example 5 minutes. 

// If your chart background turns pink- please read the error message in the upper left corner of the chart.
// Then please observe this AFL code uses ColorBlend(ColorFrom, ColorTo, Factor) which was introduced in Version 5.21 beta.
// The rules are simple- time frames from 1 up to 60 minutes AND Lower time frame must be smaller than the Higher time frame.

Version(5.21); 
SetChartOptions(2, chartShowDates);
Title = Name();
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// PARAMETERS AND SETTINGS:
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ChartLum   = Param("Chart Background Color Intensity", 0.40, 0, 1, 0.01);
TFMinShort  = Param("Short Timeframe (Minutes)", 1, 1, 60, 1);
TFMinLong   = Param("Long Timeframe (Minutes)", 5, 1, 60, 1);
OnSTFBars  = ParamToggle("Short TF Bars", "Off, On", 1);
OnLTFBars  = ParamToggle("Long TF Bars", "Off, On", 1);
BarLum1   = Param("Short TF Bar Color Intensity", 0, 0, 1, 0.01);
BarLum2   = Param("Long TF Bar Color Intensity", 0.70, 0, 1, 0.01);

SetChartBkColor(ColorBlend(colorLightBlue, colorWhite, ChartLum));
// Bar Colors for the Short Timeframe candlestick bars:
LineColor   = ColorBlend(colorBlack, colorWhite, BarLum1);
UpBarColor  = ColorBlend(colorBrightGreen, colorWhite, BarLum1);
DnBarColor  = ColorBlend(colorRed, colorWhite, BarLum1);
// Bar Colors For The Long Timeframe candlestick bars:
TFLineColor  = ColorBlend(colorBlack, colorWhite, BarLum2 - 0.1);
TFUpBarColor = ColorBlend(colorBrightGreen, colorWhite, BarLum2);
TFDnBarColor = ColorBlend(colorRed, colorWhite, BarLum2);
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// FUNCTIONS:
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
function GetVisibleBarCount() 
{ 
 lvb = Status("lastvisiblebar"); 
 fvb = Status("firstvisiblebar"); 
 return Min( Lvb - fvb, BarCount - fvb ); 
} 

function GfxConvertBarToPixelX( bar ) 
{ 
 lvb = Status("lastvisiblebar"); 
 fvb = Status("firstvisiblebar"); 
 pxchartleft = Status("pxchartleft"); 
 pxchartwidth = Status("pxchartwidth"); 
 return pxchartleft + bar  * pxchartwidth / ( Lvb - fvb + 1 ); 
} 

function GfxConvertValueToPixelY( Value ) 
{ 
 local Miny, Maxy, pxchartbottom, pxchartheight; 
 Miny = Status("axisminy"); 
 Maxy = Status("axismaxy"); 
 pxchartbottom = Status("pxchartbottom"); 
 pxchartheight = Status("pxchartheight"); 
 return pxchartbottom - floor( 0.5 + ( Value - Miny ) * pxchartheight/ ( Maxy - Miny ) ); 
} 

StaticVarKey = Name();
procedure xStaticVarSet(SName, SValue)
{
 global StaticVarKey;
 if (StaticVarKey != "")
  StaticVarSet(Sname + StaticVarKey, Svalue);
}
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
// MAIN PROGRAM:
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
if(Interval() != TFMinShort * 60)
{
 Title = Title + "\n" + "\n" + "ALERT, ALERT, ALERT!!!" + "\n" + "Set the chart time Interval to: " + NumToStr(TFMinShort, 1.0, 1) + 
     " Minute(s) or change the Short Timeframe Parameter setting.";
 OnSTFBars  = 0;
 OnLTFBars  = 0;
 SetChartBkColor(colorRose);
} 

if(TFMinShort >= TFMinLong)
{
 Title = Title + "\n" + "\n" + "ALERT, ALERT, ALERT!!!" + "\n" + "The Long
Timeframe setting must be longer than the Short Timeframe!";
 OnSTFBars  = 0;
 OnLTFBars  = 0;
 SetChartBkColor(colorRose);
}

if(OnSTFBars)
{
 BarColor  = IIf(Close > Open, UpBarColor, DnBarColor);
 SetBarFillColor(BarColor);
 Plot(Close, "", LineColor, styleCandle);
}
else
 Plot(Close, "", colorBlack, styleCandle  | styleNoDraw);

TFSec = in1Minute * TFMinLong; 
TimeFrameSet(TFSec); 
TFOpen    = Open; 
TFHigh    = High; 
TFLow     = Low; 
TFClose   = Close; 
TFBarIndex   = BarIndex();
TFLastBarIndex = LastValue(BarIndex());
TimeFrameRestore(); 

TFOpen    = TimeFrameExpand(TFOpen, TFSec, expandFirst); 
TFHigh    = TimeFrameExpand(TFHigh, TFSec, expandFirst); 
TFLow     = TimeFrameExpand(TFLow, TFSec, expandFirst); 
TFClose   = TimeFrameExpand(TFClose, TFSec, expandFirst);
TFBarIndex   = TimeFrameExpand(TFBarIndex, TFSec, expandLast + 1);
TFLastBarIndex = TimeFrameExpand(TFLastBarIndex, TFSec, expandLast + 1);

CandleTop    = Max(TFOpen, TFClose); 
CandleBottom  = Min(TFOpen, TFClose); 
//============================================================================
// GFX LOW-LEVEL GRAPHICS SECTION.
// DRAWING THE LONG TIMEFRAME CANDLESTICK BARS:
//============================================================================
if(OnLTFBars)
{ 
 GfxSetOverlayMode(1); 
 AllVisibleBars  = GetVisibleBarCount(); 
 fvb    = Status("firstvisiblebar"); 
 ChartWidth  = GfxConvertBarToPixelX(AllVisibleBars );
 PixBar    = ChartWidth / AllVisibleBars;
 Adjust   = Pixbar * 0.35;
 TFMinutes   = TFMinLong / TFMinShort;
 NewTFBar    = IIf(TFBarIndex != Ref(TFBarIndex, -1), 1, 0);
 BarInd   = BarIndex();
 TFLastBarIndex = LastValue(TFLastBarIndex);

 // DRAW BAR HISTORY AND THE CURRENT BAR:
 for(i = 0; i < AllVisibleBars; i++) 
 {
  x1 = GfxConvertBarToPixelX(i) * NewTFBar[i + fvb] - Adjust;
  if(BarInd[i + fvb] < TFLastBarIndex AND NewTFBar[i + fvb] == 1)
  {
  Counter = 0;
  for(n = i + 1; NewTFBar[n + fvb] == 0 AND n + fvb < BarCount-1; n++)
   Counter++;
  x2 = GfxConvertBarToPixelX(i + Counter) * NewTFBar[i + fvb] + 1 + Adjust;
  }

  if(TFBarIndex[i + fvb] == TFLastBarIndex)
  x2 = GfxConvertBarToPixelX(i + TFMinutes - 1) * NewTFBar[i + fvb] + 1 + Adjust;

   y1 = GfxConvertValueToPixelY(CandleTop[i + fvb]); 
   y2 = GfxConvertValueToPixelY(CandleBottom[i + fvb]); 
   yH = GfxConvertValueToPixelY(TFHigh[i + fvb]);
   yL = GfxConvertValueToPixelY(TFLow[i + fvb]);

   // Candle Body:
   GfxSelectPen(TFLineColor, 0);
   FillColor = IIf(TFOpen[i + fvb] < TFClose[i + fvb], TFUpBarColor,TFDnBarColor);
   GfxSelectSolidBrush(FillColor); 
   if(y1 == y2){y1 = y1 - Adjust; y2 = y2 + Adjust;
 GfxSelectSolidBrush(TFLineColor);}
   if(x1 > 0){
     GfxRectangle( x1, y1, x2, y2); 
     // Candle High and Low:
     GfxSelectPen(TFLineColor, 2);
     GfxMoveTo(x2+(x1-x2)/2, y1);
     GfxLineTo(x2+(x1-x2)/2, yH);
     GfxMoveTo(x2+(x1-x2)/2, y2);
     GfxLineTo(x2+(x1-x2)/2, yL);
     RequestTimedRefresh(0); 
 }
 } 
}
_SECTION_END();

// AMA System by Karthikmarar
// 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.

// AMA System by Karthikmarar
// 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("Price");
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", ParamColor("Color", colorGreen ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() ); 
_SECTION_END();

// AMA System by Karthikmarar
// 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.

// AMA System by Karthikmarar
// 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("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 and Below 
//  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. 
//   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 SET  
SDU2 = 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");

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

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

_SECTION_BEGIN("Nuevo 4");
percent  = 0.01 * 1; /* Adjust this percent as necessary,  */
firstpointL = 2;
firstpointH = 2;

y0=LastValue(Trough(L,percent,firstpointL)); 
y1=LastValue(Trough(Ref(L,-1),percent,1));

for( i = 1; i < BarCount AND y0 >= y1; i++ )
{
      
      firstpointL++;   
      y0=LastValue(Trough(L,percent,firstpointL));       
}

x0=BarCount - 1 - LastValue(TroughBars(L,percent,firstpointL)); 
x1=BarCount - 1 - LastValue(TroughBars(Ref(L,-1),percent,1)); 
LineL = LineArray( x0, y0, x1, y1, 1 ); 
/*
Plot(C, "C", colorBlack, styleCandle); 
*/
Plot( LineL, " Support Trend line", colorGreen,4 +8 ); 


yt0=LastValue(Peak(H,percent,firstpointH)); 
yt1=LastValue(Peak(Ref(H,-1),percent,1));

for(i = 1; i < BarCount AND yt0 <= yt1; i++ )
{
      
      firstpointH++;      
      yt0=LastValue(Peak(H,percent,firstpointH)); 
}
xt0=BarCount - 1 - LastValue(PeakBars(H,percent,firstpointH)); 
xt1=BarCount - 1 - LastValue(PeakBars(Ref(H,-1),percent,1)); 
LineH = LineArray( xt0, yt0, xt1, yt1, 1 ); 

Plot( LineH, "Resistance Trend line", colorBrown,4 + 8 );
_SECTION_END();

_SECTION_BEGIN("Elliot 2");
//-- Script Start -------
Option = ParamToggle("Insert To", "Price Chart|Indicator");

pr=Param("Elliot Wave minimum % move",2, 0.001,100);

//{ Beginner Elliot Wave stuff }
EWpk=PeakBars(H,pr)==0;
EWtr=TroughBars(L,pr)==0;

//{ Intermediate Elliot Wave stuff }
zz=Zig(C,pr);
zzHi=Zig(H,pr);
zzLo=Zig(L,pr);
Avg=(zzHi+zzLo)/2;

//{ Advanced Elliot Wave stuff }
RetroSuccessSecret=IIf(EWpk,zzHi,
                     IIf(EWtr,zzLo,IIf(Avg>Ref(Avg,-1),H,L)));
EW=Zig(RetroSuccessSecret,pr);

//{ Plot on price chart }
if (Option==0)
 Plot(EW, "EW", ParamColor("Color", colorBrown), ParamStyle("Style", styleNoLabel|styleThick));
else
{

//{ Buy/Sell Elliot Wave stuff }
EWbuy=TroughBars(EW,pr)==0;
EWsell=PeakBars(EW,pr)==0;

//{ Plot on own window }
Plot(EWbuy-EWsell, "EW2", ParamColor("Color", colorRed), ParamStyle("Style", styleNoLabel|styleThick));

}
//-- Script End   -------
_SECTION_END();

_SECTION_BEGIN("Volume");
Plot( Volume, _DEFAULT_NAME(), ParamColor("Color", colorBlueGrey ), ParamStyle( "Style", styleHistogram | styleOwnScale | styleThick, maskHistogram  ), 2 );
_SECTION_END();

_SECTION_BEGIN("EMA2");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 300, 1, 10 );
Plot( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") ); 
_SECTION_END();

//USE THIS WITH 1 MINUTE TIMEFRAME

Range1=Optimize("range1",70,50,80,5);
Range2=Optimize("range2",970,500,1050,5);

StopLevel = Param("trailing stop %", 0.7, 0.1, 10, 0.1 );

SetTradeDelays(0,0,0,0);

Buy = Cross( EMA(Close,Range1), EMA(Close,Range2));
Sell = 0;
ApplyStop( stopTypeTrailing, stopModePercent, StopLevel, True );
 
Equity( 1, 0 ); // evaluate stops, all quotes

InTrade = Flip( Buy, Sell );

SetOption("EveryBarNullCheck", True );
stopline = IIf( InTrade, HighestSince( Buy, High ) * ( 1 - 0.01 * StopLevel ), Null );

PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low);

PlotShapes(Sell*shapeDownArrow,colorRed,0,High);




//Plot( Close,"Price",colorBlack,styleBar);
Plot( stopline, "trailing stop line", colorRed );


Short = Cross( EMA(Close,Range2), EMA(Close,Range1));
Cover = 0;
ApplyStop( stopTypeTrailing, stopModePercent, StopLevel, True );
 
Equity( 1, 0 ); // evaluate stops, all quotes

InTrade1 = Flip( Short, Cover );

SetOption("EveryBarNullCheck", True );
stopline = IIf( InTrade1, LowestSince( Short, Low ) * ( 1 + 0.01 * StopLevel ), Null );

PlotShapes(Short*shapeDownArrow,colorRed,0,High);
PlotShapes(Cover*shapeUpArrow,colorGreen,0,High);


//Plot( Close,"Price",colorBlack,styleBar);
Plot( stopline, "trailing stop line", colorRed );
Previous
Next Post »