Files
spark/src/client/spark_api/security/ContractLegEnumerable.cs
T
John Colvin 2e9347341b fix: Don't throw ex just because leg qty is 0
ContractLegEnumerable shouldn't be responsible for security validation.
2025-01-14 12:58:58 -05:00

71 lines
2.7 KiB
C#

namespace bts.api {
using bts.utils;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Normalizes a root security (of any type) into a flat sequence of outrights
/// </summary>
/// <remarks>
/// Nested leg quantities are multiplied recursively
/// </remarks>
public class ContractLegEnumerable : IEnumerable<ContractLegImmutable> {
public ContractLegEnumerable(ContractLegImmutable root_leg)
: this(root_leg.Security, root_leg.signed_quantity()) { }
public ContractLegEnumerable(SecurityImmutable root_security, double root_quantity = 1)
: this(_get_root_legs(root_security, root_quantity), root_quantity) { }
public ContractLegEnumerable(IEnumerable<ContractLegImmutable> root_legs, double root_quantity) {
_root_legs = root_legs;
_root_quantity = root_quantity;
}
IEnumerable<ContractLegImmutable> _root_legs { get; }
double _root_quantity { get; }
IEnumerable<ContractLegImmutable> _flat_legs =>
_root_legs?.SelectMany(leg => _get_root_legs(leg, _root_quantity))
?? Enumerable.Empty<ContractLegImmutable>();
public IEnumerator<ContractLegImmutable> GetEnumerator() =>
_flat_legs.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() =>
GetEnumerator();
static IEnumerable<ContractLegImmutable> _get_root_legs(
ContractLegImmutable leg, double root_quantity) {
if (leg.HasSecurity) {
return _get_root_legs(leg.Security, leg.signed_quantity() * root_quantity);
}
if (root_quantity == 1) {
return new[] { leg };
}
var mleg = leg.CloneToMutable();
mleg.Quantity *= root_quantity.abs();
if (root_quantity < 0) {
mleg.Side = mleg.Side.other_side();
}
return new[] { new ContractLegImmutable(mleg) };
}
static IEnumerable<ContractLegImmutable> _get_root_legs(SecurityImmutable security, double root_quantity) =>
security.ContractCase switch {
Security.ContractOneofCase.Spread => security.Spread.Legs.SelectMany(l => _get_root_legs(l.Security, root_quantity * l.signed_quantity())).ToArray(),
Security.ContractOneofCase.Synthetic => security.Synthetic.Legs.SelectMany(l => _get_root_legs(l.Security, root_quantity * l.signed_quantity())).ToArray(),
_ => new[] {
new ContractLegImmutable(
new ContractLeg {
Security = security.CloneToMutable(),
Quantity = Math.Abs(root_quantity),
Side = root_quantity < 0 ? Side.Sell : Side.Buy
})
},
};
}
}