SwingHigh and SwingLow functions
Author: streak
Creation Date: 3/17/2012 11:40 PM
profile picture

streak

#1

Here's a couple of bool swing functions. Each outputs price & bar when true. The swings are true pending meeting the required number of leftside and rightside bars within 'x' number of recent bars. ie The number of bars each side can be set as-symmetric. True is not dependant on a 'percentage' or 'price value' threshold as per Peak.Series

Input Parameters :-

int bar - look farback bars from this bar to find 1st or 2nd or so on occur'ence of a swing
DataSeries ds -
int leftSide -
int rightSide -
int farback -
int occur -
out int swHighBar -
out double swHigh -
[[double equalHighLimit - option to set (I use 0.0001) a tolerance threshold for cases of equal highs [lows].
bool retLeftHigh]] - without this option (or if set to false) the right side of a multi bar high [low] is returned.

CODE:
Please log in to see this code.
profile picture

Eugene

#2
Thanks for sharing Jon. Maybe one day we'll formalize them as indicators for inclusion in Community.Indicators.
profile picture

Eugene

#3
P.S. We have a simplified version that defines 2-bar market swings:

Gann Swing Oscillator
profile picture

streak

#4
I have a logic error in "main" methods. However, the "basic" ones are fine. So, better hold back on using the "main's".
profile picture

Eugene

#5
No rush :)
profile picture

streak

#6

Here's the fixes for the "main's";
CODE:
Please log in to see this code.


And to test some plots you could try this :-
CODE:
Please log in to see this code.

profile picture

streak

#7

Here's a couple of different versions. These include ability to filter swings with value(or percent value) as well as quota of bars left and right side of the swings. To bypass value filtering set those parameters as zero. When incorporating the values the left side will require both value & bar quota to pass, while the right side will pass when either bar quota or price value(or percent) passes.

