PDA

View Full Version : Setting Strategy Defaults


glenng
10-25-2007, 05:38 AM
When loading a strategy, you must enter the insturment type, value, start date, session begin/end, etc. every time. Is it possible to enter defaults for all of this in the code?

NinjaTrader_Dierk
10-25-2007, 05:44 AM
Yes, for some of these. However you would need to find out by yourself on which ones it works. Please consult the docs for the accurate C# property names.

glenng
10-25-2007, 06:19 AM
Thank you. I checked the documentation before I posted my question. I searched for "strategy properties" and some of the property descriptions but I found nothing. Perhaps you could point me in the right direction????

NinjaTrader_Ray
10-25-2007, 06:59 AM
In the Help Guide.

NinjaScript > NinjaScript Language Reference > Custom Strategy Methods and Properties

KBJ
10-25-2007, 10:48 AM
Here are some of the defaults that I use in a strategy I've been working on...

protected override void Initialize()
{
CalculateOnBarClose = false; // If 'false' then OnBarUpdate will be called for every tick; 'true' for just once per bar.

DefaultQuantity = 1; // Order size in number of contracts per trade.

EntriesPerDirection = 1; // Only 1 short and/or 1 long position at a time.
// EntryHandling = EntryHandling.UniqueEntries; // Count EntriesPerDirection separately for each uniquely named EnterLong or EnterShort.
EntryHandling = EntryHandling.AllEntries; // Process all order entry methods until the maximum allowable entries set by the EntriesPerDirection property has been reached.

ExitOnClose = true; // Cancel all orders & all open positions at end of session.
ExitOnCloseSeconds = 1200; // Cancel all orders & all open positions 1200 seconds (20 min) before end of session.

IncludeCommission = true; // Include commission on historical backtest.

AccountSize = 2500; // Assume we start with a small amount of money.

Slippage = 2; // Amount of slippage in ticks during backtests.

TimeInForce = Cbi.TimeInForce.Day; // Set day orders (as opposed to gtc = good till cancelled.)

TraceOrders = true; // Display order information in Output window for debugging.

Print( String.Format( "Initialize for instrument {0} Period {1}({2}) Complete at {3}",
Instrument.FullName, Bars.Period.Id, Bars.Period.Value, DateTime.Now.TimeOfDay ));
}Please note that this is just a sample, and if you copy this, make sure you review each setting and pick values that make sense for your particular situation and strategy design.

KBJ

glenng
10-25-2007, 02:07 PM
Thank you KBJ - I appreciate the code.

Ray, I did check that first. I was hoping I could set all of the values like the chart interval,first date, session begin and end time, etc. I still don't see these so I will assume that it can't be done. Thx

NinjaTrader_Josh
10-25-2007, 04:04 PM
If you use the code KBJ provided you should be able to set the default for that particular strategy to whatever you want. Unfortunately there is no way to set these options on a universal basis.

Pete S
11-05-2007, 05:45 AM
I tried setting these values programatically in my Initialize method. When I check them in OnBarUpdate, they have reverted back to the values specified in the UI. Is there another step to be taken to make sure this doesn't happen? I am seeing this behavior on both backtesting & optimization.

NinjaTrader_Dierk
11-05-2007, 05:47 AM
>> Is there another step to be taken to make sure this doesn't happen?
Unfortunately this is not supported.

KBJ
11-05-2007, 09:20 AM
I forgot. I wasn't able to set the EntryHandling and EntriesPerDirection.

However, I added some code to the OnBarUpdate method to make sure the values were set correctly...


if ((EntryHandling != EntryHandling.AllEntries) // Correct setting?
|| (EntriesPerDirection != 1))
{ // No. Cause an error to abort this run.
Print( "**** Error - Entry handling is not set to AllEntries 1" ); // To output window.
throw new System.ApplicationException("EntryHandling must be AllEntries, 1"); // To log.
}
At least this way you get a reminder to set things right and it doesn't run a zillion optimizations with the wrong settings.

Jenny
11-22-2007, 07:51 AM
That is very good if we can set the default also for:
Time frame: Form=2007/07/01,
Time Frame: To=Today,
Keep best result=2,
Optimize on=max. net profit.

Thanks

NinjaTrader_Dierk
11-22-2007, 07:53 AM
Thanks for your suggestion. We'll add it to the list.

Jenny
11-22-2007, 04:40 PM
Will next version include?
Good luck.
Thanks

NinjaTrader_Ray
11-22-2007, 07:16 PM
Unfortunately not.

KBJ
12-12-2007, 08:41 PM
This was sent to me as a PM. I'm posting it over here for everyone's benefit...

Hi KBJ

In your post for setting defaults, you have this following code ...

Print( String.Format( "Initialize for instrument {0} Period {1}({2}) Complete at {3}",
Instrument.FullName, Bars.Period.Id, Bars.Period.Value, DateTime.Now.TimeOfDay ));
Can you tell me what the {1} etc are doing here?

Also ..
Have you tried this verbatim on 6.5?
If i include this in Initialize.. the strategy doesn't execute ..


