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
Daily loss limit examples
Collapse
X
-
Hello zrobfrank,
How do you know this variable is not being reset when the primary series is the first bar of a new session?
Print the bar time and the value of this variable after resetting it to confirm when and if it is being reset.
Save the output to a text file (right-click the output window select Save as) and attach this to your next post.
-
I've included a stripped down version of the script below.
Code:private double currentPnL; protected override void OnStateChange() { if (State == State.SetDefaults) { Description = @"Enter the description for your new custom Strategy here."; Name = "zzzzzzzzzzzzrandom2"; Calculate = Calculate.OnEachTick; EntriesPerDirection = 3; EntryHandling = EntryHandling.AllEntries; IsExitOnSessionCloseStrategy = true; ExitOnSessionCloseSeconds = 30; IsFillLimitOnTouch = false; MaximumBarsLookBack = MaximumBarsLookBack.Infinite; OrderFillResolution = OrderFillResolution.Standard; // OrderFillResolutionType = BarsPeriodType.Tick; // OrderFillResolutionValue = 1; Slippage = 1; StartBehavior = StartBehavior.WaitUntilFlatSynchronizeAccount; IsAdoptAccountPositionAware = true; IncludeCommission = true; TimeInForce = TimeInForce.Day; TraceOrders = true; RealtimeErrorHandling = RealtimeErrorHandling.StopCancelCloseIgnoreRejects; StopTargetHandling = StopTargetHandling.ByStrategyPosition; BarsRequiredToTrade = 20; // Disable this property for performance gains in Strategy Analyzer optimizations // See the Help Guide for additional information IsInstantiatedOnEachOptimizationIteration = true; LossLimit = 300; ProfitLimit = 12000; } else if (State == State.Configure) { AddDataSeries(Data.BarsPeriodType.Tick, 20); } else if (State == State.DataLoaded) { ClearOutputWindow(); } } protected override void OnBarUpdate() { if (CurrentBars[0] < 20 ) return; // at the start of a new session, reset the currentPnL for a new day of trading if (Bars.IsFirstBarOfSession && BarsInProgress == 0) currentPnL = 0; if(BarsInProgress == 0 && IsFirstTickOfBar == true) { SetProfitTarget("Long", CalculationMode.Ticks, 20, false); SetProfitTarget("Short", CalculationMode.Ticks, 20, false); } #region Time // Time if (((ToTime(Time[0]) >= 125900 && ToTime(Time[0]) < 150000)) && (Position.MarketPosition != MarketPosition.Flat)) //&& BarsInProgress == 0) { if (Position.MarketPosition == MarketPosition.Long) { ExitLong(0, Position.Quantity, "time", ""); } else if (Position.MarketPosition == MarketPosition.Short) { ExitShort(0, Position.Quantity, "time", ""); } } #endregion if ( ( (ToTime(Time[0]) > 50000 && ToTime(Time[0]) < 93000)) && Position.Quantity < 3 && currentPnL > -LossLimit && currentPnL < ProfitLimit && BarsInProgress == 0 && (BarsSinceEntryExecution(0, "Long", 0) > 5 || BarsSinceEntryExecution(0, "Long", 0) == -1)) { if( Close[1] > Open[1] ) { EnterLong(1,Convert.ToInt32(DefaultQuantity),"Long"); Draw.Diamond(this, "tag1" + CurrentBar, true, 0, Low[0] - TickSize, Brushes.Green); Print(currentPnL); } } if (Position.MarketPosition == MarketPosition.Long && (currentPnL + Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0])) <= -LossLimit) { //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()); Print(currentPnL); ExitLong("Daily Limit Exit", "Long"); } if (Position.Quantity > 1 && BarsInProgress == 0 && Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) > 0 && Close[0] < Open[0] && Close[1] < Open[1] ) { ExitLong("Long"); } if ( ( (ToTime(Time[0]) > 50000 && ToTime(Time[0]) < 93000)) && Position.Quantity < 3 && currentPnL > -LossLimit && currentPnL < ProfitLimit && BarsInProgress == 0 && (BarsSinceEntryExecution(0, "Short", 0) > 5 || BarsSinceEntryExecution(0, "Short", 0) == -1)) { if( Close[1] < Open[1] ) { // SetStopLoss("Long", CalculationMode.Price, Low[2] - .5, false); // EnterShortStopLimit(0,false, Convert.ToInt32(DefaultQuantity) , Low[0] + (5 * TickSize), Low[0] + (2 * TickSize), "Short"); EnterShort(1,Convert.ToInt32(DefaultQuantity),"Short"); // entryOrder = EnterLong(Convert.ToInt32(Quant),"Long"); // Draw.Diamond(this,"tag" + CurrentBar, true, 0, High[0] + TickSize, Brushes.Red); } } if (Position.MarketPosition == MarketPosition.Short && (currentPnL + Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0])) <= -LossLimit) { //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()); Print(currentPnL); LongTradeSwitch = false; ShortTradeSwitch = false; // ExitShort("Daily Limit Exit", "Short"); } if (Position.Quantity > 1 && BarsInProgress == 0 && Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) > 0 && Close[0] > Open[0] && Close[1] > Open[1] ) { ExitShort("Short"); } } protected override void OnPositionUpdate(Position position, double averagePrice, int quantity, MarketPosition marketPosition) { if (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()); Print(currentPnL); } } }
Leave a comment:
-
Hello zrobfrank,
In the DailyLossLimitExample the currentPnL variable is reset on the first bar of a new session on lines 53-54.
Is your script also resetting this variable on the first bar of a new session?
What code is in your script?
Leave a comment:
-
I have tested this script several times and it behaves as expected. However, when incorporating into my own strategy, it does not work and I cannot figure out for the life of me why not. I've added several prints to debug, and it seems like it doesn't reset the currentPnL to 0 at the proper time. Basically, it will close a trade and draw the correct text on the chart, and then the next time entry conditions are met it will enter again. I have triple checked that I have cut and pasted all the neccessary language from this script. Any advice would be greatly appreciated. Thanks.
Leave a comment:
-
Hello claudiorrb21,
This is expected. The SystemPerformance collection holds all trades, historical and real-time, submitted by the strategy since it was enabled.
When the strategy is disabled and re-enabled, the strategy recalculates the historical data and trades.
If you need the strategy to remember something, you would need to write and read that from a text file.
Leave a comment:
-
Hi!
I'm using this to check the profit, but for any reason I disable the strategy and it resets. How can I solve this problem?
SystemPerformance.AllTrades.TradesPerformance.Curr ency.CumProfit
Leave a comment:
-
Hello cpppower,
When Calculate is OnEachTick in realtime Close[0] refers to the current price (the close of the building bar is the current price).
In historical without tickreplay this is the close of the previously most fully closed bar. With TickReplay this is the current price.
Leave a comment:
-
Many thanks for your replay!
Many thanks for your reply! I think I have found the reason for lack of accuracy at my end.
My strategy is running onEachTick and I use "DailyLossLimitMultiTradeExample" to exit currently running position when the total daily loss/profit reaches certain level.
But when the strategy reads this data (currentPnL + Position.GetUnrealizedProfitLoss(PerformanceUnit.C urrency, Close[0])) <= (-LossLimit)) to close running position it is always late (unaccurate).
And here is my concerne: Close[0] in this example (when strategy works onEachTick) refers to current price or it is waiting for bar close?​
Leave a comment:
-
Hello cpppower,
Welcome to the NinjaTrader forums.
In the DailyLossLimitMultiTradeExample the currentPnL is assigned the trade profit (thisTrade.ProfitCurrency) one line 120 which would be for all contracts.
This is added with the Position.GetUnrealizedProfitLoss() of the position, for all contracts.
Testing this original script on my end I am not seeing any unexpected behavior.
Note, partial fills will cause separate trades to appear in the SystemPerformance collection. You may want to only add the PnL of a trade once the exit order has fully filled.
With your custom script, add prints to find out what is incorrect.
https://ninjatrader.com/support/foru...121#post791121
This example linked below, also has some sample code for working with part fills.
Leave a comment:
-
The script "DailyLossLimitMultiTradeExample_NT8" is completely losing accuracy when trading more than 1 contract according to logic below (where Contract1s=3, Contracts2=2, etc. )
if (entryOrders[1] == null) {entryOrders[1] = EnterLong(Convert.ToInt32(Contracts1), @"LongTP1");}
if (Contracts2 != 0 && TP2 > 0) {if (entryOrders[2] == null) {entryOrders[2] = EnterLong(Convert.ToInt32(Contracts2), @"LongTP2");}}
if (Contracts3 != 0 && TP3 > 0) {if (entryOrders[3] == null) {entryOrders[3] = EnterLong(Convert.ToInt32(Contracts3), @"LongTP3");}}
Do you know why it happens? Especially when 3 (4 or 5...) contracts order is not filled at once but is filled partially.​
Leave a comment:
-
Hello elic1968,
Our examples are created for you to learn from. They are not intended to be actually traded.
Please open the script in the Strategy Builder and learn from the logic implemented in the Conditions and Actions so that you fully understand how the script works.
Once you have an understanding of how the script works, use that knowledge to create your own script with your own custom logic.
- Likes 1
Leave a comment:
-
Hey Chelsea, I have downloaded the daily PnL script and have it as an independent strategy on my strategy builder strategies menu. What should I do in order to incorporate into an existing strategy that I have already structured?
Leave a comment:
-
Hello elic1968,
I've added the links in post # 1.
As a heads up, you cannot download files from the forum until you have completed the registration process by clicking the link in the registration email.
Leave a comment:
-
Chelsea thanks. I'm aware of the process. Problem I cant download the file (not getting the option). Could you please place it once again?
Leave a comment:
-
Hello elic1968,
To import a NinjaScript into NinjaTrader 8 do the following:- Download the script to your desktop, keep it in the compressed .zip file.
- From the Control Center window select Tools -> Import -> NinjaScript...
- Click the Desktop icon on the left to navigate to the desktop
- Select the downloaded .zip file -> then click Open
- NinjaTrader will then confirm if the import has been successful.
Below is a link to the help guide on importing NinjaScripts.
https://ninjatrader.com/support/help...-us/import.htm
The DailyLossLimitMultiTradeExample_NT8 and DailyLossLimitExample_NT8 can be viewed in the NinjaScript Editor.
New -> NinjaScript Editor -> Strategies -> DailyLossLimitExample.
The DailyLossLimitBuilderExample_NT8 can be viewed in the Strategy Builder.
New -> Strategy Builder -> select DailyLossLimitBuilderExample from the drop-down on the Welcome page.
These strategies can be run on a chart or backtested in the Strategy Analyzer.
Leave a comment:
Latest Posts
Collapse
Topics | Statistics | Last Post | ||
---|---|---|---|---|
Started by quantismo, 04-17-2024, 05:13 PM
|
3 responses
25 views
0 likes
|
Last Post Today, 05:23 AM | ||
Started by ScottWalsh, 04-16-2024, 04:29 PM
|
7 responses
34 views
0 likes
|
Last Post Today, 05:15 AM | ||
Started by cls71, Today, 04:45 AM
|
0 responses
5 views
0 likes
|
Last Post
by cls71
Today, 04:45 AM
|
||
Started by mjairg, 07-20-2023, 11:57 PM
|
3 responses
214 views
1 like
|
Last Post
by PaulMohn
Today, 04:22 AM
|
||
Started by TheWhiteDragon, 01-21-2019, 12:44 PM
|
4 responses
547 views
0 likes
|
Last Post
by PaulMohn
Today, 04:09 AM
|
Leave a comment: