Announcement

Collapse

Looking for a User App or Add-On built by the NinjaTrader community?

Visit NinjaTrader EcoSystem and our free User App Share!

Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less

Partner 728x90

Collapse

{NinjaScript} - Set Take Profit and Stop Loss On unmanaged approach

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

    {NinjaScript} - Set Take Profit and Stop Loss On unmanaged approach

    Hello!
    Im using unmanaged approach and I need to place Stop orders with StopLoss and Take Profit.
    My code is:
    IsUnmanaged=true;


    SetProfitTarget(contador.ToString(),CalculationMod e.Price,Close[0]+0.0030);
    SetStopLoss(contador.ToString(),CalculationMode.Pr ice,Close[0]-0.0060,false);
    SubmitOrderUnmanaged(0,OrderAction.Buy,OrderType.S topMarket,10000,0,Close[0]+0.0030,contador.ToString());

    I have this error: Strategy 'MyCustomStrategy': Error on calling 'OnBarUpdate' method on bar 1: Strategy 'MyCustomStrategy/206666248': Method 'SetProfitTarget' can't be called on unmanaged strategies.

    Can you help me on place StopLoss and Profit Target?
    Thank you!

    #2
    Hello fscabrera03,

    You cannot use SetStopLoss() or Enter or Exit methods or any managed methods with the unmanaged approach.

    You can only use SubmitOrder() and the other methods in the help guide under the unmanaged approach.


    Below is a link to an unmanaged example.

    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      fscabrera03
      Since you are using SubmitOrderUnmanaged, so everything likes entrylong, entryshort, stoplong, stopshort, you should be use SubmitOrderUnmanaged also.

      In short, your SetProfitTarget and SetStopLoss should not be used.
      To know how to use it, You can enter the link provided by the ninjatrader customer service.

      Comment


        #4
        Originally posted by NinjaTrader_ChelseaB View Post
        Hello fscabrera03,

        You cannot use SetStopLoss() or Enter or Exit methods or any managed methods with the unmanaged approach.

        You can only use SubmitOrder() and the other methods in the help guide under the unmanaged approach.


        Below is a link to an unmanaged example.
        Ok. I see how can I open trades (by stop order) in unmanaged approach. But I dont realize how to set StopLoss and TakeProfit for tha specific stopOrder created.
        I see that I need to create an specific order by the same size to close that position as an independent trade. I dont have any way to reference the specific exitOrder to the specific stop order?
        Can be confusing use independent exit orders to independet stop orders when you have multiple stopOrders created.
        How can I make sure that two exit orders (SL and TP) are vinculated with the specific trade created by an stop order and only will be executed depending on the stopOrder (trade)?

        Comment


          #5
          Hello fscabrera03,

          In the example I have provided you the execution.Order is compared to the entryOrder object.
          if (entryOrder != null && execution.Order == entryOrder)

          This is how you know that specific entry has filled.

          You can also do this with the exit orders. From the example I have provided you:
          profitTarget != null && profitTarget.OrderState == OrderState.Filled

          The order object also has a Name property.
          https://ninjatrader.com/support/help...nt7/iorder.htm
          Chelsea B.NinjaTrader Customer Service

          Comment


            #6
            Thank you.
            You are calling a method protected override void OnExecution(IExecution execution) to create stop loss and take profits but doesn't works. Please see attached.


            Attached Files

            Comment


              #7
              Hello fscabrera03,

              OnExecution() is a method declared in the Strategy class by NinjaTrader is automatically called by NinjaTrader each time there is an order fill.

              Below is a link to the help guide.


              If you need help with code, please show the code.
              Chelsea B.NinjaTrader Customer Service

              Comment


                #8
                Originally posted by NinjaTrader_ChelseaB View Post
                Hello fscabrera03,

                OnExecution() is a method declared in the Strategy class by NinjaTrader is automatically called by NinjaTrader each time there is an order fill.

                Below is a link to the help guide.


                If you need help with code, please show the code.
                Thank you!
                I tryed to use that method but throws me the error that I attached. Its like I dont have using instructions or I dont have some library.

                Comment


                  #9
                  Hello nandocabrera87,

                  What code is causing the error?

                  Is this is a strategy?
                  Chelsea B.NinjaTrader Customer Service

                  Comment


                    #10
                    Yes, is this a strategy, :

                    The type or namespace name 'IExecution' could not be found (are you missing a using directive or an assembly reference?)


                    ************************************************** ************
                    #region Using declarations
                    using System;
                    using System.Collections.Generic;
                    using System.ComponentModel;
                    using System.ComponentModel.DataAnnotations;
                    using System.Linq;
                    using System.Text;
                    using System.Threading.Tasks;
                    using System.Windows;
                    using System.Windows.Input;
                    using System.Windows.Media;
                    using System.Xml.Serialization;
                    using NinjaTrader.Cbi;
                    using NinjaTrader.Gui;
                    using NinjaTrader.Gui.Chart;
                    using NinjaTrader.Gui.SuperDom;
                    using NinjaTrader.Gui.Tools;
                    using NinjaTrader.Data;
                    using NinjaTrader.NinjaScript;
                    using NinjaTrader.Core.FloatingPoint;
                    using NinjaTrader.NinjaScript.Indicators;
                    using NinjaTrader.NinjaScript.DrawingTools;
                    #endregion

                    //This namespace holds Strategies in this folder and is required. Do not change it.
                    namespace NinjaTrader.NinjaScript.Strategies
                    {
                    public class MyCustomStrategy : Strategy
                    {
                    public int contador;
                    public bool submitted;
                    private double currentPtPrice, currentSlPrice, tickSizeSecondary;
                    private Order entryOrder, exitFlat;
                    private Order profitTarget, stopLoss;
                    private int profitTargetDistance, stopLossDistance;
                    private bool exitOnCloseWait, ordersCancelled, suppressCancelExit;
                    private string entryName, exitName, ptName, slName, message, ocoString;
                    private DateTime sessionBegin, sessionEnd;

                    protected override void OnStateChange()
                    {
                    if (State == State.SetDefaults)
                    {
                    Description = @"Enter the description for your new custom Strategy here.";
                    Name = "MyCustomStrategy";
                    Calculate = Calculate.OnBarClose;
                    EntriesPerDirection = 10;
                    EntryHandling = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy = false;
                    ExitOnSessionCloseSeconds = 30;
                    IsFillLimitOnTouch = false;
                    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution = OrderFillResolution.Standard;
                    Slippage = 0;
                    StartBehavior = StartBehavior.WaitUntilFlat;
                    TimeInForce = TimeInForce.Gtc;
                    TraceOrders = false;
                    RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                    StopTargetHandling = StopTargetHandling.PerEntryExecution;
                    BarsRequiredToTrade = 5;
                    // Disable this property for performance gains in Strategy Analyzer optimizations
                    // See the Help Guide for additional information
                    IsInstantiatedOnEachOptimizationIteration = true;

                    IsUnmanaged=true;
                    contador=0;
                    submitted=false;
                    }
                    else if (State == State.Configure)
                    {
                    }
                    }

                    protected override void OnBarUpdate()
                    {
                    if(!submitted)
                    abrirBuyStop();
                    }

                    public void abrirBuyStop()
                    {
                    entryName = "BuyStop";
                    entryOrder = SubmitOrderUnmanaged(0,OrderAction.Buy,OrderType.S topMarket,
                    10000,0,Close[0]+0.0030,contador.ToString()+"BUY");
                    contador++;
                    }

                    public override void OnExecution(IExecution execution)
                    {
                    Print("OnExecution");
                    if (entryOrder != null && execution.Order == entryOrder)
                    {
                    ocoString="ocoString";
                    profitTarget = SubmitOrderUnmanaged(1, OrderAction.Sell, OrderType.StopMarket,
                    execution.Order.Filled, execution.Order.AverageFillPrice+0.0060, 0, ocoString, "profit target");
                    }
                    }

                    }
                    }

                    Comment


                      #11
                      Hello fscabrera03,

                      What specific line of code is causing the error? The error message should state what line the error is on.

                      Also, I recommend you copy and paste the methods of the help guide so the code is correct.

                      You have:
                      public override void OnExecution(IExecution execution)

                      Which does not match the help guide:
                      protected override void OnExecution(IExecution execution)
                      Chelsea B.NinjaTrader Customer Service

                      Comment


                        #12
                        Originally posted by NinjaTrader_ChelseaB View Post
                        Hello fscabrera03,

                        What specific line of code is causing the error? The error message should state what line the error is on.

                        Also, I recommend you copy and paste the methods of the help guide so the code is correct.

                        You have:
                        public override void OnExecution(IExecution execution)

                        Which does not match the help guide:
                        protected override void OnExecution(IExecution execution)
                        Ok, I have changed the method signature but gives me the same error.
                        Its like I dont have some library or reference:

                        #region Using declarations
                        using System;
                        using System.Collections.Generic;
                        using System.ComponentModel;
                        using System.ComponentModel.DataAnnotations;
                        using System.Linq;
                        using System.Text;
                        using System.Threading.Tasks;
                        using System.Windows;
                        using System.Windows.Input;
                        using System.Windows.Media;
                        using System.Xml.Serialization;
                        using NinjaTrader.Cbi;
                        using NinjaTrader.Gui;
                        using NinjaTrader.Gui.Chart;
                        using NinjaTrader.Gui.SuperDom;
                        using NinjaTrader.Gui.Tools;
                        using NinjaTrader.Data;
                        using NinjaTrader.NinjaScript;
                        using NinjaTrader.Core.FloatingPoint;
                        using NinjaTrader.NinjaScript.Indicators;
                        using NinjaTrader.NinjaScript.DrawingTools;
                        #endregion

                        //This namespace holds Strategies in this folder and is required. Do not change it.
                        namespace NinjaTrader.NinjaScript.Strategies
                        {
                        public class PruebaOnOrderFill : Strategy
                        {
                        public bool tradeCreado;
                        int contador;
                        protected override void OnStateChange()
                        {
                        if (State == State.SetDefaults)
                        {
                        Description = @"Enter the description for your new custom Strategy here.";
                        Name = "PruebaOnOrderFill";
                        Calculate = Calculate.OnBarClose;
                        EntriesPerDirection = 5;
                        EntryHandling = EntryHandling.AllEntries;
                        IsExitOnSessionCloseStrategy = false;
                        ExitOnSessionCloseSeconds = 0;
                        IsFillLimitOnTouch = true;
                        MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
                        OrderFillResolution = OrderFillResolution.Standard;
                        Slippage = 0;
                        StartBehavior = StartBehavior.WaitUntilFlat;
                        TimeInForce = TimeInForce.Gtc;
                        TraceOrders = true;
                        RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
                        StopTargetHandling = StopTargetHandling.PerEntryExecution;
                        BarsRequiredToTrade = 0;
                        // Disable this property for performance gains in Strategy Analyzer optimizations
                        // See the Help Guide for additional information
                        IsInstantiatedOnEachOptimizationIteration = true;
                        IsUnmanaged=true;
                        tradeCreado=false;
                        contador=1;
                        }
                        else if (State == State.Configure)
                        {
                        }
                        }

                        protected override void OnBarUpdate()
                        {

                        contador++;
                        if(!tradeCreado)
                        {
                        Print(tradeCreado);
                        SubmitOrderUnmanaged(0,OrderAction.Buy,OrderType.S topMarket,10000,0,Close[0]+0.0060,"UnTrade"+"BUY");
                        tradeCreado=true;
                        }
                        }

                        protected override void OnExecution(IExecution execution) --> Line 77, here is the error
                        {
                        Print("Enter OnExecution");
                        }


                        }
                        }

                        The error is in line 77:

                        The type or namespace name 'IExecution' could not be found (are you missing a using directive or an assembly reference?) CS0246

                        This is a strategy, not an indicator.
                        Im using NT8

                        Attached Files

                        Comment


                          #13
                          Hello fscabrera03,

                          Thanks for your reply.

                          Regrettably, you have started this thread in the NinjaTrader7 Strategy forum and you are using NinjaTrader8, as a result, we have been pointing you to references in the NinjaTrader7 help guide. There are significant differences in the methods between NinjaTrader7 and NinjaTrader8. I will list the same references from the previous posts but to the NinjaTrader8 help guide. Please review these and correct your strategy accordingly.

                          Post#2 NT8 link: https://ninjatrader.com/support/help...runmanaged.htm
                          Post#2 NT8 link to an unmanaged example: https://ninjatrader.com/support/foru...ing#post802269
                          Post#5 NT8 order link: https://ninjatrader.com/support/help...nt8/?order.htm
                          Post#7 NT8 OnExecutionUpdate link: https://ninjatrader.com/support/help...tionupdate.htm

                          Paul H.NinjaTrader Customer Service

                          Comment

                          Latest Posts

                          Collapse

                          Topics Statistics Last Post
                          Started by PaulMohn, Today, 03:49 AM
                          0 responses
                          4 views
                          0 likes
                          Last Post PaulMohn  
                          Started by inanazsocial, Today, 01:15 AM
                          1 response
                          7 views
                          0 likes
                          Last Post NinjaTrader_Jason  
                          Started by rocketman7, Today, 02:12 AM
                          0 responses
                          10 views
                          0 likes
                          Last Post rocketman7  
                          Started by dustydbayer, Today, 01:59 AM
                          0 responses
                          2 views
                          0 likes
                          Last Post dustydbayer  
                          Started by trilliantrader, 04-18-2024, 08:16 AM
                          5 responses
                          23 views
                          0 likes
                          Last Post trilliantrader  
                          Working...
                          X