Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Breakeven coding for strategy

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

    Breakeven coding for strategy

    Hi and help!

    When I run the below code in Strategy Analyzer (as a strategy) the breakeven doesn't appear to work correctly. (full code file attached for reference)

    I have downloaded and looked at other breakeven code examples and they do not appear to work correctly either. I have played with the run settings (order fill resolution etc.), perhaps I am missing something here?

    The issue is that the breakeven occurs too early. Refer attached image - the first green trade moves to breakeven when its only 2.6 pips in positive direction (it should have been about 6 pips). I have tried playing wiht the *TickSize*10 code.

    If this code has TickSize*10 it seems to be too large.... is there a scaling issue here? <BreakevenPrice = (Position.AveragePrice - (BreakevenPIPS * TickSize * 1));>

    Also - can anyone help me print bar timestamps for output and debugging purposes?!?!

    I am using NT8 (8.0.28.0 64-bit) multi-broker. The instrument being used is forex pair.


    Code:
    [HASHTAG="t3322"]region[/HASHTAG] 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
    {
    public class RSIcrossTESTshortsX2 : Strategy
    {
    private RSI RSI1;
    private ParabolicSAR ParabolicSAR1;
    private int TriggerSTATE;
    private double CurrentAskPrice;
    private double BreakevenPrice;
    private double EntryPrice;
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "RSIcrossTESTshortsX2";
    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 = 0;
    // Disable this property for performance gains in Strategy Analyzer optimizations
    // See the Help Guide for additional information
    IsInstantiatedOnEachOptimizationIteration = true;
    RSIperiod = 13;
    RSIsmooth = 4;
    RSIextremeHIGH = 70;
    RSIextremeLOW = 64;
    StopPIPS = 4;
    BreakevenPIPS = 6;
    ProfitPIPS = 6;
    SUPERTRENDperiod = 14;
    SUPERTRENDsmooth = 14;
    TradeSize = 2000;
    SMAperiod = 14;
    BreakEvenBool = false;
    TriggerSTATE = 0;
    TrailingStopValue = 5;
    }
    else if (State == State.Configure)
    {
    }
    else if (State == State.DataLoaded)
    {
    RSI1 = RSI(Close, Convert.ToInt32(RSIperiod), Convert.ToInt32(RSIsmooth));
    RSI1.Plots[0].Brush = Brushes.DodgerBlue;
    RSI1.Plots[1].Brush = Brushes.Goldenrod;
    AddChartIndicator(RSI1);
    ParabolicSAR1 = ParabolicSAR(Close, 0.02, 0.2, 0.02);
    ParabolicSAR1.Plots[0].Brush = Brushes.Goldenrod;
    //AddChartIndicator(ParabolicSAR1);
    }
    }
    protected override void OnBarUpdate()
    {
    CurrentAskPrice = GetCurrentBid(0);
    if (BarsInProgress != 0)
    return;
    if (CurrentBars[0] < 2)
    return;
    // Set 1 - ENTRY
    if ((Position.MarketPosition == MarketPosition.Flat)
    && ())//ENTRY CRITERIA HERE );
    {
    EnterShort(Convert.ToInt32(TradeSize), @"EntryShort");
    //SetStopLoss(CalculationMode.Price, Position.AveragePrice+(StopPIPS*TickSize*10));
    ExitShortStopMarket(Convert.ToInt32(Position.Quant ity), (Position.AveragePrice + (StopPIPS * TickSize * 10)) , @"EntryShortStop", @"EntryShort");
    TriggerSTATE = 1;
    }
    
    // Set 2 - DEFINE VARIABLES
    if ((TriggerSTATE == 1)
    && (Position.MarketPosition == MarketPosition.Short))
    {
    BreakevenPrice = (Position.AveragePrice - (BreakevenPIPS * TickSize * 1));
    EntryPrice = Position.AveragePrice;
    }
    // Set 3 - TRAILING STOP
    if ((TriggerSTATE == 1)
    && (Position.MarketPosition == MarketPosition.Short)
    && (CurrentAskPrice < BreakevenPrice))
    {
    //SetStopLoss(CalculationMode.Price, EntryPrice);
    ExitShortStopMarket(Convert.ToInt32(Position.Quant ity), EntryPrice, @"EntryShortStop", @"EntryShort");
    //Print(Cbi.Connection.PlaybackConnection.Now.ToStri ng("hh:mm:ss"));
    Print(EntryPrice + " Entry Price");
    Print(BreakevenPrice + " BreakevenPrice");
    Print(Position.AveragePrice + " Position.AveragePrice");
    Print(string.Format("High: {0} | Low: {1}", High[0], Low[0]));
    //Print(Low[0], " Low");
    //Print(string.Format("{0}"), EntryShortStop);
    }
    ​
    Attached Files
    Last edited by Apm123; 08-23-2024, 01:05 AM.

    #2
    I really cannot figure it out. Below is another breakeven example (by others) that does not work in Strategy Analyzer. The images show one example where the SL BE trigger point of 5 pips (+-5) is not triggered.

    What am i doing wrong here? I have played around with the Strategy Analyzer settings quite a bit and done quite a few different coding methods.



    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.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
    {
      public class ShortBreakEvenBuilderExample : Strategy
      {
        private double StopPrice;
        private int TriggerPrice;
        private int TriggerState;
    
        protected override void OnStateChange()
        {
          if (State == State.SetDefaults)
          {
            Description                 = @"Enter the description for your new custom Strategy here.";
            Name                    = "ShortBreakEvenBuilderExample";
            Calculate                 = Calculate.OnPriceChange;
            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;
            ShortBreakEvenTrigger         = -5;
            ShortInitialStopDistance          = 10;
            ShortTargetTicks          = -20;
            StopPrice         = 0;
            TriggerPrice          = 0;
            TriggerState          = 0;
          }
          else if (State == State.Configure)
          {
          }
        }
        protected override void OnBarUpdate()
        {
          if (BarsInProgress != 0)
            return;
           // Set 1
          if ((TriggerState >= 2)
             && (Position.MarketPosition == MarketPosition.Flat))
          {
            TriggerState = 0;
          }
        
          if (CurrentBars[0] < 1)
            return;
           // Set 3
          if ((Close[0] < Close[1])
             && (Position.MarketPosition == MarketPosition.Flat))
          {
            TriggerState = 1;
            EnterShort(10000, @"ShortEntry");
          }
        
           // Set 5
          if ((TriggerState == 1)
             && (Position.MarketPosition == MarketPosition.Short))
          {
            TriggerState = 2;
            StopPrice = (Position.AveragePrice + (ShortInitialStopDistance * TickSize*10)) ;
            TriggerPrice = Convert.ToInt32((Position.AveragePrice + (ShortBreakEvenTrigger * TickSize*10)) );
          }
        
           // Set 7
          if ((TriggerState == 2)
             && (Position.MarketPosition == MarketPosition.Short)
             && (Close[0] <= TriggerPrice))
          {
            TriggerState = 3;
            StopPrice = Position.AveragePrice;
          }
        
           // Set 9
          if ((TriggerState >= 2)
             && (Position.MarketPosition == MarketPosition.Short))
          {
            ExitShortStopMarket(10000, StopPrice, @"ShortExit", @"ShortEntry");
          }
        
           // Set 11
          if ((Position.MarketPosition == MarketPosition.Short)
             && (Close[0] <= (Position.AveragePrice + (ShortTargetTicks * TickSize*10)) ))
          {
            ExitShort(10000, @"ShortProfitTarget", @"ShortEntry");
          }
        
        }
        #region Properties
        [NinjaScriptProperty]
        [Range(-999, int.MaxValue)]
        [Display(Name="ShortBreakEvenTrigger", Order=2, GroupName="Parameters")]
        public int ShortBreakEvenTrigger
        { get; set; }
        [NinjaScriptProperty]
        [Range(1, int.MaxValue)]
        [Display(Name="ShortInitialStopDistance", Order=4, GroupName="Parameters")]
        public int ShortInitialStopDistance
        { get; set; }
        [NinjaScriptProperty]
        [Range(-999, int.MaxValue)]
        [Display(Name="ShortTargetTicks", Order=6, GroupName="Parameters")]
        public int ShortTargetTicks
        { get; set; }
        #endregion
      }
    }
    ​
    Attached Files

    Comment


      #3
      Hello Apm123,

      That may be that the condition is not becoming true. The best way to check would be to use a Print and see if anything is output. I have linked a video that goes over using prints in the builder below. You can just print anything like a word inside that condition and then check the output window after doing the test. If the print is not present that means the condition was not true so you would have to check why the condition was not true as the next step.

      Comment

      Latest Posts

      Collapse

      Topics Statistics Last Post
      Started by NullPointStrategies, Today, 05:17 AM
      0 responses
      50 views
      0 likes
      Last Post NullPointStrategies  
      Started by argusthome, 03-08-2026, 10:06 AM
      0 responses
      126 views
      0 likes
      Last Post argusthome  
      Started by NabilKhattabi, 03-06-2026, 11:18 AM
      0 responses
      69 views
      0 likes
      Last Post NabilKhattabi  
      Started by Deep42, 03-06-2026, 12:28 AM
      0 responses
      42 views
      0 likes
      Last Post Deep42
      by Deep42
       
      Started by TheRealMorford, 03-05-2026, 06:15 PM
      0 responses
      46 views
      0 likes
      Last Post TheRealMorford  
      Working...
      X