Sorry, I'm not running 6.5 yet, so I have not tried this on 6.5.

Check this page for how String.Format works: http://www.blackwasp.co.uk/StringFormat.aspx

To debug this, I'd suggest deleting each "{n}" designation in turn along with the matching parameter until the problem goes away.

Lost Trader
04-29-2008, 06:10 PM
Please include this in v7... I want to set
Bars.Period.Value = 1; Bars.Period.Id = PeriodType.Day;
just like I do
CalculateOnBarClose = true; BarsRequired = 1;
As well as Time from/to, Exclude weekend, and Session begin/end times for intraday. It gets really annoying to have to remember to change them via the menu because the NT defaults are different.

You should also update your help to say this Bars & therefore Bars.Period object is invalid in the Initialize() and changing it in the OnBarUpdate() is overridden and lost.

Thanks.

NinjaTrader_Dierk
04-29-2008, 09:52 PM
Thanks for your suggestion. We'll add it to the list o future considerations.

bigtrade5
05-15-2008, 02:10 PM
Thanks for this thread (and code to get me started KBJ), I was able to default everything I set in my strategies except the Instrument (which I dont want to default anyhow). Below is the code I am using for your reference.


protected override void Initialize()
{
CalculateOnBarClose = true;
DefaultQuantity = 1;
QuantityType = QuantityType.DefaultQuantity;
EntriesPerDirection = 10;
EntryHandling = EntryHandling.AllEntries;
ExitOnClose = true;
ExitOnCloseSeconds = 50;
TimeInForce = Cbi.TimeInForce.Day;
ExcludeWeekend = true;
SessionBegin = DateTime.Parse("09:30 AM");
SessionEnd = DateTime.Parse("04:00 PM");
IncludeCommission = true;
BarsRequired = 2;
}

r2kTrader
05-20-2009, 12:16 PM
KJB,

Thanks, this was helpful. Do you perhaps know how to set Default Account to use?

Also, Default Instrument?

Can these be done programatically? I want to eliminate as much room for error as possible from the launching of a strategy.

Thanks,


r2kTrader
Here are some of the defaults that I use in a strategy I've been working on...

protected override void Initialize()
{
CalculateOnBarClose = false; // If 'false' then OnBarUpdate will be called for every tick; 'true' for just once per bar.

DefaultQuantity = 1; // Order size in number of contracts per trade.

EntriesPerDirection = 1; // Only 1 short and/or 1 long position at a time.
// EntryHandling = EntryHandling.UniqueEntries; // Count EntriesPerDirection separately for each uniquely named EnterLong or EnterShort.
EntryHandling = EntryHandling.AllEntries; // Process all order entry methods until the maximum allowable entries set by the EntriesPerDirection property has been reached.

ExitOnClose = true; // Cancel all orders & all open positions at end of session.
ExitOnCloseSeconds = 1200; // Cancel all orders & all open positions 1200 seconds (20 min) before end of session.

IncludeCommission = true; // Include commission on historical backtest.

AccountSize = 2500; // Assume we start with a small amount of money.

Slippage = 2; // Amount of slippage in ticks during backtests.

TimeInForce = Cbi.TimeInForce.Day; // Set day orders (as opposed to gtc = good till cancelled.)

TraceOrders = true; // Display order information in Output window for debugging.

Print( String.Format( "Initialize for instrument {0} Period {1}({2}) Complete at {3}",
Instrument.FullName, Bars.Period.Id, Bars.Period.Value, DateTime.Now.TimeOfDay ));
}Please note that this is just a sample, and if you copy this, make sure you review each setting and pick values that make sense for your particular situation and strategy design.

KBJ

r2kTrader
05-20-2009, 12:33 PM
Is there a way to see ALL the parameters for a given strategy as it is running, or can this only be done by the print/debug features?

I am envisioning something like the strategy tab where it shows the Instrument, Data Seris, and Custom Parameters. Where can you see the rest of the info so you can feel more secure about which parameters are actually active.

NinjaTrader_Josh
05-20-2009, 01:25 PM
Setting default account and instrument are not supported. You will have to print to see all default settings as you run a strategy.

KBJ
05-20-2009, 02:02 PM
Setting default account and instrument are not supported. You will have to print to see all default settings as you run a strategy.

r2kTrader, although you cannot set the values, you can test to make sure your strategy has been passed expected values, by using code similar to what's found in my earlier posting # 10 (http://www.ninjatrader-support2.com/~forum/vb/showpost.php?p=19169&postcount=10) (but check for expected values of "Instrument.Fullname" and/or "Account.Name" in OnBarUpdate and if it's not what you wanted, Print an error message, and Throw an exception.)

Not as good as what you asked for, but perhaps better than nothing.

r2kTrader
05-20-2009, 02:36 PM
I came up with a workaround to hard code the default instrument.

I did it using the add() under the initialize and manually selected that contract and time frame.

Now it doesn't care if I run a 60m, 10m, or which Instrument I select under the UI as it will only execute if BarsInProgress =1 or that which represents my add().

