Lean  $LEAN_TAG$
OrderSizing.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 using System;
17 using System.Linq;
22 
23 namespace QuantConnect.Orders
24 {
25  /// <summary>
26  /// Provides methods for computing a maximum order size.
27  /// </summary>
28  public static class OrderSizing
29  {
30  /// <summary>
31  /// Adjust the provided order size to respect maximum order size based on a percentage of current volume.
32  /// </summary>
33  /// <param name="security">The security object</param>
34  /// <param name="maximumPercentCurrentVolume">The maximum percentage of the current bar's volume</param>
35  /// <param name="desiredOrderSize">The desired order size to adjust</param>
36  /// <returns>The signed adjusted order size</returns>
37  public static decimal GetOrderSizeForPercentVolume(Security security, decimal maximumPercentCurrentVolume, decimal desiredOrderSize)
38  {
39  var maxOrderSize = maximumPercentCurrentVolume * security.Volume;
40  var orderSize = Math.Min(maxOrderSize, Math.Abs(desiredOrderSize));
41 
42  return Math.Sign(desiredOrderSize) * AdjustByLotSize(security, orderSize);
43  }
44 
45  /// <summary>
46  /// Adjust the provided order size to respect the maximum total order value
47  /// </summary>
48  /// <param name="security">The security object</param>
49  /// <param name="maximumOrderValueInAccountCurrency">The maximum order value in units of the account currency</param>
50  /// <param name="desiredOrderSize">The desired order size to adjust</param>
51  /// <returns>The signed adjusted order size</returns>
52  public static decimal GetOrderSizeForMaximumValue(Security security, decimal maximumOrderValueInAccountCurrency, decimal desiredOrderSize)
53  {
54  var priceInAccountCurrency = security.Price
55  * security.QuoteCurrency.ConversionRate
57 
58  if (priceInAccountCurrency == 0m)
59  {
60  return 0m;
61  }
62 
63  var maxOrderSize = maximumOrderValueInAccountCurrency / priceInAccountCurrency;
64  var orderSize = Math.Min(maxOrderSize, Math.Abs(desiredOrderSize));
65 
66  return Math.Sign(desiredOrderSize) * AdjustByLotSize(security, orderSize);
67  }
68 
69  /// <summary>
70  /// Gets the remaining quantity to be ordered to reach the specified target quantity.
71  /// </summary>
72  /// <param name="algorithm">The algorithm instance</param>
73  /// <param name="target">The portfolio target</param>
74  /// <returns>The signed remaining quantity to be ordered</returns>
75  public static decimal GetUnorderedQuantity(IAlgorithm algorithm, IPortfolioTarget target)
76  {
77  var security = algorithm.Securities[target.Symbol];
78 
79  return GetUnorderedQuantity(algorithm, target, security);
80  }
81 
82  /// <summary>
83  /// Gets the remaining quantity to be ordered to reach the specified target quantity.
84  /// </summary>
85  /// <param name="algorithm">The algorithm instance</param>
86  /// <param name="target">The portfolio target</param>
87  /// <param name="security">The target security</param>
88  /// <param name="accountForFees">True for taking into account the fee's in the order quantity.
89  /// False, otherwise.</param>
90  /// <returns>The signed remaining quantity to be ordered</returns>
91  public static decimal GetUnorderedQuantity(IAlgorithm algorithm, IPortfolioTarget target, Security security, bool accountForFees = false)
92  {
93  var holdings = security.Holdings.Quantity;
94  var openOrderQuantity = algorithm.Transactions.GetOpenOrderTickets(target.Symbol)
95  .Aggregate(0m, (d, t) => d + t.Quantity - t.QuantityFilled);
96  var quantity = target.Quantity - holdings - openOrderQuantity;
97 
98  // Adjust the order quantity taking into account the fee's
99  if (accountForFees && security.Symbol.SecurityType == SecurityType.Crypto && quantity > 0)
100  {
101  var orderFee = Extensions.GetMarketOrderFees(security, quantity, algorithm.UtcTime, out _);
102  var baseCurrency = ((Crypto)security).BaseCurrency.Symbol;
103  if (baseCurrency == orderFee.Currency)
104  {
105  quantity += orderFee.Amount;
106  }
107  }
108 
109  return AdjustByLotSize(security, quantity);
110  }
111 
112  /// <summary>
113  /// Adjusts the provided order quantity to respect the securities lot size.
114  /// If the quantity is missing 1M part of the lot size it will be rounded up
115  /// since we suppose it's due to floating point error, this is required to avoid diff
116  /// between Py and C#
117  /// </summary>
118  /// <param name="security">The security instance</param>
119  /// <param name="quantity">The desired quantity to adjust, can be signed</param>
120  /// <returns>The signed adjusted quantity</returns>
121  public static decimal AdjustByLotSize(Security security, decimal quantity)
122  {
123  var absQuantity = Math.Abs(quantity);
124  // if the amount we are missing for +1 lot size is 1M part of a lot size
125  // we suppose its due to floating point error and round up
126  // Note: this is required to avoid a diff between Py and C# equivalent
127  var remainder = absQuantity % security.SymbolProperties.LotSize;
128  var missingForLotSize = security.SymbolProperties.LotSize - remainder;
129  if (missingForLotSize < (security.SymbolProperties.LotSize / 1000000))
130  {
131  remainder -= security.SymbolProperties.LotSize;
132  }
133  absQuantity -= remainder;
134 
135  return absQuantity * Math.Sign(quantity);
136  }
137  }
138 }