NexusFi: Find Your Edge


Home Menu

 





Anyone have any hints for optimizing C# code?


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one Zondor with 20 posts (21 thanks)
    2. looks_two ZTR with 13 posts (0 thanks)
    3. looks_3 Richard with 11 posts (20 thanks)
    4. looks_4 gomi with 7 posts (15 thanks)
      Best Posters
    1. looks_one Fat Tails with 2.6 thanks per post
    2. looks_two gomi with 2.1 thanks per post
    3. looks_3 Richard with 1.8 thanks per post
    4. looks_4 Zondor with 1.1 thanks per post
    1. trending_up 48,729 views
    2. thumb_up 108 thanks given
    3. group 39 followers
    1. forum 111 posts
    2. attach_file 13 attachments




 
Search this Thread

Anyone have any hints for optimizing C# code?

  #51 (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,103

I am impressed with all the contributions in this thread. I will read this again and try to make use of it...

However, the real problems I had with NT 7 so far, came from another source. My NT sometimes used more than 50% of the CPU, when I had added some custom indicators to various charts of my workspace, although all the indicators were in CalculateOnBarClose = "True" mode.

The reason for the high CPU usage was the customized plot. The custom plots are calculated for every incoming tick, and this can have a huge impact on performance.

The solution here is to define an external method, which writes the new input values to a DataSeries or arrays object, and then let the Plot Override check for changed values, before performing the calculations.

Reply With Quote
Thanked by:

Can you help answer these questions
from other members on NexusFi?
How to apply profiles
Traders Hideout
REcommedations for programming help
Sierra Chart
Cheap historycal L1 data for stocks
Stocks and ETFs
MC PL editor upgrade
MultiCharts
NT7 Indicator Script Troubleshooting - Camarilla Pivots
NinjaTrader
 
  #52 (permalink)
 
Zondor's Avatar
 Zondor 
Portland Oregon, United States
 
Experience: Beginner
Platform: NinjatraderŽ
Broker: CQG, Kinetick
Trading: Gameplay KlownbineŽ Trading of Globex
Posts: 1,333 since Jul 2009
Thanks Given: 1,246
Thanks Received: 2,731

Great participation and help from everyone who has been visiting here lately!

I attempted to incorporate Richard's latest suggestions into the DoubleStochasticOptimized. I posted it briefly until I realized it had problems. Will re-post after it is fixed.

Regarding previous post by FatTails, if the PlotGraphics method is used, the update frequency can be throttled back by having a minimum millisecond value between screen refreshes, as is done in the RealStats indicator.


if (lastRefresh.AddMilliseconds(LevelIIRefreshDelay) < DateTime.Now){

lastRefresh = DateTime.Now;
}

It looks like the two biggest drains on performance are excessive graphics demand, and excessive and redundant use of calls to external indicators. Addressing both as applicable is very productive, especially combined with the efficiency improvements of NT7.

Follow me on Twitter Visit my NexusFi Trade Journal Reply With Quote
Thanked by:
  #53 (permalink)
 
Zondor's Avatar
 Zondor 
Portland Oregon, United States
 
Experience: Beginner
Platform: NinjatraderŽ
Broker: CQG, Kinetick
Trading: Gameplay KlownbineŽ Trading of Globex
Posts: 1,333 since Jul 2009
Thanks Given: 1,246
Thanks Received: 2,731


This version of the Double Stochastics has every coding trick I can think of.

All calls to external indicators are pre-instantiated.

It uses Richard's FastMAX and FastMin indicators instead of MIN and MAX.

Redundant p2 DataSeries from earlier version has been removed.

Calls to the FastMIN and FastMAX indicators can only happen during the first tick of a bar. And they are only called if the internal logic can no longer be sure of the actual minimum and maximum values. Usually it WILL be sure, and will not need to call these external indicators at all.

I consider this to be a coding exercise. Is it worth it? Not sure....



.... I am Ming the Merciless. I will RULE THE UNIVERSE!

Attached Files
Elite Membership required to download: DoubleStochasticsOptimized.cs
Follow me on Twitter Visit my NexusFi Trade Journal Reply With Quote
  #54 (permalink)
 gomi 
Paris
Market Wizard
 
Experience: None
Platform: NinjaTrader
Posts: 1,270 since Oct 2009
Thanks Given: 282
Thanks Received: 4,505

Another hint : if you use collections in your code, you have to beware of the complexity of access/insert the data.

Here are the objects I use the most


Most simple object is List
  • It's basically a checked, autogrowing ,and typed, array.
  • Access/Read is very quick (if you access by index of course)
  • You can sort the List, which is o(n log n) complexity

Then you have the Dictionary
  • It's a generic and typed Hashtable.
  • Access/Read is o(1) complexity, meaning access time doesn't depend on the size of the Dictionary, and is very quick (obviously less than an array as there is the hashing stuff to compute)

Then you have the sorted objects : SortedList and SortedDictionary
  • SortedList and SortedDictionary have o(log n) access
  • SortedList has o(n) insert, SortedDictionary has o(log n) insert
  • You can access SortedList by index (not possible with Dictionary)


So you have to remember if you're accessing tick data that you will be manipulating large structures, so choose the object with the less complexity that fits your need.

In special cases, if you do lots of random inserts and modifcations, and very rarely you need to access the sorted values, it can be quicker to use a List and sort it when needed than using a SortedList