I hope this helps anyone trying to "nail" up a strategy with as little intervention as possible.

I can't tell you how many times I fired up the strategy with the wrong contract or timeframe, etc. It's very expensive when it doesn't go your way. Nothing stinks worse than losing because of a pilot error. I can handle losses, but not due to an oversight. That is the whole purpose of going algo to begin with!! lol.

NT7 is much anticipated. I hope this key issues all get resolved as they are paramount to algo trading.


Thanks

r2kTrader
05-20-2009, 02:37 PM
It was helpful, another layer won't hurt!

Thank you

r2kTrader, although you cannot set the values, you can test to make sure your strategy has been passed expected values, by using code similar to what's found in my earlier posting # 10 (http://www.ninjatrader-support2.com/~forum/vb/showpost.php?p=19169&postcount=10) (but check for expected values of "Instrument.Fullname" and/or "Account.Name" in OnBarUpdate and if it's not what you wanted, Print an error message, and Throw an exception.)

Not as good as what you asked for, but perhaps better than nothing.

r2kTrader
05-20-2009, 02:43 PM
If anyone can lend a hand, and in reference to my work around posted earlier using the Add() method to hard code an instrument into the strategy in combination with BarsInProgress, I am trying to code the current front month contract for the ES, TF, etc.

Looking for a code snippet to setup a programmatic/dynamic setting which will set the current month/year for the contract ES.

Example:
Add("ES 06-09", PeriodType.Minute, 1);

the above is under initialize() (of course).

I want to get this setup so that I can plug the month / year programatically. For me to figure this out will be pain, but I am sure someone who knows C# has this syntax in their sleep.

My train of thought is to parse a date method return and then build a custom string. Which is not brain surgery, but is for someone who is not a programmer.

Anyway, if someone could post a link to an example, that would help or provide direction.


Regards,

UPDATE:
Will this work?
Add("ES " + DateTime.Now.Month.ToString + "-" + DateTime.Now.Year.ToString, PeriodType.Minute, 1);

UPDATE II:
Or this I think, forgot the ()'s.

UNDER VARIABLES:
privatestring contractDate = "ES " + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString();

UNDER INITIALIZE():
Add(contractDate, PeriodType.Minute, 1);

Will this fly?

UPDATE III:
Ok, obviously it will give the current month, not the contract month (duh, lol) and it won't add the 0 leading the month if single digit, so my guess is that the above will give something like this:
ES 5-2009 (if month is May).

So now I just need to do an if statement or Case and test for which Quarter month is in. Should I do something like an enum with 4 contract months, 1 for each quarter, and then do a case test?

I can kludge through, but if someone can help, great!

Thanks,

NinjaTrader_Josh
05-20-2009, 02:55 PM
You may or may not need to do more string manipulations then that. Print those out and see what it returns. Year most likely returns 2009 instead of 09 and you will want to cut just the part you want out.

r2kTrader
05-21-2009, 06:06 AM
Josh,

It gets more complex. I have to take current date and see if it fits in between the last contract expiration and the current expiration. As you are aware, this is not a constant as it expires the 3rd Friday of that last month. So It gets complicated.

There has to be some kind of code out there for this. For now, set it to default to current month manually and use Outlook to remind me to rollover etc. Furthermore, I don't rollover on the same timeframe every month, rather I watch the volume roll from last contract to front month contract.

If anyone could help with this, I would appreciate it.


Thanks,

NinjaTrader_Josh
05-21-2009, 07:15 AM
As a last resort you may also want to consider bringing your requirements to a 3rd party NinjaScript Consultant here: http://www.ninjatrader.com/webnew/partners_onlinetrading_NinjaScript.htm

r2kTrader
05-21-2009, 07:46 AM
As a last resort you may also want to consider bringing your requirements to a 3rd party NinjaScript Consultant here: http://www.ninjatrader.com/webnew/partners_onlinetrading_NinjaScript.htm

I am just going to code the contract manually for the front month. This is subjective for my system anyway. I decide when to start trading the front month when I see the volume where it needs to be.

Also, I am noticing that even when you hard code the parameters like ExitOnClose etc. in the code, when you go to fire up the strategy from the strategy tab, it doesn't use those hard coded parameters to overwrite the last used settings. Seems "flaky" as it feels like sometimes they change, sometimes it doesn't. Can you provide some insight as to what my expectation should be using hard coded parameters? Particularly as it relates to firing strats from the strat tab in control?


Thanks,

NinjaTrader_Josh
05-21-2009, 07:51 AM
Anything you hard code will be shown on a NEW instance of your strategy. Anything you change it to from a UI level will persist till you start another new instance.

r2kTrader
05-21-2009, 11:43 AM
Anything you hard code will be shown on a NEW instance of your strategy. Anything you change it to from a UI level will persist till you start another new instance.

Assuming I just started up NT and I have my settings hard coded.

I am at the strategy tab. I go to start a strategy, I drop down to my strategy, I select. I see the IU change my settings. Ok, good so far. I then do nothing else except say ok, to load strategy, then I start it.

