NexusFi: Find Your Edge


Home Menu

 





NinjaScript Little Helpers Code Share - Snippets/UserDefinedMethods


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one gregid with 13 posts (28 thanks)
    2. looks_two bltdavid with 12 posts (17 thanks)
    3. looks_3 Fat Tails with 3 posts (8 thanks)
    4. looks_4 ratfink with 2 posts (1 thanks)
      Best Posters
    1. looks_one Fat Tails with 2.7 thanks per post
    2. looks_two gregid with 2.2 thanks per post
    3. looks_3 timefreedom with 2 thanks per post
    4. looks_4 bltdavid with 1.4 thanks per post
    1. trending_up 10,701 views
    2. thumb_up 61 thanks given
    3. group 11 followers
    1. forum 34 posts
    2. attach_file 3 attachments




 
Search this Thread

NinjaScript Little Helpers Code Share - Snippets/UserDefinedMethods

  #11 (permalink)
 
Fat Tails's Avatar
 Fat Tails 
Berlin, Europe
Market Wizard
 
Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker: Interactive Brokers
Trading: Keyboard
Posts: 9,888 since Mar 2010
Thanks Given: 4,242
Thanks Received: 27,102


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
Thanked by:

Can you help answer these questions
from other members on NexusFi?
What is Markets Chat (markets.chat) real-time trading ro …
Trading Reviews and Vendors
MC PL editor upgrade
MultiCharts
Exit Strategy
NinjaTrader
Pivot Indicator like the old SwingTemp by Big Mike
NinjaTrader
How to apply profiles
Traders Hideout
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Just another trading journal: PA, Wyckoff & Trends
30 thanks
Spoo-nalysis ES e-mini futures S&P 500
28 thanks
Tao te Trade: way of the WLD
24 thanks
Bigger Wins or Fewer Losses?
20 thanks
GFIs1 1 DAX trade per day journal
16 thanks
  #12 (permalink)
 bltdavid 
San Jose, CA, USA
 
Experience: Intermediate
Platform: NinjaTrader
Posts: 112 since Dec 2013
Thanks Given: 35
Thanks Received: 103


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));
        }

Reply With Quote
  #13 (permalink)
 bltdavid 
San Jose, CA, USA
 
Experience: Intermediate
Platform: NinjaTrader
Posts: 112 since Dec 2013
Thanks Given: 35
Thanks Received: 103


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
Thanked by:
  #14 (permalink)
 bltdavid 
San Jose, CA, USA
 
Experience: Intermediate
Platform: NinjaTrader
Posts: 112 since Dec 2013
Thanks Given: 35
Thanks Received: 103

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; }
}

Reply With Quote
Thanked by:
  #15 (permalink)
 bltdavid 
San Jose, CA, USA
 
Experience: Intermediate
Platform: NinjaTrader
Posts: 112 since Dec 2013
Thanks Given: 35
Thanks Received: 103

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
Thanked by:
  #16 (permalink)
 
aquarius's Avatar
 aquarius 
Monterrey, Mexico
 
Experience: Beginner
Platform: NinjaTrader
Trading: Treasuries
Posts: 22 since Nov 2012
Thanks Given: 5
Thanks Received: 69


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
Thanked by:
  #17 (permalink)
 
Fat Tails's Avatar
 Fat Tails 
Berlin, Europe
Market Wizard
 
Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker: Interactive Brokers
Trading: Keyboard
Posts: 9,888 since Mar 2010
Thanks Given: 4,242
Thanks Received: 27,102


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
Thanked by:
  #18 (permalink)
 bltdavid 
San Jose, CA, USA
 
Experience: Intermediate
Platform: NinjaTrader
Posts: 112 since Dec 2013
Thanks Given: 35
Thanks Received: 103


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 [AUTOLINK]Pivot[/AUTOLINK] Points

Reply With Quote
  #19 (permalink)
 
Fat Tails's Avatar
 Fat Tails 
Berlin, Europe
Market Wizard
 
Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker: Interactive Brokers
Trading: Keyboard
Posts: 9,888 since Mar 2010
Thanks Given: 4,242
Thanks Received: 27,102


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 [AUTOLINK]Pivot[/AUTOLINK] 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
  #20 (permalink)
 
gregid's Avatar
 gregid 
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
Posts: 650 since Aug 2009
Thanks Given: 320
Thanks Received: 623


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");
        }

Started this thread Reply With Quote
Thanked by:




Last Updated on May 15, 2015


© 2024 NexusFi™, s.a., All Rights Reserved.
Av Ricardo J. Alfaro, Century Tower, Panama City, Panama, Ph: +507 833-9432 (Panama and Intl), +1 888-312-3001 (USA and Canada)
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.
About Us - Contact Us - Site Rules, Acceptable Use, and Terms and Conditions - Privacy Policy - Downloads - Top
no new posts