string workspaceName = NinjaTrader.Gui.WorkspaceOptions.GetCurrentFilename(); Print(workspaceName); // C:\Users\matthew\Documents\NinjaTrader 7\workspaces\PMTests.xml
Announcement
Collapse
Looking for a User App or Add-On built by the NinjaTrader community?
Visit NinjaTrader EcoSystem and our free User App Share!
Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less
Partner 728x90
Collapse
NinjaTrader
Undocumented/Unsupported Ninja Tips and Tricks
Collapse
X
-
Originally posted by NinjaTrader_Matthew View PostYou can get the file name...
Code:string workspaceName = NinjaTrader.Gui.WorkspaceOptions.GetCurrentFilename(); Print(workspaceName); // C:\Users\matthew\Documents\NinjaTrader 7\workspaces\PMTests.xml
In other words, supposed there were two workspaces name "WS1" and "WS2". Supposed two different charts were loaded, one in WS1, and one in WS2. Suppose WS1 was currently being displayed on screen, and WS2 was hidden. Suppose the charts were running the exact same indicator code.
I'd like to be able to do the following in the indicator code:
if ( /* running in the currently visible workspace, whether it is WS1 or WS2 */ )
{
// execute indicator code
}
else
{
// return and do nothing
}
This way, I could save CPU cycles by making the indicator calculate only within the currently visible workspace.
Is there something in the WorkspaceOptions class that would help me do this? I could already run a hack by comparing the currently displayed workspace name to the current instrument loaded and run one workspace per instrument (thereby detecting if the code is actually executing in the currently visible workspace), but a better way of doing it would also be helpful.
Comment
-
Synch Strategy from Account Postions
Originally posted by rmt81 View PostThe following code appears to copy the account positions to the strategy positions:
protectedoverridevoid OnStartUp()
{
// Copy any outstanding Positions from the Account to the Strategy
for (int i = 0; i < Positions.GetLength(0); i++)
{
Position StratPos = Positions[i];
Position AcctPos = Account.Positions.FindByInstrument(StratPos.Instru ment);
if (AcctPos != null)
Positions.SetValue(AcctPos, i);
}
}
Are there any particular issues or problems that I should look out for when using this approach to synchronize the strategy to match the account?
It just needs a change at the end like this
Code:if (AcctPos ==null) AcctPos =new Cbi.Position(this.Account,this.Instrument,MarketPosition.Flat, 0,this.Instrument.MasterInstrument.Currency,0);//ie Account has no position in this instrument Positions.SetValue(AcctPos, i);
Partly to avoid the design oddities with multiple positions I only use one Position per strategy.
Comment
-
Identify which Account Orders were created by strategy
Originally posted by rmt81 View PostI suppose that if there was a possibility of orders left outstanding, I would need to do something similar for the Orders object as I did above for the Positions object.
For instance in Managed using a strategy that reverses position will cause overfill after enough trades.
Using Unmanaged strategy, if connection goes down while a limit order created by the strategy is active (and executes while connection down) then the strategy position gets out of sync when connection returns. In this case NT on reconnection will mark the limit order as status 'unknown' and unfilled (even though it IS filled on the server).
In order to be able to code a correct recovery we need to be able to differentiate the Account Orders that were created by our strategy from those created by something else (like TWS or another strategy). Here's a start at the code:
Code:Cbi.OrderCollection aoc = Account.Orders; for (int iaoc = 0; iaoc < aoc.Count; iaoc++) { Cbi.Order ao = aoc[iaoc]; if (ao.Instrument.MasterInstrument.Name == Instrument.MasterInstrument.Name) {//limit to account orders matching the strategy's instrument Print(string.Format("Instrument.MasterInstrument.Name={0}, OrderType={1}, Account.Name={2}, OrderState={3}, Quantity={4}, LimitPrice={5},StopPrice={6}, Filled={7}, Info={8}",ao.Instrument.MasterInstrument.Name, ao.OrderType, ao.Account.Name, ao.OrderState, ao.Quantity, ao.LimitPrice, ao.StopPrice, ao.Filled, ao.Info)); Print(string.Format(" Name={0}, Oco={1}, OverFill={2}, TerminatedState={3}, Token={4}, UserLink={5}, Gtd={6}, OrderId={7}, Provider={8}, Time={9}",ao.Name, ao.Oco, ao.OverFill, ao.TerminatedState, ao.Token, ao.UserLink, ao.Gtd, ao.OrderId, ao.Provider, ao.Time)); Print(ao.ToString()); Cbi.Order mso = this.Orders.FindByToken(ao.Token);//matching strategy order (null if not found) if (mso!=null) Print(" token indicates there's a matching strategy order"); Print(""); } }
You might think this would allow you to recover correct order status after a reconnect.
However in the case of IB: After a reconnect the way NT currently works is to change the status of orders, that were executed at IB during disconnect,to 'unknown'. This happens both to Account.Orders and to the strategies orders (this.Orders). This means that we don't seem to have a way to find, in code, out the true status of the orders (that were working at disconnection) after reconnection.
TWS does have the correct status (filled), and the execution is even recorded in NT's executions.txt file (after the reconnection), but no OnExecution() event is raised.
Does anyone know an undocumented method to query the real (TWS) status of an order?
Comment
-
How to get the expected end DateTime of bar being built
This code works for Minute or Second bars, if used in OnBarUpdate:
Code:DateTime dtEndOfWorkingBar= Bars.Get(CurrentBar+1).Time
Does anyone know how to get the expected DateTime end of the bar being built when using PeriodType.Day ?
NT must surely have this data item (lets call it dtEndOfWorkingBar), because I assume their code that builds bars does something like this:
if (dtTick > dtEndOfWorkingBar)
{
// close the working bar and start another one (recalculate dtEndOfWorkingBar)
// trigger OnBarUpdate
}
Comment
-
DaveE,
You can use GetNextBeginEnd() to get the end time for the day bar.
http://www.ninjatrader.com/support/h...xtbeginend.htmCal H.NinjaTrader Customer Service
Comment
-
Originally posted by NinjaTrader_Cal View PostDaveE,
You can use GetNextBeginEnd() to get the end time for the day bar.
http://www.ninjatrader.com/support/h...xtbeginend.htm
User wants Value>1 (say 2 day bars), or a session template is being used where there is not a break defined every trading date.
Comment
-
-
Some could help on the code wherein it can detect if the Buy/Sell Market button on the chart trader is being click?
Comment
-
GetBarIdxFromXPos
Hi:
Some code I worked up based off of the functionality in charthelper.cs.
This version, however, accurately gets the barIdx under the mouse (or x-pos) within the chart whether or not the chart has EquidistantBarSpacing set to TRUE or FALSE.
Included is a bonus function to get the last visible, valid bar index in the chart regardless of equidistant mode, timeframe or scrolling.
Code:public int ConvertXtoBarIdx(int x) { _debug = ""; if (chartControl == null) return 0; int numBarsOnCanvas = 0; int idxFirstBar = 0; int idxLastBar = 0; int barIndex; int firstBarX; double dRatio; int halfBarWidth = (int)Math.Round(((double)(chartControl.BarSpace / (double)2)), 0, MidpointRounding.AwayFromZero); if (!chartControl.EquidistantBars) { // This appears to always be valid when bars are NOT equidistant idxLastBar = Bars.GetBar(chartControl.LastBarTimePainted); barIndex = idxLastBar; firstBarX = chartControl.GetXByBarIdx(Bars, barIndex); // In my case I detect if the mouse is beyond the rightmost bar in the chart by testing it against the last VisibleBar as calculated // by the helper function below... // so if the mouse is beyond the rightmost bar, let's return a barIndex that is beyond the rightmost valid visible bar index... if (x > (firstBarX + halfBarWidth)) return (idxLastBar + 1); while (firstBarX > (x+halfBarWidth)) { barIndex--; firstBarX = chartControl.GetXByBarIdx(Bars, barIndex); } // firstBarX will be the exact center of the bar... // we want to return the same index for the entire bar so we account for that... if (x < (firstBarX - halfBarWidth)) barIndex--; else if (x > (firstBarX + halfBarWidth)) barIndex++; } else { if (chartControl.LastBarPainted < Bars.Count) { numBarsOnCanvas = chartControl.LastBarPainted - chartControl.FirstBarPainted; idxFirstBar = chartControl.FirstBarPainted; idxLastBar = chartControl.LastBarPainted; } else { numBarsOnCanvas = Bars.Count - chartControl.FirstBarPainted; idxFirstBar = chartControl.FirstBarPainted; idxLastBar = Bars.Count - 1; } firstBarX = chartControl.GetXByBarIdx(Bars, idxFirstBar); int margin = firstBarX + halfBarWidth; dRatio = 1 + ((x - margin) / (double)(chartControl.BarSpace)); int numberPeriods = (int)Math.Truncate(dRatio); barIndex = idxFirstBar + numberPeriods; _debug = "BarIndex = " + barIndex + " NumBarsCanvas= " + numBarsOnCanvas + " FirstBar=" + idxFirstBar + " LastBar=" + idxLastBar + " Ratio = " + dRatio + " NumPeriods =" + numberPeriods; } return barIndex; } public int GetLastValidVisibleBarIdx() { int idxLastBar; if (!chartControl.EquidistantBars) idxLastBar = Bars.GetBar(chartControl.LastBarTimePainted); else idxLastBar = chartControl.LastBarPainted; return Math.Min(idxLastBar, Bars.Count - 1); }
Comment
-
Coordinates for multi Panel
Hi,
I've been experimenting with charthelper and its basically working for me, which is great, but I haven't been able to get correct coordinates when the chart has extra panels in it.
I'm not sure if code modifications are required, or if its just a case of correctly initialising the bounds. Can anyone give me some tips, or example code on how to make these adjustments?
Thanks,
Will.
Comment
-
Backtest with Multiple Strategies
Hi everyone,
I am trying to create a strategy where I can instantiate other strategies and have them run.
This is my code. It actually gives an error but after ignoring it, it runs but only with the saved default settings. I should be able to change them.
Code:#region Using declarations using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Drawing2D; using System.Xml.Serialization; using NinjaTrader.Cbi; using NinjaTrader.Data; using NinjaTrader.Indicator; using NinjaTrader.Gui.Chart; using NinjaTrader.Strategy; #endregion namespace NinjaTrader.Strategy { public class MultiStrategyTest : Strategy { protected override void Initialize() { CalculateOnBarClose = false; Unmanaged = true; MaximumBarsLookBack = MaximumBarsLookBack.Infinite; BarsRequired = 0; IncludeCommission = true; Slippage = 1; ConnectionLossHandling = ConnectionLossHandling.KeepRunning; RealtimeErrorHandling = RealtimeErrorHandling.TakeNoAction; ExitOnClose = false; MultiThreadSupport = false; } public StrategyBase st1; protected override void OnStartUp() { if (st1 == null) { st1 = new NinjaTrader.Strategy.CoreOne(); st1.Account = this.Account; st1.CalculateOnBarClose = this.CalculateOnBarClose; st1.BarsRequired = this.BarsRequired; st1.FillType = this.FillType; st1.Slippage = this.Slippage; st1.BackTestFrom = this.BackTestFrom; st1.BackTestTo = this.BackTestTo; st1.BackTestMode = this.BackTestMode; st1.IncludeCommission = this.IncludeCommission; st1.MaximumBarsLookBack = this.MaximumBarsLookBack; st1.ExitOnClose = this.ExitOnClose; st1.TimeInForce = this.TimeInForce; st1.Instrument = this.Instrument; st1.SetBarsPeriodInstrument(this.Bars.Period, this.Instrument); st1.SetUp(); } if (!st1.Enabled) st1.Enabled = true; if (!st1.Running) st1.Running = true; } protected override void OnTermination() { if (st1 != null) { st1.Dispose(); st1 = null; } } protected override void OnBarUpdate() {} } }
I'll be waiting for your suggestions, thanks in advance.
Comment
Latest Posts
Collapse
Topics | Statistics | Last Post | ||
---|---|---|---|---|
Started by Noerclou, Today, 04:55 AM
|
0 responses
1 view
0 likes
|
Last Post
by Noerclou
Today, 04:55 AM
|
||
Started by llanqui, Yesterday, 09:59 AM
|
2 responses
16 views
0 likes
|
Last Post
by llanqui
Today, 04:00 AM
|
||
Started by ThoriSten, Today, 03:56 AM
|
0 responses
6 views
0 likes
|
Last Post
by ThoriSten
Today, 03:56 AM
|
||
Started by PhillT, 04-19-2024, 02:16 PM
|
3 responses
20 views
0 likes
|
Last Post
by mangel2000
Today, 03:04 AM
|
||
Started by TraderBCL, Today, 02:37 AM
|
0 responses
4 views
0 likes
|
Last Post
by TraderBCL
Today, 02:37 AM
|
Comment