feat: Add setting to show notional values in ladder

This commit is contained in:
John Colvin committed 2025-01-21 01:24:23 -05:00
1 parent 986d53f4e0
commit 889e226151
12 files changed
+346 -231

No files matched your search

@@ -66,8 +66,12 @@ namespace mbts.spark {
_orders = orders;
_real_price = real_price;
_text_lines = backing(nameof(text_lines), () => {
var fmt = MDDisplayHelper.get_value_formatter(_owner.model.security_md.quantity_display);
return BadgeRender.format(side, _quantity, _filled, _current_badge_style, fmt);
var tf = _owner.model.security.tick_factors();
var fmt = MDDisplayHelper.get_value_formatter(
owner.current_settings.size_display,
_owner.model.security_md.quantity_display,
tf.to_api_tick_display_settingsi());
return BadgeRender.format(side, _quantity, _filled, price, _current_badge_style, fmt);
});
_clear_phantom_price = new(() => {
_phantom_price = double.NaN;
@@ -705,6 +705,7 @@ namespace mbts.spark {
public uint sample_quantity { get; } = 50;
public uint sample_filled { get; } = 12;
public double sample_price => 2175.50;
public Side sample_side { get; } = Side.Buy;
public Brush badge_border { get; } = new SolidColorBrush(BTSColors.MarketData.ask);
public Brush badge_background { get; } = Brushes.White;
@@ -94,8 +94,8 @@ namespace mbts.spark {
readonly MarketBreakLines _mkt_break_lines;
NativePriceSize _last_trade;
Func<NativePriceSize, string> _fmt_mkt_depth_item_impl = MDDisplayHelper.get_formatter_nps(
MarketSizeDisplay.get_default(), Security.Defaults.quantity_display_settingsi);
Func<double, string> _fmt_mkt_quantity_impl = v => v.ToString();
MarketSizeDisplay.get_default(), Security.Defaults.quantity_display_settingsi, Security.Defaults.price_display_settingsi);
Func<double, double, string> _fmt_mkt_quantity_impl = (v, p) => v.ToString();
int _old_tooltip_row = int.MaxValue;
NativePriceSize? _old_last_trade;
string _direction_arrow = string.Empty;
@@ -737,8 +737,8 @@ namespace mbts.spark {
};
view.RequestClose += (o, _) => popup.IsOpen = false;
}
string fmt_mbo_qty(int value) =>
value < 0 ? $"-{_fmt_mkt_quantity((uint)value)}" : _fmt_mkt_quantity((uint)value);
string fmt_mbo_qty(double value, double price) =>
value < 0 ? $"-{_fmt_mkt_quantity(value, price)}" : _fmt_mkt_quantity(value, price);
}
protected override void OnMouseDoubleClick(MouseButtonEventArgs e) {
@@ -997,8 +997,10 @@ namespace mbts.spark {
//System.Diagnostics.Debug.WriteLine(" Tooltip - Previous tooltip is visible, but we've changed rows");
_hide_tool_tip();
}
_tooltip_view.Content = _fmt_mkt_quantity(volume);
double price = row < 0 || row >= (_price_list?.Count ?? 0)
? double.NaN
: _price_for_row(row);
_tooltip_view.Content = _fmt_mkt_quantity(volume, price);
_tooltip_view.IsOpen = true;
ToolTip = _tooltip_view;
} else {
@@ -1178,8 +1180,16 @@ namespace mbts.spark {
_refresh_session_range();
if (last_trade_changed) {
var last_index = LadderRender.index_of(_price_list, _last_trade.price, _price_comparer);
if (last_index > 0)
LadderRender.render_last(_last_vis_tup.visual, _last_vis_tup.glyph_context, _last_trade, last_index, _settings.row_height, _settings.last_column, _fmt_mkt_quantity);
if (last_index > 0) {
LadderRender.render_last(
_last_vis_tup.visual,
_last_vis_tup.glyph_context,
_last_trade,
last_index,
_settings.row_height,
_settings.last_column,
_fmt_mkt_depth_item);
}
}
if (depth_changed)
_refresh_sizes();
@@ -1284,14 +1294,29 @@ namespace mbts.spark {
void _refresh_last_trade() {
var last_index = LadderRender.index_of(_price_list, _last_trade.price, _price_comparer);
if (last_index > 0)
LadderRender.render_last(_last_vis_tup.visual, _last_vis_tup.glyph_context, _last_trade, last_index, _settings.row_height, _settings.last_column, _fmt_mkt_quantity);
LadderRender.render_last(
_last_vis_tup.visual,
_last_vis_tup.glyph_context,
_last_trade,
last_index,
_settings.row_height,
_settings.last_column,
_fmt_mkt_depth_item);
}
void _refresh_piq() {
if (!_settings.piq_column.show)
return;
int origin_index = LadderRender.index_of(_price_list, _mkt_break_lines.origin, _price_comparer);
LadderRender.render_piqs(_piq_vis_tup.visual, _last_vis_tup.glyph_context, _price_list, _vm.price_vs_piq, _settings.row_height, _spec, _settings.piq_column, _fmt_mkt_quantity);
LadderRender.render_piqs(
_piq_vis_tup.visual,
_last_vis_tup.glyph_context,
_price_list,
_vm.price_vs_piq,
_settings.row_height,
_spec,
_settings.piq_column,
_fmt_mkt_quantity);
}
void _refresh_sizes() {
@@ -1353,7 +1378,7 @@ namespace mbts.spark {
}
// regardless of if we've arrived here via a new Last (and new direction arrow)
// or we're reusing the old one, this format bit is the same
return $"{_direction_arrow} {_fmt_mkt_quantity(_last_trade.size)} ";
return $"{_direction_arrow} {_fmt_mkt_quantity(_last_trade.size, _last_trade.price)} ";
}
}
@@ -1481,9 +1506,11 @@ namespace mbts.spark {
static GlyphContext glyph_context(LadderColumnSettings cs) =>
GlyphContext.create(cs.font_family, cs.font_weight);
var price_display = _spec.tick_factors(0).to_api_tick_display_settingsi();
_fmt_mkt_depth_item_impl = MDDisplayHelper.get_formatter_nps(
_settings.size_display, _qty_display);
_fmt_mkt_quantity_impl = MDDisplayHelper.get_value_formatter(_qty_display);
_settings.size_display, _qty_display, price_display);
_fmt_mkt_quantity_impl = MDDisplayHelper.get_value_formatter(
_settings.size_display, _qty_display, price_display);
_set_columns();
_apply_column_visual_offset();
if (prev_row_height != _settings.row_height)
@@ -1562,16 +1589,17 @@ namespace mbts.spark {
// Assign the impl delegate to a local variable, just in case it is reassigned on another thread.
// This shouldn't happen, but better to avoid the potential null ref just in case it does. Expect the unexpected.
var impl = _fmt_mkt_depth_item_impl;
impl ??= MDDisplayHelper.get_formatter_nps(MarketSizeDisplay.get_default(), _qty_display);
impl ??= MDDisplayHelper.get_formatter_nps(
MarketSizeDisplay.get_default(), _qty_display, _spec.tick_factors(0).to_api_tick_display_settingsi());
return impl(value);
}
// This is designed to be a redundant null check for _fmt_mkt_quantity_impl.
string _fmt_mkt_quantity(double value) {
string _fmt_mkt_quantity(double value, double price) {
// Assign the impl delegate to a local variable, just in case it is reassigned on another thread.
// This shouldn't happen, but better to avoid the potential null ref just in case it does. Expect the unexpected.
var impl = _fmt_mkt_quantity_impl;
return impl is null ? value.ToString() : impl(value);
return impl is null ? value.ToString() : impl(value, price);
}
void _init_tactile_adorner() {
@@ -31,19 +31,19 @@ namespace mbts.spark {
Side side,
double quantity,
double filled,
double price,
LadderSettings.BadgeStyle style,
Func<double, string> fmt_value = null
Func<double, double, string> fmt_value = null
) {
if (fmt_value is null)
fmt_value = FormattingDelegates.default_string<double>();
fmt_value ??= (v, p) => v.ToString();
switch (style) {
case LadderSettings.BadgeStyle.Alternate:
var working_qty = quantity > filled ? quantity - filled : 0;
return new[] {
$"{side.abbreviate()}:{fmt_value(filled)}",
$"W:{fmt_value(working_qty)}"
$"{side.abbreviate()}:{fmt_value(filled, price)}",
$"W:{fmt_value(working_qty, price)}"
};
default: return new[] { $"{fmt_value(filled)}/{fmt_value(quantity)}" };
default: return new[] { $"{fmt_value(filled, price)}/{fmt_value(quantity, price)}" };
}
}
@@ -290,7 +290,7 @@ namespace mbts.spark {
VolumeColumnSettings settings,
int last_index,
string last_size_and_direction,
Func<double, string> fmt_value) {
Func<double, double, string> fmt_value) {
//
if (!data.Any()) {
_clear_visual(dv);
@@ -313,12 +313,12 @@ namespace mbts.spark {
_clear_visual(dv);
return;
}
fmt_value ??= FormattingDelegates.default_string<double>();
fmt_value ??= (v, p) => v.ToString();
// inflate the max so that the graph never fills the available space
double max = data.Max(v => v.Volume) * 1.1;
_render_cells(dv, row_height, data.Select(d => (d.Price, d)), settings.general, prices, spec, render_cell);
/// local methods
void render_cell(DrawingContext dc, int r, VolumeAtPriceLevelImmutable vap) {
void render_cell(DrawingContext dc, int r, double price, VolumeAtPriceLevelImmutable vap) {
Brush text_brush = settings.general.foreground.rgb_brush();
double y = row_height * r;
var last_trade_here = r == last_index;
@@ -345,11 +345,11 @@ namespace mbts.spark {
}
x_bar += width;
if (show_numbers)
numbers_text.Add(fmt_value(v));
numbers_text.Add(fmt_value(v, vap.Price));
}
if (settings.total.show_numbers) {
numbers_text.Add(fmt_value(vap.Volume));
numbers_text.Add(fmt_value(vap.Volume, vap.Price));
}
if (settings.show_ltq && last_trade_here) {
numbers_text.Clear();
@@ -376,9 +376,17 @@ namespace mbts.spark {
}
}
public delegate void RenderCell<T>(DrawingContext dc, int row, T data_item);
public delegate void RenderCell<T>(DrawingContext dc, int row, double price, T data_item);
static void _render_cells<T>(DrawingVisual dv, double row_height, IEnumerable<(double price, T value)> cells, LadderColumnSettings settings, IList<double> prices, RegionalTickFactors spec, RenderCell<T> render_cell) {
static void _render_cells<T>(
DrawingVisual dv,
double row_height,
IEnumerable<(double price, T value)> cells,
LadderColumnSettings settings,
IList<double> prices,
RegionalTickFactors spec,
RenderCell<T> render_cell
) {
using (var dc = dv.RenderOpen())
using (_draw_with_clip(dc, settings, row_height, prices.Count)) {
if (prices.is_null_or_empty() || cells.is_null_or_empty()) {
@@ -398,7 +406,7 @@ namespace mbts.spark {
var check_price = spec.tickdown(max_price, idx);
Log.assert(spec.tick_equals(price, check_price));
Log.assert(idx >= 0 && idx < prices.Count);
render_cell(dc, idx, value);
render_cell(dc, idx, price, value);
}
}
}
@@ -410,10 +418,10 @@ namespace mbts.spark {
int index,
double row_height,
LadderColumnSettings settings,
Func<double, string> fmt_value) {
fmt_value ??= FormattingDelegates.default_string<double>();
Func<NativePriceSize, string> fmt_value) {
fmt_value ??= nps => nps.size.ToString();
using (var dc = dv.RenderOpen()) {
var gr = format_text(fmt_value(last.size), index, row_height, settings, glyph_context);
var gr = format_text(fmt_value(last), index, row_height, settings, glyph_context);
dc.DrawGlyphRun(settings.foreground.rgb_brush(), gr);
}
}
@@ -427,13 +435,13 @@ namespace mbts.spark {
double row_height,
RegionalTickFactors spec,
LadderColumnSettings settings,
Func<double, string> fmt_value
Func<double, double, string> fmt_value
) {
fmt_value ??= FormattingDelegates.default_string<double>();
fmt_value ??= (v, p) => v.ToString();
var fg = settings.foreground.rgb_brush();
_render_cells(dv, row_height, pvp, settings, prices, spec, (dc, row, piq) =>
_render_cells(dv, row_height, pvp, settings, prices, spec, (dc, row, price, piq) =>
dc.DrawGlyphRun(
fg, format_text(fmt_value(piq), row, row_height, settings, glyph_context)));
fg, format_text(fmt_value(piq, price), row, row_height, settings, glyph_context)));
}
public static void render_mkt_break(DrawingVisual dv, int index, double row_height, uint color) =>
@@ -457,6 +457,7 @@
<Binding Path="sample_side"/>
<Binding Path="sample_quantity"/>
<Binding Path="sample_filled"/>
<Binding Path="sample_price"/>
<Binding Path="DataContext.badge_style" RelativeSource="{RelativeSource AncestorType=usp:LadderSettingsView}"/>
</MultiBinding>
</c:Badge.TextLines>
+9 -2
View File
@@ -379,8 +379,15 @@ namespace mbts.ui.controls {
class BadgeTextLinesConverter : IMultiValueConverter {
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
if (ConvertUtils.try_convert_args(values, out Side side, out uint quantity, out uint filled, out mbts.spark.LadderSettings.BadgeStyle style))
return BadgeRender.format(side, quantity, filled, style);
if (ConvertUtils.TryConvertArgs(
values,
out Side side,
out uint quantity,
out uint filled,
out double price,
out LadderSettings.BadgeStyle style)) {
return BadgeRender.format(side, quantity, filled, price, style);
}
else return new string[0];
}
@@ -47,16 +47,16 @@ namespace mbts.spark {
readonly SecurityImmutable _security;
readonly MBOSecurityQueryImmutable _query;
readonly Dictionary<(string, bool), FormattedText> _cache;
readonly Func<int, string> _fmt_mbo_qty;
readonly Func<double, double, string> _fmt_mbo_qty;
int _max_order_size = 1;
double _height = 0;
double _number_width = 0;
public MBOPopupModel(MBOService mbo, SecurityImmutable security, MBOSecurityQueryImmutable query, Func<int, string> fmt_mbo_qty) {
public MBOPopupModel(MBOService mbo, SecurityImmutable security, MBOSecurityQueryImmutable query, Func<double, double, string> fmt_mbo_qty) {
_mbo = mbo;
_security = security;
_query = query;
_fmt_mbo_qty = fmt_mbo_qty ?? new Func<int, string>(v => v.ToString());
_fmt_mbo_qty = fmt_mbo_qty ?? new Func<double, double, string>((v, p) => v.ToString());
// prime the cache with numbers on the left hand side
_cache =
@@ -112,7 +112,7 @@ namespace mbts.spark {
pdp.row_numbers = p.orders.Select((o, i) => format_text((i + 1).ToString(), ismine(o))).ToList();
pdp.numbers_width = _number_width = Math.Max(_number_width, (int)pdp.row_numbers.Max(r => r.Width) + text_margin);
pdp.row_labels = p.orders.Select(o => format_text(_fmt_mbo_qty(o.Size) + (ismine(o) ? "*" : ""), ismine(o))).ToList();
pdp.row_labels = p.orders.Select(o => format_text(_fmt_mbo_qty(o.Size, o.Price) + (ismine(o) ? "*" : ""), ismine(o))).ToList();
var max_label_width = pdp.row_labels.Max(l => l.Width) + text_margin;
var available_width = pdp.width - pdp.numbers_width - max_label_width;
@@ -32,7 +32,8 @@ namespace mbts.ui.spark {
Merged,
Direct,
Implied,
Const
Const,
MergedNotional,
}
public static MarketSizeDisplay get_default() =>
@@ -145,51 +146,56 @@ namespace mbts.ui.spark {
new SizeFormattingElement(SizeFormattingElementType.Implied),
new SizeFormattingElement(SizeFormattingElementType.Const, ")")
};
public static SizeFormattingElement[] merged_notional => new SizeFormattingElement[] {
new(SizeFormattingElementType.MergedNotional)
};
}
}
static class MDDisplayHelper {
/// This delegate should be created by calling <see cref="get_formatter(MarketSizeDisplay)"/>
public delegate string SizeFormatter(double merged, double implied);
public delegate string SizeFormatter(double merged, double implied, double price);
/// The private delegates below use refs bc the <see cref="SizeFormatter"/> returned by <see cref="get_formatter(MarketSizeDisplay)"/>
/// internally uses several <see cref="_SizeFormatter"/>s to add different text components to the resultant string.
/// The refs, therefor, avoid making extra copies of the variables.
/// These are private members, so any code-readability cost is confined to a limited scope.
delegate void _SizeFormatter(ref double merged, ref double implied, ref StringBuilder sb);
delegate void _SizeFormatter(ref double merged, ref double implied, ref double price, ref StringBuilder sb);
delegate void _SizeFormatterNPS(ref NativePriceSize nps, ref StringBuilder sb);
public static Func<double, string> get_value_formatter(double divisor) =>
value => (value / divisor).ToString();
public static Func<double, string> get_value_formatter(
TickDisplaySettingsImmutable display) =>
v => display.format(v);
public static Func<NativePriceSize, string> get_formatter_nps(
MarketSizeDisplay size_display, TickDisplaySettingsImmutable display) {
var raw_fmt_size = get_formatter(size_display, display);
return nps => raw_fmt_size(
nps.implied_size + nps.direct_size,
nps.implied_size);
public static Func<double, double, string> get_value_formatter(
MarketSizeDisplay size_display, TickDisplaySettingsImmutable display, TickDisplaySettingsImmutable price_display) {
var raw_fmt_size = get_formatter(size_display, display, price_display);
return (q, p) => raw_fmt_size(q, 0, p);
}
public static SizeFormatter get_formatter(MarketSizeDisplay size_display, TickDisplaySettingsImmutable display) {
_SizeFormatter implied_absent = _get_formatter(size_display.normal, display);
public static Func<NativePriceSize, string> get_formatter_nps(
MarketSizeDisplay size_display, TickDisplaySettingsImmutable display, TickDisplaySettingsImmutable price_display) {
var raw_fmt_size = get_formatter(size_display, display, price_display);
return nps => raw_fmt_size(
nps.implied_size + nps.direct_size,
nps.implied_size,
nps.price);
}
public static SizeFormatter get_formatter(
MarketSizeDisplay size_display, TickDisplaySettingsImmutable display, TickDisplaySettingsImmutable price_display) {
_SizeFormatter implied_absent = _get_formatter(size_display.normal, display, price_display);
_SizeFormatter implied_present = _get_formatter(
size_display.implied_present ?? size_display.normal, display);
return (merged, implied) => {
size_display.implied_present ?? size_display.normal, display, price_display);
return (merged, implied, price) => {
StringBuilder sb = new StringBuilder();
(implied > 0 ? implied_present : implied_absent)(ref merged, ref implied, ref sb);
(implied > 0 ? implied_present : implied_absent)(ref merged, ref implied, ref price, ref sb);
return sb.ToString();
};
}
static _SizeFormatterNPS _get_formatter_nps(
MarketSizeDisplay.SizeFormattingElement[] fmt_elements,
TickDisplaySettingsImmutable display) {
TickDisplaySettingsImmutable display,
TickDisplaySettingsImmutable price_display) {
var formatters = fmt_elements.is_null_or_empty() ?
Array.Empty<_SizeFormatterNPS>() :
CollectionHelper.convert_array(fmt_elements, sfe => _get_formatter_nps(sfe, display));
CollectionHelper.convert_array(fmt_elements, sfe => _get_formatter_nps(sfe, display, price_display));
return new _SizeFormatterNPS((ref NativePriceSize nps, ref StringBuilder sb) => {
foreach (var f in formatters)
f(ref nps, ref sb);
@@ -198,19 +204,21 @@ namespace mbts.ui.spark {
static _SizeFormatter _get_formatter(
MarketSizeDisplay.SizeFormattingElement[] fmt_elements,
TickDisplaySettingsImmutable display) {
TickDisplaySettingsImmutable display,
TickDisplaySettingsImmutable price_display) {
_SizeFormatter[] formatters = fmt_elements.is_null_or_empty() ?
Array.Empty<_SizeFormatter>() :
CollectionHelper.convert_array(fmt_elements, sfe => _get_formatter(sfe, display));
return new _SizeFormatter((ref double m, ref double i, ref StringBuilder sb) => {
CollectionHelper.convert_array(fmt_elements, sfe => _get_formatter(sfe, display, price_display));
return new _SizeFormatter((ref double m, ref double i, ref double p, ref StringBuilder sb) => {
foreach (var f in formatters)
f(ref m, ref i, ref sb);
f(ref m, ref i, ref p, ref sb);
});
}
static _SizeFormatterNPS _get_formatter_nps(
MarketSizeDisplay.SizeFormattingElement fmt_element,
TickDisplaySettingsImmutable display) =>
TickDisplaySettingsImmutable display,
TickDisplaySettingsImmutable price_display) =>
fmt_element.type switch {
MarketSizeDisplay.SizeFormattingElementType.Const =>
SizeTokenFormatters.char_formatter_nps(fmt_element.data ?? string.Empty),
@@ -220,13 +228,16 @@ namespace mbts.ui.spark {
SizeTokenFormatters.implied_formatter_nps(display),
MarketSizeDisplay.SizeFormattingElementType.Merged =>
SizeTokenFormatters.merged_formatter_nps(display),
MarketSizeDisplay.SizeFormattingElementType.MergedNotional =>
SizeTokenFormatters.merged_notional_formatter_nps(price_display),
_ => throw ExceptionBuilder.Argument.unexpected_case(
fmt_element.type, nameof(fmt_element.type)),
};
static _SizeFormatter _get_formatter(
MarketSizeDisplay.SizeFormattingElement fmt_element,
TickDisplaySettingsImmutable display) =>
TickDisplaySettingsImmutable display,
TickDisplaySettingsImmutable price_display) =>
fmt_element.type switch {
MarketSizeDisplay.SizeFormattingElementType.Const =>
SizeTokenFormatters.char_formatter(fmt_element.data ?? string.Empty),
@@ -236,6 +247,8 @@ namespace mbts.ui.spark {
SizeTokenFormatters.implied_formatter(display),
MarketSizeDisplay.SizeFormattingElementType.Merged =>
SizeTokenFormatters.merged_formatter(display),
MarketSizeDisplay.SizeFormattingElementType.MergedNotional =>
SizeTokenFormatters.merged_notional_formatter(price_display),
_ => throw ExceptionBuilder.Argument.unexpected_case(
fmt_element.type, nameof(fmt_element.type)),
};
@@ -243,16 +256,24 @@ namespace mbts.ui.spark {
static class SizeTokenFormatters {
public static _SizeFormatter char_formatter(string data) {
string local = data.ToString();
return new _SizeFormatter((ref double m, ref double i, ref StringBuilder sb) => sb.Append(local));
return (ref double m, ref double i, ref double p, ref StringBuilder sb) =>
sb.Append(local);
}
public static _SizeFormatter merged_formatter(TickDisplaySettingsImmutable display) =>
(ref double m, ref double i, ref StringBuilder sb) => sb.Append(display.format(m));
(ref double m, ref double i, ref double p, ref StringBuilder sb) =>
sb.Append(display.format(m));
public static _SizeFormatter direct_formatter(TickDisplaySettingsImmutable display) =>
(ref double m, ref double i, ref StringBuilder sb) => sb.Append(display.format(m - i));
(ref double m, ref double i, ref double p, ref StringBuilder sb) =>
sb.Append(display.format(m - i));
public static _SizeFormatter implied_formatter(TickDisplaySettingsImmutable display) =>
(ref double m, ref double i, ref StringBuilder sb) => sb.Append(display.format(i));
(ref double m, ref double i, ref double p, ref StringBuilder sb) =>
sb.Append(display.format(i));
public static _SizeFormatter merged_notional_formatter(TickDisplaySettingsImmutable display) =>
(ref double m, ref double i, ref double p, ref StringBuilder sb) =>
sb.Append(display.format(m * p));
public static _SizeFormatterNPS char_formatter_nps(string data) {
string local = data.ToString();
@@ -270,6 +291,10 @@ namespace mbts.ui.spark {
public static _SizeFormatterNPS implied_formatter_nps(TickDisplaySettingsImmutable display) =>
(ref NativePriceSize nps, ref StringBuilder sb) =>
sb.Append(display.format((double)nps.implied_size));
public static _SizeFormatterNPS merged_notional_formatter_nps(TickDisplaySettingsImmutable display) =>
(ref NativePriceSize nps, ref StringBuilder sb) =>
sb.Append(display.format(nps.notional_size));
}
}
@@ -299,6 +324,7 @@ namespace mbts.ui.spark {
string.Concat(MarketSizeDisplay.SizeFormattingElement.merged_implied),
string.Concat(MarketSizeDisplay.SizeFormattingElement.merged_direct_implied),
string.Concat(MarketSizeDisplay.SizeFormattingElement.merged),
string.Concat(MarketSizeDisplay.SizeFormattingElement.merged_notional),
};
public IEnumerable<string> alternate_implied_format_options { get; } = new[] {
@@ -307,6 +333,7 @@ namespace mbts.ui.spark {
string.Concat(MarketSizeDisplay.SizeFormattingElement.merged_implied),
string.Concat(MarketSizeDisplay.SizeFormattingElement.merged_direct),
string.Concat(MarketSizeDisplay.SizeFormattingElement.merged_direct_implied),
string.Concat(MarketSizeDisplay.SizeFormattingElement.merged_notional),
};
public string selected_format {
@@ -347,8 +374,8 @@ namespace mbts.ui.spark {
string fmt() {
var impl = MDDisplayHelper.get_formatter(
owner.create(), Security.Defaults.quantity_display_settingsi);
return impl(merged, implied);
owner.create(), Security.Defaults.quantity_display_settingsi, Security.Defaults.price_display_settingsi);
return impl(merged, implied, 1);
}
}
@@ -41,6 +41,7 @@ namespace mbts.co2 {
public Size size => _size;
public Size direct_size => _direct_size;
public Size implied_size => _size - _direct_size;
public double notional_size => price * size;
public double price => _price.price();
public bool is_nan => _price.is_nan;
@@ -7,6 +7,7 @@ namespace mbts {
using mbts.user.settings;
using Spark.Core;
using Spark.Core.Math;
using System;
using System.Collections.Generic;
@@ -95,7 +96,7 @@ namespace mbts {
public static double reduced_base(this TickFactors tick) => MathUtils.factor_out(tick.tick_base, 10);
public static bool tick_equals(this RegionalTickFactors regional_tick, double x, double y) {
public static bool tick_equals(this RegionalTickFactors regional_tick, double x, double y, RoundingMode rounding_mode = RoundingMode.Closest) {
if (x.is_nan()) {
return y.is_nan();
}
@@ -107,15 +108,15 @@ namespace mbts {
return xtick is not null
&& ytick is not null
&& xtick.Equals(ytick)
&& xtick.tick_equals(x, y);
&& xtick.tick_equals(x, y, rounding_mode);
}
public static bool tick_equals(this TickFactors tick, double x, double y) {
public static bool tick_equals(this TickFactors tick, double x, double y, RoundingMode rounding_mode = RoundingMode.Closest) {
if (x.is_nan()) {
return y.is_nan();
}
var x_units = MathUtils.round_fractional_units(x, tick.tick_unit_frac());
var y_units = MathUtils.round_fractional_units(y, tick.tick_unit_frac());
var x_units = MathUtils.round_fractional_units(x, tick.tick_unit_frac(), rounding_mode, TickUtils.precision_const<double>());
var y_units = MathUtils.round_fractional_units(y, tick.tick_unit_frac(), rounding_mode, TickUtils.precision_const<double>());
return x_units == y_units;
}
@@ -137,10 +138,10 @@ namespace mbts {
x => NumericCastConverter<T, int>.convert(
MathUtils.round_fractional_units(x, tick.tick_unit_frac<T>())));
public static IEqualityComparer<double> tick_equality_comparer(this TickFactors tick) =>
public static IEqualityComparer<double> tick_equality_comparer(this TickFactors tick, RoundingMode rounding_mode = RoundingMode.Closest) =>
EqualityComparer.Create<double>(
(a, b) => tick_equals(tick, a, b),
x => (int)MathUtils.round_fractional_units(x, tick.tick_unit_frac()));
(a, b) => tick_equals(tick, a, b, rounding_mode),
x => (int)MathUtils.round_fractional_units(x, tick.tick_unit_frac(), rounding_mode));
public static TickFactors get_tick_for(this RegionalTickFactors rtick, double value) =>
value > rtick.low_tick_inclusive_end ? rtick.high_tick : rtick.low_tick;
+163 -143
View File
@@ -1,143 +1,163 @@
namespace System {
using bts;
using System.Diagnostics.CodeAnalysis;
public static class ConvertUtils {
public static object try_convert(Type type, object obj) {
try_convert(type, obj, out object result);
return result;
}
#nullable enable
public static bool try_convert<T>(
object obj,
[NotNullWhen(true)]out T? result,
LogLevel? log_level = null,
LogSubsystem log_subsystem = LogSubsystem.gen,
string? name = null) {
if (obj is T t) {
result = t;
return true;
}
if (try_convert(typeof(T), obj, out var result_obj)) {
result = (T)result_obj;
return true;
}
if (log_level.HasValue) {
name = name is null ? "obj" : $"'{name}'";
var msg = $"Expected {name} to be of type '{typeof(T)}', actually " +
$"'{obj?.GetType()?.ToString() ?? "null"}'.";
Log.log(new(log_subsystem, log_level.Value, msg));
}
result = default;
return false;
}
#nullable disable
public static bool try_convert(Type type, object obj, out object result) {
if (obj == null) {
result = get_default(type);
return false;
} else if (type.IsPrimitive && obj is IConvertible) {
result = Convert.ChangeType(obj, type);
return true;
} else if (type.IsAssignableFrom(obj.GetType())) {
result = obj;
return true;
} else if (type.IsEnum && obj is string) {
result = try_parse_enum(type, obj.ToString());
return true;
} else if (type.IsNullable()) {
if (try_convert(type.GetGenericArguments()[0], obj, out result)) {
return true;
}
result = null;
return false;
} else {
result = get_default(type);
return false;
}
}
public static T try_convert<T>(object obj) =>
(T)try_convert(typeof(T), obj);
public static T try_convert<T>(object obj, T default_value) =>
try_convert(obj, out T result) ? result : default_value;
public static bool try_convert<T>(object obj, out T result) {
bool rv = try_convert(typeof(T), obj, out object r_obj);
result = (T)r_obj;
return rv;
}
public static object get_default(Type type) =>
type.IsValueType ? Activator.CreateInstance(type) : null;
public static T ValueOrDefault<T>(T? nullable) where T : struct => nullable.HasValue ? nullable.Value : default;
public static bool is_compatible<T>(object obj) { return obj is T || (obj == null && default(T) == null); }
public static bool try_convert_args<T1, T2>(object[] args, out T1 arg1, out T2 arg2) {
if (args == null || args.Length != 2) {
arg1 = default;
arg2 = default;
return false;
}
bool rv = try_convert(args[0], out arg1);
rv |= try_convert(args[1], out arg2);
return rv;
}
public static bool try_convert_args<T1, T2, T3>(object[] args, out T1 arg1, out T2 arg2, out T3 arg3) {
if (args == null || args.Length != 3) {
arg1 = default;
arg2 = default;
arg3 = default;
return false;
}
bool rv = try_convert(args[0], out arg1);
rv |= try_convert(args[1], out arg2);
rv |= try_convert(args[2], out arg3);
return rv;
}
public static bool try_convert_args<T1, T2, T3, T4>(object[] args, out T1 arg1, out T2 arg2, out T3 arg3, out T4 arg4) {
if (args == null || args.Length != 4) {
arg1 = default;
arg2 = default;
arg3 = default;
arg4 = default;
return false;
}
bool rv = try_convert(args[0], out arg1);
rv |= try_convert(args[1], out arg2);
rv |= try_convert(args[2], out arg3);
rv |= try_convert(args[3], out arg4);
return rv;
}
public static object try_parse_enum(Type enum_type, string value, bool ignore_case = true) {
if (!enum_type.IsEnum) throw new ArgumentException("Must an enum type.", nameof(enum_type));
Array vals = Enum.GetValues(enum_type);
var str_comp = ignore_case ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
foreach (object v in vals) {
if (string.Equals(v.ToString(), value, str_comp))
return v;
}
return Activator.CreateInstance(enum_type);
}
public static bool update_value_type<T>(ref T field, T newval) where T : struct, IEquatable<T> {
bool rv = !field.Equals(newval);
field = newval;
return rv;
}
public static class CastDelegate<T, TResult> {
public static readonly Func<T, TResult> value =
v => v is TResult r ? r : throw new InvalidCastException($"Failed to cast element in source collection from type {typeof(T)} to {typeof(TResult)}.");
}
}
}
namespace System {
using bts;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
public static class ConvertUtils {
public static object try_convert(Type type, object obj) {
try_convert(type, obj, out object result);
return result;
}
#nullable enable
public static bool try_convert<T>(
object obj,
[NotNullWhen(true)]out T? result,
LogLevel? log_level = null,
LogSubsystem log_subsystem = LogSubsystem.gen,
string? name = null) {
if (obj is T t) {
result = t;
return true;
}
if (try_convert(typeof(T), obj, out var result_obj)) {
result = (T)result_obj;
return true;
}
if (log_level.HasValue) {
name = name is null ? "obj" : $"'{name}'";
var msg = $"Expected {name} to be of type '{typeof(T)}', actually " +
$"'{obj?.GetType()?.ToString() ?? "null"}'.";
Log.log(new(log_subsystem, log_level.Value, msg));
}
result = default;
return false;
}
#nullable disable
public static bool try_convert(Type type, object obj, out object result) {
if (obj == null) {
result = get_default(type);
return false;
} else if (type.IsPrimitive && obj is IConvertible) {
result = Convert.ChangeType(obj, type);
return true;
} else if (type.IsAssignableFrom(obj.GetType())) {
result = obj;
return true;
} else if (type.IsEnum && obj is string) {
result = try_parse_enum(type, obj.ToString());
return true;
} else if (type.IsNullable()) {
if (try_convert(type.GetGenericArguments()[0], obj, out result)) {
return true;
}
result = null;
return false;
} else {
result = get_default(type);
return false;
}
}
public static T try_convert<T>(object obj) =>
(T)try_convert(typeof(T), obj);
public static T try_convert<T>(object obj, T default_value) =>
try_convert(obj, out T result) ? result : default_value;
public static bool try_convert<T>(object obj, out T result) {
bool rv = try_convert(typeof(T), obj, out object r_obj);
result = (T)r_obj;
return rv;
}
public static object get_default(Type type) =>
type.IsValueType ? Activator.CreateInstance(type) : null;
public static T ValueOrDefault<T>(T? nullable) where T : struct => nullable.HasValue ? nullable.Value : default;
public static bool is_compatible<T>(object obj) { return obj is T || (obj == null && default(T) == null); }
public static bool try_convert_args<T1, T2>(object[] args, out T1 arg1, out T2 arg2) {
if (args == null || args.Length != 2) {
arg1 = default;
arg2 = default;
return false;
}
bool rv = try_convert(args[0], out arg1);
rv |= try_convert(args[1], out arg2);
return rv;
}
public static bool try_convert_args<T1, T2, T3>(object[] args, out T1 arg1, out T2 arg2, out T3 arg3) {
if (args == null || args.Length != 3) {
arg1 = default;
arg2 = default;
arg3 = default;
return false;
}
bool rv = try_convert(args[0], out arg1);
rv |= try_convert(args[1], out arg2);
rv |= try_convert(args[2], out arg3);
return rv;
}
public static bool try_convert_args<T1, T2, T3, T4>(object[] args, out T1 arg1, out T2 arg2, out T3 arg3, out T4 arg4) {
if (args == null || args.Length != 4) {
arg1 = default;
arg2 = default;
arg3 = default;
arg4 = default;
return false;
}
bool rv = try_convert(args[0], out arg1);
rv |= try_convert(args[1], out arg2);
rv |= try_convert(args[2], out arg3);
rv |= try_convert(args[3], out arg4);
return rv;
}
public static bool TryConvertArgs<T1, T2, T3, T4, T5>(IEnumerable<object> args, out T1 arg1, out T2 arg2, out T3 arg3, out T4 arg4, out T5 arg5) {
using var en = args.GetEnumerator();
bool success = true;
convertNext(en, ref success, out arg1);
convertNext(en, ref success, out arg2);
convertNext(en, ref success, out arg3);
convertNext(en, ref success, out arg4);
convertNext(en, ref success, out arg5);
return success;
}
public static object try_parse_enum(Type enum_type, string value, bool ignore_case = true) {
if (!enum_type.IsEnum) throw new ArgumentException("Must an enum type.", nameof(enum_type));
Array vals = Enum.GetValues(enum_type);
var str_comp = ignore_case ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;
foreach (object v in vals) {
if (string.Equals(v.ToString(), value, str_comp))
return v;
}
return Activator.CreateInstance(enum_type);
}
public static bool update_value_type<T>(ref T field, T newval) where T : struct, IEquatable<T> {
bool rv = !field.Equals(newval);
field = newval;
return rv;
}
static void convertNext<T>(IEnumerator<object> enumerator, ref bool success, out T arg) {
if (!success || !enumerator.MoveNext()) {
arg = default;
success = false;
}
success = try_convert(enumerator.Current, out arg);
}
public static class CastDelegate<T, TResult> {
public static readonly Func<T, TResult> value =
v => v is TResult r ? r : throw new InvalidCastException($"Failed to cast element in source collection from type {typeof(T)} to {typeof(TResult)}.");
}
}
}
@@ -1,5 +1,6 @@
namespace bts.utils {
using Spark.Core;
using Spark.Core.Math;
using System;
using System.Collections.Generic;
@@ -194,6 +195,22 @@ namespace bts.utils {
public static T round_fractional_units<T>(T value, T fractional_unit) where T : IFloatingPoint<T> =>
T.Round(value / fractional_unit);
public static T round_fractional_units<T>(T value, T fractional_unit, RoundingMode rounding_mode) where T : struct, IFloatingPoint<T> =>
round_fractional_units(value, fractional_unit, rounding_mode, T.Zero);
public static T round_fractional_units<T>(T value, T fractional_unit, RoundingMode rounding_mode, T epsilon) where T : IFloatingPoint<T> =>
rounding_mode switch {
RoundingMode.Up => T.Ceiling((value - epsilon) / fractional_unit),
RoundingMode.Down => T.Floor((value + epsilon) / fractional_unit),
RoundingMode.AbsUp => value < T.Zero
? T.Floor((value + epsilon) / fractional_unit)
: T.Ceiling((value - epsilon) / fractional_unit),
RoundingMode.AbsDown => value < T.Zero
? T.Ceiling((value - epsilon) / fractional_unit)
: T.Floor((value + epsilon) / fractional_unit),
_ => T.Round(value / fractional_unit),
};
public static double round_down_abs(double value) =>
round_down_abs(value, EPSILON);