merge; fixing merge
This commit is contained in:
commit
5aab4312fc
50 files changed
+1310
-730
No files matched your search
@@ -36,7 +36,6 @@ namespace bts {
|
||||
_deleted_synthetics = new HashSet<uint>(t.Where(kv => kv.Value.Deleted).Select(kv => kv.Key));
|
||||
_bus.post(SparkTags.SyntheticstrategiesTag, t);
|
||||
}));
|
||||
new DataPersistor(_bus);
|
||||
Task.Run(run);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
using bts.api;
|
||||
using mbts.spark;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.Composition;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace mbts.ui {
|
||||
[Export(typeof(IShellDaemon))]
|
||||
class RecenterDaemon : IShellDaemon, IDisposable {
|
||||
bool _run = true;
|
||||
readonly IBus _bus;
|
||||
readonly TimeSpan _time_to_center;
|
||||
DateTime _last_recenter;
|
||||
IDisposable _dispose;
|
||||
|
||||
[ImportingConstructor]
|
||||
public RecenterDaemon(IBus bus) {
|
||||
_bus = bus;
|
||||
_time_to_center = TimeSpan.FromSeconds(config.Configuration.get<bts.config.LadderKnobs>().seconds_to_recenter);
|
||||
_last_recenter = DateTime.UtcNow;
|
||||
|
||||
_dispose = _bus.subscribe(SparkTags.RequestRecenterLadder).Subscribe(_ => trigger_recenter(SparkTags.RecenterLadderNow));
|
||||
run();
|
||||
}
|
||||
|
||||
void trigger_recenter(ITag<DateTime> tag) {
|
||||
_last_recenter = DateTime.UtcNow;
|
||||
_bus.post(tag, _last_recenter);
|
||||
}
|
||||
|
||||
async void run() {
|
||||
_run = true;
|
||||
while (_run) {
|
||||
await Task.Delay(TimeSpan.FromSeconds(5));
|
||||
if (_last_recenter + _time_to_center < DateTime.UtcNow) {
|
||||
trigger_recenter(SparkTags.RecenterLadderBegin);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
Disposable.dispose(ref _dispose);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,7 +42,7 @@ namespace mbts.spark {
|
||||
_orders_model = orders_model;
|
||||
_security_text = smd.security.ToString();
|
||||
_security_key_text = security_key.ToString();
|
||||
string format_price(double price) => security.ContractSpec.format(price);
|
||||
string format_price(double price) => security.format(price);
|
||||
_position = new CellProperty<int>(0);
|
||||
_bid_price = backing(nameof(bid_price), double.NaN);
|
||||
_ask_price = backing(nameof(ask_price), double.NaN);
|
||||
@@ -106,8 +106,8 @@ namespace mbts.spark {
|
||||
public double session_high => _session_high.Value;
|
||||
public int working_bid_volume => _working_bid_volume.value;
|
||||
public int working_ask_volume => _working_ask_volume.value;
|
||||
public string working_bids_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_bid, _order_summarizer.best_working_bid_qty, _order_summarizer.working_bid_qty, security.ContractSpec);
|
||||
public string working_asks_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_ask, _order_summarizer.best_working_ask_qty, _order_summarizer.working_ask_qty, security.ContractSpec);
|
||||
public string working_bids_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_bid, _order_summarizer.best_working_bid_qty, _order_summarizer.working_bid_qty, security);
|
||||
public string working_asks_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_ask, _order_summarizer.best_working_ask_qty, _order_summarizer.working_ask_qty, security);
|
||||
public double working_best_bid => _working_best_bid.value;
|
||||
public double working_best_ask => _working_best_ask.value;
|
||||
public IList<CellAnimation> animations => _animation.get_animations().ToList();
|
||||
|
||||
@@ -76,7 +76,7 @@ namespace mbts.spark {
|
||||
BindingBase price_binding(string prop) {
|
||||
var mb = new MultiBinding { Converter = price_converter };
|
||||
mb.Bindings.Add(new Binding(prop) { Mode = BindingMode.OneWay });
|
||||
mb.Bindings.Add(new Binding($"{nameof(Row.security)}.{nameof(SecurityImmutable.ContractSpec)}") { Mode = BindingMode.OneWay });
|
||||
mb.Bindings.Add(new Binding($"{nameof(Row.security)}") { Mode = BindingMode.OneWay });
|
||||
return mb;
|
||||
}
|
||||
//
|
||||
|
||||
@@ -101,7 +101,7 @@ namespace mbts.spark {
|
||||
show_ladder = new DelegateCommand(() => parent._show_ladder_async(this).ignore());
|
||||
_security_text = security.ToString();
|
||||
_time_text = time.ToString("M/d h:mm:ss tt");
|
||||
_price_text = security.ContractSpec.format(price);
|
||||
_price_text = security.format(price);
|
||||
_size_text = size.ToString();
|
||||
_trade_key_text = _trade_key.ToString();
|
||||
_security_key_text = security_key.ToString();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
using bts.api;
|
||||
using bts.shell;
|
||||
using bts.spark;
|
||||
using mbts.spark.utilities;
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.spark;
|
||||
@@ -23,7 +24,7 @@ namespace mbts.spark {
|
||||
/// The view model designed to serve as the DataContext for the SyntheticEditorView
|
||||
/// </summary>
|
||||
partial class SyntheticEditorVM : DisposableViewModelBase, IRequestViewClose, IRequestBindingSourceUpdate, IDisposable {
|
||||
readonly ObservableCollection<TickFactors> _available_tick_factors = new ObservableCollection<TickFactors>(TickUtils.all_present_ticks());
|
||||
readonly ObservableCollection<TickFactors> _available_tick_factors = new ObservableCollection<TickFactors>(TickUtils.synthetic_presets);
|
||||
readonly QuantityModel _quantity_model;
|
||||
readonly PriceMultiplierModel _price_mult_model;
|
||||
readonly List<IDisposable> _resources = new List<IDisposable>();
|
||||
@@ -41,7 +42,7 @@ namespace mbts.spark {
|
||||
public SyntheticEditorVM(SpreaderModel model, SecurityImmutable synthetic, ExecutionStrategyImmutable strategy, IObservable<bool> security_has_working_orders)
|
||||
: this(synthetic, strategy, false) {
|
||||
ExceptionAssert.InvalidOperation.That(synthetic.Id != 0, "This constructor may only be used for already-existing synthetic securities (id must be non-zero).");
|
||||
_tick_factors = TickUtils.get_regional_ticks(synthetic.ContractSpec).low_tick;
|
||||
_tick_factors = TickUtils.get_regional_ticks(synthetic).low_tick;
|
||||
title = $"Edit '{synthetic.Synthetic.Name}'";
|
||||
icon = Icons.ModifySynthetic;
|
||||
_has_working_orders = backing(nameof(has_working_orders), security_has_working_orders.OnDispatcher());
|
||||
@@ -94,7 +95,7 @@ namespace mbts.spark {
|
||||
_set_ticks_automatically = false;
|
||||
_set_quantities_automatically = false;
|
||||
_set_price_mults_automatically = false;
|
||||
_tick_factors = TickUtils.get_regional_ticks(_synthetic.ContractSpec).low_tick;
|
||||
_tick_factors = TickUtils.get_regional_ticks(_synthetic).low_tick;
|
||||
} else {
|
||||
_deduce_name();
|
||||
_deduce_ticks();
|
||||
@@ -153,6 +154,7 @@ namespace mbts.spark {
|
||||
_set_quantities_automatically = is_new;
|
||||
_set_price_mults_automatically = is_new;
|
||||
available_tick_factors_view = CollectionViewSource.GetDefaultView(_available_tick_factors);
|
||||
((ListCollectionView)available_tick_factors_view).CustomSort = TickUtils.CompareUtils.base_unit_comparer.as_non_generic();
|
||||
available_tick_factors_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(TickFactors.tick_base)));
|
||||
|
||||
_quantity_model = new QuantityModel(!is_new);
|
||||
@@ -328,7 +330,7 @@ namespace mbts.spark {
|
||||
|
||||
void _deduce_ticks() {
|
||||
_tick_factors = TickUtils.deduce_ticks(leg_tuples.Select(l => l.leg.Security.ContractSpec));
|
||||
if (_tick_factors != null && !_available_tick_factors.Contains(tick_factors))
|
||||
if (_tick_factors != null && !_available_tick_factors.Contains(_tick_factors))
|
||||
_available_tick_factors.Add(_tick_factors);
|
||||
RaisePropertyChanged(nameof(tick_factors));
|
||||
}
|
||||
|
||||
@@ -38,23 +38,23 @@ namespace bts.spark {
|
||||
|
||||
#region formatting
|
||||
|
||||
(SecurityImmutable?, ContractSpecificationImmutable?) get_security(uint security_key) {
|
||||
SecurityImmutable? get_security(uint security_key) {
|
||||
if (_security.TryGetValue(security_key, out SecurityMD md)) {
|
||||
return (md.security, md.security.ContractSpec);
|
||||
return md.security;
|
||||
}
|
||||
return (null, null);
|
||||
return null;
|
||||
}
|
||||
string format_order_success(uint key, double price, uint size, Side side, ContractSpecificationImmutable? spec) {
|
||||
return $"({key}) {side.ToString().ToLower()} {size} @ {spec.format(price)}";
|
||||
string format_order_success(uint key, double price, uint size, Side side, SecurityImmutable? security) {
|
||||
return $"({key}) {side.ToString().ToLower()} {size} @ {security.format(price)}";
|
||||
}
|
||||
string format_order_fail(double price, uint size, Side side, ContractSpecificationImmutable? spec, string error) {
|
||||
return $"Failed to {side.ToString().ToLower()} {size} @ {spec.format(price)}. {error}";
|
||||
string format_order_fail(double price, uint size, Side side, SecurityImmutable? security, string error) {
|
||||
return $"Failed to {side.ToString().ToLower()} {size} @ {security.format(price)}. {error}";
|
||||
}
|
||||
string format_cancel_success(OrderRecordImmutable order, ContractSpecificationImmutable? spec) {
|
||||
return $"({order.Key}) Canceled {order.short_description(spec)}, was working {order.working_quantity()}";
|
||||
string format_cancel_success(OrderRecordImmutable order, SecurityImmutable? security) {
|
||||
return $"({order.Key}) Canceled {order.short_description(security)}, was working {order.working_quantity()}";
|
||||
}
|
||||
string format_cancel_error(OrderRecordImmutable order, ContractSpecificationImmutable? spec, string error) {
|
||||
return $"({order.Key}) Failed to cancel {order.short_description(spec)}: {error}";
|
||||
string format_cancel_error(OrderRecordImmutable order, SecurityImmutable? security, string error) {
|
||||
return $"({order.Key}) Failed to cancel {order.short_description(security)}: {error}";
|
||||
}
|
||||
string format_fill_summary(OrderRecordImmutable before, OrderRecordImmutable after) {
|
||||
int fb = (int)before.State.FilledQuantity;
|
||||
@@ -65,14 +65,14 @@ namespace bts.spark {
|
||||
return $"({key}) Status changed from {old_status} to {new_status}";
|
||||
}
|
||||
|
||||
public static string modified_description(OrderRecordImmutable old_order, OrderRecordImmutable new_order, ContractSpecificationImmutable? spec) {
|
||||
public static string modified_description(OrderRecordImmutable old_order, OrderRecordImmutable new_order, SecurityImmutable? security) {
|
||||
double old_price = old_order.State.Price, new_price = new_order.State.Price;
|
||||
uint old_size = old_order.State.Quantity, new_size = new_order.State.Quantity;
|
||||
string modified_size_partial_description(int working_size) {
|
||||
return $"size from {old_size} to {new_size}, working {working_size}";
|
||||
}
|
||||
string modified_price_partial_description() {
|
||||
return $"price from {spec.format(old_price)} to {spec.format(new_price)}";
|
||||
return $"price from {security.format(old_price)} to {security.format(new_price)}";
|
||||
}
|
||||
if (old_price != new_price || old_size != new_size) {
|
||||
StringBuilder sb = new StringBuilder($"({old_order.Key}) Changed ");
|
||||
@@ -102,7 +102,7 @@ namespace bts.spark {
|
||||
|
||||
foreach (var order in added) {
|
||||
if (!string.IsNullOrEmpty(order.State.LastMsg) && order.State.Created.ToDateTime().Date == DateTime.Today) {
|
||||
(var security, var spec) = get_security(order.Def.SecurityKey);
|
||||
var security = get_security(order.Def.SecurityKey);
|
||||
if (security.HasValue) {
|
||||
log_status(ActivityLogCategory.warn, security, order.State.LastMsg);
|
||||
}
|
||||
@@ -111,10 +111,10 @@ namespace bts.spark {
|
||||
|
||||
foreach (var neworder in changed) {
|
||||
var oldorder = removed[neworder.Key];
|
||||
(var security, var spec) = get_security(neworder.Def.SecurityKey);
|
||||
var security = get_security(neworder.Def.SecurityKey);
|
||||
//
|
||||
// description
|
||||
var mod_desc = modified_description(oldorder, neworder, spec);
|
||||
var mod_desc = modified_description(oldorder, neworder, security);
|
||||
if (!string.IsNullOrEmpty(mod_desc)) {
|
||||
log_status(ActivityLogCategory.modify, security, mod_desc);
|
||||
}
|
||||
@@ -145,31 +145,31 @@ namespace bts.spark {
|
||||
}
|
||||
|
||||
internal void on_send_order(OrderDefinitionImmutable order, double price, uint size, uint? key, string error) {
|
||||
(var security, var spec) = get_security(order.SecurityKey);
|
||||
var security = get_security(order.SecurityKey);
|
||||
log_status(ActivityLogCategory.order, security, key.HasValue ?
|
||||
format_order_success(key.Value, price, size, order.Side, spec) :
|
||||
format_order_fail(price, size, order.Side, spec, error));
|
||||
format_order_success(key.Value, price, size, order.Side, security) :
|
||||
format_order_fail(price, size, order.Side, security, error));
|
||||
}
|
||||
|
||||
internal void on_cancel_order(OrderRecordImmutable order, bool success, string error) {
|
||||
(var security, var spec) = get_security(order.Def.SecurityKey);
|
||||
var security = get_security(order.Def.SecurityKey);
|
||||
log_status(ActivityLogCategory.cancel, security, success ?
|
||||
format_cancel_success(order, spec):
|
||||
format_cancel_error(order, spec, error));
|
||||
format_cancel_success(order, security):
|
||||
format_cancel_error(order, security, error));
|
||||
}
|
||||
|
||||
internal void update_order(OrderRecordImmutable order, double price, uint size) {
|
||||
(var security, var spec) = get_security(order.Def.SecurityKey);
|
||||
var security = get_security(order.Def.SecurityKey);
|
||||
log_status(ActivityLogCategory.modify,
|
||||
security,
|
||||
$"({order.Key}) change from {order.State.Quantity}@{spec.format(order.State.Price)} to {size}@{spec.format(price)}");
|
||||
$"({order.Key}) change from {order.State.Quantity}@{security.format(order.State.Price)} to {size}@{security.format(price)}");
|
||||
}
|
||||
|
||||
internal void update_order_failed(OrderRecordImmutable order, double price, uint size) {
|
||||
(var security, var spec) = get_security(order.Def.SecurityKey);
|
||||
var security = get_security(order.Def.SecurityKey);
|
||||
log_status(ActivityLogCategory.modify,
|
||||
security,
|
||||
$"({order.Key}) failed to change from {order.State.Quantity}@{spec.format(order.State.Price)} to {size}@{spec.format(price)}");
|
||||
$"({order.Key}) failed to change from {order.State.Quantity}@{security.format(order.State.Price)} to {size}@{security.format(price)}");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@
|
||||
<usp:PriceEntryControl
|
||||
Grid.ColumnSpan="2"
|
||||
usp:OrderModificationControl.IsDirty="{Binding price_dirty, FallbackValue={x:Null}}"
|
||||
ContractSpec="{Binding security.ContractSpec}"
|
||||
Security="{Binding security}"
|
||||
Focusable="false"
|
||||
TickDefaultValue="{Binding current_price, Converter={StaticResource TickDefaultPriceConverter}, FallbackValue={u:Double 0}}"
|
||||
Value="{Binding price}"
|
||||
@@ -97,13 +97,13 @@
|
||||
<Button Command="{Binding set_price_command}" CommandParameter="{Binding bbo.bid}" Foreground="{u:BTSColor MarketData.bid}" FontWeight="Bold">
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
|
||||
<Binding Path="bbo.bid"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</Button>
|
||||
<Button Grid.Column="2" Command="{Binding set_price_command}" CommandParameter="{Binding bbo.ask}" Foreground="{u:BTSColor MarketData.ask}" FontWeight="Bold">
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
|
||||
<Binding Path="bbo.ask"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</Button>
|
||||
</Grid>
|
||||
|
||||
@@ -77,7 +77,7 @@
|
||||
<Run.Text>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
|
||||
<Binding Path="bid"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</Run.Text>
|
||||
</Run>
|
||||
@@ -85,7 +85,7 @@
|
||||
<Run.Text>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
|
||||
<Binding Path="ask"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</Run.Text>
|
||||
</Run>
|
||||
|
||||
@@ -126,7 +126,7 @@
|
||||
<Run.Text>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
|
||||
<Binding Path="bid"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</Run.Text>
|
||||
</Run>
|
||||
@@ -134,7 +134,7 @@
|
||||
<Run.Text>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
|
||||
<Binding Path="ask"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</Run.Text>
|
||||
</Run>
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
using bts.api;
|
||||
using bts.api.orderman;
|
||||
using mbts.spark.utilities;
|
||||
using mbts.utils;
|
||||
|
||||
namespace mbts.spark {
|
||||
static partial class OrderTypeVMFactory {
|
||||
private class StopLimitOrderVM : OrderTypeVMBase<StopLimitOrderDefinition> {
|
||||
@@ -17,8 +16,8 @@ namespace mbts.spark {
|
||||
}
|
||||
}
|
||||
|
||||
public ContractSpecificationImmutable spec { get; private set; } =
|
||||
SecurityDataHelper.Defaults.ContractSpecificationImmutable;
|
||||
public SecurityImmutable security { get; private set; } =
|
||||
SecurityDataHelper.Defaults.Security;
|
||||
|
||||
public override void assign_to(CustomOrderDefinition value) {
|
||||
if (!HasErrors) {
|
||||
|
||||
@@ -67,9 +67,11 @@ namespace mbts.spark
|
||||
public static ITag<SecurityCriteria> ShowTimeAndSalesTag { get; } = new SparkTag<SecurityCriteria>("Show TimeAndSales");
|
||||
#endregion
|
||||
|
||||
#region Persist
|
||||
public static ITag<PersistMessage> PersistCommandTag { get; } = new SparkTag<PersistMessage>("PersistCommandTag");
|
||||
public static ITag<PersistedItems> PersistedItemsTag { get; } = new SparkTag<PersistedItems>("PersistedItemsTag");
|
||||
#region Ladder
|
||||
public static ITag<Nothing> RequestRecenterLadder { get; } = new SparkTag<Nothing>(nameof(RequestRecenterLadder));
|
||||
public static ITag<DateTime> RecenterLadderBegin { get; } = new SparkTag<DateTime>(nameof(RecenterLadderBegin));
|
||||
public static ITag<DateTime> RecenterLadderNow { get; } = new SparkTag<DateTime>(nameof(RecenterLadderNow));
|
||||
|
||||
#endregion
|
||||
|
||||
public static ITag<uint> SyntheticDeleteTag { get; } = new SparkTag<uint>(nameof(SyntheticDeleteTag));
|
||||
|
||||
@@ -6,6 +6,7 @@ using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Threading;
|
||||
using bts.api.core;
|
||||
using IronPython.Runtime.Types;
|
||||
using mbts;
|
||||
@@ -49,6 +50,9 @@ namespace bts.api.diagnostic {
|
||||
readonly StringBuilder _pending = new StringBuilder();
|
||||
readonly OutputPublisher _out;
|
||||
|
||||
readonly Thread _thread;
|
||||
Dispatcher _dispatcher;
|
||||
|
||||
public ShellScriptServer(ServiceContext context, ShellDiagnosticsServiceServer parent, string qualifier) : base(context, qualifier) {
|
||||
_parent = parent;
|
||||
_out = make_output_publisher();
|
||||
@@ -59,11 +63,19 @@ namespace bts.api.diagnostic {
|
||||
_scope.SetVariable("shell_objects", new Func<object,object>(o => get_exports(o,null)));
|
||||
_scope.SetVariable("shell_named_object", new Func<object,string,object>(get_export));
|
||||
_scope.SetVariable("shell_named_objects", new Func<object,string,object>(get_exports));
|
||||
|
||||
_thread = new Thread(_ => {
|
||||
_dispatcher = Dispatcher.CurrentDispatcher;
|
||||
Thread.CurrentThread.Name = $"ShellScriptServer-{qualifier}";
|
||||
Dispatcher.Run();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public override Task<VoidMessage> dispose(VoidMessage request) {
|
||||
log("Finished", true);
|
||||
_parent.terminate(this);
|
||||
_dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle);
|
||||
return Task.FromResult(new VoidMessage());
|
||||
}
|
||||
|
||||
@@ -124,45 +136,58 @@ namespace bts.api.diagnostic {
|
||||
});
|
||||
}
|
||||
|
||||
Task<ScriptResultMessage> run_code(ScriptSource code) {
|
||||
ScriptResultMessage run_code(ScriptSource code) {
|
||||
try {
|
||||
object result = code.Execute(_scope);
|
||||
return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.Complete, Message = (result?.ToString()) ?? "" });
|
||||
return new ScriptResultMessage { Res = ScriptResult.Complete, Message = (result?.ToString()) ?? "" };
|
||||
}
|
||||
catch (Exception e) {
|
||||
//log($"Exception: {e.Message}");
|
||||
return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.RunError, Message = e.Message });
|
||||
return (new ScriptResultMessage { Res = ScriptResult.RunError, Message = e.Message });
|
||||
}
|
||||
}
|
||||
|
||||
public override Task<ScriptResultMessage> run(ScriptLines request) {
|
||||
|
||||
// append lines to _pending
|
||||
foreach (var line in request.Lines) {
|
||||
_pending.AppendLine(line);
|
||||
}
|
||||
// CreateScriptSource from pending
|
||||
var code = _engine.CreateScriptSourceFromString(_pending.ToString().TrimStart(' ', '\n', '\r'), SourceCodeKind.InteractiveCode);
|
||||
var parse_result = code.GetCodeProperties();
|
||||
if (parse_result == ScriptCodeParseResult.IncompleteStatement && code.GetCode().EndsWith(Environment.NewLine+Environment.NewLine)) {
|
||||
parse_result = Microsoft.Scripting.ScriptCodeParseResult.Complete;
|
||||
}
|
||||
// todo: If code is 'incomplete' but we have 2 blank lines run it!
|
||||
switch (parse_result) {
|
||||
// If 'complete' run code
|
||||
case ScriptCodeParseResult.Complete:
|
||||
_pending.Clear();
|
||||
return run_code(code);
|
||||
// if 'invalid' return error
|
||||
case ScriptCodeParseResult.Invalid:
|
||||
Console.WriteLine("Invalid");
|
||||
_pending.Clear();
|
||||
return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.Invalid, Message = code.GetCode() });
|
||||
// otherwise continue buffering
|
||||
default:
|
||||
Console.WriteLine("Incomplete");
|
||||
return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.Incomplete });
|
||||
var tcs = new TaskCompletionSource<ScriptResultMessage>();
|
||||
void ret(ScriptResultMessage r) {
|
||||
tcs.TrySetResult(r);
|
||||
}
|
||||
|
||||
_dispatcher.BeginInvoke(() => {
|
||||
|
||||
// append lines to _pending
|
||||
foreach (var line in request.Lines) {
|
||||
_pending.AppendLine(line);
|
||||
}
|
||||
// CreateScriptSource from pending
|
||||
var code = _engine.CreateScriptSourceFromString(_pending.ToString().TrimStart(' ', '\n', '\r'), SourceCodeKind.InteractiveCode);
|
||||
var parse_result = code.GetCodeProperties();
|
||||
if (parse_result == ScriptCodeParseResult.IncompleteStatement && code.GetCode().EndsWith(Environment.NewLine+Environment.NewLine)) {
|
||||
parse_result = Microsoft.Scripting.ScriptCodeParseResult.Complete;
|
||||
}
|
||||
// todo: If code is 'incomplete' but we have 2 blank lines run it!
|
||||
switch (parse_result) {
|
||||
// If 'complete' run code
|
||||
case ScriptCodeParseResult.Complete:
|
||||
_pending.Clear();
|
||||
ret(run_code(code));
|
||||
break;
|
||||
// if 'invalid' return error
|
||||
case ScriptCodeParseResult.Invalid:
|
||||
Console.WriteLine("Invalid");
|
||||
_pending.Clear();
|
||||
ret(new ScriptResultMessage { Res = ScriptResult.Invalid, Message = code.GetCode() });
|
||||
break;
|
||||
// otherwise continue buffering
|
||||
default:
|
||||
Console.WriteLine("Incomplete");
|
||||
ret(new ScriptResultMessage { Res = ScriptResult.Incomplete });
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
return tcs.Task;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,8 +17,10 @@ namespace mbts {
|
||||
public static double tick_unit_frac(this TickFactors tick) =>
|
||||
tick.tick_unit / tick.tick_base;
|
||||
|
||||
public static double reduced_base(this TickFactors tick) => factor_out(tick.tick_base, 10);
|
||||
|
||||
public static string format(this TickFactors tick, double value) =>
|
||||
format(tick, value, double.NaN, true, _nan_text);
|
||||
format(tick, value, double.NaN, false, _nan_text);
|
||||
|
||||
public static string format(this TickFactors tick, double value, bool show_commas) =>
|
||||
format(tick, value, double.NaN, show_commas, _nan_text);
|
||||
@@ -176,9 +178,10 @@ namespace mbts {
|
||||
if (DoubleHelper.IsNaNOrInfinity(input)) return input;
|
||||
return input <= regional_tick.low_tick_inclusive_end ? regional_tick.low_tick.round(input) : regional_tick.high_tick.round(input);
|
||||
}
|
||||
public static int display_digits(this TickFactors tick) => display_digits(tick.tick_base);
|
||||
#endregion
|
||||
|
||||
public static int n_display_digits(double tick_base) {
|
||||
public static int display_digits(double tick_base) {
|
||||
double log_tick_base = Math.Log10(tick_base);
|
||||
int floor = (int)Math.Floor(log_tick_base);
|
||||
double dec = log_tick_base - floor;
|
||||
@@ -216,7 +219,7 @@ namespace mbts {
|
||||
if (numerator_part >= tick_base) numerator_part /= Math.Pow(10, Math.Ceiling(Math.Log10(numerator_part) - Math.Log10(tick_base)));
|
||||
else {
|
||||
//e.g [tick_base 640] 1989-8 == 1989-80, or 1989-32 == 1989-320
|
||||
int ndd_diff = n_display_digits(tick_base) - numerator_text.Length;
|
||||
int ndd_diff = display_digits(tick_base) - numerator_text.Length;
|
||||
if (ndd_diff > 0) numerator_part *= Math.Pow(10, ndd_diff);
|
||||
if (numerator_part >= tick_base) numerator_part /= 10;
|
||||
}
|
||||
@@ -255,14 +258,18 @@ namespace mbts {
|
||||
double numerator_dec = value - integer_part;
|
||||
double unit_frac = tick.tick_unit / tick.tick_base;
|
||||
int n_units = (int)Math.Round(numerator_dec / unit_frac);
|
||||
if (n_units == tick.tick_base) return (integer_part + 1).ToString() + tick.separator() + new string('0', n_display_digits(tick.tick_base));
|
||||
if (n_units == tick.tick_base) return (integer_part + 1).ToString() + tick.separator() + new string('0', display_digits(tick.tick_base));
|
||||
double decimal_part = n_units * tick.tick_unit;
|
||||
if (decimal_part == tick.tick_base) {
|
||||
++integer_part;
|
||||
decimal_part = 0;
|
||||
} else {
|
||||
// some ticks are not formatted with 100% precision, using less than the required display_digits
|
||||
// for such cases, we need to truncate the decimal part rather than round it.
|
||||
decimal_part = Math.Floor(decimal_part);
|
||||
}
|
||||
string integer_part_text = show_commas ? integer_part.ToString("#,0") : integer_part.ToString();
|
||||
return integer_part_text + tick.separator() + decimal_part.ToString(new string('0', n_display_digits(tick.tick_base)));
|
||||
return integer_part_text + tick.separator() + decimal_part.ToString(new string('0', display_digits(tick.tick_base)));
|
||||
}
|
||||
} catch (OverflowException ex) {
|
||||
Logger.warn(bts.log.Subsystem.Ui, $"Arithmetic overflow exception in format_tick (tick:{tick}, value:{value}):{ex}");
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace mbts.utils {
|
||||
public static class CompareUtils {
|
||||
@@ -19,5 +21,19 @@ namespace mbts.utils {
|
||||
b.HasValue ? compare(a.Value, b.Value) : 1 :
|
||||
b.HasValue ? -1 : 0;
|
||||
#endregion
|
||||
|
||||
#region Comparer
|
||||
public static IComparer as_non_generic<T>(this IComparer<T> comparer) =>
|
||||
new NonGenericComparerWrapper<T>(comparer);
|
||||
|
||||
class NonGenericComparerWrapper<T> : IComparer {
|
||||
readonly IComparer<T> _comparer;
|
||||
|
||||
public NonGenericComparerWrapper(IComparer<T> comparer) => _comparer = comparer;
|
||||
|
||||
public int Compare(object x, object y) =>
|
||||
_comparer.Compare(ObjectHelper.try_convert<T>(x), ObjectHelper.try_convert<T>(y));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ namespace mbts.ui.controls {
|
||||
double _glyph_width, _font_size, _value;
|
||||
GlyphRun _glyph_run;
|
||||
GlyphContext _glyph_context;
|
||||
ContractSpecificationImmutable _spec;
|
||||
SecurityImmutable _security;
|
||||
|
||||
static PriceCell() =>
|
||||
WPFHelper.override_metadata<HorizontalAlignment, PriceCell>(
|
||||
@@ -41,7 +41,7 @@ namespace mbts.ui.controls {
|
||||
_padding = Padding;
|
||||
_font_size = FontSize;
|
||||
_value = Value;
|
||||
_spec = ContractSpec;
|
||||
_security = Security;
|
||||
_glyph_context = GlyphContext.create(FontFamily, FontWeight);
|
||||
}
|
||||
|
||||
@@ -147,20 +147,20 @@ namespace mbts.ui.controls {
|
||||
public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); }
|
||||
#endregion
|
||||
|
||||
#region ContractSpec
|
||||
public static readonly DependencyProperty ContractSpecProperty =
|
||||
WPFHelper.create_dp<ContractSpecificationImmutable, PriceCell>(
|
||||
nameof(ContractSpec),
|
||||
#region Security
|
||||
public static readonly DependencyProperty SecurityProperty =
|
||||
WPFHelper.create_dp<SecurityImmutable, PriceCell>(
|
||||
nameof(Security),
|
||||
FrameworkPropertyMetadataOptions.AffectsMeasure |
|
||||
FrameworkPropertyMetadataOptions.AffectsRender,
|
||||
(p, v) => {
|
||||
p._spec = v;
|
||||
p._security = v;
|
||||
p._glyph_run = null;
|
||||
}, SecurityDataHelper.Defaults.ContractSpecificationImmutable);
|
||||
}, SecurityDataHelper.Defaults.SecurityImmutable);
|
||||
|
||||
public ContractSpecificationImmutable ContractSpec {
|
||||
get => (ContractSpecificationImmutable)GetValue(ContractSpecProperty);
|
||||
set => SetValue(ContractSpecProperty, value);
|
||||
public SecurityImmutable Security {
|
||||
get => (SecurityImmutable)GetValue(SecurityProperty);
|
||||
set => SetValue(SecurityProperty, value);
|
||||
}
|
||||
#endregion
|
||||
|
||||
@@ -178,7 +178,7 @@ namespace mbts.ui.controls {
|
||||
}
|
||||
|
||||
void _set_glyph(Size size) {
|
||||
_glyph_run = _glyph_context.get_glyph_run(_spec.format(_value), _font_size, size, _horizontal_alignment, VerticalAlignment.Center, _padding);
|
||||
_glyph_run = _glyph_context.get_glyph_run(_security.format(_value), _font_size, size, _horizontal_alignment, VerticalAlignment.Center, _padding);
|
||||
_glyph_width = _glyph_run == null ? 0 : _glyph_run.AdvanceWidths.Sum();
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ namespace mbts.ui.controls {
|
||||
public override FrameworkElement view_factory() {
|
||||
var v = new PriceCell();
|
||||
v.SetBinding(PriceCell.ValueProperty, _binding_factory());
|
||||
v.SetBinding(PriceCell.ContractSpecProperty, _spec_binding_factory());
|
||||
v.SetBinding(PriceCell.SecurityProperty, _spec_binding_factory());
|
||||
return v;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@
|
||||
<ColumnDefinition/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock VerticalAlignment="Center">Stop Price</TextBlock>
|
||||
<usp:PriceEntryControl Grid.Column="1" Margin="12,0,0,0" Width="80" Value="{Binding stop_price}" ContractSpec="{Binding spec}"/>
|
||||
<usp:PriceEntryControl Grid.Column="1" Margin="12,0,0,0" Width="80" Value="{Binding stop_price}" Security="{Binding security}"/>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</usp:OrderModificationTemplateSelector.StopLimitOrderTemplate>
|
||||
@@ -82,7 +82,7 @@
|
||||
<ColumnDefinition/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock VerticalAlignment="Center">Stop Price</TextBlock>
|
||||
<usp:PriceEntryControl Grid.Column="1" Margin="12,0,0,0" Width="80" Value="{Binding stop_price}" ContractSpec="{Binding spec}"/>
|
||||
<usp:PriceEntryControl Grid.Column="1" Margin="12,0,0,0" Width="80" Value="{Binding stop_price}" Security="{Binding security}"/>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</usp:OrderModificationTemplateSelector.StopMarketOrderTemplate>
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
using bts.api;
|
||||
using mbts.spark;
|
||||
using mbts.ui.extensions;
|
||||
using mbts.ui.spark.converters;
|
||||
using System;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using static mbts.ui.utility.text.TextUtils;
|
||||
|
||||
namespace mbts.ui.spark {
|
||||
/// <summary>
|
||||
@@ -18,7 +16,7 @@ namespace mbts.ui.spark {
|
||||
|
||||
#region Value
|
||||
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(PriceEntryControl),new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceValue));
|
||||
private static object CoerceValue(DependencyObject d, object baseValue) { return TickUtils.get_regional_ticks((ContractSpecificationImmutable)d.GetValue(ContractSpecProperty)).round((double)baseValue); }
|
||||
private static object CoerceValue(DependencyObject d, object baseValue) { return TickUtils.get_regional_ticks((SecurityImmutable)d.GetValue(SecurityProperty)).round((double)baseValue); }
|
||||
public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); }
|
||||
#endregion
|
||||
|
||||
@@ -39,11 +37,11 @@ namespace mbts.ui.spark {
|
||||
public ICommand TickDownCommand { get => GetValue(TickDownCommandProperty) as ICommand; private set => SetValue(TickDownCommandPropertyKey, value); }
|
||||
#endregion
|
||||
|
||||
#region ContractSpec
|
||||
public static readonly DependencyProperty ContractSpecProperty = DependencyProperty.Register("ContractSpec", typeof(ContractSpecificationImmutable), typeof(PriceEntryControl),
|
||||
new PropertyMetadata(SecurityDataHelper.Defaults.ContractSpecificationImmutable, OnContractSpecChanged));
|
||||
static void OnContractSpecChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PriceEntryControl)d)._update_text_binding();
|
||||
public ContractSpecificationImmutable? ContractSpec { get => GetValue(ContractSpecProperty) as ContractSpecificationImmutable?; set => SetValue(ContractSpecProperty, value); }
|
||||
#region Security
|
||||
public static readonly DependencyProperty SecurityProperty = DependencyProperty.Register(
|
||||
nameof(Security), typeof(SecurityImmutable), typeof(PriceEntryControl), new PropertyMetadata(SecurityDataHelper.Defaults.SecurityImmutable, OnSecurityChanged));
|
||||
static void OnSecurityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PriceEntryControl)d)._update_text_binding();
|
||||
public SecurityImmutable? Security { get => GetValue(SecurityProperty) as SecurityImmutable?; set => SetValue(SecurityProperty, value); }
|
||||
#endregion
|
||||
|
||||
TextBox _text;
|
||||
@@ -71,8 +69,8 @@ namespace mbts.ui.spark {
|
||||
if (double.IsNaN(v)) {
|
||||
SetCurrentValue(ValueProperty, TickDefaultValue);
|
||||
} else {
|
||||
var spec = ContractSpec;
|
||||
if (spec.HasValue) SetCurrentValue(ValueProperty, spec.Value.tickup(v));
|
||||
var sec = Security;
|
||||
if (sec.HasValue) SetCurrentValue(ValueProperty, sec.Value.tickup(v));
|
||||
else SetCurrentValue(ValueProperty, TickDefaultValue);
|
||||
}
|
||||
}
|
||||
@@ -85,21 +83,21 @@ namespace mbts.ui.spark {
|
||||
if (double.IsNaN(v)) {
|
||||
SetCurrentValue(ValueProperty, TickDefaultValue);
|
||||
} else {
|
||||
var spec = ContractSpec;
|
||||
if (spec.HasValue) SetCurrentValue(ValueProperty, spec.Value.tickdown(v));
|
||||
var sec = Security;
|
||||
if (sec.HasValue) SetCurrentValue(ValueProperty, sec.Value.tickdown(v));
|
||||
else SetCurrentValue(ValueProperty, TickDefaultValue);
|
||||
}
|
||||
}
|
||||
|
||||
void _update_text_binding() {
|
||||
if (_text != null) {
|
||||
var spec = ContractSpec;
|
||||
if (spec != null) {
|
||||
var sec = Security;
|
||||
if (sec != null) {
|
||||
var be = _text.GetBindingExpression(TextBox.TextProperty);
|
||||
if (be != null) {
|
||||
var converter = be.ParentBinding.Converter as TickDisplayTwoWayConverter;
|
||||
if (converter != null) {
|
||||
converter.ContractSpec = spec;
|
||||
converter.Security = sec;
|
||||
be.UpdateTarget();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,9 +16,9 @@ namespace mbts.ui.spark.converters {
|
||||
}
|
||||
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
|
||||
var price = get_val<double>(values, 0);
|
||||
var spec = get_val<ContractSpecificationImmutable?>(values, 1);
|
||||
if (spec == null) return price.ToString();
|
||||
return spec.Value.format(price);
|
||||
var security = get_val<SecurityImmutable?>(values, 1);
|
||||
if (security == null) return price.ToString();
|
||||
return security.Value.format(price);
|
||||
}
|
||||
|
||||
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
|
||||
@@ -26,23 +26,17 @@ namespace mbts.ui.spark.converters {
|
||||
}
|
||||
|
||||
class TickDisplayTwoWayConverter : IValueConverter {
|
||||
public ContractSpecificationImmutable? ContractSpec { get; set; } =
|
||||
new ContractSpecification {
|
||||
CashPerPoint = 1.0,
|
||||
LowTick = 0.01,
|
||||
HighTick = 0.01,
|
||||
PriceBreak = double.MaxValue,
|
||||
PriceMultiplier = 1.0
|
||||
};
|
||||
public SecurityImmutable? Security { get; set; } =
|
||||
SecurityDataHelper.Defaults.SecurityImmutable;
|
||||
|
||||
public double DisplayMultiplier { get; set; } = double.NaN;
|
||||
public bool ShowCommas { get; set; } = false;
|
||||
public string NaNText { get; set; } = string.Empty;
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
|
||||
ContractSpec.Value.format((double)value, DisplayMultiplier, ShowCommas, NaNText);
|
||||
Security.format((double)value, DisplayMultiplier, ShowCommas, NaNText);
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
|
||||
ContractSpec.Value.parse(value as string, DisplayMultiplier, NaNText);
|
||||
Security.parse(value as string, DisplayMultiplier, NaNText);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ namespace mbts.ui.converters {
|
||||
class TickFactorsTextConverter : IValueConverter {
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||
if (value is TickFactors tf) {
|
||||
int n_digits = TickExtensions.n_display_digits(tf.tick_base);
|
||||
int n_digits = tf.display_digits();
|
||||
if (n_digits > 1) {
|
||||
string n_digits_format = new string('0', n_digits);
|
||||
string format = "{0:" + n_digits_format + "}/{1}";
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using bts.api;
|
||||
using System.IO;
|
||||
using mbts.ui.shell;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
public class DataPersistor
|
||||
{
|
||||
private List<IDisposable> _disp_list = new List<IDisposable>();
|
||||
private readonly IBus _bus;
|
||||
private readonly string _loc = @"C:\ProgramData\bts\temp_securities.bin"; /// TODO
|
||||
|
||||
private SparkBusData.PersistedItems _persisted_items = new SparkBusData.PersistedItems();
|
||||
|
||||
public DataPersistor(IBus bus)
|
||||
{
|
||||
_bus = bus;
|
||||
var sub = _bus.subscribe<SparkBusData.PersistMessage>(SparkTags.PersistCommandTag);
|
||||
_disp_list.Add(sub.Subscribe(p => _on_new_persist_message(p)));
|
||||
_persisted_items = _read_data_from_file();
|
||||
_bus.post(SparkTags.PersistedItemsTag, _persisted_items);
|
||||
}
|
||||
|
||||
private void _on_new_persist_message(SparkBusData.PersistMessage p)
|
||||
{
|
||||
_persisted_items.items.Add(p);
|
||||
_write_to_file(_persisted_items);
|
||||
_bus.post(SparkTags.PersistedItemsTag, new SparkBusData.PersistedItems(_persisted_items.items));
|
||||
}
|
||||
|
||||
private void _write_to_file(SparkBusData.PersistedItems items)
|
||||
{
|
||||
byte[] data = SparkUtils.serialize_proto(items);
|
||||
try
|
||||
{
|
||||
File.WriteAllBytes(_loc, data);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.gen, ex.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
private SparkBusData.PersistedItems _read_data_from_file()
|
||||
{
|
||||
var rv = new SparkBusData.PersistedItems();
|
||||
try
|
||||
{
|
||||
if (File.Exists(_loc)) {
|
||||
byte[] data = File.ReadAllBytes(_loc);
|
||||
rv = SparkUtils.deserialize_proto<SparkBusData.PersistedItems>(data);
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
using bts.api;
|
||||
using bts.api.orderman;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using static mbts.ui.utilities.DisplayNameHelper;
|
||||
@@ -75,7 +73,7 @@ namespace mbts.spark {
|
||||
if (order.HasDef) {
|
||||
sec_key_text = $"Security: {order.Def.SecurityKey}";
|
||||
if (order.HasState) {
|
||||
sb.AppendLine($"{order.Def.Side}: {TickUtils.format(security.ContractSpec, order.State.Price)}");
|
||||
sb.AppendLine($"{order.Def.Side}: {security.format(order.State.Price)}");
|
||||
sb.AppendLine($"Filled: {filled(order)} / {order.State.Quantity}");
|
||||
} else {
|
||||
sb.AppendLine($"{order.Def.Side}: (price-unknown)");
|
||||
@@ -97,8 +95,8 @@ namespace mbts.spark {
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
public static string short_description(this OrderRecordImmutable order, ContractSpecificationImmutable? spec) =>
|
||||
$"{(order.HasDef ? order.Def.Side.ToString() : "(unknown-side)")} {(order.HasState ? ($@"{spec.format(order.State.Price)} @ {order.State.Quantity}") : "(unknown-price) @ (unknown-quantity)")}";
|
||||
public static string short_description(this OrderRecordImmutable order, SecurityImmutable? security) =>
|
||||
$"{(order.HasDef ? order.Def.Side.ToString() : "(unknown-side)")} {(order.HasState ? ($@"{security.format(order.State.Price)} @ {order.State.Quantity}") : "(unknown-price) @ (unknown-quantity)")}";
|
||||
|
||||
public static bool has_parent(this OrderRecordImmutable order) =>
|
||||
order.ParentKey != 0;
|
||||
@@ -121,24 +119,12 @@ namespace mbts.spark {
|
||||
public static string order_type_display_name(CustomOrderDefinition.CustomOneofCase order_type) =>
|
||||
camel_to_title_case(Regex.Replace(order_type.ToString(), "Order", string.Empty, RegexOptions.IgnoreCase));
|
||||
|
||||
public static string order_collection_summary(ICollection<OrderRecordImmutable> orders, Comparison<double> compare_price, ContractSpecificationImmutable spec) {
|
||||
if (orders.Count == 0) return string.Empty;
|
||||
var price_lookup = orders.ToLookup(o => o.State.Price);
|
||||
var best_price = price_lookup.MaxElement(g => g.Key, compare_price);
|
||||
var best_price_volume = best_price.Sum(o => o.working_quantity());
|
||||
return order_collection_summary(
|
||||
best_price.Key,
|
||||
best_price_volume,
|
||||
best_price_volume + price_lookup.Where(g => g.Key != best_price.Key).SelectMany(g => g).Sum(o => o.working_quantity()),
|
||||
spec);
|
||||
}
|
||||
|
||||
public static string order_collection_summary(double best_price, int best_price_volume, int total_volume, ContractSpecificationImmutable spec) {
|
||||
public static string order_collection_summary(double best_price, int best_price_volume, int total_volume, SecurityImmutable security) {
|
||||
if (total_volume == 0)
|
||||
return string.Empty;
|
||||
return total_volume == best_price_volume ?
|
||||
$"{best_price_volume} @ {spec.format(best_price)}" :
|
||||
$"{best_price_volume} ({total_volume}) @ {spec.format(best_price)}";
|
||||
$"{best_price_volume} @ {security.format(best_price)}" :
|
||||
$"{best_price_volume} ({total_volume}) @ {security.format(best_price)}";
|
||||
}
|
||||
|
||||
public static string past_tense(this Side side) {
|
||||
|
||||
@@ -6,105 +6,31 @@ using mbts.utils;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
|
||||
namespace mbts.spark {
|
||||
static class TickUtils {
|
||||
#region TickFactors Cache
|
||||
static readonly TickFactors _default_tick = new TickFactors(100, 1);
|
||||
|
||||
static readonly ConcurrentDictionary<double, bool> _resolved_unknown_ticks = new ConcurrentDictionary<double, bool>();
|
||||
|
||||
static readonly ConcurrentDictionary<(double low_tick, double high_tick, double price_break), RegionalTickFactors> _regional_ticks_cache =
|
||||
new ConcurrentDictionary<(double low_tick, double high_tick, double price_break), RegionalTickFactors>();
|
||||
|
||||
static readonly double[] _descending_tick_fractional_units;
|
||||
|
||||
static readonly IReadOnlyDictionary<double, TickFactors> _ticks_cache = new[] {
|
||||
// 100 based
|
||||
new { tick_unit = 0.01, tick_factors = new TickFactors(100, 1) }, // 1/100
|
||||
new { tick_unit = 0.05, tick_factors = new TickFactors(100, 5) }, // 1/20
|
||||
new { tick_unit = 0.10, tick_factors = new TickFactors(100, 10) }, // 1/10
|
||||
new { tick_unit = 0.25, tick_factors = new TickFactors(100, 25) }, // 1/4
|
||||
new { tick_unit = 0.50, tick_factors = new TickFactors(100, 50) }, // 1/2
|
||||
// 1,000 based
|
||||
new { tick_unit = 0.001, tick_factors = new TickFactors(1000, 1) }, // 1/1,000
|
||||
new { tick_unit = 0.005, tick_factors = new TickFactors(1000, 5) }, // 1/200
|
||||
new { tick_unit = 0.025, tick_factors = new TickFactors(1000, 25) }, // 1/40
|
||||
// 10,000 based
|
||||
new { tick_unit = 0.0001, tick_factors = new TickFactors(10000, 1) }, // 1/10,000
|
||||
new { tick_unit = 0.0005, tick_factors = new TickFactors(10000, 5) }, // 1/2,000
|
||||
new { tick_unit = 0.0025, tick_factors = new TickFactors(10000, 25) }, // 1/400
|
||||
// 64 based
|
||||
new { tick_unit = 0.015625, tick_factors = new TickFactors(64, 1) }, // 1/64
|
||||
new { tick_unit = 0.03125, tick_factors = new TickFactors(64, 2) }, // 1/32
|
||||
new { tick_unit = 0.0625, tick_factors = new TickFactors(64, 4) }, // 1/16
|
||||
new { tick_unit = 0.125, tick_factors = new TickFactors(64, 8) }, // 1/8
|
||||
// 640 based
|
||||
new { tick_unit = 0.0015625, tick_factors = new TickFactors(640, 1) }, // 1/640
|
||||
new { tick_unit = 0.003125, tick_factors = new TickFactors(640, 2) }, // 1/320
|
||||
new { tick_unit = 0.00625, tick_factors = new TickFactors(640, 4) }, // 1/160
|
||||
new { tick_unit = 0.0078125, tick_factors = new TickFactors(640, 5) }, // 1/128
|
||||
new { tick_unit = 0.0125, tick_factors = new TickFactors(640, 8) }, // 1/80
|
||||
new { tick_unit = 0.0390625, tick_factors = new TickFactors(640, 25) }, // 5/128
|
||||
new { tick_unit = 0.078125, tick_factors = new TickFactors(640, 50) }, // 5/64
|
||||
// 6,400 based
|
||||
new { tick_unit = 0.00015625, tick_factors = new TickFactors(6400, 1) }, // 1/6,400
|
||||
new { tick_unit = 0.0003125, tick_factors = new TickFactors(6400, 2) }, // 1/3,200
|
||||
new { tick_unit = 0.000625, tick_factors = new TickFactors(6400, 4) }, // 1/1,600
|
||||
new { tick_unit = 0.00078125, tick_factors = new TickFactors(6400, 5) }, // 1/1,280
|
||||
new { tick_unit = 0.00125, tick_factors = new TickFactors(6400, 8) }, // 1/800
|
||||
new { tick_unit = 0.00390625, tick_factors = new TickFactors(6400, 25) }, // 1/256
|
||||
// 64,000 based
|
||||
new { tick_unit = 0.000015625, tick_factors = new TickFactors(64000, 1) }, // 1/6,400
|
||||
new { tick_unit = 0.00003125, tick_factors = new TickFactors(64000, 2) }, // 1/3,200
|
||||
new { tick_unit = 0.0000625, tick_factors = new TickFactors(64000, 4) }, // 1/1,600
|
||||
new { tick_unit = 0.000078125, tick_factors = new TickFactors(64000, 5) }, // 1/12,800
|
||||
new { tick_unit = 0.000125, tick_factors = new TickFactors(64000, 8) }, // 1/8,000
|
||||
new { tick_unit = 0.000390625, tick_factors = new TickFactors(64000, 25) }, // 1/2,560
|
||||
new { tick_unit = 0.001953125, tick_factors = new TickFactors(64000, 125) },// 1/512
|
||||
}.ToReadOnlyDictionary(obj => obj.tick_unit, obj => obj.tick_factors, EqualityComparer.Create<double>(MathUtils.epsilon_equals));
|
||||
#endregion
|
||||
|
||||
static TickUtils() {
|
||||
// overkill? Maybe, but ticks are fundamental to the entire application.
|
||||
// Any changes to the tick defaults must be deliberate, and scrutinized.
|
||||
Logger.assert(_ticks_cache.Count == 35);
|
||||
foreach(var kv in _ticks_cache) {
|
||||
double result = kv.Value.tick_unit / kv.Value.tick_base;
|
||||
Logger.assert(result == kv.Key, $"{kv.Value.tick_unit}/{kv.Value.tick_base} ({result} != {kv.Key})");
|
||||
}
|
||||
_descending_tick_fractional_units = _ticks_cache.Keys.Ordered(new ReverseComparer<double>(Comparer<double>.Default)).ToLArray();
|
||||
}
|
||||
|
||||
public static double ticksize(this ContractSpecificationImmutable spec, double price) =>
|
||||
Math.Abs(price) > spec.PriceBreak ? spec.HighTick : spec.LowTick;
|
||||
|
||||
public static string format(this ContractSpecificationImmutable spec, double price) {
|
||||
var tick_factors = _get_tick_factors(spec.ticksize(price));
|
||||
return tick_factors.format(price, false);
|
||||
}
|
||||
public static string format(this ContractSpecificationImmutable? spec, double price) {
|
||||
if (spec.HasValue) {
|
||||
return spec.Value.format(price);
|
||||
}
|
||||
return price.ToString("0.00000");
|
||||
}
|
||||
public static string format(this SecurityImmutable security, double price) =>
|
||||
TickStore.get(security).format(price);
|
||||
|
||||
public static string format(this ContractSpecificationImmutable spec, double price, double display_multiplier, bool show_commas, string nan_text) {
|
||||
var tick_factors = _get_tick_factors(spec.ticksize(price));
|
||||
return tick_factors.format(price, display_multiplier, show_commas, nan_text);
|
||||
}
|
||||
public static string format(this SecurityImmutable? security, double price) =>
|
||||
security.HasValue ? security.Value.format(price) : price.ToString("0.00000");
|
||||
|
||||
public static double parse(this ContractSpecificationImmutable spec, string text) {
|
||||
var regional_tfs = get_regional_ticks(spec);
|
||||
return regional_tfs.parse(text);
|
||||
}
|
||||
public static string format(this SecurityImmutable security, double price, double display_multiplier, bool show_commas, string nan_text) =>
|
||||
TickStore.get(security).format(price, display_multiplier, show_commas, nan_text);
|
||||
|
||||
public static double parse(this ContractSpecificationImmutable spec, string text, double display_multiplier, string nan_text) {
|
||||
var regional_tfs = get_regional_ticks(spec);
|
||||
return regional_tfs.parse(text, display_multiplier, nan_text);
|
||||
}
|
||||
public static string format(this SecurityImmutable? security, double price, double display_multiplier, bool show_commas, string nan_text) =>
|
||||
TickStore.get(security).format(price, display_multiplier, show_commas, nan_text);
|
||||
|
||||
public static double parse(this SecurityImmutable security, string text, double display_multiplier, string nan_text) =>
|
||||
TickStore.get(security).parse(text, display_multiplier, nan_text);
|
||||
|
||||
public static double parse(this SecurityImmutable? security, string text, double display_multiplier, string nan_text) =>
|
||||
TickStore.get(security).parse(text, display_multiplier, nan_text);
|
||||
|
||||
public static double low_tick(NativePriceSize[] bids, NativePriceSize[] asks) {
|
||||
double low = bids[bids.Length - 1].price;
|
||||
@@ -124,11 +50,11 @@ namespace mbts.spark {
|
||||
return high;
|
||||
}
|
||||
|
||||
public static (int n_low, int n_high) tick_diff(ContractSpecificationImmutable spec, double x, double y) =>
|
||||
get_regional_ticks(spec).tickdiff(x, y);
|
||||
public static (int n_low, int n_high) tick_diff(SecurityImmutable security, double x, double y) =>
|
||||
get_regional_ticks(security).tickdiff(x, y);
|
||||
|
||||
public static int normalized_tick_diff(ContractSpecificationImmutable spec, double x, double y) {
|
||||
var (n_low, n_high) = tick_diff(spec, x, y);
|
||||
public static int normalized_tick_diff(SecurityImmutable security, double x, double y) {
|
||||
var (n_low, n_high) = tick_diff(security, x, y);
|
||||
return n_low + n_high;
|
||||
}
|
||||
|
||||
@@ -146,36 +72,38 @@ namespace mbts.spark {
|
||||
return raw_mid - (raw_mid % tick_size);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<TickFactors> all_present_ticks() =>
|
||||
_ticks_cache.Values.ToReadOnlyList();
|
||||
public static IReadOnlyCollection<TickFactors> synthetic_presets =>
|
||||
TickStore.synthetic_presets;
|
||||
|
||||
public static TickFactors deduce_ticks(IEnumerable<ContractSpecification> contract_specs) {
|
||||
var gcd = MathUtils.GCD(contract_specs.Select(s => s.LowTick));
|
||||
if (gcd == 0) return null;
|
||||
return _try_get_tick_factors(gcd);
|
||||
return TickStore.get_tick_factors(gcd);
|
||||
}
|
||||
|
||||
public static double tickup(this ContractSpecificationImmutable contract, double value) =>
|
||||
get_regional_ticks(contract).tickup(value);
|
||||
public static double tickup(this SecurityImmutable security, double value) =>
|
||||
TickStore.get(security).tickup(value);
|
||||
|
||||
public static double tickup(this ContractSpecificationImmutable contract, double value, int count) =>
|
||||
get_regional_ticks(contract).tickup(value, (uint)count);
|
||||
public static double tickup(this SecurityImmutable security, double value, int count) =>
|
||||
TickStore.get(security).tickup(value, (uint)count);
|
||||
|
||||
public static double tickdown(this ContractSpecificationImmutable contract, double value) =>
|
||||
get_regional_ticks(contract).tickdown(value);
|
||||
public static double tickdown(this SecurityImmutable security, double value) =>
|
||||
TickStore.get(security).tickdown(value);
|
||||
|
||||
public static double tickdown(this ContractSpecificationImmutable contract, double value, int count) =>
|
||||
get_regional_ticks(contract).tickdown(value, (uint)count);
|
||||
public static double tickdown(this SecurityImmutable security, double value, int count) =>
|
||||
TickStore.get(security).tickdown(value, (uint)count);
|
||||
|
||||
public static bool tick_equals(this SecurityImmutable security, double x, double y) =>
|
||||
tick_equals(security.ContractSpec, x, y);
|
||||
|
||||
public static bool tick_equals(this ContractSpecificationImmutable contract, double x, double y) =>
|
||||
MathUtils.RoundFractionalUnits(x, contract.LowTick) == MathUtils.RoundFractionalUnits(y, contract.LowTick);
|
||||
|
||||
public static IEqualityComparer<double> tick_equality_comparer(this ContractSpecificationImmutable contract)
|
||||
{
|
||||
var eq = EqualityComparer.Create((double a, double b) => TickUtils.tick_equals(contract, a, b),
|
||||
x => MathUtils.RoundFractionalUnits(x, contract.LowTick));
|
||||
return eq;
|
||||
}
|
||||
public static IEqualityComparer<double> tick_equality_comparer(this SecurityImmutable security) =>
|
||||
security.ContractSpec.tick_equality_comparer();
|
||||
|
||||
public static IEqualityComparer<double> tick_equality_comparer(this ContractSpecificationImmutable contract) =>
|
||||
EqualityComparer.Create((double a, double b) => tick_equals(contract, a, b), x => MathUtils.RoundFractionalUnits(x, contract.LowTick));
|
||||
|
||||
public static double round_to_tick(this ContractSpecificationImmutable spec, double value) {
|
||||
double intpart = (long)value;
|
||||
@@ -185,47 +113,236 @@ namespace mbts.spark {
|
||||
return intpart + floatpart;
|
||||
}
|
||||
|
||||
public static RegionalTickFactors get_regional_ticks(ContractSpecificationImmutable spec) =>
|
||||
_regional_ticks_cache.GetOrAdd((spec.LowTick, spec.HighTick, spec.PriceBreak), _create_regional_ticks);
|
||||
public static RegionalTickFactors get_regional_ticks(SecurityImmutable security) =>
|
||||
TickStore.get(security);
|
||||
|
||||
public static RegionalTickFactors get_regional_ticks(ContractSpecification spec) =>
|
||||
_regional_ticks_cache.GetOrAdd((spec.LowTick, spec.HighTick, spec.PriceBreak), _create_regional_ticks);
|
||||
public static class CompareUtils {
|
||||
public static IComparer<TickFactors> base_unit_comparer =>
|
||||
Comparer<TickFactors>.Create(utils.CompareUtils.safe_comparison<TickFactors>(compare_base_unit));
|
||||
|
||||
static RegionalTickFactors _create_regional_ticks((double low_tick, double high_tick, double price_break) def) =>
|
||||
new RegionalTickFactors(_get_tick_factors(def.low_tick), _get_tick_factors(def.high_tick), def.price_break);
|
||||
|
||||
static TickFactors _get_tick_factors(double tick) {
|
||||
if (_ticks_cache.TryGetValue(tick, out TickFactors result))
|
||||
return result;
|
||||
// try to return the largest known tick that is divisible by this tick
|
||||
foreach (var tfu in _descending_tick_fractional_units) {
|
||||
double mod = tick % tfu;
|
||||
if (MathUtils.epsilon_equals(mod, 0)) {
|
||||
if (_resolved_unknown_ticks.TryAdd(tick, true))
|
||||
Logger.warn(bts.log.Subsystem.Ui, $"Resolved unknown tick {tick} to {tfu}, if this tick is expected, talk to John about adding it to the hard-coded defaults ASAP.");
|
||||
return _ticks_cache[tfu];
|
||||
}
|
||||
public static int compare_base_unit(TickFactors a, TickFactors b) {
|
||||
int comp = a.reduced_base().CompareTo(b.reduced_base());
|
||||
if (comp != 0)
|
||||
return comp;
|
||||
comp = a.tick_base.CompareTo(b.tick_base);
|
||||
if (comp != 0)
|
||||
return comp;
|
||||
return a.tick_unit.CompareTo(b.tick_unit);
|
||||
}
|
||||
Logger.assert(false, $"Unable to resolve tick ({tick}): going down because the application cannot run properly with unresolved ticks. " +
|
||||
$"FOR DEVS: If this tick was not caused by a bug, please talk to John about adding it to the hard-coded defaults. " +
|
||||
$"If you believe this tick belongs to a synthetic security, and should not be in the defaults, please delete said synthetic from the db " +
|
||||
$"(note: the synthetic creation dialog has changed to only allow known ticks from now on, so if you get the latest code and delete old synthetics from the db, this will not happen again). " +
|
||||
$"Direct any further questions to John.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Almost the same function as _get_tick_factors, only difference being no assert/log.
|
||||
// This seemed more practical than trying to factor this behavior out, it's only a few lines of code.
|
||||
static TickFactors _try_get_tick_factors(double tick) {
|
||||
if (_ticks_cache.TryGetValue(tick, out TickFactors result))
|
||||
return result;
|
||||
// try to return the largest known tick that is divisible by this tick
|
||||
foreach (var tfu in _descending_tick_fractional_units) {
|
||||
double mod = tick % tfu;
|
||||
if (MathUtils.epsilon_equals(mod, 0))
|
||||
return _ticks_cache[tfu];
|
||||
static class TickStore {
|
||||
static readonly RegionalTickFactors _default_rtf = new RegionalTickFactors(new TickFactors(1000, 1), new TickFactors(1000, 1), double.MaxValue);
|
||||
static readonly ConcurrentDictionary<SpecKey, RegionalTickFactors> _exchange_ticks = new ConcurrentDictionary<SpecKey, RegionalTickFactors>();
|
||||
|
||||
static readonly ReadOnlyDictionary<double, TickFactors> _synthetic_presets_cache = new[] {
|
||||
// 100 based
|
||||
new { tick_unit = 0.01, tick_factors = new TickFactors(100, 1) }, // 1/100
|
||||
new { tick_unit = 0.05, tick_factors = new TickFactors(100, 5) }, // 1/20
|
||||
new { tick_unit = 0.10, tick_factors = new TickFactors(100, 10) }, // 1/10
|
||||
new { tick_unit = 0.25, tick_factors = new TickFactors(100, 25) }, // 1/4
|
||||
new { tick_unit = 0.50, tick_factors = new TickFactors(100, 50) }, // 1/2
|
||||
// 1,000 based
|
||||
new { tick_unit = 0.001, tick_factors = new TickFactors(1000, 1) }, // 1/1,000
|
||||
new { tick_unit = 0.005, tick_factors = new TickFactors(1000, 5) }, // 1/200
|
||||
new { tick_unit = 0.025, tick_factors = new TickFactors(1000, 25) }, // 1/40
|
||||
// 10,000 based
|
||||
new { tick_unit = 0.0001, tick_factors = new TickFactors(10000, 1) }, // 1/10,000
|
||||
new { tick_unit = 0.0005, tick_factors = new TickFactors(10000, 5) }, // 1/2,000
|
||||
new { tick_unit = 0.0025, tick_factors = new TickFactors(10000, 25) }, // 1/400
|
||||
// 64 based
|
||||
new { tick_unit = 0.015625, tick_factors = new TickFactors(64, 1) }, // 1/64
|
||||
new { tick_unit = 0.03125, tick_factors = new TickFactors(64, 2) }, // 1/32
|
||||
new { tick_unit = 0.0625, tick_factors = new TickFactors(64, 4) }, // 1/16
|
||||
new { tick_unit = 0.125, tick_factors = new TickFactors(64, 8) }, // 1/8
|
||||
// 640 based
|
||||
new { tick_unit = 0.0015625, tick_factors = new TickFactors(640, 1) }, // 1/640
|
||||
new { tick_unit = 0.003125, tick_factors = new TickFactors(640, 2) }, // 1/320
|
||||
new { tick_unit = 0.00625, tick_factors = new TickFactors(640, 4) }, // 1/160
|
||||
new { tick_unit = 0.0078125, tick_factors = new TickFactors(640, 5) }, // 1/128
|
||||
new { tick_unit = 0.0125, tick_factors = new TickFactors(640, 8) }, // 1/80
|
||||
new { tick_unit = 0.0390625, tick_factors = new TickFactors(640, 25) }, // 5/128
|
||||
new { tick_unit = 0.078125, tick_factors = new TickFactors(640, 50) }, // 5/64
|
||||
// 6,400 based
|
||||
new { tick_unit = 0.00015625, tick_factors = new TickFactors(6400, 1) }, // 1/6,400
|
||||
new { tick_unit = 0.0003125, tick_factors = new TickFactors(6400, 2) }, // 1/3,200
|
||||
new { tick_unit = 0.000625, tick_factors = new TickFactors(6400, 4) }, // 1/1,600
|
||||
new { tick_unit = 0.00078125, tick_factors = new TickFactors(6400, 5) }, // 1/1,280
|
||||
new { tick_unit = 0.00125, tick_factors = new TickFactors(6400, 8) }, // 1/800
|
||||
new { tick_unit = 0.00390625, tick_factors = new TickFactors(6400, 25) }, // 1/256
|
||||
// 64,000 based
|
||||
new { tick_unit = 0.000015625, tick_factors = new TickFactors(64000, 1) }, // 1/6,400
|
||||
new { tick_unit = 0.00003125, tick_factors = new TickFactors(64000, 2) }, // 1/3,200
|
||||
new { tick_unit = 0.0000625, tick_factors = new TickFactors(64000, 4) }, // 1/1,600
|
||||
new { tick_unit = 0.000078125, tick_factors = new TickFactors(64000, 5) }, // 1/12,800
|
||||
new { tick_unit = 0.000125, tick_factors = new TickFactors(64000, 8) }, // 1/8,000
|
||||
new { tick_unit = 0.000390625, tick_factors = new TickFactors(64000, 25) }, // 1/2,560
|
||||
new { tick_unit = 0.001953125, tick_factors = new TickFactors(64000, 125) },// 1/512
|
||||
}.ToReadOnlyDictionary(obj => obj.tick_unit, obj => obj.tick_factors, EqualityComparer.Create<double>(MathUtils.epsilon_equals));
|
||||
static readonly double[] _descending_synthetic_tick_sizes;
|
||||
|
||||
static TickStore() =>
|
||||
_descending_synthetic_tick_sizes = _synthetic_presets_cache.Select(kv => kv.Key).Ordered(new ReverseComparer<double>(Comparer<double>.Default)).ToArray();
|
||||
|
||||
public static IReadOnlyCollection<TickFactors> synthetic_presets => _synthetic_presets_cache.Values;
|
||||
|
||||
public static RegionalTickFactors get(SecurityImmutable security) {
|
||||
if (security.HasContractSpec) {
|
||||
if (security.ContractCase == Security.ContractOneofCase.Synthetic) {
|
||||
return get(security.ContractSpec.LowTick);
|
||||
} else if (security.HasGlbx) {
|
||||
return _exchange_ticks.GetOrAdd(new SpecKey(security.ContractSpec, security.Glbx), _create_rtf);
|
||||
}
|
||||
}
|
||||
return _default_rtf;
|
||||
}
|
||||
|
||||
public static RegionalTickFactors get(SecurityImmutable? security) =>
|
||||
security.HasValue ? get(security.Value) : _default_rtf;
|
||||
|
||||
public static RegionalTickFactors get(double tick_size) {
|
||||
var tf = get_tick_factors(tick_size);
|
||||
return new RegionalTickFactors(tf, tf, double.MaxValue);
|
||||
}
|
||||
|
||||
public static TickFactors get_tick_factors(double tick_size) {
|
||||
if (_synthetic_presets_cache.TryGetValue(tick_size, out TickFactors result))
|
||||
return result;
|
||||
// try to return the largest known tick that is divisible by this tick
|
||||
foreach (var tfu in _descending_synthetic_tick_sizes) {
|
||||
double mod = tick_size % tfu;
|
||||
if (MathUtils.epsilon_equals(mod, 0)) {
|
||||
return _synthetic_presets_cache[tfu];
|
||||
}
|
||||
}
|
||||
return new TickFactors(1 / tick_size, tick_size);
|
||||
}
|
||||
|
||||
static RegionalTickFactors _create_rtf(SpecKey key) {
|
||||
double tick_base = key.denominator;
|
||||
if (tick_base == 0) {
|
||||
// indicates tick is a decimal
|
||||
tick_base = 100;
|
||||
}
|
||||
return _create_rtf(key.low_tick, key.high_tick, key.price_break, tick_base, key.display_digits);
|
||||
}
|
||||
|
||||
static RegionalTickFactors _create_rtf(double low_tick, double high_tick, double price_break, double reduced_target_base, uint display_digits_override) {
|
||||
var low_tf = _try_create_tf(low_tick, reduced_target_base, display_digits_override);
|
||||
var high_tf = _try_create_tf(high_tick, reduced_target_base, display_digits_override);
|
||||
if (low_tf == null) {
|
||||
low_tf = high_tf ?? (high_tf = _default_rtf.low_tick);
|
||||
} else if (high_tf == null)
|
||||
high_tf = low_tf;
|
||||
else {
|
||||
// if low/high tick-bases do not match, inflate the smaller base so they do
|
||||
// Note: this assumes the tick-bases are related by factors of 10 (i.e. they have all the same prime factors except for a different number of pairs of 5 and 2, e.g. 64 and 640)
|
||||
if (low_tf.tick_base > high_tf.tick_base) {
|
||||
high_tf = _inflate_to_base(high_tf, low_tf.tick_base);
|
||||
} else if (low_tf.tick_base < high_tf.tick_base) {
|
||||
low_tf = _inflate_to_base(low_tf, high_tf.tick_base);
|
||||
}
|
||||
}
|
||||
return new RegionalTickFactors(low_tf, high_tf, price_break);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates TickFactors with a base equal to "<paramref name="tick_base"/> * 10^n," where 'n' is a natural number (including 0).
|
||||
/// <para>Note: If <paramref name="display_digits_override"/> is non-zero, 'n' will be "<paramref name="display_digits_override"/> - Math.Ceiling(Log10(<paramref name="tick_base"/>))"</para>
|
||||
/// </summary>
|
||||
/// <param name="tick_size">The raw tick-size.</param>
|
||||
/// <param name="tick_base">The raw tick-base.</param>
|
||||
/// <returns>Well-defined TickFactors</returns>
|
||||
static TickFactors _try_create_tf(double tick_size, double tick_base, uint display_digits_override) {
|
||||
var tf = _try_create_tf(tick_size, tick_base);
|
||||
if (tf != null && display_digits_override > 0) {
|
||||
int display_digit_diff = (int)display_digits_override - tf.display_digits();
|
||||
if (display_digit_diff != 0)
|
||||
tf = _inflate_to_base(tf, tf.tick_base * Math.Pow(10, display_digit_diff));
|
||||
}
|
||||
return tf;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates TickFactors with a base equal to "reduced_target_base * 10^n," where 'n' is a natural number (including 0).
|
||||
/// </summary>
|
||||
/// <param name="tick_size">The raw tick-size.</param>
|
||||
/// <param name="reduced_target_base">The smallest acceptable tick-base.</param>
|
||||
/// <returns>Well-defined TickFactors</returns>
|
||||
static TickFactors _try_create_tf(double tick_size, double reduced_target_base) {
|
||||
if (!_check_tick_size(tick_size))
|
||||
return null;
|
||||
double raw_base = 1 / tick_size;
|
||||
double raw_base_log10 = Math.Log10(raw_base);
|
||||
double reduced_target_base_log10 = Math.Log10(reduced_target_base);
|
||||
double log10_diff = raw_base_log10 - reduced_target_base_log10;
|
||||
if (MathUtils.is_int(log10_diff))
|
||||
return raw_base > reduced_target_base ? new TickFactors(raw_base, 1) : new TickFactors(reduced_target_base, Math.Pow(10, -log10_diff));
|
||||
int count = 0;
|
||||
double factored_base = log10_diff > 0 ? reduced_target_base * Math.Pow(10, Math.Ceiling(log10_diff)) : reduced_target_base;
|
||||
do {
|
||||
if (factored_base % raw_base == 0)
|
||||
return new TickFactors(factored_base, factored_base / raw_base);
|
||||
factored_base *= 10;
|
||||
} while (++count < 10);
|
||||
return null;
|
||||
}
|
||||
|
||||
static TickFactors _create_tf(double tick_size) {
|
||||
if (!_check_tick_size(tick_size))
|
||||
return _default_rtf.low_tick;
|
||||
double matched_unit = double.MinValue;
|
||||
TickFactors matched_tf = null;
|
||||
foreach (var kv in _exchange_ticks) {
|
||||
if (kv.Key.high_tick == tick_size) {
|
||||
return kv.Value.high_tick;
|
||||
} else if (kv.Key.low_tick == tick_size) {
|
||||
return kv.Value.low_tick;
|
||||
} else if (is_better_match(kv.Key.high_tick)) {
|
||||
matched_unit = kv.Key.high_tick;
|
||||
matched_tf = kv.Value.high_tick;
|
||||
} else if (is_better_match(kv.Key.low_tick)) {
|
||||
matched_unit = kv.Key.low_tick;
|
||||
matched_tf = kv.Value.low_tick;
|
||||
}
|
||||
}
|
||||
return matched_tf ?? new TickFactors(1.0 / tick_size, 1);
|
||||
|
||||
bool is_better_match(double known_unit) =>
|
||||
known_unit < tick_size && known_unit > matched_unit && tick_size % known_unit == 0;
|
||||
}
|
||||
|
||||
static bool _check_tick_size(double tick_size) =>
|
||||
tick_size > 0 && tick_size <= 0.5;
|
||||
|
||||
static TickFactors _inflate_to_base(TickFactors tick_factors, double new_base) =>
|
||||
new TickFactors(new_base, tick_factors.tick_unit * new_base / tick_factors.tick_base);
|
||||
|
||||
struct SpecKey : IEquatable<SpecKey> {
|
||||
public readonly uint denominator, display_digits;
|
||||
public readonly double low_tick, high_tick, price_break;
|
||||
|
||||
public SpecKey(ContractSpecificationImmutable spec, GLBXExchangeDataImmutable glbx_data) {
|
||||
denominator = glbx_data.MainFraction;
|
||||
display_digits = glbx_data.PriceDisplayFormat;
|
||||
low_tick = spec.LowTick;
|
||||
high_tick = spec.HighTick;
|
||||
price_break = spec.PriceBreak;
|
||||
}
|
||||
|
||||
public bool Equals(SpecKey other) =>
|
||||
denominator == other.denominator &&
|
||||
display_digits == other.display_digits &&
|
||||
low_tick == other.low_tick &&
|
||||
high_tick == other.high_tick &&
|
||||
price_break == other.price_break;
|
||||
|
||||
public override bool Equals(object obj) =>
|
||||
obj is SpecKey sk && Equals(sk);
|
||||
|
||||
public override int GetHashCode() =>
|
||||
EqualityComparer.aggregate_hash((int)denominator, (int)display_digits, low_tick.GetHashCode(), high_tick.GetHashCode(), price_break.GetHashCode());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,6 @@ namespace mbts.spark {
|
||||
|
||||
static class SecurityRowExtensions {
|
||||
public static string format_price(this ISecurityRow row, double price) =>
|
||||
row.security.ContractSpec.format(price);
|
||||
row.security.format(price);
|
||||
}
|
||||
}
|
||||
@@ -306,13 +306,13 @@ namespace mbts.spark {
|
||||
_settings.row_height,
|
||||
_price_list,
|
||||
column.settings,
|
||||
security.ContractSpec);
|
||||
security);
|
||||
break;
|
||||
case ColumnType.Ask: render_market_col(_asks); break;
|
||||
}
|
||||
void render_market_col(NativePriceSize[] depth) {
|
||||
var mid = LadderRender.index_of(_price_list, _last_origin_price, _price_comparer);
|
||||
LadderRender.render_sizes(column.visual_tup.visual, column.visual_tup.glyph_context, mid, _price_list, depth, _settings.row_height, security.ContractSpec, column.settings);
|
||||
LadderRender.render_sizes(column.visual_tup.visual, column.visual_tup.glyph_context, mid, _price_list, depth, _settings.row_height, security, column.settings);
|
||||
}
|
||||
}
|
||||
_apply_column_visual_offset();
|
||||
@@ -390,8 +390,8 @@ namespace mbts.spark {
|
||||
SparkUtils.lazy_warn(!double.IsNaN(_mkt_break_lines.origin) && _mkt_break_lines.origin >= low && _mkt_break_lines.origin <= high,
|
||||
() => fmt_log_msg($"market break ({_mkt_break_lines.origin}) is unacceptable for the market range ({low} - {high})"));
|
||||
int prev_row_count = _row_count;
|
||||
int n_ticks_to_low = TickUtils.normalized_tick_diff(security.ContractSpec, _mkt_break_lines.origin, low);
|
||||
int n_ticks_to_high = TickUtils.normalized_tick_diff(security.ContractSpec, high, _mkt_break_lines.origin);
|
||||
int n_ticks_to_low = TickUtils.normalized_tick_diff(security, _mkt_break_lines.origin, low);
|
||||
int n_ticks_to_high = TickUtils.normalized_tick_diff(security, high, _mkt_break_lines.origin);
|
||||
int desired_row_count = Math.Max(n_ticks_to_low, n_ticks_to_high) * 2 + 1;
|
||||
_row_count = Math.Min(_max_row_count, desired_row_count);
|
||||
if (_row_count != prev_row_count) {
|
||||
@@ -412,7 +412,7 @@ namespace mbts.spark {
|
||||
}
|
||||
if (update_prices) {
|
||||
var prev_price_list = _price_list;
|
||||
_price_list = LadderRender.render_prices(_price_vis_tup.visual, _price_vis_tup.glyph_context, _mkt_break_lines.origin, _row_count, _settings.row_height, _settings.price_column, security.ContractSpec);
|
||||
_price_list = LadderRender.render_prices(_price_vis_tup.visual, _price_vis_tup.glyph_context, _mkt_break_lines.origin, _row_count, _settings.row_height, _settings.price_column, security);
|
||||
_ordershost.update_settings(_price_list, _price_comparer, _settings.row_height, _settings.orders_column);
|
||||
if (prev_price_list != null) {
|
||||
// maintain previous visible price range if possible
|
||||
@@ -447,8 +447,8 @@ namespace mbts.spark {
|
||||
if (update_prices || depth_changed) {
|
||||
Logger.assert_d(_price_list != null);
|
||||
int origin_index = LadderRender.index_of(_price_list, _mkt_break_lines.origin, _price_comparer);
|
||||
LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, security.ContractSpec, _settings.bid_column);
|
||||
LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, security.ContractSpec, _settings.ask_column);
|
||||
LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, security, _settings.bid_column);
|
||||
LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, security, _settings.ask_column);
|
||||
}
|
||||
_last_origin_price = _mkt_break_lines.origin;
|
||||
_price_dirty = false;
|
||||
@@ -472,7 +472,7 @@ namespace mbts.spark {
|
||||
double best_bid = _get_top_price(_bids);
|
||||
double best_ask = _get_top_price(_asks);
|
||||
return double.IsNaN(best_bid) ?
|
||||
double.IsNaN(best_ask) ? _vm.low : security.ContractSpec.tickdown(best_ask) :
|
||||
double.IsNaN(best_ask) ? _vm.low : security.tickdown(best_ask) :
|
||||
best_bid;
|
||||
}
|
||||
|
||||
@@ -480,15 +480,15 @@ namespace mbts.spark {
|
||||
double best_bid = _get_top_price(_bids);
|
||||
double best_ask = _get_top_price(_asks);
|
||||
return double.IsNaN(best_ask) ?
|
||||
double.IsNaN(best_bid) ? security.ContractSpec.tickdown(_vm.high) : best_bid :
|
||||
security.ContractSpec.tickdown(best_ask);
|
||||
double.IsNaN(best_bid) ? security.tickdown(_vm.high) : best_bid :
|
||||
security.tickdown(best_ask);
|
||||
}
|
||||
|
||||
double _get_mid_market_break() {
|
||||
double best_bid = _get_top_price(_bids);
|
||||
double best_ask = _get_top_price(_asks);
|
||||
return double.IsNaN(best_bid) ?
|
||||
double.IsNaN(best_ask) ? 0.5 * (_vm.low + _vm.high) : security.ContractSpec.tickdown(best_ask) :
|
||||
double.IsNaN(best_ask) ? 0.5 * (_vm.low + _vm.high) : security.tickdown(best_ask) :
|
||||
double.IsNaN(best_ask) ? best_bid : TickUtils.mid_tick(security.ContractSpec, best_bid, best_ask);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
using bts.api;
|
||||
using bts.api.orderman;
|
||||
using bts.spark;
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using System;
|
||||
@@ -99,7 +98,7 @@ namespace mbts.spark {
|
||||
|
||||
if (_orders.Count > 0)
|
||||
{
|
||||
summary = _orders.Values.Select(order => order.short_description(_parent.security.ContractSpec)).Aggregate((s1, s2) => $"{s1}{Environment.NewLine}{Environment.NewLine}{s2}");
|
||||
summary = _orders.Values.Select(order => order.short_description(_parent.security)).Aggregate((s1, s2) => $"{s1}{Environment.NewLine}{Environment.NewLine}{s2}");
|
||||
description = _orders.Values.Select(order => order.full_description(_parent.security)).Aggregate((s1, s2) => $"{s1}{Environment.NewLine}{Environment.NewLine}{s2}");
|
||||
}
|
||||
_set_badge_text();
|
||||
@@ -197,4 +196,4 @@ namespace mbts.spark {
|
||||
return $"Price: {this.price} Order Count: {this.orders.Count()}";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,6 +143,8 @@ namespace mbts.spark {
|
||||
);
|
||||
}
|
||||
|
||||
public IBus bus => _bus;
|
||||
|
||||
public event Action on_tick;
|
||||
|
||||
public MDConsumerHandle md => _model.md;
|
||||
|
||||
@@ -317,7 +317,7 @@
|
||||
<TextBlock.Text>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
|
||||
<Binding Path="change"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</TextBlock.Text>
|
||||
</TextBlock>
|
||||
@@ -325,7 +325,7 @@
|
||||
<TextBlock.Text>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
|
||||
<Binding Path="high"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</TextBlock.Text>
|
||||
</TextBlock>
|
||||
@@ -333,7 +333,7 @@
|
||||
<TextBlock.Text>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
|
||||
<Binding Path="low"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</TextBlock.Text>
|
||||
</TextBlock>
|
||||
@@ -341,7 +341,7 @@
|
||||
<TextBlock.Text>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
|
||||
<Binding Path="open"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</TextBlock.Text>
|
||||
</TextBlock>
|
||||
@@ -349,7 +349,7 @@
|
||||
<TextBlock.Text>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
|
||||
<Binding Path="settlement"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</TextBlock.Text>
|
||||
</TextBlock>
|
||||
@@ -483,6 +483,7 @@
|
||||
Background="{x:Null}" BorderBrush="{x:Null}"
|
||||
PieBackground="Transparent"
|
||||
SliceBackground="#a000"
|
||||
Bus="{Binding bus}"
|
||||
Command="{Binding RecenterCommand, ElementName=_ladder}">
|
||||
<spark:RecenterCountdown.SliceStroke>
|
||||
<Pen Thickness="1" Brush="Black" />
|
||||
|
||||
@@ -57,7 +57,7 @@ namespace mbts.spark {
|
||||
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, true);
|
||||
|
||||
public static double[] gen_prices(double mid, int row_count, ContractSpecificationImmutable spec) {
|
||||
public static double[] gen_prices(double mid, int row_count, SecurityImmutable security) {
|
||||
// require odd number
|
||||
Logger.assert(row_count % 2 == 1);
|
||||
var result = new double[row_count];
|
||||
@@ -67,32 +67,32 @@ namespace mbts.spark {
|
||||
double up = mid, down = mid;
|
||||
// Starting from the middle iterate out to the edges
|
||||
for (int x = 1; x <= range; ++x) {
|
||||
up = TickUtils.tickup(spec, up);
|
||||
down = TickUtils.tickdown(spec, down);
|
||||
up = security.tickup(up);
|
||||
down = security.tickdown(down);
|
||||
result[middle - x] = up;
|
||||
result[middle + x] = down;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static GlyphRun[] format_prices(double[] prices, double row_height, LadderColumnSettings settings, GlyphContext glyph_context, ContractSpecificationImmutable spec) {
|
||||
public static GlyphRun[] format_prices(double[] prices, double row_height, LadderColumnSettings settings, GlyphContext glyph_context, SecurityImmutable security) {
|
||||
var result = new GlyphRun[prices.Length];
|
||||
Parallel.For(0, prices.Length, i =>
|
||||
result[i] = format_text(spec.format(prices[i]), i, row_height, settings, glyph_context));
|
||||
result[i] = format_text(security.format(prices[i]), i, row_height, settings, glyph_context));
|
||||
return result;
|
||||
}
|
||||
|
||||
public static double[] render_prices(DrawingVisual price, GlyphContext glyph_context, double mid, int row_count, double row_height,
|
||||
LadderColumnSettings settings, ContractSpecificationImmutable spec) {
|
||||
var dprices = gen_prices(mid, row_count, spec);
|
||||
render_prices(price, glyph_context, row_count, row_height, dprices, settings, spec);
|
||||
LadderColumnSettings settings, SecurityImmutable security) {
|
||||
var dprices = gen_prices(mid, row_count, security);
|
||||
render_prices(price, glyph_context, row_count, row_height, dprices, settings, security);
|
||||
return dprices;
|
||||
}
|
||||
|
||||
public static void render_prices(DrawingVisual price, GlyphContext glyph_context, int row_count, double row_height, double[] dprices, LadderColumnSettings settings, ContractSpecificationImmutable spec) {
|
||||
public static void render_prices(DrawingVisual price, GlyphContext glyph_context, int row_count, double row_height, double[] dprices, LadderColumnSettings settings, SecurityImmutable security) {
|
||||
var foreground = settings.foreground.rgb_brush();
|
||||
//var background = new SolidColorBrush(settings.background.rgb_color());
|
||||
var fprices = format_prices(dprices, row_height, settings, glyph_context, spec);
|
||||
var fprices = format_prices(dprices, row_height, settings, glyph_context, security);
|
||||
using (var dc = price.RenderOpen())
|
||||
using (_draw_with_clip(dc, settings, row_height, row_count)) {
|
||||
//dc.DrawRectangle(background, null, new Rect(0, 0, settings.width, row_count * row_height));
|
||||
@@ -126,7 +126,7 @@ namespace mbts.spark {
|
||||
double[] prices,
|
||||
NativePriceSize[] rungs,
|
||||
double row_height,
|
||||
ContractSpecificationImmutable spec,
|
||||
SecurityImmutable security,
|
||||
LadderColumnSettings settings
|
||||
) {
|
||||
//var background = new SolidColorBrush(settings.background.rgb_color());
|
||||
@@ -143,7 +143,7 @@ namespace mbts.spark {
|
||||
double price = nps.price;
|
||||
ushort size = nps.size;
|
||||
// prices are in descending order, so get diff from curr_price - price
|
||||
int tick_diff = TickUtils.normalized_tick_diff(spec, curr_price, price);
|
||||
int tick_diff = TickUtils.normalized_tick_diff(security, curr_price, price);
|
||||
curr_index += tick_diff;
|
||||
curr_price = price;
|
||||
if (curr_index >= 0 && curr_index < prices.Length) {
|
||||
|
||||
@@ -1,81 +1,56 @@
|
||||
using bts.api;
|
||||
using bts.api;
|
||||
using mbts.co2;
|
||||
using mbts.ui.controls;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
|
||||
namespace mbts.spark {
|
||||
// Implement the recenter logic in a UI control
|
||||
// Kind of a hack but it makes receiving input from the UI easier
|
||||
public class RecenterCountdown : CountDownTimer {
|
||||
DispatcherTimer _timer = new DispatcherTimer(DispatcherPriority.Background) {
|
||||
Interval = TimeSpan.FromSeconds(1)
|
||||
};
|
||||
SecurityImmutable? _security;
|
||||
MDConsumerHandle _handle;
|
||||
DateTime _last_recenter = DateTime.MaxValue;
|
||||
double _last_mid = 0.0;
|
||||
IDisposable _dispose;
|
||||
readonly TimeSpan _seconds_to_center;
|
||||
IBus _bus;
|
||||
|
||||
public RecenterCountdown() {
|
||||
DataContextChanged += RecenterCountdown_DataContextChanged;
|
||||
Unloaded += (o,e) => on_unload(false);
|
||||
_timer.Tick += _timer_Tick;
|
||||
_timer.Start();
|
||||
_seconds_to_center = TimeSpan.FromSeconds(config.Configuration.get<bts.config.LadderKnobs>().seconds_to_recenter);
|
||||
Unloaded += (o, e) => on_unload(false);
|
||||
}
|
||||
|
||||
static (double,double) tick_range(double price, int tick_count, ContractSpecificationImmutable spec) {
|
||||
return (TickUtils.tickdown(spec, price, tick_count), TickUtils.tickup(spec, price, tick_count));
|
||||
public IBus Bus {
|
||||
get { return (IBus)GetValue(busProperty); }
|
||||
set { SetValue(busProperty, value); }
|
||||
}
|
||||
|
||||
private void _timer_Tick(object sender, EventArgs e) {
|
||||
if (_security != null) {
|
||||
var mid = _handle.mid();
|
||||
if (//mid < low || mid > high ||
|
||||
(_last_recenter + _seconds_to_center < DateTime.UtcNow)) {
|
||||
trigger_recenter(mid);
|
||||
}
|
||||
public static readonly DependencyProperty busProperty =
|
||||
DependencyProperty.Register("Bus", typeof(IBus), typeof(RecenterCountdown), new PropertyMetadata(null, bus_changed));
|
||||
|
||||
static void bus_changed(object sender, DependencyPropertyChangedEventArgs args) {
|
||||
if (sender is RecenterCountdown self) {
|
||||
self.setbus(args.NewValue as IBus);
|
||||
}
|
||||
}
|
||||
|
||||
void setbus(IBus value) {
|
||||
if (value != null) {
|
||||
Disposable.dispose(ref _dispose);
|
||||
_bus = value;
|
||||
_dispose =
|
||||
Disposable.Create(
|
||||
_bus?.subscribe(SparkTags.RecenterLadderBegin).OnDispatcher().Subscribe(begin_recenter),
|
||||
_bus?.subscribe(SparkTags.RecenterLadderNow).OnDispatcher().Subscribe(_ => base.OnClick())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void begin_recenter(DateTime _) => start(null);
|
||||
|
||||
private void on_unload(bool _) {
|
||||
Disposable.dispose(ref _dispose);
|
||||
_timer.Stop();
|
||||
}
|
||||
|
||||
private void RecenterCountdown_DataContextChanged(object sender, System.Windows.DependencyPropertyChangedEventArgs e) {
|
||||
Disposable.dispose(ref _dispose);
|
||||
var vm = e.NewValue as LadderVM;
|
||||
if (vm != null) {
|
||||
_security = vm.security;
|
||||
_handle = vm.md;
|
||||
reset_counters();
|
||||
vm.OnDisposed += on_unload;
|
||||
_dispose =
|
||||
Disposable.Create(
|
||||
Disposable.Create(() => vm.OnDisposed -= on_unload));
|
||||
}
|
||||
}
|
||||
|
||||
void trigger_recenter(double mid) {
|
||||
reset_counters();
|
||||
start(null);
|
||||
}
|
||||
|
||||
protected override void OnClick() {
|
||||
reset_counters();
|
||||
base.OnClick();
|
||||
}
|
||||
|
||||
void reset_counters() {
|
||||
_last_recenter = DateTime.UtcNow;
|
||||
_last_mid = _handle.mid();
|
||||
_bus?.post(SparkTags.RequestRecenterLadder, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@
|
||||
<DataGridTextColumn.Binding>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
|
||||
<Binding Path="start_pnl"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</DataGridTextColumn.Binding>
|
||||
<DataGridTextColumn.ElementStyle>
|
||||
@@ -111,7 +111,7 @@
|
||||
<DataGridTextColumn.Binding>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
|
||||
<Binding Path="day_pnl"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</DataGridTextColumn.Binding>
|
||||
<DataGridTextColumn.ElementStyle>
|
||||
@@ -136,7 +136,7 @@
|
||||
<DataGridTextColumn.Binding>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
|
||||
<Binding Path="total_pnl"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</DataGridTextColumn.Binding>
|
||||
<DataGridTextColumn.ElementStyle>
|
||||
@@ -155,7 +155,7 @@
|
||||
<DataGridTextColumn.Binding>
|
||||
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
|
||||
<Binding Path="pnl_price"/>
|
||||
<Binding Path="security.ContractSpec"/>
|
||||
<Binding Path="security"/>
|
||||
</MultiBinding>
|
||||
</DataGridTextColumn.Binding>
|
||||
</DataGridTextColumn>
|
||||
|
||||
@@ -76,7 +76,7 @@ namespace mbts.spark {
|
||||
_status_store = CellFactory.create(this, _book_vm.columns.status_column, nameof(status), r => _order.status(), r => r._status_store);
|
||||
_last_msg_store = CellFactory.create(this, _book_vm.columns.last_message_column, nameof(last_msg), r => _order.last_msg(), r => r._last_msg_store);
|
||||
//
|
||||
string format_price(double v) => _security.HasValue ? _security.Value.ContractSpec.format(v) :
|
||||
string format_price(double v) => _security.HasValue ? _security.Value.format(v) :
|
||||
Math.Round(v, _unknown_security_price_num_fractional_digits, MidpointRounding.AwayFromZero).ToString(_unknown_security_price_format_string);
|
||||
string format_date(DateTime v) => $"{v:M/d} {v:h:mm:ss.fff tt}";
|
||||
string format_sub_type(OrderSubType v) {
|
||||
|
||||
@@ -41,7 +41,7 @@ namespace mbts.spark {
|
||||
public static GlyphContext get_glyph_context(OrderBookRowVM r) => r.is_child ? _child_glyph_context : TextUtils.StandardGlyphContext;
|
||||
public static Brush get_side_brush(OrderBookRowVM r) => r.side == Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask;
|
||||
public static BindingBase get_font_weight_binding() => new Binding(nameof(OrderBookRowVM.is_child)) { Converter = _font_weight_converter };
|
||||
public static string format_price(OrderBookRowVM row, double price) => row.security.HasValue ? row.security.Value.ContractSpec.format(price) : row.price.ToString();
|
||||
public static string format_price(OrderBookRowVM row, double price) => row.security.HasValue ? row.security.Value.format(price) : row.price.ToString();
|
||||
}
|
||||
|
||||
abstract class OrderbookColumnBase : ColumnBase<Columns>, IKeyedColumn<Columns>, IFilterableColumn {
|
||||
|
||||
@@ -61,7 +61,27 @@ namespace mbts.spark.utilities {
|
||||
if (value > max) return max;
|
||||
return value;
|
||||
}
|
||||
public static bool is_within_range(double min, double max, double value) =>
|
||||
value >= min && value <= max;
|
||||
|
||||
public static int RoundFractionalUnits(double value, double fractional_unit) =>
|
||||
(int)Math.Round(value / fractional_unit);
|
||||
|
||||
public static bool is_int(double d) =>
|
||||
epsilon_equals(d, (int)d);
|
||||
|
||||
public static double factor_out(double value, double factor) =>
|
||||
factor_out(value, factor, out int _);
|
||||
|
||||
public static double factor_out(double value, double factor, out int n_factors_removed) {
|
||||
n_factors_removed = 0;
|
||||
double quotient = value / factor;
|
||||
while (is_int(quotient)) {
|
||||
value = quotient;
|
||||
++n_factors_removed;
|
||||
quotient /= factor;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,11 +15,13 @@ namespace mbts.spark
|
||||
|
||||
public static class Defaults {
|
||||
public static ContractSpecification ContractSpecification => new ContractSpecification { CashPerPoint = 1.0, LowTick = 0.01, HighTick = 0.01, PriceBreak = double.MaxValue, PriceMultiplier = 1.0 };
|
||||
public static GLBXExchangeData GlbxExchangeData => new GLBXExchangeData { MainFraction = 1000, PriceDisplayFormat = 3 };
|
||||
public static readonly ContractSpecificationImmutable ContractSpecificationImmutable = new ContractSpecificationImmutable(ContractSpecification);
|
||||
public static Security Security => new Security {
|
||||
Symbol = string.Empty,
|
||||
Exchange = Venue.Bts,
|
||||
ContractSpec = ContractSpecification,
|
||||
Glbx = GlbxExchangeData
|
||||
};
|
||||
public static readonly SecurityImmutable SecurityImmutable = new SecurityImmutable(Security);
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/services/AdminService.proto;api/services/ApiUnitTestService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/services/UserService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/Executor.conf;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/edge.conf;config/defaults/expiration_display_offset.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/testkeys.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/environment.proto;config/protos/expiration_display_offset.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/quickbus_cfg.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPriceLantencyTester.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/Dispatcher.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp)
|
||||
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/services/AdminService.proto;api/services/ApiUnitTestService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/services/UserService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/Executor.conf;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cpp_config.conf;config/defaults/edge.conf;config/defaults/expiration_display_offset.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/testkeys.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cpp_config.proto;config/protos/environment.proto;config/protos/expiration_display_offset.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/quickbus_cfg.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPriceLantencyTester.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/Dispatcher.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp)
|
||||
@@ -197,5 +197,30 @@ TEST_CASE("Synthetic3Legs", "[md][synthetic]") {
|
||||
|
||||
}
|
||||
|
||||
TEST_CASE("SPARK-955", "[md][synthetic]") {
|
||||
shared_ptr<SyntheticStrategy> synthetic;
|
||||
vector<Co2TestInstrument> test_instr;
|
||||
tie(synthetic, test_instr) = make_securities({ {1.0, 0.25, api::SIDE_BUY}, {2.0, 0.25, api::SIDE_SELL }, { 1.0, 0.25, api::SIDE_BUY}});
|
||||
auto esm8 = test_instr[0];
|
||||
auto esu8 = test_instr[1];
|
||||
auto esz8 = test_instr[2];
|
||||
MDConsumerHandle synthetic_handle(synthetic);
|
||||
|
||||
setup_market(esm8.producer(),
|
||||
{{2594.50, 47}, {2594.25,63}, {2594.00,117}, {2593.75,137}},
|
||||
{{2594.75, 52}, {2595.00,138}, {2594.25,119}, {2595.50,128}});
|
||||
setup_market(esu8.producer(),
|
||||
{{2598.50, 14}, {2598.25, 15}, {2598.00,16}, {2597.75, 15}},
|
||||
{{2599.75, 1}, {2600.00, 16}, {2600.25,15}, {2600.50, 75}});
|
||||
setup_market(esz8.producer(),
|
||||
{{2601.25, 2}, {2600.50, 3}, {2600.25, 10}},
|
||||
{{2607.25, 3}, {2607.50, 1}, {2608.25, 9}});
|
||||
expect_market(synthetic_handle,
|
||||
// If we do strict price this is right. If we're pessimistic we get {-4.25,2}
|
||||
{ {-4.00, 1}, {-4.25, 1}, { -5.00, 3}, {-5.25, 3}, {-5.50,1}, {-5.75, 6} },
|
||||
{ {5.00, 3}, {5.25, 1}, {6.00,3}, {6.50,6} });
|
||||
}
|
||||
|
||||
|
||||
|
||||
}}}//namespace
|
||||
+120
-16
@@ -15,14 +15,94 @@ body {
|
||||
height:100%;
|
||||
}
|
||||
|
||||
.nbsp {
|
||||
margin-left:1em;
|
||||
}
|
||||
|
||||
.is-sidebar-menu {
|
||||
padding: 2.5rem;
|
||||
padding: 1.5rem;
|
||||
background: $grey-lighter;
|
||||
border-right: 0.6px solid $border;
|
||||
min-width: 12rem;
|
||||
min-width: 14rem;
|
||||
li {
|
||||
a {
|
||||
color: $grey-dark
|
||||
color: $grey-dark;
|
||||
&:hover {
|
||||
.menu-icon {
|
||||
display: inline;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.menu-label {
|
||||
color: $text;
|
||||
text-transform: none;
|
||||
}
|
||||
.circle-icon {
|
||||
margin: 0 0em 0 3.5em;
|
||||
.button {
|
||||
&:active {
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
.fabutton {
|
||||
background-color: transparent;
|
||||
border-width: 0;
|
||||
.icon {
|
||||
i {
|
||||
color: $menu-label-color;
|
||||
font-size: 1.75em;
|
||||
margin-top:-0.2em;
|
||||
&:hover {
|
||||
color:$text;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.is-active {
|
||||
.menu-icon {
|
||||
display:inline;
|
||||
.button {
|
||||
color: $white;
|
||||
}
|
||||
}
|
||||
}
|
||||
.menu-icon {
|
||||
display:none;
|
||||
margin: 0 -0.5em 0 0;
|
||||
.dropdown {
|
||||
.dropdown-trigger {
|
||||
.button {
|
||||
padding: 0 1ex;
|
||||
margin: -0.1em 0 0 0;
|
||||
height:auto;
|
||||
border:0;
|
||||
background-color:transparent;
|
||||
&:active {
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
.fabutton {
|
||||
max-height: 1em;
|
||||
background-color: transparent;
|
||||
border-width: 0;
|
||||
//padding:0 0.25em;
|
||||
.icon {
|
||||
i {
|
||||
font-size: 1em;
|
||||
&:hover {
|
||||
color:$menu-label-color;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.dropdown-menu {
|
||||
left: unset;
|
||||
right:0;//-1.25em;
|
||||
width:10rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,34 +167,51 @@ body {
|
||||
-moz-appearance: none;
|
||||
-webkit-appearance: none;
|
||||
background-color: transparent;
|
||||
//color: $white;
|
||||
border: none;
|
||||
color: $menu-label-color;
|
||||
border: 2px solid $menu-label-color;
|
||||
border-radius: 50%;
|
||||
cursor: pointer;
|
||||
display: inline-block;
|
||||
flex-grow: 0;
|
||||
flex-shrink: 0;
|
||||
font-size: 14px;
|
||||
height: 21px;
|
||||
max-height: 21px;
|
||||
max-width: 21px;
|
||||
min-height: 21px;
|
||||
min-width: 21px;
|
||||
width: 21px;
|
||||
line-height:14px;
|
||||
height: 20px;
|
||||
max-height: 20px;
|
||||
min-height: 20px;
|
||||
width: 20px;
|
||||
max-width: 20px;
|
||||
min-width: 20px;
|
||||
outline: none;
|
||||
position: relative;
|
||||
vertical-align: middle;
|
||||
text-align: center;
|
||||
padding: 0.275em 0 0 0.07em;
|
||||
padding: 0px;
|
||||
margin: 0ex 0 0 1.5em;
|
||||
padding: auto;
|
||||
&:hover {
|
||||
background-color: $shell_gray;
|
||||
color: $text;
|
||||
border-color: $text;
|
||||
}
|
||||
.icon {
|
||||
&.is-small{
|
||||
height:14px;
|
||||
width:14px;
|
||||
min-width:14px;
|
||||
line-height: 14px;
|
||||
font-size: 14px;
|
||||
margin:2px 3.3px;
|
||||
vertical-align: middle;
|
||||
text-align: center;
|
||||
i {
|
||||
height:14px;
|
||||
width:14px;
|
||||
min-width:14px;
|
||||
line-height: 14px;
|
||||
font-size: 14px;
|
||||
vertical-align: middle;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
i {
|
||||
@@ -221,9 +318,10 @@ body {
|
||||
&:focus {
|
||||
background-color: $white;
|
||||
}
|
||||
}
|
||||
.is-checkbox-cell {
|
||||
width: 3rem;
|
||||
&[type="checkbox"] {
|
||||
height:1em;
|
||||
margin-top: 0.75em;
|
||||
}
|
||||
}
|
||||
.delete {
|
||||
margin:.6rem .4rem;
|
||||
@@ -231,5 +329,11 @@ body {
|
||||
.table-buttons {
|
||||
width:auto;
|
||||
}
|
||||
tr.is-selected {
|
||||
background: $grey_lighter;
|
||||
}
|
||||
tr.is-warning {
|
||||
background: $yellow;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ open Elmish
|
||||
open Fable.PowerPack.PromiseImpl
|
||||
open Fable.Import
|
||||
open bts.co2
|
||||
open Fable
|
||||
|
||||
let isNewAccount (account:BTSAccount) =
|
||||
account.id = 0u && account.isPresent
|
||||
@@ -23,8 +24,12 @@ let init (context:ServiceContext.ServiceContext) =
|
||||
mdRelayExpNameData = Array.empty<ExpirationNameList>
|
||||
scratch = emptyAccount
|
||||
previousScratch = emptyAccount
|
||||
AllValue = "*"
|
||||
AllValueDisplay = "All"
|
||||
AllValue = ""
|
||||
AllValueDisplay = "Select"
|
||||
OptionsMenuOpen = ""
|
||||
ConfirmModal = "", (Msg.SelectTab General)
|
||||
SelectedClipLimits = []
|
||||
SelectedPositionLimits = []
|
||||
}, Access.getAdminData admin UpdateAdminData NoAdminData
|
||||
|
||||
let existingSelection (scratch:BTSAccount) (previousScratch:BTSAccount) (data:AdminData) =
|
||||
@@ -99,6 +104,38 @@ let erase (arr:'a[]) i =
|
||||
let right = arr.[1+i..]
|
||||
Array.concat [left;right]
|
||||
|
||||
let clearSelection model =
|
||||
{ model with
|
||||
SelectedClipLimits = []
|
||||
SelectedPositionLimits = []
|
||||
}
|
||||
|
||||
let ClipLimitIsEqual (limit1:AccountSecurityClipLimitUnit) (limit2:AccountSecurityClipLimitUnit) =
|
||||
(limit1.security.exchange = limit2.security.exchange)
|
||||
&& (limit1.security.securityType = limit2.security.securityType)
|
||||
&& (limit1.security.securitySymbol = limit2.security.securitySymbol)
|
||||
|
||||
let PositionLimitIsEqual (limit1:AccountProductPositionLimitUnit) (limit2:AccountProductPositionLimitUnit) =
|
||||
(limit1.product.exchange = limit2.product.exchange)
|
||||
&& (limit1.product.securityType = limit2.product.securityType)
|
||||
&& (limit1.product.securitySymbol = limit2.product.securitySymbol)
|
||||
|
||||
let modifyClipLimitRow limits (oldRow:AccountSecurityClipLimitUnit) (newRow:AccountSecurityClipLimitUnit) =
|
||||
match (Array.tryFindIndex (fun l -> oldRow = l) limits) with
|
||||
| None -> limits
|
||||
| Some ind ->
|
||||
let left = Array.append (limits.[..ind-1]) [| newRow |]
|
||||
let right = limits.[1+ind..]
|
||||
Array.concat [left; right]
|
||||
|
||||
let modifyProductPositionRow limits (oldRow:AccountProductPositionLimitUnit) (newRow:AccountProductPositionLimitUnit) =
|
||||
match (Array.tryFindIndex (fun l -> oldRow = l) limits) with
|
||||
| None -> limits
|
||||
| Some ind ->
|
||||
let left = Array.append (limits.[..ind-1]) [| newRow |]
|
||||
let right = limits.[1+ind..]
|
||||
Array.concat [left; right]
|
||||
|
||||
let update msg (model:Model) : Model * Cmd<Msg> =
|
||||
match msg with
|
||||
| UpdateAdminData data ->
|
||||
@@ -110,11 +147,12 @@ let update msg (model:Model) : Model * Cmd<Msg> =
|
||||
Global.alert Global.Info msg
|
||||
model, Cmd.Empty
|
||||
| SelectAccount account ->
|
||||
{ model with previousScratch = model.scratch; scratch = account }, Cmd.Empty
|
||||
{ (clearSelection model) with previousScratch = model.scratch; scratch = account }, Cmd.Empty
|
||||
| DeleteAccount account ->
|
||||
let mdl = { model with OptionsMenuOpen = ""}
|
||||
match Fable.Import.Browser.window.confirm (sprintf "Are you sure you want to delete '%s'" account.name) with
|
||||
| true -> model, Cmd.ofExistingPromise (deleteAccount model.admin account) id (box>>ErrorOccured)
|
||||
| false -> model, Cmd.Empty
|
||||
| true -> mdl, Cmd.ofExistingPromise (deleteAccount model.admin account) id (box>>ErrorOccured)
|
||||
| false -> mdl, Cmd.Empty
|
||||
| AddAccount ->
|
||||
// Create a new scratch account. Send to server after user has filled in details
|
||||
{ model with previousScratch = model.scratch; scratch = { emptyAccount with name = "New Account" } }, Cmd.ofMsg <| SelectTab General
|
||||
@@ -127,16 +165,77 @@ let update msg (model:Model) : Model * Cmd<Msg> =
|
||||
Browser.console.log msg
|
||||
model,Cmd.Empty
|
||||
| SelectTab tab ->
|
||||
{ model with tab = tab }, Cmd.Empty
|
||||
{ (clearSelection model) with tab = tab }, Cmd.Empty
|
||||
| Update field ->
|
||||
{ model with scratch = applyUpdate model.scratch field }, Cmd.Empty
|
||||
| ClipLimits limits ->
|
||||
{ model with scratch = { model.scratch with securityClipLimits = { limit = limits } } }, Cmd.Empty
|
||||
| ClipLimits (oldLimit, newLimit) ->
|
||||
//if the new limit matches the empty limit then add it to the list, otherwise update the existing row
|
||||
match (ClipLimitIsEqual newLimit { security = { SecurityScope.empty with securitySymbol = model.AllValue }; clipSize = 0u }), (Array.tryFindIndex (fun l -> ClipLimitIsEqual newLimit l) model.scratch.securityClipLimits.limit) with
|
||||
| true, None ->
|
||||
let limits = Array.concat [ model.scratch.securityClipLimits.limit; [| newLimit |]]
|
||||
{ model with scratch = { model.scratch with securityClipLimits = { limit = limits } } }, Cmd.Empty
|
||||
| true, Some i -> model, Cmd.Empty
|
||||
| false, _ ->
|
||||
let limits = modifyClipLimitRow model.scratch.securityClipLimits.limit oldLimit newLimit
|
||||
let selectedlimits = List.ofArray (modifyClipLimitRow (Array.ofList model.SelectedClipLimits) oldLimit newLimit)
|
||||
{ model with scratch = { model.scratch with securityClipLimits = { limit = limits } }; SelectedClipLimits = selectedlimits }, Cmd.Empty
|
||||
| ChangeMultipleClipLimits (value, selectedLimits) ->
|
||||
let newLimits = Array.ofList [for row in (List.ofArray model.scratch.securityClipLimits.limit) do yield (
|
||||
match (Array.tryFindIndex (fun elm -> ClipLimitIsEqual elm row) selectedLimits) with
|
||||
| None -> row
|
||||
| Some _ -> {row with clipSize = value}
|
||||
)]
|
||||
let newSelected = [for row in (List.ofArray selectedLimits) do yield ( {row with clipSize = value})]
|
||||
{ model with scratch = { model.scratch with securityClipLimits = { limit = newLimits } }; SelectedClipLimits = newSelected }, Cmd.Empty
|
||||
| SelectClipLimit (chckd, limit) ->
|
||||
let scl = match chckd with
|
||||
| true -> (limit::model.SelectedClipLimits)
|
||||
| false -> List.filter (fun elm -> (ClipLimitIsEqual elm limit) |> not) model.SelectedClipLimits
|
||||
{model with SelectedClipLimits = scl}, Cmd.Empty
|
||||
| DeleteClipLimit i ->
|
||||
let limits = erase model.scratch.securityClipLimits.limit i
|
||||
{ model with scratch = { model.scratch with securityClipLimits = { limit = limits } } }, Cmd.Empty
|
||||
| ProductLimits limits ->
|
||||
{ model with scratch = { model.scratch with productPositionLimits = limits } }, Cmd.Empty
|
||||
| ProductLimits (oldLimit, newLimit) ->
|
||||
let emptyLimit = {
|
||||
product = {
|
||||
exchange = bts.api.Venue.GLBX
|
||||
securityType = bts.api.SecurityType.FUTURE
|
||||
securitySymbol = model.AllValue
|
||||
}
|
||||
longPositionLimit = 0u
|
||||
shortPositionLimit = 0u
|
||||
netPositionLimit = 0u
|
||||
}
|
||||
//if the new limit matches the empty limit then add it to the list, otherwise update the existing row
|
||||
match (PositionLimitIsEqual newLimit emptyLimit), (Array.tryFindIndex (fun l -> PositionLimitIsEqual newLimit l) model.scratch.productPositionLimits) with
|
||||
| true, None ->
|
||||
let limits = Array.concat [ model.scratch.productPositionLimits; [| newLimit |]]
|
||||
{ model with scratch = { model.scratch with productPositionLimits = limits } }, Cmd.Empty
|
||||
| true, Some i -> model, Cmd.Empty
|
||||
| false, _ ->
|
||||
let limits = modifyProductPositionRow model.scratch.productPositionLimits oldLimit newLimit
|
||||
let selectedlimits = List.ofArray (modifyProductPositionRow (Array.ofList model.SelectedPositionLimits) oldLimit newLimit)
|
||||
{ model with scratch = { model.scratch with productPositionLimits = limits }; SelectedPositionLimits = selectedlimits }, Cmd.Empty
|
||||
| ChangeMultipleProductLimits (valueName, value, selectedLimits) ->
|
||||
let newLimits = Array.ofList [for row in (List.ofArray model.scratch.productPositionLimits) do yield (
|
||||
match (Array.tryFindIndex (fun elm -> PositionLimitIsEqual elm row) selectedLimits), valueName with
|
||||
| Some _, "long" -> {row with longPositionLimit = value}
|
||||
| Some _, "short" -> {row with shortPositionLimit = value}
|
||||
| Some _, _ -> row
|
||||
| None, _ -> row
|
||||
)]
|
||||
let newSelected = [for row in (List.ofArray selectedLimits) do yield (
|
||||
match valueName with
|
||||
| "long" -> { row with longPositionLimit = value}
|
||||
| "short" -> { row with shortPositionLimit = value}
|
||||
| _ -> row
|
||||
)]
|
||||
{ model with scratch = { model.scratch with productPositionLimits = newLimits }; SelectedPositionLimits = newSelected }, Cmd.Empty
|
||||
| SelectProductLimit (chckd, limit) ->
|
||||
let scl = match chckd with
|
||||
| true -> (limit::model.SelectedPositionLimits)
|
||||
| false -> List.filter (fun elm -> (PositionLimitIsEqual elm limit) |> not) model.SelectedPositionLimits
|
||||
{model with SelectedPositionLimits = scl}, Cmd.Empty
|
||||
| DeleteProductLimit i ->
|
||||
let limits = erase model.scratch.productPositionLimits i
|
||||
{ model with scratch = { model.scratch with productPositionLimits = limits } }, Cmd.Empty
|
||||
@@ -156,7 +255,7 @@ let update msg (model:Model) : Model * Cmd<Msg> =
|
||||
{ model with scratch = { model.scratch with connections = { model.scratch.connections with exchangeConnectionNames = newCons }}}, Cmd.Empty
|
||||
| RemoveConnection conName ->
|
||||
let newCons = erase model.scratch.connections.exchangeConnectionNames (Array.findIndex (fun a -> a = conName) model.scratch.connections.exchangeConnectionNames)
|
||||
{ model with scratch = { model.scratch with connections = { model.scratch.connections with exchangeConnectionNames = newCons }}}, Cmd.Empty
|
||||
{ model with scratch = { model.scratch with connections = { model.scratch.connections with exchangeConnectionNames = newCons }}; ConfirmModal = ("", Msg.SelectTab model.tab)}, Cmd.Empty
|
||||
//
|
||||
// Exchange data
|
||||
| UpdateCME field ->
|
||||
@@ -171,3 +270,7 @@ let update msg (model:Model) : Model * Cmd<Msg> =
|
||||
model, Cmd.ofExistingPromise (requestExpNames model.mdRelay) id (box>>ErrorOccured)
|
||||
| UpdateExpirationNames (data:ExpirationNameList[]) ->
|
||||
{ model with mdRelayExpNameData = data }, Cmd.Empty
|
||||
| OpenOptionsMenu acc ->
|
||||
{model with OptionsMenuOpen = acc}, Cmd.Empty
|
||||
| OpenConfirmModal (title, okMessage) ->
|
||||
{model with ConfirmModal = title, okMessage}, Cmd.Empty
|
||||
@@ -8,7 +8,6 @@ open bts.co2
|
||||
|
||||
type Tab =
|
||||
| General
|
||||
//| ClipLimitsTab
|
||||
| LimitsTab
|
||||
| CreditLimitsTab
|
||||
| ExchangeSettingsTab
|
||||
@@ -19,19 +18,6 @@ let securityTypes = SecurityType.values |> Array.skip 1
|
||||
|
||||
let emptyAccount = Access.Accounts.empty
|
||||
|
||||
type Model = {
|
||||
tab : Tab
|
||||
admin : IAdminService
|
||||
adminData : AdminData option
|
||||
mdRelay : IMarketDataRelay
|
||||
mdRelayProductData: Product[]
|
||||
mdRelayExpNameData: ExpirationNameList[]
|
||||
scratch : BTSAccount
|
||||
previousScratch : BTSAccount
|
||||
AllValue: string
|
||||
AllValueDisplay: string
|
||||
}
|
||||
|
||||
type AccountField =
|
||||
| AccountName of string
|
||||
| Description of string
|
||||
@@ -61,10 +47,17 @@ type Msg =
|
||||
| SelectTab of Tab
|
||||
// General
|
||||
| Update of AccountField
|
||||
| ClipLimits of AccountSecurityClipLimitUnit[]
|
||||
// Clip Limits
|
||||
| ClipLimits of AccountSecurityClipLimitUnit * AccountSecurityClipLimitUnit
|
||||
| ChangeMultipleClipLimits of uint32 * AccountSecurityClipLimitUnit[]
|
||||
| SelectClipLimit of bool * AccountSecurityClipLimitUnit
|
||||
| DeleteClipLimit of int
|
||||
| ProductLimits of AccountProductPositionLimitUnit[]
|
||||
//Product (position) Limits
|
||||
| ChangeMultipleProductLimits of string * uint32 * AccountProductPositionLimitUnit []
|
||||
| SelectProductLimit of bool * AccountProductPositionLimitUnit
|
||||
| ProductLimits of AccountProductPositionLimitUnit * AccountProductPositionLimitUnit
|
||||
| DeleteProductLimit of int
|
||||
|
||||
| SecurityLimits of AccountSecurityPositionLimitUnit[]
|
||||
| DeleteSecurityLimit of int
|
||||
// ExchangeData
|
||||
@@ -75,4 +68,23 @@ type Msg =
|
||||
| UpdateExpirationNames of ExpirationNameList[]
|
||||
| AddConnection of string
|
||||
| RemoveConnection of string
|
||||
| OpenOptionsMenu of string
|
||||
| OpenConfirmModal of string * Msg
|
||||
|
||||
|
||||
type Model = {
|
||||
tab : Tab
|
||||
admin : IAdminService
|
||||
adminData : AdminData option
|
||||
mdRelay : IMarketDataRelay
|
||||
mdRelayProductData: Product[]
|
||||
mdRelayExpNameData: ExpirationNameList[]
|
||||
scratch : BTSAccount
|
||||
previousScratch : BTSAccount
|
||||
AllValue: string
|
||||
AllValueDisplay: string
|
||||
SelectedClipLimits: AccountSecurityClipLimitUnit list
|
||||
SelectedPositionLimits: AccountProductPositionLimitUnit list
|
||||
OptionsMenuOpen:string
|
||||
ConfirmModal: string * Msg
|
||||
}
|
||||
+283
-170
@@ -4,7 +4,6 @@ open Accounts.Types
|
||||
open Accounts.State
|
||||
open Fable.Helpers.React
|
||||
open Fable.Helpers.React.Props
|
||||
open Button
|
||||
open bts.api.admin
|
||||
open bts.api.orderman
|
||||
open EnumUtils
|
||||
@@ -30,41 +29,15 @@ let saveButton model dispatch =
|
||||
let isNew = isNewAccount model.scratch
|
||||
let buttonText = if isNew then "Create" else "Save"
|
||||
let dirty = isDirty model || isNew
|
||||
let enabled = if dirty then Enabled else Disabled
|
||||
let enabled = if dirty then Button.Enabled else Button.Disabled
|
||||
let flavor = if dirty then "is-success" else "is-light"
|
||||
Button.button buttonText flavor "" enabled (fun _ -> dispatch SaveScratch)
|
||||
(*
|
||||
let mappedDataGridWithAddDelete<'a,'r> title (descriptor:MappedDataGridDescriptor<'a,'r>) props (rows:'a[]) erase (dispatch:'a[]->unit) =
|
||||
let addRow _ = Array.append rows [| descriptor.emptyRow |] |> dispatch
|
||||
// Why can't `erase` have the same signature as dispatch?
|
||||
// Because the react Column is the one invoking erase and it doesn't really understand equality
|
||||
// so when rows is updated this column probably *won't be* so it **cannot** close over rows
|
||||
// If it closes over rows the grid will reset to the first visible state (when the tab was made visible)
|
||||
let deleteColumn = ReactGrid.buttonColumn erase "" "times" (box rows)
|
||||
let descriptor' = { descriptor with columns = Array.append [| deleteColumn |] descriptor.columns }
|
||||
div [] [
|
||||
h5 [ClassName "title is-5"] [ str title ]
|
||||
mappedDataGrid descriptor' props rows dispatch
|
||||
div [ClassName "level"] [
|
||||
div [ClassName "level-left"] []
|
||||
div [ClassName "level-right"] [
|
||||
div [ClassName "level-item"] [
|
||||
Button.addButton Button.Enabled addRow
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
*)
|
||||
//
|
||||
// General
|
||||
//
|
||||
let generalView model dispatch =
|
||||
let account = model.scratch
|
||||
|
||||
let remButton =
|
||||
match selectedAccount model with
|
||||
| None -> Button.button "Remove Account" "is-danger-hover" "times" Disabled ignore
|
||||
| Some acc -> Button.button "Remove Account" "is-danger-hover" "times" Enabled (fun _ -> dispatch <| DeleteAccount acc)
|
||||
|
||||
let revertFun =
|
||||
match model.adminData with
|
||||
@@ -76,7 +49,7 @@ let generalView model dispatch =
|
||||
(div [] [
|
||||
Fields.text "Name" account.name [] (AccountName >> Update >> dispatch)
|
||||
Fields.text "Description" account.description [] (Description >> Update >> dispatch)
|
||||
Fields.checkbox "Active" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
|
||||
Fields.checkbox "Can Trade Into Account" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
|
||||
])
|
||||
(fun _ -> dispatch SaveScratch)
|
||||
revertFun
|
||||
@@ -86,37 +59,38 @@ let generalView model dispatch =
|
||||
br []
|
||||
Fields.text "Name" account.name [] (AccountName >> Update >> dispatch)
|
||||
Fields.text "Description" account.description [] (Description >> Update >> dispatch)
|
||||
Fields.checkbox "Active" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
|
||||
remButton
|
||||
Fields.checkbox "Can Trade Into Account" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
|
||||
(if State.isNewAccount account then modal else span[][])
|
||||
]
|
||||
|
||||
let clipLimitsView model dispatch =
|
||||
let headerRow:TableControl.row =
|
||||
{
|
||||
cells =
|
||||
[
|
||||
TableControl.Cell (str "")
|
||||
TableControl.Cell (str "Exchange")
|
||||
TableControl.Cell (str "Security Type")
|
||||
TableControl.Cell (str "Symbol")
|
||||
TableControl.Cell (str "Security")
|
||||
TableControl.Cell (str "Clip Size")
|
||||
]
|
||||
className = ""
|
||||
header = None
|
||||
}
|
||||
let GetSymbolArray (model:Model) =
|
||||
[|
|
||||
[| model.AllValueDisplay |];
|
||||
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|
||||
|]
|
||||
|> Array.concat
|
||||
|> Array.distinct
|
||||
|
||||
let symbolArray = [|
|
||||
[| model.AllValueDisplay |];
|
||||
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|
||||
|]
|
||||
|> Array.concat
|
||||
|> Array.distinct
|
||||
let limitFilter (positionLimit:AccountSecurityPositionLimitUnit option) (clipLimit:AccountSecurityClipLimitUnit option) allValueDisplay (array:'a []) =
|
||||
match positionLimit, clipLimit with
|
||||
| Some limit, None ->
|
||||
Array.filter (fun (x:bts.co2.ExpirationNameList) -> (
|
||||
((x.product.exchange = limit.security.exchange) || (x.product.exchange = bts.api.Venue.UNSET))
|
||||
&& ((x.product.``type`` = limit.security.securityType) || (x.product.``type`` = bts.api.SecurityType.UNSET))
|
||||
&& ((x.product.symbol = limit.security.securitySymbol) || (x.product.symbol = allValueDisplay))
|
||||
))
|
||||
array
|
||||
| None, Some limit ->
|
||||
Array.filter (fun (x:bts.co2.ExpirationNameList) -> (
|
||||
((x.product.exchange = limit.security.exchange) || (x.product.exchange = bts.api.Venue.UNSET))
|
||||
&& ((x.product.``type`` = limit.security.securityType) || (x.product.``type`` = bts.api.SecurityType.UNSET))
|
||||
&& ((x.product.symbol = limit.security.securitySymbol) || (x.product.symbol = allValueDisplay))
|
||||
))
|
||||
array
|
||||
| _ , _ -> array
|
||||
|
||||
let getSecurityMap (limit:AccountSecurityClipLimitUnit) =
|
||||
let allOption = {
|
||||
product = {
|
||||
let getSecurityMap (model:Model) (positionLimit:AccountSecurityPositionLimitUnit option) (clipLimit:AccountSecurityClipLimitUnit option) =
|
||||
let allOption = { product = {
|
||||
exchange = bts.api.Venue.UNSET
|
||||
``type`` = bts.api.SecurityType.UNSET
|
||||
symbol = model.AllValueDisplay
|
||||
@@ -125,92 +99,148 @@ let clipLimitsView model dispatch =
|
||||
}:ExpirationNameList
|
||||
|
||||
Array.concat [ [| allOption |]; model.mdRelayExpNameData]
|
||||
|> Array.filter (fun (x:bts.co2.ExpirationNameList) -> (
|
||||
((x.product.exchange = limit.security.exchange) || (x.product.exchange = bts.api.Venue.UNSET))
|
||||
&& ((x.product.``type`` = limit.security.securityType) || (x.product.``type`` = bts.api.SecurityType.UNSET))
|
||||
&& ((x.product.symbol = limit.security.securitySymbol) || (x.product.symbol = model.AllValueDisplay))
|
||||
)
|
||||
)
|
||||
|> (limitFilter positionLimit clipLimit model.AllValueDisplay)
|
||||
|> Seq.map (fun x -> x.names ) |> JSMap.concat
|
||||
|
||||
let modifyRow (oldRow:AccountSecurityClipLimitUnit) (newRow:AccountSecurityClipLimitUnit) =
|
||||
let i = Array.findIndex (fun l -> oldRow = l) model.scratch.securityClipLimits.limit
|
||||
let left = Array.append (model.scratch.securityClipLimits.limit.[..i-1]) [| newRow |]
|
||||
let right = model.scratch.securityClipLimits.limit.[1+i..]
|
||||
Array.concat [left; right]
|
||||
|
||||
let changeVenue (oldRow:AccountSecurityClipLimitUnit) (value:string) =
|
||||
|
||||
let clipLimitsView model dispatch =
|
||||
let symbols = GetSymbolArray model
|
||||
let headerRow:TableControl.row =
|
||||
{
|
||||
cells =
|
||||
[
|
||||
TableControl.Cell (str "")
|
||||
TableControl.Cell (str "")
|
||||
TableControl.Cell (str "Exchange")
|
||||
TableControl.Cell (str "Security Type")
|
||||
TableControl.Cell (str "Symbol")
|
||||
//TableControl.Cell (str "Security")
|
||||
TableControl.Cell (str "Clip Size")
|
||||
]
|
||||
className = ""
|
||||
header = None
|
||||
}
|
||||
let footerRow:TableControl.row =
|
||||
{
|
||||
cells =
|
||||
[
|
||||
{ content = span [Class "nbsp"] [str "Apply to Selected Rows:"]
|
||||
className = "has-text-right"
|
||||
isHeader = false
|
||||
colSpan = 5
|
||||
}
|
||||
TableControl.Cell (Fields.text
|
||||
""
|
||||
(sprintf "%i" (match (List.tryHead model.SelectedClipLimits) with
|
||||
| Some r -> r.clipSize
|
||||
| None -> 0u
|
||||
))
|
||||
[ ]
|
||||
((fun value -> (value, (Array.ofList model.SelectedClipLimits))) >> ChangeMultipleClipLimits >> dispatch)
|
||||
)
|
||||
]
|
||||
className = match (model.SelectedClipLimits.Length > 0) with
|
||||
| true -> ""
|
||||
| false -> "is-hidden-touch is-hidden-desktop"
|
||||
header = None
|
||||
}
|
||||
|
||||
let changeVenue (oldRow:AccountSecurityClipLimitUnit) (value:string) =
|
||||
let venueValue = EnumUtils.fromHuman<bts.api.Venue> venues value
|
||||
let newRow = { oldRow with security = { oldRow.security with exchange = venueValue } }
|
||||
modifyRow oldRow newRow
|
||||
{ oldRow with security = { oldRow.security with exchange = venueValue } }
|
||||
|
||||
let changeType (oldRow:AccountSecurityClipLimitUnit) (value:string) =
|
||||
let typeValue = EnumUtils.fromHuman<bts.api.SecurityType> securityTypes value
|
||||
let newRow = { oldRow with security = { oldRow.security with securityType = typeValue } }
|
||||
modifyRow oldRow newRow
|
||||
{ oldRow with security = { oldRow.security with securityType = typeValue } }
|
||||
|
||||
let changeSymbol (oldRow:AccountSecurityClipLimitUnit) (value:string) =
|
||||
let v = match (value = model.AllValueDisplay) with
|
||||
| false -> value
|
||||
| true -> model.AllValue
|
||||
modifyRow oldRow { oldRow with security = { oldRow.security with securitySymbol = v } }
|
||||
{ oldRow with security = { oldRow.security with securitySymbol = v } }
|
||||
|
||||
let changeSecurityId (oldRow:AccountSecurityClipLimitUnit) (value:string) =
|
||||
modifyRow oldRow { oldRow with security = { oldRow.security with securityId = (uint32 value) } }
|
||||
let changeSecurityId (oldRow:AccountSecurityClipLimitUnit) (value:string) =
|
||||
{ oldRow with security = { oldRow.security with securityId = (uint32 value) } }
|
||||
|
||||
let changeClipSize (oldRow:AccountSecurityClipLimitUnit) (value:string) =
|
||||
{ oldRow with clipSize = (uint32 value) }
|
||||
|
||||
let limitIsDuplicate exchange secType symbol (limits:AccountSecurityClipLimitUnit []) =
|
||||
Array.exists<AccountSecurityClipLimitUnit>
|
||||
(fun elem -> (
|
||||
elem.security.exchange = exchange &&
|
||||
elem.security.securityType = secType &&
|
||||
elem.security.securitySymbol = symbol
|
||||
)
|
||||
)
|
||||
limits
|
||||
|
||||
let filterSymbols exchange secType symbol =
|
||||
Array.filter (fun elem -> (limitIsDuplicate exchange secType symbol model.scratch.securityClipLimits.limit))
|
||||
|
||||
let isSelected limit =
|
||||
List.exists (fun (elm:AccountSecurityClipLimitUnit) -> State.ClipLimitIsEqual elm limit) model.SelectedClipLimits
|
||||
|
||||
let changeClipSize (oldRow:AccountSecurityClipLimitUnit) (value:string) =
|
||||
modifyRow oldRow { oldRow with clipSize = (uint32 value) }
|
||||
|
||||
let rws:TableControl.row list =
|
||||
[ for limit in model.scratch.securityClipLimits.limit do yield {
|
||||
cells =
|
||||
[
|
||||
TableControl.controlCell (Button.deleteButton Button.Enabled (fun _ -> (Array.findIndex (fun l -> limit = l) model.scratch.securityClipLimits.limit) |> DeleteClipLimit |> dispatch))
|
||||
TableControl.controlCell (Fields.checkbox "" ""
|
||||
(List.exists (fun (elm:AccountSecurityClipLimitUnit) -> State.ClipLimitIsEqual elm limit) model.SelectedClipLimits)
|
||||
[]
|
||||
(fun chckd -> ((chckd, limit) |> SelectClipLimit |> dispatch)))
|
||||
TableControl.Cell (Fields.enumSelect<string>
|
||||
""
|
||||
(EnumUtils.toHuman<bts.api.Venue> false venues limit.security.exchange)
|
||||
(EnumUtils.allToHuman<bts.api.Venue> false venues)
|
||||
[Class ""]
|
||||
((changeVenue limit) >> ClipLimits >> dispatch)
|
||||
(fun value -> ((limit, (changeVenue limit value)) |> ClipLimits |> dispatch))
|
||||
)
|
||||
TableControl.Cell (Fields.enumSelect<string>
|
||||
""
|
||||
(EnumUtils.toHuman<bts.api.SecurityType> false securityTypes limit.security.securityType)
|
||||
(EnumUtils.allToHuman<bts.api.SecurityType> false (Array.filter (fun a -> a <> bts.api.SecurityType.SYNTHETIC) securityTypes))
|
||||
[]
|
||||
((changeType limit) >> ClipLimits >> dispatch)
|
||||
(fun value -> ((limit, (changeType limit value)) |> ClipLimits |> dispatch))
|
||||
)
|
||||
TableControl.Cell (Fields.enumSelect<string>
|
||||
""
|
||||
limit.security.securitySymbol
|
||||
symbolArray
|
||||
(GetSymbolArray model)
|
||||
[]
|
||||
((changeSymbol limit) >> ClipLimits >> dispatch)
|
||||
(fun value -> ((limit, (changeSymbol limit value)) |> ClipLimits |> dispatch))
|
||||
)
|
||||
TableControl.Cell (Fields.mapSelect
|
||||
(*TableControl.Cell (Fields.mapSelect
|
||||
""
|
||||
(JSMap.toMap (getSecurityMap limit))
|
||||
(JSMap.toMap (getSecurityMap model None (Some limit)))
|
||||
None
|
||||
(Some (sprintf "%i" limit.security.securityId))
|
||||
((changeSecurityId limit) >> ClipLimits >> dispatch)
|
||||
)
|
||||
)*)
|
||||
TableControl.Cell (Fields.text
|
||||
""
|
||||
(sprintf "%i" limit.clipSize)
|
||||
[ ]
|
||||
((changeClipSize limit) >> ClipLimits >> dispatch)
|
||||
(fun value -> ((limit, (changeClipSize limit value)) |> ClipLimits |> dispatch))
|
||||
)
|
||||
]
|
||||
className = ""
|
||||
className = match (isSelected limit), (limit.security.securitySymbol = "") with
|
||||
| false, false -> ""
|
||||
| true, false -> "is-selected"
|
||||
| _, true -> "is-warning"
|
||||
header = None
|
||||
}
|
||||
]
|
||||
] @ [footerRow]
|
||||
|
||||
let emptyLimit = {
|
||||
security = { SecurityScope.empty with securitySymbol = model.AllValue }
|
||||
clipSize = 0u
|
||||
}
|
||||
|
||||
let addRow _ = Array.append model.scratch.securityClipLimits.limit [| emptyLimit |] |> (ClipLimits >> dispatch)
|
||||
let addRow _ = (emptyLimit, emptyLimit) |> ClipLimits |> dispatch
|
||||
div []
|
||||
[
|
||||
div [ ClassName "columns" ][
|
||||
@@ -226,6 +256,7 @@ let productLimits model dispatch =
|
||||
{
|
||||
cells =
|
||||
[
|
||||
TableControl.Cell (str "")
|
||||
TableControl.Cell (str "")
|
||||
TableControl.Cell (str "Exchange")
|
||||
TableControl.Cell (str "Security Type")
|
||||
@@ -237,84 +268,125 @@ let productLimits model dispatch =
|
||||
header = None
|
||||
}
|
||||
|
||||
let symbolArray = [|
|
||||
[| model.AllValueDisplay |];
|
||||
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|
||||
|]
|
||||
|> Array.concat
|
||||
|> Array.distinct
|
||||
|
||||
let modifyRow (oldRow:AccountProductPositionLimitUnit) (newRow:AccountProductPositionLimitUnit) =
|
||||
let i = Array.findIndex (fun l -> oldRow = l) model.scratch.productPositionLimits
|
||||
let left = Array.append (model.scratch.productPositionLimits.[..i-1]) [| newRow |]
|
||||
let right = model.scratch.productPositionLimits.[1+i..]
|
||||
Array.concat [left; right]
|
||||
let footerRow:TableControl.row =
|
||||
{
|
||||
cells =
|
||||
[
|
||||
{ content = span [Class "nbsp"] [str "Apply to Selected Rows:"]
|
||||
className = "has-text-right"
|
||||
isHeader = false
|
||||
colSpan = 5
|
||||
}
|
||||
TableControl.Cell (Fields.text
|
||||
""
|
||||
(sprintf "%i" (match (List.tryHead model.SelectedPositionLimits) with
|
||||
| Some r -> r.longPositionLimit
|
||||
| None -> 0u
|
||||
))
|
||||
[ ]
|
||||
((fun value -> ("long", value, (Array.ofList model.SelectedPositionLimits))) >> ChangeMultipleProductLimits >> dispatch)
|
||||
)
|
||||
TableControl.Cell (Fields.text
|
||||
""
|
||||
(sprintf "%i" (match (List.tryHead model.SelectedPositionLimits) with
|
||||
| Some r -> r.shortPositionLimit
|
||||
| None -> 0u
|
||||
))
|
||||
[ ]
|
||||
((fun value -> ("short", value, (Array.ofList model.SelectedPositionLimits))) >> ChangeMultipleProductLimits >> dispatch)
|
||||
)
|
||||
]
|
||||
className = match (model.SelectedPositionLimits.Length > 0) with
|
||||
| true -> ""
|
||||
| false -> "is-hidden-touch is-hidden-desktop"
|
||||
header = None
|
||||
}
|
||||
|
||||
let changeVenue (oldRow:AccountProductPositionLimitUnit) (value:string) =
|
||||
let venueValue = EnumUtils.fromHuman<bts.api.Venue> venues value
|
||||
let newRow = { oldRow with product = { oldRow.product with exchange = venueValue } }
|
||||
modifyRow oldRow newRow
|
||||
{ oldRow with product = { oldRow.product with exchange = venueValue } }
|
||||
|
||||
|
||||
let changeType (oldRow:AccountProductPositionLimitUnit) (value:string) =
|
||||
let typeValue = EnumUtils.fromHuman<bts.api.SecurityType> securityTypes value
|
||||
let newRow = { oldRow with product = { oldRow.product with securityType = typeValue } }
|
||||
modifyRow oldRow newRow
|
||||
{ oldRow with product = { oldRow.product with securityType = typeValue } }
|
||||
|
||||
|
||||
let changeSymbol (oldRow:AccountProductPositionLimitUnit) (value:string) =
|
||||
let v = match (value = model.AllValueDisplay) with
|
||||
| false -> value
|
||||
| true -> model.AllValue
|
||||
modifyRow oldRow { oldRow with product = { oldRow.product with securitySymbol = v } }
|
||||
{ oldRow with product = { oldRow.product with securitySymbol = v } }
|
||||
|
||||
let changeLongPositionLimit (oldRow:AccountProductPositionLimitUnit) (value:string) =
|
||||
modifyRow oldRow { oldRow with longPositionLimit = (uint32 value) }
|
||||
{ oldRow with longPositionLimit = (uint32 value) }
|
||||
|
||||
let changeShortPositionLimit (oldRow:AccountProductPositionLimitUnit) (value:string) =
|
||||
modifyRow oldRow { oldRow with shortPositionLimit = (uint32 value) }
|
||||
{ oldRow with shortPositionLimit = (uint32 value) }
|
||||
|
||||
let limitIsDuplicate exchange secType symbol (limits:AccountProductPositionLimitUnit []) =
|
||||
Array.exists<AccountProductPositionLimitUnit>
|
||||
(fun elem -> (
|
||||
elem.product.exchange = exchange &&
|
||||
elem.product.securityType = secType &&
|
||||
elem.product.securitySymbol = symbol
|
||||
)
|
||||
)
|
||||
limits
|
||||
|
||||
let isSelected limit =
|
||||
List.exists (fun (elm:AccountProductPositionLimitUnit) -> State.PositionLimitIsEqual elm limit) model.SelectedPositionLimits
|
||||
|
||||
let rws:TableControl.row list =
|
||||
[ for limit in model.scratch.productPositionLimits do yield {
|
||||
cells =
|
||||
[
|
||||
TableControl.Cell (Button.deleteButton Button.Enabled (fun _ -> (Array.findIndex (fun l -> limit = l) model.scratch.productPositionLimits) |> DeleteProductLimit |> dispatch))
|
||||
TableControl.controlCell (Fields.checkbox "" ""
|
||||
(List.exists (fun (elm:AccountProductPositionLimitUnit) -> State.PositionLimitIsEqual elm limit) model.SelectedPositionLimits)
|
||||
[]
|
||||
(fun chckd -> ((chckd, limit) |> SelectProductLimit |> dispatch)))
|
||||
TableControl.Cell (Fields.enumSelect<string>
|
||||
""
|
||||
(EnumUtils.toHuman<bts.api.Venue> false venues limit.product.exchange)
|
||||
(EnumUtils.allToHuman<bts.api.Venue> false venues)
|
||||
[]
|
||||
((changeVenue limit) >> ProductLimits >> dispatch)
|
||||
(fun value -> ((limit, (changeVenue limit value)) |> ProductLimits |> dispatch))
|
||||
)
|
||||
TableControl.Cell (Fields.enumSelect<string>
|
||||
""
|
||||
(EnumUtils.toHuman<bts.api.SecurityType> false securityTypes limit.product.securityType)
|
||||
(EnumUtils.allToHuman<bts.api.SecurityType> false (Array.filter (fun a -> a <> bts.api.SecurityType.SYNTHETIC) securityTypes))
|
||||
[]
|
||||
((changeType limit) >> ProductLimits >> dispatch)
|
||||
(fun value -> ((limit, (changeType limit value)) |> ProductLimits |> dispatch))
|
||||
)
|
||||
TableControl.Cell (Fields.enumSelect<string>
|
||||
""
|
||||
limit.product.securitySymbol
|
||||
symbolArray
|
||||
(GetSymbolArray model)
|
||||
[]
|
||||
((changeSymbol limit) >> ProductLimits >> dispatch)
|
||||
(fun value -> ((limit, (changeSymbol limit value)) |> ProductLimits |> dispatch))
|
||||
)
|
||||
TableControl.Cell (Fields.text
|
||||
""
|
||||
(sprintf "%i" limit.longPositionLimit)
|
||||
[ ]
|
||||
((changeLongPositionLimit limit) >> ProductLimits >> dispatch)
|
||||
(fun value -> ((limit, (changeLongPositionLimit limit value)) |> ProductLimits |> dispatch))
|
||||
)
|
||||
TableControl.Cell (Fields.text
|
||||
""
|
||||
(sprintf "%i" limit.shortPositionLimit)
|
||||
[ ]
|
||||
((changeShortPositionLimit limit) >> ProductLimits >> dispatch)
|
||||
(fun value -> ((limit, (changeShortPositionLimit limit value)) |> ProductLimits |> dispatch))
|
||||
)
|
||||
]
|
||||
className = ""
|
||||
className = match (isSelected limit), (limit.product.securitySymbol = "") with
|
||||
| false, false -> ""
|
||||
| true, false -> "is-selected"
|
||||
| _, true -> "is-warning"
|
||||
header = None
|
||||
}
|
||||
]
|
||||
] @ [footerRow]
|
||||
let emptyLimit = {
|
||||
product = {
|
||||
exchange = bts.api.Venue.GLBX
|
||||
@@ -326,11 +398,11 @@ let productLimits model dispatch =
|
||||
netPositionLimit = 0u
|
||||
}
|
||||
|
||||
let addRow _ = Array.append model.scratch.productPositionLimits [| emptyLimit |] |> (ProductLimits >> dispatch)
|
||||
let addRow _ = (emptyLimit, emptyLimit) |> ProductLimits |> dispatch
|
||||
div []
|
||||
[
|
||||
div [ ClassName "columns" ][
|
||||
h1 [ ClassName "is-size-3 column is-narrow" ][str "Product Limits" ]
|
||||
h1 [ ClassName "is-size-3 column is-narrow" ][str "Position Limits" ]
|
||||
div [ ClassName "column is-size-7 has-text-grey-mid is-help-text" ]
|
||||
[str "This limits the net position for a product (i.e. accumulated position over all securities belonging to a product). This can be set for one product, or for all products within a security type by selecting \"All\" for symbol"]
|
||||
]
|
||||
@@ -339,7 +411,7 @@ let productLimits model dispatch =
|
||||
]
|
||||
|
||||
|
||||
let securityLimits model dispatch =
|
||||
let securityLimitsView model dispatch =
|
||||
let headerRow:TableControl.row =
|
||||
{
|
||||
cells =
|
||||
@@ -356,32 +428,6 @@ let securityLimits model dispatch =
|
||||
header = None
|
||||
}
|
||||
|
||||
let symbolArray = [|
|
||||
[| model.AllValueDisplay |];
|
||||
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|
||||
|]
|
||||
|> Array.concat
|
||||
|> Array.distinct
|
||||
|
||||
let getSecurityMap (limit:AccountSecurityPositionLimitUnit) =
|
||||
let allOption = {
|
||||
product = {
|
||||
exchange = bts.api.Venue.UNSET
|
||||
``type`` = bts.api.SecurityType.UNSET
|
||||
symbol = model.AllValueDisplay
|
||||
};
|
||||
names = (JSMap.add<string> "0" model.AllValueDisplay JSMap.empty<string>)
|
||||
}:ExpirationNameList
|
||||
|
||||
Array.concat [ [| allOption |]; model.mdRelayExpNameData]
|
||||
|> Array.filter (fun (x:bts.co2.ExpirationNameList) -> (
|
||||
((x.product.exchange = limit.security.exchange) || (x.product.exchange = bts.api.Venue.UNSET))
|
||||
&& ((x.product.``type`` = limit.security.securityType) || (x.product.``type`` = bts.api.SecurityType.UNSET))
|
||||
&& ((x.product.symbol = limit.security.securitySymbol) || (x.product.symbol = model.AllValueDisplay))
|
||||
)
|
||||
)
|
||||
|> Seq.map (fun x -> x.names ) |> JSMap.concat
|
||||
|
||||
let modifyRow (oldRow:AccountSecurityPositionLimitUnit) (newRow:AccountSecurityPositionLimitUnit) =
|
||||
let i = Array.findIndex (fun l -> oldRow = l) model.scratch.securityPositionLimits
|
||||
let left = Array.append (model.scratch.securityPositionLimits.[..i-1]) [| newRow |]
|
||||
@@ -435,13 +481,13 @@ let securityLimits model dispatch =
|
||||
TableControl.Cell (Fields.enumSelect<string>
|
||||
""
|
||||
limit.security.securitySymbol
|
||||
symbolArray
|
||||
(GetSymbolArray model)
|
||||
[]
|
||||
((changeSymbol limit) >> SecurityLimits >> dispatch)
|
||||
)
|
||||
TableControl.Cell (Fields.mapSelect
|
||||
""
|
||||
(JSMap.toMap (getSecurityMap limit))
|
||||
(JSMap.toMap (getSecurityMap model (Some limit) None))
|
||||
None
|
||||
(Some (sprintf "%i" limit.security.securityId))
|
||||
((changeSecurityId limit) >> SecurityLimits >> dispatch)
|
||||
@@ -485,8 +531,7 @@ let LimitsView model dispatch =
|
||||
div [ Class "limits-container"] [
|
||||
clipLimitsView model dispatch
|
||||
productLimits model dispatch
|
||||
securityLimits model dispatch
|
||||
|
||||
//securityLimitsView model dispatch
|
||||
]
|
||||
|
||||
let ConnectionsView (model:Accounts.Types.Model) dispatch =
|
||||
@@ -504,25 +549,47 @@ let ConnectionsView (model:Accounts.Types.Model) dispatch =
|
||||
let rows:TableControl.row list =
|
||||
[for c in conMap do yield {
|
||||
cells = [
|
||||
{ content = str c.Value
|
||||
className = "is-narrow"
|
||||
isHeader = false
|
||||
colSpan = 1
|
||||
|
||||
}
|
||||
{ content = (Fields.checkbox "" "" (
|
||||
Array.contains c.Value conNames)
|
||||
[]
|
||||
(fun _ -> (match (Array.contains c.Value conNames) with | true -> c.Value |> (RemoveConnection >> dispatch) | false -> c.Key |> (AddConnection>> dispatch)))
|
||||
(fun _ -> (
|
||||
let message:Msg = c.Value |> (RemoveConnection)
|
||||
match (Array.contains c.Value conNames) with
|
||||
| true -> (OpenConfirmModal ((sprintf "Are you sure you want to remove the %s connection from this account?" c.Value), message))
|
||||
| false -> (c.Key |> (AddConnection))
|
||||
|> dispatch
|
||||
)
|
||||
)
|
||||
);
|
||||
className = "is-checkbox-cell";
|
||||
className = "";
|
||||
isHeader = false;
|
||||
colSpan = 0
|
||||
}
|
||||
(TableControl.Cell (str c.Value))
|
||||
}
|
||||
]
|
||||
className=""
|
||||
header = None
|
||||
}
|
||||
]
|
||||
|
||||
div []
|
||||
let headerRow:TableControl.row = {
|
||||
cells =
|
||||
[
|
||||
TableControl.Cell(str "Connection")
|
||||
TableControl.Cell(str "Enabled")
|
||||
]
|
||||
className = ""
|
||||
header = None
|
||||
}
|
||||
|
||||
div [ ]
|
||||
[
|
||||
TableControl.createSelectorTable None rows
|
||||
TableControl.createSelectorTable (Some headerRow) rows
|
||||
]
|
||||
|
||||
let creditLimitsView model dispatch = div [] [str "lorem ipsum"]
|
||||
@@ -547,7 +614,6 @@ let tabContent model dispatch =
|
||||
div [Key (string model.scratch.id); ClassName "is-tab-content"] [
|
||||
(match model.tab with
|
||||
| General -> generalView model dispatch
|
||||
//| ClipLimitsTab -> clipLimitsView model dispatch
|
||||
| LimitsTab -> LimitsView model dispatch
|
||||
| ConnectionsTab -> ConnectionsView model dispatch
|
||||
| CreditLimitsTab -> creditLimitsView model dispatch
|
||||
@@ -563,13 +629,18 @@ let accountControls model (dispatch:Msg->unit) =
|
||||
|
||||
div [ClassName "is-main-control-bar"] [
|
||||
saveButton model dispatch
|
||||
Button.button "Revert" "is-light" "" (if isDirty model then Enabled else Disabled) revertFun
|
||||
Button.button "Revert" "is-light" "" (if isDirty model then Button.Enabled else Button.Disabled) revertFun
|
||||
]
|
||||
|
||||
let isActive account = function
|
||||
| Some a when a = account-> "is-active"
|
||||
| Some a when a = account -> "is-active"
|
||||
| _ -> ""
|
||||
|
||||
let isOptionsMenuOpen accountName openName =
|
||||
match accountName = openName with
|
||||
| true -> "is-active"
|
||||
| false -> ""
|
||||
|
||||
let isActiveItem a b = if a = b then "is-active" else ""
|
||||
|
||||
let accountsMenu (accounts:BTSAccount[]) selectedAccount dispatch =
|
||||
@@ -638,7 +709,7 @@ let selectionPageContent (adminData:AdminData) (model:Model) (dispatch:Msg->Unit
|
||||
(div [] [
|
||||
Fields.text "Name" account.name [] (AccountName >> Update >> dispatch)
|
||||
Fields.text "Description" account.description [] (Description >> Update >> dispatch)
|
||||
Fields.checkbox "Active" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
|
||||
Fields.checkbox "Can Trade Into Account" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
|
||||
])
|
||||
(fun _ -> dispatch SaveScratch)
|
||||
revertFun
|
||||
@@ -649,27 +720,60 @@ let selectionPageContent (adminData:AdminData) (model:Model) (dispatch:Msg->Unit
|
||||
(if State.isNewAccount model.scratch then modal else span[][])
|
||||
]
|
||||
|
||||
let menuItem account selectedAccount model dispatch =
|
||||
a [ ClassName (isActive account selectedAccount)
|
||||
OnClick (fun _ -> SelectAccount account |> dispatch)
|
||||
] [
|
||||
span [] [ str account.name ]
|
||||
span [ Class "is-pulled-right menu-icon" ]
|
||||
[
|
||||
div [ Class (sprintf "dropdown %s" (isOptionsMenuOpen account.name model.OptionsMenuOpen)) ]
|
||||
[ div [ Class "dropdown-trigger" ]
|
||||
[ button [ Class "button"
|
||||
AriaHasPopup true
|
||||
OnClick (fun _ -> account.name |> OpenOptionsMenu |> dispatch)
|
||||
HTMLAttr.Custom ("aria-controls", (sprintf "dropdown-menu-%s" account.name)) ]
|
||||
[ span [ Class "icon is-small" ]
|
||||
[ i [ Class "fa fa-ellipsis-v"
|
||||
HTMLAttr.Custom ("aria-hidden", "true") ][ ]
|
||||
]
|
||||
]
|
||||
]
|
||||
div [ Class "dropdown-menu"
|
||||
Id (sprintf "dropdown-menu-%s" account.name)
|
||||
Role "menu"
|
||||
|
||||
let NavRoot (accounts:BTSAccount[]) selectedAccount dispatch =
|
||||
]
|
||||
[ div [ Class "dropdown-content" ]
|
||||
[ //hr [ Class "dropdown-divider" ]
|
||||
a [ Class "dropdown-item"
|
||||
OnClick (fun _ -> dispatch <| DeleteAccount account)
|
||||
]
|
||||
[ str "Remove" ]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
let NavRoot (accounts:BTSAccount[]) selectedAccount model dispatch =
|
||||
div [ Class "column is-narrow is-sidebar-menu" ]
|
||||
[ aside [ Class "menu" ]
|
||||
[ div [ Class "has-text-right" ]
|
||||
[ Button.faRoundButton "Add Account" "plus" Enabled (fun _ -> dispatch AddAccount) ]
|
||||
[ p [ Class "menu-label" ] [
|
||||
span [Class "is-size-4"] [str "Accounts"]
|
||||
span [ Class "is-pulled-right circle-icon" ]
|
||||
[ Button.fabutton "Add Account" "plus-circle" "" Button.Enabled (fun _ -> dispatch AddAccount) ]
|
||||
]
|
||||
|
||||
ul [ Class "menu-list" ]
|
||||
[
|
||||
for account in accounts do
|
||||
yield li [] [
|
||||
a [
|
||||
ClassName (isActive account selectedAccount)
|
||||
OnClick (fun _ -> SelectAccount account |> dispatch) ] [
|
||||
str account.name]
|
||||
]
|
||||
yield li [] [ menuItem account selectedAccount model dispatch ]
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
let tabName = function
|
||||
//| ClipLimitsTab -> "Clip Limits"
|
||||
| LimitsTab -> "Limits"
|
||||
| CreditLimitsTab -> "Credit Limits"
|
||||
| ConnectionsTab -> "Connections"
|
||||
@@ -682,18 +786,26 @@ let tabHeader tab currentTab dispatch =
|
||||
]
|
||||
|
||||
let root (model:Model) dispatch =
|
||||
let modal = match (fst model.ConfirmModal) with
|
||||
| "" -> span [] []
|
||||
| _ -> Modal.showConfirm (fst model.ConfirmModal) (fun () -> (snd model.ConfirmModal) |> dispatch) (fun _ -> OpenConfirmModal ("", Msg.SelectTab model.tab ) |> dispatch)
|
||||
match model.adminData with
|
||||
| None -> div[][str "Loading account list..."]
|
||||
| Some data ->
|
||||
div
|
||||
[ Class "columns is-fullheight" ]
|
||||
[ NavRoot data.accounts (selectedAccount model) dispatch
|
||||
[ Class "columns is-fullheight"
|
||||
OnClick (fun _ ->
|
||||
match model.OptionsMenuOpen.Length > 0 with
|
||||
| true -> "" |> OpenOptionsMenu |> dispatch
|
||||
| _ -> ()
|
||||
)
|
||||
]
|
||||
[ NavRoot data.accounts (selectedAccount model) model dispatch
|
||||
div [ Class "column is-main-content" ]
|
||||
[
|
||||
div [ ClassName "tabs is-boxed" ] [
|
||||
ul [] [
|
||||
tabHeader General model.tab dispatch
|
||||
//tabHeader ClipLimitsTab model.tab dispatch
|
||||
tabHeader LimitsTab model.tab dispatch
|
||||
tabHeader ConnectionsTab model.tab dispatch
|
||||
// tabHeader CreditLimits model.tab dispatch
|
||||
@@ -702,5 +814,6 @@ let root (model:Model) dispatch =
|
||||
]
|
||||
tabContent model dispatch
|
||||
accountControls model dispatch
|
||||
modal
|
||||
]
|
||||
]
|
||||
@@ -22,16 +22,9 @@ open ServiceContext
|
||||
let topLevel (sc:ServiceContext.ServiceContext) currentPage dispatch content =
|
||||
div
|
||||
[ Class "columns is-fullheight" ]
|
||||
[ Nav.root currentPage sc dispatch
|
||||
[ Nav.navRoot currentPage sc dispatch
|
||||
div [ Class "column is-main-content" ]
|
||||
[ content]
|
||||
(*
|
||||
div
|
||||
[ ClassName "navbar-bg" ]
|
||||
[ div
|
||||
[ ClassName "container" ]
|
||||
[(App.Nav.navRoot currentPage sc dispatch) ] ]
|
||||
//[(App.Nav.nav' currentPage sc dispatch) ] ]*)
|
||||
[ content ]
|
||||
]
|
||||
|
||||
let root model dispatch =
|
||||
|
||||
@@ -48,12 +48,12 @@ let faRoundButton title icon disabled click =
|
||||
]
|
||||
|
||||
|
||||
let fabutton title icon disabled click =
|
||||
let fabutton title icon classname disabled click =
|
||||
a [ ClassName "button fabutton"
|
||||
HTMLAttr.Disabled (isDisabled disabled)
|
||||
Title title
|
||||
OnClick click ] [
|
||||
span [ ClassName "icon is-small" ] [
|
||||
span [ ClassName (sprintf "icon %s" classname) ] [
|
||||
i [ ClassName (sprintf "fa fa-%s" icon)] [ ] ]
|
||||
]
|
||||
|
||||
|
||||
@@ -96,8 +96,8 @@ let map (lbl:string) (dv:JSMap<string>) (attrs:IHTMLProp list) (onchange: JSMap<
|
||||
[HTMLAttr.Disabled true; Placeholder "Enter New Item Name:"; ]
|
||||
[ OnBlur ((fun ev -> !!ev.target?value |> newEntry )) ]
|
||||
[
|
||||
Button.fabutton "" "" Button.Enabled ignore
|
||||
Button.fabutton "Add" "check" Button.Enabled ignore
|
||||
Button.fabutton "" "" "is-small" Button.Enabled ignore
|
||||
Button.fabutton "Add" "check" "is-small" Button.Enabled ignore
|
||||
]
|
||||
change
|
||||
| _ ->
|
||||
@@ -105,7 +105,7 @@ let map (lbl:string) (dv:JSMap<string>) (attrs:IHTMLProp list) (onchange: JSMap<
|
||||
i
|
||||
[HTMLAttr.Disabled true]
|
||||
[]
|
||||
[Button.fabutton "Delete" "times" Button.Enabled (fun _ -> (remove i))]
|
||||
[Button.fabutton "Delete" "times" "is-small" Button.Enabled (fun _ -> (remove i))]
|
||||
change
|
||||
)]
|
||||
|
||||
@@ -113,7 +113,7 @@ let map (lbl:string) (dv:JSMap<string>) (attrs:IHTMLProp list) (onchange: JSMap<
|
||||
[
|
||||
Label lbl
|
||||
div [] elementList
|
||||
Button.fabutton "Add" "plus" Button.Enabled ((fun _ -> change ("","") "" ""))
|
||||
Button.fabutton "Add" "plus" "is-small" Button.Enabled ((fun _ -> change ("","") "" ""))
|
||||
]
|
||||
|
||||
let password (lbl:string) (dv:string) (attrs:IHTMLProp list) onchange =
|
||||
@@ -213,4 +213,21 @@ let simpleSelect (lbl:string) (options:string list) (defaultValue:string) (oncha
|
||||
[ for opt in options do yield option [ Value opt ] [ str (opt) ] ]
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
let menuSelect (options:string list) (onchange:'a->unit) =
|
||||
div [ ClassName "field" ]
|
||||
[
|
||||
div [ ClassName "control" ]
|
||||
[
|
||||
div [ ClassName "select menu-select" ]
|
||||
[
|
||||
select [
|
||||
Value ""
|
||||
OnChange (fun ev -> !!ev.target?value |> onchange)
|
||||
]
|
||||
[ for opt in options do yield option [ Value opt ] [ str (opt) ] ]
|
||||
]
|
||||
]
|
||||
]
|
||||
@@ -9,31 +9,39 @@ open Global
|
||||
open Fable
|
||||
|
||||
|
||||
let show (title:string) (content:ReactElement) (footerContent:ReactElement) (onCloseClick: MouseEvent -> Unit) =
|
||||
let show (title:string) (content:ReactElement) (footerContent:ReactElement) (onCloseClick: MouseEvent -> Unit) =
|
||||
div [ Class "modal is-active" ]
|
||||
[ div [ Class "modal-background" ][ ]
|
||||
div [ Class "modal-card" ]
|
||||
[ header [ Class "modal-card-head" ]
|
||||
[ p [ Class "modal-card-title" ][ str title ]
|
||||
button [ Class "delete"; OnClick onCloseClick ] [ ]
|
||||
button [ Class "delete"; OnClick onCloseClick ] [ ]
|
||||
]
|
||||
section [ Class "modal-card-body" ] [ content ]
|
||||
footer [ Class "modal-card-foot" ] [ footerContent ]
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
let showCreate title content (onCreateClick: MouseEvent -> Unit) (onCloseClick: MouseEvent -> Unit) =
|
||||
show
|
||||
title
|
||||
content
|
||||
show
|
||||
title
|
||||
content
|
||||
(div [] [ button [ Class "button is-success"; OnClick onCreateClick ]
|
||||
[ str "Create" ]
|
||||
button [ Class "button"; OnClick onCloseClick ]
|
||||
[ str "Cancel" ]
|
||||
])
|
||||
(onCloseClick: MouseEvent -> Unit)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
let showConfirm description (onOK:unit->unit) onCancel =
|
||||
show
|
||||
"Confirm"
|
||||
(str description)
|
||||
(div [] [ button [ Class "button is-success"; OnClick (ignore>>onOK) ]
|
||||
[ str "Confirm" ]
|
||||
button [ Class "button"; OnClick onCancel ]
|
||||
[ str "Cancel" ]
|
||||
])
|
||||
(onCancel: MouseEvent -> Unit)
|
||||
|
||||
@@ -17,6 +17,8 @@ open Fable.Helpers.React.Props
|
||||
open Elmish.React.Common
|
||||
open ServiceContext
|
||||
open Fable.Helpers
|
||||
open Imports
|
||||
open Fable.Import.React
|
||||
|
||||
let isCurrentPage page currentPage =
|
||||
match page, currentPage with
|
||||
@@ -57,4 +59,4 @@ let root (currentPage:Page) (sc:ServiceContext) dispatch =
|
||||
]
|
||||
]
|
||||
|
||||
//let navRoot = lazyView3With (fun a b -> isCurrentPage (fst a) (fst b)) root
|
||||
let (navRoot: 'a -> ServiceContext -> Dispatch<Msg> -> ReactElement) = lazyView3With (fun b c -> isCurrentPage (fst b) (fst c)) root
|
||||
@@ -12,6 +12,12 @@ open Fable.PowerPack.PromiseImpl
|
||||
open bts.api.admin
|
||||
open Global
|
||||
|
||||
let SMPInstructionMap:Map<string, string> = Map.empty
|
||||
.Add("O", "Cancel Resting")
|
||||
.Add("N", "Cancel Agressing")
|
||||
.Add("", "Undefined")
|
||||
|
||||
|
||||
let isNewUser (user:BTSUser) =
|
||||
user.id = 0u && user.isPresent
|
||||
|
||||
@@ -90,6 +96,8 @@ let init (context:ServiceContext.ServiceContext) : Model * Cmd<Msg> =
|
||||
currentTab = Tab.General
|
||||
admin = admin
|
||||
adminData = None
|
||||
OptionsMenuOpen = ""
|
||||
ConfirmModal = "", (Msg.SwitchTab Tab.General)
|
||||
}, getAdminData admin
|
||||
|
||||
let rec removeUser (user:BTSUser) (userList:BTSUser list) =
|
||||
@@ -116,7 +124,6 @@ let getCurrentOrFirstUser (model:Model) (userList:BTSUser list) =
|
||||
| Some cu, _ -> cu
|
||||
| None, Some pu -> pu
|
||||
| None, None -> getFirstUser userList
|
||||
//| None, None -> defaultScratchUser
|
||||
|
||||
let getCurrentUser (model:Model) = getCurrentOrFirstUser model model.userList
|
||||
|
||||
@@ -212,7 +219,7 @@ let update msg (model:Users.Types.Model) : Model * Cmd<Msg> =
|
||||
printf "%s" str
|
||||
model, Cmd.Empty
|
||||
| UpdateField field ->
|
||||
{ model with scratchUser = applyUpdate field model.scratchUser } , Cmd.Empty
|
||||
{ model with scratchUser = applyUpdate field model.scratchUser; ConfirmModal = ("", Msg.SwitchTab model.currentTab) } , Cmd.Empty
|
||||
| Clone usr ->
|
||||
{ model with scratchUser = { usr with id = 0u; name = usr.name + "_copy" }}, Cmd.Empty
|
||||
| CopyFrom (usrSrc, usrDest) ->
|
||||
@@ -225,9 +232,10 @@ let update msg (model:Users.Types.Model) : Model * Cmd<Msg> =
|
||||
{ model with scratchUser = nusr }, Cmd.Empty
|
||||
|
||||
| Delete usr ->
|
||||
let mdl = { model with OptionsMenuOpen = "" }
|
||||
match Fable.Import.Browser.window.confirm (sprintf "Are you sure you want to delete '%s'" usr.name) with
|
||||
| true -> model, Cmd.ofExistingPromise (deleteUser model.admin usr) id (box>>ErrorOccured)
|
||||
| false -> model, Cmd.Empty
|
||||
| true -> mdl, Cmd.ofExistingPromise (deleteUser model.admin usr) id (box>>ErrorOccured)
|
||||
| false -> mdl, Cmd.Empty
|
||||
|
||||
| AddUser ->
|
||||
{ model with PreviousScratchUser = model.scratchUser; scratchUser = { defaultScratchUser with name = "New User" }}, Cmd.ofMsg (SwitchTab General)
|
||||
@@ -247,3 +255,7 @@ let update msg (model:Users.Types.Model) : Model * Cmd<Msg> =
|
||||
//Browser.console.log msg
|
||||
Global.alert Global.Error (string msg)
|
||||
model,Cmd.Empty
|
||||
| OpenOptionsMenu usrName ->
|
||||
{ model with OptionsMenuOpen = usrName }, Cmd.Empty
|
||||
| OpenConfirmModal (title, okMessage) ->
|
||||
{model with ConfirmModal = title, okMessage}, Cmd.Empty
|
||||
@@ -9,16 +9,6 @@ type Tab =
|
||||
| MDEntitlements
|
||||
| OrderRouting
|
||||
|
||||
type Model = {
|
||||
userList: BTSUser list
|
||||
accountsList: BTSAccount list
|
||||
scratchUser:BTSUser
|
||||
PreviousScratchUser:BTSUser
|
||||
currentTab:Tab
|
||||
admin : IAdminService
|
||||
adminData : AdminData option
|
||||
}
|
||||
|
||||
type UserField =
|
||||
| Name of string
|
||||
| Password of string
|
||||
@@ -53,4 +43,17 @@ type Msg =
|
||||
| SwitchUser of BTSUser
|
||||
| SaveUser
|
||||
| ErrorOccured of obj
|
||||
| OpenOptionsMenu of string
|
||||
| OpenConfirmModal of string * Msg
|
||||
|
||||
type Model = {
|
||||
userList: BTSUser list
|
||||
accountsList: BTSAccount list
|
||||
scratchUser:BTSUser
|
||||
PreviousScratchUser:BTSUser
|
||||
currentTab:Tab
|
||||
admin : IAdminService
|
||||
adminData : AdminData option
|
||||
OptionsMenuOpen: string
|
||||
ConfirmModal: string * Msg
|
||||
}
|
||||
@@ -25,6 +25,11 @@ let isActiveUser id (currentUser:BTSUser) =
|
||||
| true -> "is-active"
|
||||
| false -> ""
|
||||
|
||||
let isOptionsMenuOpen userName openName =
|
||||
match userName = openName with
|
||||
| true -> "is-active"
|
||||
| false -> ""
|
||||
|
||||
let saveButton (model:Users.Types.Model) dispatch =
|
||||
let buttonText = if State.isNewUser model.scratchUser then "Create" else "Save"
|
||||
let dirty = State.userIsdirty State.defaultScratchUser model.scratchUser (State.getCurrentUser model)
|
||||
@@ -32,7 +37,7 @@ let saveButton (model:Users.Types.Model) dispatch =
|
||||
let flavor = if dirty then "is-success" else "is-light"
|
||||
Button.button buttonText flavor "" enabled (fun _ -> dispatch SaveUser)
|
||||
|
||||
let generalTabContent (model:Model) (dispatch:Msg->Unit) =
|
||||
let generalTabView (model:Model) (dispatch:Msg->Unit) =
|
||||
let modal = Modal.showCreate
|
||||
"Create User"
|
||||
(div [][
|
||||
@@ -49,7 +54,6 @@ let generalTabContent (model:Model) (dispatch:Msg->Unit) =
|
||||
Fields.password "Password" model.scratchUser.password [ ] (Password >> UpdateField >> dispatch)
|
||||
Fields.checkbox "Active" "Unchecking this stops the user from entering orders" model.scratchUser.isActive [] (IsActive >> UpdateField >> dispatch)
|
||||
(if State.isNewUser model.scratchUser then modal else span[][])
|
||||
Button.button "Remove User" "is-danger-hover" "times" Button.Enabled (fun _ -> dispatch <| Delete model.scratchUser)
|
||||
]
|
||||
|
||||
let accountNameLookup (accountsList:BTSAccount list) (id:string) =
|
||||
@@ -58,7 +62,7 @@ let accountNameLookup (accountsList:BTSAccount list) (id:string) =
|
||||
| None -> "Account Not Found"
|
||||
|
||||
|
||||
let accountsTabContent (model:Model) (dispatch:Msg->Unit) =
|
||||
let accountsTabView (model:Model) (dispatch:Msg->Unit) =
|
||||
let accountPermissions = model.scratchUser.userData.accountPermissions.accountPermissions
|
||||
|
||||
let keys =
|
||||
@@ -87,12 +91,18 @@ let accountsTabContent (model:Model) (dispatch:Msg->Unit) =
|
||||
let rows:TableControl.row list =
|
||||
[for acc in accMap do yield {
|
||||
cells = [
|
||||
//TableControl.Cell(Button.removeButton Button.Enabled (fun _ -> key |> (RemoveAccount >> UpdateField >> dispatch)))
|
||||
TableControl.Cell(str acc.Value)
|
||||
{ content = (Fields.checkbox "" "" (
|
||||
keymap.Contains <| acc.Value)
|
||||
[]
|
||||
(fun _ -> acc.Key |> ((match (keymap.Contains <| acc.Value) with | true -> RemoveAccount | false -> AddAccount) >> UpdateField >> dispatch))
|
||||
(fun _ -> (
|
||||
let message:Msg = acc.Key |> (RemoveAccount >> UpdateField)
|
||||
match (keymap.Contains <| acc.Value) with
|
||||
| true -> (OpenConfirmModal ((sprintf "Are you sure you want to remove trading permission for %s?" acc.Value), message))
|
||||
| false -> (acc.Key |> (AddAccount >> UpdateField))
|
||||
|> dispatch
|
||||
)
|
||||
)
|
||||
);
|
||||
className = "";
|
||||
isHeader = false;
|
||||
@@ -118,7 +128,7 @@ let accountsTabContent (model:Model) (dispatch:Msg->Unit) =
|
||||
TableControl.createSelectorTable (Some headerRow) rows
|
||||
]
|
||||
|
||||
let mdEntitlementsTabContent (model:Model) (dispatch:Msg->Unit) =
|
||||
let mdEntitlementsTabView (model:Model) (dispatch:Msg->Unit) =
|
||||
let cmeData = model.scratchUser.userData.exchangeMdEntitlementData.cmeData
|
||||
div []
|
||||
[
|
||||
@@ -134,7 +144,7 @@ let mdEntitlementsTabContent (model:Model) (dispatch:Msg->Unit) =
|
||||
]
|
||||
]
|
||||
|
||||
let orderRoutingTabContent (model:Model) (dispatch:Msg->Unit) =
|
||||
let orderRoutingTabView (model:Model) (dispatch:Msg->Unit) =
|
||||
let cmeData = model.scratchUser.userData.exchangeUserData.cmeData
|
||||
div []
|
||||
[
|
||||
@@ -143,8 +153,8 @@ let orderRoutingTabContent (model:Model) (dispatch:Msg->Unit) =
|
||||
[
|
||||
Fields.text "Operator ID" cmeData.operatorId [] (OperatorID >> UpdateField >> dispatch)
|
||||
//Fields.text "ATS Operator ID" cmeData.atsOperatorId [] (ATSOperatorID >> UpdateField >> dispatch)
|
||||
//Fields.text "SMP ID" cmeData.smpId [] (SMPID >> UpdateField >> dispatch)
|
||||
Fields.text "SMP Instruction" cmeData.smpInstruction [] (SMPInstruction >> UpdateField >> dispatch)
|
||||
Fields.text "SMP ID" cmeData.smpId [] (SMPID >> UpdateField >> dispatch)
|
||||
Fields.mapSelect "SMP Instruction" State.SMPInstructionMap None (Some cmeData.smpInstruction) (SMPInstruction >> UpdateField >> dispatch)
|
||||
Fields.text "Location" cmeData.location [] (Location >> UpdateField >> dispatch)
|
||||
//Fields.text "Max Order Rate Per Connection" cmeData.maxOrderRatePerConnection [] (MaxOrderRatePerConnection >> UpdateField >> dispatch)
|
||||
//Fields.map "Misc Tag Mapping" cmeData.miscTags [] (MiscTags >> UpdateField >> dispatch)
|
||||
@@ -155,10 +165,10 @@ let tabContent (model:Model) (dispatch:Msg->Unit) =
|
||||
div [Key (string model.scratchUser.id); ClassName "is-tab-content"] [
|
||||
(match model.currentTab, (State.userIsSelected model.scratchUser State.defaultScratchUser) with
|
||||
| _, false -> p [Style [ Color "Red" ]] [ str "Select a User" ]
|
||||
| Tab.General, true -> generalTabContent model dispatch
|
||||
| Tab.Accounts, true -> accountsTabContent model dispatch
|
||||
| Tab.MDEntitlements, true -> mdEntitlementsTabContent model dispatch
|
||||
| Tab.OrderRouting, true -> orderRoutingTabContent model dispatch)
|
||||
| Tab.General, true -> generalTabView model dispatch
|
||||
| Tab.Accounts, true -> accountsTabView model dispatch
|
||||
| Tab.MDEntitlements, true -> mdEntitlementsTabView model dispatch
|
||||
| Tab.OrderRouting, true -> orderRoutingTabView model dispatch)
|
||||
]
|
||||
|
||||
let userControls (model:Model) (dispatch:Msg->Unit) =
|
||||
@@ -167,7 +177,6 @@ let userControls (model:Model) (dispatch:Msg->Unit) =
|
||||
|
||||
div [ ClassName "is-main-control-bar" ]
|
||||
[
|
||||
nbsp.element
|
||||
saveButton model dispatch
|
||||
Button.button "Revert" "is-light" "" (if dirty then Button.Enabled else Button.Disabled) (fun _ -> SwitchUser (currentUser) |> dispatch)
|
||||
(*p [ ClassName "control" ]
|
||||
@@ -254,28 +263,59 @@ let userSelectionGrid (usersList:BTSUser list) (currentUser:BTSUser) (dispatch:M
|
||||
TableControl.createSelectorTable (Some headerRow) rws
|
||||
]
|
||||
|
||||
let menuItem (user:BTSUser) (selectedUser:BTSUser) model dispatch =
|
||||
a [ ClassName (isActiveUser user.id selectedUser)
|
||||
OnClick (fun _ -> SwitchUser user |> dispatch)
|
||||
] [
|
||||
span [] [ str user.name ]
|
||||
span [ Class "is-pulled-right menu-icon" ]
|
||||
[
|
||||
div [ Class (sprintf "dropdown %s" (isOptionsMenuOpen user.name model.OptionsMenuOpen)) ]
|
||||
[ div [ Class "dropdown-trigger" ]
|
||||
[ button [ Class "button"
|
||||
AriaHasPopup true
|
||||
OnClick (fun _ -> user.name |> OpenOptionsMenu |> dispatch)
|
||||
HTMLAttr.Custom ("aria-controls", (sprintf "dropdown-menu-%s" user.name))
|
||||
]
|
||||
[ span [ Class "icon is-small" ]
|
||||
[ i [ Class "fa fa-ellipsis-v"
|
||||
HTMLAttr.Custom ("aria-hidden", "true") ][ ]
|
||||
]
|
||||
]
|
||||
]
|
||||
div [ Class "dropdown-menu"
|
||||
Id (sprintf "dropdown-menu-%s" user.name)
|
||||
Role "menu"
|
||||
|
||||
let NavRoot (usersList:BTSUser list) (currentUser:BTSUser) (dispatch:Msg->Unit) =
|
||||
]
|
||||
[ div [ Class "dropdown-content" ]
|
||||
[ //hr [ Class "dropdown-divider" ]
|
||||
a [ Class "dropdown-item"
|
||||
OnClick (fun _ -> dispatch <| Delete user)
|
||||
]
|
||||
[ str "Remove" ]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
]
|
||||
|
||||
let NavRoot (usersList:BTSUser list) (currentUser:BTSUser) model (dispatch:Msg->Unit) =
|
||||
let activeUsers =
|
||||
usersList |> List.sortBy (fun u -> u.name.ToLower())
|
||||
|
||||
div [ Class "column is-narrow is-sidebar-menu" ]
|
||||
[ aside [ Class "menu" ]
|
||||
[ div [ Class "has-text-right" ]
|
||||
[
|
||||
Button.faRoundButton "Add User" "plus" Button.Enabled (fun _ -> dispatch <| AddUser)
|
||||
]
|
||||
[ p [ Class "menu-label" ] [
|
||||
span [Class "is-size-4"] [str "Users"]
|
||||
span [ Class "is-pulled-right circle-icon" ]
|
||||
[ Button.fabutton "Add User" "plus-circle" "" Button.Enabled (fun _ -> dispatch AddUser) ]
|
||||
]
|
||||
|
||||
ul [ Class "menu-list" ]
|
||||
[
|
||||
for u in activeUsers do yield li []
|
||||
[ a [
|
||||
ClassName (isActiveUser u.id currentUser)
|
||||
OnClick (fun _ -> (u |> SwitchUser |> dispatch))
|
||||
]
|
||||
[
|
||||
str u.name
|
||||
]
|
||||
]
|
||||
[ menuItem u currentUser model dispatch]
|
||||
]
|
||||
]
|
||||
]
|
||||
@@ -297,13 +337,31 @@ let selectionPageContent (model:Model) (dispatch:Msg->Unit) =
|
||||
]
|
||||
|
||||
let root (model:Model) (dispatch:Msg->Unit) =
|
||||
|
||||
(*
|
||||
Fable.Import.Browser.document.addEventListener_keydown (fun (e:Fable.Import.Browser.KeyboardEvent) ->
|
||||
match e.ctrlKey, (e.keyCode = 83.0) with
|
||||
| true, true ->
|
||||
match (State.userIsdirty State.defaultScratchUser model.scratchUser (State.getCurrentUser model)) with
|
||||
| true -> SaveUser |> dispatch |> e.preventDefault
|
||||
| false -> () |> e.preventDefault
|
||||
| _, _ -> ()
|
||||
)
|
||||
*)
|
||||
let modal = match (fst model.ConfirmModal) with
|
||||
| "" -> span [] []
|
||||
| _ -> Modal.showConfirm (fst model.ConfirmModal) (fun () -> (snd model.ConfirmModal) |> dispatch) (fun _ -> OpenConfirmModal ("", Msg.SwitchTab model.currentTab ) |> dispatch)
|
||||
(match model.adminData with
|
||||
| None -> div[][str "Loading user list..."]
|
||||
| Some data ->
|
||||
div
|
||||
[ Class "columns is-fullheight" ]
|
||||
[ NavRoot model.userList model.scratchUser dispatch
|
||||
[ Class "columns is-fullheight"
|
||||
OnClick (fun _ ->
|
||||
match model.OptionsMenuOpen.Length > 0 with
|
||||
| true -> "" |> OpenOptionsMenu |> dispatch
|
||||
| _ -> ()
|
||||
)
|
||||
]
|
||||
[ NavRoot model.userList model.scratchUser model dispatch
|
||||
div [ Class "column is-main-content" ]
|
||||
[
|
||||
div [ ClassName "tabs is-boxed" ]
|
||||
@@ -325,6 +383,7 @@ let root (model:Model) (dispatch:Msg->Unit) =
|
||||
]
|
||||
tabContent model dispatch
|
||||
userControls model dispatch
|
||||
modal
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
Reference in new issue
Block a user