New strategy template
Forums › ProRealTime English forum › ProOrder support › New strategy template
- This topic has 35 replies, 10 voices, and was last updated 3 years ago by
Chrisinobi.
-
-
05/15/2021 at 10:39 AM #169730
I’ve been working on a strategy template and thought I’d post it here in case anyone finds it useful. The idea is to include as many common features as possible, most of them being switchable so you can easily opt out of the bits you don’t want. It also includes typical optimization parameters so they don’t have to be entered again and again – just build or insert a strategy and most of the other stuff will already be there with provisional values.
Most of what’s here are snippets created by various people – namely Nicolas, Vonasi, Roberto and Paul among others – that i’ve picked up along the way and found useful. I’m hoping the overall package can be improved and it would be great to hear suggestions for anything else you feel should be included (as well as checking for errors that may have crept into the coding).
There’s a choice of 3 different trailing stops, and I thought of doing the same for MoneyManagement options but, as this seems to be quite a personal choice, I only included the one that I normally use. You can swap it out for whichever you prefer, as long as it produces a value for ‘positionsize’.
This version has some aspects specific to the DAX: spread, minimum positionsize, minimum stop distance (for ATR TS), and certain MoneyManagement details. These have to be altered if you want to use it with other instruments.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558DEFPARAM CumulateOrders = false // Cumulating positions deactivatedDEFPARAM preloadbars = 10000//Money Management DAXMM = 0 // 0 = level stakes for optimizationif MM = 0 thenpositionsize= 1ELSIF MM thenONCE startpositionsize = 0.5ONCE factor = f // adjust for speed of change, higher = slower. factor of 10 means margin will increase/decrease by 10% of strategy profit; factor 20 = 5% etcONCE margin = (close*.05) //IG tier 1 margin value of 1 contract in instrument currency; change decimal according to available leverageONCE margin2 = (close*.05)//IG tier 2 margin value of 1 contract in instrument currency; change decimal according to available leverageONCE tier1 = 105 // IG first tier margin limitONCE maxpositionsize = 1050 // IG tier 2 margin limitONCE minpositionsize = 0.5 // IG minimum position allowedIF StrategyProfit <> StrategyProfit[1] THENpositionsize = startpositionsize + Strategyprofit/(factor*margin)ENDIFIF StrategyProfit <> StrategyProfit[1] THENIF startpositionsize + Strategyprofit/(factor*margin) > tier1 thenpositionsize = (((startpositionsize + (Strategyprofit/(factor*margin))-tier1)*(factor*margin))/(factor*margin2)) + tier1 //incorporating tier 2 marginENDIFIF StrategyProfit <> StrategyProfit[1] THENif startpositionsize + Strategyprofit/(factor*margin) < minpositionsize THENpositionsize = minpositionsize //keeps positionsize from going below allowed minimumENDIFIF (((startpositionsize + (Strategyprofit/(factor*margin))-tier1)*(factor*margin))/(factor*margin2)) + tier1 > maxpositionsize thenpositionsize = maxpositionsize// keeps positionsize from going above IG tier 2 margin limitENDIFENDIFENDIFENDIFonce tradetype = 1 // [1] long/short [2]long [3]shortonce closeonreversal = 0 // if tradetype=2 or tradetype=3, close position when opposite conditions obtainTradetime = time >=h1 and time <h2 //active hours for entering trades//Tradetime = 1 // 24 hour trading//Strategy****************************************************************************Insert all the funky stuff***CBUY = Tradetime and (tradetype=1 or tradetype=2) and (CONDITIONS)CSELL = Tradetime and (tradetype=1 or tradetype=3) and (CONDITIONS)// Conditions to enter long positionsIF NOT LongOnMarket AND CBUY THENBUY positionsize CONTRACTS AT MARKETENDIF// Conditions to exit long positionsIf LongOnMarket AND (CONDITIONS) THENSELL AT MARKETENDIFif closeonreversal and tradetype=2 and CSELL thensell at marketendif// Conditions to enter short positionsIF NOT ShortOnMarket AND CSELL THENSELLSHORT positionsize CONTRACTS AT MARKETENDIF// Conditions to exit short positionsIF ShortOnMarket AND (CONDITIONS) THENEXITSHORT AT MARKETENDIFif closeonreversal and tradetype=3 and CBUY thenEXITSHORT at marketendif// partial closeonce partialclose = 0If partialclose thenONCE PerCent = pcc //0.1 = 10% positions to closeONCE PerCentGain = pcg //0.005 = 0.5% gainONCE MinLotSize = 0.5 //IG minimumExitQuantity = abs(CountOfPosition) * PerCentLeftQty = max(MinLotSize,abs(CountOfPosition) - ExitQuantity)CloseQuantity = abs(CountOfPosition) - LeftQtyIF Not OnMarket THENFlag = 1ENDIFIF partialclose AND LongOnMarket and close >= (PositionPrice * (1 + PerCentGain)) AND Flag THENSELL CloseQuantity Contracts AT MarketFlag = 0endifIF partialclose AND ShortOnMarket and close <= (PositionPrice * (1 - PerCentGain)) AND Flag THENexitshort CloseQuantity Contracts AT MarketFlag = 0endifendif// Stops and targetsDONCHIANSTOP = 0if DONCHIANSTOP thenUpper = Highest[DC](high)Lower = Lowest[DC](low)if longonmarket thenlaststop = Lower[1]endifif shortonmarket thenlaststop = Upper[1]endifif onmarket thensell at laststop stopexitshort at laststop stopendifendifif LongOnMarket and not DONCHIANSTOP thenSET STOP %LOSS slENDIFif ShortOnMarket and not DONCHIANSTOP thenSET STOP %LOSS slsENDIFIf LongOnMarket THENSET TARGET %PROFIT tpENDIFIf ShortOnMarket THENSET TARGET %PROFIT tpsENDIF//EXIT ZOMBIE TRADE, closes long-running unprofitable trades after specified number of barsEZT = 0if EZT thenIF longonmarket and barindex-tradeindex(1)<= z1 and close<positionprice thensell at marketendifIF shortonmarket and barindex-tradeindex(1)>= z2 and close>positionprice thenexitshort at marketendifendif//trailing stoponce trailingstopPC = 1 // Percentage TS, includes break even functiononce enableBreakEven = 0 //Break even, can be used in conjunction with ATR TSonce trailingstopATR = 0 //ATR TSonce trailingstopRTS = 0 //RobertoGozzi trailing stop// Percentage trailing stop function incl. cumulative positionsif trailingstopPC thentrailingpercentlong = tsl // %trailingpercentshort = tss // %once acceleratorlong = a1 // always > 0 (typically TSL/10)once acceleratorshort= a2 // always > 0 (typically TSS/10)ts2sensitivity = 2 // 1 = close 2 = High/Low 3 = Low/High 4 = typicalprice (do not use once)//====================once steppercentlong = (trailingpercentlong/10)*acceleratorlongonce steppercentshort = (trailingpercentshort/10)*acceleratorshortif onmarket thentrailingstartlong = positionprice*(trailingpercentlong/100)trailingstartshort = positionprice*(trailingpercentshort/100)trailingsteplong = positionprice*(steppercentlong/100)trailingstepshort = positionprice*(steppercentshort/100)endifif not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) thennewsl = 0mypositionprice = 0endifpositioncount = abs(countofposition)if newsl > 0 thenif positioncount > positioncount[1] thenif longonmarket thennewsl = max(newsl,positionprice * newsl / mypositionprice)elsenewsl = min(newsl,positionprice * newsl / mypositionprice)endifendifendifif ts2sensitivity=1 thents2sensitivitylong=closets2sensitivityshort=closeelsif ts2sensitivity=2 thents2sensitivitylong=hights2sensitivityshort=lowelsif ts2sensitivity=3 thents2sensitivitylong=lowts2sensitivityshort=highelsif ts2sensitivity=4 thents2sensitivitylong=typicalpricets2sensitivityshort=typicalpriceendifif longonmarket thenif newsl=0 and ts2sensitivitylong-positionprice>=trailingstartlong*pipsize thennewsl = positionprice+trailingsteplong*pipsizeendifif newsl>0 and ts2sensitivitylong-newsl>=trailingsteplong*pipsize thennewsl = newsl+trailingsteplong*pipsizeendifendifif shortonmarket thenif newsl=0 and positionprice-ts2sensitivityshort>=trailingstartshort*pipsize thennewsl = positionprice-trailingstepshort*pipsizeendifif newsl>0 and newsl-ts2sensitivityshort>=trailingstepshort*pipsize thennewsl = newsl-trailingstepshort*pipsizeendifendifif barindex-tradeindex>1 thenif longonmarket thenif newsl>0 thensell at newsl stopendifif newsl>0 thenif low crosses under newsl thensell at marketendifendifendifif shortonmarket thenif newsl>0 thenexitshort at newsl stopendifif newsl>0 thenif high crosses over newsl thenexitshort at marketendifendifendifendifmypositionprice = positionpriceendif// break even stop incl. cumulative positionsif enableBreakEven then//====================once besg = be //% break even stop gainonce besl = bes //% break even stop level (+ or -)besensitivity = 2 // 1 = close 2 = High/Low 3 = Low/High 4 = typicalprice (do not use once)//====================if not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) thenbenewsl=0mypositionpricebe = 0endifpositioncountbe = abs(countofposition)if benewsl > 0 thenif positioncountbe > positioncountbe[1] thenif longonmarket thenbenewsl = max(benewsl,positionprice * benewsl / mypositionpricebe)elsebenewsl = min(benewsl,positionprice * benewsl / mypositionpricebe)endifendifendifif besensitivity=1 thenbesensitivitylong=closebesensitivityshort=closeelsif besensitivity=2 thenbesensitivitylong=highbesensitivityshort=lowelsif besensitivity=3 thenbesensitivitylong=lowbesensitivityshort=highendifif longonmarket thenif besensitivitylong-positionprice>=((positionprice/100)*besg)*pointsize thenbenewsl=positionprice+((positionprice/100)*besl)*pointsizeendifendifif shortonmarket thenif positionprice-besensitivityshort>=((positionprice/100)*besg)*pointsize thenbenewsl=positionprice-((positionprice/100)*besl)*pointsizeendifendifif barindex-tradeindex>1 thenif longonmarket thenif benewsl>0 thensell at benewsl stopendifif benewsl>0 thenif low crosses under benewsl thensell at marketendifendifendifif shortonmarket thenif benewsl>0 thenexitshort at benewsl stopendifif benewsl>0 thenif high crosses over benewsl thenexitshort at marketendifendifendifendifmypositionpricebe = positionpriceendif// trailing atr stop incl. cumulative positionsif trailingstopATR = 1 then//====================once tsincrements = tsi // set to 0 to ignore tsincrementsonce tsminatrdist = tsmonce tsatrperiod = 14 // atr parameteronce tsminstop = 5 // IG minimum stop distance: DAX = 5, DJ = 12, NAS = 4, SP500 = 1tssensitivity = 2 // 1 = close 2 = High/Low 3 = Low/High 4 = typicalprice (do not use once)//====================if barindex=tradeindex thentrailingstoplong = ATRL // ts atr distancetrailingstopshort = ATRS // ts atr distanceelseif longonmarket thenif tsnewsl>0 thenif trailingstoplong>tsminatrdist thenif tsnewsl>tsnewsl[1] thentrailingstoplong=trailingstoplongelsetrailingstoplong=trailingstoplong-tsincrementsendifelsetrailingstoplong=tsminatrdistendifendifendifif shortonmarket thenif tsnewsl>0 thenif trailingstopshort>tsminatrdist thenif tsnewsl<tsnewsl[1] thentrailingstopshort=trailingstopshortelsetrailingstopshort=trailingstopshort-tsincrementsendifelsetrailingstopshort=tsminatrdistendifendifendifendiftsatr=averagetruerange[tsatrperiod]((close/10))/1000//tsatr=averagetruerange[tsatrperiod]((close/1)) // (forex)tgl=round(tsatr*trailingstoplong)tgs=round(tsatr*trailingstopshort)if not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) thentsmaxprice=0tsminprice=closetsnewsl=0mypositionpriceatr = 0endifpositioncountatr = abs(countofposition)if tsnewsl > 0 thenif positioncountatr > positioncountatr[1] thenif longonmarket thentsnewsl = max(tsnewsl,positionprice * tsnewsl / mypositionpriceatr)elsetsnewsl = min(tsnewsl,positionprice * tsnewsl / mypositionpriceatr)endifendifendifif tssensitivity=1 thentssensitivitylong=closetssensitivityshort=closeelsif tssensitivity=2 thentssensitivitylong=hightssensitivityshort=lowelsif tssensitivity=3 thentssensitivitylong=lowtssensitivityshort=highelsif tssensitivity=4 thentssensitivitylong=typicalpricetssensitivityshort=typicalpriceendifif longonmarket thentsmaxprice=max(tsmaxprice,tssensitivitylong)if tsmaxprice-positionprice>=tgl*pointsize thenif tsmaxprice-positionprice>=tsminstop thentsnewsl=tsmaxprice-tgl*pointsizeelsetsnewsl=tsmaxprice-tsminstop*pointsizeendifendifendifif shortonmarket thentsminprice=min(tsminprice,tssensitivityshort)if positionprice-tsminprice>=tgs*pointsize thenif positionprice-tsminprice>=tsminstop thentsnewsl=tsminprice+tgs*pointsizeelsetsnewsl=tsminprice+tsminstop*pointsizeendifendifendifif longonmarket thenif tsnewsl>0 thensell at tsnewsl stopendifif tsnewsl>0 thenif low crosses under tsnewsl thensell at market // when stop is rejectedendifendifendifif shortonmarket thenif tsnewsl>0 thenexitshort at tsnewsl stopendifif tsnewsl>0 thenif high crosses over tsnewsl thenexitshort at market // when stop is rejectedendifendifendifmypositionpriceatr = positionpriceendif//RobertoGozzi TS with cumulative ordersIF trailingstopRTS thenONCE UseCLOSE = 0 //1=use CLOSE, 0=use High/LowsrcH = close //defaults to CLOSEsrcL = close //defaults to CLOSEIF UseCLOSE = 0 THENsrcH = highsrcL = lowENDIFONCE UsePerCentage = 1 //0=use Pips (default), 1=use PercentagesONCE UseEquity = 0 //0=use price (default), 1=use current Equity (initial Capital + StrategyProfit, as defined by variable MyEquity)MyEquity = 1000DirectionSwitch = (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket) //True when there's been a change in the direction (likely to be due to a Stop & Reverse)//IF Not OnMarket OR DirectionSwitch THEN // when NOT OnMarket or thare's been a change in direction, reset values to their default settingsStartPerCent = pc //0.25 = 0.25% movement to trigger Trailing Stop (when UsePerCentage=1)StepPerCent = spc //50 = 50% (of the 0.25% above) as a Trailing Step (when UsePerCentage=1) (set to 100 to make StepSize=TrailStart, set to 200 to make it twice TrailStart)TrailStart = 30 //30 Start trailing profits from this point (when UsePerCentage=0)MinStart = 10 //10 Minimum value for TrailStart (when UseEquity=1, to prevent TrailStart from dropping below ZERO when Equity turns negative)IF UsePerCentage THENTrailStart = (close / PipSize) * StartPerCent / 100 //use current price (CLOSE) for calculationsIF UseEquity THEN //alternative calculations using EQUITYTrailStart = Max(MinStart,(MyEquity / PipValue) * StartPerCent / 100) //MyEquity is the variable (feel free to use a different name) retaining your current equityENDIFENDIF//BasePerCent = bpc //0.08 - 0.2 Profit percentage to keep when setting BerakEvenStepSize = ss //5 - 15 Pip chunks to increase PercentageIF UsePerCentage THENStepSize = TrailStart * StepPerCent / 100ENDIFPerCentInc = pci //0.06 - 0.14 PerCent increment after each StepSize chunkRoundTO = -0.5 //-0.5 rounds always to Lower integer, +0.4 rounds always to Higher integer, 0 defaults PRT behaviourPriceDistance = 5 * pipsize //broker's minimum distance from current pricey1 = 0 //reset to 0y2 = 0 //reset to 0ProfitPerCent = BasePerCent //reset to desired default value//PositionCount = 0SellPrice = 0SellPriceX = 0ExitPrice = 9999999ExitPriceX = 9999999ELSE//------------------------------------------------------// --- Update Stop Loss after accumulating new positions//------------------------------------------------------//PositionCount = max(PositionCount,abs(CountOfPosition))//// update Stop Loss only when PositionPrice has changed (actually when increased, we don't move it if there's been some positions exited)////IF PositionCount <> PositionCount[1] AND (ExitPrice + SellPrice)<>9999999 THEN //go on only if Trailing Stop had already started trailingIF PositionPrice <> PositionPrice[1] AND (ExitPrice + SellPrice) <> 9999999 THEN //go on only if Trailing Stop had already started trailingIF LongOnMarket THENq1 = PositionPrice + ((srcH - PositionPrice) * ProfitPerCent) //calculate new SLSellPriceX = max(max(SellPriceX,SellPrice),q1)SellPrice = max(max(SellPriceX,SellPrice),PositionPrice + (y1 * pipsize)) //set exit price to whatever grants greater profits, comopared to the previous oneELSIF ShortOnMarket THENr1 = PositionPrice - ((PositionPrice - srcL) * ProfitPerCent) //calculate new SLExitPriceX = min(min(ExitPriceX,ExitPrice),r1)ExitPrice = min(min(ExitPriceX,ExitPrice),PositionPrice - (y2 * pipsize)) //set exit price to whatever grants greater profits, comopared to the previous oneENDIFENDIF// --- Update ENDENDIF//IF LongOnMarket AND srcH > (PositionPrice + (y1 * pipsize)) THEN //LONG positions//// compute the value of the Percentage of profits, if any, to lock in for LONG trades//x1 = (srcH - PositionPrice) / pipsize //convert price to pipsIF x1 >= TrailStart THEN // go ahead only if N+ pipsDiff1 = abs(TrailStart - x1) //difference from current profit and TrailStartChunks1 = max(0,round((Diff1 / StepSize) + RoundTO)) //number of STEPSIZE chunksProfitPerCent = BasePerCent + (BasePerCent * (Chunks1 * PerCentInc)) //compute new size of ProfitPerCentProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent)) //make sure ProfitPerCent doess not exceed 100%y1 = max(x1 * ProfitPerCent, y1) //y1 = % of max profitENDIFELSIF ShortOnMarket AND srcL < (PositionPrice - (y2 * pipsize)) THEN //SHORT positions//// compute the value of the Percentage of profits, if any, to lock in for SHORT trades//x2 = (PositionPrice - srcL) / pipsize //convert price to pipsIF x2 >= TrailStart THEN // go ahead only if N+ pipsDiff2 = abs(TrailStart - x2) //difference from current profit and TrailStartChunks2 = max(0,round((Diff2 / StepSize) + RoundTO)) //number of STEPSIZE chunksProfitPerCent = BasePerCent + (BasePerCent * (Chunks2 * PerCentInc)) //compute new size of ProfitPerCentProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent)) //make sure ProfitPerCent doess not exceed 100%y2 = max(x2 * ProfitPerCent, y2) //y2 = % of max profitENDIFENDIF//------------------------------------------------------------------------------// manage actual Exit, if needed//------------------------------------------------------------------------------IF y1 THEN //Place pending STOP order when y1 > 0 (LONG positions)SellPrice = max(SellPrice,PositionPrice + (y1 * pipsize)) //convert pips to price//// check the minimun distance between ExitPrice and current price//IF abs(close - SellPrice) > PriceDistance THEN//// place either a LIMIT or STOP pending order according to current price positioning//IF close >= SellPrice THENSELL AT SellPrice STOPELSESELL AT SellPrice LIMITENDIFELSE////sell AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price//SELL AT MarketENDIFENDIFIF y2 THEN //Place pending STOP order when y2 > 0 (SHORT positions)ExitPrice = min(ExitPrice,PositionPrice - (y2 * pipsize)) //convert pips to price//// check the minimun distance between ExitPrice and current price//IF abs(close - ExitPrice) > PriceDistance THEN//// place either a LIMIT or STOP pending order according to current price positioning//IF close <= ExitPrice THENEXITSHORT AT ExitPrice STOPELSEEXITSHORT AT ExitPrice LIMITENDIFELSE////ExitShort AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price//EXITSHORT AT MarketENDIFENDIFENDIF10 users thanked author for this post.
05/15/2021 at 11:21 AM #169734Nice job nonetheless, this will spare many of us hours of searching and coding.
Thank you 🙂
1 user thanked author for this post.
05/15/2021 at 12:22 PM #169739Hey Roberto, glad you like it. A lot of the code is yours so grazie a te!
I wanted to check, in your TS, at line 456 above, there’s a value for PriceDistance. Is this a variable, or the IG minimum stop distance?
(I assumed the latter)
05/15/2021 at 12:24 PM #16974005/15/2021 at 12:51 PM #169742your assumption is right, it’s the broker’s minimum distance required for pending orders.
05/15/2021 at 12:54 PM #16974305/15/2021 at 1:04 PM #169745Link to above Combo Snippet Template added as Log 286 here …
05/15/2021 at 1:11 PM #169746pulling all the snippets together!
Well, not ALL the snippets, but hopefully some of the more useful ones. Let’s see if any changes/improvements come to light over the next few days and I’ll knock up separate versions for the main indices to lodge in the Snippet Library for posterity…
Actually I spotted a mistake already, line 139 should be >=
1IF longonmarket and barindex-tradeindex(1)>= z1 and close<positionprice thenDon’t know how that happened ???
1 user thanked author for this post.
05/15/2021 at 1:21 PM #169747v2 with minor changes and corrections…
05/15/2021 at 1:43 PM #169749let’s try that again, I think I exported without saving and somehow the correction didn’t register ???
5 users thanked author for this post.
05/16/2021 at 10:27 AM #169795Excellent idea. This would make it very streamlined to optimise and may lead to interesting results.
We could add candlestick patterns or generic filters into the template. Ofcourse Grahals snippets.
Ill try to contribute as well when i can.
05/16/2021 at 4:11 PM #169809some minor changes, plus versions specific to DJ, NAS, SP500
1 user thanked author for this post.
05/16/2021 at 7:15 PM #169826Thank you very much for this initiative! I was just thinking of creating a few specific topics to bring together the snippets by theme: trailing stop, money management, etc. Bravo!
1 user thanked author for this post.
05/16/2021 at 9:41 PM #169840a few more changes, corrections…
3 users thanked author for this post.
05/17/2021 at 1:07 PM #169892On small simplification suggestion:
Line 23 and 26 of the original code
23: if positionsize < minpositionsize then
26: if positionsize > maxpositionsize then
Thanks for sharing your template
1 user thanked author for this post.
-
AuthorPosts
Find exclusive trading pro-tools on