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

Target and Stop Loss Management

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

  • Cormick
    replied
    Hi Jim,

    Thanks for the direction.

    I've added the Short side to your MultistepBreakeven strategy,
    to a new Strategy MultistepBreakevenLongAndShort.

    After testing, the chart shows both Long and Short trades,
    so it seems it's working as intended.

    Screenshot:

    Click image for larger version  Name:	vmplayer_VYiJZa0I1J.png Views:	0 Size:	736.9 KB ID:	1165472

    Full Code:

    Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.


    Zip code NT8 Export Code attached.

    I finally grasped how to nest the multiple if() statements within both the If() Else If() statements structure.

    The 1st if() statement's action/scope can/needs to be be treated as an independent scope (without if() statement—
    it's if is the Top one/The one from the If() Else if() structure.

    if ((Position.MarketPosition == MarketPosition.Flat) && (Close[0] > Open[0]))
    {
    {
    EnterLong(Convert.ToInt32(DefaultQuantity), "");
    StopLossModeLong = 0;
    }

    If(X)
    {
    do A;
    }

    If(Y)
    {
    do B;
    }

    If(Z)
    {
    do C;
    }
    }
    else if ((Position.MarketPosition == MarketPosition.Flat) && (Close[0] < Open[0]))
    {
    {
    EnterShort(Convert.ToInt32(DefaultQuantity), "");
    StopLossModeShort = 0;
    }

    If(P)
    {
    do D;
    }
    If(Q)
    {
    do E;
    }

    If(R)
    {
    do F;
    }
    }




    I'll tackle next testing the Unmanaged Order approach, then the PositionAccount.Quantity method.
    Attached Files
    Last edited by Cormick; 07-28-2021, 02:43 AM.

    Leave a comment:


  • NinjaTrader_Jim
    replied
    Hello Cormick,

    You can use PositionAccount to monitor an account position instead of a strategy position. PositionAccount.Quantity will tell you the current quantity of the account position.

    PositionAccount - https://ninjatrader.com/support/help...ionaccount.htm

    Leave a comment:


  • Cormick
    replied
    Hi Jim,

    After further tests, the Strategy auto-disables itself.

    Here's the test post:
    I'll start from scratch tomorrow back to your strategy trying to add the Short side and see if I can make it work.

    I'll be back with the results and we'll see from there.

    Be well!

    Leave a comment:


  • Cormick
    replied
    Hi Jim,

    Thanks a lot for the reply! I just noticed it today.

    I've updated my code.
    It's working now both for Long and Short with the simple If() Else If() structure.

    I'll do some more testing and be back with definitive results asap.

    Be well!

    EDIT:

    About the Quantity parameter of the SubmitOrderUnmanaged() method:

    Documentation:


    It states:
    quantity Sets the number of contracts to submit with the order

    Is it possible to get the SubmitOrderUnmanaged() auto-detect the quantity from the Manually entered order?—

    —Thanks a lot for the AdoptAccountPositionTestUnmanaged.zip sample above, great new concepts with the OnExecutionUpdate() method and the sumFilled variable to track quantities.
    I also found the 'Position.Quantity' way to set the quantity in the (State == State.Realtime) method. That should do!

    I'll try figuring it out from there and be back later with result!

    Be well!


    Last edited by Cormick; 07-26-2021, 08:14 AM. Reason: EDIT: sumFilled variable to track quantities, OnExecutionUpdate(), (State == State.Realtime), Position.Quantity

    Leave a comment:


  • NinjaTrader_Jim
    replied
    Hello Cormick,

    Yes, you can use the same approach outlined in the in my MultiStepBreakevenStrategyBuilder example for long and short side.

    Some items to keep in mind:

    Order prices for Long orders would need to be flipped to be on the other side of the market to be valid for short side.

    You cannot have a pending Long entry and Short entry at the same time unless you use the Unmanaged Approach because having pending orders for long and short entry would not be allowed by the Managed Approach. The Strategy Builder generates Managed Approach code.

    Internal Rules of the Managed Approach - https://ninjatrader.com/support/help...antedPositions

    Any short side target and stop logic should be checked with Position checks for Short side, similarly to how the Long position checks are made.

    If you want to use Set methods for Long/Short side, I recommend using separate Entry Signal names and having separate Set methods tied to each unique entry.

    For creating a strategy that captures the account position. I suggest unlocking the code, skipping historical processing with if (State == State.Historical) return; at the top of OnBarUpdate, and then checking the captured Position in OnStateChange when State == State.Realtime to place target and stop based on the captured position. I have attached Managed and Unmanaged examples.
    Attached Files

    Leave a comment:


  • Cormick
    replied
    Originally posted by NinjaTrader_Jim View Post
    Hello SamuelO,

    It is possible to create your own Auto Breakeven and Auto Trail logic using Exit methods in the Conditions and Actions section of the Strategy Builder. I have attached an example that can demonstrate moving a stop market order for the stop loss using logic in Conditions and Actions.

    To get more acquainted with building strategies with the Strategy Builder, I suggest starting with the Strategy Builder 301 tutorial and testing our Conditions and Actions examples. Once you are familiar with how to set up logic with the Strategy Builder, I would then suggest building a simple strategy, and then to add complexity after creating smaller test strategies.

    Strategy Builder 301 — https://www.youtube.com/watch?v=_KQF2Sv27oE

    Live webinar - https://ninjatrader.com/Webinar/Strategy-Builder-301

    Conditions examples —https://ninjatrader.com/support/help...on_builder.htm

    Actions examples — https://ninjatrader.com/support/help...us/actions.htm

    We look forward to assisting.
    Hi Jim,

    Wondering if we can extend the logic to include the Short side in your code.

    Would a simple else if structure do?

    I saw this NT7 code includes both Long and Short that way:




    Could you please tell if it would work with your code?

    The use is for a strategy that auto-manages manually placed trades, either long or short ones.
    The references I've used:

    https://ninjatrader.com/support/foru...ons#post675767
    https://ninjatrader.com/support/help...runmanaged.htm
    https://ninjatrader.com/support/help...d_approach.htm
    https://ninjatrader.com/support/help...er_methods.htm
    https://ninjatrader.com/support/help...d_approach.htm
    https://ninjatrader.com/support/help...rderupdate.htm
    https://ninjatrader.com/support/help...nt8/?order.htm
    https://ninjatrader.com/support/help...d_approach.htm

    CancelOrder()
    OnOrderUpdate()
    Order
    ChangeOrder()
    if(PositionAccount.MarketPosition != MarketPosition.Flat)
    IsAdoptAccountPositionAware = true;
    StartBehavior = StartBehavior.AdoptAccountPosition;
    unmanaged SubmitOrderUnmanaged()
    Remember to set IsUnmanaged = true in State.SetDefaults




    Would something like:

    if (PositionAccount.MarketPosition == MarketPosition.Long)
    {
    //manage the Long Position multi steps breakeven logic
    // Sets 1 to 6



    }
    else if (PositionAccount.MarketPosition == MarketPosition.Short)
    {
    //manage the Short Position multi steps breakeven logic
    // Sets 7 to 12



    }

    I ask because it seems not that straightforward with the multiple if statements of the embedded Sets.
    I previously had the issue that only the 2nd part of the if ... else if statement would execute on another strategy here:

    Do you know if we can do the embedding and both parts still execute?
    Else do you see a workaround if we can't do it with the simple if ... else if structure.

    I attached back your code unchanged.
    Thanks.
    Attached Files
    Last edited by Cormick; 07-19-2021, 06:00 AM.

    Leave a comment:


  • NinjaTrader_Jim
    replied
    Hello SamuelO,

    For new inquires, please feel free to open a new thread as it can help other users searching the forum to quickly find answers.

    We currently do not save the Strategy with the order in the database, but you can see this in Trade Performance if the strategy is currently running.

    I have added a vote on your behalf to SFT-1817 for consideration to have the strategy also saved with the order in the database.

    Feature Request Disclaimer

    We receive many requests and cannot reasonably implement all requested features or changes. Interest is tracked internally and if enough interest is tracked, it would be weighed against how feasible it would be to make those changes to consider implementing.

    When new features are implemented, they will be listed in the Release Notes page of the Help Guide. The ID number will be different than the internal feature request tracking ID, but the description of the feature will let you know if that feature has been implemented.

    Release Notes -
    https://ninjatrader.com/support/help...ease_notes.htm

    Please let us know if there is anything else we can do to help.

    Leave a comment:


  • SamuelO
    replied
    Hello.
    How do I get the strategy name to be saved in all my orders when I see Trade Performance, Orders in Strategy Column.
    Thanks

    Leave a comment:


  • NinjaTrader_Jim
    replied
    Hello SamuelO,

    There is no intrabar data in a historical backtest (Strategy Analyzer.) Historical orders are filled estimating how the market would move from the Open High Low and Close values of the bar used to fill the order. Logic is also forced to calculate using Calculate.OnBarClose.

    Discrepancies between realtime and backtesting — https://ninjatrader.com/support/help...ime_vs_bac.htm

    Understanding Historical Fill Processing - https://ninjatrader.com/support/help...ical_fill_.htm

    Additional steps can be taken to get Strategy Analyzer results closer to realtime simulations.

    Tick Replay allows for intrabar logical processing so OnBarUpdate can be processed with historical data following Calculate.OnEachTick or Calculate.OnPriceChange.

    High Order Fill resolution allows for having orders filled with intrabar data. This is the same effect as adding a single tick data series and then submitting orders to that data series. Set methods do not allow for specifying the data series used to fill the order. I would recommend using Exit methods if you want to specify which data series should be used to fill the order.

    High Order Fill Resolution is not compatible with Multi Time Frame strategies or Tick Replay strategies. Those strategies should then submit orders to a single tick data series to have them filled intrabar. The example below can demonstrate.

    Backtesting with intrabar granularity (can be used in place of High Order Fill Resolution) — https://ninjatrader.com/support/help...ipt_strate.htm

    Further detail on comparing historical and realtime processing can be found below.

    Comparing real-time, historical, and replay performance — https://ninjatrader.com/support/foru...mance?t=102504

    Please let us know if we can be of further assistance.

    Leave a comment:


  • SamuelO
    replied
    Hello, I continue working with my strategy and I have it in tests.

    In MarketReplay it works very well, however in the Strategy Analyzer the results are not reliable.
    Do I have to add any code to my strategy so that the Strategy Analzer will give me more reliable results?

    Leave a comment:


  • NinjaTrader_Jim
    replied
    Hello,

    For debugging tips with the Strategy Builder, please see the resources below. The Playback Connection can help to repeat cases that have happened with realtime data so you can take debugging steps to analyze how your logic executes at that time.

    Debugging Tips - https://ninjatrader.com/support/help...script_cod.htm
    TraceOrders - https://ninjatrader.com/support/help...aceorders2.htm
    Debugging in the Strategy Builder - https://drive.google.com/file/d/1mTq...w?usp=drivesdk
    Playback Connection - https://ninjatrader.com/support/help...connection.htm
    Debugging Demo - https://drive.google.com/file/d/1rOz...w?usp=drivesdk

    guidoisot The MultiStepBreakeven strategy works by setting a StopLossMode for each level we want to move the stop loss to. It sets the StopLossMode to 0 once we enter, and then on the next bar, the stop will be placed 10 ticks away from the average entry price. If you want to place the stop loss sooner to protect the position as soon as an entry is made, OnExecutionUpdate can be used. (OnExecutionUpdate will occur whenever a strategy order is filled. This will not depend on another bar formation as it will be processed as a separate event when NinjaTrader sees a strategy order executed.)

    The SampleOnOrderUpdate strategy demonstrates using OnOrderUpdate and OnExecutionUpdate for handling profit target and stop loss. You can then add your own logic to update these orders to new levels similar to the MultiStepBreakeven strategy which modifies Exit orders in OnBarUpdate.

    SampleOnOrderUpdate - https://ninjatrader.com/support/help...and_onexec.htm

    In regards to your feature requests, could you email me at platformsupport [at] ninjatrader [dot] com with the text "Attn Jim 2569284" and include a link to this thread? I would like to discuss these further with you but would like to keep this thread on topic.

    We look forward to assisting.

    Leave a comment:


  • guidoisot
    replied
    with regard to the attached image and to the MultiStepBreakevenStrategy discussed here, how would it be possible to avoid that the SL goes down to -38 ticks, instead of being executed at -12 ticks, as it would be expected according to Set 2?
    When price reached BE trigger levels, this last position was not exited to let it possibly become a “runner”, always maintaining active its Default_SL_long, ie at -12 ticks. However the actual exit was at -38 ticks.
    Strategy is set to cycle “onpricechange” and it includes a 1 tick additional data series.

    thx

    Click image for larger version  Name:	ES 06-20 (10 Minute) 2020_05_13 (10_24_47).png Views:	0 Size:	132.0 KB ID:	1102351
    Last edited by guidoisot; 05-29-2020, 03:03 AM.

    Leave a comment:


  • guidoisot
    replied
    Since I find confusing to look at tables with hundreds of rows of homogeneous gray numbers with many decimals each, I prefer to carry out simple debugging by drawing on the chart lines and/or text rather than using prints on the NinjaScript Output, as shown on the attached video.
    The problem here is that I do not know either how to draw all the various (green, red, yellow, …) vertical lines only on a specific additional panel, or how to draw the lines and the text only on a limited zone at the bottom of the price panel, rather than n_ticks above or below price.

    If the possibility “to add/send any one/or/many drawing only on a specific additional/existing panel” is not already available, could you please consider this as a new feature request?

    Another feature to add to the draw command that I think would be interesting is the possibility of selecting a transparency degree of the drawings, this way one could draw them also over the price panel, without hiding everything else is already on the price panel. Thx.




    Click image for larger version  Name:	ES 06-20 (500 Tick) 2020_05_28 (09_34_08).png Views:	0 Size:	138.7 KB ID:	1102345

    Last edited by guidoisot; 05-29-2020, 01:57 AM.

    Leave a comment:


  • SamuelO
    replied
    Can you support me with videos of the use of the Ninja debugger? The NinjaScript Output

    Thanks

    Leave a comment:


  • NinjaTrader_Jim
    replied
    Hello SamuelO,

    Thanks for your reply.

    In my strategy, I am managing the StopLoss, and I have a defined Profit, but it is not to take profit by touching it.
    I want to activate a TrailingStop by touching the expected Profit ... and from then on follow it with Trailing Stop.
    Any example that can help me?
    You would need to set up logic in Conditions and Actions similar to the example script provided to control your Trailing Stop with your own trigger. For example, you could check if the current market price (Close[0]) is equal to your profit target's price (if you have a variable for it's price level,) or to see if the price has risen X number of ticks from the the Average Entry Price when you are in a Long position. When this condition is true, set a bool variable to true or set an integer variable (like StopLossMode in the example) to set an "AutoTrail Mode."

    When the script is in "AutoTrail Mode", move the stop loss in association to the Average Entry Price.

    To keep the stop loss from adjusting if price is going down, you can keep track of the current market price when you move the stop loss.

    For example, you could check something like if (StopLossMode == 4 && Close[0] > LastSavedPrice)

    and then move the stop loss and save the current market price (Close[0]) to your LastSavedPrice variable.

    Daily Loss limit strategies cannot be programmed in the Stratetgy Builder since the Strategy Builder is limited in performing mathematical offsets to user variables. An example for doing this with unlocked code can be found below.

    Hello, I've updated the DailyLossLimit and DailyLosLimitMultiTrade examples that were posted on the forum for NinjaTrader 7 for NinjaTrader 8. These are often requested and I felt they are good examples to have for NT8. DailyLossLimitExample_NT7 - http://ninjatrader.com/support/forum...241#post451241 (http://ninjatrader


    For controlling when the strategy will be allowed to trade, you can use the time filters to control when strategy actions should be taken. Please see How to create a Time Filter in our Strategy Builder conditions examples.



    You can then create the time filter, enable the strategy, and then it will only tke the actions you specify within those time time filters.

    We look forward to assisting.

    Leave a comment:

Latest Posts

Collapse

Topics Statistics Last Post
Started by Waxavi, Today, 02:10 AM
1 response
16 views
0 likes
Last Post NinjaTrader_LuisH  
Started by Kaledus, Today, 01:29 PM
5 responses
13 views
0 likes
Last Post NinjaTrader_Jesse  
Started by Waxavi, Today, 02:00 AM
1 response
11 views
0 likes
Last Post NinjaTrader_LuisH  
Started by alifarahani, Today, 09:40 AM
5 responses
23 views
0 likes
Last Post NinjaTrader_Jesse  
Started by gentlebenthebear, Today, 01:30 AM
3 responses
16 views
0 likes
Last Post NinjaTrader_Jesse  
Working...
X