NexusFi: Find Your Edge


Home Menu

 





Execute trade intrabar on bar close indicator


Discussion in NinjaTrader

Updated
    1. trending_up 4,386 views
    2. thumb_up 2 thanks given
    3. group 2 followers
    1. forum 3 posts
    2. attach_file 0 attachments




 
Search this Thread

Execute trade intrabar on bar close indicator

  #1 (permalink)
 
spinnybobo's Avatar
 spinnybobo 
Crete, IL/USA
 
Experience: Intermediate
Platform: NinjaTrader, Mt4
Broker: Tradestation/Tradestation, NinjaTrader, FXCM and Tallinex
Trading: ES, CL, EUR/USD, TF
Posts: 173 since Aug 2009
Thanks Given: 105
Thanks Received: 61

Hello
I have a programming question. I am using the Swing indicator built into NinjaTrader to go Long as soon as it is 1 tick above the swingHigh, or go Short as soon as it is 1 tick below the swingLow.

This obviously needs to be done CalculateOnBarClose = false; to enter the trade intrabar
However, now the indicator is being calculated on bar close = false;

I just wanted to know the best way to have a strategy that has the entry for OnBarUpdate when I need:
goLong/goShort-------> needs to be CalculateOnBarClose = false;
Swing(5) indicator--------->needs to be CalculateOnBarClose = true;

Do I create 2 separate methods?
 
Code
public void calculateIndicator()
{
Add(Swing(5));
CalculateOnBarClose = true;
}
public void orderEntry()
{
CalculateOnBarClose = false;
}
T

