PageRenderTime 50ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/Common/Securities/CashBook.cs

https://gitlab.com/deicon/Lean
C# | 300 lines | 142 code | 30 blank | 128 comment | 3 complexity | aeb1703afd16cb955e194cba8c030f5d MD5 | raw file
  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.Collections;
  18. using System.Collections.Generic;
  19. using System.Linq;
  20. using System.Text;
  21. using QuantConnect.Data;
  22. namespace QuantConnect.Securities
  23. {
  24. /// <summary>
  25. /// Provides a means of keeping track of the different cash holdings of an algorithm
  26. /// </summary>
  27. public class CashBook : IDictionary<string, Cash>
  28. {
  29. /// <summary>
  30. /// Gets the base currency used
  31. /// </summary>
  32. public const string AccountCurrency = "USD";
  33. private readonly Dictionary<string, Cash> _currencies;
  34. /// <summary>
  35. /// Gets the total value of the cash book in units of the base currency
  36. /// </summary>
  37. public decimal TotalValueInAccountCurrency
  38. {
  39. get { return _currencies.Values.Sum(x => x.ValueInAccountCurrency); }
  40. }
  41. /// <summary>
  42. /// Initializes a new instance of the <see cref="CashBook"/> class.
  43. /// </summary>
  44. public CashBook()
  45. {
  46. _currencies = new Dictionary<string, Cash>();
  47. _currencies.Add(AccountCurrency, new Cash(AccountCurrency, 0, 1.0m));
  48. }
  49. /// <summary>
  50. /// Adds a new cash of the specified symbol and quantity
  51. /// </summary>
  52. /// <param name="symbol">The symbol used to reference the new cash</param>
  53. /// <param name="quantity">The amount of new cash to start</param>
  54. /// <param name="conversionRate">The conversion rate used to determine the initial
  55. /// portfolio value/starting capital impact caused by this currency position.</param>
  56. public void Add(string symbol, decimal quantity, decimal conversionRate)
  57. {
  58. var cash = new Cash(symbol, quantity, conversionRate);
  59. _currencies.Add(symbol, cash);
  60. }
  61. /// <summary>
  62. /// Checks the current subscriptions and adds necessary currency pair feeds to provide real time conversion data
  63. /// </summary>
  64. /// <param name="securities">The SecurityManager for the algorithm</param>
  65. /// <param name="subscriptions">The SubscriptionManager for the algorithm</param>
  66. /// <param name="marketHoursDatabase">A security exchange hours provider instance used to resolve exchange hours for new subscriptions</param>
  67. /// <param name="symbolPropertiesDatabase">A symbol properties database instance</param>
  68. /// <param name="marketMap">The market map that decides which market the new security should be in</param>
  69. /// <returns>Returns a list of added currency securities</returns>
  70. public List<Security> EnsureCurrencyDataFeeds(SecurityManager securities, SubscriptionManager subscriptions, MarketHoursDatabase marketHoursDatabase, SymbolPropertiesDatabase symbolPropertiesDatabase, IReadOnlyDictionary<SecurityType, string> marketMap)
  71. {
  72. var addedSecurities = new List<Security>();
  73. foreach (var cash in _currencies.Values)
  74. {
  75. var security = cash.EnsureCurrencyDataFeed(securities, subscriptions, marketHoursDatabase, symbolPropertiesDatabase, marketMap, this);
  76. if (security != null)
  77. {
  78. addedSecurities.Add(security);
  79. }
  80. }
  81. return addedSecurities;
  82. }
  83. /// <summary>
  84. /// Converts a quantity of source currency units into the specified destination currency
  85. /// </summary>
  86. /// <param name="sourceQuantity">The quantity of source currency to be converted</param>
  87. /// <param name="sourceCurrency">The source currency symbol</param>
  88. /// <param name="destinationCurrency">The destination currency symbol</param>
  89. /// <returns>The converted value</returns>
  90. public decimal Convert(decimal sourceQuantity, string sourceCurrency, string destinationCurrency)
  91. {
  92. var source = this[sourceCurrency];
  93. var destination = this[destinationCurrency];
  94. var conversionRate = source.ConversionRate*destination.ConversionRate;
  95. return sourceQuantity*conversionRate;
  96. }
  97. /// <summary>
  98. /// Converts a quantity of source currency units into the account currency
  99. /// </summary>
  100. /// <param name="sourceQuantity">The quantity of source currency to be converted</param>
  101. /// <param name="sourceCurrency">The source currency symbol</param>
  102. /// <returns>The converted value</returns>
  103. public decimal ConvertToAccountCurrency(decimal sourceQuantity, string sourceCurrency)
  104. {
  105. return Convert(sourceQuantity, sourceCurrency, AccountCurrency);
  106. }
  107. /// <summary>
  108. /// Returns a string that represents the current object.
  109. /// </summary>
  110. /// <returns>
  111. /// A string that represents the current object.
  112. /// </returns>
  113. /// <filterpriority>2</filterpriority>
  114. public override string ToString()
  115. {
  116. var sb = new StringBuilder();
  117. sb.AppendLine(string.Format("{0} {1,13} {2,10} = {3}", "Symbol", "Quantity", "Conversion", "Value in " + AccountCurrency));
  118. foreach (var value in Values)
  119. {
  120. sb.AppendLine(value.ToString());
  121. }
  122. sb.AppendLine("-------------------------------------------------");
  123. sb.AppendLine(string.Format("CashBook Total Value: {0}{1}",
  124. Currencies.CurrencySymbols[AccountCurrency],
  125. Math.Round(TotalValueInAccountCurrency, 2))
  126. );
  127. return sb.ToString();
  128. }
  129. #region IDictionary Implementation
  130. /// <summary>
  131. /// Gets the count of Cash items in this CashBook.
  132. /// </summary>
  133. /// <value>The count.</value>
  134. public int Count
  135. {
  136. get { return _currencies.Count; }
  137. }
  138. /// <summary>
  139. /// Gets a value indicating whether this instance is read only.
  140. /// </summary>
  141. /// <value><c>true</c> if this instance is read only; otherwise, <c>false</c>.</value>
  142. public bool IsReadOnly
  143. {
  144. get { return ((IDictionary<string, Cash>) _currencies).IsReadOnly; }
  145. }
  146. /// <summary>
  147. /// Add the specified item to this CashBook.
  148. /// </summary>
  149. /// <param name="item">KeyValuePair of symbol -> Cash item</param>
  150. public void Add(KeyValuePair<string, Cash> item)
  151. {
  152. _currencies.Add(item.Key, item.Value);
  153. }
  154. /// <summary>
  155. /// Add the specified key and value.
  156. /// </summary>
  157. /// <param name="symbol">The symbol of the Cash value.</param>
  158. /// <param name="value">Value.</param>
  159. public void Add(string symbol, Cash value)
  160. {
  161. _currencies.Add(symbol, value);
  162. }
  163. /// <summary>
  164. /// Clear this instance of all Cash entries.
  165. /// </summary>
  166. public void Clear()
  167. {
  168. _currencies.Clear();
  169. }
  170. /// <summary>
  171. /// Remove the Cash item corresponding to the specified symbol
  172. /// </summary>
  173. /// <param name="symbol">The symbolto be removed</param>
  174. public bool Remove(string symbol)
  175. {
  176. return _currencies.Remove (symbol);
  177. }
  178. /// <summary>
  179. /// Remove the specified item.
  180. /// </summary>
  181. /// <param name="item">Item.</param>
  182. public bool Remove(KeyValuePair<string, Cash> item)
  183. {
  184. return _currencies.Remove(item.Key);
  185. }
  186. /// <summary>
  187. /// Determines whether the current instance contains an entry with the specified symbol.
  188. /// </summary>
  189. /// <returns><c>true</c>, if key was contained, <c>false</c> otherwise.</returns>
  190. /// <param name="symbol">Key.</param>
  191. public bool ContainsKey(string symbol)
  192. {
  193. return _currencies.ContainsKey(symbol);
  194. }
  195. /// <summary>
  196. /// Try to get the value.
  197. /// </summary>
  198. /// <remarks>To be added.</remarks>
  199. /// <returns><c>true</c>, if get value was tryed, <c>false</c> otherwise.</returns>
  200. /// <param name="symbol">The symbol.</param>
  201. /// <param name="value">Value.</param>
  202. public bool TryGetValue(string symbol, out Cash value)
  203. {
  204. return _currencies.TryGetValue(symbol, out value);
  205. }
  206. /// <summary>
  207. /// Determines whether the current collection contains the specified value.
  208. /// </summary>
  209. /// <param name="item">Item.</param>
  210. public bool Contains(KeyValuePair<string, Cash> item)
  211. {
  212. return _currencies.Contains(item);
  213. }
  214. /// <summary>
  215. /// Copies to the specified array.
  216. /// </summary>
  217. /// <param name="array">Array.</param>
  218. /// <param name="arrayIndex">Array index.</param>
  219. public void CopyTo(KeyValuePair<string, Cash>[] array, int arrayIndex)
  220. {
  221. ((IDictionary<string, Cash>) _currencies).CopyTo(array, arrayIndex);
  222. }
  223. /// <summary>
  224. /// Gets or sets the <see cref="QuantConnect.Securities.Cash"/> with the specified symbol.
  225. /// </summary>
  226. /// <param name="symbol">Symbol.</param>
  227. public Cash this[string symbol]
  228. {
  229. get
  230. {
  231. Cash cash;
  232. if (!_currencies.TryGetValue(symbol, out cash))
  233. {
  234. throw new Exception("This cash symbol (" + symbol + ") was not found in your cash book.");
  235. }
  236. return cash;
  237. }
  238. set { _currencies[symbol] = value; }
  239. }
  240. /// <summary>
  241. /// Gets the keys.
  242. /// </summary>
  243. /// <value>The keys.</value>
  244. public ICollection<string> Keys
  245. {
  246. get { return _currencies.Keys; }
  247. }
  248. /// <summary>
  249. /// Gets the values.
  250. /// </summary>
  251. /// <value>The values.</value>
  252. public ICollection<Cash> Values
  253. {
  254. get { return _currencies.Values; }
  255. }
  256. /// <summary>
  257. /// Gets the enumerator.
  258. /// </summary>
  259. /// <returns>The enumerator.</returns>
  260. public IEnumerator<KeyValuePair<string, Cash>> GetEnumerator()
  261. {
  262. return _currencies.GetEnumerator();
  263. }
  264. IEnumerator IEnumerable.GetEnumerator()
  265. {
  266. return ((IEnumerable) _currencies).GetEnumerator();
  267. }
  268. #endregion
  269. }
  270. }