Compare commits

..
16 Commits
Author SHA1 Message Date
John Colvin 1ec2423ad2 SPARK-1215 fills performance - do not copy dictionaries in FillTupleSource 2018-06-07 21:17:58 -04:00
Taha Afzal 1a88e52a08 subtle change in the QuoterWaitingForAck where book changes on the hedging side make it dissapear, hence order needs to be pulled 2018-06-07 20:06:40 -04:00
Taha Afzal a1b52d083d SPARK-1200 2018-06-07 17:50:09 -04:00
Michael Harding f364317cfa Better window border compromise 2018-06-07 17:10:16 -04:00
Michael Harding f474af1925 Update a few manual tests 2018-06-07 16:09:53 -04:00
Michael Harding 03ac5035fc AdminUI: Minor tweaks and fixes 2018-06-07 16:09:53 -04:00
Michael Harding e78d8208fa AdminUI: Add application name to login page 2018-06-07 16:09:53 -04:00
Pedro Pinto 7f8c591f75 Instrumenting server for perf measurements. 2018-06-07 13:58:02 -04:00
Taha Afzal 7d9685f995 SPARK-1211 cor id 2018-06-07 13:11:27 -04:00
John Colvin 699736ff52 Merged in badge-style-row-height-unification (pull request #35)
SPARK-1204 Ladder/Badge - row height needs to fit different badge styles

Approved-by: Eric Harding <eric.harding@bluetradesys.com>
2018-06-07 16:36:03 +00:00
John Colvin 8d0e7bc467 pr finishing touch 2018-06-07 12:35:03 -04:00
Michael Harding df784e9961 SPARK-1201: Fix and style table headers 2018-06-07 10:21:14 -04:00
Michael Harding af39aab153 AdminUI: Fix default security symbol for new rows 2018-06-07 10:21:13 -04:00
John Colvin 3adfd7056a Merge branch 'master' into badge-style-row-height-unification 2018-06-06 18:48:18 -04:00
John Colvin 837aa51adf SPARK-1204 pr edits 2018-06-05 18:02:32 -04:00
John Colvin 410e17aec5 SPARK-1204 Ladder/Badge - row height needs to fit different badge styles 2018-06-05 16:46:50 -04:00
72 changed files with 1168 additions and 484 deletions

No files matched your search

@@ -24,13 +24,13 @@ namespace mbts.spark {
public FillsVM(IBus bus, OrdersModel model, StartupData state)
: this(bus, model, _get_observable(bus, model, state), state.sorting_criteria, state.filters) { }
FillsVM(IBus bus, OrdersModel model, IObservable<ITableUpdateTransform<FillTuple, string>> fills_source, IReadOnlyCollection<SortingCriteria> sorting_criteria, FilterStates filters)
: base(RXCollection.CreateTableUpdate(fills_source), sorting_criteria) {
FillsVM(IBus bus, OrdersModel model, IObservable<IIncrementalUpdate<FillTuple, string>> fills_source, IReadOnlyCollection<SortingCriteria> sorting_criteria, FilterStates filters)
: base(RXCollection.CreateIncrementalUpdate(fills_source), sorting_criteria) {
_model = model;
account_filter = DiscreteValuesFilterVM.Create<Row, string>(_model.factory.subscribe_accounts(), r => r.account, nameof(Row.account));
user_filter = DiscreteValuesFilterVM.Create<Row, string>(_model.factory.subscribe_users(), r => r.user, nameof(Row.user));
security_filter = DiscreteValuesFilterVM.Create<Row, SecurityImmutable, SecurityCriteria>(
fills_source.with_respect_to(ft => ft.security ?? SecurityDataHelper.Defaults.SecurityImmutable, s => s.Id, ft => ft.key).Select(t => (t.added, t.removed)),
fills_source.with_respect_to(ft => ft.security ?? SecurityDataHelper.Defaults.SecurityImmutable, s => s.Id, ft => ft.key).Select(t => (t.added.Values, t.removed.Values)),
r => r.security,
SecurityCriteria.from_securities,
SecurityCriteria.get_to_securities(bus),
@@ -126,7 +126,7 @@ namespace mbts.spark {
protected override Row row_factory(FillTuple row_model) => new Row(row_model, _model);
protected override IEnumerable<SortingCriteria> get_default_sorting() { yield return new SortingCriteria(nameof(Row.fill_time), false); }
static IObservable<ITableUpdateTransform<FillTuple, string>> _get_observable(IBus bus, OrdersModel model, StartupData state) {
static IObservable<IIncrementalUpdate<FillTuple, string>> _get_observable(IBus bus, OrdersModel model, StartupData state) {
if (state.orders != null && state.orders.Length == 0) {
var orders_hash = new HashSet<uint>(state.orders);
return model.on_fill_tuples.filter(f => orders_hash.Contains(f.fill.OrderKey));
@@ -77,6 +77,7 @@ namespace bts.shell {
s.ask_break_line = LadderSettings.Default.ask_break_line;
if (s.mid_break_line == null)
s.mid_break_line = LadderSettings.Default.mid_break_line;
s.row_height = LadderRender.measure_row_height(s);
return s;
}
}
+92 -64
View File
@@ -7,18 +7,19 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
namespace mbts.spark {
class FillTupleSource : IDisposable {
public static IObservable<ITableUpdateTransform<FillTuple, string>> create_observable(
public static IObservable<IIncrementalUpdate<FillTuple, string>> create_observable(
IObservable<IReadOnlyDictionary<uint, SecurityMD>> securities,
IObservable<TableUpdate<OrderRecordImmutable, uint>> orders,
IObservable<TableUpdate<FillImmutable, string>> fills
) {
FillTupleSource source = null;
int ref_count = 0;
return Observable.Create<TableUpdateTransform<FillTuple, string>>(observer => {
return Observable.Create<IIncrementalUpdate<FillTuple, string>>(observer => {
if (Interlocked.Increment(ref ref_count) == 1) {
SparkUtils.lazy_assert(source == null, () => fmt_assert_msg("source should be null, there must be a leak."));
source = new FillTupleSource(securities, orders, fills);
@@ -40,35 +41,38 @@ namespace mbts.spark {
IObservable<TableUpdate<OrderRecordImmutable, uint>> orders,
IObservable<TableUpdate<FillImmutable, string>> fills) {
State state = new State();
var src = Observable.FromEvent<Action<TableUpdateTransform<FillTuple, string>>, TableUpdateTransform<FillTuple, string>>(cb => _updated += cb, cb => _updated -= cb);
fill_tuples = Observable.Create<TableUpdateTransform<FillTuple, string>>(observer => {
var init_state = state.fill_tuples.state.ToDictionary();
observer.OnNext(new TableUpdateTransform<FillTuple, string>(init_state, init_state.Values.ToList(), new List<FillTuple>(0)));
return src.Subscribe(observer);
fill_tuples = Observable.Create<IIncrementalUpdate<FillTuple, string>>(observer => {
observer.OnNext(new IncrementalUpdate<FillTuple, string>(state.full_state.ToDictionary(), new Dictionary<string, FillTuple>(0)));
return _subject.Subscribe(observer);
});
_dispose = Disposable.Create(
securities.ObserveOnDispatcher().Subscribe(s => update(state.update_securities(s))),
orders.ObserveOnDispatcher().Subscribe(o => update(state.update_orders(o))),
fills.ObserveOnDispatcher().Subscribe(f => update(state.update_fills(f)))
);
void update(State new_state) {
state = new_state;
_updated?.Invoke(state.fill_tuples);
}
securities.ObserveOnDispatcher().Subscribe(s => {
state.update_securities(s);
_subject.OnNext(state.last_update);
}),
orders.ObserveOnDispatcher().Subscribe(o => {
state.update_orders(o);
_subject.OnNext(state.last_update);
}),
fills.ObserveOnDispatcher().Subscribe(f => {
state.update_fills(f);
_subject.OnNext(state.last_update);
}));
}
event Action<TableUpdateTransform<FillTuple, string>> _updated;
readonly Subject<IIncrementalUpdate<FillTuple, string>> _subject = new Subject<IIncrementalUpdate<FillTuple, string>>();
IObservable<TableUpdateTransform<FillTuple, string>> fill_tuples { get; }
IObservable<IIncrementalUpdate<FillTuple, string>> fill_tuples { get; }
public void Dispose() =>
Disposable.dispose(ref _dispose);
class State {
readonly IReadOnlyDictionary<string, FillImmutable> _fills;
readonly IReadOnlyDictionary<uint, OrderRecordImmutable> _orders;
readonly IReadOnlyDictionary<uint, SecurityMD> _securities;
readonly TableUpdateTransform<FillTuple, string> _fill_tuples;
IReadOnlyDictionary<string, FillImmutable> _fills;
IReadOnlyDictionary<uint, OrderRecordImmutable> _orders;
IReadOnlyDictionary<uint, SecurityMD> _securities;
IncrementalUpdate<FillTuple, string> _last_update;
readonly Dictionary<string, FillTuple> _state;
readonly SetMap<uint, string> _order_fills;
readonly SetMap<uint, string> _security_fills;
@@ -76,7 +80,8 @@ namespace mbts.spark {
new Dictionary<string, FillImmutable>(),
new Dictionary<uint, OrderRecordImmutable>(),
new Dictionary<uint, SecurityMD>(),
new TableUpdateTransform<FillTuple, string>(new Dictionary<string, FillTuple>(), new List<FillTuple>(), new List<FillTuple>()),
new IncrementalUpdate<FillTuple, string>(new Dictionary<string, FillTuple>(), new Dictionary<string, FillTuple>()),
new Dictionary<string, FillTuple>(),
new SetMap<uint, string>(),
new SetMap<uint, string>()
) { }
@@ -85,94 +90,117 @@ namespace mbts.spark {
IReadOnlyDictionary<string, FillImmutable> fills,
IReadOnlyDictionary<uint, OrderRecordImmutable> orders,
IReadOnlyDictionary<uint, SecurityMD> securities,
TableUpdateTransform<FillTuple, string> fill_tuples,
IncrementalUpdate<FillTuple, string> last_update,
Dictionary<string, FillTuple> state,
SetMap<uint, string> order_fill_tuples,
SetMap<uint, string> security_fill_tuples
) {
_fills = fills;
_orders = orders;
_securities = securities;
_fill_tuples = fill_tuples;
_last_update = last_update;
_state = state;
_order_fills = order_fill_tuples;
_security_fills = security_fill_tuples;
}
public TableUpdateTransform<FillTuple, string> fill_tuples => _fill_tuples;
public IncrementalUpdate<FillTuple, string> last_update => _last_update;
public IReadOnlyDictionary<string, FillTuple> full_state => _state;
public State update_fills(TableUpdate<FillImmutable, string> fills) {
var removed = fills.removed.Select(get_fill_tuple).ToList();
var added = fills.added.Select(get_fill_tuple).ToList();
var order_fills = _order_fills.clone();
var security_fills = _security_fills.clone();
public void update_fills(TableUpdate<FillImmutable, string> fills) {
var removed = fills.removed.ToDictionary(f => f.FillKey, get_fill_tuple);
var added = fills.added.ToDictionary(f => f.FillKey, get_fill_tuple);
HashSet<string> added_keys = new HashSet<string>(fills.added.Select(f => f.FillKey)),
removed_keys = new HashSet<string>(fills.removed.Select(f => f.FillKey));
foreach (var ft in removed) {
string k = ft.fill.FillKey;
if (!added_keys.Contains(k)) {
order_fills.remove(ft.fill.OrderKey, k);
security_fills.remove(ft.fill.SecurityKey, k);
foreach (var kv in removed) {
_state.Remove(kv.Key);
if (!added_keys.Contains(kv.Key)) {
_order_fills.remove(kv.Value.fill.OrderKey, kv.Key);
_security_fills.remove(kv.Value.fill.SecurityKey, kv.Key);
}
}
foreach (var ft in added) {
string k = ft.fill.FillKey;
if (!removed_keys.Contains(k)) {
order_fills.add(ft.fill.OrderKey, k);
security_fills.add(ft.fill.SecurityKey, k);
foreach (var kv in added) {
_state.Add(kv.Key, kv.Value);
if (!removed_keys.Contains(kv.Key)) {
_order_fills.add(kv.Value.fill.OrderKey, kv.Key);
_security_fills.add(kv.Value.fill.SecurityKey, kv.Key);
}
}
return new State(fills.state, _orders, _securities, _fill_tuples.update(removed, added, f => f.key), order_fills, security_fills);
_fills = fills.state;
_last_update = new IncrementalUpdate<FillTuple, string>(added, removed);
//
FillTuple get_fill_tuple(FillImmutable fill) =>
new FillTuple(fill, _orders.TryGetValue(fill.OrderKey, out OrderRecordImmutable o) ? o : new OrderRecordImmutable?(),
_securities.TryGetValue(fill.SecurityKey, out SecurityMD s) ? s.security : new SecurityImmutable?());
}
public State update_orders(TableUpdate<OrderRecordImmutable, uint> orders) {
List<FillTuple> added = new List<FillTuple>(), removed = new List<FillTuple>();
orders.detect_changed_keys(o => o.Key, out HashSet<uint> removed_keys, out HashSet<uint> added_keys, out HashSet<uint> changed_keys);
foreach (var k in removed_keys) {
if (_order_fills.try_lookup(k, out ISet<string> fill_keys)) {
removed.AddRange(get_fill_tuples(_orders[k], fill_keys));
added.AddRange(get_fill_tuples(null, fill_keys));
public void update_orders(TableUpdate<OrderRecordImmutable, uint> orders) {
Dictionary<string, FillTuple> added = new Dictionary<string, FillTuple>(), removed = new Dictionary<string, FillTuple>();
Dictionary<uint, (OrderRecordImmutable oldval, OrderRecordImmutable newval)> changed_orders = new Dictionary<uint, (OrderRecordImmutable oldval, OrderRecordImmutable newval)>();
foreach (var o in orders.removed) {
if (orders.try_get(o.Key, out OrderRecordImmutable newval))
changed_orders.Add(o.Key, (o, newval));
else if (_order_fills.try_lookup(o.Key, out ISet<string> fill_keys)) {
foreach (FillTuple ft in get_fill_tuples(o, fill_keys))
removed.Add(ft.key, ft);
foreach (FillTuple ft in get_fill_tuples(null, fill_keys))
added.Add(ft.key, ft);
}
}
foreach (var k in added_keys) {
if (_order_fills.try_lookup(k, out ISet<string> fill_keys)) {
removed.AddRange(get_fill_tuples(null, fill_keys));
added.AddRange(get_fill_tuples(orders.get(k), fill_keys));
foreach (var o in orders.added) {
if (!changed_orders.ContainsKey(o.Key) && _order_fills.try_lookup(o.Key, out ISet<string> fill_keys)) {
foreach (FillTuple ft in get_fill_tuples(null, fill_keys))
removed.Add(ft.key, ft);
foreach (FillTuple ft in get_fill_tuples(o, fill_keys))
added.Add(ft.key, ft);
}
}
foreach (var k in changed_keys) {
if (_order_fills.try_lookup(k, out ISet<string> fill_keys)) {
removed.AddRange(get_fill_tuples(_orders[k], fill_keys));
added.AddRange(get_fill_tuples(orders.get(k), fill_keys));
foreach (var kv in changed_orders) {
if (_order_fills.try_lookup(kv.Key, out ISet<string> fill_keys)) {
var fs_pairs = get_fill_security_pairs(fill_keys).ToList();
foreach (FillTuple ft in fs_pairs.Select(fsp => new FillTuple(fsp.fill, kv.Value.oldval, fsp.security)))
removed.Add(ft.key, ft);
foreach (FillTuple ft in fs_pairs.Select(fsp => new FillTuple(fsp.fill, kv.Value.newval, fsp.security)))
added.Add(ft.key, ft);
}
}
return new State(_fills, orders.state, _securities, _fill_tuples.update(removed, added, ft => ft.key), _order_fills, _security_fills);
_orders = orders.state;
_last_update = new IncrementalUpdate<FillTuple, string>(added, removed);
//
IEnumerable<FillTuple> get_fill_tuples(OrderRecordImmutable? o, ISet<string> fill_keys) =>
fill_keys.Select(k => {
var fill = _fills[k];
return new FillTuple(fill, o, _securities.TryGetValue(fill.SecurityKey, out SecurityMD s) ? s.security : new SecurityImmutable?());
});
IEnumerable<(FillImmutable fill, SecurityImmutable? security)> get_fill_security_pairs(ISet<string> fill_keys) =>
fill_keys.Select(k => {
var fill = _fills[k];
return (fill, _securities.TryGetValue(fill.SecurityKey, out SecurityMD s) ? s.security : new SecurityImmutable?());
});
}
public State update_securities(IReadOnlyDictionary<uint, SecurityMD> securities) {
List<FillTuple> added = new List<FillTuple>(), removed = new List<FillTuple>();
public void update_securities(IReadOnlyDictionary<uint, SecurityMD> securities) {
Dictionary<string, FillTuple> added = new Dictionary<string, FillTuple>(), removed = new Dictionary<string, FillTuple>();
_securities.Keys.difference(securities.Keys, out IEnumerable<uint> added_keys, out IEnumerable<uint> removed_keys);
foreach (var k in removed_keys) {
if (_security_fills.try_lookup(k, out ISet<string> fill_keys)) {
removed.AddRange(get_fill_tuples(_securities[k].security, fill_keys));
added.AddRange(get_fill_tuples(null, fill_keys));
foreach (FillTuple ft in get_fill_tuples(_securities[k].security, fill_keys))
removed.Add(ft.key, ft);
foreach (FillTuple ft in get_fill_tuples(null, fill_keys))
added.Add(ft.key, ft);
}
}
foreach (var k in added_keys) {
if (_security_fills.try_lookup(k, out ISet<string> fill_keys)) {
removed.AddRange(get_fill_tuples(null, fill_keys));
added.AddRange(get_fill_tuples(securities[k].security, fill_keys));
foreach (FillTuple ft in get_fill_tuples(null, fill_keys))
removed.Add(ft.key, ft);
foreach (FillTuple ft in get_fill_tuples(securities[k].security, fill_keys))
added.Add(ft.key, ft);
}
}
return new State(_fills, _orders, securities, _fill_tuples.update(removed, added, f => f.key), _order_fills, _security_fills);
_securities = securities;
_last_update = new IncrementalUpdate<FillTuple, string>(added, removed);
//
IEnumerable<FillTuple> get_fill_tuples(SecurityImmutable? s, ISet<string> fill_keys) =>
fill_keys.Select(k => {
+1 -1
View File
@@ -53,7 +53,7 @@ namespace mbts.spark {
public SpreaderModel spreader => _spreader;
public IObservable<TableUpdate<OrderRecordImmutable, uint>> on_orders { get; }
public IObservable<TableUpdate<FillImmutable, string>> on_fills { get; }
public IObservable<ITableUpdateTransform<FillTuple, string>> on_fill_tuples { get; }
public IObservable<IIncrementalUpdate<FillTuple, string>> on_fill_tuples { get; }
public IObservable<IReadOnlyDictionary<uint,OrderRecordImmutable>> working_orders { get; }
public IObservable<ITableUpdateTransform<OrderRecordImmutable, uint>> on_security_orders(uint security) =>
@@ -54,5 +54,33 @@
rv |= try_convert(args[1], out arg2);
return rv;
}
public static bool try_convert_args<T1, T2, T3>(object[] args, out T1 arg1, out T2 arg2, out T3 arg3) {
if (args == null || args.Length != 3) {
arg1 = default;
arg2 = default;
arg3 = default;
return false;
}
bool rv = try_convert(args[0], out arg1);
rv |= try_convert(args[1], out arg2);
rv |= try_convert(args[2], out arg3);
return rv;
}
public static bool try_convert_args<T1, T2, T3, T4>(object[] args, out T1 arg1, out T2 arg2, out T3 arg3, out T4 arg4) {
if (args == null || args.Length != 4) {
arg1 = default;
arg2 = default;
arg3 = default;
arg4 = default;
return false;
}
bool rv = try_convert(args[0], out arg1);
rv |= try_convert(args[1], out arg2);
rv |= try_convert(args[2], out arg3);
rv |= try_convert(args[3], out arg4);
return rv;
}
}
}
@@ -7,12 +7,27 @@ using System.Linq;
using System.Reactive.Linq;
namespace mbts.utils {
interface IIncrementalUpdate<T, TKey> where TKey : IEquatable<TKey> {
IReadOnlyDictionary<TKey, T> added { get; }
IReadOnlyDictionary<TKey, T> removed { get; }
}
interface ITableUpdateTransform<T, TKey> where TKey : IEquatable<TKey> {
IReadOnlyDictionary<TKey, T> state { get; }
IReadOnlyList<T> added { get; }
IReadOnlyList<T> removed { get; }
}
class IncrementalUpdate<T, TKey> : IIncrementalUpdate<T, TKey> where TKey : IEquatable<TKey> {
public IncrementalUpdate(IReadOnlyDictionary<TKey, T> added, IReadOnlyDictionary<TKey, T> removed) {
this.added = added;
this.removed = removed;
}
public IReadOnlyDictionary<TKey, T> added { get; }
public IReadOnlyDictionary<TKey, T> removed { get; }
}
class TableUpdateTransform<T, TKey> : ITableUpdateTransform<T, TKey> where TKey : IEquatable<TKey> {
readonly Dictionary<TKey, T> _state;
readonly IReadOnlyList<T> _added, _removed;
@@ -44,6 +59,15 @@ namespace mbts.utils {
table._state.Add(key(item), item);
return table;
}
public TableUpdateTransform<T, TKey> update(IIncrementalUpdate<T, TKey> update, Func<T, TKey> key) {
var table = new TableUpdateTransform<T, TKey>(new Dictionary<TKey, T>(_state), added, removed);
foreach (var k in update.removed.Keys)
table._state.Remove(k);
foreach (var kv in update.added)
table._state.Add(kv.Key, kv.Value);
return table;
}
}
[Browsable(false)]
@@ -69,6 +93,33 @@ namespace mbts.utils {
source.Scan(new PivotTableUpdateTransform<T, TKey, TResult, TResultKey>(selector, result_key, key),
(pivot, table) => pivot.update(table));
/// <summary>
/// Converts sequence to show incremental changes with respect to the [TResult] value returned by result_selector.
/// </summary>
public static IObservable<IIncrementalUpdate<TResult, TResultKey>> with_respect_to<T, TKey, TResult, TResultKey>(
this IObservable<IIncrementalUpdate<T, TKey>> source, Func<T, TResult> selector, Func<TResult, TResultKey> result_key, Func<T, TKey> key)
where TKey : IEquatable<TKey>
where TResultKey : IEquatable<TResultKey> =>
//
source.Scan(new PivotIncrementalUpdate<T, TKey, TResult, TResultKey>(selector, result_key, key),
(pivot, table) => pivot.update(table));
/// <summary>
/// Uses a Scan operator to accumulate state in the resulting ITableUpdateTransform sequence.
/// </summary>
public static IObservable<ITableUpdateTransform<T, TKey>> table<T, TKey>(this IObservable<IIncrementalUpdate<T, TKey>> source, Func<T, TKey> key) where TKey : IEquatable<TKey> =>
source.Scan(
new TableUpdateTransform<T, TKey>(),
(table, update) => table.update(update, key));
/// <summary>
/// Filters the incremental added/removed lists by a predicate. Observers are only notified when the filtered added/removed lists have elements.
/// </summary>
public static IObservable<IIncrementalUpdate<T, TKey>> filter<T, TKey>(this IObservable<IIncrementalUpdate<T, TKey>> source, Func<T, bool> predicate)
where TKey : IEquatable<TKey> => source
.Select(u => new IncrementalUpdate<T, TKey>(u.added.Where(kv => predicate(kv.Value)).ToDictionary(), u.removed.Where(kv => predicate(kv.Value)).ToDictionary()))
.Where(u => u.added.Count > 0 || u.removed.Count > 0);
class FilteredTableUpdateTransform<T, TKey> : ITableUpdateTransform<T, TKey> where TKey : IEquatable<TKey> {
internal FilteredTableUpdateTransform(ITableUpdateTransform<T, TKey> source, Func<T, bool> predicate) {
state = source.state;
@@ -81,6 +132,57 @@ namespace mbts.utils {
public IReadOnlyList<T> removed { get; }
}
class PivotIncrementalUpdate<T, TKey, TResult, TResultKey> : IIncrementalUpdate<TResult, TResultKey> where TKey : IEquatable<TKey> where TResultKey : IEquatable<TResultKey> {
readonly Dictionary<TResultKey, TResult> _state;
readonly SetMap<TResultKey, TKey> _key_map;
readonly Func<T, TResult> _selector;
readonly Func<TResult, TResultKey> _result_key;
readonly Func<T, TKey> _key;
internal PivotIncrementalUpdate(Func<T, TResult> selector, Func<TResult, TResultKey> result_key, Func<T, TKey> key) :
this(new Dictionary<TResultKey, TResult>(), new Dictionary<TResultKey, TResult>(0), new Dictionary<TResultKey, TResult>(0), new SetMap<TResultKey, TKey>(), selector, result_key, key) { }
PivotIncrementalUpdate(Dictionary<TResultKey, TResult> state, IReadOnlyDictionary<TResultKey, TResult> added, IReadOnlyDictionary<TResultKey, TResult> removed,
SetMap<TResultKey, TKey> key_map, Func<T, TResult> selector, Func<TResult, TResultKey> result_key, Func<T, TKey> key) {
//
_state = state;
this.added = added;
this.removed = removed;
_key_map = key_map;
_selector = selector;
_result_key = result_key;
_key = key;
}
public IReadOnlyDictionary<TResultKey, TResult> state => _state;
public IReadOnlyDictionary<TResultKey, TResult> added { get; }
public IReadOnlyDictionary<TResultKey, TResult> removed { get; }
public PivotIncrementalUpdate<T, TKey, TResult, TResultKey> update(IIncrementalUpdate<T, TKey> table) {
Dictionary<TResultKey, TResult> removed = new Dictionary<TResultKey, TResult>(), added = new Dictionary<TResultKey, TResult>();
var state_clone = new Dictionary<TResultKey, TResult>(_state);
foreach (var kv in table.removed) {
var result = _selector(kv.Value);
var rkey = _result_key(result);
if (_key_map.removes_key(rkey, kv.Key))
removed.Add(rkey, result);
}
foreach (var kv in table.added) {
var result = _selector(kv.Value);
var rkey = _result_key(result);
if (_key_map.adds_key(rkey, kv.Key)) {
if (!removed.Remove(rkey))
added.Add(rkey, result);
}
}
foreach (var k in removed.Keys)
state_clone.Remove(k);
foreach (var kv in added)
state_clone.Add(kv.Key, kv.Value);
return new PivotIncrementalUpdate<T, TKey, TResult, TResultKey>(state_clone, added, removed, _key_map, _selector, _result_key, _key);
}
}
class PivotTableUpdateTransform<T, TKey, TResult, TResultKey> : ITableUpdateTransform<TResult, TResultKey> where TKey : IEquatable<TKey> where TResultKey : IEquatable<TResultKey> {
readonly Dictionary<TResultKey, TResult> _state;
readonly SetMap<TResultKey, TKey> _key_map;
+191 -112
View File
@@ -1,141 +1,220 @@
using mbts.spark;
using mbts.ui.extensions;
using bts.api;
using mbts.spark;
using mbts.ui.utility.text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Data;
using System.Windows.Media;
using static mbts.config.Configuration;
using FontFamily = System.Windows.Media.FontFamily;
namespace mbts.ui.controls {
public class Badge: Control {
readonly static double _dpi = get<bts.config.System>().dpi_ratio;
public class Badge : Control {
public const double LINE_SPACING = 1;
// Storing the defaults here for readability
// Warning: these properties are used to calculate the ladder's row_height. Please change the values below if you want to change properties that affect the layout.
// ** - value is not the actual PropertyMetadata.DefaultValue
public static readonly Thickness
DefaultMargin = new Thickness(4, 2, 4, 2), // **
DefaultPadding = new Thickness(1),
DefaultBorderThickness = new Thickness(2);
public static readonly double
DefaultCornerRadius = 1,
DefaultFontSize = 10,
DefaultWidth = 63; // **
public static readonly FontFamily DefaultFontFamily = new FontFamily("Consolas");
readonly GlyphContentRect _gcr = new GlyphContentRect();
Brush _background, _foreground, _border_brush;
Typeface _face;
FormattedText _center_text;
FormattedText _top_text;
FormattedText _bottom_text;
static Badge() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(typeof(Badge)));
WidthProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(15.0));
HeightProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(10.0));
FontSizeProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(10.0, FrameworkPropertyMetadataOptions.AffectsRender /*| FrameworkPropertyMetadataOptions.AffectsMeasure*/, update_text));
ForegroundProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(Brushes.White, update_text));
BackgroundProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsRender));
BorderThicknessProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(new Thickness(1)));
BorderBrushProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(Brushes.Black));
FontFamilyProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(new FontFamily("Consolas"), FrameworkPropertyMetadataOptions.AffectsRender /*| FrameworkPropertyMetadataOptions.AffectsMeasure*/, update_text));
//TextProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure, update_text));
//TopTextProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure, update_text));
//BottomTextProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.AffectsMeasure, update_text));
// MinWidth
WPFHelper.override_metadata<double, Badge>(
MinWidthProperty,
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._gcr.min_width = v,
0);
// Width
WPFHelper.override_metadata<double, Badge>(
WidthProperty,
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._gcr.width = v,
double.NaN);
// Max Width
WPFHelper.override_metadata<double, Badge>(
MaxWidthProperty,
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._gcr.max_width = v,
double.MaxValue);
// Min Height
WPFHelper.override_metadata<double, Badge>(
MinHeightProperty,
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._gcr.min_height = v,
0);
// Height
WPFHelper.override_metadata<double, Badge>(
HeightProperty,
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._gcr.height = v,
double.NaN);
// Max Height
WPFHelper.override_metadata<double, Badge>(
MaxHeightProperty,
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._gcr.max_height = v,
double.MaxValue);
// FontSize
WPFHelper.override_metadata<double, Badge>(
FontSizeProperty,
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._gcr.font_size = v,
DefaultFontSize);
// Foreground
WPFHelper.override_metadata<Brush, Badge>(
ForegroundProperty,
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._foreground = v,
Brushes.White);
// Background
WPFHelper.override_metadata<Brush, Badge>(
BackgroundProperty,
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._background = v,
Brushes.Transparent);
// BorderThickness
WPFHelper.override_metadata<Thickness, Badge>(
BorderThicknessProperty,
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._gcr.border_thickness = v,
DefaultBorderThickness);
// BorderBrush
WPFHelper.override_metadata<Brush, Badge>(
BorderBrushProperty,
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._border_brush = v,
Brushes.Black);
// FontFamily
WPFHelper.override_metadata<FontFamily, Badge>(
FontFamilyProperty,
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._gcr.glyph_context = b._gcr.glyph_context.with(v),
DefaultFontFamily);
// HoriontalAlignment
WPFHelper.override_metadata<HorizontalAlignment, Badge>(
HorizontalAlignmentProperty,
FrameworkPropertyMetadataOptions.AffectsArrange |
FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._gcr.horizontal_alignment = v,
HorizontalAlignment.Stretch);
// HoriontalContentAlignment
WPFHelper.override_metadata<HorizontalAlignment, Badge>(
HorizontalContentAlignmentProperty,
FrameworkPropertyMetadataOptions.AffectsArrange |
FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._gcr.horizontal_content_alignment = v,
HorizontalAlignment.Center);
// VerticalAlignment
WPFHelper.override_metadata<VerticalAlignment, Badge>(
VerticalAlignmentProperty,
FrameworkPropertyMetadataOptions.AffectsArrange |
FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._gcr.vertical_alignment = v,
VerticalAlignment.Center);
// VerticalContentAlignment
WPFHelper.override_metadata<VerticalAlignment, Badge>(
VerticalContentAlignmentProperty,
FrameworkPropertyMetadataOptions.AffectsArrange |
FrameworkPropertyMetadataOptions.AffectsRender,
(o, v) => o._gcr.vertical_content_alignment = v,
VerticalAlignment.Center);
// Padding
WPFHelper.override_metadata<Thickness, Badge>(
PaddingProperty,
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(p, v) => p._gcr.padding = v,
DefaultPadding);
}
public string Text {
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(Badge), new PropertyMetadata(string.Empty,
format_text((b,v) => b._center_text= v)));
public string TopText {
get { return (string)GetValue(TopTextProperty); }
set { SetValue(TopTextProperty, value); }
}
public static readonly DependencyProperty TopTextProperty =
DependencyProperty.Register(nameof(TopText), typeof(string), typeof(Badge), new PropertyMetadata(string.Empty,
format_text((b, v) => b._top_text = v)));
public string BottomText {
get { return (string)GetValue(BottomTextProperty); }
set { SetValue(BottomTextProperty, value); }
public Badge() {
_gcr.min_width = MinWidth;
_gcr.width = Width;
_gcr.max_width = MaxWidth;
_gcr.min_height = MinHeight;
_gcr.height = Height;
_gcr.max_height = Height;
_gcr.padding = Padding;
_gcr.border_thickness = BorderThickness;
_gcr.horizontal_alignment = HorizontalAlignment;
_gcr.horizontal_content_alignment = HorizontalContentAlignment;
_gcr.vertical_alignment = VerticalAlignment;
_gcr.vertical_content_alignment = VerticalContentAlignment;
_background = Background;
_foreground = Foreground;
_border_brush = BorderBrush;
_gcr.font_size = FontSize;
_gcr.text_lines = TextLines;
_gcr.glyph_context = GlyphContext.create(FontFamily, FontWeight);
}
public static readonly DependencyProperty BottomTextProperty =
DependencyProperty.Register(nameof(BottomText), typeof(string), typeof(Badge), new PropertyMetadata(string.Empty,
format_text((b,v)=>b._bottom_text=v)));
public static readonly DependencyProperty TextLinesProperty =
WPFHelper.create_dp<IReadOnlyList<string>, Badge>(
nameof(TextLines),
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._gcr.text_lines = v,
new string[0]);
public IReadOnlyList<string> TextLines {
get => GetValue(TextLinesProperty) as IReadOnlyList<string>;
set => SetValue(TextLinesProperty, value);
}
public double CornerRadius {
get { return (double)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
}
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.Register("CornerRadius", typeof(double), typeof(Badge), new PropertyMetadata(3.0));
WPFHelper.create_dp<double, Badge>(nameof(CornerRadius), DefaultCornerRadius);
static PropertyChangedCallback format_text(Action<Badge,FormattedText> f) {
return (d, e) => {
Badge b = (Badge)d;
ensure_fontface(b);
string text = e.NewValue as string;
if (string.IsNullOrEmpty(text)) f(b, null);
f(b, new FormattedText(text,
System.Globalization.CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
b._face, b.FontSize, b.Foreground, _dpi));
b.InvalidateVisual();
};
protected override Size ArrangeOverride(Size finalSize) => finalSize;
protected override Size MeasureOverride(Size availableSize) {
_gcr.available_size = availableSize;
return _gcr.layout_size;
}
static FormattedText format_text(Badge badge, DependencyProperty source) {
FormattedText result = null;
var value = badge.GetValue(source);
format_text((b, v) => result = v)(badge, new DependencyPropertyChangedEventArgs(source, value, value));
return result;
}
static void update_text(DependencyObject d, DependencyPropertyChangedEventArgs args) {
// Force formatted text regeneration when font/color changes
Badge badge = (Badge)d;
badge._face = null;
ensure_fontface(badge);
badge._center_text = format_text(badge, TextProperty);
badge._top_text = format_text(badge, TopTextProperty);
badge._bottom_text = format_text(badge, BottomTextProperty);
}
private static void ensure_fontface(Badge b) {
b._face = b._face ?? new Typeface(b.FontFamily, b.FontStyle, b.FontWeight, b.FontStretch);
}
//protected override Size MeasureOverride(Size availableSize) {
// Double calc_height = 0.0;
// Double calc_width = 0.0;
// Size size = new Size(0, 0);
// Size center_size = new Size(_center_text.Width, _center_text.Height);
// Size top_size = new Size(_top_text.Width, _top_text.Height);
// Size bottom_size = new Size(_bottom_text.Width, _bottom_text.Height);
// calc_width = Math.Max(center_size.Width, top_size.Width);
// calc_width = Math.Max(calc_width, bottom_size.Width);
// calc_height += center_size.Height;
// calc_height += top_size.Height;
// calc_height += bottom_size.Height;
// size.Width = calc_width;
// size.Height = calc_height;
// return size;
//}
protected override void OnRender(DrawingContext dc) {
base.OnRender(dc);
double border_thickness = BorderThickness.Top;
var pen = new Pen(BorderBrush, border_thickness);
dc.DrawRoundedRectangle(Background, pen, new Rect(0, 0 + border_thickness, ActualWidth, ActualHeight - 2 * border_thickness), CornerRadius, CornerRadius);
if (_center_text != null)
dc.DrawText(_center_text, new Point((ActualWidth-_center_text.Width)/2, (ActualHeight-_center_text.Height)/2));
if (_top_text != null)
dc.DrawText(_top_text, new Point(border_thickness, border_thickness));
if (_bottom_text != null)
dc.DrawText(_bottom_text, new Point(border_thickness, ActualHeight - _bottom_text.Height - border_thickness));
dc.DrawRoundedRectangle(Background, pen, new Rect(0, border_thickness, _gcr.layout_size.Width, _gcr.layout_size.Height), CornerRadius, CornerRadius);
var gr = _gcr.glyph_run;
if (gr != null)
dc.DrawGlyphRun(_foreground, gr);
}
}
}
class BadgeTextLinesConverter : IMultiValueConverter {
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
if (ObjectHelper.try_convert_args(values, out Side side, out uint quantity, out uint filled, out mbts.spark.LadderSettings.BadgeStyle style))
return BadgeRender.format(side, quantity, filled, style);
else return new string[0];
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) => throw new NotImplementedException();
}
}
@@ -49,7 +49,7 @@ namespace mbts.spark.filters {
) => new DynamicItemsFilter<TRow, TValue, TState>(items, get_row_val, get_state, load_state, prop_name, equality_comparer, comparer);
public static IDataGridColumnPersistentFilter<TRow, TState> Create<TRow, TValue, TState>(
IObservable<(IReadOnlyList<TValue> added, IReadOnlyList<TValue> removed)> items,
IObservable<(IEnumerable<TValue> added, IEnumerable<TValue> removed)> items,
Func<TRow, TValue> get_row_val,
Func<ISet<TValue>, TState> get_state,
Func<TState, IObservable<IEnumerable<TValue>>> load_state,
@@ -122,7 +122,7 @@ namespace mbts.spark.filters {
}
public DynamicItemsFilter(
IObservable<(IReadOnlyList<TValue> added, IReadOnlyList<TValue> removed)> items,
IObservable<(IEnumerable<TValue> added, IEnumerable<TValue> removed)> items,
Func<TRow, TValue> get_row_val,
Func<ISet<TValue>, TState> get_state,
Func<TState, IObservable<IEnumerable<TValue>>> load_state,
@@ -15,7 +15,7 @@
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<c:Badge Background="{Binding Metadata, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource OrderTypeBrushConverter}}" Width="15" Height="10" HorizontalAlignment="Left" />
<c:Badge Background="{Binding Metadata, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource OrderTypeBrushConverter}}" BorderThickness="1" Width="15" Height="10" HorizontalAlignment="Left" />
<TextBlock Text="{Binding OrderType, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource OrderTypeDisplayTextConverter}}" Margin="20,0,0,0" HorizontalAlignment="Left" />
</Grid>
</Border>
@@ -22,7 +22,7 @@
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Window}">
<Border BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" Loaded="style_loaded" x:Name="window_border" u:WindowStyle.IsNonClientArea="true">
<Border BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" Loaded="style_loaded" x:Name="window_border" u:WindowStyle.IsNonClientArea="true">
<Grid Margin="{TemplateBinding Margin}">
<Grid.RowDefinitions>
<RowDefinition Height="20" />
@@ -134,8 +134,8 @@
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding Path=WindowState, RelativeSource={RelativeSource self}}" Value="Normal">
<Setter Property="Padding" Value="0,0,0,0" />
<Setter Property="BorderThickness" Value="7,1,2.66,2.66" TargetName="window_border" />
<Setter Property="Padding" Value="0,0,2,2" />
<Setter Property="BorderThickness" Value="7,1,1,1" TargetName="window_border" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
@@ -149,6 +149,15 @@ namespace mbts.spark {
}
}
public static string abbreviate(this Side side) {
switch (side) {
case Side.Buy: return "B";
case Side.Sell: return "S";
case Side.Undefined:
default: return "E";
}
}
public static string order_sub_type_display_name(OrderSubType sub_type, bool use_long_name) {
switch(sub_type) {
case OrderSubType.HedgingLeg:
@@ -67,19 +67,16 @@ namespace mbts.spark {
FontWeight get_font_weight(LadderSettings s) => ui.utility.text.TextUtils.from_open_type_weight_safe(s.orders_column.font_weight);
double get_font_size(LadderSettings s) => s.orders_column.font_size;
Brush get_foreground(LadderSettings s) => s.orders_column.foreground.rgb_brush();
_text = _bottom_line = _top_line = string.Empty;
//
add_order(o);
_dispose = Disposable.Create(
_bs.Subscribe( badge => {
_bs.Subscribe(badge => {
_current_badge_style = badge;
_set_badge_text();
})
);
add_order(o);
}
public void update() {
// update brushes
Color color;
@@ -107,17 +104,8 @@ namespace mbts.spark {
}
private void _set_badge_text() {
if (_orders.Count > 0) {
switch (_current_badge_style) {
case LadderSettings.BadgeStyle.Alternate:
top_line = $"{_buy_sell_indicator}:{filled}";
bottom_line = $"W:{ working_quantity}";
break;
case LadderSettings.BadgeStyle.Normal:
default:
text = $"{filled}/{quantity}"; break;
}
}
text_lines = BadgeRender.format(side, quantity, filled, _current_badge_style);
RaisePropertyChanged(nameof(text_lines));
}
public void add_order(OrderRecordImmutable new_order) {
@@ -138,7 +126,6 @@ namespace mbts.spark {
public uint security_key => _parent.security.Id;
public double price { get => double.IsNaN(_phantom_price) ? _real_price : _phantom_price; }
public double real_price => _real_price;
public Side side {
get {
var distinct_sides = _orders.Values.Select(o => o.side()).Distinct();
@@ -149,55 +136,9 @@ namespace mbts.spark {
}
}
string _buy_sell_indicator {
get {
switch (side) {
case Side.Buy: return "B";
case Side.Sell: return "S";
case Side.Undefined:
default:
return "E";
}
}
}
IEnumerable<OrderRecordImmutable> _parent_and_child_not_sharing_slot() => _orders.Values.Where(o => !_orders.ContainsKey(o.ParentKey));
private string _text;
public string text {
get { return _text; }
private set {
_text = value;
if (value != string.Empty) {
top_line = string.Empty;
bottom_line = string.Empty;
}
RaisePropertyChanged(); }
}
private string _top_line;
public string top_line {
get { return _top_line; }
private set {
_top_line = value;
if (value != string.Empty) {
text = string.Empty;
}
RaisePropertyChanged();
}
}
private string _bottom_line;
public string bottom_line {
get { return _bottom_line; }
private set {
_bottom_line = value;
if (value != string.Empty) {
text = string.Empty;
}
RaisePropertyChanged();
}
}
public IReadOnlyList<string> text_lines { get; private set; }
public bool has_parent => _orders.Values.Any( order => order.has_parent());
public bool has_phantom_price => !double.IsNaN(_phantom_price);
@@ -254,4 +195,4 @@ namespace mbts.spark {
return $"Price: {this.price} Order Count: {this.orders.Count()}";
}
}
}
}
@@ -143,8 +143,9 @@ namespace mbts.spark {
return price_cell.panel;
else if (_price_list != null && !double.IsNaN(_row_height)) {
var panel = new StackPanel() {
Margin = Badge.DefaultMargin,
Orientation = Orientation.Horizontal,
MaxWidth = _col_width,
MaxWidth = _col_width
//MaxHeight = _row_height,
//ClipToBounds = true
};
@@ -1,8 +1,8 @@
using bts.spark;
using mbts.spark.utilities;
using bts.api;
using mbts.ui;
using mbts.ui.controls.color_picker;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
@@ -14,6 +14,7 @@ namespace mbts.spark {
class LadderSettingsVM : ViewModelBase, IWindowSettingsVM<LadderSettings> {
readonly Property<LadderSettings.BadgeStyle> _badge_style;
readonly Property<uint> _alternate_order_size;
readonly DelegateProperty<double> _row_height;
LadderSettings _current;
LadderColumnSettingsVM
_orders = new OrdersColumnSettingsVM(),
@@ -30,6 +31,13 @@ namespace mbts.spark {
_badge_style = backing<LadderSettings.BadgeStyle>(nameof(badge_style));
_badge_style.Changed += _badge_style_Changed;
_alternate_order_size = backing<uint>(nameof(alternate_order_size));
_row_height = backing(nameof(row_height), () => LadderRender.measure_row_height(get_result()));
_orders.font_size_changed += on_font_size_changed;
_bid.font_size_changed += on_font_size_changed;
_price.font_size_changed += on_font_size_changed;
_ask.font_size_changed += on_font_size_changed;
_last.font_size_changed += on_font_size_changed;
void on_font_size_changed(double oldval, double newval) => _row_height.refresh();
}
private void _badge_style_Changed(LadderSettings.BadgeStyle oldval, LadderSettings.BadgeStyle newval) {
@@ -38,6 +46,7 @@ namespace mbts.spark {
} else if (newval == LadderSettings.BadgeStyle.Normal && _orders.font_size == 7) {
_orders.font_size = 10;
}
_row_height.refresh();
}
public LadderSettings.BadgeStyle badge_style {
@@ -50,6 +59,8 @@ namespace mbts.spark {
set => _alternate_order_size.Value = value;
}
public double row_height => _row_height.Value;
public IEnumerable<LadderColumnSettingsVM> column_items {
get {
yield return _orders;
@@ -89,7 +100,6 @@ namespace mbts.spark {
}
public LadderSettings get_result() {
const double row_padding = 12;
var clone = SparkUtils.clone_proto(_current);
clone.badge_style = badge_style;
clone.alternate_order_size = alternate_order_size;
@@ -101,13 +111,7 @@ namespace mbts.spark {
clone.bid_break_line = _bid_mkt_line.get_settings();
clone.ask_break_line = _ask_mkt_line.get_settings();
clone.mid_break_line = _mid_mkt_line.get_settings();
clone.row_height = new[] {
clone.orders_column,
clone.bid_column,
clone.price_column,
clone.ask_column,
clone.last_column
}.Max(cs => cs.font_size) + row_padding;
clone.row_height = LadderRender.measure_row_height(clone);
return clone;
}
@@ -131,6 +135,7 @@ namespace mbts.spark {
_background = backing(nameof(background), Colors.White);
_font_display_name = backing(nameof(font_display_name),
() => TextUtils.display_name(font_family, font_weight, font_size), nameof(font_family), nameof(font_weight), nameof(font_size));
_font_size.Changed += (oldval, newval) => font_size_changed?.Invoke(oldval, newval);
}
public string name { get; }
@@ -145,6 +150,7 @@ namespace mbts.spark {
public Color background { get => _background.Value; set => _background.Value = value; }
public ObservableCollection<ColorPaletteVM> foreground_palettes { get; }
public ObservableCollection<ColorPaletteVM> background_palettes { get; }
public event Action<double, double> font_size_changed;
public virtual string sample_text => "999-56789.01234";
@@ -178,7 +184,9 @@ namespace mbts.spark {
public class OrdersColumnSettingsVM : LadderColumnSettingsVM, ITemplateSelectorKey {
public OrdersColumnSettingsVM() : base("Orders") { }
public override string sample_text => "12/50";
public uint sample_quantity { get; } = 50;
public uint sample_filled { get; } = 12;
public Side sample_side { get; } = Side.Buy;
public Brush badge_border { get; } = new SolidColorBrush(BTSColors.MarketData.ask);
public Brush badge_background { get; } = Brushes.White;
@@ -213,4 +221,4 @@ namespace mbts.spark {
};
}
}
}
}
@@ -11,6 +11,7 @@
TextElement.FontSize="{x:Static u:FontSizes.Small}"
>
<UserControl.Resources>
<c:BadgeTextLinesConverter x:Key="BadgeTextLinesConverter"/>
<u:KeyedTemplateSelector x:Key="ColumnSampleTemplateSelector">
<u:KeyedTemplateSelector.Default>
<DataTemplate>
@@ -28,18 +29,23 @@
<u:TemplateSelectorKeyValue Key="{x:Static usp:LadderSettingsView.OrdersColumnSampleTemplateKey}">
<DataTemplate>
<c:Badge
Width="50"
Height="20"
Background="{Binding badge_background}"
BorderBrush="{Binding badge_border}"
BorderThickness="3"
FontFamily="{Binding font_family}"
FontSize="{Binding font_size}"
FontWeight="{Binding font_weight}"
Foreground="{Binding foreground, Converter={StaticResource ColorToBrushConverter}}"
Text="{Binding sample_text}"
VerticalAlignment="Center"
/>
Width="{x:Static c:Badge.DefaultWidth}"
>
<c:Badge.TextLines>
<MultiBinding Converter="{StaticResource BadgeTextLinesConverter}">
<Binding Path="sample_side"/>
<Binding Path="sample_quantity"/>
<Binding Path="sample_filled"/>
<Binding Path="DataContext.badge_style" RelativeSource="{RelativeSource AncestorType=usp:LadderSettingsView}"/>
</MultiBinding>
</c:Badge.TextLines>
</c:Badge>
</DataTemplate>
</u:TemplateSelectorKeyValue>
</u:KeyedTemplateSelector>
@@ -82,7 +88,7 @@
<ItemsControl Grid.Row="1" ItemsSource="{Binding column_items}" Margin="8,0">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Height="27">
<Grid Height="{Binding DataContext.row_height, Mode=OneWay, RelativeSource={RelativeSource AncestorType=usp:LadderSettingsView}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="c0"/>
<ColumnDefinition SharedSizeGroup="c1"/>
@@ -124,7 +130,7 @@
<c:FontPicker SelectedFontSize="{Binding font_size}" Typeface="{Binding typeface}"/>
</c:PopupControl>
<Border Grid.Column="4" Background="{Binding background, Converter={StaticResource ColorToBrushConverter}}" BorderBrush="Black" BorderThickness="2,0,0,0" Padding="4,0">
<ContentControl Content="{Binding}" ContentTemplateSelector="{StaticResource ColumnSampleTemplateSelector}"/>
<ContentControl Content="{Binding}" ContentTemplateSelector="{StaticResource ColumnSampleTemplateSelector}" VerticalContentAlignment="Center"/>
</Border>
<Rectangle Grid.Column="1" Grid.ColumnSpan="5" Fill="DimGray" Height="1" HorizontalAlignment="Stretch" VerticalAlignment="Bottom"/>
</Grid>
@@ -448,15 +448,9 @@
<Setter Property="FontFamily" Value="{Binding font_family}"/>
<Setter Property="FontSize" Value="{Binding font_size}"/>
<Setter Property="Foreground" Value="{Binding foreground}"/>
<Setter Property="Text" Value="{Binding text}" />
<Setter Property="TopText" Value="{Binding top_line}" />
<Setter Property="BottomText" Value="{Binding bottom_line}" />
<Setter Property="BorderThickness" Value="2" />
<Setter Property="Width" Value="63" />
<Setter Property="Height" Value="21" />
<Setter Property="Margin" Value="4,0,0,0" />
<Setter Property="TextLines" Value="{Binding text_lines}" />
<Setter Property="Width" Value="{x:Static controls:Badge.DefaultWidth}"/>
<Setter Property="ToolTip" Value="{Binding description}" />
<Setter Property="CornerRadius" Value="1" />
<Setter Property="Cursor" Value="Hand"/>
<Setter Property="ContextMenu">
<Setter.Value>
@@ -507,4 +501,4 @@
</Button>
</Grid>
</AdornerDecorator>
</UserControl>
</UserControl>
@@ -1,20 +1,61 @@
using bts.api;
using mbts.co2;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.utility.text;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
namespace mbts.spark {
static class BadgeRender {
// IMPORTANT: the return values for this method MUST BE IN SYNC with the "format" method, else "measure_height" and "LadderRender.measure_row_height" will be broken.
static int _line_count_for_style(LadderSettings.BadgeStyle badge_style) => badge_style == LadderSettings.BadgeStyle.Alternate ? 2 : 1;
// IMPORTANT: at the risk of being redundant, see above comment.
public static IReadOnlyList<string> format(Side side, uint quantity, uint filled, LadderSettings.BadgeStyle style) {
switch (style) {
case LadderSettings.BadgeStyle.Alternate:
return new[] {
$"{side.abbreviate()}:{filled}",
$"W:{quantity - filled}"
};
default: return new[] { $"{filled}/{quantity}" };
}
}
public static double measure_height(LadderSettings.BadgeStyle badge_style, Thickness border_thickness, Thickness padding, double font_size) =>
measure_height(_line_count_for_style(badge_style), border_thickness, padding, font_size);
public static double measure_height(int line_count, Thickness border_thickness, Thickness padding, double font_size) =>
WPFHelper.control_base_height(border_thickness, padding) + font_size * line_count + Badge.LINE_SPACING * (line_count - 1);
}
static class LadderRender {
// Note: the orders-column has a separate "row_padding" value: Badge.DefaultMargin
// (see how it is incorporated in measure_row_height() below)
public static readonly Thickness row_padding = new Thickness(6);
// IMPORTANT: this method ONLY WORKS if Badges use the BadgeRender.margin/border_thickness/padding values.
// TODO: elminate the dependency on BadgeRender.margin/border_thickness/padding by integrating them into settings.
public static double measure_row_height(LadderSettings settings) =>
Math.Max(new[] {
settings.bid_column.font_size,
settings.price_column.font_size,
settings.ask_column.font_size,
settings.last_column.font_size
}.Max() + row_padding.Top + row_padding.Bottom,
BadgeRender.measure_height(
settings.badge_style, Badge.DefaultBorderThickness, Badge.DefaultPadding, settings.orders_column.font_size
) + Badge.DefaultMargin.Top + Badge.DefaultMargin.Bottom);
public static int index_of(double[] prices, double price, IComparer<double> comparer) =>
Array.BinarySearch(prices, price, comparer);
public static GlyphRun format_text(string text, int row, double row_height, LadderColumnSettings settings, GlyphContext glyph_context) =>
glyph_context.get_glyph_run(text, settings.font_size, settings.width, row_height, HorizontalAlignment.Center, 0, VerticalAlignment.Center, row * row_height);
glyph_context.get_glyph_run(text, settings.font_size, settings.width, row_height, HorizontalAlignment.Center, 0, VerticalAlignment.Center, row * row_height, true);
public static double[] gen_prices(double mid, int row_count, ContractSpecificationImmutable spec) {
// require odd number
@@ -1,4 +1,5 @@
using bts.api;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
@@ -25,7 +26,7 @@ namespace mbts.spark
public IObservable<List<PnLData>> on_pnl_data =>
// combine w/ Securities to get SecurityMD
_order_model.on_fill_tuples.CombineLatest(_bus.subscribe(SparkTags.SecuritiesTag), (fills, securities) => {
_order_model.on_fill_tuples.table(ft => ft.key).CombineLatest(_bus.subscribe(SparkTags.SecuritiesTag), (fills, securities) => {
List<PnLData> pnl_data = new List<PnLData>(fills.state.Count);
foreach (var ft in fills.state.Values) {
if (ft.security.HasValue && securities.TryGetValue(ft.security.Value.Id, out SecurityMD sec_md)) {
@@ -41,7 +41,7 @@ namespace mbts.spark {
partial class CVOrderBookVM {
public class CVOrderBookColumnCollection : ObservableCollection<ColumnBase>, IDisposable {
public CVOrderBookColumnCollection(IBus bus, OrdersModel model, OrderBookStartupData startup_data, IObservable<(IReadOnlyList<SecurityImmutable> added, IReadOnlyList<SecurityImmutable> removed)> order_securities) {
public CVOrderBookColumnCollection(IBus bus, OrdersModel model, OrderBookStartupData startup_data, IObservable<(IEnumerable<SecurityImmutable> added, IEnumerable<SecurityImmutable> removed)> order_securities) {
// security
Add(security_column = new SecurityColumn(this,
DiscreteValuesFilterVM.Create<CVOrderBookRowVM, SecurityImmutable, SecurityCriteria>(
@@ -24,8 +24,8 @@ namespace mbts.spark {
// copying the collection locally avoids constantly casting rows_view to ICollectionViewLiveShaping.
readonly ObservableCollection<string> _live_sorting_props;
readonly Property<CVOrderBookRowVM> _current_row;
readonly Subject<(IReadOnlyList<SecurityImmutable> added, IReadOnlyList<SecurityImmutable> removed)> _order_securities_subject =
new Subject<(IReadOnlyList<SecurityImmutable> added, IReadOnlyList<SecurityImmutable> removed)>();
readonly Subject<(IEnumerable<SecurityImmutable> added, IEnumerable<SecurityImmutable> removed)> _order_securities_subject =
new Subject<(IEnumerable<SecurityImmutable> added, IEnumerable<SecurityImmutable> removed)>();
IReadOnlyDictionary<uint, OrderRecordImmutable> _orders_cache = new Dictionary<uint, OrderRecordImmutable>();
Dictionary<uint, CVOrderBookRowVM> _order_vms_cache = new Dictionary<uint, CVOrderBookRowVM>();
+65 -3
View File
@@ -53,7 +53,7 @@ namespace mbts.ui.utility.text {
public GlyphRun get_glyph_run(
string text, double font_size, double available_width, double available_height,
HorizontalAlignment x_alignment, double x_offset, VerticalAlignment y_alignment, double y_offset) {
HorizontalAlignment x_alignment, double x_offset, VerticalAlignment y_alignment, double y_offset, bool use_layout_rounding = false) {
//
if (string.IsNullOrEmpty(text))
return null;
@@ -61,7 +61,7 @@ namespace mbts.ui.utility.text {
var advance_widths = new double[text.Length];
if (!_try_get_glyph_params(text, font_size, ref glyph_indices, ref advance_widths, out double glyph_width))
return null;
var origin = _calculate_glyph_run_origin(font_size, available_width, available_height, glyph_width, x_alignment, x_offset, y_alignment, y_offset);
var origin = _calculate_glyph_run_origin(font_size, available_width, available_height, glyph_width, x_alignment, x_offset, y_alignment, y_offset, use_layout_rounding);
return new GlyphRun(_glyph_typeface, 0, false, font_size, HighDpiExtensions.fdpi_ratio, glyph_indices, origin, advance_widths, null, null, null, null, null, null);
}
@@ -87,7 +87,7 @@ namespace mbts.ui.utility.text {
static Point _calculate_glyph_run_origin(
double font_size, double available_width, double available_height, double glyph_width,
HorizontalAlignment x_alignment, double x_offset, VerticalAlignment y_alignment, double y_offset ) {
HorizontalAlignment x_alignment, double x_offset, VerticalAlignment y_alignment, double y_offset, bool use_layout_rounding = false) {
//
double x, y;
switch (x_alignment) {
@@ -104,6 +104,10 @@ namespace mbts.ui.utility.text {
default: y = available_height - 0.5 * (available_height - font_size); break;
}
y += y_offset;
if (use_layout_rounding) {
x = Math.Round(x);
y = Math.Round(y);
}
return new Point(x, y);
}
@@ -148,6 +152,64 @@ namespace mbts.ui.utility.text {
return true;
}
#region MultiLine
public bool arrange_glyph_run(
IReadOnlyList<string> lines, double line_spacing, TextAlignment text_alignment, double font_size,
out ushort[] glyph_indices, out double[] advance_widths, out Point[] glyph_offsets, out double glyph_width, out double glyph_height) {
//
glyph_width = 0;
glyph_height = 0;
if (lines.is_null_or_empty()) {
glyph_indices = new ushort[0];
advance_widths = new double[0];
glyph_offsets = new Point[0];
return false;
}
int size = lines.Sum(s => s.Length);
glyph_indices = new ushort[size];
advance_widths = new double[size];
glyph_offsets = new Point[size];
switch (text_alignment) {
case TextAlignment.Left:
return _try_get_glyph_params_left_aligned(lines, line_spacing, font_size, ref glyph_indices, ref advance_widths, ref glyph_offsets, out glyph_width, out glyph_height);
case TextAlignment.Center: // TODO
case TextAlignment.Right: // TODO
default: goto case TextAlignment.Left;
}
}
public GlyphRun from_arranged(double font_size, Point origin, ushort[] indices, double[] advance_widths, Point[] offsets) =>
new GlyphRun(_glyph_typeface, 0, false, font_size, HighDpiExtensions.fdpi_ratio, indices, origin, advance_widths, offsets, null, null, null, null, null);
bool _try_get_glyph_params_left_aligned(
IReadOnlyList<string> lines, double line_spacing, double font_size, ref ushort[] glyph_indices, ref double[] advance_widths, ref Point[] glyph_offsets, out double glyph_width, out double glyph_height) {
//
glyph_width = 0;
glyph_height = 0;
double x_offset = 0;
int n = 0;
foreach (string text in lines) {
double line_width = 0;
foreach (char c in text) {
if (!_char_map.TryGetValue(c, out (ushort index, double width) gc))
return false;
glyph_indices[n] = gc.index;
double w = gc.width * font_size;
advance_widths[n] = w;
line_width += w;
glyph_offsets[n] = new Point(x_offset, glyph_height);
n++;
}
x_offset -= line_width;
if (line_width > glyph_width)
glyph_width = line_width;
glyph_height += (font_size + line_spacing);
}
glyph_height -= line_spacing; // remove the last line space
return true;
}
#endregion
static ReadOnlyDictionary<int, (ushort index, double width)> _get_glyph_char_map(GlyphTypeface glyph_typeface) =>
_glyph_char_maps.GetOrAdd(glyph_typeface, gt => new Lazy<ReadOnlyDictionary<int, (ushort index, double width)>>(() => {
var widths = glyph_typeface.AdvanceWidths;
@@ -0,0 +1,185 @@
using mbts.ui.utility.text;
using mbts.utils;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
namespace mbts.ui {
interface IVisualContentRect {
Size layout_size { get; }
Rect content_area { get; }
}
// the "Control" in 'IControlVisualContentRect' is a double entendre:
// it hosts a set of input-properties inspired by the System.Windows.Control class,
// and it gives the caller "control" to modify the layout and content_area.
interface IControlVisualContentRect : IVisualContentRect {
Thickness border_thickness { get; set; }
Thickness padding { get; set; }
HorizontalAlignment horizontal_alignment { get; set; }
HorizontalAlignment horizontal_content_alignment { get; set; }
VerticalAlignment vertical_alignment { get; set; }
VerticalAlignment vertical_content_alignment { get; set; }
double content_width { get; set; }
double content_height { get; set; }
double min_width { get; set; }
double width { get; set; }
double max_width { get; set; }
double min_height { get; set; }
double height { get; set; }
double max_height { get; set; }
Size available_size { get; set; }
}
/// <summary>
/// Uses a set of standard r/w properties to measure and arrange the layout of a rectangular border-region with content inside.
/// </summary>
class VisualContentRect : IControlVisualContentRect {
Thickness
_padding,
_border_thickness;
HorizontalAlignment
_horizontal_alignment,
_horizontal_content_alignment = HorizontalAlignment.Center;
VerticalAlignment
_vertical_alignment,
_vertical_content_alignment = VerticalAlignment.Center;
double
_content_width,
_content_height,
_min_width,
_width,
_max_width,
_min_height,
_height,
_max_height;
Size _available_size, _layout_size;
Rect _content_area;
bool _dirty;
public Thickness border_thickness { get => _border_thickness; set => _set(ref _border_thickness, value); }
public Thickness padding { get => _padding; set => _set(ref _padding, value); }
public HorizontalAlignment horizontal_alignment { get => _horizontal_alignment; set => _set(ref _horizontal_alignment, value); }
public HorizontalAlignment horizontal_content_alignment { get => _horizontal_content_alignment; set => _set(ref _horizontal_content_alignment, value); }
public VerticalAlignment vertical_alignment { get => _vertical_alignment; set => _set(ref _vertical_alignment, value); }
public VerticalAlignment vertical_content_alignment { get => _vertical_content_alignment; set => _set(ref _vertical_content_alignment, value); }
public double content_width { get => _content_width; set => _set(ref _content_width, value); }
public double content_height { get => _content_height; set => _set(ref _content_height, value); }
public double min_width { get => _min_width; set => _set(ref _min_width, value); }
public double width { get => _width; set => _set(ref _width, value); }
public double max_width { get => _max_width; set => _set(ref _max_width, value); }
public double min_height { get => _min_height; set => _set(ref _min_height, value); }
public double height { get => _height; set => _set(ref _height, value); }
public double max_height { get => _max_height; set => _set(ref _max_height, value); }
public Size available_size { get => _available_size; set => _set(ref _available_size, value, _size_comparer); }
public Size layout_size { get { _ensure_current(); return _layout_size; } }
public Rect content_area { get { _ensure_current(); return _content_area; } }
void _ensure_current() {
if (_dirty) {
WPFHelper.measure_visual_content(
_border_thickness, _padding, _horizontal_alignment, _horizontal_content_alignment, _vertical_alignment, _vertical_content_alignment,
_min_width, _width, _max_width, _min_height, _height, _max_height,
_content_width, _content_height, _available_size, out _content_area, out _layout_size, true);
_dirty = false;
}
}
void _set<T>(ref T field, T value) =>
_set(ref field, value, EqualityComparer<T>.Default);
void _set<T>(ref T field, T value, IEqualityComparer<T> comparer) {
if (!comparer.Equals(field, value)) {
field = value;
_dirty = true;
}
}
static readonly IEqualityComparer<Size> _size_comparer = EqualityComparer.Create<Size>((a, b) => a == b);
}
// this class was designed to organize/contain the littany of properties needed to arrange glyph content
// in addition to the usual-suspects (width, horizontalalignment, etc.), it stores the glyph-arrays: glyph_indices, advance_widths, and glyph_offsets
class GlyphContentRect : IControlVisualContentRect {
readonly VisualContentRect _vcr = new VisualContentRect();
ushort[] _glyph_indices;
double[] _advance_widths;
Point[] _glyph_offsets;
bool _arrange_dirty;
// fields of public properties
double _font_size, _line_spacing;
IReadOnlyList<string> _text_lines;
GlyphContext _glyph_context;
GlyphRun _glyph_run;
public GlyphContext glyph_context { get => _glyph_context; set => _set(ref _glyph_context, value); }
public IReadOnlyList<string> text_lines { get => _text_lines; set => _set(ref _text_lines, value); }
public double font_size { get => _font_size; set => _set(ref _font_size, value); }
public double line_spacing { get => _line_spacing; set => _set(ref _line_spacing, value); }
public Thickness border_thickness { get => _vcr.border_thickness; set => _vcr.border_thickness = value; }
public Thickness padding { get => _vcr.padding; set => _vcr.padding = value; }
public HorizontalAlignment horizontal_alignment { get => _vcr.horizontal_alignment; set => _vcr.horizontal_alignment = value; }
public HorizontalAlignment horizontal_content_alignment { get => _vcr.horizontal_content_alignment; set => _vcr.horizontal_content_alignment = value; }
public VerticalAlignment vertical_alignment { get => _vcr.vertical_alignment; set => _vcr.vertical_alignment = value; }
public VerticalAlignment vertical_content_alignment { get => _vcr.vertical_content_alignment; set => _vcr.vertical_content_alignment = value; }
public double content_width { get { _ensure_current(); return _vcr.content_width; } set { /*TODO: maybe add a Clip property and set it here?*/ } }
public double content_height { get { _ensure_current(); return _vcr.content_height; } set { /*TODO: maybe add a Clip property and set it here?*/ } }
public double min_width { get => _vcr.min_width; set => _vcr.min_width = value; }
public double width { get => _vcr.width; set => _vcr.width = value; }
public double max_width { get => _vcr.max_width; set => _vcr.max_width = value; }
public double min_height { get => _vcr.min_height; set => _vcr.min_height = value; }
public double height { get => _vcr.height; set => _vcr.height = value; }
public double max_height { get => _vcr.max_height; set => _vcr.max_height = value; }
public Size available_size { get => _vcr.available_size; set => _vcr.available_size = value; }
public Size layout_size { get { _ensure_current(); return _vcr.layout_size; } }
public Rect content_area { get { _ensure_current(); return _vcr.content_area; } }
public GlyphRun glyph_run {
get {
if (_text_lines.is_null_or_empty())
return null;
_ensure_current();
Point pt = _vcr.content_area.BottomLeft;
if (_glyph_run == null) {
_glyph_run = _glyph_context.from_arranged(_font_size, pt, _glyph_indices, _advance_widths, _glyph_offsets);
} else if (_glyph_run.BaselineOrigin != pt) {
_glyph_run.BaselineOrigin = pt;
}
return _glyph_run;
}
}
void _ensure_current() {
if (_arrange_dirty) {
if (_text_lines.is_null_or_empty()) {
_vcr.content_width = 0;
_vcr.content_height = 0;
} else {
_glyph_context.arrange_glyph_run(_text_lines, _line_spacing, TextAlignment.Left, _font_size, out _glyph_indices, out _advance_widths, out _glyph_offsets, out double glyph_width, out double glyph_height);
_vcr.content_width = glyph_width;
_vcr.content_height = glyph_height;
}
_glyph_run = null;
_arrange_dirty = false;
}
}
void _set<T>(ref T field, T value) =>
_set(ref field, value, EqualityComparer<T>.Default);
void _set<T>(ref T field, T value, IEqualityComparer<T> comparer) {
if (!comparer.Equals(field, value)) {
field = value;
_arrange_dirty = true;
}
}
}
static class VisualContentRectExtensions {
// since the Margin is an external factor - an amount of space outside of the control's render-region - it is not included directly in the layout_size
public static Size layout_size_plus_margin(this IVisualContentRect vcr, Thickness margin) {
var sz = vcr.layout_size;
return new Size(margin.Left + sz.Width + margin.Right, margin.Top + sz.Height + margin.Bottom);
}
}
}
@@ -59,6 +59,9 @@ namespace mbts.ui.utility {
public static ITableUpdateCollection<T, TKey> CreateTableUpdate<T, TKey>(IObservable<ITableUpdateTransform<T, TKey>> source, Func<T, bool> collection_filter) where TKey : IEquatable<TKey> =>
new TableUpdateTransformCollection<T, TKey>(source, collection_filter ?? new Func<T, bool>(_ => true));
public static IRXCollection<T> CreateIncrementalUpdate<T, TKey>(IObservable<IIncrementalUpdate<T, TKey>> source) where TKey : IEquatable<TKey> =>
new IncrementalUpdateCollection<T, TKey>(source);
class AnonymousRXCollection<T, TData> : ObservableCollection<T>, IRXCollection<T> {
IDisposable _sub;
@@ -103,5 +106,20 @@ namespace mbts.ui.utility {
public bool TryGetValue(TKey key, out T result) => _raw_state.TryGetValue(key, out result);
public void Dispose() => Disposable.dispose(ref _sub);
}
class IncrementalUpdateCollection<T, TKey> : ObservableCollection<T>, IRXCollection<T> where TKey : IEquatable<TKey> {
IDisposable _sub;
internal IncrementalUpdateCollection(IObservable<IIncrementalUpdate<T, TKey>> source) {
_sub = source.ObserveOnDispatcher().Subscribe(u => {
foreach (T val in u.removed.Values)
Remove(val);
foreach (T val in u.added.Values)
Add(val);
});
}
public void Dispose() => Disposable.dispose(ref _sub);
}
}
}
@@ -1,3 +1,4 @@
using mbts.spark.utilities;
using mbts.utils;
using System;
using System.Collections;
@@ -222,5 +223,96 @@ namespace mbts.ui {
public static double control_base_height(Thickness border_thickness, Thickness padding) =>
border_thickness.Top + padding.Top + padding.Bottom + border_thickness.Bottom;
public static void measure_visual_content(
Thickness border_thickness,
Thickness padding,
HorizontalAlignment x_align,
HorizontalAlignment x_content_align,
VerticalAlignment y_align,
VerticalAlignment y_content_align,
double min_width,
double width,
double max_width,
double min_height,
double height,
double max_height,
double content_width,
double content_height,
Size available_size,
out Rect content_area,
out Size resultant_size,
bool use_layout_rounding = false) {
//
double result_width, content_left;
if (!double.IsNaN(width)) {
result_width = MathUtils.within_range(min_width, max_width, width);
switch (x_content_align) {
case HorizontalAlignment.Left: content_left = border_thickness.Left + padding.Left; break;
case HorizontalAlignment.Center: content_left = 0.5 * (result_width - content_width); break;
case HorizontalAlignment.Right: content_left = result_width - border_thickness.Right - padding.Right; break;
default: goto case HorizontalAlignment.Center;
}
} else {
switch (x_align) {
case HorizontalAlignment.Left:
case HorizontalAlignment.Center:
case HorizontalAlignment.Right:
result_width = MathUtils.within_range(min_width, max_height, border_thickness.Left + padding.Left + content_width + padding.Right + border_thickness.Right);
content_left = border_thickness.Left + padding.Left;
break;
case HorizontalAlignment.Stretch: {
result_width = MathUtils.within_range(min_width, max_height, available_size.Width);
switch (x_content_align) {
case HorizontalAlignment.Left: content_left = border_thickness.Left + padding.Left; break;
case HorizontalAlignment.Center: content_left = 0.5 * (result_width - content_width); break;
case HorizontalAlignment.Right: content_left = result_width - content_width - border_thickness.Right - padding.Right; break;
default: goto case HorizontalAlignment.Center;
}
}
break;
default: goto case HorizontalAlignment.Center;
}
}
double result_height, content_top;
if (!double.IsNaN(height)) {
result_height = MathUtils.within_range(min_height, max_height, height);
switch (y_content_align) {
case VerticalAlignment.Top: content_top = border_thickness.Top + padding.Top; break;
case VerticalAlignment.Center: content_top = 0.5 * (result_height - content_height); break;
case VerticalAlignment.Bottom: content_top = result_height - border_thickness.Bottom - padding.Bottom; break;
default: goto case VerticalAlignment.Center;
}
} else {
switch (y_align) {
case VerticalAlignment.Top:
case VerticalAlignment.Center:
case VerticalAlignment.Bottom:
result_height = border_thickness.Top + padding.Top + content_height + padding.Bottom + border_thickness.Bottom;
content_top = border_thickness.Top + padding.Top;
break;
case VerticalAlignment.Stretch:
result_height = available_size.Height;
switch (y_content_align) {
case VerticalAlignment.Top: content_top = border_thickness.Top + padding.Top; break;
case VerticalAlignment.Center: content_top = 0.5 * (result_height - content_height); break;
case VerticalAlignment.Bottom: content_top = result_height - content_height - border_thickness.Bottom - padding.Bottom; break;
default: goto case VerticalAlignment.Center;
}
break;
default: goto case VerticalAlignment.Center;
}
}
if (use_layout_rounding) {
content_left = Math.Round(content_left);
content_top = Math.Round(content_top);
content_width = Math.Round(content_width);
content_height = Math.Round(content_height);
result_width = Math.Round(result_width);
result_height = Math.Round(result_height);
}
content_area = new Rect(content_left, content_top, content_width, content_height);
resultant_size = new Size(result_width, result_height);
}
}
}
@@ -45,7 +45,7 @@ const bts::api::admin::ExchangeConnection* AdminServiceUtils::find_default_accou
const bts::api::admin::BTSAccount& account,
bts::api::Venue exchange){
//todo:get from parent accounts if not overridden
if(account.has_connections())
if(account.has_connections())
for (const std::string& conn_name : account.connections().exchange_connection_names()){
const bts::api::admin::ExchangeConnection* conn = find_connection(data, conn_name);
if (conn!=nullptr && has_exchange(*conn, exchange))
@@ -53,6 +53,44 @@ const bts::api::admin::ExchangeConnection* AdminServiceUtils::find_default_accou
}
return nullptr;
}
const bts::api::admin::ExchangeConnection*
AdminServiceUtils::resolve_cme_connection(const bts::api::admin::AdminData& data,
const bts::api::admin::BTSAccount& account,
const bts::api::Security& sec){
if(account.has_connections())
for (const std::string& conn_name : account.connections().exchange_connection_names()){
const bts::api::admin::ExchangeConnection* conn = find_connection(data, conn_name);
if (conn!=nullptr && conn->has_cme_connection())
if (conn->cme_connection().has_cgw_connection() ||
(sec.has_glbx() && conn->cme_connection().has_msgw_connection() &&
conn->cme_connection().msgw_connection().market_segment_id() == sec.glbx().market_segment_id()))
return conn;
}
return nullptr;
}
const bts::api::admin::ExchangeConnection*
AdminServiceUtils::resolve_connection(const bts::api::admin::AdminData& data,
const bts::api::admin::BTSAccount& account,
const bts::api::Security& sec){
const bts::api::admin::ExchangeConnection* rv = nullptr;
switch(sec.exchange()){
case api::Venue::VENUE_GLBX:
rv = resolve_cme_connection(data, account, sec);
break;
case api::Venue::VENUE_UNSET:
case api::Venue::VENUE_BTS:
case api::Venue::VENUE_CBOE:
case api::Venue::VENUE_CBOECFE:
case api::Venue::VENUE_ICE:
case api::Venue::Venue_INT_MIN_SENTINEL_DO_NOT_USE_:
case api::Venue::Venue_INT_MAX_SENTINEL_DO_NOT_USE_:
rv = nullptr;
break;
}
return rv;
}
////////////////////////////////////////////
// connection mutators /////////////////////
////////////////////////////////////////////
@@ -71,7 +109,10 @@ void AdminServiceUtils::fill_connections_from_config(bts::api::admin::AdminData&
uint32_t new_id = find_max_connection_id(admin_data)+1;
connection.set_id(new_id);
connection.set_name(c.name());
connection.mutable_cme_connection()->mutable_msgw_connection();
if (c.cme_market_segment_id()==0)
connection.mutable_cme_connection()->mutable_cgw_connection();
else
connection.mutable_cme_connection()->mutable_msgw_connection()->set_market_segment_id(c.cme_market_segment_id());
add_connection(admin_data,connection);
}
for(int i=0;i<admin_data.accounts_size();i++)
@@ -267,7 +308,8 @@ bts::api::orderman::RoutingRecord AdminServiceUtils::get_routing_record(const bt
out_result.set_error_text("Could not find user");
return rv;
}
const bts::api::admin::ExchangeConnection* conn_ptr = find_default_account_connection(data, *account_ptr, sec.exchange());
const bts::api::admin::ExchangeConnection* conn_ptr = //find_default_account_connection(data, *account_ptr, sec.exchange());
resolve_connection(data,*account_ptr,sec);
if(conn_ptr == nullptr){
out_result.set_is_success(false);
out_result.set_error_text("Could not find connection");
@@ -29,6 +29,12 @@ public:
static const bts::api::admin::ExchangeConnection* find_default_account_connection(const bts::api::admin::AdminData& data,
const bts::api::admin::BTSAccount& account,
bts::api::Venue exchange);
static const bts::api::admin::ExchangeConnection* resolve_cme_connection(const bts::api::admin::AdminData& data,
const bts::api::admin::BTSAccount& account,
const bts::api::Security& sec);
static const bts::api::admin::ExchangeConnection* resolve_connection(const bts::api::admin::AdminData& data,
const bts::api::admin::BTSAccount& account,
const bts::api::Security& sec);
////////////////////////////////////////////
// connection mutators /////////////////////
////////////////////////////////////////////
+1
View File
@@ -235,6 +235,7 @@ message CMEMSGWConnection{
string password = 30;
string secret_key = 40;
string access_key_id = 50;
uint32 market_segment_id = 60;
}
message CMEAccountData{
-1
View File
@@ -97,7 +97,6 @@ void configure_logging(bts::config::Logging const&cfg)
{log::persist,"persist"},
{log::User,"User"},
{log::OrderMan,"OrderMan"},
{log::Latency,"Latency"},
{log::Assert,"Assert"},
{log::Engine,"Engine"},
{log::Ui,"UI"},
+1 -2
View File
@@ -34,8 +34,7 @@ constexpr log::Subsystem Api {md.ordinal+1 };
constexpr log::Subsystem persist {Api.ordinal+1 };
constexpr log::Subsystem User {persist.ordinal+1 };
constexpr log::Subsystem OrderMan {User.ordinal+1 };
constexpr log::Subsystem Latency {OrderMan.ordinal+1 };
constexpr log::Subsystem Assert {Latency.ordinal+1 };
constexpr log::Subsystem Assert {OrderMan.ordinal+1 };
constexpr log::Subsystem Engine {Assert.ordinal+1 };
constexpr log::Subsystem Ui {Engine.ordinal+1 };
constexpr log::Subsystem ExSim {Ui.ordinal+1 };
@@ -3,6 +3,8 @@
#include "server/sparkd/jetfix/store/session_name.h"
#include "lib/logging/logging.h"
#include "lib/utils/TimeStamp.h"
#include "server/sparkd/tracing/bts_trace.h"
#include "lib/utils/helper_macros.h"
#include <arpa/inet.h>
#include <sys/types.h>
@@ -101,6 +103,7 @@ int SocketConnection::read (char* to_buffer,size_t read_count)
int SocketConnection::write (WriteVec const&vec,size_t vec_size,size_t cid)
{
UNUSED(cid); // clang
bts_assert (_fd>=0);
struct iovec iv [MaxWriteVecSz];
@@ -109,9 +112,9 @@ int SocketConnection::write (WriteVec const&vec,size_t vec_size,size_t cid)
iv[i].iov_len = vec[i].second;
}
LOG(Latency,Info,"SocketConnection_write_pre_write {} {}", cid, utils::TimeStamp::now().to_uint64());
tracepoint (bts_trace,trace_order,(char*) "SocketConnection.pre_write", 0,cid);
auto result = ::writev (_fd,iv,(int) vec_size);
LOG(Latency,Info,"SocketConnection_write_post_write {} {}", cid, utils::TimeStamp::now().to_uint64());
tracepoint (bts_trace,trace_order,(char*) "SocketConnection.post_write", 0,cid);
if (_log && result >0) {
for (size_t i = 0; i < vec_size;i++)
_out_log.write (vec[i].first, vec[i].second);
@@ -11,6 +11,7 @@
#include "lib/utils/datetime.h"
#include "lib/utils/bts_chrono.h"
#include "server/sparkd/orderman/orderman_utils/orderman_common.h"
#include "server/sparkd/tracing/bts_trace.h"
#include <thread>
#include <atomic>
@@ -160,7 +161,7 @@ CoreGateway::~CoreGateway ()
void CoreGateway::send (orderman::TickToTradeCorID cid, OutFIXPtr const &fix)
{
LOG(Latency,Info,"CoreGateway_send {} {}", cid, utils::TimeStamp::now().to_uint64());
tracepoint (bts_trace,trace_order,(char*) "CoreGateway.send", 0,cid);
me->event_queue.enqueue (EventData (&CoreGateway::sync_send,cid,fix));
}
@@ -277,7 +278,7 @@ void CoreGateway::sync_stop (EventData const&)
void CoreGateway::sync_send (EventData const &ev)
{
LOG(Latency,Info,"CoreGateway_sync_send {} {}", ev.cid, utils::TimeStamp::now().to_uint64());
tracepoint (bts_trace,trace_order,(char*) "CoreGateway.sync_send", 0,ev.cid);
switch (me->state)
{
case State::OFF:
+4 -5
View File
@@ -12,6 +12,7 @@
#include "server/sparkd/jetfix/connection/IConnection.h"
#include "server/sparkd/jetfix/gateway/ICoreGatewayEventSink.h"
#include "server/sparkd/jetfix/store/IFIXStore.h"
#include "server/sparkd/tracing/bts_trace.h"
#include "lib/config/protos/jetfix.pb.h"
@@ -105,6 +106,7 @@ void Session::start() {
}
void Session::send(orderman::TickToTradeCorID cid, OutFIXPtr const &msgs) {
tracepoint (bts_trace,trace_order,(char*) "Session.send", 0,cid);
switch (me->state) {
case State::READY:
case State::CERT_MODE:
@@ -561,15 +563,12 @@ void Session::internal_send(orderman::TickToTradeCorID cid,
data_vec[i].first = s.data();
data_vec[i].second = s.size();
}
LOG(Latency, Info, "Session_internal_send_pre_write {} {}", cid,
utils::TimeStamp::now().to_uint64());
tracepoint (bts_trace,trace_order,(char*) "Session.internal_send.pre_write", 0,cid);
if (me->connection.write(data_vec, msgs->fix.size(), cid) < 0) {
terminate_session(JetFIXError::CONNECTION_ERROR);
return;
}
LOG(Latency, Info, "Session_internal_send_post_write {} {}", cid,
utils::TimeStamp::now().to_uint64());
tracepoint (bts_trace,trace_order,(char*) "Session.internal_send.post_write", 0,cid);
me->last_sent_msg_timestamp = me->now();
me->store.store(msgs);
msgs->set_ts(OutFIX::POST_STORE, utils::TimeStamp::now());
@@ -7,7 +7,7 @@
#include "server/sparkd/orderman/events/NewExecutionReportEvent.h"
#include "server/sparkd/orderman/events/NewSecuritiesEvent.h"
#include "server/sparkd/orderman/orderman_utils/fix_order_codec.h"
#include "server/sparkd/tracing/bts_trace.h"
#include "lib/logging/logging.h"
#include <boost/pool/object_pool.hpp>
@@ -265,8 +265,7 @@ void ExecutionGateway::on_outgoing_fix(
mercury::Update<OutFIXMsgEvent> const &msg) {
if (msg.events)
for (auto const &ev : *(msg.events)) {
LOG(Latency, Info, "Gateway {} {}", ev.cid,
utils::TimeStamp::now().to_uint64());
tracepoint (bts_trace,trace_order,(char*) "on_outgoing_fix", 0,ev.cid);
me->gw.send(ev.cid, ev.msg);
}
}
@@ -65,9 +65,6 @@ class MDSource : public mercury::Actor, public mercury::IPollableActor {
md::HandleReadResult::SUCCESS) {
book._security_key = SecurityKey(handle->key());
corid = handle->sequence();
LOG(Latency, Info, "MDSource {} {}", corid,
utils::TimeStamp::now().to_uint64());
tracepoint (bts_trace,trace_order,(char*) "MDSource", 0, corid);
publish(_book_update, book, corid);
}
@@ -63,11 +63,11 @@ public:
_order_services->send_update(_order->key(),p,q,cid);
}
void crack()
void crack(TickToTradeCorID cid = 0)
{
bts_assert(_order);
bts_assert(_active);
_order_services->send_crack(_order->key());
_order_services->send_crack(_order->key(),cid);
}
void cancel(TickToTradeCorID cid = 0)
@@ -102,7 +102,8 @@ void OrderManager::on_order_recovery(
auto serv_ptr = oi.order_services.get();
me->orders[order.key()] = std::move(oi);
order.on_activate(Price(ostate.price()),
Quantity(ostate.quantity()), *serv_ptr);
Quantity(ostate.quantity()), *serv_ptr,
TickToTradeCorID(0));
}
// signal that we are ready
@@ -133,7 +134,7 @@ void OrderManager::on_execution_report(
auto serv_ptr = oi.order_services.get();
me->orders[order->key()] = std::move(oi);
order->on_activate(report.data->price, report.data->quantity,
*serv_ptr);
*serv_ptr, TickToTradeCorID(0));
}
}
}
@@ -148,7 +149,8 @@ void OrderManager::on_activate_order(
OrderInfo oi{*order, me->services_data};
auto serv_ptr = oi.order_services.get();
me->orders[k] = std::move(oi);
order->on_activate(ev.price, ev.quantity, *serv_ptr);
order->on_activate(ev.price, ev.quantity, *serv_ptr,
ev.correlation_id);
}
}
@@ -158,7 +160,8 @@ void OrderManager::on_update_order(const mercury::Update<UpdateOrderEvent> &m) {
auto k = ev.key();
auto it = me->orders.find(k);
if (it != me->orders.end())
it->second.order->on_update(ev.price, ev.quantity);
it->second.order->on_update(ev.price, ev.quantity,
ev.correlation_id);
else {
LOG(OrderMan, Error,
"Received an update request for an unknown order {}. "
@@ -174,7 +177,7 @@ void OrderManager::on_cancel_order(const mercury::Update<CancelOrderEvent> &m) {
auto k = ev.key();
auto it = me->orders.find(k);
if (it != me->orders.end())
it->second.order->on_cancel();
it->second.order->on_cancel(ev.correlation_id);
else {
LOG(OrderMan, Error,
"Received a cancel request for an unknown order {}. "
@@ -190,7 +193,7 @@ void OrderManager::on_crack_order(const mercury::Update<CrackOrderEvent> &m) {
auto k = ev.key();
auto it = me->orders.find(k);
if (it != me->orders.end())
it->second.order->on_crack();
it->second.order->on_crack(ev.correlation_id);
else {
LOG(OrderMan, Error,
"Received a crack request for an unknown order {}. "
@@ -118,8 +118,8 @@ class OrderServices {
void send_update(OrderKey k, Price p, Quantity q, TickToTradeCorID cid = 0) {
_data.owner.publish(_data.update_order_pub, k, p, q,cid);
}
void send_crack(OrderKey k) {
_data.owner.publish(_data.crack_order_pub, k);
void send_crack(OrderKey k, TickToTradeCorID cid = 0) {
_data.owner.publish(_data.crack_order_pub, k, cid);
}
void send_cancel(OrderKey k, TickToTradeCorID cid = 0) {
_data.owner.publish(_data.cancel_order_pub, k, cid);
@@ -2,23 +2,23 @@
#include <memory>
#include "server/sparkd/orderman/orderman_utils/orderman_common.h"
#include "server/sparkd/mercury/events/Event.h"
#include "server/sparkd/orderman/orderman_utils/orderman_common.h"
namespace bts {
namespace orderman {
class CrackOrderEvent : public mercury::Event<CrackOrderEvent>
{
public:
class CrackOrderEvent : public mercury::Event<CrackOrderEvent> {
public:
using SynopsisPolicy = mercury::NoSynopsis;
CrackOrderEvent(OrderKey k) : k (k) {}
CrackOrderEvent(OrderKey k, TickToTradeCorID cid = 0)
: k(k), correlation_id(cid) {}
// used by ContentSubscription
OrderKey key() const {return k;}
// used by ContentSubscription
OrderKey key() const { return k; }
OrderKey k;
TickToTradeCorID correlation_id;
};
}}
}
}
@@ -88,7 +88,7 @@ void IcebergOrder::on_init_recovered(api::orderman::OrderRecord const &rec,
}
}
void IcebergOrder::on_activate(Price p, Quantity q, OrderServices &services) {
void IcebergOrder::on_activate(Price p, Quantity q, OrderServices &services, TickToTradeCorID) {
bts_assert(!me->services);
me->services = &services;
me->child_builder.activate(services);
@@ -125,7 +125,7 @@ void IcebergOrder::on_activate(Price p, Quantity q, OrderServices &services) {
report_state();
}
void IcebergOrder::on_update(Price p, Quantity q) {
void IcebergOrder::on_update(Price p, Quantity q, TickToTradeCorID) {
switch (me->state.status()) {
case ORDER_STATUS_WORKING:
case ORDER_STATUS_PENDING_WORKING:
@@ -151,9 +151,9 @@ void IcebergOrder::on_update(Price p, Quantity q) {
report_state();
}
void IcebergOrder::on_crack() {}
void IcebergOrder::on_crack(TickToTradeCorID) {}
void IcebergOrder::on_cancel() {
void IcebergOrder::on_cancel(TickToTradeCorID) {
switch (me->state.status()) {
case ORDER_STATUS_WORKING:
LOG(OrderMan, Info, "Canceling Iceberg Order {}", key().value());
@@ -19,10 +19,10 @@ public:
const PreActivationOrderServices&) override;
void on_init_recovered(api::orderman::OrderRecord const&,
const PreActivationOrderServices &) override;
void on_activate(Price,Quantity,OrderServices &) override ;
void on_update(Price , Quantity ) override ;
void on_crack() override ;
void on_cancel() override ;
void on_activate(Price,Quantity,OrderServices &, TickToTradeCorID) override ;
void on_update(Price , Quantity,TickToTradeCorID ) override ;
void on_crack(TickToTradeCorID) override ;
void on_cancel(TickToTradeCorID) override ;
private:
void report_state();
@@ -11,6 +11,7 @@
#include "server/sparkd/orderman/orderman_utils/fix_order_codec.h"
#include "server/sparkd/orderman/orders/PreActivationOrderServices.h"
#include "server/sparkd/securities/ISecurityDB.h"
#include "server/sparkd/tracing/bts_trace.h"
#include "server/sparkd/orderman/actors/order_manager/OrderServices.h"
@@ -263,7 +264,9 @@ void NativeOrder::on_init_from_exe_report(
NativeOrder::~NativeOrder() {}
void NativeOrder::on_activate(Price p, Quantity q,
bts::orderman::OrderServices &services) {
bts::orderman::OrderServices &services,
TickToTradeCorID cid) {
tracepoint (bts_trace,trace_order,(char*) "on_activate", 0,cid);
bts_assert(!me->services);
me->services = &services;
@@ -355,7 +358,7 @@ void NativeOrder::on_activate(Price p, Quantity q,
auto &f = stream.new_msg(jetfix::MessageTypes::NewOrderSingle);
f.append(me->create_encoding);
stream.close();
me->session_services->send_fix_buffer(0, buffer);
me->session_services->send_fix_buffer(cid, buffer);
me->state.set_status(ORDER_STATUS_PENDING_WORKING);
me->state.set_price(p.value());
me->state.set_quantity(q.value());
@@ -422,7 +425,8 @@ void NativeOrder::on_activate(Price p, Quantity q,
report_state();
}
void NativeOrder::on_update(Price p, Quantity q) {
void NativeOrder::on_update(Price p, Quantity q, TickToTradeCorID cid) {
tracepoint (bts_trace,trace_order,(char*) "on_update", 0,cid);
switch (me->state.status()) {
case ORDER_STATUS_WORKING: {
@@ -452,7 +456,7 @@ void NativeOrder::on_update(Price p, Quantity q) {
transition(me->state.status(), msg);
else {
me->state.set_last_msg(msg);
on_cancel();
on_cancel(cid);
}
} else {
@@ -472,7 +476,7 @@ void NativeOrder::on_update(Price p, Quantity q) {
auto &f = stream.new_msg(jetfix::MessageTypes::CancelReplace);
f.append(me->update_encoding);
stream.close();
me->session_services->send_fix_buffer(0, buffer);
me->session_services->send_fix_buffer(cid, buffer);
if (me->state.last_msg().size())
me->state.set_last_msg("");
}
@@ -497,9 +501,9 @@ void NativeOrder::on_update(Price p, Quantity q) {
report_state();
}
void NativeOrder::on_crack() {}
void NativeOrder::on_crack(TickToTradeCorID) {}
void NativeOrder::on_cancel() {
void NativeOrder::on_cancel(TickToTradeCorID cid) {
switch (me->state.status()) {
case ORDER_STATUS_WORKING: {
@@ -512,7 +516,7 @@ void NativeOrder::on_cancel() {
auto &f = stream.new_msg(jetfix::MessageTypes::Cancel);
f.append(me->cancel_encoding);
stream.close();
me->session_services->send_fix_buffer(0, buffer);
me->session_services->send_fix_buffer(cid, buffer);
break;
}
@@ -23,10 +23,10 @@ public:
const PreActivationOrderServices&) override;
void on_init_recovered(api::orderman::OrderRecord const&,
const PreActivationOrderServices &) override;
void on_activate(Price,Quantity,OrderServices &) override ;
void on_update(Price , Quantity ) override ;
void on_crack() override ;
void on_cancel() override ;
void on_activate(Price,Quantity,OrderServices &, TickToTradeCorID) override ;
void on_update(Price , Quantity,TickToTradeCorID ) override ;
void on_crack(TickToTradeCorID) override ;
void on_cancel(TickToTradeCorID) override ;
void on_init_from_exe_report(ExecutionReport const&,const PreActivationOrderServices &);
private:
+27 -19
View File
@@ -1,18 +1,25 @@
#pragma once
#include <memory>
#include "server/sparkd/orderman/orderman_utils/orderman_common.h"
#include <memory>
// fwd
namespace bts {
namespace securities {class ISecurityDB;}
namespace orderman {class IOrderFactory;}
namespace securities {
class ISecurityDB;
}
namespace orderman {
class IOrderFactory;
}
namespace api {
namespace orderman {
class OrderDefinition;
class OrderRecord;
class OrderState;
}}}
}
}
}
// end fwd
namespace bts {
namespace orderman {
@@ -20,32 +27,33 @@ namespace orderman {
class PreActivationOrderServices;
class OrderServices;
class Order
{
public:
class Order {
public:
virtual ~Order();
OrderKey key() const {return _key;}
OrderKey parent_key() const {return _parent_key;}
OrderKey key() const { return _key; }
OrderKey parent_key() const { return _parent_key; }
virtual api::orderman::OrderDefinition const&definition() const = 0;
virtual api::orderman::OrderDefinition const &definition() const = 0;
// construction - can be slow
virtual void on_init_new(api::orderman::OrderDefinition const&, const PreActivationOrderServices&) = 0;
virtual void on_init_recovered(api::orderman::OrderRecord const&, const PreActivationOrderServices &) = 0;
virtual void on_init_new(api::orderman::OrderDefinition const &,
const PreActivationOrderServices &) = 0;
virtual void on_init_recovered(api::orderman::OrderRecord const &,
const PreActivationOrderServices &) = 0;
// activation - cannot be slow
virtual void on_activate(Price, Quantity,OrderServices &) = 0;
virtual void on_activate(Price, Quantity, OrderServices &, TickToTradeCorID) = 0;
// order is running, maintenance
virtual void on_update(Price , Quantity ) = 0;
virtual void on_crack() = 0;
virtual void on_cancel() = 0;
virtual void on_update(Price, Quantity, TickToTradeCorID) = 0;
virtual void on_crack(TickToTradeCorID) = 0;
virtual void on_cancel(TickToTradeCorID) = 0;
private:
private:
OrderKey _key;
OrderKey _parent_key;
friend class OrderFactory;
};
}}
}
}
@@ -83,7 +83,7 @@ void TimeBoxOrder::on_init_recovered(api::orderman::OrderRecord const &rec,
}
}
void TimeBoxOrder::on_activate(Price p, Quantity q, OrderServices &services) {
void TimeBoxOrder::on_activate(Price p, Quantity q, OrderServices &services,TickToTradeCorID) {
bts_assert(!me->services);
me->services = &services;
me->child_builder.activate(services);
@@ -121,7 +121,7 @@ void TimeBoxOrder::on_activate(Price p, Quantity q, OrderServices &services) {
report_state();
}
void TimeBoxOrder::on_update(Price p, Quantity q) {
void TimeBoxOrder::on_update(Price p, Quantity q,TickToTradeCorID) {
LOG(OrderMan, Info, "Updating TimeBox Order {}", key().value());
switch (me->state.status()) {
@@ -181,9 +181,9 @@ void TimeBoxOrder::on_update(Price p, Quantity q) {
report_state();
}
void TimeBoxOrder::on_crack() {}
void TimeBoxOrder::on_crack(TickToTradeCorID) {}
void TimeBoxOrder::on_cancel() {
void TimeBoxOrder::on_cancel(TickToTradeCorID) {
LOG(OrderMan, Info, "Canceling TimeBox Order {}", key().value());
switch (me->state.status()) {
@@ -19,10 +19,10 @@ public:
const PreActivationOrderServices&) override;
void on_init_recovered(api::orderman::OrderRecord const&,
const PreActivationOrderServices &) override;
void on_activate(Price,Quantity,OrderServices &) override ;
void on_update(Price , Quantity ) override ;
void on_crack() override ;
void on_cancel() override ;
void on_activate(Price,Quantity,OrderServices &, TickToTradeCorID) override ;
void on_update(Price , Quantity,TickToTradeCorID ) override ;
void on_crack(TickToTradeCorID) override ;
void on_cancel(TickToTradeCorID) override ;
private:
void report_state();
@@ -168,7 +168,7 @@ void BookAlgo::on_init_recovered(const api::orderman::OrderRecord& rec,
}
}
void BookAlgo::on_activate(Price p, Quantity q, OrderServices& services)
void BookAlgo::on_activate(Price p, Quantity q, OrderServices& services,TickToTradeCorID)
{
bts_assert(!me->services);
me->services = &services;
@@ -210,7 +210,7 @@ void BookAlgo::on_activate(Price p, Quantity q, OrderServices& services)
report_state();
}
void BookAlgo::on_update(Price p, Quantity q)
void BookAlgo::on_update(Price p, Quantity q,TickToTradeCorID)
{
LOG(OrderMan, Info, "Updating BookAlgo {}", key().value());
switch (this_state().status())
@@ -267,9 +267,9 @@ void BookAlgo::on_update(Price p, Quantity q)
report_state();
}
void BookAlgo::on_crack() {}
void BookAlgo::on_crack(TickToTradeCorID) {}
void BookAlgo::on_cancel()
void BookAlgo::on_cancel(TickToTradeCorID)
{
LOG(OrderMan, Info, "Canceling BookAlgo Order {}", key().value());
@@ -24,10 +24,10 @@ public:
const PreActivationOrderServices&) override;
void on_init_recovered(const api::orderman::OrderRecord&,
const PreActivationOrderServices &) override;
void on_activate(Price, Quantity, OrderServices&) override;
void on_update(Price, Quantity) override;
void on_crack() override;
void on_cancel() override;
void on_activate(Price,Quantity,OrderServices &, TickToTradeCorID) override ;
void on_update(Price , Quantity,TickToTradeCorID ) override ;
void on_crack(TickToTradeCorID) override ;
void on_cancel(TickToTradeCorID) override ;
protected:
virtual void setup_child(const api::orderman::OrderDefinition& parent, const PreActivationOrderServices&,
@@ -43,25 +43,25 @@ void SpreaderOrder::on_init_recovered(const bts::api::orderman::OrderRecord& ord
_report_state();
}
void SpreaderOrder::on_activate(Price price, Quantity quantity,
OrderServices& services){
OrderServices& services, TickToTradeCorID){
if (!_active) return;
SpreaderOrderServices spreader_order_services (&services);
_on_activate(price, quantity, spreader_order_services);
_report_state();
}
void SpreaderOrder::on_update(Price price, Quantity quantity){
void SpreaderOrder::on_update(Price price, Quantity quantity,TickToTradeCorID){
if (!_active) return;
LOG(OrderMan, Info, "SpreaderOrder.on_update key: {} price: {} quantity: {}", key().value(), price.value(), quantity.value());
_state_worker->on_update(price, quantity);
_report_state();
}
void SpreaderOrder::on_cancel(){
void SpreaderOrder::on_cancel(TickToTradeCorID){
if (!_active) return;
LOG(OrderMan, Info, "SpreaderOrder.on_cancel key: {}", key().value());
_state_worker->on_cancel();
_report_state();
}
void SpreaderOrder::on_crack(){
void SpreaderOrder::on_crack(TickToTradeCorID){
if (!_active) return;
LOG(OrderMan, Info, "SpreaderOrder.on_crack key: {}", key().value());
_state_worker->on_crack();
@@ -314,4 +314,4 @@ bts::api::orderman::OrderStatus SpreaderOrder::_get_order_status () const{
return bts::api::orderman::OrderStatus::ORDER_STATUS_INACTIVE;
}
}
}}
}}
@@ -91,15 +91,15 @@ public:
const PreActivationOrderServices&) override;
// this is in the critical path, orders can be submitted now
// (this is only called once and after the on_init_new)
void on_activate(Price, Quantity, OrderServices&) override;
void on_activate(Price, Quantity, OrderServices&,TickToTradeCorID) override;
// called when the user (or a higher level order)
// updates the order's price or quantity
void on_update(Price, Quantity) override;
void on_update(Price, Quantity,TickToTradeCorID) override;
// called when the user (or higher level order) cancels an order
void on_cancel() override;
void on_cancel(TickToTradeCorID) override;
// crack means to let the lower level orders lose from the higher
// level order and cancel the higher level order
void on_crack() override;
void on_crack(TickToTradeCorID) override;
// ISpreaderManager ////////////////////
////////////////////////////////////////
public:
@@ -230,4 +230,4 @@ public:
void test_only_on_activate(Price price, Quantity quantity, SpreaderOrderServices& order_services) {_on_activate(price, quantity, order_services);}
void test_only_on_time (TimeStamp){}
};
}}
}}
@@ -144,8 +144,12 @@ private:
bool _target_reached(){
return _price_quantity_state.target_reached();
}
void _place_order (Price price, Quantity quantity) {_child_order_state.place_order(price, quantity);}
void _modify_order (Price price, Quantity quantity) {_child_order_state.modify_order(price, quantity);}
void _place_order (Price price, Quantity quantity, TickToTradeCorID cid = 0) {
_child_order_state.place_order(price, quantity, cid);
}
void _modify_order (Price price, Quantity quantity, TickToTradeCorID cid = 0) {
_child_order_state.modify_order(price, quantity, cid);
}
void _cancel_order () {_child_order_state.cancel_order();}
// this updates the hedge reduction in _price_quantity_state
void _incorporate_other_leg_fill (size_t leg_index, Quantity filled_quantity);
@@ -114,7 +114,8 @@ public:
}
// order actions ////////////////////
/////////////////////////////////////
void place_order(Price price, Quantity quantity){
void place_order(Price price, Quantity quantity,
TickToTradeCorID cid = 0){
_out_price = price;
_out_quantity = quantity;
bts_assert(_n_place_orders == 0);
@@ -122,16 +123,17 @@ public:
LOG(OrderMan, Info, "SpreaderChildOrderState::place_order order_key: {} is_quoting: {} sec_key: {} live: {} price: {} quantity: {}",
order_key().value(), _is_quoting, _sec_key, _is_live, price.value(), quantity.value());
if (_is_live)
_child_order.activate(price, quantity);
_child_order.activate(price, quantity, cid);
}
void modify_order(Price price, Quantity quantity){
void modify_order(Price price, Quantity quantity,
TickToTradeCorID cid = 0){
_out_price = price;
_out_quantity = quantity;
_n_modify_orders++;
LOG(OrderMan, Info, "SpreaderChildOrderState::modify_order order_key: {} is_quoting: {} sec_key: {} live: {} price: {} quantity: {} mod_no: {}",
order_key().value(), _is_quoting, _sec_key, _is_live, price.value(), quantity.value(), _n_modify_orders);
if (_is_live)
_child_order.update(price, quantity);
_child_order.update(price, quantity, cid);
}
void cancel_order(){
bts_assert(_n_cancel_orders == 0);
@@ -175,7 +175,7 @@ public:
if (price_change_ticks != 0){
bool price_increasing = price_change_ticks > 0;
uint32_t abs_price_change_ticks = static_cast<uint32_t>(std::abs(price_change_ticks));
LOG(OrderMan, Info, "SpreaderUtils::reprice_quote_mute_zone current_price: {} new_price: {} price_change_ticks: {} abs_price_change_ticks: {} inside_limit_ticks: {} outside_limit_ticks: {}",
LOG(OrderMan, Diag, "SpreaderUtils::reprice_quote_mute_zone current_price: {} new_price: {} price_change_ticks: {} abs_price_change_ticks: {} inside_limit_ticks: {} outside_limit_ticks: {}",
current_price, new_price, price_change_ticks, abs_price_change_ticks, quote_mute_zone.inside_ticks(), quote_mute_zone.outside_ticks());
if (quote_side == api::SIDE_BUY){
if (price_increasing) // moving toward inside market
@@ -7,8 +7,10 @@
namespace bts{
namespace orderman{
QuoterState QuoterEndStateWorker::state () const {return QuoterState::END;}
void QuoterEndStateWorker::on_transition (){
QuoterState QuoterEndStateWorker::state () const {
return QuoterState::END;
}
void QuoterEndStateWorker::on_transition (){
bool is_final = _quoter->_is_permenantly_cancelled || _quoter->_price_quantity_state.target_reached ();
if (!is_final){
// getting new order
@@ -23,7 +23,8 @@ void QuoterWaitingForFirstAckWorker::on_order_update (const SpreaderChildOrderSt
}
void QuoterWaitingForFirstAckWorker::on_book (bts::orderman::TickToTradeCorID,
size_t,
const bts::orderman::Book&){
const bts::orderman::Book&){
_analyze_and_act();
}
void QuoterWaitingForFirstAckWorker::cancel(){
_quoter->_transform_to_WAITING_FOR_FIRST_ACK_CANCELLED ();
@@ -46,5 +47,11 @@ void QuoterWaitingForFirstAckWorker::update_spreader_order (Price price,
void QuoterWaitingForFirstAckWorker::_analyze_and_act (){
if (_quoter->_price_quantity_state.target_reached())
_quoter->_transform_to_WAITING_FOR_FIRST_ACK_CANCELLED();
else{
Price computed_price; Quantity computed_quantity;
_quoter->_compute_price_quantity (computed_price, computed_quantity);
if (computed_quantity.value() == 0)
_quoter->_transform_to_WAITING_FOR_FIRST_ACK_CANCELLED();
}
}
}}
@@ -42,7 +42,7 @@ void QuoterWaitingForSizeStateWorker::update_spreader_order (Price price, Quanti
_quoter->_price_quantity_state.update_target_price_quantity (price, quantity);
_longpath_analyze_and_act (orderman::NullTickToTradeCorID);
}
void QuoterWaitingForSizeStateWorker::_longpath_analyze_and_act (orderman::TickToTradeCorID){
void QuoterWaitingForSizeStateWorker::_longpath_analyze_and_act (orderman::TickToTradeCorID cid){
if (_quoter->_price_quantity_state.target_reached()){
LOG(OrderMan, Info, "QuoterWaitingForSizeStateWorker key: {}, target reached, transforming to end", _quoter->_key().value());
_quoter->_transform_to_END ();
@@ -54,7 +54,7 @@ void QuoterWaitingForSizeStateWorker::_longpath_analyze_and_act (orderman::TickT
_quoter->_commit_drivers ();
LOG(OrderMan, Info, "QuoterWaitingForSizeStateWorker sending order key: {} price: {} quantity: {}", _quoter->_key(), out_price, out_quantity);
// this is the only place where a quoter order is entered
_quoter->_place_order(out_price, out_quantity);
_quoter->_place_order(out_price, out_quantity, cid);
_quoter->_transform_to_WAITING_FOR_FIRST_ACK ();
}
}
@@ -11,6 +11,13 @@ namespace orderman{
QuoterState QuoterWorkingStateWorker::state () const {
return QuoterState::WORKING;
}
void QuoterWorkingStateWorker::on_transition (){
// since from the time the order was entered and we had been
// waiting for the ack, things could have changed (namely
// fills in other legs, books, order qty change), hence
// we analyze and potentially modify/cxl immediatly
_longpath_analyze_and_act (orderman::NullTickToTradeCorID);
}
void QuoterWorkingStateWorker::one_time_activate (Price,
Quantity){
bts_assert_msg (false, "QuoterWorkingStateWorker::one_time_activate is an illegal operation");
@@ -20,7 +27,7 @@ void QuoterWorkingStateWorker::on_order_update (const SpreaderChildOrderState& u
if (u.terminal_status())
_quoter->_transform_to_END ();
else
_longpath_analyze_and_act (orderman::NullTickToTradeCorID);
_longpath_analyze_and_act (orderman::NullTickToTradeCorID);
}
void QuoterWorkingStateWorker::on_book (bts::orderman::TickToTradeCorID corid,
size_t,
@@ -82,12 +89,13 @@ void QuoterWorkingStateWorker::_longpath_analyze_and_act (bts::orderman::TickToT
}
}
}
void QuoterWorkingStateWorker::_modify_order (orderman::TickToTradeCorID , Price price, Quantity quantity){
void QuoterWorkingStateWorker::_modify_order (orderman::TickToTradeCorID cid, Price price, Quantity quantity){
bool same_price_qty = _quoter->_price_quantity_state.out_quantity() == quantity &&
bts::securities::test_price_equality(_quoter->_price_quantity_state.out_price().value(), price.value(), _quoter->_this_leg_data.tick_size());
bts::securities::test_price_equality(_quoter->_price_quantity_state.out_price().value(),
price.value(), _quoter->_this_leg_data.tick_size());
if (!same_price_qty){
_quoter->_commit_drivers ();
_quoter->_modify_order(price, quantity);
_quoter->_modify_order(price, quantity, cid);
}
}
}}
@@ -20,7 +20,7 @@ public:
QuoterWorkingStateWorker (SingleLegQuoter* quoter) :_quoter(quoter) {}
QuoterState state () const override;
const std::string state_text () const override {return "WORKING";}
virtual void on_transition () override {}
virtual void on_transition () override;
void one_time_activate (Price, Quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (bts::orderman::TickToTradeCorID corid, size_t leg_id, const bts::orderman::Book& book) override;
@@ -747,7 +747,7 @@ TEST_CASE ("quoter_WAITING_FOR_FIRST_ACK", "[spreader]")
SpreaderChildOrderState& u = bookeeping_data.get_leg_data(1).order_update_message();
on_order_update (u, api::orderman::OrderStatus::ORDER_STATUS_WORKING, Quantity (70), Price (2000));
quoter.update_order_status(u);
verify_complete_quoter_state (quoter, QuoterState::WORKING, false, spreader_price, spreader_quantity, Quantity(70), Quantity(0), Price(2000.75), Quantity(100), Quantity (30), false);
verify_complete_quoter_state (quoter, QuoterState::WORKING, false, spreader_price, spreader_quantity, Quantity(70), Quantity(0), Price(1999.75), Quantity(100), Quantity (30), false);
LOG(OrderMan, Diag, "quoter_WAITING_FOR_FIRT_ACK.update_order_status_non_terminal");
}
SECTION("3. update_order_status_terminal")
@@ -763,7 +763,7 @@ TEST_CASE ("quoter_WAITING_FOR_FIRST_ACK", "[spreader]")
// orders are not updated in this state
double prices[] = {0, 0, 0, 0, 0}; uint16_t sizes[] = {0, 0, 0, 0, 0};
fire_book_update (prices, sizes, api::Side::SIDE_SELL, 0, sm, quoter);
verify_complete_quoter_state (quoter, QuoterState::WAITING_FOR_FIRST_ACK, false, spreader_price, spreader_quantity, Quantity(0), Quantity(0), Price(2000.75), Quantity(100), Quantity (100), false);
verify_complete_quoter_state (quoter, QuoterState::WAITING_FOR_FIRST_ACK_CANCELLED, false, spreader_price, spreader_quantity, Quantity(0), Quantity(0), Price(2000.75), Quantity(100), Quantity (100), false);
LOG(OrderMan, Diag, "quoter_WAITING_FOR_FIRT_ACK.on_book");
}
SECTION("4. cancel_order")
@@ -1621,7 +1621,7 @@ TEST_CASE ("spreader_START", "[spreader]")
}
SECTION("5. on_cancel")
{
spreader.on_cancel();
spreader.on_cancel(TickToTradeCorID(0));
REQUIRE(spreader.test_only_func_spreader_state() == SpreaderState::END);
LOG(OrderMan, Diag, "spreader_START.on_cancel");
}
@@ -1733,7 +1733,7 @@ TEST_CASE ("spreader_WORKING", "[spreader]")
// be as is
spreader_price = Price (0);
spreader_quantity = Quantity (200);
spreader.on_update (spreader_price, spreader_quantity);
spreader.on_update (spreader_price, spreader_quantity,TickToTradeCorID(0));
verify_basic_spreader_state (spreader, SpreaderState::WORKING, spreader_price, spreader_quantity);
verify_complete_quoter_state (leg_data_1.quoter(), QuoterState::WORKING, false, spreader_price, spreader_quantity, Quantity (30), Quantity(55), Price(1998), Quantity(130), Quantity(115), false);
verify_complete_quoter_state (leg_data_2.quoter(), QuoterState::WORKING, false, spreader_price, spreader_quantity, Quantity (55), Quantity(30), Price(2004), Quantity(165), Quantity(115), false);
@@ -1743,7 +1743,7 @@ TEST_CASE ("spreader_WORKING", "[spreader]")
}
SECTION("5. on_cancel")
{
spreader.on_cancel();
spreader.on_cancel(TickToTradeCorID(0));
verify_basic_spreader_state (spreader, SpreaderState::WAITING_FOR_CANCEL_ALL, spreader_price, spreader_quantity);
generic_validate_quoters (QuoterState::WAITING_FOR_CANCEL_ACK, true);
generic_validate_hedgers (HedgerState::WAITING_FOR_CANCEL_ACK);
@@ -2038,7 +2038,7 @@ TEST_CASE ("spreader_WAITING_FOR_CANCEL_ACK", "[spreader]")
// now cancel the spreader
bts::TimeStamp cancel_timestamp = std::chrono::system_clock::now();
spreader.test_only_on_time (cancel_timestamp);
spreader.on_cancel ();
spreader.on_cancel (TickToTradeCorID(0));
auto validate_state = [&]() -> void
{
verify_basic_spreader_state (spreader, SpreaderState::WAITING_FOR_CANCEL_ALL, spreader_price, spreader_quantity);
@@ -2061,7 +2061,7 @@ TEST_CASE ("spreader_WAITING_FOR_CANCEL_ACK", "[spreader]")
}
SECTION("4. on_update")
{
spreader.on_update (Price(-0.05), Quantity(200));
spreader.on_update (Price(-0.05), Quantity(200),TickToTradeCorID(0));
validate_state();
// order changes dont go through
validate_state();
@@ -2069,7 +2069,7 @@ TEST_CASE ("spreader_WAITING_FOR_CANCEL_ACK", "[spreader]")
}
SECTION("5. on_cancel")
{
spreader.on_cancel();
spreader.on_cancel(TickToTradeCorID(0));
// already in cancel state, no change
validate_state();
LOG(OrderMan, Diag, "spreader_WAITING_FOR_CANCEL_ACK.on_cancel");
@@ -2377,4 +2377,4 @@ TEST_CASE ("scratch_pad", "[spreader]"){
REQUIRE(rvuser_1.rv.i==100);
}
}}
}}
+7
View File
@@ -51,6 +51,13 @@ input[type=text], input[type=password]
input[type=text].login-input, input[type=password].login-input
width: 100%
.table-bordered
border: 1px solid $border
thead th
background-color: $brand_primary
color: $white
font-weight: normal
.btstable td
vertical-align: middle
+1 -1
View File
@@ -38,7 +38,7 @@ module SecurityScope =
let empty = {
exchange = Venue.GLBX
securityType = SecurityType.FUTURE
securitySymbol = ""
securitySymbol = "*"
securityId = 0u
}
-1
View File
@@ -26,7 +26,6 @@ let init (context:ServiceContext.ServiceContext) =
}, Access.getAdminData admin UpdateAdminData NoAdminData
let existingSelection (scratch:BTSAccount) (previousScratch:BTSAccount) (data:AdminData) =
printf "%O" data.accounts
List.choose id [
data.accounts |> Array.tryFind (fun a -> a.name = scratch.name)
data.accounts |> Array.tryFind (fun a -> a.name = previousScratch.name)
+6 -6
View File
@@ -195,14 +195,14 @@ let clipLimitsView model dispatch =
}
]
let emptyLimit = {
security = Access.SecurityScope.empty
security = { SecurityScope.empty with securitySymbol = model.AllValue }
clipSize = 0u
}
let addRow _ = Array.append model.scratch.securityClipLimits.limit [| emptyLimit |] |> (ClipLimits >> dispatch)
div []
[
TableControl.createTableWithStyle (Some headerRow) rws [Width "100%"; Border "1px solid lightgray"]
TableControl.createTableWithStyle (Some headerRow) rws "table-bordered" [Width "100%"]
span [ClassName "is-pulled-right"] [ Button.button "Add" "contrast-button" "plus" Button.Enabled addRow ]
span [ClassName "is-clearfix"][]
]
@@ -311,7 +311,7 @@ let productLimits model dispatch =
div []
[
h1 [ ClassName "is-size-4" ][str "Product Limits"]//; span [ClassName "is-size-7 has-text-grey-light"][ str " This is a limit for products"] ]
TableControl.createTableWithStyle (Some headerRow) rws [Width "100%"; Border "1px solid lightgray"]
TableControl.createTableWithStyle (Some headerRow) rws "table-bordered" [Width "100%"]
span [ClassName "is-pulled-right"] [ Button.button "Add" "contrast-button" "plus" Button.Enabled addRow ]
span [ClassName "is-clearfix"][]
]
@@ -437,7 +437,7 @@ let securityLimits model dispatch =
}
]
let emptyLimit = {
security = SecurityScope.empty
security = { SecurityScope.empty with securitySymbol = model.AllValue }
longPositionLimit = 0u
shortPositionLimit = 0u
netPositionLimit = 0u
@@ -447,7 +447,7 @@ let securityLimits model dispatch =
div []
[
h1 [ ClassName "is-size-4" ][str "Security Limits"]//; span [ClassName "is-size-7 has-text-grey-light"][ str " This is a limit for Securities"]]
TableControl.createTableWithStyle (Some headerRow) rws [Width "100%"; Border "1px solid lightgray"]
TableControl.createTableWithStyle (Some headerRow) rws "table-bordered" [Width "100%"]
span [ClassName "is-pulled-right"] [ Button.button "Add" "contrast-button" "plus" Button.Enabled addRow ]
span [ClassName "is-clearfix"][]
@@ -580,7 +580,7 @@ let root (model:Model) dispatch =
| None -> ignore
match model.adminData with
| None -> div[][str "Loading user list..."]
| None -> div[][str "Loading account list..."]
| Some data ->
div [ClassName "columns"] [
accountsMenu data.accounts (selectedAccount model) dispatch
+15 -12
View File
@@ -16,26 +16,29 @@ type row = {
header:string option
}
let createCell (c:cell) =
match c.isHeader with
let createCell (inHeaderRow:bool) (c:cell) =
match c.isHeader || inHeaderRow with
| false -> td [ ClassName c.className; ColSpan (float c.colSpan) ] [ c.content ]
| true -> th [ ClassName c.className; ColSpan (float c.colSpan) ] [ c.content ]
let createRow (r:row) =
match r.header with
| None -> tr [ ClassName r.className ] (List.map<cell, ReactElement> createCell r.cells)
| Some h -> tr [ ClassName r.className ] (th [] [str h] :: (List.map<cell, ReactElement> createCell r.cells))
let createRow (isHeaderRow:bool) (r:row) =
match r.header, isHeaderRow with
| None, false -> tr [ ClassName r.className ] (List.map<cell, ReactElement> (createCell isHeaderRow) r.cells)
| None, true -> tr [ ClassName r.className ] (List.map<cell, ReactElement> (createCell isHeaderRow) r.cells)
| Some h, true -> tr [ ClassName r.className ] (th [] [str h] :: (List.map<cell, ReactElement> (createCell isHeaderRow) r.cells ))
| Some h, false -> tr [ ClassName r.className ] (th [] [str h] :: (List.map<cell, ReactElement> (createCell isHeaderRow) r.cells ))
let createTableWithStyle (headers:row option) (rl:row list) styles =
let createTableWithStyle (headers:row option) (rl:row list) className styles =
let rws = List.map<row,ReactElement> (createRow false) rl
let tbl = match headers with
| Some h ->
[
thead [] [ createRow h ]
tbody [] (List.map<row,ReactElement> createRow rl)
thead [] [ createRow true h]
tbody [] rws
]
| None ->
[ tbody [] (List.map<row,ReactElement> createRow rl) ]
table [ ClassName "table is-narrow btstable"; Style styles ] tbl
[ tbody [] rws ]
table [ ClassName (sprintf "table is-narrow btstable %s" className); Style styles ] tbl
let createTable (headers:row option) (rl:row list) = createTableWithStyle headers rl []
let createTable (headers:row option) (rl:row list) = createTableWithStyle headers rl "" []
+5 -5
View File
@@ -64,29 +64,29 @@ let root model dispatch =
figure [ ClassName "avatar" ] [
img [ Src sparkImg ]
]
h1 [ ClassName "is-size-1" ] [str "Spark"]
h1 [ Style [ Float "right"; FontSize "1.2rem"; Margin "1.6rem .5rem 0 -1rem"; Transform "rotate(90deg)"] ] [ str "beta" ]
h1 [ ClassName "is-size-1" ] [ span [] [str "Spark AdminUI"]]
]
form [ OnSubmit (fun e ->
e.preventDefault()
dispatch Submit) ] [
div [ ClassName "field" ] [
div [ ClassName "control" ] [
input [ ClassName "input is-large login-input"
input [ ClassName "input login-input"
Type "text"
OnChange (handler Username)
AutoFocus true
Placeholder "Username" ] ] ]
div [ ClassName "field" ] [
div [ ClassName "control" ] [
input [ ClassName "input is-large login-input"
input [ ClassName "input login-input"
Type "password"
OnChange (handler Password)
Placeholder "Password" ] ] ]
div [ Style [Color "red"] ] [str model.error]
br []
button [OnClick (fun _ -> dispatch Submit)
ClassName "button is-block is-primary is-large is-fullwidth" ] [
ClassName "button is-block is-primary is-fullwidth" ] [
str "Login" ] ] ]
] ] ] ]
+1 -1
View File
@@ -101,7 +101,7 @@ let accountsTabContent (model:Model) (dispatch:Msg->Unit) =
div []
[
TableControl.createTable (Some headerRow) rows
TableControl.createTableWithStyle (Some headerRow) rows "table-bordered" []
]
let mdEntitlementsTabContent (model:Model) (dispatch:Msg->Unit) =
+3 -3
View File
@@ -1,8 +1,8 @@
This test verifies that clip limits are followed, and rule presedence works correctly
This test verifies that clip limits are followed, and rule precedence works correctly
1. Pick a future, lets say ESU8.
2. In the risk admin, go to accounts and select the default account for your user (let say ACC A1).
2. In the AdminUI, go to accounts and select the default account for your user (let say ACC A1).
Go to Position Limits and enter large values (for both security and product level), so that
position limits are bypassed.
@@ -21,4 +21,4 @@ Enter a Clip Size of 10. Make sure orders > 10 are rejected and < 10 are allowed
10. Verify that ESU8 is still controlled by a clip size of 10.
11. Enter a future spread order. It should be rejected since we dont have any clip limits for futures.
11. Enter a future spread order. It should be rejected since we don't have any clip limits for futures.
+5 -10
View File
@@ -17,22 +17,17 @@ Prerequisites
User settings
-------------
3. Navigate to http://sparkvm:8000 (or wherever your sparkd resides), Users tab
4. Btween bts and bts_2 users, verify that have distinct operator ids
4. Btween bts and bts_2 users, verify that have distinct operator ids (Order Routing tab)
5. In another ssh session on your server, let's tail the sim fix log for orders
tail -f ~/sparkdata/data/jetfix/sim/current/fix | grep --line-buffered 35=D | tr '\001' '|'
6. Open up a client, login as bts, pick your favorite symbol and submit an order
7. Your tail should show the fix from the order. Scan the line for 50={operator id}. The operator id found should match the value from the web ui.
7. Your tail should show the fix from the order. Scan the line for 50={operator id}. The operator id found should match the value from the AdminUI.
8. Change your user's operator's id, submit a new order, and verify the new value is being sent out on the tag 50
9. Relaunch the gui and login as bts_2
10. Submit an order and verify the tag 50 matches what is specified in the web ui
10. Submit an order and verify the tag 50 matches what is specified in the AdminUI
Account settings
-----------------
11. Within the web UI, switch over to Accounts and choose an account in which your users can trade (ACC A1), then switch to the exchange settings tab
12. Place an order and check that the CTI Code, Origin, and Clearing Accont match what is specified in the web ui
11. Within the AdminUI, switch over to Accounts and choose an account in which your users can trade (ACC A1), then switch to the exchange settings tab
12. Place an order and check that the CTI Code, Origin, and Clearing Account match what is specified in the AdminUI
13. Change the values, place another order, and verify the new values are being sent
@@ -1,13 +1,13 @@
This test verifies that product position limits are enforced correctly. (Position limits are
enforced at both the security and account level)
0. Clear up your orders and fills so we dont have any lingering positions
0. Clear up your orders and fills so we don't have any lingering positions
(run rm -r orders and rm -r fills from /sparkdata/data/databases). Restart your sparkd
1. Pick 2 futures, lets say SIU8 and SIZ8
2. In the risk admin, select the default account for your user (lets say ACC A1)
and enter big clip limits so that clip limits dont interfare with this test.
2. In the AdminUI, select the default account for your user (lets say ACC A1)
and enter big clip limits so that clip limits don't interfere with this test.
3. Go to the Position limits and remove all entries at both the product and security level
@@ -1,24 +1,24 @@
This test verifies that security position limits are enforced correctly. (Position limits are
enforced at both the security and account level)
0. Clear up your orders and fills so we dont have any lingering positions
0. Clear up your orders and fills so we don't have any lingering positions
(run rm -r orders and rm -r fills from /sparkdata/data/databases). Restart your sparkd
1. Pick a future, lets say ESU8 and an account, lets say ACC A1.
2. In the risk admin, select the default account for your user, and enter big clip limits so that
clip limits dont interfare with this test.
2. In the AdminUI, select the default account for your user, and enter big clip limits so that
clip limits don't interfere with this test.
3. Go to the Position limits and remove all entries at both the product and security level
4. Enter an ESU8 order. It should be rejected. Make sure the rejection message makes sense
5. Now enter a product level rule for GLBX, Future, ES, 1,000,000, 1,000,000 (to bypass it),
5. Now enter a product level rule for GLBX, Future, ES, 1,000,000, 1,000,000 (to bypass it),
and a security level rule GLBX, Future, ES, 50, 100
6. Enter a 10 lot. This brings our 'position' to 10 (where 'positions' = fills + working orders).
Enter more orders to get it to 50. Now try to get past 50 and you should be stopped with a clear message.
Dont cancel these yet.
don't cancel these yet.
6. Now start selling 10 lots. Since we are already long 50, and our short limit is 100, we can go all
the way to 150 (net 100 short), but not beyond that. Verify that.
@@ -26,9 +26,9 @@ the way to 150 (net 100 short), but not beyond that. Verify that.
8. Cancel all your buy orders. Cancel some of your sell orders to get the net short position to 50.
Start selling again, and make sure you are stopped at 100.
9. Try another future, lets say SIU8. Since we dont have a position rule for it, it should fail.
9. Try another future, lets say SIU8. Since we don't have a position rule for it, it should fail.
10. Enter a new rule for the product (and use * for the symbol) and enter 10 for the long and short limits.
10. Enter a new rule for the product (and use All for the symbol) and enter 10 for the long and short limits.
11. Now enter a 1 lot SIU8 again. Keep buying more and make sure you are stopped at the long limit of 10.
@@ -5,8 +5,8 @@ ii. leg limits are checked when entering spread orders
i:
1. Pick a 2 legged spread (lets say SIU8-SIZ8). Set the clip limits high so that they dont interfare.
Set the product position limits high as well so they dont interfare either.
1. Pick a 2 legged spread (lets say SIU8-SIZ8). Set the clip limits high so that they don't interfere.
Set the product position limits high as well so they don't interfere either.
2. For the security limits (which is what we will be testing), we want Max Long and Max Short of 20 and 30
for the SI futures and 100 and 110 for the SI spreads respectively.
@@ -26,4 +26,4 @@ ii:
6. Enter a 15 lot buy for SIU8. Any spread buy order of > 5 should be rejected, since this will violate the 20 long limit.
8. Enter a 20 sell for SIZ8. Any spread buy order of > 10 should be rejected since it will
violate the 30 short limit.
violate the 30 short limit.
@@ -1,19 +1,19 @@
This test verifies that users and accounts can be de activated which
This test verifies that users and accounts can be de activated which
1. Pick a future, lets say SIU8.
2. Enter an order and verify that it goes in.
3. In the risk admin, select your logged in user, uncheck "Is Active" and save.
3. In the AdminUI, select your logged in user, uncheck "Is Active" and save.
4. Now enter an order again, verify that its rejected and that the rejection message
makes sense.
5. Do the same for the account (ie in the risk admin, go to the account selected in the
5. Do the same for the account (i.e. in the AdminUI, go to the account selected in the
ladder dropdown and uncheck "Is Active").
6. Verify that orders going into that account are rejected and that the rejection message
is clear.
7. Verify that the account's "Is Active" is correctly applying to that account only, ie you
can still enter orders into other accounts
7. Verify that the account's "Is Active" is correctly applying to that account only, i.e. you
can still enter orders into other accounts
@@ -1,11 +1,11 @@
This test verifies that users can be created and their passwords can be changed
1. Log on to the risk admin. Go to the users tab on the left. This will display the users. Select the user you normally
1. Log on to the AdminUI. Go to the users tab on the left. This will display the users. Select the user you normally
log in the shell with. Change the password (and remember it)
2. Now start the shell, and make sure you can log in with the changed password.
3. In the risk admin, click on the add sign and add a new user. Make sure that it shows up there.
3. In the AdminUI, click on the add sign and add a new user. Make sure that it shows up there.
4. Now relaunch the shell and make sure you can log in with the new user (and the password you entered in 3)
@@ -15,6 +15,6 @@ log in the shell with. Change the password (and remember it)
-----------------------------------------------------------
7. Go the main account tab, add an account and make sure it shows up in the risk admin.
7. Go the main account tab, add an account and make sure it shows up in the AdminUI.
b. Associate the user you usually use with this account and make sure it shows up in the account dropdown in the ladder.
b. Associate the user you usually use with this account and make sure it shows up in the account dropdown in the ladder.