diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/Book.cs b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/Book.cs new file mode 100644 index 000000000..7bf95f87a --- /dev/null +++ b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/Book.cs @@ -0,0 +1,36 @@ +using System; +using System.Linq; + +namespace SpreaderFrontEnd { + public class Book : IEquatable { + public Book(BookSide bids = null, BookSide asks = null) { + this.bids = bids ?? new BookSide(); + this.asks = asks ?? new BookSide(); + } + + public BookSide bids { get; } + public BookSide asks { get; } + + public Book Clone() { + return new Book( + new BookSide(bids.levels.ToList()), + new BookSide(asks.levels.ToList())); + } + + public bool Equals(Book other) { + return other != null && other.bids.Equals(bids) && other.asks.Equals(asks); + } + + public override bool Equals(object obj) { + return Equals(obj as Book); + } + + public override int GetHashCode() { + return HashCodeHelper.combine(bids.GetHashCode(), asks.GetHashCode()); + } + + public override string ToString() { + return $"bid: {bids} | ask: {asks}"; + } + } +} diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/BookSide.cs b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/BookSide.cs new file mode 100644 index 000000000..c6cfb1e11 --- /dev/null +++ b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/BookSide.cs @@ -0,0 +1,38 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace SpreaderFrontEnd { + public class BookSide : IEquatable { + public BookSide() { + levels = new List(); + } + + public BookSide(IEnumerable levels) { + this.levels = levels?.ToList() ?? new List(); + } + + public IList levels { get; } + + public BookSide Clone() { + return new BookSide(levels.ToList()); + } + + public bool Equals(BookSide other) { + return other != null && levels.SequenceEqual(other.levels); + } + + public override bool Equals(object obj) { + return Equals(obj as BookSide); + } + + public override int GetHashCode() { + return levels.Select(l => l.GetHashCode()).Skip(1).Aggregate( + levels[0].GetHashCode(), HashCodeHelper.combine); + } + + public override string ToString() { + return string.Join("; ", levels); + } + } +} diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/LegBookSideCursor.cs b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/LegBookSideCursor.cs new file mode 100644 index 000000000..f18496798 --- /dev/null +++ b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/LegBookSideCursor.cs @@ -0,0 +1,120 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; + +namespace SpreaderFrontEnd { + public class LegCursor { + public LegCursor(int leg_size, IList levels) { + this.leg_size = leg_size; + this.levels = levels; + } + + /// + /// The [signed] quantity of this leg in the SpreaderContract to which it belongs + /// + public int leg_size { get; } + + /// + /// The [unsigned] quantity of this leg in the SpreaderContract to which it belongs + /// + public int leg_size_abs { + get { + return Math.Abs(leg_size); + } + } + + /// + /// The price levels of the underlying BookSide + /// + public IList levels { get; } + + /// + /// The index of the current level. When + /// is called, quantity consumption begins at this level. Once this level's quantity is fully + /// consumed, is incremented, and + /// is reset to 0. + /// + public int cursor { get; private set; } + + /// + /// The quantity that has been consumed at the current level (i.e., the level at index + /// ) + /// + public uint curr_level_consumed_qty { get; private set; } + + /// + /// Consumes the specified quantity of units at the best available price(s) + /// + /// + /// The unit quantity to consume + /// + /// True if the entire quantity is consumed, otherwise false. + public bool consume_unit_qty(uint unit_qty, out List consumed_levels) { + consumed_levels = new List(); + uint marg_qty = (uint)(unit_qty * leg_size_abs); + var consumed_qty = _consume_raw_qty(marg_qty, ref consumed_levels); + Debug.Assert(consumed_qty % leg_size_abs == 0); + uint consumed_units = (uint)(consumed_qty / leg_size_abs); + return consumed_units == unit_qty; + } + + /// + /// Gets the number of units (raw_quantity / leg_size_abs) available at the best price + /// + public PriceLevel curr_synth_level() { + if (cursor >= levels.Count) { + return PriceLevel.empty; + } + + var curr_level = levels[cursor]; + Debug.Assert(curr_level.qty >= curr_level_consumed_qty); + var curr_level_rem_qty = curr_level.qty - curr_level_consumed_qty; + if (curr_level_rem_qty >= leg_size_abs) { + return new PriceLevel( + price: curr_level.price * leg_size_abs, + qty: (uint)(curr_level_rem_qty / leg_size_abs)); + } + + double unit_cost = curr_level.price * curr_level_rem_qty; + var unit_rem = leg_size_abs - curr_level_rem_qty; + for (int i = cursor + 1; i < levels.Count; i++) { + curr_level = levels[i]; + if (curr_level.qty >= unit_rem) { + unit_cost += curr_level.price * unit_rem; + return new PriceLevel(price: unit_cost, qty: 1); + } + unit_cost += curr_level.price * curr_level.qty; + unit_rem -= curr_level.qty; + } + return PriceLevel.empty; + } + + /// + /// Consumes as much of the specified [raw] quantity as possible + /// + /// + /// The quantity that was actually consumed + /// + uint _consume_raw_qty(uint raw_qty, ref List dest) { + if (levels == null || cursor >= levels.Count) { + return 0; + } + var curr_level = levels[cursor]; + // Cursor should be incremented when curr_level_consumed_qty == levels[cursor].qty + // (i.e., curr_level.qty should never be less than curr_level_consumed_qty) + Debug.Assert(curr_level.qty > curr_level_consumed_qty); + var curr_level_qty_rem = curr_level.qty - curr_level_consumed_qty; + if (curr_level_qty_rem > raw_qty) { + curr_level_consumed_qty += raw_qty; + dest.Add(new PriceLevel(price: curr_level.price, qty: raw_qty)); + return raw_qty; + } + // The input qty is greater than the qty that remains at this level. Consume the rest on + // the next level. + cursor++; + curr_level_consumed_qty = 0; + dest.Add(new PriceLevel(price: curr_level.price, qty: curr_level_qty_rem)); + return curr_level_qty_rem + _consume_raw_qty(raw_qty - curr_level_qty_rem, ref dest); + } + } +} diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/PriceLevel.cs b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/PriceLevel.cs new file mode 100644 index 000000000..eac078437 --- /dev/null +++ b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/PriceLevel.cs @@ -0,0 +1,44 @@ +using System; + +namespace SpreaderFrontEnd { + public struct PriceLevel : IEquatable { + public PriceLevel(double price, uint qty) { + this.price = price; + this.qty = qty; + } + + public static PriceLevel empty { + get { + return new PriceLevel(double.NaN, 0); + } + } + + public double price { get; } + public uint qty { get; } + + public PriceLevel subtract_qty(uint value) { + System.Diagnostics.Debug.Assert(value <= qty); + return new PriceLevel(price, qty - value); + } + + public PriceLevel add_qty(uint value) { + return new PriceLevel(price, qty + value); + } + + public override string ToString() { + return $"{price} ({qty})"; + } + + public bool Equals(PriceLevel other) { + return qty == other.qty && price.Equals(other.price); + } + + public override bool Equals(object obj) { + return obj is PriceLevel other && Equals(other); + } + + public override int GetHashCode() { + return HashCodeHelper.combine(price.GetHashCode(), qty.GetHashCode()); + } + } +} diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SpreaderBookCalculator.cs b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SpreaderBookCalculator.cs index a491892f0..bde5f5f24 100644 --- a/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SpreaderBookCalculator.cs +++ b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SpreaderBookCalculator.cs @@ -1,28 +1,49 @@ -namespace SpreaderFrontEnd { - using System; - using System.Collections.Generic; - using System.Linq; - using System.Text; - using System.Threading.Tasks; - - public class PriceLevel { - double price = Double.NaN; - uint qty = 0; - } - - public class BookSide { - IEnumerable levels; - } - - public class Book { - BookSide? bids; - BookSide? asks; - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Diagnostics; +namespace SpreaderFrontEnd { public static class SpreaderBookCalculator { - static Book? compute_sreader_book(SpreaderContract contract, IEnumerable leg_books) { - System.Diagnostics.Debug.Assert(contract.spread_legs.Count() == leg_books.Count()); - return null; + public static Book compute_spreader_book( + SpreaderContract contract, IEnumerable leg_books) { + if (contract == null) { + throw new ArgumentNullException(nameof(contract)); + } + if (leg_books == null) { + throw new ArgumentNullException(nameof(leg_books)); + } + var leg_book_list = leg_books as IList ?? leg_books.ToList(); + var synth_book = new SyntheticBook(contract, leg_book_list); + return synth_book.to_book(); + } + + public static BookSide compute_spreader_book_side( + SpreaderContract contract, IList leg_books, bool is_bid) { + Debug.Assert(contract.spread_legs.Count == leg_books.Count); + var leg_cursors = leg_books.Select((b, i) => new LegCursor( + contract.spread_legs[i].qty, + contract.spread_legs[i].qty < 0 == is_bid ? b.asks.levels : b.bids.levels)).ToList(); + var level_qty = leg_cursors.Select(lc => lc.curr_synth_level().qty).Min(); + var result = new BookSide(); + + while (level_qty > 0) { + double level_price = 0; + for (int i = 0; i < leg_cursors.Count; i++) { + var lc = leg_cursors[i]; + bool did_consume = lc.consume_unit_qty(level_qty, out var consumed_levels); + Debug.Assert(did_consume); + var leg_cost = consumed_levels.Select(l => l.price * l.qty).Sum() / level_qty; + if (lc.leg_size < 0) { + level_price -= leg_cost; + } else { + level_price += leg_cost; + } + } + result.levels.Add(new PriceLevel(price: level_price, qty: level_qty)); + level_qty = leg_cursors.Select(lc => lc.curr_synth_level().qty).Min(); + } + return result; } } } diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SyntheticBook.cs b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SyntheticBook.cs new file mode 100644 index 000000000..f3f8c6974 --- /dev/null +++ b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SyntheticBook.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +namespace SpreaderFrontEnd { + class SyntheticBook { + public SyntheticBook(SpreaderContract contract, IList leg_books) { + bids = new SyntheticBookSide(contract, leg_books, true); + asks = new SyntheticBookSide(contract, leg_books, false); + } + + public SyntheticBookSide bids { get; } + public SyntheticBookSide asks { get; } + + public Book to_book() { + return new Book(bids: bids.to_book_side(), asks: asks.to_book_side()); + } + } +} diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SyntheticBookSide.cs b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SyntheticBookSide.cs new file mode 100644 index 000000000..178924ce3 --- /dev/null +++ b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SyntheticBookSide.cs @@ -0,0 +1,28 @@ +using System.Collections; +using System.Collections.Generic; + +namespace SpreaderFrontEnd { + class SyntheticBookSide : IEnumerable { + readonly SpreaderContract _contract; + readonly IList _leg_books; + readonly bool _is_bid; + + public SyntheticBookSide(SpreaderContract contract, IList leg_books, bool is_bid) { + _contract = contract; + _leg_books = leg_books; + _is_bid = is_bid; + } + + public BookSide to_book_side() { + return new BookSide(this); + } + + public IEnumerator GetEnumerator() { + return new SyntheticBookSideEnumerator(_contract, _leg_books, _is_bid); + } + + IEnumerator IEnumerable.GetEnumerator() { + return GetEnumerator(); + } + } +} diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SyntheticBookSideEnumerator.cs b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SyntheticBookSideEnumerator.cs new file mode 100644 index 000000000..82a797084 --- /dev/null +++ b/SpreaderFrontEnd/SpreaderFrontEnd/BookCalcs/SyntheticBookSideEnumerator.cs @@ -0,0 +1,59 @@ +using System.Collections.Generic; +using System.Linq; +using System.Diagnostics; +using System.Collections; + +namespace SpreaderFrontEnd { + class SyntheticBookSideEnumerator : IEnumerator { + readonly List _leg_cursors; + + PriceLevel _current; + uint _level_qty; + + public SyntheticBookSideEnumerator( + SpreaderContract contract, IList leg_books, bool is_bid) { + Debug.Assert(contract.spread_legs.Count == leg_books.Count); + _leg_cursors = new List(leg_books.Count); + for (int i = 0; i < leg_books.Count; i++) { + _leg_cursors.Add(new LegCursor( + contract.spread_legs[i].qty, + contract.spread_legs[i].qty < 0 == is_bid ? + leg_books[i].asks.levels : leg_books[i].bids.levels)); + } + } + + public PriceLevel Current => _current; + + object IEnumerator.Current => _current; + + public void Dispose() { } + + public bool MoveNext() { + _level_qty = _leg_cursors.Select(lc => lc.curr_synth_level().qty).Min(); + if (_level_qty == 0) { + return false; + } + double level_price = 0; + for (int i = 0; i < _leg_cursors.Count; i++) { + var lc = _leg_cursors[i]; + bool did_consume = lc.consume_unit_qty(_level_qty, out var consumed_levels); + Debug.Assert(did_consume); + var leg_cost = consumed_levels.Select(l => l.price * l.qty).Sum() / _level_qty; + if (lc.leg_size < 0) { + level_price -= leg_cost; + } else { + level_price += leg_cost; + } + } + _current = new PriceLevel(price: level_price, qty: _level_qty); + return true; + } + + public void Reset() { + for (int i = 0; i < _leg_cursors.Count; i++) { + var lc = _leg_cursors[i]; + _leg_cursors[i] = new LegCursor(lc.leg_size, lc.levels); + } + } + } +} diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/HashCodeHelper.cs b/SpreaderFrontEnd/SpreaderFrontEnd/HashCodeHelper.cs new file mode 100644 index 000000000..842ce0565 --- /dev/null +++ b/SpreaderFrontEnd/SpreaderFrontEnd/HashCodeHelper.cs @@ -0,0 +1,8 @@ +namespace SpreaderFrontEnd { + static class HashCodeHelper { + // Copied from https://referencesource.microsoft.com/#System.Numerics/System/Numerics/HashCodeHelper.cs + public static int combine(int h1, int h2) { + return (((h1 << 5) + h1) ^ h2); + } + } +} diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/Program.cs b/SpreaderFrontEnd/SpreaderFrontEnd/Program.cs index ecc65e6c3..664ed676a 100644 --- a/SpreaderFrontEnd/SpreaderFrontEnd/Program.cs +++ b/SpreaderFrontEnd/SpreaderFrontEnd/Program.cs @@ -8,6 +8,7 @@ namespace SpreaderFrontEnd { /// [STAThread] static void Main() { + SyntheticBookTest.run(); // To customize application configuration such as set high DPI settings or default font, // see https://aka.ms/applicationconfiguration. ApplicationConfiguration.Initialize(); diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/SpreaderContract.cs b/SpreaderFrontEnd/SpreaderFrontEnd/SpreaderContract.cs index d943ec774..fd5837864 100644 --- a/SpreaderFrontEnd/SpreaderFrontEnd/SpreaderContract.cs +++ b/SpreaderFrontEnd/SpreaderFrontEnd/SpreaderContract.cs @@ -15,12 +15,12 @@ namespace SpreaderFrontEnd { public static uint max_nlegs = 5; public string name = String.Empty; - public IEnumerable spread_legs = new List(); + public IList spread_legs = new List(); public SpreaderContract(string name, IEnumerable spread_legs) { this.name = name; - this.spread_legs = spread_legs; + this.spread_legs = spread_legs.ToList(); } public static SpreaderContract empty diff --git a/SpreaderFrontEnd/SpreaderFrontEnd/Tests/SyntheticBookTest.cs b/SpreaderFrontEnd/SpreaderFrontEnd/Tests/SyntheticBookTest.cs new file mode 100644 index 000000000..8197a2f0b --- /dev/null +++ b/SpreaderFrontEnd/SpreaderFrontEnd/Tests/SyntheticBookTest.cs @@ -0,0 +1,230 @@ +using System; +using System.Diagnostics; +using System.Collections.Generic; +using System.Linq; + +namespace SpreaderFrontEnd { + public static class SyntheticBookTest { + /// + /// Run synthetic book computation tests + /// + public static int run() { + // Seed the test with a standard butterfly spread. Leg size multipliers will be applied to + // each leg to generate more variations to test. + var legs = new List { + new SpreaderLegContract() { + security = "Leg1Sec", + qty = 1 + }, + new SpreaderLegContract() { + security = "Leg2Sec", + qty = -2 + }, + new SpreaderLegContract() { + security = "Leg3Sec", + qty = 1 + } + }; + var leg_multipliers = new List { 1, -1, 2, -2, 3, -3 }; + var contract = new SpreaderContract("Test", legs); + + // Define a book (seed) for each leg. Quantities will be added to each price level for each + // leg's book to generate more variations to test. + var leg1_book = new Book( + bids: new BookSide(levels: new List { + new PriceLevel(price: 3, qty: 10), + new PriceLevel(price: 2, qty: 4), + new PriceLevel(price: 1, qty: 6) + }), + asks: new BookSide(levels: new List { + new PriceLevel(price: 4, qty: 5), + new PriceLevel(price: 5, qty: 7), + new PriceLevel(price: 6, qty: 8) + })); + var leg2_book = new Book( + bids: new BookSide(levels: new List { + new PriceLevel(price: 3, qty: 1), + new PriceLevel(price: 2, qty: 7), + new PriceLevel(price: 1, qty: 2) + }), + asks: new BookSide(levels: new List { + new PriceLevel(price: 4, qty: 3), + new PriceLevel(price: 5, qty: 3), + new PriceLevel(price: 6, qty: 5) + })); + var leg3_book = new Book( + bids: new BookSide(levels: new List { + new PriceLevel(price: 3, qty: 2), + new PriceLevel(price: 2, qty: 1), + new PriceLevel(price: 1, qty: 8) + }), + asks: new BookSide(levels: new List { + new PriceLevel(price: 4, qty: 4), + new PriceLevel(price: 5, qty: 3), + new PriceLevel(price: 6, qty: 4) + })); + var level_qty_additions = new List { 1, 2, 3, 4 }; + var leg_books = new List { leg1_book, leg2_book, leg3_book }; + + for (int i = 0; i < leg_multipliers.Count; i++) { + var leg_mult = leg_multipliers[i]; + for (int j = 0; j < contract.spread_legs.Count; j++) { + // Apply leg mult + contract.spread_legs[j].qty *= leg_mult; + foreach (var lqa in level_qty_additions) { + foreach(var lb in leg_books) { + // Apply qty addition to bid-levels + for (int level_idx = 0; level_idx < lb.bids.levels.Count; level_idx++) { + var orig_level = lb.bids.levels[level_idx]; + lb.bids.levels[level_idx] = orig_level.add_qty(lqa); + run(leg_books, contract); + // Subtract the qty that was just added so each qty addition is applied to + // the original level + lb.bids.levels[level_idx] = lb.bids.levels[level_idx].subtract_qty(lqa); + } + + // Apply qty additions to ask-levels + for (int level_idx = 0; level_idx < lb.asks.levels.Count; level_idx++) { + var orig_level = lb.asks.levels[level_idx]; + lb.asks.levels[level_idx] = orig_level.add_qty(lqa); + run(leg_books, contract); + // Subtract the qty that was just added so each qty addition is applied to + // the original level + lb.asks.levels[level_idx] = lb.asks.levels[level_idx].subtract_qty(lqa); + } + } + } + // Divide by leg_mult so the each mult is applied to the original leg + contract.spread_legs[j].qty /= leg_mult; + } + } + return 0; + } + + public static void run(List leg_books, SpreaderContract contract) { + var synth_book = SpreaderBookCalculator.compute_spreader_book(contract, leg_books); + for (int i = 0; i < contract.spread_legs.Count; i++) { + Console.WriteLine($"Leg{i} (qty {contract.spread_legs[i].qty}): {leg_books[i]}"); + } + Console.WriteLine($"Synthetic Book: {synth_book}"); + var leg_book_tups = _to_leg_book_tuples(leg_books, contract); + var expected_book = _compute_synth_book(leg_book_tups); + Console.WriteLine($"Expected Book: {expected_book}"); + Debug.Assert(expected_book.Equals(synth_book)); + } + + static List> _to_leg_book_tuples(List leg_books, SpreaderContract contract) { + Debug.Assert(leg_books.Count == contract.spread_legs.Count); + var rv = new List>(); + for (int i = 0; i < leg_books.Count; i++) { + rv.Add(Tuple.Create(leg_books[i], contract.spread_legs[i].qty)); + } + return rv; + } + + static List> _to_leg_book_side_tuples(List> leg_books, bool is_bid) { + var leg_book_tups = new List>(); + for (int i = 0; i < leg_books.Count; i++) { + var leg_size = leg_books[i].Item2; + var leg_book = leg_books[i].Item1; + var is_buy_leg = leg_size > 0; + var leg_book_side = is_buy_leg == is_bid ? leg_book.bids : leg_book.asks; + leg_book_tups.Add(Tuple.Create(leg_book_side, leg_size)); + } + return leg_book_tups; + } + + static Book _compute_synth_book(List> leg_books) { + var leg_bids = _to_leg_book_side_tuples(leg_books, true); + var leg_asks = _to_leg_book_side_tuples(leg_books, false); + var synth_bids = _compute_synth_book_side(leg_bids); + var synth_asks = _compute_synth_book_side(leg_asks); + return new Book(synth_bids, synth_asks); + } + + // + // Computes the synthetic book in a simple/unoptimized way, to ensure correctness. Books + // generated by the 'optimized' routine, which will be used in practice, should match those + // generated by this one. + // + static BookSide _compute_synth_book_side(IEnumerable> leg_books) { + // Clone the books so we can mutate them without changing the input 'leg_books' + var leg_books_list = leg_books.Select(lb => Tuple.Create(lb.Item1.Clone(), lb.Item2)).ToList(); + var levels = new List(); + var top_level = _get_top_level(leg_books_list); + while (top_level.qty > 0) { + levels.Add(top_level); + foreach (var lb in leg_books_list) { + _remove_qty_from_top(lb.Item1, (int)(top_level.qty * Math.Abs(lb.Item2))); + } + top_level = _get_top_level(leg_books_list); + } + return new BookSide(levels); + } + + static PriceLevel _get_top_level(IEnumerable> leg_books) { + var leg_sizes = leg_books.Select(lb => lb.Item2).ToList(); + var top_levels = leg_books.Select(_get_top_level).ToList(); + var qty = top_levels.Select(l => l.qty).Min(); + if (qty == 0) { + return PriceLevel.empty; + } + double price = 0; + for (int i = 0; i < top_levels.Count; i++) { + var leg_price = top_levels[i].price; + var leg_size = leg_sizes[i]; + if (leg_size < 0) { + price -= leg_price; + } else { + price += leg_price; + } + } + return new PriceLevel(price, qty); + } + + static PriceLevel _get_top_level(Tuple leg_book) { + return _get_top_level(leg_book.Item1, leg_book.Item2); + } + + static PriceLevel _get_top_level(BookSide book, int leg_size) { + if (book.levels.Count == 0) { + return PriceLevel.empty; + } + var first_level = book.levels.First(); + var abs_leg_size = Math.Abs(leg_size); + if (first_level.qty >= abs_leg_size) { + return new PriceLevel(first_level.price * abs_leg_size, (uint)(first_level.qty / abs_leg_size)); + } + double price = first_level.qty * first_level.price; + var qty_rem = abs_leg_size - first_level.qty; + for (int i = 1; i < book.levels.Count; i++) { + var level = book.levels[i]; + if (level.qty >= qty_rem) { + price += qty_rem * level.price; + return new PriceLevel(price, 1); + } + price += level.qty * level.price; + qty_rem -= level.qty; + } + return PriceLevel.empty; + } + + /// + /// Removes the specified quantity from the top of the book + /// + static void _remove_qty_from_top(BookSide book, int qty) { + var subtracted_qty = 0; + while (subtracted_qty < qty && book.levels.Count > 0) { + var first_level = book.levels[0]; + var qty_to_subtract = qty - subtracted_qty; + if (first_level.qty > qty_to_subtract) { + first_level = first_level.subtract_qty((uint)qty_to_subtract); + book.levels[0] = first_level; + return; + } + book.levels.RemoveAt(0); + subtracted_qty += (int)first_level.qty; + } + } + } +}