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

Strategy Builder Order Issues with Trail Stop Loss in place

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

    Strategy Builder Order Issues with Trail Stop Loss in place


    I have a simple below code where I want to place a long order when the price close above 13 EMA and Short order with price close below 13 EMA.

    And when the order is placed i want a Trail Stop set with 20 ticks as default.

    Now the issue is with TSL in place the Long and Short orders are not places based on 13 EMA until TSL is hit.

    For example a long order is placed when the price crossed 13 EMA and then Trail Stop is set. When the price falls below 13 EMA i want the long order to be closed and Short order to be triggered, But the order is not getting triggered until Stop is hit.

    Can someone help me in fixing the code

    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 VamsiStratTSL3 : Strategy
    {
    private EMA EMA1;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Simple Price Cross EMa Strat with SL";
    Name = "VamsiStratTSL3";
    Calculate = Calculate.OnEachTick;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = true;
    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 = 20;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    TrailStop = 20;
    }
    else if (State == State.Configure)
    {
    AddDataSeries(Data.BarsPeriodType.Minute, 5);
    AddDataSeries(Data.BarsPeriodType.Minute, 2);
    }
    else if (State == State.DataLoaded)
    {
    EMA1 = EMA(Close, 13);
    SetTrailStop(@"", CalculationMode.Ticks, TrailStop, false);
    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 1)
    return;

    // Set 1
    if (CrossAbove(Close, EMA1, 1))
    {
    EnterLong(Convert.ToInt32(DefaultQuantity), "");
    }

    // Set 2
    if (CrossBelow(Close, EMA1, 1))
    {
    EnterShort(Convert.ToInt32(DefaultQuantity), "");
    }

    }

    region Properties
    [NinjaScriptProperty]
    [Range(0, int.MaxValue)]
    [Display(Name="TrailStop", Order=1, GroupName="Parameters")]
    public int TrailStop
    { get; set; }
    #endregion

    }
    }​

    #2
    Hello kirankt,

    Welcome to the NinjaTrader forums!

    Please enable TraceOrders on the Defaults page, then remove the instance of the script and add a new instance.
    Open the NinjaScript Output window and then enable the strategy.


    Save the output to a text file (right-click -> Save as) and attach this to your next post.



    As a tip, so you can avoid posting the entire code of a script, to export a NinjaTrader 8 NinjaScript so this can be shared and imported by the recipient do the following:
    1. Click Tools -> Export -> NinjaScript Add-on...
    2. Click the 'add' link -> check the box(es) for the script(s) and reference(s) you want to include
    3. Click the 'Export' button
    4. Enter the script name in the value for 'File name:'
    5. Choose a save location -> click Save
    6. Click OK to clear the export location message
    By default your exported file will be in the following location:
    • (My) Documents/NinjaTrader 8/bin/Custom/ExportNinjaScript/<export_file_name.zip>
    Below is a link to the help guide on Exporting NinjaScripts.
    http://ninjatrader.com/support/helpG...nt8/export.htm
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      New to the CS coding. I have added TraceOrder in OnStateChange()

      else if (State == State.Configure)

      {

      TraceOrders = true;

      AddDataSeries(Data.BarsPeriodType.Minute, 5);

      AddDataSeries(Data.BarsPeriodType.Minute, 2);

      }

      And i dont have OnOrderUpdate() in the code. Where should i add the "Print(order.ToString());
      "

      Comment


        #4
        Hello kirankt,

        You would need to add the OnOrderUpdate() override to the script (within the scope of the class).


        protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string comment)
        {
        Print(order.ToString());
        }
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Getting error after adding this code.
          Attached Files

          Comment


            #6
            Hello kirankt,

            Can you comment this out compile, and then export the script so I can take a look on my end?
            Attach the exported file to your next post.
            Chelsea B.NinjaTrader Customer Service

            Comment


              #7
              Here it is
              Attached Files

              Comment

              Latest Posts

              Collapse

              Topics Statistics Last Post
              Started by StockTrader88, 03-06-2021, 08:58 AM
              44 responses
              3,964 views
              3 likes
              Last Post jhudas88  
              Started by rbeckmann05, Today, 06:48 PM
              0 responses
              4 views
              0 likes
              Last Post rbeckmann05  
              Started by rhyminkevin, Today, 04:58 PM
              4 responses
              52 views
              0 likes
              Last Post dp8282
              by dp8282
               
              Started by iceman2018, Today, 05:07 PM
              0 responses
              5 views
              0 likes
              Last Post iceman2018  
              Started by lightsun47, Today, 03:51 PM
              0 responses
              8 views
              0 likes
              Last Post lightsun47  
              Working...
              X