PDA

View Full Version : Slope function output


Gumphrie
07-16-2007, 09:38 AM
Hi,

Does anyone know what the output of the Slope() function actually represents?
It seems to change on ticksize. How can I just convert it to degrees?
(where 90 is straight up and -90 is straight down)


Thanks in Advance

NinjaTrader_Ray
07-16-2007, 09:59 AM
I can give you the math we use:

y2 - y1 / x2 - x1 = price2 - price1 / endBarNumber - startBarNumber

Gumphrie
07-16-2007, 01:25 PM
OK, I worked it out. You can't use the Slope() function for the angle as it gives a price related calculation as its ouput. But you can work the true angle if you override the Plot class to get the value. Of course, a side effect of working out the true angle is that as the chart is resized or stretched the angle outputted changes too. Here's the code for anyone wanting it:



public override void Plot(Graphics graphics, Rectangle bounds, double min, double max)
{
// Default plotting in base class.
base.Plot(graphics, bounds, min, max);

int index = -1;
int bars = CalculateOnBarClose ? (ChartControl.BarsPainted - 2) : (ChartControl.BarsPainted - 1);
DataSeries emaSeries = this.EMASeries; // populated in onBarUpDate


if (base.Bars != null)
{
while (bars >= 0)
{
double emaSlope;

index = ((ChartControl.LastBarPainted - ChartControl.BarsPainted) + 1) + bars;
if (ChartControl.ShowBarsRequired || ((index - base.Displacement) >= base.BarsRequired))
{
double val = emaSeries.Get(index);
if (!double.IsNaN(val) && (val != 0))
{
int y2 = (bounds.Y + bounds.Height) - ((int) (((val - min) / ChartControl.MaxMinusMin(max, min)) * bounds.Height));
val = emaSeries.Get(index+1);
if (!double.IsNaN(val) && (val != 0))
{
int y1 = (bounds.Y + bounds.Height) - ((int) (((val - min) / ChartControl.MaxMinusMin(max, min)) * bounds.Height));
emaSlope = ((180/Math.PI) * Math.Atan2(y1-y2,ChartControl.BarSpace))*-1;
// do something
}
}
}
bars--;
}
}
}

dwalls
07-16-2007, 04:11 PM
Hello Gumphrie,
This is great. I would really like to learn how to use slope in a strategy or just with an indicator. Could you please show us an example of how this could be applied/attached to the working EMA indicator code or how you to use it in a working strategy using the slope code.


Thanks so much.

NinjaTrader_Josh
07-16-2007, 04:59 PM
Couldn't you also just use some math to determine the angle? Slope of 1 is 45 degrees and slope of -1 is -45. Slope of 0 is 0 degrees. You don't have to worry about 90 or -90 because those won't exist on a chart.

Basically just use m=tan θ where m is the slope and θ is the degrees.

Example
(System.Math.Atan(Slope(SMA(5),CurrentBar-1,CurrentBar))*180/Math.PI).ToString()
This will give you the angle in degrees of an SMA.

Gumphrie
07-16-2007, 06:10 PM
uacvax,

Do you mean the output from Slope()? I thought that was what is was too, 1 to -1 = the angle, but it isn't. Try it on instrument with a different tick size! The output of Slope() is in effect the same as the percentage rise or fall of the given index. If thats not what you mean then I'm not sure as my trigonometry is very rusty.

dwalls

Please find attached. I've used Ray's MA switching code as a base and used the slope angle code to create a 'slope box' at the bottom right corner of the chart.

-- attachment removed - see latest post(s) --

NinjaTrader_Josh
07-16-2007, 06:43 PM
I'm not quite sure what you mean by an indicator with a different tick size. Can you give me an example?

Gumphrie
07-16-2007, 06:49 PM
I'm not quite sure what you mean by an indicator with a different tick size. Can you give me an example?

Lets say NQ and SE, one is 0.25, the other is 0.0001. So when Slope() takes one price away from the other the results will be quite different across these instruments.

dwalls
07-16-2007, 09:29 PM
Gumphrie,
Thanks, I got it work. Much appreciated.
I have two things:

1) Would it be possible for you to add the LSMA to the list of indicators in the MASlopeBox or make a seperate MASlopeBox for the LSMA? Thanks

2) I found this in another code and was hoping it might help you in some way with you previous post about the different instruments:

