Calculating Diagonal Trend Lines Using Fractals and Trigonometry
Forums › ProRealTime English forum › ProOrder support › Calculating Diagonal Trend Lines Using Fractals and Trigonometry
- This topic has 28 replies, 1 voice, and was last updated 3 years ago by eckaw.
-
-
10/25/2017 at 7:31 AM #5043410/30/2017 at 3:26 PM #50934
I tried at that moment but I did not manage to obtain something satisfactory in the time that I had been imparted to this task … Too many good topics and good ideas to explore and only so little time 😐
1 user thanked author for this post.
10/30/2017 at 10:57 PM #5098701/12/2018 at 4:25 PM #59212@Nicolas, I would like us to revisit this strategy. I have noticed that it has performed well since I posted my last version on 11 September, adding 33 new trades with a win rate of 63.64% and a Gain/Loss Ratio of 2.71 and a Gain to Drawdown ratio of 3.39.
I still need some help graphing the trend lines.
01/12/2018 at 4:39 PM #5921801/13/2018 at 1:52 PM #59349Hi Nicolas
Okay so here is the part of the code that calculates the trend.
The first point of the trend line is obviously the last swing high/low (FractalH or FractalL) and the bar position being FractalP
The second point would be the last high/low that results in the MaxAngle to be greater than the last value it held.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071//Calculate Fractal (Swing Point)once FracH = 0 //initialize fractal countonce FracL = 0 //initialize fractal countFor i = 0 to 4 DoIf high[2] > high[i] Then //look for high fractal with 2 lower highs on either sideFracH = FracH + 1EndIfIf low[2] < low[i] Then //look for low fractal with 2 higher lows on either sideFracL = FracL + 1EndIfNextIf FracH = 4 Then //High Fractal IdentifiedIf Bear = 0 and Bull = 0 ThenBear = 1 //Initialize first trend directionEndIfFractalH = high[2] //High Fractal Price LevelFractalP = barindex - 2 //High Fractal Bar PositionEndIfIf FracL = 4 Then //Low Fractal IdentifiedIf Bear = 0 and Bull = 0 ThenBull = 1 //Initialize first trend directionEndIfFractalL = low[2] //Low Fractal Price LevelFractalP = barindex - 2 //Low Fractal Bar PositionEndIfFracH = 0 //reset fractal countFracL = 0 //reset fractal count//Calculate trendline using widest angle from extreme of last fractal to curent extreme (Trigonometry Function)If Bear = 1 Then //Down trendHeight = FractalH - high //Calcululate height between high fractal and high of current barHeightB = FractalH - close //Calcululate height between high fractal and close of current bar (used to determine trend violation)ElsIf Bull = 1 Then //Up trendHeight = Low - FractalL //Calcululate height between low fractal and low of current barHeightB = close - FractalL //Calcululate height between high fractal and close of current bar (used to determine trend violation)EndIfIf barindex - 2 = FractalP Then //Initialize angle using high of last bar of fractal setMaxAngle = Tan(2/Height) //Initial value of the angle between the fractal and the last highEndIfonce Trendbreak = 0If barindex - 2 > FractalP Then //If current bar greater than end of fractal set:If Bear = 1 Then //For Down TrendIf (Tan((barindex-FractalP)/Height) > MaxAngle) and (((close < open) or (close < close[1]))) ThenMaxAngle = Tan((barindex-FractalP)/Height) //calculate new max trend if down trend rules are validTrendbreak = 0 //No Trend Violation PresentEndIfIf Trendbreak = 0 and (Tan((barindex-FractalP)/HeightB) > MaxAngle) and close > open ThenTrendBreak = 1 //Trend violation potentially present, wait for confirmation on close of next barElsIf Trendbreak = 1 and (Tan(((barindex-1)-FractalP)/HeightB) > MaxAngle) and close > close[1] ThenTrendbreak = 2 //Trend violation confirmed, there was a close outside the trend line (close angle > trend)EndIfElsIf Bull = 1 Then //For Up TrendIf (Tan((barindex-FractalP)/Height) > MaxAngle) and (((close > open) or (close > close[1]))) ThenMaxAngle = Tan((barindex-FractalP)/Height) //calculate new max trend if up trend rules are validTrendbreak = 0 //No Trend Violation PresentEndIfIf Trendbreak = 0 and (Tan((barindex-FractalP)/HeightB) > MaxAngle) and close < open ThenTrendBreak = 1 //Trend violation potentially present, wait for confirmation on close of next barElsIf Trendbreak = 1 and (Tan(((barindex-1)-FractalP)/HeightB) > MaxAngle) and close < close[1] ThenTrendbreak = 2 //Trend violation confirmed, there was a close outside the trend line (close angle < trend)EndIfEndIfEndIf1 user thanked author for this post.
01/13/2018 at 3:14 PM #59358Something like this? (made only the support lines)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879defparam calculateonlastbars=1000//Calculate Fractal (Swing Point)once FracH = 0 //initialize fractal countonce FracL = 0 //initialize fractal countFor i = 0 to 4 DoIf high[2] > high[i] Then //look for high fractal with 2 lower highs on either sideFracH = FracH + 1EndIfIf low[2] < low[i] Then //look for low fractal with 2 higher lows on either sideFracL = FracL + 1EndIfNextIf FracH = 4 Then //High Fractal IdentifiedIf Bear = 0 and Bull = 0 ThenBear = 1 //Initialize first trend directionEndIfFractalH = high[2] //High Fractal Price LevelFractalP = barindex - 2 //High Fractal Bar PositionEndIfIf FracL = 4 Then //Low Fractal IdentifiedIf Bear = 0 and Bull = 0 ThenBull = 1 //Initialize first trend directionEndIfFractalL = low[2] //Low Fractal Price LevelFractalP = barindex - 2 //Low Fractal Bar PositionEndIfFracH = 0 //reset fractal countFracL = 0 //reset fractal count//Calculate trendline using widest angle from extreme of last fractal to curent extreme (Trigonometry Function)If Bear = 1 Then //Down trendHeight = FractalH - high //Calcululate height between high fractal and high of current barHeightB = FractalH - close //Calcululate height between high fractal and close of current bar (used to determine trend violation)ElsIf Bull = 1 Then //Up trendHeight = Low - FractalL //Calcululate height between low fractal and low of current barHeightB = close - FractalL //Calcululate height between high fractal and close of current bar (used to determine trend violation)EndIfIf barindex - 2 = FractalP Then //Initialize angle using high of last bar of fractal setMaxAngle = Tan(2/Height) //Initial value of the angle between the fractal and the last highEndIfonce Trendbreak = 0If barindex - 2 > FractalP Then //If current bar greater than end of fractal set:If Bear = 1 Then //For Down TrendIf (Tan((barindex-FractalP)/Height) > MaxAngle) and (((close < open) or (close < close[1]))) ThenMaxAngle = Tan((barindex-FractalP)/Height) //calculate new max trend if down trend rules are validTrendbreak = 0 //No Trend Violation PresentEndIfIf Trendbreak = 0 and (Tan((barindex-FractalP)/HeightB) > MaxAngle) and close > open ThenTrendBreak = 1 //Trend violation potentially present, wait for confirmation on close of next barElsIf Trendbreak = 1 and (Tan(((barindex-1)-FractalP)/HeightB) > MaxAngle) and close > close[1] ThenTrendbreak = 2 //Trend violation confirmed, there was a close outside the trend line (close angle > trend)EndIfElsIf Bull = 1 Then //For Up TrendIf (Tan((barindex-FractalP)/Height) > MaxAngle) and (((close > open) or (close > close[1]))) ThenMaxAngle = Tan((barindex-FractalP)/Height) //calculate new max trend if up trend rules are validTrendbreak = 0 //No Trend Violation PresentEndIfIf Trendbreak = 0 and (Tan((barindex-FractalP)/HeightB) > MaxAngle) and close < open ThenTrendBreak = 1 //Trend violation potentially present, wait for confirmation on close of next barElsIf Trendbreak = 1 and (Tan(((barindex-1)-FractalP)/HeightB) > MaxAngle) and close < close[1] ThenTrendbreak = 2 //Trend violation confirmed, there was a close outside the trend line (close angle < trend)EndIfEndIfEndIfif bull and maxangle>maxangle[1] thendrawsegment(barindex,low,fractalP,fractalL) coloured(200,0,0)endifreturn //fractalH,fractalL, MaxAngleIf “MaxAngle” is superior to the last one and it’s a bull trend, draw a new segment (not a complete line to have a clear chart).
01/13/2018 at 6:29 PM #59372Dear Juan,
will you please post your latest version. This is very interesting. I noticed the part of the code that you have reposted is slightly different form the one posted last year. I know slight difference in a code could be the difference between losing and winning!
Many thanks.
01/15/2018 at 4:53 PM #59568@Nicolas, thank you for the indicator.
It is difficult to say whether or not it looks correct as I can imagine there to be many new lines being drawn constantly.
However the rules is basically as follows:
Once a swing high/low is identified with 2 lower highs/higher lows on either side;
- Draw an initial line from the high/low of the swing point to the high/low of the 2nd shoulder which should technically be the lowest/highest of the 2 shoulders. This gives the initial value for MaxAngle.
- Now after every new bar the angle between the high/low of the swing point and the latest high/low will be calculated and compared to the current value being held by MaxAngle. If the new angle is greater it means a high/low outside the diagonal line is present. To determine whether this constitutes a break, we recalculate the angle using the close. If the close also falls outside the trend line a potential break is present and we will wait for the next candle stick to confirm. If the close does not fall outside the trend line, then the trend remains intact and the high/low will be used to update the new MaxAngle value.
- If a new swing high/low is present, this will be used as the new point from which the trend line is calculated.
1 user thanked author for this post.
01/15/2018 at 5:00 PM #5957001/16/2018 at 10:15 PM #59683Juan, you can use the line equation. like this:
If the line equation is y=mx+b and the coordinates of a point is (x0,y0) then compare y0 and mxo+b, for example if y0>mxo+b then the point is above the line, etc.
x0 is bar index and y0 is price.
in case needed, equation of a line passing two points
y − y1 = m(x − x1)
m= y2-y1/x2-x1 y is price,m is bar index
thus forget the angle business all together
01/18/2018 at 9:56 AM #59778I ran this puppy on USDJPY and were quite surprised by the results (see attached), especially considering that I used the EURUSD during optimization and testing:
@Golha Here is the latest version of the code:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278//Stategy: Trend Breakout//Author: Juan Jacobs (Jd3gjacobs@gmail.com)//Market: Neutral//Timezone: UTC +2//Timeframe: 1Hr but not 'completely' timeframe dependantDefparam cumulateorders = FalseIf hour < 3 or hour >= 20 then //market hours EURUSD: 8-23 USDJPY: 3-20 AUDUSD: 5-20possize = 0If longonmarket Thensell at marketElsIf shortonmarket Thenexitshort at marketEndIfBear = 0Bull = 0Trendbreak = 0Elsepossize = 1 //position contract sizeEndIf// Heuristics Algorithm Startonce OPT = 1If OPT < 2 and onmarket thenOPT = 0ElsIf countofposition = 0 ThenOPT = 1EndIFIf OPT = 0 Thenoptimize = optimize + 1OPT = 2EndIf//////////////////////////////////////////GRAPH periods AS "Periods"once periods = 2.5Increment = 0.05MaxIncrement = 6Reps = 6 //Number of trades to use for analysisonce PIncPos = 1 //Positive Increment Positiononce NIncPos = 1 //Neative Increment Positiononce Optimize = 0 ////Initialize Heuristicks Engine Counter (Must be Incremented at Position Start or Exit)once Mode = 1 //Switches between negative and positive incrementsonce WinCountB = 0 //Initialize Best Win Countonce StratAvgB = 0 //Initialize Best Avg Strategy ProfitIf Optimize = Reps ThenWinCountA = 0 //Initialize current Win CountStratAvgA = 0 //Initialize current Avg Strategy ProfitFor i = 1 to Reps DoIf positionperf(i) > 0 ThenWinCountA = WinCountA + 1 //Increment Current WinCountEndIfStratAvgA = StratAvgA + positionperf(i)NextStratAvgA = StratAvgA/Reps //Calculate Current Avg Strategy ProfitIf StratAvgA >= StratAvgB ThenStratAvgB = StratAvgA //Update Best Strategy ProfitBestA = PeriodsEndIfIf WinCountA >= WinCountB ThenWinCountB = WinCountA //Update Best Win CountBestB = PeriodsEndIfIf WinCountA > WinCountB and StratAvgA > StratAvgB ThenMode = 0ElsIf WinCountA < WinCountB and StratAvgA < StratAvgB and Mode = 1 ThenPeriods = Periods - (Increment*NIncPos)NIncPos = NIncPos + 1Mode = 2ElsIf WinCountA >= WinCountB or StratAvgA >= StratAvgB and Mode = 1 ThenPeriods = Periods + (Increment*PIncPos)PIncPos = PIncPos + 1Mode = 1ElsIf WinCountA < WinCountB and StratAvgA < StratAvgB and Mode = 2 ThenPeriods = Periods + (Increment*PIncPos)PIncPos = PIncPos + 1Mode = 1ElsIf WinCountA > WinCountB or StratAvgA > StratAvgB and Mode = 2 ThenPeriods = Periods - (Increment*NIncPos)NIncPos = NIncPos + 1Mode = 2EndIfIf NIncPos > MaxIncrement or PIncPos > MaxIncrement ThenIf BestA = BestB ThenPeriods = BestAElsePeriods = (BestA+BestB)/2EndIfNIncPos = 1PIncPos = 1EndIFOptimize = 0EndIf// Heuristics Algorithm EndIf Trendbreak = 0 Then //No potential trendbreaks have been identified//Calculate FractalFracH = 0 //initialize fractal countFracL = 0 //initialize fractal countFor i = 0 to 4 DoIf high[2] > high[i] Then //look for high fractal with 2 lower highs on either sideFracH = FracH + 1EndIfIf low[2] < low[i] Then //look for low fractal with 2 higher lows on either sideFracL = FracL + 1EndIfNextIf FracH = 4 Then //High Fractal IdentifiedIf Bear = 0 and Bull = 0 ThenBear = 1 //Initialize first trend directionEndIfFractalH = high[2] //High Fractal Price LevelLFractalH = low[2] //Low of High FractalIf Bear = 1 ThenFractalP = barindex - 2 //High Fractal Bar PositionEndIfElsIf FracL = 4 Then //Low Fractal IdentifiedIf Bear = 0 and Bull = 0 ThenBull = 1 //Initialize first trend directionEndIfFractalL = low[2] //Low Fractal Price LevelHFractalL = high[2] //High of Low FractalIf Bull = 1 ThenFractalP = barindex - 2 //Low Fractal Bar PositionEndIfEndIf//Calculate trendline using widest angle from extreme of last fractal to curent extreme (Trigonometry Function)If barindex = FractalP + 2 Then //Initialize angle using greatest candle after fractal candleIf Bear = 1 ThenMaxAngleA = Tan(1/(FractalH - high[0])) //Initial value of the angle between the fractal and the 1st high after fractal highMaxAngleB = Tan(1/(FractalH - high[1])) //Initial value of the angle between the fractal and the 2nd high after fractal highMaxAngle = MAX(MaxAngleA,MaxAngleB)ElsIf Bull = 1 ThenMaxAngleA = Tan(1/(low[0]-FractalL)) //Initial value of the angle between the fractal and the 1st low after fractal lowMaxAngleB = Tan(1/(low[1]-FractalL)) //Initial value of the angle between the fractal and the 2nd low after fractal lowMaxAngle = MAX(MaxAngleA,MaxAngleB)EndIfEndIfEndIfIf Bear = 1 Then //Down trendHeight = abs(FractalH - high) //Calcululate height between high fractal and high of current barHeightB = abs(FractalH - close) //Calcululate height between high fractal and close of current bar (used to determine trend violation)HeightC = abs(FractalH - close[1]) //Calcululate height between high fractal and close of current bar (used to determine trend violation)ElsIf Bull = 1 Then //Up trendHeight = abs(Low - FractalL) //Calcululate height between low fractal and low of current barHeightB = abs(close - FractalL) //Calcululate height between high fractal and close of current bar (used to determine trend violation)HeightC = abs(close[1] - FractalL) //Calcululate height between high fractal and close of current bar (used to determine trend violation)EndIfIf barindex > FractalP + 2 Then //If current bar greater than end of fractal set:If Bear = 1 Then //For Down TrendIf Trendbreak = 1 and close >= close[1] ThenTrendbreak = 2 //Trend violation confirmed, there was a close outside the trend line (close angle > trend)BreakoutP = Barindex //Breakout positionOrderLevel = LFractalH + (AverageTrueRange[22](close)*periods) //Enter into long position at specified price levelPreviousLow = FractalL //Lowest[15](low)//Level to re-initate preious trendElsIf Trendbreak = 1 and Tan((barindex-FractalP)/HeightC) > TAngle ThenMaxAngle = TAngle //New max trend as trend break was invalidatedTrendbreak = 0EndIfIf Trendbreak = 0 and (Tan((barindex-FractalP)/Height) < MaxAngle) and (Tan((barindex-FractalP)/HeightB) > MaxAngle) ThenMaxAngle = Tan((barindex-FractalP)/Height) //calculate new max trend if down trend rules are validElsIf Trendbreak = 0 and (Tan((barindex-FractalP)/Height) < MaxAngle) and (Tan((barindex-FractalP)/HeightB) < MaxAngle) ThenTrendBreak = 1 //Trend violation potentially present, wait for confirmation on close of next barTAngle = Tan((barindex-FractalP)/Height) //Save temporary angle to use if trend violation invalidatedEndIFElsIf Bull = 1 Then //For Up TrendIf Trendbreak = 1 and close <= close[1] ThenTrendbreak = 2 //Trend violation confirmed, there was a close outside the trend line (close angle < trend)BreakoutP = Barindex //Breakout positionOrderLevel = HFractalL - (AverageTrueRange[22](close)*periods) //Enter into short position at specified price levelPreviousHigh = FractalH // Highest[15](high) //Level to re-initiate previous trendElsIf Trendbreak = 1 and Tan((barindex-FractalP)/HeightC) > TAngle ThenMaxAngle = TAngle //New max trend as trend break was invalidatedTrendbreak = 0EndIfIf Trendbreak = 0 and (Tan((barindex-FractalP)/Height) < MaxAngle) and (Tan((barindex-FractalP)/HeightB) > MaxAngle) ThenMaxAngle = Tan((barindex-FractalP)/Height) //calculate new max trend if up trend rules are validElsIf Trendbreak = 0 and (Tan((barindex-FractalP)/Height) < MaxAngle) and (Tan((barindex-FractalP)/HeightB) < MaxAngle) ThenTrendBreak = 1 //Trend violation potentially present, wait for confirmation on close of next barTAngle = Tan((barindex-FractalP)/Height) //Save temporary angle to use if trend violation invalidatedEndIfEndIfEndIfIf Trendbreak = 2 Then //Trend violation is confirmed:If Bear = 1 and close > PreviousLow ThenBuy possize contract at OrderLevel stopElsIf Bull = 1 and close < PreviousHigh ThenSellshort possize contract at OrderLevel stopEndIfIf barindex >= BreakoutP ThenIf Bear = 1 and longonmarket Then //If position is opened counter last trend, reset variables and initialize new trendTrendbreak = 0Bear = 0Bull = 1ElsIf Bear = 1 and close < PreviousLow Then //New trend invalidated and previous trend resumedTrendbreak = 0ElsIf Bull = 1 and shortonmarket Then //If position is opened counter last trend, reset variables and initialize new trendTrendbreak = 0Bear = 1Bull = 0ElsIf Bull = 1 and close > PreviousHigh Then //New trend invalidated and previous trend resumedTrendbreak = 0EndIfEndIfEndIf//Trade Management (Note that Trend Direction need to be reset with exits's)Deviations = 1.618period = 42PRICE = LOG(customclose)alpha = 2/(PERIOD+1)if barindex < PERIOD thenEWMA = AVERAGE[3](PRICE)elseEWMA = alpha * PRICE + (1-alpha)*EWMAendiferror = PRICE - EWMAdev = SQUARE(error)if barindex < PERIODS+1 thenvar = develsevar = alpha * dev + (1-alpha) * varendifESD = SQRT(var)BollU = EXP(EWMA + (DEVIATIONS*ESD))BollL = EXP(EWMA - (DEVIATIONS*ESD))RS2 = ROUND(RSI[2](close))PSH = Highest[100](high)[1]PSL = Lowest[100](low)[1]If longonmarket and ((close[1] > BollU and close < BollU) or (high[1] > BollU and high < BollU) or (close > PSH or close < PSL)) ThenLE = 1ElsIf shortonmarket and ((close[1] < BollL and close > BollL) or (low[1] < BollL and low > BollL) or (close < PSL or close > PSH)) ThenSE = 1EndIfIf longonmarket and LE = 1 and RS2 >= 85 and close < BollU ThenSell at marketBear = 0Bull = 0ElsIf shortonmarket and SE = 1 and RS2 <= 15 and close > BollL ThenExitshort at marketBear = 0Bull = 0EndIf03/07/2021 at 8:18 PM #163381@JuanJ I find this strategy really interesting! However, I am struggling to make Money Management work with this. None of the MM code I can find here seems to work. I have made sure to change positionsize to possize but it still doesn’t work, there seem to be something in your code that overrides it but I cannot figure out what. Any help would be massively appreciated.
03/07/2021 at 8:19 PM #163382 -
AuthorPosts
Find exclusive trading pro-tools on