// Downloaded From https://www.WiseStockTrader.com
// Visualization of Buy/Sell levels, profit and exitsignals( ie stoplossses) in the chart////////////

// Takes the analytical part of the backtesting to an entire new level in my opion (reduces the importance of backtesting)!
// The code is far from complete and perfect but I dont have the energy to do more. Maybe someone
// could countineou developing the code to include for example:

// 1) an option in the parameter window, to show Buy/Sell/Cover statistics only

// if one would place the mousepointer on each "buy shapes". (GetCursorYPosition() GetCursorXPosition() ) 
// The display becomes quite messy if you display a Low time resolution Chart (monthly, yearly) One alternative would also to use
// the code for displaying digits based on the diffrent sell signal (shapeDigit1). Then it would be sufficient
// to display the profit/loss for each trade. 

// 2) Another drawback is the parameter hiracy. Each parameter 
// subcategories should only be able to work if the user choose Yes on the main category question. 
// Now you have to set all sub-parameters equal to zero instead of activative/deactivating the major ones. 

// 3) Some overal statistics displayed on the lefthand side of the chart
// (# of trades, # winning/lossing trades, total profit/loss etc)


//The following code works best with a black background
//would also like to take the opportunity to thank Marcin Gorzynski for his help with this one


//////////////////////////////  BASIC STRATEGY AND PLOTS ////////////////////

Buy = Cross( Close, MA(Close, 35) ); 
Short= Cross( MA(Close, 35), Close ); 
Sell=LinRegSlope( MA(Close,18), 2 )<0; 
Cover=LinRegSlope( MA(Close,18), 2 )>0; 

Plot( Close, "C", colorWhite, styleLine); 
Plot( MA(Close,100), "MA-100", colorRed, styleLine); 



// I am sceptical to if the original applystop functions (trailing etc) really works!? 
//I have therefor coded my own stop functions below.

////////////////////////////// STOP LOSS PARAMETERS ////////////////////
e = Equity(1,0);  /* Highly Important!!. "Removes all extra signals, evaluates
						stops AND writes BACK signals to Sell/Cover arrays". As it should be!!*/

Lprofit = e - ValueWhen( Buy, e); 
Sprofit = e - ValueWhen( Short, e); 


/////////////////////////////// TRAILING PROFIT STOP////////////////////////////

TL=ParamToggle("FANCY A TRAILING STOP?" , "No|Yes",0);
TLL= ParamToggle("           DO YOU WANT TO PLOT PROFIT + CRITICAL TRAILING LINE IN GRAPH?" , "No|Yes",0);
x2=Param("           SET MAX ACCEPTED DECLINE OF PROFIT IN PERCENT ",1 ,0 ,100 ,1);
//x3=Param("           SET MAX ACCEPTED DECLINE OF PROFIT IN POINTS ",1 ,0 ,100,1);

////////FOR LONG POSITION PERCENT////
XXL=HighestSince( Buy==1, Lprofit, 1 ); //returns the highest profit since last Buy Signal. the basis for the trailing calculation. 
XXXL= XXL*(1-(x2/100)); // if trailing turned on =ok otherwise =null
ZL= ExRem( Cross(XXXL, Lprofit), Buy==1);	// Just first signal counts. highly important!!!!!!!! Also calculates critical Sell levels
Sell= IIf(ZL==1 AND TL==True, 4, 0);	// return a sell signal=4 if z1=1 and TL=True (yes)

////////FOR SHORT POSITION PERCENT////
XXS=HighestSince( Short==1, Sprofit, 1 );  // same as above
XXXS= XXS*(1-(x2/100));
ZS= ExRem( Cross(XXXS, Lprofit), Short==1);
Cover= IIf(ZS==1 AND TL==True, 4, 0);	

PlotShapes( Buy* shapeUpArrow , colorGreen, 0); 
PlotShapes( Short* shapeDownArrow , colorGreen, 0);
PlotShapes( Sell* shapeDigit1 , colorRed, 0);
PlotShapes( Cover* shapeDigit2 , colorRed, 0);


if(TLL==True AND TL=True)	Plot(Lprofit,"LPROFIT",colorYellow,styleLeftAxisScale, styleLine) AND
									Plot(Sprofit,"S PROFIT",colorYellow,styleLeftAxisScale, styleLine) AND
									Plot(XXXL, "L TRAILING LEVEL",colorGreen,styleLeftAxisScale,styleLine) AND
 									Plot(XXXS, "S TRAILING LEVEL",colorGreen,styleLeftAxisScale,styleLine);


//////////ABSOLUTE PROFIT STOP////////////////////////////
ML=ParamToggle("FANCY A MAX STOP IN PERCENT?", "No|Yes",0);
x1=Param( "          SET MAX ACCEPTED LOSS PER TRADE IN PERCENT", 1, 0 ,50,1);
XS =ExRem(Cross (1-(x1/100),e), Buy==1);
Sell=IIf( XS==1 AND ML==True, 2, 0); 



//////////////////////////////  SETTINGS AND BASIC DEFINITIONS////////////////////

SetOption("MaxOpenPositions", 2 ); 
PositionSize = 10000;
GraphXSpace=10;   /*"adds 10% extra space above AND below the graph line." In order to fit the extra text
						"When GraphXSpace is NOT defined in the formula then default 2% is used."*/
dist=200;
bcolor=scolor=colorBlue;


//////////////////////////////  EXIT AND ENTRY MARKERS DEFINED ////////////////////
PlotShapes( Buy* shapeUpArrow , bcolor, 0); 
PlotShapes( Short* shapeDownArrow , scolor, 0); 

sellshape = IIf( Sell == 1, shapeSquare + shapePositionAbove, 
			  	IIf( Sell == 2, shapeSquare + shapePositionAbove, 
			  	IIf( Sell == 3, shapeSquare + shapePositionAbove, 
				IIf( Sell == 4, shapeSquare + shapePositionAbove, 
				IIf( Sell == 5, shapeSquare + shapePositionAbove,0 ))))); 

Covershape=	IIf( Cover == 1, shapeSquare, 
			  	IIf( Cover == 2, shapeSquare, 
			  	IIf( Cover == 3, shapeSquare, 
				IIf( Cover == 4, shapeSquare, 
				IIf( Cover == 5, shapeSquare,0 ))))); 

LColor= IIf(Lprofit>0, colorGreen, colorRed);
Scolor=IIf(Sprofit>0, colorGreen, colorRed);
PlotShapes( SellShape, Lcolor, 0, C);
PlotShapes( covershape, Scolor, 0, C);

_SECTION_BEGIN("Chandelier Exit or Advanced Trailing Stop");
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
//  Chandelier Exit v2 by Geoff Mulhall
//
//  Modified 1-Feb-2003 to take advantage of Ami 2.5 Param Functionality and to
//  allow for Short Trades as well as Long Trades. The Chandelier Exit is a
//  Volatility based exit. Refer to http://www.traderclub.com/discus/board.html
//  Bulletin 35 Trailing Stops - The Chandelier Exit for more detail. Set
//  Scaling to Automatic, Set Gridlines as follows Level 0 On, Show dates On,
//  Middle On Right Click anywhere in the Chart, Select Parameters to get the
//  Param Dialogue and move the slides to see the effect of changing
//  ATRMultiplier ATRRange &amp; HHVRange.
//
//------------------------------------------------------------------------------


/* Chandelier Exit v2 */
/* by Geoff Mulhall */ 
/* Modified 1-Feb-2003 to take advantage of Ami 2.5 Param Functionality */
/* and to allow for Short Trades as well as Long Trades */
/* The Chandelier Exit is a Volatility based exit. */
/* Refer to http://www.traderclub.com/discus/board.html 
/* Bulletin 35 Trailing Stops - The Chandelier Exit for more detail */
/* Set Scaling to Automatic, Set Gridlines as follows Level 0 On, Show dates On, Middle On */
/* Right Click anywhere in the Chart, Select Parameters to get the Param Dialogue and move the slides to */
/* see the effect of changing ATRMultiplier ATRRange & HHVRange */ 
 
