199 lines
9.5 KiB
C#
199 lines
9.5 KiB
C#
using bts;
|
|
using bts.api;
|
|
using bts.api.core;
|
|
using bts.api.synthetic;
|
|
using bts.collections;
|
|
using bts.spark;
|
|
|
|
using mbts.utils;
|
|
|
|
using Spark.Core;
|
|
using Spark.Core.Reactive;
|
|
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Composition;
|
|
using System.Linq;
|
|
using System.Reactive.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace mbts.spark {
|
|
[Export]
|
|
class SpreaderModel {
|
|
readonly IBus _bus;
|
|
readonly SyntheticSecurityService _service;
|
|
readonly ErrorReporter _error;
|
|
readonly uint _user_id;
|
|
|
|
[ImportingConstructor]
|
|
public SpreaderModel(IBus bus, SyntheticSecurityService service, AdminModel admin_model, ErrorReporter error, Lazy<UserTuple> user) {
|
|
_bus = bus;
|
|
_service = service;
|
|
_error = error;
|
|
_user_id = user.Value.id;
|
|
// synthetic tuples
|
|
var strategy_source = _bus.subscribe(SparkTags.SyntheticstrategiesTag)
|
|
.Select(map => MappedDictionary.create<uint, ExecutionStrategyImmutable, (uint security_id, ExecutionStrategyImmutable strategy)>(map, (k, v) => (k, v)))
|
|
.Table(tup => tup.security_id);
|
|
|
|
var synthetic_source = _bus.subscribe(SparkTags.SecuritiesTag)
|
|
.Select(map => new FilteredDictionary<uint, SecurityMD>(map, smd => smd.security.ContractCase == Security.ContractOneofCase.Synthetic))
|
|
.Table(smd => smd.security.Id);
|
|
|
|
var synthetic_user_join = synthetic_source.LeftJoin(
|
|
admin_model.all_user_tuples,
|
|
SecurityMD.key_fn,
|
|
UserTuple.key_fn,
|
|
smd => smd.security.Synthetic.UserId,
|
|
(smd, sid, ut, uid) => new SyntheticSecurityTuple(smd.security, ut.name, null),
|
|
(smd, sid, uid) => new SyntheticSecurityTuple(smd.security, null, null),
|
|
SyntheticSecurityTuple.key_fn);
|
|
|
|
synthetic_tuples = synthetic_user_join.LeftJoin(
|
|
strategy_source,
|
|
SyntheticSecurityTuple.key_fn,
|
|
tup => tup.security_id,
|
|
(synth_tup, id, strat_tup) => new SyntheticSecurityTuple(synth_tup.security, synth_tup.user_name, strat_tup.strategy),
|
|
(synth_tup, id) => synth_tup,
|
|
SyntheticSecurityTuple.key_fn);
|
|
}
|
|
|
|
public IObservable<IReadOnlyDictionary<uint, ExecutionStrategyImmutable>> strategy => _bus.subscribe(SparkTags.SyntheticstrategiesTag);
|
|
public IObservable<IReadOnlyDictionary<uint, (ExecutionStrategyImmutable? strategy, SecurityMD md)>> strategy_tuple =>
|
|
_bus.subscribe(SparkTags.SecuritiesTag)
|
|
.Select(md_map => md_map.Values.Where(smd => smd.security.ContractCase == Security.ContractOneofCase.Synthetic).ToList())
|
|
// CombineLatest waits for both sources to fire once, sometimes strategy does not fire, so StartWith circumvents this issue
|
|
.CombineLatest(_bus.subscribe(SparkTags.SyntheticstrategiesTag).StartWith(new Dictionary<uint, ExecutionStrategyImmutable>()),
|
|
(synthetics, strategies) => synthetics
|
|
.ToDictionary(smd => smd.security.Id)
|
|
.LeftJoin(strategies, (security, strategy) => (new ExecutionStrategyImmutable?(strategy), security), security => (new ExecutionStrategyImmutable?(), security))
|
|
);
|
|
|
|
public IObservable<TableUpdate<SyntheticSecurityTuple, uint>> synthetic_tuples { get; }
|
|
|
|
public IObservable<ExecutionStrategyImmutable> security_strategy(uint security_key) =>
|
|
strategy.TrySelect(s => {
|
|
bool success = s.TryGetValue(security_key, out ExecutionStrategyImmutable result);
|
|
return (result, success);
|
|
});
|
|
|
|
public Task<ExecutionStrategyImmutable?> lookup_strategy_async(SecurityImmutable security) =>
|
|
lookup_strategy_async(security.Id);
|
|
|
|
public Task<ExecutionStrategyImmutable?> lookup_strategy_async(uint id) =>
|
|
_error.safe_execute(
|
|
() => _service.query_security_metadata_async(new MetadataQuery { SecurityKey = { id } }),
|
|
mdc => mdc.Data.Count == 1 && mdc.Data[0].SecurityKey == id,
|
|
mdc => $"did not find strategy for security id '{id}.'",
|
|
(mdc, success) => success ? mdc.Data[0].Strategy : (ExecutionStrategyImmutable?)null,
|
|
"lookup strategy");
|
|
|
|
public Task<(uint? key, string error_msg)[]> create_synthetics(IEnumerable<(SecurityImmutable security, ExecutionStrategyImmutable strategy)> synthetics) {
|
|
var tasks = synthetics.Select(tup => {
|
|
var (sec, strat) = tup;
|
|
if (sec.ContractCase != Security.ContractOneofCase.Synthetic)
|
|
return Task.FromException<(Result<CreateResult>, Result<UpdateResult>?)>(ExceptionBuilder.Argument.unexpected_case(sec.ContractCase, nameof(sec)));
|
|
if (sec.Synthetic.UserId != _user_id) {
|
|
var msec = sec.CloneToMutable();
|
|
msec.Synthetic.UserId = _user_id;
|
|
sec = new SecurityImmutable(msec);
|
|
}
|
|
return impl();
|
|
async Task<(Result<CreateResult> sec, Result<UpdateResult>? strat)> impl() {
|
|
var result = await _service.create_synthetic_async(sec);
|
|
Result<UpdateResult>? strategy;
|
|
if (result.success && result.value.Error == CreateResult.Types.Error.Ok) {
|
|
strategy = await _service.update_security_metadata_async(new Metadata {
|
|
SecurityKey = result.value.Key,
|
|
Strategy = tup.strategy.CloneToMutable()
|
|
});
|
|
} else {
|
|
strategy = null;
|
|
}
|
|
return (result, strategy);
|
|
}
|
|
});
|
|
return _error.safe_execute_batch(tasks,
|
|
tup => {
|
|
var (sec, strat) = tup;
|
|
// security
|
|
string sec_error_msg = null;
|
|
uint? key = null;
|
|
if (!sec.success) {
|
|
sec_error_msg = sec.error_message;
|
|
} else if (sec.value.Error != CreateResult.Types.Error.Ok) {
|
|
sec_error_msg = sec.value.Error.ToString();
|
|
} else {
|
|
key = sec.value.Key;
|
|
}
|
|
// strategy
|
|
string strat_error_msg = null;
|
|
if (!strat.HasValue) {
|
|
strat_error_msg = "Strategy was not successfully saved";
|
|
} else if (!strat.Value.success) {
|
|
strat_error_msg = strat.Value.error_message;
|
|
} else if (strat.Value.value.Error != UpdateResult.Types.Error.Ok) {
|
|
strat_error_msg = strat.Value.value.Error.ToString();
|
|
}
|
|
// merge error msgs (result should be null if both errors are empty)
|
|
var error_msg = string.Join(Environment.NewLine, new[] { sec_error_msg, strat_error_msg }.ExceptNull());
|
|
return (key, error_msg.null_if_empty());
|
|
},
|
|
"Synthetic",
|
|
"creating synthetics");
|
|
}
|
|
|
|
public Task<uint?> create_synthetic(SecurityImmutable synthetic) {
|
|
if (synthetic.ContractCase != Security.ContractOneofCase.Synthetic)
|
|
return null;
|
|
if (synthetic.Synthetic.UserId != _user_id) {
|
|
var msynth = synthetic.CloneToMutable();
|
|
msynth.Synthetic.UserId = _user_id;
|
|
synthetic = new SecurityImmutable(msynth);
|
|
}
|
|
return _error.safe_execute(
|
|
() => _service.create_synthetic_async(synthetic),
|
|
r => r.Error == CreateResult.Types.Error.Ok,
|
|
r => r.Error.ToString(),
|
|
(r, success) => success ? r.Key : (uint?)null,
|
|
"creating synthetic");
|
|
}
|
|
|
|
public Task<bool> save_strategy(uint synthetic, ExecutionStrategyImmutable strategy) =>
|
|
_error.safe_execute(
|
|
() => _service.update_security_metadata_async(new Metadata { SecurityKey = synthetic, Strategy = strategy.CloneToMutable() }),
|
|
r => r.Error == UpdateResult.Types.Error.Ok,
|
|
r => r.Error.ToString(),
|
|
(r, success) => success,
|
|
"saving strategy");
|
|
|
|
public async Task<string[]> save_strategies(IEnumerable<(uint key, ExecutionStrategyImmutable strategy)> items) {
|
|
// Copy everything to a new list, to guarentee that it won't be altered during the op.
|
|
// The performance impact should be insignificant, as this should be a rare call.
|
|
var item_list = new List<(uint key, ExecutionStrategyImmutable strategy, int index)>(items.Select((item, index) => (item.key, item.strategy, index)));
|
|
string[] errors = new string[item_list.Count];
|
|
await Task.WhenAll(item_list.Select(impl));
|
|
return errors;
|
|
async Task impl((uint key, ExecutionStrategyImmutable strategy, int index) tup) {
|
|
var (key, strategy, index) = tup;
|
|
try {
|
|
var result = await _service.update_security_metadata_async(new Metadata {
|
|
SecurityKey = key,
|
|
Strategy = strategy.CloneToMutable()
|
|
});
|
|
if (!result.success)
|
|
errors[index] = result.error_message;
|
|
} catch (Exception ex) {
|
|
errors[index] = ex.ToString();
|
|
}
|
|
}
|
|
}
|
|
|
|
public async Task<bool> verify_name_is_unique(string name) {
|
|
var (result, success) = await strategy_tuple.FirstAsyncTask(SparkUtils.DefaultTimeOut);
|
|
name = name.Trim().ToLower();
|
|
return success && !result.Values.Any(st => st.md.security.Synthetic.Name.Trim().ToLower() == name);
|
|
}
|
|
}
|
|
}
|