/
SecurityHolding.cs
505 lines (456 loc) · 16.1 KB
/
SecurityHolding.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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/*
* 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 QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
namespace QuantConnect.Securities
{
/// <summary>
/// SecurityHolding is a base class for purchasing and holding a market item which manages the asset portfolio
/// </summary>
public class SecurityHolding
{
/// <summary>
/// Event raised each time the holdings quantity is changed.
/// </summary>
public event EventHandler<SecurityHoldingQuantityChangedEventArgs> QuantityChanged;
//Working Variables
private decimal _averagePrice;
private decimal _quantity;
private decimal _price;
private decimal _totalSaleVolume;
private decimal _profit;
private decimal _lastTradeProfit;
private decimal _totalFees;
private readonly Security _security;
private readonly ICurrencyConverter _currencyConverter;
/// <summary>
/// Create a new holding class instance setting the initial properties to $0.
/// </summary>
/// <param name="security">The security being held</param>
/// <param name="currencyConverter">A currency converter instance</param>
public SecurityHolding(Security security, ICurrencyConverter currencyConverter)
{
_security = security;
//Total Sales Volume for the day
_totalSaleVolume = 0;
_lastTradeProfit = 0;
_currencyConverter = currencyConverter;
}
/// <summary>
/// Create a new holding class instance copying the initial properties
/// </summary>
/// <param name="holding">The security being held</param>
protected SecurityHolding(SecurityHolding holding)
{
_security = holding._security;
_averagePrice = holding._averagePrice;
_quantity = holding._quantity;
_price = holding._price;
_totalSaleVolume = holding._totalSaleVolume;
_profit = holding._profit;
_lastTradeProfit = holding._lastTradeProfit;
_totalFees = holding._totalFees;
_currencyConverter = holding._currencyConverter;
}
/// <summary>
/// The security being held
/// </summary>
protected Security Security
{
get
{
return _security;
}
}
/// <summary>
/// Gets the current target holdings for this security
/// </summary>
public IPortfolioTarget Target
{
get; set;
}
/// <summary>
/// Average price of the security holdings.
/// </summary>
public decimal AveragePrice
{
get
{
return _averagePrice;
}
protected set
{
_averagePrice = value;
}
}
/// <summary>
/// Quantity of the security held.
/// </summary>
/// <remarks>Positive indicates long holdings, negative quantity indicates a short holding</remarks>
/// <seealso cref="AbsoluteQuantity"/>
public decimal Quantity
{
get
{
return _quantity;
}
protected set
{
_quantity = value;
}
}
/// <summary>
/// Symbol identifier of the underlying security.
/// </summary>
public Symbol Symbol
{
get
{
return _security.Symbol;
}
}
/// <summary>
/// The security type of the symbol
/// </summary>
public SecurityType Type
{
get
{
return _security.Type;
}
}
/// <summary>
/// Leverage of the underlying security.
/// </summary>
public virtual decimal Leverage
{
get
{
return _security.BuyingPowerModel.GetLeverage(_security);
}
}
/// <summary>
/// Acquisition cost of the security total holdings in units of the account's currency.
/// </summary>
public virtual decimal HoldingsCost
{
get
{
if (Quantity == 0)
{
return 0;
}
return AveragePrice * Quantity * _security.QuoteCurrency.ConversionRate * _security.SymbolProperties.ContractMultiplier;
}
}
/// <summary>
/// Unlevered Acquisition cost of the security total holdings in units of the account's currency.
/// </summary>
public virtual decimal UnleveredHoldingsCost
{
get { return HoldingsCost/Leverage; }
}
/// <summary>
/// Current market price of the security.
/// </summary>
public virtual decimal Price
{
get
{
return _price;
}
protected set
{
_price = value;
}
}
/// <summary>
/// Absolute holdings cost for current holdings in units of the account's currency.
/// </summary>
/// <seealso cref="HoldingsCost"/>
public virtual decimal AbsoluteHoldingsCost
{
get
{
return Math.Abs(HoldingsCost);
}
}
/// <summary>
/// Unlevered absolute acquisition cost of the security total holdings in units of the account's currency.
/// </summary>
public virtual decimal UnleveredAbsoluteHoldingsCost
{
get
{
return Math.Abs(UnleveredHoldingsCost);
}
}
/// <summary>
/// Market value of our holdings in units of the account's currency.
/// </summary>
public virtual decimal HoldingsValue
{
get
{
if (Quantity == 0)
{
return 0;
}
return GetQuantityValue(Quantity);
}
}
/// <summary>
/// Absolute of the market value of our holdings in units of the account's currency.
/// </summary>
/// <seealso cref="HoldingsValue"/>
public virtual decimal AbsoluteHoldingsValue
{
get { return Math.Abs(HoldingsValue); }
}
/// <summary>
/// Boolean flat indicating if we hold any of the security
/// </summary>
public virtual bool HoldStock
{
get
{
return (AbsoluteQuantity > 0);
}
}
/// <summary>
/// Boolean flat indicating if we hold any of the security
/// </summary>
/// <remarks>Alias of HoldStock</remarks>
/// <seealso cref="HoldStock"/>
public virtual bool Invested
{
get
{
return HoldStock;
}
}
/// <summary>
/// The total transaction volume for this security since the algorithm started in units of the account's currency.
/// </summary>
public virtual decimal TotalSaleVolume
{
get { return _totalSaleVolume; }
}
/// <summary>
/// Total fees for this company since the algorithm started in units of the account's currency.
/// </summary>
public virtual decimal TotalFees
{
get { return _totalFees; }
}
/// <summary>
/// Boolean flag indicating we have a net positive holding of the security.
/// </summary>
/// <seealso cref="IsShort"/>
public virtual bool IsLong
{
get
{
return Quantity > 0;
}
}
/// <summary>
/// BBoolean flag indicating we have a net negative holding of the security.
/// </summary>
/// <seealso cref="IsLong"/>
public virtual bool IsShort
{
get
{
return Quantity < 0;
}
}
/// <summary>
/// Absolute quantity of holdings of this security
/// </summary>
/// <seealso cref="Quantity"/>
public virtual decimal AbsoluteQuantity
{
get
{
return Math.Abs(Quantity);
}
}
/// <summary>
/// Record of the closing profit from the last trade conducted in units of the account's currency.
/// </summary>
public virtual decimal LastTradeProfit
{
get
{
return _lastTradeProfit;
}
}
/// <summary>
/// Calculate the total profit for this security in units of the account's currency.
/// </summary>
/// <seealso cref="NetProfit"/>
public virtual decimal Profit
{
get { return _profit; }
}
/// <summary>
/// Return the net for this company measured by the profit less fees in units of the account's currency.
/// </summary>
/// <seealso cref="Profit"/>
/// <seealso cref="TotalFees"/>
public virtual decimal NetProfit
{
get
{
return Profit - TotalFees;
}
}
/// <summary>
/// Gets the unrealized profit as a percenage of holdings cost
/// </summary>
public decimal UnrealizedProfitPercent
{
get
{
if (AbsoluteHoldingsCost == 0) return 0m;
return UnrealizedProfit/AbsoluteHoldingsCost;
}
}
/// <summary>
/// Unrealized profit of this security when absolute quantity held is more than zero in units of the account's currency.
/// </summary>
public virtual decimal UnrealizedProfit
{
get { return TotalCloseProfit(); }
}
/// <summary>
/// Adds a fee to the running total of total fees in units of the account's currency.
/// </summary>
/// <param name="newFee"></param>
public void AddNewFee(decimal newFee)
{
_totalFees += newFee;
}
/// <summary>
/// Adds a profit record to the running total of profit in units of the account's currency.
/// </summary>
/// <param name="profitLoss">The cash change in portfolio from closing a position</param>
public void AddNewProfit(decimal profitLoss)
{
_profit += profitLoss;
}
/// <summary>
/// Adds a new sale value to the running total trading volume in units of the account's currency.
/// </summary>
/// <param name="saleValue"></param>
public void AddNewSale(decimal saleValue)
{
_totalSaleVolume += saleValue;
}
/// <summary>
/// Set the last trade profit for this security from a Portfolio.ProcessFill call in units of the account's currency.
/// </summary>
/// <param name="lastTradeProfit">Value of the last trade profit</param>
public void SetLastTradeProfit(decimal lastTradeProfit)
{
_lastTradeProfit = lastTradeProfit;
}
/// <summary>
/// Set the quantity of holdings and their average price after processing a portfolio fill.
/// </summary>
public virtual void SetHoldings(decimal averagePrice, int quantity)
{
SetHoldings(averagePrice, (decimal) quantity);
}
/// <summary>
/// Set the quantity of holdings and their average price after processing a portfolio fill.
/// </summary>
public virtual void SetHoldings(decimal averagePrice, decimal quantity)
{
var previousQuantity = _quantity;
var previousAveragePrice = _averagePrice;
_quantity = quantity;
_averagePrice = averagePrice;
OnQuantityChanged(previousAveragePrice, previousQuantity);
}
/// <summary>
/// Update local copy of closing price value.
/// </summary>
/// <param name="closingPrice">Price of the underlying asset to be used for calculating market price / portfolio value</param>
public virtual void UpdateMarketPrice(decimal closingPrice)
{
_price = closingPrice;
}
/// <summary>
/// Gets the total value of the specified <paramref name="quantity"/> of shares of this security
/// in the account currency
/// </summary>
/// <param name="quantity">The quantity of shares</param>
/// <returns>The value of the quantity of shares in the account currency</returns>
public virtual decimal GetQuantityValue(decimal quantity)
{
return GetQuantityValue(quantity, _price);
}
/// <summary>
/// Gets the total value of the specified <paramref name="quantity"/> of shares of this security
/// in the account currency
/// </summary>
/// <param name="quantity">The quantity of shares</param>
/// <param name="price">The current price</param>
/// <returns>The value of the quantity of shares in the account currency</returns>
public virtual decimal GetQuantityValue(decimal quantity, decimal price)
{
return price * quantity * _security.QuoteCurrency.ConversionRate * _security.SymbolProperties.ContractMultiplier;
}
/// <summary>
/// Profit if we closed the holdings right now including the approximate fees in units of the account's currency.
/// </summary>
/// <remarks>Does not use the transaction model for market fills but should.</remarks>
public virtual decimal TotalCloseProfit()
{
if (Quantity == 0)
{
return 0;
}
// this is in the account currency
var marketOrder = new MarketOrder(_security.Symbol, -Quantity, _security.LocalTime.ConvertToUtc(_security.Exchange.TimeZone));
var orderFee = _security.FeeModel.GetOrderFee(
new OrderFeeParameters(_security, marketOrder)).Value;
var feesInAccountCurrency = _currencyConverter.
ConvertToAccountCurrency(orderFee).Amount;
var price = marketOrder.Direction == OrderDirection.Sell ? _security.BidPrice : _security.AskPrice;
if (price == 0)
{
// Bid/Ask prices can both be equal to 0. This usually happens when we request our holdings from
// the brokerage, but only the last trade price was provided.
price = _security.Price;
}
return (price - AveragePrice) * Quantity * _security.QuoteCurrency.ConversionRate
* _security.SymbolProperties.ContractMultiplier - feesInAccountCurrency;
}
/// <summary>
/// Event invocator for the <see cref="QuantityChanged"/> event
/// </summary>
protected virtual void OnQuantityChanged(decimal previousAveragePrice, decimal previousQuantity)
{
QuantityChanged?.Invoke(this, new SecurityHoldingQuantityChangedEventArgs(
_security, previousAveragePrice, previousQuantity
));
}
}
}