Home › Forums › Trading System Mentor Course Community › Trading System Brainstorming › Trading System Graveyard
- This topic is empty.
-
AuthorPosts
-
April 9, 2017 at 9:59 pm #101628Nick RadgeKeymaster
This thread is for discarded trading systems and ideas. Whilst what is presented here may not work for the user, it may work for other users or may provide ideas and other insights to be included in the ongoing research of members.
**Note** It is up to each user to validate the coding provided. It may have not been signed off by Craig or I and therefore all responsibility is on the user.
April 9, 2017 at 10:02 pm #106597Nick RadgeKeymasterHere is an old Turtle trading system I used for quite a number of years. I stopped trading it back in about 2012 as slippage on the ASX was costing me 11%pa
Code:///////////////////////////////////////////////////////11
// Turtle Original v2.5 – Apr10 – Monte Carlo_SECTION_BEGIN(“Monte Carlo”);
////////////////////////////////////////////////////////////////////////////////////
/////Monte Carlo Simulation
////////////////////////////////////////////////////////////////////////////////////
// MCS Monte Carlo Part 1 of 2
RUNS = Param(“Number of Runs”, 100,0,100000,100);
Run = Optimize (“Run”, 1,1,runs,1);MCP = Param(“Probability of Ignoring any Entry Signal %”, 25, 1,100,1);
//MCP = Optimize(“MCP”, 15,0,100,2);
_SECTION_END();_SECTION_BEGIN(“Historical Data Base Testing”);
////////////////////////////////////////////////////////////////////////////////////
/////Historical Data Base Testing
////////////////////////////////////////////////////////////////////////////////////
ASXList = ParamList(“ASX Historical Watchlist:”,”1: Off|2: ASX 20|3: ASX 50|4: ASX 100|5: ASX 200|6: ASX 300|7: ASX All Ordinaries|8: ASX Small Ordinaries|9: ASX Emerging Companies|10: Excluding ASX 300″,0);if(ASXList == “1: Off”) HistDB = 1;
if(ASXList == “2: ASX 20”) HistDB = IsIndexConstituent(“$XTL”);
if(ASXList == “3: ASX 50”) HistDB = IsIndexConstituent(“$XFL”);
if(ASXList == “4: ASX 100”) HistDB = IsIndexConstituent(“$XTO”);
if(ASXList == “5: ASX 200”) HistDB = IsIndexConstituent(“$XJO”);
if(ASXList == “6: ASX 300”) HistDB = IsIndexConstituent(“$XKO”);
if(ASXList == “7: ASX All Ordinaries”) HistDB = IsIndexConstituent(“$XAO”);
if(ASXList == “8: ASX Small Ordinaries”) HistDB = IsIndexConstituent(“$XSO”);
if(ASXList == “9: ASX Emerging Companies”) HistDB = IsIndexConstituent(“$XEC”);
if(ASXList == “10: Excluding ASX 300”) HistDB = IsIndexConstituent(“$XKO”)==0;////////////////////////////////////////////////////////////////////////////////////
USList = ParamList(“US Historical Watchlist:”,”1: Off|2: Russell 1000|3: Russell 2000|4: Russell 3000|5: NASDAQ 100|6: Dow Jones Industrial Average|7: S&P 500|8: S&P 100|9: S&P MidCap 400|10: S&P SmallCap 600|11: S&P 1500|12: Russell MicroCap|13: Russell MidCap”,0);
if(USList == “1: Off”) USHistDB = 1;
if(USList == “2: Russell 1000”) USHistDB = IsIndexConstituent(“$RUI”);
if(USList == “3: Russell 2000”) USHistDB = IsIndexConstituent(“$RUT”);
if(USList == “4: Russell 3000”) USHistDB = IsIndexConstituent(“$RUA”);
if(USList == “5: NASDAQ 100”) USHistDB = IsIndexConstituent(“$NDX”);
if(USList == “6: Dow Jones Industrial Average”) USHistDB = IsIndexConstituent(“$DJI”);
if(USList == “7: S&P 500”) USHistDB = IsIndexConstituent(“$SPX”);
if(USList == “8: S&P 100”) USHistDB = IsIndexConstituent(“$OEX”);
if(USList == “9: S&P MidCap 400”) USHistDB = IsIndexConstituent(“$MID”);
if(USList == “10: S&P SmallCap 600”) USHistDB = IsIndexConstituent(“$SML”);
if(USList == “11: S&P 1500”) USHistDB = IsIndexConstituent(“$SP1500”);
if(USList == “12: Russell MicroCap”) USHistDB = IsIndexConstituent(“$RUMIC”);
if(USList == “13: Russell MidCap”) USHistDB = IsIndexConstituent(“$RMC”);HDBFilter = HistDB AND USHistDB;
_SECTION_END();
_SECTION_BEGIN(“Price”);
SetChartOptions(0,chartShowArrows|chartShowDates);
////////////////////////////////////////////////////////////////
_N(Title = StrFormat(“{{NAME}} – {{INTERVAL}} {{DATE}}
Open: %g
Hi: %g
Lo: %g
Close: %g (%.1f%%)
Volume: ” +WriteVal( V, 1.0 ) +”
{{VALUES}}”, O, H, L, C, SelectedValue( ROC( C, 1 ) ),V ));
////////////////////////////////////////////////////////////////
PS = ParamToggle(“BarStyle”,”CandleStick | OHLC Bar “,1 ) ;
PlotStyle = IIf(PS, 128,64);
Col = IIf(C >= Ref(C,-1),5,4);
Colour = IIf(PS,Col,16);
Plot( C, “Close”, Colour, PlotStyle | styleNoTitle | ParamStyle(“Style”) | GetPriceStyle() );
////////////////////////////////////////////////////////////////
GraphXSpace = 20;
////////////////////////////////////////////////////////////////
_SECTION_END();
_SECTION_BEGIN (“Basic Share Filters”);
“Basic Share Filter”;
BasLiquid = ParamList(“Basic Filter : Entry Type”, “1 : Basic Filter Off|2 : Max-Min Share Price (Basic Price)|3 : Basic Price and Volume|4 : MA Turnover|5 : Basic Price and Turnover|6 : MA Volume|7 : Bar Volume”,5 );
////////////////////////////////////////////////////////////////
MinSP = Param(“Minimum Share Price – $”,0.05,0,10000000,0.001);
MaxSP = Param(“Maximum Share Price – $”,2,0,10000000,0.001);
MinVol = Param(“Minimum Volume”,300000,0,10000000,1);
MinTO = Param(“Minimum Turnover – $”,300000,0,10000000,1000);
MAVar = Param(“MA Period – “,7,1,1000,1);
////////////////////////////////////////////////////////////////
CondMinSp = C >= MinSP;
CondMaxSP = C <= MaxSP; //////////////////////////////////////////////////////////////// // 1 : No Filter Liquid1 = 1; // 2 : Max-Min Share Price (Basic Price) Liquid2 = CondMaxSP AND CondMinSp ; // 3 : Basic Price and Volume Liquid3 = Liquid2 AND V >= MinVol;
// 4 : MA Turnover
Turnover = C*V;
ToMA = MA(Turnover,MAVar);
Liquid4 = ToMA > MinTO;
// 5 : Basic Price and Turnover
Liquid5 = Liquid2 AND Liquid4;
// 6 : MA Volume
Liquid6 = Liquid5 AND MA(V,MAvar)>= MinVol;
// 7: Bar Volume
Liquid7 = V>= MinVol;
////////////////////////////////////////////////////////////////
if(BasLiquid == “1 : Basic Filter Off”) Liquidout= liquid1;
if(BasLiquid == “2 : Max-Min Share Price (Basic Price)”) Liquidout= liquid2;
if(BasLiquid == “3 : Basic Price and Volume”) Liquidout= liquid3;
if(Basliquid == “4 : MA Turnover”) Liquidout= Liquid4;
if(Basliquid == “5 : Basic Price and Turnover”) LiquidOut= Liquid5;
if(Basliquid == “6 : MA Volume”) LiquidOut= Liquid6;
if(Basliquid == “7 : Bar Volume”) LiquidOut= Liquid7;
////////////////////////////////////////////////////////////////
_SECTION_END();
_SECTION_BEGIN(“Index Filter Switch”);
/*Index Filter Switch*/
ForeignTicker = ParamStr(“Foreign Ticker”,”$XSO.asx”);
Index = Foreign(ForeignTicker,”C”);
IndexLBP = 100; //Index Filter MA Length
IndexfilterUp = Index > MA( Index, IndexLBP); //Index is UP
IndexfilterDn = Index < MA( Index, IndexLBP); //Index is DOWN RibbonColor = IIf( IndexfilterUp AND Liquidout, 27, 32); Plot ( 1, "", RibbonColor, styleArea | styleOwnScale | styleNoLabel, -0.0001, 190 ); _SECTION_END(); /////////////////////////////////////////////////////// // Clear Signals /////////////////////////////////////////////////////// Short = False; Cover = False; Buy = False; Sell = False; /////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// _SECTION_BEGIN ("Formula Parameters"); // Tick Sizes PxH = IIf(H >= 2.00, 0.01, IIf(H >= 0.10, 0.005, 0.001)); // Price Increment – High Tick
PxL = IIf(L <= 0.10, 0.001, IIf(L <= 2.00, 0.005, 0.010)); // Price Increment - Low Tick /////////////////////////////////////////////////////// // Parameters /////////////////////////////////////////////////////// ECHANNEL =30; //30 XCHANNEL =10; ATRBARS =15; ATRmulti =2.7; EnablePyramid = ParamToggle("Pyramid into Open Trades : ","False|True"); /////////////////////////////////////////////////////// // Variables and Calculations /////////////////////////////////////////////////////// UP =0; First =True; LASTB =Open; LASTS =99999; ATRma = MA(ATR(1),ATRBARS); HHVE =HHV(H,ECHANNEL); LLVE =LLV(L,ECHANNEL); _SECTION_END(); ////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////// _SECTION_BEGIN ("Formula Calcs"); /*-Up-*/ Minbars = Cum(1) > ECHANNEL;
Up = Flip(H > Ref(HHVE,-1) && Minbars,L < Ref(LLVE,-1) && Minbars); /*-LASTB-*/ for( j = 1 ; j < BarCount; j++ ) { if (up[j] && up[j-1] == False) { LASTB[j] = Max(HHVE[j-1],Open[j]); } else LASTB[j] = LASTB[j-1]; } /*-LASTS-*/ for( j = 1 ; j < BarCount; j++ ) { if (up[j]==False && up[j-1]) { LASTS[j] = Min(LLVE[j-1],Open[j]); } else LASTS[j] = LASTS[j-1]; } /////////////////////////////////////////////////////// // BUY AND SELL SIGNALS /////////////////////////////////////////////////////// //delisted stock exit NTPeriod = 300; DN = DateNum(); LastDate = Status("rangetodate"); NT = LastDate - LastValue(DN) >= NTPeriod AND DN == LastValue(DN);
LastBarExit = BarIndex() == LastValue( BarIndex() );
///////////////////////////////////////////////////////IFU = IndexfilterUp;
PercentFilter = C >= 0.95*(HHVE+Pxh) AND C <= (HHVE+Pxh); // Long Entry Price LEP = Ref(HHVE,-1)+PxH; //Note 1.0 BO1setup = HHVE > LASTS AND UP == False AND ifu AND Liquidout; //Note 1.1
BO2setup = HHVE > LASTS AND UP AND LASTS < LASTB AND ifu AND LiquidOut; //Note 1.1 BO1 = Ref(BO1setup,-1) AND H >= LEP ; //Note 1.1
BO2 = Ref(BO2setup,-1) AND H >= LEP ; //Note 1.1
// Long Entry
LE = (BO1 OR BO2) AND Ref(PercentFilter,-1)AND Ref(Liquidout,-1) AND HDBFilter AND NT == 0; // AND Ref(Liquid,-1); // new entrys need to have been within 5% of the trigger price yesterday to open
BuyPrice = Max(O,LEP); // Changed to account for a Open above the Long Entry Price
“”;////////////////////////////////////////////////////////////////////////////////////
//MCS code
if (mcp)
LE = LE && Random()*100 >= mcp;////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Stop Initial
StopInitial = L – (ATRmulti*ATRma); //Raw Initial Stop
SIT = IIf(Stopinitial >= 2.00, 0.01, IIf(Stopinitial >= 0.10, 0.005, 0.001)); //Stop Initial Tick Value
SITVal = floor(Stopinitial / SIT); // Tick Count of the Initial Stop rounded down
/////////////////////////////////////////
StopInitialT = SITVal * SIT; //Tick Count * tick Value
/////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Stop Trailing
TSP = Param(“Trailing Stop Normal”,10,1,30,1); //ok//
StopTrail = LLV(L-PxL, TSP); // Lowest Low of the Low minus the Low Tick Value over the last
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Linitialstop = Max(StopInitialT,Stoptrail); //ok// Initial stop
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Stop Weak
TSPW = Param(“Trailing Stop Weak”,1,1,30,1); //ok//
StopWeak = LLV(L-PxL, TSPW); // Lowest Low of the (low minus the Tick Value) over the last day.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Trailing Stop Adaptive // Changes with Index Up And down
TrailingStopAdp = IIf(IndexfilterDn, Stopweak, Stoptrail); //ok
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
DSExit = IIf(NT,LastBarExit,0);///////////////////////////////////////////////////////
// Long Exits Calculations
///////////////////////////////////////////////////////Sell = 0;
LPriceAtBuy = 0;
LBIT = 0; // Number of bars in Trade
LStop = Null;
LIS = Null;for (j = 1; j < BarCount; j++) // { if (LPriceAtBuy==0 AND LE[j] AND Linitialstop[j] > 0) // if Long price at buy is equal to 0 and LE at j is true and longinital Stop at j is greater than 0 then
{
Buy[j] = True; // BUY at J is true
LPriceAtBuy = BuyPrice[j]; // Long price at buy = Buy Price at j
LStop[j-1] = Linitialstop[j-1]; // Long Stop at j – 1 equals Long Inital Stop at J – 1
LStop[j] = LStop[j-1]; // Long Stop at J = Lostopstop at j – 1
LBIT[j] = 1; // Long bars in trade = 1//////////////////////////////////
// CHECK EXITS
//////////////////////////////////
if (L[j] <= LStop[j-1]) // Low at j is less than or equal to long Stop at j-1 then { Sell[j] = True; // Sell at J is true & SellPrice[j] = Min(O[j],LStop[j-1]); // Sell Price at j = the Minimum of the open at J or the Long stop at j-1 & LPriceAtBuy = 0; // Long Price at buy = 0 } if (DSExit[j]) { Sell[j] = True; SellPrice[j] = C[j]; LPriceAtBuy = 0; } } else // Else No 1 if (LPriceAtBuy > 0 AND BO2[j] && EnablePyramid) // Pyramiding // if the long price at buy is greater than zero and BO2 at J and Enable Payramid is set to true, then
{
Buy[j]=sigScaleIn; //Buy at j = SigScaleIn
LStop[j] = LStop[j-1]; //Long Stop at j = Long stop at J-1
LBIT[j] = LBIT[j-1]+1; //Long bars in trade at j equal the Long bars in trade at (j – 1) + 1//////////////////////////////////
// CHECK EXITS
//////////////////////////////////
if (L[j] <= LStop[j-1]) // if the Low at j is less than the Long Stop at j -1, then { Sell[j] = True; //Sell at J is True SellPrice[j] = Min(O[j],LStop[j-1]); //Sell Price at J equals the Minimum of the open at J or the Long stop at j-1 LPriceAtBuy = 0; //Long Price at Buy equals 0 } if (DSExit[j]) { Sell[j] = True; SellPrice[j] = C[j]; LPriceAtBuy = 0; } } else // Else No 2 if (LPriceAtBuy > 0) // if the Long Price at buy is greater than 0, then
{
LStop[j] = Max(LStop[j-1],trailingstopadp[j]); //Long Stop at J = the MAximum of the LongStop at j -1 or the Sell Stop at J
LBIT[j] = LBIT[j-1]+1; //Long Bars in trade = Long bars in trade at (j – 1) + 1//////////////////////////////////
// CHECK EXITS
//////////////////////////////////if (L[j] <= LStop[j-1]) // if the Low at j is less than the Long Stop at j -1, then { Sell[j] = True; //Sell at J is True SellPrice[j] = Min(O[j],LStop[j-1]); //Sell Price at J equals the Minimum of the open at J or the Long stop at j-1 LPriceAtBuy = 0; //Long Price at Buy equals 0 } if (DSExit[j]) { Sell[j] = True; SellPrice[j] = C[j]; LPriceAtBuy = 0; } } } //Misc Calcs PendingTrade = LBIT == 0; RiskAmt = (HHVE+Pxh) - Linitialstop; TriggerPrice = HHVE+Pxh; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Plots the Word BUY and Sell along with the Price. FirstVisibleBar = Status( "FirstVisibleBar" ); Lastvisiblebar = Status("LastVisibleBar"); for( b = Firstvisiblebar; b <= Lastvisiblebar AND b < BarCount; b++) { if(Buy[b]) PlotText("n Buyn "+NumToStr(BuyPrice[b],1.3),b,BuyPrice[b]*0.9985,colorWhite); else if(Sell[b]) PlotText("n Selln "+NumToStr(SellPrice[b],1.3),b,SellPrice[b]*1.0025,colorWhite); } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Interpretation Window "Long Entry Setup : "+WriteIf (Bo1Setup OR BO2Setup ,"True", "" ); "Within 5% of Buy Trigger : " +WriteIf((BO1setup OR BO2setup) AND PendingTrade AND PercentFilter,"Yes","No" ); ""; "Trigger Price : $ " +WriteVal(IIf( (BO1setup OR BO2setup) AND PendingTrade, HHVE+PxH,0),1.3); //or LEP rather than HHVE+PxH "Inital Stop : $ " +WriteVal( IIf( (BO1setup OR BO2setup) AND PendingTrade, Linitialstop,0),1.3 ); "Risk Amount : $ " +WriteVal( IIf( (BO1setup OR BO2setup) AND PendingTrade,(HHVE+PxH) - Linitialstop,0), 1.3); "% Risk : % " +WriteVal( IIf( (BO1setup OR BO2setup) AND PendingTrade,(RiskAmt /TriggerPrice)* 100,0), 1.2); ""; "Next Stop : $ " +WriteVal(IIf(Lstop >0,LSTOP,0),1.9);
“”;
“Buy : “+WriteIf (Buy,”Buy”, “” );
“Buy Price : $ ” +WriteVal(IIf(Buy,BuyPrice,0),1.3);
“”;
“Sell : ” +WriteIf (Sell,”Sell”, “” );
“Sell Price : $ ” +WriteVal(IIf(Sell,SellPrice,0),1.3);
“”;
“Close within 5% of Buy Trigger : ” +WriteIf((BO1setup OR BO2setup) AND PendingTrade AND PercentFilter,”Yes”,”No” );
“”;
“Bars in Trade : ” +WriteVal(Lbit,1.0);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Plots Shapes on Chart
PlotShapes( shapeUpArrow*Buy, colorBrightGreen,0, L, -80);
PlotShapes( shapeDownArrow*Sell, colorRed,0, H, -80);
PlotShapes( shapeHollowSmallSquare*Sell, colorWhite,0,SellPrice, 0);
PlotShapes( shapeHollowSmallSquare*Buy, colorWhite,0,BuyPrice, 0);
Plot (Lstop,”Next Stop”,colorRed,styleThick );
///Plots the Trigger Price and Long Initial StopOn the Chart ”Visual Aid Only””
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
bi = BarIndex() ;
bi = bi – bi[0]; // “bi” is now array index
selBar = SelectedValue(bi);
hv = IIf(bi >= selBar-ECHANNEL && bi <= selBar+5, SelectedValue(TriggerPrice), Null); Plot(HV, "Trigger Price", ParamColor( "Trigger Line Color", colorBlue ), styleDashed |styleNoTitle, Null, Null, 0); bii = BarIndex() ; bii = bii - bii[0]; // "bi" is now array index selBarl = SelectedValue(bi); Lv = IIf(bii >= selBarl-XCHANNEL && bii <= selBarl+5, SelectedValue(LinitialStop), Null); Plot(LV, "Inital Stop", ParamColor( "Initial Stop Line Color", colorBlue ), styleDashed | styleNoTitle, Null, Null, 0); /////////////////////////////////////////////////////// // Exploration and Trade Information /////////////////////////////////////////////////////// Filter = ((BO1setup OR BO2setup) AND (PendingTrade AND PercentFilter) ) OR Buy OR Sell OR Lbit>0;
SetSortColumns(-4,-12,-10,-17,-8,1);
//Last Close
AddColumn (C,”Last Close”,1.30);
// New Trades
AddColumn ( IIf( ((BO1setup OR BO2setup) AND PendingTrade AND PercentFilter) OR ((BO1setup OR BO2setup) AND Sell==1 AND PercentFilter),1,Null),”Pending”,1.0,colorDefault, IIf( ((BO1setup OR BO2setup) AND PendingTrade AND PercentFilter) OR ((BO1setup OR BO2setup) AND Sell==1 AND PercentFilter), colorAqua, colorDefault ));
AddColumn ( IIf( ((BO1setup OR BO2setup) AND PendingTrade AND PercentFilter) OR ((BO1setup OR BO2setup) AND Sell==1 AND PercentFilter), TriggerPrice,Null),”Entry Trigger”,1.30);
AddColumn ( IIf( ((BO1setup OR BO2setup) AND PendingTrade AND PercentFilter) OR ((BO1setup OR BO2setup) AND Sell==1 AND PercentFilter), Linitialstop,Null),”Initial Stop”, 1.30);
AddColumn ( IIf( ((BO1setup OR BO2setup) AND PendingTrade AND PercentFilter) OR ((BO1setup OR BO2setup) AND Sell==1 AND PercentFilter), (RiskAmt / TriggerPrice) *100,Null),”% Risk Filter”);
// Current Trades
AddColumn (IIf(Lbit>0 AND Sell==0,1,Null),”Open Trades”,1.0,colorDefault, IIf( Lbit>0, colorGreen, colorDefault ));
AddColumn (IIf(lStop AND Sell==0,Lstop,Null), “Trailing Stop Price”,1.30);
// New Buys, Trade’s entered today
AddColumn(IIf(Buy==1,Buy,Null),”Todays Entrys”,1.0,colorDefault, IIf( Buy==1, colorBrightGreen, colorDefault ));
AddColumn(IIf(Buy==1,BuyPrice,Null),”BuyPrice”,1.30);
// Trade’s Exited Today
AddColumn(IIf(Sell==1,Sell,Null),”Todays Exits”,1.0,colorDefault, IIf( Sell==1, colorRed, colorDefault ));
AddColumn(IIf(Sell==1,SellPrice,Null), “Sell Price”,1.30);
// Misc Data
AddColumn (IIf(Lbit, Lbit, Null),”Bars in Trade”,1.0);
AddColumn (V*C,”Todays Turnover”,1.0);
AddTextColumn(WriteIf(IFU,”Up”,”Down”),”Index”,1.3,IIf(IFU,colorGreen,colorRed),2,40);
AddTextColumn(WriteIf(Lbit>0 && Lstop > Ref(Lstop,-1),”Move Trail Stop to ” + LStop,””),”Comment”,1.3,29,IIf(LBit>0 && LStop > Ref(Lstop,-1),41,2),140);
_SECTION_END();
_SECTION_BEGIN (“Backtesting Parameters”);
SetTradeDelays (0,0,0,0);
SetOption (“priceboundchecking”,True);
SetOption (“ReverseSignalForcesExit”,False);
SetOption (“ActivateStopsImmediately”,True);
SetOption (“AllowSameBarExit”,True);
Capital = Param(“Backtesting : Initial Capital $”, 100000, 1000, 10000000, 1000);
MaxPos = Param(“Backtesting : Maxium Open Positions”, 25,1,10000,1);
SetOption (“InitialEquity”, Capital);
SetOption (“MaxOpenPositions”, MaxPos );
PositionScore = Random();
///////////////////////////////////////////////////////
// Position Sizing
///////////////////////////////////////////////////////
Risk = Param ( “Backtesting : Fixed Fractional Risk %”, 1, 0.01, 5, 0.01); // Risk Percentage VariablePositionSize = -Risk*BuyPrice/(BuyPrice-Ref(Linitialstop,-1)); // Note – Fixed Fractional
_SECTION_END();
////11April 9, 2017 at 10:51 pm #106605LeeDanelloParticipantA group collaboration idea that got me started.
Too many variables for my liking and trade frequency too low for ASX. Code is attached as a txt file.Code:/*For the sake of getting started here is a swing trading strategy using BB.the rules are as follows:
No index Filter
Min average Volume is 500K
Close is above MA 100 days
BB (5,1.5)
Close below the lower band
BB width is greater than 5% (BBWidth = (BBTop – BBBot)/ BBBot *100;)
Buy on limit order if the price drops a bit under the low (0.5ATR(10))
Sell cross with MA 5days*/
#include_once “FormulasNorgate DataNorgate Data Functions.afl”
_SECTION_BEGIN( “Historical Database Testing” );
//====================================================================
//Historical Database Testing
//====================================================================ASXList = ParamList( “ASX Historical Watchlist:”, “1: Off|2: ASX 20|3: ASX 50|4: ASX 100|5: ASX 200|6: ASX 300|7: ASX All Ordinaries|8: ASX Small Ordinaries|9: ASX Emerging Companies|10: Excluding ASX 300|11: In XAO but Exc ASX 100|12: Exc XAO”, 0 );
HistDB = 1;//set to 1 to start
if( ASXList == “1: Off” ) HistDB = 1;
if( ASXList == “2: ASX 20” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XTL” );
if( ASXList == “3: ASX 50” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XFL” );
if( ASXList == “4: ASX 100” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XTO” );
if( ASXList == “5: ASX 200” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XJO” );
if( ASXList == “6: ASX 300” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XKO” );
if( ASXList == “7: ASX All Ordinaries” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XAO” );
if( ASXList == “8: ASX Small Ordinaries” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XKO” ) AND NOT NorgateIndexConstituentTimeSeries ( “$XTO” );
if( ASXList == “9: ASX Emerging Companies” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XEC” );
if( ASXList == “10: Excluding ASX 300” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XKO” ) == 0;
if( ASXList == “11: In XAO but Exc ASX 100” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XAO” )AND NOT NorgateIndexConstituentTimeSeries ( “$XTO” );
if( ASXList == “12: Exc XAO” ) HistDB = NorgateIndexConstituentTimeSeries ( “$XAO” ) == 0;//———————————————————————————
USList = ParamList(“US Historical Watchlist:”,”1: Off|2: Russell 1000|3: Russell 2000|4: Russell 3000|5: NASDAQ 100|6: Dow Jones Industrial Average|7: S&P 500|8: S&P 100|9: S&P MidCap 400|10: S&P SmallCap 600|11: S&P 1500|12: Russell MicroCap|13: Russell MidCap”,0);
USHistDB = 1;//set to 1 to startif(USList == “1: Off”) USHistDB = 1;
if(USList == “2: Russell 1000”) USHistDB = NorgateIndexConstituentTimeSeries (“$RUI”);
if(USList == “3: Russell 2000”) USHistDB = NorgateIndexConstituentTimeSeries (“$RUT”);
if(USList == “4: Russell 3000”) USHistDB = NorgateIndexConstituentTimeSeries (“$RUA”);
if(USList == “5: NASDAQ 100”) USHistDB = NorgateIndexConstituentTimeSeries (“$NDX”);
if(USList == “6: Dow Jones Industrial Average”) USHistDB = NorgateIndexConstituentTimeSeries (“$DJI”);
if(USList == “7: S&P 500”) USHistDB = NorgateIndexConstituentTimeSeries (“$SPX”);
if(USList == “8: S&P 100”) USHistDB = NorgateIndexConstituentTimeSeries (“$OEX”);
if(USList == “9: S&P MidCap 400”) USHistDB = NorgateIndexConstituentTimeSeries (“$MID”);
if(USList == “10: S&P SmallCap 600”) USHistDB = NorgateIndexConstituentTimeSeries (“$SML”);
if(USList == “11: S&P 1500”) USHistDB = NorgateIndexConstituentTimeSeries (“$SP1500”);
if(USList == “12: Russell MicroCap”) USHistDB = NorgateIndexConstituentTimeSeries (“$RUMIC”);
if(USList == “13: Russell MidCap”) USHistDB = NorgateIndexConstituentTimeSeries (“$RMC”);//———————————————————————————
HDBFilter = HistDB AND USHistDB;
//====================================================================
_SECTION_END();_SECTION_BEGIN (“Optional Price & Volume Filters”);
//=================================================================================
//Optional Price & Volume Filters
//=================================================================================
CloseToggle = ParamToggle(“Close Price”,”Adjusted|Unadjusted”,0);
CloseArray = IIf(CloseToggle,NorgateOriginalCloseTimeSeries(),Close);VolumeToggle = ParamToggle(“Volume”,”Adjusted|Unadjusted”,0);
VolumeArray = IIf(VolumeToggle,NorgateOriginalVolumeTimeSeries(),Volume);
//———————————————————————————
PriceTog = ParamToggle(“Price Filter”,”Off|On”,1);
MinSP = Param(“Minimum Share Price – $”,0.25,0.00,1000,0.01);
MaxSP = Param(“Maximum Share Price – $”,25,0.00,2000,0.01);
MinMaxSP = CloseArray >= MinSP AND CloseArray <= MaxSP; PriceFilt = IIf(PriceTog,MinMaxSP,1); //--------------------------------------------------------------------------------- TOTog = ParamToggle("Turnover Filter","Off|On",0); Turnover = CloseArray*VolumeArray; MinTO = Param("Minimum Turnover - $",500000,0,10000000,1000); currentYr = Year(); //http://www.rateinflation.com/inflation-rate/australia-historical-inflation-rate?start-year=1999&end-year=2017 //Year ann inflation //2016 1.30% //2015 1.50% //2014 2.50% //2013 2.50% //2012 1.70% //2011 3.30% //2010 2.90% //2009 1.70% //2008 4.40% //2007 2.30% //2006 3.50% //2005 2.70% //2004 2.30% //2003 2.70% //2002 3.10% //2001 4.30% //2000 4.50% Factor2016 = 1.013; Factor2015 = 1.028195; Factor2014 = 1.053899875; Factor2013 = 1.080247371875; Factor2012 = 1.09861157719687; Factor2011 = 1.13486575924437; Factor2010 = 1.16777686626246; Factor2009 = 1.18762907298892; Factor2008 = 1.23988475220043; Factor2007 = 1.26840210150104; Factor2006 = 1.31279617505358; Factor2005 = 1.34824167178003; Factor2004 = 1.37925123023097; Factor2003 = 1.4164910134472; Factor2002 = 1.46040223486406; Factor2001 = 1.52319953096322; Factor2000 = 1.59174350985656; MinTO=IIf(currentYr==2017,MinTO, IIf(currentYr==2016,MinTO/Factor2016, IIf(currentYr==2015,MinTO/Factor2015, IIf(currentYr==2014,MinTO/Factor2014, IIf(currentYr==2013,MinTO/Factor2013, IIf(currentYr==2012,MinTO/Factor2012, IIf(currentYr==2011,MinTO/Factor2011, IIf(currentYr==2010,MinTO/Factor2010, IIf(currentYr==2009,MinTO/Factor2009, IIf(currentYr==2008,MinTO/Factor2008, IIf(currentYr==2007,MinTO/Factor2007, IIf(currentYr==2006,MinTO/Factor2006, IIf(currentYr==2005,MinTO/Factor2005, IIf(currentYr==2004,MinTO/Factor2004, IIf(currentYr==2003,MinTO/Factor2003, IIf(currentYr==2002,MinTO/Factor2002, IIf(currentYr==2001,MinTO/Factor2001, IIf(currentYr==2000,MinTO/Factor2000,0)))))))))))))))))); TOMA = Param("Turnover MA",10,1,200,1); AveTO = MA(Turnover,TOMA); TOFilter = AveTO > MinTO AND Turnover > MinTO;
TOFilt = IIf(TOTog,TOFilter,1);
//———————————————————————————
VolTog = ParamToggle(“Volume Filter”,”Off|On”,1);
MinVol = Param(“Minimum Volume”,250000,0,10000000,1000);
VolFilter = VolumeArray > MinVol;
VolFilt = IIf(VolTog,VolFilter,1);
//———————————————————————————
AveVolTog = ParamToggle(“Average Volume Filter”,”Off|On”,1);
MinAveVol = Param(“Minimum Average Volume”,500000,0,10000000,1000);
AVPer = Param(“Volume EMA”,10,1,200,1);
AveVol = EMA(VolumeArray,AVPer) > MinAveVol;
AveVolFilt = IIf(AveVolTog,AveVol,1);
//———————————————————————————
OptFilt = PriceFilt AND TOFilt AND VolFilt AND AveVolFilt;//=================================================================================
_SECTION_END();_SECTION_BEGIN(“Index Filter”);
//====================================================================
//Index Filter
//====================================================================
IndexTog = ParamToggle(“Index Filter”,”On|Off”,1);
IndexCode = ParamStr(“Index Symbol”,”$SPX”);
Index = Foreign(IndexCode,”C”);
IndMA = Param(“Index Filter MA”,150,2,250,1);
IndexFiltUp = Index > MA(Index,IndMA);
IndexUp = IIf(IndexTog,1,IndexFiltUp);
//====================================================================
_SECTION_END();//====================================================================
//Universe Filter
//====================================================================
List = Paramlist(“Universe Filter:”,”1:Off|2:Resources|3:Industrials”,0); //– this sets the drop down list
UniverseFilter = 1; //– set the filter to 1 to start
If (List == “1:Off”) UniverseFilter = 1;
If (List == “2:Resources”) UniverseFilter = InGics(“10”) OR InGics(“151040”);
If (List == “3:Industrials”) UniverseFilter = InGics(“10”)==0 OR InGics(“151040”)==0;
//====================================================================
_SECTION_END();_SECTION_BEGIN(“Gap Filter”);
//=========================================================
// Gap Filter
//=========================================================
“nGap filter:”;
gapTog = ParamToggle(“Gap Filter”,”On|Off”,0);
gapPercent = Param(“Gap %”,15,10,100,1);
gapPeriod = Param(“Gap Up Lookback”,100,20,100,5);
priceField1 = C;
priceField2 = Ref(C,-1);
ratio = ((priceField1-priceField2)/priceField2)*100;gap = (GapUp() OR GapDown()) AND abs(ratio) >= gapPercent;
gapNumber = Sum(gap,gapPeriod);
gapFilter = gapNumber == 0;
gapFilterOn = IIf(gapTog,1,gapFilter);
//=========================================================
_SECTION_END();//====================================================================
//Entry and Exit Rules
//====================================================================
MArange = Param(“MA Range”,100,1,1000,1);
Periods = Param(“Bollinger Period”,5,1,100,1);
stddev = Param(“Standard Deviation Bands”,1.5,0,3,0.1);UpperBand = BBandTop( C, Periods, stddev );
LowerBand = BBandBot( C, Periods, stddev );
percentb = (C – LowerBand)/(UpperBand – LowerBand);
BBWidth = (UpperBand – LowerBand)/ LowerBand *100;
BBParam = Param(“% BB width”,5,1,50,0.1);
consecCloses = Param(“consecutive closes below band”,1,1,5,1);
adxPeriod = Param(“ADX period”,8,8,30,2);
adxMin = Param(“ADX Min”, 30,20,60,5);
/*
%b = (Price – Lower Band)/(Upper Band – Lower Band)
%b equals 1 when price is at the upper band
%b equals 0 when price is at the lower band
%b is above 1 when price is above the upper band
%b is below 0 when price is below the lower band
%b is above .50 when price is above the middle band (5-day SMA)
%b is below .50 when price is below the middle band (5-day SMA)
*/
lowerbandlimit = Param(“Lower Band Limit”,0.0,-0.5,0.5,0.1);
upperbandlimit = Param(“Upper Band Limit”,0.5,0,1.5,0.1);function ParamOptimize(pname,defaultval,minv,maxv,step)
{
return Optimize(pname,Param(pname,defaultval,minv,maxv,step),minv,maxv,step);
}
//——————————————————————–
//Limit Entry using the stretch
//——————————————————————–
ATRp = Param(“Limit Price: ATR period”,10,1,20,1);
ATRmulti = Param(“Limit Price: ATR Multi”,0.5,0,1.5,.1);
ATRVal = ATR(ATRp)*ATRmulti;
BuyLimP = L – ATRval; //stretch
TickLo = IIf(MarketID(0) == 10 OR MarketID(0) == 14 ,IIf(L<0.10,0.001,IIf(L<2.00,0.005,0.01)),0.01);
BuyLimVal = round(BuyLimP/TickLo);
BuyLim = BuyLimVal * TickLo; //stretchCond1 = LLV(percentb < lowerbandlimit,consecCloses); //close below lower band Cond2 = C > MA(C,MArange);
Cond3 = OptFilt AND IndexUp AND UniverseFilter AND HDBFilter;
Cond4 = BBWidth > BBParam;
Cond5 = ADX(adxPeriod) > adxMin;OnLastTwoBarsOfDelistedSecurity = BarIndex() >= (LastValue(BarIndex()) -1) AND !IsNull(GetFnData(“DelistingDate”));
OnSecondLastBarOfDelistedSecurity = BarIndex() == (LastValue(BarIndex()) -1) AND !IsNull(GetFnData(“DelistingDate”));BuySetUp = Cond1 AND Cond2 AND Cond3 AND Cond4 AND Cond5;
LE = Ref(BuySetUp,-1) AND L <= Ref(BuyLim,-1) AND NOT OnLastTwoBarsOfDelistedSecurity; LEPrice = Min(O,ref(BuyLim,-1)); LExPrice = O; SellSetUp = percentb > upperbandlimit; //sell at middle band
LEx = Ref(SellSetUp,-1);
//——————————————————————–
//Stops
//——————————————————————–
Short = Cover = False;
ExitBars = Param(“# Exit Bars”,9,2,100,1);
StopLossPercentage = Param(“% Hard Stop Loss”,10,0,100,1); //Stop Loss
//====================================================================
//Looping
//====================================================================
Buy = 0;
Sell = 0;
LPriceAtBuy = 0;
LBIT = 0;
FlagExit = 0;
MaxLossPrice = Null;
//====================================================================
for( j = 1; j < BarCount; j++ ) { if( LPriceAtBuy == 0 AND LE[j] ) { Buy[j] = True; LPriceAtBuy = LEPrice[j]; BuyPrice[j] = LEPrice[j]; MaxLossPrice[j] = LPriceAtBuy * ( 1 - StopLossPercentage / 100 ); LBIT[j] = 1; if( LBIT[j] > 1 AND LEx[j] OR OnSecondLastBarOfDelistedSecurity[j] )
{Sell[j] = True;
SellPrice[j] = LExPrice[j];
LPriceAtBuy = 0;
}if( LBIT[j] > 1 AND L[j – 1] <= MaxLossPrice[j - 1] ) { Sell[j] = True; SellPrice[j] = LExPrice[j]; LPriceAtBuy = 0; } } else if( LPriceAtBuy > 0 )
{
LBIT[j] = LBIT[j – 1] + 1;
MaxLossPrice[j] = MaxLossPrice[j – 1];if( LBIT[j] > 1 AND L[j – 1] <= MaxLossPrice[j - 1] OR OnSecondLastBarOfDelistedSecurity[j] ) { Sell[j] = True; SellPrice[j] = LExPrice[j]; LPriceAtBuy = 0; } if( LBIT[j] == ExitBars ) //Exit trade after a certain number of bars { FlagExit[j] = True; } if( LBIT[j] > ExitBars )
{
Sell[j] = True;
SellPrice[j] = LExPrice[j];
LPriceAtBuy = 0;
}if( LBIT[j] > 1 AND LEx[j])
{
Sell[j] = True;
SellPrice[j] = LExPrice[j];
LPriceAtBuy = 0;
}
}
}//====================================================================
LESetup = IIf(LBIT==0 OR Sell==1,BuySetUp,0); //Long Entry Set Up
LExSetup = IIf(LBIT>0 AND Sell==0,SellSetup,0); //Long Exit Set Up//——————————————————————–
Filter = Buy OR Sell OR LESetUp OR LExSetUp OR LBIT>0;
AddTextColumn(WriteIf(LESetup,”Buy Setup”,””),”Entry Signal”,1.2,colorDefault,IIf(LESetup,colorBrightGreen,colorDefault),130);
AddTextColumn(WriteIf(LExSetup,”Exit”,””),”Exit Signal”,1.2,colorDefault,IIf(LExSetup,colorRed,colorDefault),100);
AddTextColumn(WriteIf(Buy,”Buy”,””),”Today’s Entries”,1.2,colorDefault,IIf(Buy,colorGreen,colorDefault),130);
AddTextColumn(WriteIf(Sell,”Sell”,””),”Today’s Exits”,1.2,colorDefault,IIf(Sell,colorRed,colorDefault),130);
AddColumn(LBIT,”LBIT”,1.0);
SetSortColumns(-3,-4,-5,-6,1);/*Filter = 1;
AddColumn(BuySetUp,”Buy Setup”,1);
AddColumn(Buy,”Buy”,1);
AddColumn(SellSetUp, “Sell Setup”,1);
AddColumn(Sell,”Sell”,1);
*/
//====================================================================
//Interpretation Window
//====================================================================
//”Stop Level: “+NumToStr(StopLossExit,1.3);
“3 Lower Closes and below lower band: “+WriteIf(Cond1,”Yes”,”No”);
“Above long term MA: “+WriteIf(Cond2,”Yes”,”No”);
“Index Filer On: “+WriteIf(IndexTog,”No”,”Yes”);
“”;
“Bars In Trade: “+NumToStr(LBIT,1);
“Close above mid band: “+WriteIf(SellSetUp,”Yes”,”No”);
//====================================================================
_SECTION_BEGIN(“Chart Plotting”);
//====================================================================
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 ) ) ));
ChartType = ParamList(“Chart Type”,”OHLC Bar|Candle|Line”,0);
SetChartBkColor(ParamColor(“Background Colour”,colorWhite));UpColour = ParamColor(“Bar/Candle Up Colour”,colorGreen);
DownColour = ParamColor(“Bar/Candle Down Colour”,colorRed);Colour1 = IIf(C > Ref(C,-1),UpColour,DownColour);
Colour2 = IIf(C > O,UpColour,DownColour);
Colour3 = ParamColor(“Line Chart Colour”,colorRed);
TextColour = ParamColor(“Text Colour”,colorBlack);if(ChartType == “OHLC Bar”) ChartOption = styleBar;
if(ChartType == “Candle”) ChartOption = styleCandle;
if(ChartType == “Line”) ChartOption = styleLine;if(ChartType == “OHLC Bar”) ColourOption = Colour1;
if(ChartType == “Candle”) ColourOption = Colour2;
if(ChartType == “Line”) ColourOption = Colour3;
//——————————————————————–
Plot(Close,”Close”,ColourOption,styleNoTitle|ChartOption|ParamStyle(“Chart Style”));
GraphXSpace = 10;PlotShapes(shapehollowUpArrow*LESetup,colorGreen,0,L,-40); //plots an arrow for a setup bar
PlotShapes(shapehollowdownArrow*LExSetup,colorRed,0,H,-40); //plots an arrow for an exit bar
PlotShapes(shapeHollowSmallSquare*Buy,TextColour,0,BuyPrice,0); //plots a small hollow square right at the buy price
PlotShapes(shapeHollowSmallSquare*Sell,TextColour,0,SellPrice,0); //plots a small hollow square right at the sell price
//——————————————————————–
FirstVisibleBar = Status(“FirstVisibleBar”);
LastVisibleBar = Status(“LastVisibleBar”);for( b = Firstvisiblebar; b <= Lastvisiblebar AND b < BarCount; b++) { if(Buy[b]) PlotText("n Buyn "+NumToStr(BuyPrice[b],1.3),b,BuyPrice[b]*0.9985,TextColour); else if(Sell[b]) PlotText("n Selln "+NumToStr(SellPrice[b],1.3),b,SellPrice[b]*0.9985, TextColour); } //==================================================================== _SECTION_END(); _SECTION_BEGIN("Backtesting"); //===================================================================== //options in automatic analysis settings //===================================================================== SetTradeDelays(0,0,0,0); SetOption("UsePrevBarEquityForPosSizing",True); Capital = Param("Initial Equity $",25000,1000,1000000,100); SetOption("InitialEquity",Capital); MaxPos = Param("Maximum Open Positions",10,1,100,1); SetOption("MaxOpenPositions",MaxPos); SetOption("AllowSameBarExit",False); SetOption("AllowPositionShrinking", False ); SetOption("InterestRate",0); SetOption("Minshares",1); SetOption("CommissionMode",2); //Fixed Dollar Amount SetOption("CommissionAmount",6); //Use IB commision rates Margin = Param("Margin",100,1,100,1); SetOption("AccountMargin",Margin); PositionScore = mtRandom(); //--------------------------------------------------------------------- ""; "Position Sizing Method:"; PosSizeMethod = ParamList("Position Sizing Method:","Fixed Fractional Risk %|Fixed $ Risk Amount|Fixed $ Total Position Size|Fixed % of Portfolio Equity",3); //Risk Calculation FDAmount = Param("Fixed $ Total Position Size",5000,100,100000,100); //Fixed % of Portfolio Equity FPAmount = Param("Fixed % of Portfolio Equity",10,1,100,1); if(PosSizeMethod == "Fixed Fractional Risk %") SetPositionSize(Risk1,spsPercentOfEquity); if(PosSizeMethod == "Fixed $ Risk Amount") SetPositionSize(Risk2,spsShares); if(PosSizeMethod == "Fixed $ Total Position Size") SetPositionSize(FDAmount,spsValue); if(PosSizeMethod == "Fixed % of Portfolio Equity") SetPositionSize(FPAmount,spsPercentOfEquity); //==================================================================== _SECTION_END();
April 10, 2017 at 7:25 am #106606ScottMcNabParticipantEver try it with a trailing stop Maurice ?…short term pullback to get into a longer term trend ?
April 10, 2017 at 10:23 am #106608LeeDanelloParticipant.short term pullback to get into a longer term trend ?
Not sure what you mean Scott, but stops impact the performance so I don’t use them. I use the stale stop instead
April 10, 2017 at 10:25 am #106598LeeDanelloParticipantA couple more for the gravy yard.
Nothing too imaginative here.
Both MR systems. 1st one uses the lower Bollinger band to enter, 2nd one uses consecutive lower closes and an oversold RSI.
April 10, 2017 at 4:19 pm #106610SaidBitarMemberooo this is the time i regret hitting the delete button otherwise i will have loads of them i will search the hard disc for some
April 10, 2017 at 8:06 pm #106609ScottMcNabParticipantMaurice Petterlin wrote:.short term pullback to get into a longer term trend ?Not sure what you mean Scott, but stops impact the performance so I don’t use them. I use the stale stop instead
The system is in an uptrend (close above 100 MA) and then waits for a pullback (close below lower BB) to enter…..during the mentor group phone call recently this was suggested as a possible set up for an entry to a trend following system…so same entry but use a trailing stop to let it run….?
April 10, 2017 at 9:30 pm #106611Nick RadgeKeymaster** Please put a small description of what the system was built to do – even just one or two sentences. Will help users look for specific things.
Thanks
April 10, 2017 at 11:34 pm #106612LeeDanelloParticipantScott, I think that’s what I basically posted above. I’ve found that stops don’t work too well for short term systems
April 11, 2017 at 12:55 am #106613LeeDanelloParticipantLooking for a discarded rotational system.
April 11, 2017 at 6:34 am #106614JulianCohenParticipantMaurice Petterlin wrote:Looking for a discarded rotational system.here’s One for you maurice. I ran it for a few months but it went into hard drawdown so I stopped it. Fairly basic. I haven’t found a rotational system that I want to run yet. I feel better using WTT variants instead.
Code:/*
Gap Filter 25% over 100 days
Entry C>MA(200) and ADX(10)>=30
Index Filter 150 daysIf Index Filter is green on last day of month then OK to buy.
*/
#include_once “FormulasNorgate DataNorgate Data Functions.afl”
_SECTION_BEGIN(“Index Filter”);
//=====================================================================
//Index Filter
//=====================================================================
“”;
“Index Filter”;
IndexTog = ParamToggle(“Index Filter”,”On|Off”,0);
IndexCode = ParamStr(“Index Symbol”,”$XAO.AU”);
Index = Foreign(IndexCode,”C”);
IndMA = Param(“Index Filter MA”,200,75,200,25);
IndexFilterUp = Index > MA(Index,IndMA);
IndexUp = IIf(IndexTog,1,IndexFilterUp);
//=====================================================================
_SECTION_END();_SECTION_BEGIN(“Gap Filter”);
//=========================================================
// Gap Filter
//=========================================================
“nGap filter:”;
gapTog = ParamToggle(“Gap Filter”,”On|Off”,0);
gapPercent = Param(“Gap %”,15,5,40,5);
gapPeriod = Param(“Gap Up Lookback”,100,10,150,5);
priceField1 = C;
priceField2 = Ref(C,-1);
ratio = ((priceField1-priceField2)/priceField2)*100;gap = (GapUp() OR GapDown()) AND abs(ratio) >= gapPercent;
gapNumber = Sum(gap,gapPeriod);
gapFilter = gapNumber == 0;
gapFilterOn = IIf(gapTog,1,gapFilter);
//=========================================================
_SECTION_END();_SECTION_BEGIN(“Historical Data Base Testing”);
//=================================================================================
//Historical Data Base Testing
//=================================================================================
ASXList = ParamList(“ASX Historical Watchlist:”,”1: Off|2: ASX 20|3: ASX 50|4: ASX 100|5: ASX 200|6: ASX 300|7: ASX All Ordinaries|8: ASX Small Ordinaries|9: ASX Emerging Companies|10: Excluding ASX 300″,4);HistDB = 1;
if(ASXList == “1: Off”) HistDB = 1;
if(ASXList == “2: ASX 20”) HistDB = NorgateIndexConstituentTimeSeries(“$XTL”);
if(ASXList == “3: ASX 50”) HistDB = NorgateIndexConstituentTimeSeries(“$XFL”);
if(ASXList == “4: ASX 100”) HistDB = NorgateIndexConstituentTimeSeries(“$XTO”);
if(ASXList == “5: ASX 200”) HistDB = NorgateIndexConstituentTimeSeries(“$XJO”);
if(ASXList == “6: ASX 300”) HistDB = NorgateIndexConstituentTimeSeries(“$XKO”);
if(ASXList == “7: ASX All Ordinaries”) HistDB = NorgateIndexConstituentTimeSeries(“$XAO”);
if(ASXList == “8: ASX Small Ordinaries”) HistDB = NorgateIndexConstituentTimeSeries(“$XSO”);
if(ASXList == “9: ASX Emerging Companies”) HistDB = NorgateIndexConstituentTimeSeries(“$XEC”);
if(ASXList == “10: Excluding ASX 300”) HistDB = NorgateIndexConstituentTimeSeries(“$XKO”)==0;//———————————————————————————
USList = ParamList(“US Historical Watchlist:”,”1: Off|2: Russell 1000|3: Russell 2000|4: Russell 3000|5: NASDAQ 100|6: Dow Jones Industrial Average|7: S&P 500|8: S&P 100|9: S&P MidCap 400|10: S&P SmallCap 600|11: S&P 1500|12: Russell MicroCap|13: Russell MidCap|14: Russell 2000 Excluding S&P 500|15: Russell 1000 Excluding S&P 500″,0);USHistDB = 1;
if(USList == “1: Off”) USHistDB = 1;
if(USList == “2: Russell 1000”) USHistDB = NorgateIndexConstituentTimeSeries(“$RUI”);
if(USList == “3: Russell 2000”) USHistDB = NorgateIndexConstituentTimeSeries(“$RUT”);
if(USList == “4: Russell 3000”) USHistDB = NorgateIndexConstituentTimeSeries(“$RUA”);
if(USList == “5: NASDAQ 100”) USHistDB = NorgateIndexConstituentTimeSeries(“$NDX”);
if(USList == “6: Dow Jones Industrial Average”) USHistDB = NorgateIndexConstituentTimeSeries(“$DJI”);
if(USList == “7: S&P 500”) USHistDB = NorgateIndexConstituentTimeSeries(“$SPX”);
if(USList == “8: S&P 100”) USHistDB = NorgateIndexConstituentTimeSeries(“$OEX”);
if(USList == “9: S&P MidCap 400”) USHistDB = NorgateIndexConstituentTimeSeries(“$MID”);
if(USList == “10: S&P SmallCap 600”) USHistDB = NorgateIndexConstituentTimeSeries(“$SML”);
if(USList == “11: S&P 1500”) USHistDB = NorgateIndexConstituentTimeSeries(“$SP1500”);
if(USList == “12: Russell MicroCap”) USHistDB = NorgateIndexConstituentTimeSeries(“$RUMIC”);
if(USList == “13: Russell MidCap”) USHistDB = NorgateIndexConstituentTimeSeries(“$RMC”);
if(USList == “14: Russell 2000 Excluding S&P 500”) USHistDB = NorgateIndexConstituentTimeSeries(“$RUT”) AND NOT NorgateIndexConstituentTimeSeries(“$SPX”);
if(USList == “15: Russell 1000 Excluding S&P 500”) USHistDB = NorgateIndexConstituentTimeSeries(“$RUI”) AND NOT NorgateIndexConstituentTimeSeries(“$SPX”);//———————————————————————————
HDBFilter = HistDB AND USHistDB;//=================================================================================
_SECTION_END();//=================================================================================
_SECTION_END();_SECTION_BEGIN(“Universe Filter”);
//=====================================================================
//Universe Filter
//=====================================================================
“”;
“Universe Filter:”;
Universe = ParamList(“Universe Filter:”,”1: Off|2: Rescources|3: Industrials”,0);
UniverseFilter = 1;
if(Universe == “1: Off”) UniverseFilter = 1;
if(Universe == “2: Rescources”) UniverserFilter = InGics(“10”) OR InGics(“151040”);
if(Universe == “3: Industrials”) UniverserFilter = InGics(“10”) == 0 AND InGics(“151040”)== 0;
//=====================================================================
_SECTION_END();_SECTION_BEGIN (“Optional Price & Volume Filters”);
//=================================================================================
//Optional Price & Volume Filters
//=================================================================================
PriceTog = ParamToggle(“Price Filter”,”Off|On”,1);
CloseToggle = ParamToggle(“Close Price”, “Adjusted|Unadjusted”,1);
CP = IIf(CloseToggle,NorgateOriginalCloseTimeSeries(),Close);
MinSP = Param(“Minimum Share Price – $”,0.20,0.00,1000,0.01);
MaxSP = Param(“Maximum Share Price – $”,150,0.00,1500,0.01);
MinMaxSP = CP >= MinSP AND CP <= MaxSP; PriceFilt = IIf(PriceTog,MinMaxSP,1); //--------------------------------------------------------------------------------- AveVolTog = ParamToggle("Average Volume Filter","Off|On",1); MinAveVol = Param("Minimum Average Volume",500000,0,10000000,1000); AVPer = Param("Volume EMA",50,1,200,1); AveVol = EMA(V,AVPer) > MinAveVol;
AveVolFilt = IIf(AveVolTog,AveVol,1);
//———————————————————————————
OptFilt = PriceFilt AND AveVolFilt;
_SECTION_END();_SECTION_BEGIN (“System Parameters”);
//=================================================================================
//Parameters
//=================================================================================
Duration = Param(“Length of ROC”,252,10,504,10);
MADuration = Param(“MA Length”,200,150,250,25);LMA = WMA(C,MADuration);
HV = 100 * StDev(log(C/Ref(C,-1)),20) * sqrt(252);//=================================================================================
//Entry & Exit
//=================================================================================
OnLastTwoBarsOfDelistedSecurity = BarIndex() >= (LastValue(BarIndex()) -1) AND !IsNull(GetFnData(“DelistingDate”));Cond1 = HV > 5 AND HV < 20; Cond2 = ROC(C,Duration) > 0;
Cond3 = C > LMA;
Cond4 = IndexUp AND OptFilt AND HDBFilter AND gapFilterOn;LESetup = Cond1 AND Cond2 AND Cond3 AND Cond4; //Any additional buy rules apart from the rotational criteria – e.g index, price filters etc
LE = Ref(LESetUp,-1) AND NOT OnLastTwoBarsOfDelistedSecurity;//=================================================================================
_SECTION_END();_SECTION_BEGIN (“Backtesting Options”);
//=================================================================================
//Backtesting Parameters
//=================================================================================
posqty = Param(“# Positions”,30,1,100,1);
Eq = Param(“Initial Equity”,100000,1,10000000,1);
SetOption(“InitialEquity”,Eq);
SetOption(“MaxOpenPositions”,posqty);
SetOption(“UsePrevBarEquityForPosSizing”,True);
SetOption(“AccountMargin”,100);
SetOption(“AllowPositionShrinking”,True);
//SetOption(“WorstRankHeld”,100);
SetTradeDelays(0,0,0,0);SetBacktestMode(backtestRotational);
EOM = Month() != Ref(Month(),-1);
score = Ref(ROC(C, Duration),-1);//score is the rotational criteria
Score = IIf(LE,score,0);
PositionScore = IIf(Year()>=1985 AND EOM,score,scoreNoRotate);
//———————————————————————————
PortfRisk = Param(“% daily Portfolio Risk”, 0.2, 0, 2, 0.05);
SetPositionSize( Ref(C,-1) * PortfRisk /Ref(ATR(20),-1), spsPercentOfEquity);//=================================================================================
_SECTION_END();_SECTION_BEGIN (“Exploration”);
//=================================================================================
//Exploration
//=================================================================================
Filter = LESetup;Capital = Param(“Account Balance”,100000,1,1000000,1);
AddTextColumn(WriteIf(LESetUp,”Buy SetUp”,””),”Entry Signal”,1.2,colorDefault,IIf(LESetUp,colorBrightGreen,colorDefault),130);
AddColumn(C * PortfRisk /ATR(21),”Position Size %”,1.2,colorDefault,colorDefault,100);
AddColumn(floor(Capital / 100 * (PortfRisk /ATR(20))),”# shares”,1,colorDefault,colorDefault,100);
AddColumn(ROC(C,Duration),”Rate of Change”,1.2);
AddColumn(C, “Closing Price”, 1.2);SetSortColumns(-6,1);
//=====================================================================
//Interpretation Window
//=====================================================================
“”;
“ROC Value: “+NumToStr(ROC(C,Duration),1);//”Breakout? “+WriteIf(Cond1==1,”Yes”,”No”);
//”Close above MA: “+WriteIf(Cond3==1,”Yes”,”No”);//=====================================================================
_SECTION_END();
_SECTION_BEGIN(“Chart Plotting”);
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat(“{{NAME}} – ” + FullName() + ” {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}”, O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));“”;
“Chart Type:”;
ChartType = ParamList(“Chart Type”,”OHLC Bar|Candle|Line”,0);SetChartBkColor(ParamColor(“Background Colour”,colorWhite));
UpColour = ParamColor(“Bar/Candle Up Colour”,colorBrightGreen);
DownColour = ParamColor(“Bar/Candle Down Colour”,colorRed);
Colour1 = IIf(C > Ref(C,-1),UpColour,DownColour);
Colour2 = IIf(C > O,UpColour,DownColour);
Colour3 = ParamColor(“Line Chart Colour”,colorRed);
TextColour = ParamColor(“Text Colour”,colorBlack);if(ChartType == “OHLC Bar”) ChartOption = styleBar|styleThick;
if(ChartType == “Candle”) ChartOption = styleCandle;
if(ChartType == “Line”) ChartOption = styleLine;if(ChartType == “OHLC Bar”) ColourOption = Colour1;
if(ChartType == “Candle”) ColourOption = Colour2;
if(ChartType == “Line”) ColourOption = Colour3;Plot(Close,”Close”,ColourOption,styleNoTitle|ChartOption | ParamStyle(“Chart Style”));
GraphXSpace = 10;
//———————————————————————PlotShapes(shapeUpArrow*LESetUp,colorGreen,0,L,-80); //plots an arrow for the setup bar
//———————————————————————
Plot(LMA,”LMA”,colorBlue,styleLine);
//Plot(LinReg,”Linear Regression”,colorGreen,styleLine);
//———————————————————————
RibbonColour = IIf(IndexFilterUp,colorGreen,colorRed);
Rib = IIf(IndexTog,Null,1); //Links with the Index Filter.If off, nothing (null). If on, 1, which in this case is the ribbon height in percent of pane width
Plot(Rib,””,RibbonColour,styleArea|styleOwnScale|styleNoLabel,-0.00001,190); //Plots line above
//———————————————————————//=====================================================================
_SECTION_END();_SECTION_BEGIN(“Max Wait Days”);
SetCustomBacktestProc(“”);
if (Status(“action”) == actionPortfolio)
{
bo = GetBacktesterObject();
bo.Backtest();
Eqty = Foreign(“~~~Equity”, “C”);
MaxEq = Highest(Eqty);
FlatEq = BarsSince(MaxEq > Ref(MaxEq,-1));
MaxFlat = LastValue(Highest(FlatEq));
bo.AddCustomMetric(“Max Flat Eq Bars”, MaxFlat);
}_SECTION_END();
April 12, 2017 at 8:40 am #106599AnonymousInactiveThis is not so much a discarded system, rather a work in progress. I would be keen to collaborate on expanding the ideas into a rule set. I have been trying out a few ideas using “extremes” measured by 1-2 SD’s away from “x” and not really finding something that is working out, maybe someone will see something I may be missing. I start with an idea and then find a new one along the way and I am getting caught up rather than stepping back and finding the logic and sense. I will post the idea in a separate post.
April 12, 2017 at 9:21 am #106600AnonymousInactiveTrying to capture a swing trade in an uptrend
Defining the trends
Longer term uptrend defined by a 150, 180, 200, 252 MA?
Short term trend defined by a linear regression slope (LRS), 20-30 period lookback
Moving average of the slope, 5-10 day MA
Normalise the LRS with a 14? period ATR – this will make the slope comparable across all prices, volatilities (NLRS)Defining the extreme or buy zone
Average of the NLRS over the last 150, 180, 200, 252 periods?
1 & 2 SD of the NLRS over the same period
Lower band Ave NLRS – 2SD and maybe 1SDEntry ideas
Zone is when the NLRS crosses above it’s MA in the extreme zone – between 1 & 2SD – The NLRS is above it’s MA in that zone!
A swing low should have been formed because of the change in slope and crossing it’s MA
Setup bar could be a number of patterns; inside bar, double inside bar, a compressed range bar (relative to its ave range). Nick posted an article on bar patterns in The Trading System Article Depository
Look to buy 5-10c above the setup barStop loss is 5-10 c below the swing low? Or the setup bar? Or ATR
Condition could be that the distance to the 10-20 day high must be > 2 X the SL at a minimum
Trail the stop with a 2 bar low?? Or other
Profit target at 2R? or let it run and get stopped with the trailing stop or “x” bar exit
Take half the profit at 2R and see what the other half does – I have not thought about coding this option.The idea would be to get average losses less than 1R, maybe around 0.6 – 0.8R level,
Average profits around 1.5R, with a 50/50 W/L ratio this may work depending on the number of opportunities.I would maybe limit the number of trades to 5? Maybe a little more.
I have been trying a few ideas around this kind of thing, looking at extremes based on “something” happening in the 1-2SD area.
The above is one idea, the others are not quite graveyard, but need refining or perhaps there is little merit in my logic and I should put it in the graveyard.Any thoughts would be welcome.
April 12, 2017 at 10:57 pm #106620Nick RadgeKeymasterThe Elder Triple Screen used to be a good method for trading trends from a pullback.
Been awhile since I looked at it…
-
AuthorPosts
- You must be logged in to reply to this topic.