Announcement

Collapse
No announcement yet.

Partner 728x90

Collapse

Opposite direction trade indicator

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

    Opposite direction trade indicator

    I want to build an indicator where I can place a trade and sned an inverse order to another instrument, as a hedge.
    Example, if I go long +1 ES, then go short -10 MES. And enable the indicator to set hedge amount and TP and SL levels for the position.

    I tried some on the Script Editor but getting some errors.


    Full 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.DrawingTools;
    #endregion

    //This namespace holds Indicators in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Indicators
    {
    public class Hedger : Indicator
    {
    // Define variables for selecting instruments and contract size
    private string instrument1 = "ES"; // Enter the symbol of the first instrument
    private string instrument2 = "NQ"; // Enter the symbol of the second instrument
    private int contractSize = 1; // Enter the contract size for both instruments

    // Initialize the opposite trade flag to false
    private bool oppositeTrade = false;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Indicator here.";
    Name = "Hedger";
    Calculate = Calculate.OnBarClose;
    IsOverlay = false;
    DisplayInDataBox = true;
    DrawOnPricePanel = true;
    DrawHorizontalGridLines = true;
    DrawVerticalGridLines = true;
    PaintPriceMarkers = true;
    ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
    //Disable this property if your indicator requires custom values that cumulate with each new market data event.
    //See Help Guide for additional information.
    IsSuspendedWhileInactive = true;
    }
    else if (State == State.Configure)
    {
    }
    }

    protected override void OnBarUpdate()
    {
    //Add your custom indicator logic here.
    // Check if a trade has been placed in instrument1
    if (Position.MarketPosition != MarketPosition.Flat && Position.Instrument.FullName == Instrument.FullName && !oppositeTrade)
    {
    // Calculate the opposite trade quantity for instrument2
    int oppositeQuantity = -(int)(Position.Quantity * Instrument.MasterInstrument.PointValue / Instrument.MasterInstrument.TickSize * contractSize);

    // Place an opposite trade in instrument2
    int EnterShort(instrument2, oppositeQuantity, "Opposite Trade");

    // Set the opposite trade flag to true
    oppositeTrade = true;
    }
    // Reset the opposite trade flag when the position in instrument1 is closed
    else if (Position.MarketPosition == MarketPosition.Flat && oppositeTrade)
    {
    oppositeTrade = false;
    }
    }
    }
    }

    region NinjaScript generated code. Neither change nor remove.

    namespace NinjaTrader.NinjaScript.Indicators
    {
    public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
    {
    private Hedger[] cacheHedger;
    public Hedger Hedger()
    {
    return Hedger(Input);
    }

    public Hedger Hedger(ISeries<double> input)
    {
    if (cacheHedger != null)
    for (int idx = 0; idx < cacheHedger.Length; idx++)
    if (cacheHedger[idx] != null && cacheHedger[idx].EqualsInput(input))
    return cacheHedger[idx];
    return CacheIndicator<Hedger>(new Hedger(), input, ref cacheHedger);
    }
    }
    }

    namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
    {
    public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
    {
    public Indicators.Hedger Hedger()
    {
    return indicator.Hedger(Input);
    }

    public Indicators.Hedger Hedger(ISeries<double> input )
    {
    return indicator.Hedger(input);
    }
    }
    }

    namespace NinjaTrader.NinjaScript.Strategies
    {
    public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
    {
    public Indicators.Hedger Hedger()
    {
    return indicator.Hedger(Input);
    }

    public Indicators.Hedger Hedger(ISeries<double> input )
    {
    return indicator.Hedger(input);
    }
    }
    }

    #endregion​

    #2
    I want to build an indicator where I can place a trade and sned an inverse order to another instrument, as a hedge.
    Example, if I go long +1 ES, then go short -10 MES. And enable the indicator to set hedge amount and TP and SL levels for the position.

    I tried some on the Script Editor but getting some errors.


    Full 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.DrawingTools;
    #endregion

    //This namespace holds Indicators in this folder and is required. Do not change it.
    namespace NinjaTrader.NinjaScript.Indicators
    {
    public class Hedger : Indicator
    {
    // Define variables for selecting instruments and contract size
    private string instrument1 = "ES"; // Enter the symbol of the first instrument
    private string instrument2 = "NQ"; // Enter the symbol of the second instrument
    private int contractSize = 1; // Enter the contract size for both instruments

    // Initialize the opposite trade flag to false
    private bool oppositeTrade = false;

    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"Enter the description for your new custom Indicator here.";
    Name = "Hedger";
    Calculate = Calculate.OnBarClose;
    IsOverlay = false;
    DisplayInDataBox = true;
    DrawOnPricePanel = true;
    DrawHorizontalGridLines = true;
    DrawVerticalGridLines = true;
    PaintPriceMarkers = true;
    ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
    //Disable this property if your indicator requires custom values that cumulate with each new market data event.
    //See Help Guide for additional information.
    IsSuspendedWhileInactive = true;
    }
    else if (State == State.Configure)
    {
    }
    }

    protected override void OnBarUpdate()
    {
    //Add your custom indicator logic here.
    // Check if a trade has been placed in instrument1
    if (Position.MarketPosition != MarketPosition.Flat && Position.Instrument.FullName == Instrument.FullName && !oppositeTrade)
    {
    // Calculate the opposite trade quantity for instrument2
    int oppositeQuantity = -(int)(Position.Quantity * Instrument.MasterInstrument.PointValue / Instrument.MasterInstrument.TickSize * contractSize);

    // Place an opposite trade in instrument2
    int EnterShort(instrument2, oppositeQuantity, "Opposite Trade");

    // Set the opposite trade flag to true
    oppositeTrade = true;
    }
    // Reset the opposite trade flag when the position in instrument1 is closed
    else if (Position.MarketPosition == MarketPosition.Flat && oppositeTrade)
    {
    oppositeTrade = false;
    }
    }
    }
    }

    region NinjaScript generated code. Neither change nor remove.

    namespace NinjaTrader.NinjaScript.Indicators
    {
    public partial class Indicator : NinjaTrader.Gui.NinjaScript.IndicatorRenderBase
    {
    private Hedger[] cacheHedger;
    public Hedger Hedger()
    {
    return Hedger(Input);
    }

    public Hedger Hedger(ISeries<double> input)
    {
    if (cacheHedger != null)
    for (int idx = 0; idx < cacheHedger.Length; idx++)
    if (cacheHedger[idx] != null && cacheHedger[idx].EqualsInput(input))
    return cacheHedger[idx];
    return CacheIndicator<Hedger>(new Hedger(), input, ref cacheHedger);
    }
    }
    }

    namespace NinjaTrader.NinjaScript.MarketAnalyzerColumns
    {
    public partial class MarketAnalyzerColumn : MarketAnalyzerColumnBase
    {
    public Indicators.Hedger Hedger()
    {
    return indicator.Hedger(Input);
    }

    public Indicators.Hedger Hedger(ISeries<double> input )
    {
    return indicator.Hedger(input);
    }
    }
    }

    namespace NinjaTrader.NinjaScript.Strategies
    {
    public partial class Strategy : NinjaTrader.Gui.NinjaScript.StrategyRenderBase
    {
    public Indicators.Hedger Hedger()
    {
    return indicator.Hedger(Input);
    }

    public Indicators.Hedger Hedger(ISeries<double> input )
    {
    return indicator.Hedger(input);
    }
    }
    }

    #endregion

    Comment


      #3
      Hello carlosgutierrez,

      NinjaScript Strategies are better suited for placing orders than indicators. Are you certain you want an indicator and not a strategy?

      Below is a link to a forum post with helpful resources on getting started with NinjaScript and C#.
      https://ninjatrader.com/support/foru...pts#post786040

      An indicator is intended to mark the chart with plots and drawing objects as indications on market actions.
      A strategy is a trading strategy that automates placing orders.


      The Position object property and EnterShort order method are only available to NinjaScript Strategies.

      Below are links to the help guide.
      https://ninjatrader.com/support/help...8/position.htm
      https://ninjatrader.com/support/help...entershort.htm
      https://ninjatrader.com/support/help...8/strategy.htm

      The account position from a NinjaScript Strategy can be found with the PositionAccount.
      https://ninjatrader.com/support/help...ionaccount.htm


      You can add a data series with another instrument if you want to place orders to the barsInProgress index that other instrument series.




      For an indicator, you will need to use the Addon approach and get position updates from an account object and place orders using that account object.

      Below is a link to the help guide.

      https://ninjatrader.com/support/help...tionupdate.htm
      https://ninjatrader.com/support/help...reateorder.htm
      https://ninjatrader.com/support/help...nt8/submit.htm
      https://ninjatrader.com/support/help...ount_class.htm


      Regarding hedging (being long and short at the same time) this is not possible on the same account and instrument. You would need to have a separate account to have separate positions. The forum post below discusses.
      https://ninjatrader.com/support/foru...660#post792660


      As a tip, if you can provide an export of a script instead of posting the full text of a script on the forum.

      To export a NinjaTrader 8 NinjaScript so this can be shared and imported by the recipient do the following:
      1. Click Tools -> Export -> NinjaScript Add-on...
      2. Click the 'add' link -> check the box(es) for the script(s) and reference(s) you want to include
      3. Click the 'Export' button
      4. Enter a unique name for the file in the value for 'File name:'
      5. Choose a save location -> click Save
      6. Click OK to clear the export location message
      By default your exported file will be in the following location:
      • (My) Documents/NinjaTrader 8/bin/Custom/ExportNinjaScript/<export_file_name.zip>
      Below is a link to the help guide on Exporting NinjaScripts.
      http://ninjatrader.com/support/helpG...-us/export.htm
      Chelsea B.NinjaTrader Customer Service

      Comment


        #4
        I want to build a strategy where I can place a trade and sned an inverse order to another instrument, as a hedge.
        Example, if I go long +1 ES, then go short -10 MES. And enable the indicator to set hedge amount and TP and SL levels for the position.

        Main error code CS15258 "Expected; or = (cannot specify constructor arguments in declaration)"

        error is highlighted on the code. Line 71 column 23

        I tried some on the Script Editor but getting some errors.

        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 Hedger : Indicator
        {
        // Define variables for selecting instruments and contract size
        private string instrument1 = "ES"; // Enter the symbol of the first instrument
        private string instrument2 = "NQ"; // Enter the symbol of the second instrument
        private int contractSize = 1; // Enter the contract size for both instruments

        // Initialize the opposite trade flag to false
        private bool oppositeTrade = false;

        protected override void OnStateChange()
        {
        if (State == State.SetDefaults)
        {
        Description = @"Enter the description for your new custom Indicator here.";
        Name = "Hedger";
        Calculate = Calculate.OnBarClose;
        IsOverlay = false;
        DisplayInDataBox = true;
        DrawOnPricePanel = true;
        DrawHorizontalGridLines = true;
        DrawVerticalGridLines = true;
        PaintPriceMarkers = true;
        ScaleJustification = NinjaTrader.Gui.Chart.ScaleJustification.Right;
        //Disable this property if your indicator requires custom values that cumulate with each new market data event.
        //See Help Guide for additional information.
        IsSuspendedWhileInactive = true;
        }
        else if (State == State.Configure)
        {
        }
        }

        protected override void OnBarUpdate()
        {
        //Add your custom strategy logic here.
        // Check if a trade has been placed in instrument1
        if (Position.MarketPosition != MarketPosition.Flat && Position.Instrument.FullName == Instrument.FullName && !oppositeTrade)
        {
        // Calculate the opposite trade quantity for instrument2
        int oppositeQuantity = -(int)(Position.Quantity * Instrument.MasterInstrument.PointValue / Instrument.MasterInstrument.TickSize * contractSize);

        // Place an opposite trade in instrument2
        int EnterShort(instrument2, oppositeQuantity, "Opposite Trade");

        // Set the opposite trade flag to true
        oppositeTrade = true;
        }
        // Reset the opposite trade flag when the position in instrument1 is closed
        else if (Position.MarketPosition == MarketPosition.Flat && oppositeTrade)
        {
        oppositeTrade = false;
        }
        }
        }
        }

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by Geovanny Suaza, 02-11-2026, 06:32 PM
        0 responses
        649 views
        0 likes
        Last Post Geovanny Suaza  
        Started by Geovanny Suaza, 02-11-2026, 05:51 PM
        0 responses
        370 views
        1 like
        Last Post Geovanny Suaza  
        Started by Mindset, 02-09-2026, 11:44 AM
        0 responses
        109 views
        0 likes
        Last Post Mindset
        by Mindset
         
        Started by Geovanny Suaza, 02-02-2026, 12:30 PM
        0 responses
        573 views
        1 like
        Last Post Geovanny Suaza  
        Started by RFrosty, 01-28-2026, 06:49 PM
        0 responses
        576 views
        1 like
        Last Post RFrosty
        by RFrosty
         
        Working...
        X