Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

SetStop at dynamic levels

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

    SetStop at dynamic levels

    I've created a strategy to enter a long position under certain conditions and at the same time place a RiskReward drawing based on the candle prior to entering the position.

    Now, I'm attempting to place a profit target at the same price as the Reward line of the RiskReward drawing and I cannot figure it out (I am very new so I'm sure this is simple or simply not possible).

    The code I have now, which I'll paste below, does hit profit targets but I can't see any correlation with the levels set by the RiskReward tool.

    Any guidance or assistance would be greatly appreciated.


    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.EmaTest.Long
    {
    public class BesrForBullWPT : Strategy
    {
    private int TradeCounter;

    private EMA EMA1;
    private VWAP VWAP1;
    private EMA EMA2;
    private ExampleMADifference ExampleMADifference1;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enters long position when price crosses below EMA[50] and closes above it. ";
    Name = "BestForBullWPT";
    Calculate = Calculate.OnBarClose;
    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;
    ProfitTarget = 1000;
    StopLoss = 1000;
    EmaDifference = 0;
    MaxTrades = 100;
    EntryEmaOffset = 0;
    EmaDiffMinAgo = 1;
    RiskReward = 1;
    }
    else if (State == State.Configure)
    {
    }
    else if (State == State.DataLoaded)
    {
    EMA1 = EMA(Close, 50);
    VWAP1 = VWAP(Close);
    EMA2 = EMA(Close, 50);
    ExampleMADifference1 = ExampleMADifference(Close);
    EMA1.Plots[0].Brush = Brushes.SteelBlue;
    ExampleMADifference1.Plots[0].Brush = Brushes.Goldenrod;
    SetProfitTarget("", CalculationMode.Ticks, ProfitTarget);
    SetStopLoss("", CalculationMode.Ticks, StopLoss, false);

    }
    }

    protected override void OnBarUpdate()
    {
    if (Bars.IsFirstBarOfSession)
    {
    TradeCounter = 0; // reset on new trading day
    }

    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 10)
    return;

    // Set 1
    if ((EMA1[0] > VWAP1.PlotVWAP[0])
    && (Position.MarketPosition == MarketPosition.Flat && TradeCounter < MaxTrades)
    && (Low[1] <= EMA2[1] + (EntryEmaOffset * TickSize))
    && (Close[1] >= EMA2[1])
    && (Close[0] > EMA2[0])
    && (Close[1] > EMA2[1] + (4 * TickSize))


    // between times
    && (Times[0][0].TimeOfDay > new TimeSpan(8, 30, 0))
    && (Times[0][0].TimeOfDay < new TimeSpan(16, 0, 0))

    // AddOns
    && ((ExampleMADifference1[0] > EmaDifference)
    && (ExampleMADifference1[0] > ExampleMADifference1[EmaDiffMinAgo])))
    {

    EnterLong(Convert.ToInt32(DefaultQuantity), "Long");
    TradeCounter++;

    //drawing
    Draw.RiskReward(this, "tag1" + CurrentBar, true, 0, Close[0], -15, (Low[1] - (4 * TickSize)), RiskReward, true);

    //problem area
    SetProfitTarget(CalculationMode.Ticks, (Convert.ToInt32(Close[0] - (Low[1] - (4 * TickSize)))));
    }

    // Set 2
    if ((Close[0] < EMA2[0])
    && (Low[1] < EMA2[1])
    || (Times[0][0].TimeOfDay > new TimeSpan(16, 38, 0)))

    {
    ExitLong(Convert.ToInt32(DefaultQuantity), "", "");
    }

    Print (Time[0]+"TradeCount = "+TradeCounter);

    }

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

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

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

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

    [NinjaScriptProperty]
    [Range(-16, int.MaxValue)]
    [Display(Name="EntryEmaOffset", Order=5, GroupName="Parameters")]
    public int EntryEmaOffset
    { get; set; }

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

    [NinjaScriptProperty]
    [Range(1, double.MaxValue)]
    [Display(Name="RiskReward", Order=7, GroupName="Parameters")]
    public double RiskReward
    { get; set; }



    #endregion

    }
    }

    #2
    Hello setardiff,

    A sell limit is placed above the current bid price, a buy limit is placed below the current ask price.
    This appears to be a sell limit to exit a long position. However the price you have chosen would be below the bid not above the bid.
    Were you intending to use a sell stop order which would be below the bid?

    Also, Set methods cannot be unset, and should be called before placing entry order.

    The ProfitChaseStopTrailSetMethodsExample provides an example of dynamically using Set methods.
    Chelsea B.NinjaTrader Customer Service

    Comment


      #3
      Thanks for the quick response. You'll have to bear with me as I'm very much a novice.

      In terms of the it appearing to be a sell limit, are you referring to the SetProfitTarget line?

      I guess a better way to explain is I'm trying to set a profit target that is equal in distance to Close[0] - Low[1]. So for example in /ES: if Close[0] is 5000 and Low[1] is 4996, the profit target would be set to 16 upon order entry.

      The line I'm attempting to make work:
      SetProfitTarget(CalculationMode.Ticks, (Convert.ToInt32(Close[0] - (Low[1] - (4 * TickSize)))));

      The drawing tool that draws the value I'm looking to replicate:.
      Draw.RiskReward(this, "tag1" + CurrentBar, true, 0, Close[0], -15, (Low[1] - (4 * TickSize)), RiskReward, true);

      As I said before, it is hitting profit targets. I'm just not sure why they don't match the levels drawn by the RiskReward tool, as they're seemingly the same calculations.

      Comment


        #4
        Hello setardiff,

        Yes, a profit target for a long position would be a sell limit order.

        What value is being produced by the calculation?

        Convert.ToInt32(Close[0] - (Low[1] - (4 * TickSize))))

        Print this this to the output window to make sure this is making sense as a number of ticks (using CalculationMode.Ticks).

        Below is a link to a support article on adding debugging prints to understand behavior.
        Chelsea B.NinjaTrader Customer Service

        Comment


          #5
          Assuming I'm using the Print function right, it shows =5 for every minute in the output window. I figured it would only print when the conditions are met, but it's printing every minute as 5 regardless of bar data.

          Comment


            #6
            Actually, disregard my last response. I was not reading it correctly.

            Comment


              #7
              It seems to make sense, as in it's calculating a reasonable number, though it's not calculating Close[0] - (Low[1] - (4 * TickSize)))) the same way that the drawing tool does.
              And I can't seem to find the correlation between these profit targets and what the drawing tool is calculating.

              The drawing is initiated on the close of the candle but the position enters at the open of the next candle. But there's never more than a tick difference between the order entry and the 0 line of the drawing, so that doesn't account for the greater difference I'm seeing.

              Comment


                #8
                I was able to find a solution.

                SetProfitTarget(CalculationMode.Ticks, (Convert.ToInt32((((Close[0] - Low[1])*4)+4))));

                I suspect I was using TickSize improperly and/or misplacing parenthesis, but either way, this seems to work.

                Thanks again.

                Comment

                Latest Posts

                Collapse

                Topics Statistics Last Post
                Started by NullPointStrategies, Yesterday, 05:17 AM
                0 responses
                71 views
                0 likes
                Last Post NullPointStrategies  
                Started by argusthome, 03-08-2026, 10:06 AM
                0 responses
                143 views
                0 likes
                Last Post argusthome  
                Started by NabilKhattabi, 03-06-2026, 11:18 AM
                0 responses
                76 views
                0 likes
                Last Post NabilKhattabi  
                Started by Deep42, 03-06-2026, 12:28 AM
                0 responses
                47 views
                0 likes
                Last Post Deep42
                by Deep42
                 
                Started by TheRealMorford, 03-05-2026, 06:15 PM
                0 responses
                51 views
                0 likes
                Last Post TheRealMorford  
                Working...
                X