//**************************************
// This secion is performed on First bar only
// Contains Set-ups that remain constant for chart, so don't need to be repeated every bar/tick
//
if (CurrentBar == 1)
{
// Set the stringformat parameter for decimal places to suit the instrument.
// This ensures that trailing zeros are always displayed - maybe an easier way to do this?
double temp1 = TickSize - (int)TickSize;// get fractional part of TickSize
decimals = temp1.ToString(); // make it into a string
int tickLength = decimals.Length; // get the number of characters in the string
switch (tickLength) // set format depending on length of string
{
case1: decimals = "f0"; // eg YM 1t = 1 point
break;
case3: decimals = "f1"; // eg ER2 1t = 0.1 point
break;
case4: decimals = "f2"; // eg NQ 1t = 0.25 point
break;
case5: decimals = "f3"; // eg 1t = 0.001 point
break;
case6: decimals = "f4"; // eg 6E 1t = 0.0001 point
break;
case7: decimals = "f5"; // eg 1t = 0.00001 point
break;
default: decimals = ""; // default is no fixed decimal format
break;
// more options can be added if neccessary......
}

// StringFormat set up
formatCenter.Alignment = StringAlignment.Center; // text centered
formatRight.Alignment = StringAlignment.Far; // text right aligned

dwalls
07-16-2007, 09:40 PM
I also found this on the slope:

// slope compares current EMA with the average of the 2 prior bars (or the EMA 1.5 bars back)
ema34slope = (int)(RadToDegrees*(Math.Atan((EMA(34)[0]-(EMA(34)[1]+EMA(34)[2])/2)/1.5/TickSize)));

NinjaTrader_Josh
07-16-2007, 09:55 PM
Hmm I'm not quite sure as to why you would take one away from the other in that fashion. Slope is a function of a single line or curve. You are taking two different curves and in effect using priceSE-priceNQ/1. I'm not sure exactly what that calculates, but I'm pretty sure that isn't a slope. If there is some relationship between the two instruments that you wanted a slope of you need to first plot that relationship as its own curve and then take the slope of that new composite curve.

When you go (priceSE[2]-priceSE[1])/(2-1) and compare it to (priceNQ[2]-priceNQ[1])/(2-1) the two slopes are "normalized" on the (-1,1) scale so the 0.00 vs 0.0000 shouldn't matter. A numerical move of the same magnitude on both price scales will result in the same slope (e.g. a 0.50 cent move on either instrument yields a slope of 1/2).

Since the 0.0000 scale is smaller, a 5% change in price in that instrument will not yield a slope equal to a 5% change in price of an instrument on the 0.00 scale. This is to be expected because your "run" factor for calculating the slope is the same, 1min/bar/etc on both bars. This is proper slope calculation so I'm not sure what kind of number you were hoping to get out of the Slope() function. The slopes you get on the 0.0000 scale will just generally be smaller than on the 0.00 scale because of the normalized "run".

Also, slope is not a function to determine percent change. If you wanted percent change you would do (NewPrice-OldPrice)/OldPrice.

Edit: I believe the code dwalls posted from the WoodiesCCIPanel indicator will work to your particular likings. It normalizes the ticksizes so the slopes should be directly comparable.

Gumphrie
07-17-2007, 02:19 AM
uacvax

I'm not directly taking one price away from the other, I'm just saying that Slope() is in effect doing that in the calculation ( (priceSE[2]-priceSE[1])/(1) and (priceNQ[2]-priceNQ[1])/(1) ). I'm not saying it is the same as the percentage either, just that also does something similar in that its taking one price away from another.

There doesn't seem to be a proper way, just different ones. I'm throwing out my study results in effect. I wouldn't use the code I posted in a strategy as its chart specific, being dependent on the scale of the chart, but it may help someone whose trading style is chart orientated or if you need quick visual clarification. I might use the output of Slope() but its not really the slope at all, but a price change comparison for the given instrument. That may be what you want or it might not be. So something like the Woodies calculation is probably the best compromise, taking into account the ticksize its probably the best you can get for strategy work

Its interesting that most people who use Woodies and other similar systems seem to use tick bars rather than time based ones. Seeing as the slope is calculated on the basis that the 'x' axis is the number of new prices rather than time periods or 'chart space' that seems to make sense.

NinjaTrader_Josh
07-17-2007, 02:30 AM
Well isn't a price change comparison exactly what a slope is on a chart? Rise/Run with Rise being the y-axis (price) and Run being the x-axis (time). But I see your point. I was just slightly confused :cool:.

Gumphrie
07-17-2007, 02:42 AM
dwalls,

I don't have the code for LSMA, could you send or redirect. Thanks!

Funny you digged out the WoodiesCCIPanel indicator code, thats exactly the point I got to. I hadn't noticed the emaSlope calculation though, Thanks Again!

Gumphrie
07-17-2007, 02:47 AM
Well isn't a price change comparison exactly what a slope is on a chart? Rise/Run with Rise being the y-axis (price) and Run being the x-axis (time). But I see your point. I was just slightly confused :cool:.

Me too. Maths is not my strong point. :confused: It just seems any number based on time is not 'quantifiable' when comparing it to the charts.

dwalls
07-17-2007, 07:23 AM
Gumphrie,
Yes Thanks. In Ninja its the stock (pre loaded) Linear Regression indicator.

Here is a Ninja panel from Woodies site

Thanks

Gumphrie
07-17-2007, 08:43 AM
OK, to tidy this all up I've attached a new SlopeBox indicator with LSMA and the ability to select the 'SlopeType' calculation used as follows :

WYS : WhatYouSee - as in the chart based calculation
WDS : WooDiesSlope - as in the calculation dwalls posted
NTS : NinjaTraderSlope - as in the output of Slope() converted to degrees as uacvax posted


----attachment removed - see later post----

dwalls
07-17-2007, 09:25 AM
Wow, very cool.
Thanks Gumphrie

By the way, if anyone trys the WoodiesCCIpanel from below, the right hand margin will need to be changed to about 141 or so...as not to cover up the CCI.

Gumphrie
07-17-2007, 02:49 PM
Thanks.

The WDS calc was wrong, I've updated the attachment.

NinjaTrader_Josh
07-17-2007, 04:57 PM
Hmm there must be a better way to do the enum stuff. Because you are using a public enum AverageType in your MASlopeBox and because I already have that type in another one of my indicators it creates a conflict between the two indicators and does not allow for me to import your indicator.

Basically there can only be one instance of
public enum AverageType
{
EMA,
SMA,
WMA,
} in all of our indicators.

Also your NTS is producing a constant 0 degrees with sporadic -1 degree erroneous readings.

Gumphrie
07-17-2007, 05:58 PM
Also your NTS is producing a constant 0 degrees with sporadic -1 degree erroneous readings.

I know! Its the Slope() output equation you posted dependent on ticksize. How should I modify it? Would you rather it doesn't do the degree convertion in that case?

NinjaTrader_Dierk
07-17-2007, 11:38 PM
Hmm there must be a better way to do the enum stuff. Because you are using a public enum AverageType in your MASlopeBox and because I already have that type in another one of my indicators it creates a conflict between the two indicators and does not allow for me to import your indicator.

Basically there can only be one instance of
public enum AverageType
{
EMA,
SMA,
WMA,
} in all of our indicators.

Also your NTS is producing a constant 0 degrees with sporadic -1 degree erroneous readings.


You could define any enum/class/type within the scope of another class (e.g. indicator), even as "public" ... BUT this is not recommended by MS due to limitations on the compiled .NET assembly

-> better go with your current approach of one enum for all indicators.

Learning1
08-28-2007, 02:06 PM
Hi There,

I was seeking a slope indicator (of linear regression), but there doesn't seem to be one in the standard indicators. I then came accross this post in the forum. Unfortunately, when I tried to import it, I got an error that didn't allow the import due to programming errors. I assume this is due to the enum/class issues last posted. Have these issues been resolved and the indicator is posted elsewhere (I couldn't find it with a simple search)? If not, do you have any suggestions around the simplest way to likely fix this challenge to allow import?

Thanks,

Gumphrie
08-28-2007, 03:22 PM
Hi There,

I was seeking a slope indicator (of linear regression), but there doesn't seem to be one in the standard indicators. I then came accross this post in the forum. Unfortunately, when I tried to import it, I got an error that didn't allow the import due to programming errors. I assume this is due to the enum/class issues last posted. Have these issues been resolved and the indicator is posted elsewhere (I couldn't find it with a simple search)? If not, do you have any suggestions around the simplest way to likely fix this challenge to allow import?

Thanks,

Yes, that's because it conflicts with another indicator you already have installed.

This thing is a proof of a concept thing only, so I don't know if its what you looking for. Either way, here is a new version without the conflict.

Learning1
08-28-2007, 03:45 PM
Thanks Lots Gumphrie!

This imported fine and provides a good input for me to play around with in the strategy I'm contemplating. I appreciate the help both on this issue and all the other coding you've done for the forum. I've found a number of your posts / indicators to be very helpful and thought provoking.

Thanks Again,

Learning1

pdawg
10-06-2007, 09:04 PM
Gumphrie,

Would it be possible to add a user definable option for the range of bars to use to calculate the slope? I see you have it set to CurrentBar-1.

Also could there be a user definable threshold level for for when the slope hits a desired angle that the color changes? That would work with a 3 color plot. A color for negative, nuetral and positive angles, based on the threshold level selected.

Thanks,

Philip

Gumphrie
10-07-2007, 10:19 AM
Gumphrie,

Would it be possible to add a user definable option for the range of bars to use to calculate the slope? I see you have it set to CurrentBar-1.

Also could there be a user definable threshold level for for when the slope hits a desired angle that the color changes? That would work with a 3 color plot. A color for negative, nuetral and positive angles, based on the threshold level selected.

Thanks,

Philip

The bar range is based on the Period of the MA selected. Not sure where you saw CurrentBar-1?

Sure there could be. Just change the degrees>0 colour check in the Plot method and hook that into some user properties as needed.

pdawg
10-07-2007, 12:25 PM
NTSeries.Set((180/Math.PI) *(Math.Atan(Slope(EMA(Period),CurrentBar-1,CurrentBar))));

The range for the MA is different than the range for the slope calc. I like to use CurrentBar-5 for my slope calcs.

pdawg
10-10-2007, 01:52 AM
I was looking through this thread, and when it comes to Slope() it does vary it's output depending on tick size as mentioned before. It looks like if you want to normalize the Slope() output no matter what the instrument, you would just divide the slope calc by the TickSize:

(Slope(EMA(34),CurrentBar - 5, CurrentBar)/TickSize)

Just looking at the output between the YM and ER, that seems to do the trick.

Burga1
01-29-2008, 11:45 AM
Gumphrie can you please explain a lil bit on how to utilize that code you posted earlier on "overriding" the Plot Class?? Thank you.

Gumphrie
01-29-2008, 12:33 PM
Gumphrie can you please explain a lil bit on how to utilize that code you posted earlier on "overriding" the Plot Class?? Thank you.

Hi Burga,

The Plot class is the lower level method to OnBarUpdate which lets you directly manipulate the graphics used to draw stuff on the chart. So in this example I used it to draw a box to put the degree values in, which wouldn't normally be possible just using the NinjaScript Draw functions.

Burga1
01-29-2008, 01:30 PM
Hi,

Thank you for your reply. So the code you did should be included within the "OnBarUpdate" function, or elsewhere?

Burga1
01-29-2008, 08:03 PM
Hi again Gumphrie,

OK I think I figured out how to construct the indicator...I just have a couple of questions about your code please. In the code you wrote "do something" where I assume code is inserted after the degree angle has been determined, correct?

Also you have "populated in OnBarUpdate" for the "EMASeries" variable, I assume that the values for "EMASeries" is to be calculated there...?

Don44
03-03-2008, 08:13 PM
Gumphrie,
I like your MaSlopeBox...just what I was looking for. Could you please provide a quick response as to how I would tweak it to plot the actual "degrees" values, say for the SMA WYS, instead of the price SMA itself. If I can plot the degrees DataSeries, then I can use the values in subsequent logic. Thanks for yor help.
Don44

Elliott Wave
04-12-2008, 09:06 PM
I'd really like to be able to use this indicator, but it doesn't seem to do anything.

No value is every shown in the data box and plot is always empty.

Am I doing something wrong?

It looks like the last version was quite a while ago so perhaps it needs a few tweaks to work with 6.5.

NinjaTrader_Josh
04-12-2008, 10:01 PM
Your suspicion is most likely correct. Please see if there are any errors in the Control Center logs tab when running this indicator for a clue as to the culprit.

Gumphrie
04-13-2008, 01:02 AM
Find attached, NT changed their implementation of the Slope() function with 6.5.

Elliott Wave
04-13-2008, 03:25 AM
Thank you very much. This is SO useful. :)http://www.ninjatrader-support.com/vb/images/icons/icon14.gif

I'm still getting the hang of it, but I'm wondering if there is a way to display the slope in the Databox? Currently it shows the moving average value, rather than the slope.

Currently the only indication of slope is a small box in the bottom right corner and it seems many indicators (BarTimer, CandleStickPattern, etc) like to use this exact spot which can make the result difficult to see. I'd like to use this indicator for multiple EMAs at once , but the degrees display overlaps itself...
:(

Elliott Wave
04-13-2008, 10:13 PM
I changed this so you can use multiple instances without having the data boxes covering each other up.

Just change the boxnumber parameter.

This may conflict with previous versions due to the public enums, if so simply open the .cs file in notepad and comment that code and it should work.

Elliott Wave
04-16-2008, 01:13 AM
Find attached, NT changed their implementation of the Slope() function with 6.5.

This is such an awesome indicator I decided to 'enhance' it as part of my NinjaScript learning experience.

Feel free to optimize anything that could be done better. My main goal was to allow multiple instances, increase the number of MA types supported, enhance readability with higher resolutions, and prevent the data box from conflicting with every other indicator that likes to use that same spot on the chart. :)

http://www.ninjatrader-support.com/vb/local_links.php?catid=1&keyid=&page=1&pp=15&sort=d

altrader
04-17-2008, 01:25 AM
This is a really interesting indicator, many thanks to Gumphrie & Elliot Wave for putting it together, presumably it's being used to try and determine if market is range bound or trending (maybe with a couple of different MAs e.g. fast and slow)?

Has anyone nailed down anything more than that (period,type, slope etc) or have some initial values to look at?

Elliott Wave
04-17-2008, 02:04 PM
I'm still experimenting, but I think you have the idea. Basically its to avoid trading false signals when the market is directionless.

At the moment I'm using 5 different periods. I like to use EMAs and the WDS slope as its independent of the chart view. A way to use it that often identifies good trades is that when all 5 periods are negative (a long downtrend), then the shortest three turn positive I will go long (a confirmed reversal). Another example is to go short when all 5 period are negative (definitely not a false trend), and then cover when the shortest period turn positive above 80 degrees (a sharp reversal).

Another benefit would be as a quick way to get out of bad trades. For example if you are short and the 5 period EMA slope suddenly goes to +70 degrees, it might be time to bail... :D Looking at historically bad trades in my strategy, this could be a good filter to keep the losses as small as possible, rather than waiting for slower reacting conditions to exit the trade.


There's countless ways this could be used, but until the slope output is accessible externally to the strategy wizard and as the input of other indicators, its not as powerful as it could be.

If the degrees calculation is made into a plot, it could also be used in the market analyzer.

I'm still scratching my head on how to do it though. :confused: I'll have to look at a few more examples and work on it tonight.

altrader
04-17-2008, 02:42 PM
These all seem like good ideas. You're right - if the degree output could be used within strategies then it could have a number of potential uses as an indicator. I'd love to help, but that's way above my programming level at the moment.

Are you aware of some of the TRO indicators Josh ported over? TRO_PMSM_Trend would give you an alternative way of showing trend direction of multiple MAs that you could reference in a strategy. http://www.ninjatrader-support.com/vb/showthread.php?t=2671

However, having the degree of the slope could be much more powerful.

Paul_J
04-17-2008, 03:37 PM
Awesome indicator. Is there a way to change the font color so the number doesn't clash with the background?

Elliott Wave
04-17-2008, 03:57 PM
Paul, thats something I'd eventually like to make a parameter that can be changed but at the moment, you'll have to edit the code.

I made the font a bit bigger than the original because I'm using a high resolution.

In the code under variables this line sets the default font:
private System.Drawing.Font textFont = new Font("Arial", 12);

To change the colors of the font from lime and red, use the search and replace function and search for

Color.Red and Color.LimeGreen and replace all instances with whatever colors your prefer.

-----

These all seem like good ideas. You're right - if the degree output could be used within strategies then it could have a number of potential uses as an indicator. I'd love to help, but that's way above my programming level at the moment.

Are you aware of some of the TRO indicators Josh ported over? TRO_PMSM_Trend would give you an alternative way of showing trend direction of multiple MAs that you could reference in a strategy. http://www.ninjatrader-support.com/vb/showthread.php?t=2671

Above my level too, but I'll see if I can figure it out. Those indicators looks interesting, but it appears they aren't 6.5 compatible yet.

I'm really excited for NT7 when hopefully the "InputSeries" parameter is supported from the indicator dialog on the charts. Currently it appears you have to plot an indicator as part of a strategy to be able to set the input of the indicator to the output of other indicators.

Being able to measure the slope of any indicator value would be really useful.

dwalls
04-17-2008, 04:07 PM
Hello,
Great indicator. Thanks.
I have a couple questions:
1) Is MASlopeBox the same as MASlopeBoxMulti?
2) Could you possibly and that new Zero Lag EMA to the drop down list?

