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

MACD Crossover Bot / Executes on Playback/Analyzer but not Live

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

    MACD Crossover Bot / Executes on Playback/Analyzer but not Live

    Hello everyone! I've been working on a MACDbot crossover for only longs and during the backtesting and optimization it worked great, but when I go live it doesn't enter the trades that it should, if it enters any.... So I ask you guys, is there something I can do to make my strategy MACD Cross Above execute in the Live enviroment?? Thank you for your time!

    Here is the code of the strategy:

    [CODE ]
    ​public class MACDbot2v2 : Strategy
    {
    private bool DayisOK;
    private double Accomulated;

    private MACD MACD1;
    private EMA EMA1;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Longs only, basic TPnSL, EMA, PnL Limits";
    Name = "MACDbot2v2";
    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;
    Start = DateTime.Parse("08:00", System.Globalization.CultureInfo.InvariantCulture) ;
    End = DateTime.Parse("16:00", System.Globalization.CultureInfo.InvariantCulture) ;
    Position1 = 1;
    Target1 = 40;
    Stop1 = -40;
    MovingAverage = 21;
    Fast = 1;
    Slow = 1;
    Smoth = 1;
    MaxLoss = -200;
    MaxProfit = 300;
    DayisOK = true;
    Accomulated = 0;
    }
    else if (State == State.Configure)
    {
    }
    else if (State == State.DataLoaded)
    {
    MACD1 = MACD(Close, 12, 26, 9);
    EMA1 = EMA(Close, Convert.ToInt32(MovingAverage));
    MACD1.Plots[0].Brush = Brushes.DarkCyan;
    MACD1.Plots[1].Brush = Brushes.Crimson;
    MACD1.Plots[2].Brush = Brushes.DodgerBlue;
    EMA1.Plots[0].Brush = Brushes.Aqua;
    AddChartIndicator(MACD1);
    AddChartIndicator(EMA1);
    }
    }

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

    if (CurrentBars[0] < 1)
    return;

    // Set 1
    if (
    (CrossAbove(MACD1.Default, MACD1.Avg, 1))
    && (Position.MarketPosition == MarketPosition.Flat)
    // EntryAfter1Bar
    && ((BarsSinceExitExecution(0, "", 0) == -1)
    || (BarsSinceExitExecution(0, "", 0) > 1))
    && (Times[0][0].TimeOfDay >= Start.TimeOfDay)
    && (Times[0][0].TimeOfDay <= End.TimeOfDay)
    && (Close[0] > EMA1[0])
    && (DayisOK == true)
    )
    {
    EnterLong(Convert.ToInt32(Position1), @"Entry1");
    }

    // Set 2
    if (
    (SystemPerformance.AllTrades.TradesPerformance.Cur rency.CumProfit - Accomulated < MaxLoss)
    || (SystemPerformance.AllTrades.TradesPerformance.Cur rency.CumProfit - Accomulated > MaxProfit)
    )
    {
    DayisOK = false;
    }

    // Set 3
    if (Position.MarketPosition == MarketPosition.Long)
    {
    ExitLongLimit(Convert.ToInt32(Position1), (Position.AveragePrice + (Target1 * TickSize)) , @"Target1", @"Entry1");
    ExitLongStopMarket(Convert.ToInt32(Position1), (Position.AveragePrice + (Stop1 * TickSize)) , @"Stop1", @"Entry1");
    }

    // Set 4
    if (Bars.IsFirstBarOfSession)
    {
    DayisOK = true;
    Accomulated = SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit;
    }

    [/CODE]

    #2
    Hello jesusjosepr,

    Thank you for your post.

    First, I would like to note, a strategy running real-time (live brokerage account, live market simulation, Playback connection etc...) will produce different results than the performance results generated during a backtest.

    Please review the help guide page on the differences on real-time vs backtest.

    https://ninjatrader.com/support/help...ime_vs_bac.htm

    When in historical data, only the Open, High, Low, and Close will be available and there will be no intra-bar data. This means actions cannot happen intra-bar, fills cannot happen intra-bar. All prices and actions come from and occur when the bar closes as this is all the information that is known.

    Because of this, OnBarUpdate will only update 'On bar close' as it does not have the intra-bar information necessary for 'On price change' or 'On each tick' and the script will not have the intra-bar information to accurately fill an order at the exact price and time.

    Calculate - https://ninjatrader.com/support/help.../calculate.htm

    Discrepancies: Real-time vs. Backtest - https://ninjatrader.com/support/help...ime_vs_bac.htm


    If the expected trade(s) are not appearing, this would indicate that the condition to place the order is not evaluating as true and the order is not being submitted, or the order is being ignored for other reasons, or the order is being cancelled.

    To understand why the script is behaving as it is, such as placing orders or not placing orders or drawing objects when expected, 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.​
    Gaby V.NinjaTrader Customer Service

    Comment


      #3
      Thank you! I will post an update after implementing the changes!

      Comment

      Latest Posts

      Collapse

      Topics Statistics Last Post
      Started by AaronKoRn, Yesterday, 09:49 PM
      0 responses
      11 views
      0 likes
      Last Post AaronKoRn  
      Started by carnitron, Yesterday, 08:42 PM
      0 responses
      10 views
      0 likes
      Last Post carnitron  
      Started by strategist007, Yesterday, 07:51 PM
      0 responses
      12 views
      0 likes
      Last Post strategist007  
      Started by StockTrader88, 03-06-2021, 08:58 AM
      44 responses
      3,982 views
      3 likes
      Last Post jhudas88  
      Started by rbeckmann05, Yesterday, 06:48 PM
      0 responses
      10 views
      0 likes
      Last Post rbeckmann05  
      Working...
      X