Now, if I go to ADD ANOTHER STRATEGY, and select a NEW strategy from the drop down, will it keep my other settings persistant or draw from the hard coded settings. And if it does keep settings persistant, can I assume that my hard coded settings will override and take priority or is this not a good idea?

Please advise. I am looking forward to NT 7 because as much as I can tell, the strategy management piece of NT 6.x is just not feasible for the real world in regards to algo trading. I will remain faithful to the cause and looking forward to 7, but this is very frustrating. It should not be this complicated I should think. <end of rant>

NinjaTrader_Josh
05-21-2009, 11:58 AM
r2kTrader,

The behavior is easiest understood if you just observe it. Please just try it. When you select a new strategy the hard coded settings will take over. Depending on which other strategy you select and if they hard coded anything or not the settings may or may not persist.

For example, CalculateOnBarClose will not take hard coded values unless specifically hard coded to false.

r2kTrader
05-21-2009, 12:09 PM
Josh,

That is frustrating. It was through observation that I was unsure about what works and what doesn't. For example, how in the heck are we supposed to know that COBC won't take hard coded unless false? I mean is that documented anywhere?

What takes precendence?

What are the rules?

Please give us a scope as I am doing all this so as to avoid accidentally setting the wrong settings prior to starting the system.

<extremely frustrated>

r2kTrader,

The behavior is easiest understood if you just observe it. Please just try it. When you select a new strategy the hard coded settings will take over. Depending on which other strategy you select and if they hard coded anything or not the settings may or may not persist.

For example, CalculateOnBarClose will not take hard coded values unless specifically hard coded to false.

zweistein
05-21-2009, 12:43 PM
Everything you define in
Initialize() will override the settings from the UI.

This is meant by hardcoded.
example

protectedoverridevoid Initialize()
{
CalculateOnBarClose = false;
BarsRequired=100;
ExitOnClose=false;
}

the rest is set by the UI, and the UI keeps the last selected value in memory and shows this.



Oh, I am just rreading the previous post better,

He is right and I am wrong!

NT team, please document better

There is a trick though:

Define the following property in your strategy class

[Description("Calculate on bar close")]
[Category("General")]
publicbool CalculateOnBarClose
{
get { return true; }
set { base.CalculateOnBarClose=true;}

}

should coerce to always true

and the UI will reflect this also!

same for the other Properties

NinjaTrader_Josh
05-21-2009, 12:53 PM
It is very simple. New instance means hard coded. Selecting a different strategy with hard coded settings will set those as well otherwise it will use whatever was there before. CalculateOnBarClose is kind of like an exception where it will take on the prior value unless explicitly set to false.

Also, please realize that hard setting many of these values is not officially supported.

r2kTrader
05-21-2009, 01:20 PM
zweistein,

Do I do that for all the properties I want to site? Will that force a UI override of the persist settings from last strategy loaded?

By the way, do you know how to auto-select the account you want it to trade off of? Ideally I would like it to default to my broker, UNLESS, global sim mode is set. Any ideas welcomed.

Thanks for the help by the way.




Everything you define in
Initialize() will override the settings from the UI.

This is meant by hardcoded.
example

protectedoverridevoid Initialize()
{
CalculateOnBarClose = false;
BarsRequired=100;
ExitOnClose=false;
}

the rest is set by the UI, and the UI keeps the last selected value in memory and shows this.



Oh, I am just rreading the previous post better,

He is right and I am wrong!

NT team, please document better

There is a trick though:

Define the following property in your strategy class

[Description("Calculate on bar close")]
[Category("General")]
publicbool CalculateOnBarClose
{
get { return true; }
set { base.CalculateOnBarClose=true;}

}

should coerce to always true

and the UI will reflect this also!

same for the other Properties

r2kTrader
05-21-2009, 01:30 PM
It is very simple. New instance means hard coded. Selecting a different strategy with hard coded settings will set those as well otherwise it will use whatever was there before. CalculateOnBarClose is kind of like an exception where it will take on the prior value unless explicitly set to false.

Also, please realize that hard setting many of these values is not officially supported.


So is ExitOnClose, that is not overriden by the hard coded settings. If you manually set to True, then it will auto-fill the values you have hard coded for number of seconds to exit before close on, but not the boolean itself. My spidey sense tells me that I want to use zweistein's work around. Will try now.

NinjaTrader_Josh
05-21-2009, 01:35 PM
I cannot provide further support on this. Please use zweistein's suggestion.

r2kTrader
05-21-2009, 01:36 PM
Josh and Zweisstein,

This is what I did. It seems to hard code and force the settings. Apparently the booleans need to be hard coded. Zweis, I made one change and you had publicbool without a space. I changed "General" to Order Handling so that it showed under the right area. What I like is that 1. I get the overriding behavior, and 2. you can't change it if you set it in the variables to the preferred setting.

here is the code. Josh, please let me know if this will work. It seems to behave correctly, I just want to make sure what I am seeing is what will occur. Please advise,