Thanks,
dwalls

Elliott Wave
04-17-2008, 04:16 PM
Hello,
Great indicator. Thanks.
I have a couple questions:
1) Is MASlopeBox the same as MASlopeBoxMulti?
2) Could you possibly and that new Zero Lag EMA to the drop down list?

Thanks,
dwalls

No they are different. Because they use the same public variables, you'd have to delete MASlopeBox before adding the multi version and vice-versa.

MASlopeBox is the original made by Gumphrie, and MASlopeBoxMulti is my tweaked version which supports more MA types, allows you to use more than one instance (with the original the boxes would overlap), and also the color of the slope box matches the color of the MA plot whereas in the original the slope boxes would all be lime green and red, matching the color of the degrees font, making it more difficult to know which box is for which slope.

As for the zero lag MA, I plan to add that as well as KAMA, MAMA and VMA types, but that requires a bit more tweaking because those moving average types have more than one input parameter.

The NonLagMA for example has 5 parameters where the other MA types only have one. It shouldn't be hard to add basic support for those types, but initially only the period parameter would be user definable from the dialog.

I'll work on that later tonight.

Elliott Wave
04-17-2008, 10:08 PM
The MASlopeBox now supports 4 new MA types for 13 in total:

VOLMA (Volume Moving Average, only works with WYS slope type)
VMA (Variable Moving Average)
KAMA (Kaufman Moving Average)
NONLAGMA (Zi NonLag Moving Average)

