0% found this document useful (0 votes)
29 views5 pages

BreakEven Builder Strategy for NinjaTrader

The document contains a C# strategy class for NinjaTrader named 'BreakEvenBuilderExampleUNLOCKE' that implements a trading strategy using various indicators such as EMA and WMA. It defines parameters for trade execution, including break-even triggers, stop losses, and trading hours. The strategy manages long and short positions based on specific market conditions and indicator crossovers.

Uploaded by

diglemar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views5 pages

BreakEven Builder Strategy for NinjaTrader

The document contains a C# strategy class for NinjaTrader named 'BreakEvenBuilderExampleUNLOCKE' that implements a trading strategy using various indicators such as EMA and WMA. It defines parameters for trade execution, including break-even triggers, stop losses, and trading hours. The strategy manages long and short positions based on specific market conditions and indicator crossovers.

Uploaded by

diglemar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

#region Using declarations

using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
#endregion

//This namespace holds Strategies in this folder and is required. Do not change it.
namespace [Link]
{
public class BreakEvenBuilderExampleUNLOCKE : Strategy
{
private double StopPrice;
private double TriggerPrice;
private int TriggerState;

private EMA EMA1;


private WMA WMA1;
private EMA EMA2;
private EMA EMA3;

protected override void OnStateChange()


{
if (State == [Link])
{
Description = @"";
Name = "BreakEvenBuilderExampleUNLOCKE";
Calculate = [Link];
EntriesPerDirection = 1;
EntryHandling = [Link];
IsExitOnSessionCloseStrategy = true;
ExitOnSessionCloseSeconds = 30;
IsFillLimitOnTouch = false;
MaximumBarsLookBack =
[Link];
OrderFillResolution = [Link];
Slippage = 0;
StartBehavior = [Link];
TimeInForce = [Link];
TraceOrders = false;
RealtimeErrorHandling = [Link];

Page 1 of 5
StopTargetHandling = [Link];
BarsRequiredToTrade = 20;
// Disable this property for performance gains in Strategy Analyzer optimizations
// See the Help Guide for additional information
IsInstantiatedOnEachOptimizationIteration = true;
BreakEvenTrigger = 10;
InitialStopLong = -15;
TP = 45;
Maxprofit = 200;
Fast = 8;
Slow = 35;
Histo_UP = 150;
Histo_Down = 700;
Start_TradingDay = [Link]("02:00",
[Link]);
End_TradingDay = [Link]("11:00",
[Link]);
InitialStopShort = 15;
StopPrice = 0;
TriggerPrice = 0;
TriggerState = 0;
}
else if (State == [Link])
{
}
else if (State == [Link])
{
EMA1 = EMA(Close, Convert.ToInt32(Fast));
WMA1 = WMA(Close, Convert.ToInt32(Slow));
EMA2 = EMA(Close, Convert.ToInt32(Histo_UP));
EMA3 = EMA(Close, Convert.ToInt32(Histo_Down));
[Link][0].Brush = [Link];
[Link][0].Brush = [Link];
[Link][0].Brush = [Link];
[Link][0].Brush = [Link];
AddChartIndicator(EMA1);
AddChartIndicator(WMA1);
AddChartIndicator(EMA2);
AddChartIndicator(EMA3);
}
}

protected override void OnBarUpdate()


{
if (BarsInProgress != 0)
return;

// Set 1
if ((TriggerState >= 2)
&& ([Link] == [Link]))
{
TriggerState = 0;
}

if (CurrentBars[0] < 1)
return;

// Set 2

Page 2 of 5
if ((CrossAbove(EMA1, WMA1, 1))
&& (EMA2[0] > EMA3[0])
&& (Times[0][0].TimeOfDay >= Start_TradingDay.TimeOfDay)
&& (Times[0][0].TimeOfDay < End_TradingDay.TimeOfDay))
{
TriggerState = 1;
EnterLong(Convert.ToInt32(DefaultQuantity), @"COMPRA");
}

// Set 3
if ((TriggerState == 1)
&& ([Link] == [Link]))
{
TriggerState = 2;
TriggerPrice = ([Link] + (BreakEvenTrigger * TickSize)) ;
StopPrice = ([Link] + (InitialStopLong * TickSize)) ;
}

// Set 4
if ((TriggerState == 2)
&& (Close[0] >= TriggerPrice))
{
TriggerState = 3;
StopPrice = [Link];
}

// Set 5
if (TriggerState >= 2)
{
ExitLongStopMarket(Convert.ToInt32(DefaultQuantity), StopPrice, @"StopLoss",
@"COMPRA");
}

// Set 6
if ([Link]([Link], Close[0]) >= TP)
{
ExitLong(Convert.ToInt32(DefaultQuantity), @"You Win", @"");
ExitShort(Convert.ToInt32(DefaultQuantity), @"You Win", "");
}

// Set 7
if ((CrossBelow(EMA1, WMA1, 1))
&& (EMA2[0] < EMA3[0])
&& (Times[0][0].TimeOfDay >= Start_TradingDay.TimeOfDay)
&& (Times[0][0].TimeOfDay < End_TradingDay.TimeOfDay))
{
TriggerState = 1;
EnterShort(Convert.ToInt32(DefaultQuantity), @"VENTA");
}

// Set 8
if ((TriggerState == 1)
&& ([Link] == [Link]))
{
TriggerState = 2;
TriggerPrice = ([Link] + (BreakEvenTrigger * TickSize)) ;
StopPrice = ([Link] + (InitialStopShort * TickSize)) ;
}

Page 3 of 5
// Set 9
if ((TriggerState == 2)
&& (Close[0] <= TriggerPrice))
{
TriggerState = 3;
StopPrice = [Link];
}

// Set 10
if (TriggerState >= 2)
{
ExitShortStopMarket(Convert.ToInt32(DefaultQuantity), StopPrice, @"StopLoss",
@"VENTA");
}

// Set 11
if ((Times[0][0].TimeOfDay >= Start_TradingDay.TimeOfDay)
&& (Times[0][0].TimeOfDay < End_TradingDay.TimeOfDay))
{
BackBrush = [Link];
}

#region Properties
[NinjaScriptProperty]
[Range(1, [Link])]
[Display(Name="BreakEvenTrigger", Description="Number of ticks above entry the breakeven
movement trigger is set", Order=1, GroupName="Parameters")]
public int BreakEvenTrigger
{ get; set; }

[NinjaScriptProperty]
[Range(-999, [Link])]
[Display(Name="InitialStopLong", Description="(use a negative) Number of ticks from entry
the stop will initially be placed below", Order=2, GroupName="Parameters")]
public int InitialStopLong
{ get; set; }

[NinjaScriptProperty]
[Range(1, [Link])]
[Display(Name="TP", Order=3, GroupName="Parameters")]
public int TP
{ get; set; }

[NinjaScriptProperty]
[Range(1, [Link])]
[Display(Name="Maxprofit", Order=4, GroupName="Parameters")]
public double Maxprofit
{ get; set; }

[NinjaScriptProperty]
[Range(1, [Link])]
[Display(Name="Fast", Order=5, GroupName="Parameters")]
public int Fast
{ get; set; }

Page 4 of 5
[NinjaScriptProperty]
[Range(1, [Link])]
[Display(Name="Slow", Order=6, GroupName="Parameters")]
public int Slow
{ get; set; }

[NinjaScriptProperty]
[Range(1, [Link])]
[Display(Name="Histo_UP", Order=7, GroupName="Parameters")]
public int Histo_UP
{ get; set; }

[NinjaScriptProperty]
[Range(1, [Link])]
[Display(Name="Histo_Down", Order=8, GroupName="Parameters")]
public int Histo_Down
{ get; set; }

[NinjaScriptProperty]
[PropertyEditor("[Link]")]
[Display(Name="Start_TradingDay", Order=9, GroupName="Parameters")]
public DateTime Start_TradingDay
{ get; set; }

[NinjaScriptProperty]
[PropertyEditor("[Link]")]
[Display(Name="End_TradingDay", Order=10, GroupName="Parameters")]
public DateTime End_TradingDay
{ get; set; }

[NinjaScriptProperty]
[Range(1, [Link])]
[Display(Name="InitialStopShort", Order=11, GroupName="Parameters")]
public int InitialStopShort
{ get; set; }
#endregion

}
}

Page 5 of 5

Common questions

Powered by AI

TriggerState is a numerical variable used to track the progression of trade conditions and actions in the strategy. It holds different values indicating the trade's lifecycle stages: from initiating a trade (value 1), modifying the stop price to breakeven (value 2), to adjusting the stop price once the TriggerPrice is met (value 3). Managing these states is crucial for executing precise trade actions, synchronizing trade operations, and ensuring coherent state transitions during the trade's lifecycle .

Within the "BreakEvenBuilderExampleUNLOCKE" strategy, several chart indicators are added to enhance visual analysis and decision-making. Specifically, EMA1 is plotted using a Goldenrod brush, WMA1 with a White brush, EMA2 with Dark Cyan, and EMA3 with Dark Red. These visual cues help traders quickly interpret market conditions and crossovers through color-coded indicators directly on the chart, aligning with the strategy's logic and facilitating the trader’s situational awareness .

The property "IsInstantiatedOnEachOptimizationIteration" is disabled to improve the performance of strategy analyzer optimizations. By default, each optimization creates a new instance of the strategy, which can be resource-intensive when running multiple iterations. Setting this property to false reduces the overhead by reusing instances where possible, thereby speeding up the optimization process and consuming fewer system resources .

The "BreakEvenBuilderExampleUNLOCKE" strategy employs both Exponential Moving Averages (EMA) and Weighted Moving Average (WMA) to generate entry signals. Specifically, the strategy enters a long position if there is a crossover where EMA1 crosses above WMA1, coupled with a condition that EMA2 is greater than EMA3 during the specified trading hours. Conversely, for a short position, the strategy looks for EMA1 crossing below WMA1 with EMA2 being less than EMA3 .

The "OrderFillResolution" option set to "Standard" determines the granularity at which order fills are simulated within the strategy. A "Standard" resolution provides a balanced level of detail in fill simulation, which is sufficient for many strategies while maintaining computational efficiency. It affects how accurately the backtesting environment represents market conditions, influencing the strategy's historical performance analysis and real-world execution similarity .

The strategy is configured to start trading at 2:00 AM and end at 11:00 AM. These times are crucial as they define the trading window during which the strategy will actively monitor and execute trades. This time frame might align with specific market sessions that the strategy designer considers beneficial for trading, possibly due to higher liquidity or volatility .

The breakeven trigger in the "BreakEvenBuilderExampleUNLOCKE" strategy is used to adjust the position's stop price based on certain trade conditions. When a position reaches the specified number of ticks beyond the entry price (as defined by BreakEvenTrigger), the stop price is adjusted to the entry price for minimizing potential losses and locking in profits. This mechanism changes the trade's risk profile by reducing the possibility of a loss once the market has moved favorably .

The "InitialStopLong" and "InitialStopShort" parameters determine the initial placement of stop-loss orders when entering long and short positions, respectively. "InitialStopLong" is expressed as a negative number, representing the number of ticks below the entry price for a long position, while "InitialStopShort" is a positive number for ticks above the entry price for a short position. These parameters are critical for setting the initial risk level of each trade .

Once the unrealized profit of a position reaches or exceeds the Take Profit (TP) threshold specified in ticks, the strategy executes an exit order. It closes both long and short positions via the "ExitLong" and "ExitShort" methods with the label "You Win,” ensuring that profits are locked in and positions are closed once the specified profit target is met .

The "ExitOnSessionClose" functionality is designed to exit positions a specified number of seconds before the market close. In this strategy, the positions are exited 30 seconds before the session closes. This feature ensures that all open trades are closed within the current trading session, mitigating risks related to overnight price gaps and ensuring the strategy does not hold positions outside its defined active window .

You might also like