From b0eb691e727865014cc208b8ee968b7457226923 Mon Sep 17 00:00:00 2001 From: moshferatu Date: Wed, 15 Nov 2023 06:28:52 -0800 Subject: [PATCH] Add basic moving average crossover strategy --- strategies/MovingAverageCrossover.cs | 79 ++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 strategies/MovingAverageCrossover.cs diff --git a/strategies/MovingAverageCrossover.cs b/strategies/MovingAverageCrossover.cs new file mode 100644 index 0000000..f11b1e8 --- /dev/null +++ b/strategies/MovingAverageCrossover.cs @@ -0,0 +1,79 @@ +#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 MovingAverageCrossover : Strategy + { + private EMA fastMA; + private EMA slowMA; + + protected override void OnStateChange() + { + if (State == State.SetDefaults) + { + Description = @"Moving Average Crossover"; + Name = "Moving Average Crossover"; + 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; + } + else if (State == State.Configure) + { + fastMA = EMA(3); + slowMA = EMA(17); + } + } + + protected override void OnBarUpdate() + { + if (CurrentBar < BarsRequiredToTrade) + return; + + if (CrossAbove(fastMA, slowMA, 1)) + { + if (Position.MarketPosition != MarketPosition.Long) + EnterLong(); + } + else if (CrossBelow(fastMA, slowMA, 1)) + { + if (Position.MarketPosition != MarketPosition.Short) + EnterShort(); + } + } + } +}