The KAMA has 3 parameters fast, period and slow, with the defaults being 2, 10, 30. To keep the same ratio without complicating the indicator too much the fast period is automatically calculated as 0.2 x the period, and the slow as 3 x the period set in the parameters box.

For the VMA period and volatility period default to the same so one value is used.

The NonLagMA is the most complex so I just left all the variables to the default with only the period being changed.

dwalls
04-18-2008, 10:33 AM
Elliot Wave,
I was accually preferring to the Zero Lagging EMA. It is the last indicator found at the bottom of page 7 in the Indicators section in this forum. Maybe see if it would be easier to use than the ZI NonLag Moving Average you are currently using, found on page 5.
fwiw

thanks

Elliott Wave
04-18-2008, 12:40 PM
Ok I see the one you are talking about.

It is definitely simpler as it only has one parameter.

I'll have to look into it and see what the differences are.

---------------------

I've added the ZeroLagEMA. Also on the advice of Gumphrie I changed the public enums, which fixes the conflict between the multi version and the original.

I think that pretty much covers all the moving average types.

Hopefully in the near future a degrees plot will be added, allowing the indicator to be used with automated strategies. It may take a little while though...

ssierra
04-20-2008, 07:03 AM
Hi Elliott,

This is really great!

I am developing some strategies using MAs and I wonder if it is possible to have each MA assigned with a number. With something like this we could run a strategy optimization and see which is the best MA.

