NinjaScript - Intercepting order submission - futures io
futures io futures trading



NinjaScript - Intercepting order submission


Discussion in NinjaTrader

Updated by Jasonnator
      Top Posters
    1. looks_one askerix with 4 posts (7 thanks)
    2. looks_two Adfra with 4 posts (2 thanks)
    3. looks_3 Jasonnator with 3 posts (3 thanks)
    4. looks_4 planetkill with 2 posts (5 thanks)
      Best Posters
    1. looks_one planetkill with 2.5 thanks per post
    2. looks_two gomi with 2.0 thanks per post
    3. looks_3 askerix with 1.8 thanks per post
    4. looks_4 Jasonnator with 1.0 thanks per post
    1. trending_up 748 views
    2. thumb_up 19 thanks given
    3. group 9 followers
    1. forum 15 replies
    2. attach_file 1 attachments




Welcome to futures io: the largest futures trading community on the planet, with well over 100,000 members
  • Genuine reviews from real traders, not fake reviews from stealth vendors
  • Quality education from leading professional traders
  • We are a friendly, helpful, and positive community
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts
  • We are here to help, just let us know what you need
You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

(If you already have an account, login at the top of the page)

 
Search this Thread
 

NinjaScript - Intercepting order submission

(login for full post details)
  #1 (permalink)
Melbourne
 
Experience: Intermediate
Platform: NinjaTrader
Broker: MB Trading, Kinetick
Trading: Forex, AUD/USD
 
Posts: 18 since Aug 2011
Thanks: 11 given, 8 received

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

Can you help answer these questions
from other members on futures io?
FX Futures have been nagging me for a while
Currencies
Capping Size in Tradestation
TradeStation
SC parameter optimization
Sierra Chart
3x Fangdango
Traders Hideout
Macros for flatten and reverse
TradeStation
 
 
(login for full post details)
  #2 (permalink)
Site Moderator
Sarasota FL
 
Experience: Advanced
Platform: Sierra Chart
Trading: ES, YM
 
bobwest's Avatar
 
Posts: 5,966 since Jan 2013
Thanks: 45,965 given, 19,999 received


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
Visit my futures io Trade Journal Reply With Quote
 
(login for full post details)
  #3 (permalink)
Paris
 
Experience: None
Platform: NinjaTrader
 
Posts: 1,239 since Oct 2009
Thanks: 266 given, 4,361 received


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
The following 2 users say Thank You to gomi for this post:
 
(login for full post details)
  #4 (permalink)
Melbourne
 
Experience: Intermediate
Platform: NinjaTrader
Broker: MB Trading, Kinetick
Trading: Forex, AUD/USD
 
Posts: 18 since Aug 2011
Thanks: 11 given, 8 received


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

Reply With Quote
The following user says Thank You to Adfra for this post:
 
(login for full post details)
  #5 (permalink)
Switzerland
 
Experience: None
Platform: NT
Trading: Ukulele
 
Posts: 26 since Mar 2011
Thanks: 381 given, 31 received


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
 
(login for full post details)
  #6 (permalink)
Chicago IL
 
 
Posts: 73 since Apr 2016
Thanks: 183 given, 48 received


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
 
(login for full post details)
  #7 (permalink)
Switzerland
 
Experience: None
Platform: NT
Trading: Ukulele
 
Posts: 26 since Mar 2011
Thanks: 381 given, 31 received


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
The following user says Thank You to askerix for this post:
 
(login for full post details)
  #8 (permalink)
New York City + NY/United States
 
 
Posts: 237 since Sep 2018
Thanks: 90 given, 193 received

@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


Visit my futures io Trade Journal Reply With Quote
The following 3 users say Thank You to planetkill for this post:
 
(login for full post details)
  #9 (permalink)
Switzerland
 
Experience: None
Platform: NT
Trading: Ukulele
 
Posts: 26 since Mar 2011
Thanks: 381 given, 31 received


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
The following 3 users say Thank You to askerix for this post:
 
(login for full post details)
  #10 (permalink)
New York City + NY/United States
 
 
Posts: 237 since Sep 2018
Thanks: 90 given, 193 received


@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://ninjatrader.com/support/forum/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.

Visit my futures io Trade Journal Reply With Quote
The following 2 users say Thank You to planetkill for this post:


futures io Trading Community Platforms and Indicators NinjaTrader > NinjaScript - Intercepting order submission


September 6, 2020


Upcoming Webinars and Events
     



Copyright © 2020 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
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.
no new posts