NexusFi: Find Your Edge


Home Menu

 





Code Snippets needed!


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one zeller4 with 5 posts (9 thanks)
    2. looks_two jackyd with 2 posts (4 thanks)
    3. looks_3 slacker with 2 posts (4 thanks)
    4. looks_4 Saroj with 1 posts (0 thanks)
      Best Posters
    1. looks_one slacker with 2 thanks per post
    2. looks_two jackyd with 2 thanks per post
    3. looks_3 zeller4 with 1.8 thanks per post
    4. looks_4 Trader.Jon with 1 thanks per post
    1. trending_up 6,863 views
    2. thumb_up 18 thanks given
    3. group 6 followers
    1. forum 11 posts
    2. attach_file 0 attachments




 
Search this Thread

Code Snippets needed!

  #1 (permalink)
 zeller4 
Orlando Florida
 
Experience: Intermediate
Platform: NT8
Trading: CL, NQ, ES, RTY
Posts: 477 since Jun 2009
Thanks Given: 1,416
Thanks Received: 404

Hello Mike and all,

Mike, I'm not sure how the download section for code snippets will work since most snippets I've seen are only a portion of a working code...

My programming experience came from finding indicators built-in to NT or on the NT support forum (that I could then rename with a _v01) and then proceed to try new things that I was learning at the time. I started using the wizard several months ago and am now able to customize some of the indicators and strategies that I like to use.

I'd appreciate others sharing code snippets that you find worthwhile. I'll share a couple things I like to use here and in the following posts:

PLOTTING LINES OF VARIOUS SIZE / COLOR
 
Code
 
Add(new Plot(Color.FromKnownColor(KnownColor.Green), PlotStyle.Line, "Plot1"));
 
or

Add(new Plot(Color.Orange, "HMA"));
This shows up with line width 1 and may be too narrow to see well plus I never understood "FromKnownColor" purpose.

or
 
Code
Add(new Plot(Color.Blue, "EMAup"));
Plots[0].Pen.Width = 3;
Plots[0].Pen.DashStyle = DashStyle.Dash;
3 lines of code required...

 
Code
Add(new Plot(new Pen(Color.Green,3), PlotStyle.Line, "ChannelHigh"));
 
- okay, now I've got the line width built-in to the plot command...

For newbies the process of learning how to get things to plot are quite a challenge - i.e. the difference required when using DashStyle.Dash and PlotStyle.Line. I can't begin to calculate how many hours I spent trying to get plots to work... Plotting in Strategies is another matter...

Kirk

Started this thread Reply With Quote
Thanked by:

Can you help answer these questions
from other members on NexusFi?
Trade idea based off three indicators.
Traders Hideout
Quant vue
Trading Reviews and Vendors
NT7 Indicator Script Troubleshooting - Camarilla Pivots
NinjaTrader
MC PL editor upgrade
MultiCharts
Pivot Indicator like the old SwingTemp by Big Mike
NinjaTrader
 
  #2 (permalink)
 zeller4 
Orlando Florida
 
Experience: Intermediate
Platform: NT8
Trading: CL, NQ, ES, RTY
Posts: 477 since Jun 2009
Thanks Given: 1,416
Thanks Received: 404

ALERT SOUNDS
 
