Files
spark/src/client/spark/Modules/Trading/Ladder/VM/LadderOrderVM.cs
T

351 lines
17 KiB
C#

using bts.api;
using bts.api.orderman;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.shell;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace mbts.spark {
class LadderOrderVM : DisposableViewModelBase {
#region Colors
static readonly Color _colorbg = Colors.White, _darkbg = Color.FromRgb(0xbf, 0xbf, 0xbf);
static readonly Brush _color_bg_brush = _colorbg.rgb_color().rgb_brush();
static Brush mkbrush(Color color, Color endcolor, double pct_complete) {
GradientStopCollection stops = new GradientStopCollection();
stops.Add(new GradientStop(color, 0.0));
stops.Add(new GradientStop(color, pct_complete));
stops.Add(new GradientStop(endcolor, pct_complete));
stops.Add(new GradientStop(endcolor, 1.0));
return new LinearGradientBrush(stops) {
StartPoint = new System.Windows.Point(0, 0.5),
EndPoint = new System.Windows.Point(1, 0.5)
};
}
#endregion
readonly LadderVM _owner;
readonly IBus _bus;
readonly Property<FontFamily> _font_family;
readonly Property<FontWeight> _font_weight;
readonly Property<double> _font_size;
readonly Property<Brush> _foreground, _background, _hoverbackground, _border;
readonly Property<bool> _has_multiple_orders_at_same_level, _is_hedge_order;
readonly Property<CustomOrderDefinition.CustomOneofCase> _algo_type;
readonly Property<string> _algo_studio_abbreviation;
IObservable<LadderSettings.BadgeStyle> _bs;
LadderSettings.BadgeStyle _current_badge_style;
int _n_active_price_change_ops = 0;
double _real_price = double.NaN, _phantom_price = double.NaN;
uint filled, quantity, num_root_orders;
int working_quantity;
uint? _min_piq = UInt32.MaxValue;
public event Action piq_changed;
LadderModel model => _owner.model;
Dictionary<uint, (OrderRecordImmutable order, uint? p, AlgoData? algo, AlgoDefinitionMetadata? meta)> _orders = new Dictionary<uint, (OrderRecordImmutable order, uint? p, AlgoData? algo, AlgoDefinitionMetadata? meta)>();
public LadderOrderVM((OrderRecordImmutable, uint?, AlgoData?, AlgoDefinitionMetadata?) op, double real_price, LadderVM owner, IBus bus, IObservable<LadderSettings.BadgeStyle> bs) {
_owner = owner;
_bus = bus;
_bs = bs;
_real_price = real_price;
// settings
var fs = UserSettings.factory_defaults.ladder;
_font_family = backing(nameof(font_family), owner.settings, get_font_family, get_font_family(fs));
_font_weight = backing(nameof(font_weight), owner.settings, get_font_weight, get_font_weight(fs));
_font_size = backing(nameof(font_size), owner.settings, get_font_size, get_font_size(fs));
_foreground = backing(nameof(foreground), owner.settings, get_foreground, get_foreground(fs));
_background = backing(nameof(background), _color_bg_brush);
_hoverbackground = backing(nameof(hoverbackground), _color_bg_brush);
_border = backing(nameof(border), _color_bg_brush);
_has_multiple_orders_at_same_level = backing(nameof(has_multiple_orders_at_same_level), false);
_is_hedge_order = backing(nameof(is_hedge_order), false);
_algo_type = backing(nameof(algo_type), CustomOrderDefinition.CustomOneofCase.None);
_algo_studio_abbreviation = backing(nameof(algo_studio_abbreviation), string.Empty);
FontFamily get_font_family(LadderSettings s) => new FontFamily(s.orders_column.font_family);
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();
//
add_order(op);
_dispose = Disposable.Create(
_bs.Subscribe(badge => {
_current_badge_style = badge;
_set_badge_text();
})
);
}
public void update() {
// update brushes
Color color;
switch (side) {
case Side.Buy: color = BTSColors.MarketData.bid_alt; break;
case Side.Sell: color = BTSColors.MarketData.ask_alt; break;
case Side.Undefined:
default:
color = BTSColors.MarketData.bid_ask_alt_blend; break;
}
var darker = BTSColor.darken2(color.R, color.G, color.B, 0.75);
Color dark = new Color() { A = 255, R = darker.r, G = darker.g, B = darker.b };
var buy_sell_background_fill_color = new SolidColorBrush(color);
buy_sell_background_fill_color.Freeze();
background = buy_sell_background_fill_color;
hoverbackground = mkbrush(dark, _darkbg, 0);
filled = quantity = num_root_orders = 0;
working_quantity = 0;
foreach(var n in _root_nodes()) {
num_root_orders++;
filled += n.filled();
working_quantity += n.working_quantity();
quantity += n.quantity();
}
// if this badge only represents a single order, then is_exchange_order and the border (= algo color)
// should be set appropriately
if (num_root_orders == 1) {
var single_order = _root_nodes().First();
var single_order_metadata = _owner.model.order_gateway.factory.get_metadata(single_order);
border = single_order_metadata.Color.rgb_brush();
if (_orders.TryGetValue(single_order.Key, out var opm)) {
algo_studio_abbreviation = _sanitize_abbreviation(string.IsNullOrEmpty(opm.meta?.abbreviation) ? _generate_abbreviation_for_algo_studio_algo(opm.algo) : opm.meta?.abbreviation);
border = opm.meta?.badge_color?.rgb_color().rgb_brush() ?? border;
}
if (single_order.order_type().is_bts_algo_type()) {
algo_type = single_order.order_type();
} else {
algo_type = CustomOrderDefinition.CustomOneofCase.None;
}
} else {
border = new SolidColorBrush(color);
}
has_multiple_orders_at_same_level = num_root_orders > 1;
is_hedge_order = _root_nodes().Any(o => o.sub_type() == OrderSubType.HedgingLeg);
_set_badge_text();
string _generate_abbreviation_for_algo_studio_algo(AlgoData? a) {
char[] delim = { ' ' };
string candidate = string.Empty;
if (a.HasValue) {
var algo_name = a.Value.name;
var words = algo_name.Split(delim);
if (words.Length == 1) {
var single_word = words[0];
if (single_word.Length > 1) {
candidate = words[0];
} else {
candidate = single_word;
}
} else {
candidate = words.Take(2).Select(w => w.Substring(0, 1)).list_string(string.Empty);
}
}
return candidate.ToUpper();
}
string _sanitize_abbreviation(string ab) {
string candidate = ab;
if (ab.Length > 2) {
candidate = candidate.Substring(0, 2);
}
return candidate.ToUpper();
}
}
private void _set_badge_text() {
text_lines = BadgeRender.format(side, quantity, filled, _current_badge_style);
RaisePropertyChanged(nameof(text_lines));
}
/// <summary>
/// Add Order performs an add the first time it's called via the constructor. When it's called, directly
/// it really serves as an update/replace. Also note that since the min_piq is a separate piece of state representing
/// the lowest piq of the orders the badge represents, we must reevaluate if that has changed on said update.
/// </summary>
public void add_order((OrderRecordImmutable order, uint? p, AlgoData? algo, AlgoDefinitionMetadata? meta) new_op) {
_orders[new_op.order.Key] = new_op;
// reevaluate min piq if this order's piq is less
if (new_op.p.HasValue) {
// if this lovm only represents 1 order and the piq is now different, regardless of what it is that's our piq
if (_orders.Count == 1 && new_op.p.Value != min_piq) {
min_piq = new_op.p.Value;
} else if (new_op.p.Value < min_piq) {
min_piq = new_op.p.Value;
}
}
}
public void remove_order(uint order_key) {
_orders.Remove(order_key);
// on a remove, potentially the order w/ the lowest piq has been removed, so
// if the min() is now > than the current min_piq, update the min_piq
var prospective_piq = _orders.Select(op => op.Value.p).Where(piq => piq.HasValue).Min();
if (prospective_piq > min_piq) {
min_piq = prospective_piq;
}
}
//public void update(OrderRecordImmutable neworder) {
// Log.assert(neworder.Key == id, $"OrderVM.update was called with an order with a different Key({neworder.Key}) from original({id})");
// using (detect_property_changes()) {
// _init(neworder);
// }
//}
public uint security_key => _owner.security.Id;
public double price { get => double.IsNaN(_phantom_price) ? _real_price : _phantom_price; }
public uint? min_piq {
get {
return _min_piq;
}
set {
if (Set(ref _min_piq, value)) {
piq_changed?.Invoke();
}
}
}
public double real_price => _real_price;
public Side side {
get {
var distinct_sides = _root_nodes().Select(o => o.side()).Distinct();
if (distinct_sides.Count() > 1) {
return Side.Undefined;
}
return distinct_sides.FirstOrDefault();
}
}
IEnumerable<OrderRecordImmutable> _root_nodes() => _orders.Values.Select(_owner.get_root_at_price).DistinctOn(OrderUtils.RecordKeySelector);
public IReadOnlyList<string> text_lines { get; private set; }
public bool has_phantom_price => !double.IsNaN(_phantom_price);
public ICommand cancel_command => new DelegateCommand(() => _execute_command(_cancel_order));
public event Action command_executed;
void _execute_command(Action action) {
action();
command_executed?.Invoke();
}
public FontFamily font_family => _font_family.Value;
public FontWeight font_weight => _font_weight.Value;
public double font_size => _font_size.Value;
public Brush foreground => _foreground.Value;
public Brush background { get => _background.Value; private set => _background.Value = value; }
public Brush hoverbackground { get => _hoverbackground.Value; private set => _hoverbackground.Value = value; }
public Brush border { get => _border.Value; private set => _border.Value = value; }
public string summary => _root_nodes().Any() ? $"Badge containing root orders: {string.Join(",", _root_nodes().Select(o => o.Key))}" : string.Empty;
public bool has_multiple_orders_at_same_level { get => _has_multiple_orders_at_same_level.Value; private set => _has_multiple_orders_at_same_level.Value = value; }
public bool is_hedge_order { get => _is_hedge_order.Value; private set => _is_hedge_order.Value = value; }
public CustomOrderDefinition.CustomOneofCase algo_type { get => _algo_type.Value; private set => _algo_type.Value = value; }
public string algo_studio_abbreviation { get => _algo_studio_abbreviation.Value; private set => _algo_studio_abbreviation.Value = value; }
public IReadOnlyList<uint> order_keys => _orders.Keys.ToReadOnlyList();
public IEnumerable<OrderRecordImmutable> root_orders => _root_nodes();
void _cancel_order() {
foreach (var order in _root_nodes()) {
model.order_gateway.cancel_order(order).ignore();
}
}
public async void try_set_price(OrderRecordImmutable order, double new_price) {
// don't change stop or stop_limits => server crash
if (order.order_type() == bts.api.orderman.CustomOrderDefinition.CustomOneofCase.Stop || order.order_type() == bts.api.orderman.CustomOrderDefinition.CustomOneofCase.StopLimit) return;
if (order.working_quantity() <= 0) return;
_phantom_price = new_price;
RaisePropertyChanged(nameof(price));
++_n_active_price_change_ops;
if (await _owner.model.order_gateway.update_order(order, new_price, order.State.Quantity)) {
// wait 3 secs, then give up if price change still hasn't taken effect
await Task.Delay(3000);
}
// only update when the last price change op is finished
if (--_n_active_price_change_ops == 0) {
_phantom_price = double.NaN;
RaisePropertyChanged(nameof(price));
}
}
public OrderBookVM create_orderbook_vm() {
// We are returning a new OrderBookVM each time b/c after
// successive launches of the mini-ob from the same badge, we get an exception
// System.InvalidOperationException: Sharing GridViewColumn among multiple GridViewColumnCollections or adding the same GridViewColumn into one GridViewColumnCollection more than once is not allowed.
// I checked with Eric and he guesses that what is happening is that the Popup is throwing away the grid, but the binding doesn't remove the columns from that grid
//
// I think returning a new OrderbookVM is okay at the moment since this Popup window will not be saving any state at this time
var price_filter = new filters.DoubleMinMaxState();
price_filter.minimum.value = real_price;
price_filter.maximum.value = real_price;
var obvm = new OrderBookVM(null, _owner.bus, null, _owner.model.order_gateway, null, true);
var state = new bts.shell.orderbook.OrderBookStartupData(
new bts.shell.orderbook.FilterStates {
security_criteria = new SecurityCriteria(_owner.security),
price = price_filter,
statuses = new[] { OrderStatus.Working },
order_types = AlgoID.exchange_algo_keys
},
bts.shell.orderbook.OrderBookStartupData.default_mini_grid,
use_defaults: false
);
// NOTE:
// we might need the ObservableAppend to InsertAt
// if these EditXXX ever support settings.
// The end result after this group of lines will be
// ----------------------------------------------
// | Cancel | Update | Qty | Price | Commit | Attach | Detach | ...
// ----------------------------------------------
//
obvm.columns.Insert(0, new OrderBookVM.AttachDetachColumn(typeof(MiniOrderBookView)));
obvm.columns.Insert(0, new OrderBookVM.CommitColumn());
var price_col = obvm.columns.FirstOrDefault(x => x.id == OrderBookGridView.ColumnKeys.Price.ToString());
var price_index = obvm.columns.indexOf(price_col);
if (price_index > -1) {
var existing_editprice_col = obvm.columns.FirstOrDefault(x => x.id == OrderBookGridView.ColumnKeys.EditablePrice.ToString());
var existing_editprice_index = obvm.columns.indexOf(existing_editprice_col);
if (existing_editprice_index == -1) {
// insert the edit price column at the beginning
obvm.columns.Insert(0, new OrderBookVM.EditablePriceColumn());
}
}
var qty_col = obvm.columns.FirstOrDefault(x => x.id == OrderBookGridView.ColumnKeys.Size.ToString());
var qty_index = obvm.columns.indexOf(qty_col);
if (qty_index > -1) {
var existing_editqty_col = obvm.columns.FirstOrDefault(x => x.id == OrderBookGridView.ColumnKeys.EditableQty.ToString());
var existing_editqty_index = obvm.columns.indexOf(existing_editqty_col);
if (existing_editqty_index == -1) {
// insert the edit quantity column at the beginning
obvm.columns.Insert(0, new OrderBookVM.EditableQtyColumn());
}
}
obvm.columns.Insert(0, new OrderBookVM.UpdateColumn(typeof(MiniOrderBookView)));
obvm.columns.Insert(0, new OrderBookVM.CancelColumn(nameof(OrderBookRowVM.cancel_command)));
obvm.columns.Insert(0, new OrderBookVM.CheckColumn(nameof(OrderBookRowVM.is_selected)));
obvm.load_from(state);
return obvm;
}
public override string ToString() {
return $"Price: {price} Order Count: {_orders.Values.Count()} Root Order Count: {_root_nodes().Count()} PIQ: {(this.min_piq.HasValue ? this.min_piq.Value.ToString() : "")}";
}
}
}