here is my code so far:
 
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
{
    
    [Description("CL trading strategy")]
    public class CLStrategy : Strategy
    {
        #region Variables
        private string            atmStrategyId        = string.Empty;
        private string            orderId                = string.Empty;
        
        private int                _numberOfContracts    = 2;
        private int                _strength            = 5;
        private int                _startTime            = 80000;
        private int                _endTime            = 103000;
        private string            _alertSound            = "NONE";
        private string            _atmName            = "crude";
        
        #endregion

        
        protected override void Initialize()
        {
            Add(spencerSwing(_strength)); //spencerSwing is same as Swing except different color and size of dot
                                                             //plus DisplayInDataBox    = true;   and I made some of the private members
                                                              //in the properties public just to make sure it could be used by 
                                                              //an outside strategy
            CalculateOnBarClose = true;
            EntriesPerDirection = _numberOfContracts;
            EntryHandling = EntryHandling.AllEntries;
            TraceOrders = true;
        }

       
        protected override void OnBarUpdate()
        {
            if(ToTime(Time[0])>=StartTime && ToTime(Time[0])<=EndTime)
            {
                if(Historical)
                    return;
                //for longs
                if(orderId.Length==0
                    && atmStrategyId.Length == 0
                    && (High[0]>spencerSwing(_strength).SwingHigh[0] && High[1]<spencerSwing(_strength).SwingHigh[0]))
                {
                    atmStrategyId = GetAtmStrategyUniqueId();
                    orderId = GetAtmStrategyUniqueId();
                    AtmStrategyCreate(Cbi.OrderAction.Buy, OrderType.Market, 0, 0, TimeInForce.Day, orderId, _atmName, atmStrategyId);
                }
                if(orderId.Length==0
                    && atmStrategyId.Length==0
                    && (Low[0]<spencerSwing(_strength).SwingLow[0] && Low[1] > spencerSwing(_strength).SwingLow[0]))
                {
                    atmStrategyId = GetAtmStrategyUniqueId();
                    orderId = GetAtmStrategyUniqueId();
                    AtmStrategyCreate(Cbi.OrderAction.Sell, OrderType.Market, 0, 0, TimeInForce.Day, orderId, _atmName, atmStrategyId);
                }
                if(orderId.Length > 0)
                {
                    string[] status = GetAtmStrategyEntryOrderStatus(orderId);
                    //if the status call cant find the order specified, the
                    //return array length will be zero otherwise it will hold elements
                    if(status.GetLength(0) > 0)
                    {
                        //print out some info about the order
                        Print("The entry order average fill price is: "+status[0]);
                        Print("The entry order filled amount is: " +status[1]);
                        Print("The entry order order state is: "+status[2]);
                        //if the order state is terminal, reset the order id value
                        if(status[2] == "Filled" || status[2] == "Cancelled" || status[2]=="Rejected")
                            orderId = string.Empty;
                    }
                }
                else if(atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
                    atmStrategyId = string.Empty;
            }//end put on trade
        }
        #region Properties
        [Description("The Number of contracts traded")]
        [Category("Parameters")]
        [Gui.Design.DisplayName("01. Number Of Contracts")]
        public int NumberOfContracts
        {
            get{return _numberOfContracts;}
            set{_numberOfContracts = Math.Max(1, value);}
        }
        [Description("The input strength of swing")]
        [Category("Parameters")]
        [Gui.Design.DisplayName("02. Swing Strength")]
        public int Strength
        {
            get{return _strength;}
            set{_strength = Math.Max(1, value);}
        }
        [Description("The time trading starts")]
        [Category("Parameters")]
        [Gui.Design.DisplayName("03. Start")]
        public int StartTime
        {
            get{return _startTime;}
            set{_startTime = Math.Max(1, value);}
        }
        [Description("The time trading ends")]
        [Category("Parameters")]
        [Gui.Design.DisplayName("04. Ends")]
        public int EndTime
        {
            get{return _endTime;}
            set{_endTime = Math.Max(1, value);}
        }
        [Description("A .wav file to play as an alert")]
        [Category("Parameters")]
        [Gui.Design.DisplayName("05. Wave File")]
        public string AlertWavFile
        {
            get{return _alertSound;}
            set{
                    _alertSound = value;
                    _alertSound = _alertSound.Trim();
                    if(_alertSound.ToUpperInvariant().CompareTo("NONE")== 0 )
                        _alertSound = "NONE";
                }
        }
        [Description("Enter the ATM strategy name")]
        [Category("Parameters")]
        [Gui.Design.DisplayName("06. Strategy Name")]
        public string ATMName
        {
            get{return _atmName;}
            set{_atmName = value;}
        }
       
        #endregion
The only other thing I can think of is use the indicator on the chart and have a FileWriter write the Swing High, Swing Low to a swingLow.txt and swingHigh.txt and then the Strategy uses these .txt files. However, I am thinking this might cause delays, but not sure, etc...
The other way can be using a data structure like ArrayList or something on an indicator page, and then the Strategy page reads the return.

 
Code
//this would be put on the indicator
public ArrayList<double> getCurrentValue()
{
ArrayList<double> currentSwingHighValue = new ArrayList<double>();
ArrayList<double> currentSwingLowValue = new ArrayList<double>();
currentSwingHighValue.add(SwingHigh);
currentSwingLowValue.add(SwingLow);
return ArrayList<double>;
}
Then the strategy can grab this
BTW, my most comfortable programming language is Java, so it is taking a little while for me to learn C#----not that bad, just trying to relate how things are done differently-----like with get, and set

thanks
Spencer

Follow me on Twitter Started this thread Reply With Quote

Can you help answer these questions
from other members on NexusFi?
NexusFi Journal Challenge - April 2024
Feedback and Announcements
Build trailing stop for micro index(s)
Psychology and Money Management
Are there any eval firms that allow you to sink to your …
Traders Hideout
Better Renko Gaps
The Elite Circle
Online prop firm The Funded Trader (TFT) going under?
Traders Hideout
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Get funded firms 2023/2024 - Any recommendations or word …
60 thanks
Funded Trader platforms
37 thanks
NexusFi site changelog and issues/problem reporting
24 thanks
GFIs1 1 DAX trade per day journal
22 thanks
The Program
19 thanks
  #2 (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,399 since Jun 2009
Thanks Given: 33,175
Thanks Received: 101,541

If your "calling" indicator or strategy (the one added to your chart) is set to COBC = false, then anything other than COBC = false in all the child indicators will result in problems. The best thing is to remove COBC from #init altogether, which means it defaults to true, unless the parent is false in which case it defaults to false.

It is not possible to have the parent be different than the child and get correct results. Not in any of my experiences at least.

If you need this, you would have to simulate it yourself. Run everything COBC false, then code a function to simulate filling your dataseries or whatever based on COBC true. I've had to do this several times.

Mike

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
Thanked by:
  #3 (permalink)
 
spinnybobo's Avatar
 spinnybobo 
Crete, IL/USA
 
Experience: Intermediate
Platform: NinjaTrader, Mt4
Broker: Tradestation/Tradestation, NinjaTrader, FXCM and Tallinex
Trading: ES, CL, EUR/USD, TF
Posts: 173 since Aug 2009
Thanks Given: 105
Thanks Received: 61


Hi Mike

thanks for the reply. yeah, I think you confirmed my suspicions that this is more complex than I originally thought. I will have to think about this more:-) thanks

Spencer

Follow me on Twitter Started this thread Reply With Quote
  #4 (permalink)
doculik
London, UK
 
Posts: 1 since Aug 2011
Thanks Given: 1
Thanks Received: 0


Big Mike View Post
If your "calling" indicator or strategy (the one added to your chart) is set to COBC = false, then anything other than COBC = false in all the child indicators will result in problems. The best thing is to remove COBC from #init altogether, which means it defaults to true, unless the parent is false in which case it defaults to false.

It is not possible to have the parent be different than the child and get correct results. Not in any of my experiences at least.

If you need this, you would have to simulate it yourself. Run everything COBC false, then code a function to simulate filling your dataseries or whatever based on COBC true. I've had to do this several times.

Mike

Hi Mike,

The million dollar question I'm trying to answer, and it seems you may be up to something already, is how exactly would I code a function to simulate filling my dataseries?
An example of that would prove very useful to me, I've been straining my brain for a reliable solution for ages...

Thanks for your help,
Dan M.

Reply With Quote




Last Updated on April 2, 2012


© 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