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

Error CS0115 in a protected override void OnExecution() for CalculateAndSetLotSize

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

    Error CS0115 in a protected override void OnExecution() for CalculateAndSetLotSize

    hello, cant solve this issue

    the code
    namespace NinjaTrader.NinjaScript.Strategies
    {
    public class My_D_S_15min_210224 : Strategy
    {


    private EMA EMA_Fast;
    private EMA EMA_Slow;
    private SMA SMA;
    private SlopeEnhancedOp SlopeEnhancedOp_Long;
    private SlopeEnhancedOp SlopeEnhancedOp_Short;

    private ParabolicSAR ParabolicSAR1;

    private DifferencesIndicator DifferencesIndicator1;

    private bool okToGoShort = true;
    private bool okToGoLong = true;

    private int currentTime;

    private double CurrentTrail_Stop = 0.0;

    private double GetDiff_EMASlow_SMA(double price1, double price2)
    {
    double difference = price1 - price2;
    return Math.Abs(difference);
    }

    private double GetDiff_EMASlow_EMAFast(double price3, double price4)
    {
    double difference = price3 - price4;
    return Math.Abs(difference);
    }

    private double GetDiff_EMASlow_Close(double price5, double price6)
    {
    double difference = price5 - price6;
    return Math.Abs(difference);
    }

    private double GetDiff_SMA_Close(double price7, double price8)
    {
    double difference = price7 - price8;
    return Math.Abs(difference);
    }

    private double GetDiff_EMAFast_Close(double price9, double price10)
    {
    double difference = price9 - price10;
    return Math.Abs(difference);
    }

    // Helper method to convert DateTime to HHmm format
    private int ToHHmm(DateTime time)
    {
    return time.Hour * 100 + time.Minute;
    }

    // Helper method to check if a given time falls within a time period
    private bool IsWithinTimePeriod(int time, int startTime, int endTime)
    {
    return time >= startTime && time <= endTime;
    }

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"10.06.2023, 12.06.2023 Condition group added, EMA_Fast bar before direction added";
    Name = "My_D_S_SP500_15min_210224";
    Calculate = Calculate.OnPriceChange;
    EntriesPerDirection = 1;
    EntryHandling = EntryHandling.AllEntries;
    IsExitOnSessionCloseStrategy = false;
    ExitOnSessionCloseSeconds = 30;
    IsFillLimitOnTouch = false;
    MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
    OrderFillResolution = OrderFillResolution.Standard;
    Slippage = 0;
    StartBehavior = StartBehavior.WaitUntilFlat;
    TimeInForce = TimeInForce.Gtc;
    TraceOrders = false;
    RealtimeErrorHandling = RealtimeErrorHandling.IgnoreAllErrors; // Check alternative handling !!!!
    StopTargetHandling = StopTargetHandling.PerEntryExecution;
    BarsRequiredToTrade = 20;
    IsInstantiatedOnEachOptimizationIteration = true;

    LONG_Distance_EMA_Slow_EMA_Fast = 8;
    LONG_Distance_EMA_Slow_SMA = 8;
    LONG_Distance_EMA_Slow_Close = 10;
    LONG_Distance_EMA_Fast_Close = 9;
    LONG_Distance_SMA_Close = 5;


    SHORT_Distance_EMA_Slow_EMA_Fast = 10;
    SHORT_Distance_EMA_Slow_SMA = 10;
    SHORT_Distance_EMA_Slow_Close = 12;
    SHORT_Distance_EMA_Fast_Close = 9;
    SHORT_Distance_SMA_Close = 10;


    Init_Stop_long = 35;
    Init_Stop_short = 35;
    Bars_Since_Exit = 1;
    Bars_Since_Entry = 3;
    InitOrderQuant = 2;
    Stop_Profit_Long = 6500;
    Stop_Profit_Short = 7000;
    EMA_Slow_Period = 50;
    EMA_Fast_Period = 9;
    SMA_Period = 40;

    ParabAccelaration = 0.015d;
    ParabAccelMax = 0.15d;
    ParabAccelStep = 0.015d;

    Min_Slope_Long = 0.75d;
    Min_Slope_Short = 0.75d;


    }


    else if (State == State.Configure)
    {
    }

    else if (State == State.DataLoaded)
    {

    EMA_Fast = EMA(Close, EMA_Fast_Period);
    EMA_Slow = EMA(Close, EMA_Slow_Period);
    SMA = SMA(Close, SMA_Period);

    SlopeEnhancedOp_Long = SlopeEnhancedOp(Close, 3, 56, 3, false, InputSeriesType.EMA, NormType.None, Brushes.Green, Brushes.Red);
    SlopeEnhancedOp_Short = SlopeEnhancedOp(Close, 3, 56, 3, false, InputSeriesType.EMA, NormType.None, Brushes.Green, Brushes.Red);

    var DifferencesIndicator1 = DifferencesIndicator();

    // define color MA's
    EMA_Fast.Plots[0].Brush = Brushes.Goldenrod;
    EMA_Fast.Plots[0].Width = 1;
    EMA_Slow.Plots[0].Brush = Brushes.Purple;
    EMA_Slow.Plots[0].Width = 2;
    SMA.Plots[0].Brush = Brushes.Red;
    SMA.Plots[0].Width = 2;

    ParabolicSAR1 = ParabolicSAR(Close, ParabAccelaration, ParabAccelMax, ParabAccelStep);
    ParabolicSAR1.Plots[0].Brush = Brushes.Snow;
    ParabolicSAR1.Plots[0].Width = 1;

    AddChartIndicator(EMA_Fast);
    AddChartIndicator(EMA_Slow);
    AddChartIndicator(SMA);
    AddChartIndicator(ParabolicSAR1);
    AddChartIndicator(SlopeEnhancedOp_Short);
    AddChartIndicator(SlopeEnhancedOp_Long);
    AddChartIndicator(DifferencesIndicator1);
    }
    }

    protected override void OnBarUpdate()
    {


    double previousTrail_Stop = 0.0;

    if (BarsInProgress != 0)
    return;

    if (CurrentBars[0] < 75)
    return;

    bool isFlat = Position.MarketPosition == MarketPosition.Flat;

    if (Bars.IsFirstBarOfSession && isFlat)
    {
    CalculateAndSetLotSize();
    }

    int currentTime = ToHHmm(Time[0]);

    bool isTradingTime = IsWithinTimePeriod(currentTime, startTimePeriod1, endTimePeriod1)
    || IsWithinTimePeriod(currentTime, startTimePeriod2, endTimePeriod2);


    // check entry criteria
    if ((isFlat) && (isTradingTime))
    {

    if ( ((BarsSinceExitExecution(0, "", 0) > Bars_Since_Exit) || (BarsSinceExitExecution(0, "", 0) == -1) ))



    {
    if (okToGoLong) // OK to test long entry
    {



    if ( (SlopeEnhancedOp_Long[0] > Min_Slope_Long)

    && ( (GetDiff_EMASlow_SMA (EMA_Slow[0], SMA[0]) <= LONG_Distance_EMA_Slow_SMA)
    && (GetDiff_EMASlow_EMAFast(EMA_Slow[0], EMA_Fast[0]) <= LONG_Distance_EMA_Slow_EMA_Fast)
    && (GetDiff_EMASlow_Close (EMA_Slow[0], Close[0]) <= LONG_Distance_EMA_Slow_Close)
    && (GetDiff_EMAFast_Close (EMA_Fast[0], Close[0]) <= LONG_Distance_EMA_Fast_Close)
    && (GetDiff_SMA_Close (SMA[0], Close[0]) <= LONG_Distance_SMA_Close)
    )
    )

    {

    if (Close[0] >= EMA_Fast[0])
    {
    if (EMA_Fast[0] >= EMA_Slow[0] && EMA_Fast[0] >= SMA[0])
    {
    EnterLong(Convert.ToInt32(InitOrderQuant), @"LONG");
    SetStopLoss(CalculationMode.Ticks, Init_Stop_long);
    SetProfitTarget(@"LONG",CalculationMode.Currency, Stop_Profit_Long);
    }
    }
    }
    }

    if (okToGoShort) // OK to test short entry
    {



    if ( (SlopeEnhancedOp_Short[0] < -Min_Slope_Short)

    && ( (GetDiff_EMASlow_SMA (EMA_Slow[0], SMA[0]) <= SHORT_Distance_EMA_Slow_SMA)
    && (GetDiff_EMASlow_EMAFast(EMA_Slow[0], EMA_Fast[0]) <= SHORT_Distance_EMA_Slow_EMA_Fast)
    && (GetDiff_EMASlow_Close (EMA_Slow[0], Close[0]) <= SHORT_Distance_EMA_Slow_Close)
    && (GetDiff_EMAFast_Close (EMA_Fast[0], Close[0]) <= SHORT_Distance_EMA_Fast_Close)
    && (GetDiff_SMA_Close (SMA[0], Close[0]) <= SHORT_Distance_SMA_Close)
    )

    )

    {

    if (Close[0] <= EMA_Fast[0])
    {
    if (EMA_Fast[0] <= EMA_Slow[0] && EMA_Fast[0] <= SMA[0])
    {
    EnterShort(Convert.ToInt32(InitOrderQuant), @"SHORT");
    SetStopLoss(CalculationMode.Ticks, Init_Stop_short);
    SetProfitTarget(@"SHORT",CalculationMode.Currency, Stop_Profit_Short);
    }
    }
    }
    }
    }
    }
    else // if not flat manage trade
    {
    if (Position.MarketPosition == MarketPosition.Long)
    {
    // before changing the current trailing stop price, keep a copy
    previousTrail_Stop = CurrentTrail_Stop;

    if (IsFirstTickOfBar)
    {
    if (BarsSinceEntryExecution(0, "", 0) > Bars_Since_Entry)
    {
    if (ParabolicSAR1[1] < Low[1])
    {
    if (ParabolicSAR1[1] > (Position.AveragePrice - (Init_Stop_long * TickSize)) )
    {
    if (Close[0] > ParabolicSAR1[1])
    {
    CurrentTrail_Stop = ParabolicSAR1[0];
    }
    }
    }
    }
    }

    // if the CurrentTrail_Stop has changed then set the new stop loss
    if (CurrentTrail_Stop != previousTrail_Stop)
    SetStopLoss(CalculationMode.Price, CurrentTrail_Stop);


    }
    else if (Position.MarketPosition == MarketPosition.Short)
    {
    // before changing the current trailing stop price, keep a copy
    previousTrail_Stop = CurrentTrail_Stop;

    if (IsFirstTickOfBar)
    {
    if (BarsSinceEntryExecution(0, "", 0) > Bars_Since_Entry)
    {
    if (ParabolicSAR1[1] > High[1])
    {
    if (ParabolicSAR1[1] < (Position.AveragePrice + (Init_Stop_short * TickSize)) )
    {
    if (Close[0] < ParabolicSAR1[1])
    {
    CurrentTrail_Stop = ParabolicSAR1[0];
    }
    }
    }
    }
    }

    // if the CurrentTrail_Stop has changed then set the new stop loss
    if (CurrentTrail_Stop != previousTrail_Stop)
    SetStopLoss(CalculationMode.Price, CurrentTrail_Stop);
    }
    }
    }

    protected override void OnExecution(Execution execution)
    {
    if (execution.Order != null && execution.Order.OrderState == OrderState.Filled)
    {
    // Check if manual position management is enabled
    if (ManualPositionManagement) return;

    // Your logic here, for example:
    // Recalculate lot size or other actions after a trade is executed
    if (Position.Quantity == 0) // This checks if your position is flat after execution
    {
    CalculateAndSetLotSize();
    }
    }
    }



    private void CalculateAndSetLotSize()
    {
    if (Position.MarketPosition != MarketPosition.Flat) return;

    double accountBalance = Account.Get(AccountItem.CashValue, Currency.UsDollar);

    double maxTradeAmount = accountBalance * (MaxAccountUtilizationPercent / 100.0);

    int newLotSize = (int)(maxTradeAmount / MarginSize);

    InitOrderQuant = Math.Max(newLotSize, 1); // Assuming InitOrderQuant is used for trade volume
    }​

    #2
    Hello Triple_M,

    There is no method named OnExecution which is the reason for the error, the method is OnExecutionUpdate and needs to be defined like the following:

    Code:
    protected override void OnExecutionUpdate(Execution execution, string executionId, double price, int quantity, MarketPosition marketPosition, string orderId, DateTime time)
    {
    
    
    }​
    JesseNinjaTrader Customer Service

    Comment


      #3
      Yes, i know, ..... as heard this was an old version or whatever, btw. an ChatGPT proposal to solve the issue :-) but dont works, yes, BUT !!! with OnExecutionUpdate, i got the same error "no suitable method found to override"

      I attach the *.cs file
      Attached Files

      Comment


        #4
        Hello Triple_M,

        The code you provided is still not valid, you need to define the method exactly as shown in the help guide for OnExecutionUpdate. In regard to chatgpt, that cannot generate valid NinjaScript code so we suggest to avoid using that as it will provide code that cannot compile. I have included a link to the help guide for OnExecutionUpdate and also a disclaimer about chatgpt below.





        From our experience at this time, ChatGpt and other AI models are not quite 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, and use the NinjaTrader help guide for examples of valid code.

        Below is a link to a forum thread that discusses ChatGpt and it's limitations.
        I'm not a pro coder, and I only learned C# out of necessity due to Ninjatrader. I have actually gained some new, recent knowledge about C# from ChatGPT, and it's been very forthcoming in providing sample code that works. Especially if it involves something off the beaten NT path and yet simple for many but perhaps not to me (a


        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 list of affiliate consultants who would be happy to create this script or any others at your request or provide one on one educational services.




        JesseNinjaTrader Customer Service

        Comment


          #5
          Dear Jesse,

          thank you so far. I want to mention that I dont agree regarding Chat GPT. I think it can be important for anybody else who is reading this :-) That ChatGPT can not provide a complete code is right, but it provides many code sequences what are very well compiling. No question you always have to know what you are doin. But in general, Chat GPT offers the possibiltiy to learn it, quite fast, much faster then any other possibilty. It may not replace it, to learn C# properly, but my problem, limited time, may be many others have the same problem. And to develop a code together with ChatGPT is much faster. You can describe what you want and it is delivered, within "seconds". With every answer, i get a better understanding how things are coded. You and the whole team is very helpful, but you always have to wait for an answer, even your response time is really good. But as soon as it gets some more tricky, you and the NT Team does refer to the helpguides. That helps then only if you know about programming. I get my tasks faster and better and thats a big advantage i think so. And even what I heard from really professional programmers, that even they let write ChatGPT big sequences to save time. So to anybody out there, "yes" go for it :-) how ever you get it done, finally it must be profitable.
          Regards
          Peter

          EDIT:
          Whats also very interesting, once you copy the NT8 reference and paste it into Chat GPT, it was able to solve the issue and provide a working and even compilable code. That does mean, it learns quite fast.
          Last edited by Triple_M; 03-08-2024, 09:19 AM.

          Comment

          Latest Posts

          Collapse

          Topics Statistics Last Post
          Started by futtrader, 04-21-2024, 01:50 AM
          5 responses
          56 views
          0 likes
          Last Post NinjaTrader_Eduardo  
          Started by PeakTry, Today, 10:49 AM
          0 responses
          2 views
          0 likes
          Last Post PeakTry
          by PeakTry
           
          Started by llanqui, Today, 10:32 AM
          0 responses
          5 views
          0 likes
          Last Post llanqui
          by llanqui
           
          Started by StockTrader88, 03-06-2021, 08:58 AM
          45 responses
          3,992 views
          3 likes
          Last Post johntraderuser2  
          Started by TAJTrades, Today, 09:46 AM
          0 responses
          8 views
          0 likes
          Last Post TAJTrades  
          Working...
          X