Flatten everything once unrealized P/L reaches a certain number - futures io
futures io futures trading



Flatten everything once unrealized P/L reaches a certain number


Discussion in NinjaTrader

Updated by CannonTrading
      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 1,428 views
    2. thumb_up 8 thanks given
    3. group 5 followers
    1. forum 22 replies
    2. attach_file 1 attachments




Welcome to futures io: the largest futures trading community on the planet, with well over 100,000 members
  • Genuine reviews from real traders, not fake reviews from stealth vendors
  • Quality education from leading professional traders
  • We are a friendly, helpful, and positive community
  • We do not tolerate rude behavior, trolling, or vendors advertising in posts
  • We are here to help, just let us know what you need
You'll need to register in order to view the content of the threads and start contributing to our community.  It's free and simple.

-- Big Mike, Site Administrator

(If you already have an account, login at the top of the page)

 
Search this Thread
 

Flatten everything once unrealized P/L reaches a certain number

(login for full post details)
  #1 (permalink)
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
 
Posts: 36 since Dec 2014
Thanks: 9 given, 2 received

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!

Reply With Quote

Can you help answer these questions
from other members on futures io?
Degiro Negative Balance Advice
Traders Hideout
QDEL
Stocks and ETFs
Dollar crash in 2021
Currencies
Macros for flatten and reverse
TradeStation
3x Fangdango
Traders Hideout
 
Best Threads (Most Thanked)
in the last 7 days on futures io
VWAP for stock index futures trading?
41 thanks
Coronavirus COVID-19
20 thanks
Price Action Kewltech Style
19 thanks
Emini 4 Tick Scalp still valid?
17 thanks
Is back testing a waste of time?
13 thanks
 
(login for full post details)
  #2 (permalink)
Site Moderator
 
 
sam028's Avatar
 
Posts: 3,639 since Jun 2009
Thanks: 3,767 given, 4,445 received


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
The following 2 users say Thank You to sam028 for this post:
 
(login for full post details)
  #3 (permalink)
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
 
Posts: 36 since Dec 2014
Thanks: 9 given, 2 received



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.

Reply With Quote
 
(login for full post details)
  #4 (permalink)
Site Moderator
 
 
sam028's Avatar
 
Posts: 3,639 since Jun 2009
Thanks: 3,767 given, 4,445 received


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
 
(login for full post details)
  #5 (permalink)
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
 
Posts: 36 since Dec 2014
Thanks: 9 given, 2 received


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

Reply With Quote
 
(login for full post details)
  #6 (permalink)
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
 
Posts: 36 since Dec 2014
Thanks: 9 given, 2 received


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

Reply With Quote
 
(login for full post details)
  #7 (permalink)
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
 
Posts: 36 since Dec 2014
Thanks: 9 given, 2 received


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.

Reply With Quote
 
(login for full post details)
  #8 (permalink)
Site Moderator
 
 
sam028's Avatar
 
Posts: 3,639 since Jun 2009
Thanks: 3,767 given, 4,445 received


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
 
(login for full post details)
  #9 (permalink)
Toronto, Ontario/Canada
 
Experience: Intermediate
Platform: TOS
Trading: stocks
 
Posts: 36 since Dec 2014
Thanks: 9 given, 2 received


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?

Reply With Quote
 
(login for full post details)
  #10 (permalink)
Site Moderator
 
 
sam028's Avatar
 
Posts: 3,639 since Jun 2009
Thanks: 3,767 given, 4,445 received



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
The following 2 users say Thank You to sam028 for this post:


futures io Trading Community Platforms and Indicators NinjaTrader > Flatten everything once unrealized P/L reaches a certain number


December 3, 2019


Upcoming Webinars and Events
 

An Afternoon With futures io member TropicalTrader

Elite only
     



Copyright © 2020 by futures io, s.a., Av Ricardo J. Alfaro, Century Tower, Panama, +507 833-9432, info@futures.io
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.
no new posts