/* Plot the Chart */
//Title = "Chandelier"; 
GraphXSpace = 2;
/* Candle chart */ 
Plot(Close,"Close",1,1);
//Plot(WMA(Close,30),"Close WMA30",4,1);
/* Chandelier Exit */
/* Param( "ATRMultiplier", default, Min, Max, step ); */
ShortLongSwitch = Param( "Sht(0) Lng(1)",1,0,1,1); // Set to 0 for a Short Trade, 1 for a Long Trade
HighCloseSwitch = Param( "C(0) H/L(1)",1,0,1,1); // Set to 0 to hang from the close, 1 for High (Long) or Low (Short)
ATRMultiplier =3.0;// Param( "ATR Mult", 3.0, 1, 4, 0.1);
ATRRange =10; // Param( "ATR Rng", 10, 2, 30, 1);
HHVLLVRange =10;// Param( "HHVLLV Rng", 10, 2, 30, 1);
LongExitHungExHigh = HHV(High - AtrMultiplier * ATR(AtrRange),HHVLLVRange);
LongExitHungExClose = HHV(Close - AtrMultiplier * ATR(AtrRange),HHVLLVRange);
ShortExitHungExLow = LLV(Low + AtrMultiplier * ATR(AtrRange),HHVLLVRange);
ShortExitHungExClose = LLV(Close + AtrMultiplier * ATR(AtrRange),HHVLLVRange);
LongExit = IIf(HighCloseSwitch == 1, LongExitHungExHigh,LongExitHungExClose);
ShortExit = IIf(HighCloseSwitch == 1, ShortExitHungExLow,ShortExitHungExClose);
Exit1 = IIf(ShortLongSwitch == 1, LongExit, ShortExit);
Exit0 = shortExit;
Plot(Exit1,"Chandelier Green",colorBrightGreen,styleLine); 
Plot(Exit0,"Chandelier Red",colorRed,styleLine); 
G0 = Close;
G1 = Exit1;
G2 = Exit0;
Buy = Cross(G0,G1); // OR Cross(G0,G2);
//Cover = Cross(G0,G1); // OR Cross(G0,G2);
Sell = Cross(G2,G0); // OR Cross(G1,G0);
//Short = Sell ; //Cross(G2,G0); // OR Cross(G1,G0);
Short=Sell;
Cover=Buy;
Buy=ExRem(Buy,Sell); Sell=ExRem(Sell,Buy); Short=ExRem(Short,Cover); Cover=ExRem(Cover,Short);
Equity(1);
B1 = (Buy * Close);
S1 = (Sell * Close);
B2= B1>S1;
S2= S1>B1;
Equity(1);
Buy1 = Buy;
Sell1 = Sell;
//////////////////////////////////////
//Plot(B1, "B1",5,6);
PlotShapes( IIf( Sell , shapeSmallDownTriangle/*+ "shapePositonAbove"*/, shapeNone ), colorRed );
PlotShapes( IIf( Buy , shapeSmallUpTriangle/*+ "shapePositonAbove"*/, shapeNone ), colorBrightGreen ); 
Plot(10, /* defines the height of the ribbon in percent of pane width */"",IIf( B2, colorBrightGreen, IIf( S2, colorRed, 0 )), /* choose color*/styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );
 
_SECTION_END();


/*======================================================
		FOREX INTRADAY HEIKIN ASHI + PIVOT POINTS
  ======================================================*/

//---- heikin ashi
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 ) ); 
xDiff = (HaHigh - Halow) * IIf(StrFind(Name(),"JPY"),100,10000);
barcolor = IIf(HaClose >= HaOpen,colorGreen,colorRed);
PlotOHLC( HaOpen, HaHigh, HaLow, HaClose, "", barcolor, styleCandle ); 
// Plot(EMA(HaClose,9),"",colorWhite, styleLine);
// Plot(EMA(HaClose,18),"",colorBlack, styleLine);

_SECTION_BEGIN("Bollinger Bands");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 100, 1 );
Width = Param("Width", 2, 0, 10, 0.05 );
Color = ParamColor("Color", colorCycle );
Style = ParamStyle("Style");
Plot( BBandTop( P, Periods, Width ), "BBTop" + _PARAM_VALUES(), Color, Style );

Plot( BBandBot( P, Periods, Width ), "BBBot" + _PARAM_VALUES(), Color, Style );

_SECTION_END();

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




//////////////////////////////  FOR LOOP FOR PLOTING ENTRY AND EXIT TEXT////////////////////
for( i = 0; i < BarCount; i++ ) 
{ 

	xx  = Sum(Buy,i ); // counting of long trades. xx will not get a higher value until a new long position is Open
						// therefor if we only allow one long and one short position (Exrem() ) xx can also be used as an identification 
						//	number for the diffrent positions. 
	yy  = Sum(Short,i);
	

		if( Buy[i]==1)  PlotText("LONG : " + xx[i] + "\nBuyPrice: "+ BuyPrice[ i ], i, H[ i ]-dist, colorBlack, bcolor ); 
   
				if( Sell[i]==1 ) PlotText( "LONG : " +xx[i]+ "\nREGULAR EXIT\n"+ "Sell:  "+ SellPrice[ i ]+"\nP/ L:     " 
				+Lprofit[ i ], i, H[ i ]+dist, colorBlack, Lcolor[i] ); 
				if( Sell[i]==2 ) PlotText( "LONG : " +xx[i]+ "\nMAXIMUM LOSS\n"+ "Sell:    "+ SellPrice[ i ] +"\nP/ L:     " 
				+Lprofit[ i ], i, H[ i ]+dist, colorBlack, Lcolor[i] ); 
				if( Sell[i]==3 ) PlotText( "LONG : " +xx[i]+ "\nPROFIT TARGET\n"+ "Sell:   "+ SellPrice[ i ] +"\nP/ L:     " 
				+Lprofit[ i ], i, H[ i ]+dist, colorBlack, Lcolor[i] ); 
				if( Sell[i]==4 ) PlotText( "LONG : " +xx[i]+ "\nTRAILING STOP\n"+ "Sell:   "+ SellPrice[ i ] +"\nP/ L:     " 
				+Lprofit[ i ], i, H[ i ]+dist, colorBlack, Lcolor[i] ); 
				if( Sell[i]==5 ) PlotText( "LONG ; " +xx[i]+ "\nNBAR STOP\n"+ "Sell:       "+ SellPrice[ i ] +"\nP/ L:     " 
				+Lprofit[ i ], i, H[ i ]+dist, colorBlack, Lcolor[i] ); 
		
	
		if( Short[i]==1 ) PlotText( "SHORT : "+ yy[i]+ "\nShortprice: "+ ShortPrice[ i ], i, L[ i ]-dist, colorBlack, bcolor ); 

				if( Cover[i]==1 ) PlotText( "SHORT : " +yy[i]+ "\nREGULAR EXIT\n"+ "Cover: "+ CoverPrice[ i ]+"\nP/ L:    " 
				+Sprofit[ i ], i, H[ i ]+dist, colorBlack, Scolor[i] ); 
				if( Cover[i]==2 ) PlotText( "SHORT : " +yy[i]+ "\nMAXIMUM LOSS\n"+ "Cover: "+ CoverPrice[ i ]+"\nP/ L:    " 
				+Sprofit[ i ], i, H[ i ]+dist, colorBlack, Scolor[i] ); 
				if( Cover[i]==3 ) PlotText( "SHORT : " +yy[i]+ "\nPROFIT TARGET\n"+ "Cover:"+ CoverPrice[ i ]+"\nP/ L:    " 
				+Sprofit[ i ], i, H[ i ]+dist, colorBlack, Scolor[i] ); 
				if( Cover[i]==4 ) PlotText( "SHORT : " +yy[i]+ "\nTRAILING STOP\n"+ "Cover:"+ CoverPrice[ i ]+"\nP/ L:    " 
				+Sprofit[ i ], i, H[ i ]+dist, colorBlack, Scolor[i] ); 
				if( Cover[i]==5 ) PlotText( "SHORT : " +yy[i]+ "\nNBAR STOP\n"+ "Cover:    "+ CoverPrice[ i ]+"\nP/ L:    " 
				+Sprofit[ i ], i, H[ i ]+dist, colorBlack, Scolor[i] ); 
}