Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Strategy not executing

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    Strategy not executing

    Hi,

    I am trying to execute a strategy where each entry is handled independently. TO do this I instantiate a new object when the entry criteria is met and the new object manages itself till the order is closed. The problems I have are -

    1. The code inside the new class does not execute.
    2. Even though I call the strategy on bar update it does not seem to be doing so. It seems to be getting called only on bar close. I used the visual studio debugging process to fnd this out.

    Can someone help me with what I am doing wrong.

    The code is a pretty simple one and is below..


    #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

    // This namespace holds all strategies and is required. Do not change it.
    namespace NinjaTrader.Strategy
    {
    /// <summary>
    /// Enter the description of your strategy here
    /// </summary>
    [Description("Enter the description of your strategy here")]
    public class DIBS : Strategy
    {
    #region Variables
    // Wizard generated variables
    private int validationPips = 1; // Default setting for ValidationPips
    // User defined variables (add any user defined variables below)
    private IOrder entryOrder = null;
    private bool orderPlaced;
    #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()
    {
    }

    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
    if (CurrentBar<2)return;

    if (FirstTickOfBar)
    {
    orderPlaced=false;
    }

    if (orderPlaced==false && DIBSIndicator().DIBSLong.ContainsValue(1) && Close[0]>High[1])
    {
    new SOrder(Action.Buy, OrderType.Market, Close[0], 100000, Low[1], High[1]-Low[1], "", Time[0]);
    orderPlaced=true;
    }
    }

    protected override void OnOrderUpdate(IOrder order)
    {
    if (entryOrder != null && entryOrder.Token == order.Token)
    {
    Print(order.ToString());
    if (order.OrderState == OrderState.Filled)
    entryOrder = null;
    }
    }

    public class SOrder : Strategy
    {
    public readonly OrderType orderType;
    public readonly Action action;
    public readonly double orderPrice, stopLoss, takeProfit;
    public readonly int quantity;
    public readonly DateTime expiration;
    public readonly string trailingProfit;

    private bool orderPlaced=false;
    private IOrder order;

    public SOrder(Action act, OrderType ordType, double entPrc, int qty, double stpLss, double tkePrft, string trlPrft, DateTime exp)
    {
    action=act;
    orderType=ordType;
    orderPrice=entPrc;
    quantity=qty;
    stopLoss=stpLss;
    takeProfit=tkePrft;
    trailingProfit=trlPrft;
    expiration=exp;
    }

    protected override void OnBarUpdate()
    {
    if (action==Action.Buy)
    {
    switch (orderType)
    {
    case OrderType.Market:
    order=EnterLong(quantity, "Order");
    orderPlaced=true;
    break;

    case OrderType.Stop:
    order=EnterLongStop(quantity, orderPrice, "Order");
    orderPlaced=true;
    break;
    }
    }
    else if (action==Action.Sell)
    {
    switch (orderType)
    {
    case OrderType.Market:
    order=EnterShort(quantity, "Order");
    orderPlaced=true;
    break;

    case OrderType.Stop:
    order=EnterShortStop(quantity, orderPrice, "Order");
    orderPlaced=true;
    break;
    }
    }

    if (order.OrderState==OrderState.Filled)
    {
    SetStopLoss("Order", CalculationMode.Price, stopLoss, true);
    SetProfitTarget("Order", CalculationMode.Price, takeProfit);
    }

    if (Time[0]>expiration && order.OrderType==OrderType.Stop && order.OrderState != OrderState.Filled)
    {
    CancelOrder(order);
    }


    }

    }
    }
    }
    Last edited by Eklavya; 01-02-2010, 04:08 AM. Reason: small issue with code

    #2
    DIBSIndicator Code

    public class DIBSIndicator : Indicator
    {
    #region Variables
    // Wizard generated variables
    // User defined variables (add any user defined variables below)
    private int operativeHours =10;
    private DateTime sessionStartTime;
    #endregion

    /// <summary>
    /// This method is used to configure the indicator and is called once before any bar data is loaded.
    /// </summary>
    protected override void Initialize()
    {
    Add(new Plot(Color.FromKnownColor(KnownColor.Green), PlotStyle.Dot, "DIBSLong"));
    Add(new Plot(Color.FromKnownColor(KnownColor.Red), PlotStyle.Dot, "DIBSShort"));
    CalculateOnBarClose = true;
    Overlay = true;
    PriceTypeSupported = false;
    }

    /// <summary>
    /// Called on each bar update event (incoming tick)
    /// </summary>
    protected override void OnBarUpdate()
    {
    // if number of bars is less than 2, return
    if (CurrentBar<2)return;

    //if (Time[0].DayOfWeek==DayOfWeek.Friday)return;

    if (Bars.FirstBarOfSession)
    sessionStartTime=Time[1];

    if (High[0]<=High[1] && Low[0]>=Low[1] && High[0]>CurrentDayOHL().CurrentOpen[0]
    && Time[0]<=sessionStartTime.AddHours(operativeHours))
    {
    DIBSLong.Set(Low[0]-10*TickSize);
    }

    if (High[0]<=High[1] && Low[0]>=Low[1] && Low[0]<CurrentDayOHL().CurrentOpen[0]
    && Time[0]<=sessionStartTime.AddHours(operativeHours))
    {
    DIBSShort.Set(High[0]+10*TickSize);
    }

    if (DIBSLong.ContainsValue(1) && High[0]<=High[1])
    DIBSLong.Reset(1);

    if (DIBSShort.ContainsValue(1) && Low[0]>=Low[1])
    DIBSShort.Reset(1);
    // Use this method for calculating your indicator values. Assign a value to each
    // plot below by replacing 'Close[0]' with your own formula.
    }

    #region Properties
    [Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
    [XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
    public DataSeries DIBSLong
    {
    get { return Values[0]; }
    }

    [Browsable(false)] // this line prevents the data series from being displayed in the indicator properties dialog, do not remove
    [XmlIgnore()] // this line ensures that the indicator can be saved/recovered as part of a chart template, do not remove
    public DataSeries DIBSShort
    {
    get { return Values[1]; }
    }

    #endregion
    }

    Comment


      #3
      Eklavya, the code will be called on bar close always if you're backtesting - updating calcs on each tick / intrabar would apply to realtime use or market replay only, since then the tick formation would be known.

      You would need to debug both the class and strategy with Prints to see what is actually happening 'under the hood', for this please simplify as much as possible and be also sure to work with TraceOrders to have access to the default order debugging features -



      BertrandNinjaTrader Customer Service

      Comment


        #4
        Thank You Bertrand...

        1. How can I accurately back test a strategy when the code is called only on barclose? Any suggestions? Do I need to use multi bars and trade on the 1 min while taking signals on my trading timeframe?

        2. Will the following code conceptually work?

        public class DIBS : Strategy
        {
        protected override void OnBarUpdate()
        {
        if entry condition met then new Sorder();
        }
        }

        public class Sorder : Strategy
        {

        public SOrder()
        {
        Enter Order;
        }

        protected override void OnBarUpdate()
        {
        manage order depending on price action;
        }
        }


        Originally posted by NinjaTrader_Bertrand View Post
        Eklavya, the code will be called on bar close always if you're backtesting - updating calcs on each tick / intrabar would apply to realtime use or market replay only, since then the tick formation would be known.

        You would need to debug both the class and strategy with Prints to see what is actually happening 'under the hood', for this please simplify as much as possible and be also sure to work with TraceOrders to have access to the default order debugging features -



        http://www.ninjatrader-support2.com/...ead.php?t=3418

        Comment


          #5
          Correct, you would need to check into this concept introduced in this sample to simulate intrabar fills -

          You can submit orders to different Bars objects. This allows you the flexibility of submitting orders to different timeframes. Like in live trading, taking entry conditions from a 5min chart means executing your order as soon as possible instead of waiting until the next 5min bar starts building. You can achieve this by


          Conceptually the issue here is that cross strategy communication is not supported...
          BertrandNinjaTrader Customer Service

          Comment

          Latest Posts

          Collapse

          Topics Statistics Last Post
          Started by PhillT, Today, 02:16 PM
          2 responses
          3 views
          0 likes
          Last Post PhillT
          by PhillT
           
          Started by Kaledus, Today, 01:29 PM
          3 responses
          9 views
          0 likes
          Last Post NinjaTrader_Jesse  
          Started by frankthearm, Yesterday, 09:08 AM
          14 responses
          47 views
          0 likes
          Last Post NinjaTrader_Clayton  
          Started by gentlebenthebear, Today, 01:30 AM
          2 responses
          14 views
          0 likes
          Last Post gentlebenthebear  
          Started by PaulMohn, Today, 12:36 PM
          2 responses
          17 views
          0 likes
          Last Post PaulMohn  
          Working...
          X