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 47,809 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?

  #101 (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


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

Can you help answer these questions
from other members on NexusFi?
NT7 Indicator Script Troubleshooting - Camarilla Pivots
NinjaTrader
ZombieSqueeze
Platforms and Indicators
New Micros: Ultra 10-Year & Ultra T-Bond -- Live Now
Treasury Notes and Bonds
My NT8 Volume Profile Split by Asian/Euro/Open
NinjaTrader
The space time continuum and the dynamics of a financial …
Emini and Emicro Index
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Get funded firms 2023/2024 - Any recommendations or word …
59 thanks
Funded Trader platforms
37 thanks
NexusFi site changelog and issues/problem reporting
22 thanks
GFIs1 1 DAX trade per day journal
22 thanks
The Program
20 thanks
  #102 (permalink)
 kbeary33 
Calgary AB
 
Experience: Intermediate
Platform: AmiBroker, IB
Broker: Interactive Brokers
Trading: Stocks
Posts: 10 since Mar 2013
Thanks Given: 5
Thanks Received: 2

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



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
Thanked by:
  #104 (permalink)
 kbeary33 
Calgary AB
 
Experience: Intermediate
Platform: AmiBroker, IB
Broker: Interactive Brokers
Trading: Stocks
Posts: 10 since Mar 2013
Thanks Given: 5
Thanks Received: 2

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
  #105 (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


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
Thanked by:
  #106 (permalink)
 kbeary33 
Calgary AB
 
Experience: Intermediate
Platform: AmiBroker, IB
Broker: Interactive Brokers
Trading: Stocks
Posts: 10 since Mar 2013
Thanks Given: 5
Thanks Received: 2

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
  #107 (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


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
Thanked by:
  #108 (permalink)
 kbeary33 
Calgary AB
 
Experience: Intermediate
Platform: AmiBroker, IB
Broker: Interactive Brokers
Trading: Stocks
Posts: 10 since Mar 2013
Thanks Given: 5
Thanks Received: 2

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
Thanked by:
  #109 (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


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
Thanked by:
  #110 (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


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
Elite Membership required to download: FoM.cs
Follow me on Twitter Visit my NexusFi Trade Journal Reply With Quote
Thanked by:




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