Merged DJ_ICE_proprietary_risk into DJ_ICE
This commit is contained in:
commit
30feda72bb
21 files changed
+1166
-152
No files matched your search
@@ -109,6 +109,22 @@ namespace mbts.spark {
|
||||
public AccountTuple? get_default_account() =>
|
||||
_account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).TryFirst();
|
||||
|
||||
public async Task<Result<AdminServiceOperationResult>[]> set_risk_limits(IReadOnlyDictionary<uint, IEnumerable<(uint, RiskLimits)>> state) {
|
||||
var results = await Task.WhenAll(state.Select(impl));
|
||||
return results;
|
||||
async Task<Result<AdminServiceOperationResult>> impl(KeyValuePair<uint, IEnumerable<(uint, RiskLimits)>> kv) {
|
||||
var prlimits = new ProprietaryRiskLimits();
|
||||
foreach (var (sec, lim) in kv.Value) {
|
||||
var api_lim = AccountSecurityRiskLimitsDataHelper.from_client_data(sec, lim);
|
||||
prlimits.SecurityLimits.Add(api_lim);
|
||||
}
|
||||
return await _service.update_proprietary_risk_limits_async(new ProprietaryRiskLimitsAPIArgument {
|
||||
AccountId = kv.Key,
|
||||
ProprietaryRiskLimits = prlimits
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public Task<(bool success, string error_msg)> add_or_update_risk_limits(uint account_key, IEnumerable<(uint security_key, RiskLimits limits)> new_limits) {
|
||||
return _modify_risk_limits("Updating Risk Limits", account_key, add_limits);
|
||||
//
|
||||
|
||||
@@ -22,6 +22,9 @@ namespace bts.admin.risk {
|
||||
|
||||
public override int GetHashCode() =>
|
||||
EqualityComparer.auto_phase(security.GetHashCode(), account.GetHashCode());
|
||||
|
||||
public static bool operator ==(AccountSecurityKey a, AccountSecurityKey b) => a.Equals(b);
|
||||
public static bool operator !=(AccountSecurityKey a, AccountSecurityKey b) => !a.Equals(b);
|
||||
}
|
||||
|
||||
readonly struct AccountSecurityRiskLimits : IEquatable<AccountSecurityRiskLimits> {
|
||||
@@ -138,9 +141,9 @@ namespace bts.admin.risk {
|
||||
api_data.MinSellPrice,
|
||||
api_data.MaxBuyPrice));
|
||||
|
||||
public static AccountSecurityRiskLimits with(this AccountSecurityRiskLimits cli_data, RiskLimits? limits = null, AccountTuple? account = null, SecurityImmutable? security = null) =>
|
||||
public static AccountSecurityRiskLimits with(this AccountSecurityRiskLimits cli_data, RiskLimits? limits = null, AccountTuple? account = null, SecurityImmutable? security = null, AccountSecurityKey? key = null) =>
|
||||
new AccountSecurityRiskLimits(
|
||||
cli_data.key,
|
||||
key ?? cli_data.key,
|
||||
limits ?? cli_data.limits,
|
||||
account: account ?? new AccountTuple(cli_data.account_key, cli_data.account_name),
|
||||
security: security ?? cli_data.security);
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
using bts.admin.risk;
|
||||
using bts.api.core;
|
||||
using bts.collections;
|
||||
using mbts;
|
||||
using mbts.ui;
|
||||
using mbts.ui.utility;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using Component = bts.shell.risk_management.RiskLimitsImportConflictsView.RiskLimitsComponent;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
static class RiskLimitsImporter {
|
||||
/// <summary>
|
||||
/// Parses the specified file and passes the results to the <paramref name="on_parsed"/> delegate.
|
||||
/// If the parser encounters improperly formatted values, a dialog is automatically opened
|
||||
/// </summary>
|
||||
/// <returns>An IDisposable that will close the import-conflicts-dialog (if it was launched).</returns>
|
||||
public static IDisposable import_limits(string file_name, IReadOnlyDictionary<uint, SecurityMD> security_map, IReadOnlyDictionary<uint, string> account_map, Action<IEnumerable<ParsedRiskLimits>> on_parsed) {
|
||||
if (string.IsNullOrEmpty(file_name))
|
||||
throw new ArgumentException("File name is null or empty.", nameof(file_name));
|
||||
if (security_map is null)
|
||||
throw new ArgumentNullException(nameof(security_map));
|
||||
if (account_map is null)
|
||||
throw new ArgumentNullException(nameof(account_map));
|
||||
if (on_parsed is null)
|
||||
throw new ArgumentNullException(nameof(on_parsed));
|
||||
IReadOnlyList<ParsedRiskLimits> parsed_limit_items;
|
||||
try {
|
||||
parsed_limit_items = RiskLimitsParser.parse_rows(
|
||||
File.ReadAllLines(file_name),
|
||||
MappedDictionary.create(security_map, sec_md => sec_md.security),
|
||||
account_map)
|
||||
.ToList();
|
||||
} catch (Exception ex) {
|
||||
BTSMessageBox.Error($"Error importing limits: {ex}.", RiskManagementWindow.window_type_display_name);
|
||||
return null;
|
||||
}
|
||||
var conflicts = RiskLimitsParser.get_conflicts(parsed_limit_items);
|
||||
if (conflicts.Count > 0) {
|
||||
// init vm
|
||||
var vm = new RiskLimitsImportVM(parsed_limit_items.Count) {
|
||||
security_map = security_map
|
||||
};
|
||||
// add rows
|
||||
foreach (var kv in conflicts) {
|
||||
var resolve_del = RiskLimitsParser.assign_component(kv.Key);
|
||||
foreach (var text_groups in kv.Value) {
|
||||
var eval = get_error_value(kv.Key);
|
||||
var row = new RiskLimitsImportVM.Row(kv.Key, text_groups.Key, text_groups.Value, eval, eval);
|
||||
vm.rows.Add(row);
|
||||
vm.import_request += () => {
|
||||
foreach (var pmf in text_groups.Value) {
|
||||
if (resolve_del(pmf.result, row.value) is AccountSecurityRiskLimits resolved)
|
||||
pmf.result = resolved;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
var win = new RiskLimitsImportConflictsDialog {
|
||||
DataContext = vm,
|
||||
Title = RiskManagementWindow.window_type_display_name,
|
||||
Topmost = true
|
||||
};
|
||||
IDisposable dispose = null;
|
||||
vm.RequestClose += (s, e) => Disposable.dispose(ref dispose);
|
||||
vm.import_request += () => {
|
||||
on_parsed(parsed_limit_items);
|
||||
Disposable.dispose(ref dispose);
|
||||
};
|
||||
Disposable.dispose(ref dispose);
|
||||
vm.accounts.SetItems(account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).Cast<AccountTuple?>());
|
||||
dispose = Disposable.Create(
|
||||
vm,
|
||||
Disposable.Create(close));
|
||||
win.move_to_mouse(-200, -75);
|
||||
win.Show();
|
||||
return dispose;
|
||||
|
||||
void close() => WindowUtilities.force_close(win);
|
||||
object get_error_value(Component component) {
|
||||
switch (component) {
|
||||
case Component.MaxNetLongPosition:
|
||||
case Component.MaxNetShortPosition:
|
||||
case Component.ClipLimit:
|
||||
return 0;
|
||||
case Component.MinPrice:
|
||||
case Component.MaxPrice:
|
||||
return double.NaN;
|
||||
case Component.IsPositionLimitEnabled:
|
||||
case Component.IsClipLimitEnabled:
|
||||
case Component.IsPriceLimitEnabled:
|
||||
return false;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
on_parsed(parsed_limit_items);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
using bts.admin.risk;
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
using bts.utils;
|
||||
using mbts.ui.utility;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using RiskLimitsComponent = bts.shell.risk_management.RiskLimitsImportConflictsView.RiskLimitsComponent;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
class ParsedRiskLimits {
|
||||
public readonly Guid unpersisted_id = Guid.NewGuid();
|
||||
public AccountSecurityRiskLimits result { get; set; }
|
||||
|
||||
public (string text, bool success) security { get; set; }
|
||||
public (string text, bool success) account { get; set; }
|
||||
public (string text, bool success) max_long_position { get; set; }
|
||||
public (string text, bool success) max_short_position { get; set; }
|
||||
public (string text, bool success) is_position_limit_enabled { get; set; }
|
||||
public (string text, bool success) clip_limit { get; set; }
|
||||
public (string text, bool success) is_clip_limit_enabled { get; set; }
|
||||
public (string text, bool success) min_price { get; set; }
|
||||
public (string text, bool success) max_price { get; set; }
|
||||
public (string text, bool success) is_price_limit_enabled { get; set; }
|
||||
|
||||
public bool Equals(ParsedRiskLimits other) => other != null && unpersisted_id == other.unpersisted_id;
|
||||
public override bool Equals(object obj) => Equals(obj as ParsedRiskLimits);
|
||||
public override int GetHashCode() => unpersisted_id.GetHashCode();
|
||||
}
|
||||
|
||||
static class RiskLimitsParser {
|
||||
public const string file_extension = "csv";
|
||||
|
||||
public static Func<AccountSecurityRiskLimits, object, object> assign_component(RiskLimitsComponent component) {
|
||||
switch (component) {
|
||||
case RiskLimitsComponent.Security: return (mf, val) => mf.with(key: new AccountSecurityKey(mf.account_key, ConvertUtils.try_convert<SecurityImmutable?>(val)?.Id ?? 0));
|
||||
case RiskLimitsComponent.Account: return (mf, val) => mf.with(key: new AccountSecurityKey(ConvertUtils.try_convert<AccountTuple?>(val)?.id ?? 0, mf.key.security));
|
||||
case RiskLimitsComponent.MaxNetLongPosition: return (mf, val) => mf.with(mf.limits.with(max_long_position: ConvertUtils.try_convert<uint>(val)));
|
||||
case RiskLimitsComponent.MaxNetShortPosition: return (mf, val) => mf.with(mf.limits.with(max_short_position: ConvertUtils.try_convert<uint>(val)));
|
||||
case RiskLimitsComponent.IsPositionLimitEnabled: return (mf, val) => mf.with(mf.limits.with(is_price_limit_enabled: ConvertUtils.try_convert<bool>(val)));
|
||||
case RiskLimitsComponent.ClipLimit: return (mf, val) => mf.with(mf.limits.with(clip_limit: ConvertUtils.try_convert<uint>(val)));
|
||||
case RiskLimitsComponent.IsClipLimitEnabled: return (mf, val) => mf.with(mf.limits.with(is_price_limit_enabled: ConvertUtils.try_convert<bool>(val)));
|
||||
case RiskLimitsComponent.MinPrice: return (mf, val) => mf.with(mf.limits.with(min_price: ConvertUtils.try_convert(val, double.NaN)));
|
||||
case RiskLimitsComponent.MaxPrice: return (mf, val) => mf.with(mf.limits.with(max_price: ConvertUtils.try_convert(val, double.NaN)));
|
||||
case RiskLimitsComponent.IsPriceLimitEnabled: return (mf, val) => mf.with(mf.limits.with(is_price_limit_enabled: ConvertUtils.try_convert<bool>(val)));
|
||||
default: throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public static ImmutableDictionary<RiskLimitsComponent, ImmutableDictionary<string, ImmutableList<ParsedRiskLimits>>> get_conflicts(IEnumerable<ParsedRiskLimits> parsed_limits) {
|
||||
// Add all the components up front (a simple optimizatino since there aren't many),
|
||||
// so there is no need to check for there existence as various conflicts are added.
|
||||
// After all conflicts have been added, remove the empty entries.
|
||||
var missing_components = EnumHelper.get_values<RiskLimitsComponent>()
|
||||
.ToImmutableDictionary(c => c, c => ImmutableDictionary<string, ImmutableList<ParsedRiskLimits>>.Empty)
|
||||
.ToBuilder();
|
||||
foreach (var pmf in parsed_limits) {
|
||||
if (!pmf.security.success) {
|
||||
add_missing(RiskLimitsComponent.Security, pmf.security.text, pmf);
|
||||
}
|
||||
if (!pmf.account.success) {
|
||||
add_missing(RiskLimitsComponent.Account, pmf.account.text, pmf);
|
||||
}
|
||||
if (!pmf.max_long_position.success) {
|
||||
add_missing(RiskLimitsComponent.MaxNetLongPosition, pmf.max_long_position.text, pmf);
|
||||
}
|
||||
if (!pmf.max_short_position.success) {
|
||||
add_missing(RiskLimitsComponent.MaxNetShortPosition, pmf.max_short_position.text, pmf);
|
||||
}
|
||||
if (!pmf.is_position_limit_enabled.success) {
|
||||
add_missing(RiskLimitsComponent.IsPositionLimitEnabled, pmf.is_position_limit_enabled.text, pmf);
|
||||
}
|
||||
if (!pmf.clip_limit.success) {
|
||||
add_missing(RiskLimitsComponent.ClipLimit, pmf.clip_limit.text, pmf);
|
||||
}
|
||||
if (!pmf.is_clip_limit_enabled.success) {
|
||||
add_missing(RiskLimitsComponent.IsClipLimitEnabled, pmf.is_clip_limit_enabled.text, pmf);
|
||||
}
|
||||
if (!pmf.min_price.success) {
|
||||
add_missing(RiskLimitsComponent.MinPrice, pmf.min_price.text, pmf);
|
||||
}
|
||||
if (!pmf.max_price.success) {
|
||||
add_missing(RiskLimitsComponent.MaxPrice, pmf.max_price.text, pmf);
|
||||
}
|
||||
if (!pmf.is_price_limit_enabled.success) {
|
||||
add_missing(RiskLimitsComponent.IsPriceLimitEnabled, pmf.is_price_limit_enabled.text, pmf);
|
||||
}
|
||||
}
|
||||
// remove empty component conflicts
|
||||
var empty_keys = missing_components.Where(kv => kv.Value.Count == 0).Select(kv => kv.Key).ToList();
|
||||
missing_components.RemoveRange(empty_keys);
|
||||
return missing_components.ToImmutable();
|
||||
// local methods
|
||||
void add_missing(RiskLimitsComponent component, string text, ParsedRiskLimits prl) {
|
||||
if (!missing_components.TryGetValue(component, out var conflicts)) {
|
||||
conflicts = ImmutableDictionary<string, ImmutableList<ParsedRiskLimits>>.Empty;
|
||||
}
|
||||
if (!conflicts.TryGetValue(text, out var affected)) {
|
||||
affected = ImmutableList<ParsedRiskLimits>.Empty;
|
||||
}
|
||||
missing_components[component] = conflicts.SetItem(text, affected.Add(prl));
|
||||
}
|
||||
}
|
||||
|
||||
// This implementation prioritizes simplicity over speed.
|
||||
// The security desc lookup could be better optimized, but the speed at which limits are imported is probably not a paramount concern.
|
||||
public static IEnumerable<ParsedRiskLimits> parse_rows(IEnumerable<string> rows, IReadOnlyDictionary<uint, SecurityImmutable> security_map, IReadOnlyDictionary<uint, string> account_map) =>
|
||||
parse_rows(rows,
|
||||
reverse_lookup(MappedDictionary.create(security_map, s => s.ToString())),
|
||||
reverse_lookup(account_map));
|
||||
|
||||
public static IEnumerable<ParsedRiskLimits> parse_rows(IEnumerable<string> rows, Func<string, uint> security_id_lookup, Func<string, uint> account_id_lookup) {
|
||||
var columns = new[] {
|
||||
(Headers.Security, Cells.security(security_id_lookup)),
|
||||
(Headers.Account, Cells.account(account_id_lookup)),
|
||||
(Headers.MaxNetLongPosition, Cells.max_long_position),
|
||||
(Headers.MaxNetShortPosition, Cells.max_short_position),
|
||||
(Headers.IsPositionLimitEnabled, Cells.is_position_limit_enabled),
|
||||
(Headers.ClipLimit, Cells.clip_limit),
|
||||
(Headers.IsClipLimitEnabled, Cells.is_clip_limit_enabled),
|
||||
(Headers.MinPrice, Cells.min_price),
|
||||
(Headers.MaxPrice, Cells.max_price),
|
||||
(Headers.IsPriceLimitEnabled, Cells.is_price_limit_enabled)
|
||||
}.ToDictionary(col => col.Item1, col => col.Item2.with_null_check());
|
||||
return RowParser.parse_rows(rows, columns, Cells.delimiter);
|
||||
}
|
||||
|
||||
public static Func<string, TKey> reverse_lookup<TKey>(IReadOnlyDictionary<TKey, string> map) {
|
||||
var lookup = map.ToLookup(kv => kv.Value, kv => kv.Key);
|
||||
return cell_text => lookup.Contains(cell_text) ? lookup[cell_text].First() : default;
|
||||
}
|
||||
|
||||
static class Headers {
|
||||
public const string
|
||||
Security = "Security",
|
||||
Account = "Account",
|
||||
MaxNetLongPosition = "Max Long",
|
||||
MaxNetShortPosition = "Max Short",
|
||||
IsPositionLimitEnabled = "Enforce Position",
|
||||
ClipLimit = "Clip",
|
||||
IsClipLimitEnabled = "Enforce Clip",
|
||||
MinPrice = "Min Price",
|
||||
MaxPrice = "Max Price",
|
||||
IsPriceLimitEnabled = "Enforce Price";
|
||||
}
|
||||
|
||||
static class Cells {
|
||||
public const char delimiter = ',';
|
||||
|
||||
public static RowParser.AssignColumnValue<ParsedRiskLimits> security(Func<string, uint> reverse_id_lookup) {
|
||||
return impl;
|
||||
void impl(ref ParsedRiskLimits pmf, string text) {
|
||||
pmf.result = pmf.result.with(key: new AccountSecurityKey(pmf.result.key.account, reverse_id_lookup(text)));
|
||||
pmf.security = (text, pmf.result.key.security != 0);
|
||||
}
|
||||
}
|
||||
|
||||
public static RowParser.AssignColumnValue<ParsedRiskLimits> account(Func<string, uint> reverse_id_lookup) {
|
||||
return impl;
|
||||
void impl(ref ParsedRiskLimits pmf, string text) {
|
||||
pmf.result = pmf.result.with(key: new AccountSecurityKey(reverse_id_lookup(text), pmf.result.key.security));
|
||||
pmf.account = (text, pmf.result.key.account != 0);
|
||||
}
|
||||
}
|
||||
|
||||
public static void max_long_position(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (uint.TryParse(cell_text, out uint v)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(max_long_position: v));
|
||||
pmf.max_long_position = (cell_text, true);
|
||||
} else {
|
||||
pmf.max_long_position = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void max_short_position(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (uint.TryParse(cell_text, out uint v)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(max_short_position: v));
|
||||
pmf.max_short_position = (cell_text, true);
|
||||
} else {
|
||||
pmf.max_short_position = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void is_position_limit_enabled(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (_try_parse_yes_no(cell_text, out var result)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(is_position_limit_enabled: result));
|
||||
pmf.is_position_limit_enabled = (cell_text, true);
|
||||
} else {
|
||||
pmf.is_position_limit_enabled = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void clip_limit(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (uint.TryParse(cell_text, out uint v)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(clip_limit: v));
|
||||
pmf.clip_limit = (cell_text, true);
|
||||
} else {
|
||||
pmf.clip_limit = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void is_clip_limit_enabled(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (_try_parse_yes_no(cell_text, out var result)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(is_clip_limit_enabled: result));
|
||||
pmf.is_clip_limit_enabled = (cell_text, true);
|
||||
} else {
|
||||
pmf.is_clip_limit_enabled = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
static bool _try_parse_yes_no(string text, out bool result) {
|
||||
switch (text?.Trim()?.ToLower()) {
|
||||
case "y": result = true; break;
|
||||
case "n": result = false; break;
|
||||
default: result = default; return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void min_price(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (double.TryParse(cell_text, out var v)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(min_price: v));
|
||||
pmf.min_price = (cell_text, true);
|
||||
} else {
|
||||
pmf.min_price = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void max_price(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (double.TryParse(cell_text, out var v)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(max_price: v));
|
||||
pmf.max_price = (cell_text, true);
|
||||
} else {
|
||||
pmf.max_price = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void is_price_limit_enabled(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (_try_parse_yes_no(cell_text, out var result)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(is_price_limit_enabled: result));
|
||||
pmf.is_price_limit_enabled = (cell_text, true);
|
||||
} else {
|
||||
pmf.is_price_limit_enabled = (cell_text, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
using bts.admin.risk;
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
using bts.spark;
|
||||
using mbts;
|
||||
using mbts.persist;
|
||||
@@ -18,15 +19,15 @@ using System.Windows.Data;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
class RiskManagementWindow : SparkWindow<RiskManagementSettings>, ISharedWindow {
|
||||
const string
|
||||
_window_type_id = "RiskManagement",
|
||||
_window_type_display_name = "Risk Management";
|
||||
public const string
|
||||
window_type_id = "RiskManagement",
|
||||
window_type_display_name = "Risk Management";
|
||||
|
||||
readonly IWindowSettingsManager<GridSettings> _settings_manager;
|
||||
readonly AdminModel _model;
|
||||
FrameworkElement _view;
|
||||
IReadOnlyList<SparkCommand> _commands;
|
||||
IDisposable _settings_sub, _securities_sub;
|
||||
IDisposable _settings_sub, _securities_sub, _cmd_subscriptions;
|
||||
RiskManagementSettings _settings;
|
||||
RiskManagementVM _vm;
|
||||
SimpleGridSettingsManagerVM<RiskManagementControl.Columns> _grid_settings_manager => _vm.grid_settings_manager;
|
||||
@@ -39,17 +40,17 @@ namespace bts.shell.risk_management {
|
||||
IWindowSettingsManager<GridSettings> settings_manager,
|
||||
ISaveWindow<RiskManagementSettings> isw,
|
||||
RiskManagementSettings settings)
|
||||
: base(_window_type_display_name, bus, isw, Icons.Risk) {
|
||||
: base(window_type_display_name, bus, isw, Icons.Risk) {
|
||||
//
|
||||
_settings_manager = settings_manager;
|
||||
_settings = settings;
|
||||
_model = model;
|
||||
thread_id = mbts.config.Configuration.get<bts.config.MultiThreadedWindows>().risk_management ? "OrderBook" : null;
|
||||
thread_id = mbts.config.Configuration.get<bts.config.MultiThreadedWindows>().risk_management ? window_type_id : null;
|
||||
_securities_sub = bus.subscribe(SparkTags.SecuritiesTag).Subscribe(sec_map => _security_map = sec_map);
|
||||
}
|
||||
|
||||
public override IEnumerable<SparkCommand> Commands => _commands;
|
||||
public override string window_type => _window_type_id;
|
||||
public override string window_type => window_type_id;
|
||||
|
||||
public override RiskManagementSettings SaveState =>
|
||||
(_vm?.create() ?? RiskManagementSettings.Default).with(menu_display: _menu_display_vm.safe_create());
|
||||
@@ -65,6 +66,7 @@ namespace bts.shell.risk_management {
|
||||
public string thread_id { get; }
|
||||
|
||||
public override void Dispose() {
|
||||
Disposable.dispose(ref _cmd_subscriptions);
|
||||
_commands.empty_if_null().OfType<IDisposable>().DisposeAll();
|
||||
Disposable.dispose(ref _securities_sub);
|
||||
Disposable.dispose(ref _settings_sub);
|
||||
@@ -79,11 +81,11 @@ namespace bts.shell.risk_management {
|
||||
Log.assert(_settings_sub == null, "Grid settings subscription has already been initialized.");
|
||||
// initialize everything: menu_display_vm, vm, settings subscription, and view
|
||||
_menu_display_vm = _init_menu_display_vm(_settings.menu_display);
|
||||
_vm = _init_vm(_model, _settings);
|
||||
_vm = _init_vm(_bus.subscribe(SparkTags.SecuritiesTag), _model, _settings);
|
||||
_settings_sub = _settings_manager.subscribe_current()
|
||||
.OnDispatcher()
|
||||
.Subscribe(gs => _vm.load_from(gs));
|
||||
_commands = new List<SparkCommand>(_mk_commands());
|
||||
(_commands, _cmd_subscriptions) = _mk_commands();
|
||||
_view = new RiskManagementControl { DataContext = _vm };
|
||||
}
|
||||
|
||||
@@ -93,17 +95,25 @@ namespace bts.shell.risk_management {
|
||||
return vm;
|
||||
}
|
||||
|
||||
static RiskManagementVM _init_vm(AdminModel model, RiskManagementSettings settings) {
|
||||
static RiskManagementVM _init_vm(IObservable<IReadOnlyDictionary<uint, SecurityMD>> securities_source, AdminModel model, RiskManagementSettings settings) {
|
||||
var vm = new RiskManagementVM(model.account_security_risk_limits, model.on_account_tuples);
|
||||
vm.request_update_limit += update_limit;
|
||||
vm.load_from(settings);
|
||||
var vm_sec_sub = securities_source.OnDispatcher().Subscribe(sec_map => vm.security_map = sec_map);
|
||||
vm.OnDisposed += _ => Disposable.dispose(ref vm_sec_sub);
|
||||
return vm;
|
||||
void update_limit(AccountSecurityRiskLimits lim) =>
|
||||
model.add_or_update_risk_limits(lim.account_key, new[] { (lim.security_key, lim.limits) }).ignore();
|
||||
void update_limit(AccountSecurityRiskLimits lim) {
|
||||
model.set_risk_limits(
|
||||
MappedDictionary.create(
|
||||
vm.build_account_limits_map(), acc_sec_lims => acc_sec_lims.Select(asl => (asl.security_key, asl.limits))))
|
||||
.ignore();
|
||||
}
|
||||
}
|
||||
|
||||
IEnumerable<SparkCommand> _mk_commands() {
|
||||
yield return new SparkCommandCommand("Add New Limits", Icons.AddBoxes, new DialogCommand(() => {
|
||||
(List<SparkCommand> cmds, IDisposable subscriptions) _mk_commands() {
|
||||
var subs = new List<IDisposable>();
|
||||
var cmds = new List<SparkCommand>();
|
||||
cmds.Add(new SparkCommandCommand("Add New Limits", Icons.AddBoxes, new DialogCommand(() => {
|
||||
if (_vm is null)
|
||||
return null;
|
||||
var account_id = _vm.selected_account?.id ?? 0;
|
||||
@@ -122,33 +132,60 @@ namespace bts.shell.risk_management {
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
var edit_selected_rows_cmd = new DialogCommand(() => {
|
||||
})));
|
||||
var edit_cmd = new DialogCommand(() => {
|
||||
if (!(_vm?.selected_account).HasValue)
|
||||
return null;
|
||||
var account_id = _vm.selected_account.Value.id;
|
||||
var targets = _vm.selected_rows.Select(r => r.create()).ToList();
|
||||
var targets = _vm.selected_rows.Select(r => r.data).ToList();
|
||||
var init_state = RiskLimitsModification.aggregate_common_props(targets);
|
||||
return mk_row_editor_dialog(init_state, commit, false);
|
||||
void commit(RiskLimitsModification mod) =>
|
||||
_model.add_or_update_risk_limits(account_id, targets.Select(r => (r.security_key, mod.apply(r.limits)))).ignore();
|
||||
_vm.modify_rows(targets.WrapSelector(t => t.key, null), mod);
|
||||
}, () => _vm.selected_rows.Count > 0, true, off_x: -300, off_y: -60);
|
||||
_vm.selected_rows_changed += edit_selected_rows_cmd.RaiseCanExecuteChanged;
|
||||
yield return new SparkCommandCommand("Edit Selected Rows", Icons.ModifyOrder, edit_selected_rows_cmd);
|
||||
_vm.selected_rows_changed += edit_cmd.RaiseCanExecuteChanged;
|
||||
cmds.Add(new SparkCommandCommand("Edit Selected Rows", Icons.ModifyOrder, edit_cmd));
|
||||
var revert_selected_rows_cmd = ObservantCommand.create(() => _vm?.revert(_vm.selected_rows), out var revert_selected_rows_observer);
|
||||
subs.Add(_vm.subscribe_selected_rows()
|
||||
.Select(srs => srs.Count > 0)
|
||||
.And(_vm.subscribe_has_dirty_rows())
|
||||
.OnDispatcher()
|
||||
.Subscribe(revert_selected_rows_observer));
|
||||
cmds.Add(new SparkCommandCommand("Revert Selected Rows", Icons.UndoCircular, revert_selected_rows_cmd));
|
||||
|
||||
var delete_selected_rows_cmd = new DelegateCommand(() => {
|
||||
cmds.Add(new SparkCommandCommand("Import Limits", Icons.Import,
|
||||
FileDialogCommand.open_file(file => _vm?.import_limits(file), extensions: RiskLimitsParser.file_extension)));
|
||||
|
||||
var save_cmd = new SparkCommandCommand("Save", Icons.Disk, ObservantCommand.create(() => {
|
||||
//_vm.selected_account.Value.id, _vm.rows.Where(r => r.)
|
||||
var lims = _vm.build_account_limits_map();
|
||||
var mlims = MappedDictionary.create(lims, l => l.Select(lim => (lim.security_key, lim.limits)));
|
||||
_model.set_risk_limits(mlims).ignore();
|
||||
}, out var save_observer));
|
||||
cmds.Add(save_cmd);
|
||||
subs.Add(_vm.subscribe_has_dirty_rows().OnDispatcher().Subscribe(save_observer));
|
||||
|
||||
var delete_cmd = new DelegateCommand(() => {
|
||||
if (!(_vm?.selected_account).HasValue)
|
||||
return;
|
||||
var selected_rows = _vm.selected_rows;
|
||||
var to_remove = _vm.selected_rows;
|
||||
var account_id = _vm.selected_account.Value.id;
|
||||
if (BTSMessageBox.Confirm($"Are you sure you want to delete the selected limits ({selected_rows.Count})?", "Delete Limits"))
|
||||
_model.delete_risk_limits(account_id, selected_rows.Select(r => r.security_key)).ignore();
|
||||
if (BTSMessageBox.Confirm($"Are you sure you want to delete the selected limits ({to_remove.Count})?", "Delete Limits")) {
|
||||
// remove unpersisted limits first (i.e., imports), then delete the persisted ones.
|
||||
foreach (var r in to_remove) {
|
||||
if (!r.is_persisted) {
|
||||
_vm.rows.RemoveSorted(r, _vm.row_comparer);
|
||||
to_remove = to_remove.Remove(r);
|
||||
}
|
||||
}
|
||||
_model.delete_risk_limits(account_id, to_remove.Select(r => r.security_key)).ignore();
|
||||
}
|
||||
}, () => _vm.selected_rows.Count > 0);
|
||||
_vm.selected_rows_changed += delete_selected_rows_cmd.RaiseCanExecuteChanged;
|
||||
_vm.selected_rows_changed += delete_cmd.RaiseCanExecuteChanged;
|
||||
|
||||
yield return new SparkCommandCommand("Delete", Icons.Trash, delete_selected_rows_cmd);
|
||||
cmds.Add(new SparkCommandCommand("Delete", Icons.Trash, delete_cmd));
|
||||
// wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes
|
||||
yield return SparkCommands.window_settings_command(new DialogCommand(() => {
|
||||
cmds.Add(SparkCommands.window_settings_command(new DialogCommand(() => {
|
||||
if (_vm is null)
|
||||
return null;
|
||||
_settings_manager.instance_settings = _vm.create().grid;
|
||||
@@ -162,8 +199,9 @@ namespace bts.shell.risk_management {
|
||||
var dialog = new ShellSettingsDialog { DataContext = settings_vm };
|
||||
settings_vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog);
|
||||
return dialog;
|
||||
}));
|
||||
yield return _menu_display_vm.spark_cmd;
|
||||
})));
|
||||
cmds.Add(_menu_display_vm.spark_cmd);
|
||||
return (cmds, Disposable.wrap_collection(subs));
|
||||
|
||||
// although only the api only requires security keys,
|
||||
// the actual securities are used in this method so the user can see them in the view
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
using mbts;
|
||||
using mbts.collections;
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Input;
|
||||
using Component = bts.shell.risk_management.RiskLimitsImportConflictsView.RiskLimitsComponent;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
class RiskLimitsImportVM : DisposableViewModelBase, IRequestViewClose {
|
||||
readonly RefCountMap<ParsedRiskLimits> _conflicts = new RefCountMap<ParsedRiskLimits>();
|
||||
IReadOnlyDictionary<uint, SecurityMD> _security_map = DictionaryHelper.empty<uint, SecurityMD>();
|
||||
|
||||
public RiskLimitsImportVM(int num_limits) {
|
||||
rows_view = CollectionViewSource.GetDefaultView(rows);
|
||||
ok_cmd = new DelegateCommand(() => import_request?.Invoke());
|
||||
cancel_cmd = new DelegateCommand(() => RequestClose?.Invoke(this, new EventArgs()));
|
||||
this.num_limits = num_limits;
|
||||
_dispose = ObservableAutoWrapper.connect_item_hooks(rows, r =>
|
||||
r.subscribe_has_error().Subscribe(has_error => {
|
||||
if (has_error) {
|
||||
if (r.affected_limits.Count(_conflicts.increment_adds_key) == 0)
|
||||
return;
|
||||
} else if (r.affected_limits.Count(_conflicts.decrement_removes_key) == 0)
|
||||
return;
|
||||
RaisePropertyChanged(nameof(num_successfully_parsed_limits));
|
||||
}));
|
||||
}
|
||||
|
||||
public event Action import_request;
|
||||
public event EventHandler RequestClose;
|
||||
|
||||
public ObservableCollection<Row> rows { get; } = new ObservableCollection<Row>();
|
||||
public ICollectionView rows_view { get; }
|
||||
public int num_limits { get; }
|
||||
public int num_successfully_parsed_limits => num_limits - _conflicts.Count;
|
||||
// misc items sources
|
||||
public IEnumerable<Side> sides => new[] { Side.Buy, Side.Sell };
|
||||
public ObservableCollection<AccountTuple?> accounts { get; } = new ObservableCollection<AccountTuple?>();
|
||||
public IReadOnlyDictionary<uint, SecurityMD> security_map {
|
||||
get => _security_map;
|
||||
set {
|
||||
if (!ReferenceEquals(_security_map, value)) {
|
||||
_security_map = value;
|
||||
_resolve_securities();
|
||||
RaisePropertyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
// commands
|
||||
public ICommand ok_cmd { get; }
|
||||
public ICommand cancel_cmd { get; }
|
||||
|
||||
void _resolve_securities() {
|
||||
if (_security_map == null)
|
||||
return;
|
||||
var reverse_lookup = RiskLimitsParser.reverse_lookup(MappedDictionary.create(_security_map, v => v.security.ToString()));
|
||||
foreach (var r in rows) {
|
||||
if (r.component == Component.Security && r.has_error) {
|
||||
var id = reverse_lookup(r.text);
|
||||
if (id != 0 && _security_map.TryGetValue(id, out var smd))
|
||||
r.value = smd.security;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Row : ViewModelBase, ITemplateSelectorKey {
|
||||
readonly DelegateProperty<bool> _has_error;
|
||||
object _value;
|
||||
string _text;
|
||||
|
||||
public Row(Component component, string text, IReadOnlyCollection<ParsedRiskLimits> affected_limits, object error_value, object value) {
|
||||
this.component = component;
|
||||
this.text = text;
|
||||
this.affected_limits = affected_limits;
|
||||
_value = value;
|
||||
_has_error = backing(nameof(has_error), () => Equals(this.value, error_value));
|
||||
}
|
||||
|
||||
public Component component { get; }
|
||||
public string text { get => _text; set => Set(ref _text, value); }
|
||||
public IReadOnlyCollection<ParsedRiskLimits> affected_limits { get; }
|
||||
public object value {
|
||||
get => _value;
|
||||
set {
|
||||
if (Set(ref _value, value))
|
||||
_has_error.refresh();
|
||||
}
|
||||
}
|
||||
public bool has_error => _has_error.Value;
|
||||
string ITemplateSelectorKey.key => component.ToString();
|
||||
|
||||
public IObservable<bool> subscribe_has_error() => _has_error.observe_current(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,7 @@ namespace bts.shell.risk_management {
|
||||
public RiskLimitsModification(
|
||||
SecurityImmutable? security = null,
|
||||
SecurityCriteria security_criteria = null,
|
||||
AccountTuple? account = null,
|
||||
uint? max_long_position = null,
|
||||
uint? max_short_position = null,
|
||||
bool? is_position_limit_enabled = null,
|
||||
@@ -98,6 +99,7 @@ namespace bts.shell.risk_management {
|
||||
//
|
||||
this.security = security;
|
||||
this.security_criteria = security_criteria;
|
||||
this.account = account;
|
||||
this.max_long_position = max_long_position;
|
||||
this.max_short_position = max_short_position;
|
||||
this.is_position_limit_enabled = is_position_limit_enabled;
|
||||
@@ -110,6 +112,7 @@ namespace bts.shell.risk_management {
|
||||
|
||||
public SecurityImmutable? security { get; }
|
||||
public SecurityCriteria security_criteria { get; }
|
||||
public AccountTuple? account { get; }
|
||||
// position
|
||||
public uint? max_long_position { get; }
|
||||
public uint? max_short_position { get; }
|
||||
@@ -126,6 +129,7 @@ namespace bts.shell.risk_management {
|
||||
new RiskLimitsModification(
|
||||
_common_value(limit_items, l => l.security, s => s),
|
||||
null,
|
||||
_common_value(limit_items, l => new AccountTuple(l.account_key, l.account_name)),
|
||||
_common_value(limit_items, l => l.limits.max_long_position),
|
||||
_common_value(limit_items, l => l.limits.max_short_position),
|
||||
_common_value(limit_items, l => l.limits.is_position_limit_enabled),
|
||||
@@ -146,8 +150,25 @@ namespace bts.shell.risk_management {
|
||||
min_price: min_price ?? target.min_price,
|
||||
max_price: max_price ?? target.max_price);
|
||||
|
||||
public RiskLimitsModification with(RiskLimitsModification other_mod) =>
|
||||
with(
|
||||
other_mod.security.HasValue ? other_mod.security.Value : security,
|
||||
other_mod.account.HasValue ? other_mod.account.Value : account,
|
||||
security_criteria: other_mod.security_criteria ?? security_criteria,
|
||||
max_long_position: other_mod.max_long_position ?? max_long_position,
|
||||
max_short_position: other_mod.max_short_position ?? max_short_position,
|
||||
is_position_limit_enabled: other_mod.is_position_limit_enabled ?? is_position_limit_enabled,
|
||||
clip_limit: other_mod.clip_limit ?? clip_limit,
|
||||
is_clip_limit_enabled: other_mod.is_clip_limit_enabled ?? is_clip_limit_enabled,
|
||||
min_price: other_mod.min_price ?? min_price,
|
||||
max_price: other_mod.max_price ?? max_price,
|
||||
is_price_limit_enabled: other_mod.is_price_limit_enabled ?? is_price_limit_enabled);
|
||||
//new RiskLimitsModification(security: other_mod.security ?? security,
|
||||
// security_criteria: other_mod.security ?? security);
|
||||
|
||||
public RiskLimitsModification with(
|
||||
OptionalNullable<SecurityImmutable>? security = null,
|
||||
OptionalNullable<AccountTuple>? account = null,
|
||||
SecurityCriteria security_criteria = null,
|
||||
OptionalNullable<uint>? max_long_position = null,
|
||||
OptionalNullable<uint>? max_short_position = null,
|
||||
@@ -161,6 +182,7 @@ namespace bts.shell.risk_management {
|
||||
new RiskLimitsModification(
|
||||
security.HasValue ? security.Value.value : this.security,
|
||||
security_criteria ?? this.security_criteria,
|
||||
account.HasValue ? account.Value.value : this.account,
|
||||
max_long_position.HasValue ? max_long_position.Value.value : this.max_long_position,
|
||||
max_short_position.HasValue ? max_short_position.Value.value : this.max_short_position,
|
||||
is_position_limit_enabled.HasValue ? is_position_limit_enabled.Value.value : this.is_position_limit_enabled,
|
||||
|
||||
@@ -1,89 +1,114 @@
|
||||
using bts.admin.risk;
|
||||
using bts.api;
|
||||
using bts.utils;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
class RiskLimitsVM : ViewModelBase, IValueFactory<AccountSecurityRiskLimits> {
|
||||
readonly DeferrableActionWrapper _result_changed;
|
||||
// The user can modify some props directly in the grid.
|
||||
// However, the sorting relies on immutable data
|
||||
// (binary search may break if the applicable comparisons change,
|
||||
// depending on the current sorting criteria).
|
||||
// As a work-around, the rows are sorted by the committed_data.
|
||||
// Any modifications made through the prop setters are assumed to be 'user-changes'
|
||||
// (as the props are bound to the view),
|
||||
/// and the committed data is only changed through <see cref="load_from(AccountSecurityRiskLimits)"/>.
|
||||
AccountSecurityRiskLimits _committed_data, _mutable_data;
|
||||
class RiskLimitsVM : ViewModelBase, IEquatable<RiskLimitsVM> {
|
||||
RiskLimitsVM(AccountSecurityKey id) =>
|
||||
this.id = id;
|
||||
|
||||
public RiskLimitsVM() =>
|
||||
_result_changed = new DeferrableActionWrapper(() => result_changed?.Invoke());
|
||||
public event Action request_commit;
|
||||
|
||||
public RiskLimitsVM(AccountSecurityRiskLimits data) : this() {
|
||||
_committed_data = data;
|
||||
_mutable_data = data;
|
||||
}
|
||||
/// The user can modify some props directly in the grid,
|
||||
/// which may or may not give the row a new sort-position.
|
||||
/// For this reason, the owner-viewmodel (<see cref="RiskManagementVM"/>)
|
||||
/// is notified both immediately before, and after the changes are reflected in <see cref="data"/>.
|
||||
/// By responding to those events, the owner-viewmodel can safely process any
|
||||
/// sorting-changes without breaking binary search functionality.
|
||||
/// <see cref="value_changing"/>, <see cref="value_changed"/>
|
||||
|
||||
public event Action result_changed;
|
||||
/// <summary>
|
||||
/// This event is raised just before a new value is assigned to <see cref="data"/>.
|
||||
/// </summary>
|
||||
public event Action<(AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value)> value_changing;
|
||||
/// <summary>
|
||||
/// This event is raised immediately after a new value is assigned to <see cref="data"/>.
|
||||
/// </summary>
|
||||
public event Action<(AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value)> value_changed;
|
||||
public event Action is_dirty_changed;
|
||||
|
||||
public SecurityImmutable? security => _committed_data.security;
|
||||
public uint security_key => _committed_data.security_key;
|
||||
public string account_name => _committed_data.account_name;
|
||||
public uint account_key => _committed_data.account_key;
|
||||
public AccountSecurityKey id { get; }
|
||||
public SecurityImmutable? security => data.security;
|
||||
public string security_text => is_persisted ? security.ToString() : $"*{security}";
|
||||
public uint security_key => data.security_key;
|
||||
public string account_name => data.account_name;
|
||||
public uint account_key => data.key.account;
|
||||
// position limit
|
||||
public bool is_position_limit_enabled { get => _mutable_limits.is_position_limit_enabled; set => _set_limits(_mutable_limits.with(is_position_limit_enabled: value)); }
|
||||
public uint max_long_position { get => _mutable_limits.max_long_position; set => _set_limits(_mutable_limits.with(max_long_position: value)); }
|
||||
public uint max_short_position { get => _mutable_limits.max_short_position; set => _set_limits(_mutable_limits.with(max_short_position: value)); }
|
||||
public bool is_position_limit_enabled { get => _limits.is_position_limit_enabled; set => _modify(new RiskLimitsModification(is_position_limit_enabled: value)); }
|
||||
public uint max_long_position { get => _limits.max_long_position; set => _modify(new RiskLimitsModification(max_long_position: value)); }
|
||||
public uint max_short_position { get => _limits.max_short_position; set => _modify(new RiskLimitsModification(max_short_position: value)); }
|
||||
// clip limit
|
||||
public bool is_clip_limit_enabled { get => _mutable_limits.is_clip_limit_enabled; set => _set_limits(_mutable_limits.with(is_clip_limit_enabled: value)); }
|
||||
public uint clip_limit { get => _mutable_limits.clip_limit; set => _set_limits(_mutable_limits.with(clip_limit: value)); }
|
||||
public bool is_clip_limit_enabled { get => _limits.is_clip_limit_enabled; set => _modify(new RiskLimitsModification(is_clip_limit_enabled: value)); }
|
||||
public uint clip_limit { get => _limits.clip_limit; set => _modify(new RiskLimitsModification(clip_limit: value)); }
|
||||
// price limit
|
||||
public bool is_price_limit_enabled { get => _mutable_limits.is_price_limit_enabled; set => _set_limits(_mutable_limits.with(is_price_limit_enabled: value)); }
|
||||
public double max_price { get => _mutable_limits.max_price; set => _set_limits(_mutable_limits.with(max_price: value)); }
|
||||
public double min_price { get => _mutable_limits.min_price; set => _set_limits(_mutable_limits.with(min_price: value)); }
|
||||
public AccountSecurityKey row_id => new AccountSecurityKey(account_key, security_key);
|
||||
public AccountSecurityRiskLimits committed_data => _committed_data;
|
||||
public bool is_price_limit_enabled { get => _limits.is_price_limit_enabled; set => _modify(new RiskLimitsModification(is_price_limit_enabled: value)); }
|
||||
public double min_price { get => _limits.min_price; set => _modify(new RiskLimitsModification(min_price: value)); }
|
||||
public double max_price { get => _limits.max_price; set => _modify(new RiskLimitsModification(max_price: value)); }
|
||||
|
||||
RiskLimits _mutable_limits {
|
||||
get => _mutable_data.limits;
|
||||
set => _mutable_data = _mutable_data.with(limits: value);
|
||||
public bool is_persisted => committed_data.HasValue;
|
||||
public bool is_dirty => !committed_data.HasValue || !committed_data.Value.Equals(data);
|
||||
|
||||
public AccountSecurityRiskLimits data { get; private set; }
|
||||
public AccountSecurityRiskLimits? committed_data { get; private set; }
|
||||
RiskLimits _limits => data.limits;
|
||||
|
||||
public static RiskLimitsVM create_placeholder(AccountSecurityRiskLimits state) {
|
||||
var vm = new RiskLimitsVM(state.key);
|
||||
vm.load(state, false);
|
||||
return vm;
|
||||
}
|
||||
|
||||
public AccountSecurityRiskLimits create() => _mutable_data;
|
||||
public static RiskLimitsVM create_persisted(AccountSecurityRiskLimits state) {
|
||||
var vm = new RiskLimitsVM(state.key);
|
||||
vm.load(state, true);
|
||||
return vm;
|
||||
}
|
||||
|
||||
public void load_from(AccountSecurityRiskLimits value) {
|
||||
using (_result_changed.defer_execution())
|
||||
public void load(AccountSecurityRiskLimits new_state, bool is_committed) {
|
||||
using (detect_property_changes()) {
|
||||
_committed_data = value;
|
||||
_mutable_data = value;
|
||||
bool was_dirty = is_dirty;
|
||||
if (is_committed)
|
||||
committed_data = new_state;
|
||||
if (!data.Equals(new_state)) {
|
||||
value_changing?.Invoke((data, new_state));
|
||||
var orig_state = data;
|
||||
data = new_state;
|
||||
value_changed?.Invoke((orig_state, new_state));
|
||||
}
|
||||
if (is_dirty != was_dirty)
|
||||
is_dirty_changed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public void apply_modifications(RiskLimitsModification m) =>
|
||||
load_from(_committed_data.with(
|
||||
_committed_data.limits.with(m.is_position_limit_enabled,
|
||||
m.max_long_position,
|
||||
m.max_short_position,
|
||||
m.is_clip_limit_enabled,
|
||||
m.clip_limit,
|
||||
m.is_price_limit_enabled,
|
||||
m.min_price,
|
||||
m.max_short_position),
|
||||
new AccountTuple(_committed_data.account_key, _committed_data.account_name),
|
||||
m.security));
|
||||
public bool Equals(RiskLimitsVM other) =>
|
||||
other != null && id == other.id;
|
||||
|
||||
void _set_limits(RiskLimits new_limits, [CallerMemberName] string prop = "") =>
|
||||
_set_limits(new_limits, new[] { prop });
|
||||
public override bool Equals(object obj) =>
|
||||
Equals(obj as RiskLimitsVM);
|
||||
|
||||
void _set_limits(RiskLimits new_limits, params string[] invalidate_props) {
|
||||
if (!_mutable_limits.Equals(new_limits)) {
|
||||
_mutable_limits = new_limits;
|
||||
RaisePropertyChanged(invalidate_props);
|
||||
_result_changed.execute();
|
||||
public override int GetHashCode() =>
|
||||
id.GetHashCode();
|
||||
|
||||
void _modify(RiskLimitsModification mod) {
|
||||
var new_value = data.with(limits: mod.apply(data.limits));
|
||||
if (committed_data.HasValue) {
|
||||
// if the user just toggled one of the limits on/off, request an immediate update to persist the change
|
||||
// (the on/off toggles are the only props that can be edited directly in the grid,
|
||||
// the user might find it annoying if they have to click 'Save' just to turn the limits on/off.
|
||||
var clims = committed_data.Value.limits;
|
||||
load(new_value, false);
|
||||
var revert_mod = new RiskLimitsModification(is_position_limit_enabled: clims.is_position_limit_enabled, is_clip_limit_enabled: clims.is_clip_limit_enabled, is_price_limit_enabled: clims.is_price_limit_enabled);
|
||||
var reverted_lims = new_value = new_value.with(limits: revert_mod.apply(new_value.limits));
|
||||
if (reverted_lims.limits.Equals(clims)) {
|
||||
// since only the limit toggle props were reverted,
|
||||
// the above equality indicates that only the limit toggle props were modified.
|
||||
request_commit?.Invoke();
|
||||
}
|
||||
} else {
|
||||
load(new_value, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows.Controls;
|
||||
@@ -36,27 +37,32 @@ namespace bts.shell.risk_management {
|
||||
.wrap<AccountSecurityKey, AccountSecurityRiskLimits>(r => r.key);
|
||||
|
||||
static IComparer<RiskLimitsVM> _row_id_comparer =>
|
||||
_data_row_id_comparer.wrap<AccountSecurityRiskLimits, RiskLimitsVM>(r => r.committed_data);
|
||||
_data_row_id_comparer.wrap<AccountSecurityRiskLimits, RiskLimitsVM>(r => r.data);
|
||||
|
||||
readonly DeferrableActionWrapper _result_changed, _refresh_filter_changed, _selected_rows_changed;
|
||||
readonly DeferrableActionWrapper _refresh_filter_changed, _selected_rows_changed, _dirty_rows_changed;
|
||||
readonly ColumnSortManager _sort_manager;
|
||||
readonly ObservableCollection<RiskManagementColumnModel> _columns = new ObservableCollection<RiskManagementColumnModel>();
|
||||
readonly Dictionary<Columns, RiskManagementColumnModel> _column_map = new Dictionary<Columns, RiskManagementColumnModel>();
|
||||
readonly SelectorVM<AccountTuple?, uint> _accounts_vm = new SelectorVM<AccountTuple?, uint>(acc => acc?.id ?? 0) { comparer = Comparer<AccountTuple>.Default.to_nullable() };
|
||||
IReadOnlyDictionary<AccountSecurityKey, AccountSecurityRiskLimits> _cache = DictionaryHelper.empty<AccountSecurityKey, AccountSecurityRiskLimits>();
|
||||
ImmutableSortedSet<RiskLimitsVM> _selected_rows = ImmutableSortedSet.Create(_row_id_comparer);
|
||||
IList<AccountSecurityRiskLimits> _data_rows;
|
||||
ImmutableSortedSet<RiskLimitsVM> _selected_rows = ImmutableSortedSet.Create(_row_id_comparer);
|
||||
IComparer<AccountSecurityRiskLimits> _data_comparer = _data_row_id_comparer;
|
||||
IComparer<RiskLimitsVM> _row_comparer;
|
||||
IDisposable _import_limits_op;
|
||||
ImmutableDictionary<AccountSecurityKey, RiskLimitsVM> _dirty_rows = ImmutableDictionary<AccountSecurityKey, RiskLimitsVM>.Empty;
|
||||
ImmutableDictionary<AccountSecurityKey, RiskLimitsVM> _imported_row_map = ImmutableDictionary<AccountSecurityKey, RiskLimitsVM>.Empty;
|
||||
Dictionary<AccountSecurityKey, RiskLimitsVM> _row_cache = new Dictionary<AccountSecurityKey, RiskLimitsVM>();
|
||||
|
||||
public RiskManagementVM(IObservable<TableUpdate<AccountSecurityRiskLimits, AccountSecurityKey>> data_source, IObservable<IReadOnlyList<AccountTuple>> accounts_source) {
|
||||
_result_changed = new DeferrableActionWrapper(() => result_changed?.Invoke());
|
||||
_selected_rows_changed = new DeferrableActionWrapper(() => selected_rows_changed?.Invoke());
|
||||
_refresh_filter_changed = new DeferrableActionWrapper(() => _filter_changed?.Invoke(_mk_filter()));
|
||||
_dirty_rows_changed = new DeferrableActionWrapper(() => dirty_rows_changed?.Invoke(dirty_rows));
|
||||
_sort_manager = new ColumnSortManager(_columns.OfType<ISortableDIYGridColumn>(), null);
|
||||
_data_rows = rows.WrapSelector(r => r.committed_data, lim => new RiskLimitsVM(lim));
|
||||
_sort_manager.active_sorting_changed += () =>
|
||||
data_comparer = _sort_manager.BuildComparer(id => _find_column(id)?.row_comparer, _data_comparer);
|
||||
_data_rows = rows.WrapSelector(r => r.data, null);
|
||||
_accounts_vm.selected_item_changed += () => {
|
||||
RaisePropertyChanged(nameof(selected_account));
|
||||
_result_changed.execute();
|
||||
_refresh_filter_changed.execute();
|
||||
};
|
||||
column_map = FunctionalIndex.create<string, RiskManagementColumnModel>(_find_column);
|
||||
@@ -66,7 +72,6 @@ namespace bts.shell.risk_management {
|
||||
throw new InvalidOperationException();
|
||||
}, c => c.id.ToString(), cs => cs.id);
|
||||
}, null);
|
||||
_refresh_filter_changed = new DeferrableActionWrapper(() => _filter_changed?.Invoke(_mk_filter()));
|
||||
/////////////////
|
||||
// Columns
|
||||
/////////////////
|
||||
@@ -155,6 +160,7 @@ namespace bts.shell.risk_management {
|
||||
}).to_comparer();
|
||||
_column_map = _columns.ToDictionary(c => c.id);
|
||||
columns = ObservableAutoWrapper.SelectObservable(_columns, c => c);
|
||||
|
||||
var filter_source =
|
||||
Observable.FromEvent<Func<AccountSecurityRiskLimits, bool>>(cb => _filter_changed += cb, cb => _filter_changed -= cb)
|
||||
.StartWith(_mk_filter);
|
||||
@@ -209,13 +215,31 @@ namespace bts.shell.risk_management {
|
||||
return col;
|
||||
}
|
||||
|
||||
IDisposable subscribe_row_changes(RiskLimitsVM r) {
|
||||
r.result_changed += on_limits_changed;
|
||||
return Disposable.Create(() => r.result_changed -= on_limits_changed);
|
||||
void on_limits_changed() {
|
||||
var lim = r.create();
|
||||
if (_cache.TryGetValue(lim.key, out var curr_lim) && !lim.Equals(curr_lim))
|
||||
request_update_limit?.Invoke(lim);
|
||||
IDisposable subscribe_row_changes(RiskLimitsVM row) {
|
||||
row.value_changing += on_value_changing;
|
||||
row.value_changed += on_value_changed;
|
||||
row.request_commit += on_request_commit;
|
||||
check_dirty();
|
||||
return Disposable.Create(() => {
|
||||
row.value_changing -= on_value_changing;
|
||||
row.value_changed -= on_value_changed;
|
||||
row.request_commit -= on_request_commit;
|
||||
});
|
||||
|
||||
void on_value_changing((AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value) change) =>
|
||||
on_row_data_changed(new Change<AccountSecurityRiskLimits>(change.old_value, change.new_value), false);
|
||||
|
||||
void on_value_changed((AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value) change) =>
|
||||
check_dirty();
|
||||
|
||||
void on_request_commit() =>
|
||||
request_update_limit?.Invoke(row.data);
|
||||
|
||||
void check_dirty() {
|
||||
int dr_count = _dirty_rows.Count;
|
||||
_dirty_rows = row.is_dirty ? _dirty_rows.Add(row.id, row) : _dirty_rows.Remove(row.id);
|
||||
if (dr_count != _dirty_rows.Count)
|
||||
_dirty_rows_changed.execute();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,22 +247,74 @@ namespace bts.shell.risk_management {
|
||||
_accounts_vm.update_items(new_accounts.Cast<AccountTuple?>());
|
||||
|
||||
void on_data(TableUpdate<AccountSecurityRiskLimits, AccountSecurityKey> table) {
|
||||
_cache = table.state;
|
||||
var comp = data_comparer;
|
||||
_data_rows.RemoveSorted(table.removed.Concat(table.changes.Old()), comp);
|
||||
_data_rows.InsertSorted(table.added.Concat(table.changes.New()), comp);
|
||||
using (_dirty_rows_changed.defer_execution())
|
||||
using (_selected_rows_changed.defer_execution()) {
|
||||
foreach (var lim in table.removed) {
|
||||
if (_row_cache.TryGetValue(lim.key, out var row)) {
|
||||
_data_rows.RemoveSorted(row.data, data_comparer);
|
||||
if (row.committed_data.HasValue)
|
||||
_row_cache.Remove(lim.key);
|
||||
}
|
||||
}
|
||||
foreach (var ch in table.changes) {
|
||||
on_row_data_changed(ch, true);
|
||||
}
|
||||
foreach (var lim in table.added) {
|
||||
if (_row_cache.TryGetValue(lim.key, out var row)) {
|
||||
// if row is already here, it must be an import
|
||||
// overwrite the import with the persisted row (this probably won't happen in practice)
|
||||
rows.RemoveSorted(row, row_comparer);
|
||||
}
|
||||
var new_row = RiskLimitsVM.create_persisted(lim);
|
||||
_row_cache[lim.key] = new_row;
|
||||
rows.InsertSorted(new_row, row_comparer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void on_row_data_changed(Change<AccountSecurityRiskLimits> change, bool is_persisted) {
|
||||
Log.assert(_row_cache.TryGetValue(change.Old.key, out var row));
|
||||
int old_index = CollectionHelper.binary_search(rows, row, row_comparer);
|
||||
Log.assert(old_index >= 0);
|
||||
int new_index = CollectionHelper.binary_search(_data_rows, change.New, _data_comparer);
|
||||
// if the change came from the server (i.e., a persisted change that the row-vm doesn't already know about),
|
||||
// load the new data (current modifications will be overwritten).
|
||||
// Otherwise, the change is presumably the result of an uncommitted user-edit, which the row must already know about.
|
||||
if (is_persisted) {
|
||||
row.load(change.New, true);
|
||||
if (_dirty_rows.Remove(row.id, out _dirty_rows))
|
||||
_dirty_rows_changed.execute();
|
||||
}
|
||||
if (new_index < 0)
|
||||
new_index = ~new_index;
|
||||
if (Math.Abs(new_index - old_index) > 1) {
|
||||
if (new_index > old_index)
|
||||
new_index--;
|
||||
rows.Move(old_index, new_index);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public event Action result_changed, selected_rows_changed;
|
||||
public event Action selected_rows_changed;
|
||||
public event Action<AccountSecurityRiskLimits> request_update_limit;
|
||||
public event Action<ImmutableDictionary<AccountSecurityKey, RiskLimitsVM>> dirty_rows_changed;
|
||||
event Action<Func<AccountSecurityRiskLimits, bool>> _filter_changed;
|
||||
|
||||
public IReadOnlyIndex<string, RiskManagementColumnModel> column_map { get; }
|
||||
public bool has_unpersisted_limits => false;
|
||||
// this collection is needed to control the column order
|
||||
public IReadOnlyObservableCollection<IDIYGridColumn> columns { get; }
|
||||
public ObservableCollection<RiskLimitsVM> rows { get; } = new ObservableCollection<RiskLimitsVM>();
|
||||
public IReadOnlyList<RiskLimitsVM> selected_rows => _selected_rows;
|
||||
/// <summary>
|
||||
/// The selected rows are provided as an <see cref="ImmutableSortedSet{T}"/> so they can be observed/accessed on different threads.
|
||||
/// <see cref="RiskManagementVMExtensions.subscribe_selected_rows(RiskManagementVM)"/>.
|
||||
/// </summary>
|
||||
public ImmutableSortedSet<RiskLimitsVM> selected_rows => _selected_rows;
|
||||
/// <summary>
|
||||
/// The dirty rows are provided as an <see cref="ImmutableDictionary{TKey, TValue}"/> so they can be observed/accessed on different threads.
|
||||
/// <see cref="RiskManagementVMExtensions.subscribe_has_dirty_rows(RiskManagementVM)(RiskManagementVM)"/>.
|
||||
/// </summary>
|
||||
public ImmutableDictionary<AccountSecurityKey, RiskLimitsVM> dirty_rows => _dirty_rows;
|
||||
public IReadOnlyObservableCollection<AccountTuple?> accounts => _accounts_vm.items;
|
||||
public AccountTuple? selected_account {
|
||||
get => _accounts_vm.selected_item ?? default;
|
||||
@@ -251,13 +327,20 @@ namespace bts.shell.risk_management {
|
||||
if (value != null) {
|
||||
_data_comparer = value;
|
||||
_row_comparer = null;
|
||||
_data_rows.sync_with(_data_rows.Ordered(value).ToList());
|
||||
rows.sync_with(rows.Ordered(row_comparer));
|
||||
_selected_rows = _selected_rows.WithComparer(row_comparer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public IComparer<RiskLimitsVM> row_comparer =>
|
||||
_row_comparer ?? (_row_comparer = data_comparer?.wrap<AccountSecurityRiskLimits, RiskLimitsVM>(r => r.committed_data));
|
||||
_row_comparer ?? (_row_comparer = data_comparer?.wrap<AccountSecurityRiskLimits, RiskLimitsVM>(r => r.data));
|
||||
|
||||
public IReadOnlyDictionary<uint, SecurityMD> security_map { get; set; } = DictionaryHelper.empty<uint, SecurityMD>();
|
||||
|
||||
public IReadOnlyDictionary<uint, IEnumerable<AccountSecurityRiskLimits>> build_account_limits_map() =>
|
||||
_data_rows.GroupBy(dr => dr.account_key)
|
||||
.ToDictionary(g => g.Key, g => g.AsEnumerable());
|
||||
|
||||
public RiskManagementSettings create() {
|
||||
var grid = grid_settings_manager.create();
|
||||
@@ -268,9 +351,10 @@ namespace bts.shell.risk_management {
|
||||
public void load_from(RiskManagementSettings settings) {
|
||||
if (settings is null)
|
||||
throw new ArgumentNullException(nameof(settings));
|
||||
using (_result_changed.defer_execution()) {
|
||||
if (settings.grid != null)
|
||||
grid_settings_manager.load_from(settings.grid);
|
||||
if (settings.grid != null)
|
||||
grid_settings_manager.load_from(settings.grid);
|
||||
_sort_manager.SortingCriteria = settings.sorting_criteria;
|
||||
using (_refresh_filter_changed.defer_execution()) {
|
||||
foreach (var col in _columns)
|
||||
col.load_from(null, settings.filters);
|
||||
_accounts_vm.try_select(settings.account_id, true);
|
||||
@@ -280,8 +364,48 @@ namespace bts.shell.risk_management {
|
||||
public void load_from(GridSettings grid) {
|
||||
if (grid is null)
|
||||
throw new ArgumentNullException(nameof(grid));
|
||||
using (_result_changed.defer_execution())
|
||||
grid_settings_manager.load_from(grid);
|
||||
grid_settings_manager.load_from(grid);
|
||||
}
|
||||
|
||||
public void modify_rows(IEnumerable<AccountSecurityKey> targets, RiskLimitsModification mod) {
|
||||
foreach (var key in targets) {
|
||||
if (_row_cache.TryGetValue(key, out var row)) {
|
||||
var new_data = row.data.with(limits: mod.apply(row.data.limits));
|
||||
row.load(new_data, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void revert(IEnumerable<RiskLimitsVM> targets) {
|
||||
foreach (var row in targets) {
|
||||
if (row.committed_data.HasValue)
|
||||
row.load(row.committed_data.Value, true);
|
||||
}
|
||||
}
|
||||
|
||||
public void import_limits(string file_name) {
|
||||
Disposable.dispose(ref _import_limits_op);
|
||||
_import_limits_op = RiskLimitsImporter.import_limits(file_name,
|
||||
security_map,
|
||||
accounts.Where(a => a.HasValue)
|
||||
.ToDictionary(a => a.Value.id, a => a.Value.name),
|
||||
add_imported_rows);
|
||||
|
||||
void add_imported_rows(IEnumerable<ParsedRiskLimits> imported_rows) {
|
||||
foreach (var ir in imported_rows) {
|
||||
var res = ir.result;
|
||||
if (!res.security.HasValue && security_map.TryGetValue(res.security_key, out var sec_md))
|
||||
res = res.with(security: sec_md.security);
|
||||
if (string.IsNullOrEmpty(res.account_name) && accounts.TryGetFirst(a => a?.id == res.account_key, out var acc))
|
||||
res = res.with(account: acc);
|
||||
var new_row = RiskLimitsVM.create_placeholder(res);
|
||||
if (_row_cache.TryGetValue(res.key, out var row)) {
|
||||
rows.RemoveSorted(row, row_comparer);
|
||||
}
|
||||
_row_cache[res.key] = new_row;
|
||||
rows.InsertSorted(new_row, row_comparer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void IHandleRowSelection.row_selection_changed(SelectionChangedEventArgs e) {
|
||||
@@ -293,7 +417,7 @@ namespace bts.shell.risk_management {
|
||||
|
||||
void IHandleGridSorting.on_sorting(object sender, DIYGridSortingEventArgs e) {
|
||||
_sort_manager.OnColumnClick(e.Column, KeyboardExtensions.IsShiftDown());
|
||||
data_comparer = _sort_manager.BuildComparer(id => _find_column(id)?.row_comparer, _data_comparer);
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
RiskManagementColumnModel _find_column(string key_str) =>
|
||||
@@ -310,4 +434,33 @@ namespace bts.shell.risk_management {
|
||||
return lim => lim.account_key == acc_id && (col_filter_pred is null || col_filter_pred(lim));
|
||||
}
|
||||
}
|
||||
|
||||
static class RiskManagementVMExtensions {
|
||||
public static IObservable<ImmutableSortedSet<RiskLimitsVM>> subscribe_selected_rows(this RiskManagementVM vm) =>
|
||||
vm is null ?
|
||||
throw new ArgumentNullException(nameof(vm)) :
|
||||
Observable.Create<ImmutableSortedSet<RiskLimitsVM>>(o => {
|
||||
o.OnNext(vm.selected_rows);
|
||||
vm.selected_rows_changed += on_selected_rows_changed;
|
||||
return Disposable.Create(() => vm.selected_rows_changed -= on_selected_rows_changed);
|
||||
void on_selected_rows_changed() =>
|
||||
o.OnNext(vm.selected_rows);
|
||||
})
|
||||
.SubscribeOnDispatcher();
|
||||
|
||||
public static IObservable<bool> subscribe_has_dirty_rows(this RiskManagementVM vm) =>
|
||||
vm is null ?
|
||||
throw new ArgumentNullException(nameof(vm)) :
|
||||
Observable.Create<bool>(o => {
|
||||
bool last_fired = vm.dirty_rows.Count > 0;
|
||||
o.OnNext(last_fired);
|
||||
vm.dirty_rows_changed += on_dirty_rows_changed;
|
||||
return Disposable.Create(() => vm.dirty_rows_changed -= on_dirty_rows_changed);
|
||||
void on_dirty_rows_changed(ImmutableDictionary<AccountSecurityKey, RiskLimitsVM> drs) {
|
||||
if (last_fired != drs.Count > 0)
|
||||
o.OnNext(last_fired = !last_fired);
|
||||
}
|
||||
})
|
||||
.SubscribeOnDispatcher();
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<Window
|
||||
x:Class="bts.shell.risk_management.RiskLimitsImportConflictsDialog"
|
||||
x:ClassModifier="internal"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:risk="clr-namespace:bts.shell.risk_management"
|
||||
xmlns:u="clr-namespace:mbts.ui"
|
||||
xmlns:c="clr-namespace:mbts.ui.controls"
|
||||
u:WindowStyle.AllowResize="True"
|
||||
u:WindowStyle.SizeToContent="WidthAndHeight"
|
||||
u:WindowStyle.TitleContent="Import Limits Conflicts"
|
||||
Style="{StaticResource BTSDialogTitleTemplate}"
|
||||
>
|
||||
<u:WindowStyle.TitleContentTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
|
||||
<Image Height="12" Margin="5,2" Source="{x:Static u:Icons.Import}"/>
|
||||
<TextBlock Margin="4,0,0,0" Text="{Binding}"/>
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</u:WindowStyle.TitleContentTemplate>
|
||||
<Window.Content>
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<risk:RiskLimitsImportConflictsView Margin="12,10,12,8"/>
|
||||
<c:DialogSkirt Grid.Row="1">
|
||||
<c:DialogSkirt.RightItems>
|
||||
<x:Array Type="{x:Type Button}">
|
||||
<Button Command="{Binding ok_cmd}">Continue</Button>
|
||||
<Button Command="{Binding cancel_cmd}" IsCancel="True">Cancel</Button>
|
||||
</x:Array>
|
||||
</c:DialogSkirt.RightItems>
|
||||
</c:DialogSkirt>
|
||||
</Grid>
|
||||
</Window.Content>
|
||||
</Window>
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
/// <summary>
|
||||
/// Interaction logic for RiskLimitsImportConflictsDialog.xaml
|
||||
/// </summary>
|
||||
partial class RiskLimitsImportConflictsDialog : Window {
|
||||
public RiskLimitsImportConflictsDialog() =>
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
<UserControl
|
||||
x:Class="bts.shell.risk_management.RiskLimitsImportConflictsView"
|
||||
x:ClassModifier="internal"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:risk="clr-namespace:bts.shell.risk_management"
|
||||
xmlns:u="clr-namespace:mbts.ui"
|
||||
xmlns:c="clr-namespace:mbts.ui.controls"
|
||||
xmlns:cv="clr-namespace:mbts.ui.converters"
|
||||
MinWidth="400"
|
||||
>
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="VerticallyCenteredText" TargetType="TextBlock">
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
</Style>
|
||||
<DataTemplate x:Key="UIntTemplate">
|
||||
<c:TickUpDownUInt Value="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
|
||||
</DataTemplate>
|
||||
<DataTemplate x:Key="DoubleTemplate">
|
||||
<c:TickUpDownDouble Value="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
|
||||
</DataTemplate>
|
||||
<DataTemplate x:Key="BooleanTemplate">
|
||||
<CheckBox IsChecked="{Binding value}"/>
|
||||
</DataTemplate>
|
||||
<DataTemplate x:Key="PriceReadTemplate">
|
||||
<TextBlock Text="{Binding value, Converter={StaticResource DoubleTextConverter}}" VerticalAlignment="Center"/>
|
||||
</DataTemplate>
|
||||
<!--Value Cell Template Selector-->
|
||||
<u:KeyedTemplateSelector x:Key="ValueCellTemplateSelector">
|
||||
<u:KeyedTemplateSelector.Default>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding value}" VerticalAlignment="Center"/>
|
||||
</DataTemplate>
|
||||
</u:KeyedTemplateSelector.Default>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MinPrice, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource PriceReadTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MaxPrice, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource PriceReadTemplate}"/>
|
||||
</u:KeyedTemplateSelector>
|
||||
<!--Value Cell Editing Template Selector-->
|
||||
<u:KeyedTemplateSelector x:Key="ValueCellEditingTemplateSelector">
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static Security, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}">
|
||||
<DataTemplate>
|
||||
<c:ContractPickerPopup
|
||||
HorizontalAlignment="Stretch"
|
||||
VerticalAlignment="Stretch"
|
||||
CloseOnCancel="True"
|
||||
CloseOnOK="True"
|
||||
Header="{Binding value}"
|
||||
IsEditMode="False"
|
||||
IsLazy="True"
|
||||
SecurityMap="{Binding DataContext.security_map, RelativeSource={RelativeSource AncestorType=DataGrid}, Mode=OneWay}"
|
||||
SelectedSecurity="{Binding value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
|
||||
ShowDialogSkirt="True"
|
||||
/>
|
||||
</DataTemplate>
|
||||
</u:TemplateSelectorKeyValue>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static Account, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}">
|
||||
<DataTemplate>
|
||||
<ComboBox ItemsSource="{Binding DataContext.accounts, RelativeSource={RelativeSource AncestorType=DataGrid}}" SelectedItem="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
|
||||
</DataTemplate>
|
||||
</u:TemplateSelectorKeyValue>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MaxNetLongPosition, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource UIntTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MaxNetShortPosition, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource UIntTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static IsPositionLimitEnabled, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource BooleanTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static ClipLimit, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource UIntTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static IsClipLimitEnabled, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource BooleanTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MinPrice, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource DoubleTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MaxPrice, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource DoubleTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static IsPriceLimitEnabled, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource BooleanTemplate}"/>
|
||||
</u:KeyedTemplateSelector>
|
||||
</UserControl.Resources>
|
||||
<!--Content-->
|
||||
<Grid x:Name="content_root">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Image VerticalAlignment="Center" Margin="0,0,8,0">
|
||||
<Image.Source>
|
||||
<Binding Source="{x:Static MessageBoxImage.Exclamation}">
|
||||
<Binding.Converter>
|
||||
<cv:SystemIconConverter/>
|
||||
</Binding.Converter>
|
||||
</Binding>
|
||||
</Image.Source>
|
||||
</Image>
|
||||
<Canvas x:Name="text_canvas" Grid.Column="1" HorizontalAlignment="Stretch"/>
|
||||
<TextBlock Grid.Column="1" TextWrapping="Wrap" Width="{Binding ActualWidth, ElementName=text_canvas}">
|
||||
<Run Text="{Binding num_successfully_parsed_limits, Mode=OneWay}"/>
|
||||
<Run Text="/"/>
|
||||
<Run Text="{Binding num_limits, Mode=OneWay}"/>
|
||||
<Run Text=" limit items have been successfully converted."/>
|
||||
<Run Text="Resolve conflicts below by selecting a value to assign each affected limit item,"/>
|
||||
<Run Text="or modify individual limit items in the main window."/>
|
||||
<LineBreak/>
|
||||
<LineBreak/>
|
||||
<Run Text="Click 'Continue' to proceed to the main window."/>
|
||||
</TextBlock>
|
||||
<DataGrid
|
||||
x:Name="data_grid"
|
||||
u:DataGridBehavior.SingleClickEdit="True"
|
||||
Grid.Row="1"
|
||||
Grid.ColumnSpan="2"
|
||||
AutoGenerateColumns="False"
|
||||
CanUserAddRows="False"
|
||||
CanUserDeleteRows="False"
|
||||
CanUserReorderColumns="False"
|
||||
CanUserSortColumns="True"
|
||||
HeadersVisibility="All"
|
||||
ItemsSource="{Binding rows_view}"
|
||||
Margin="0,8,0,0"
|
||||
MinRowHeight="17"
|
||||
RowHeaderWidth="22"
|
||||
>
|
||||
<DataGrid.CellStyle>
|
||||
<Style TargetType="DataGridCell" BasedOn="{StaticResource DataGridCellBaseStyle}">
|
||||
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
|
||||
</Style>
|
||||
</DataGrid.CellStyle>
|
||||
<DataGrid.RowStyle>
|
||||
<Style TargetType="DataGridRow">
|
||||
<Setter Property="IsSelected" Value="{Binding is_selected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource Self}}" Value="True">
|
||||
<Setter Property="Background" Value="{StaticResource SelectedRowBackground}"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</DataGrid.RowStyle>
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Component" Binding="{Binding component}" ElementStyle="{StaticResource VerticallyCenteredText}" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="Text" Binding="{Binding text}" ElementStyle="{StaticResource VerticallyCenteredText}" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="Affected Limit Items" Binding="{Binding affected_limits.Count}" ElementStyle="{StaticResource VerticallyCenteredText}" IsReadOnly="True"/>
|
||||
<DataGridTemplateColumn Header="Value" CellTemplateSelector="{StaticResource ValueCellTemplateSelector}" CellEditingTemplateSelector="{StaticResource ValueCellEditingTemplateSelector}"/>
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
/// <summary>
|
||||
/// Interaction logic for RiskLimitsImportConflictsView.xaml
|
||||
/// </summary>
|
||||
partial class RiskLimitsImportConflictsView : UserControl {
|
||||
public RiskLimitsImportConflictsView() =>
|
||||
InitializeComponent();
|
||||
|
||||
public enum RiskLimitsComponent {
|
||||
Security,
|
||||
Account,
|
||||
MaxNetLongPosition,
|
||||
MaxNetShortPosition,
|
||||
IsPositionLimitEnabled,
|
||||
ClipLimit,
|
||||
IsClipLimitEnabled,
|
||||
MinPrice,
|
||||
MaxPrice,
|
||||
IsPriceLimitEnabled
|
||||
}
|
||||
|
||||
public static class RiskLimitsComponentNames {
|
||||
public static readonly string
|
||||
Security = RiskLimitsComponent.Security.ToString(),
|
||||
Account = RiskLimitsComponent.Account.ToString(),
|
||||
MaxNetLongPosition = RiskLimitsComponent.MaxNetLongPosition.ToString(),
|
||||
MaxNetShortPosition = RiskLimitsComponent.MaxNetShortPosition.ToString(),
|
||||
IsPositionLimitEnabled = RiskLimitsComponent.IsPositionLimitEnabled.ToString(),
|
||||
ClipLimit = RiskLimitsComponent.ClipLimit.ToString(),
|
||||
IsClipLimitEnabled = RiskLimitsComponent.IsClipLimitEnabled.ToString(),
|
||||
MinPrice = RiskLimitsComponent.MinPrice.ToString(),
|
||||
MaxPrice = RiskLimitsComponent.MaxPrice.ToString(),
|
||||
IsPriceLimitEnabled = RiskLimitsComponent.IsPriceLimitEnabled.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,14 @@
|
||||
Background="{StaticResource CommonBackground}"
|
||||
>
|
||||
<UserControl.Resources>
|
||||
<cv:BooleanToObjectConverter x:Key="IsDirtyOpacityConverter">
|
||||
<cv:BooleanToObjectConverter.ValueForFalse>
|
||||
<sys:Double>1.0</sys:Double>
|
||||
</cv:BooleanToObjectConverter.ValueForFalse>
|
||||
<cv:BooleanToObjectConverter.ValueForTrue>
|
||||
<sys:Double>0.6</sys:Double>
|
||||
</cv:BooleanToObjectConverter.ValueForTrue>
|
||||
</cv:BooleanToObjectConverter>
|
||||
<Style x:Key="TextCell" TargetType="c:TextCell">
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
<Setter Property="Padding" Value="2,0"/>
|
||||
@@ -27,6 +35,7 @@
|
||||
<Setter Property="FontFamily" Value="{Binding Path='(c:DIYGrid.Column).font_family', RelativeSource={RelativeSource Self}}"/>
|
||||
<Setter Property="FontWeight" Value="{Binding Path='(c:DIYGrid.Column).font_weight', RelativeSource={RelativeSource Self}}"/>
|
||||
<Setter Property="FontSize" Value="{Binding Path='(c:DIYGrid.Column).font_size', RelativeSource={RelativeSource Self}}"/>
|
||||
<Setter Property="Opacity" Value="{Binding is_dirty, Converter={StaticResource IsDirtyOpacityConverter}}"/>
|
||||
</Style>
|
||||
<Style x:Key="CellBorder" TargetType="Border">
|
||||
<Setter Property="HorizontalAlignment" Value="Stretch"/>
|
||||
@@ -84,7 +93,7 @@
|
||||
<c:TextCell
|
||||
c:DIYGrid.ColumnKey="Security"
|
||||
c:DIYGrid.Column="{Binding Path='DataContext.column_map[Security]', RelativeSource={RelativeSource AncestorType=c:DIYGrid}}"
|
||||
Text="{Binding security}"
|
||||
Text="{Binding security_text}"
|
||||
Style="{StaticResource TextCell}"
|
||||
/>
|
||||
<c:TextCell
|
||||
@@ -156,6 +165,13 @@
|
||||
Style="{StaticResource LimitToggleSwitch}"
|
||||
/>
|
||||
</Border>
|
||||
<!--<Border
|
||||
c:DIYGrid.ColumnKey="IsDirty"
|
||||
c:DIYGrid.Column="{Binding Path='DataContext.column_map[IsDirty]', RelativeSource={RelativeSource AncestorType=c:DIYGrid}}"
|
||||
Style="{StaticResource CellBorder}"
|
||||
>
|
||||
<Image Source="{x:Static u:Icons.CheckMark}" Visibility="{Binding is_persisted, Converter={StaticResource BooleanToVisibilityConverter}}"/>
|
||||
</Border>-->
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</c:DIYGrid.RowTemplate>
|
||||
|
||||
@@ -242,7 +242,8 @@ namespace mbts.ui.utility {
|
||||
}
|
||||
if (_map.Count != this.items.Count)
|
||||
throw new InvalidOperationException("Map and items are out of sync (different item counts).");
|
||||
try_select(target_key, _is_pending_selection || _items.Count == 0);
|
||||
if (try_select(target_key, _is_pending_selection || _items.Count == 0) && _is_pending_selection)
|
||||
_is_pending_selection = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -265,6 +265,10 @@ namespace mbts.ui.controls {
|
||||
get => GetValue(SortDirectionProperty) as ListSortDirection?;
|
||||
set => SetValue(SortDirectionProperty, value);
|
||||
}
|
||||
ListSortDirection? ISortableDIYGridColumn.SortDirection {
|
||||
get => SortDirection;
|
||||
set => SetCurrentValue(SortDirectionProperty, value);
|
||||
}
|
||||
|
||||
#region IsVisible
|
||||
public static readonly DependencyProperty IsVisibleProperty =
|
||||
@@ -323,6 +327,7 @@ namespace mbts.ui.controls {
|
||||
model.width = Width;
|
||||
width_changed += on_width_changed;
|
||||
model.width_changed += on_model_width_changed;
|
||||
model.result_changed += on_result_changed;
|
||||
_model_hooks = Disposable.Create(() => {
|
||||
width_changed -= on_width_changed;
|
||||
model.width_changed -= on_model_width_changed;
|
||||
@@ -336,6 +341,8 @@ namespace mbts.ui.controls {
|
||||
model.width = value;
|
||||
model.width_changed += on_model_width_changed;
|
||||
}
|
||||
void on_result_changed() =>
|
||||
load_from(model.create());
|
||||
}
|
||||
|
||||
/// important: don't access any dependency props in here.
|
||||
@@ -370,7 +377,6 @@ namespace mbts.ui.controls {
|
||||
original_width = settings.width;
|
||||
SetCurrentValue(WidthProperty, original_width);
|
||||
}
|
||||
//
|
||||
}
|
||||
|
||||
// 'fallback' font-params (aka 'grid-level' font-params)
|
||||
|
||||
@@ -6,7 +6,6 @@ using mbts.ui.shell;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
@@ -22,19 +21,20 @@ namespace mbts.ui.controls {
|
||||
}
|
||||
}
|
||||
|
||||
interface IDIYGridColumnModel : DIYGrid.IFilterableColumn {
|
||||
interface IDIYGridColumnModel : DIYGrid.IFilterableColumn, IValueFactoryVM<GridColumnSettings> {
|
||||
string id { get; }
|
||||
string column_template { get; }
|
||||
IComparer row_comparer { get; }
|
||||
double width { get; set; }
|
||||
event Action<double> width_changed;
|
||||
event Action result_changed;
|
||||
}
|
||||
|
||||
interface IDIYGridColumnFactory {
|
||||
DIYGrid.ColumnBase create_view();
|
||||
}
|
||||
|
||||
class DIYGridColumnModel<TKey> : ViewModelBase, IDIYGridColumnModel, ISortableDIYGridColumn<TKey>, ISortableDIYGridColumn, IValueFactory<GridColumnSettings> where TKey : struct {
|
||||
class DIYGridColumnModel<TKey> : ViewModelBase, IDIYGridColumnModel, ISortableDIYGridColumn<TKey>, ISortableDIYGridColumn, IValueFactoryVM<GridColumnSettings> where TKey : struct {
|
||||
readonly DeferrableActionWrapper _result_changed;
|
||||
|
||||
FontWeight _fallback_font_weight;
|
||||
@@ -96,15 +96,6 @@ namespace mbts.ui.controls {
|
||||
width_changed?.Invoke(value);
|
||||
}
|
||||
}
|
||||
double _actual_width;
|
||||
public double actual_width {
|
||||
get => _actual_width;
|
||||
set {
|
||||
_actual_width = value;
|
||||
width = value;
|
||||
RaisePropertyChanged(nameof(actual_width));
|
||||
}
|
||||
}
|
||||
public bool is_visible { get => _is_visible; set => _set(ref _is_visible, value); }
|
||||
public ListSortDirection? sort_direction { get => _sort_direction; set => Set(ref _sort_direction, value); }
|
||||
public Color? background_color_override { get => _background_color_override; set => _set(ref _background_color_override, value); }
|
||||
@@ -144,6 +135,31 @@ namespace mbts.ui.controls {
|
||||
}
|
||||
}
|
||||
|
||||
public void load_from(GridColumnSettings value) {
|
||||
if (!value.strong_id<TKey>().Equals(id))
|
||||
throw new ArgumentException("Column id in settings object does not match the column model's id.", nameof(value));
|
||||
using (_result_changed.defer_execution())
|
||||
using (_detect_result_changed())
|
||||
using (detect_property_changes(nameof(font_color), nameof(font_weight), nameof(background_color))) {
|
||||
display_name = value.display_name;
|
||||
is_visible = value.is_visible;
|
||||
font_color_override = value.font_color_override;
|
||||
font_weight_override = value.font_weight_override;
|
||||
background_color_override = value.background_color_override;
|
||||
width = value.width;
|
||||
horizontal_alignment = value.horizontal_alignment;
|
||||
}
|
||||
}
|
||||
|
||||
IDisposable _detect_result_changed() {
|
||||
var orig_state = create();
|
||||
return Disposable.Create(() => {
|
||||
var curr_state = create();
|
||||
if (!orig_state.Equals(curr_state))
|
||||
result_changed?.Invoke();
|
||||
});
|
||||
}
|
||||
|
||||
bool _set<T>(ref T backing, T new_value, [CallerMemberName]string prop = null) =>
|
||||
_set(ref backing, new_value, EqualityComparer<T>.Default, prop);
|
||||
|
||||
@@ -161,20 +177,6 @@ namespace mbts.ui.controls {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void load_from(GridColumnSettings value) {
|
||||
if (!value.strong_id<TKey>().Equals(id))
|
||||
throw new ArgumentException("Column id in settings object does not match the column model's id.", nameof(value));
|
||||
using (_result_changed.defer_execution()) {
|
||||
display_name = value.display_name;
|
||||
is_visible = value.is_visible;
|
||||
font_color_override = value.font_color_override;
|
||||
font_weight_override = value.font_weight_override;
|
||||
background_color_override = value.background_color_override;
|
||||
width = value.width;
|
||||
horizontal_alignment = value.horizontal_alignment;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DIYGridColumnModel<TKey, TRow, TGridFilter> : DIYGridColumnModel<TKey> where TKey : struct {
|
||||
|
||||
@@ -905,7 +905,7 @@ namespace mbts.ui.controls {
|
||||
if (cb is null) {
|
||||
cb = new DIYGridColumn { id = cm.id };
|
||||
BindingOperations.SetBinding(cb, ColumnBase.HeaderProperty, new Binding(nameof(DIYGridColumnModel<int>.header)) { Source = cm });
|
||||
BindingOperations.SetBinding(cb, ColumnBase.SortDirectionProperty, new Binding(nameof(DIYGridColumnModel<int>.sort_direction)) { Source = cm });
|
||||
BindingOperations.SetBinding(cb, ColumnBase.SortDirectionProperty, new Binding(nameof(DIYGridColumnModel<int>.sort_direction)) { Source = cm, Mode = BindingMode.TwoWay });
|
||||
cb.set_model(cm);
|
||||
BindingOperations.SetBinding(cb, ColumnBase.IsVisibleProperty, new Binding(nameof(DIYGridColumnModel<int>.is_visible)) { Source = cm });
|
||||
if (cm is IFilterableColumn fc) {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace bts.collections {
|
||||
static class ImmutableDictionaryExtensions {
|
||||
/// <summary>
|
||||
/// Adds the specified key/value pair if the dictionary does not already contain the key, otherwise replaces the value for that key.
|
||||
/// </summary>
|
||||
/// <returns><see cref="true"/> if a new key was added; otherwise <see cref="false"/>.</returns>
|
||||
public static bool AddOrSet<TKey, TValue>(this ImmutableDictionary<TKey, TValue> dictionary, TKey key, TValue value, out ImmutableDictionary<TKey, TValue> result) {
|
||||
int orig_count = dictionary.Count;
|
||||
result = dictionary.SetItem(key, value);
|
||||
return result.Count != orig_count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the entry with specified key.
|
||||
/// </summary>
|
||||
/// <returns><see cref="true"/> if the entry was removed; otherwise <see cref="false"/>.</returns>
|
||||
public static bool Remove<TKey, TValue>(this ImmutableDictionary<TKey, TValue> dictionary, TKey key, out ImmutableDictionary<TKey, TValue> result) {
|
||||
result = dictionary.Remove(key);
|
||||
return result.Count != dictionary.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,5 +25,21 @@ namespace bts.collections {
|
||||
bd.Remove(v);
|
||||
return bd.ToImmutable();
|
||||
}
|
||||
|
||||
public static bool Add<T>(this ImmutableHashSet<T> source, T value, out ImmutableHashSet<T> result) {
|
||||
int orig_count = source.Count;
|
||||
result = source.Add(value);
|
||||
return result.Count != orig_count;
|
||||
}
|
||||
|
||||
public static ImmutableHashSet<T> AddRange<T>(this ImmutableHashSet<T> source, IEnumerable<T> value) {
|
||||
if (source is null)
|
||||
throw new ArgumentNullException(nameof(source));
|
||||
if (value is null)
|
||||
throw new ArgumentNullException(nameof(value));
|
||||
var bd = source.ToBuilder();
|
||||
bd.AddRange(value);
|
||||
return bd.ToImmutable();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,9 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace System.Reactive.Linq {
|
||||
public static class ObservableExtensions {
|
||||
public static IObservable<bool> And(this IObservable<bool> source1, IObservable<bool> source2) =>
|
||||
source1.CombineLatest(source2).Select(tup => tup.Item1 && tup.Item2);
|
||||
|
||||
/// <summary>
|
||||
/// <para>Creates an "Observable Heartbeat" that will publish true/false to indicate whether or not the heartbeat is detected, it will only send updates when the 'heartbeat status' has changed.</para>
|
||||
/// <para>Whenever the source produces an update, the heartbeat evaluates to true and the heartbeat duration clock is reset.</para>
|
||||
|
||||
Reference in new issue
Block a user