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

Incorrect Number of Limit Orders Submitted over TDAMERITRADE When Scaling Out

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

    Incorrect Number of Limit Orders Submitted over TDAMERITRADE When Scaling Out

    Greetings!


    SUMMARY OF THE ISSUE:
    When I create a strategy using "Strategy Builder" to try and scale out over the TDAMERITRADE connection, no matter the conditions for entry, the end result is each limit order increasing to the total position size, while the position size remains as configured. So, if I have a position of 2 shares and with 2 limit orders of 1 share exit each, they CHANGE automatically after submission within a few seconds to 2 share limit order exits. And then, because my position is "2," the position exits completely as soon as it hits the first target.


    DETAILS OF THE ISSUE
    • Inputs are defined for Quantity and Target on the "Inputs and Variables" menu.
    • The desired position size is 2 for a long position using 2 market orders with 2 limit orders set for the targets.
    • 2 market orders are setup on the 'Conditions and Actions' menu, each with its own signal.
    • 2 targets are defined on the 'Stops and Targets' menu, each with its own exit signal, and pointing back to the specified entry signal.
    • If I am connected to the 'Simulated Data Feed,' everything works as expected.
    • If I connect to the TDAMERITRADE data, the problem begins. The orders will submit, but within a few seconds, each limit order DOUBLES, and my position remains 2.
    • The position closes as soon as the 1st target is reached.

    I noticed when I click the properties of the Strategy, and the "Stop and Target Submission" dropdown list changes from "PER ENTRY EXECUTION" to "BY STRATEGY POSITION" all by itself. It does not change when using the 'Simulated Data Feed.' If I reset the dropdown to "BY STRATEGY POSITION," the issue repeats. Why is this setting modifying itself? I think this is what is causing the problem. Or am I doing something wrong? Or is this some kind of problem with TDAMERITRADE data?


    Please see attached screenshots, logs, and the script below (continued in next post). Please let me know where additional clarifications are needed.

    Thank you for your time and valuable support!
    Last edited by FlimFlam; 08-02-2022, 09:44 PM.

    #2

    ================================================== ===============================
    ===============================BEGIN LOG OUTPUT=================================
    ================================================== ===============================
    Enabling NinjaScript strategy 'Test/270916986' : On starting a real-time strategy - StartBehavior=WaitUntilFlatSynchronizeAccount Position=AMD 2L EntryHandling=All entries EntriesPerDirection=50 StopTargetHandling=By strategy position ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=False SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On each tick IsUnmanaged=False MaxRestarts=4 in 5 minutes
    8/2/2022 7:54:40 PM Strategy 'Test/270916986': Entered internal SubmitOrderManaged() method at 8/2/2022 7:54:40 PM: BarsInProgress=0 Action=Sell OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='LongExit1' FromEntrySignal='LongEntry1'
    8/2/2022 7:54:40 PM Strategy 'Test/270916986': Entered internal SubmitOrderManaged() method at 8/2/2022 7:54:40 PM: BarsInProgress=0 Action=Sell OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='LongExit2' FromEntrySignal='LongEntry2'
    8/2/2022 7:54:40 PM Strategy 'Test/270916986: Cancelled pending exit order, since associated position is closed, orderId='NT-16579-1165' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=92.91 stopPrice=0 quantity=2 tif=Gtc oco='NT-11748-1165' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2022-08-02 19:51:00' gtd='2099-12-01' statementDate='2022-08-02'
    8/2/2022 7:54:40 PM Strategy 'Test/270916986: Cancelled pending exit order, since associated position is closed, orderId='NT-16580-1165' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=93.16 stopPrice=0 quantity=2 tif=Gtc oco='NT-11749-1165' filled=0 averageFillPrice=0 onBehalfOf='' id=-1 time='2022-08-02 19:51:00' gtd='2099-12-01' statementDate='2022-08-02'
    8/2/2022 7:54:41 PM Strategy 'Test/270916986': Entered internal SubmitOrderManaged() method at 8/2/2022 7:54:41 PM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='LongEntry1' FromEntrySignal=''
    8/2/2022 7:54:41 PM Strategy 'Test/270916986': Entered internal SubmitOrderManaged() method at 8/2/2022 7:54:41 PM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='LongEntry2' FromEntrySignal=''
    8/2/2022 7:54:42 PM Strategy 'Test/270916986': Amended target order orderId='da7899eda6fe4efeaaab466d9b3e8cfc' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=92.84 stopPrice=0 quantity=1 tif=Gtc oco='9f549d77aae746049d57c21ae78befcf' filled=0 averageFillPrice=0 onBehalfOf='' id=285 time='2022-08-02 19:54:41' gtd='2099-12-01' statementDate='2022-08-02' limitPriceChanged=92.84
    8/2/2022 7:54:42 PM Strategy 'Test/270916986': Amended target order orderId='6e55b778245a432d9575614be1999c4b' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=93.09 stopPrice=0 quantity=1 tif=Gtc oco='cef87a48a7ff4671a8bd054002c68db9' filled=0 averageFillPrice=0 onBehalfOf='' id=286 time='2022-08-02 19:54:41' gtd='2099-12-01' statementDate='2022-08-02' limitPriceChanged=93.09
    8/2/2022 7:54:51 PM Strategy 'Test/270916986': Entered internal SubmitOrderManaged() method at 8/2/2022 7:54:51 PM: BarsInProgress=0 Action=Sell OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='LongExit1' FromEntrySignal='LongEntry1'
    8/2/2022 7:54:51 PM Strategy 'Test/270916986': Entered internal SubmitOrderManaged() method at 8/2/2022 7:54:51 PM: BarsInProgress=0 Action=Sell OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='LongExit2' FromEntrySignal='LongEntry2'
    8/2/2022 7:54:51 PM Strategy '270916986/Test: Cancelled pending exit order, since associated position is closed, orderId='da7899eda6fe4efeaaab466d9b3e8cfc' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=92.84 stopPrice=0 quantity=2 tif=Gtc oco='9f549d77aae746049d57c21ae78befcf' filled=0 averageFillPrice=0 onBehalfOf='' id=285 time='2022-08-02 19:54:42' gtd='2099-12-01' statementDate='2022-08-02'
    8/2/2022 7:54:51 PM Strategy '270916986/Test: Cancelled pending exit order, since associated position is closed, orderId='6e55b778245a432d9575614be1999c4b' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=93.09 stopPrice=0 quantity=2 tif=Gtc oco='cef87a48a7ff4671a8bd054002c68db9' filled=0 averageFillPrice=0 onBehalfOf='' id=286 time='2022-08-02 19:54:42' gtd='2099-12-01' statementDate='2022-08-02'
    8/2/2022 7:54:52 PM Strategy 'Test/270916986': Entered internal SubmitOrderManaged() method at 8/2/2022 7:54:52 PM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='LongEntry1' FromEntrySignal=''
    8/2/2022 7:54:52 PM Strategy 'Test/270916986': Entered internal SubmitOrderManaged() method at 8/2/2022 7:54:52 PM: BarsInProgress=0 Action=Buy OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='LongEntry2' FromEntrySignal=''
    8/2/2022 7:54:53 PM Strategy 'Test/270916986': Amended target order orderId='97adac64e49f4e72b8ff6ef8f5c35dc4' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=92.85 stopPrice=0 quantity=1 tif=Gtc oco='e538aea4d94d463691386beb364ff770' filled=0 averageFillPrice=0 onBehalfOf='' id=291 time='2022-08-02 19:54:52' gtd='2099-12-01' statementDate='2022-08-02' limitPriceChanged=92.85
    8/2/2022 7:54:53 PM Strategy 'Test/270916986': Amended target order orderId='726c65d16d344d86b6fd5f52777130d8' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=93.1 stopPrice=0 quantity=1 tif=Gtc oco='5701b6825e5a4d6d865ab40d01352adf' filled=0 averageFillPrice=0 onBehalfOf='' id=292 time='2022-08-02 19:54:52' gtd='2099-12-01' statementDate='2022-08-02' limitPriceChanged=93.1
    8/2/2022 7:54:59 PM Strategy 'Test/270916986': Entered internal SubmitOrderManaged() method at 8/2/2022 7:54:59 PM: BarsInProgress=0 Action=Sell OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='LongExit1' FromEntrySignal='LongEntry1'
    8/2/2022 7:54:59 PM Strategy 'Test/270916986': Entered internal SubmitOrderManaged() method at 8/2/2022 7:54:59 PM: BarsInProgress=0 Action=Sell OrderType=Market Quantity=1 LimitPrice=0 StopPrice=0 SignalName='LongExit2' FromEntrySignal='LongEntry2'
    8/2/2022 7:54:59 PM Strategy '270916986/Test: Cancelled pending exit order, since associated position is closed, orderId='97adac64e49f4e72b8ff6ef8f5c35dc4' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=92.85 stopPrice=0 quantity=2 tif=Gtc oco='e538aea4d94d463691386beb364ff770' filled=0 averageFillPrice=0 onBehalfOf='' id=291 time='2022-08-02 19:54:53' gtd='2099-12-01' statementDate='2022-08-02'
    8/2/2022 7:54:59 PM Strategy '270916986/Test: Cancelled pending exit order, since associated position is closed, orderId='726c65d16d344d86b6fd5f52777130d8' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=93.1 stopPrice=0 quantity=2 tif=Gtc oco='5701b6825e5a4d6d865ab40d01352adf' filled=0 averageFillPrice=0 onBehalfOf='' id=292 time='2022-08-02 19:54:53' gtd='2099-12-01' statementDate='2022-08-02'
    Disabling NinjaScript strategy 'Test/270916986'

    ================================================== ===============================
    =============================== END LOG OUTPUT=================================
    ================================================== ===============================



    Comment


      #3

      ================================================== ===============================
      =============================== BEGIN STRATEGY BUILDER SCRIPT ====================
      ================================================== ===============================

      namespace NinjaTrader.NinjaScript.Strategies
      {
      public class Test : Strategy
      {
      private SMA SMA1;
      private SMA SMA2;

      protected override void OnStateChange()
      {
      if (State == State.SetDefaults)
      {
      Description = @"";
      Name = "Test";
      Calculate = Calculate.OnEachTick;
      EntriesPerDirection = 4;
      EntryHandling = EntryHandling.AllEntries;
      IsExitOnSessionCloseStrategy = false;
      ExitOnSessionCloseSeconds = 15;
      IsFillLimitOnTouch = false;
      MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
      OrderFillResolution = OrderFillResolution.Standard;
      Slippage = 0;
      StartBehavior = StartBehavior.WaitUntilFlatSynchronizeAccount;
      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;
      LongQuantity1 = 1;
      LongQuantity2 = 0;
      LongTarget1 = 1;
      LongTarget2 = 0;
      }
      else if (State == State.Configure)
      {
      }
      else if (State == State.DataLoaded)
      {
      SMA1 = SMA(Close, 3);
      SMA2 = SMA(Close, 8);
      SMA1.Plots[0].Brush = Brushes.Coral;
      SMA2.Plots[0].Brush = Brushes.SaddleBrown;
      AddChartIndicator(SMA1);
      AddChartIndicator(SMA2);
      SetProfitTarget(@"LongEntry1", CalculationMode.Ticks, LongTarget1);
      SetProfitTarget(@"LongEntry2", CalculationMode.Ticks, LongTarget2);
      }
      }

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

      if (CurrentBars[0] < 1)
      return;

      // Set 1
      if ((Position.MarketPosition == MarketPosition.Flat)
      && (SMA1[0] > SMA2[0]))
      {
      EnterLong(Convert.ToInt32(LongQuantity1), @"LongEntry1");
      EnterLong(Convert.ToInt32(LongQuantity2), @"LongEntry2");
      }

      // Set 2
      if ((Position.MarketPosition == MarketPosition.Long)
      && (SMA1[0] < SMA2[0]))
      {
      ExitLong(Convert.ToInt32(LongQuantity1), @"LongExit1", @"LongEntry1");
      ExitLong(Convert.ToInt32(LongQuantity2), @"LongExit2", @"LongEntry2");
      }

      }

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

      [NinjaScriptProperty]
      [Range(0, int.MaxValue)]
      [Display(Name="LongQuantity2", Order=2, GroupName="Parameters")]
      public int LongQuantity2
      { get; set; }

      [NinjaScriptProperty]
      [Range(1, int.MaxValue)]
      [Display(Name="LongTarget1", Order=3, GroupName="Parameters")]
      public int LongTarget1
      { get; set; }

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


      ================================================== ===============================
      =============================== END STRATEGY BUILDER SCRIPT ======================
      ================================================== ===============================

      Comment


        #4
        Hello FlimFlam,

        I would suspect the StopTargetHandling is set to ByStrategyPosition which would cause this behavior.

        You are stating that you are setting this to PerEntryExecution but it's changing back to ByStrategyPosition automatically?

        Are you using 8.0.26.1?

        Can you reproduce this using the SampleMACrossover included with NinjaTrader?
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Hi Chelsea,

          Thanks a lot for your help!
          1. Yes, I am setting PerEntryExecution within the strategy.
            • It does not reset if I use the 'Simulated Data Feed.'
            • It changes to "ByStrategyPosition" during the following conditions:
              • Connected to TDAMERITRADE data feed.
              • Enable the strategy.
              • A condition for order entry is met.
              • A 2-share position is taken with 2 limit orders for exit issued, both with 1 share each.
              • Within a few seconds, both limit orders change from 1 share each --> 2 shares. (2 shares for 2 limit orders).
              • If the 1st limit exit is reached, the position closes completely.
              • When I disable the strategy and check the 'properties,"ByStrategyPosition" is now set.
          2. I'm on 8.0.26.0. I will install this latest version.
          3. I have been able to reproduce the issue with other strategies, but I will try out SampleMACrossover.

          After I take care of the upgrade and SampleMACrossover test, I will report back with an update.

          Thanks again!

          Comment


            #6
            Originally posted by NinjaTrader_ChelseaB View Post

            Are you using 8.0.26.1?
            The upgrade didn't resolve the issue, unfortunately.

            Here is the log output - Same issue - Conversion to 'BY STRATEGY POSITION,' and another set of orders promptly submitted.


            ================================================== ===============================
            ===============================BEGIN LOG OUTPUT=================================
            ================================================== ===============================

            Enabling NinjaScript strategy 'Test/270916986' : On starting a real-time strategy - StartBehavior=WaitUntilFlatSynchronizeAccount EntryHandling=All entries EntriesPerDirection=50 StopTargetHandling=By strategy position ErrorHandling=Stop strategy, cancel orders, close positions ExitOnSessionClose=False SetOrderQuantityBy=Strategy ConnectionLossHandling=Recalculate DisconnectDelaySeconds=10 CancelEntriesOnStrategyDisable=False CancelExitsOnStrategyDisable=False Calculate=On each tick IsUnmanaged=False MaxRestarts=4 in 5 minutes
            NinjaScript strategy 'Test/270916986' submitting order
            NinjaScript strategy 'Test/270916986' submitting order
            8/3/2022 5:06:34 PM Strategy 'Test/270916986': Amended target order orderId='bdb9a0360bce46b78709be1fddb84373' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=98 stopPrice=0 quantity=1 tif=Gtc oco='f28306ccce934429a7a4ecc18bb09d7e' filled=0 averageFillPrice=0 onBehalfOf='' id=307 time='2022-08-03 17:06:29' gtd='2099-12-01' statementDate='2022-08-03' limitPriceChanged=98
            8/3/2022 5:06:34 PM Strategy 'Test/270916986': Amended target order orderId='3bd2d9d756db40a69e4eaf6d97c93cf7' account='Sim101' name='Profit target' orderState=Working instrument='AMD' orderAction=Sell orderType='Limit' limitPrice=98.25 stopPrice=0 quantity=1 tif=Gtc oco='89ccf7cae849440690b86fe76d0bf6ad' filled=0 averageFillPrice=0 onBehalfOf='' id=308 time='2022-08-03 17:06:29' gtd='2099-12-01' statementDate='2022-08-03' limitPriceChanged=98.25
            Disabling NinjaScript strategy 'Test/270916986'

            ================================================== ===============================
            =============================== END LOG OUTPUT===================================
            ================================================== ===============================

            Originally posted by NinjaTrader_ChelseaB View Post

            Can you reproduce this using the SampleMACrossover included with NinjaTrader?
            I have transferred over relevant parts of the "Test" script built using 'Strategy Builder' into the "SampleMACrossOver" and saved this as "SampleMACrossOverTest." I didn't unlock the script I created with 'Strategy Builder.' I saved "SampleMACrossOver" into SampleMACrossOverTest, and then edited within the newly saved file. I think you were asking me to test this issue without using Strategy Builder? If so, this is what I have done. Again, unfortunately, the problem persists. Within a few seconds after conditions are met to cause a position entry and 1 limit each is shown on the chart, the limit orders automatically adjust to 2 shares each and 'BY STRATEGY POSITION' is once again automatically changed from the initial setting of "PER ENTRY EXECUTION."

            So, it looks like it isn't specifically an issue with 'Strategy Builder.'

            I'll copy this script into the next post.
            Attached Files
            Last edited by FlimFlam; 08-03-2022, 06:39 PM.

            Comment


              #7
              ================================================== ===============================
              =============================== BEGIN SampleMACrossOverTest SCRIPT =================
              ================================================== ===============================

              //
              // Copyright (C) 2022, NinjaTrader LLC <www.ninjatrader.com>.
              // NinjaTrader reserves the right to modify or overwrite this NinjaScript component with each release.
              //
              #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.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 SampleMACrossOverTest : Strategy
              {
              private SMA smaFast;
              private SMA smaSlow;

              protected override void OnStateChange()
              {
              if (State == State.SetDefaults)
              {
              Description = NinjaTrader.Custom.Resource.NinjaScriptStrategyDes criptionSampleMACrossOver;
              Name = "SampleMACrossOverTest";
              Fast = 3;
              Slow = 8;
              LongQuantity1 = 1;
              LongQuantity2 = 1;
              LongTarget1 = 10;
              LongTarget2 = 20;
              ShortQuantity1 = 1;
              ShortQuantity2 = 1;
              ShortTarget1 = 10;
              ShortTarget2 = 20;
              Calculate = Calculate.OnEachTick;
              EntriesPerDirection = 4;
              EntryHandling = EntryHandling.AllEntries;
              IsExitOnSessionCloseStrategy = false;
              ExitOnSessionCloseSeconds = 15;
              IsFillLimitOnTouch = false;
              MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
              OrderFillResolution = OrderFillResolution.Standard;
              Slippage = 0;
              StartBehavior = StartBehavior.WaitUntilFlatSynchronizeAccount;
              TimeInForce = TimeInForce.Gtc;
              RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
              StopTargetHandling = StopTargetHandling.PerEntryExecution;
              TraceOrders = true;
              IsInstantiatedOnEachOptimizationIteration = false;
              // This strategy has been designed to take advantage of performance gains in Strategy Analyzer optimizations
              // See the Help Guide for additional information


              }
              else if (State == State.DataLoaded)
              {
              smaFast = SMA(Fast);
              smaSlow = SMA(Slow);
              smaFast.Plots[0].Brush = Brushes.Goldenrod;
              smaSlow.Plots[0].Brush = Brushes.SeaGreen;
              AddChartIndicator(smaFast);
              AddChartIndicator(smaSlow);

              SetProfitTarget(@"LongEntry1", CalculationMode.Ticks, LongTarget1);
              SetProfitTarget(@"LongEntry2", CalculationMode.Ticks, LongTarget2);
              SetProfitTarget(@"ShortEntry1", CalculationMode.Ticks, ShortTarget1);
              SetProfitTarget(@"ShortEntry2", CalculationMode.Ticks, ShortTarget2);
              }
              }

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

              if (CurrentBars[0] < 1)
              return;

              if ((Position.MarketPosition == MarketPosition.Flat)
              && (CrossAbove(smaFast, smaSlow, 1)))

              {
              EnterLong(Convert.ToInt32(LongQuantity1), @"LongEntry1");
              EnterLong(Convert.ToInt32(LongQuantity2), @"LongEntry2");
              }

              if ((Position.MarketPosition == MarketPosition.Flat)
              && (CrossBelow(smaFast, smaSlow, 1)))

              {
              EnterShort(Convert.ToInt32(ShortQuantity1), @"ShortEntry1");
              EnterShort(Convert.ToInt32(ShortQuantity2), @"ShortEntry2");
              }

              if ((Position.MarketPosition == MarketPosition.Long)
              && (CrossBelow(smaFast, smaSlow, 1)))

              {
              ExitLong(Convert.ToInt32(LongQuantity1), @"LongExit1", @"LongEntry1");
              ExitLong(Convert.ToInt32(LongQuantity2), @"LongExit2", @"LongEntry2");
              }

              if ((Position.MarketPosition == MarketPosition.Short)
              && (CrossAbove(smaFast, smaSlow, 1)))

              {
              ExitShort(Convert.ToInt32(ShortQuantity1), @"ShortExit1", @"ShortEntry1");
              ExitShort(Convert.ToInt32(ShortQuantity2), @"ShortExit2", @"ShortEntry2");
              }
              }

              #region Properties
              [Range(1, int.MaxValue), NinjaScriptProperty]
              [Display(ResourceType = typeof(Custom.Resource), Name = "Fast", GroupName = "NinjaScriptStrategyParameters", Order = 0)]
              public int Fast
              { get; set; }

              [Range(1, int.MaxValue), NinjaScriptProperty]
              [Display(ResourceType = typeof(Custom.Resource), Name = "Slow", GroupName = "NinjaScriptStrategyParameters", Order = 1)]
              public int Slow
              { get; set; }

              [Range(1, int.MaxValue), NinjaScriptProperty]
              [Display(ResourceType = typeof(Custom.Resource), Name = "Long Quantity 1", GroupName = "NinjaScriptStrategyParameters", Order = 2)]
              public int LongQuantity1
              { get; set; }

              [Range(0, int.MaxValue), NinjaScriptProperty]
              [Display(ResourceType = typeof(Custom.Resource), Name = "Long Quantity 2", GroupName = "NinjaScriptStrategyParameters", Order = 3)]
              public int LongQuantity2
              { get; set; }

              [Range(1, int.MaxValue), NinjaScriptProperty]
              [Display(ResourceType = typeof(Custom.Resource), Name = "Long Target 1", GroupName = "NinjaScriptStrategyParameters", Order = 4)]
              public int LongTarget1
              { get; set; }

              [Range(0, int.MaxValue), NinjaScriptProperty]
              [Display(ResourceType = typeof(Custom.Resource), Name = "Long Target 2", GroupName = "NinjaScriptStrategyParameters", Order = 5)]
              public int LongTarget2
              { get; set; }

              [Range(1, int.MaxValue), NinjaScriptProperty]
              [Display(ResourceType = typeof(Custom.Resource), Name = "Short Quantity 1", GroupName = "NinjaScriptStrategyParameters", Order = 6)]
              public int ShortQuantity1
              { get; set; }

              [Range(0, int.MaxValue), NinjaScriptProperty]
              [Display(ResourceType = typeof(Custom.Resource), Name = "Short Quantity 2", GroupName = "NinjaScriptStrategyParameters", Order = 7)]
              public int ShortQuantity2
              { get; set; }

              [Range(1, int.MaxValue), NinjaScriptProperty]
              [Display(ResourceType = typeof(Custom.Resource), Name = "Short Target 1", GroupName = "NinjaScriptStrategyParameters", Order = 8)]
              public int ShortTarget1
              { get; set; }

              [Range(0, int.MaxValue), NinjaScriptProperty]
              [Display(ResourceType = typeof(Custom.Resource), Name = "Short Target 2", GroupName = "NinjaScriptStrategyParameters", Order = 9)]
              public int ShortTarget2
              { get; set; }

              #endregion
              }
              }

              ================================================== ===============================
              =============================== END SampleMACrossOverTest SCRIPT =================
              ================================================== ===============================
              Last edited by FlimFlam; 08-03-2022, 04:33 PM.

              Comment


                #8
                Hello FlimFlam,

                I am wanting to test the SampleMACrossover included with NinjaTrader, not a custom script.

                We just want to ensure we can use a system strategy to reproduce for our report to our development. Is the StopTargetHandling changing when testing the SampleMACrossover included with NinjaTrader? (Please do not test a different script)
                Chelsea B.NinjaTrader Customer Service

                Comment


                  #9
                  Originally posted by NinjaTrader_ChelseaB View Post
                  Hello FlimFlam,

                  I am wanting to test the SampleMACrossover included with NinjaTrader, not a custom script.

                  We just want to ensure we can use a system strategy to reproduce for our report to our development. Is the StopTargetHandling changing when testing the SampleMACrossover included with NinjaTrader? (Please do not test a different script)
                  Hi Chelsea,

                  Thank you for the clarification. I have tested the SampleMACrossOver built-in script, and yes StopTargetHandling has automatically changed from PerEntryExecution --> ByStrategyPosition.

                  It does not make this change when connected to the "Simulated Data Feed," however; only when connected to TDAMERITRADE.


                  Thank you once more for your continued assistance!
                  Last edited by FlimFlam; 08-04-2022, 09:11 AM.

                  Comment


                    #10
                    Hello FlimFlam,

                    Thanks for confirming that.

                    I'll get this reported and will update this thread once I have a tracking ID.
                    Chelsea B.NinjaTrader Customer Service

                    Comment


                      #11
                      Originally posted by NinjaTrader_ChelseaB View Post
                      Hello FlimFlam,

                      Thanks for confirming that.

                      I'll get this reported and will update this thread once I have a tracking ID.
                      Great, thank you very much!

                      Comment


                        #12
                        Hello FlimFlam,

                        Our development pointed out this is expected behavior.

                        From the help guide:
                        "Warning: If your strategy executes to an Interactive Brokers or TD Ameritrade account, the StopTargetHandling will always be forced to .ByStrategyPosition"


                        This is due to how TDA handles OCO orders. With TDA, once an oco pair is submitted they cannot be modified in quantity or price. So the stops and targets are not submitted until the entry fills and are submitted for the full position quantity, not just the entry's quantity.

                        Use the unmanaged approach if you need to scale into and out of a position with TDA.


                        Chelsea B.NinjaTrader Customer Service

                        Comment


                          #13
                          Originally posted by NinjaTrader_ChelseaB View Post
                          Hello FlimFlam,

                          Our development pointed out this is expected behavior.

                          From the help guide:
                          "Warning: If your strategy executes to an Interactive Brokers or TD Ameritrade account, the StopTargetHandling will always be forced to .ByStrategyPosition"


                          This is due to how TDA handles OCO orders. With TDA, once an oco pair is submitted they cannot be modified in quantity or price. So the stops and targets are not submitted until the entry fills and are submitted for the full position quantity, not just the entry's quantity.

                          Use the unmanaged approach if you need to scale into and out of a position with TDA.


                          https://ninjatrader.com/support/help...runmanaged.htm
                          Darn it, I was afraid of that. I still should have looked in the help file, though. Thank you very much for all of your help!

                          Comment


                            #14
                            Originally posted by NinjaTrader_ChelseaB View Post
                            Hello FlimFlam,

                            Our development pointed out this is expected behavior.

                            From the help guide:
                            "Warning: If your strategy executes to an Interactive Brokers or TD Ameritrade account, the StopTargetHandling will always be forced to .ByStrategyPosition"


                            This is due to how TDA handles OCO orders. With TDA, once an oco pair is submitted they cannot be modified in quantity or price. So the stops and targets are not submitted until the entry fills and are submitted for the full position quantity, not just the entry's quantity.

                            Use the unmanaged approach if you need to scale into and out of a position with TDA.


                            https://ninjatrader.com/support/help...runmanaged.htm
                            Hi, I'm not sure if this error I'm getting is related to this topic, or to QA-5850 (synchronization problems between accounts)

                            I am trying to make simple strategies in TDA, market entry and exit with stoploss or profit target (without scaling). In the first test that I did in TOS everything did be ok during the trade ,1lot for each order in the OCO, however in Ninjatrader the stoploss was "2S".

                            The stoploss was reached and there was a pending stoploss order "1S", the strategy desynchronized and did not generated a new trade after a few candles. In TOS everything ran fine. The oco, and the cancellation of the profit target.

                            The code is very simple:

                            difflong = Close[0] - MIN(Low,KA2)[0];
                            if (CrossAbove(MACD2.Default, MACD2.Avg, 1) && Position.Quantity == 0)
                            {
                            SetStopLoss(@"LE",CalculationMode.Price, Math.Floor((Close[0]-difflong*KA1-TickSize)/TickSize)*TickSize,false);
                            SetProfitTarget(@"LE",CalculationMode.Price, Math.Ceiling((Close[0]+difflong*KA3)/TickSize)*TickSize,false);
                            this.TimeInForce = TimeInForce.Day;
                            EnterLong(Convert.ToInt32(LotsSize), "LE");
                            }
                            this.TimeInForce = TimeInForce.Gtc;
                            Attached Files

                            Comment

                            Latest Posts

                            Collapse

                            Topics Statistics Last Post
                            Started by jaybedreamin, Today, 05:56 PM
                            0 responses
                            2 views
                            0 likes
                            Last Post jaybedreamin  
                            Started by DJ888, 04-16-2024, 06:09 PM
                            6 responses
                            18 views
                            0 likes
                            Last Post DJ888
                            by DJ888
                             
                            Started by Jon17, Today, 04:33 PM
                            0 responses
                            1 view
                            0 likes
                            Last Post Jon17
                            by Jon17
                             
                            Started by Javierw.ok, Today, 04:12 PM
                            0 responses
                            6 views
                            0 likes
                            Last Post Javierw.ok  
                            Started by timmbbo, Today, 08:59 AM
                            2 responses
                            10 views
                            0 likes
                            Last Post bltdavid  
                            Working...
                            X