One way I could do this would be with a custom indicator that performs the same trailing stop calculation but can change a flag value from False to True. Is there any other way? Any suggestions on making such a custom indicator?
Announcement
Collapse
Looking for a User App or Add-On built by the NinjaTrader community?
Visit NinjaTrader EcoSystem and our free User App Share!
Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
Have a question for the NinjaScript developer community? Open a new thread in our NinjaScript File Sharing Discussion Forum!
See more
See less
Partner 728x90
Collapse
NinjaTrader
trailing stop
Collapse
X
-
trailing stop
Within a strategy I am working on, I use a trailing stop, let's say %2. I would like to try to change my strategy so that when this %2 stop is reached, I don't exit right then, but instead wait for a signal from another indicator. I would do this by having a flag change from false to true, and then work the indicator for an exit within that true condition.
One way I could do this would be with a custom indicator that performs the same trailing stop calculation but can change a flag value from False to True. Is there any other way? Any suggestions on making such a custom indicator?Tags: None
-
Hello,
You do not need a new indicator. You can do something like this:
if(Position.GetProfitLoss(Close[0], PerformanceUnit.Percent) == some_percentage_here
&& Position.MarketPosition != MarketPosition.Flat)
{
has_reached_percentage = true;
}
Now you can use that true setting wherever you want within your code.
You may want to also reset the has_reached_percentage like this:
if(Position.MarketPosition == MarketPosition.Flat)
{
has_reached_percentage = false;
}
Here are some links that will help:
DenNinjaTrader Customer Service
-
Ben I will look at those links. To be clear here, in your example code, could I use that as a trailing stop or is that just a %2 stop from the initial market position? I am a not so good coder yet.
And, currently as a form of position sizing, when I actually run a strategy live, I use "Order Properties, Account Size $10000". I think since I will be changing that account size amount depending on the stock, I would want to be coding with percentage changes and never with open profit and loss?
Comment
-
Hello,
What I provided is just a condition and true/false toggle you could use to determine if your order has reached the % PnL you want. You will need to then add code to then determine if you want to actually exit the trade or some other action.
It sounds like you will need to code your own logic to determine your trail stop.DenNinjaTrader Customer Service
Comment
-
Sorry to be vague here. What I am trying to get is how as a trade moves in my favor (let's say a short) the stop will get lower and lower. If the price reverses and then hits that new lower stop, I then want to have a flag be true (which I can code now from your previous help).
Can I have the actual trailing stop code that is used by for instance strategy generator?
For instance if I could duplicate this code within my strategy as an onbarevent instead of calling it I would be all set.
SetTrailStop("", CalculationMode.Percent, TrailingStop, true);
Comment
-
-
sauer11155,
Here is some food for thought. Not tested, but it should help get you kicked off in how to code it yourself.
Code:// In Variables section private double trailStop = 0; private double prevValue = 0; private bool justEntered = false; // In OnBarUpdate() method if (Close[0] > Open[0] && Position.MarketPosition == MarketPosition.Flat) { EnterLong(); justEntered = true; } if (Position.MarketPosition == MarketPosition.Long && justEntered == true) { trailStop = 0.98 * Position.AvgPrice; prevValue = Position.AvgPrice; justEntered = false; Print("TRAIL STOP TRACKING: " + trailStop); } if (Position.MarketPosition == MarketPosition.Long) { if (Close[0] > Position.AvgPrice && Close[0] > prevValue) { trailStop = trailStop + (Close[0] - prevValue); prevValue = Close[0]; Print("TRAIL STOP RAISED: " + trailStop + " " + prevValue); } Print(Time[0] + " " + Close[0] + " " + prevValue); } if (Close[0] <= trailStop) { Print("TRAIL STOP HIT: " + trailStop + " " + Close[0]); // Trailing stop has been hit; do whatever you want here trailStop = 0; prevValue = 0; }
Josh P.NinjaTrader Customer Service
Comment
-
Thanks dude, I was overwhelmed lol. With what you gave me I have all weekend busy now, this should advance my coding some more. I gotta say I am getting far with this and it's been 1 month and 2 weeks.
Comment
-
Coded percentage trailing stop
I coded and have working a coded in onbarupdate trailing stop, thanks for the help in here. Here is the code, I will post this and another version in the scripts section:
#region Variables
// Wizard generated variables
private double trailStop = 0; // Default setting for TrailStop
private double prevValue = 0; // Default setting for PrevValue
private double trailStopPercentage = .02;
private bool justEntered = false; // Default setting for JustEntered
// User defined variables (add any user defined variables below)
#endregion
/// <summary>
/// This method is used to configure the strategy and is called once before any strategy method is called.
/// </summary>
protected override void Initialize()
{
CalculateOnBarClose = true;
}
/// <summary>
/// Called on each bar update event (incoming tick)
/// </summary>
protected override void OnBarUpdate()
{
if (Close[0] > Open[0] && Position.MarketPosition == MarketPosition.Flat)
{
EnterLong();
justEntered = true;
Print(Time[0] + " Entered Long " + " symbol " + Instrument.FullName);
}
if (Position.MarketPosition == MarketPosition.Long && justEntered == true)
{
trailStop = Position.AvgPrice - (trailStopPercentage * Position.AvgPrice);
prevValue = Position.AvgPrice;
justEntered = false;
Print(" TRAIL STOP TRACKING: " + trailStop + " symbol " + Instrument.FullName);
}
if (Position.MarketPosition == MarketPosition.Long)
{
if (High[0] > Position.AvgPrice && High[0] > prevValue)
{
trailStop = trailStop + (High[0] - prevValue);
prevValue = High[0];
Print(" TRAIL STOP RAISED: " + trailStop + " PrevValue " + prevValue + " symbol " + Instrument.FullName);
}
Print(Time[0] + " High " + High[0] + " PrevValue " + prevValue + " symbol " + Instrument.FullName);
}
if (Low[0] <= trailStop)
{
Print(" TRAIL STOP HIT: " + trailStop + " " + Close[0] + " symbol " + Instrument.FullName);
// Trailing stop has been hit; do whatever you want here
ExitLong("","");
trailStop = 0;
prevValue = 0;
}
}
#region Properties
[Description("")]
[Category("Parameters")]
public double TrailStop
{
get { return trailStop; }
set { trailStop = Math.Max(0.00, value); }
}
[Description("")]
[Category("Parameters")]
public double PrevValue
{
get { return prevValue; }
set { prevValue = Math.Max(0.00, value); }
}
[Description("")]
[Category("Parameters")]
public double TrailStopPercentage
{
get { return trailStopPercentage; }
set { trailStopPercentage = Math.Max(0.00, value); }
}
[Description("")]
[Category("Parameters")]
public bool JustEntered
{
get { return justEntered; }
set { justEntered = value; }
}
#endregion
}
}
Comment
-
sauer11155, thanks for your scripts.
Playing with StochasticCrosswTrailingStopExit raised some questions:
1. I thought that at the end of the code you forgot to reset TrailStop and PrevValue to 0 and JustEntered to false. So I changedf (Position.MarketPosition == MarketPosition.Flat)
{
ExitFlag = false;
}
if (Position.MarketPosition == MarketPosition.Flat)
{
ExitFlag = false;
TrailStop= 0;
PrevValue=0;
JustEntered = false; BUT this lowers the result in my backtesting
}
But resetting JustEntered to false when MarketPosition == MarketPosition.Flat lowers my bcktesting results.
Do you have any idea why adding JustEntered to false here would influence the result? I tried to follow the logic but can't see why.
BTW Some minor details:
2. I think 2 of your variables are not used anywhere in the code
3. Do you have a reason to declare trailStop, prevValue, justEntered and exitFlag as PUBLIC in the properties ?
Code:{ #region Variables // Wizard generated variables private int periodD = 10; // Default setting for PeriodD private int periodK = 20; // Default setting for PeriodK private int smooth = 5; // Default setting for Smooth private int topLine = 80; // Default setting for TopLine private int bottomLine = 20; // Default setting for BottomLine [COLOR=Red]private int unrealizedPL = 1; // Default setting for UnrealizedPL private bool aFlag1 = false; // Default setting for AFlag1[/COLOR] private double trailStop = 0; // Default setting for TrailStop private double prevValue = 0; // Default setting for PrevValue private double trailStopPercentage = .02; private bool justEntered = false; // Default setting for JustEntered private bool exitFlag = false; private double safetyTrailingStop = 0.04; // Default setting forSafetyTrailingStop private double profitTarget2 = 0.02; // Default setting for ProfitTarget2 // User defined variables (add any user defined variables below) #endregion /// <summary> /// This method is used to configure the strategy and is called once before any strategy method is called. /// </summary> protected override void Initialize() { Add(Stochastics(PeriodD, PeriodK, Smooth)); Add(Stochastics(PeriodD, PeriodK, Smooth)); SetTrailStop("", CalculationMode.Percent, SafetyTrailingStop, true); SetProfitTarget("", CalculationMode.Percent, ProfitTarget2); CalculateOnBarClose = true; } /// <summary> /// Called on each bar update event (incoming tick) /// </summary> protected override void OnBarUpdate() { // Condition set 1 if (CrossAbove(Stochastics(PeriodD, PeriodK, Smooth).D, BottomLine, 1) && Position.MarketPosition == MarketPosition.Flat) { EnterLong(DefaultQuantity, ""); justEntered = true; Print(Time[0] + " Entered Long " + " symbol " + Instrument.FullName); } if (Position.MarketPosition == MarketPosition.Long && justEntered == true) { trailStop = Position.AvgPrice - (trailStopPercentage * Position.AvgPrice); prevValue = Position.AvgPrice; justEntered = false; Print(" TRAIL STOP TRACKING: " + trailStop + " symbol " + Instrument.FullName); } if (Position.MarketPosition == MarketPosition.Long) { if (High[0] > Position.AvgPrice && High[0] > prevValue) { trailStop = trailStop + (High[0] - prevValue); prevValue = High[0]; Print(" TRAIL STOP RAISED: " + trailStop + " PrevValue " + prevValue + " symbol " + Instrument.FullName); } Print(Time[0] + " High " + High[0] + " PrevValue " + prevValue + " symbol " + Instrument.FullName); } if (Low[0] <= trailStop && (Position.MarketPosition == MarketPosition.Long)) { Print(" TRAIL STOP HIT: " + trailStop + " " + Close[0] + " symbol " + Instrument.FullName); // Trailing stop has been hit; do whatever you want here DrawDot(Time[0].ToString() + "Buy", 0, Low[0] - TickSize, Color.Red); ExitFlag = true; } if (ExitFlag == true) { if (CrossBelow(Stochastics(PeriodD, PeriodK, Smooth).D, TopLine, 1)) ExitLong("",""); } if (Position.MarketPosition == MarketPosition.Flat) { ExitFlag = false; } } #region Properties [Description("")] [Category("Parameters")] public int PeriodD { get { return periodD; } set { periodD = Math.Max(1, value); } } [Description("")] [Category("Parameters")] public int PeriodK { get { return periodK; } set { periodK = Math.Max(1, value); } } [Description("")] [Category("Parameters")] public int Smooth { get { return smooth; } set { smooth = Math.Max(1, value); } } [Description("")] [Category("Parameters")] public int TopLine { get { return topLine; } set { topLine = Math.Max(1, value); } } [Description("")] [Category("Parameters")] public int BottomLine { get { return bottomLine; } set { bottomLine = Math.Max(1, value); } } [COLOR=Red] [Description("")] [Category("Parameters")] public int UnrealizedPL { get { return unrealizedPL; } set { unrealizedPL = Math.Max(1, value); } } [Description("")] [Category("Parameters")] public bool AFlag1 { get { return aFlag1; } set { aFlag1 = value; } }[/COLOR] [Description("")] [Category("Parameters")] [COLOR=Red]public[/COLOR] double TrailStop { get { return trailStop; } set { trailStop = Math.Max(0.00, value); } } [Description("")] [Category("Parameters")] [COLOR=Red]public[/COLOR] double PrevValue { get { return prevValue; } set { prevValue = Math.Max(0.00, value); } } [Description("")] [Category("Parameters")] public double TrailStopPercentage { get { return trailStopPercentage; } set { trailStopPercentage = Math.Max(0.00, value); } } [Description("")] [Category("Parameters")] [COLOR=Red]public [/COLOR]bool JustEntered { get { return justEntered; } set { justEntered = value; } } [Description("")] [Category("Parameters")] [COLOR=Red] public[/COLOR] bool ExitFlag { get { return exitFlag; } set { exitFlag = value; } } [Description("")] [Category("Parameters")] public double SafetyTrailingStop { get { return safetyTrailingStop; } set { safetyTrailingStop = Math.Max(0.00, value); } } [Description("")] [Category("Parameters")] public double ProfitTarget2 { get { return profitTarget2; } set { profitTarget2 = Math.Max(0.005, value); } } #endregion }
Comment
-
3. Variables are public in the Properties so you can access them and change them in the Strategy selection window. This effectively creates them as user defined parameters. As far as why flags are there I have not followed the code intimately so I would not know. Hope that helps.Josh P.NinjaTrader Customer Service
Comment
-
Thanks Josh,
re 3: I should have formulated better. As far as I can see, these variables are set and overridden in the OnBarUpdate logic, so to me it does not make sense having them as Public and making the list in the optimizing windows larger then necessary.
But I might miss something and it is there on purpose ... hence the question to Sauer.
Comment
Latest Posts
Collapse
Topics | Statistics | Last Post | ||
---|---|---|---|---|
Started by Irukandji, 05-06-2024, 03:06 PM
|
3 responses
27 views
0 likes
|
Last Post Today, 09:36 AM | ||
Started by RamiRK86, 05-06-2024, 08:05 AM
|
2 responses
31 views
0 likes
|
Last Post
by RamiRK86
Today, 09:35 AM
|
||
Started by synthhokie, Today, 09:24 AM
|
1 response
20 views
0 likes
|
Last Post Today, 09:30 AM | ||
Started by sofortune, Yesterday, 09:49 PM
|
4 responses
17 views
0 likes
|
Last Post Today, 09:27 AM | ||
Started by phayes, Today, 09:13 AM
|
2 responses
25 views
0 likes
|
Last Post
by phayes
Today, 09:22 AM
|
Comment