NexusFi: Find Your Edge


Home Menu

 





NinjaScript - Intercepting order submission


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one askerix with 4 posts (8 thanks)
    2. looks_two Adfra with 4 posts (2 thanks)
    3. looks_3 Jasonnator with 3 posts (4 thanks)
    4. looks_4 planetkill with 2 posts (6 thanks)
      Best Posters
    1. looks_one planetkill with 3 thanks per post
    2. looks_two askerix with 2 thanks per post
    3. looks_3 gomi with 2 thanks per post
    4. looks_4 Jasonnator with 1.3 thanks per post
    1. trending_up 4,789 views
    2. thumb_up 22 thanks given
    3. group 9 followers
    1. forum 15 posts
    2. attach_file 1 attachments




 
Search this Thread

NinjaScript - Intercepting order submission

  #1 (permalink)
 Adfra 
Melbourne
 
Experience: Intermediate
Platform: NinjaTrader
Broker: MB Trading, Kinetick
Trading: Forex, AUD/USD
Posts: 19 since Aug 2011
Thanks Given: 11
Thanks Received: 9

Hi there,

Looking for some pointers or a code snippet that would allow me to intercept (and cancel!) a users order submission. So to be precise: I'd like to:

a) intercepts the button clicks on the chart trader (buy market, sell market etc.)
b) evaluate certain conditions and
c) based on the result cancel the submission of the order under certain circumstances


From the NT forum I found the relevant script that let's me trigger additional activities off the back of the button clicks, so effectively a) and b) are sorted. My problem is that I am unable to cancel the order once it is submitted.

My thinking is:
- OnClick Event => Evaluate Condition => Cancel event submission (i.e. order)

...alternatively maybe implement this as a strategy and work with onOrderUpdate() and check for orderState.Initialised and then update the orderState to Cancelled.

Preferred would be to have this as a generic addon which just runs in the background rather than an indicator or strategy, but at this stage - any will do

Another option would be to implement new buttons which do the checks first and then submit the orders only when conditions are met.

Thanks in advance!
Frank

Started this thread Reply With Quote

Can you help answer these questions
from other members on NexusFi?
MC PL editor upgrade
MultiCharts
Pivot Indicator like the old SwingTemp by Big Mike
NinjaTrader
Better Renko Gaps
The Elite Circle
Increase in trading performance by 75%
The Elite Circle
ZombieSqueeze
Platforms and Indicators
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Just another trading journal: PA, Wyckoff & Trends
33 thanks
Tao te Trade: way of the WLD
24 thanks
My NQ Trading Journal
14 thanks
HumbleTraders next chapter
11 thanks
GFIs1 1 DAX trade per day journal
11 thanks
  #2 (permalink)
 
bobwest's Avatar
 bobwest 
Western Florida
Site Moderator
 
Experience: Advanced
Platform: Sierra Chart
Trading: ES, YM
Frequency: Several times daily
Duration: Minutes
Posts: 8,168 since Jan 2013
Thanks Given: 57,433
Thanks Received: 26,276


Adfra View Post
Looking for some pointers or a code snippet that would allow me to intercept (and cancel!) a users order submission. So to be precise: I'd like to:

a) intercepts the button clicks on the chart trader (buy market, sell market etc.)
b) evaluate certain conditions and
c) based on the result cancel the submission of the order under certain circumstances

I don't have an answer, or any idea really, but this seems like an attempt to impose a last-ditch trade discipline on the trader.... which I can understand, knowing I sometimes ask myself afterward, "Why did I do that???"

Is this the intention? Just asking.

Or is it simply a last-minute check that the trader accurately took everything, or certain critical things, into account?

I could see value in both.

I hope someone responds with some actual coding help.

Bob.

When one door closes, another opens.
-- Cervantes, Don Quixote
Reply With Quote
  #3 (permalink)
 gomi 
Paris
Market Wizard
 
Experience: None
Platform: NinjaTrader
Posts: 1,270 since Oct 2009
Thanks Given: 282
Thanks Received: 4,505


I've tried using discipline aids like in Sierra using the "halt trading after some loss is met", and multiple times I have disabled them after they triggered.
So you need discipline to not disable the aid.
But then if you're disciplined you don't need the aid :-)

Reply With Quote
Thanked by:
  #4 (permalink)
 Adfra 
Melbourne
 
Experience: Intermediate
Platform: NinjaTrader
Broker: MB Trading, Kinetick
Trading: Forex, AUD/USD
Posts: 19 since Aug 2011
Thanks Given: 11
Thanks Received: 9


bobwest View Post
I don't have an answer, or any idea really, but this seems like an attempt to impose a last-ditch trade discipline on the trader.... which I can understand, knowing I sometimes ask myself afterward, "Why did I do that???"

Is this the intention? Just asking.

Hi Bob,

Spot on - it is intended as an approach to define a few market conditions under which I am happy to trade. e.g. something simple like "Only allow trades in direction of the 15min moving avg." and intercept attempts to do otherwise. The intend is to keep the "inner monkey" (refer FT71) in check which just clicks too much, too large and without consideration of context parameters. I anticipate it to be easy to disable, but I think it would still help me personally to just avoid dumb and expensive trades that severely damage my account.

Hope there is a technical way to actually do this

Cheers!
Frank

Started this thread Reply With Quote
Thanked by:
  #5 (permalink)
 askerix 
Zurich Switzerland
 
Experience: None
Platform: NT
Trading: Ukulele
Frequency: Never
Duration: Never
Posts: 60 since Mar 2011
Thanks Given: 554
Thanks Received: 62


Adfra View Post
Hi there,

Another option would be to implement new buttons which do the checks first and then submit the orders only when conditions are met.

This!

You can register additional functions to the original buttons but you can't intercept their trade execution. Therefore you need to place your order through additional buttons that you can inject in the charttrader via an indicator. There you can implement all you checks before executing the order.
When you place an simple order or an ATMStrategy with your new buttons the existing cancel button is still working for them.

You already found the main thread in the NT forum for this topic.

hth
askerix

Reply With Quote
  #6 (permalink)
userque
Chicago IL
 
Posts: 180 since Apr 2016
Thanks Given: 573
Thanks Received: 130


askerix View Post
...You can register additional functions to the original buttons but you can't intercept their trade execution. ...

If this is the case, can a new function be to close the newly opened position (or cancel the newly placed order)?

I ask because the OP stated they have a discipline issue, so ... Why would such a person click the button that might block what they want to do; instead of clicking the button that will certainly execute what they want to do?

The goal of self-forcing compliance, should be to make it as difficult as possible to timely circumvent the mechanism; otherwise, it won't work.

Just my opinions.

Reply With Quote
  #7 (permalink)
 askerix 
Zurich Switzerland
 
Experience: None
Platform: NT
Trading: Ukulele
Frequency: Never
Duration: Never
Posts: 60 since Mar 2011
Thanks Given: 554
Thanks Received: 62


userque View Post
If this is the case, can a new function be to close the newly opened position (or cancel the newly placed order)?

yes - could also be possible.

but finding a solution to hide the original charttrader entry-buttons seems to me a lot easier than implementing a solid order (and order state, ATM attached? OCO? ... ) detection function for an unknown entry order.

Reply With Quote
Thanked by:
  #8 (permalink)
 planetkill 
New York City + NY/United States
 
Posts: 356 since Sep 2018
Thanks Given: 108
Thanks Received: 302

@Adfra I agree with @askerix that it may be easier to create custom buttons to do everything you want and hide the original buttons, instead of reprogramming the original order buttons.

I used the sample ChartTraderCustomButtonsExample code from the NT support thread you linked to create buttons tho submit a buy/sell stop limit orders at the high/low of the current & previous bar. The code can be modified to submit a different order type and add additional if conditions for your own rules. Here are the relevant parts to add within ChartTraderCustomButtonsExample

 
Code
protected override void OnBarUpdate() 
		{
			if (CurrentBar < 1)
			return;	
			
			high = High[0];
			low = Low[0];
			high1 = High[1];
			low1 = Low[1];

			
			
		}
			
			
		
		
protected void Button1Click(object sender, RoutedEventArgs e)
		{
			
			//Account Selector
			NinjaTrader.Gui.Tools.AccountSelector chartTraderAccountSelector = Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlAccountSelector") as NinjaTrader.Gui.Tools.AccountSelector;
			//Print(chartTraderAccountSelector.SelectedAccount.DisplayName);
			//Print(chartTraderAccountSelector.SelectedAccount.Name);
			Account a = chartTraderAccountSelector.SelectedAccount;

			//Quantity saved in quantitySelector.Value
			NinjaTrader.Gui.Tools.QuantityUpDown quantitySelector = (Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlQuantitySelector") as NinjaTrader.Gui.Tools.QuantityUpDown);
			//Print("Quantity: " + quantitySelector.Value);
			
			//Instrument Name
			//Print(Instrument.FullName);	
			
			//ATM Strategy
			//NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrategySelector ATMselector = Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlATMStrategySelector") as NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrategySelector;
			//Print(ATMselector.);
			
			price = Math.Max(high, high1);

			//Submit Buy Stop Limit Order
			Order buyOrder = a.CreateOrder(Instrument, OrderAction.Buy, OrderType.StopLimit, TimeInForce.Day, quantitySelector.Value, price + .25, price + .25, string.Empty, "Entry", null);
            NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy("1", buyOrder);
			

			ForceRefresh();
		}

protected void Button2Click(object sender, RoutedEventArgs e)
		{
			//Account Selector
			NinjaTrader.Gui.Tools.AccountSelector chartTraderAccountSelector = Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlAccountSelector") as NinjaTrader.Gui.Tools.AccountSelector;
			Account a = chartTraderAccountSelector.SelectedAccount;

			//Quantity saved in quantitySelector.Value
			NinjaTrader.Gui.Tools.QuantityUpDown quantitySelector = (Window.GetWindow(ChartControl.Parent).FindFirst("ChartTraderControlQuantitySelector") as NinjaTrader.Gui.Tools.QuantityUpDown);
			
			price = Math.Min(low, low1);
			
			//Submit Sell Stop Limit Order
			Order sellOrder = a.CreateOrder(Instrument, OrderAction.Sell, OrderType.StopLimit, TimeInForce.Day, quantitySelector.Value, price - .25, price - .25, string.Empty, "Entry", null);
            NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy("1", sellOrder);
			
			ForceRefresh();
		}
It will use the account, quantity, and instrument already selected in chart trader. I didn't do the ATM strat, so you just need to change the hard coded name from "1" to whatever the name of your ATM strat is. If you make improvements, please let me know if you figure out how to auto select the ATM strat already selected in chart trader instead of having it hard coded like I have it.





Adfra View Post
Hi there,

Looking for some pointers or a code snippet that would allow me to intercept (and cancel!) a users order submission. So to be precise: I'd like to:

a) intercepts the button clicks on the chart trader (buy market, sell market etc.)
b) evaluate certain conditions and
c) based on the result cancel the submission of the order under certain circumstances


