ninjatrader/strategies/2-period-rsi/TwoPeriodRSI.cs

89 lines
3.1 KiB
C#

#region Using declarations
using NinjaTrader.Cbi;
using NinjaTrader.NinjaScript.Indicators;
using System;
using System.ComponentModel.DataAnnotations;
#endregion
namespace NinjaTrader.NinjaScript.Strategies
{
public class TwoPeriodRSI : Strategy
{
private SMA longTermTrend;
private SMA shortTermTrend;
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;
LongTermTrendPeriod = 200;
ShortTermTrendPeriod = 5;
}
else if (State == State.DataLoaded)
{
longTermTrend = SMA(LongTermTrendPeriod);
shortTermTrend = SMA(ShortTermTrendPeriod);
rsi = RSI(2, 1);
}
}
protected override void OnBarUpdate()
{
if (CurrentBar < Math.Max(LongTermTrendPeriod, ShortTermTrendPeriod))
return;
// Entries
int quantity = (int)Math.Floor(1000000 / Close[0]);
if (Close[0] > longTermTrend[0] && rsi[0] < 5)
{
if (Position.MarketPosition != MarketPosition.Long)
EnterLong(quantity);
}
else if (Close[0] < longTermTrend[0] && rsi[0] > 95)
{
if (Position.MarketPosition != MarketPosition.Short)
EnterShort(quantity);
}
// Exits
if (Position.MarketPosition == MarketPosition.Long && Close[0] > shortTermTrend[0])
ExitLong();
else if (Position.MarketPosition == MarketPosition.Short && Close[0] < shortTermTrend[0])
ExitShort();
}
public override string DisplayName
{
get { return Name; }
}
[NinjaScriptProperty]
[Display(Name = "Long Term Trend Period", GroupName = "2 Period RSI", Order = 1)]
public int LongTermTrendPeriod { get; set; }
[NinjaScriptProperty]
[Display(Name = "Short Term Trend Period", GroupName = "2 Period RSI", Order = 2)]
public int ShortTermTrendPeriod { get; set; }
}
}