Code for bet size as Equity % using ATR
Forums › ProRealTime English forum › ProOrder support › Code for bet size as Equity % using ATR
- This topic has 6 replies, 2 voices, and was last updated 2 years ago by robertogozzi.
-
-
04/27/2021 at 10:10 AM #168163
Dear Traders and Coders,
I’ve coded a system that takes very short term entries using a simple moving average cross over, but also looks at the higher time frame to filter the direction it takes.
I also use the ATR as the value for a trailing stop loss.
My question is this:
Is there a way to adjust bet size so that it’s 0.5% of account equity for each trade?
This would need to take the ATR value and account equity into account and then adjust the bet size accordingly for each trade.
Here is what I’ve cobbled together so far:
Needs Custom % Bet Sizing12345678910111213141516171819202122232425262728293031323334353637//Definition of code parametersDEFPARAM CumulateOrders = False // Cumulating positions deactivated//Check for trend on higher timeframetimeframe(1 day,updateonclose)emaHTF100 = ExponentialAverage[100]emaHTF200 = ExponentialAverage[200]C1= (close > emaHTF100)C3= (close < emaHTF100)C5= (close < emaHTF200)C6= (close > emaHTF200)// Conditions to enter long positionstimeframe(default)indicator1 = ExponentialAverage[5]indicator2 = ExponentialAverage[20]C2= (indicator1 CROSSES OVER Indicator2)IF CountOfPosition < 2 AND C1 AND C2 THENBUY 1 PERPOINT AT MARKETENDIF// Conditions to enter short positionstimeframe(default)C4= (indicator1 CROSSES UNDER Indicator2)IF CountOfPosition < 2 AND C3 AND C4 THENSELLSHORT 1 PERPOINT AT MARKETENDIF// TRAILING STOPmyATR = 5* averagetruerange[14](close)//trailing stopSET STOP TRAILING myATRMany Thanks
Matt
04/27/2021 at 12:13 PM #168168My Attempt1234567891011121314151617181920212223242526272829303132333435363738394041424344454647//Definition of code parametersDEFPARAM CumulateOrders = False // Cumulating positions deactivated//Check for trend on higher timeframetimeframe(1 day,updateonclose)emaHTF100 = ExponentialAverage[100]emaHTF200 = ExponentialAverage[200]C1= (close > emaHTF100)C3= (close < emaHTF100)C5= (close < emaHTF200)C6= (close > emaHTF200)// Conditions to enter long positionstimeframe(default)indicator1 = ExponentialAverage[5]indicator2 = ExponentialAverage[20]C2= (indicator1 CROSSES OVER Indicator2)IF CountOfPosition < 2 AND C1 AND C2 THENBUY PositionSize CONTRACTS AT MARKETENDIF// Conditions to enter short positionstimeframe(default)C4= (indicator1 CROSSES UNDER Indicator2)IF CountOfPosition < 2 AND C3 AND C4 THENSELLSHORT PositionSize CONTRACTS AT MARKETENDIFREM Money ManagementCapital = 50000Risk = 0.005StopLoss = myATRREM Calculate contractsequity = Capital + StrategyProfitmaxrisk = round(equity*Risk)PositionSize = abs(round((maxrisk/StopLoss)/PointValue)*pipsize)// TRAILING STOPmyATR = 5* averagetruerange[14](close)//trailing stopSET STOP TRAILING myATRThis was my attempt, it seems to work, but the worst trade is always larger than 5% of 50,000. So that makes me think that at some point it’s not always doing it right. Because with a trailing SL the absolute maximum starting risk should be at £250 (5% of £50k) and often when booking a losing trade it would have moved into profit at least a bit and this would then have trailed the stop up meaning the ‘Loss of Worst Trade’ should always be under £250 regardless of the number of points the trailing stop loss used (taking 5x ATR as the max/start point).
Anybody have any other suggestions or alternatives methods?
Cheers
04/27/2021 at 3:15 PM #168218Try adding this snippet between lines 14 and 15 of your first code:
123456789ONCE Capital = 10000ONCE PerCent = 0.5 //0.5%Equity = Capital + StrategyProfitRisk = -(Equity * PerCent / 100)CurrentGain = PositionPerf * PositionPrice * PipValueIF CurrentGain <= Risk THENSELL AT MarketEXITSHORT AT MarketENDIFit exits as soon as the current loss reaches your RISK level. Of course on a low TF this will be quite accurate, while on a higher TF (such as 1+ hour) the loss can easily exceed your planned risk (MTF might help much in this case).
Change your Capital as needed.
0,5% is quite low, it may turn your code into a hugely losing strategy.
1 user thanked author for this post.
04/28/2021 at 5:14 PM #168302Thank you for the reply Roberto. I’ve added that snippet to the existing code, and added a few time restrictions. So now the code looks like this:
Updated Code12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364//Definition of code parametersDEFPARAM CumulateOrders = False // Cumulating positions deactivated// Prevents the system from creating new orders to enter the market or increase position size before the specified timenoEntryBeforeTime = 080000timeEnterBefore = time >= noEntryBeforeTime// Prevents the system from placing new orders to enter the market or increase position size after the specified timenoEntryAfterTime = 190000timeEnterAfter = time < noEntryAfterTime//Check for trend on higher timeframetimeframe(1 day,updateonclose)emaHTF100 = ExponentialAverage[100]emaHTF200 = ExponentialAverage[200]C1= (close > emaHTF100)C3= (close < emaHTF100)C5= (close < emaHTF200)C6= (close > emaHTF200)// Conditions to enter long positionstimeframe(default)ONCE Capital = 50000ONCE PerCent = 0.5 //0.5%Equity = Capital + StrategyProfitRisk = -(Equity * PerCent / 100)CurrentGain = PositionPerf * PositionPrice * PipValueIF CurrentGain <= Risk THENSELL AT MarketEXITSHORT AT MarketENDIFindicator1 = ExponentialAverage[5]indicator2 = ExponentialAverage[20]C2= (indicator1 CROSSES OVER Indicator2)IF CountOfPosition < 2 AND (timeEnterBefore AND timeEnterAfter) AND C1 AND C2 THENBUY PositionSize CONTRACTS AT MARKETENDIF// Conditions to enter short positionstimeframe(default)C4= (indicator1 CROSSES UNDER Indicator2)IF CountOfPosition < 2 AND (timeEnterBefore AND timeEnterAfter) AND C3 AND C4 THENSELLSHORT PositionSize CONTRACTS AT MARKETENDIFREM Money ManagementCapital = 50000Risk = 0.005StopLoss = myATRREM Calculate contractsequity = Capital + StrategyProfitmaxrisk = round(equity*Risk)PositionSize = abs(round((maxrisk/StopLoss)/PointValue)*pipsize)// TRAILING STOPmyATR = 5* averagetruerange[1000](close)//trailing stopSET STOP TRAILING myATRIt appears to be working, but it’s hard to tell as the backtest results at present on PRT seem to be giving some suspicious data back, occasionally only returning like 5 trades over 2 years, when clearly it should have easily placed hundreds. However, for the time being these are the results I’m seeing when run on the 5minute charts on the DOW.
1 user thanked author for this post.
04/28/2021 at 6:02 PM #168306One issue is line 61, since it is executed every bar, it changes while a trade is open, affecting the trailing stop each time. It should be left unchanged when OnMarket:
123IF Not OnMarket THENmyATR = 5* averagetruerange[1000](close)ENDIFanother issue is line 64, since SET STOP TRAILING only sets a pace, not a start. Most people (and myself as well) use the redy-to-run snippet by Nicolas from lines 17 to 56 at https://www.prorealcode.com/blog/trading/complete-trailing-stop-code-function/.
04/28/2021 at 6:41 PM #168308Do I also need to repeat this snippet to apply to the short trades too? Or does adding it in between lines 14 and 15 work for both long and short orders?
I’m afraid my novice skills are being tested here and I’m probably making more of a mess of it.
Using Nicholas’ trailing SL code and your snippet above, this is what I have. It’s incredibly profitable, but it’s not right haha.
My Picaso Code123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102//Definition of code parametersDEFPARAM CumulateOrders = False // Cumulating positions deactivated// Prevents the system from creating new orders to enter the market or increase position size before the specified timenoEntryBeforeTime = 080000timeEnterBefore = time >= noEntryBeforeTime// Prevents the system from placing new orders to enter the market or increase position size after the specified timenoEntryAfterTime = 190000timeEnterAfter = time < noEntryAfterTime//Check for trend on higher timeframetimeframe(1 day,updateonclose)emaHTF100 = ExponentialAverage[100]emaHTF200 = ExponentialAverage[200]C1= (close > emaHTF100)C3= (close < emaHTF100)C5= (close < emaHTF200)C6= (close > emaHTF200)// Conditions to enter long positionstimeframe(default)ONCE Capital = 50000ONCE PerCent = 0.5 //0.5%Equity = Capital + StrategyProfitRisk = -(Equity * PerCent / 100)CurrentGain = PositionPerf * PositionPrice * PipValueIF CurrentGain <= Risk THENSELL AT MarketEXITSHORT AT MarketENDIFindicator1 = ExponentialAverage[5]indicator2 = ExponentialAverage[20]C2= (indicator1 CROSSES OVER Indicator2)IF CountOfPosition < 2 AND (timeEnterBefore AND timeEnterAfter) AND C1 AND C2 THENBUY PositionSize CONTRACTS AT MARKETENDIF// Conditions to enter short positionstimeframe(default)C4= (indicator1 CROSSES UNDER Indicator2)IF CountOfPosition < 2 AND (timeEnterBefore AND timeEnterAfter) AND C3 AND C4 THENSELLSHORT PositionSize CONTRACTS AT MARKETENDIFREM Money ManagementCapital = 50000Risk = 0.005StopLoss = myATRREM Calculate contractsequity = Capital + StrategyProfitmaxrisk = round(equity*Risk)PositionSize = abs(round((maxrisk/StopLoss)/PointValue)*pipsize)// TRAILING STOPmyATR = 5* averagetruerange[1000](close)//************************************************************************//trailing stop functiontrailingstart = myATR //trailing will start @trailinstart points profittrailingstep = 1 //trailing step to move the "stoploss"//reset the stoploss valueIF NOT ONMARKET THENnewSL=0ENDIF//manage long positionsIF LONGONMARKET THEN//first move (breakeven)IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THENnewSL = tradeprice(1)+trailingstep*pipsizeENDIF//next movesIF newSL>0 AND close-newSL>=trailingstep*pipsize THENnewSL = newSL+trailingstep*pipsizeENDIFENDIF//manage short positionsIF SHORTONMARKET THEN//first move (breakeven)IF newSL=0 AND tradeprice(1)-close>=trailingstart*pipsize THENnewSL = tradeprice(1)-trailingstep*pipsizeENDIF//next movesIF newSL>0 AND newSL-close>=trailingstep*pipsize THENnewSL = newSL-trailingstep*pipsizeENDIFENDIF//stop order to exit the positionsIF newSL>0 THENSELL AT newSL STOPEXITSHORT AT newSL STOPENDIF//************************************************************************There may well be some redundant code in there now, I really appreciate your help and patience here.
Cheers
04/28/2021 at 7:11 PM #168309It works for both Long and Short trades.
If you use MyATR then you have to change line 65:
1trailingstart = myATR/PipSizebecause MyATR is a (difference in) price, while that code requires pips.
It works fine as it is now with Nasdaq, Dax and other indices, but not with other instruments such as fx currency pairs.
-
AuthorPosts
Find exclusive trading pro-tools on