NexusFi: Find Your Edge


Home Menu

 





Flatten everything once unrealized P/L reaches a certain number


Discussion in NinjaTrader

Updated
      Top Posters
    1. looks_one runit with 13 posts (0 thanks)
    2. looks_two sam028 with 7 posts (7 thanks)
    3. looks_3 pstrusi with 2 posts (0 thanks)
    4. looks_4 CannonTrading with 1 posts (1 thanks)
    1. trending_up 5,318 views
    2. thumb_up 8 thanks given
    3. group 5 followers
    1. forum 22 posts
    2. attach_file 1 attachments




 
Search this Thread

Flatten everything once unrealized P/L reaches a certain number

  #1 (permalink)
 runit 
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
Posts: 38 since Dec 2014
Thanks Given: 10
Thanks Received: 3

Is it possible to automatically set NT8 to flatten all of my account positions once the unrealized P/L reaches a certain $ value? And if so, does the platform need to continue running on the computer?

Thank you!

Started this thread Reply With Quote

Can you help answer these questions
from other members on NexusFi?
NT7 Indicator Script Troubleshooting - Camarilla Pivots
NinjaTrader
ZombieSqueeze
Platforms and Indicators
MC PL editor upgrade
MultiCharts
Trade idea based off three indicators.
Traders Hideout
How to apply profiles
Traders Hideout
 
Best Threads (Most Thanked)
in the last 7 days on NexusFi
Spoo-nalysis ES e-mini futures S&P 500
33 thanks
Just another trading journal: PA, Wyckoff & Trends
28 thanks
Tao te Trade: way of the WLD
23 thanks
Bigger Wins or Fewer Losses?
23 thanks
GFIs1 1 DAX trade per day journal
21 thanks
  #2 (permalink)
 
sam028's Avatar
 sam028 
Site Moderator
 
Posts: 3,765 since Jun 2009
Thanks Given: 3,825
Thanks Received: 4,629


runit View Post
Is it possible to automatically set NT8 to flatten all of my account positions once the unrealized P/L reaches a certain $ value? And if so, does the platform need to continue running on the computer?

Thank you!

It's possible in creating a strategy where its only goal would be to check the PnL of all your open positions and close them if the $ value is reached.

Success requires no deodorant! (Sun Tzu)
Follow me on Twitter Reply With Quote
Thanked by:
  #3 (permalink)
 runit 
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
Posts: 38 since Dec 2014
Thanks Given: 10
Thanks Received: 3



sam028 View Post
It's possible in creating a strategy where its only goal would be to check the PnL of all your open positions and close them if the $ value is reached.

Could you please clarify on how this would be done? When I looked into it, it was for one particular instrument. I have more than one instrument running at the same time. It seems like a simple solution - I'd appreciate the help.

Started this thread Reply With Quote
  #4 (permalink)
 
sam028's Avatar
 sam028 
Site Moderator
 
Posts: 3,765 since Jun 2009
Thanks Given: 3,825
Thanks Received: 4,629


runit View Post
Could you please clarify on how this would be done? When I looked into it, it was for one particular instrument. I have more than one instrument running at the same time. It seems like a simple solution - I'd appreciate the help.

You can use Account.positions. With this you can see the positions for all instruments, not only the one you're running the "fake" strategy on.
I'm not sure we can say it's a simple solution but that's the only one I have in mind.

Success requires no deodorant! (Sun Tzu)
Follow me on Twitter Reply With Quote
  #5 (permalink)
 runit 
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
Posts: 38 since Dec 2014
Thanks Given: 10
Thanks Received: 3


sam028 View Post
You can use Account.positions. With this you can see the positions for all instruments, not only the one you're running the "fake" strategy on.
I'm not sure we can say it's a simple solution but that's the only one I have in mind.

I'm not sure I'm doing this correctly. Could you assist please?

#region Using declarations
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
using NinjaTrader.Gui;
using NinjaTrader.Gui.Chart;
using NinjaTrader.Gui.SuperDom;
using NinjaTrader.Gui.Tools;
using NinjaTrader.Data;
using NinjaTrader.NinjaScript;
using NinjaTrader.Core.FloatingPoint;
using NinjaTrader.NinjaScript.Indicators;
using NinjaTrader.NinjaScript.DrawingTools;
#endregion

