/*
//System3
//=================================
// NW 0903, AB 5.23, Status: Developmental
//
// This Script is for EDUCATIONAL PURPOSES ONLY. It is NOT a TRADABLE SYSTEM.
// ---------------------------------------------------------------------------
//
// Futures System
//
// StopLoss 1.5 ATR 10
// Population: ASX300, 1/7/02 - 30/6/07, Number of positions, Liquidity; all assumed
// Trades assessed on the Close overnight, entries and exits on the Open next Bar
// Standard brokerage (0.11%, $30 min, - E-Trade) and interest on cash (5%).
// Database : FTSE
// Objective : FTSE
// Settings : FTSE
//
//
// Set Backtest Conditions
// =======================
// Set Starting Equity
*/
EqtSttAmt = 20000 ; // Equity Start Amount
//
// #### Defines market hours
//##########################################################
RequestTimedRefresh( 1 );
DOW = Now( 9 );//day of the week
WeekEnd = IIf( ( DOW == 1 OR DOW == 7 ), 1, 0 );
Time = TimeNum();
MarketOpen = 100000;//08:00:00;
MarketClose = 163000;//20:00:00 or 163000
MarketON = TimeNum() >= MarketOpen AND (Now( 4 ) < MarketClose) AND NOT WeekEnd;
MarketOFF = IIf(TimeNum() >= MarketClose,0,1) ;//day's over
Hhmod = frac( MArketclose / 10000 );
//
// Population and Position sizing
// ==============================
//
// Set Number of positions (as a % of Current Equity)
//PosOpnMax = 1 ; //Optimize("NumPos", 10, 5, 15, 1) ;
//PositionSize = 1 / PosOpnMax ;
PositionSize = MarginDeposit = 1; // Required for trading futures contracts
//
// Set Population Minimum Turnover (Liquidity)
LiqMinCur = 400 ; //Optimize("LiqMin-K", 400, 300, 1000, 50) ;
LiqSmaPed = 20 ;
LiqActAmt = MA(C * V, LiqSmaPed) / 1000 ;
LiqActSwt = LiqActAmt > LiqMinCur ;
/* First we need to enable custom backtest procedure and
** tell AmiBroker to use current formula
*/
SetCustomBacktestProc("");
/* Now custom-backtest procedure follows */
if( Status("action") == actionPortfolio )
{
bo = GetBacktesterObject();
bo.Backtest(); // run default backtest procedure
st = bo.GetPerformanceStats(0); // get stats for all trades
// Expectancy calculation (the easy way)
// %Win * AvgProfit - %Los * AvgLos
// note that because AvgLos is already negative
// in AmiBroker so we are adding values instead of subtracting them
// we could also use simpler formula NetProfit/NumberOfTrades
// but for the purpose of illustration we are using more complex one :-)
expectancy = st.GetValue("WinnersAvgProfit")*st.GetValue("WinnersPercent")/100 +
st.GetValue("LosersAvgLoss")*st.GetValue("LosersPercent")/100;
// Here we add custom metric to backtest report
bo.AddCustomMetric( "Expectancy ($)", expectancy );
}
//
// External Functions
// ==============================
//
function Pivot ()
{
return (High+Low+Close)/3;
};
function PivotRibbon(PivotMA)
{
Result=0;Uptrend=0;Dntrend=0;
FastP=Pivot();
SlowP=MA( FastP, PivotMA ); // Usally3
Uptrend=IIf(FastP>SlowP,True,False);
Dntrend=IIf(FastP<SlowP,True,False);
Result = IIf( Uptrend,1,IIf( Dntrend,-1,0));
return Result;
};
function PivotHist(SMAPeriods,PivotPeriods)
{
P = ParamField("Price field",-1);
// Periods = Param("SMA Periods", SMAPeriods, 2, 300, 1, 10 );
// PPeriods = Param("Pivot Periods", PivotPeriods, 2, 300, 1, 10 );
Periods = SMAPeriods;
PPeriods = PivotPeriods;
i = MA(P, Periods )-MA(Pivot(),PPeriods);
return I ;
}
// ==========================================================================================
//
// Entry Conditions
// ================
//
// Optimise variables for Entry formula
//EntSmaSht = Optimize("EntSmaSht", 5, 3, 30, 1) ; //40
//EntSmaLng = Optimize("EntSmaLng", 8, 5, 30, 1) ; //110
//EntCrsSht = Optimize("EntCrsSht", 10, 2, 16, 2) ;
//EntCrsLng = Optimize("EntCrsLng", 16, 2, 16, 2) ;
//TrendFilter = Optimize("MA Periods", 165, 5, 200, 5) ;
TrendFilter = 165 ;
//EntSMAPeriods = Optimize("SMA Periods", 11, 1, 20, 1) ;
//EntPivotPeriods = Optimize("Pivot Periods", 12, 1, 20, 1) ;
//EntRibbon = Optimize("Ribbon MA", 3, 1, 10, 1) ;
EntSMAPeriods = 11 ;
EntPivotPeriods = 12 ;
EntRibbon = 2 ;
RiskAmount=Optimize("RiskAmount",Param("RiskAmount",10),5,30,1);
//RiskAmount=15;
//
// Generate a Buy Signal (Entry)
EntSigSwt =
(PivotRibbon(EntRibbon)==1)
AND ((PivotHist(EntSMAPeriods,EntPivotPeriods) > 0) OR ((PivotHist(EntSMAPeriods,EntPivotPeriods) > Ref(PivotHist(EntSMAPeriods,EntPivotPeriods),-1))))
AND V > Ref(V,-1)
AND C > (H+L)/2
AND MA(Close,TrendFilter) > Ref(MA(Close,TrendFilter),-1)
AND (TimeNum() > 100000) AND (TimeNum() < 160000)
//AND (DateNum()>1090518)
;
//IIf((PivotRibbon(3)==1) AND (PivotHist() > 0), BuySigInd=1,0);
//
// Sell signals (None in this model)
// ---------------------------------
//ExtSigSwt = Close < SAR(0.02,0.2 ) ;
ExtSigSwt = Close < MA(Close,8) ;
Plot(MA(Close,8), "ESL", colorGreen, styleLine) ;
//
// Initial Stop Loss
//------------------ // Number of Bars for ISL ATR
IslAtrBar = 3;//IslAtrBar = Optimize("IslATRBars", 3, 3, 10, 1) ;
//IslAtrBar = 5 ;
// ATR Factor
IslAtrFac = 2.6;//IslAtrFac = Optimize("IslAtrFac", 2.6, 0.4, 3, 0.2) ;
//IslAtrFac = 2.2 ;
//
// Trailing Stop Loss
// -------------------
// Number of Bars for TSL ATR calc
TslAtrBar = 3; //TslAtrBar = Optimize("TslAtrBar", 6, 3, 10, 1) ;
//TslAtrBar = 5 ;
// ATR Factor
TslAtrFac = 2 ;//TslAtrFac = Optimize("TslATRFac", 2.6, 1.0, 3, 0.2) ;
//TslAtrFac = 2.8 ;
//
// Trade Processing Loop
// =====================
//
// Set arrays to a starting condition
Buy = 0 ;
Sell = 0 ;
BuySigInd = 0 ;
SelSigInd = 0 ;
IslPntArr = Null ;
TslPntArr = Null ;
IslBarStp = 0 ;
TslBarStp = 0 ;
IslBarGap = IslAtrFac * ATR(IslAtrBar) ;
TslBarGap = TslAtrFac * ATR(TslAtrBar) ;
TrdBarCnt = 0 ;
TrdProfit = 0 ;
TrdEntry = 0;
Position = 0 ;
Free_Trade = 0;
Initial_Stop = 0;
HalfBreakEven = 0;
FullBreakEven = 0;
LossSigInd = 0 ;
TradeEntryPrice = 0;
HalfBreakEvenReached=0;
//
//
// Trade Processing Loop proper
for( i = 1 ; i < BarCount ; i++)
{
if(i < BarCount -1)
{
// Buy processing
if( EntSigSwt[i] AND Position[i]==0 )// AND ! TslBarStp[i])// AND EntSigSwt[i-1])// AND TrdBarCnt[i+1] = 1)
{
BuySigInd[i] = 1 ;
Position[i+1] = 1 ; // Entered Long Position
Buy[i+1] = 1 ;
BuyPrice[i+1] = O[i+1] ;
Initial_Stop[i+1]=BuyPrice[i+1]-RiskAmount;
Free_trade[i]=0;
TradeEntryPrice[i+1]=BuyPrice[i+1];
TrdProfit[i+1]=Close[i+1]-BuyPrice[i+1];
TrdBarCnt[i+1]=1;
Initial_Stop[i]=BuyPrice[i+1]-RiskAmount;
IslPntArr[i +1] = Initial_Stop[i] ; // Update the ISL Line
HalfBreakEvenReached[i]=0;
}
// Sell processing
if(Position[i]==1)
{
if(Free_Trade[i]==1)
{ // Execute Trailing Stop
TslPntArr[i +1] = TslPntArr[i +1] ; // Update the TSL Line
if(ExtSigSwt[i])
{
Sell[i +1] = 1 ;
SellPrice[i +1] = O[i + 1] ;
SelSigInd[i]=1;
// Clear_Static_Variables
Position[i]=0;
Free_trade[i]=Null;
};
}
else
{
if( High[i]-RiskAmount>TradeEntryPrice[i])
{ // Free Trade - Adjust to breakeven point
if(Initial_Stop[i] < TradeEntryPrice[i])
{
Initial_Stop[i] = TradeEntryPrice[i];
};
IslPntArr[i] = Initial_Stop[i] ; //
TslPntArr[i] = Close[i] ; // Update the ISL Line
Free_Trade[i] = 1; // Move onto trailing stop
FullBreakEven[i] = 1; // Display Star
}
else
if( High[i]-(RiskAmount/2)>TradeEntryPrice[i] AND HalfBreakEvenReached[i]==0)
{ // 1/2 point of a breakeven trade
HalfBreakEven[i]=1;
HalfBreakEvenReached[i]=1;
if(Initial_Stop[i] < (TradeEntryPrice[i]-(RiskAmount/2)))
{
Initial_Stop[i] = TradeEntryPrice[i]-(RiskAmount/2);
};
IslPntArr[i] = Initial_Stop[i] ; //
}
else
if( TrdBarCnt[i]>5)
{ // Sideways Stop
if(Low[i]>Initial_Stop[i])
{
Initial_Stop[i] = Low[i] ;
IslPntArr[i] = Initial_Stop[i] ; //
}
};
if(Close[i]<Initial_Stop[i] AND Initial_Stop[i]>TradeEntryPrice[i]) // Above Entry but sideways
{ // Exit due to either a time stop or a breach of the Initial stop
Sell[i] = 1 ;
SellPrice[i] = Initial_Stop[i] ;
LossSigInd[i]=1;
Position[i]=0;
}
if(Low[i]<Initial_Stop[i] AND Initial_Stop[i]<TradeEntryPrice[i]) // Below Entry but sideways
{ // Exit due to either a time stop or a breach of the Initial stop
Sell[i] = 1 ;
SellPrice[i] = Initial_Stop[i] ;
SidewaysSigInd[i]=1;
Position[i]=0;
}
if(TrdBarCnt[i]>72)
{ // Exit due to either a time stop or a breach of the Initial stop
Sell[i] = 1 ;
SellPrice[i] = Initial_Stop[i] ;
LossSigInd[i]=1;
Position[i]=0;
}
}
}
// Somewhere between the Entry and the exit
if( Position[i]==1 )
{
// IslBarStp[i +1] = C[i] - IslBarGap[i] ;
IslBarStp[i +1] = IslBarStp[i] ;
IslPntArr[i +1] = IslPntArr[i] ; // Update the ISL Line
TslBarStp[i +1] = C[i] - TslBarGap[i] ;
TslPntArr[i+1] = TslPntArr[i] ;
TrdEntry[i+1] = O[i +1];
TrdProfit[i+1] = Close[i+1]-TradeEntryPrice[i];
TrdBarCnt[i+1] = TrdBarCnt[i] +1;
Position[i+1] = Position[i];
Free_trade[i+1] = Free_trade[i];
Initial_Stop[i+1] = Initial_Stop[i];
HalfBreakEvenReached[i+1]=HalfBreakEvenReached[i];
TradeEntryPrice[i+1] = TradeEntryPrice[i];
}
}
}
/*
// Sell processing
if(Position=1 AND (ExtSigSwt[i] OR C[i] < IslBarStp[i] OR C[i] < TslBarStp[i]) AND TslBarStp[i] > 0)
{
SelSigInd[i] = 1 ;
if( i < BarCount -1)
{
TrdBarCnt[i +1] = TrdBarCnt[i] + 1 ;
if(MarketOFF[i]==0)
{
Sell[i +1] = 1 ;
SellPrice[i +1] = O[i + 1] ;
}
else
{
Sell[i +1] = 1 ;
SellPrice[i +1] = O[i + 1] ;
}
StaticVarSet("Position",0);
}
} else // Main Trade loop
{
// if((TslBarStp[i] > 0) OR (IslBarStp[i] > 0) AND (i < BarCount -1))
if(Position=1 AND (i < BarCount -1))
{ // Keep array up to date
TrdBarCnt[i +1] = TrdBarCnt[i] + 1 ;
IslBarStp[i +1] = IslBarStp[i] ;
TrdEntry[i +1] = TrdEntry[i] ;
TrdProfit[i+1] = Close[i+1]-TrdEntry[I+1]; // Update Trade Profit
if(C[i+1] < (TrdEntry[i+1]+ RiskAmount[i+1]))
{ // Entry Cover
//if(TrdProfit[i+1] > RiskAmount[i+1]/2)
// IslBarStp[i +1] = (TrdProfit[i+1] - RiskAmount[i+1])+TrdEntry[i+1];
//if(TslBarStp[i +1] < IslBarStp[i +1])
IslBarStp[i +1] = Max(H[i +1] - TslBarGap[i +1], IslBarStp[i]) ;
IslPntArr[i +1] = IslBarStp[i +1] ; // Update the ISL Line
}
else
{ // Re calc trailing stop
TslBarStp[i +1] = Max(C[i +1] - TslBarGap[i +1], TslBarStp[i]) ; // Should be at least C if not H
//if(TslBarStp[i +1] > IslBarStp[i +1])
TslPntArr[i +1] = TslBarStp[i +1] ; // Update the TSL Line
}
}
}
*/
//
ToolTip=StrFormat( "Position: %g", Position);
ToolTip=StrFormat( "Free_Trade: %g", Free_Trade);
ToolTip=StrFormat( "TradeEntryPrice: %g", TradeEntryPrice);
ToolTip=StrFormat( "TrdProfit: %g", TrdProfit);
ToolTip=StrFormat( "RiskAmount: %g\n", RiskAmount);
ToolTip=StrFormat( "Initial_Stop: %g\n", Initial_Stop);
ToolTip=StrFormat( "IslBarStp: %g", IslBarStp);
ToolTip=StrFormat( "IslPntArr: %g\n", IslPntArr);
ToolTip=StrFormat( "TslBarStp: %g", TslBarStp);
ToolTip=StrFormat( "TslPntArr: %g\n", TslPntArr);
ToolTip=StrFormat( "X: %g", C);
ToolTip=StrFormat( "Y: %g\n", TrdEntry+ RiskAmount);
//ApplyStop( stopTypeNBar, stopModeBars, 2 ,1); // Time Stop
//ApplyStop(stopTypeLoss, stopModePoint, 7.5,1,False );
//AddTextColumn( string, Name, format = 1.2, textColor = colorDefault, bkgndColor = colorDefault, width = -1 )
//AddTextColumn( Close, "Name", format = 1.2, colorRed, colorBlue,5 ) ;
//AddTextColumn( Group_id(1), "Name" ) ;
AddColumn(Buy, "Buy2", 1);
//
// Format Simple Chart
// ===================
GraphXSpace = 5 ;
PlotShapes(BuySigInd * shapeSmallUpTriangle, colorGreen, 0, Low - ATR(5)) ;
PlotShapes(SelSigInd * shapeSmallDownTriangle, colorRed, 0, High + ATR(5)) ;
PlotShapes(Buy * shapeUpArrow, colorGreen, 0, Low - ATR(5)) ;
PlotShapes(Sell * shapeDownArrow, colorRed, 0, High + ATR(5)) ;
PlotShapes(HalfBreakEven * shapeHollowStar, colorRed, 0, High + ATR(5)) ;
PlotShapes(FullBreakEven * shapeStar, colorRed, 0, High + ATR(5)) ;
PlotShapes(LossSigInd * shapeCircle, colorRed, 0, High + ATR(5)) ;
//PlotShapes(SidewaysSigInd * shapeSquare, colorRed, 0, High + ATR(5)) ;
//GraphZOrder = 2;
//PlotShapes(LossSigInd * 53, colorRed, 0, (High + Low+Close/3)) ;
//PlotText( "Sell\n@" + C, 0, H + ATR(10), colorRed, colorYellow );
Offset = High + ATR(10);
PlotText( "Sell\n@" + C, 0, Offset[0], colorRed, colorYellow );
//
Plot( C, "Price", colorBlack, styleCandle ) ;
//ToolTip=StrFormat( "Open: %g\nHigh: %g\nLow: %g\nClose: %g (%.1f%%)\nVolume: %g\nPivot: %g\n", O, H, L, C,NumToStr( V, 1 ));//,1,2, SelectedValue( ROC( C, 1 )),Pivot());
ToolTip=StrFormat( "Open: %g\nHigh: %g\nLow: %g\nClose: %g (%.1f%%)\nPivot: %g\nMarketoff:%6g\nTrdBarCnt:%6g\n", O, H, L, C,0,PivotRibbon(3),MarketOff,TrdBarCnt);
ToolTip=StrFormat( "Buy %g\nBuyPrice: %g\nTrdProfit: %g\nTrdEntry: %g\nClose: %g (%.1f%%)\nPivot: %g\nMarketoff:%6g\nTrdBarCnt:%6g\n", Buy,BuyPrice, TrdProfit, TrdEntry, C,0,PivotRibbon(3),MarketOff,TrdBarCnt);
ToolTip=StrFormat( "EntSigSwt %g\n", EntSigSwt);
ToolTip=StrFormat( "TrdEntry: %g\n", TrdEntry);
//
Plot(IslPntArr, "ISL", colorBlue, styleLine) ;
Plot(TslPntArr, "TSL", colorRed, styleLine) ;
//
//Plot( MA( C, EntSmaSht ), "MA-Short", colorGreen, styleDashed);
//Plot( MA( C, EntSmaLng ), "MA-Long", colorRed, styleDashed);
//Plot( MA( C, EntCrsSht ), "MA-Cross", colorGreen, styleLine | styleThick);
//Plot( MA( C, EntCrsLng ), "MA-Short", colorBlue, styleLine);
//
// System Settings
SetOption("InitialEquity", EqtSttAmt) ; // Set Initial Equity
//SetOption("MaxOpenPositions", PosOpnMax) ; // Maximum number of Open Positions
SetOption("AllowPositionShrinking", False) ; // Allow code to manage
//
// System is Long Only
Short=Cover=0 ;
//
// General Settings & Options
// ===================
// Set Optimizer engine
OptimizerSetEngine("cmae") ;
SetOption("ExtraColumnsLocation",1); // Put Custom Columns at the begining of the report
// END
Plot( 5, /* defines the height of the ribbon in percent of pane width
*/"Pivot Ribbon",
IIf( PivotRibbon(EntRibbon)==1, colorGreen, IIf( PivotRibbon(EntRibbon)==-1, colorRed, 0 )), /* choose color */
styleOwnScale|styleArea|styleNoLabel, -0.5, 100 );
_SECTION_END();
_SECTION_BEGIN("EMA");
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();
_SECTION_BEGIN("EMA1");
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();
_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();
|