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

Gap strategy

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

    Gap strategy

    Hi

    I'm trying to make a gap strategy, where I wish to open a position if todays opening price is higher than yesterdays closing price. The problem is that I want to take a position as soon at the market opens if it opens higher. But I can only get it to take a position on the open of the second bar of the session. This also means that I can't test it on a daily timeframe, since there is no second bar in the session (I have the strategy set to exit on close of session).

    This is my code, can you please tell what I'm doing wrong?

    #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 Gaps : Strategy
    {
    protected override void OnStateChange()
    {
    if (State == State.SetDefaults)
    {
    Description = @"How to trade gaps";
    Name = "Gaps";
    Calculate = Calculate.OnEachTick;
    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;
    MinimumGapUp = 40;
    MinimumGapDown = 1;
    MinimumGapUpPercent = 0;
    MinimumGapDownPercent = 0;
    MAshorttrend = 7;
    MAmediumtrend = 1;
    MAlongtrend = 1;
    SLpoint = 1;
    }
    else if (State == State.Configure)
    {
    }
    }

    protected override void OnBarUpdate()
    {
    if(CurrentBar < MAshorttrend) return;

    if(GapUp)
    {
    EnterShort();
    SetProfitTarget(CalculationMode.Price, Close[1]);
    SetStopLoss(CalculationMode.Price, (CurrentDayOHL().CurrentOpen[0]-PriorDayOHLC().PriorClose[0])/3+CurrentDayOHL().CurrentOpen[0]);
    Draw.Dot(this, "short"+CurrentBar, true, 0, Low[0], Brushes.Yellow);
    }

    }


    #region Helpers

    bool GapUp { get {return (CurrentDayOHL().CurrentOpen[0] - PriorDayOHLC().PriorClose[0]) > MinimumGapUp;}}

    #endregion

    #region Properties
    [NinjaScriptProperty]
    [Range(0, double.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name="MinimumGapUp", Description="The minimum size of a gap up", Order=1, GroupName="NinjaScriptStrategyParameters")]
    public double MinimumGapUp
    { get; set; }

    [NinjaScriptProperty]
    [Range(0, double.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name="MinimumGapDown", Description="The minimum size of a gap down", Order=2, GroupName="NinjaScriptStrategyParameters")]
    public double MinimumGapDown
    { get; set; }

    [NinjaScriptProperty]
    [Range(0, double.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name="MinimumGapUpPercent", Description="The minimum gap up as a percent of price", Order=3, GroupName="NinjaScriptStrategyParameters")]
    public double MinimumGapUpPercent
    { get; set; }

    [NinjaScriptProperty]
    [Range(0, double.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name="MinimumGapDownPercent", Description="The minimum gap up as a percent of price", Order=4, GroupName="NinjaScriptStrategyParameters")]
    public double MinimumGapDownPercent
    { get; set; }

    [NinjaScriptProperty]
    [Range(0, int.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name="MAshorttrend", Description="The best MA to describe the short trend", Order=5, GroupName="NinjaScriptStrategyParameters")]
    public int MAshorttrend
    { get; set; }

    [NinjaScriptProperty]
    [Range(0, int.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name="MAmediumtrend", Description="The best MA to describe the medium trend", Order=6, GroupName="NinjaScriptStrategyParameters")]
    public int MAmediumtrend
    { get; set; }

    [NinjaScriptProperty]
    [Range(0, int.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name="MAlongtrend", Description="The best MA to describe the long trend", Order=7, GroupName="NinjaScriptStrategyParameters")]
    public int MAlongtrend
    { get; set; }

    [NinjaScriptProperty]
    [Range(0, int.MaxValue)]
    [Display(ResourceType = typeof(Custom.Resource), Name="SLpoint", Description="Number of points to StopLoss", Order=8, GroupName="NinjaScriptStrategyParameters")]
    public int SLpoint
    { get; set; }
    #endregion

    }
    }

    #2
    Hello The_Wiz, and thank you for your question.

    It will be easier to answer questions about strategies not producing expected results if we could answer as many of the following questions as possible. Could you take a few minutes to review these questions? I am happy to explain further any of the below questions and the rationale behind asking them.


    • Do you see expected results when running the same test environment on the SampleMaCrossOver strategy in NinjaTrader with a 3 and 14 period?
      • By expected results, I mean that the SampleMACrossover places trades whenever a 3 and 14 period SMA cross
    • Who are you connected to? This is displayed in green on lower left corner of the Control Center window.
    • Are you connected to your data feed provider when running this test?
    • What instrument(s) (and expiry if applicable) have you selected?
    • What Data Series Type have you selected? Example: Tick, Minute, Day
    • What From and To date is selected?
    • Do you receive an error on screen? Are there errors on the Log tab of the Control Center? If so, what do these errors report?
    Jessica P.NinjaTrader Customer Service

    Comment


      #3
      Click image for larger version

Name:	Gap.jpg
Views:	1
Size:	54.4 KB
ID:	882179Hi

      I'm not expecting a specific result, I just want to be able to take a position at the opening of candle[0] if the price differs from the closing price of candle [1]. The problem is that I can't get it to take a position at the open of candle[0] but it will first do it on candle[-1]. See attached picture.

      Best regards
      The_Wiz

      Comment


        #4
        Thank you for this added information The_Wiz. For the convenience of our community I have attached your source as a C# file to this reply. I would like to ask that in the future you surrounded your code with [code][/code] tags. This will make it easier for community members to read your code.

        To answer your question directly, if you want code to enter at a specified price, you will need to place Limit, MIT, Stop Limit, or Stop Market orders. If you would like to place regular market orders as you are doing, but would like to increase the odds of you getting into the market at the current market price, you may use a multi-timeframe strategy with more granular bars than the ones you are using to detect trade conditions, and use a BarsInProgress index when placing trades.

        More information on multi-timeframe strategies


        More information on using a BarsInProgress index to place market trades


        Please let us know if there are any other ways we can help
        Attached Files
        Jessica P.NinjaTrader Customer Service

        Comment

        Latest Posts

        Collapse

        Topics Statistics Last Post
        Started by elirion, Today, 01:36 AM
        0 responses
        2 views
        0 likes
        Last Post elirion
        by elirion
         
        Started by gentlebenthebear, Today, 01:30 AM
        0 responses
        2 views
        0 likes
        Last Post gentlebenthebear  
        Started by samish18, Yesterday, 08:31 AM
        2 responses
        9 views
        0 likes
        Last Post elirion
        by elirion
         
        Started by Mestor, 03-10-2023, 01:50 AM
        16 responses
        389 views
        0 likes
        Last Post z.franck  
        Started by rtwave, 04-12-2024, 09:30 AM
        4 responses
        31 views
        0 likes
        Last Post rtwave
        by rtwave
         
        Working...
        X