namespace NinjaTrader.NinjaScript.Strategies
{
public class HeikenAshiRealTime : Strategy
{
private LinReg LinReg1;
private VWMA VWMA1;
private int stopLossTicks;
private int takeProfitTicks;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Run in Real time - Heiken Ashi 1-Min - 13/20/10/-40/20/60 settings";
Name = "HeikenAshiRealTime";
Calculate = Calculate.OnBarClose;
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 30;
IsFillLimitOnTouch = false;
MaximumBarsLookBack = MaximumBarsLookBack.TwoHundredFiftySix;
OrderFillResolution = OrderFillResolution.High;
OrderFillResolutionType = BarsPeriodType.Minute;
OrderFillResolutionValue = 1;
Slippage = 0;
StartBehavior = StartBehavior.WaitUntilFlat;
TimeInForce = TimeInForce.Gtc;
TraceOrders = false;
RealtimeErrorHandling = RealtimeErrorHandling.StopCancelClose;
StopTargetHandling = StopTargetHandling.PerEntryExecution;
BarsRequiredToTrade = 20;
IsInstantiatedOnEachOptimizationIteration = true;
LinRegres = 13;
VMARes = 20;
StopLossTicks = 20;
TakeProfitTicks = 50;
}
else if (State == State.Configure)
{
stopLossTicks = StopLossTicks;
takeProfitTicks = TakeProfitTicks;
}
else if (State == State.DataLoaded)
{
LinReg1 = LinReg(Close, Convert.ToInt32(LinRegres));
VWMA1 = VWMA(Close, Convert.ToInt32(VMARes));
}
}
protected override void OnBarUpdate()
{
if (BarsInProgress != 0)
return;
if (CurrentBars[0] < 1)
return;
if(State == State.Historical)
return;
if (Position.MarketPosition == MarketPosition.Flat)
{
// Set 1
if (CrossAbove(LinReg1, VWMA1, 1))
{
SetStopLoss("LongEntry", CalculationMode.Ticks, stopLossTicks, false);
SetProfitTarget("LongEntry", CalculationMode.Ticks, takeProfitTicks);
EnterLong(Convert.ToInt32(DefaultQuantity), "LongEntry");
//SetStopLoss("ShortEntry", CalculationMode.Ticks, stopLossTicks, false);
//SetProfitTarget("ShortEntry", CalculationMode.Ticks, takeProfitTicks);
//EnterShort(Convert.ToInt32(DefaultQuantity), "ShortEntry");
}
// Set 2
if (CrossBelow(LinReg1, VWMA1, 1))
{
SetStopLoss("ShortEntry", CalculationMode.Ticks, stopLossTicks, false);
SetProfitTarget("ShortEntry", CalculationMode.Ticks, takeProfitTicks);
EnterShort(Convert.ToInt32(DefaultQuantity), "ShortEntry");
//SetStopLoss("LongEntry", CalculationMode.Ticks, stopLossTicks, false);
//SetProfitTarget("LongEntry", CalculationMode.Ticks, takeProfitTicks);
//EnterLong(Convert.ToInt32(DefaultQuantity), "LongEntry");
}
}
}
#region Properties
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="LinRegres", Order=1, GroupName="Parameters")]
public int LinRegres
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="VMARes", Order=2, GroupName="Parameters")]
public int VMARes
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="Stop Loss Ticks", Order=3, GroupName="Parameters")]
public int StopLossTicks
{ get; set; }
[NinjaScriptProperty]
[Range(1, int.MaxValue)]
[Display(Name="Take Profit Ticks", Order=4, GroupName="Parameters")]
public int TakeProfitTicks
{ get; set; }
#endregion
namespace NinjaTrader.NinjaScript.Strategies
{
public class DailyLossLimitExample : Strategy
{
private double currentPnL;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Prevents new entries after PnL is less than the LossLimit";
Name = "DailyProfitLossExampleTSmod";
Calculate = Calculate.OnBarClose;
BarsRequiredToTrade = 1;
LossLimit = 500;
ProfitLimit = 1000; ///Define your Profit target
}
else if (State == State.DataLoaded)
{
ClearOutputWindow();
SetStopLoss("long1", CalculationMode.Ticks, 50, false);
}
}
protected override void OnBarUpdate()
{
if (State != State.Realtime) //Only trades realtime. Ignores historical trades.
{
return;
}
// at the start of a new session, reset the currentPnL for a new day of trading
if (Bars.IsFirstBarOfSession)
currentPnL = 0;
// if flat and below the loss limit of the day enter long
if (
(Position.MarketPosition == MarketPosition.Flat)
&& (currentPnL > -LossLimit) ///Loss remains 'above' limit
&& (currentPnL < ProfitLimit) ///Profit remains 'below' limit
)
{
EnterLong(DefaultQuantity, "long1");
}
// if in a position and the realized day's PnL plus the position PnL is greater than the loss limit then exit the order
if (
(Position.MarketPosition == MarketPosition.Long)
&& ( ((currentPnL + Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0])) <= -LossLimit)
|| ((currentPnL + Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0])) >= ProfitLimit) ) ///If unrealized goes under LossLimit 'OR' Above ProfitLimit
)
{
//Print((currentPnL+Position.GetProfitLoss(Close[0], PerformanceUnit.Currency)) + " - " + -LossLimit);
// print to the output window if the daily limit is hit in the middle of a trade
Print("daily limit hit, exiting order " + Time[0].ToString());
ExitLong("Daily Limit Exit", "long1");
}
}
protected override void OnPositionUpdate(Position position, double averagePrice, int quantity, MarketPosition marketPosition)
{
if (Position.MarketPosition == MarketPosition.Flat && SystemPerformance.AllTrades.Count > 0)
{
// when a position is closed, add the last trade's Profit to the currentPnL
currentPnL += SystemPerformance.AllTrades[SystemPerformance.AllTrades.Count - 1].ProfitCurrency;
// print to output window if the daily limit is hit
if (currentPnL <= -LossLimit)
{
Print("daily limit hit, no new orders" + Time[0].ToString());
}
if (currentPnL >= ProfitLimit)
{
Print("daily Profit limit hit, no new orders" + Time[0].ToString()); ///Prints message to output
}
}
}
#region Properties
///Needed to customize our Profit
[NinjaScriptProperty]
[Range(0, double.MaxValue)]
[Display(ResourceType = typeof(Custom.Resource), Name="ProfitLimit", Description="Amount of dollars of acceptable Win", Order=1, GroupName="NinjaScriptStrategyParameters")]
public double ProfitLimit
{ get; set; }
[NinjaScriptProperty]
[Range(0, double.MaxValue)]
[Display(ResourceType = typeof(Custom.Resource), Name="LossLimit", Description="Amount of dollars of acceptable loss", Order=2, GroupName="NinjaScriptStrategyParameters")]
public double LossLimit
{ get; set; }
#endregion

Comment