[Description("Calculate on bar close")]
[Category("Order Handling")]
publicbool CalculateOnBarClose
{
get { returntrue; }
set { base.CalculateOnBarClose=true;}
}

[Description("Exit On Close")]
[Category("Order Handling")]
publicbool ExitOnClose
{
get { returntrue; }
set { base.ExitOnClose=true;}
}

NinjaTrader_Josh
05-21-2009, 01:41 PM
Unfortunately I cannot provide you any guidance on this. This is unsupported and you guys will have to play with it on your own.

zweistein
05-21-2009, 02:32 PM
r2kTrader

I had the exact same problems as you and for me my proposed solution works. The UI display corresponds the strategy behaviour
As I understand the calling sequence of a strategy is
1. Setters are called
2. Getters are called (or viceversa)
3. Variable section ist called
4. Initialize() is called
5. OnBarUpdate() is called

I am using this on my strategies (only simple exit strategies) for almost 2 weeks and I do 5 to 10 real trades a day (DAX, GBL, 6E, ES) and so far it seems to work

regards

Andreas


P.S. I liked the mental exercise, so here I wrote the


FrontContract() function:


static string FrontContract(string symbol)
{
string s=symbol;
DateTime NextExpiry=new DateTime();
DateTime t = DateTime.Now;
//DateTime t = new DateTime(2009,12,27);
int quarterend;
for(quarterend=3;quarterend<=12;quarterend+=3){
if (t.Month <= quarterend) break;
}
DateTime firstdayofquarter = new DateTime(t.Year,quarterend,1);
DateTime thirdfriday = firstdayofquarter.AddDays(14 + (DayOfWeek.Friday - firstdayofquarter.DayOfWeek));
if (t.CompareTo(thirdfriday) >= 0){
firstdayofquarter=firstdayofquarter.AddMonths(3);
thirdfriday = firstdayofquarter.AddDays(14 + (DayOfWeek.Friday - firstdayofquarter.DayOfWeek));
quarterend += 3;
quarterend = quarterend % 12;
}
NextExpiry = thirdfriday;
s += " " + quarterend.ToString("D2") + "-" + (thirdfriday.Year - 100 * (int)(thirdfriday.Year / 100)).ToString("D2");
return s;
}

zweistein
05-21-2009, 02:44 PM
I have this in my code, but I havn't worked on it yet. I use a Multibroker Licence, but I usually choose the account by hand

This is your starting point, let me know your results...
Be advised that in the getter/ setter functions you have VERY LIMITED access to the NinjaTrader functions, so always check for null, etc, or do what you can with standard .Net

I would use a debugger (CLR) to find out about the exposed functions of the Account class





[XmlIgnore()]
[Description("Account.")]
[Category("General")]
public Account Account {
get {returnbase.Account;}
set {
base.Account=value;
// Print("Andreas.Account="+base.Account.Name.ToString());
}
}

r2kTrader
05-21-2009, 02:45 PM
This causes NT to lock up when you attempt to start a strategy.

[Description("Entries Per Direction")]
[Category("Order Handling")]
publicint EntriesPerDirection
{
get { return EntriesPerDirection; }
set { base.EntriesPerDirection=1;}
}

I duplicated the problem and this was the code that caused the system to freeze (and also corrupt databases).

zweistein
05-21-2009, 02:47 PM
This will always crash because your function EntriesPerDirection is calling itself

=> stack overflow

so, before I turn off the PC

#Variables
int entriesperdirection=2;




publicint EntriesPerDirection
{
get { return entriesperdirection; }
set { base.EntriesPerDirection=entriesperdirection;}
}


should work

r2kTrader
05-21-2009, 03:12 PM
Zweistein,

Lol, that makes sense. I was just copying the initial logic, lol. and didn't think it through, thank you so much for your help.

Do you know how to access all the variables? I want to lock down as much as a I can as I lost real money making a mistake with wrong market, etc. It was brutal, lol. Funny now, but it was a couple of NT licenses!


Thanks again!

This will always crash because your function EntriesPerDirection is calling itself

=> stack overflow

so, before I turn off the PC

#Variables
int entriesperdirection=2;




publicint EntriesPerDirection
{
get { return entriesperdirection; }set { base.EntriesPerDirection=entriesperdirection;}
}


should work

r2kTrader
05-21-2009, 03:18 PM
Will this work?

[Description("Entries Per Direction")]
[Category("Order Handling")]
publicint EntriesPerDirection
{
get { return entriesPerDirection; }
set { base.EntriesPerDirection=entriesPerDirection;}
}

So should I also take out EntriesPerDirection under initialize()?

r2kTrader
05-21-2009, 03:50 PM
zweistein,

Do you know if it is possible to set the "Instrument" using the same method as above?


[Description("Instrument")]
[Category("Data Series")]
public string Instrument
{
get { return contract; }
set { base.Instrument=contract;}
}

The above code generates an error:
Cannot convert type string to NinjaTrader.Cbi.Instrument

r2kTrader
05-21-2009, 05:59 PM
Josh/zweistein,

