From bdac441f1e59058f2e126df65d8c183f29f72748 Mon Sep 17 00:00:00 2001 From: moshferatu Date: Sat, 20 Jul 2024 05:39:13 -0700 Subject: [PATCH] Initial commit of 2 Period RSI strategy taken from Short Term Trading Strategies That Work --- strategies/TwoPeriodRSI.cs | 78 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 strategies/TwoPeriodRSI.cs diff --git a/strategies/TwoPeriodRSI.cs b/strategies/TwoPeriodRSI.cs new file mode 100644 index 0000000..113ed04 --- /dev/null +++ b/strategies/TwoPeriodRSI.cs @@ -0,0 +1,78 @@ +#region Using declarations +using NinjaTrader.Cbi; +using NinjaTrader.NinjaScript.Indicators; +using System; +#endregion + +namespace NinjaTrader.NinjaScript.Strategies +{ + public class TwoPeriodRSI : Strategy + { + private SMA sma200; + private SMA sma5; + private RSI rsi; + + protected override void OnStateChange() + { + if (State == State.SetDefaults) + { + Description = @"Taken from chapter 9 of Short Term Trading Strategies That Work"; + Name = "2 Period RSI"; + 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; + IsInstantiatedOnEachOptimizationIteration = true; + } + else if (State == State.DataLoaded) + { + sma200 = SMA(200); + sma5 = SMA(5); + rsi = RSI(2, 1); + } + } + + protected override void OnBarUpdate() + { + if (CurrentBar < 200) return; + + double sma200Value = sma200[0]; + double sma5Value = sma5[0]; + + // Entries + int quantity = (int)Math.Floor(1000000 / Close[0]); + if (Close[0] > sma200Value && rsi[0] < 5) + { + if (Position.MarketPosition != MarketPosition.Long) + EnterLong(quantity); + } + else if (Close[0] < sma200Value && rsi[0] > 95) + { + if (Position.MarketPosition != MarketPosition.Short) + EnterShort(quantity); + } + + // Exits + if (Position.MarketPosition == MarketPosition.Long && Close[0] > sma5Value) + ExitLong(); + else if (Position.MarketPosition == MarketPosition.Short && Close[0] < sma5Value) + ExitShort(); + } + + public override string DisplayName + { + get { return Name; } + } + } +}