// LAYER 0 Guard for NinjaTrader 8 -- version 0.3
//
// Holds the limits a trader set on a calm day, inside the platform where
// the trades happen. Per account:
// - Daily loss limit: closed trades plus the open position. When it is
// reached, the position is flattened and every new order is cancelled
// until the next trading day (17:00 Chicago, the CME day).
// - Max trades a day: after the last allowed round trip closes, the
// account is locked for the rest of the day.
// - Lockout after a losing trade: 20, then 35, then 50 minutes (the same
// ladder as the LAYER 0 app; the settings can make it longer, not
// shorter). Orders that open or add are cancelled meanwhile.
// - Max contracts in a position: an order that would take the position
// past it is cancelled; if one fills anyway, the position is flattened.
// - No adding to a loser: an order that would add to a position while
// the account's open P&L is negative is cancelled.
// - Limits can be tightened during the day, never loosened: the day's
// limits are frozen when the trading day starts, so raising them in the
// settings file after a loss only counts from the next day. The same
// goes for switching a rule off or taking an account out of the file.
// - Orders that reduce a position (stops, targets, exits) are never
// blocked, so a lock can't leave a position unprotected.
//
// What it can't do: NinjaTrader has no hook to refuse an order before it is
// sent, so a blocked order is cancelled, and any position it opens is
// flattened, the moment NinjaTrader reports it. It only runs while
// NinjaTrader runs and only sees orders placed through NinjaTrader: keep
// the daily loss limit at the broker too.
//
// Settings: Documents\NinjaTrader 8\LAYER0Guard.xml (created on first run).
// Lock state survives a restart: Documents\NinjaTrader 8\LAYER0Guard.state.xml.
// Install: see README.md next to this file.
#region Using declarations
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Serialization;
using NinjaTrader.Cbi;
#endregion
namespace NinjaTrader.NinjaScript.AddOns
{
public class GuardAccountSettings
{
[XmlAttribute] public string Name = "Sim101";
/// Daily loss limit in dollars for this account; 0 turns it off.
[XmlAttribute] public double DailyLossLimit = 100;
/// Round trips allowed per trading day; 0 turns it off.
[XmlAttribute] public int MaxTradesPerDay = 3;
/// Largest position, in contracts; 0 turns it off.
[XmlAttribute] public int MaxContracts = 0;
/// Lock this account after a losing trade (20 / 35 / 50 minutes).
[XmlAttribute] public bool LockoutAfterLoss = true;
/// Cancel orders that add to a position while the account's open P&L is negative.
[XmlAttribute] public bool NoAddingToLoser = true;
}
public class GuardSettings
{
/// Minutes locked after the 1st, 2nd and 3rd-or-later losing trade of the day.
public int[] LockoutMinutes = { 20, 35, 50 };
public List Accounts = new List { new GuardAccountSettings() };
}
public class GuardAccountState
{
[XmlAttribute] public string Name;
[XmlAttribute] public string Day;
/// Sum of today's closed round trips, counted here rather than read from the account, so a platform restart that reports realized P&L from 0 again can't wipe the day's losses.
[XmlAttribute] public double TodayRealized;
[XmlAttribute] public double RealizedAtOpen;
[XmlAttribute] public int TradesToday;
[XmlAttribute] public int LossesToday;
[XmlAttribute] public bool InPosition;
/// A round trip closed and its result isn't counted yet (the P&L update can arrive after the position update).
[XmlAttribute] public bool PendingClose;
/// UTC ticks; 0 when not locked.
[XmlAttribute] public long LockedUntilUtc;
[XmlAttribute] public string LockReason = "";
/// The day's limits, frozen at the start of the trading day: they can be tightened during the day, never loosened (same rule as the LAYER 0 app).
[XmlAttribute] public double DayLossLimit;
[XmlAttribute] public int DayMaxTrades;
[XmlAttribute] public int DayMaxContracts;
[XmlAttribute] public bool DayLockoutAfterLoss;
[XmlAttribute] public bool DayNoAddingToLoser;
[XmlIgnore] public double Unrealized;
}
public class GuardState
{
public List Accounts = new List();
}
public class LAYER0Guard : AddOnBase
{
private static readonly string Folder = NinjaTrader.Core.Globals.UserDataDir;
private static readonly string SettingsPath = Path.Combine(Folder, "LAYER0Guard.xml");
private static readonly string StatePath = Path.Combine(Folder, "LAYER0Guard.state.xml");
// The CME day starts at 17:00 Chicago. Fixed, so the day can't be moved to reset a lock.
private const int DayStartHourChicago = 17;
// The shortest lockouts allowed; the settings file can only make them longer.
private static readonly int[] MinLockoutMinutes = { 20, 35, 50 };
private readonly object sync = new object();
private readonly HashSet watched = new HashSet();
private GuardSettings settings;
private GuardState state;
private TimeZoneInfo chicago;
// Orders this add-on submits itself while flattening are never cancelled.
private DateTime flatteningUntilUtc = DateTime.MinValue;
protected override void OnStateChange()
{
if (State == State.SetDefaults)
{
Name = "LAYER0Guard";
Description = "LAYER 0 Guard: daily loss limit, max trades, max contracts and post-loss lockout, held inside NinjaTrader.";
}
else if (State == State.Active)
{
chicago = FindChicago();
settings = LoadSettings();
state = Load(StatePath) ?? new GuardState();
List accounts;
lock (Account.All)
accounts = Account.All.ToList();
foreach (Account account in accounts)
Watch(account);
Account.AccountStatusUpdate += OnAccountStatusUpdate;
Print("LAYER 0 Guard 0.3 is running. Settings: " + SettingsPath);
}
else if (State == State.Terminated)
{
Account.AccountStatusUpdate -= OnAccountStatusUpdate;
lock (sync)
{
foreach (Account account in watched)
{
account.OrderUpdate -= OnOrderUpdate;
account.PositionUpdate -= OnPositionUpdate;
account.AccountItemUpdate -= OnAccountItemUpdate;
}
watched.Clear();
}
}
}
// ----- Accounts -----------------------------------------------------
private void OnAccountStatusUpdate(object sender, AccountStatusEventArgs e)
{
if (e.Account != null)
Watch(e.Account);
}
private void Watch(Account account)
{
if (account == null || Config(account) == null)
return;
lock (sync)
{
if (!watched.Add(account))
return;
account.OrderUpdate += OnOrderUpdate;
account.PositionUpdate += OnPositionUpdate;
account.AccountItemUpdate += OnAccountItemUpdate;
GuardAccountState s = StateFor(account);
bool inPosition = OpenPositions(account).Count > 0;
if (inPosition && !s.InPosition)
s.RealizedAtOpen = Realized(account);
s.InPosition = inPosition;
SaveState();
}
Print("LAYER 0 Guard is watching " + account.Name + ".");
}
/// The account's settings. An account taken out of the settings file stays guarded with the day's frozen limits until the next trading day.
private GuardAccountSettings Config(Account account)
{
if (settings == null)
return null;
GuardAccountSettings cfg = settings.Accounts.FirstOrDefault(a => string.Equals(a.Name, account.Name, StringComparison.OrdinalIgnoreCase));
if (cfg != null)
return cfg;
lock (sync)
{
GuardAccountState s = state == null ? null : state.Accounts.FirstOrDefault(a => a.Name == account.Name);
if (s == null || s.Day != TradingDay(DateTime.UtcNow))
return null;
return new GuardAccountSettings
{
Name = account.Name,
DailyLossLimit = s.DayLossLimit,
MaxTradesPerDay = s.DayMaxTrades,
MaxContracts = s.DayMaxContracts,
LockoutAfterLoss = s.DayLockoutAfterLoss,
NoAddingToLoser = s.DayNoAddingToLoser,
};
}
}
/// Call inside lock (sync).
private GuardAccountState StateFor(Account account)
{
string day = TradingDay(DateTime.UtcNow);
GuardAccountState s = state.Accounts.FirstOrDefault(a => a.Name == account.Name);
if (s == null)
{
s = new GuardAccountState { Name = account.Name, Day = day };
FreezeLimits(s, Config(account));
state.Accounts.Add(s);
}
if (s.Day != day)
{
// A new trading day: counts, limits and the day's lock start fresh.
s.Day = day;
s.TodayRealized = 0;
s.TradesToday = 0;
s.LossesToday = 0;
s.PendingClose = false;
s.LockedUntilUtc = 0;
s.LockReason = "";
FreezeLimits(s, Config(account));
}
return s;
}
private static double Realized(Account account)
{
return account.Get(AccountItem.RealizedProfitLoss, Currency.UsDollar);
}
private static List OpenPositions(Account account)
{
lock (account.Positions)
return account.Positions.Where(p => p.MarketPosition != MarketPosition.Flat).ToList();
}
// ----- Limits -------------------------------------------------------
private static void FreezeLimits(GuardAccountState s, GuardAccountSettings cfg)
{
s.DayLossLimit = cfg == null ? 0 : cfg.DailyLossLimit;
s.DayMaxTrades = cfg == null ? 0 : cfg.MaxTradesPerDay;
s.DayMaxContracts = cfg == null ? 0 : cfg.MaxContracts;
s.DayLockoutAfterLoss = cfg != null && cfg.LockoutAfterLoss;
s.DayNoAddingToLoser = cfg != null && cfg.NoAddingToLoser;
}
/// The stricter of two limits, where 0 means off.
private static double Tighter(double frozen, double current)
{
if (frozen <= 0) return current;
if (current <= 0) return frozen;
return Math.Min(frozen, current);
}
private static double LossLimit(GuardAccountState s, GuardAccountSettings cfg) { return Tighter(s.DayLossLimit, cfg.DailyLossLimit); }
private static int TradeLimit(GuardAccountState s, GuardAccountSettings cfg) { return (int)Tighter(s.DayMaxTrades, cfg.MaxTradesPerDay); }
private static int ContractLimit(GuardAccountState s, GuardAccountSettings cfg) { return (int)Tighter(s.DayMaxContracts, cfg.MaxContracts); }
// A switch turned on at the start of the day stays on until the next one.
private static bool LockoutOn(GuardAccountState s, GuardAccountSettings cfg) { return s.DayLockoutAfterLoss || cfg.LockoutAfterLoss; }
private static bool NoAddingOn(GuardAccountState s, GuardAccountSettings cfg) { return s.DayNoAddingToLoser || cfg.NoAddingToLoser; }
/// Today's P&L: closed round trips, plus what the open position has realized (scale-outs) and, with withOpen, its open P&L. Call inside lock (sync).
private static double Today(Account account, GuardAccountState s, bool withOpen)
{
if (!s.InPosition)
return s.TodayRealized;
return s.TodayRealized + Realized(account) - s.RealizedAtOpen + (withOpen ? s.Unrealized : 0);
}
/// Locks the account for the day if today's P&L is at the loss limit. Returns true when it just locked. Call inside lock (sync).
/// Count the open P&L too. Off on a realized update: the open P&L seen last may still include what was just realized.
private bool CheckLossLimit(Account account, GuardAccountState s, GuardAccountSettings cfg, bool withOpen)
{
double lossLimit = LossLimit(s, cfg);
double today = Today(account, s, withOpen);
if (lossLimit <= 0 || IsLockedForDay(s) || today > -lossLimit)
return false;
LockForDay(s, "daily loss limit reached (" + Money(today) + ")");
return true;
}
// ----- Events -------------------------------------------------------
private void OnPositionUpdate(object sender, PositionEventArgs e)
{
Account account = sender as Account;
GuardAccountSettings cfg = account == null ? null : Config(account);
if (cfg == null)
return;
List open = OpenPositions(account);
bool flattenNow = false;
lock (sync)
{
GuardAccountState s = StateFor(account);
if (!s.InPosition && open.Count > 0)
{
s.InPosition = true;
s.TradesToday++;
s.RealizedAtOpen = Realized(account);
if (IsLocked(s))
flattenNow = true; // a position opened while locked
}
else if (s.InPosition && open.Count == 0)
{
s.InPosition = false;
s.Unrealized = 0;
s.PendingClose = true;
// The trade count doesn't need the P&L: check it now.
int tradeLimit = TradeLimit(s, cfg);
if (tradeLimit > 0 && s.TradesToday >= tradeLimit && !IsLockedForDay(s))
LockForDay(s, "max " + tradeLimit + " trades reached");
// The result may already be in; if not, the next realized update counts it.
SettleClose(account, s, cfg);
}
int contractLimit = ContractLimit(s, cfg);
if (contractLimit > 0 && open.Any(p => p.Quantity > contractLimit))
{
LockFor(s, TimeSpan.FromMinutes(LockoutLadder()[0]), "position above your max of " + contractLimit + " contracts");
flattenNow = true;
}
SaveState();
}
if (flattenNow)
Enforce(account);
}
private void OnAccountItemUpdate(object sender, AccountItemEventArgs e)
{
Account account = sender as Account;
GuardAccountSettings cfg = account == null ? null : Config(account);
if (cfg == null)
return;
bool flattenNow = false;
lock (sync)
{
GuardAccountState s = StateFor(account);
if (e.AccountItem == AccountItem.RealizedProfitLoss)
{
if (s.PendingClose)
SettleClose(account, s, cfg);
else if (CheckLossLimit(account, s, cfg, false))
flattenNow = s.InPosition; // a scale-out took the day to the limit
SaveState();
}
else if (e.AccountItem == AccountItem.UnrealizedProfitLoss && s.InPosition)
{
// The daily loss limit also counts the open position, so a
// losing trade is cut at the limit rather than after it.
s.Unrealized = e.Value;
if (CheckLossLimit(account, s, cfg, true))
{
SaveState();
flattenNow = true;
}
}
}
if (flattenNow)
Enforce(account);
}
/// Counts a closed round trip once its realized result is known. Call inside lock (sync).
private void SettleClose(Account account, GuardAccountState s, GuardAccountSettings cfg)
{
double result = Realized(account) - s.RealizedAtOpen;
if (result == 0)
return; // not in yet, or a scratch; a later realized update settles it
s.PendingClose = false;
s.TodayRealized += result;
if (CheckLossLimit(account, s, cfg, false))
return;
if (result < 0 && LockoutOn(s, cfg) && !IsLockedForDay(s))
{
s.LossesToday++;
int[] ladder = LockoutLadder();
int minutes = ladder[Math.Min(s.LossesToday, ladder.Length) - 1];
LockFor(s, TimeSpan.FromMinutes(minutes), "lockout after loss " + s.LossesToday + " today (" + minutes + " min)");
}
}
private void OnOrderUpdate(object sender, OrderEventArgs e)
{
Account account = sender as Account;
GuardAccountSettings cfg = account == null ? null : Config(account);
if (cfg == null || e.Order == null)
return;
if (DateTime.UtcNow < flatteningUntilUtc)
return; // our own closing orders
bool live = e.OrderState == OrderState.Submitted || e.OrderState == OrderState.Accepted || e.OrderState == OrderState.Working;
if (!live)
return;
Position position = OpenPositions(account).FirstOrDefault(p => p.Instrument == e.Order.Instrument);
string reason = null;
lock (sync)
{
GuardAccountState s = StateFor(account);
// Orders that reduce a position (stops, targets, exits) always go through.
bool adds = Adds(position, e.Order);
int contractLimit = ContractLimit(s, cfg);
int after = (position == null ? 0 : position.Quantity) + e.Order.Quantity;
if (adds && IsLocked(s))
reason = account.Name + " is locked (" + s.LockReason + ") until " + UntilText(s);
else if (adds && contractLimit > 0 && after > contractLimit)
reason = "it would take the position to " + after + " contracts, above your max of " + contractLimit;
else if (adds && position != null && NoAddingOn(s, cfg) && s.Unrealized < 0)
reason = "it adds to a losing position (" + Money(s.Unrealized) + " open)";
}
if (reason == null)
return;
account.Cancel(new[] { e.Order });
Notify("Order cancelled on " + account.Name + ": " + reason + ".");
}
/// Whether an order opens or grows a position, rather than reducing it.
private static bool Adds(Position position, Order order)
{
if (position == null || position.MarketPosition == MarketPosition.Flat)
return true;
bool buy = order.OrderAction == OrderAction.Buy || order.OrderAction == OrderAction.BuyToCover;
return (position.MarketPosition == MarketPosition.Long && buy) || (position.MarketPosition == MarketPosition.Short && !buy);
}
// ----- Locks --------------------------------------------------------
private int[] LockoutLadder()
{
int[] configured = settings.LockoutMinutes ?? new int[0];
int length = Math.Max(configured.Length, MinLockoutMinutes.Length);
int[] ladder = new int[length];
for (int i = 0; i < length; i++)
{
int floor = MinLockoutMinutes[Math.Min(i, MinLockoutMinutes.Length - 1)];
ladder[i] = i < configured.Length ? Math.Max(configured[i], floor) : floor;
}
return ladder;
}
private void LockFor(GuardAccountState s, TimeSpan duration, string reason)
{
long until = DateTime.UtcNow.Add(duration).Ticks;
if (until > s.LockedUntilUtc)
{
s.LockedUntilUtc = until;
s.LockReason = reason;
}
Notify(s.Name + " locked until " + UntilText(s) + ": " + reason + ".");
}
private void LockForDay(GuardAccountState s, string reason)
{
s.LockedUntilUtc = NextDayStartUtc().Ticks;
s.LockReason = reason;
Notify(s.Name + " locked for the rest of the trading day: " + reason + ". This is the limit you set on a calm day.");
}
private static bool IsLocked(GuardAccountState s)
{
return s.LockedUntilUtc > DateTime.UtcNow.Ticks;
}
private bool IsLockedForDay(GuardAccountState s)
{
return s.LockedUntilUtc >= NextDayStartUtc().Ticks;
}
/// Cancels every working order and flattens every position on the account.
private void Enforce(Account account)
{
flatteningUntilUtc = DateTime.UtcNow.AddSeconds(5);
List working;
lock (account.Orders)
working = account.Orders
.Where(o => o.OrderState == OrderState.Working || o.OrderState == OrderState.Accepted || o.OrderState == OrderState.Submitted)
.ToList();
if (working.Count > 0)
account.Cancel(working);
List open = OpenPositions(account).Select(p => p.Instrument).ToList();
if (open.Count > 0)
account.Flatten(open);
Notify(account.Name + ": working orders cancelled and positions flattened.");
}
// ----- Time ---------------------------------------------------------
private static TimeZoneInfo FindChicago()
{
try { return TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time"); }
catch { return TimeZoneInfo.Utc; }
}
/// The trading day a moment belongs to: from 17:00 Chicago it is already the next day.
private string TradingDay(DateTime utc)
{
DateTime local = TimeZoneInfo.ConvertTimeFromUtc(utc, chicago);
if (local.Hour >= DayStartHourChicago)
local = local.AddDays(1);
return local.ToString("yyyy-MM-dd");
}
private DateTime NextDayStartUtc()
{
DateTime local = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, chicago);
DateTime start = local.Date.AddHours(DayStartHourChicago);
if (local >= start)
start = start.AddDays(1);
return TimeZoneInfo.ConvertTimeToUtc(DateTime.SpecifyKind(start, DateTimeKind.Unspecified), chicago);
}
private static string UntilText(GuardAccountState s)
{
return new DateTime(s.LockedUntilUtc, DateTimeKind.Utc).ToLocalTime().ToString("HH:mm");
}
private static string Money(double value)
{
return (value < 0 ? "-$" : "$") + Math.Abs(value).ToString("0.00");
}
// ----- Messages and files -------------------------------------------
private void Notify(string message)
{
Print("LAYER 0 Guard: " + message);
Log("LAYER 0 Guard: " + message, LogLevel.Alert);
}
private GuardSettings LoadSettings()
{
GuardSettings loaded = Load(SettingsPath);
if (loaded != null)
return loaded;
GuardSettings defaults = new GuardSettings();
if (File.Exists(SettingsPath))
{
// A typo in the file must not silently replace the trader's limits with the defaults.
Notify("can't read " + SettingsPath + " (a typo in the XML?). Only Sim101 is guarded until it is fixed and NinjaTrader restarts.");
return defaults;
}
Save(SettingsPath, defaults);
Print("LAYER 0 Guard: created " + SettingsPath + " -- put your account names and limits in it, then restart NinjaTrader.");
return defaults;
}
private void SaveState()
{
Save(StatePath, state);
}
private static T Load(string path) where T : class
{
try
{
if (!File.Exists(path))
return null;
using (FileStream stream = File.OpenRead(path))
return (T)new XmlSerializer(typeof(T)).Deserialize(stream);
}
catch
{
return null;
}
}
private static void Save(string path, T value)
{
try
{
using (FileStream stream = File.Create(path))
new XmlSerializer(typeof(T)).Serialize(stream, value);
}
catch
{
// The guard keeps working from memory; the next save retries.
}
}
}
}