Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

ATM Strategy not getting triggered with Strategy

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

    ATM Strategy not getting triggered with Strategy

    Hey everyone!

    I've always found it a bit tricky when it comes to crafting a strategy from scratch or even tweaking one that's already out there. I've been using ChatGPT Plus, particularly version 4, hoping for the best outcomes. Yet, even with ChatGPT, I've noticed some logical inconsistencies.

    Here's something that's been bugging me: I came across a piece of code from this forum, and for some reason, it isn't triggering the ATM strategy I've set up. I'm trying to wrap my head around why certain actions seem to take priority over my commands.

    Would any of you mind taking a peek at my code? I'll also share my settings below to give you a clearer picture.

    When I am in a trade, I can't even close it manually.

    Code:
    //This namespace holds Strategies in this folder and is required. Do not change it.
    
    namespace NinjaTrader.NinjaScript.Strategies
    {
        public class Strategy1 : Strategy
        {
            private LinReg LinReg1;
            private VWMA VWMA1;
    
            public class FriendlyAtmConverter : TypeConverter
        {  
            // Set the values to appear in the combo box
            public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
            {
                List<string> values = new List<string>();
                string[] files = System.IO.Directory.GetFiles(System.IO.Path.Combine(NinjaTrader.Core.Globals.UserDataDir, "templates", "AtmStrategy"), "*.xml");  
    
                foreach(string atm in files)
                {
                    values.Add(System.IO.Path.GetFileNameWithoutExtension(atm));
                    NinjaTrader.Code.Output.Process(System.IO.Path.GetFileNameWithoutExtension(atm), PrintTo.OutputTab1);
                }
                return new StandardValuesCollection(values);
            }
    
            public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
            {
                return value.ToString();
            }
    
            public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
            {
                return value;
            }
    
            // required interface members needed to compile
            public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
            { return true; }
    
            public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
            { return true; }
    
            public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
            { return true; }
    
            public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
            { return true; }}
    
            protected override void OnStateChange()
            {
                if (State == State.SetDefaults)
                {
                    Description                                    = @"Enter the description for your new custom Strategy here.";
                    Name                                        = "Strategy1";
                    Calculate                                    = Calculate.OnBarClose;
                    EntriesPerDirection                            = 1;
                    EntryHandling                                = EntryHandling.AllEntries;
                    IsExitOnSessionCloseStrategy                = true;
                    ExitOnSessionCloseSeconds                    = 30;
                    IsFillLimitOnTouch                            = true;
                    MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                    OrderFillResolution                            = OrderFillResolution.High;
                    OrderFillResolutionType                        = BarsPeriodType.Minute;
                    OrderFillResolutionValue                    = 2;
                    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;
                    LinRegres                    = 14;
                    VMARes                        = 14;
                }
                else if (State == State.Configure)
                {
                }
                else if (State == State.DataLoaded)
                {                
                    LinReg1                = LinReg(Close, Convert.ToInt32(LinRegres));
                    VWMA1                = VWMA(Close, Convert.ToInt32(VMARes));
                }
            }
    
            protected override void OnBarUpdate()
            {
                if (BarsInProgress != 0)
                    return;
    
                if (CurrentBars[0] < 1)
                    return;
    
                 // Set 1
                if (CrossAbove(LinReg1, VWMA1, 1))
                {
                    EnterLong(Convert.ToInt32(DefaultQuantity), AtmStrategy);
                }
    
                 // Set 2
                if (CrossBelow(LinReg1, VWMA1, 1))
                {
                    EnterShort(Convert.ToInt32(DefaultQuantity), AtmStrategy);
                }
    
            }
    
            #region Properties
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="LinRegres", Order=1, GroupName="Parameters")]
            public int LinRegres
            { get; set; }
    
            [NinjaScriptProperty]
            [Range(1, int.MaxValue)]
            [Display(Name="VMARes", Order=2, GroupName="Parameters")]
            public int VMARes
            { get; set; }
    
            [TypeConverter(typeof(FriendlyAtmConverter))] // Converts the found ATM template file names to string values
            [PropertyEditor("NinjaTrader.Gui.Tools.StringStandardValuesEditorKey")] // Create the combo box on the property grid
            [Display(Name = "Atm Strategy", Order = 3, GroupName = "AtmStrategy")]
            public string AtmStrategy
            { get; set; }
    
            #endregion
    
        }
    }​
    Attached Files

    #2
    Also, there's another quirk: Whenever I kick off the strategy, it seems to assume I'm already in a trade. This is puzzling, especially since I've set it to "StartBehavior.WaitUntilFlat", but it's like the setting isn't even being acknowledged.

    Comment


      #3
      I took the ATM Strategy code off and when I run the strategy on my sim account (live market) it still starts on its own and displays the history. I don't care for the history, I've never seen this before. I just want it to start when I click Enable.
      Attached Files

      Comment


        #4
        Hello zayone,

        I would suggest looking at the SampleATMStrategy that comes with NinjaTrader if you want to submit atms from a strategy.

        We cannot assist with generated code from chatgpt, that tool does not produce valid NinjaScript so I would not suggest using that tool. Because the code you provided has a lot of unnecessary code and is not logically correct I would suggest to delete the file you had generated and start over from scratch. I have included a disclaimer about that below.



        From our experience at this time, ChatGpt is not adequate to generate valid compilable NinjaScripts that function as the user has intentioned. We often find that the generated code will call non-existent properties and methods, use improper classes or inheritance, and may have incorrect logic. We highly encourage that you create a new NinjaScript yourself using the NinjaScript Editor.

        While It would not be within our support model to correct these scripts at user request, we would be happy to provide insight for any direct specific inquiries you may have if you would like to create this script yourself. Our support is able to assist with finding resources in our help guide as well as simple examples.

        You can also contact a professional NinjaScript Consultant who would be eager to create or modify this script at your request or assist you with your script. The NinjaTrader Ecosystem has affiliate contacts who provide educational as well as consulting services. Please let me know if you would like a member of the ecosystem team to contact you with resources.

        Comment


          #5
          Okay, So I removed all the ATM strategy codes and have the original code. I do agree with you on not using GPT since that bot is annoying. I uploaded the file as well. One thing I can't wrap my head around is the fact when I enable the Strategy, it thinks I'm in a trade now. Is this because of the "Load data based on".

          Code:
          //This namespace holds Strategies in this folder and is required. Do not change it.
          namespace NinjaTrader.NinjaScript.Strategies
          {
              public class Strategy1 : Strategy
              {
                  private LinReg LinReg1;
                  private VWMA VWMA1;
          
                  protected override void OnStateChange()
                  {
                      if (State == State.SetDefaults)
                      {
                          Description                                    = @"Enter the description for your new custom Strategy here.";
                          Name                                        = "Strategy1";
                          Calculate                                    = Calculate.OnBarClose;
                          EntriesPerDirection                            = 1;
                          EntryHandling                                = EntryHandling.AllEntries;
                          IsExitOnSessionCloseStrategy                = true;
                          ExitOnSessionCloseSeconds                    = 30;
                          IsFillLimitOnTouch                            = false;
                          MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                          OrderFillResolution                            = OrderFillResolution.High;
                          OrderFillResolutionType                        = BarsPeriodType.Minute;
                          OrderFillResolutionValue                    = 2;
                          Slippage                                    = 0;
                          StartBehavior                                = StartBehavior.WaitUntilFlatSynchronizeAccount;
                          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;
                          LinRegres                    = 14;
                          VMARes                        = 14;
                      }
                      else if (State == State.Configure)
                      {
                      }
                      else if (State == State.DataLoaded)
                      {                
                          LinReg1                = LinReg(Close, Convert.ToInt32(LinRegres));
                          VWMA1                = VWMA(Close, Convert.ToInt32(VMARes));
                      }
                  }
          
                  protected override void OnBarUpdate()
                  {
                      if (BarsInProgress != 0)
                          return;
          
                      if (CurrentBars[0] < 1)
                          return;
          
                       // Set 1
                      if (CrossAbove(LinReg1, VWMA1, 1))
                      {
                          Print("Attempting to place a long limit order.");
                          EnterLong(Convert.ToInt32(DefaultQuantity));
                          //EnterLong(Convert.ToInt32(DefaultQuantity), AtmStrategy);
                      }
          
                       // Set 2
                      if (CrossBelow(LinReg1, VWMA1, 1))
                      {
                          Print("Attempting to place a short limit order.");
                          EnterShort(Convert.ToInt32(DefaultQuantity));
                          //EnterShort(Convert.ToInt32(DefaultQuantity), AtmStrategy);
                      }
          
                  }
          
                  #region Properties
                  [NinjaScriptProperty]
                  [Range(1, int.MaxValue)]
                  [Display(Name="LinRegres", Order=1, GroupName="Parameters")]
                  public int LinRegres
                  { get; set; }
          
                  [NinjaScriptProperty]
                  [Range(1, int.MaxValue)]
                  [Display(Name="VMARes", Order=2, GroupName="Parameters")]
                  public int VMARes
                  { get; set; }
          
          
                  #endregion
          
              }
          }​
          Attached Files

          Comment


            #6
            Hello zayone,

            When you enable a strategy it starts processing from bar 0 in the dataset and does a historical backtest. Once that finishes it will start working in realtime. If the strategy enters a position historically but does not exit that position you will see the strategy as yellow color in the control center. That means its waiting for your exit to happen before working in Realtime. That is the default start behavior for a strategy.

            If you don't want to place trades historically and just have it work in Realtime you can add a condition checking the state:
            Code:
            protected override void OnBarUpdate()
            {
            if (BarsInProgress != 0)
            return;
            
            if (CurrentBars[0] < 1)
            return;
            ​
            if(State == State.Historical)
            return;
            You can also wait for the opposite cross condition to become true which would close the position by means of a reversal.





            Comment


              #7
              Thank you, that seemed to work. I looked at the ATM Templet and I incorporated it in the code. The only change I did was I named 'AtmStrategyTemplate' to Scalp as that is the only ATM I have created. Now when I run the test. No trades are going through. I have no errors in the code.

              Code:
              //This namespace holds Strategies in this folder and is required. Do not change it.
              namespace NinjaTrader.NinjaScript.Strategies
              {
                  public class Strategy1 : Strategy
                  {
                      private LinReg LinReg1;
                      private VWMA VWMA1;
              
                      private string atmStrategyId = string.Empty;
                      private string orderId = string.Empty;
                      private bool isAtmStrategyCreated = false;
              
                      protected override void OnStateChange()
                      {
                          if (State == State.SetDefaults)
                          {
                              Description                                    = @"Enter the description for your new custom Strategy here.";
                              Name                                        = "Strategy1";
                              Calculate                                    = Calculate.OnBarClose;
                              EntriesPerDirection                            = 1;
                              EntryHandling                                = EntryHandling.AllEntries;
                              IsExitOnSessionCloseStrategy                = true;
                              ExitOnSessionCloseSeconds                    = 30;
                              IsFillLimitOnTouch                            = false;
                              MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                              OrderFillResolution                            = OrderFillResolution.High;
                              OrderFillResolutionType                        = BarsPeriodType.Minute;
                              OrderFillResolutionValue                    = 2;
                              Slippage                                    = 0;
                              StartBehavior                                = StartBehavior.WaitUntilFlatSynchronizeAccount;
                              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;
                              LinRegres                    = 14;
                              VMARes                        = 14;
                          }
                          else if (State == State.Configure)
                          {
                          }
                          else if (State == State.DataLoaded)
                          {                
                              LinReg1                = LinReg(Close, Convert.ToInt32(LinRegres));
                              VWMA1                = VWMA(Close, Convert.ToInt32(VMARes));
                          }
                      }
              
                      protected override void OnBarUpdate()
                      {
                          if (BarsInProgress != 0) return;
                          if (CurrentBars[0] < 1) return;
                          if(State == State.Historical) return;
              
                          // Submits an entry limit order at the current low price to initiate an ATM Strategy if both order id and strategy id are in a reset state
                          // **** YOU MUST HAVE AN ATM STRATEGY TEMPLATE NAMED 'AtmStrategyTemplate' CREATED IN NINJATRADER (SUPERDOM FOR EXAMPLE) FOR THIS TO WORK ****
                          if (orderId.Length == 0 && atmStrategyId.Length == 0 && Close[0] > Open[0])
                          {
                              isAtmStrategyCreated = true;  // reset atm strategy created check to false
                              atmStrategyId = GetAtmStrategyUniqueId();
                              orderId = GetAtmStrategyUniqueId();
                              AtmStrategyCreate(OrderAction.Buy, OrderType.Limit, Low[0], 0, TimeInForce.Day, orderId, "Scalp", atmStrategyId, (atmCallbackErrorCode, atmCallBackId) => {
                                  //check that the atm strategy create did not result in error, and that the requested atm strategy matches the id in callback
                                  if (atmCallbackErrorCode == ErrorCode.NoError && atmCallBackId == atmStrategyId)
                                      isAtmStrategyCreated = false;
                              });
                          }
              
                          // Check that atm strategy was created before checking other properties
                          if (!isAtmStrategyCreated)
                              return;
              
                          // Check for a pending entry order
                          if (orderId.Length > 0)
                          {
                              string[] status = GetAtmStrategyEntryOrderStatus(orderId);
              
                              // If the status call can't find the order specified, the return array length will be zero otherwise it will hold elements
                              if (status.GetLength(0) > 0)
                              {
                                  // Print out some information about the order to the output window
                                  Print("The entry order average fill price is: " + status[0]);
                                  Print("The entry order filled amount is: " + status[1]);
                                  Print("The entry order order state is: " + status[2]);
              
                                  // If the order state is terminal, reset the order id value
                                  if (status[2] == "Filled" || status[2] == "Cancelled" || status[2] == "Rejected")
                                      orderId = string.Empty;
                              }
                          } // If the strategy has terminated reset the strategy id
                          else if (atmStrategyId.Length > 0 && GetAtmStrategyMarketPosition(atmStrategyId) == Cbi.MarketPosition.Flat)
                              atmStrategyId = string.Empty;
              
                          if (atmStrategyId.Length > 0)
                          {
                              // You can change the stop price
                              if (GetAtmStrategyMarketPosition(atmStrategyId) != MarketPosition.Flat)
                                  AtmStrategyChangeStopTarget(0, Low[0] - 3 * TickSize, "STOP1", atmStrategyId);
              
                              // Print some information about the strategy to the output window, please note you access the ATM strategy specific position object here
                              // the ATM would run self contained and would not have an impact on your NinjaScript strategy position and PnL
                              Print("The current ATM Strategy market position is: " + GetAtmStrategyMarketPosition(atmStrategyId));
                              Print("The current ATM Strategy position quantity is: " + GetAtmStrategyPositionQuantity(atmStrategyId));
                              Print("The current ATM Strategy average price is: " + GetAtmStrategyPositionAveragePrice(atmStrategyId));
                              Print("The current ATM Strategy Unrealized PnL is: " + GetAtmStrategyUnrealizedProfitLoss(atmStrategyId));
                          }
              
                           // Set 1
                          if (CrossAbove(LinReg1, VWMA1, 1))
                          {
                              Print("Attempting to place a long limit order.");
                              EnterLong(Convert.ToInt32(DefaultQuantity), "");
                              //EnterLong(Convert.ToInt32(DefaultQuantity), AtmStrategy);
                          }
              
                           // Set 2
                          if (CrossBelow(LinReg1, VWMA1, 1))
                          {
                              Print("Attempting to place a short limit order.");
                              EnterShort(Convert.ToInt32(DefaultQuantity), "");
                              //EnterShort(Convert.ToInt32(DefaultQuantity), AtmStrategy);
                          }
              
                      }​

              Comment


                #8
                Hello zayone,

                Are you testing in realtime and do you see the ATM entry being submitted in the control center orders tab?

                Comment


                  #9
                  I looks like when I tested it out live now, It did a Limit Order. Interestingly, while I was writing this, another limit order was triggered. Why would it do that? I would only want 1 working order at a time. Not really a laddering kind of order. I would think it would do a market buy when the conditions are met. I did not change any of the code given.
                  Attached Files

                  Comment


                    #10
                    Code:
                    isAtmStrategyCreated = true;  // reset atm strategy created check to false
                                    atmStrategyId = GetAtmStrategyUniqueId();
                                    orderId = GetAtmStrategyUniqueId();
                                    AtmStrategyCreate(OrderAction.Buy, OrderType.Limit, Low[0], 0, TimeInForce.Day, orderId, "Scalp", atmStrategyId, (atmCallbackErrorCode, atmCallBackId) => {
                                        //check that the atm strategy create did not result in error, and that the requested atm strategy matches the id in callback
                                        if (atmCallbackErrorCode == ErrorCode.NoError && atmCallBackId == atmStrategyId)
                                            isAtmStrategyCreated = false;​


                    Looks like in the code it's doing a OrderType.Limit - Can I change that to OrderType.Market?

                    Still trying to run this on the Strategy Analyzer but no results when the ATM code it applied.

                    Comment


                      #11
                      I'm looking at the Strategy and it's creating the order with one of "my" created ATM strategies?
                      Attached Files

                      Comment


                        #12
                        Hello zayone,

                        It looks like in the file that you provided you are using both the managed approach and ATMs which are not able to be combined. Using orders like EnterLong while also using an atm is not correct, you would need to remove those parts of the script so your script matches the SampleATMCrrossOver strategy.

                        You can change the entry order type, you would do that by changing the options being used with AtmStrategyCreate.

                        In the image it does appear that your ATM is being used, the strategy listed matches the name you used in AtmStrategyCreate.

                        Comment


                          #13
                          I find it very odd that you cant use an ATM strategy on a back test, is the back testing on Strategy Analyser or Playback? If I can't use an ATM strategy, can I write out the code in the strategy like I have it in my atm strategy to test out?

                          You can create an automated strategy that generates a trade signal that executes a NinjaTrader ATM Strategy.
                          • ATM Strategies operate in real-time only and will not execute on historical data thus they can't be backtested
                          • Executions resulting from an ATM Strategy that is created from within a NinjaScript automated strategy will not plot on a chart during real-time operation
                          • Strategy set up parameters such as EntriesPerDirection, EntryHandling, IsExitOnSessionCloseStrategy do not apply when calling the AtmStrategyCreate() method
                          • Executions from ATM Strategies will not have an impact on the hosting NinjaScript strategy position and PnL - the NinjaScript strategy hands off the execution aspects to the ATM, thus no monitoring via the regular NinjaScript strategy
                          methods will take place (also applies to strategy performance tracking)
                          • ATM Strategy stop orders can either be StopMarket or StopLimit orders, depending on which type is defined in the ATM Strategy Template (Advanced Options) you call in the AtmStrategyCreate() method in your NinjaScript strategy. To
                          make the distinction clear which is used, following a naming convention for the template name is highly suggested (i.e. AtmStrategyTemplate_STPLMT)
                          • A general sample for calling ATM's is preinstalled with NinjaTrader under the 'SampleATMStrategy' script - for a script showing how to implement reversal type setups, please see this link to our online resources.​

                          Comment


                            #14
                            Now that I added the code of my own ATM strategy I cant seem to be able to Optimize the values like I can for LinRegres and VMARes - I know I'm missing something.

                            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 Strategy1 : Strategy
                                {
                                    private LinReg LinReg1;
                                    private VWMA VWMA1;
                                    private int profitTrigger;
                                    private int plusTicks;
                                    private int stopLossTicks;
                                    private int takeProfitTicks;
                            
                            
                                    protected override void OnStateChange()
                                    {
                                        if (State == State.SetDefaults)
                                        {
                                            Description                                    = @"Use the Renko Chart, 10,10,10";
                                            Name                                        = "Renko Strategy";
                                            Calculate                                    = Calculate.OnBarClose;
                                            EntriesPerDirection                            = 1;
                                            EntryHandling                                = EntryHandling.AllEntries;
                                            IsExitOnSessionCloseStrategy                = true;
                                            ExitOnSessionCloseSeconds                    = 30;
                                            IsFillLimitOnTouch                            = false;
                                            MaximumBarsLookBack                            = MaximumBarsLookBack.TwoHundredFiftySix;
                                            OrderFillResolution                            = OrderFillResolution.High;
                                            OrderFillResolutionType                        = BarsPeriodType.Minute;
                                            OrderFillResolutionValue                    = 1;
                                            Slippage                                    = 0;
                                            StartBehavior                                = StartBehavior.WaitUntilFlat;
                                            TimeInForce                                    = TimeInForce.Gtc;
                                            TraceOrders                                    = false;
                                            RealtimeErrorHandling                        = RealtimeErrorHandling.StopCancelClose;
                                            StopTargetHandling                            = StopTargetHandling.PerEntryExecution;
                                            BarsRequiredToTrade                            = 20;
                                            IsInstantiatedOnEachOptimizationIteration    = true;
                                            LinRegres                                    = 14;
                                            VMARes                                        = 14;
                                            ProfitTrigger                                 = 20;
                                            PlusTicks                                     = -1;
                                            StopLossTicks                                 = 30;
                                            TakeProfitTicks                             = 40;
                                        }
                                        else if (State == State.Configure)
                                        {
                                            //profitTrigger = ProfitTrigger;
                                            //plusTicks = PlusTicks;
                                            //stopLossTicks = StopLossTicks;
                                            //takeProfitTicks = TakeProfitTicks;
                                        }
                                        else if (State == State.DataLoaded)
                                        {                
                                            LinReg1                = LinReg(Close, Convert.ToInt32(LinRegres));
                                            VWMA1                = VWMA(Close, Convert.ToInt32(VMARes));
                                        }
                                    }
                            
                                    protected override void OnBarUpdate()
                                    {
                                        if (BarsInProgress != 0)
                                            return;
                            
                                        if (CurrentBars[0] < 1)
                                            return;
                            
                                        //if(State == State.Historical)
                                            //return;
                            
                                         // Set 1
                                        if (CrossAbove(LinReg1, VWMA1, 1))
                                        {
                                            EnterLong(Convert.ToInt32(DefaultQuantity), "LongEntry");
                                            SetStopLoss("LongEntry", CalculationMode.Ticks, stopLossTicks, false);
                                            SetProfitTarget("LongEntry", CalculationMode.Ticks, takeProfitTicks);
                                        }
                            
                                         // Set 2
                                        if (CrossBelow(LinReg1, VWMA1, 1))
                                        {
                                            EnterShort(Convert.ToInt32(DefaultQuantity), "ShortEntry");
                                            SetStopLoss("ShortEntry", CalculationMode.Ticks, stopLossTicks, false);
                                            SetProfitTarget("ShortEntry", CalculationMode.Ticks, takeProfitTicks);
                                        }
                            
                                         // For Long Positions
                                        if (Position.MarketPosition == MarketPosition.Long)
                                        {
                                            // If the trade has moved in favor by profitTrigger ticks
                                            if (Close[0] - Position.AveragePrice >= TickSize * profitTrigger)
                                            {
                                                // Adjust the stop loss to entry price plus the plusTicks value
                                                SetStopLoss(CalculationMode.Price, Position.AveragePrice + (TickSize * plusTicks));
                                            }
                                        }
                            
                                        // For Short Positions
                                        if (Position.MarketPosition == MarketPosition.Short)
                                        {
                                            // If the trade has moved in favor by profitTrigger ticks
                                            if (Position.AveragePrice - Close[0] >= TickSize * profitTrigger)
                                            {
                                                // Adjust the stop loss to entry price minus the plusTicks value
                                                SetStopLoss(CalculationMode.Price, Position.AveragePrice - (TickSize * plusTicks));
                                            }
                            
                                        }
                                    }
                                    #region Properties
                                    [NinjaScriptProperty]
                                    [Range(1, int.MaxValue)]
                                    [Display(Name="LinRegres", Order=1, GroupName="Parameters")]
                                    public int LinRegres
                                    { get; set; }
                            
                                    [NinjaScriptProperty]
                                    [Range(1, int.MaxValue)]
                                    [Display(Name="VMARes", Order=2, GroupName="Parameters")]
                                    public int VMARes
                                    { get; set; }
                            
                                    [NinjaScriptProperty]
                                    [Range(1, int.MaxValue)]
                                    [Display(Name="Profit Trigger", Order=3, GroupName="Parameters")]
                                    public int ProfitTrigger
                                    { get; set; }
                            
                                    [NinjaScriptProperty]
                                    [Range(-50, 0)]
                                    [Display(Name="Plus Ticks", Order=4, GroupName="Parameters")]
                                    public int PlusTicks
                                    { get; set; }
                            
                                    [NinjaScriptProperty]
                                    [Range(1, int.MaxValue)]
                                    [Display(Name="Stop Loss Ticks", Order=5, GroupName="Parameters")]
                                    public int StopLossTicks
                                    { get; set; }
                            
                                    [NinjaScriptProperty]
                                    [Range(1, int.MaxValue)]
                                    [Display(Name="Take Profit Ticks", Order=6, GroupName="Parameters")]
                                    public int TakeProfitTicks
                                    { get; set; }
                            
                                    #endregion
                            
                                }
                            }
                            ​
                            Attached Files

                            Comment


                              #15
                              Now it seems to work. Strange
                              Attached Files

                              Comment

                              Latest Posts

                              Collapse

                              Topics Statistics Last Post
                              Started by NullPointStrategies, Yesterday, 05:17 AM
                              0 responses
                              66 views
                              0 likes
                              Last Post NullPointStrategies  
                              Started by argusthome, 03-08-2026, 10:06 AM
                              0 responses
                              141 views
                              0 likes
                              Last Post argusthome  
                              Started by NabilKhattabi, 03-06-2026, 11:18 AM
                              0 responses
                              75 views
                              0 likes
                              Last Post NabilKhattabi  
                              Started by Deep42, 03-06-2026, 12:28 AM
                              0 responses
                              46 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