From the NT forum I found the relevant script that let's me trigger additional activities off the back of the button clicks, so effectively a) and b) are sorted. My problem is that I am unable to cancel the order once it is submitted.

My thinking is:
- OnClick Event => Evaluate Condition => Cancel event submission (i.e. order)

...alternatively maybe implement this as a strategy and work with onOrderUpdate() and check for orderState.Initialised and then update the orderState to Cancelled.

Preferred would be to have this as a generic addon which just runs in the background rather than an indicator or strategy, but at this stage - any will do

Another option would be to implement new buttons which do the checks first and then submit the orders only when conditions are met.

Thanks in advance!
Frank


Reply With Quote
Thanked by:
  #9 (permalink)
 askerix 
Zurich Switzerland
 
Experience: None
Platform: NT
Trading: Ukulele
Frequency: Never
Duration: Never
Posts: 60 since Mar 2011
Thanks Given: 554
Thanks Received: 62


planetkill View Post
... If you make improvements, please let me know if you figure out how to auto select the ATM strat already selected in chart trader instead of having it hard coded like I have it....

@planetkill
here is a solution to place the order with an ATMStrategy attached:
 
Code
Order entryOrderLong;
AtmStrategy longStrat;

NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrategySelector atmSelector ;

atmSelector = chartTraderControl.FindFirst("ChartTraderControlATMStrategySelector") as NinjaTrader.Gui.NinjaScript.AtmStrategy.AtmStrategySelector;
AtmStrategy strat = atmSelector.SelectedAtmStrategy;

if ( strat == null)
{
Print("No Strat selected");
// cancel exection 
}
// prepare Order
entryOrderLong = usedAccount.CreateOrder(Instrument, OrderAction.Buy, OrderType.StopLimit, strat.TimeInForce, chartTraderControl.Quantity,entryprice,entryprice, string.Empty, "Entry", null);
				
// submit order
entryOrderLong.Account.Submit(new[] { entryOrderLong });
				
// attach ATM Strategy
longStrat =  NinjaTrader.NinjaScript.AtmStrategy.StartAtmStrategy(strat, entryOrderLong);

I use a similar setup to place stop limit orders above developing Range bars.
created entry orders (with attached ATM Strategy) can be adjusted with this code when the Order object is stored in the indicator:

 
Code
// set new values
entryOrderLong.LimitPriceChanged = newbuyHighPrice;
entryOrderLong.StopPriceChanged = newbuyHighPrice;
// submit changed order
entryOrderLong.Account.Change(new[] { entryOrderLong });
hope this helps
askerix

Reply With Quote
Thanked by:
  #10 (permalink)
 planetkill 
New York City + NY/United States
 
Posts: 356 since Sep 2018
Thanks Given: 108
Thanks Received: 302


@askerix Thank you for the help with selecting the ATM strat.

The code for adjusting the stop price is very helpful too. I want to attach the stop to an indicator (trail by 1 tick below the previous bar). From NT support threads, it doesn't look like there is a built in function to attach a stop to an indicator in code. https://forum.ninjatrader.com/forum/ninjatrader-8/platform-technical-support-aa/96961-attaching-orders-to-indicators-automatically

In my case I am using buy/sell stop limit orders, so after the code submits the order, the order will sit until it is executed or canceled.
I'm guessing I'll need to check if the order was executed and if there is an active stop, OnOrderUpdate.

Reply With Quote
Thanked by:




Last Updated on September 6, 2020


© 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