18 using System.Collections.Generic;
29 private readonly decimal _maximumDrawdownPercent;
30 private readonly Dictionary<Symbol, HoldingsState> _trailingAbsoluteHoldingsState =
new Dictionary<Symbol, HoldingsState>();
38 _maximumDrawdownPercent = Math.Abs(maximumDrawdownPercent);
48 foreach (var kvp
in algorithm.Securities)
51 var security = kvp.Value;
54 if (!security.Invested)
56 _trailingAbsoluteHoldingsState.Remove(symbol);
61 var absoluteHoldingsValue = security.Holdings.AbsoluteHoldingsValue;
62 HoldingsState trailingAbsoluteHoldingsState;
65 if (!_trailingAbsoluteHoldingsState.TryGetValue(symbol, out trailingAbsoluteHoldingsState) ||
66 position != trailingAbsoluteHoldingsState.Position)
68 _trailingAbsoluteHoldingsState[symbol] = trailingAbsoluteHoldingsState =
new HoldingsState(position, security.Holdings.AbsoluteHoldingsCost);
71 var trailingAbsoluteHoldingsValue = trailingAbsoluteHoldingsState.AbsoluteHoldingsValue;
74 if ((position ==
PositionSide.Long && trailingAbsoluteHoldingsValue < absoluteHoldingsValue) ||
75 (position ==
PositionSide.Short && trailingAbsoluteHoldingsValue > absoluteHoldingsValue))
77 trailingAbsoluteHoldingsState.AbsoluteHoldingsValue = absoluteHoldingsValue;
81 var drawdown = Math.Abs((trailingAbsoluteHoldingsValue - absoluteHoldingsValue) / trailingAbsoluteHoldingsValue);
83 if (_maximumDrawdownPercent < drawdown)
86 algorithm.Insights.Cancel(
new[] { symbol });
88 _trailingAbsoluteHoldingsState.Remove(symbol);
99 private class HoldingsState
102 public decimal AbsoluteHoldingsValue;
104 public HoldingsState(
PositionSide position, decimal absoluteHoldingsValue)
107 AbsoluteHoldingsValue = absoluteHoldingsValue;