-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Cash.cs
398 lines (351 loc) · 16.2 KB
/
Cash.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using ProtoBuf;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Interfaces;
using QuantConnect.Logging;
using QuantConnect.Securities.CurrencyConversion;
namespace QuantConnect.Securities
{
/// <summary>
/// Represents a holding of a currency in cash.
/// </summary>
[ProtoContract(SkipConstructor = true)]
public class Cash
{
private ICurrencyConversion _currencyConversion;
private readonly object _locker = new object();
/// <summary>
/// Event fired when this instance is updated
/// <see cref="AddAmount"/>, <see cref="SetAmount"/>, <see cref="Update"/>
/// </summary>
public event EventHandler Updated;
/// <summary>
/// Event fired when this instance's <see cref="CurrencyConversion"/> is set/updated
/// </summary>
public event EventHandler CurrencyConversionUpdated;
/// <summary>
/// Gets the symbols of the securities required to provide conversion rates.
/// If this cash represents the account currency, then an empty enumerable is returned.
/// </summary>
public IEnumerable<Symbol> SecuritySymbols => CurrencyConversion.ConversionRateSecurities.Any()
? CurrencyConversion.ConversionRateSecurities.Select(x => x.Symbol)
// we do this only because Newtonsoft.Json complains about empty enumerables
: new List<Symbol>(0);
/// <summary>
/// Gets the object that calculates the conversion rate to account currency
/// </summary>
[JsonIgnore]
public ICurrencyConversion CurrencyConversion
{
get
{
return _currencyConversion;
}
internal set
{
var lastConversionRate = 0m;
if (_currencyConversion != null)
{
lastConversionRate = _currencyConversion.ConversionRate;
_currencyConversion.ConversionRateUpdated -= OnConversionRateUpdated;
}
_currencyConversion = value;
if (_currencyConversion != null)
{
if (lastConversionRate != 0m)
{
// If a user adds cash with an initial conversion rate and then this is overriden to a SecurityCurrencyConversion,
// we want to keep the previous rate until the new one is updated.
_currencyConversion.ConversionRate = lastConversionRate;
}
_currencyConversion.ConversionRateUpdated += OnConversionRateUpdated;
}
CurrencyConversionUpdated?.Invoke(this, EventArgs.Empty);
}
}
private void OnConversionRateUpdated(object sender, decimal e)
{
OnUpdate();
}
/// <summary>
/// Gets the symbol used to represent this cash
/// </summary>
[ProtoMember(1)]
[JsonProperty("symbol")]
public string Symbol { get; }
/// <summary>
/// Gets or sets the amount of cash held
/// </summary>
[ProtoMember(2)]
[JsonProperty("amount")]
public decimal Amount { get; private set; }
/// <summary>
/// Gets the conversion rate into account currency
/// </summary>
[ProtoMember(3)]
[JsonProperty("conversionRate")]
public decimal ConversionRate
{
get
{
return _currencyConversion.ConversionRate;
}
internal set
{
if (_currencyConversion == null)
{
CurrencyConversion = new ConstantCurrencyConversion(Symbol, null, value);
}
_currencyConversion.ConversionRate = value;
}
}
/// <summary>
/// The symbol of the currency, such as $
/// </summary>
[ProtoMember(4)]
[JsonProperty("currencySymbol")]
public string CurrencySymbol { get; }
/// <summary>
/// Gets the value of this cash in the account currency
/// </summary>
[JsonProperty("valueInAccountCurrency")]
public decimal ValueInAccountCurrency => Amount * ConversionRate;
/// <summary>
/// Initializes a new instance of the <see cref="Cash"/> class
/// </summary>
/// <param name="symbol">The symbol used to represent this cash</param>
/// <param name="amount">The amount of this currency held</param>
/// <param name="conversionRate">The initial conversion rate of this currency into the <see cref="CashBook.AccountCurrency"/></param>
public Cash(string symbol, decimal amount, decimal conversionRate)
{
if (string.IsNullOrEmpty(symbol))
{
throw new ArgumentException(Messages.Cash.NullOrEmptyCashSymbol);
}
Amount = amount;
Symbol = symbol.LazyToUpper();
CurrencySymbol = Currencies.GetCurrencySymbol(Symbol);
CurrencyConversion = new ConstantCurrencyConversion(Symbol, null, conversionRate);
}
/// <summary>
/// Marks this cash object's conversion rate as being potentially outdated
/// </summary>
public void Update()
{
_currencyConversion.Update();
}
/// <summary>
/// Adds the specified amount of currency to this Cash instance and returns the new total.
/// This operation is thread-safe
/// </summary>
/// <param name="amount">The amount of currency to be added</param>
/// <returns>The amount of currency directly after the addition</returns>
public decimal AddAmount(decimal amount)
{
lock (_locker)
{
Amount += amount;
}
OnUpdate();
return Amount;
}
/// <summary>
/// Sets the Quantity to the specified amount
/// </summary>
/// <param name="amount">The amount to set the quantity to</param>
public void SetAmount(decimal amount)
{
var updated = false;
// lock can be null when proto deserializing this instance
lock (_locker ?? new object())
{
if (Amount != amount)
{
Amount = amount;
// only update if there was actually one
updated = true;
}
}
if (updated)
{
OnUpdate();
}
}
/// <summary>
/// Ensures that we have a data feed to convert this currency into the base currency.
/// This will add a <see cref="SubscriptionDataConfig"/> and create a <see cref="Security"/> at the lowest resolution if one is not found.
/// </summary>
/// <param name="securities">The security manager</param>
/// <param name="subscriptions">The subscription manager used for searching and adding subscriptions</param>
/// <param name="marketMap">The market map that decides which market the new security should be in</param>
/// <param name="changes">Will be used to consume <see cref="SecurityChanges.AddedSecurities"/></param>
/// <param name="securityService">Will be used to create required new <see cref="Security"/></param>
/// <param name="accountCurrency">The account currency</param>
/// <param name="defaultResolution">The default resolution to use for the internal subscriptions</param>
/// <returns>Returns the added <see cref="SubscriptionDataConfig"/>, otherwise null</returns>
public List<SubscriptionDataConfig> EnsureCurrencyDataFeed(SecurityManager securities,
SubscriptionManager subscriptions,
IReadOnlyDictionary<SecurityType, string> marketMap,
SecurityChanges changes,
ISecurityService securityService,
string accountCurrency,
Resolution defaultResolution = Resolution.Minute
)
{
// this gets called every time we add securities using universe selection,
// so must of the time we've already resolved the value and don't need to again
if (CurrencyConversion.DestinationCurrency != null)
{
return null;
}
if (Symbol == accountCurrency)
{
CurrencyConversion = ConstantCurrencyConversion.Identity(accountCurrency);
return null;
}
// existing securities
var securitiesToSearch = securities.Select(kvp => kvp.Value)
.Concat(changes.AddedSecurities)
.Where(s => ProvidesConversionRate(s.Type));
// Create a SecurityType to Market mapping with the markets from SecurityManager members
var markets = securities.Select(x => x.Key)
.GroupBy(x => x.SecurityType)
.ToDictionary(x => x.Key, y => y.Select(symbol => symbol.ID.Market).ToHashSet());
if (markets.ContainsKey(SecurityType.Cfd) && !markets.ContainsKey(SecurityType.Forex))
{
markets.Add(SecurityType.Forex, markets[SecurityType.Cfd]);
}
if (markets.ContainsKey(SecurityType.Forex) && !markets.ContainsKey(SecurityType.Cfd))
{
markets.Add(SecurityType.Cfd, markets[SecurityType.Forex]);
}
var forexEntries = GetAvailableSymbolPropertiesDatabaseEntries(SecurityType.Forex, marketMap, markets);
var cfdEntries = GetAvailableSymbolPropertiesDatabaseEntries(SecurityType.Cfd, marketMap, markets);
var cryptoEntries = GetAvailableSymbolPropertiesDatabaseEntries(SecurityType.Crypto, marketMap, markets);
var potentialEntries = forexEntries
.Concat(cfdEntries)
.Concat(cryptoEntries)
.ToList();
if (!potentialEntries.Any(x =>
Symbol == x.Key.Symbol.Substring(0, x.Key.Symbol.Length - x.Value.QuoteCurrency.Length) ||
Symbol == x.Value.QuoteCurrency))
{
// currency not found in any tradeable pair
Log.Error(Messages.Cash.NoTradablePairFoundForCurrencyConversion(Symbol, accountCurrency, marketMap.Where(kvp => ProvidesConversionRate(kvp.Key))));
CurrencyConversion = ConstantCurrencyConversion.Null(accountCurrency, Symbol);
return null;
}
// Special case for crypto markets without direct pairs (They wont be found by the above)
// This allows us to add cash for "StableCoins" that are 1-1 with our account currency without needing a conversion security.
// Check out the StableCoinsWithoutPairs static var for those that are missing their 1-1 conversion pairs
if (marketMap.TryGetValue(SecurityType.Crypto, out var market)
&&
(Currencies.IsStableCoinWithoutPair(Symbol + accountCurrency, market)
|| Currencies.IsStableCoinWithoutPair(accountCurrency + Symbol, market)))
{
CurrencyConversion = ConstantCurrencyConversion.Identity(accountCurrency, Symbol);
return null;
}
var requiredSecurities = new List<SubscriptionDataConfig>();
var potentials = potentialEntries
.Select(x => QuantConnect.Symbol.Create(x.Key.Symbol, x.Key.SecurityType, x.Key.Market));
var minimumResolution = subscriptions.Subscriptions.Select(x => x.Resolution).DefaultIfEmpty(defaultResolution).Min();
var makeNewSecurity = new Func<Symbol, Security>(symbol =>
{
var securityType = symbol.ID.SecurityType;
// use the first subscription defined in the subscription manager
var type = subscriptions.LookupSubscriptionConfigDataTypes(securityType, minimumResolution, false).First();
var objectType = type.Item1;
var tickType = type.Item2;
// set this as an internal feed so that the data doesn't get sent into the algorithm's OnData events
var config = subscriptions.SubscriptionDataConfigService.Add(symbol,
minimumResolution,
fillForward: true,
extendedMarketHours: false,
isInternalFeed: true,
subscriptionDataTypes: new List<Tuple<Type, TickType>>
{new Tuple<Type, TickType>(objectType, tickType)}).First();
var newSecurity = securityService.CreateSecurity(symbol,
config,
addToSymbolCache: false);
Log.Trace("Cash.EnsureCurrencyDataFeed(): " + Messages.Cash.AddingSecuritySymbolForCashCurrencyFeed(symbol, Symbol));
securities.Add(symbol, newSecurity);
requiredSecurities.Add(config);
return newSecurity;
});
CurrencyConversion = SecurityCurrencyConversion.LinearSearch(Symbol,
accountCurrency,
securitiesToSearch.ToList(),
potentials,
makeNewSecurity);
return requiredSecurities;
}
/// <summary>
/// Returns a <see cref="string"/> that represents the current <see cref="Cash"/>.
/// </summary>
/// <returns>A <see cref="string"/> that represents the current <see cref="Cash"/>.</returns>
public override string ToString()
{
return ToString(Currencies.USD);
}
/// <summary>
/// Returns a <see cref="string"/> that represents the current <see cref="Cash"/>.
/// </summary>
/// <returns>A <see cref="string"/> that represents the current <see cref="Cash"/>.</returns>
public string ToString(string accountCurrency)
{
return Messages.Cash.ToString(this, accountCurrency);
}
private static IEnumerable<KeyValuePair<SecurityDatabaseKey, SymbolProperties>> GetAvailableSymbolPropertiesDatabaseEntries(
SecurityType securityType,
IReadOnlyDictionary<SecurityType, string> marketMap,
IReadOnlyDictionary<SecurityType, HashSet<string>> markets
)
{
var marketJoin = new HashSet<string>();
{
string market;
if (marketMap.TryGetValue(securityType, out market))
{
marketJoin.Add(market);
}
HashSet<string> existingMarkets;
if (markets.TryGetValue(securityType, out existingMarkets))
{
foreach (var existingMarket in existingMarkets)
{
marketJoin.Add(existingMarket);
}
}
}
return marketJoin.SelectMany(market => SymbolPropertiesDatabase.FromDataFolder()
.GetSymbolPropertiesList(market, securityType));
}
private static bool ProvidesConversionRate(SecurityType securityType)
{
return securityType == SecurityType.Forex || securityType == SecurityType.Crypto || securityType == SecurityType.Cfd;
}
private void OnUpdate()
{
Updated?.Invoke(this, EventArgs.Empty);
}
}
}