Anyone have any hints for optimizing C# code? - futures io
futures io futures trading



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 33,400 views
    2. thumb_up 108 thanks given
    3. group 40 followers
    1. forum 111 posts
    2. attach_file 13 attachments




Welcome to futures io: the largest futures trading community on the planet, with well over 125,000 members
  • Genuine reviews from real traders, not fake reviews from stealth vendors
  • Quality education from leading professional traders
  • We are a friendly, helpful, and positive community
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts
  • We are here to help, just let us know what you need
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

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

 
Search this Thread
 

Anyone have any hints for optimizing C# code?

(login for full post details)
  #101 (permalink)
Market Wizard
Berlin, Europe
 
Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker: Interactive Brokers
Trading: Keyboard
 
Fat Tails's Avatar
 
Posts: 9,855 since Mar 2010
Thanks: 4,238 given, 26,731 received


kbeary33 View Post
How would you go about this "economization" of indicators if you are using a multi-instrument strategy?

ie, if you declared

 
Code
class MyIndicator : Indicator {
private SMA sma1;
private SMA sma2;
...
protected void override OnStartup() {
sma1 = SMA(Close,5);
sma2 = SMA(Close, 13);
...
}
How could you then call sma1 or sma2 for a BarsArray[index] item?


This should work:

 
Code
protected void override OnStartup() 
{
       sma1 = SMA(Closes[index],5);
       sma2 = SMA(Closes[index], 13);
       ...
}

Reply With Quote
The following 5 users say Thank You to Fat Tails for this post:
 
(login for full post details)
  #102 (permalink)
Calgary AB
 
Experience: Intermediate
Platform: AmiBroker, IB
Broker: Interactive Brokers
Trading: Stocks
 
Posts: 10 since Mar 2013
Thanks: 5 given, 2 received

Thanks very much for the reply. I still don't quite get it though... Just to clarify, I am setting this up inside a strategy, not inside an Indicator (I don't know if that makes a difference)

Say that I have 10 instruments, and that I want to maintain a ranked list based on their current SMA. Should I somehow specify:


 
Code
//Inside variables:
private SMA sma1;
int numInstruments = 10;
int smaPeriod = 10;
...

//Inside OnStartup()  -> I know this won't work, I just wasn't sure how else to communicate what I was thinking...
for(int i = 0; i < numInstruments; i++);
sma1[i] = SMA(i,smaPeriod);
...

Or, can you somehow declare sma1 with :
 
Code
sma1 = SMA(Index Placeholder, smaPeriod)
...

double smaInstrument1 = sma1(0)[0];
double smaInstrument2 = sma1(1)[0];
double smaInstrument3 = sma1(2)[0];

Or, lastly, do you have to hard code:
 
Code
private SMA sma1;
private SMA sma2;
private SMA sma3;
...

sma1 = SMA(Closes[0],smaPeriod);
sma2 = SMA(Closes[1],smaPeriod);
sma3 = SMA(Closes[2],smaPeriod);

Reply With Quote
 
(login for full post details)
  #103 (permalink)
Market Wizard
Berlin, Europe
 
Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker: Interactive Brokers
Trading: Keyboard
 
Fat Tails's Avatar
 
Posts: 9,855 since Mar 2010
Thanks: 4,238 given, 26,731 received


kbeary33 View Post
Thanks very much for the reply. I still don't quite get it though... Just to clarify, I am setting this up inside a strategy, not inside an Indicator (I don't know if that makes a difference)

Say that I have 10 instruments, and that I want to maintain a ranked list based on their current SMA. Should I somehow specify:


 
Code
//Inside variables:
private SMA sma1;
int numInstruments = 10;
int smaPeriod = 10;
...

//Inside OnStartup()  -> I know this won't work, I just wasn't sure how else to communicate what I was thinking...
for(int i = 0; i < numInstruments; i++);
sma1[i] = SMA(i,smaPeriod);
...

Or, can you somehow declare sma1 with :
 
Code
sma1 = SMA(Index Placeholder, smaPeriod)
...

double smaInstrument1 = sma1(0)[0];
double smaInstrument2 = sma1(1)[0];
double smaInstrument3 = sma1(2)[0];

Or, lastly, do you have to hard code:
 
Code
private SMA sma1;
private SMA sma2;
private SMA sma3;
...

sma1 = SMA(Closes[0],smaPeriod);
sma2 = SMA(Closes[1],smaPeriod);
sma3 = SMA(Closes[2],smaPeriod);



If you want to use an indicator in a strategy, it is best to add an instance of the indicator to the strategy via the Add() method.

If you want to use your strategy with 10 different instruments, you would first add the 10 instruments in the Initialize() section of the strategy. Bar Index 0 denotes the primary bars, and bar indices 1 to 10 would denote the 10 added bar series (index follows the order in which they have been added).

Within the Initialize() section you can then add indicators to your strategy, also via Add(). This is required if you wish that the indicators are plotted, otherwise you can call indicators directly in OnBarUpdate().

Reply With Quote
The following 3 users say Thank You to Fat Tails for this post:
 
(login for full post details)
  #104 (permalink)
Calgary AB
 
Experience: Intermediate
Platform: AmiBroker, IB
Broker: Interactive Brokers
Trading: Stocks
 
Posts: 10 since Mar 2013
Thanks: 5 given, 2 received

OK, sounds good, thanks again.

Just so that I'm clear, what if I only need the indicator for calculations, but don't care about plotting it?
> If I want to apply this indicator to each of the 10 instruments, should I have to add a separate instance of the indicator for each of the instruments?
 
Code
Initialize()
{
Add(....all instruments...);

for(int i = 1; i <= numberOfAddedInstruments; i++)
{
Add(SMA(Closes[i],smaPeriod));
}
> Or, can I somehow add one instance of the indicator and then point that to various DataSeries later in the strategy?

Sorry if I'm not describing it quite clearly (Although, I would imagine that if I could just figure out a way to describe it, I probably wouldn't have any issue programming it...)

Thanks a million for helping with this, I'm very much lost in the dark right now

Reply With Quote
 
(login for full post details)
  #105 (permalink)
Market Wizard
Berlin, Europe
 
Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker: Interactive Brokers
Trading: Keyboard
 
Fat Tails's Avatar
 
Posts: 9,855 since Mar 2010
Thanks: 4,238 given, 26,731 received


kbeary33 View Post
Just so that I'm clear, what if I only need the indicator for calculations, but don't care about plotting it?

You can call it directly from within OnBarUpdate() as SMA(Closes[i], period).


kbeary33 View Post
> If I want to apply this indicator to each of the 10 instruments, should I have to add a separate instance of the indicator for each of the instruments?

That is what I would try to do.


kbeary33 View Post
> Or, can I somehow add one instance of the indicator and then point that to various DataSeries later in the strategy?

No, this will not work.

Reply With Quote
The following 2 users say Thank You to Fat Tails for this post:
 
(login for full post details)
  #106 (permalink)
Calgary AB
 
Experience: Intermediate
Platform: AmiBroker, IB
Broker: Interactive Brokers
Trading: Stocks
 
Posts: 10 since Mar 2013
Thanks: 5 given, 2 received

Hi again,

Thanks very much for your input, but I still haven't been able to find an efficient way of implementing this.

First I tried:

 
Code
private override void Initialize()
for(int i = 0; i <= numInstruments; i++)
{
	Add(ATR(BarsArray[i],ATRPeriod));
	Add(ROC(BarsArray[i],RankingPeriod1));
}
... But NinjaTrader throws an error saying that you can't access BarsArray inside of the Initialize function

So, I then tried:
 
