# Trend Line Plots



## GreatPig (20 July 2005)

Just been playing around with this in AmiBroker and thought others might be interested in it. Was hoping to use it for some backtesting ideas, but it's far too slow as it. Would need to be rewritten into a plug-in DLL.

I realise AmiBroker has built-in functions similar to some of the ones I've written here myself, but like I say, I've just been experimenting.

I've attached the AFL as a file rather than list it all in a message. Just rename the .TXT extension to .AFL or copy and paste into a new indicator. A couple of plot results also attached to show what it looks like.

Cheers,
GP


----------



## wayneL (20 July 2005)

&^%$ing good effort GP.

An extraordinarily difficult thing to program and you've done it rather well.

Cheers


----------



## GreatPig (20 July 2005)

Thanks, Wayne.



			
				wayneL said:
			
		

> An extraordinarily difficult thing to program



Just as well you didn't tell me that before I started 

Cheers,
GP


----------



## tech/a (21 July 2005)

*Now that IS sensational!!*

Now how can I get that into Metastock??

I'll have a go at coding it for M/S---might even pass it on the Roy Larson who is the best Ive seen in M/S.

Tremendous effort---thats saleable GP--you know that?


----------



## kaveman (21 July 2005)

GP, that is a great job. congratulations


----------



## GreatPig (21 July 2005)

Thanks guys.

Sorry Tech, don't know anything about programming Metastock.

As for difficulty, well I'm a professional programmer and have been programming embedded real-time systems for about 25 years. While by no means trivial, I thought this was relatively easy compared to some of the things I've had to do 

My original aim was to get something I could use in backtests to look for trend line breaks. As is this is way too slow, as it would need to recalculate the most recent trend line for every day of the price array. Then I'd have to figure out how to stop the most recent prices during a new rise being included in the trend line calculation, thus making the trend line always sit on top of the rising prices.

Anyway, I'll probably keep plugging away at it as I have time.

Hope you find it useful.

Cheers,
GP


----------



## mit (21 July 2005)

Good work. Pity it takes a while to calculate as it would be good to do an animation of it over a period of time. If it doesn't have the same problems that the zigzag indicator has you would really be onto something. 

MIT


----------



## GreatPig (21 July 2005)

mit said:
			
		

> If it doesn't have the same problems that the zigzag indicator has



What problems are they?

Cheers,
GP


----------



## kaveman (21 July 2005)

I think mit is referring to that zigzag must change by a certain price percent before a turning point can be defined.

mit, I think this lie all other trend indications, or most indicators that is, the price alsoi has to move in opposite direction, or at least a certain distance in a direction before the trend line can be determined.
the opening statement mentions this in GP's afl



> The turning points for the trend lines are determined by the "change" parameter, which is the percentage move in the opposite direction behind a low or high to trigger a direction change.





This is just normal as you can never define something until it has appeared.


----------



## kaveman (22 July 2005)

GP, one way that might work to reduce the plotting time would be to reduce the number of lines calculated to either around the selected bar, or to the bars that are currently on the screen.


----------



## GreatPig (22 July 2005)

Kaveman,

Yeah, plotting just one line would be quicker. I initially started plotting just the most recent line. To be useful as a visual tool, that may be all that's necessary - just doesn't look as impressive . To do that, it's just a matter of altering the main routine to only do the first plot, not loop backwards through the stock.

Doing only the bars on the screen is a little trickier. I'm not sure how you can find out in code what bars are currently visible. I know how to get the start and end bars when a region is selected, but is there a function to find out what bars are currently displayed?

And for a selected bar, plotting backwards to the previous high or low would be easy, but I'd have to change things a bit to be able to move forward to the next one to do a full trend line. Although it may also be useful to only plot from the selected point back to the previous high or low, so that you can see what a trend line would look like only up to the selected point. That may also fit in better with a back tester.

And I guess being able to plot a line (or lines) within a selected region could also be useful.

Some good ideas to think about, thanks.

Cheers,
GP


----------



## kaveman (22 July 2005)

status("barvisible") produces 0 or 1 depending if you can see the bar or not
this should be enough tog et started on that

CanSeeBar = status("b+arvisible");
FirstBar = valuewhen(CanSeeBar and ref(CanSeeBar,-1)==0, barindex() );
LastBar = valuewhen( CanSeeBar and ref(CanSeeBar,1)==0, barindex() );

if using this inside code then need to make sure that barcount-1 is used for the last chart bar as you can have the vacant bars extend to the right beyond the price data bars, eg

UseLastbar = min( LastBar, Barcount-1);


----------



## GreatPig (22 July 2005)

