NexusFi: Find Your Edge


Home Menu

 





scaling in causes stop loss orders to stop working.


Discussion in NinjaTrader

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




 
Search this Thread

scaling in causes stop loss orders to stop working.

  #1 (permalink)
maggtrading
quintana roo, méxico
 
Posts: 84 since Mar 2013
Thanks Given: 222
Thanks Received: 40

regards to everyone,



i have been working on a particular strategy but i haven't been able to get it to perform as intended.


this below is an outline of the structure i have in mind:

-----

if downtrend

ordinary short entry at market ( 2 contracts )

create stop loss order for ordinary short entry at +200 ticks from initial average entry price ( ordinary short entry )


if pullback

pullback short entry at market ( 1 contract )

move - redefine - reset - modify (create) stop loss order for ordinary short entry at + 80 ticks from combined average entry price ( average of ordinary and pullback short entries )

create stop loss order for pullback short entry at +80 ticks from combined average entry price ( average of ordinary and pullback short entries )


if downtrend ends


liquidate all short entries

cancel all stop orders


(long positions would be identical, just inverted. if i can get the short logic to work i should be able to take care of the long code as well).


-----



the problem is that once the secondary pullback entry is triggered, stop loss orders will not function anymore and the losing trades will end up being several times the maximum monetary amount that the stop loss orders should keep them to. the different experimental strategies i have created will compile and run without issue, but it has been impossible to get the stop loss orders to work.


the people with nt support recommended that i use onorderupdate and onexecutionupdate methods and i have been trying to make the only sample strategy that nt makes available work for several weeks. i have tried all the changes and experiments i could think of but haven't been able to get every entry to have its own stop loss order.

nt's help guide has zero information on these matters and even when i have two kilometric threads on the nt fora, nt support has not been of much help either. if anyone can take a look at the strategy i have uploaded or point me to any resources where i can learn how to fix this i will be most grateful.


very well, thanks, regards.

Attached Files
Elite Membership required to download: OnOrderUpdatetests.cs
Reply With Quote

Can you help answer these questions
from other members on NexusFi?
Strategy stop orders partially filled
EasyLanguage Programming
Trade idea based off three indicators.
Traders Hideout
MC PL editor upgrade
MultiCharts
Quantum physics & Trading dynamics
The Elite Circle
Cheap historycal L1 data for stocks
Stocks and ETFs
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Just another trading journal: PA, Wyckoff & Trends
22 thanks
What is Markets Chat (markets.chat) real-time trading ro …
19 thanks
GFIs1 1 DAX trade per day journal
15 thanks
ApexTraderFunding.com experience and review
15 thanks
EG Indicators
11 thanks
  #2 (permalink)
maggtrading
quintana roo, méxico
 
Posts: 84 since Mar 2013
Thanks Given: 222
Thanks Received: 40

this is the strategy that i haven't been able to make work.



 
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.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion

// This namespace holds all strategies and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Strategies
{
    public class OnOrderUpdatetests : Strategy
    {
		
		private EMA ema1;
		private bool utc = false;
		private bool dtc = false;
		private bool shpuco = false;
		private bool lopuco = false;
		private Order shorenor = null; 
        private Order shorenstor = null; 
		private Order shpuenor = null;
		private Order shpuenstor = null;
		private Order loorenor = null;
		private Order loorenstor = null;
		private Order lopuenor = null;
		private Order lopuenstor = null;
        private int shorenorsufi = 0;
		private int shpuenorsufi = 0;
		private int loorenorsufi = 0;
		private int lopuenorsufi = 0;
		
        protected override void OnStateChange()
        {
            if (State == State.SetDefaults)
            {
                Description = @"OnOrderUpdatetests";
                Name = "OnOrderUpdatetests";
                Calculate									= Calculate.OnBarClose;
				EntriesPerDirection							= 1;
				EntryHandling								= EntryHandling.UniqueEntries;
				IsExitOnSessionCloseStrategy				= false;
				ExitOnSessionCloseSeconds					= 10;
				IsFillLimitOnTouch							= false;
				MaximumBarsLookBack							= MaximumBarsLookBack.TwoHundredFiftySix;
				OrderFillResolution							= OrderFillResolution.Standard;
				Slippage									= 4;
				StartBehavior								= StartBehavior.ImmediatelySubmitSynchronizeAccount;
				TimeInForce									= TimeInForce.Gtc;
				TraceOrders									= true;
				RealtimeErrorHandling						= RealtimeErrorHandling.StopCancelCloseIgnoreRejects;
				StopTargetHandling							= StopTargetHandling.PerEntryExecution;
				BarsRequiredToTrade							= 256;				
				
				
				Ordinaryentrysize 				= 1;
				Pullbackentrysize 				= 1;
				Emap 							= 255;
				Instlonuti						= 140;
				Punuti							= 60;
				Costlonuti						= 80;
				
            }
			else if (State == State.Configure)
			{
				AddDataSeries(Data.BarsPeriodType.Minute, 1);				
			}
			else if (State == State.DataLoaded)
			{
				ema1 = EMA(Close, Convert.ToInt32(Emap));
			}
            else if (State == State.Realtime)
            {
                // one time only, as we transition from historical
                // convert any old historical order object references
                // to the new live order submitted to the real-time account
                if (shorenor != null)
                    shorenor = GetRealtimeOrder(shorenor);
                if (shorenstor != null)
                    shorenstor = GetRealtimeOrder(shorenstor);
                if (shpuenor != null)
                    shpuenor = GetRealtimeOrder(shpuenor);
				if (shpuenstor != null)
                    shpuenstor = GetRealtimeOrder(shpuenstor);
                if (loorenor != null)
                    loorenor = GetRealtimeOrder(loorenor);
                if (loorenstor != null)
                    loorenstor = GetRealtimeOrder(loorenstor);
				if (lopuenor != null)
                    lopuenor = GetRealtimeOrder(lopuenor);
                if (lopuenstor != null)
                    lopuenstor = GetRealtimeOrder(lopuenstor);
				
            }
        }

        protected override void OnBarUpdate()
        {
			
			if(BarsInProgress == 0)
			{
			
				if (CurrentBars[0] < BarsRequiredToTrade)
				return;
				
				// Set 1
				if ( Close[1] >= ema1[1]
				&& Close[0] < ema1[0] )
				{
				dtc = true;
				utc = false;
				if ( shorenor == null				 
				&& Position.MarketPosition != MarketPosition.Short )
				{
				EnterShort(Convert.ToInt32(Ordinaryentrysize), @"shoren01");
				}
				}


				// Set 2
				if ( Close[1] <= ema1[1]
				&& Close[0] > ema1[0] )
				{
				utc = true;
				dtc = false;
				if ( loorenor == null
				&& Position.MarketPosition != MarketPosition.Long )
				{
				EnterLong(Convert.ToInt32(Ordinaryentrysize), @"looren01");
				}
				}
				
			}
			else if(BarsInProgress == 1)
			{
				
//				if ( Position.MarketPosition == MarketPosition.Long && High[0] >= Position.AveragePrice + (200 * TickSize ) )
//	            {
//	                // Checks to see if our Stop Order has been submitted already
//	                if (loorenstor != null && loorenstor.StopPrice < Position.AveragePrice)
//	                {
//	                    // Modifies stop-loss to breakeven
//	                    loorenstor = ExitLongStopMarket(0, true, loorenstor.Quantity, Position.AveragePrice, "storlooren01", "looren01");
//	                }
//	            }
//				else if ( Position.MarketPosition == MarketPosition.Short && Low[0] <= Position.AveragePrice - (200 * TickSize ) )
//				{
//					 // Checks to see if our Stop Order has been submitted already
//	                if (shorenstor != null && shorenstor.StopPrice > Position.AveragePrice)
//	                {
//	                    // Modifies stop-loss to breakeven
//	                    shorenstor = ExitShortStopMarket(0, true, shorenstor.Quantity, Position.AveragePrice, "storshoren01", "shoren01");
//	                }
//				}
				
				
				if (Position.MarketPosition != MarketPosition.Short)
	            {
				shpuco = true;
	            }
				
				if ( dtc == true && shpuco == true && High[0] > ( Position.AveragePrice + ( Punuti * TickSize ) ) )
                {
				EnterShort(Convert.ToInt32(Pullbackentrysize), @"shpuen01");
				shpuco = false;
                }
	            	
				if (Position.MarketPosition != MarketPosition.Long)
	            {
				lopuco = true;
	            }
				if ( utc == true && lopuco == true && Low[0] > ( Position.AveragePrice - ( Punuti * TickSize ) ) )
                {
				EnterLong(Convert.ToInt32(Pullbackentrysize), @"lopuen01");
				lopuco = false;
                }
	            
			}
        }

        protected override void OnOrderUpdate(Order order, double limitPrice, double stopPrice, int quantity, int filled, double averageFillPrice, OrderState orderState, DateTime time, ErrorCode error, string nativeError)
        {
            // Handle entry orders here. The shorenor object allows us to identify that the order that is calling the OnOrderUpdate() method is the entry order.
            // Assign shorenor in OnOrderUpdate() to ensure the assignment occurs when expected.
            // This is more reliable than assigning Order objects in OnBarUpdate, as the assignment is not gauranteed to be complete if it is referenced immediately after submitting
            if (order.Name == "shoren01")
            {
                shorenor = order;

                // Reset the shorenor object to null if order was cancelled without any fill
                if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
                {
                    shorenor = null;
                    shorenorsufi = 0;
                }
            }
			else if (order.Name == "shpuen01")
            {
                shpuenor = order;

                // Reset the shorenor object to null if order was cancelled without any fill
                if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
                {
                    shpuenor = null;
                    shpuenorsufi = 0;
                }
            }
			else if (order.Name == "looren01")
            {
                loorenor = order;

                // Reset the shorenor object to null if order was cancelled without any fill
                if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
                {
                    loorenor = null;
                    loorenorsufi = 0;
                }
            }
			else if (order.Name == "lopuen01")
            {
                lopuenor = order;

                // Reset the shorenor object to null if order was cancelled without any fill
                if (order.OrderState == OrderState.Cancelled && order.Filled == 0)
                {
                    lopuenor = null;
                    lopuenorsufi = 0;
                }
            }
        }

        protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
        {
            /* We advise monitoring OnExecution to trigger submission of stop/target orders instead of OnOrderUpdate() since OnExecution() is called after OnOrderUpdate()
			which ensures your strategy has received the execution which is used for internal signal tracking. */
            if (shorenor != null && shorenor == execution.Order)
            {
                if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                {
                    // We sum the quantities of each execution making up the entry order
                    shorenorsufi += execution.Quantity;                    
					
					 // Submit exit orders for partial fills
                    if (execution.Order.OrderState == OrderState.PartFilled && marketPosition == MarketPosition.Short)
                    {
                        shorenstor = ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Instlonuti * TickSize ), "orstshoren01", "shoren01");
                        
                    }
                    // Update our exit order quantities once orderstate turns to filled and we have seen execution quantities match order quantities
                    else if (execution.Order.OrderState == OrderState.Filled && shorenorsufi == execution.Order.Filled && marketPosition == MarketPosition.Short)
                    {
                        // Stop-Loss order for OrderState.Filled
                        shorenstor = ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Instlonuti * TickSize ), "orstshoren01", "shoren01");
                        
                    }

                    // Resets the shorenor object and the sumFilled counter to null / 0 after the order has been filled
                    if (execution.Order.OrderState != OrderState.PartFilled && shorenorsufi == execution.Order.Filled)
                    {
                        shorenor = null;
                        shorenorsufi = 0;
                    }
                }
            }
			
			if (shpuenor != null && shpuenor == execution.Order)
            {
                if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                {
                    shpuenorsufi += execution.Quantity;                    
					
					 if (execution.Order.OrderState == OrderState.PartFilled && marketPosition == MarketPosition.Short)
                    {
                        shpuenstor = ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustshpuen01", "shpuen01");
//						shorenstor = ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustshoren01", "shoren01");
                    }
                    
                    else if (execution.Order.OrderState == OrderState.Filled && shpuenorsufi == execution.Order.Filled && marketPosition == MarketPosition.Short)
                    {
						shpuenstor = ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustshpuen01", "shpuen01");
//						shorenstor = ExitShortStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice + ( Costlonuti * TickSize ), "pustshoren01", "shoren01");
                    }

                    if (execution.Order.OrderState != OrderState.PartFilled && shpuenorsufi == execution.Order.Filled)
                    {
                        shpuenor = null;
                        shpuenorsufi = 0;
                    }
                }
            }
			
			if (loorenor != null && loorenor == execution.Order)
            {
                if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                {
                    loorenorsufi += execution.Quantity;

                    if (execution.Order.OrderState == OrderState.PartFilled && marketPosition == MarketPosition.Long)
                    {
                        loorenstor = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - ( Instlonuti * TickSize ), "orstlooren01", "looren01");
                    }
                    
                    else if (execution.Order.OrderState == OrderState.Filled && loorenorsufi == execution.Order.Filled && marketPosition == MarketPosition.Long)
                    {
                        loorenstor = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - ( Instlonuti * TickSize ), "orstlooren01", "looren01");
                    }

                    if (execution.Order.OrderState != OrderState.PartFilled && loorenorsufi == execution.Order.Filled)
                    {
                        loorenor = null;
                        loorenorsufi = 0;
                    }
                }
            }
			
			if (lopuenor != null && lopuenor == execution.Order)
            {
                if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled || (execution.Order.OrderState == OrderState.Cancelled && execution.Order.Filled > 0))
                {
                    lopuenorsufi += execution.Quantity;

                    if (execution.Order.OrderState == OrderState.PartFilled && marketPosition == MarketPosition.Long)
                    {
                        lopuenstor = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - ( Costlonuti * TickSize ), "pustlopuen01", "lopuen01");
//						loorenstor = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - ( Costlonuti * TickSize ), "pustlooren01", "looren01");
                    }
                    
                    else if (execution.Order.OrderState == OrderState.Filled && lopuenorsufi == execution.Order.Filled && marketPosition == MarketPosition.Long)
                    {
                        lopuenstor = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - ( Costlonuti * TickSize ), "pustlopuen01", "lopuen01");
