refactor: Enable nullability in Bts.Spark.Api

This commit is contained in:
John Colvin committed 2026-03-08 16:00:50 +00:00
1 parent de3e491843
commit baa43cbecf
66 files changed
+315 -307

No files matched your search

+1 -1
View File
@@ -146,7 +146,7 @@ namespace bts {
var qtyDisplay = meta.HasValue && meta.Value.HasQuantityDisplay ? meta.Value.QuantityDisplay : Security.Defaults.quantity_display_settingsi;
if (sec.HasContractSpec) {
var pd = priceDisplay.CloneToMutable();
pd.TickFactors = TickUtils.get_tick(sec, 0).to_api_tick_factors();
pd.TickFactors = sec.tick_factors().to_api_tick_factors();
priceDisplay = new(pd);
if (sec.ContractSpec.QuantityInfos.TryGetFirst(out var qtyInfo)) {
var qd = qtyDisplay.CloneToMutable();
@@ -73,7 +73,7 @@ namespace Spark.Trading {
meta.Value.Value.PriceDisplay : Security.Defaults.price_display_settingsi;
if (security.HasValue) {
rv = rv.with(
tick_factors: security.Value.regional_ticks().low_tick.to_api_tick_factors());
tick_factors: security.Value.tick_factors().to_api_tick_factors());
}
return rv;
}
@@ -681,7 +681,6 @@ namespace mbts.spark {
void _on_property_added<T>(string prop_name, int target_field_number, OneofDescriptor oneof_descriptor, IProperty<T> prop, Action<T> assign_to_prop, T non_uniform_value, bool validate_on_changed, AlgoParamPermissions permissions) where T : struct {
var target_field_desc = ProtoHelper.Descriptor<TMutable>().FindFieldByNumber(target_field_number);
var param = new AlgoParamVM<T>(prop_name, DisplayNameHelper.snake_to_title_case(prop_name), prop.Value) { permissions = permissions };
var oneof_index = ProtoHelper.get_oneof_descriptor_index<T>(oneof_descriptor);
_algo_params.Add(param);
_auto_props.Add(new AutoProp(prop_name, mval => {
if (mval == null || !param.has_value)
+1 -1
View File
@@ -27,7 +27,7 @@ namespace bts.utils {
}
}
public static TResult[] safe_convert<T, TResult>(T[] array, Func<T, TResult> convert) =>
public static TResult[] safe_convert<T, TResult>(T[]? array, Func<T, TResult> convert) =>
array == null ? Array.Empty<TResult>() : Array.ConvertAll(array, new Converter<T, TResult>(convert));
public static TResult[] convert<T, TResult>(ICollection<T> source, Func<T, TResult> convert) {
@@ -9,7 +9,7 @@ namespace Spark.Core.Diagnostics {
public static ArgumentException unexpected_case<T>(T value, string name) =>
new ArgumentException($"Unexpected {typeof(T)} '{value}.'", name);
public static ArgumentException not_of_type<T>(string name, Type actual = null) =>
public static ArgumentException not_of_type<T>(string name, Type? actual = null) =>
actual is null ?
not_of_type(name, typeof(T)) :
not_of_type(name, typeof(T), actual);
@@ -45,7 +45,7 @@ namespace mbts.analytics {
theta.Equals(other.theta) &&
rho.Equals(other.rho);
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
obj is GreeksTuple gt && Equals(gt);
public override int GetHashCode() =>
@@ -2,6 +2,7 @@
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Nullable>enable</Nullable>
<Platforms>x64</Platforms>
<PlatformTarget>x64</PlatformTarget>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
+1 -5
View File
@@ -2,10 +2,6 @@ namespace bts.md {
using bts.api;
using bts.api.core;
using mbts;
using mbts.co2;
using mbts.spark;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -40,7 +36,7 @@ namespace bts.md {
bids.SequenceEqual(other.bids) &&
asks.SequenceEqual(other.asks);
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
obj is Book other && Equals(other);
public override int GetHashCode() =>
security_id.GetHashCode();
@@ -19,7 +19,7 @@ namespace mbts.co2 {
[DllImport("libspark")]
internal static extern IntPtr create_md_consumer(
[MarshalAs(UnmanagedType.LPArray)] UserSymbol[] symbols, uint count, bool shared);
[MarshalAs(UnmanagedType.LPArray)] UserSymbol[]? symbols, uint count, bool shared);
[DllImport("libspark")]
internal static extern void destroy_md_consumer(IntPtr consumer);
+2 -2
View File
@@ -26,8 +26,8 @@ namespace mbts.co2 {
public bool Equals(IntPrice other) =>
_exponent == other._exponent && _mantissa == other._mantissa;
public override bool Equals(object obj) =>
base.Equals(obj);
public override bool Equals(object? obj) =>
obj is IntPrice other && Equals(other);
public override int GetHashCode() =>
_mantissa.GetHashCode();
@@ -43,6 +43,10 @@ namespace mbts.co2 {
public IntPtr native_pointer() => _consumer;
[MemberNotNull(nameof(on_security))]
public IObservable<List<SecurityAndHandle>> RequireSecurities() =>
on_security ?? throw new InvalidOperationException("Securities not initialized");
public MDConsumerHandle? try_get_handle(security_key key) =>
Co2NativeMethods.md_consumer_get_handle(_consumer, key, out var raw) ?
new MDConsumerHandle(_consumer, null, raw) : null;
@@ -18,7 +18,7 @@
internal MDConsumerHandle(
IntPtr consumer,
Security security,
Security? security,
Co2NativeMethods.BlitPointerTuple tuple) {
_header = (ColdHeader*)tuple.cold_header.ToPointer();
_cold = (ColdEntry*)tuple.cold_data.ToPointer();
+1 -1
View File
@@ -39,7 +39,7 @@ namespace bts.md {
_relay = new Co2RelayControl(consumer, relay_throttle);
_relay.preload_securities((co2.MDRequest.Types.Flags)0xff).ignore();
_securities_src = consumer.on_security
_securities_src = consumer.RequireSecurities()
.Buffer(output_throttle)
.Select(buffer => buffer.SelectMany(_ => _).Where(sec_filter))
.Where(buffer => buffer.Any())
@@ -49,7 +49,7 @@ namespace mbts.co2 {
public override string ToString() =>
$"{price} {size} ({implied_size})";
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
obj is NativePriceSize p ? Equals(p) : base.Equals(obj);
public override int GetHashCode() =>
+2 -2
View File
@@ -28,14 +28,14 @@ namespace bts.md {
implied_size = this.implied_size
};
public bool Equals(PriceSize other) =>
public bool Equals(PriceSize? other) =>
other is not null &&
size == other.size &&
direct_size == other.direct_size &&
implied_size == other.implied_size &&
price == other.price;
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
Equals(obj as PriceSize);
public override int GetHashCode() =>
@@ -91,9 +91,6 @@
readonly Dictionary<uint, SecurityMD> _security_mds;
long _cursor = 0;
public ChannelConsumer(MDConsumerChannel channel) =>
_channel = channel;
public ChannelConsumer(MDConsumerChannel channel, IEnumerable<SecurityMD> security_mds) {
_channel = channel;
_security_mds = security_mds.ToDictionary(s => s.id, DuplicateKeyPolicy.Overwrite);
+4 -15
View File
@@ -1,32 +1,21 @@
using System;
namespace bts {
public readonly struct AccountTuple : IEquatable<AccountTuple>, IComparable<AccountTuple>, IComparable {
public readonly record struct AccountTuple(uint id, string name = "") : IComparable<AccountTuple>, IComparable {
public static readonly Func<AccountTuple, uint> key_fn = a => a.id;
public static readonly Func<AccountTuple?, uint> nullable_key_fn = a => a.HasValue ? a.Value.id : 0u;
public readonly uint id;
public readonly string name;
public AccountTuple(uint id, string name) {
this.id = id;
this.name = name;
}
public int CompareTo(AccountTuple other) {
int comp = string.Compare(name, other.name);
return comp == 0 ? id.CompareTo(other.id) : comp;
}
int IComparable.CompareTo(object obj) =>
int IComparable.CompareTo(object? obj) =>
obj is AccountTuple other ? CompareTo(other) : 1;
public bool Equals(AccountTuple other) => other.id == id && other.name == name;
public override bool Equals(object obj) => obj is AccountTuple other && Equals(other);
public override int GetHashCode() => id.GetHashCode();
public override string ToString() => name;
public static bool operator ==(AccountTuple a, AccountTuple b) => a.Equals(b);
public static bool operator !=(AccountTuple a, AccountTuple b) => !a.Equals(b);
public override string ToString() =>
name ?? string.Empty;
}
}
+1 -1
View File
@@ -58,7 +58,7 @@ namespace mbts.spark {
name == other.name &&
OrderEqualityComparer.custom_order_defi_comparer.Equals(value, other.value);
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
EqualityComparer.equals_obj(in this, obj);
public override int GetHashCode() =>
@@ -15,9 +15,9 @@ namespace mbts.spark {
public static readonly Func<AlgoDefinitionMetadata, AlgoKey> key_fn = m => m.id;
public readonly AlgoKey id, default_template;
readonly AlgoKey[] _favorite_templates;
readonly AlgoKey[]? _favorite_templates;
public readonly bool is_favorite, is_hidden;
public readonly string abbreviation;
public readonly string? abbreviation;
public readonly uint? badge_color;
public AlgoDefinitionMetadata(AlgoKey id)
@@ -26,10 +26,10 @@ namespace mbts.spark {
public AlgoDefinitionMetadata(
AlgoKey id,
AlgoKey default_template,
AlgoKey[] favorite_templates,
AlgoKey[]? favorite_templates,
bool is_favorite,
bool is_hidden,
string abbreviation,
string? abbreviation,
uint? badge_color
) {
this.id = id;
@@ -51,7 +51,15 @@ namespace mbts.spark {
favorite_templates.Where(t => t.mode == AlgoKey.Mode.Persisted).Select(t => new AlgoPersistedKey(t.persisted)).ToArray(),
is_favorite, is_hidden, abbreviation, new NullableColorProto(badge_color));
public AlgoDefinitionMetadata with(AlgoKey? id = null, AlgoKey? default_template = null, IEnumerable<AlgoKey> favorite_templates = null, bool? is_favorite = null, bool? is_hidden = null, string abbreviation = null, NullableColorProto? badge_color = null) =>
public AlgoDefinitionMetadata with(
AlgoKey? id = null,
AlgoKey? default_template = null,
IEnumerable<AlgoKey>? favorite_templates = null,
bool? is_favorite = null,
bool? is_hidden = null,
string? abbreviation = null,
NullableColorProto? badge_color = null
) =>
new AlgoDefinitionMetadata(
id ?? this.id,
default_template ?? this.default_template,
@@ -70,7 +78,7 @@ namespace mbts.spark {
badge_color == other.badge_color &&
favorite_templates.SequenceEqual(other.favorite_templates);
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
EqualityComparer.equals_obj(in this, obj);
public override int GetHashCode() =>
@@ -21,20 +21,20 @@ namespace bts.persist.algo {
[ProtoMember(2)]
public readonly AlgoPersistedKey default_template;
[ProtoMember(3)]
readonly AlgoPersistedKey[] _favorite_templates;
readonly AlgoPersistedKey[]? _favorite_templates;
[ProtoMember(4)]
public readonly bool is_favorite;
[ProtoMember(5)]
public readonly bool is_hidden;
[ProtoMember(6)]
public readonly string abbreviation;
public readonly string? abbreviation;
[ProtoMember(7)]
public readonly NullableColorProto badge_color;
public AlgoDefinitionPersistedMetadata(AlgoPersistedKey id)
: this(id, default, default, default, default, default, default) { }
public AlgoDefinitionPersistedMetadata(AlgoPersistedKey id, AlgoPersistedKey default_template, AlgoPersistedKey[] favorite_templates, bool is_favorite, bool is_hidden, string abbreviation, NullableColorProto badge_color) {
public AlgoDefinitionPersistedMetadata(AlgoPersistedKey id, AlgoPersistedKey default_template, AlgoPersistedKey[]? favorite_templates, bool is_favorite, bool is_hidden, string? abbreviation, NullableColorProto badge_color) {
this.id = id;
this.default_template = default_template;
_favorite_templates = favorite_templates;
@@ -49,7 +49,14 @@ namespace bts.persist.algo {
public AlgoDefinitionMetadata to_definition_data() =>
new AlgoDefinitionMetadata(id.to_algo_key(), default_template.to_algo_key(), ArrayHelper.safe_convert(_favorite_templates, k => k.to_algo_key()), is_favorite, is_hidden, abbreviation, badge_color.value);
public AlgoDefinitionPersistedMetadata with(AlgoPersistedKey? default_template = null, IEnumerable<AlgoPersistedKey> favorite_templates = null, bool? is_favorite = null, bool? is_hidden = null, string abbreviation = null, NullableColorProto? badge_color = null) =>
public AlgoDefinitionPersistedMetadata with(
AlgoPersistedKey? default_template = null,
IEnumerable<AlgoPersistedKey>? favorite_templates = null,
bool? is_favorite = null,
bool? is_hidden = null,
string? abbreviation = null,
NullableColorProto? badge_color = null
) =>
new AlgoDefinitionPersistedMetadata(id,
default_template ?? this.default_template,
favorite_templates == null ? _favorite_templates : favorite_templates.ToArray(),
@@ -67,7 +74,7 @@ namespace bts.persist.algo {
badge_color == other.badge_color &&
favorite_templates.SequenceEqual(other.favorite_templates);
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
EqualityComparer.equals_obj(in this, obj);
public override int GetHashCode() =>
@@ -77,7 +84,7 @@ namespace bts.persist.algo {
is_favorite.GetHashCode(),
is_hidden.GetHashCode(),
abbreviation == null ? 0 : abbreviation.GetHashCode(),
EqualityComparer.aggregate_hash_limited(_favorite_templates));
EqualityComparer.aggregate_hash_limited(_favorite_templates ?? []));
public static bool operator ==(AlgoDefinitionPersistedMetadata a, AlgoDefinitionPersistedMetadata b) => a.Equals(b);
public static bool operator !=(AlgoDefinitionPersistedMetadata a, AlgoDefinitionPersistedMetadata b) => !a.Equals(b);
+12 -8
View File
@@ -6,6 +6,8 @@ using mbts.utils;
using ProtoBuf;
using Spark.Api.Orders;
using Spark.Core;
using Spark.Core.Diagnostics;
using System;
using System.Linq;
@@ -18,7 +20,7 @@ namespace mbts.spark {
[ProtoMember(1)]
readonly CustomOrderDefinition.CustomOneofCase? _factory_key;
[ProtoMember(2)]
readonly string _dynamic_key;
readonly string? _dynamic_key;
[ProtoMember(3)]
readonly uint? _persisted_key;
@@ -77,7 +79,7 @@ namespace mbts.spark {
_dynamic_key == other._dynamic_key &&
_persisted_key == other._persisted_key;
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
obj is AlgoID other && Equals(other);
public override int GetHashCode() =>
@@ -93,7 +95,7 @@ namespace mbts.spark {
public readonly struct AlgoKey : IEquatable<AlgoKey> {
readonly uint? _composite_key;
readonly Guid? _unpersisted;
readonly string _dynamic_type;
readonly string? _dynamic_type;
readonly CustomOrderDefinition.CustomOneofCase? _factory_type;
AlgoKey(Guid id_guid) {
@@ -135,10 +137,10 @@ namespace mbts.spark {
public bool is_persisted => mode == Mode.Persisted;
public bool is_composite => _composite_key.HasValue || _unpersisted.HasValue;
public uint persisted => _composite_key.Value;
public Guid unpersisted => _unpersisted.Value;
public CustomOrderDefinition.CustomOneofCase factory => _factory_type.Value;
public string dynamic_type => _dynamic_type;
public uint persisted => _composite_key.RequireValue();
public Guid unpersisted => _unpersisted.RequireValue();
public CustomOrderDefinition.CustomOneofCase factory => _factory_type.RequireValue();
public string dynamic_type => ExceptionAssert.NotNull(_dynamic_type);
public Mode mode {
get {
@@ -192,7 +194,9 @@ namespace mbts.spark {
return false;
}
public override bool Equals(object obj) => EqualityComparer.equals_obj(this, obj);
public override bool Equals(object? obj) =>
EqualityComparer.equals_obj(this, obj);
public override int GetHashCode() {
int hash, phase_mult;
switch (mode) {
@@ -8,7 +8,7 @@ namespace bts.persist.algo {
[ProtoContract]
public readonly struct AlgoPersistedKey : IEquatable<AlgoPersistedKey> {
[ProtoMember(1)]
readonly string _id_string;
readonly string? _id_string;
[ProtoMember(2)]
readonly uint? _id_uint;
@@ -56,7 +56,7 @@ namespace bts.persist.algo {
return false;
}
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
EqualityComparer.equals_obj(in this, obj);
public override int GetHashCode() {
@@ -1,4 +1,5 @@
namespace Spark.Api.Orders {
using bts;
using bts.api.orderman;
using Google.Protobuf;
@@ -15,7 +16,7 @@ namespace Spark.Api.Orders {
static readonly IReadOnlyDictionary<Type, OrderType> _algo_type_case_index;
static readonly IReadOnlyDictionary<OrderType, AlgoTypeCaseDescriptorData> _algo_type_case_descriptor_data;
static readonly OneofDescriptor _oneof_desc =
CustomOrderDefinition.Descriptor.Oneofs.FirstOrDefault(fd => fd.Name == "custom");
Log.notnull(CustomOrderDefinition.Descriptor.Oneofs.FirstOrDefault(fd => fd.Name == "custom"));
static AlgoTreeEnumerator() {
var algo_type_case_index = new Dictionary<Type, OrderType>();
@@ -82,9 +83,9 @@ namespace Spark.Api.Orders {
}
}
public static IEnumerable<(OrderType type, string dyn, uint studio, uint spreader_sec)> enumerate_algo_structure(
public static IEnumerable<(OrderType type, string? dyn, uint studio, uint spreader_sec)> enumerate_algo_structure(
CustomOrderDefinitionImmutable custom_defi) {
string dyn = null;
string? dyn = null;
uint studio = 0, spreader_sec = 0;
foreach (var cd in get_hierarchy(custom_defi.CloneToMutable())) {
switch (cd.CustomCase) {
@@ -146,7 +147,7 @@ namespace Spark.Api.Orders {
dyn.OrderParams.GetOrAdd(kv.Key, k => new DynamicOrderParam()).AsOrderDef = child;
}
},
def => def.Dynamic.OrderParams.TryGetValue(kv.Key, out DynamicOrderParam param) &&
def => def.Dynamic.OrderParams.TryGetValue(kv.Key, out var param) &&
param.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef ?
param.AsOrderDef : null,
(def, child) => def.Dynamic.OrderParams.GetOrAdd(
@@ -164,7 +165,7 @@ namespace Spark.Api.Orders {
}
public static IReadOnlyList<ChildAlgoNode> get_child(OrderType algo_type) =>
_algo_type_case_descriptor_data.TryGetValue(algo_type, out AlgoTypeCaseDescriptorData d) ?
_algo_type_case_descriptor_data.TryGetValue(algo_type, out var d) ?
d.child_algo_data : Array.Empty<ChildAlgoNode>();
}
}
+4 -5
View File
@@ -1,4 +1,3 @@
#nullable enable
namespace Spark.Api.Orders {
using bts.api.orderman;
@@ -8,16 +7,16 @@ namespace Spark.Api.Orders {
public readonly struct ChildAlgoNode {
public readonly string name;
public readonly Func<IMessage, CustomOrderDefinition> get_child_from_impl;
public readonly Func<IMessage, CustomOrderDefinition?> get_child_from_impl;
public readonly Action<IMessage, CustomOrderDefinition> assign_child_to_impl;
public readonly Func<CustomOrderDefinition, CustomOrderDefinition> get_child;
public readonly Func<CustomOrderDefinition, CustomOrderDefinition?> get_child;
public readonly Action<CustomOrderDefinition, CustomOrderDefinition> assign_child;
public ChildAlgoNode(
string name,
Func<IMessage, CustomOrderDefinition> get_child_from_impl,
Func<IMessage, CustomOrderDefinition?> get_child_from_impl,
Action<IMessage, CustomOrderDefinition> assign_child_to_impl,
Func<CustomOrderDefinition, CustomOrderDefinition> get_child,
Func<CustomOrderDefinition, CustomOrderDefinition?> get_child,
Action<CustomOrderDefinition, CustomOrderDefinition> assign_child
) {
this.name = name;
+2 -2
View File
@@ -68,13 +68,13 @@ namespace mbts.spark {
public bool is_aggressor =>
fill.FillAggressorFlag == FillAggressorFlag.Aggressor;
public bool Equals(FillTuple other) =>
public bool Equals(FillTuple? other) =>
other != null &&
_order_tuple.Equals(other._order_tuple) &&
security.HasValue == other.security.HasValue &&
fill.Equals(other.fill);
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
Equals(obj as FillTuple);
public override int GetHashCode() =>
@@ -29,7 +29,7 @@ namespace bts {
EqualityComparer.nullable_equals(account, other.account) &&
EqualityComparer.nullable_equals(user, other.user);
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
obj is ManualFillTuple other && Equals(other);
public override int GetHashCode() =>
@@ -10,7 +10,7 @@ namespace Spark.Api.Orders {
double best_price,
double best_price_volume,
double total_volume,
Func<double, string> fmt_qty = null) =>
Func<double, string>? fmt_qty = null) =>
order_collection_summary(
best_price,
best_price_volume,
@@ -23,7 +23,7 @@ namespace Spark.Api.Orders {
double best_price_volume,
double total_volume,
ContractSpecificationImmutable spec,
Func<double, string> fmt_qty = null) {
Func<double, string>? fmt_qty = null) {
if (total_volume == 0)
return string.Empty;
fmt_qty ??= v => v.ToString();
+11 -12
View File
@@ -24,16 +24,16 @@ using OrderState = bts.api.orderman.OrderState;
namespace mbts.spark.utilities {
public readonly struct ChildAlgoData {
public readonly string name;
public readonly Func<IMessage, CustomOrderDefinition> get_child_from_impl;
public readonly Func<IMessage?, CustomOrderDefinition?> get_child_from_impl;
public readonly Action<IMessage, CustomOrderDefinition> assign_child_to_impl;
public readonly Func<CustomOrderDefinition, CustomOrderDefinition> get_child;
public readonly Func<CustomOrderDefinition, CustomOrderDefinition?> get_child;
public readonly Action<CustomOrderDefinition, CustomOrderDefinition> assign_child;
public ChildAlgoData(
string name,
Func<IMessage, CustomOrderDefinition> get_child_from_impl,
Func<IMessage?, CustomOrderDefinition?> get_child_from_impl,
Action<IMessage, CustomOrderDefinition> assign_child_to_impl,
Func<CustomOrderDefinition, CustomOrderDefinition> get_child,
Func<CustomOrderDefinition, CustomOrderDefinition?> get_child,
Action<CustomOrderDefinition, CustomOrderDefinition> assign_child) {
//
this.name = name;
@@ -64,7 +64,7 @@ namespace mbts.spark.utilities {
const string _primary_child_field = "child";
// algo-type-case maps
// Note: obv this will break if we change the name of the 'CustomOneofCase' field
static readonly OneofDescriptor _oneof_desc = CustomOrderDefinition.Descriptor.Oneofs.FirstOrDefault(fd => fd.Name == "custom");
static readonly OneofDescriptor _oneof_desc = CustomOrderDefinition.Descriptor.Oneofs.First(fd => fd.Name == "custom");
static readonly IReadOnlyDictionary<System.Type, CustomOrderDefinition.CustomOneofCase> _algo_type_case_index;
static readonly IReadOnlyDictionary<CustomOrderDefinition.CustomOneofCase, AlgoTypeCaseDescriptorData> _algo_type_case_descriptor_data;
@@ -110,8 +110,8 @@ namespace mbts.spark.utilities {
throw new ArgumentException(
$"Failed to find descriptor data for algo type '{algo_type}'", nameof(algo_type));
public static IEnumerable<(CustomOrderDefinition.CustomOneofCase type, string dyn, uint studio, uint spreader_sec)> enumerate_algo_structure(CustomOrderDefinitionImmutable custom_defi) {
string dyn = null;
public static IEnumerable<(CustomOrderDefinition.CustomOneofCase type, string? dyn, uint studio, uint spreader_sec)> enumerate_algo_structure(CustomOrderDefinitionImmutable custom_defi) {
string? dyn = null;
uint studio = 0, spreader_sec = 0;
foreach (var cd in enumerate_algo_hierarchy(custom_defi.CloneToMutable())) {
switch (cd.CustomCase) {
@@ -206,7 +206,7 @@ namespace mbts.spark.utilities {
}
public static IReadOnlyList<ChildAlgoData> get_child_algo_data(CustomOrderDefinition.CustomOneofCase algo_type) =>
_algo_type_case_descriptor_data.TryGetValue(algo_type, out AlgoTypeCaseDescriptorData d) ? d.child_algo_data : Array.Empty<ChildAlgoData>();
_algo_type_case_descriptor_data.GetValueOrDefault(algo_type)?.child_algo_data ?? Array.Empty<ChildAlgoData>();
#endregion
public static string abbreviate_algo_type(CustomOrderDefinition.CustomOneofCase algo_type) {
@@ -289,10 +289,10 @@ namespace mbts.spark.utilities {
};
public static readonly CustomOrderDefinition.CustomOneofCase[] all_order_types = exchange_order_types.Union(spreader_order_types).ToArray();
public static void copy_values(CustomOrderDefinitionImmutable source, ref CustomOrderDefinition target) =>
public static void copy_values(CustomOrderDefinitionImmutable source, ref CustomOrderDefinition? target) =>
copy_values(source.CloneToMutable(), ref target);
public static void copy_values(CustomOrderDefinition source, ref CustomOrderDefinition target) {
public static void copy_values(CustomOrderDefinition? source, ref CustomOrderDefinition? target) {
if (source == null || target == null || source.CustomCase != target.CustomCase)
return;
var desc_data = _algo_type_case_descriptor_data[source.CustomCase];
@@ -314,8 +314,7 @@ namespace mbts.spark.utilities {
public static void setup_generic_custom_order(
CustomOrderDefinition custom, CustomOrderDefinition.CustomOneofCase type) {
var prop = typeof(CustomOrderDefinition).GetProperty(type.ToString(),
BindingFlags.Instance | BindingFlags.Public);
var prop = ExceptionAssert.NotNull(typeof(CustomOrderDefinition).GetProperty(type.ToString(), BindingFlags.Instance | BindingFlags.Public));
var rt = prop.PropertyType;
var rtt = Activator.CreateInstance(rt);
@@ -1,4 +1,3 @@
#nullable enable
namespace Spark.Api.Orders {
using bts;
@@ -226,7 +226,7 @@ namespace Spark.Api.Orders {
public static string display_name(
this OrderRecordImmutable order, AlgoData? algo, SecurityImmutable? security = null) {
if (order.order_type() == CustomOrderDefinition.CustomOneofCase.Spreader && security.HasValue)
return security.Value.ToString();
return security.Value.ToString() ?? string.Empty;
if (algo.HasValue) {
return algo.Value.name;
} else if (order.HasDef && order.Def.HasCustomDef) {
@@ -321,7 +321,7 @@ namespace Spark.Api.Orders {
return sb.ToString();
}
public static string update_description(
public static string? update_description(
OrderRecordImmutable order,
double? new_price = null,
double? new_quantity = null,
@@ -442,7 +442,8 @@ namespace Spark.Api.Orders {
void impl(StringBuilder sb, CustomOrderDefinition mdef) {
sb.Append(abbreviate(mdef.CustomCase));
foreach (var cad in AlgoTreeEnumerator.get_child(def.CloneToMutable())) {
var child = cad.get_child(mdef);
var child = cad.get_child(mdef)
?? throw new Exception($"Failed to get algo child '{mdef.CustomCase}.{cad.name}'");
sb.Append(".[");
impl(sb, child);
sb.Append("]");
@@ -455,7 +456,7 @@ namespace Spark.Api.Orders {
.ToDictionary(kv => Enum.Parse<CustomOrderDefinition.CustomOneofCase>(kv.Key), kv => kv.Value);
public static string abbreviate(this CustomOrderDefinition.CustomOneofCase type) =>
_abbreviated_exchange_types.TryGetValue(type, out string result) ? result : type.ToString();
_abbreviated_exchange_types.TryGetValue(type, out var result) ? result : type.ToString();
public static string abbreviate_algo_type(this CustomOrderDefinition.CustomOneofCase algo_type) {
switch (algo_type) {
@@ -1,4 +1,3 @@
#nullable enable
namespace Spark.Trading {
using bts;
using bts.api.core;
@@ -28,7 +27,7 @@ namespace Spark.Trading {
ISecurityResolver sec_resolver) =>
// join pnl data w/ security and user
pnl_data_source
.Select(d => d.day_trades
.Select(d => (d.day_trades ?? [])
.Select(DayFillsRowData.from_trade)
.ToDictionary(DayFillsRowData.key_fn))
.Table(DayFillsRowData.key_fn)
@@ -37,8 +36,8 @@ namespace Spark.Trading {
.LeftJoin(
inverse_users,
DayFillsRowData.key_fn,
user => user.name,
row_data => row_data.user_name,
user => user.name ?? string.Empty,
row_data => row_data.user_name ?? string.Empty,
(row_data, row_key, user, user_name) => new DayFillsRowData(
row_data.trade, row_data.security, user.id),
(row_data, row_key, user_name) => row_data,
+2 -3
View File
@@ -1,11 +1,10 @@
using System.Collections.Generic;
namespace mbts.analytics {
public class PNLData {
// keyed on account, sec
internal IEnumerable<IPNLUnit> position_data { get; init; }
internal IEnumerable<IPNLUnit>? position_data { get; init; }
// List of day trades
internal IEnumerable<IPNLTradeRow> day_trades { get; init; }
internal IEnumerable<IPNLTradeRow>? day_trades { get; init; }
}
}
+5 -5
View File
@@ -38,7 +38,7 @@ namespace bts.shell.pnl {
public readonly SecurityImmutable? security;
public readonly QuantityConversionData<double> qty_conversion;
public readonly uint account_id;
public readonly string account_name;
public readonly string? account_name;
public readonly PNLCalculationType calc_type;
public readonly PositionPriceSizeWithGreeks sod;
public readonly PositionPriceSizeWithGreeks day;
@@ -67,7 +67,7 @@ namespace bts.shell.pnl {
WorkingOrderData? working = null,
SecurityImmutable? security = null,
uint account_id = 0,
string account_name = null,
string? account_name = null,
PNLCalculationType calc_type = PNLCalculationType.Mid,
QuantityConversionData<double>? qty_conversion = null) {
//
@@ -89,7 +89,7 @@ namespace bts.shell.pnl {
this.qty_conversion = qty_conversion ?? new();
}
public AccountTuple account => new(account_id, account_name);
public AccountTuple account => new(account_id, account_name ?? string.Empty);
public string symbol => security?.pnl_symbol() ?? string.Empty;
public ExpirationDate expiration =>
security?.normal_expirations()?.MinOrDefault(ExpirationDate.None) ?? ExpirationDate.None;
@@ -237,7 +237,7 @@ namespace bts.shell.pnl {
public PNLRowData with(
SecurityImmutable? security = null,
uint? account_id = null,
string account_name = null,
string? account_name = null,
WorkingOrderData? working = null,
PNLCalculationType? calc_type = null,
double? bid_price = null,
@@ -285,7 +285,7 @@ namespace bts.shell.pnl {
working.summary == other.working.summary &&
qty_conversion == other.qty_conversion;
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
obj is PNLRowData other && Equals(other);
// assuming callers will not combine different values with the same key,
@@ -75,7 +75,7 @@ namespace Spark.Trading {
DayFillsDataSource.create(users, pnlDataSource, sec_resolver).Cache().ToObservable());
pnl = pnlDataSource
.Select(d => d.position_data.ToDictionary(u => u.id(), PNLRowData.from_pnl_unit))
.Select(d => d.position_data?.ToDictionary(u => u.id(), PNLRowData.from_pnl_unit) ?? [])
.Table(PNLRowData.key_fn)
.LeftJoin(
mdClient.Books(),
@@ -6,6 +6,7 @@ using bts.collections;
using bts.md;
using Spark.Api.MarketData;
using Spark.Core.Diagnostics;
using Spark.Core.Disposables;
using System;
@@ -22,8 +23,8 @@ using security_key = System.UInt32;
namespace Spark.Api.Reactive {
public class SecurityResolver : ISecurityResolver, IDisposable {
readonly MarketDataRelay _md;
IDisposable _dispose;
IReadOnlyDictionary<security_key, SecurityImmutable> _live_securities;
IDisposable? _dispose;
IReadOnlyDictionary<security_key, SecurityImmutable>? _live_securities;
readonly ConcurrentDictionary<security_key, SecurityImmutable> _cache = new ConcurrentDictionary<security_key, SecurityImmutable>();
readonly Subject<IReadOnlyDictionary<security_key, SecurityImmutable>> _cache_subject = new Subject<IReadOnlyDictionary<security_key, SecurityImmutable>>();
@@ -40,7 +41,7 @@ namespace Spark.Api.Reactive {
IObservable<IReadOnlyDictionary<security_key, SecurityImmutable>> on_securities;
SecurityImmutable? try_get_local(security_key key, IReadOnlyDictionary<security_key, SecurityImmutable> live = null) {
SecurityImmutable? try_get_local(security_key key, IReadOnlyDictionary<security_key, SecurityImmutable>? live = null) {
// Try live securities first
live = live ?? _live_securities;
if (live != null) {
@@ -57,7 +58,7 @@ namespace Spark.Api.Reactive {
return null;
}
async Task<SecurityImmutable?> get_security(security_key key, IReadOnlyDictionary<security_key, SecurityImmutable> live) {
async Task<SecurityImmutable?> get_security(security_key key, IReadOnlyDictionary<security_key, SecurityImmutable>? live) {
var local_sec = try_get_local(key, live);
if (local_sec.HasValue) {
return local_sec;
@@ -80,7 +81,7 @@ namespace Spark.Api.Reactive {
return null;
}
async Task<IReadOnlyDictionary<security_key, SecurityImmutable>> get_securities(IEnumerable<security_key> keys, IReadOnlyDictionary<security_key, SecurityImmutable> live) {
async Task<IReadOnlyDictionary<security_key, SecurityImmutable>> get_securities(IEnumerable<security_key> keys, IReadOnlyDictionary<security_key, SecurityImmutable>? live) {
var result = new Dictionary<security_key, SecurityImmutable>();
var missing = new SecurityKeyList();
foreach (var key in keys) {
@@ -190,7 +191,7 @@ namespace Spark.Api.Reactive {
var state = ImmutableDictionary<TKey, (SecurityImmutable? s, T t)>.Empty;
var gate = new object();
// We get thie function from the first source update
Func<(SecurityImmutable?, T t), TKey> rowkeyfn = null;
Func<(SecurityImmutable?, T t), TKey>? rowkeyfn = null;
void on_securities_updated(object ambiguous) {
if (rowkeyfn == null) return;
@@ -283,7 +284,7 @@ namespace Spark.Api.Reactive {
join(
source,
get_sec_key,
t => (t.Index.Values, t.AddedItems, t.Changes, t.RemovedItems, t.KeySelector),
t => (t.Index.Values, t.AddedItems, t.Changes, t.RemovedItems, ExceptionAssert.NotNull(t.KeySelector)),
(state, added, changes, removed, key) => new TableUpdate<(SecurityImmutable?, T), TKey>(
state, added, changes, removed, key));
@@ -1,4 +1,3 @@
#nullable enable
namespace Spark.Api.Services;
using bts.api.core;
@@ -1,4 +1,3 @@
#nullable enable
namespace Spark.Api.Services;
using bts;
@@ -1,4 +1,3 @@
#nullable enable
namespace Spark.Api.Services;
public class SparkCredentials {
@@ -1,4 +1,3 @@
#nullable enable
namespace Spark.Api.Services;
using bts;
@@ -1,4 +1,3 @@
#nullable enable
namespace Spark.Api.Services;
using bts;
+2 -2
View File
@@ -11,7 +11,7 @@ namespace bts.api.core {
static class ApiNativeMethods {
[DllImport("libspark")]
internal static extern IntPtr api_create_quickbus(byte[] qbconfig, long length);
internal static extern IntPtr api_create_quickbus(byte[]? qbconfig, long length);
[DllImport("libspark")]
internal static extern void api_destroy_quickbus(IntPtr qbus);
@@ -64,7 +64,7 @@ namespace bts.api.core {
internal static extern void api_client_send(IntPtr nchannel, byte[] buffer, int length, raw_pb_callback p, IntPtr extra);
[DllImport("libspark")]
internal static extern IntPtr api_client_subscribe(IntPtr client, string method, string qualifier, raw_subscription_callback cb, IntPtr extra);
internal static extern IntPtr api_client_subscribe(IntPtr client, string method, string? qualifier, raw_subscription_callback cb, IntPtr extra);
[DllImport("libspark")]
internal static extern void api_client_unsubscribe(IntPtr client, IntPtr subscription);
@@ -1,17 +1,12 @@
using Google.Protobuf.WellKnownTypes;
using Google.Protobuf;
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reactive.Linq;
using System.IO;
using System.Reactive.Disposables;
using mbts;
using System.Threading;
using System.Reactive.Linq;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
namespace bts.api.core {
@@ -69,7 +64,7 @@ namespace bts.api.core {
});
}
public override IObservable<RawUpdate<TOut>> subscribe<TParse,TOut>(int method_id, string method, string qualifier, MessageParser<TParse> parser, Func<TParse,TOut> converter) {
public override IObservable<RawUpdate<TOut>> subscribe<TParse, TOut>(int method_id, string method, string? qualifier, MessageParser<TParse> parser, Func<TParse, TOut>? converter) {
var result = Observable.Create<RawUpdate<TOut>>(async observer => {
IntPtr temp_subscription = IntPtr.Zero;
void unsubscribe_temp_sub() {
@@ -79,7 +74,7 @@ namespace bts.api.core {
// 'tcs' and 'temp_callback' are defined in the same scope as 'temp_subscription'
// (rather than in the 'while loop' scope) to prevent premature garbage collection
TaskCompletionSource<bool> tcs = null;
TaskCompletionSource<bool>? tcs = null;
ApiNativeMethods.raw_subscription_callback temp_callback =
(event_type, changes, change_count, unused) => {
tcs?.TrySetResult(true);
@@ -115,21 +110,23 @@ namespace bts.api.core {
// is disposed
GC.KeepAlive(temp_callback);
GC.KeepAlive(tcs);
return SubscribeNative(method, qualifier, parser, converter, observer);
return subscribeNative(method, qualifier, parser, converter, observer);
});
Log.QBus.diag($"Subscribing for sub: '{method}/{qualifier}'");
return result;
}
private Task<Result<StreamAccessResponse>> check_stream_access(int method_id, string qualifier) {
private Task<Result<StreamAccessResponse>> check_stream_access(int method_id, string? qualifier) {
var request = new StreamAccessRequest() { Qualifier = qualifier ?? "" };
return send<StreamAccessRequest, StreamAccessResponse>(method_id, request);
}
private unsafe IDisposable SubscribeNative<TParse, TOut>(string method, string qualifier, MessageParser<TParse> parser, Func<TParse, TOut> converter, IObserver<RawUpdate<TOut>> observer) where TParse : IMessage<TParse> {
unsafe IDisposable subscribeNative<TParse, TOut>(
string method, string? qualifier, MessageParser<TParse> parser, Func<TParse, TOut>? converter, IObserver<RawUpdate<TOut>> observer) where TParse : IMessage<TParse> {
converter ??= p => (TOut)(object)p;
bool first_update = true;
// Memory optimization. There is only one update per subscription.
RawUpdate<TOut> the_update = new RawUpdate<TOut>();
ApiNativeMethods.raw_subscription_callback cb = (event_type, changes, change_count, unused) => {
ApiNativeMethods.raw_subscription_callback? cb = (event_type, changes, change_count, unused) => {
the_update.Clear();
try {
if (event_type == ApiNativeMethods.EventType.TABLE_UPDATED) {
@@ -177,7 +174,8 @@ namespace bts.api.core {
}
private class FinalizeableAnonymousDisposable : IDisposable {
private Action<bool> _action;
Action<bool>? _action;
public FinalizeableAnonymousDisposable(Action<bool> dispose) {
_action = dispose;
}
+3 -1
View File
@@ -13,7 +13,9 @@ namespace bts.api.core {
public abstract void Dispose();
public abstract Task<Result<Response>> send<Request, Response>(int method_id, Request request)
where Request: IImmutableMessage where Response : class,IMessage,new();
public abstract IObservable<RawUpdate<TOut>> subscribe<TParse,TOut>(int method_id, string method, string qualifier, MessageParser<TParse> parser, Func<TParse,TOut> converter=null)
public abstract IObservable<RawUpdate<TOut>> subscribe<TParse, TOut>(
int method_id, string method, string? qualifier, MessageParser<TParse> parser, Func<TParse, TOut>? converter = null)
where TParse : IMessage<TParse>;
public abstract bool is_sync_call_ok();
@@ -1,4 +1,3 @@
#nullable enable
namespace Spark.Core;
using bts.api.core;
+5 -13
View File
@@ -2,7 +2,7 @@
namespace bts.api.core {
public readonly struct Result<T> {
readonly T _result;
readonly T? _result;
public Result(T v) {
_result = v;
@@ -15,17 +15,10 @@ namespace bts.api.core {
_result = default;
}
public T value {
get {
if (success) {
return _result;
}
if (typeof(T).IsValueType) {
throw new ApiException(error_message);
}
return default;
}
}
public T value =>
success
? _result ?? throw new ApiException("Response code is Success but value is null")
: throw new ApiException(error_message);
public bool success =>
code == ApiError.Success;
@@ -43,7 +36,6 @@ namespace bts.api.core {
_ => "Unknown error",
};
public override string ToString() =>
error_message.is_null_or_empty() ? code.ToString() : $"{code}: {error_message}";
}
+3 -3
View File
@@ -32,10 +32,10 @@ namespace bts.api.core {
public void dispatch(RequestHeader header, Stream request, Action<byte[]> on_response) {
on_request?.Invoke(header, request, on_response);
}
public Action<RequestHeader, Stream, Action<byte[]>> on_request;
public Action<RequestHeader, Stream, Action<byte[]>>? on_request;
public IntPtr create_table(string method, string qualifier) {
return ApiNativeMethods.api_server_create_table(_server, method, qualifier);
public IntPtr create_table(string method, string? qualifier) {
return ApiNativeMethods.api_server_create_table(_server, method, qualifier ?? string.Empty);
}
public void Dispose() {
+4 -5
View File
@@ -1,5 +1,4 @@
#nullable enable
namespace bts.api.core {
namespace bts.api.core {
using bts.api.user;
using System;
@@ -87,8 +86,8 @@ namespace bts.api.core {
var auth_service = locate<AuthService>();
var result = await auth_service.authenticate_login_async(
new AuthenticateLoginRequest() {
Login = username ?? string.Empty,
Password = password ?? string.Empty
Login = username,
Password = password,
});
if (result.success) {
if (result.value.IsValid) {
@@ -132,7 +131,7 @@ namespace bts.api.core {
}
}
internal ServerChannel publish<T>(T service, string service_type, string qualifier) where T : IApiServer {
internal ServerChannel publish<T>(T service, string service_type, string? qualifier) where T : IApiServer {
var ch = new ServerChannel(this, service_type, qualifier ?? "");
ch.on_request += service.dispatch;
return ch;
@@ -1,7 +1,5 @@
namespace Spark.Api.Data;
using mbts.ui;
using System;
using System.Collections.Generic;
using System.Numerics;
@@ -13,9 +11,9 @@ public class DisplayQuantityMultiplier<T> : IDisplayTranslator<T> where T : stru
QuantityConversionData<T> _conversion_data;
public DisplayQuantityMultiplier(
Func<QuantityConversionData<T>, T, T> to_display,
Func<QuantityConversionData<T>, T, T> from_display,
IEqualityComparer<T> comparer = null,
Func<QuantityConversionData<T>, T, T>? to_display,
Func<QuantityConversionData<T>, T, T>? from_display,
IEqualityComparer<T>? comparer = null,
T actual_value = default,
QuantityConversionData<T> conversion_data = default) {
//
@@ -26,7 +24,7 @@ public class DisplayQuantityMultiplier<T> : IDisplayTranslator<T> where T : stru
_conversion_data = conversion_data;
}
public event Action value_changed;
public event Action? value_changed;
public T actual_value {
get => _actual_value;
@@ -58,7 +56,7 @@ public class OptionalDisplayQuantityMultiplier<T> : IDisplayTranslator<T?> where
T? _actual_value;
QuantityConversionData<T> _conversion_data;
public event Action value_changed;
public event Action? value_changed;
public T? actual_value {
get => _actual_value;
+1 -1
View File
@@ -36,7 +36,7 @@ public readonly struct ExpirationDate : IEquatable<ExpirationDate>, IComparable<
public bool Equals(ExpirationDate other) =>
Value == other.Value && Type == other.Type;
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
obj is ExpirationDate other && Equals(other);
public override int GetHashCode() =>
@@ -29,7 +29,7 @@ public readonly struct QuantityConversionData<T> : IEquatable<QuantityConversion
value == other.value &&
op == other.op;
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
obj is QuantityConversionData<T> other && Equals(other);
public override int GetHashCode() =>
+8 -20
View File
@@ -1,25 +1,16 @@
using System;
namespace bts {
public readonly struct UserTuple : IEquatable<UserTuple>, IComparable<UserTuple>, IComparable {
public readonly record struct UserTuple(
uint id = 0,
string name = "",
UserTuple.Permissions permissions = UserTuple.Permissions.Regular
) : IComparable<UserTuple>, IComparable {
const string _admin_name = "bts";
public static readonly Func<UserTuple, uint> key_fn = u => u.id;
public static UserTuple admin => new UserTuple(0, _admin_name, Permissions.Admin);
public readonly uint id;
public readonly string name;
public readonly Permissions permissions;
public UserTuple(uint id, string name)
: this(id, name, name == _admin_name ? Permissions.Admin : Permissions.Regular) { }
public UserTuple(uint id, string name, Permissions permissions) {
this.id = id;
this.name = name;
this.permissions = permissions;
}
public enum Permissions {
Regular,
Admin
@@ -32,16 +23,13 @@ namespace bts {
return comp == 0 ? id.CompareTo(other.id) : comp;
}
int IComparable.CompareTo(object obj) =>
int IComparable.CompareTo(object? obj) =>
obj is UserTuple other ? CompareTo(other) : 1;
public bool Equals(UserTuple other) => other.id == id && other.name == name;
public override bool Equals(object obj) => obj is UserTuple other && Equals(other);
public override int GetHashCode() => id.GetHashCode();
public override string ToString() => name;
public static bool operator ==(UserTuple a, UserTuple b) => a.Equals(b);
public static bool operator !=(UserTuple a, UserTuple b) => !a.Equals(b);
public override string ToString() =>
name ?? string.Empty;
}
public static class UserTupleExtensions {
@@ -1,25 +1,30 @@
using bts.utils;
using ProtoBuf;
using Spark.Core.Collections;
using Spark.Core.Diagnostics;
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
namespace mbts.user.settings {
[ProtoContract]
public class RegionalTickFactors : IEquatable<RegionalTickFactors> {
[ProtoMember(1)]
readonly TickFactors _low_tick;
readonly TickFactors? _low_tick;
[ProtoMember(2)]
readonly TickFactors _high_tick;
readonly TickFactors? _high_tick;
[ProtoMember(3), DefaultValue(double.NaN)]
readonly double _low_tick_inclusive_end;
public RegionalTickFactors()
: this(new TickFactors(), new TickFactors(), double.MinValue) { }
public RegionalTickFactors(TickFactors tick)
public RegionalTickFactors(TickFactors? tick)
: this(tick, tick, double.PositiveInfinity) { }
public RegionalTickFactors(TickFactors low_tick, TickFactors high_tick, double low_tick_inclusive_end) {
public RegionalTickFactors(TickFactors? low_tick, TickFactors? high_tick, double low_tick_inclusive_end) {
_low_tick = low_tick;
_high_tick = high_tick;
_low_tick_inclusive_end = low_tick_inclusive_end;
@@ -28,17 +33,25 @@ namespace mbts.user.settings {
public static RegionalTickFactors Default =>
new(new(10000, 1), new(10000, 1), double.MaxValue);
public TickFactors low_tick => _low_tick;
public TickFactors high_tick => _high_tick;
public TickFactors? low_tick => _low_tick;
public TickFactors? high_tick => _high_tick;
public double low_tick_inclusive_end => _low_tick_inclusive_end;
public bool Equals(RegionalTickFactors other) =>
[MemberNotNull(nameof(low_tick))]
public TickFactors RequireLowTick() =>
ExceptionAssert.MemberNotNull(low_tick);
[MemberNotNull(nameof(high_tick))]
public TickFactors RequireHighTick() =>
ExceptionAssert.MemberNotNull(high_tick);
public bool Equals(RegionalTickFactors? other) =>
other != null &&
other._low_tick == _low_tick &&
other._high_tick == _high_tick &&
NullCheckEqualityComparer.Equals(other._low_tick, _low_tick) &&
NullCheckEqualityComparer.Equals(other._high_tick, _high_tick) &&
MathUtils.epsilon_equals(other._low_tick_inclusive_end, _low_tick_inclusive_end);
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
Equals(obj as RegionalTickFactors);
public override int GetHashCode() {
@@ -53,12 +66,16 @@ namespace mbts.user.settings {
x_not_null._high_tick == y_not_null._high_tick &&
x_not_null._low_tick_inclusive_end == y_not_null._low_tick_inclusive_end;
public static bool operator ==(RegionalTickFactors x, RegionalTickFactors y) {
if ((object)x == null) return (object)y == null;
if ((object)y == null) return false;
public static bool operator ==(RegionalTickFactors? x, RegionalTickFactors? y) {
if (x is null) {
return y is null;
}
if (y is null) {
return false;
}
return _equals(x, y);
}
public static bool operator !=(RegionalTickFactors x, RegionalTickFactors y) => !(x == y);
public static bool operator !=(RegionalTickFactors? x, RegionalTickFactors? y) => !(x == y);
}
}
@@ -7,6 +7,7 @@ namespace mbts {
using mbts.user.settings;
using Spark.Core;
using Spark.Core.Diagnostics;
using Spark.Core.Math;
using System;
@@ -15,7 +16,7 @@ namespace mbts {
using System.Numerics;
public static class TickExtensions {
static string _nan_text => TickDisplaySettings.Default.nan_text;
static string _nan_text => TickDisplaySettings.Default.nan_text ?? string.Empty;
public static TickFactors to_tick_factors(
this bts.api.domain.TickFactorsImmutable api_tick_factors) =>
@@ -68,7 +69,7 @@ namespace mbts {
}
public static bool is_valid(this RegionalTickFactors regional_tick) =>
regional_tick.low_tick.is_valid() && regional_tick.high_tick.is_valid();
(regional_tick.low_tick?.is_valid() ?? false) && (regional_tick.high_tick?.is_valid() ?? false);
public static bool is_integer(this TickFactors tick) {
if (tick.tick_unit == tick.tick_base) {
@@ -81,7 +82,7 @@ namespace mbts {
return false;
}
public static TickFactors tick_factors(this RegionalTickFactors regional_tick, double value) =>
public static TickFactors? tick_factors(this RegionalTickFactors regional_tick, double value) =>
value > regional_tick.low_tick_inclusive_end ?
regional_tick.high_tick : regional_tick.low_tick;
@@ -143,7 +144,7 @@ namespace mbts {
(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) =>
public static TickFactors? get_tick_for(this RegionalTickFactors rtick, double value) =>
value > rtick.low_tick_inclusive_end ? rtick.high_tick : rtick.low_tick;
public static string format_without_decimal_part(this TickFactors tick, double value) =>
@@ -162,23 +163,25 @@ namespace mbts {
public static string format<T>(this TickDisplaySettings settings, T value)
where T : IFloatingPointIeee754<T> =>
format(settings.tick_factors, value, settings);
settings.tick_factors?.format(value, settings)
?? value.ToString()
?? string.Empty;
public static string format<T>(
this bts.api.domain.TickDisplaySettingsImmutable settings, T value)
where T : IFloatingPointIeee754<T> =>
settings.to_tick_display_settings().format(value);
public static string format<T>(this TickFactors tick, T value, TickDisplaySettings settings)
public static string format<T>(this TickFactors tick, T value, TickDisplaySettings? settings)
where T : IFloatingPoint<T> {
if (settings is null) {
settings = TickDisplaySettings.Default;
}
if (T.IsNaN(value)) {
return settings.nan_text;
return settings.nan_text ?? string.Empty;
}
if (T.IsInfinity(value)) {
return value.ToString();
return value.ToString() ?? string.Empty;
}
return _format_tick(tick, value, settings);
}
@@ -192,8 +195,10 @@ namespace mbts {
bool show_decimal_part = true
) where T : IFloatingPointIeee754<T> {
var value_d = NumericCastConverter<T, double>.convert(value);
return regional_tick.tick_factors(value_d)
.format(value, display_multiplier, show_commas, nan_text, show_decimal_part);
var tick = regional_tick.tick_factors(value_d);
return tick?.format(value, display_multiplier, show_commas, nan_text, show_decimal_part)
?? value.ToString()
?? string.Empty;
}
public static string format<T>(
@@ -212,25 +217,23 @@ namespace mbts {
nan_text: nan_text,
show_decimal_part: show_decimal_part));
public static string format_without_decimal_part(this RegionalTickFactors regional_tick, double value) =>
format_without_decimal_part(
value <= regional_tick.low_tick_inclusive_end ? regional_tick.low_tick : regional_tick.high_tick,
value);
public static string format_without_decimal_part(this RegionalTickFactors regional_tick, double value) {
var tick = get_tick_for(regional_tick, value);
return tick is null
? value.ToString() ?? string.Empty
: format_without_decimal_part(tick, value);
}
public static string format(this RegionalTickFactors regional_tick, double value, TickDisplaySettings settings = null) =>
format(
value <= regional_tick.low_tick_inclusive_end ? regional_tick.low_tick : regional_tick.high_tick,
value,
settings);
public static string format(this RegionalTickFactors regional_tick, double value, TickDisplaySettings? settings = null) =>
regional_tick.tick_factors(value)?.format(value, settings)
?? value.ToString()
?? string.Empty;
public static string format(this RegionalTickFactors regional_tick, double value, double display_multiplier, bool show_commas, string nan_text) =>
format(
value <= regional_tick.low_tick_inclusive_end ? regional_tick.low_tick : regional_tick.high_tick,
value,
display_multiplier,
show_commas, nan_text);
regional_tick.tick_factors(value)?.format(value, display_multiplier, show_commas, nan_text)
?? value.ToString()
?? string.Empty;
#nullable enable
public static string format(this TickDisplaySettingsTuple tick_disp_tup, double value) {
if (tick_disp_tup.factors is null) {
throw new ArgumentException($"{nameof(tick_disp_tup.factors)} is null", nameof(tick_disp_tup));
@@ -279,12 +282,17 @@ namespace mbts {
}
public static double parse(this TickDisplaySettings display_settings, string text) =>
parse(display_settings.tick_factors, text, display_settings);
display_settings.tick_factors?.parse(text, display_settings)
?? double.Parse(text);
public static T parse<T>(this TickDisplaySettings display_settings, string text)
where T : IFloatingPointIeee754<T> =>
parse<T>(display_settings.tick_factors, text, display_settings);
#nullable disable
where T : IFloatingPointIeee754<T> {
var tick = display_settings.tick_factors;
if (tick is null) {
return T.Parse(text, null);
}
return tick.parse<T>(text, display_settings);
}
public static double parse(this TickFactors tick, string text, TickDisplaySettings display_settings) =>
parse<double>(tick, text, display_settings);
@@ -405,18 +413,18 @@ namespace mbts {
T tuf;
T ltie = regional_tick.low_tick_inclusive_end.as_type<double, T>();
if (input < ltie) {
tuf = regional_tick.low_tick.tick_unit_frac<T>();
tuf = regional_tick.RequireLowTick().tick_unit_frac<T>();
var ieeer = T.Ieee754Remainder(input, tuf);
input -= ieeer;
if (ieeer < -precision) count--;
val = input + tuf * count.as_type<ulong, T>();
if (val > ltie) {
count -= MathUtils.round_up((ltie - input) / tuf, precision).as_type<T, ulong>();
tuf = regional_tick.high_tick.tick_unit_frac<T>();
tuf = regional_tick.RequireHighTick().tick_unit_frac<T>();
val = ltie + tuf * count.as_type<ulong, T>();
}
} else {
tuf = regional_tick.high_tick.tick_unit_frac<T>();
tuf = regional_tick.RequireHighTick().tick_unit_frac<T>();
var ieeer = T.Ieee754Remainder(input, tuf);
input -= ieeer;
if (ieeer < -precision) count--;
@@ -491,7 +499,7 @@ namespace mbts {
T tuf;
T low_tick_inclusive_end = TFromDouble.convert(regional_tick.low_tick_inclusive_end);
if (input > low_tick_inclusive_end) {
tuf = regional_tick.high_tick.tick_unit_frac<T>();
tuf = regional_tick.RequireHighTick().tick_unit_frac<T>();
var ieeer = T.Ieee754Remainder(input, tuf);
input -= ieeer;
if (ieeer > precision) count--;
@@ -499,11 +507,11 @@ namespace mbts {
if (val < low_tick_inclusive_end) {
count -= TToUInt16.convert(MathUtils.round_up(
(input - low_tick_inclusive_end) / tuf, precision));
tuf = regional_tick.low_tick.tick_unit_frac<T>();
tuf = regional_tick.RequireLowTick().tick_unit_frac<T>();
val = low_tick_inclusive_end - tuf * TFromDouble.convert(count);
}
} else {
tuf = regional_tick.low_tick.tick_unit_frac<T>();
tuf = regional_tick.RequireLowTick().tick_unit_frac<T>();
var ieeer = T.Ieee754Remainder(input, tuf);
input -= ieeer;
if (ieeer > precision) count--;
@@ -37,12 +37,12 @@
public TickFactors Clone() =>
new(tick_base, tick_unit);
public bool Equals(TickFactors other) =>
public bool Equals(TickFactors? other) =>
other is not null &&
tick_base.Equals(other.tick_base) &&
tick_unit.Equals(other.tick_unit);
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
Equals(obj as TickFactors);
public override int GetHashCode() =>
@@ -55,10 +55,10 @@
object ICloneable.Clone() =>
Clone();
public static bool operator ==(TickFactors x, TickFactors y) =>
public static bool operator ==(TickFactors? x, TickFactors? y) =>
x.safe_equals(y);
public static bool operator !=(TickFactors x, TickFactors y) =>
public static bool operator !=(TickFactors? x, TickFactors? y) =>
!(x == y);
}
}
@@ -31,10 +31,10 @@ namespace bts.data.ticks {
_default_rtf;
static RegionalTickFactors _create_rtf(SecurityImmutable? security) {
var meta = SecurityMetadataStore.instance.get(security.Value);
var meta = security.HasValue ? SecurityMetadataStore.instance.get(security.Value) : null;
return meta?.PriceRules?.Any() ?? false ?
_create_rtf(meta.Value.PriceRules.ToList()) :
_create_rtf(new SpecKey(security.Value.spec_or_default()));
_create_rtf(new SpecKey(security.spec_or_default()));
}
static RegionalTickFactors _create_rtf(
@@ -93,7 +93,7 @@ namespace bts.data.ticks {
/// <param name="tick_size">The raw tick-size.</param>
/// <param name="tick_base">The raw tick-base.</param>
/// <returns>Well-defined TickFactors</returns>
static TickFactors _try_create_tf(double tick_size, double tick_base, uint display_digits_override) {
static TickFactors? _try_create_tf(double tick_size, double tick_base, uint display_digits_override) {
var tf = _try_create_tf(tick_size, tick_base);
if (tf != null && display_digits_override > 0) {
int display_digit_diff = (int)display_digits_override - tf.display_digits();
@@ -110,7 +110,7 @@ namespace bts.data.ticks {
/// <param name="tick_size">The raw tick-size.</param>
/// <param name="reduced_target_base">The smallest acceptable tick-base.</param>
/// <returns>Well-defined TickFactors</returns>
static TickFactors _try_create_tf(double tick_size, double reduced_target_base) {
static TickFactors? _try_create_tf(double tick_size, double reduced_target_base) {
if (!_check_tick_size(tick_size))
return null;
double raw_base = 1 / tick_size;
@@ -163,7 +163,7 @@ namespace bts.data.ticks {
high_tick == other.high_tick &&
price_break == other.price_break;
public override bool Equals(object obj) =>
public override bool Equals(object? obj) =>
obj is SpecKey sk && Equals(sk);
public override int GetHashCode() =>
+23 -16
View File
@@ -6,6 +6,7 @@ using bts.utils;
using mbts.user.settings;
using Spark.Core;
using Spark.Core.Diagnostics;
using Spark.Core.Math;
using System;
@@ -19,7 +20,7 @@ namespace mbts.spark {
const double _precision_const = 0.00000001;
[ThreadStatic]
static TickFactorsFactory _exchange_ticks_backing;
static TickFactorsFactory? _exchange_ticks_backing;
static TickFactorsFactory _exchange_ticks =>
_exchange_ticks_backing ?? (_exchange_ticks_backing = new TickFactorsFactory());
@@ -55,8 +56,8 @@ namespace mbts.spark {
}
public static double ticksize(this RegionalTickFactors rtick, double price) {
var low_tick = rtick.low_tick.tick_unit_frac();
var high_tick = rtick.high_tick.tick_unit_frac();
var low_tick = ExceptionAssert.NotNull(rtick.low_tick).tick_unit_frac();
var high_tick = ExceptionAssert.NotNull(rtick.high_tick).tick_unit_frac();
var price_break = rtick.low_tick_inclusive_end;
if (!low_tick.is_real_positive()) {
return high_tick;
@@ -74,10 +75,10 @@ namespace mbts.spark {
_get(spec).format_without_decimal_part(price / spec.ticksize(price)) :
_get(spec).format(price);
public static string format(this ContractSpecificationImmutable spec, double price, TickDisplaySettings settings = null) =>
public static string format(this ContractSpecificationImmutable spec, double price, TickDisplaySettings? settings = null) =>
_get(spec).format(price, settings);
public static string format(this ContractSpecificationImmutable? spec, double price, TickDisplaySettings settings = null) =>
public static string format(this ContractSpecificationImmutable? spec, double price, TickDisplaySettings? settings = null) =>
spec.spec_or_default().format(price, settings);
public static string format(this ContractSpecificationImmutable spec, double price, double display_multiplier, bool show_commas, string nan_text) =>
@@ -136,9 +137,12 @@ namespace mbts.spark {
}
public static TickFactors deduce_ticks(IEnumerable<SecurityImmutable> securities) {
var ticks = new HashSet<TickFactors>(securities.Select(_get).SelectMany(rtf => new[] { rtf.low_tick, rtf.high_tick }));
var ticks = securities.Select(_get)
.SelectMany(rtf => new[] { rtf.low_tick, rtf.high_tick })
.ExceptNull()
.ToHashSet();
switch (ticks.Count) {
case 0: return _exchange_ticks.default_rtf.low_tick;
case 0: return ExceptionAssert.NotNull(_exchange_ticks.default_rtf.low_tick);
case 1: return ticks.First();
default:
double tick_base_lcm = MathUtils.lcm(ticks.Select(t => (int)t.tick_base));
@@ -148,7 +152,7 @@ namespace mbts.spark {
}
public static TickFactors tick_factors(this SecurityImmutable sec) =>
_get(sec).low_tick;
ExceptionAssert.NotNull(_get(sec).low_tick);
public static double tickup(this ContractSpecificationImmutable spec, double value) =>
_get(spec).tickup(value);
@@ -242,9 +246,9 @@ namespace mbts.spark {
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.RequireLowTick().tick_unit_frac(),
rtick.low_tick_inclusive_end,
rtick.high_tick.tick_unit_frac(),
rtick.RequireHighTick().tick_unit_frac(),
0,
rounded_value);
return n;
@@ -259,17 +263,20 @@ namespace mbts.spark {
public static RegionalTickFactors get_regional_ticks(SecurityImmutable? security) =>
_exchange_ticks.get(security);
public static TickFactors get_tick(SecurityImmutable? security, double value) {
public static TickFactors? get_tick(SecurityImmutable? security, double value) {
var rtick = get_regional_ticks(security);
var tick = rtick.low_tick_inclusive_end > value ? rtick.high_tick : rtick.low_tick;
return tick;
}
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 RegionalTickFactors multiply_tick_size(RegionalTickFactors spec, uint factor) {
return new(Multiply(spec.low_tick), Multiply(spec.high_tick), spec.low_tick_inclusive_end);
TickFactors? Multiply(TickFactors? tick) =>
tick is null
? null
: new(tick.tick_base, tick.tick_unit * factor);
}
public static double normalize_price(RegionalTickFactors rtick, double price) {
var maybe_ticks = rtick.count_ticks(price);
@@ -94,7 +94,7 @@ static class ExchangeSpecificUtilities{
bool ice_lots = is_ice_lots(security.Value),
tas = is_tas(security.Value);
return String.Format("{0}{1}{2}{3}{4}",
security?.Symbol,
security.Value.Symbol,
ice_lots? " ICE Lots" : String.Empty,
tas ? " TAS" : String.Empty,
String.Compare(security.Value.Ice.HubAlias, _default_hub,true)==0 ? String.Empty :
@@ -119,10 +119,13 @@ static class ExchangeSpecificUtilities{
return sec.Symbol;
}
public static string format_security(SecurityImmutable? security){
if(security?.HasIce == true)
return ICE.format_security(security);
return security?.ToString();
}
public static string? format_security(SecurityImmutable? security) =>
security.HasValue
? format_security(security.Value)
: null;
public static string format_security(SecurityImmutable security) =>
security.HasIce
? ICE.format_security(security)
: security.ToString() ?? string.Empty;
}}
+3 -7
View File
@@ -1,8 +1,4 @@
using mbts.spark;
using Microsoft.VisualBasic;
using System;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -92,13 +88,13 @@ namespace bts.api {
}
partial struct SecurityImmutable : IComparable<SecurityImmutable>, IComparable, IJsonFormatter<SecurityImmutable> {
public int CompareTo(object obj) =>
public int CompareTo(object? obj) =>
obj is SecurityImmutable ? CompareTo((SecurityImmutable)obj) : -1;
public int CompareTo(SecurityImmutable other) =>
SecurityComparer.compare(this, other);
partial void ToStringOverride(ref bool didrun, ref string result) {
partial void ToStringOverride(ref bool didrun, ref string? result) {
result = SecurityFormatter.format(this);
didrun = true;
}
@@ -10,7 +10,7 @@ namespace bts.api {
public static IComparer<Security> instance { get; } = _instance;
public static IComparer<SecurityImmutable> instance_immutable { get; } = _instance;
public static int compare(Security x, Security y) {
public static int compare(Security? x, Security? y) {
if (ReferenceEquals(x, y)) {
return 0;
}
@@ -44,7 +44,7 @@ namespace bts.api {
return 0;
}
int IComparer<Security>.Compare(Security x, Security y) =>
int IComparer<Security>.Compare(Security? x, Security? y) =>
compare(x, y);
int IComparer<SecurityImmutable>.Compare(SecurityImmutable x, SecurityImmutable y) =>
@@ -8,7 +8,7 @@ namespace bts.api {
public static IEqualityComparer<Security> instance { get; } = _instance;
public static IEqualityComparer<SecurityImmutable> instance_immutable { get; } = _instance;
public static bool equals(Security x, Security y) =>
public static bool equals(Security? x, Security? y) =>
x?.Id == y?.Id;
public static bool equals(SecurityImmutable x, SecurityImmutable y) =>
@@ -20,7 +20,7 @@ namespace bts.api {
public static int get_hash_code([DisallowNull] SecurityImmutable security) =>
(int)security.Id;
bool IEqualityComparer<Security>.Equals(Security x, Security y) =>
bool IEqualityComparer<Security>.Equals(Security? x, Security? y) =>
equals(x, y);
bool IEqualityComparer<SecurityImmutable>.Equals(SecurityImmutable x, SecurityImmutable y) =>
@@ -19,16 +19,16 @@
return string.Join("", _format_legs(future_legs));
}
public static string format_future(string symbol, DateTime exp) =>
public static string format_future(string? symbol, DateTime exp) =>
format_future(symbol, (uint)exp.Year, (uint)exp.Month, (uint)exp.Day);
public static string format_future(string symbol, uint exp_year, uint exp_month, uint exp_day) =>
public static string format_future(string? symbol, uint exp_year, uint exp_month, uint exp_day) =>
$"{symbol}{format_expiration(new((int)exp_year, (int)exp_month, (int)exp_day))}";
public static string format_future(string symbol, FutureContractImmutable future) =>
public static string format_future(string? symbol, FutureContractImmutable future) =>
format_future(symbol, future.ExpirationYear, future.ExpirationMonth, future.ExpirationDay);
public static string format_future(string symbol, string exch_desc, FutureContractImmutable future) =>
public static string format_future(string? symbol, string exch_desc, FutureContractImmutable future) =>
string.IsNullOrEmpty(exch_desc) ? format_future(symbol, future) : exch_desc;
public static string format_option(string symbol, uint exp_year, uint exp_month, uint exp_day, double strike, PutOrCall call_put) {
@@ -41,7 +41,7 @@ namespace bts.threading {
}
}
event Action<T> _action;
event Action<T>? _action;
public void Invoke(T value) =>
_action?.Invoke(value);
+8 -8
View File
@@ -26,7 +26,7 @@ namespace bts.utils {
public static OneofDescriptor get_oneof_descriptor<T>(string prop_name) where T : IMessage, new() {
prop_name = prop_name.iremove_suffix(_case_suffix);
return Descriptor<T>().Oneofs.FirstOrDefault(d => d.Name.iequals(prop_name));
return Descriptor<T>().Oneofs.First(d => d.Name.iequals(prop_name));
}
public static IReadOnlyDictionary<TOneofCase, (FieldDescriptor field_descriptor, Type field_type)> get_oneof_descriptor_index<T, TOneofCase>(string prop_name)
@@ -34,8 +34,8 @@ namespace bts.utils {
where TOneofCase : struct =>
_DescriptorImpl<T>.OneofImpl<TOneofCase>.get_descriptor_case_index(prop_name);
public static FieldDescriptor get_oneof_field_descriptor<T, TOneofCase>(TOneofCase oneof_case) where T : IMessage, new() where TOneofCase : struct {
string oneof_name = oneof_case.ToString();
public static FieldDescriptor? get_oneof_field_descriptor<T, TOneofCase>(TOneofCase oneof_case) where T : IMessage, new() where TOneofCase : struct {
var oneof_name = oneof_case.ToString();
return Descriptor<T>().Fields.InFieldNumberOrder().FirstOrDefault(fd => fd.Name.Replace("_", "").iequals(oneof_name));
}
@@ -58,21 +58,21 @@ namespace bts.utils {
}
public static TImmutable immutable_factory<TMutable, TImmutable>(TMutable m) where TMutable : IMessage, new() where TImmutable : IImmutableMessage =>
(TImmutable)Activator.CreateInstance(typeof(TImmutable), m);
(TImmutable)Activator.CreateInstance(typeof(TImmutable), m)!;
public static IMessage mutable_factory(Type type) =>
MutableFactoryStore.get(type)();
static class MutableFactoryStore {
[ThreadStatic]
static Dictionary<Type, Func<IMessage>> _factories_backing;
static Dictionary<Type, Func<IMessage>>? _factories_backing;
static Dictionary<Type, Func<IMessage>> _factories => _factories_backing ?? (_factories_backing = new Dictionary<Type, Func<IMessage>>());
public static Func<IMessage> get(Type type) =>
_factories.GetOrAdd(type,
t => typeof(MutableFactory<>).MakeGenericType(t)
t => (Func<IMessage>)typeof(MutableFactory<>).MakeGenericType(t)
.GetField(nameof(MutableFactory<LimitOrderDefinition>.anonymous_factory), BindingFlags.Static | BindingFlags.Public)
.GetValue(null) as Func<IMessage>);
!.GetValue(null)!);
}
static class MutableFactory<T> where T : IMessage<T>, new() {
@@ -118,7 +118,7 @@ namespace bts.utils {
public static IReadOnlyDictionary<TOneofCase, (FieldDescriptor field_descriptor, Type field_type)> get_descriptor_case_index(string prop_name) {
/// Use local copy because <see cref="_descriptor_case_indices"/> is updated atomically.
var dci = _descriptor_case_indices;
if (!dci.TryGetValue(prop_name, out IReadOnlyDictionary<TOneofCase, (FieldDescriptor field_descriptor, Type field_type)> rv)) {
if (!dci.TryGetValue(prop_name, out var rv)) {
/// Update <see cref="_descriptor_case_indices"/> atomically (lock-free).
/// 1) clone the local copy.
/// 2) add the new KeyValue to the clone.
@@ -1,9 +1,13 @@
#nullable enable
namespace Spark.Core {
using System;
using System.Runtime.CompilerServices;
public static class NullableExtensions {
public static T assert_value<T>(this T? nullable) where T : struct =>
nullable ?? throw new ArgumentNullException(nameof(nullable));
public static T RequireValue<T>(this T? nullable, [CallerArgumentExpression(nameof(nullable))] string name = "") where T : struct =>
nullable ?? throw new ArgumentNullException(name);
}
}
@@ -27,17 +27,17 @@ namespace {{package}} {
readonly Lazy<IObservable<TableUpdate<{{output_type_full}}Immutable, {{key_type.cstype}}>>> _{{name}}_tablei_src;
// {{comment}}
public IObservable<Update<{{output_type_full}}, {{key_type.cstype}}>> subscribe_{{name}}(string qualifier = null) =>
public IObservable<Update<{{output_type_full}}, {{key_type.cstype}}>> subscribe_{{name}}(string? qualifier = null) =>
_channel.subscribe<{{output_type_full}}, {{output_type_full}}>(
{{@index}}, "{{name}}", qualifier, {{output_type_full}}.Parser, a => a)
.reconstitute(_key);
public IObservable<Update<{{output_type_full}}Immutable, {{key_type.cstype}}>> subscribei_{{name}}(string qualifier = null) =>
public IObservable<Update<{{output_type_full}}Immutable, {{key_type.cstype}}>> subscribei_{{name}}(string? qualifier = null) =>
_channel.subscribe<{{output_type_full}}, {{output_type_full}}Immutable>(
{{@index}}, "{{name}}", qualifier, {{output_type_full}}.Parser, a => ({{output_type_full}}Immutable)a)
{{@index}}, "{{name}}", qualifier, {{output_type_full}}.Parser, a => ({{output_type_full}}Immutable)a!)
.reconstitute(_key);
public IObservable<TableUpdate<{{output_type_full}}Immutable, {{key_type.cstype}}>> subscribei_{{name}}_table(string qualifier = null) =>
public IObservable<TableUpdate<{{output_type_full}}Immutable, {{key_type.cstype}}>> subscribei_{{name}}_table(string? qualifier = null) =>
_{{name}}_tablei_src.Value;
static {{key_type.cstype}} _key({{output_type_full}} row) =>
@@ -61,7 +61,7 @@ namespace {{package}} {
// {{comment}}
public {{output_type_full}} {{name}}({{input_type_full}} request) {
if (_channel.is_sync_call_ok()) {
return {{name}}_async(request).Result.value;
return {{name}}_async(request).Result.value ?? throw new InvalidOperationException("Response is null");
}
throw new ApiException(
"API blocking call cannot be made on this thread. Please use {{name}}_async instead.");
@@ -69,7 +69,7 @@ namespace {{package}} {
internal {{output_type_full}} {{name}}({{input_type_full}}Immutable request) {
if (_channel.is_sync_call_ok()) {
return {{name}}_async(request).Result.value;
return {{name}}_async(request).Result.value ?? throw new InvalidOperationException("Response is null");
}
throw new ApiException(
"API blocking call cannot be made on this thread. Please use {{name}}_async instead.");
@@ -17,7 +17,7 @@ namespace {{package}} {
abstract class Authenticated{{name}}Base : ApiServer, IDisposable {
readonly ServerChannel _channel;
public Authenticated{{name}}Base(ServiceContext context, string qualifier = "") =>
public Authenticated{{name}}Base(ServiceContext context, string? qualifier = null) =>
_channel = context.publish(this, "{{name}}", qualifier);
enum ServiceMethods {
@@ -66,7 +66,7 @@ namespace {{package}} {
{{#each method}}
{{#if server_streaming}}
public virtual Task<StreamAccessResponse> allow_{{name}}(
AuthTokenImmutable? token, string qualifier) {
AuthTokenImmutable? token, string? qualifier) {
var r = new StreamAccessResponse() { Authorized = true };
return Task.FromResult(r);
}
@@ -75,7 +75,7 @@ namespace {{package}} {
row.{{camel key_field}};
//{{comment}}
protected {{cap name}}Publisher make_{{name}}_publisher(string qualifier = null) {
protected {{cap name}}Publisher make_{{name}}_publisher(string? qualifier = null) {
var table = _channel.create_table("{{name}}", qualifier);
return new {{cap name}}Publisher(table);
}
@@ -97,9 +97,9 @@ namespace {{package}} {
}
public void publish(
List<{{output_type_full}}> added = null,
HashSet<{{key_type.cstype}}> removed = null,
List<{{output_type_full}}> changed = null) {
List<{{output_type_full}}>? added = null,
HashSet<{{key_type.cstype}}>? removed = null,
List<{{output_type_full}}>? changed = null) {
int add_count = added is null ? 0 : added.Count;
int change_count = changed is null ? 0 : changed.Count;
int remove_count = removed is null ? 0 : removed.Count;
@@ -112,8 +112,7 @@ namespace {{package}} {
if (added is not null) {
foreach (var a in added) {
var key = {{name}}_key(a);
var is_change = removed == null ? false : removed.Contains(key);
if (is_change) { removed.Remove(key); }
var is_change = removed?.Remove(key) ?? false;
changes[change_index++] = _pack(a, is_change, pinned_buffers);
}
}
@@ -190,7 +189,7 @@ namespace {{package}} {
// {{comment}}
abstract class {{name}}Base : Authenticated{{name}}Base , IDisposable {
public {{name}}Base(ServiceContext context, string qualifier="")
public {{name}}Base(ServiceContext context, string? qualifier = null)
: base(context, qualifier) { }
{{#each method}}
{{#unless server_streaming}}