I was able to get the Instrument to default to "NULL" (blank) and kill the Type/Value for when the strategy starts by doing the following:

VARIABLES
private NinjaTrader.Cbi.Instrument contract = null;

INITIALIZE()
DataSeriesConfigurable = false;

PROPERTIES
[Description("Instrument")]
[Category("Data Series")]
public NinjaTrader.Cbi.Instrument Instrument
{
get { return contract; }
set { base.Instrument=contract;}
}

How can I pass the instrument value to replace Null? As it stands, I am simply adding the contract I want to trade and trying to kill the initial instrument, but ideally, I would like to set the instrument which I believe is not possible according to Ray's post.

UPDATE:
I tested it and it will still use the default intrument that is first in your list, or persisting from last strategy. Any suggestions? FYI, tested the code and it is operating correctly other than what is outlined in this update.

UPDATEIII:
Disregard II, can't access FullName until after initialize. Makes sense.

UPDATE II:
I tried this, but when I use

private NinjaTrader.Cbi.Instrument.FullName contract = "ES 06-09;

I get an error saying FullName does not exist for Cbi.Instrument. As per below, it should work? Help?? lol.

Definition
Returns the full NinjaTrader name of an instrument. For futures, this would include the expiration date. The June S&P 500 Emini contract full name is "ES 06-07".


Property Value
A string representing the full name of the instrument.


Syntax
Instrument.FullName


Property Of
Custom Indicator, Custom Strategy


Additional Access Information
This property can be accessed without a null reference check in the OnBarUpdate() event handler. When the OnBarUpdate() event is triggered, there will always be an Instrument object. Should you wish to access this property elsewhere, check for null reference first. e.g. if (Instrument != null)

zweistein
05-22-2009, 12:15 AM
Instrument is for sure a complex class with more variables to it than we know. So I would leave that in the NT framework.

have you tried something like

#Variables
string contract = "ES 06-09";


