Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Number of contracts is offset by 1 trade

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

    Number of contracts is offset by 1 trade

    Hello,

    I've coded a simple EMA cross strategy.
    In this strategy, I tried to code the number of contracts to trade based on 1% of the account.

    It seems to work but the only problem is that the number of contract for a given trade is actually applied to the next trade.
    I guess it's a problem of code logic and architecture but I'm not sure how to re-arrange this.

    Below is the code.

    Thanks for your help!



    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Strategy here.";
    Name = "FirstStrategyunlocked";
    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;
    CrossEMA = 6;
    RR_Reward = 5;
    StopLossTicks = 200;
    ProfitTargetTicks = 1000;

    }
    else if (State == State.Configure)
    {
    /* Safety SL, incrementend at entry */
    SetStopLoss(CalculationMode.Ticks, StopLossTicks);

    }
    else if (State == State.DataLoaded)
    {
    /* Indicators */
    EMA1 = EMA(Close, CrossEMA);

    /* Visuals */
    EMA1.Plots[0].Brush = Brushes.Goldenrod;
    AddChartIndicator(EMA1);

    }
    }

    protected override void OnBarUpdate()
    {
    if (BarsInProgress != 0)
    return;

    bool market_open = ToTime(Time[0]) >= 000000 && ToTime(Time[0]) <= 230059;
    bool cross_above = CrossAbove(Close, EMA1, 1);
    bool cross_below = CrossBelow(Close, EMA1, 1);
    Long = "Yes";
    Short = "Yes";






    if (Position.MarketPosition == MarketPosition.Flat)
    {

    TradeSet = "No";
    SetProfitTarget(CalculationMode.Ticks, ProfitTargetTicks);
    SetStopLoss(CalculationMode.Ticks, StopLossTicks);
    }


    if (TradeSet == "No")
    {
    if (Position.MarketPosition == MarketPosition.Long)
    {
    entryPrice = Position.AveragePrice;// Assuming entry price is one tick above the high
    stopPrice = Low[1];
    targetPrice = Position.AveragePrice + (Position.AveragePrice - stopPrice) * RR_Reward;
    Print(ToTime(Time[0]));
    Print("Entry Price:"+ entryPrice);
    Print("stopPrice:"+ stopPrice);
    Print("targetPrice:"+ targetPrice);
    TradeSet = "Yes";
    SetProfitTarget(CalculationMode.Price, targetPrice);
    SetStopLoss(CalculationMode.Price, stopPrice);
    }

    if (Position.MarketPosition == MarketPosition.Short)
    {
    entryPrice = Position.AveragePrice;// Assuming entry price is one tick above the high
    stopPrice = High[1];
    targetPrice = Position.AveragePrice + (Position.AveragePrice - stopPrice) * RR_Reward;
    Print(ToTime(Time[0]));
    Print("Entry Price:"+ entryPrice);
    Print("stopPrice:"+ stopPrice);
    Print("targetPrice:"+ targetPrice);
    TradeSet = "Yes";
    SetProfitTarget(CalculationMode.Price, targetPrice);
    SetStopLoss(CalculationMode.Price, stopPrice);
    }



    }

    // Calculate position size based on account value (1% of cash value)
    double accountSize = Account.Get(AccountItem.CashValue, Currency.UsDollar);
    double myPositionSize = accountSize * 0.01;

    // Print the calculated account size and position size
    Print("Account Size (USD): " + accountSize.ToString("F2"));
    Print("Position Size (USD): " + myPositionSize.ToString("F2"));

    // Define tick value (replace tickValue with the actual tick value of your instrument)
    double tickValue = 5;
    // Print the tick value
    Print("Tick Value: " + tickValue.ToString("F2"));

    double TicksSL = Math.Abs(entryPrice - stopPrice) / TickSize;

    // Print the calculated number of ticks for stop loss
    Print("Ticks for Stop Loss: " + TicksSL.ToString("F2"));

    int contractsToTrade = (int)Math.Floor(myPositionSize / tickValue / TicksSL); // Convert to integer number of contracts

    // Print the calculated number of contracts to trade
    Print("Contracts to Trade: " + contractsToTrade.ToString());


    if (market_open)
    {
    if (cross_above)
    {
    if (Long == "Yes" && Position.MarketPosition == MarketPosition.Flat)
    {
    EnterLong(contractsToTrade,"Long"); //EnterLong(Convert.ToInt32(DefaultQuantity),"Long") , Convert.ToString(CurrentBar)+"LongEntry"
    Print("TRADE");
    Print(ToTime(Time[0]));

    }
    }
    else if (cross_below && Short == "Yes")
    {
    if (Position.MarketPosition == MarketPosition.Flat)
    {
    EnterShort(contractsToTrade,"Short");

    }
    }



    #2
    Hello TraderBCL,

    Thank you for your post.

    To understand why the script is behaving as it is, it is necessary to add prints to the script that print the values used for the logic of the script to understand how the script is evaluating.

    In the strategy add prints (outside of any conditions) that print the date time of the bar and all values compared in every condition that places an order.

    The prints should include the time of the bar and should print all values from all variables and all hard coded values in all conditions that must evaluate as true for this action to be triggered. It is very important to include a text label for each value and for each comparison operator in the print to understand what is being compared in the condition sets.

    Prints will appear in the NinjaScript Output window (New > NinjaScript Output window).

    Further, enable TraceOrders which will let us know if any orders are being ignored and not being submitted when the condition to place the orders is evaluating as true.

    I am happy to assist you with analyzing the output from the output window.

    Run or backtest the script and when the output from the output window appears save this by right-clicking the output window and selecting Save As... -> give the output file a name and save -> then attach the output text file to your reply.

    Below is a link to a forum post that demonstrates using informative prints to understand behavior and includes a link to a video recorded using the Strategy Builder to add prints.


    Please let me know if I may further assist with analyzing the output or if you need any assistance creating a print or enabling TraceOrders.​

    Sincerely,
    Gaby V.
    NinjaTrader Client Services

    Risk Disclosure Futures, foreign currency and options trading involves substantial risk and is not appropriate for everyone.

    This communication is sent from NinjaTrader Brokerage, a CFTC registered introducing broker (NFA #339976) providing industry leading support and technology for futures traders

    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