//This namespace holds Strategies in this folder and is required. Do not change it.
namespace NinjaTrader.NinjaScript.Strategies
{
public class accpositions : Strategy
{
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Description = @"Enter the description for your new custom Strategy here.";
Name = "accpositions";
Calculate = Calculate.OnEachTick;
EntriesPerDirection = 1;
EntryHandling = EntryHandling.AllEntries;
IsExitOnSessionCloseStrategy = false;
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.ByStrategyPosition;
BarsRequiredToTrade = 20;
// Disable this property for performance gains in Strategy Analyzer optimizations
// See the Help Guide for additional information
IsInstantiatedOnEachOptimizationIteration = true;
}
else if (State == State.Configure)
{
AddDataSeries(Data.BarsPeriodType.Minute, 1);
}
}

protected override void OnBarUpdate()
{
if (BarsInProgress != 0)
return;

if (CurrentBars[0] < 1)
return;

// Set 1
if (Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Close[0]) >= 100)
{
ExitLong(Convert.ToInt32(DefaultQuantity), "", "");
ExitShort(Convert.ToInt32(DefaultQuantity), "", "");
}

}
}
}

#region Wizard settings, neither change nor remove
/*@
<?xml version="1.0"?>
<ScriptProperties xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Calculate>OnEachTick</Calculate>
<ConditionalActions>
<ConditionalAction>
<Actions>
<WizardAction>
<Children />
<IsExpanded>false</IsExpanded>
<IsSelected>true</IsSelected>
<Name>Exit long position</Name>
<OffsetType>Arithmetic</OffsetType>
<ActionProperties>
<DashStyle>Solid</DashStyle>
<DivideTimePrice>false</DivideTimePrice>
<Id />
<File />
<IsAutoScale>false</IsAutoScale>
<IsSimulatedStop>false</IsSimulatedStop>
<IsStop>false</IsStop>
<LogLevel>Information</LogLevel>
<Mode>Currency</Mode>
<OffsetType>Currency</OffsetType>
<Priority>Medium</Priority>
<Quantity>
<DefaultValue>0</DefaultValue>
<IsInt>true</IsInt>
<DynamicValue>
<Children />
<IsExpanded>false</IsExpanded>
<IsSelected>false</IsSelected>
<Name>Default order quantity</Name>
<OffsetType>Arithmetic</OffsetType>
<AssignedCommand>
<Command>DefaultQuantity</Command>
<Parameters />
</AssignedCommand>
<BarsAgo>0</BarsAgo>
<CurrencyType>Currency</CurrencyType>
<Date>2019-11-22T09:53:48.865809</Date>
<DayOfWeek>Sunday</DayOfWeek>
<EndBar>0</EndBar>
<ForceSeriesIndex>false</ForceSeriesIndex>
<LookBackPeriod>0</LookBackPeriod>
<MarketPosition>Long</MarketPosition>
<Period>0</Period>
<ReturnType>Number</ReturnType>
<StartBar>0</StartBar>
<State>Undefined</State>
<Time>0001-01-01T00:00:00</Time>
</DynamicValue>
<IsLiteral>false</IsLiteral>
<LiveValue xsi:type="xsd:string">DefaultQuantity</LiveValue>
</Quantity>
<ServiceName />
<ScreenshotPath />
<SoundLocation />
<Tag>
<SeparatorCharacter> </SeparatorCharacter>
<Strings>
<NinjaScriptString>
<Index>0</Index>
<StringValue>Set Exit long position</StringValue>
</NinjaScriptString>
</Strings>
</Tag>
<TextPosition>BottomLeft</TextPosition>
<VariableDateTime>2019-11-22T09:53:48.865809</VariableDateTime>
<VariableBool>false</VariableBool>
</ActionProperties>
<ActionType>Exit</ActionType>
<Command>
<Command>ExitLong</Command>
<Parameters>
<string>quantity</string>
<string>signalName</string>
<string>fromEntrySignal</string>
</Parameters>
</Command>
</WizardAction>
<WizardAction>
<Children />
<IsExpanded>false</IsExpanded>
<IsSelected>true</IsSelected>
<Name>Exit short position</Name>
<OffsetType>Arithmetic</OffsetType>
<ActionProperties>
<DashStyle>Solid</DashStyle>
<DivideTimePrice>false</DivideTimePrice>
<Id />
<File />
<IsAutoScale>false</IsAutoScale>
<IsSimulatedStop>false</IsSimulatedStop>
<IsStop>false</IsStop>
<LogLevel>Information</LogLevel>
<Mode>Currency</Mode>
<OffsetType>Currency</OffsetType>
<Priority>Medium</Priority>
<Quantity>
<DefaultValue>0</DefaultValue>
<IsInt>true</IsInt>
<DynamicValue>
<Children />
<IsExpanded>false</IsExpanded>
<IsSelected>false</IsSelected>
<Name>Default order quantity</Name>
<OffsetType>Arithmetic</OffsetType>
<AssignedCommand>
<Command>DefaultQuantity</Command>
<Parameters />
</AssignedCommand>
<BarsAgo>0</BarsAgo>
<CurrencyType>Currency</CurrencyType>
<Date>2019-11-22T09:55:32.3623877</Date>
<DayOfWeek>Sunday</DayOfWeek>
<EndBar>0</EndBar>
<ForceSeriesIndex>false</ForceSeriesIndex>
<LookBackPeriod>0</LookBackPeriod>
<MarketPosition>Long</MarketPosition>
<Period>0</Period>
<ReturnType>Number</ReturnType>
<StartBar>0</StartBar>
<State>Undefined</State>
<Time>0001-01-01T00:00:00</Time>
</DynamicValue>
<IsLiteral>false</IsLiteral>
<LiveValue xsi:type="xsd:string">DefaultQuantity</LiveValue>
</Quantity>
<ServiceName />
<ScreenshotPath />
<SoundLocation />
<Tag>
<SeparatorCharacter> </SeparatorCharacter>
<Strings>
<NinjaScriptString>
<Index>0</Index>
<StringValue>Set Exit short position</StringValue>
</NinjaScriptString>
</Strings>
</Tag>
<TextPosition>BottomLeft</TextPosition>
<VariableDateTime>2019-11-22T09:55:32.3623877</VariableDateTime>
<VariableBool>false</VariableBool>
</ActionProperties>
<ActionType>Exit</ActionType>
<Command>
<Command>ExitShort</Command>
<Parameters>
<string>quantity</string>
<string>signalName</string>
<string>fromEntrySignal</string>
</Parameters>
</Command>
</WizardAction>
</Actions>
<AnyOrAll>Any</AnyOrAll>
<Conditions>
<WizardConditionGroup>
<AnyOrAll>Any</AnyOrAll>
<Conditions>
<WizardCondition>
<LeftItem xsi:type="WizardConditionItem">
<Children />
<IsExpanded>false</IsExpanded>
<IsSelected>true</IsSelected>
<Name>Unrealized PnL</Name>
<OffsetType>Arithmetic</OffsetType>
<AssignedCommand>
<Command>Position.GetUnrealizedProfitLoss(PerformanceUnit.{0}, {1})</Command>
<Parameters>
<string>CurrencyType</string>
<string>Series1</string>
<string>BarsAgo</string>
</Parameters>
</AssignedCommand>
<BarsAgo>0</BarsAgo>
<CurrencyType>Currency</CurrencyType>
<Date>2019-11-22T09:49:17.2606251</Date>
<DayOfWeek>Sunday</DayOfWeek>
<EndBar>0</EndBar>
<ForceSeriesIndex>false</ForceSeriesIndex>
<LookBackPeriod>0</LookBackPeriod>
<MarketPosition>Long</MarketPosition>
<Period>0</Period>
<ReturnType>Number</ReturnType>
<StartBar>0</StartBar>
<State>Undefined</State>
<Time>0001-01-01T00:00:00</Time>
</LeftItem>
<Lookback>1</Lookback>
<Operator>GreaterEqual</Operator>
<RightItem xsi:type="WizardConditionItem">
<Children />
<IsExpanded>false</IsExpanded>
<IsSelected>true</IsSelected>
<Name>Numeric value</Name>
<OffsetType>Arithmetic</OffsetType>
<AssignedCommand>
<Command>{0}</Command>
<Parameters>
<string>NumericValue</string>
</Parameters>
</AssignedCommand>
<BarsAgo>0</BarsAgo>
<CurrencyType>Currency</CurrencyType>
<Date>2019-11-22T09:49:17.2705892</Date>
<DayOfWeek>Sunday</DayOfWeek>
<EndBar>0</EndBar>
<ForceSeriesIndex>false</ForceSeriesIndex>
<LookBackPeriod>0</LookBackPeriod>
<MarketPosition>Long</MarketPosition>
<NumericValue>
<DefaultValue>0</DefaultValue>
<IsInt>false</IsInt>
<IsLiteral>true</IsLiteral>
<LiveValue xsi:type="xsd:string">100</LiveValue>
</NumericValue>
<Period>0</Period>
<ReturnType>Number</ReturnType>
<StartBar>0</StartBar>
<State>Undefined</State>
<Time>0001-01-01T00:00:00</Time>
</RightItem>
</WizardCondition>
</Conditions>
<IsGroup>false</IsGroup>
<DisplayName>Position.GetUnrealizedProfitLoss(PerformanceUnit.Currency, Default input[0]) &gt;= 100</DisplayName>
</WizardConditionGroup>
</Conditions>
<SetName>Set 1</SetName>
<SetNumber>1</SetNumber>
</ConditionalAction>
</ConditionalActions>
<CustomSeries />
<DataSeries>
<DataSeriesProperties>
<InstrumentName>&lt;Primary&gt;</InstrumentName>
<PriceBasedOn xsi:nil="true" />
<SameAsPrimary>true</SameAsPrimary>
<Type>Minute</Type>
<Value>1</Value>
</DataSeriesProperties>
</DataSeries>
<Description>Enter the description for your new custom Strategy here.</Description>
<DisplayInDataBox>true</DisplayInDataBox>
<DrawHorizontalGridLines>true</DrawHorizontalGridLines>
<DrawOnPricePanel>true</DrawOnPricePanel>
<DrawVerticalGridLines>true</DrawVerticalGridLines>
<EntriesPerDirection>1</EntriesPerDirection>
<EntryHandling>AllEntries</EntryHandling>
<ExitOnSessionClose>false</ExitOnSessionClose>
<ExitOnSessionCloseSeconds>30</ExitOnSessionCloseSeconds>
<FillLimitOrdersOnTouch>false</FillLimitOrdersOnTouch>
<InputParameters />
<IsTradingHoursBreakLineVisible>true</IsTradingHoursBreakLineVisible>
<IsInstantiatedOnEachOptimizationIteration>true</IsInstantiatedOnEachOptimizationIteration>
<MaximumBarsLookBack>TwoHundredFiftySix</MaximumBarsLookBack>
<MinimumBarsRequired>20</MinimumBarsRequired>
<OrderFillResolution>Standard</OrderFillResolution>
<OrderFillResolutionValue>1</OrderFillResolutionValue>
<OrderFillResolutionType>Minute</OrderFillResolutionType>
<OverlayOnPrice>false</OverlayOnPrice>
<PaintPriceMarkers>true</PaintPriceMarkers>
<PlotParameters />
<RealTimeErrorHandling>StopCancelClose</RealTimeErrorHandling>
<ScaleJustification>Right</ScaleJustification>
<ScriptType>Strategy</ScriptType>
<Slippage>0</Slippage>
<StartBehavior>WaitUntilFlat</StartBehavior>
<StopsAndTargets />
<StopTargetHandling>ByStrategyPosition</StopTargetHandling>
<TimeInForce>Gtc</TimeInForce>
<TraceOrders>false</TraceOrders>
<UseOnAddTradeEvent>false</UseOnAddTradeEvent>
<UseOnAuthorizeAccountEvent>false</UseOnAuthorizeAccountEvent>
<UseAccountItemUpdate>false</UseAccountItemUpdate>
<UseOnCalculatePerformanceValuesEvent>true</UseOnCalculatePerformanceValuesEvent>
<UseOnConnectionEvent>false</UseOnConnectionEvent>
<UseOnDataPointEvent>true</UseOnDataPointEvent>
<UseOnFundamentalDataEvent>false</UseOnFundamentalDataEvent>
<UseOnExecutionEvent>false</UseOnExecutionEvent>
<UseOnMouseDown>true</UseOnMouseDown>
<UseOnMouseMove>true</UseOnMouseMove>
<UseOnMouseUp>true</UseOnMouseUp>
<UseOnMarketDataEvent>false</UseOnMarketDataEvent>
<UseOnMarketDepthEvent>false</UseOnMarketDepthEvent>
<UseOnMergePerformanceMetricEvent>false</UseOnMergePerformanceMetricEvent>
<UseOnNextDataPointEvent>true</UseOnNextDataPointEvent>
<UseOnNextInstrumentEvent>true</UseOnNextInstrumentEvent>
<UseOnOptimizeEvent>true</UseOnOptimizeEvent>
<UseOnOrderUpdateEvent>false</UseOnOrderUpdateEvent>
<UseOnPositionUpdateEvent>false</UseOnPositionUpdateEvent>
<UseOnRenderEvent>true</UseOnRenderEvent>
<UseOnRestoreValuesEvent>false</UseOnRestoreValuesEvent>
<UseOnShareEvent>true</UseOnShareEvent>
<UseOnWindowCreatedEvent>false</UseOnWindowCreatedEvent>
<UseOnWindowDestroyedEvent>false</UseOnWindowDestroyedEvent>
<Variables />
<Name>accpositions</Name>
</ScriptProperties>
@*/
#endregion

