Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Setting stop loss based on time

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

    Setting stop loss based on time

    Hi, I'm trying to test a simple strategy - after setting my profit target and calling EnterLong(), if my long position is still open after 30 thirty days (i.e. profit target still not achieved) then I would like to exit that position. Btw I have only 1 open long position at any given time (i.e. I set EntriesPerDirection = 1) and I'm using 5-min bars.

    To achieve this, the code I have in mind is:

    Code:
    protected override void OnBarUpdate()
    {
     	if (CrossAbove(SMA(10), SMA(20), 1))
    		EnterLong(100, "myEntryOrder");
    	
    	/* Check if position is still open 30 days (i.e. 8640 5-min bars) later */
    	if ((Position.MarketPosition != MarketPosition.Flat) && (BarsSinceEntryExecution() > 8640)) 
    		ExitLong();
    }
    Would this work? I'm asking because I looked through the documentation for NinjaTrader 8 and saw that there might be other means available (e.g. using Order.Time?) so I'm just wondering if there might be a better way to do this...

    Greatly appreciate any advice, thanks

    #2
    Hello Vypre,

    Thanks for your post.

    Yes, BarsSinceEntryExecution() will work and in the case of a named entry "myEntryOrder" you would want to specify that same name in the within the method, ie: BarsSinceEntryExecution("myEntryOrder")

    Using 5 minute bars, 8640 bars would equate to 720 trading hours. If you instead wanted to exit after 30 calendar days then you could so something like:

    if (your conditions to enter)
    {
    EnterLong("myEntryOrder");
    myEntrydatetime = Time[0]; // assign the entry bar time to a previously created variable datetime called myEntrydatetime
    }

    if (Position.MarketPosition != MarketPosition.Flat && Time[0] >= myEntrydatetime.AddDays(30)) // add 30 calendar days to the entry date
    {
    ExitLong("myEntryOrder");
    }


    Please note that you can test any situation using the Sim101 account.

    Comment

    Latest Posts

    Collapse

    Topics Statistics Last Post
    Started by NullPointStrategies, Yesterday, 05:17 AM
    0 responses
    56 views
    0 likes
    Last Post NullPointStrategies  
    Started by argusthome, 03-08-2026, 10:06 AM
    0 responses
    132 views
    0 likes
    Last Post argusthome  
    Started by NabilKhattabi, 03-06-2026, 11:18 AM
    0 responses
    73 views
    0 likes
    Last Post NabilKhattabi  
    Started by Deep42, 03-06-2026, 12:28 AM
    0 responses
    45 views
    0 likes
    Last Post Deep42
    by Deep42
     
    Started by TheRealMorford, 03-05-2026, 06:15 PM
    0 responses
    49 views
    0 likes
    Last Post TheRealMorford  
    Working...
    X