Kaveman,

Thanks for that. I'll play around with it some more.

Cheers,
GP


----------



## GreatPig (25 July 2005)

I've spent a bit more time on this and moved the line fitting code into a plug-in DLL, where obviously it runs a lot faster. For display and exploration purposes, it's now fast enough. Still pretty slow for backtesting, but at least usable where the fully-AFL version wasn't.

I would like to upload this latest version here. However, the plug-in kit has a comment in it that resulting software is only licenced for "personal, non-commercial use". I don't think non-commercial is a problem, as I'm not selling it, but does "personal use" effectively prevent me from uploading the plug-in here (just the DLL, not the source code)?

Have other plug-ins been uploaded to Yahoo, etc, and if so, have they needed permission from AmiBroker to do that?

Cheers,
GP


----------



## kaveman (25 July 2005)

Before you place a plugin to AB yahoo or AB website you ahve to submit to TJ. It must ensure that there is no conflict between your variable names and those built-in to AB or into other 3rd party plugins that are laready used.
Basically any variable called up in AFL must be unique to your plugin. 
Normally this is done by always having your initials as the first 2 letters of the variable/function name.

eg anything I would write into plugin and called upa s function in AFL would have gk in front, eg gkDate()

cannot recall where the info for that came from, just something in the dim memory cells of past discussions.


----------



## GreatPig (25 July 2005)

Kaveman,

Thanks for that.

There's only one function in the DLL and it does start with my initials (GP that is), but I also have a few global variables that are shared which currently don't. I might rename them first and then take a look on the AB Website.

Cheers,
GP


----------



## Victor H (25 July 2005)

I'm impressed with the coding for these trendlines.  If I may suggest 2 things which might make life a little easier for others.  Both are under "Main Procedure" in the Code.

#1.   The following code adjustment will automatically adjust the "tchg" to each individual stock - instead of a user defined input.

Replace "tchg = ................."        with 

mp =(H+L)/2;
r0 = IIf(mp>=Ref(mp,-1),ATR(1),0);
r1 = log(IIf(r0>0,ATR(1),mp)/mp);
r2 = Cum(r1)/Max(1,Cum(IIf(r0>0,1,0)));
tchg = LastValue(100*exp(LastValue(r2)));

#2.   Also, I find the trendlines easier on the eye if coded with Highs & Lows: 

Bottom = Low;
Top = High;

Regards Victor.


----------



## GreatPig (25 July 2005)

Thanks Victor.



			
				Victor H said:
			
		

> mp =(H+L)/2;
> r0 = IIf(mp>=Ref(mp,-1),ATR(1),0);
> r1 = log(IIf(r0>0,ATR(1),mp)/mp);
> r2 = Cum(r1)/Max(1,Cum(IIf(r0>0,1,0)));
> tchg = LastValue(100*exp(LastValue(r2)));



I'll take a look through that when I get a chance and try and see what it's doing 



> #2.   Also, I find the trendlines easier on the eye if coded with Highs & Lows:



I think that's a matter of taste. With my manual trend line placement, I sometimes use highs and lows and sometimes opens and closes, depending on what seems best for the particular stock in that region. As you noted though, it's easily changed.

Cheers,
GP


----------



## Victor H (26 July 2005)

HI GP,

I have worked mostly with Metastock and now I am slowly getting the hang of AB code.  Forget my previous post as this is probably simpler.
It calculates the "average" ATR(1) [based on a Log-Normal Distribution] as a percentage of the Median Price.  A turning point usually occurs when this %value is exceeded.

mp =(H+L)/2;
r1 = log(IIf(ATR(1)>0,ATR(1),mp)/mp);
r2 = Cum(r1)/Max(1,Cum(ATR(1)>0));
tchg = LastValue(100*exp(LastValue(r2)));  

Regards Victor.


----------



## GreatPig (26 July 2005)

kaveman said:
			
		

> Before you place a plugin to AB yahoo or AB website you ahve to submit to TJ



I sent him an email and he said I can distribute it provided it has installation and usage instructions (which I'm just finalising) and with the function and variable prefix I suggested to avoid conflicts.

So as soon as I get the documentation done up a bit, I'll upload the package (basically the DLL, AFL code for the indicator, exploration, and backtesting, and the instruction document).

Cheers,
GP


----------



## Milk Man (26 July 2005)

Much appreciated GP!


----------



## poormantrading (5 December 2005)

GP, if you modified this code to produce a ABC wave (or similar) as described in Nick Radge's recent book (thanks Nick an interesting book), without having to use a zizzag function it would make a useful tool for part of a system. Needing only 3 trend lines it might be a bit simpler. Although I'm not sure if you can use ABC wave as a stand alone function without needing to confirm the 5 part Elliot Wave, can it? anyone?

Apparently zizzag functions skew backtesting results, I don't fully understand why as I've tended to avoid them.


regards


----------



## GreatPig (5 December 2005)

Poormantrading,

I haven't read Nick's book yet, so I don't know about this ABC wave thing.

Apparently the zig-zag indicator can look into the future, which will affect backtesting. The way I've done the trend line calculation though doesn't involve any looking into the future (that I'm aware of), so it shouldn't do that.

However, backtesting with the trendline calculation is very slow, as it effectively has to calculate a new trendline for every day in the price array. This is because an existing trendline can change positions if a new low or high point occurs. In fact, a line can even disappear and the previous line become extended to the new point.

Cheers,
GP


----------



## kaveman (5 December 2005)

It can be done fairly efficiently so that it does not affect the processing time too much. It is a matter of calculating the lines at certain key points rather than for every point


----------



## poormantrading (5 December 2005)

Ok guys thanks for the replys.

The abc wave as I understand it basically a 3 point reversal patern, that can be represented by looking for the 2 most recent troughs & peaks. Ive attached a simple system that I think represents it or at least one form of it.

I think looking for key reversals or pivot points would do the same ... candlestick patterns perhaps.

Anyway the code also includes setting profit targets, stops etc to determine risk/reward & could form the basis of a system if anyone wants to play with it or comment on it.

At the moment it is best used as an exploration to find the most recent patterns.



Regards


----------



## tech/a (5 December 2005)

The problem with using Peak and Trough formula is that Zig Zag is used to define peak and trough.

The last leg of a peak or a trough are dynamic and cannot be seen as complete until the next trough or peak has been completed.

In realtime many peaks and troughs of today will not be tommorow.

In testing patterns can be confirmed complete due to hindsite.

Therefore false indications of a methods reliability will be formed when used.


----------



## kaveman (6 December 2005)

Tech all you have to do is have any signals given at or after the bar that creates the new peak or trough. That is what I do with system using this. It ensures validity, also shows how much error comes in if you use the actual turning points that you see in the history


----------



## tech/a (6 December 2005)

Kave 

2 days later the stock can move in the opposite direction to confirmation and the trough or peak then is no longer valid.

Anyway I'm not here to convince people of the dynamics of the last leg.
If your happy with how you use it then thats fine.


----------



## kaveman (6 December 2005)

Tech
Once the price has moved past the reversal value and defined a peak or trough that turning point is fixed. This is exactly the same principle that creates the P&F charts
somehow will se if I can post a chart
this is a zigzag with $1.00 reversal to define the turning points. The red star is located at the bar where the price crosses the reversal price. This then sets that turning point in stone, and only the next point is yet to be defined. Thus when backtesting you only need to define that any signal be after the create bar (star shown circled) and you will then be using the correct zig direction as if that bar was the end of the chart.


----------



## tech/a (6 December 2005)

Graham

This chart is still dynamic.
If price fell by another 50% from where it is today then the trough *now shown * would disappear!!!!!!!


----------



## kaveman (6 December 2005)

No way, you are so wrong. The turning points showing are fixed and will never move.
The star means that the last turning point has been determined because the price rose enough to pass above the reversal level. The only point that can now be determined is a new peak.
The last leg follows the price until a reversal level is reached, then that tp is fixed ad it waits for the next opposite tp be calculated.





Here is he last leg of the chart. Any movement down past a closing price of $23.05 will create a new peak at the circled bar. Any movement up will just take the last zig leg higher and if the price close higher than $24.05 will just move the goal posts for a new peak level reversal definition. eg price goes to $25.00 then the revcersal to creat a new peak is a fall after that to $24.00

The only item in a zigzag that is not set in stone is the last leg, and this is just waiting for the price to move enough to either create a new turning point, or to define a new goal post for the new turning point.


----------



## tech/a (6 December 2005)

Ah yes now I see where your coming from.

You are correct in that once the % change is in place then the peak or trough is set.

I apologise for falling fowl of not being thourough.
However most fall for the trick of setting the peak or trough before a % swing is achieved locking it in place.

Any move then would be that % lagging.
I've also had the feeling that at the time of an exploration for example the peak or trough shown is "true" at that time and as such will either prove to be true of be taken out.
Knowing this a stop can easily be set below or above the trough or peak and trade early.

Again my apologies .


----------



## GreatPig (6 December 2005)

kaveman said:
			
		

> Thus when backtesting you only need to define that any signal be after the create bar (star shown circled)



Do you mean the very next bar after the create bar? Otherwise, it seems to me that prices are always after a create bar, since until the next create bar, there's no change in line direction.

I do my trendlines a little different, in that I start at the last day and work backwards, using an MA to decide the direction of the most-recent line. Because of that, the most-recent line can suddenly change from up to down or vice-versa if the MA slope changes. This can actually cause the most recent line to disappear completely and the one that was before it to be extended up to the current day (see attached images - the first one takes the select line as being the last day).

Also, the slow part is not calculating the pivot points, but rather fitting the lines to the top and bottom edges of the prices.

Cheers,
GP


----------



## kaveman (6 December 2005)

For an example
You want an entry when the zig is rising and exit when it is falling.
When backtesting you make sure that only the real bars for each leg are used.
I will call the bars where the price crosses the reversal level CreatePeak and CreateTrough. The are definite bars as can be seen on my previous screen shots as the abrs with the stars.
So 
buy = CreateTrough;
Sell = CreatePeak;


If you have the trades requiring a rising or falling leg of the zigzag then you can use this in backtesting

ZigRise = barssince(createTrough) < barssince( createPeak );
ZigFall = barssince(createTrough) > barssince( createPeak );

buy = OtherBuyConditions and zigrise;
short = OtherShortconditions and zigfall;

This is the only way you can use the zigzag for backtesting and be certain you are not looking forward


----------



## GreatPig (6 December 2005)

kaveman said:
			
		

> If you have the trades requiring a rising or falling leg of the zigzag then you can use this in backtesting
> 
> ZigRise = barssince(createTrough) < barssince( createPeak );
> ...
> buy = OtherBuyConditions and zigrise;



The way I see it, this formula for ZigRise won't always give a point on a rising line. For example, on the day before the next createPeak day, ZigRise will still be true (since createPeak hasn't happened yet) but that bar will ultimately be on a falling line. In fact, for all bars between the actual peak and the createPeak bar, ZigRise will be true, as createTrough will still be the most recent bar of the two.

So with this formula, depending of course on what the OtherBuyConditions are, you could quite easily buy just after the actual peak at the start of the next down line. Perhaps if the OtherBuyConditions included buying on a new high for the preceding 'X' periods, or something like that.

Cheers,
GP


----------



## kaveman (7 December 2005)

You have to create a trough to get a rising leg


----------



## tarmie (18 September 2010)

HI GP:

the trendline code you created, changes signals and adjusts with time and candles as that is dependent on percent changes and peak/trough.....have your worked on something that minimizes this misleading and autoadjustments?....some signals vanishes over time; is there any way to scape that? 

Will be highly benefeited if you hint something....


thanks,

tarmi


----------



## tarmie (19 September 2010)

I have tried with every parameter and possible changes but still many close_above signals vanishes/adjusted over time....i have also tried the kaveman suggestions but still no luck..is it not possible in Amibroker? Is there any possiblity with tradestation or metastock?...pls someone suggest...


----------



## tech/a (20 September 2010)

Every time its mentioned I point out you CANT use ZIGZAG.
People keep telling me you can and Graham keeps popping up telling everyone you can.

BUT
Proof is in the in ability to plot what you want.
The last Peak or Trough will always be dynamic so your trend will alwys be a peak or trough behind and as such will alter from time to time.
Spend long enough stuffing around with it and you'll see exactly what I mean.

Ho hum.


----------



## tech/a (20 September 2010)

Try this for $99 solves all your problems plus much more.
I had the old version but dont have this one.
Worked great.


http://www.nebadawn.com/


----------



## Gringotts Bank (20 September 2010)

I think GP meant this code only as an 'eyeball' guide for the current trend.  It's pretty good for that purpose alone, keeping in mind that new data will move the last shown line.  Then again, new data will sometimes change your manually drawn trendlines, won't it?  

If Kaveman's caveats are applied, in order to make it valid for backtesting, (possible) it would lose a large chunk of its effectiveness.  So, it can't be used 'as is' for backtesting, but for discretionary traders, could be useful.


----------



## LimitBid100 (21 September 2010)

Have you done any backtesting of any trading strategies based on your trendlines?  If so, are the results any good?

Cheers,

LimitBid


----------



## tarmie (24 September 2010)

Hi tech/a:

Thanks for your suggestion, i understand that the formula is future looking and it may produce wrong signals in real trading...

But i was wondering if it was possible to avoid peak/trough/...zig zag and use something/ some way to avoid that auto adjustments....

Ramp seems good and they must be using some good logic...what could be something like that......


----------