Started this thread Reply With Quote
  #6 (permalink)
 runit 
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
Posts: 38 since Dec 2014
Thanks Given: 10
Thanks Received: 3


sam028 View Post
You can use Account.positions. With this you can see the positions for all instruments, not only the one you're running the "fake" strategy on.
I'm not sure we can say it's a simple solution but that's the only one I have in mind.

I found "unrealized P/L" - greater or equal to "numeric value", and if met, "exit long pos" "exit short pos". All of this running on "default instrument" at the start.

What did you have in mind?

Thank you

Started this thread Reply With Quote
  #7 (permalink)
 runit 
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
Posts: 38 since Dec 2014
Thanks Given: 10
Thanks Received: 3


runit View Post
I found "unrealized P/L" - greater or equal to "numeric value", and if met, "exit long pos" "exit short pos". All of this running on "default instrument" at the start.

What did you have in mind?

Thank you

What I was explaining above doesn't work. Need help.

Started this thread Reply With Quote
  #8 (permalink)
 
sam028's Avatar
 sam028 
Site Moderator
 
Posts: 3,765 since Jun 2009
Thanks Given: 3,825
Thanks Received: 4,629


runit View Post
What I was explaining above doesn't work. Need help.

It's not that simple, a strategy will only see its own instrument and its own PnL.