There are 3 indicator type series. one returns both high & low, the others are just high and low series. And there are the 2 bool methods that will also return the 'occurrence' bar number and price via the 'out' modifiers (I'll probably replace price with the slope ?) of the requested occurrence from the 'bar' number.

Series;
CODE:
Please log in to see this code.


methods;
CODE:
Please log in to see this code.


test;
CODE:
Please log in to see this code.
profile picture

Eugene

#8
Wow! Could you please formalize the indicators for inclusion in Community Indicators and provide some brief documentation? It doesn't have to be formatted (the Wiki will handle it) - just the parameter descriptions, purpose, interpretation, suggestions etc. Thank you in advance.
profile picture

streak

#9
OK thanks. Have to start up again tomorrow - now midnight.


Also some feedback could be good; ie On the series am wondering whether to leave values after most recent swing as they are (equal to the swing value itself), or increment these with the remaining (previous) slope. Depends on how they'd want to be made useful (if)?

Would the methods have to go in Community.Components (I have made some basic .Value methods in a dll, but the methods here have ability to return the 'x' mro of a swing)?
profile picture

streak

#10
Apologies. Have found 2 bugs in the series (indicator) calculations. The bool methods should be fine.

The first bug is with the right side parameters when requiring a price(or percent) filter with right side bars > 1. As this is an 'or' condition, sometimes it would be true at the last bar when the extra bars quota would have it bypassed - a critical scenario on the last bar!

The second bug is when a bar meets both swing high and swing low parameters on the same bar. This is maybe irreconcilable and can be seen in the following 2 pics, where switching between displaying/plotting the left to right side of the swing highlights how the code is currently handling the situation. (the code currently is at risk of a divide by zero err here but the way the code flows the if() block that would throw it is bypassed.




Uploaded with ImageShack.us
profile picture

streak

#11
QUOTE:
Could you please formalize the indicators for inclusion in Community Indicators and provide some brief documentation?


Have worked on some improvements, and now trying to send off the details for Community.Indicators & Community.Components

While I have in a previous custom extension, and been able to set the ext attributes etc that worked ok (except for one icon), and have the code working fine in my own local dll, I cannot seem to attached the correct detail and get it uploaded for wiki.

http://www2.wealth-lab.com/WL5Wiki/osProcedures.ashx suggests
QUOTE:
# When you (a developer) have an addition to a project, create a wiki page
. I cannot see how to do this.

http://www2.wealth-lab.com/WL5WIKI/kbPublishExtension.ashx demonstrates an Extensions.Attribute but I cannot understand this in as much as the demo seems to be for a new extension, but not for adding to an existing one. eg I added this extension attribute changing only my name as publisher and included the reference but the upload still could not find it.

Please help.
profile picture

Eugene

#12
You can safely disregard the part on ExtensionInfo attribute, and the other page as well.

It's enough to have just this:

1. A .cs file with your indicator (the DataSeries/Helper classes)
2. Some brief documentation (no need to format it) - the parameter descriptions, purpose, interpretation, suggestions etc.

Simply attach that to a new ticket, please.
profile picture

shardis89

#13
Streak what are the methodologies behind your calculations (i.e. basis for your work via book, research, etc.). I would sure like to learn more about the method as to be able to customize the parameters to my liking, but would like to first know what changing each parameter accomplishes.

Further, do any of these functions or would changing any of the parameters result in a peeking effect during backtesting? Likewise, is their anything to be cautious about when live trading. Based on testing to date, I have discovered a very large number of orphaned positions, so makes me curious to know if by changing one of the parameters in a swing high or lo function would help reduce this.
profile picture

streak

#14
shardis89

The basis for the set of swing methods was to be able to define/customise a swing based on any combination of parameters :-
- a minimum (asymmetric) number of bars either side of the swing high (or low) bar(s).
and /or
- a minimum price either side of the swing bar(s) (optionally asymmetric setting again).
- an option to require the price as a percentage move.
- to cater where there are a cluster of bars forming a swing (ie with equal prices on adjacent bars), and then to have options to define :-
- a tolerance to discern what is being called 'equal'.
- whether we want the left or right bar the 'swing bar'.

The indicator versions may help visualising the swings. The bool methods you might find more functional to ascertain some swing immediately its occurance (pending the required right-side bars) within a loop. You should not find any peeking issue here, and can easily assign data for trendline code etc.

Could you please explain more about your comment
QUOTE:
I have discovered a very large number of orphaned positions
?
profile picture

Eugene

#15
QUOTE:
I have discovered a very large number of orphaned positions

Stephen here probably means the orphaned positions as a result of trading in his WealthSignals account. As stated in the documentation, there are 5 groups of likely causes behind orphaned positions, such as: price rounding, failure to assign priority, data issues, buying power (margin), and operator error.
profile picture

shardis89

#16
Streak thanks for the comments and thanks for the functions.

QUOTE:
I have discovered a very large number of orphaned positions

I get a large number of orphaned positions in both my wealthsignals account and in my live trading accounts. I have taken numerous measures to reduce the amount of orphaned positions (i.e. I do not turn off limit/stop order rounding in the preferences, I do not have limit order slippage enabled, I have assigned position priority using the SetTimeofDayContext, and I trade in Raw Profit mode). Thus I thought maybe the swing indicator might be recalculating and changing the swing value on past bars based on a new price bar which might cause a previous alerted position to no longer show that a position existed. However, it sounds like it might be more of a function of the price data I am using. I am currently using Fidelity Price data, so I guess I will try Yahoo data and see if that helps. Currently utilizing the strategy monitor what I am experiencing running in raw profit mode on my live account, an alert will trigger and I will monitor the alerts in my quotes tool until its limit price is within 1% of the current price when it is staged. I then place the staged order. I have been seeing a large number of trades filled then within 1 or 2 days my system will not recognize that an alert was ever triggered and a traded placed. Thus I end up with a orphaned position and I end up having to manually place stop loss orders and manually exit trades.
profile picture

streak

#17
I'm not up to speed with WealthSignals, so my only suggestion to test if the swing functions are an issue with your script is to replace them with one of the other functions like Peak() or Trough() - to reduce your variables.

Are you using the bool methods or the indicator series? If using the indicator you could be peeking. Run this to visualise, if it helps, on June$Aus;
CODE:
Please log in to see this code.

profile picture

shardis89

#18
Streak, I am using the indicators, but for now consider the example swing functions on the Wiki: http://www2.wealth-lab.com/WL5WIKI/SwingFunctions.ashx. Take the example from the Wiki and add some buy and sell logic (e.g.

CODE:
Please log in to see this code.
)

Now run on ISRG from 1/1/2013 up to 7/19/2013. You will notice a buy alert triggered on the July 19th for ISRG based on code parameters for swgLo (see Chart). However note as you move towards July 22, the swgLo dataseries has changed to reflect the new swgLo and now the previous position you now own based on your buy logic for (bar +1) is no longer valid (i.e. you have orphaned position). Hence, if you are running the strategy monitor it will not process exit logic for the position because it now recognizes that the swgLo dataseries has changed based on the new low price, thus the system does not recognize the Price CrossUnder on the 19th because as we have progressed into the future the dataseries changed based on the new bars. I guess that is just an inherent nature of the swing function and price data. Obviously the parameter combinations of the swgLo dataseries is unlimited, but do you have any ideas or suggestions on ways to avoid some of these common occurrences?

Regards
profile picture

Eugene

#19
I second that. The ISRG trade should have probably happened on 7/22 because prices that day went way lower than the alert limit price.
profile picture

streak

#20
Shardis89,

yours is an important point. The issue stems from placing swing into a dataseries, and then joining the swings with lines. Great for visualising but can drive one nuts when systemising.

If one has 5 consecutively lower swing lows they can all be valid swings but the series line joining these will do as you suggested - leaving orphans.

The only solution is to not use crossing of a series line, when that line can always readjust/reset pending a new swing.

Try the bool methods instead (I haven't tested per with the Strategy Monitor and not au fait with it, so keen to hear your test)...
CODE:
Please log in to see this code.
profile picture

shardis89

#21
I am still entry level when it comes to coding, so can you help me understand what your code is doing. My assumption is that you are telling it too only buy if the last bar was equal to an actual swing lo and not crossing under the dataseries that connect the swing lo's. Unfortunately when I tried to implement this code, it didn't seem to be getting out of positions fast enough or at all.
profile picture

streak

#22
Yes, the code does not use the dataseries SwingHi or SwingLo. And yes the code leaves many open positions (I only put some basics in as a demo of one means to overcome the issue you pointed out). And yes the code works off the swings themselves and only after they are known ie no peeking).

The bool methods replace the dataseries. If either method returns true then its 'out' parameter is assigned the bar number of the swing, else it's assigned -1.

So for each bar in the loop, we know the last swing bar. If Low[bar] goes below the last swing low( Low[lastLoBar] ) the we buy.

Before this in the loop, if 'almost' the reciprocal happens we sell. But with much of your original code there, only the last position can be sold ie if there are 2 consecutive entries only the last one is being tested for a sell. You'll have to modify it to suit if you wish to use these methods as opposed to the dataseries. I'm sure you'd consolidate it and make more efficient. Interesting results if you remove the checks for last position check and contains string.
profile picture

shardis89

#23
My apologies I am not much for coding. Been trying to code so that all positions close out. I have managed to get the code to run but it seems like it takes too long and then I get stacks of annotations for each swing occurrence (i.e. multiple instances of same annotation occurrence stacked up at swing hi and swing lo). I have tried to fix but I keep getting these errors such as -- "warning CS0612 @ (116, 10): 'Community.Components.IsSwing is obsolete" or if I don't get that, I get this --"Runtime error: Index was out of range. Must be non-negative and less than the size of the collection. at WealthLab.Strategies,. MyStrategy.Execute() at System.Collection.Generic.List1.get_item(Int32index)."and cant figure out how to overcome. Further, it looks like my strategy is not buying after the annotated swing low, but at random 2 bar lows.

Streak do you mind illustrating your full code here with the buy and sell logic that will close multiple potions so I can see what I am doing wrong. Actually I would only prefer to have one position per symbol, if you don't mind illustrating that way. I usually am decent at adapting code to my liking but this is more complex than what I am accustomed too. I would greatly appreciate it. I have spent about 4 hours trying to get this too work, with no result.
profile picture

Eugene

#24
QUOTE:
"warning CS0612 @ (116, 10): 'Community.Components.IsSwing is obsolete"

Disregard this message, it's expected.
profile picture

streak

#25
shardis89

Aside from defining a swing which can have complex parameters the logic in the loop you should find quite easy. The IsSwing methods simply work each bar returning true or false if a swing is found within the lookback period and if found assign the 'out' variable with the swing high or low bar and further assigned to lastLoBar etc.

As these methods are run first during each step of the loop the most recent occurrences (bar numbers) are known every bar.

Instead of assigning 2 dataseries to the CrossOver & CrossUnder methods just assign one dataseries and a double ie price.
Enclose the exit statements with a test;
CODE:
Please log in to see this code.
and for a single position system enclose the entry statements with a test;
CODE:
Please log in to see this code.


CODE:
Please log in to see this code.
profile picture

kcbars

#26
Hello. I, too, have been having a similar issue with "orphaned" positions using this function for what I believe are the reasons described above. I was curious if anyone has had any luck with a workaround or way to get the positions to loop correctly/close out? Thanks.
profile picture

streak

#27
QUOTE:
I, too, have been having a similar issue with "orphaned" positions using this function

What function are you using?

Did you test the code above in #25 on ISRG from 01-Jan-2013 to 24-Jul-2013 both with and without the commenting around
CODE:
Please log in to see this code.
?
profile picture

kcbars

#28
Thanks for responding. I think I may have spoken too soon. I was able to get the changes above to run with the bool method instead of the data series. I had been attempting to use the swing low function in automated strategies, and was having trouble with positions being left open due the changing data series/lines. But I think I now understand how to deal with it. Thanks for the help!
This website uses cookies to improve your experience. We'll assume you're ok with that, but you can opt-out if you wish (Read more).