Cheers,

NinjaTrader_Josh
04-20-2008, 02:46 PM
You can try using a switch-case design on your code and just change between MAs. Then you can backtest each different variant and decide which you like the best.

timmyb
04-20-2008, 07:29 PM
so has anyone found a way to use the output in a strategy yet?? I just found this and agree this could be an amazing indicator

ssierra
04-21-2008, 03:46 PM
You can try using a switch-case design on your code and just change between MAs. Then you can backtest each different variant and decide which you like the best.

Thanks, but I don't have enough knowledge programming L

Maybe someone can help with this.

cheers

NinjaTrader_Josh
04-22-2008, 12:12 AM
Check this out. http://www.csharp-station.com/Tutorials/Lesson03.aspx

timmyb
04-22-2008, 10:40 AM
Can anyone explain the slope() function in ninja a little for me, i have read the manual, and tried to use it but to no avail. I really dont understand what it it outputting.

NinjaTrader_Ray
04-22-2008, 12:00 PM
It returns the slope as calculated by rise over run. Here is some further data - http://www.purplemath.com/modules/slopgrph.htm

timmyb
04-23-2008, 06:22 PM
So the slope is calculated in radians, from -1 to 1. Is there a specific reason why ninja could not have put what .10 or -.10 means in terms of degrees somewhere in documentaion. Ok so anyhoo, gonna do some googleing and see if i can figure it out, thanks for great software

timmyb
04-23-2008, 06:40 PM
Ok since I have been told ninja wont output radians larger than 1 or less than -1 this is what i am getting for what radians mena decimal wise, please let me know if i am wrong

1 Radian = 57.29 degrees
.95 radian = 54.4 degrees
.90 radian = 51.5 degrees
.80 = 45.8
.70 = 40.10
.60 = 34.3
.50 = 28.6
.40 = 22.9
.30 = 17.18
.20 = 11.45
.10 = 5.72
.05 = 2.86

i am guessing 0 is flat line

- radians are the exact opposite, now a question i have is a positive radian, so what plane is zero at. is taht the horizontal plane?? or vertical plane


One thing to understand about a radian is that it is bigger than a degree. In fact:1 radian = 57.2957 degrees

1 degree = 0.0174532 radians


So atleast for me if u want to use the slope function in the wizard, use the MAmultislopebox indictor and look at see waht angle u want to see, the take that angle and multiply it by the measurment of .0174532 and use that in the wizard, i think :) dont know if this helps anyone for using this in a strategy but i think its gonna help me

timmyb
04-23-2008, 10:41 PM
Ok i am obvioulsy not a ninja expert, but i am trying my best, I realize i must be way off base, but in a attempt to get this indicator to work under strategies this is where i have gotten,

I added another plot here:



[Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
[XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
public DataSeries Degrees

{
get { return Values [0]; }
}

I named it Degrees

I tried to get the (int) number needed from here this way:

if (haveLabel)
{
switch (MySlopeType)
{
case SlopeTypeMulti.WYS:
degrees=(int)wysSlope;
Degrees.Set(0,(int)wysSlope);
break;
case SlopeTypeMulti.WDS:
degrees=(int)wdsSlope;
Degrees.Set(0,(int)wdsSlope);
break;
case SlopeTypeMulti.NTS:
degrees=(int)ntsSlope;
Degrees.Set(0,(int)ntsSlope);
break;


Now what i see wrong is that i am trying to get the value from in the plot section, i dunno if this is the wrong way or not, but basically depending on the selection here it displays the degrees in the little box on the chart. So i typed Degrees.Set and used the same info they have. And well i get no trades when using the plot of degrees, I then tried to "Degrees.Set" here:
protectedoverridevoid OnBarUpdate()
{
if (CurrentBar < 2) return;
switch (MyAverageType)
{
case SlopeBoxMultiAverageType.SMA:
Plot0.Set(SMA(Period)[0]);
NTSeries.Set((180/Math.PI) *(Math.Atan(Slope(SMA(Period),1,0))));
Degrees.Set((180/Math.PI) *(Math.Atan(Slope(SMA(Period),1,0))));

since i figured that where it all starts, it then will get a numerical value but nothing close to what appears right when using teh indicator.

Well no expert am I but hey its a good learning lesson, if anyone has input just let me know. It appears allot of people would love to have this indicator and use it in strategies myself included.

timmyb
04-23-2008, 11:00 PM
Ok i think i got it to work but when the indicator shows on the screen now it, squishes the candle at the top, and the moving average at the bottom, i dont really see why. But i am trying nonetheless

NinjaTrader_Josh
04-24-2008, 02:09 AM
Try turning AutoScale off on your indicator.

timmyb
04-24-2008, 09:55 AM
Tried that last night it didnt make a difference, still working on trying to capture the output of degrees to a plot that can be used in a strategy,

what is the funtion i use so i can see what the code is doing when it is running??

the output code

timmyb
04-24-2008, 09:46 PM
Ok i got a degree indicator built that allows output of the degree for strategy developement, It is absed off the TRO with the colored dots. Let me know if you would like me to upload it. I am doing testing now, but it appears to work

NinjaTrader_Josh
04-25-2008, 12:45 AM
Outputting can be done through the Print() function. I'm sure the community would appreciate any new indicator you feel like releasing.

timmyb
04-25-2008, 09:52 AM
So by using the print funtion, in the MAslopebox indicator you could get the slope outputed for a strategy to use??

NinjaTrader_Josh
04-26-2008, 04:49 AM
I am not familiar with the MASlopeBox, but if the original author made accessible values then yes you can. You will need to contact the original author for more information.

altrader
04-26-2008, 05:19 AM
From my understanding the degrees value is not currently accessible from a strategy and the code would need modified. It would be great if it was accessible though, but unfortunately it's beyond my level to do this .:(

timmyb
04-27-2008, 09:49 AM
The degree value is not able to be outputed at this time, I tried my best with what i know, but was unable to get it to work right << Newb. I was able to use the code to create another indicator taht uses the EMA average that does output a limit of the Angle. IE if it is above 20 degrees to output a 1. You can then use this in a strategy set to whatever you want, IE 5 degrees etc. It is only for the EMA right now. When i test it moe tongiht i will upload it, If someone can tell me how to upload a indicator here.

NinjaTrader_Josh
04-27-2008, 03:53 PM
You can upload through the file sharing section of the forum. There is a button called "Add Entry". Just click on that to add.

steveg
04-27-2008, 07:04 PM
Is there an indicator already available that would color the MACD lines red when sloping downward, blue when sloping upward and yellow when flat? I use the DoubleMA indicator to color EMA lines this way, but it doesn't seem to work on the MACD lines. I am not interested in coloring the MACD histogram.

NinjaTrader_Josh
04-27-2008, 08:59 PM
I don't remember if there was one made already, but you can try searching in the file sharing section of the forums.

ssierra
05-14-2008, 02:41 PM
Hi All,

Have someone been able to get the slope into a strategy?

I have tried to plot the slope without any success but my knowledge is very limited :(

Cheer

Gumphrie
05-14-2008, 04:14 PM
Attached is MASlopePlot, based on MASlopeBox. I think doing the plot has exposed a problem with the SlopeBox, in that the calculation on the box version has to have 'calculate on bar on close' set to false to get the same values as the plot, it matches up for NTS, but not for WDS for some reason.

That problem aside you can call it from a strategy or just use the Slope() function directly in the code.

ssierra
05-14-2008, 04:31 PM
Thanks this is great!!!

I will test it

Cheers

Elliott Wave
05-14-2008, 05:27 PM
This works great.

timmyb
05-19-2008, 03:47 PM
Great work Gumphrie, I for one bow down :)

If anyone wants this, its the first indicator i am posting here,

http://img120.imageshack.us/img120/3710/emademoya6.png (http://imageshack.us)
http://img120.imageshack.us/img120/3710/emademoya6.7dcee82486.jpg (http://g.imageshack.us/g.php?h=120&i=emademoya6.png)

Now if someone can just tell me how to uplaod it so others can try it :)

Elliott Wave
05-19-2008, 04:40 PM
Looks nice Timmy :)

I look forward to trying this.

Thanks.

Gumphrie
05-19-2008, 04:46 PM
Thats great timmyb, particularly with the range bars, makes a lot of sense.

Well done!

dwalls
05-20-2008, 09:25 AM
Great indicator timmyb. I like it alot.
Would it be possible to include an option for the WDS slope as well as the NTS slope in your indicator? or create a seperate second indicator the uses the WDS slope?

Thanks for your help.

Elliott Wave
05-20-2008, 03:39 PM
I was unable to get this to work. Not sure why. It imports fine, but doesn't plot anything...

Any ideas?

timmyb
05-20-2008, 07:26 PM
Wow never imagined the responses,

Shure I can make it WDS, slope, I use NT just cause it more of a rise to run, But i have found it excellent so far,

I am not shure why it is not working for you, try adjusting the long and short threshold, it may be the EMA your using does not get past the setting.

Let me know anything else you guys may want

i used green for long and red for short cause well it made sense to me

i also have about 12 others i made using "gumprhies" dots

Tim

timmyb
05-20-2008, 07:33 PM
Here is a tad better explanation:

http://img238.imageshack.us/img238/9779/emadegreeexplaindc4.png (http://imageshack.us)
http://img238.imageshack.us/img238/9779/emadegreeexplaindc4.cfd221be1e.jpg (http://g.imageshack.us/g.php?h=238&i=emadegreeexplaindc4.png)

timmyb
05-20-2008, 07:43 PM
Figure the EMA guys might like this one also:

http://img204.imageshack.us/img204/408/emacrossha8.png (http://imageshack.us)
http://img204.imageshack.us/img204/408/emacrossha8.a6e19bdde0.jpg (http://g.imageshack.us/g.php?h=204&i=emacrossha8.png)




Simple:
Fast above slow = Green Dot
Slow above Fast= Red Dot

Like any other EMA cross, i like it better than watching the lines cross

stephenszpak
05-27-2008, 12:19 AM
I'm not sure if this has been covered or not (in a script).
This is a conversion I did at:

http://www.onlineconversion.com/angles.htm

It may help me eventually, at least. -Stephen

__________________________________________________ ___________

0 degree = 0 radian
5 degree = 0.087 266 462 6 radian
10 degree = 0.174 532 925 2 radian
15 degree = 0.261 799 387 8 radian
20 degree = 0.349 065 850 4 radian
25 degree = 0.436 332 313 radian
30 degree = 0.523 598 775 6 radian
35 degree = 0.610 865 238 2 radian
40 degree = 0.698 131 700 8 radian
45 degree = 0.785 398 163 4 radian
50 degree = 0.872 664 626 radian
55 degree = 0.959 931 088 6 radian
60 degree = 1.047 197 551 2 radian
65 degree = 1.134 464 013 8 radian
70 degree = 1.221 730 476 4 radian
75 degree = 1.308 996 939 radian
80 degree = 1.396 263 401 6 radian
85 degree = 1.483 529 864 2 radian
90 degree = 1.570 796 326 8 radian
95 degree = 1.658 062 789 4 radian
100 degree = 1.745 329 252 radian
105 degree = 1.832 595 714 6 radian
110 degree = 1.919 862 177 2 radian
115 degree = 2.007 128 639 8 radian
120 degree = 2.094 395 102 4 radian
125 degree = 2.181 661 565 radian
130 degree = 2.268 928 027 6 radian
135 degree = 2.356 194 490 2 radian
140 degree = 2.443 460 952 8 radian
145 degree = 2.530 727 415 4 radian
150 degree = 2.617 993 878 radian
155 degree = 2.705 260 340 6 radian
160 degree = 2.792 526 803 2 radian
165 degree = 2.879 793 265 8 radian
170 degree = 2.967 059 728 4 radian
175 degree = 3.054 326 191 radian
180 degree = 3.141 592 653 6 radian
185 degree = 3.228 859 116 2 radian
190 degree = 3.316 125 578 8 radian
195 degree = 3.403 392 041 4 radian
200 degree = 3.490 658 504 radian
205 degree = 3.577 924 966 6 radian
210 degree = 3.665 191 429 2 radian
215 degree = 3.752 457 891 8 radian
220 degree = 3.839 724 354 4 radian
225 degree = 3.926 990 817 radian
230 degree = 4.014 257 279 6 radian
235 degree = 4.101 523 742 2 radian
240 degree = 4.188 790 204 8 radian
245 degree = 4.276 056 667 4 radian
250 degree = 4.363 323 13 radian
255 degree = 4.450 589 592 6 radian
260 degree = 4.537 856 055 2 radian
265 degree = 4.625 122 517 8 radian
270 degree = 4.712 388 980 4 radian
275 degree = 4.799 655 443 radian
280 degree = 4.886 921 905 6 radian
285 degree = 4.974 188 368 2 radian
290 degree = 5.061 454 830 8 radian
295 degree = 5.148 721 293 4 radian
300 degree = 5.235 987 756 radian
305 degree = 5.323 254 218 6 radian
310 degree = 5.410 520 681 2 radian
315 degree = 5.497 787 143 8 radian
320 degree = 5.585 053 606 4 radian
325 degree = 5.672 320 069 radian
330 degree = 5.759 586 531 6 radian
335 degree = 5.846 852 994 2 radian
340 degree = 5.934 119 456 8 radian
345 degree = 6.021 385 919 4 radian
350 degree = 6.108 652 382 radian
355 degree = 6.195 918 844 6 radian
360 degree = 6.283 185 307 2 radian



-5 degree = -0.087 266 462 6 radian

stephenszpak
05-27-2008, 12:57 AM
This is some code from a script called practiceslope:

// Prints the slope of the 20 period simple moving average of the last 10 bars
Print(Slope(SMA(20), 10, 0));

Inclosed is a screen shot using simulated data 10 second bars and
a maximum uptrend.
The values in the output window are not what I thought they would be (???).
Of course I tend to make mistakes. If anyone thinks the images are
right or wrong feel free to post.

Also a downtrend image is enclosed.

-Stephen

Ninja B
07-23-2008, 06:12 AM
Thanks Gumprhie, Elliott Wave, timmyb, and everybody else in this thread. So much info.

Thanks again. This is a great thread

rlotz
08-12-2008, 11:52 AM
Nice work Tiimy, but I'm having trouble changing the color and size of th indicator dots. Tahnks again for your work.

dwalls
08-12-2008, 01:41 PM
stephenszpak,
Or anyone. How do I get that Output window up to show the values,
like in your pictures.

Thanks

NinjaTrader_Ben
08-12-2008, 01:44 PM
Hello,

You can find this by going to Tools>Output window from your control center.

dwalls
08-12-2008, 01:51 PM
Hello Ben,
Thanks for the quick response.
I open up the output window but nothing displays in it.
How do I get something to display in it?
Like the slope values shown below or another indicators values?

Thanks

NinjaTrader_Ben
08-12-2008, 02:02 PM
Hello,

You are welcome.

Use Print(your_val_here); or Print("test");

This link will assist you with Print():
http://www.ninjatrader-support.com/HelpGuideV6/Print.html

dwalls
08-12-2008, 06:26 PM
Ben,
If I wanted to have the value of a regular EMA go to the output window, what are the changes to the code below to make that happen?
Normal EMA code is below.
Use the : Print()
Like:// Prints the current bar EMA value to the output window
Print(EMA(Close, 34)[0]);

Thanks for you help.




///<summary>
/// Exponential Moving Average. The Exponential Moving Average is an indicator that shows the average value of a security's price over a period of time. When calculating a moving average. The EMA applies more weight to recent prices than the SMA.
///</summary>
[Description("The Exponential Moving Average is an indicator that shows the average value of a security's price over a period of time. When calculating a moving average. The EMA applies more weight to recent prices than the SMA.")]
publicclass EMA : Indicator
{
#region Variables
privateint period = 14;
#endregion
///<summary>
/// This method is used to configure the indicator and is called once before any bar data is loaded.
///</summary>
protectedoverridevoid Initialize()
{
Add(new Plot(Color.Orange, "EMA"));
Overlay = true;
PriceTypeSupported = true;
}

///<summary>
/// Called on each bar update event (incoming tick)
///</summary>
protectedoverridevoid OnBarUpdate()
{
Value.Set(CurrentBar == 0 ? Input[0] : Input[0] * (2.0 / (1 + Period)) + (1 - (2.0 / (1 + Period))) * Value[1]);
}
#region Properties
///<summary>
///</summary>
[Description("Numbers of bars used for calculations")]
[Category("Parameters")]
publicint Period
{
get { return period; }
set { period = Math.Max(1, value); }
}
#endregion
}
}

NinjaTrader_Ben
08-13-2008, 08:09 AM
Hello,

You will want to place Print(EMA(Close, 34)[0]); within the OnBarUpdate() block to print the current value of the EMA.

dwalls
08-13-2008, 07:33 PM
Great, Thanks Ben

anachronist
08-19-2008, 09:59 AM
If anyone's interested, I posted a super fast calculation for regression slope in the indicator file area, called LinRegSlopeSFX. It calculates the slope of a regression line two ways, one way gives identical results to the traditional method, and another way uses exponential moving averages in lieu of sums.

I never liked the built-in Slope() method. It basically returns momentum divided by intervals. True slope is the slope of the best-fit line, i.e. the slope of a regression line. That's what LinRegSlopeSFX returns.

-Alex

stefy
08-20-2008, 08:27 AM
Hi everyone

I just noticed this post... maybe I missed something... did anyone post yet an indicator plotting the Linear Regression slope in degrees (classic range -90 / 90 or -45 / 45 degrees rather than numbers)?

Thank you

anachronist
08-20-2008, 08:56 AM
I just noticed this post... maybe I missed something... did anyone post yet an indicator plotting the Linear Regression slope in degrees (classic range -90 / 90 or -45 / 45 degrees rather than numbers)?
That would be meaningless, because (a) the vertical and horizontal scaling of a chart is arbitrary, and (b) the units of the x and y axes are different. The only time you can validly get degrees is if the units on both axes are the same.
-Alex

stefy
08-21-2008, 07:50 AM
Right, anachronist, but random values like 0.005 plotted on the slope chart are useless to me. Does it mean the slope is steep? How can I determine this? Someone could offer an example of how to use the slope (and its values) in a useful way?

Thank you everyone

anachronist
08-21-2008, 08:38 AM
Right, anachronist, but random values like 0.005 plotted on the slope chart are useless to me. Does it mean the slope is steep? How can I determine this?
Stefy, the same argument can be said for angle, because you have no objective way of determining if an angle is "steep". Is 45° steep? How about 50°? What about 30°? Larger angles are merely steeper than smaller angles. Similarly, larger slopes are steeper than smaller slopes.

Because you need the same units on both axes, and the same scaling on both axes for slope to be meaningful, the only meaningful value is zero.

Even if you had the same units and scaling, you still wouldn't need degrees. Math.Atan(slope) gives you angle in radians, 180.0/Math.PI*radians gives you degrees. A slope of 1.0 is the same as 45° (when horizontal and vertical movement are equal).

But degrees mean nothing when you have time on one axis and price on another. If you got a slope of 1.0, that wouldn't be an angle, it simply means that price changes at a rate of 1 price unit per bar -- whatever a "price unit" is for your market (a dollar, a tick, a multiple of ticks, or something adaptive - see below).

Someone could offer an example of how to use the slope (and its values) in a useful way?There are several ways in which slope can be useful:

1. You could define a "price unit" as an expected average displacement of price per bar in a trend. This would be different for each market. Then slope would tell you if a trend is steeper or shallower than expected for that market. One useful definition of expected slope would be a random-walk definition: take the standard deviation of (Close[0]-Close[1]) over N bars (ending with Close[N-1]-Close[N]) where N is large. The expected slope of m-bar trends would be this standard deviation multiplied by Math.Sqrt(m-1)/(m-1). Now, if you calculate slope over m bars, you can compare it with your expectation to determine if the market is trending more steeply relative to what you'd expect from a random walk.

2. You might use a zero crossing (when slope goes from positive to negative, or negative to positive) to indicate a change in trend direction.

3. Slope is also useful as an oscillator. If you plot slope as an indicator, you will see that it occupies a range of values. This range will be different for each market because the price scales are different. When the slope is near its maximum historical value, or near its minimum historical value, it's "steep".

4. You could use slopes of different lengths as a crossover signal, similar to MACD.

5. Any oscillator such as slope can be used for divergence signals.

6. I have used slope and intercept to get an equation for a regression line, from which I calculate price deviations over an interval, and I use those deviations as a noise measurement, from which I built adaptive indicators.

Hope that gives some ideas. No guarantee any of them will be profitable.
-Alex

NinjaTrader_Ray
08-21-2008, 09:05 AM
Thanks Alex, very on point.

Mindset
11-03-2008, 10:03 AM
[QUOTE=dwalls;12734]Gumphrie,


Put this in the initialize() section


if (TickSize.ToString().StartsWith("1E-"))

{
Digits=Convert.ToInt32(TickSize.ToString().Substri ng(3));
}
else if (TickSize.ToString().IndexOf(".")>0)
{
Digits=TickSize.ToString().Substring(TickSize.ToSt ring().IndexOf("."),TickSize.ToString().Length-1).Length-1;
}

And add this to your OnBarUpdate()

string dec = "N" + Digits.ToString();

Then you can simply code your actual string output using the following

string myoutputstring.ToString(dec);


Borrowed the initialize section from one of the samples (StatusBox) and just amended it to my own ends. I am not a programmer so I can't decipher or help with what it does ; but the output is the no of decimal points the symbol seems to require.
The string addition is all my own!

Gumphrie
11-03-2008, 11:24 AM
Borrowed the initialize sectiont from one of the samples

Think I remember writing that one, don't forget to initialize/declare Digits as 0 or it'll break.

Mindset
11-03-2008, 11:36 AM
Think I remember writing that one, don't forget to initialize/declare Digits as 0 or it'll break.

private int Digits = 0;

Apologies Gumphrie I couldn't remember who wrote StatusBox which I found a couple of weeks ago.
It is v useful having code that works - deciphering it is hard ( I am still waiting for my C# book to arrive) - I guess it's a little like learning to fly - I am still scrabbling to leave the gate!

gabga100
10-22-2009, 02:49 PM
Couldn't you also just use some math to determine the angle? Slope of 1 is 45 degrees and slope of -1 is -45. Slope of 0 is 0 degrees. You don't have to worry about 90 or -90 because those won't exist on a chart.

Basically just use m=tan θ where m is the slope and θ is the degrees.

Example
(System.Math.Atan(Slope(SMA(5),CurrentBar-1,CurrentBar))*180/Math.PI).ToString()
This will give you the angle in degrees of an SMA.


So waht is ithe good way to use the slope function ( I just want the slope from last period to this period and let's assume teh current bar = 20

According to the user guide I should get it like that

Slope(IDataSeries series,1, 0) (if we want the last available slope)

here 1> 0

According to this post :

Slope(IDataSeries series,CurrentBar-1, CurrentBar)

Slope(IDataSeries series,19, 20)

19 < 20

What is the correct way ?

Thank You

NinjaTrader_Josh
10-22-2009, 03:20 PM
Should be startBarsAgo and then endBarsAgo.

luxurious_04
01-23-2011, 05:45 PM
Hello dwall please help me also on the plotting of slope in different charts because I have also the same problem about the ticksize. Please send me LSMA and share the code.:confused:

Benluk
02-18-2012, 07:04 PM
I just find this indicator here and import to NJ v7. I see a box and a degree on the right-hand bottom of the screen. When I scroll the chart to previous hours or days, the degree inside the box does not change.

What do I need to do to see an updated slope when I scroll my chart for studying?