Announcement
Collapse
No announcement yet.
Partner 728x90
Collapse
NinjaTrader
2 entry orders help!
Collapse
X
-
Hello Bob,
If you already have a working stop and limit exit order for the entry, you could either:
Move the limit behind the market price so it fills and exits the position immediately. For example changing a sell limit to the bid price minus a few ticks should cause it to fill immediately (unless there is a very large rapid price decrease before the order is accepted by the brokerage).
ChangeOrder(myLongExitLimitOrderVariableNameHere, myLongExitLimitOrderVariableNameHere.Quantity, GetCurrentBid() - 5 * TickSize, 0);
ChangeOrder(Order order, int quantity, double limitPrice, double stopPrice)
OR
Cancel the stop and limit with CancelOrder(). Then when the orders update as cancelled in OnOrderUpdate() submit a market order to close the position.
CancelOrder(myLongExitLimitOrderVariableNameHere);
CancelOrder(Order order)
In OnOrderUpdate():
if (order.Name == "myLongExitLimitOrderVariableNameHere" && order.OrderState == OrderState.Cancelled)
{
SubmitOrderUnmanaged(1, OrderAction.Sell, OrderType.Market, 1, 0, 0, string.Empty, "longMarketExit");
}
Note, if you are using Order type variables, these need to be assigned order objects from OnOrderUpdate() and not assigned from the order object returned from the SubmitOrderUmanaged() call.
The ProfitChaseStopTrailUnmanagedExample example linked below demonstrates assigning order objects to variables from OnOrderUpdate().
Leave a comment:
-
Hi Chelsea,Originally posted by NinjaTrader_ChelseaB View PostHello bobperez,
Scaling in:
Exiting a position:Code:if (Position.MarketPosition == MarketPosition.Long && Quantity == 1 /* other condtions to scale in here */) { SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Market, 1, 0, 0, string.Empty, "longEntry2"); }
These are just basic examples. Your logic will depend on what you are doing in the script. For example if you want to reverse the position and have a working stop loss and profit target using OCO working for a position, you would want to either just move the limit behind the market price and allow this to fill and exit the position and submit the entry when the limit order fills in OnExecutionUpdate(), or call CancelOrder() on the stop order and in OnOrderUpdate() detect the order is cancelled, and then submit the entry in the opposite direction.Code:if (Position.MarketPosition == MarketPosition.Long /* conditions to exit here */) { SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Market, Position.Quantity, 0, 0, string.Empty, "positionExit"); }
"Would I also need to create opposing Target and Stop-Loss child orders in OnExecutionUpdate()?"
This depends on what you want the script to do. You can submit a stop loss and limit target for any new entry if you want. If the first entry has a stop and limit target and you just want to adjust the quantity of these orders you could do that instead. Yes, this would be in OnExecutionUpdate() when a new entry fills.
I'm still not getting the results I expect.
If I have a long OCO position entered with longStopEntry1 = SubmitOrderUnmanaged(1, OrderAction.Buy, OrderType.StopMarket, Contracts1, 0, entry_price_L1, ocoString1, "longStopEntry1"); and it has its corresponding child target and stop-loss created in OnExecutionUpdate(), what command do I need to use to close this position?
Bob
Leave a comment:
-
Thank you, Chelsea. I'll see if I can get it right with your input.
Bob
Leave a comment:
-
Hello bobperez,
Scaling in:
Exiting a position:Code:if (Position.MarketPosition == MarketPosition.Long && Quantity == 1 /* other condtions to scale in here */) { SubmitOrderUnmanaged(0, OrderAction.Buy, OrderType.Market, 1, 0, 0, string.Empty, "longEntry2"); }
These are just basic examples. Your logic will depend on what you are doing in the script. For example if you want to reverse the position and have a working stop loss and profit target using OCO working for a position, you would want to either just move the limit behind the market price and allow this to fill and exit the position and submit the entry when the limit order fills in OnExecutionUpdate(), or call CancelOrder() on the stop order and in OnOrderUpdate() detect the order is cancelled, and then submit the entry in the opposite direction.Code:if (Position.MarketPosition == MarketPosition.Long /* conditions to exit here */) { SubmitOrderUnmanaged(0, OrderAction.Sell, OrderType.Market, Position.Quantity, 0, 0, string.Empty, "positionExit"); }
"Would I also need to create opposing Target and Stop-Loss child orders in OnExecutionUpdate()?"
This depends on what you want the script to do. You can submit a stop loss and limit target for any new entry if you want. If the first entry has a stop and limit target and you just want to adjust the quantity of these orders you could do that instead. Yes, this would be in OnExecutionUpdate() when a new entry fills.
Leave a comment:
-
Chelsea,
I got the code to close open positions at the session end.
Can you provide an example of:
"You can continue scaling in with new entries in the same direction if you would like. With the unmanaged approach you can submit new orders without the position being closed or previous orders cancelled.
If you want to exit the position, call SubmitOrderUnmanaged() with a market order in the opposite direction of the position. (For example if the position is Long 5, submit a sell market order with a quantity of 5)."
Would I also need to create opposing Target and Stop-Loss child orders in OnExecutionUpdate()?
Leave a comment:
-
Hello Bob,
"The issue with continuing to scale in is that the new OCO order may trigger a Short entry while the previous open order is in a Long position. This would generate an error, correct?"
This would depend on the broker and if they are sensitive to the OrderAction being correct in relation to the position. However, I would recommend that you submit an exit order using OrderAction.Sell before calling an entry with OrderAction.SellShort to ensure this works with all brokerages.
"I do prefer to rely on the Exit on session close behavior to cancel working orders and close open positions, but it does not seem to be working."
The forum post I've linked does have a video demonstrating the Exit on session close behavior does work, but does not prevent new entries after the event and before the end of the session.
The code you suggested does not appear to calling CancelOrder() to cancel any orders. Further there are no entry orders below the return that would not be reached.
Leave a comment:
-
Thank you Chelsea,Originally posted by NinjaTrader_ChelseaB View PostHello Bob,
"Regarding this topic, if two OCO orders are simultaneously filled at say 3:55 PM, each with different targets and stop-losses, and I want to enter again at 3:58 PM, do the 3:55 orders need to be closed before submitting the new ones at 3:58? If so, how do I close the open position?"
You can continue scaling in with new entries in the same direction if you would like. With the unmanaged approach, you can submit new orders without the position being closed or previous orders cancelled.
If you want to exit the position, call SubmitOrderUnmanaged() with a market order in the opposite direction of the position. (For example if the position is Long 5, submit a sell market order with a quantity of 5).
"Also, how do I close any open OCO orders at session end?"
If you are not wanting to rely on the Exit on session close behavior to cancel working orders and close open positions, you can write custom logic and use a SessionIterator to call CancelOrder() on working orders some time before the sesssion ends.
The PreventEntryAfterExitOnCloseExample example below has sample logic of using a sessionIterator.
NinjaTrader Community, A common inquiry is that the Exit on close didn't work in a NinjaScript Strategy because there is a position after the exit on close should have occurred. When viewing the log we often find that the Exit on close does indeed exit the position shortly before the end of the session (based on the Exit on
Instead of setting a bool to prevent new entries when the time is reached, you could instead call CancelOrder() and supply the variable holding the order.
Scale-In
- The issue with continuing to scale in is that the new OCO order may trigger a Short entry while the previous open order is in a Long position. This would generate an error, correct?
Custom SessionIterator
I do prefer to rely on the Exit on session close behavior to cancel working orders and close open positions, but it does not seem to be working. So I tried using your custom iterator:
I want to see Historical results, so I placed this command on the OnBarUpdate() method, instead of OnMarketData()Code:// prevents entry orders after the exit on close until the start of the new session private bool ExitOnCloseWait(DateTime QuickTime) { // the sessionIterator only needs to be updated when the session changes (after its first update) if (Bars.IsFirstBarOfSession) sessionIterator.GetNextSession(Time[0], true); // if after the exit on close, prevent new orders until the new session if (tickTime >= sessionIterator.ActualSessionEnd.AddSeconds(-ExitOnSessionCloseSeconds) && tickTime <= sessionIterator.ActualSessionEnd) exitOnCloseWait = true; // an exit on close occurred in the previous session, reset for a new entry on the first bar of a new session if (exitOnCloseWait && Bars.IsFirstBarOfSession) exitOnCloseWait = false; return exitOnCloseWait; }
Is there something I did incorrectly because it does not work either?Code:if (ExitOnCloseWait(Time[0])) { return; } sessionIterator.GetNextSession(Time[0], true);
Bob Perez
Leave a comment:
-
Hello Bob,
"Regarding this topic, if two OCO orders are simultaneously filled at say 3:55 PM, each with different targets and stop-losses, and I want to enter again at 3:58 PM, do the 3:55 orders need to be closed before submitting the new ones at 3:58? If so, how do I close the open position?"
You can continue scaling in with new entries in the same direction if you would like. With the unmanaged approach you can submit new orders without the position being closed or previous orders cancelled.
If you want to exit the position, call SubmitOrderUnmanaged() with a market order in the opposite direction of the position. (For example if the position is Long 5, submit a sell market order with a quantity of 5).
"Also, how do I close any open OCO orders at session end?"
If you are not wanting to rely on the Exit on session close behavior to cancel working orders and close open positions, you can write custom logic and use a SessionIterator to call CancelOrder() on working orders some time before the sesssion ends.
The PreventEntryAfterExitOnCloseExample example below has sample logic of using a sessionIterator.
NinjaTrader Community, A common inquiry is that the Exit on close didn't work in a NinjaScript Strategy because there is a position after the exit on close should have occurred. When viewing the log we often find that the Exit on close does indeed exit the position shortly before the end of the session (based on the Exit on
Instead of setting a bool to prevent new entries when the time is reached, you could instead call CancelOrder() and supply the variable holding the order.
Leave a comment:
-
Hi Chelsea,Originally posted by NinjaTrader_ChelseaB View PostHello bobperez,
In the UnmanagedOCOBracketExample_NT8 note I've used OrderType.StopMarket orders.
A buy stop order would be placed above the ask, a sell stop order would be placed below the bid.
In this code you have chosen to use OrderType.Limit which are placed on the reverse side of the market.
A buy limit would be placed below the ask, a sell limit would be placed above the bid.
I see in your code you've submitted the buy limit at the High of the most recently closed bar and the sell limit at the Low of the most recently closed bar. These orders will most likely be on the wrong side of the market when the new bar opens.
With some brokerages that order will be immediately filled (including NinjaTrader), with other brokerages that order would be rejected (such as Forex brokerages).
Also, orders should be assigned to variables in OnOrderUpdate() and not directly from the order method.
I've changed is and tested the suggested code and I am finding this is working.
Below is a link to a video of the test.
[ATTACH]n1295472[/ATTACH]
There are no exit orders or setting the variables back to null so it only places orders once, but this works as expected.
Regarding this topic, if two OCO orders are simultaneously filled at say 3:55 PM, each with different targets and stop-losses, and I want to enter again at 3:58 PM, do the 3:55 orders need to be closed before submitting the new ones at 3:58? If so, how do I close the open position?
Also, how do I close any open OCO orders at session end?
Thanks,
Bob Perez
Leave a comment:
-
Hello Bob,
With 'Wait until flat' and not 'Wait until flat synchronize account' and the exchange trading hours, I would not expect an order to be submitted while the market is closed.
If you would like me to investigate further, please send an email to scriptingsupport[at]ninjatrader[dot]com so that I may request your log and trace files.
In the email, please include a link to this forum thread.
Leave a comment:
-
'use instrument settings' I : YesOriginally posted by NinjaTrader_ChelseaB View PostHello Bob,
During the weekend the markets are closed and there is no real-time data.
However the Trading hours template should have prevented any trades.
Do you have Trading hours set to 'use instrument settings' in the Data Series window?
What Start behavior is selected in the Strategies window?
Start behavior I: Waiting UntilFlat
Bob
Leave a comment:
-
Hello Bob,
During the weekend the markets are closed and there is no real-time data.
However the Trading hours template should have prevented any trades.
Do you have Trading hours set to 'use instrument settings' in the Data Series window?
What Start behavior is selected in the Strategies window?
Leave a comment:
-
HI Chelsea, During the weekend I was connected to Rithmic, as well as today. Today it worked fine.Originally posted by NinjaTrader_ChelseaB View PostHello bobperez,
The message is stating there is no real-time data.
Who are you connected to for data? (Do you see changing ask and bid prices in Chart Trader?)
Are these orders being submitted during market hours?
Bob
Leave a comment:
-
Hello bobperez,
The message is stating there is no real-time data.
Who are you connected to for data? (Do you see changing ask and bid prices in Chart Trader?)
Are these orders being submitted during market hours?
Leave a comment:
Latest Posts
Collapse
| Topics | Statistics | Last Post | ||
|---|---|---|---|---|
|
Started by CarlTrading, 05-11-2026, 05:56 AM
|
0 responses
56 views
0 likes
|
Last Post
by CarlTrading
05-11-2026, 05:56 AM
|
||
|
Started by CarlTrading, 05-10-2026, 08:12 PM
|
0 responses
33 views
0 likes
|
Last Post
by CarlTrading
05-10-2026, 08:12 PM
|
||
|
Started by Hwop38, 05-04-2026, 07:02 PM
|
0 responses
195 views
0 likes
|
Last Post
by Hwop38
05-04-2026, 07:02 PM
|
||
|
Started by CaptainJack, 04-24-2026, 11:07 PM
|
0 responses
359 views
0 likes
|
Last Post
by CaptainJack
04-24-2026, 11:07 PM
|
||
|
Started by Mindset, 04-21-2026, 06:46 AM
|
0 responses
280 views
0 likes
|
Last Post
by Mindset
04-21-2026, 06:46 AM
|
Leave a comment: