NinjaScript Little Helpers Code Share - Snippets/UserDefinedMethods - NinjaTrader Programming | futures io social day trading
futures io futures trading


NinjaScript Little Helpers Code Share - Snippets/UserDefinedMethods
Updated: Views / Replies:3,686 / 34
Created: by gregid Attachments:3

Welcome to futures io.

(If you already have an account, login at the top of the page)

futures io is the largest futures trading community on the planet, with over 90,000 members. At futures io, our goal has always been and always will be to create a friendly, positive, forward-thinking community where members can openly share and discuss everything the world of trading has to offer. The community is one of the friendliest you will find on any subject, with members going out of their way to help others. Some of the primary differences between futures io and other trading sites revolve around the standards of our community. Those standards include a code of conduct for our members, as well as extremely high standards that govern which partners we do business with, and which products or services we recommend to our members.

At futures io, our focus is on quality education. No hype, gimmicks, or secret sauce. The truth is: trading is hard. To succeed, you need to surround yourself with the right support system, educational content, and trading mentors Ė all of which you can find on futures io, utilizing our social trading environment.

With futures io, you can find honest trading reviews on brokers, trading rooms, indicator packages, trading strategies, and much more. Our trading review process is highly moderated to ensure that only genuine users are allowed, so you donít need to worry about fake reviews.

We are fundamentally different than most other trading sites:
  • We are here to help. Just let us know what you need.
  • We work extremely hard to keep things positive in our community.
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts.
  • We firmly believe in and encourage sharing. The holy grail is within you, we can help you find it.
  • We expect our members to participate and become a part of the community. Help yourself by helping others.

You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

Reply
 3  
 
Thread Tools Search this Thread
 

NinjaScript Little Helpers Code Share - Snippets/UserDefinedMethods

  #11 (permalink)
Elite Member
Berlin, Europe
 
Futures Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker/Data: Interactive Brokers
Favorite Futures: Keyboard
 
Fat Tails's Avatar
 
Posts: 9,652 since Mar 2010
Thanks: 4,226 given, 25,601 received
Forum Reputation: Legendary


timefreedom View Post
Here is the code from @Fat Tails that displays treasury formats. Insert #region Miscellaneous after #region Properties.

This was indeed the original code that I had published. It had a little bug. Sometimes it would display 32'' instead of 31'' or 0''. Please use the modified code as per below:
 
Code
public override string FormatPriceMarker(double price)
{
	double trunc = Math.Truncate(price);
	int fraction = 0;
	string priceMarker = "";
	if (TickSize == 0.03125) 
	{
		fraction = Convert.ToInt32(32 * Math.Abs(price - trunc));	
		if (fraction < 10)
			priceMarker = trunc.ToString() + "'0" + fraction.ToString();
		else if(fraction == 32)
		{	
			trunc = trunc + 1;
			fraction = 0;
			priceMarker = trunc.ToString() + "'0" + fraction.ToString();
		}	
		else 
			priceMarker = trunc.ToString() + "'" + fraction.ToString();
	}
	else if (TickSize == 0.015625)
	{
		fraction = 5 * Convert.ToInt32(64 * Math.Abs(price - trunc));	
		if (fraction < 10)
			priceMarker = trunc.ToString() + "'00" + fraction.ToString();
		else if (fraction < 100)
			priceMarker = trunc.ToString() + "'0" + fraction.ToString();
		else if(fraction == 320)
		{	
			trunc = trunc + 1;
			fraction = 0;
			priceMarker = trunc.ToString() + "'00" + fraction.ToString();
		}	
		else	
			priceMarker = trunc.ToString() + "'" + fraction.ToString();
	}
	else if (TickSize == 0.0078125)
	{
		fraction = Convert.ToInt32(Math.Truncate(2.5 * Convert.ToInt32(128 * Math.Abs(price - trunc))));	
		if (fraction < 10)
			priceMarker = trunc.ToString() + "'00" + fraction.ToString();
		else if (fraction < 100)
			priceMarker = trunc.ToString() + "'0" + fraction.ToString();
		else if(fraction == 320)
		{	
			trunc = trunc + 1;
			fraction = 0;
			priceMarker = trunc.ToString() + "'00" + fraction.ToString();
		}	
		else	
			priceMarker = trunc.ToString() + "'" + fraction.ToString();
	}
	else
		priceMarker = price.ToString(Gui.Globals.GetTickFormatString(TickSize));
	return priceMarker;
}

Reply With Quote
The following 3 users say Thank You to Fat Tails for this post:
 
  #12 (permalink)
Elite Member
San Jose, CA, USA
 
Futures Experience: Intermediate
Platform: NinjaTrader, RCG/Continuum
Favorite Futures: GC,CL
 
Posts: 89 since Dec 2013
Thanks: 14 given, 89 received


