Consolidate tick rounding functions

Too many functions were performing essentially the same service:
rounding ticks. It was confusing.
This commit is contained in:
John Colvin committed 2025-01-09 01:03:32 -05:00
1 parent 4fdc866485
commit c7dfd69b90
7 files changed
+1027 -1095

No files matched your search

File diff suppressed because it is too large. Load diff
@@ -1401,7 +1401,10 @@ namespace mbts.spark {
double _get_bid_market_break() {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return LadderPriceLineViewAdapter.bid_line(best_bid, best_ask, _vm.settlement, _spec);
var v = best_bid
.if_nan(_spec.tickdown(best_ask))
.if_nan(_vm.settlement);
return _spec.round_to_tick(v, RoundingMode.AbsDown);
}
double _normalize_price(double price) =>
@@ -1410,13 +1413,20 @@ namespace mbts.spark {
double _get_ask_market_break() {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return LadderPriceLineViewAdapter.ask_line(best_bid, best_ask, _vm.settlement, _spec);
var v = _spec.tickdown(best_ask)
.if_nan(best_bid)
.if_nan(_vm.settlement);
return _spec.round_to_tick(v, RoundingMode.AbsDown);
}
double _get_mid_market_break() {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return LadderPriceLineViewAdapter.mid_line(best_bid, best_ask, _vm.settlement, _spec);
var v = TickUtils.mid_tick(_spec, best_bid, best_ask)
.if_nan(best_bid)
.if_nan(_spec?.tickdown(best_ask) ?? double.NaN)
.if_nan(_vm.settlement);
return _spec.round_to_tick(v, RoundingMode.AbsDown);
}
double _get_session_low() => _normalize_price(_get_session_low_raw());
@@ -1,62 +0,0 @@
using bts.api;
namespace mbts.spark {
using RegionalTickFactors = user.settings.RegionalTickFactors;
class LadderPriceLineViewAdapter {
public static double bid_line(
double bid, double ask, double settlement, RegionalTickFactors spec) {
return TickUtils.normalize_price(spec, impl());
double impl() {
if (!double.IsNaN(bid)) {
return bid;
}
if (!double.IsNaN(ask)) {
return _try_tick_down(spec, ask);
}
return settlement;
}
}
public static double ask_line(
double bid, double ask, double settlement, RegionalTickFactors spec) {
return TickUtils.normalize_price(spec, impl());
double impl() {
if (!double.IsNaN(ask)) {
return _try_tick_down(spec, ask);
}
if (!double.IsNaN(bid)) {
return bid;
}
return settlement;
}
}
public static double mid_line(
double bid, double ask, double settlement, RegionalTickFactors spec) {
return TickUtils.normalize_price(spec, impl());
double impl() {
if (double.IsNaN(bid)) {
if (double.IsNaN(ask)) {
return settlement;
}
return _try_tick_down(spec, ask);
}
if (double.IsNaN(ask)) {
return bid;
}
if (spec is not null) {
return TickUtils.mid_tick(spec, bid, ask);
}
return bid;
}
}
static double _try_tick_down(RegionalTickFactors spec, double value) {
if (spec is not null) {
return spec.tickdown(value);
}
return value;
}
}
}
@@ -63,7 +63,7 @@ namespace mbts {
if (ticks_per_base.is_int()) {
return true;
}
return tick.tick_unit > tick.tick_base && tick.tick_base == 1;
return tick.tick_unit > tick.tick_base && tick.tick_unit_frac().is_int();
}
public static bool is_valid(this RegionalTickFactors regional_tick) =>
@@ -179,10 +179,7 @@ namespace mbts {
if (T.IsInfinity(value)) {
return value.ToString();
}
return tick?.is_valid() ?? false ?
_format_tick(tick, value, settings) :
_format_no_tick(
value, settings.display_multiplier.as_type<double, T>(), settings.show_commas);
return _format_tick(tick, value, settings);
}
public static string format<T>(
+60 -93
View File
@@ -6,6 +6,7 @@ using bts.utils;
using mbts.user.settings;
using Spark.Core;
using Spark.Core.Math;
using System;
using System.Collections.Generic;
@@ -189,52 +190,58 @@ namespace mbts.spark {
public static int compare_tick_fallback_to_double(this ContractSpecificationImmutable contract, double x, double y) =>
tick_equals(contract, x, y) ? 0 : x.CompareTo(y);
public static double round_to_tick(this ContractSpecificationImmutable spec, double value) =>
round_to_tick(spec.ticksize(value), value);
public static double round_to_tick(this ContractSpecificationImmutable spec, double value, RoundingMode rounding_mode = RoundingMode.Closest) =>
round_to_tick(spec.ticksize(value), value, rounding_mode);
public static decimal round_to_tick(this ContractSpecificationImmutable spec, decimal value) =>
round_to_tick((decimal)spec.ticksize((double)value), value);
public static decimal round_to_tick(this ContractSpecificationImmutable spec, decimal value, RoundingMode rounding_mode = RoundingMode.Closest) =>
round_to_tick((decimal)spec.ticksize((double)value), value, rounding_mode);
public static double round_to_tick(this RegionalTickFactors rtick, double value) =>
round_to_tick(rtick.ticksize(value), value);
public static double round_to_tick(this RegionalTickFactors rtick, double value, RoundingMode rounding_mode = RoundingMode.Closest) =>
round_to_tick(rtick.ticksize(value), value, rounding_mode);
public static decimal round_to_tick(this RegionalTickFactors rtick, decimal value) =>
round_to_tick((decimal)rtick.ticksize((double)value), value);
public static decimal round_to_tick(this RegionalTickFactors rtick, decimal value, RoundingMode rounding_mode = RoundingMode.Closest) =>
round_to_tick((decimal)rtick.ticksize((double)value), value, rounding_mode);
public static double round_to_tick(double tick_size, double value) {
double intpart = (long)value;
double floatpart = value % 1;
floatpart = ((int)Math.Round(floatpart / tick_size)) * tick_size;
return intpart + floatpart;
public static double round_to_tick(double tick_size, double value, RoundingMode rounding_mode = RoundingMode.Closest) {
double n = rounding_mode switch {
RoundingMode.Closest => Math.Round(value / tick_size),
RoundingMode.Up => Math.Ceiling((value - _precision_const) / tick_size),
RoundingMode.Down => Math.Floor((value + _precision_const) / tick_size),
RoundingMode.AbsUp => value < 0
? Math.Floor((value + _precision_const) / tick_size)
: Math.Ceiling((value - _precision_const) / tick_size),
RoundingMode.AbsDown => value < 0
? Math.Ceiling((value - _precision_const) / tick_size)
: Math.Floor((value + _precision_const) / tick_size),
_ => double.NaN,
};
return n * tick_size;
}
public static decimal round_to_tick(decimal tick_size, decimal value) {
decimal intpart = (long)value;
decimal floatpart = value % 1;
floatpart = ((int)(floatpart / tick_size)) * tick_size;
return intpart + floatpart;
public static decimal round_to_tick(decimal tick_size, decimal value, RoundingMode rounding_mode = RoundingMode.Closest) {
decimal n = rounding_mode switch {
RoundingMode.Closest => Math.Round(value / tick_size),
RoundingMode.Up => Math.Ceiling(value / tick_size),
RoundingMode.Down => Math.Floor(value / tick_size),
RoundingMode.AbsUp => value < 0
? Math.Floor(value / tick_size)
: Math.Ceiling(value / tick_size),
RoundingMode.AbsDown => value < 0
? Math.Ceiling(value / tick_size)
: Math.Floor(value / tick_size),
_ => throw new ArgumentException("Invalid rounding mode", nameof(rounding_mode)),
};
return n * tick_size;
}
public static long? count_ticks(this RegionalTickFactors rtick, double value) {
if (!rtick.is_valid()) {
return null;
}
public static long? count_ticks(this RegionalTickFactors rtick, double value, RoundingMode rounding_mode = RoundingMode.AbsDown) {
var rounded_value = rtick.round_to_tick(value, rounding_mode);
var n = _count_ticks(
rtick.low_tick.tick_unit_frac(),
rtick.low_tick_inclusive_end,
rtick.high_tick.tick_unit_frac(),
0,
value);
var orig_n = n;
// Enforce proper rounding
var rounded_val = rtick.round_to_tick(value);
var half_tick = rtick.get_tick_for(value).tick_unit_frac() / 2;
if (n < 0 && (value - rounded_val) > half_tick) {
++n;
} else if (n > 0 && (rounded_val - value) > half_tick) {
--n;
}
Log.assert(n == orig_n);
rounded_value);
return n;
}
@@ -253,71 +260,19 @@ namespace mbts.spark {
return tick;
}
public static RegionalTickFactors multiply_tick_size(RegionalTickFactors spec, uint factor) {
factor = _fit_ticks_per_row_to_dollars(spec, factor) ?? 1;
return new(
public static RegionalTickFactors multiply_tick_size(RegionalTickFactors spec, uint factor) =>
new(
new(spec.low_tick.tick_base, spec.low_tick.tick_unit * factor),
new(spec.high_tick.tick_base, spec.high_tick.tick_unit * factor),
spec.low_tick_inclusive_end);
}
public static double normalize_price(RegionalTickFactors rtick, double price) {
if (!price.is_real()) {
var maybe_ticks = rtick.count_ticks(price);
if (!maybe_ticks.HasValue) {
return price;
}
var ticks = rtick.count_ticks(price);
if (!ticks.HasValue) {
return price;
}
var normalized = rtick.tick(0, ticks.Value);
var tick = price > rtick.low_tick_inclusive_end ? rtick.high_tick : rtick.low_tick;
// Diff should always be < 1/2 tick
Log.assert((normalized - price).abs() < tick.tick_unit_frac() * 0.5);
return normalized;
}
public static uint fit_ticks_per_row_to_dollars(SecurityImmutable sec, uint ticks_per_row) =>
_fit_ticks_per_row_to_dollars(sec, ticks_per_row) ?? 1;
public static uint fit_ticks_per_row_to_dollars(RegionalTickFactors rtick, uint ticks_per_row) =>
_fit_ticks_per_row_to_dollars(rtick, ticks_per_row) ?? 1;
static uint? _fit_ticks_per_row_to_dollars(SecurityImmutable sec, uint ticks_per_row) =>
_fit_ticks_per_row_to_dollars(sec.regional_ticks(), ticks_per_row);
static uint? _fit_ticks_per_row_to_dollars(RegionalTickFactors tf, uint ticks_per_row) {
if (ticks_per_row == 0)
return null;
// it is assumed that low tick will be the same as high tick;
// however, best to double check - return null if this isn't the case (let the caller decide what to do).
if (!tf.low_tick.Equals(tf.high_tick) || !tf.is_valid() || tf.low_tick.is_integer())
return null;
var ticks_per_dollar = (uint)(tf.low_tick.tick_base / tf.low_tick.tick_unit);
// if ticks_per_row is greater than ticks_per_dollar, round to a multiple of ticks_per_dollar
if (ticks_per_row > ticks_per_dollar) {
if (ticks_per_dollar == 0) {
return null;
}
return (uint)(ticks_per_dollar * Math.Floor((double)(ticks_per_row / ticks_per_dollar)));
} else if (ticks_per_row == ticks_per_dollar) {
return ticks_per_row;
} else {
uint max_decrease_adj = ticks_per_row;
uint max_increase_adj = ticks_per_dollar - ticks_per_row - 1;
for (uint adj = 0; adj < Math.Max(max_decrease_adj, max_increase_adj); adj++) {
if (adj < max_decrease_adj) {
var result = ticks_per_row - adj;
if (ticks_per_dollar % result == 0)
return result;
}
if (adj < max_increase_adj) {
var result = ticks_per_row + adj;
if (ticks_per_dollar % result == 0)
return result;
}
}
}
return null;
var ticks = maybe_ticks.Value;
return rtick.tick(0, (long)ticks);
}
static long? _count_ticks(
@@ -367,8 +322,20 @@ namespace mbts.spark {
static long count_single_tick_sz(
double tick_sz, double from, double to) {
var from_n = (long)MathUtils.round_fractional_units(from, tick_sz);
var to_n = (long)MathUtils.round_fractional_units(to, tick_sz);
from = round_to_tick(tick_sz, from, RoundingMode.AbsDown);
to = round_to_tick(tick_sz, to, RoundingMode.AbsDown);
if (from < 0) {
from -= _precision_const;
} else {
from += _precision_const;
}
if (to < 0) {
to -= _precision_const;
} else {
to += _precision_const;
}
var from_n = (long)(from / tick_sz);
var to_n = (long)(to / tick_sz);
return to_n - from_n;
}
}
@@ -0,0 +1,17 @@
#nullable enable
namespace Spark.Core.Math;
public enum RoundingMode {
None,
// Round to the closest integer (up if decimal part is >= 0.5, otherwise down)
Closest,
// Round up
Up,
// Round down
Down,
// Round positive numbers up, and negative numbers down
AbsUp,
// Round positive numbers down, and negative numbers up
AbsDown
}
+3 -1
View File
@@ -6,6 +6,8 @@ using mbts;
using mbts.spark;
using mbts.user.settings;
using Spark.Core.Math;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -159,7 +161,7 @@ namespace bts.tests.security {
var price_break = tick.low_tick_inclusive_end;
foreach (var p in prices) {
var expected_ticks_from_zero = TickTestHelper.count_ticks(tick, p);
var actual_ticks_from_zero = TickUtils.count_ticks(tick, p);
var actual_ticks_from_zero = TickUtils.count_ticks(tick, p, RoundingMode.Closest);
Assert.That(expected_ticks_from_zero == actual_ticks_from_zero,
$"Expected ticks from zero to be '{expected_ticks_from_zero}', actually '{actual_ticks_from_zero}' " +
$"(low/high/pricebreak: {tick.low_tick}/{tick.high_tick}/{price_break}, price: {p}).");