Code
private override void OnBarUpdate()
{
...
if(!init)
{
for(int i = 0; i <= numInstruments; i++) { Add(ATR(BarsArray[i],ATRPeriod)); Add(ROC(BarsArray[i],RankingPeriod1)); } init = true;
... But NinjaTrader then throws an error saying that you can't use "Add()" outside of the initialize function

I am actually working with a fairly large list of instruments (300+), so obviously I don't want to type a line manually for each of the indicators that I want to add. Is there some other way than what I've tried to do in the code above to iterate through the list of instruments and add their corresponding indicator?

Also, from a memory usage standpoint: If I'm running an optimization run, and NinjaTrader creates a new instance of each indicator for each set of parameters, will Ninja ever release that memory, or no? Right now, the memory usage gradually explodes (using all 12GB of RAM), and the only way to fix it is to close NT and restart.

I understand that the best way to handle this on a single instrument strategy is to create a unique instance of the indicator, and just reference that instance, but how can you hard code that to iterate automatically? Is there a way in C# to use a dynamic string when declaring variables? Not sure how to explain, but I'm thinking something along the lines of:

 
Code
for (int i = 0; i < numberInstruments; i++)
{
private SMA sma[i] = SMA(BarsArray[i], smaPeriod);
}

Reply With Quote
 
(login for full post details)
  #107 (permalink)
Wrocław, Poland
 
Experience: Intermediate
Platform: NinjaTrader, Racket
Trading: Ockham's razor
 
gregid's Avatar
 
Posts: 651 since Aug 2009
Thanks: 320 given, 620 received


kbeary33 View Post
... But NinjaTrader throws an error saying that you can't access BarsArray inside of the Initialize function

Try using Closes instead:
 
Code
Add(ATR(Closes[i],ATRPeriod));
And see how this works instead.

Reply With Quote
The following 2 users say Thank You to gregid for this post:
 
(login for full post details)
  #108 (permalink)
Calgary AB
 
Experience: Intermediate
Platform: AmiBroker, IB
Broker: Interactive Brokers
Trading: Stocks
 
Posts: 10 since Mar 2013
Thanks: 5 given, 2 received

Thanks very much, this seemed to work. I had thought that because the ATR calc needed all of the high/low/close/open, it would have to be passed the BarsArray item. Passing Closes returned the same value though, so apparently that's ok

One last thing - Will adding the indicators to the strategy serve the same purpose as declaring a unique named instance of the indicator?

ie

Add(ATR(Closes[1],ATRPeriod)) --> same performance as: private ATR myATR1 = ATR(Closes[1],ATRPeriod)

Reply With Quote
The following user says Thank You to kbeary33 for this post:
 
(login for full post details)
  #109 (permalink)
Market Wizard
Berlin, Europe
 
Experience: Advanced
Platform: NinjaTrader, MultiCharts
Broker: Interactive Brokers
Trading: Keyboard
 
Fat Tails's Avatar
 
Posts: 9,855 since Mar 2010
Thanks: 4,238 given, 26,731 received


kbeary33 View Post
Thanks very much, this seemed to work. I had thought that because the ATR calc needed all of the high/low/close/open, it would have to be passed the BarsArray item. Passing Closes returned the same value though, so apparently that's ok

If you look at the code of the ATR indicator, it does not use Input[0] anywhere. If it did, the output values would depend on the type of data passed. Therefore ATR(Closes[1], ATRPeriod) is the same as ATR(Highs[1], ATRPeriod). I would prefer to write ATR(Inputs[1], ATRPeriod) as this covers the general case.



kbeary33 View Post
One last thing - Will adding the indicators to the strategy serve the same purpose as declaring a unique named instance of the indicator?

ie

Add(ATR(Closes[1],ATRPeriod)) --> same performance as: private ATR myATR1 = ATR(Closes[1],ATRPeriod)

The main purpose of addingan indicator via the ADD() method is to have them directly plotted by the strategy. If this is not required, the code below is a simpler solution:

 
Code
#region Variables

private ATR   myATR1;

#endregion

protected override void OnStartUp()
{
     myATR1 = ATR(Inputs[1], ATRPeriod);
}

Reply With Quote
The following 2 users say Thank You to Fat Tails for this post:
 
(login for full post details)
  #110 (permalink)
Portland Oregon, United States
 
Experience: Beginner
Platform: Ninjatrader®
Broker: CQG, Kinetick
Trading: Gameplay Klownbine® Trading of Globex
 
Zondor's Avatar
 
Posts: 1,347 since Jul 2009
Thanks: 1,245 given, 2,721 received

An Array can store any type, including DataSeries objects. As an example, let's create an array to hold more than one DataSeries. The rank (number of elements) of the array does not need to be hard coded. It can be user selected or programmatically controlled, and the setting of the object references can be done in a For loop.

Declare the array. At this point the rank (number of elements) is not yet defined and the array is empty.

 
Code
private DataSeries [] multiSeries;
 //declare an array that will contain object references to DataSeries objects.
In the Initialize() method:
 
Code
//specify the number of elements in the array, which is the integer called rank 
multiSeries[]=new DataSeries[rank];           

//the array now contains the number rank of object references that need to be set to instances of objects

for (int count = 0; count<rank; count++)
multiSeries[count]=new DataSeries(this);           
Remember, an array is a ZERO BASED collection. So, for example, if an array contains 5 items, the subscripts of the items will be 0 through 4, not 1 through 5. Hence the start and end points of the For loop.

Each of these objects is accessed like any other DataSeries, but don't forget the first subscript that tells you which one is being accessed.

 
Code
double value_X_BarsBack_of_multiSeriesN = multiSeries[N][X];
That's it, we're almost done for today. Have a nice day!

But before I return to my undisclosed location, here is an example of how to use this technique, based on the Freedom of Movement Indicator in the April 2014 issue of TASC. By eliminating dependencies on external classes, the performance of the indicator has been improved. (I have other, more ambitious uses in mind for this technique, since for this particular indicator it is not really worth the trouble.)

"If we don't loosen up some money, this sucker is going down." -GW Bush, 2008
“Lack of proof that something is true does not prove that it is not true - when you want to believe.” -Humpty Dumpty, 2014
“The greatest shortcoming of the human race is our inability to understand the exponential function.”
Prof. Albert Bartlett
Attached Files
Register to download File Type: cs FoM.cs (17.5 KB, 31 views)
Follow me on Twitter Visit my futures io Trade Journal Reply With Quote
The following 3 users say Thank You to Zondor for this post:
 
(login for full post details)
  #111 (permalink)
Portland Oregon, United States
 
Experience: Beginner
Platform: Ninjatrader®
Broker: CQG, Kinetick
Trading: Gameplay Klownbine® Trading of Globex
 
Zondor's Avatar
 
Posts: 1,347 since Jul 2009
Thanks: 1,245 given, 2,721 received

Good information here, especially regarding object oriented coding:



Probably being used by those coming here on H1B visas, where the guys that they are going to replace are forced to train them to take over their own jobs.

https://www.zerohedge.com/news/2015-10-30/offshoring-economy-why-us-road-third-world

"If we don't loosen up some money, this sucker is going down." -GW Bush, 2008
“Lack of proof that something is true does not prove that it is not true - when you want to believe.” -Humpty Dumpty, 2014
“The greatest shortcoming of the human race is our inability to understand the exponential function.”
Prof. Albert Bartlett
Follow me on Twitter Visit my futures io Trade Journal Reply With Quote
 
(login for full post details)
  #112 (permalink)
Austin TX
 
Experience: Intermediate
Platform: SaintGobain Crystal Ball
Trading: 6E
 
Posts: 81 since Oct 2010
Thanks: 102 given, 133 received

Here's the link to the Microsoft Patterns and Practices page containing information on how to improve C# code performance. It is not related to NinjaTrader-specific programming, however it has proven to be a very valuable resource in my day-to-day activities as a dev.

Microsoft Patterns and Practices - Improving Managed Code Performance

Another suggestion I would make is to use multi-threading such as Task Parallel Library. Although TPL has been originally released in .NET4 and NT7 runs on .NET 3.5, recently TPL has been released for 3.5 as part of Reactive Extensions. All the NT plugins I see posted here use blocking, synchronous code and definitely could use multithreading to speed things up.
JB

Reply With Quote
The following 4 users say Thank You to Jaba for this post:


futures io Trading Community Platforms and Indicators NinjaTrader > Anyone have any hints for optimizing C# code?


Last Updated on December 24, 2015


Upcoming Webinars and Events
 

NinjaTrader Indicator Challenge!

Ongoing
 

Battlestations! Show us your trading desk - $1,500 in prizes!

March
 

Importance of Finding Your Own Way w/Adam Grimes

Elite only
 

Journal Challenge w/Jigsaw

April
     



Copyright © 2021 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