It should be something like this:
Account myAccount;
In OnStateChange() -> configure:
lock (Account.All)
myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");

In OnBarUpdate():
double PnL = 0;
foreach (Position position in myAccount.Positions) {
PnL+= position.GetUnrealizedProfitLoss(PerformanceUnit.Currency);
}
if (PnL > 1000)
....find the instruments/quantity/side of the open positions then close them with CreateOrder()

Success requires no deodorant! (Sun Tzu)
Follow me on Twitter Reply With Quote
  #9 (permalink)
 runit 
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
Posts: 38 since Dec 2014
Thanks Given: 10
Thanks Received: 3


sam028 View Post
It's not that simple, a strategy will only see its own instrument and its own PnL.

It should be something like this:
Account myAccount;
In OnStateChange() -> configure:
lock (Account.All)
myAccount = Account.All.FirstOrDefault(a => a.Name == "Sim101");

In OnBarUpdate():
double PnL = 0;
foreach (Position position in myAccount.Positions) {
PnL+= position.GetUnrealizedProfitLoss(PerformanceUnit.Currency);
}
if (PnL > 1000)
....find the instruments/quantity/side of the open positions then close them with CreateOrder()

Thank you. I'm quite new to NT and have zero coding experience. How can I create this strategy, step by step, if you you could please?

Started this thread Reply With Quote
  #10 (permalink)
 
sam028's Avatar
 sam028 
Site Moderator
 
Posts: 3,765 since Jun 2009
Thanks Given: 3,825
Thanks Received: 4,629



runit View Post
Thank you. I'm quite new to NT and have zero coding experience. How can I create this strategy, step by step, if you you could please?

For this specific need it's going to be too long to explain step by step, and if you're not experienced this kind of strategy is a bit dangerous.
If I have some free time I'll put a functional example in this thread.

Success requires no deodorant! (Sun Tzu)
Follow me on Twitter Reply With Quote
Thanked by:




Last Updated on December 3, 2019


© 2024 NexusFi™, s.a., All Rights Reserved.
Av Ricardo J. Alfaro, Century Tower, Panama City, Panama, Ph: +507 833-9432 (Panama and Intl), +1 888-312-3001 (USA and Canada)
All information is for educational use only and is not investment advice. There is a substantial risk of loss in trading commodity futures, stocks, options and foreign exchange products. Past performance is not indicative of future results.
About Us - Contact Us - Site Rules, Acceptable Use, and Terms and Conditions - Privacy Policy - Downloads - Top
no new posts