timefreedom View Post
Here is the code from @Fat Tails that displays treasury formats. Insert #region Miscellaneous after #region Properties.

 
Code
		#region Miscellaneous

		public override string FormatPriceMarker(double price)
		{
			double trunc = Math.Truncate(price);
			int fraction = Convert.ToInt32(320 * Math.Abs(price - trunc) - 0.0001); // rounding down for ZF and ZT
			string priceMarker = "";
			if (TickSize == 0.03125) 
			{
				fraction = fraction/10;
				if (fraction < 10)
					priceMarker = trunc.ToString() + "'0" + fraction.ToString();
				else 
					priceMarker = trunc.ToString() + "'" + fraction.ToString();
			}
			else if (TickSize == 0.015625 || TickSize == 0.0078125)
			{
				if (fraction < 10)
					priceMarker = trunc.ToString() + "'00" + fraction.ToString();
				else if (fraction < 100)
					priceMarker = trunc.ToString() + "'0" + fraction.ToString();
				else	
					priceMarker = trunc.ToString() + "'" + fraction.ToString();
			}
			else
				priceMarker = price.ToString(Gui.Globals.GetTickFormatString(TickSize));
			return priceMarker;
		}		
		#endregion

Is that any different than FormatPrice?

 
Code
        public double Round2TickSize(double DoubleValue)
        {
            return Instrument.MasterInstrument.Round2TickSize(DoubleValue);
        }

        public string FormatPrice(double DoubleValue)
        {
            return Instrument.MasterInstrument.FormatPrice(Round2TickSize(DoubleValue));
        }


Last edited by bltdavid; April 3rd, 2015 at 10:43 PM. Reason: change access modifier 'private' to 'public'
Reply With Quote
 
  #13 (permalink)
Elite Member
San Jose, CA, USA
 
Futures Experience: Intermediate
Platform: NinjaTrader, RCG/Continuum
Favorite Futures: GC,CL
 
Posts: 89 since Dec 2013
Thanks: 14 given, 89 received


I use my "FormatMoney" routine to print money values.

An empty cents ".00" suffix is generally useless; I usually prefer to see "$2400" vs "$2,400.00". But if the cents are there, I print them.

I've also made commas optional by providing an overloaded method.

 
Code
public string FormatMoney(double Money)
{
    return FormatMoney(Money, false);
}

public string FormatMoney(double Money, bool WantCommas)
{
    string retval = String.Format("{0:C2}", Money);

    if (!WantCommas)
        retval = retval.Replace(",", String.Empty);

    return retval.Replace(".00", String.Empty);
}

Reply With Quote
The following user says Thank You to bltdavid for this post:
 
  #14 (permalink)
Elite Member
San Jose, CA, USA
 
Futures Experience: Intermediate
Platform: NinjaTrader, RCG/Continuum
Favorite Futures: GC,CL
 
Posts: 89 since Dec 2013
Thanks: 14 given, 89 received

For strategies that trade futures, I've standardized on accessing certain NinjaTrader values via these properties, which are descriptive and simply named.

 
Code
public string ContractBaseName {
    get { return Instrument.MasterInstrument.Name; }
}

public string ContractFullName {
    get { return Instrument.FullName; }
}

public DateTime ContractExpiration {
    get { return Instrument.Expiry; }
}

I've also found these useful,
 
Code
public int BarInterval {
    get { return BarsPeriod.Value; }
}

public string BarType {
    get { return BarsPeriod.Id.ToString(); }
}

public string BarSeries {
    get { return BarInterval.ToString() + "-" + BarType; }
}


Last edited by bltdavid; April 3rd, 2015 at 11:24 PM. Reason: damn, had to change 'private' to 'public' again
Reply With Quote
The following 3 users say Thank You to bltdavid for this post:
 
  #15 (permalink)
Elite Member
San Jose, CA, USA
 
Futures Experience: Intermediate
Platform: NinjaTrader, RCG/Continuum
Favorite Futures: GC,CL
 
Posts: 89 since Dec 2013
Thanks: 14 given, 89 received

I have about a dozen boolean variables and properties that all use the naming convention "IsStrategyXXX".

This family of variables and properties handles strategy wide conditions, and it all started with these three,
 
Code
public bool IsStrategyLong {
    get { return Position.MarketPosition == MarketPosition.Long; }
}

public bool IsStrategyShort {
    get { return Position.MarketPosition == MarketPosition.Short; }
}

public bool IsStrategyFlat {
    get { return Position.MarketPosition == MarketPosition.Flat; }
}

Define others as you see the need.

I have these as global booleans,

IsStrategyHalted
IsStrategyInited
IsStrategyStarted
IsStrategyPaused
IsStrategyDisabled
IsStrategyExiting
IsStrategyReversing
IsStrategyRunning
IsStrategyManual

and these as boolean properties,

IsStrategyIdle
IsStrategyLive
IsStrategyPerforming

I use IsStrategyIdle to know when it's safe to reverse a position. It looks like this,
 
Code
public bool IsStrategyIdle {
    get { return IsStrategyFlat && NoOrderPending; }
}

public bool NoOrderPending {
    get { return CountEntryOrders == 0 && CountStopOrders == 0 && CountTargetOrders == 0; }
}

You'll have to hookup the order counters yourself.

Reply With Quote
The following 2 users say Thank You to bltdavid for this post:
 
  #16 (permalink)
Elite Member
Monterrey, Mexico
 
Futures Experience: Beginner
Platform: NinjaTrader
Favorite Futures: Treasuries
 
aquarius's Avatar
 
Posts: 22 since Nov 2012
Thanks: 5 given, 69 received

Haven't tried it, though ...


Fat Tails View Post
This was indeed the original code that I had published. It had a little bug. Sometimes it would display 32'' instead of 31'' or 0''. Please use the modified code as per below:

I'd change a few lines, but that's just me ...

 
Code
        public override string FormatPriceMarker(double price)
        {
            double trunc = Math.Truncate(price);
            int fraction = 0;
            string priceMarker = string.Empty;
            if (TickSize == 0.03125)
            {
                fraction = Convert.ToInt32(32 * Math.Abs(price - trunc));
                if (fraction == 32)
                {
                    trunc = trunc + 1;
                    fraction = 0;
                }
                priceMarker = string.Format("{0}'{1:00}", trunc, fraction); 
            }
            else if (TickSize == 0.015625)
            {
                fraction = 5 * Convert.ToInt32(64 * Math.Abs(price - trunc));
                if (fraction == 320)
                {
                    trunc = trunc + 1;
                    fraction = 0;
                }
                priceMarker = string.Format("{0}'{1:000}", trunc, fraction); 
            }
            else if (TickSize == 0.0078125)
            {
                fraction = Convert.ToInt32(Math.Truncate(2.5 * Convert.ToInt32(128 * Math.Abs(price - trunc))));
                if (fraction == 320)
                {
                    trunc = trunc + 1;
                    fraction = 0;
                }
                priceMarker = string.Format("{0}'{1:000}", trunc, fraction); 
            }
            else
                priceMarker = price.ToString(Gui.Globals.GetTickFormatString(TickSize));
            return priceMarker;
        }

Reply With Quote
The following user says Thank You to aquarius for this post:
 
  #17 (permalink)
Elite Member
Berlin, Europe
 
Futures Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker/Data: Interactive Brokers
Favorite Futures: Keyboard
 
Fat Tails's Avatar
 
Posts: 9,652 since Mar 2010
Thanks: 4,226 given, 25,601 received
Forum Reputation: Legendary


aquarius View Post
I'd change a few lines, but that's just me ...

 
Code
        public override string FormatPriceMarker(double price)
        {
            double trunc = Math.Truncate(price);
            int fraction = 0;
            string priceMarker = string.Empty;
            if (TickSize == 0.03125)
            {
                fraction = Convert.ToInt32(32 * Math.Abs(price - trunc));
                if (fraction == 32)
                {
                    trunc = trunc + 1;
                    fraction = 0;
                }
                priceMarker = string.Format("{0}'{1:00}", trunc, fraction); 
            }
            else if (TickSize == 0.015625)
            {
                fraction = 5 * Convert.ToInt32(64 * Math.Abs(price - trunc));
                if (fraction == 320)
                {
                    trunc = trunc + 1;
                    fraction = 0;
                }
                priceMarker = string.Format("{0}'{1:000}", trunc, fraction); 
            }
            else if (TickSize == 0.0078125)
            {
                fraction = Convert.ToInt32(Math.Truncate(2.5 * Convert.ToInt32(128 * Math.Abs(price - trunc))));
                if (fraction == 320)
                {
                    trunc = trunc + 1;
                    fraction = 0;
                }
                priceMarker = string.Format("{0}'{1:000}", trunc, fraction); 
            }
            else
                priceMarker = price.ToString(Gui.Globals.GetTickFormatString(TickSize));
            return priceMarker;
        }

@aquarius: This code does exactly the same thing, but the formatting of the strings is visibly more elegant.

Thank you for posting it.

I recommend it over the code that I have posted.

Reply With Quote
The following user says Thank You to Fat Tails for this post:
 
  #18 (permalink)
Elite Member
San Jose, CA, USA
 
Futures Experience: Intermediate
Platform: NinjaTrader, RCG/Continuum
Favorite Futures: GC,CL
 
Posts: 89 since Dec 2013
Thanks: 14 given, 89 received


Fat Tails View Post
@aquarius: This code does exactly the same thing, but the formatting of the strings is visibly more elegant.

Thank you for posting it.

I recommend it over the code that I have posted.

I submit there is something even better: just use the builtin FormatPrice() method.

See my post here:
NinjaTrader Support Forum - Price marker format for T-Notes Futures Pivot Points

Reply With Quote
The following 4 users say Thank You to bltdavid for this post:
 
  #19 (permalink)
Elite Member
Berlin, Europe
 
Futures Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker/Data: Interactive Brokers
Favorite Futures: Keyboard
 
Fat Tails's Avatar
 
Posts: 9,652 since Mar 2010
Thanks: 4,226 given, 25,601 received
Forum Reputation: Legendary


bltdavid View Post
I submit there is something even better: just use the builtin FormatPrice() method.

See my post here:
NinjaTrader Support Forum - Price marker format for T-Notes Futures Pivot Points


@bltdavid: Good, this means that we can use inbuilt NinjaTrader methods that already exist to simplify the task.


My conclusion is that whenever you code an indicator in overlay mode - that is an indicator which is shown on the price panel - you should add the following lines of code:

 
Code
public override string FormatPriceMarker(double price)
{
     return Instrument.MasterInstrument.FormatPrice(Instrument.MasterInstrument.Round2TickSize(price));
}

This would do the same as my more cumbersome suggestion or the improved version from #17, as the method is alreay built into NinjaTrader. A simple solution certainly beats the complex one!

Reply With Quote
The following 4 users say Thank You to Fat Tails for this post:
 
  #20 (permalink)
Elite Member
Wrocław, Poland
 
Futures Experience: Intermediate
Platform: NinjaTrader, Racket
Favorite Futures: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 321 given, 605 received

Optional Formatting of TimeSpan


As I was writing g3ChartSpan indicator I needed a way of formatting the TimeSpan to optionally exclude some information if it == 0 and additionally give me some further info like years, months and weeks. I couldn't find anything generic that would satisfy my needs, so I ended up writing this simple method that gives me close enough approximation for the purpose of the indicator. So here is the code:

 
Code
        public static string OptionalFormat(TimeSpan ts)
        {
            var totalDays = ts.TotalDays;
            var years = (int)Math.Floor(totalDays / 365.25);
            var months = (int)Math.Floor((totalDays % 365.25) / 30.5);
            var weeks = (int)Math.Floor(((totalDays % 365.25) % 30.5 )/ 7);
            var days = (int)Math.Floor((((totalDays % 365.25) % 30.5 )% 7));
            return (years == 0 ? "" : years.ToString() + " Year" + (years == 1 ?", " :"s, "))
                    + (months == 0 ? "" : months.ToString() + " Month" + (months == 1 ? ", " : "s, "))
                    + (weeks == 0 ? "" : weeks.ToString() + " Week" + (weeks == 1 ? ", " : "s, "))
                    + (days == 0 ? "" : days.ToString() + " Day" + (days == 1 ? ", " : "s, "))
                    + (ts.Hours == 0 ? "" : ts.Hours.ToString("00") + "h")
                    + (ts.Minutes == 0 ? "" : ts.Minutes.ToString("00") + "m")
                    + (ts.Seconds == 0 ? "" : ts.Seconds.ToString("00") + "s");
        }

Reply With Quote
The following 2 users say Thank You to gregid for this post:

Reply



futures io > > > > > NinjaScript Little Helpers Code Share - Snippets/UserDefinedMethods

Thread Tools Search this Thread
Search this Thread:

Advanced Search



Upcoming Webinars and Events (4:30PM ET unless noted)

Jigsaw Trading: TBA

Elite only

FuturesTrader71: TBA

Elite only

NinjaTrader: TBA

Jan 18

RandBots: TBA

Jan 23

GFF Brokers & CME Group: Futures & Bitcoin

Elite only

Adam Grimes: TBA

Elite only

Ran Aroussi: TBA

Elite only
     

Similar Threads
Thread Thread Starter Forum Replies Last Post
vvhg's Little Helpers - Keeping Them In One Place vvhg The Elite Circle 32 January 7th, 2016 11:58 PM
Code TRX Channel for TOS (MT4 Code here) rommark ThinkOrSwim Programming 0 October 1st, 2014 04:55 PM
Code Snippets needed! zeller4 NinjaTrader Programming 11 June 20th, 2011 04:21 PM
code snippets Saroj Feedback and Announcements 1 September 11th, 2009 02:10 PM


All times are GMT -4. The time now is 04:33 PM.

Copyright © 2017 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
All information is for educational use only and is not investment advice.
There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
no new posts
Page generated 2017-12-13 in 0.13 seconds with 20 queries on phoenix via your IP 54.90.92.204