Lean  $LEAN_TAG$
MaximumUnrealizedProfitPercentPerSecurity.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  *
15 */
16 
17 using System;
18 using System.Collections.Generic;
20 
22 {
23  /// <summary>
24  /// Provides an implementation of <see cref="IRiskManagementModel"/> that limits the unrealized profit
25  /// per holding to the specified percentage
26  /// </summary>
28  {
29  private readonly decimal _maximumUnrealizedProfitPercent;
30 
31  /// <summary>
32  /// Initializes a new instance of the <see cref="MaximumUnrealizedProfitPercentPerSecurity"/> class
33  /// </summary>
34  /// <param name="maximumUnrealizedProfitPercent">The maximum percentage unrealized profit allowed for any single security holding,
35  /// defaults to 5% drawdown per security</param>
37  decimal maximumUnrealizedProfitPercent = 0.05m
38  )
39  {
40  _maximumUnrealizedProfitPercent = Math.Abs(maximumUnrealizedProfitPercent);
41  }
42 
43  /// <summary>
44  /// Manages the algorithm's risk at each time step
45  /// </summary>
46  /// <param name="algorithm">The algorithm instance</param>
47  /// <param name="targets">The current portfolio targets to be assessed for risk</param>
48  public override IEnumerable<IPortfolioTarget> ManageRisk(QCAlgorithm algorithm, IPortfolioTarget[] targets)
49  {
50  foreach (var kvp in algorithm.Securities)
51  {
52  var security = kvp.Value;
53 
54  if (!security.Invested)
55  {
56  continue;
57  }
58 
59  var pnl = security.Holdings.UnrealizedProfitPercent;
60  if (pnl > _maximumUnrealizedProfitPercent)
61  {
62  var symbol = security.Symbol;
63 
64  // Cancel insights
65  algorithm.Insights.Cancel(new[] { symbol });
66 
67  // liquidate
68  yield return new PortfolioTarget(symbol, 0);
69  }
70  }
71  }
72  }
73 }