AFL used in this case is given below
_SECTION_BEGIN( " PAPER TRADE COMPOSITE" );
/* Logging and displaying trades - USING A TRADE COMPOSITE
version PaperTrading_V5_Parameters 11th FEB
In real trading it is desirable to use a persistent trade record so that trades for multiple sessions be analyzed using the Backtester.
The easiest way to do this is to save the trades in a composite. The code shown below is a simplified version of what will be used
in the TDash104 system, however, it can be used with any trading system.
After placing some trades you can send the code to the Backtester for analysis.
http://www.amibroker.org/userkb/2011/03/29/using-a-trade-composite/
*/
#include <ControlPanelInclude-004.afL>
global ColNumber;
ButtonHeight = Param("Button Height",13,5,200,1);
ButtonWidth = Param("Button Width",102,5,200,1);
PanelYoffset = Param("Button Row Offset (px)",40,0,Status("pxheight"),1);
PanelXoffset = Param("Button Column Offset (px)",2,0,Status("pxwidth"),1);
FontRatio = Param("Font: ButtonHeight ratio",1.9,1,20,0.1);
DoubleClickInterval = Param("Double Click Max. Interval",330,1,1000,1);
ButtonColumnBegin( "0" );
ButtonHeader( "Virtual Trade", colorBlue, colorBlue,colorWhite);
pBUY = ButtonTrigger( "BUY", colorGreen, colorWhite, colorBlack);
pSELL = ButtonTrigger( "SELL", colorGrey40, colorWhite, colorBlack);
pSHORT = ButtonTrigger( "SHORT", colorRed, colorWhite, colorBlack);
pCOVER = ButtonTrigger( "COVER", colorGrey40, colorWhite, colorBlack);
pREVLONG= ButtonTrigger( "Reverse to Long", colorBrightGreen, colorWhite, colorBlack);
pREVSHORT= ButtonTrigger( "Reverse to Short", colorBrightGreen, colorWhite, colorBlack);
pEmptyTitle= ButtonTrigger( "= EMPTY LAST =", colorAqua, colorWhite, colorBlack);
// ButtonText( "= Delete Title =", colorAqua, colorBlue);
pArrowsOFF=ButtonRotate( "SIGNALS-ON,SIGNALS-OFF", "1,1,1", "5,50,41" );
pOrderType=ButtonRotate( "FOREX,DECIMAL,INTEGER", "1,1,1", "5,50,41" ); // 2,2,2, 3 ( 2,0,0 )
chartImage = ButtonTrigger( "Foto", colorBrightGreen, colorRed, colorBlack);
pDELETE = ButtonTrigger( "Delete History", colorBlack, colorWhite, colorOrange);
ButtonColumnEnd( );
// --------END -- button Rotate ---------------
// SIGNALS-ON / OFF Show/hide trade arrows
switch( pArrowsOFF)
{
case "SIGNALS-ON":
StaticVarSet("--pArrowsON",1); pArrows=StaticVarGet("--pArrowsON");
break;
case "SIGNALS-OFF":
StaticVarSet("--pArrowsOFF",0); pArrows=StaticVarGet("--pArrowsOFF");
break;
}
// ---- Decimals
//dec = (Param("Decimals",4,0,7,1)/10 )+1; // to Parameters Window
decN = pOrderType;
switch( decN)
{
case "FOREX":
dec =(4/10)+1;
break;
case "DECIMAL":
dec= (2/10)+1;
break;
case "INTEGER":
dec =1;
break;
// etc.
}
// GfxTextOut( ""+Prec(LastValue(C),decN),120,241);
function DeleteComposite( CompositeName )
{
global Ticker;
oAB = CreateObject( "Broker.Application" );
oStocks = oAB.Stocks();
oStocks.Remove( CompositeName );
oAB.RefreshAll();
}
function AddTradeToComposite( Ticker, Action, LMTPrice )
{
global Ticker;
BI = BarIndex();
LBI = LastValue( BI );
if ( Action != "" )
{
SignalArray = Nz( Foreign( Ticker + "~SignalArrays", "V", False ) );
BuyPriceArray = Nz( Foreign( Ticker + "~SignalArrays", "O", False ) );
SellPriceArray = Nz( Foreign( Ticker + "~SignalArrays", "H", False ) );
ShortPriceArray = Nz( Foreign( Ticker + "~SignalArrays", "L", False ) );
CoverPriceArray = Nz( Foreign( Ticker + "~SignalArrays", "C", False ) );
switch ( Action )
{
case "BUY":
SignalArray[LBI] = SignalArray[LBI] | 1;
BuyPriceArray[LBI] = LMTPrice;
break;
case "SELL":
SignalArray[LBI] = SignalArray[LBI] | 2;
SellPriceArray[LBI] = LMTPrice;
break;
case "SHORT":
SignalArray[LBI] = SignalArray[LBI] | 4;
ShortPriceArray[LBI] = LMTPrice;
break;
case "COVER":
SignalArray[LBI] = SignalArray[LBI] | 8;
CoverPriceArray[LBI] = LMTPrice;
break;
case "REVLONG":
SignalArray[LBI] = SignalArray[LBI] | 8 | 1;
CoverPriceArray[LBI] = BuyPriceArray[LBI] = LMTPrice;
break;
case "REVSHORT":
SignalArray[LBI] = SignalArray[LBI] | 2 | 4;
SellPriceArray[LBI] = ShortPriceArray[LBI] = LMTPrice;
break;
}
AddToComposite( SignalArray, Ticker + "~SignalArrays", "V", 7 | atcFlagEnableInIndicator );
AddToComposite( BuyPriceArray, Ticker + "~SignalArrays", "O", 7 | atcFlagEnableInIndicator );
AddToComposite( SellPriceArray, Ticker + "~SignalArrays", "H", 7 | atcFlagEnableInIndicator );
AddToComposite( ShortPriceArray, Ticker + "~SignalArrays", "L", 7 | atcFlagEnableInIndicator );
AddToComposite( CoverPriceArray, Ticker + "~SignalArrays", "C", 7 | atcFlagEnableInIndicator );
}
} // end-- AddTradeToComposite
Ticker = Name();
Action = "";
LastC=LastValue( Close );
// ----- parameters
if ( pBuy ) {Action = "BUY"; kStaticVarSet("--pBuyPriceO",LastC); Say("b");}
if ( pSELL) {Action = "SELL"; kStaticVarSet("--pBuyPriceS",LastC);}
if ( pSHORT ) {Action = "SHORT"; kStaticVarSet("--pBuyPriceSort",LastC); Say("sort");}
if ( pCOVER ) {Action = "COVER"; kStaticVarSet("--pBuyPriceC",LastC);}
if ( pREVLONG) {Action = "REVLONG"; StaticVarRemove("--pBuyPriceSort*"); kStaticVarSet("--pBuyPriceO",LastC); }
if ( pREVSHORT ) {Action = "REVSHORT"; StaticVarRemove("--pBuyPriceO*"); kStaticVarSet("--pBuyPriceSort",LastC); }
if ( pEmptyTitle) {StaticVarRemove("--pBuyPrice*"); }
if ( pDELETE ) {DeleteComposite( Ticker + "~SignalArrays" ); }
AddTradeToComposite( Ticker, Action, LastValue( Close ) );
// Foreign()
RequestTimedRefresh( 0.1 );
if ( SetForeign( Ticker + "~SignalArrays" ) )
{
SignalArray = Nz( Foreign( Ticker + "~SignalArrays", "V", False ) );
Buy = IIf( SignalArray & 1, 1, 0 );
Sell = IIf( SignalArray & 2, 1, 0 );
Short = IIf( SignalArray & 4, 1, 0 );
Cover = IIf( SignalArray & 8, 1, 0 );
BuyPrice = Nz( Foreign( Ticker + "~SignalArrays", "O" ) );
SellPrice = Nz( Foreign( Ticker + "~SignalArrays", "H" ) );
ShortPrice = Nz( Foreign( Ticker + "~SignalArrays", "L" ) );
CoverPrice = Nz( Foreign( Ticker + "~SignalArrays", "C" ) );
if ( pArrowsOFF != "SIGNALS-ON" ) // Show/hide trade arrows
{
PlotShapes( IIf( Buy, shapeSmallUpTriangle, shapeNone ), colorBlue, 0, BuyPrice, -15 );
PlotShapes( Buy*shapeSmallCircle, colorWhite, 0, BuyPrice, 0 );
PlotShapes( IIf( Sell, shapeSmallDownTriangle, shapeNone ), colorBlue, 0, SellPrice, -15 );
PlotShapes( IIf( Sell, shapeSmallCircle, shapeNone ) ,colorWhite, 0, SellPrice, 0 );
PlotShapes( IIf( Short, shapeHollowDownTriangle, shapeNone ), colorOrange, 0, ShortPrice, -15 );
PlotShapes( Short*shapeSmallCircle, colorOrange, 0, ShortPrice, 0 );
PlotShapes( IIf( Cover, shapeHollowUpTriangle, shapeNone ), colorOrange, 0, CoverPrice, -15 );
PlotShapes( Cover*shapeSmallCircle, colorOrange, 0, CoverPrice, 0 );
}
}
RestorePriceArrays();
//--------- ------------------
function gfxPlotRightLine( YPixels, Color )
{
pxchartright= Status("pxchartright") ;
GfxSelectPen( Color ) ;
GfxMoveTo( pxchartright-20, YPixels );
GfxLineTo( pxchartright-200, YPixels );
}
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 ) );
}
// show me the Last Trade and the PROFIT
obp=Nz(kStaticVarGet("--pBuyPriceO"));
sbp=Nz(kStaticVarGet("--pBuyPriceS"));
shbp=Nz(kStaticVarGet("--pBuyPriceSort"));
cbp=Nz(kStaticVarGet("--pBuyPriceC"));
if (sbp OR cbp ) // empty before open a new trade
{ StaticVarRemove("--pBuyPrice*"); /*StaticVarRemove("--pBuyPriceO*");*/}
if(obp !=0 ) // for long trade
{
diferent=IIf(obp>LastC,LastC-obp,LastC-obp);
diferentColor=IIf(obp<LastC,colorBrightGreen ,colorOrange );
PosostoLong=((LastC- obp)/obp)*100;
if (LastC<(obp-12)) GfxTextOut( "Stop Lost Hit",300,100);
GfxSetTextColor( diferentColor);
GfxTextOut(""+NumToStr(obp,dec)+", ("+NumToStr(PosostoLong,1.2)+")",120,62);
GfxTextOut( "PROFIT "+NumToStr(diferent,dec),120,82);
PlotText(""+NumToStr(diferent,dec), BarCount + 1, LastValue(L,1), diferentColor); // LastValue(L,1),
gfxPlotRightLine( GfxConvertValueToPixelY( obp), colorGreen );
}
if(shbp!=0 ) // forShort trade
{
diferent=IIf(shbp>LastC,shbp-LastC,shbp-LastC);
diferentColor=IIf(shbp>LastC,colorBrightGreen ,colorOrange );
PosostoShort=((shbp- LastC)/LastC)*100;
if (LastC>(shbp+12)) GfxTextOut( "Stop Lost Hit",300,122);
GfxSetTextColor( diferentColor);
GfxTextOut( NumToStr(shbp,dec)+", ("+NumToStr(PosostoShort,1.2)+")",120,102);
GfxTextOut( "PROFIT "+NumToStr(diferent,dec),120,122);
PlotText(""+NumToStr(diferent,dec), BarCount + 1, LastValue(L,1), colorBlack,diferentColor); // LastValue(L,1),
gfxPlotRightLine( GfxConvertValueToPixelY( shbp), colorOrange );
}
// GfxGradientRect( 10, 10, 100, 100, colorWhite, colorGrey50 );
/*
/////////////------------------- this is an extra control panel for Bharat just in case he need it
ButtonColumnBegin( "1" );
ButtonHeader( "TRADES", colorBlue, colorBlue,colorWhite);
ButtonText( NumToStr(obp), colorAqua, colorBlue);
ButtonText( NumToStr(sbp), colorAqua, colorBlue);
ButtonText( NumToStr(shbp), colorAqua, colorBlue);
ButtonText( NumToStr(cbp), colorAqua, colorBlue);
ButtonColumnEnd( );
*/
if ( chartImage )
{ foto="C:\\temp\\exportChart.png"; // path to Export foto
Say("Foto");
AB = CreateObject("Broker.Application");
AW = AB.ActiveWindow;
AW.ExportImage(foto);
}
_SECTION_END();
_SECTION_BEGIN("Add On- exporation and tools");
// xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
SignalArraysExist = ParamToggle("PRESS ME IN EMERGENCY","HIDE|SHOW",0); if( SignalArraysExist )
{
// backtest by panos 05-01-07 last update for backtest 17-NOV-2011
// SetBarsRequired(10000,10); /* All bars are here and not only that we see in the chart */
SetTradeDelays( 0, 0, 0, 0 ); /* delay entry/exit by zero bar */
Buy= ExRem(Buy,Sell); Sell= ExRem(Sell,Buy);
Short= ExRem(Short,Cover); Cover=ExRem(Cover,Short);
//////////////--------------------- EXPLORATION
lastpriceBuy=ValueWhen(Buy,BuyPrice,1); // this holds the price of your BUY trade
lastpriceSELL=ValueWhen(Sell,SellPrice,1);
lastpriceShort=ValueWhen(Short,ShortPrice,1);
lastpriceCover=ValueWhen(Cover,CoverPrice,1);
BuyProfit= lastpriceSELL- lastpriceBuy; "BuyProfit= "+WriteVal(BuyProfit,1.4); // return a single trade BUY-Sell
ShortProfit =lastpriceShort-lastpriceCover;
//// Gainers/Lossers
monodesLong= Cum(BuyProfit) ;
monadesShort=Cum(ShortProfit );
total= monodesLong;
if(Status("Action")==actionScan OR Status("Action")==actionExplore)
{
Width60=60;
// Filter = Status("lastbarinrange");
Filter = Buy OR Sell OR Short OR Cover;
colorBuyProfit = IIf(BuyProfit>0,colorBrightGreen,colorRed);
ColorShortProfit = IIf(ShortProfit >0,colorBrightGreen,colorRed);
SetOption("NoDefaultColumns", True);
AddTextColumn(Name(), "Symbol", 77, 1, colorDefault, 70);
AddColumn(DateTime(), "Date", formatDateTime, 1, colorDefault, 120);
// these 5 linea are for Long trades
AddColumn(IIf(Buy, Asc("B",0), Asc("S")), "PosL", formatChar);
AddColumn( Buy, "Buy", 1 );
AddColumn(IIf( Buy, lastpriceBuy, Null ) ,"BUY",1.4,colorDefault,colorDefault,60);
//AddColumn(lastpriceSELL,"SELL",1.4,colorDefault,colorDefault,60); // <<<< i cut the null out but i will have all the results now this was my problem
AddColumn(IIf(Sell,lastpriceSELL,Null),"SELL",1.4,colorDefault,colorDefault,60); //Null here mean donot give me results
AddColumn(a1=IIf(Sell,lastpriceSELL- Ref(lastpriceBuy,-1),Null),"Long-Pip",1.4,colorDefault,colorBuyProfit ,60);
// these 5 linea are for Short trades
AddColumn(IIf(Short, Asc("S",0), Asc("C")), "PosS", formatChar);
AddColumn( Sell, "Cover", 1 );
AddColumn(IIf( Short, lastpriceShort, Null ) ,"Short",1.4,colorDefault,colorDefault,60);
AddColumn(IIf(Cover,lastpriceCover,Null),"Cover",1.4,colorDefault,colorDefault,60);
AddColumn(b1=IIf(Cover,Ref(lastpriceshort,-1)-lastpriceCover,Null),"ShortPip",1.4,colorDefault,ColorShortProfit ,60);
a3=IIf(Sell,a1,IIf( Cover,b1 ,Null)); // tell me the points of every trade
AddColumn(a3,"Gain/Lose",1.4,colorDefault,colorBuyProfit ,80); // contains wining trades of every 2 lines
// all above are corect for for BUY SELL sort cover
// in this line you can add a nuber of the column and returns the Total results in the Top of the column
AddSummaryRows( 1, 1.4, 4,7,9, 12,13,15);
} // end actionExplore
//--------------------- appearance of various signals of long / short in the chart
if( Status("Action")==actionIndicator )
{
SetChartOptions(0,chartShowArrows|chartShowDates);
strWeekday = StrMid("SunMonTueWedThuFriSat", SelectedValue(DayOfWeek())*3,3);
Title1=Name() +","+Date()+","+ " TimeFrame: " + Interval(2)+"\n Open "+O +", High " +H +", Low "+L +", Close "+C+ ", "+"(" +WriteVal(ROC(C,1),1.2)+"%)" ;
////////////////////// Arrows
belakiaBS = ParamToggle("Arrows Buy-Sell","HIDE|SHOW",0);
if( belakiaBS )
{
PlotShapes(IIf (Buy,shapeUpArrow,shapeNone),colorGreen,0,L,-30);
PlotShapes(IIf (Sell,shapeDownArrow,shapeNone),colorRed,0,H,-40);
PlotShapes(IIf (Sell,shapeSmallCircle,shapeNone),colorRed,0,O,0);
}
belakiaSC = ParamToggle("Arrows Short-Cover","HIDE|SHOW",0);
if( belakiaSC )
{
PlotShapes(IIf(Short,shapeSmallDownTriangle,shapeNone),colorRed,0,H,-30);
PlotShapes(IIf(Cover,shapeSmallUpTriangle,shapeNone),colorOrange,0,L,-40);
PlotShapes(IIf (Cover,shapeSmallCircle,shapeNone),colorOrange,0,O,0);
}
////////////////////// Sum Total buy and short positions
// Dear Panos, Regards Bharat
// Value of one lot of Nifty is approx. Rs.250,000 for which Rs.25000 margin is required.
// commission for 1 lot=Rs250 Stop=12
TotalPosBuy=Cum(Buy); x1=Cum(BuyProfit); x2=Sum(ShortProfit,98);
NumContracts = Param("NumContracts ", 1,1,100,1);
Commission = TickSize*Param("Commission",250,1,400,1); //commission for 1 lot=Rs250
TotalCommisionTrade =TotalPosBuy*NumContracts*Commission ;
TitleSynolo=" Total Position Buy ="+TotalPosBuy +"\n Num Contracts "+NumContracts + "\nTotal Commision Of BUY Trades RS = "+TotalCommisionTrade +
"";
EventNum =TotalPosBuy;
FirstVisibleBar = Status( "FirstVisibleBar" );
Lastvisiblebar = Status("LastVisibleBar");
for( b = Firstvisiblebar; b < Lastvisiblebar AND b < BarCount; b++)
{
dist = TickSize*9;
colorBuyProfit = IIf(BuyProfit
>0,colorGreen,colorRed);
ColorShortProfit = IIf(ShortProfit >0,colorGreen,colorRed);
////////////////////// PlotText Total Pos Buy appear
TextEventNum = ParamToggle("Event TotalPosBuy","HIDE|SHOW",0); if( TextEventNum )
{
if( Buy ) PlotText("\n\n\n\nEvent\n"+NumToStr(EventNum,1.0,False),b,L,colorWhite);
if( Sell ) PlotText("Event\n"+NumToStr(EventNum,1.0,False),b,H,colorWhite);
}
////////////////////// PlotText we appear gainers / lossers
TextPipsBS = ParamToggle("Plot Buy Pips","HIDE|SHOW",0); if( TextPipsBS )
{
if( Buy ) PlotText( "Buy\n\n" + lastpriceBuy , b, L-dist, colorBrightGreen ); //ColorShortProfit
if( Sell ) PlotText( "Sell\n"+lastpriceSELL +"\n" + WriteVal(BuyProfit ,1.4) , b, H+dist, colorBlack,colorBuyProfit );
}
TextPipsSC = ParamToggle("Plot Short Pips","HIDE|SHOW",0); if( TextPipsSC)
{
if( Short ) PlotText( "\n\n\nShort\n" + lastpriceShort, b, H+dist, colorOrange );
if( Cover ) PlotText( "\n\n\nCover\n"+ lastpriceCover+"\n"+WriteVal(ShortProfit ,1.4), b, L-dist, colorBlack, ColorShortProfit );
}
///////// END ///////////// PlotText we appear gainers / lossers
////////////////////// PlotText we appear the Time of the Trade
myDateTime = DateTime();
TextDateOnChart = ParamToggle("Plot Text Date Time","SHOW TextDate|HIDE TextDate",0);
if( TextDateOnChart )
{
if( Buy ) PlotText("\n\n\n"+NumToStr(myDateTime,formatDateTime) +"", b, H[ b ]-dist, colorLime );
if( Sell ) PlotText("\n\n\n"+NumToStr(myDateTime,formatDateTime)+"" , b, L[ b ]+dist, colorLime );
}
//////// END ////////////// PlotText we appear the Time of the Trade
} // end FirstVisibleBar
Eq = Equity( 1 );
if ( ParamToggle( "Equity", "HIDE|SHOW", 0 ) ) Plot( Eq, "", colorYellow, 1 | styleOwnScale );
Title=" # "+strWeekday+" # "+Title1 + "\n total ="+total +" Long Units = "+monodesLong +", Short Units= "+monadesShort+
"\n\n"; //+TitleSynolo ;
} // end actionIndicator
} // End SignalArraysExist
_SECTION_END();
// Plot( C, "Close", ParamColor("Color", colorGrey50), ParamStyle("Style") | GetPriceStyle() );
_SECTION_BEGIN("Candlestick Template");
formulaname="Candlestick Template.afl";
PlotCandle = ParamList("Candlestick Style","Amibroker Style|Chris Style|Panos Style|Panos IndicatorsOverBoughtSold|GEM Style|Bar Style|VPAStyle|Line Style",3);
//SetChartOptions( Mode = 0, Flags = 0, gridFlags = 0) ;
SetChartBkColor(ParamColor(" ",colorBlack));
switch( PlotCandle)
{
case "Amibroker Style":
Plot( C, "Close", ParamColor("Color", colorGrey50), ParamStyle("Style") | GetPriceStyle() );
break;
case "Chris Style":
Plot( C, "",IIf(C > O, colorGreen, IIf(C < O, colorRed, colorGrey50)), styleCandle );
break;
case "Panos Style":
SetBarFillColor( IIf( C > O, colorDarkBlue,colorDarkGrey));
Plot( C, "", IIf( C < O,colorGrey50, colorGrey50), styleCandle ) ;
break;
case "Panos IndicatorsOverBoughtSold":
OverBought = (StochK(14) > 80) AND (RSI(14) > 70) AND (CCI(14) >100);
Oversold =(StochK() < 20)AND (RSI(14) < 30) AND (CCI(14) < -100);
XROMA = IIf (OverBought, 4, IIf (Oversold ,5,ParamColor("Bar color.",colorGrey50)));
Plot( C, "C ", XROMA, 64); GraphXSpace=1;
break;
case "GEM Style":
SetBarFillColor( IIf( C > O, colorBrightGreen,colorRed));
Plot( C, "",IIf(C > O, colorGreen, IIf(C < O, colorRed, colorGrey50)), styleCandle );
break;
case "Bar Style":
Plot(C,"",colorGrey50,128);
break;
case "VPAStyle":
PlotOHLC( Null,H,L,C, "High =" +H +" Low =" + L + " Close", colorGrey50, styleBar );
break;
case "Line Style":
color = ParamColor("Bar color",colorGrey50); Plot(C,"Close",color);
break;
// etc.
}
_SECTION_END();