Reply With Quote
Thanked by:
  #55 (permalink)
 
ZTR's Avatar
 ZTR 
 
Experience: Advanced
Platform: NinjaTrader7
Broker: Mirus RCG/Zen-Fire
Trading: CL & 6e, looking at ES, ZB and AU again.
Posts: 2,096 since Nov 2009
Thanks Given: 1,099
Thanks Received: 1,393

Since this is an answer box & can just click thanks.

Thank you Gomi.

R.I.P. Andy Zektzer (ZTR), 1960-2010.
Please visit this thread for more information.
Visit my NexusFi Trade Journal Started this thread Reply With Quote
  #56 (permalink)
Richard
Dallas TX/USA
 
Posts: 153 since Jun 2009
Thanks Given: 33
Thanks Received: 284


Zondor View Post
This version of the Double Stochastics has every coding trick I can think of.

Since MAX and MIN maintain the max and min, I'm not sure why the indicator code keeps checking to see if the low is lower than the minLow[0]... if it's working correctly it never should be... so without running the code, I imagine OnBarUpdate() should look more like this:

 
Code
double r = maxHigh[0] - minLow[0];
p1.Set(((Close[0] - minLow[0]) / (r == 0 ? 1 : r)) * 100);
			
double s = maxpEMA[0] - minpEMA[0];
p3.Set(((pEMA[0] - minpEMA[0]) / (s == 0 ? 1 : s)) * 100);
K.Set(kEMA[0]);
			
if(Rising(K))PlotColors[0][0]=upColor;
if(Falling(K))PlotColors[0][0]=downColor;
much simpler. Maybe I misunderstood something, but glancing at the code that's what it looks like to me.

Reply With Quote
Thanked by:
  #57 (permalink)
 
ZTR's Avatar
 ZTR 
 
Experience: Advanced
Platform: NinjaTrader7
Broker: Mirus RCG/Zen-Fire
Trading: CL & 6e, looking at ES, ZB and AU again.
Posts: 2,096 since Nov 2009
Thanks Given: 1,099
Thanks Received: 1,393

Richard are you willing to do a Webinar?

R.I.P. Andy Zektzer (ZTR), 1960-2010.
Please visit this thread for more information.
Visit my NexusFi Trade Journal Started this thread Reply With Quote
  #58 (permalink)
 MXASJ 
Asia
 
Experience: Beginner
Platform: NinjaTrader, TOS
Posts: 796 since Jun 2009
Thanks Given: 109
Thanks Received: 800

Hi guys,

I'm still trying to get my head around this, so can you guys help me with something simple? An example of something that I find to be painfully slow is a Market Analyzer grid I use every week or so that looks at the 14, 21, 50, and 200 day ROC of a basket of roughly 70 ETFs. The default ROC code is this:

 
Code
                            
protected override void OnBarUpdate()
{
int barsAgo Math.Min(CurrentBarPeriod);
Value.Set(((Input[0] - Input[barsAgo]) / Input[barsAgo]) * 100);

Is there an example of how this code could be optimized? I'm still not getting what types of calculations should be taken out of OnBarUpdate... or am I totally missing something? Thanks for the enlightenment.

Attached Thumbnails
Click image for larger version

Name:	NinjaTrader Grid 2010-05-28 10_38 AM.jpg
Views:	319
Size:	239.8 KB
ID:	14436  
Reply With Quote
  #59 (permalink)
 
Zondor's Avatar
 Zondor 
Portland Oregon, United States
 
Experience: Beginner
Platform: NinjatraderŽ
Broker: CQG, Kinetick
Trading: Gameplay KlownbineŽ Trading of Globex
Posts: 1,333 since Jul 2009
Thanks Given: 1,246
Thanks Received: 2,731

protected override void OnBarUpdate()
{
int barsAgo = Math.Min(CurrentBar, Period);
Value.Set(((Input[0] - Input[barsAgo]) / Input[barsAgo]) * 100);
}


The above will execute every time a BarUpate is triggered. However, during the lifetime of a bar, the value of CurrentBar never changes. So after executing the first time, on successive updates to a bar, this statement is calculating the same thing over and over and over and over.... and over again.

It should only execute ONCE per bar, as soon as a new bar starts.... ie on FirstTickOfBar.

So try this, (and before doing the division on the Value.Set line, be sure that the value of the denominator cannot be zero)


protected override void OnBarUpdate()
{
if(FirstTickOfBar)
{
int barsAgo = Math.Min(CurrentBar, Period);
Value.Set(((Input[0] - Input[barsAgo]) / Input[barsAgo]) * 100);
}
}





I am MING THE MERCILESS. I will RULE THE UNIVERSE!

Follow me on Twitter Visit my NexusFi Trade Journal Reply With Quote
Thanked by:
  #60 (permalink)
 MXASJ 
Asia
 
Experience: Beginner
Platform: NinjaTrader, TOS
Posts: 796 since Jun 2009
Thanks Given: 109
Thanks Received: 800


Thanks Zondor,

I get the FirstTickOfBar thing if CalculateOnBarClose == false, but in this particular case its historical EOD data.

In retrospect, my performance issue is probably because I'm calling up four indicators per instrument (one each for the 14, 21, 50, and 200 ROC), on roughly 90 instruments.

So perhaps that was a poor choice on my part to use an example.

Let me look at some of the code posted here and I'll post back if I'm still confused.

Reply With Quote




Last Updated on December 24, 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