//						loorenstor = ExitLongStopMarket(0, true, execution.Order.Filled, execution.Order.AverageFillPrice - ( Costlonuti * TickSize ), "pustlooren01", "looren01");
                    }
					
                    if (execution.Order.OrderState != OrderState.PartFilled && lopuenorsufi == execution.Order.Filled)
                    {
                        lopuenor = null;
                        lopuenorsufi = 0;
                    }
                }
            }

            // Reset our stop order and target orders' Order objects after our position is closed. (1st Entry)
            if (shorenstor != null && shorenstor == execution.Order) 
            {
                if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
                {
                    shorenstor = null;                    
                }
            }
			if (shpuenstor != null && shpuenstor == execution.Order) 
            {
                if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
                {
                    shpuenstor = null;                    
                }
            }
			if (loorenstor != null && loorenstor == execution.Order) 
            {
                if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
                {
                    loorenstor = null;                    
                }
            }
			if (lopuenstor != null && lopuenstor == execution.Order) 
            {
                if (execution.Order.OrderState == OrderState.Filled || execution.Order.OrderState == OrderState.PartFilled)
                {
                    lopuenstor = null;                    
                }
            }
			
        }
		
		
		#region Properties

		[NinjaScriptProperty]
		[Range(1, int.MaxValue)]
		[Display(Name="Emap", Description="emap.", Order=1, GroupName="Parameters")]
		public int Emap
		{ get; set; }
		
		[NinjaScriptProperty]
		[Range(int.MinValue, int.MaxValue)]
		[Display(Name="Instlonuti", Description="instlonuti.", Order=2, GroupName="Parameters")]
		public int Instlonuti
		{ get; set; }
		
		[NinjaScriptProperty]
		[Range(int.MinValue, int.MaxValue)]
		[Display(Name="Punuti", Description="punuti.", Order=3, GroupName="Parameters")]
		public int Punuti
		{ get; set; }
		
		[NinjaScriptProperty]
		[Range(int.MinValue, int.MaxValue)]
		[Display(Name="Costlonuti", Description="costlonuti.", Order=4, GroupName="Parameters")]
		public int Costlonuti
		{ get; set; }
		
		[NinjaScriptProperty]
		[Range(int.MinValue, int.MaxValue)]
		[Display(Name="Ordinaryentrysize", Description="ordinaryentrysize.", Order=5, GroupName="Parameters")]
		public int Ordinaryentrysize
		{ get; set; }
		
		[NinjaScriptProperty]
		[Range(int.MinValue, int.MaxValue)]
		[Display(Name="Pullbackentrysize", Description="pullbackentrysize.", Order=6, GroupName="Parameters")]
		public int Pullbackentrysize
		{ get; set; }

		#endregion

    }
}

Reply With Quote
  #3 (permalink)
maggtrading
quintana roo, méxico
 
Posts: 84 since Mar 2013
Thanks Given: 222
Thanks Received: 40


¿can anyone recommend an experienced nt programmer who could help me with this strategy? i have been working on this code for a long time but haven't been able to make it work. i would be interested in getting quotes of how much could it cost for some proficient programmer to help with this strategy.



very well, thanks, regards.

Reply With Quote




Last Updated on September 23, 2021


© 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