Simple Moving Average Crossover Strategy

Viewing 15 posts - 31 through 45 (of 96 total)
  • Author
    Posts
  • #190532 quote
    GraHal
    Participant
    Master

    NAS-5m-MACross-v4.1-L1.itf contains 216 lines of code.

    NAS 5m MACross v4.1 L contains 288 lines of code.

    Maybe there is good reason?

    Souhail Sam thanked this post
    #190534 quote
    Souhail Sam
    Participant
    Senior

    Oh Yes There is a very good reason :’D , i did a mistake by replacing a lot of lines by what @nonetheless have gave me. Thanks for the notice.
    Also i did remove the MM code.
    If i correct that, the code will be : ( no spread, MM off, 2000 capital)

    // opt: 01/03/2022
    //=======================================================================
    DEFPARAM CUMULATEORDERS = FALSE
    DEFPARAM preloadbars = 10000
    //Money Management
    
    positionsize=1
    
    //Tradetime
    //adjustment for American Daylight Savings time
    ADLS =1
    if ADLS then
    DLS =(Date >= 20100314 and date <=20100328) or (Date >= 20101031 and date <=20101107) or (Date >= 20110313 and date <=20110327) or (Date >= 20111030 and date <=20111106) or (Date >= 20120311 and date <=20120325) or (Date >= 20121028 and date <=20121104) or (Date >= 20130310 and date <=20130331) or (Date >= 20131027 and date <=20131103) or (Date >= 20140309 and date <=20140330) or (Date >= 20141026 and date <=20141102) or (Date >= 20150308 and date <=20150329) or (Date >= 20151025 and date <=20151101) or (Date >= 20160313 and date <=20160327) or (Date >= 20161030 and date <=20161106) or (Date >= 20170312 and date <=20170326) or (Date >= 20171030 and date <=20171105) or (Date >= 20180311 and date <=20180325) or (Date >= 20181028 and date <=20181104) or (Date >= 20190310 and date <=20190331) or (Date >= 20191027 and date <=20191103) or (Date >= 20200308 and date <=20200329) or (Date >= 20201025 and date <=20201101) or (Date >= 20210314 and date <=20210328) or (Date >= 20211031 and date <=20211107) or (Date >= 20220313 and date <=20220327) or (Date >= 20221030 and date <=20221106) or (Date >= 20230312 and date <=20230326) or (Date >= 20231029 and date <=20231105) or (Date >= 20240310 and date <=20240331) or (Date >= 20241027 and date <=20241103)
    If DLS then
    Tradetime = time >=h1-10000 and time <h2-10000
    elsif not DLS then
    Tradetime = time >=h1 and time <h2
    endif
    endif
    
    if not ADLS then
    Tradetime = time >=h1 and time <h2
    endif
    
    //Long Entry Filter
    Timeframe(4 hours)
    FMA1 = average[p,t](typicalprice)
    //FMA2 = average[p1,t](typicalprice)
    cb1 = FMA1 > FMA1[1]
    //cs1 = FMA1 < FMA2
    
    Timeframe(15 minutes)
    M15 = average[p2,t2](typicalprice)
    cb2 = (close>m15)
    //cs2 = close<average[p2,t2](typicalprice)
    
    Timeframe(Default)
    //Long Entry Criteria
    MA1=average[p3,t3](typicalprice)
    MA2=average[p4,t3](typicalprice)
    cb3 = MA1 crosses over MA2
    //cs3 = MA1 crosses under MA2
    
    //Stochastic RSI | indicator
    lengthRSI = lr //RSI period
    lengthStoch = ls //Stochastic period
    smoothK = sk //Smooth signal of stochastic RSI
    smoothD = sd //Smooth signal of smoothed stochastic RSI
    myRSI = RSI[lengthRSI](close)
    MinRSI = lowest[lengthStoch](myrsi)
    MaxRSI = highest[lengthStoch](myrsi)
    StochRSI = (myRSI-MinRSI) / (MaxRSI-MinRSI)
    K = average[smoothK](stochrsi)*100
    D = average[smoothD](K)
    cb4 = K>D
    
    // Conditions to enter long positions
    If Tradetime and cb1 and cb2 and cb3 and cb4 Then
    Buy PositionSize CONTRACTS AT MARKET
    ENDIF
    
    SET STOP %LOSS sl
    SET TARGET %PROFIT tp
    
    //  Break even and trailing stop RTS
    IF Not OnMarket THEN
    // when NOT OnMarket reset values to default values
    ts = (tradeprice*pc)/100   // % trailing start
    TrailStart    = ts         //30     Start trailing profits from this point
    BasePerCent   = base       //  0.200  20.0%  Profit percentage to keep when setting BerakEven
    StepSize      = ss           //10     Pip chunks to increase Percentage
    PerCentInc    = pci        // 0.100  10.0%  PerCent increment after each StepSize chunk
    BarNumber     = bn           //10     Add further % so that trades don't keep running too long
    BarPerCent    = bpc       // 0.100 10%    Add this additional percentage every BarNumber bars
    RoundTO       = 0        //-0.5   rounds always to Lower integer,   +0.4 rounds always to Higher integer,     0 defaults PRT behaviour
    PriceDistance = 4 * pipsize //IG  minimun distance from current price
    y1            = 0           //reset to 0
    y2            = 0           //reset to 0
    ProfitPerCent = BasePerCent //reset to desired default value
    TradeBar      = BarIndex
    ELSIF LongOnMarket AND close > (TradePrice + (y1 * pipsize)) THEN
    //LONG positions
    //
    // compute the value of the Percentage of profits, if any, to lock in for LONG trades
    //
    x1 = (close - tradeprice) / pipsize                                     //convert price to pips
    IF x1 >= TrailStart THEN                                                //    go ahead only if N+ pips
    Diff1         = abs(TrailStart - x1)                                 //difference from current profit and TrailStart
    Chunks1       = max(0,round((Diff1 / StepSize) + RoundTO))           //number of STEPSIZE chunks
    ProfitPerCent = BasePerCent + (BasePerCent * (Chunks1 * PerCentInc)) //compute new size of ProfitPerCent
    // compute number of bars elapsed and add an additionl percentage
    // (this percentage is different from PerCentInc, since it's a direct percentage, not a Percentage of BasePerCent)
    // (if BasePerCent is 20% and this is 10%, the whole percentage will be 30%, not 22%)
    BarCount      = BarIndex - TradeBar
    IF BarCount MOD BarNumber = 0 THEN
    ProfitPerCent = ProfitPerCent + BarPerCent
    ENDIF
    //
    ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent))         //make sure ProfitPerCent doess not exceed 100%
    y1 = max(x1 * ProfitPerCent, y1)                                     //y1 = % of max profit
    ENDIF
    ELSIF ShortOnMarket AND close < (TradePrice - (y2 * pipsize)) THEN
    //SHORT positions
    //
    // compute the value of the Percentage of profits, if any, to lock in for SHORT trades
    //
    x2 = (tradeprice - close) / pipsize                                     //convert price to pips
    IF x2 >= TrailStart THEN                                                //      go ahead only if N+ pips
    Diff2         = abs(TrailStart - x2)                                 //difference from current profit and TrailStart
    Chunks2       = max(0,round((Diff2 / StepSize) + RoundTO))           //number of STEPSIZE chunks
    ProfitPerCent = BasePerCent + (BasePerCent * (Chunks2 * PerCentInc)) //compute new size of ProfitPerCent
    // compute number of bars elapsed and add an additionl percentage
    // (this percentage is different from PerCentInc, since it's a direct percentage, not a Percentage of BasePerCent)
    // (if BasePerCent is 20% and this is 10%, the whole percentage will be 30%, not 22%)
    BarCount      = BarIndex - TradeBar
    IF BarCount MOD BarNumber = 0 THEN
    ProfitPerCent = ProfitPerCent + BarPerCent
    ENDIF
    //
    ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent))         //make sure ProfitPerCent doess not exceed 100%
    y2 = max(x2 * ProfitPerCent, y2)                                     //y2 = % of max profit
    ENDIF
    ENDIF
    
    IF y1 THEN                                                                 //Place pending STOP order when y1 > 0   (LONG positions)
    SellPrice = Tradeprice + (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 THEN
    SELL AT SellPrice STOP
    ELSE
    SELL AT SellPrice LIMIT
    ENDIF
    ELSE
    //
    //sell AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price
    //
    SELL AT Market
    ENDIF
    ENDIF
    IF y2 THEN                                                                 //Place pending STOP order when y2 > 0   (SHORT positions)
    ExitPrice = Tradeprice - (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 THEN
    EXITSHORT AT ExitPrice STOP
    ELSE
    EXITSHORT AT ExitPrice LIMIT
    ENDIF
    ELSE
    //
    //ExitShort AT MARKET when EXITPRICE does not meet the broker's minimun distance from current price
    //
    EXITSHORT AT Market
    ENDIF
    ENDIF
    
    //----------------------------------------------------------------------------
    
    //EXIT ZOMBIE TRADE
    EZT = 1
    if EZT then
    IF (longonmarket and barindex-tradeindex(1)>= b1 and positionperf>0) or (longonmarket and barindex-tradeindex(1)>= b2 and positionperf<0) then
    sell at market
    endif
    IF (shortonmarket and barindex-tradeindex(1)>= 4000 and positionperf>0) or (shortonmarket and barindex-tradeindex(1)>= 4000 and positionperf<0) then
    exitshort at market
    endif
    endif
    
    //----------------------------------------------------------------------------
    
    RSIexit = 1 // in profit
    if RSIexit then
    myrsi2=rsi[r](close)
    if myrsi2<rl and barindex-tradeindex>1 and longonmarket and positionperf>0 then
    sell at market
    endif
    if myrsi2>70 and barindex-tradeindex>1 and shortonmarket and positionperf>0 then
    exitshort at market
    endif
    endif
    
    //----------------------------------------------------------------------------
    DSD = 1
    if DSD then
    once openStrongLong = 0
    once openStrongShort = 0
    if (time <= 120000 or time >= 170000) then // 070000, 100000
    openStrongLong = 0
    openStrongShort = 0
    endif
     
    //detect strong direction for market open
    once rangeOK = rok // 30
    once tradeMin = tm  // 1000
    IF (time >= 120500) AND (time <= 120500 + tradeMin) AND ABS(close - open) > rangeOK THEN
    IF close > open and close > open[1] THEN
    openStrongLong = 1
    openStrongShort = 0
    ENDIF
    IF close < open and close < open[1] THEN
    openStrongLong = 0
    openStrongShort = 1
    ENDIF
    ENDIF
    
    once bollperiod = bp // 20
    once bollMAType = 1
    once s = 2
    
    bollMA = average[bollperiod, bollMAType](close)
    STDDEV = STD[bollperiod]
    bollUP = bollMA + s * STDDEV
    bollDOWN = bollMA - s * STDDEV
    IF bollUP = bollDOWN THEN
    bollPercent = 50
    ELSE
    bollPercent = 100 * (close - bollDOWN) / (bollUP - bollDOWN)
    ENDIF
    
    once trendPeriod = trp //80
    once trendPeriodResume = tpr // 10
    once trendGap = 4
    once trendResumeGap = 4
    if not onmarket then
    fullySupported = 0
    fullyResisted = 0
    endif
    //Market supported in the wrong direction
    IF shortonmarket AND fullySupported = 0 AND summation[trendPeriod](bollPercent > 50) >= trendPeriod - trendGap THEN
    fullySupported = 1
    ENDIF
    
    //Market pull back but continue to be supported
    IF shortonmarket AND fullySupported = 1 AND bollPercent[trendPeriodResume + 1] < 0 AND summation[trendPeriodResume](bollPercent > 50) >= trendPeriodResume - trendResumeGap THEN
    exitshort at market
    ENDIF
    
    //Market resisted in wrong direction
    IF longonmarket AND fullyResisted = 0 AND summation[trendPeriod](bollPercent < 50) >= trendPeriod - trendGap THEN
    fullyResisted = 1
    ENDIF
    
    //Market pull back but continue to be resisted
    IF longonmarket AND fullyResisted = 1 AND bollPercent[trendPeriodResume + 1] > 100 AND summation[trendPeriodResume](bollPercent < 50) >= trendPeriodResume - trendResumeGap THEN
    sell at market
    ENDIF
    
    //Started real wrong direction
    once strongTrend = st // 60
    once strongPeriod = sp // 4
    once strongTrendGap = stg // 2
    IF shortonmarket and openStrongLong and barindex - tradeindex < 12 and summation[strongPeriod](bollPercent > strongTrend) = strongPeriod - strongTrendGap then
    exitshort at market
    ENDIF
    
    IF longonmarket and openStrongShort and barindex - tradeindex < 12 and summation[strongPeriod](bollPercent < 100 - strongTrend) = strongPeriod - strongTrendGap then
    sell at market
    ENDIF
    endif
    
    V4.1-1M-no-spread-2.png V4.1-1M-no-spread-2.png NAS-5m-MACross-v4.1-L2.itf
    #190581 quote
    VinzentVega
    Participant
    Veteran

    In my opinion, it´s sensless to do a backtest without spread, the results are falsified.

    Souhail Sam thanked this post
    #190582 quote
    Souhail Sam
    Participant
    Senior

    I agree with you, it’s just to help to find what’s wrong with my backtest wich is 55% less good than Nonetheless Backtest :’D

    GraHal thanked this post
    #190583 quote
    GraHal
    Participant
    Master

    I though that, but surely the spread is in the code somehow / somewhere??

    I just glanced over the code, but spread didn’t jump out at me.

    Souhail Sam thanked this post
    #190584 quote
    Souhail Sam
    Participant
    Senior

    Attached are the results with a constant exposure value of €10k, gives a better visual on the histogram and the curve.

    I am comparing my backtest with the backtest of this “constant exposure” that i don’t know what it is. Thanks

    #190592 quote
    JS
    Participant
    Veteran

    Line 223 STDDEV = STD[bollperiod]

    STDDEV = STD[bollperiod] (price)

    Missing the (price) ?

    Souhail Sam thanked this post
    #190596 quote
    nonetheless
    Participant
    Master

    comparing my backtest with the backtest of this “constant exposure”

    this means positionsize = 10000/close

    shows performance if you had risked a constant value (€10k) rather than a constant size per point

    this would definitely explain the difference you are seeing!

    Souhail Sam thanked this post
    #190597 quote
    Souhail Sam
    Participant
    Senior

    Thank you very much @nonetheless, I understand now the difference !

    #190664 quote
    phoentzs
    Participant
    Master

    @nonetheless

    What are your experiences with this type of optimization? I see a lot of small wins and a big SL. In the report, the average gains are also much smaller than the average losses. In my experience, with such values, the strategy usually collapses in sideways phases, so it is not robust. I optimize as much as possible in such a way that the average wins are always greater than the average losses. So you still have the chance to come out plus/minus 0 in sideways phases. Hit rate is then of course lower, between 40-60%.

    how do you see it?

    #190670 quote
    nonetheless
    Participant
    Master

    I have some systems with only 55% win rate, but very high risk/reward, others with over 90% wins but risk/reward around .3 or so. Then I have one with the best of both worlds … but very few trades, maybe one per month. There’s always going to be a trade-off between these factors and I think the difference is largely psychological. Either can turn a profit in the long term, it depends on what you’re comfortable with.

    A broker I had years ago liked to say, “No one ever went bankrupt by booking small gains” … and I guess that message stuck as I tend towards high win rate, even if the wins are small. This often means a low breakeven level and high SL that others may find makes them anxious. Personally it doesn’t bother me to carry a trade the wrong way for 1.6 or 1.8% knowing that 90% of the time it will turn around and close for a profit.

    Attached is the first few weeks OOS for v4.1L, positionsize = 1

    (nicely demonstrates one good thing about long-only systems: what you lose on the way down you will probably get back on the way up)

    thanked this post
    NAS-5m-MACross-v4.1-L-oos.jpg NAS-5m-MACross-v4.1-L-oos.jpg
    #190672 quote
    phoentzs
    Participant
    Master

    @nonetheless

    Thanks for the information. I’ll just try it on one of my systems to achieve a high hit rate. Then I’ll try running it next to the original and compare.

    #190777 quote
    phoentzs
    Participant
    Master

    Here is my humble contribution to an MA Cross system. I use SP500 here because most of my systems are based on it (many systems, little margin, little spread, portfolio building).
    I solved it completely conventionally, with simple SMAs. The all-important trend seems to be the weekly trend. M15/SMA480 = D1/SMA5

    Here is the system, long/short combined. Maybe there is still room for improvement?


    @nonetheless

    You always have a golden touch. Maybe you can take a look?

    //30.03.2022  200000k
    //US500 M5 Spread 0.6
    //German Time
    
    defparam preloadbars = 10000
    defparam CUMULATEORDERS = false
    
    
    possize = 5
    
    timeframe(15minute, updateonclose)
    RangeMAD5 = average[480,0](close)   //Wochentrend Daily MA5
    RangelongD5  = close > RangeMAD5
    RangeshortD5 = close < RangeMAD5
    
    RangeMAD20 = average[1920,0](close)  //"Monatstrend" Daily MA20
    RangelongD20  = RangeMAD5 > RangeMAD20
    RangeshortD20 = RangeMAD5 < RangeMAD20
    
    
    MA1 = average[x1,0](close)
    MA2 = average[x2,0](close)
    //MA3 = average[x3,0](close)
    MA4 = average[x5,1](close)
    MA5 = average[x6,1](close)
    
    longA  = MA1 > MA2 //and MA2 > MA3 //and MA2 > MA2[1]
    shortA = MA4 < MA5 //and MA5 < MA5[1]
    
    MAL1 = average[5,0](close)
    MAL2 = average[15,0](close) //15
    longB  = MAL1 crosses over MAL2
    shortB = MAL1 crosses under MAL2
    
    
    timeframe(default)//M5
    long   =   RangelongD5 and longB and longA     //and RangelongD20
    short  =   RangeshortD5 and shortB and shortA  //and RangeshortD20
    Exit1 = RangeshortD5
    Exit2 = RangelongD5
    
    // trading window
    ONCE BuyTime   = 110000
    ONCE SellTime  = 213000
    ONCE BuyTime2  = 150000
    ONCE SellTime2 = 213000
     
    // position management
    IF Time >= buyTime AND Time <= SellTime THEN
    
    If long then                           //not onmarket and
    BUY possize CONTRACT AT market
    SET STOP %LOSS hl
    SET TARGET %PROFIT gl
    EndIf
    
    endif
    
    IF Time >= buyTime2 AND Time <= SellTime2 THEN
    
    If short then
    sellshort possize CONTRACT AT market
    SET STOP %LOSS hs
    SET TARGET %PROFIT gs
    EndIf
    
    endif
    
    If longonmarket and Exit1 then
    sell at market
    endif
    
    If shortonmarket and Exit2 then
    exitshort at market
    endif
     
    
    if time = 223000 then  //223000
    //sell at market
    exitshort at market
    endif
    
    if time = 225500 and dayofweek=5 then  //225500
    sell at market
    exitshort at market
    endif
    
    ////////////////////////////////////////
    // %trailing stop function incl. cumulative positions
    once trailingstoptype = 1
    if trailingstoptype then
    //====================
    trailingpercentlong  = startl // %
    trailingpercentshort = start // %
    once acceleratorlong = stepl // typically tst*0.1
    once acceleratorshort= step // typically tss*0.1
    ts2sensitivity  = 2 // [1] close [2] high/low [3] low/high [4] typicalprice
    //====================
    once steppercentlong  = (trailingpercentlong/10)*acceleratorlong
    once steppercentshort = (trailingpercentshort/10)*acceleratorshort
    if onmarket then
    trailingstartlong = positionprice*(trailingpercentlong/100)
    trailingstartshort = positionprice*(trailingpercentshort/100)
    trailingsteplong = positionprice*(steppercentlong/100)
    trailingstepshort = positionprice*(steppercentshort/100)
    endif
    
    if not onmarket or ((longonmarket and shortonmarket[1]) or (longonmarket[1] and shortonmarket)) then
    newsl           = 0
    mypositionprice = 0
    endif
    positioncount = abs(countofposition)
    if newsl > 0 then
    if positioncount > positioncount[1] then
    if longonmarket then
    newsl = max(newsl,positionprice * newsl / mypositionprice)
    else
    newsl = min(newsl,positionprice * newsl / mypositionprice)
    endif
    endif
    endif
    if ts2sensitivity=1 then
    ts2sensitivitylong=close
    ts2sensitivityshort=close
    elsif ts2sensitivity=2 then
    ts2sensitivitylong=high
    ts2sensitivityshort=low
    elsif ts2sensitivity=3 then
    ts2sensitivitylong=low
    ts2sensitivityshort=high
    elsif ts2sensitivity=4 then
    ts2sensitivitylong=(typicalprice)
    ts2sensitivityshort=(typicalprice)
    endif
    if longonmarket then
    if newsl=0 and ts2sensitivitylong-positionprice>=trailingstartlong then
    newsl = positionprice+trailingsteplong + 0.2
    endif
    if newsl>0 and ts2sensitivitylong-newsl>=trailingsteplong then
    newsl = newsl+trailingsteplong
    endif
    endif
    if shortonmarket then
    if newsl=0 and positionprice-ts2sensitivityshort>=trailingstartshort then
    newsl = positionprice-trailingstepshort
    endif
    if newsl>0 and newsl-ts2sensitivityshort>=trailingstepshort then
    newsl = newsl-trailingstepshort
    endif
    endif
    if barindex-tradeindex>1 then
    if longonmarket then
    if newsl>0 then
    sell at newsl stop
    endif
    if newsl>0 then
    if low crosses under newsl then
    sell at market
    endif
    endif
    endif
    if shortonmarket then
    if newsl>0 then
    exitshort at newsl stop
    endif
    if newsl>0 then
    if high crosses over newsl then
    exitshort at market
    endif
    endif
    endif
    endif
    mypositionprice = positionprice
    endif
    
    if (shortonmarket and newsl > 0) or (longonmarket and newsl>0) then
    if positioncount > positioncount[1] then
    if longonmarket then
    newsl = max(newsl,positionprice * newsl / mypositionprice)
    endif
    if shortonmarket then
    newsl = min(newsl,positionprice * newsl / mypositionprice)
    endif
    endif
    endif
    //////////////////////////////////////////////////////////////
    
    GraHal and Razz thanked this post
    T4-Multi-SP500-M5-V3.itf T4-Multi-SP500-M5-V3.jpg T4-Multi-SP500-M5-V3.jpg
    #190795 quote
    MauroPro
    Participant
    Veteran

    This is the same version (rewritten)of Phoentzs  [ T4 -Multi -SP500 -M5-V3] , with Roberto’trailing. The performance up to 200k is slighthly better, up to 100k is better (see image).

    //TS MULTI SP500 v4 - CFD 1 euro - Spread 0.6
    defparam CUMULATEORDERS = false
    positionSize = 5
    //---------------------------------------------------------------------------------------
    timeFrame(15 minute, updateOnClose)   //15 minutes
    avgWeekly = average[480,0](close)     //weekTrend Daily
    c1L  = close > avgWeekly
    c1S = close < avgWeekly
    
    avg1 = average[15,0](close)
    avg2 = average[55,0](close)
    avg3 = average[14,1](close)
    avg4 = average[20,1](close)
    c2L  = avg1 > avg2                      //trend
    c2S = avg3 < avg4
    
    avg5 = average[5,0](close)
    avg6 = average[15,0](close)
    c3L  = avg5 crosses over avg6          //trigger
    c3S = avg5 crosses under avg6
    //---------------------------------------------------------------------------------------
    timeFrame(default)                       //5 minutes = DEFAULT
    cLong   =  c1L and c2L and c3L
    cShort  =  c1S and c2S and c3S
    cLongExit = c1S
    cShortExit = c1L
    //--------------------------------------------------------------------------------------
    ONCE buyTime   = 110000
    ONCE sellTime  = 213000
    ONCE buyTimeShort  = 150000
    ONCE sellTimeShort = 213000
    //--------------------------------------------------------------------------------------
    if time >= buyTime and time <= sellTime then                         //LONG
    if cLong then
    buy positionSize contract at market
    endif
    endif
    if longOnMarket and cLongExit then
    sell at market
    endif
    //----------------------------
    if time >= buyTimeShort and time <= sellTimeShort then                //SHORT
    if cShort then
    sellshort positionSize contract at market
    endif
    endif
    if shortOnMarket and cShortExit then
    exitShort at market
    endif
    //----------------------------------------------------------------------------------------
    if longOnMarket then                    //SL & TP
    set stop %loss 1.7
    elsif shortOnMarket then
    set stop %loss 0.5
    endif
    if longOnMarket then
    set target %profit 1
    elsif shortOnMarket then
    set target %profit 1
    endif
    //------------------------------------------------------------------------------------
    if time = 223000 then                   //time Exit
    //sell at market
    exitshort at market
    endif
    if time = 225500 and dayofweek=5 then
    sell at market
    exitshort at market
    endif
    //--------------------------------------------------------------------------------------------
    DirectionSwitch = (LongOnMarket AND ShortOnMarket[1]) OR (LongOnMarket[1] AND ShortOnMarket)                 //TrP
    IF Not OnMarket OR DirectionSwitch THEN
    TrailStart    = 40        // Start trailing profits
    PointToKeep   = 0.2      // 20% Profit percentage to keep when setting BreakEven
    StepSize      = 5        // Point to increase Percentage
    PerCentInc    = 0.2      // 20% PerCent increment after each StepSize Chunk
    RoundTO       = -0.6        //-0.5  rounds always to Lower integer, 0 defaults PRT behaviour
    PriceDistance = 6* pipsize  //minimun distance from current price
    maxProfitL            = 0
    maxProfitS            = 0
    ProfitPerCent = PointToKeep //reset to desired default value
    SellPriceX    = 0
    SellPrice     = 0
    ExitPriceX    = 9999999
    ExitPrice     = 9999999
    ELSE
    IF PositionPrice <> PositionPrice[1] AND (ExitPrice + SellPrice) <> 9999999 THEN     //go on only if Trailing Stop had already started trailing
    IF LongOnMarket THEN
    newSlL         = PositionPrice + ((close - PositionPrice) * ProfitPerCent)      //calculate new SL
    SellPriceX = max(max(SellPriceX,SellPrice),newSlL)
    SellPrice  = max(max(SellPriceX,SellPrice),PositionPrice + (maxProfitL * pipsize)) //set exit price to whatever grants greater profits, comopared to the previous one
    ELSIF ShortOnMarket THEN
    newSlS         = PositionPrice - ((PositionPrice - close) * ProfitPerCent)
    ExitPriceX = min(min(ExitPriceX,ExitPrice),newSlS)
    ExitPrice  = min(min(ExitPriceX,ExitPrice),PositionPrice - (maxProfitS * pipsize))
    ENDIF
    ENDIF
    ENDIF
    //---------------------------------------------------------------------------------------------------------------------------------------------------
    IF LongOnMarket AND close > (PositionPrice + (maxProfitL * pipsize)) THEN                              //LONG positions
    // compute the value of the Percentage of profits, if any, to lock in for LONG trades
    profitL = (close - PositionPrice) / pipsize                                      //convert price to pips
    IF profitL >= TrailStart THEN                                                   // go ahead only if N+ pips
    Diff1         = abs(TrailStart - profitL)                                    //difference from current profit and TrailStart
    Chunks1       = max(0,round((Diff1 / StepSize) + RoundTO))                   //number of STEPSIZE chunks
    ProfitPerCent = PointToKeep + (PointToKeep * (Chunks1 * PerCentInc))         //compute new size of ProfitPerCent
    ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent))                //make sure ProfitPerCent doess not exceed 100%
    maxProfitL = max(profitL * ProfitPerCent, maxProfitL)
    ENDIF
    ELSIF ShortOnMarket AND close < (PositionPrice - (maxProfitS * pipsize)) THEN                             //SHORT positions
    profitS = (PositionPrice - close) / pipsize
    IF profitS >= TrailStart THEN
    Diff2         = abs(TrailStart - profitS)
    Chunks2       = max(0,round((Diff2 / StepSize) + RoundTO))
    ProfitPerCent = PointToKeep + (PointToKeep * (Chunks2 * PerCentInc))
    ProfitPerCent = max(ProfitPerCent[1],min(100,ProfitPerCent))
    maxProfitS = max(profitS * ProfitPerCent, maxProfitL)
    ENDIF
    ENDIF
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    IF maxProfitL THEN                                                          //LONG positions  -  Place pending STOP order when maxProftiL > 0   (LONG positions)
    SellPrice = max(SellPrice,PositionPrice + (maxProfitL * pipsize))                  //convert pips to price
    IF abs(close - SellPrice) > PriceDistance THEN
    IF close >= SellPrice THEN
    SELL AT SellPrice STOP
    ELSE
    SELL AT SellPrice LIMIT
    ENDIF
    ELSE
    SELL AT Market
    ENDIF
    ENDIF
    IF maxProfitS THEN
    ExitPrice = min(ExitPrice,PositionPrice - (maxProfitS * pipsize))        //SHORT positions
    IF abs(close - ExitPrice) > PriceDistance THEN
    IF close <= ExitPrice THEN
    EXITSHORT AT ExitPrice STOP
    ELSE
    EXITSHORT AT ExitPrice LIMIT
    ENDIF
    ELSE
    EXITSHORT AT Market
    ENDIF
    ENDIF
    //------------------------------------------------------------------------------------------------------------------------
    
    
    
    
    
    
    
    Purasangre and thanked this post
    SP500.jpg SP500.jpg
    #190798 quote
    phoentzs
    Participant
    Master

    Thank you Mauro, did you really just take another trailing stop? Didn’t think it would make such a big difference.

Viewing 15 posts - 31 through 45 (of 96 total)
  • You must be logged in to reply to this topic.

Simple Moving Average Crossover Strategy


ProOrder: Automated Strategies & Backtesting

New Reply
Summary

This topic contains 95 replies,
has 12 voices, and was last updated by CRISRJ
3 years, 1 month ago.

Topic Details
Forum: ProOrder: Automated Strategies & Backtesting
Language: English
Started: 01/26/2022
Status: Active
Attachments: 39 files
Logo Logo
Loading...