Code for bet size as Equity % using ATR

Viewing 7 posts - 1 through 7 (of 7 total)
  • Author
    Posts
  • #168163 quote
    AugustusKing
    Participant
    Junior

    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:

    //Definition of code parameters
    DEFPARAM CumulateOrders = False // Cumulating positions deactivated
    
    //Check for trend on higher timeframe
    timeframe(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 positions
    timeframe(default)
    indicator1 = ExponentialAverage[5]
    indicator2 = ExponentialAverage[20]
    C2= (indicator1 CROSSES OVER Indicator2)
    
    IF CountOfPosition < 2 AND C1 AND C2 THEN
    
    BUY 1 PERPOINT AT MARKET
    ENDIF
    
    // Conditions to enter short positions
    timeframe(default)
    C4= (indicator1 CROSSES UNDER Indicator2)
    
    IF CountOfPosition < 2 AND C3 AND C4 THEN
    
    SELLSHORT 1 PERPOINT AT MARKET
    ENDIF
    
    // TRAILING STOP
    myATR = 5* averagetruerange[14](close)
    
    //trailing stop
    SET STOP TRAILING myATR

    Many Thanks

    Matt

    #168168 quote
    AugustusKing
    Participant
    Junior
    //Definition of code parameters
    DEFPARAM CumulateOrders = False // Cumulating positions deactivated
    
    //Check for trend on higher timeframe
    timeframe(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 positions
    timeframe(default)
    indicator1 = ExponentialAverage[5]
    indicator2 = ExponentialAverage[20]
    C2= (indicator1 CROSSES OVER Indicator2)
    
    IF CountOfPosition < 2 AND C1 AND C2 THEN  
    
    BUY PositionSize CONTRACTS AT MARKET
    ENDIF
    
    // Conditions to enter short positions
    timeframe(default)
    C4= (indicator1 CROSSES UNDER Indicator2)
    
    IF CountOfPosition < 2 AND C3 AND C4 THEN 
    
    SELLSHORT PositionSize CONTRACTS AT MARKET
    ENDIF
    
    REM Money Management
    Capital = 50000
    Risk = 0.005
    StopLoss = myATR
     
    REM Calculate contracts
    equity = Capital + StrategyProfit
    maxrisk = round(equity*Risk)
    PositionSize = abs(round((maxrisk/StopLoss)/PointValue)*pipsize)
    
    // TRAILING STOP
    myATR = 5* averagetruerange[14](close)
    
    //trailing stop
    SET STOP TRAILING myATR

    This 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

    #168218 quote
    robertogozzi
    Moderator
    Master

    Try adding this snippet between lines 14 and 15 of your first code:

    ONCE Capital    = 10000
    ONCE PerCent    = 0.5                       //0.5%
    Equity          = Capital + StrategyProfit
    Risk            = -(Equity * PerCent / 100)
    CurrentGain     = PositionPerf * PositionPrice * PipValue
    IF CurrentGain <= Risk THEN
       SELL AT Market
       EXITSHORT AT Market
    ENDIF

    it 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.

    AugustusKing thanked this post
    #168302 quote
    AugustusKing
    Participant
    Junior

    Thank 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:

    //Definition of code parameters
    DEFPARAM CumulateOrders = False // Cumulating positions deactivated
    
    // Prevents the system from creating new orders to enter the market or increase position size before the specified time
    noEntryBeforeTime = 080000
    timeEnterBefore = time >= noEntryBeforeTime
    
    // Prevents the system from placing new orders to enter the market or increase position size after the specified time
    noEntryAfterTime = 190000
    timeEnterAfter = time < noEntryAfterTime
    
    //Check for trend on higher timeframe
    timeframe(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 positions
    timeframe(default)
    ONCE Capital    = 50000
    ONCE PerCent    = 0.5                       //0.5%
    Equity          = Capital + StrategyProfit
    Risk            = -(Equity * PerCent / 100)
    CurrentGain     = PositionPerf * PositionPrice * PipValue
    IF CurrentGain <= Risk THEN
    SELL AT Market
    EXITSHORT AT Market
    ENDIF
    indicator1 = ExponentialAverage[5]
    indicator2 = ExponentialAverage[20]
    C2= (indicator1 CROSSES OVER Indicator2)
    
    IF CountOfPosition < 2 AND (timeEnterBefore AND timeEnterAfter) AND C1 AND C2 THEN
    
    BUY PositionSize CONTRACTS AT MARKET
    ENDIF
    
    // Conditions to enter short positions
    timeframe(default)
    C4= (indicator1 CROSSES UNDER Indicator2)
    
    IF CountOfPosition < 2 AND (timeEnterBefore AND timeEnterAfter) AND C3 AND C4 THEN
    
    SELLSHORT PositionSize CONTRACTS AT MARKET
    ENDIF
    
    REM Money Management
    Capital = 50000
    Risk = 0.005
    StopLoss = myATR
     
    REM Calculate contracts
    equity = Capital + StrategyProfit
    maxrisk = round(equity*Risk)
    PositionSize = abs(round((maxrisk/StopLoss)/PointValue)*pipsize)
    
    // TRAILING STOP
    myATR = 5* averagetruerange[1000](close)
    
    //trailing stop
    SET STOP TRAILING myATR
    

    It 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.

    robertogozzi thanked this post
    #168306 quote
    robertogozzi
    Moderator
    Master

    One 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:

    IF Not OnMarket THEN
       myATR = 5* averagetruerange[1000](close)
    ENDIF

    another 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/.

    #168308 quote
    AugustusKing
    Participant
    Junior

    Do 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.

    //Definition of code parameters
    DEFPARAM CumulateOrders = False // Cumulating positions deactivated
     
    // Prevents the system from creating new orders to enter the market or increase position size before the specified time
    noEntryBeforeTime = 080000
    timeEnterBefore = time >= noEntryBeforeTime
     
    // Prevents the system from placing new orders to enter the market or increase position size after the specified time
    noEntryAfterTime = 190000
    timeEnterAfter = time < noEntryAfterTime
     
    //Check for trend on higher timeframe
    timeframe(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 positions
    timeframe(default)
    ONCE Capital    = 50000
    ONCE PerCent    = 0.5                       //0.5%
    Equity          = Capital + StrategyProfit
    Risk            = -(Equity * PerCent / 100)
    CurrentGain     = PositionPerf * PositionPrice * PipValue
    IF CurrentGain <= Risk THEN
    SELL AT Market
    EXITSHORT AT Market
    ENDIF
    indicator1 = ExponentialAverage[5]
    indicator2 = ExponentialAverage[20]
    C2= (indicator1 CROSSES OVER Indicator2)
     
    IF CountOfPosition < 2 AND (timeEnterBefore AND timeEnterAfter) AND C1 AND C2 THEN
     
    BUY PositionSize CONTRACTS AT MARKET
    ENDIF
     
    // Conditions to enter short positions
    timeframe(default)
    C4= (indicator1 CROSSES UNDER Indicator2)
     
    IF CountOfPosition < 2 AND (timeEnterBefore AND timeEnterAfter) AND C3 AND C4 THEN
     
    SELLSHORT PositionSize CONTRACTS AT MARKET
    ENDIF
     
    REM Money Management
    Capital = 50000
    Risk = 0.005
    StopLoss = myATR
     
    REM Calculate contracts
    equity = Capital + StrategyProfit
    maxrisk = round(equity*Risk)
    PositionSize = abs(round((maxrisk/StopLoss)/PointValue)*pipsize)
     
    // TRAILING STOP
    myATR = 5* averagetruerange[1000](close)
     
    //************************************************************************
    //trailing stop function
    trailingstart = myATR //trailing will start @trailinstart points profit
    trailingstep = 1 //trailing step to move the "stoploss"
     
    //reset the stoploss value
    IF NOT ONMARKET THEN
    newSL=0
    ENDIF
     
    //manage long positions
    IF LONGONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND close-tradeprice(1)>=trailingstart*pipsize THEN
    newSL = tradeprice(1)+trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND close-newSL>=trailingstep*pipsize THEN
    newSL = newSL+trailingstep*pipsize
    ENDIF
    ENDIF
     
    //manage short positions
    IF SHORTONMARKET THEN
    //first move (breakeven)
    IF newSL=0 AND tradeprice(1)-close>=trailingstart*pipsize THEN
    newSL = tradeprice(1)-trailingstep*pipsize
    ENDIF
    //next moves
    IF newSL>0 AND newSL-close>=trailingstep*pipsize THEN
    newSL = newSL-trailingstep*pipsize
    ENDIF
    ENDIF
     
    //stop order to exit the positions
    IF newSL>0 THEN
    SELL AT newSL STOP
    EXITSHORT AT newSL STOP
    ENDIF
    //************************************************************************

    There may well be some redundant code in there now, I really appreciate your help and patience here.

    Cheers

    #168309 quote
    robertogozzi
    Moderator
    Master

    It works for both Long and Short trades.

    If you use MyATR then you have to change line 65:

    trailingstart = myATR/PipSize

    because 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.

Viewing 7 posts - 1 through 7 (of 7 total)
  • You must be logged in to reply to this topic.

Code for bet size as Equity % using ATR


ProOrder support

New Reply
Author
Summary

This topic contains 6 replies,
has 2 voices, and was last updated by robertogozzi
4 years, 9 months ago.

Topic Details
Forum: ProOrder support
Language: English
Started: 04/27/2021
Status: Active
Attachments: 2 files
Logo Logo
Loading...