NexusFi: Find Your Edge


Home Menu

 





Code for range break out strategy


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one NJAMC with 6 posts (3 thanks)
    2. looks_two fctrader with 5 posts (7 thanks)
    3. looks_3 ticker with 3 posts (1 thanks)
    4. looks_4 baruchs with 2 posts (2 thanks)
      Best Posters
    1. looks_one traderwerks with 2 thanks per post
    2. looks_two fctrader with 1.4 thanks per post
    3. looks_3 baruchs with 1 thanks per post
    4. looks_4 NJAMC with 0.5 thanks per post
    1. trending_up 15,662 views
    2. thumb_up 16 thanks given
    3. group 11 followers
    1. forum 22 posts
    2. attach_file 0 attachments




 
Search this Thread

Code for range break out strategy

  #1 (permalink)
 
ticker's Avatar
 ticker 
Houston TX
 
Experience: Advanced
Platform: NinjaTrader
Trading: TF
Posts: 49 since Oct 2010
Thanks Given: 63
Thanks Received: 9

Code for range break out strategy - (in ninjatrader) Im attempting to write a simple strategy to enter a trade after price breaks the range of a given time period.

Example, if price breaks the high of the 9:00 to 9:30 price range then go long for 1 point... or if price breaks the low of the 9:00 to 9:30 price range, then go short for 1 point...

Lots of sharp people, would appreciate your insights, thanks!

*****************
original question edited for to better articulate the challenge...thanks

- Ticker

Started this thread Reply With Quote
The following user says Thank You to ticker for this post:

Can you help answer these questions
from other members on NexusFi?
NexusFi Journal Challenge - April 2024
Feedback and Announcements
Request for MACD with option to use different MAs for fa …
NinjaTrader
My NT8 Volume Profile Split by Asian/Euro/Open
NinjaTrader
ZombieSqueeze
Platforms and Indicators
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Retail Trading As An Industry
67 thanks
Battlestations: Show us your trading desks!
48 thanks
NexusFi site changelog and issues/problem reporting
47 thanks
GFIs1 1 DAX trade per day journal
32 thanks
What percentage per day is possible? [Poll]
31 thanks

  #3 (permalink)
 
Big Mike's Avatar
 Big Mike 
Manta, Ecuador
Site Administrator
Developer
Swing Trader
 
Experience: Advanced
Platform: Custom solution
Broker: IBKR
Trading: Stocks & Futures
Frequency: Every few days
Duration: Weeks
Posts: 50,322 since Jun 2009
Thanks Given: 33,143
Thanks Received: 101,476


 
Thread Moved


Moved to NinjaTrader Programming



When creating a new thread, note which subforum you are in. Here is a short list of suggestions:

- Topic: Anything to do with an Elite indicator -> Subforum: The Elite Circle
- Topic: Looking for an existing indicator, or how-to use an indicator -> Subforum: (the platform)
- Topic: Programmer needing help with non-Elite indicator -> Subforum: (the platform) - Programming
- Topic: Want an indicator created/modified -> Reply to "Want indicator created free" in Elite Circle
- Topic: Vendors (trading rooms, commercial indicators) -> Subforum: Vendors/Product Reviews
- Topic: Discussion of Forex or Currency trading -> Subforum: Forex and Currency Trading
- Topic: Journals of your trading -> Subforum: Trading Journals or Elite Trading Journals
- Topic: General trading related discussions -> Subforum: Traders Hideout
- Topic: Discussion of a trading method -> Subforum: Traders Hideout
- Topic: Automated Trading -> Subforum: Elite Automated Trading

Last, any Elite Member may create more or less any of these topics in The Elite Circle at your own discretion (your support is appreciated).

This is just a short general list and doesn't cover everything. If you are unsure where to create your new thread, just create it in Traders Hideout and a moderator will move it if necessary.

-- Big Mike Trading


We're here to help: just ask the community or contact our Help Desk

Quick Links: Change your Username or Register as a Vendor
Searching for trading reviews? Review this list
Lifetime Elite Membership: Sign-up for only $149 USD
Exclusive money saving offers from our Site Sponsors: Browse Offers
Report problems with the site: Using the NexusFi changelog thread
Follow me on Twitter Visit my NexusFi Trade Journal Reply With Quote
  #4 (permalink)
 
NJAMC's Avatar
 NJAMC 
Atkinson, NH USA
Market Wizard
 
Experience: Intermediate
Platform: NinjaTrader 8/TensorFlow
Broker: NinjaTrader Brokerage
Trading: Futures, CL, ES, ZB
Posts: 1,970 since Dec 2010
Thanks Given: 3,037
Thanks Received: 2,394


ticker View Post
Code for range break out strategy - (in ninjatrader) Im attempting to write a simple strategy to enter a trade after price breaks the range of a given time period. Example, if price breaks out long after 9:00 to 9:30 then go long for 1 point... or if price breaks the low from 9:00 to 9:30, then go short for 1 point...
Lots of sharp people, would appreciate your insights, thanks!

Hi,

This is the type of flexibility I was adding to NT using the LOM. This can only be done with unmanaged transactions which require a lot of overhead in NT7. The LOM project on futures.io (formerly BMT) is designed to encapsulate that complexity and give very complex transactions with minimal programming effort.

I will bring your attention to 2 functions:
publicvoid SetAutoSLPTTicks(int m_StopLoss, int m_ProfitTarget,int m_PositionNumber)
publicbool GoMarketBracket(int m_SharesTraded,double low,double high,int m_PositionNumber)


Use the first function in LOM to set your automatic SL & PT in Ticks. The 2nd function would be in your main OnBarUpdate () or OnMarketData() functions to set the High & Low brackets you wish to enter. Once the order is filled, LOM will set the SL & PT correctly depending if the Short or Long was entered based upon your bracket.

Nil per os
-NJAMC [Generic Programmer]

LOM WIKI: NT-Local-Order-Manager-LOM-Guide
Artificial Bee Colony Optimization
Visit my NexusFi Trade Journal Reply With Quote
The following 2 users say Thank You to NJAMC for this post:
  #5 (permalink)
 baruchs 
Israel
 
Experience: Intermediate
Platform: NinjaTrader
Broker: pfg
Trading: eminis
Posts: 323 since Jun 2009


Quoting 
This can only be done with unmanaged transactions

Are you sure?

Reply With Quote
  #6 (permalink)
 
serac's Avatar
 serac 
Arizona, USA
 
Experience: Intermediate
Platform: NinjaTrader
Broker: MB Trading
Trading: Cello
Posts: 116 since Jan 2011
Thanks Given: 321
Thanks Received: 138


baruchs View Post
Are you sure?


I'm sure.

Concurrent [AUTOLINK]Stop Orders[/AUTOLINK]? - [AUTOLINK]NinjaTrader[/AUTOLINK] Support Forum

Reply With Quote
The following user says Thank You to serac for this post:
  #7 (permalink)
 fctrader 
Fort Collins, Colorado
 
Experience: Intermediate
Platform: NT7
Trading: ES
Posts: 57 since Feb 2011
Thanks Given: 48
Thanks Received: 45

Here is some simple code that does what you want. It has no stop-loss / profit-targets, and it doesn't display the opening range on the chart, but those are easy to add yourself.

I could be missing something, since others seem to think it isn't possible, but it seems to work for opening an order based on your criteria. Adding a profit target should be as easy as picking the amount away from your entry. I wrote it from the ground up, and I have to profess, I don't know anything about "unmanaged transactions" so tell me if I missed something.

 
Code
public class OpenRangeBreakout : Strategy
    {
        #region Variables
        // Wizard generated variables
        // User defined variables (add any user defined variables below)
			private double CurrentDay;
			private double CurrentOpenRangeHigh;
			private double CurrentOpenRangeLow;
        #endregion

        /// <summary>
        /// This method is used to configure the strategy and is called once before any strategy method is called.
        /// </summary>
        protected override void Initialize()
        {
            CalculateOnBarClose = true;
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            // Condition set 1
            if (ToDay(Time[0]) != CurrentDay)
			{
				CurrentDay = ToDay(Time[0]);
				CurrentOpenRangeHigh = 0;
				CurrentOpenRangeLow = 100000;
			}
			if (ToTime(Time[0]) >= ToTime(9, 0, 0)
                && ToTime(Time[0]) <= ToTime(9, 30, 0))
            {
                if (High[0] > CurrentOpenRangeHigh)
				{
					CurrentOpenRangeHigh = High[0];
				}
				if (Low[0] < CurrentOpenRangeLow)
				{
					CurrentOpenRangeLow = Low[0];
				}
            }
			if (ToTime(Time[0]) > ToTime(9, 30, 0) && ToTime(Time[0]) < ToTime(16, 0, 0))
			{
				if (Close[0] > CurrentOpenRangeHigh)
				{
					EnterLong(DefaultQuantity, "");
				}
				if (Close[0] < CurrentOpenRangeLow)
				{
					EnterShort(DefaultQuantity, "");
				}
			}
        }
As it is currently written, it will enter the trade, and then in the analyzer, close it at the end of day if you have it set to do so.

Hope it helps.

Visit my NexusFi Trade Journal Reply With Quote
The following user says Thank You to fctrader for this post:
  #8 (permalink)
 fctrader 
Fort Collins, Colorado
 
Experience: Intermediate
Platform: NT7
Trading: ES
Posts: 57 since Feb 2011
Thanks Given: 48
Thanks Received: 45

For fun... Here it is with a 4 tick Profit Target and a 4 tick Stop Loss. Because it has targets and losses, I have made it so that it only goes long once per day, and short once per day. If you want it to only trade on the first break, change both the "LongTrade" and "ShortTrade" to be just TodaysTrade, and you will get only one trade per day.

 
Code
 /// Buys a breakout above Opening Range. Sells a breakout below.
    /// </summary>
    [Description("Buys a breakout above Opening Range. Sells a breakout below.")]
    public class OpenRangeBreakout : Strategy
    {
        #region Variables
        // Wizard generated variables
        // User defined variables (add any user defined variables below)
			private double CurrentDay;
			private double CurrentOpenRangeHigh;
			private double CurrentOpenRangeLow;
			private int LongTrade;
			private int ShortTrade;
        #endregion

        /// <summary>
        /// This method is used to configure the strategy and is called once before any strategy method is called.
        /// </summary>
        protected override void Initialize()
        {
            CalculateOnBarClose = true;
			SetProfitTarget("", CalculationMode.Ticks, 4);
            SetStopLoss("", CalculationMode.Ticks, 4, true);
        }

        /// <summary>
        /// Called on each bar update event (incoming tick)
        /// </summary>
        protected override void OnBarUpdate()
        {
            // Condition set 1
            if (ToDay(Time[0]) != CurrentDay)
			{
				CurrentDay = ToDay(Time[0]);
				CurrentOpenRangeHigh = 0;
				CurrentOpenRangeLow = 100000;
				LongTrade = 0;
				ShortTrade = 0;
			}
			if (ToTime(Time[0]) >= ToTime(9, 0, 0)
                && ToTime(Time[0]) <= ToTime(9, 30, 0))
            {
                if (High[0] > CurrentOpenRangeHigh)
				{
					CurrentOpenRangeHigh = High[0];
				}
				if (Low[0] < CurrentOpenRangeLow)
				{
					CurrentOpenRangeLow = Low[0];
				}
            }
			if (ToTime(Time[0]) > ToTime(9, 30, 0) && ToTime(Time[0]) < ToTime(16, 0, 0))
			{
				if (Close[0] > CurrentOpenRangeHigh && LongTrade <1)
				{
					EnterLong(DefaultQuantity, "");
					LongTrade++;
				}
				if (Close[0] < CurrentOpenRangeLow && ShortTrade < 1)
				{
					EnterShort(DefaultQuantity, "");
					ShortTrade++;
				}
			}
        }

Visit my NexusFi Trade Journal Reply With Quote
The following 3 users say Thank You to fctrader for this post:
  #9 (permalink)
 
NJAMC's Avatar
 NJAMC 
Atkinson, NH USA
Market Wizard
 
Experience: Intermediate
Platform: NinjaTrader 8/TensorFlow
Broker: NinjaTrader Brokerage
Trading: Futures, CL, ES, ZB
Posts: 1,970 since Dec 2010
Thanks Given: 3,037
Thanks Received: 2,394



Good find, it is worth trying as a managed OCO order. Here is the recommended approach:

 
Code
SubmitOrder(0,OrderAction.Buy,OrderType.Stop, 1, 0, Close[0] + 10 * TickSize, "EntryStopOCO", "BuyStopEntry" );

SubmitOrder(0, OrderAction.Sell, OrderType.Stop, 1, 0, Close[0] - 10 * TickSize, "EntryStopOCO", "SellStopEntry");
Thanks @serac

Nil per os
-NJAMC [Generic Programmer]

LOM WIKI: NT-Local-Order-Manager-LOM-Guide
Artificial Bee Colony Optimization
Visit my NexusFi Trade Journal Reply With Quote
  #10 (permalink)
 
NJAMC's Avatar
 NJAMC 
Atkinson, NH USA
Market Wizard
 
Experience: Intermediate
Platform: NinjaTrader 8/TensorFlow
Broker: NinjaTrader Brokerage
Trading: Futures, CL, ES, ZB
Posts: 1,970 since Dec 2010
Thanks Given: 3,037
Thanks Received: 2,394



fctrader View Post
Here is some simple code that does what you want. It has no stop-loss / profit-targets, and it doesn't display the opening range on the chart, but those are easy to add yourself.

I could be missing something, since others seem to think it isn't possible, but it seems to work for opening an order based on your criteria. Adding a profit target should be as easy as picking the amount away from your entry. I wrote it from the ground up, and I have to profess, I don't know anything about "unmanaged transactions" so tell me if I missed something.

As it is currently written, it will enter the trade, and then in the analyzer, close it at the end of day if you have it set to do so.

Hope it helps.

Hi @fctrader,

Your approach here works, but your OCO bracket is driven by your PC. These are not live orders on the market, but you go Long/Short when you detect the event. You could set this to run per tick to minimize slipage if you have a large movement on one bar.

I think the intent was to have two live StopLimit orders, one in each direction to catch the break out. Not sure, if this works for the person starting the thread it certainly works with those limitations.

Thanks for your perspective.

Nil per os
-NJAMC [Generic Programmer]

LOM WIKI: NT-Local-Order-Manager-LOM-Guide
Artificial Bee Colony Optimization
Visit my NexusFi Trade Journal Reply With Quote





Last Updated on April 20, 2016


© 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