Code
PlaySound(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\NinjaTrader 6.5\\sounds\\alarma_submarino.wav");
 
If your code is set up and all you hear is the incessant alarm going off, you may need to use "FirstTickOfBar":
 
Code
if (CurrentBar == 0 && FirstTickOfBar)
{
PlaySound(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\NinjaTrader 6.5\\sounds\\Train.wav");
 
}
You can find several resources here and on the NT support forum for alerts.

Try them on your basic script routines and you'll learn where / where not to use them.
Kirk

Started this thread Reply With Quote
Thanked by:
  #3 (permalink)
 zeller4 
Orlando Florida
 
Experience: Intermediate
Platform: NT8
Trading: CL, NQ, ES, RTY
Posts: 477 since Jun 2009
Thanks Given: 1,416
Thanks Received: 404


PLOTTING GRAPHICS / DOTS, DIAMONDS, TRIANGLES, etc.
Do you like basic dots?
 
Code
DrawDot("Dot",false,0,0,Color.Blue);
or
 
Code
DrawDiamond("Down Diamond" + CurrentBar, 0, SMA(20)[0], Color.Magenta);//I like to name them what their purpose or color is
DrawTriangleDown("Down Triangle" + CurrentBar,0,LinReg(High,(7))[0],Color.Aqua);
 
Or enhanced "larger" dots or different shapes
In Variables
 
Code
private Font textFontBig = new Font("Arial", 16);
private Font textFontMedium = new Font("Arial", 14);
private Font textFontSmall = new Font("Arial", 10);
private Font textFontSymbol = new Font("Webdings", 20);//"a" is checkmark
private Font textFontSymbolWing = new Font("Wingdings", 12);//"l" is a circle
see continued section below...

Started this thread Reply With Quote
Thanked by:
  #4 (permalink)
 zeller4 
Orlando Florida
 
Experience: Intermediate
Platform: NT8
Trading: CL, NQ, ES, RTY
Posts: 477 since Jun 2009
Thanks Given: 1,416
Thanks Received: 404

...continued from previous post...

if you look at your character map for these different fonts (Webdings, Wingdings, etc.), you'll soon see some useful graphics that will help highlight your charts. You just have to figure out what keystroke is required to give you the desired symbol.

In OnBarUpdate for a larger Wingdings "l" (small-case L) solid circle,
 
Code
DrawText("DotBlue"+CurrentBar, false, "l", 0, Low[0]-6*TickSize, Color.Blue, textFontSymbolWing, 
StringAlignment.Center, Color.Empty, Color.Empty, 10);
 
This allows you to use the font size from variables to make as large as you need.

Kirk

Started this thread Reply With Quote
Thanked by:
  #5 (permalink)
 
jackyd's Avatar
 jackyd 
Calgary Canada
 
Experience: Intermediate
Platform: Ninja
Broker: IB/Kinetic
Trading: 6E, CL
Posts: 47 since Jun 2009
Thanks Given: 44
Thanks Received: 20

Good idea zeller. Here's some code I came up with from various samples to give me some peace of mind if you were to run your strategies unattended. (in case I ever have a strategy that makes money!!!)

This is probably very simplistic and old hat for many, but hopefully it will help someone. It can be easily personalized with your own messages, input variables, etc.

 
Code
// At the start of a new session calculate the prior cum profit so it won't be included in the 
// calculation. Need this for historical testing.
if (Bars.FirstBarOfSession)
	{priorCumProfit = Performance.AllTrades.TradesPerformance.Currency.CumProfit;}

// *** Calculate the toal profit (cumulative profit minus prior profit plus the current position profit 
double myMaxProfit = (double) 1000;
double myMaxLoss = (double) -1000;
double cumProfit = (double) Performance.AllTrades.TradesPerformance.Currency.CumProfit;
double curPosition = (double) Position.GetProfitLoss(Close[0], PerformanceUnit.Currency);
double totCumProfit = (double) cumProfit - priorCumProfit + curPosition ;
			
// *** STOP the strategy! if a total profit or loss exceeds the max
if (totCumProfit <= myMaxLoss || totCumProfit >= myMaxProfit)
	{
	if (Position.MarketPosition == MarketPosition.Long) {ExitLong("DMA: Exit Long - max Profit/Loss exceeded", "");}
	if (Position.MarketPosition == MarketPosition.Short) {ExitShort("DMA: Exit Short - max Profit/Loss exceeded", "");}
	Print(Time[0] + ": EXIT STRATEGY - Max Profit/Loss exceeded: $" + myMaxProfit + "/$" + myMaxLoss + ", Current: $" + totCumProfit);
	return;
	}

Reply With Quote
Thanked by:
  #6 (permalink)
 zeller4 
Orlando Florida
 
Experience: Intermediate
Platform: NT8
Trading: CL, NQ, ES, RTY
Posts: 477 since Jun 2009
Thanks Given: 1,416
Thanks Received: 404

Thanks jackyd,

only questions I have before trying,

where in OnBarUpdate do you place this, near bottom after trades are placed?
or is there some critical items to address before or after?

I understand about the variables to define...

kz

Started this thread Reply With Quote
  #7 (permalink)
 
jackyd's Avatar
 jackyd 
Calgary Canada
 
Experience: Intermediate
Platform: Ninja
Broker: IB/Kinetic
Trading: 6E, CL
Posts: 47 since Jun 2009
Thanks Given: 44
Thanks Received: 20

You're welcome. I place it at the very top of OnBarUpdate as a standard first thing it always checks for. Also, keep in mind that it doesn't actually stop the strategy, but only prevents it from taking any more trades for that session, which is also necessary so that it doesn't interfere with backtesting.

Reply With Quote
  #8 (permalink)
 
Saroj's Avatar
 Saroj 
Arcata, CA
 
Experience: Intermediate
Platform: NinjaTrader
Trading: index futures, oil
Posts: 485 since Jun 2009
Thanks Given: 232
Thanks Received: 415

I'm still mulling over how to provide a "store" of code snippets in a way that makes them easy to find and easy to figure out how to integrate into a custom code file... within the futures.io (formerly BMT) forum construct... (or possibly "without" - in the mathematical sense - it may be best to create a wiki type environment which can be linked to from within futures.io (formerly BMT)).

An example is the one I did on how to code sound alerts.. but that takes a lot of time and I wouldn't want to require that from all contributors... however there is no question that we need categories to organize them... "fundamentals"; "data definitions and usage"; "plotting and drawing"; "referencing objects from other code files"; "performance tips and tricks"; "order handling", etc.

Any and all ideas are welcomed.

Reply With Quote
  #9 (permalink)
 
Mindset's Avatar
 Mindset 
Singapore
 
Experience: Intermediate
Platform: NT
Broker: ib
Trading: MES
Posts: 365 since Sep 2009
Thanks Given: 90
Thanks Received: 291

Programming some code today I discovered an error that is unusual and took me a while to solve.

Very occasionally on an IB feed I noticed that my entryprice vs current price in ticks was out by 1 ie 10t profit was showing as 9t in my code but NOT all the time.
Eventually I reasoned that it's due to some internal rounding that NT does. It is most noticeable on forex futures eg 6E.

The solution seems messy but it does work

price = Close[0] or whatever you want;


 
Code
val = RoundPrice(Math.Abs((price - entryprice)))/TickSize;
//solves rounding issue
Obviously for a short position you would invert the above code (entryprice - price)

Here is the function code for RoundPrice

 
Code
//RoundPrice(Round2TickSize)
public Double RoundPrice ( double price) 
{
return base.Bars.Instrument.MasterInstrument.Round2TickSize(price);
}

Reply With Quote
  #10 (permalink)
 
Trader.Jon's Avatar
 Trader.Jon 
Near the BEuTiFULL Horse Shoe
 
Experience: Beginner
Platform: NinjaTrader
Broker: MBTrading Dukascopy ZenFire
Trading: $EURUSD when it is trending
Posts: 473 since Jul 2009
Thanks Given: 401
Thanks Received: 184


Not exactly a code snippet, yet ...

NT Support recommends that any indicator that is used within a strategy NOT have any reference to CalculateOnBarClose ...

I looked at a random sample of the default indicators and they do not have COBC in their code. I tried it myself for backtesting a strategy and it does make a small difference in outputs (depending on the complexity of the indicator)

YMMV !!

Jon

Reply With Quote
Thanked by:




Last Updated on June 20, 2011


© 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