#Properties
[Description("Instrument")]
[Category("Data Series")]
public NinjaTrader.Cbi.Instrument Instrument
{
get { return base.Instrument; }
set {
foreach(Instrument I in base.InstrumentList) {
if(I.FullName==contract) base.Instrument=I;
}
}

Common sense tells me there must be an InstrumentList in NT, and then you can also iterate through it.

So I would debug and try to find the exact name of such an Instrument list. Please report if you find out

Regards

r2kTrader
05-22-2009, 07:42 AM
Instrument is for sure a complex class with more variables to it than we know. So I would leave that in the NT framework.

have you tried something like

#Variables
string contract = "ES 06-09";


#Properties
[Description("Instrument")]
[Category("Data Series")]
public NinjaTrader.Cbi.Instrument Instrument
{
get { return base.Instrument; }
set {
foreach(Instrument I in base.InstrumentList) {
if(I.FullName==contract) base.Instrument=I;
}
}

Common sense tells me there must be an InstrumentList in NT, and then you can also iterate through it.

So I would debug and try to find the exact name of such an Instrument list. Please report if you find out

Regards




From a first glance, other than making sure we checked to see if the contract exists, it's not really different than just saying "base.Instrument=contract", no?

Anyway, there is no InstrumentList, but there is Instruments (with the s) and that did compile, but is not doing anything.

[update]
forgot to post code:

[Description("Instrument")]
[Category("Data Series")]
public NinjaTrader.Cbi.Instrument Instrument
{
get { returnbase.Instrument; }
set {
foreach(Instrument I inbase.Instruments)
{
if(I.FullName==contract) base.Instrument=I;
}

}
}

zweistein
05-22-2009, 08:02 AM
contract is a simple string now!

One needs to find the undocumented Instrument Manager Instrument list.

This is different from the Instruments which are set by NT only at Initialize() after you call Add("ES 12-06");

Something not so easy to find, and NT support will not tell you because it means a myriad of more questions.

If you find out, please let us know

regards

r2kTrader
05-22-2009, 08:09 AM
[Description("Instrument")]
[Category("Data series")]
publicstring Instrument
{
get { return contract; }
set { base.Instrument.MasterInstrument.Name=contract; }

// foreach(Instrument I in base.Instruments)
// {
// if(I.FullName==contract) base.Instrument=I;
// }

}

Lol, it will rename your contracts to whatever you set value contract to.

Now my ZB, YM and ZN shows up as "ES 06-09 06-09" in the Instrument List, lol. I am going to rename them back and fix instrument list. I thought I had cracked the case as it seemed like it was working. But it changed the "name" not the actual contract.

r2kTrader
05-22-2009, 08:15 AM
contract is a simple string now!

One needs to find the undocumented Instrument Manager Instrument list.

This is different from the Instruments which are set by NT only at Initialize() after you call Add("ES 12-06");

Something not so easy to find, and NT support will not tell you because it means a myriad of more questions.

If you find out, please let us know

regards

After thinking this through I see the need for the loop. It's a way to apply the proper instrument without knowing the actual "id". This was necessary because we can't make a string and instrument. lol. Let me keep going, I think it's possible. Heck, if I was able to RENAME my instruments from within my code, then certainly I can set the default instrument, lol.

r2kTrader
05-22-2009, 08:32 AM
Instrument.MasterInstrument.Name = contract;

The above is a no-no, it will just rename the Name of the MasterInstrument in your Instruments list to the value of contract variable.

Not a good idea, lol.

zweistein
05-22-2009, 10:15 AM
It is not a good idea to coerce the instrument from within a strategy .

Remember, you have 2 ways to open a strategy: first, from the strategy tab, and second from the chart window.

Using the chart window the instrument property is omitted in the parameters fields, for obvious reasons as you are supposed to apply the strategy to the instrument of the chart.

Therefore I would say that the only choice you have is:

OnBarUpdate(){
if(Instrument.FullName!="ES 06-09) return;
...

here comes your code


}


regards

Andreas

P.S. Not sure what still to expect from this trading day... maybe there will be a relief rally after bernanke? I am not so convinced in this, so if then I will put little money in such a trade. Everybody seems on holidays, so better wait for monday

zweistein
05-22-2009, 11:04 AM
So,

just to mention: I will not contribute more, because usually I see the questions from other people, then I become curious and I want to try out and I want to help also. But fact is that when I am active in this forum I am NOT disciplined enough for trading.
In the end of the day I loose concentration on my own trades, - today I was waiting for the FGBL to break the 120, entered 2 times but always out of the trades with nothing, and now finally 10 minutes ago the expected move, offcours without me.

Please understand that I have:

My own trading first,

my own strategy development second ( my questions are more scientific as I am trying to find a clustering algoritm that reproduces my trade experience. Currently QT Clustering stuff, we will see..

my private life also


So ,

r2kTrader,

you can do the following, it should work: I used a NetObject Spy to find out and a lot of common sense:

[XmlIgnore()]
[Description("Instrument.")]
[Category("Data series")]
public Instrument Instrument {
get {returnbase.Instrument ;}
set {
NinjaTrader.Cbi.InstrumentList il =NinjaTrader.Cbi.InstrumentList.GetObject("Default"); // other lists also possible
foreach(Instrument i in il.Instruments) {
if(i.FullName=="ES 06-09") base.Instrument=i;
}
}
}

r2kTrader
05-22-2009, 05:50 PM
zweistein,

Thank you much.

For what it's worth, I will be happy to help you with your Clustering project.

Also, please remember, programmers don't always make the best traders and traders don't always make the best programmers. I have very strong market kung fu, reading markets I do well. (not bragging, I paid the cost).

If there is anything I can do to help you, let me know. I have a strong set of technical skills as it relates to technology and business. Feel free to pick my brain.

Laurent68
05-26-2009, 12:10 PM
hello,

seems to work well :)

any idea for obtain same thing (automatic setting) with Type (minute,...) and Value ?


That's so crazy this feature is not yet enable since begin in Ninja....

KBJ
05-26-2009, 07:28 PM
any idea for obtain same thing (automatic setting) with Type (minute,...) and Value ?

That's so crazy this feature is not yet enable since begin in Ninja....

Laurent68, It's not crazy, it's just a design limitation. In a real-time program like NinjaTrader there are many considerations and constraints the developers have to satisfy in order to implement what sometimes seems like a simple change. The developers are pushing the envelope on a lot of their work, so I guess we have to have a little patience.

I made a recent (05-20-2009 04:02 PM) posting showing how to check for expected values. Also, look at r2kTrader's clever technique re Add'ing another timeframe to make sure the desired timeframe is available.

There's also a little more on this in another thread: http://www.ninjatrader-support2.com/vb/showthread.php?t=1895 (which has my original code on how to check for an expected value, and how to use a special code setting to suppress certain parameter entries when starting the strategy.)

And more (on what not to do) in this thread:
http://www.ninjatrader-support2.com/vb/showthread.php?t=3423
(where I wrote some brilliant code where I was trying to work around this problem by dynamically selecting various timeframes during an Strategy Analyzer optimization -- but, although the code can be used to select a timeframe once, it won't work as intended in the optimizer using various timeframes to see which one is better.)

Laurent68
05-27-2009, 01:07 AM
Hello,

I have to make automatic trading on IB so I choose Ninja.
Feature about automatic setting was suggested more than 18 months ago, apparently always not available in ninja 7.
Order Gat (and more...) available in IB are not implemented on ninja.

Previous years according broker i trade full automatic trading (up to 15 strategy) on Tradestation and/or metatrader and/or Strategyrunner.
with ninja it's not automatic trading, it's assisted automatic trading with poor feature for that.

I have already code for check parameters, but i launch 12 strategy each morning, with different instrument, timeframe etc...

I need a software than i can trust.

Laurent68, It's not crazy, it's just a design limitation. In a real-time program like NinjaTrader there are many considerations and constraints the developers have to satisfy in order to implement what sometimes seems like a simple change. The developers are pushing the envelope on a lot of their work, so I guess we have to have a little patience.

I made a recent (05-20-2009 04:02 PM) posting showing how to check for expected values. Also, look at r2kTrader's clever technique re Add'ing another timeframe to make sure the desired timeframe is available.

There's also a little more on this in another thread: http://www.ninjatrader-support2.com/vb/showthread.php?t=1895 (which has my original code on how to check for an expected value, and how to use a special code setting to suppress certain parameter entries when starting the strategy.)

And more (on what not to do) in this thread:
http://www.ninjatrader-support2.com/vb/showthread.php?t=3423
(where I wrote some brilliant code where I was trying to work around this problem by dynamically selecting various timeframes during an Strategy Analyzer optimization -- but, although the code can be used to select a timeframe once, it won't work as intended in the optimizer using various timeframes to see which one is better.)

r2kTrader
05-27-2009, 02:32 PM
And more (on what not to do) in this thread:
http://www.ninjatrader-support2.com/vb/showthread.php?t=3423
(where I wrote some brilliant code where I was trying to work around this problem by dynamically selecting various timeframes during an Strategy Analyzer optimization -- but, although the code can be used to select a timeframe once, it won't work as intended in the optimizer using various timeframes to see which one is better.)

<tooting your horn>

Yes, it's brilliant!

r2kTrader
10-31-2009, 07:27 PM
zweistein,

I was re-visiting this issue today. I found a better way to hard code.

Basically don't put in the Description and the Category, rather just set the value of the part you want to "harden". The benefit is:

1. Less typing!

2. Categories like "Time frame" will not let you overwrite, rather 2 categories show up. It's not clean.

3. By not putting in a description or category, you still harden the value you want to preset, but it will preseve the description, etc. It's working fine for me.

Thought someone else may benefit from this.


Everything you define in
Initialize() will override the settings from the UI.

This is meant by hardcoded.
example

protectedoverridevoid Initialize()
{
CalculateOnBarClose = false;
BarsRequired=100;
ExitOnClose=false;
}

the rest is set by the UI, and the UI keeps the last selected value in memory and shows this.



Oh, I am just rreading the previous post better,

He is right and I am wrong!

NT team, please document better

There is a trick though:

Define the following property in your strategy class

[Description("Calculate on bar close")]
[Category("General")]
publicbool CalculateOnBarClose
{
get { return true; }
set { base.CalculateOnBarClose=true;}

}

should coerce to always true

and the UI will reflect this also!

same for the other Properties

r2kTrader
10-31-2009, 10:43 PM
Zweistein,

This is almost working. I don't think we can get better than this:


// [XmlIgnore()]
// [Description("Instrument")]
// [Category("Data series")]
public Instrument Instrument
{
get {returnbase.Instrument ;}
set
{
NinjaTrader.Cbi.InstrumentList il =NinjaTrader.Cbi.InstrumentList.GetObject("Default"); // other lists also possible
foreach(Instrument i in il.Instruments)
{
if(i.FullName.Contains("TF 09-09"))
{
base.Instrument=i;
Print("Startup Instrument " + base.Instrument.MasterInstrument.Name.ToString());

}

}
}
}


If you go to strategy tab and then click add strategy, then go to your strategy that has this code, then select instrument from the list and no matter what you select it will snap back to whatever you have between the Quotes. (The key was .Contains() with a partial string, that grabbed the right id.

I don't have a debugger setup yet, but if you could get the list for "Account" that would be great. I tried hard setting the account, but it only changes the name and it screws up the database. I looked at the mdb file and their is an Id with each account (see the table in the mdb file).

So we need to loop through the accounts and then grab the account we want to use. It should work like the other property settings.

Anyway, the code worked. But it's a little flaky. I also tried running similar code in a method and then calling the method on initialize, but it clearly doesn't want to let you change the Master nstrument during the initialization method.

I hope this helps. Thanks for your startup code. With a debugger, I could get a better look under the hood. If you could provide a simple how to for how you would go about getting the methods for a class that is not typically exposed, that would be great. I could use a bump!

So,

just to mention: I will not contribute more, because usually I see the questions from other people, then I become curious and I want to try out and I want to help also. But fact is that when I am active in this forum I am NOT disciplined enough for trading.
In the end of the day I loose concentration on my own trades, - today I was waiting for the FGBL to break the 120, entered 2 times but always out of the trades with nothing, and now finally 10 minutes ago the expected move, offcours without me.

Please understand that I have:

My own trading first,

my own strategy development second ( my questions are more scientific as I am trying to find a clustering algoritm that reproduces my trade experience. Currently QT Clustering stuff, we will see..

my private life also


So ,

r2kTrader,

you can do the following, it should work: I used a NetObject Spy to find out and a lot of common sense:

[XmlIgnore()]
[Description("Instrument.")]
[Category("Data series")]
public Instrument Instrument {
get {returnbase.Instrument ;}
set {
NinjaTrader.Cbi.InstrumentList il =NinjaTrader.Cbi.InstrumentList.GetObject("Default"); // other lists also possible
foreach(Instrument i in il.Instruments) {
if(i.FullName=="ES 06-09") base.Instrument=i;
}
}
}