Merged in fix_mics (pull request #98)

Fix mics - Ready to Merge

Approved-by: Michael Harding <michael.harding@bluetradesys.com>
Approved-by: Jake Norbut <jake.norbut@bluetradesys.com>
This commit is contained in:
Kevin Darby authored and Pedro Pinto committed 2018-12-03 20:45:57 +00:00
commit d3deac46d4
50 files changed
+1308 -530

No files matched your search

+7
View File
@@ -1,3 +1,10 @@
1.4.2
- Be sure the system has a bts user before deployment. bts is the superuser, he has all permissions and can see all market data
- After deployment re-permission all existing users for trading, riskadmin, and/or md admin permissions as appropriate
- Also note which users can add other users and accounts and permission them appropriately (Can Add?)
- Permission users for appropriate market data entitlements; this has monetary consequences so ask Kevin if you aren't sure.
- MIC reporting needs to be added to audit Jenkins job (https://bluetradesys.atlassian.net/browse/SPARK-1900)
1.3.5
- Change in market data wire format. Old shell will get only direct market data instead of merged which may not match what the servers is driving from.
+1 -1
View File
@@ -36,7 +36,7 @@ namespace mbts.spark {
IEnumerable<BTSAccountImmutable> active_accounts =
from admin_data in update.all
from bts_account in admin_data.Accounts
where bts_account.IsPresent
where bts_account.IsPresent && _wrapper_subject.Value.can_view_account(bts_account.Name)
join account_id in (
from bts_user in active_users
from account_id in bts_user.UserData.AccountPermissions.AccountPermissions.Keys
+10 -12
View File
@@ -16,26 +16,26 @@ namespace mbts.spark
{
_admin_data = admin_data;
_user_name = user_name ?? string.Empty;
_allowed_accounts = search_admin(u => u.Name == _user_name).Select(x => x.Item1).ToList();
foreach(var val in _allowed_accounts)
_allowed_accounts = search_admin(u => u.Name == _user_name).Where(x =>
{
return x.Item2.HasPermissions || x.Item3.HasPermissions;
}).Select(xx => xx.Item1).ToList();
foreach (var val in _allowed_accounts)
_allowed_account_dict[val.Name] = val.Name;
}
public IEnumerable<Tuple<BTSAccountImmutable, TradingPermissionUnitImmutable>> get_trading_permissions(UInt32 user_id)
{
return search_admin(u => u.Id == user_id);
}
public IEnumerable<BTSAccountImmutable> viewable_accounts()
{
return _allowed_accounts;
}
public bool can_view_account(string account)
{
return _allowed_account_dict.ContainsKey(account) || _user_name.ToLower() == "bts";
return _allowed_account_dict.ContainsKey(account) || _user_name.ToLower().Equals("bts");
}
IEnumerable<Tuple<BTSAccountImmutable, TradingPermissionUnitImmutable>> search_admin(Func<BTSUserImmutable, bool> predicate)
IEnumerable<Tuple<BTSAccountImmutable, TradingPermissionUnit, AdminPermissionUnit>>
search_admin(Func<BTSUserImmutable, bool> predicate)
{
var rv = new List<Tuple<BTSAccountImmutable, TradingPermissionUnitImmutable>>();
var rv = new List<Tuple<BTSAccountImmutable, TradingPermissionUnit, AdminPermissionUnit>>();
if (_admin_data.HasValue)
{
var users = _admin_data.Value.Users.Where(predicate);
@@ -51,9 +51,7 @@ namespace mbts.spark
if (accounts != null && accounts.Count() == 1)
{
var account = accounts.ElementAt(0);
var tp = kv.Value.TradingPermission;
var rv_val = new TradingPermissionUnitImmutable(tp);
rv.Add(Tuple.Create(account, rv_val));
rv.Add(Tuple.Create(account, kv.Value.TradingPermission, kv.Value.AdminPermission));
}
}
}
@@ -25,7 +25,7 @@ namespace mbts.spark
cross_threshold = new InlineUserProperty<bts.spark.QuantityMeasure>(
new bts.spark.QuantityMeasure() { Ratio = 1.0, Absolute = 1}, false);
max_chase_ticks = new InlineUserProperty<uint>(2, false);
trade_toward_behavior = new InlineUserProperty<LeanOrderDefinition.Types.OnToward>(LeanOrderDefinition.Types.OnToward.Cancel, false);
trade_toward_behavior = new InlineUserProperty<LeanOrderDefinition.Types.OnToward>(LeanOrderDefinition.Types.OnToward.NoChange, false);
}
public readonly InlineUserProperty<OrderTemplateHeader> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<OrderTemplateHeader>> child_order_types;
@@ -47,7 +47,7 @@ namespace mbts.spark
public bts.spark.QuantityMeasure cross_threshold { get; set; } = new bts.spark.QuantityMeasure() { Ratio = 1.0, Absolute = 1 };
public uint max_chase_ticks { get; set; } = 2;
public LeanOrderDefinition.Types.OnToward trade_toward_behavior { get; set; } = LeanOrderDefinition.Types.OnToward.Cancel;
public LeanOrderDefinition.Types.OnToward trade_toward_behavior { get; set; } = LeanOrderDefinition.Types.OnToward.NoChange;
public LeanOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string id, string display_name)
: this(model, security_md_source, security_md_source.Select(smd =>
+23
View File
@@ -0,0 +1,23 @@
using System;
using System.Threading.Tasks;
using bts.api;
using bts.api.core;
namespace bts.api
{
public class Authenticator
{
readonly static Lazy<user.UserService> _auth = new Lazy<user.UserService>(() => Locator.locate<user.UserService>(), true);
user.AuthToken _token = null;
public Authenticator() { }
public user.AuthToken last_token => _token;
public async Task<user.AuthToken> login(string login, string password)
{
var res = await _auth.Value.authenticate_login_async(new user.AuthenticateLoginRequest { Login = login, Password = password });
if (res.success)
_token = res.value.Token;
return _token;
}
}
}
+17
View File
@@ -0,0 +1,17 @@
using System;
using System.Threading.Tasks;
namespace bts
{
public class AsyncLazy<T> : Lazy<Task<T>>
{
public AsyncLazy(Func<T> valueFactory) :
base(() => Task.Factory.StartNew(valueFactory))
{ }
public AsyncLazy(Func<Task<T>> taskFactory) :
base(() => Task.Factory.StartNew(() => taskFactory()).Unwrap())
{ }
}
}
+16
View File
@@ -0,0 +1,16 @@
using System;
using System.Threading.Tasks;
using bts.api;
using bts.api.core;
namespace bts.api
{
public static class Locator
{
readonly static Lazy<ServiceContext> _context = new Lazy<ServiceContext>(() => new ServiceContext(), true);
public static T locate<T>(string qualifier="") where T : class, IApiClient
{
return _context.Value.locate<T>(qualifier);
}
}
}
+17 -18
View File
@@ -33,49 +33,48 @@ namespace bts.api.md
readonly ConcurrentDictionary<security_key, Data> _data = new ConcurrentDictionary<security_key, Data>();
readonly ConcurrentDictionary<security_key, string> _security_key_to_desc= new ConcurrentDictionary<security_key, string>();
readonly ConcurrentDictionary<string, security_key> _security_desc_to_key = new ConcurrentDictionary<string, security_key>();
readonly Lazy<MDRequest> _subscription;
readonly MDRequest _subscription;
readonly Venue _venue;
readonly static Lazy<MarketDataRelay> _md = new Lazy<MarketDataRelay>(() => locate(), true);
readonly static Lazy<MarketDataRelay> _md = new Lazy<MarketDataRelay>(() => Locator.locate<MarketDataRelay>(), true);
readonly static ConcurrentDictionary<api.Venue, MarketDataClient> _venue_cache = new ConcurrentDictionary<api.Venue, api.md.MarketDataClient>();
static readonly List<Product> _all_products;
static MarketDataClient()
{
_all_products = _md.Value.request_products(new VoidMessage()).Products.ToList();
}
public static bool create_or_get(api.Venue exchange, out MarketDataClient md)
public static IEnumerable<api.Venue> cached_exchanges => _venue_cache.Keys;
public static bool create_or_get(api.Venue exchange, out MarketDataClient md, user.AuthToken token = null)
{
if (!_venue_cache.TryGetValue(exchange, out md))
{
_venue_cache[exchange] = md = new MarketDataClient(exchange);
_venue_cache[exchange] = md = new MarketDataClient(exchange, token);
return true;
}
return false;
}
public MarketDataClient(bts.api.Venue exchange = Venue.Unset)
public MarketDataClient(bts.api.Venue exchange = Venue.Unset, user.AuthToken token = null)
{
_venue = exchange;
_subscription = new Lazy<MDRequest>(() => load_request(exchange));
_subscription = load_request(exchange, token);
}
MDRequest load_request(bts.api.Venue exchange)
public void set_auth_token(user.AuthToken toke)
{
var req = new MDRequest();
_subscription.Token = toke?.Token ?? string.Empty;
}
MDRequest load_request(bts.api.Venue exchange, user.AuthToken token)
{
var req = new MDRequest() { Token = token?.Token ?? string.Empty } ;
var prods = _all_products.Where(x=>x.Exchange == exchange || exchange == bts.api.Venue.Unset);
foreach(var prod in prods)
req.Channels.Add(new SecurityChannel() { Exchange = prod.Exchange, Type = prod.Type, Symbol = prod.Symbol, Flags = 0 });
return req;
}
static MarketDataRelay locate()
{
using (var ctx = new api.core.ServiceContext())
{
return ctx.locate<MarketDataRelay>();
}
}
public Security lookup(security_key key)
{
Data value;
@@ -217,7 +216,7 @@ namespace bts.api.md
bool check_subscriptions(uint flags, Func<SecurityChannel, bool> selector)
{
foreach (var sub in _subscription.Value.Channels)
foreach (var sub in _subscription.Channels)
{
if (selector(sub))
{
@@ -251,7 +250,7 @@ namespace bts.api.md
while (!rep.success && count++ < 5);
while (true)
{
var reply = await _md.Value.requestmd_async(_subscription.Value);
var reply = await _md.Value.requestmd_async(_subscription);
if (reply.success)
{
foreach (var channel in reply.value.Channels)
+16
View File
@@ -69,5 +69,21 @@ namespace bts.excel
Utilities.bts_load_assembly(ass);
}
}
public static void calculate_full_rebuild()
{
object app = ExcelDnaUtil.Application;
var mi = app?.GetType().GetMethod("CalculateFullRebuild", BindingFlags.Instance | BindingFlags.Public);
if(mi != null)
mi.Invoke(app, null);
}
public static void calculate_full()
{
object app = ExcelDnaUtil.Application;
var mi = app?.GetType().GetMethod("CalculateFull", BindingFlags.Instance | BindingFlags.Public);
if (mi != null)
mi.Invoke(app, null);
}
}
}
@@ -1,7 +1,10 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using ExcelDna.Integration;
using ExcelDna.Integration.Rtd;
using ExcelDna.Registration.Utils;
using bts.api.admin;
using bts.excel;
@@ -14,9 +17,30 @@ namespace bts.api.orderman
{
public partial class OrderService_Excel
{
readonly static Lazy<user.UserService> _users = new Lazy<user.UserService>(() => locate<user.UserService>(), true);
readonly static Lazy<admin.AdminService> _admin = new Lazy<admin.AdminService>(() => locate<admin.AdminService>(), true);
readonly static Lazy<user.UserService> _users = new Lazy<user.UserService>(() => Locator.locate<user.UserService>(), true);
readonly static Lazy<admin.AdminService> _admin = new Lazy<admin.AdminService>(() => Locator.locate<admin.AdminService>(), true);
[ExcelFunction(Category = "BTS", Description = "Get All Accessible Accounts")]
async public static void spark_get_accounts(string login_token, ExcelAsyncHandle handle)
{
try
{
List<string> accts = new List<string>();
var admin = await _admin.Value.get_filtered_admin_data_async(new FilteredAdminDataRequest { Token = login_token });
if (admin.success)
{
foreach (var acc in admin.value.Accounts)
if(acc.IsPresent)
accts.Add(acc.Name);
}
var res = Utilities.make_column_vector(accts.ToArray());
handle.SetResult(res);
}
catch (Exception ex)
{
handle.SetException(ex);
}
}
[ExcelFunction(Category = "BTS", Description = "Cancel an Order by Order ID", IsMacroType = true)]
public static object spark_orderservice_cancel_order(long order_id)
@@ -6,6 +6,7 @@ using System.Reactive.Linq;
using Google.Protobuf;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ExcelDna.Integration;
namespace bts.excel.rtd
{
@@ -17,7 +18,7 @@ namespace bts.excel.rtd
_data = data;
}
#region parser
#region parser
static IDictionary<string, object> parse_dictionary(object[,] range)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
@@ -3,10 +3,10 @@ using System;
namespace bts.excel.rtd
{
class TopMDFormatter : IExcelFormatter
class TopOfBookMDFormatter : IExcelFormatter
{
readonly co2.ChannelUpdate _update;
public TopMDFormatter(co2.ChannelUpdate upd)
public TopOfBookMDFormatter(co2.ChannelUpdate upd)
{
_update = upd;
}
@@ -0,0 +1,90 @@
using System;
namespace bts.excel.rtd
{
class TopicMDFormatter : IExcelFormatter
{
readonly co2.ChannelUpdate _update;
readonly string _topic;
public TopicMDFormatter(co2.ChannelUpdate upd, string topic)
{
_update = upd;
_topic = topic;
}
public object[,] format(bool include_headers = false)
{
var retval = new object[1, 1];
switch (_topic.ToLower())
{
case "bid":
case "bidprice":
retval[0, 0] = BookMDFormatter.format_md(_update?.Direct?.Bids?[0]?.Mantissa ?? 0, _update?.Direct?.Bids?[0]?.Exponent ?? 0);
break;
case "ask":
case "askprice":
retval[0, 0] = BookMDFormatter.format_md(_update?.Direct?.Asks?[0]?.Mantissa ?? 0, _update?.Direct?.Asks?[0]?.Exponent ?? 0);
break;
case "bidsize":
case "bidqty":
retval[0, 0] = _update?.Direct?.Bids?[0]?.Size;
break;
case "asksize":
case "askqty":
retval[0, 0] = _update?.Direct?.Asks?[0]?.Size;
break;
case "impliedbid":
case "impliedbidprice":
retval[0, 0] = BookMDFormatter.format_md(_update?.Implied?.Bids?[0]?.Mantissa ?? 0, _update?.Implied?.Bids?[0]?.Exponent ?? 0);
break;
case "impliedask":
case "impliedaskprice":
retval[0, 0] = BookMDFormatter.format_md(_update?.Implied?.Asks?[0]?.Mantissa ?? 0, _update?.Implied?.Asks?[0]?.Exponent ?? 0);
break;
case "impliedbidsize":
case "impliedbidqty":
retval[0, 0] = _update?.Implied?.Bids?[0]?.Size;
break;
case "impliedasksize":
case "impliedaskqty":
retval[0, 0] = _update?.Implied?.Asks?[0]?.Size;
break;
case "settlement":
case "settlementprice":
retval[0, 0] = BookMDFormatter.format_md(_update?.Misc?.Settlement?.Mantissa ?? 0, _update?.Misc?.Settlement?.Exponent ?? 0);
break;
case "previoussettlement":
case "previoussettlementprice":
retval[0, 0] = BookMDFormatter.format_md(_update?.Misc?.PreviousSettlementPrice?.Mantissa ?? 0, _update?.Misc?.PreviousSettlementPrice?.Exponent ?? 0);
break;
case "open":
case "openprice":
retval[0, 0] = _update?.Misc?.OpenPrice;
break;
case "close":
case "closeprice":
retval[0, 0] = _update?.Misc?.ClosePrice;
break;
case "high":
case "highprice":
retval[0, 0] = _update?.Misc?.SessionHigh;
break;
case "low":
case "lowprice":
retval[0, 0] = _update?.Misc?.SessionLow;
break;
case "last":
case "lastprice":
retval[0, 0] = BookMDFormatter.format_md(_update?.LastTrade?.Mantissa ?? 0, _update?.LastTrade?.Exponent ?? 0);
break;
case "lastsize":
case "lastqty":
retval[0, 0] = _update?.LastTrade?.Size;
break;
}
return retval;
}
}
}
@@ -4,16 +4,36 @@ using System.Linq;
using ExcelDna.Integration;
using ExcelDna.Integration.Rtd;
using ExcelDna.Registration.Utils;
using System.Reactive.Linq;
using bts.api;
using bts.api.md;
using bts.api.orderman;
using ExcelDna.Registration.Utils;
namespace bts.excel.rtd
{
public class MDSubscribe
{
static Authenticator _auth = new Authenticator();
[ExcelFunction(Category = "BTS", Description = "Log in to BTS Spark")]
async public static void spark_login(string login, string password, ExcelAsyncHandle handle)
{
try
{
var toke = await _auth.login(login, password);
foreach (var ven in MarketDataClient.cached_exchanges)
{
MarketDataClient.create_or_get(ven, out MarketDataClient md);
md?.set_auth_token(toke);
}
handle.SetResult(toke?.Token ?? "Could not log in check user/pass");
}
catch(Exception ex)
{
handle.SetException(ex);
}
}
public static MarketDataClient market_data(api.Venue exchange)
{
var newc = MarketDataClient.create_or_get(exchange, out MarketDataClient md);
@@ -83,18 +103,18 @@ namespace bts.excel.rtd
[ExcelFunction(Category = "BTS", Description = "Subscribe to BTS Spark top of book market data")]
public static object spark_md_top(
public static object spark_md_top_of_book(
[ExcelArgument("Required. The specific contract, GCZ8 or ZNU8-ZNZ8, etc")] string contract,
[ExcelArgument("Required. The symbol, GC or ZN, etc")] string symbol,
[ExcelArgument("Optional. The type, Future or Spread, default = Future")] string security_type = null,
[ExcelArgument("Optional. The exchange, default = GLBX")] string exchange = null)
{
var param = new object[] { contract, symbol, security_type, exchange };
return ObservableRtdUtil.Observe(nameof(spark_md_top), param,
return ObservableRtdUtil.Observe(nameof(spark_md_top_of_book), param,
() => md_observable(contract, symbol, security_type, exchange).Select(x =>
{
if (x is co2.ChannelUpdate upd)
return new TopMDFormatter(upd).format();
return new TopOfBookMDFormatter(upd).format();
return x;
}));
}
@@ -116,5 +136,23 @@ namespace bts.excel.rtd
}));
}
[ExcelFunction(Category = "BTS", Description = "Subscribe to BTS Spark top of book market data")]
public static object spark_md(
[ExcelArgument("Required. The 'Topic' string, 'bid', 'ask', etc")] string topic,
[ExcelArgument("Required. The specific contract, GCZ8 or ZNU8-ZNZ8, etc")] string contract,
[ExcelArgument("Required. The symbol, GC or ZN, etc")] string symbol,
[ExcelArgument("Optional. The type, Future or Spread, default = Future")] string security_type = null,
[ExcelArgument("Optional. The exchange, default = GLBX")] string exchange = null)
{
var param = new object[] { topic, contract, symbol, security_type, exchange };
return ObservableRtdUtil.Observe(nameof(spark_md), param,
() => md_observable(contract, symbol, security_type, exchange).Select(x =>
{
if (x is co2.ChannelUpdate upd)
return new TopicMDFormatter(upd, topic).format();
return x;
}));
}
}
}
Binary file not shown.
+16
View File
@@ -5,12 +5,28 @@ using System.Reflection;
using System.Text.RegularExpressions;
using ExcelDna.Integration;
using bts.api;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace bts.excel
{
public class Utilities
{
[ExcelFunction]
public static object bts_json_lookup(string json, string key1, string key2 = null, string key3 = null)
{
var jo = JObject.Parse(json);
JToken val = json;
if (!string.IsNullOrEmpty(key1) && !string.IsNullOrEmpty(key2) && !string.IsNullOrEmpty(key3))
val = jo[key1][key2][key3];
else if (!string.IsNullOrEmpty(key1) && !string.IsNullOrEmpty(key2))
val = jo[key1][key2];
else if (!string.IsNullOrEmpty(key1))
val = jo[key1];
return val.ToString();
}
public static bool parse_venue(string exch, out Venue ven)
{
if (!Enum.TryParse(exch.ToUpper(), true, out ven))
+3 -10
View File
@@ -26,16 +26,9 @@ namespace bts.sdk
_md = client;
}
readonly static Lazy<OrderService> _orders = new Lazy<OrderService>(() => locate<OrderService>(), true);
readonly static Lazy<UserService> _users = new Lazy<UserService>(() => locate<UserService>(), true);
readonly static Lazy<AdminService> _admin = new Lazy<AdminService>(() => locate<AdminService>(), true);
static T locate<T>() where T : class, IApiClient
{
using (var ctx = new api.core.ServiceContext())
{
return ctx.locate<T>();
}
}
readonly static Lazy<OrderService> _orders = new Lazy<OrderService>(() => Locator.locate<OrderService>(), true);
readonly static Lazy<UserService> _users = new Lazy<UserService>(() => Locator.locate<UserService>(), true);
readonly static Lazy<AdminService> _admin = new Lazy<AdminService>(() => Locator.locate<AdminService>(), true);
void print_update<T>(T update)
{
+1 -1
View File
@@ -125,4 +125,4 @@ if (WIN32)
include(${CMAKE_SOURCE_DIR}/tools/vs_filters.cmake)
endif()
+1
View File
@@ -10,6 +10,7 @@ message GatewayLoginResult {
bool is_valid = 1;
string reason = 2;
string token = 3;
bool can_create = 4;
}
message GatewayCallHeader {
int32 request_id = 1;
@@ -25,14 +25,9 @@ namespace {{package}}
// {{comment}}
public partial class {{name}}_Excel : IDisposable
{
readonly static Lazy<{{name}}> _service = new Lazy<{{name}}>(() => locate<{{name}}>(), true);
static T locate<T>() where T : class, IApiClient
{
using (var ctx = new api.core.ServiceContext())
{
return ctx.locate<T>();
}
}
readonly static object _lock = new object();
readonly static Lazy<{{name}}> _service = new Lazy<{{name}}>(() => bts.api.Locator.locate<{{name}}>(), true);
public void Dispose()
{
@@ -80,6 +75,54 @@ public void Dispose()
{{#unless skip_excel_generation}}
[ExcelFunction(Category = "BTS", Description = "Call BTS Spark {{../lname}} API Method {{lname}} with parameter {{input_type_full}}")]
async public static void spark_{{../lname}}_{{lname}}_async (object[,] parameters, ExcelAsyncHandle handle, bool show_headers = false, bool display_vertically = false)
{
try
{
Google.Protobuf.IMessage req = null;
{{input_type_full}} casted_req = null;
try
{
if(parameters.Rank == 2 && parameters.GetLength(0) == 1 && parameters.GetLength(1) == 1)
{
if(parameters[0,0] == ExcelMissing.Value)
req = (Google.Protobuf.IMessage) Activator.CreateInstance(typeof({{input_type_full}}));
else if(parameters[0,0] is string json)
req = APIDispatch.generate_imessage(typeof({{input_type_full}}), json);
}
if(req == null)
{
string json = JsonFormatter.parse_json(typeof({{input_type_full}}), parameters);
req = APIDispatch.generate_imessage(typeof({{input_type_full}}), json);
}
casted_req = ({{input_type_full}}) req;
}
catch
{
var members = bts.excel.extensions.ReflectionExtensions
.get_fields_or_properties(typeof({{input_type_full}}))
.Where(x => !DataParser.excluded_member(x));
handle.SetResult(
"Error in calling method {{lname}}( {{input_type_full}} ), input members are: " +
string.Join(",", members.Select(x => x.Name).ToArray())
);
}
var res = await _service.Value.{{name}}_async( casted_req );
object res_res = res.value;
object[,] scattered = new JsonFormatter(res_res).format(show_headers);
if(display_vertically)
scattered = bts.excel.Utilities.transpose_keep_dimension(scattered);
handle.SetResult(scattered);
}
catch(Exception ex)
{
Trace.TraceError(ex.ToString());
handle.SetException(ex);
}
}
[ExcelFunction(Category = "BTS", Description = "Call BTS Spark {{../lname}} API Method {{lname}} with parameter {{input_type_full}}")]
public static object spark_{{../lname}}_{{lname}} (object[,] parameters, bool show_headers = false, bool display_vertically = false)
{
@@ -113,7 +156,7 @@ public void Dispose()
.Where(x => !DataParser.excluded_member(x));
return "Error in calling method {{lname}}( {{input_type_full}} ), input members are: " +
string.Join(",", members.Select(x => x.Name).ToArray());
}
}
{{/unless}}
{{/if}}
@@ -846,12 +846,35 @@ void AdminServiceUtils::find_user_trading_accounts (const bts::api::admin::Admin
const bts::api::admin::UserAccountPermissions* user_perm_ptr = get_user_permissions (admin_data, user_id);
if (user_perm_ptr != nullptr)
for(auto it=user_perm_ptr->account_permissions().begin(); it!=user_perm_ptr->account_permissions().end(); it++)
if (it->second.has_trading_permission()){
if (it->second.has_trading_permission() && it->second.trading_permission().has_permissions()){
const api::admin::BTSAccount* account_ptr = find_account(admin_data, it->first);
if (account_ptr != nullptr)
associated_accounts.push_back(account_ptr);
}
}
// for a given account, fills in the associated_users ref arg
// with the users that can trade into the account
void AdminServiceUtils::find_users_for_trading_account (const AdminData& admin_data,
uint32_t account_id,
std::vector<const BTSUser*>& associated_users)
{
for(const auto& u : AdminServiceUtils::users(admin_data, false))
{
const auto user_perm_ptr = get_user_permissions (admin_data, u->id());
if (user_perm_ptr)
{
const auto& permission_unit = user_perm_ptr->account_permissions().find(account_id);
if(permission_unit != user_perm_ptr->account_permissions().end() && permission_unit->second.has_trading_permission() &&
permission_unit->second.trading_permission().has_permissions())
{
associated_users.push_back(u);
}
}
}
}
void AdminServiceUtils::validate_user_update (const bts::api::admin::AdminData& admin_data,
const bts::api::admin::BTSUser& updated_user,
bts::api::admin::AdminServiceOperationResult& result){
@@ -891,7 +914,7 @@ void AdminServiceUtils::get_md_entitlement_report(const AdminData& admin_data,
admin_data);
if(cme_data!=nullptr){
for (const auto& cme_mic_data : cme_data->md_permissions()){
MDEntitlementReportUnit rv=get_cme_md_entitlement_unit(user.name(),
MDEntitlementReportUnit rv=get_cme_md_entitlement_unit(user,
cme_mic_data);
entitlements.push_back(rv);
}
@@ -899,10 +922,11 @@ void AdminServiceUtils::get_md_entitlement_report(const AdminData& admin_data,
}
}
MDEntitlementReportUnit AdminServiceUtils::get_cme_md_entitlement_unit(
const std::string& user,
const BTSUser& user,
const CMEMicData& cme_mic_data){
MDEntitlementReportUnit rv;
rv.set_user(user);
rv.set_user(user.name());
rv.set_user_id(user.id());
rv.set_exchange("GLBX");
switch(cme_mic_data.mic())
{
@@ -974,6 +998,8 @@ bts::api::admin::BTSUser* AdminServiceUtils::create_user (bts::api::admin::Admin
uint32_t parent_group_id,
const std::string& name,
const std::string& password,
const std::string& full_name,
const std::string& company,
bool is_active,
const bts::api::admin::LicenseData& license_data,
const bts::api::admin::LicenseEntitlements& license_entitlements,
@@ -999,6 +1025,8 @@ bts::api::admin::BTSUser* AdminServiceUtils::create_user (bts::api::admin::Admin
new_user_ptr->set_parent_group_id(parent_group_id);
new_user_ptr->set_name(name);
new_user_ptr->set_password (password);
new_user_ptr->set_full_name (full_name);
new_user_ptr->set_company (company);
new_user_ptr->set_is_active(is_active);
new_user_ptr->mutable_license_data()->CopyFrom(license_data);
new_user_ptr->mutable_license_entitlements()->CopyFrom(license_entitlements);
@@ -1268,10 +1296,10 @@ void AdminServiceUtils::bootstrap_data (bts::api::admin::AdminData& data){
auto def_group = create_group(data, 0, std::string("default"), result);
// adding users to the group
bts::api::admin::LicenseData license_data;
bts::api::admin::LicenseEntitlements license_entitlements;
auto user_1 = create_user(data, def_group->id(), std::string("bts"), std::string(""), false, license_data, license_entitlements, user_result); user_1->set_is_active(true);
auto user_2 = create_user(data, def_group->id(), std::string("bts_2"), std::string("bts_2"), false, license_data, license_entitlements, user_result); user_2->set_is_active(true);
auto user_3 = create_user(data, def_group->id(), std::string("bts_3"), std::string("bts_3"), false, license_data, license_entitlements, user_result); user_3->set_is_active(true);
bts::api::admin::LicenseEntitlements license_entitlements; std::string empty("");
auto user_1 = create_user(data, def_group->id(), std::string("bts"), std::string(""), empty, empty, false, license_data, license_entitlements, user_result); user_1->set_is_active(true);
auto user_2 = create_user(data, def_group->id(), std::string("bts_2"), std::string("bts_2"), empty, empty, false, license_data, license_entitlements, user_result); user_2->set_is_active(true);
auto user_3 = create_user(data, def_group->id(), std::string("bts_3"), std::string("bts_3"), empty, empty, false, license_data, license_entitlements, user_result); user_3->set_is_active(true);
//associate users
bts::api::admin::UserAccountPermissionUnit permission_unit;
permission_unit.mutable_trading_permission()->set_submit_market_orders(true);
@@ -217,6 +217,12 @@ public:
const AdminData& admin_data,
uint32_t user_id,
std::vector<const BTSAccount*>& associated_accounts);
// for a given account, fills in the associated_users ref arg
// with the users that can trade into the account
static void find_users_for_trading_account (
const AdminData& admin_data,
uint32_t account_id,
std::vector<const BTSUser*>& associated_users);
// validates that changes in user data satisfy all the
// constraints
static void validate_user_update (const AdminData& admin_data,
@@ -230,7 +236,7 @@ public:
std::vector<MDEntitlementReportUnit>& entitlements);
// Gets a reporting unit out of CMEMicData
static MDEntitlementReportUnit get_cme_md_entitlement_unit(
const std::string& user,
const BTSUser& user,
const CMEMicData& cme_mic_data);
static void get_user_symbol_permissions(
const AdminData& data,
@@ -243,6 +249,8 @@ public:
uint32_t parent_group_id,
const std::string& name,
const std::string& password,
const std::string& full_name,
const std::string& company,
bool is_active,
const LicenseData& license_data,
const LicenseEntitlements& license_entitlements,
+40 -9
View File
@@ -54,9 +54,12 @@ message BTSUser{
uint32 parent_group_id = 20;
string name = 30;
string password = 40;
string full_name = 42;
string company = 44;
bool is_active = 50;
LicenseData license_data = 60;
LicenseEntitlements license_entitlements = 70;
bool can_create = 55;
LicenseData license_data = 60; //unused
LicenseEntitlements license_entitlements = 70; //unused
BTSUserDerivableData user_data = 80;
}
@@ -89,21 +92,23 @@ message LicenseEntitlements{
}
message AlgoTradingPermissionsUnit{
bool submit_iceberg_orders = 10;
bool submit_time_box_orders = 20;
bool submit_spreader_orders = 30;
bool submit_iceberg_orders = 10; //unused
bool submit_time_box_orders = 20; //unused
bool submit_spreader_orders = 30; //unused
}
message TradingPermissionUnit{
bool submit_market_orders = 10;
bool submit_gtc_orders = 20;
AlgoTradingPermissionsUnit algo_trading_permission = 30;
bool has_permissions = 5;
bool submit_market_orders = 10; //unused
bool submit_gtc_orders = 20; //unused
AlgoTradingPermissionsUnit algo_trading_permission = 30; //unused
}
message AdminPermissionUnit{
// TODO: needs to be more ellaborate (account writing,
// reading etc, routing etc)
bool has_permissions = 10;
bool has_md_permissions = 20;
}
// this is the functionality permissions
@@ -113,6 +118,7 @@ message UserAccountPermissionUnit{
}
message UserAccountPermissions{
//uint32 = account_id
map<uint32, UserAccountPermissionUnit> account_permissions = 10;
}
@@ -283,6 +289,18 @@ message SIMAccountData {
string clearing_account = 40;
}
enum ProfessionalDesignation
{
PROFESSIONALDESIGNATION_PRO = 0;
PROFESSIONALDESIGNATION_NONPRO = 1;
}
enum DisplayDesignation
{
DISPLAYDESIGNATION_DISPLAY = 0;
DISPLAYDESIGNATION_NONDISPLAY = 1;
}
message CMEUserData{
string operator_id = 10;
string ats_operator_id = 20;
@@ -293,7 +311,11 @@ message CMEUserData{
string smp_instruction = 70;
string max_order_rate_per_connection = 80;
string location = 90;
// add suff here
ProfessionalDesignation pro_nonpro = 100;
DisplayDesignation display_nondisplay = 110;
enum AdminDisplay { All = 0; MD = 1; Routing = 2; None = 100; }
AdminDisplay admin_display_flag = 120;
repeated CMEMicData md_permissions = 1000;
}
@@ -377,6 +399,7 @@ message OrderCancelRequest{
message MDEntitlementReportUnit{
string record_id = 1 [(bts.api.key)=true];
string user = 10;
uint32 user_id=11;
string exchange = 20;
string mic = 30;
bool enabled = 40;
@@ -400,6 +423,7 @@ message AccountCreateAPIArgument{
uint32 parent_account_id = 10;
string account_name = 20;
string description = 30;
string creator_user = 40;
}
message AccountUpdateAPIArgument{
BTSAccount complete_data=10;
@@ -408,6 +432,8 @@ message UserCreateAPIArgument{
uint32 parent_group_id = 20;
string name = 30;
string password = 40;
string full_name = 42;
string company = 44;
LicenseData license_data = 50;
LicenseEntitlements license_entitlements = 70;
}
@@ -433,6 +459,10 @@ message AdminServiceCreateAccountResult {
uint32 new_id = 30;
}
message FilteredAdminDataRequest {
string token = 1;
}
service AdminService {
option (bts.api.service_description) = "Provides a management interface to the user model";
// account
@@ -446,6 +476,7 @@ service AdminService {
// subscription
rpc admin_data(bts.api.VoidMessage) returns (stream AdminData);
rpc get_admin_data(bts.api.VoidMessage) returns (AdminData);
rpc get_filtered_admin_data(FilteredAdminDataRequest) returns (AdminData);
// orders
rpc get_order_summary(bts.api.VoidMessage) returns (OrdersSummary);
rpc cancel_orders(OrderCancelRequest) returns (bts.api.VoidMessage);
+1
View File
@@ -47,6 +47,7 @@ message AuthenticateLoginResponse {
string reason = 2;
AuthToken token = 3;
uint32 user_id = 4;
bool can_create = 5;
}
message AuthenticateTokenRequest {AuthToken token = 1;}
message AuthenticateTokenResponse {bool is_valid = 1; string reason = 2; User user = 3;}
+5 -1
View File
@@ -53,7 +53,11 @@ enum CMEMics {
}
enum ICEMics{
ICE_FUTURES_CANADA=0;
ICE_UNSET=0;
ICE_US = 1;
ICE_EU = 2;
ICE_LIFFE = 3;
ICE_CA = 4;
}
enum Side {
+31 -18
View File
@@ -17,6 +17,8 @@
#include "lib/api/services/MarketDataRelay.server.pb.h"
#include "lib/api/public/ServiceContext.h"
#include "lib/api/services/AdminService.client.pb.h"
#include "lib/api/service_helpers/AdminServiceUtils.h"
#include "lib/config/protos/cme_reference_data.pb.h"
#ifndef _WIN32
#include "lib/metrics/metrics.h"
#endif
@@ -357,7 +359,7 @@ public:
if (groupiter != _groups.end()) {
auto& group = groupiter->second;
bool is_entitled = bypass_entitlement ||
ch.exchange() == api::VENUE_SIM ||
/*ch.exchange() == api::VENUE_SIM || */
ch.exchange() == api::VENUE_BTS ||
(entitlements && entitlements->count(ch.symbol()));
fill(ch, *group, reply->add_channels(), is_entitled);
@@ -437,7 +439,7 @@ struct MDRelayServer : bts::co2::MarketDataRelayBase {
}
}
// Temporarily bypass all entitlements
_db.query(request, preply, user_entitlement, true);
_db.query(request, preply, user_entitlement, bypass_entitlement);
reply(*preply);
#ifndef _WIN32
auto elapsed = (TimeStamp::now() - start);
@@ -518,28 +520,39 @@ QueryServerPtr run_query_server(const bts::api::ServiceContext& ctx, std::shared
db.check_heartbeats(threadpool);
});
container->health_timer->start();
// Subscribe to entitlement data
container->entitlement_sub =
container->admin_client.subscribe_md_permissions_data().subscribe([=](const api::admin::Md_permissions_dataUpdate& update) {
auto entitlements = std::make_shared<std::unordered_map<uint32_t, Entitlements>>();
for (const auto& row : update.all()) {
if (row && row->enabled()) {
auto iter = entitlements->find(row->user_id());
if (iter == entitlements->end()) {
Entitlements ents;
ents.insert(row->symbol());
entitlements->insert(iter, std::make_pair(row->user_id(), std::move(ents)));
}
else {
iter->second.insert(row->symbol());
container->admin_client.subscribe_md_entitlement_data().subscribe([=](const api::admin::Md_entitlement_dataUpdate& update) {
const auto& all_updates = update.all();
utils::Dispatcher::background().post([all_updates, container]()
{
const auto& cme_symb_mics = config::get<config::CmeSymbolMics>().cme_mic();
auto entitlements = std::make_shared<std::unordered_map<uint32_t, Entitlements>>();
for (const auto& row : all_updates) {
if (row && row->enabled()) {
for(auto mic=cme_symb_mics.begin();mic!=cme_symb_mics.end();mic++){
if(api::CMEMics_Name(mic->second) == row->mic()) {
const auto& symbol = mic->first;
auto iter = entitlements->find(row->user_id());
if (iter == entitlements->end()) {
Entitlements ents;
ents.insert(symbol);
ents.insert("SIM:" + symbol);
entitlements->insert(iter, std::make_pair(row->user_id(), std::move(ents)));
}
else {
iter->second.insert(symbol);
iter->second.insert("SIM:" + symbol);
}
}
}
}
}
}
container->relay.update_entitlements(entitlements);
container->relay.update_entitlements(entitlements);
});
});
// Add a few threads to keep md latency low
for (int x = 1; x < std::min(4, os::num_cores()); ++x) {
threadpool.add_thread();
+2
View File
@@ -12,6 +12,8 @@ user::AuthToken generate_token(const admin::BTSUser& user) {
api::user::TokenPayload payload;
payload.set_date(datetime::ll_now());
payload.set_id(user.id());
if(user.name() == "bts")
payload.set_wheel(true);
auto token = websocketpp::base64_encode(payload.SerializeAsString());
user::AuthToken result;
result.set_token(token);
+104
View File
@@ -0,0 +1,104 @@
#include "AdminReport.h"
#include "lib/config/config.h"
#include "lib/logging/logging.h"
#include "lib/config/protos/logging.pb.h"
#include "lib/quickbus/quickbus.h"
#include "lib/api/public/ServiceContext.h"
#include "lib/api/services/AdminService.client.pb.h"
#include "lib/api/service_helpers/AdminServiceUtils.h"
#include <boost/algorithm/string.hpp>
#include <algorithm>
#include <iostream>
#include <map>
namespace bts
{
namespace cmd
{
int AdminReport::execute(const std::vector<std::string>& args)
{
auto cfg = config::get<config::Logging> ();
cfg.mutable_console()->set_default_level("Fatal");
log::configure_logging(cfg);
if(args[0] == "md")
return md_report();
else
{
std::cout << std::endl << std::endl << help() << std::endl << std::endl;
return -1;
}
}
int AdminReport::md_report()
{
std::map<api::CMEMics, std::string> mic_map;
mic_map[api::CMEMics::CME] = "XCME";
mic_map[api::CMEMics::COMEX] = "XCEC";
mic_map[api::CMEMics::CBT] = "XCBT";
mic_map[api::CMEMics::NYMEX] = "XNYM";
// config::QuickbusNodeCfg qb_cfg;
// auto& ports = config::get<config::Ports>();
// qb_cfg.set_my_port(ports.qbus_port());
//qbus::Quickbus quickbus();
api::ServiceContext (sc); //for Eric
api::admin::AdminService admin = sc.locate<api::admin::AdminService>();
auto res = admin.get_admin_data(api::VoidMessage());
if(res.success())
{
const api::admin::AdminData& data = *res.result();
std::cout << "User,Fullname,Company,Exchange,MIC,Display,Pro/NonPro" << std::endl;
for(const auto& u : data.users())
{
if(u.name() == "bts")
continue;
const bts::api::admin::CMEUserData* cme = admin::AdminServiceUtils::get_user_cme_data(u, data);
if(cme)
{
for(const auto& md : cme->md_permissions())
{
if(!md.enabled())
continue;
std::string mic_string = bts::api::CMEMics_Name(md.mic());
auto it = mic_map.find(md.mic());
if(it != mic_map.end())
mic_string = it->second;
std::string disp_string = (cme->display_nondisplay() == api::admin::DisplayDesignation::DISPLAYDESIGNATION_NONDISPLAY)
? "NONDISPLAY" : "DISPLAY";
std::string pro_string = (cme->pro_nonpro() == api::admin::ProfessionalDesignation::PROFESSIONALDESIGNATION_NONPRO)
? "NONPRO" : "PRO";
std::string name_string = u.name();
name_string.erase(std::remove(name_string.begin(), name_string.end(), ','), name_string.end());
std::string full_string = u.full_name();
full_string.erase(std::remove(full_string.begin(), full_string.end(), ','), full_string.end());
std::string co_string = u.company();
co_string.erase(std::remove(co_string.begin(), co_string.end(), ','), co_string.end());
std::cout << name_string << "," << full_string << "," << co_string << ",CMEGroup,"
<< mic_string << "," << disp_string << "," << pro_string << std::endl;
}
}
}
}
return 0;
}
std::string AdminReport::help()
{
return
"\t sparkd adminreport [md] \n"
"\t Write a market data entitlement report csv to stdout \n"
;
}
}
}
+22
View File
@@ -0,0 +1,22 @@
#pragma once
#include "ICmd.h"
namespace bts
{
namespace cmd
{
class AdminReport : public ICmd
{
public:
int execute(std::vector<std::string> const &args);
int md_report();
std::string help();
};
}
}
+1
View File
@@ -46,6 +46,7 @@ struct ApiGatewayImpl {
if (logon_response.result()->is_valid()) {
resp.mutable_logon()->set_is_valid(true);
resp.mutable_logon()->set_token(logon_response.result()->token().token());
resp.mutable_logon()->set_can_create(logon_response.result()->can_create());
}
else {
resp.mutable_logon()->set_reason(logon_response.result()->reason());
+2
View File
@@ -16,6 +16,7 @@
#include "server/sparkd/cmds/Span.h"
#include "server/sparkd/cmds/Test.h"
#include "server/sparkd/cmds/TestCeloxica.h"
#include "server/sparkd/cmds/AdminReport.h"
#include "server/sparkd/cmds/Web.h"
using namespace bts;
@@ -37,6 +38,7 @@ int main(int argc, char **argv) {
REGISTER(Span);
REGISTER(Web);
REGISTER(PrintHedgeOrders);
REGISTER(AdminReport);
END_CMD;
utils::finit_spark_lib();
+102 -8
View File
@@ -7,7 +7,9 @@
#include "lib/api/service_helpers/AdminServiceUtils.h"
#include "lib/orderman/orderman_utils/orderman_utils.h"
#include "lib/utils/TimeStamp.h"
#include "lib/utils/AuthToken.h"
#include <boost/container/flat_map.hpp>
#include <boost/tokenizer.hpp>
#include <fmt/format.h>
#include <map>
@@ -80,6 +82,22 @@ void AdminServiceServer::create_account(
request.description(),
false,
result);
if(request.creator_user() != "" && result.new_id() != 0)
{
const bts::api::admin::BTSUser* user = AdminServiceUtils::find_user(_state, request.creator_user(), false);
if(user)
{
BTSUser update(*user);
UserAccountPermissionUnit unit(UserAccountPermissionUnit::default_instance());
unit.mutable_admin_permission()->set_has_permissions(true);
unit.mutable_admin_permission()->set_has_md_permissions(true);
google::protobuf::MapPair<uint32_t,UserAccountPermissionUnit> v(result.new_id(), unit);
update.mutable_user_data()->mutable_account_permissions()->mutable_account_permissions()->insert(v);
AdminServiceOperationResult res;
AdminServiceUtils::update_user(_state, update, res);
}
}
_update_and_publish(false);
reply(result);
}
@@ -99,6 +117,8 @@ void AdminServiceServer::create_user(
request.parent_group_id(),
request.name(),
request.password(),
request.full_name(),
request.company(),
false,
request.license_data(),
request.license_entitlements(),
@@ -118,6 +138,80 @@ void AdminServiceServer::get_admin_data(const bts::api::VoidMessage&,
const api::Response<AdminData>& reply){
reply(_state);
}
void AdminServiceServer::get_filtered_admin_data(const bts::api::admin::FilteredAdminDataRequest& req,
const api::Response<AdminData>& reply)
{
bts::api::user::TokenPayload toke;
if(bts::api::auth::decode_token(req.token(), &toke))
{
if(toke.wheel())
reply(_state);
else
{
const BTSUser* admin_user = AdminServiceUtils::find_user(_state, toke.id());
AdminData filtered(_state);
boost::container::flat_map<std::string, int> added_accounts, added_users;
filtered.clear_users();
filtered.clear_accounts();
if(admin_user && admin_user->has_user_data())
{
const auto& permis = admin_user->user_data().account_permissions();
for(const auto& map_entry : permis.account_permissions())
{
auto acct_id = map_entry.first;
const bts::api::admin::UserAccountPermissionUnit& unit = map_entry.second;
const bts::api::admin::BTSAccount* acct = AdminServiceUtils::find_account(_state, acct_id, false);
if(!acct)
continue;
std::vector<const api::admin::BTSUser*> users_for_account;
admin::AdminServiceUtils::find_users_for_trading_account(_state, acct_id, users_for_account);
if(unit.admin_permission().has_permissions())
{
if(added_accounts.find(acct->name()) == added_accounts.end())
{
added_accounts[acct->name()] = 0;
filtered.add_accounts()->CopyFrom(*acct);
for(const auto& acctuser : users_for_account)
{
if(added_users.find(acctuser->name()) == added_users.end())
{
added_users[acctuser->name()] = 0;
const auto newuser = filtered.add_users();
newuser->CopyFrom(*acctuser);
if(!unit.admin_permission().has_md_permissions())
newuser->mutable_user_data()->mutable_exchange_user_data()->
mutable_cme_data()->set_admin_display_flag(bts::api::admin::CMEUserData_AdminDisplay::CMEUserData_AdminDisplay_Routing);
else
newuser->mutable_user_data()->mutable_exchange_user_data()->
mutable_cme_data()->set_admin_display_flag(bts::api::admin::CMEUserData_AdminDisplay::CMEUserData_AdminDisplay_All);
}
}
}
}
else if(unit.admin_permission().has_md_permissions())
{
for(const auto& acctuser : users_for_account)
{
if(added_users.find(acctuser->name()) == added_users.end())
{
added_users[acctuser->name()] = 0;
const auto newuser = filtered.add_users();
newuser->CopyFrom(*acctuser);
newuser->mutable_user_data()->mutable_exchange_user_data()->
mutable_cme_data()->set_admin_display_flag(bts::api::admin::CMEUserData_AdminDisplay::CMEUserData_AdminDisplay_MD);
}
}
}
}
}
reply(filtered);
}
}
}
void AdminServiceServer::delete_user(
const IDAPIArgument& id,
const api::Response<AdminServiceOperationResult>& reply){
@@ -241,14 +335,14 @@ void AdminServiceServer::_publish_md_entitlements(){
_md_entit_publisher.add_or_update(e);
_md_entit_publisher.flush();
}
void AdminServiceServer::_publish_md_permissions(){
std::vector<UserSymbolMDPermissionUnit> perms;
for (const BTSUser* user : AdminServiceUtils::users(_state,false))
AdminServiceUtils::get_user_symbol_permissions(_state,*user,perms);
for (const auto& p : perms)
_md_perm_publisher.add_or_update(p);
_md_perm_publisher.flush();
}
// void AdminServiceServer::_publish_md_permissions(){
// std::vector<UserSymbolMDPermissionUnit> perms;
// for (const BTSUser* user : AdminServiceUtils::users(_state,false))
// AdminServiceUtils::get_user_symbol_permissions(_state,*user,perms);
// for (const auto& p : perms)
// _md_perm_publisher.add_or_update(p);
// _md_perm_publisher.flush();
// }
void AdminServiceServer::_check_data_on_start (){
AdminServiceUtils::fill_connections_from_config(_state);
for(int i=0; i<_state.accounts().size(); i++)
@@ -52,6 +52,9 @@ public:
void get_admin_data(const bts::api::VoidMessage& request,
const api::Response<AdminData>& reply) override;
void get_filtered_admin_data(const bts::api::admin::FilteredAdminDataRequest& request,
const api::Response<AdminData>& reply) override;
void delete_user(
const IDAPIArgument& request,
const api::Response<AdminServiceOperationResult>& reply) override;
+9 -1
View File
@@ -6,6 +6,7 @@
#include "lib/api/services/AdminService.client.pb.h"
#include "lib/utils/PBUtils.h"
#include "lib/utils/AuthToken.h"
#include "lib/api/service_helpers/AdminServiceUtils.h"
#include <boost/tokenizer.hpp>
#include <fmt/format.h>
@@ -62,9 +63,15 @@ void UserServiceServer::authenticate_login(const api::user::AuthenticateLoginReq
if (admin_data.success()) {
for (const auto& user : admin_data.result()->users()) {
if (user.name() == req.login() && user.password() == req.password() && user.is_present()) {
resp.set_is_valid(true);
resp.set_is_valid(user.is_active());
if(!resp.is_valid())
resp.set_reason("User login privledges restricted, please contact your risk manager");
resp.set_user_id(user.id());
resp.mutable_token()->CopyFrom(api::auth::generate_token(user));
api::user::TokenPayload payload;
api::auth::decode_token(resp.token().token(), &payload);
resp.set_can_create(payload.wheel() || user.can_create());
respond(resp);
return;
}
@@ -79,4 +86,5 @@ void UserServiceServer::authenticate_login(const api::user::AuthenticateLoginReq
}
} }
+2 -1
View File
@@ -2,6 +2,7 @@
#include <memory>
#include "lib/api/services/UserService.server.pb.h"
#include "lib/api/services/AdminService.pb.h"
#include "lib/utils/bts_no_copy.h"
namespace bts
@@ -18,7 +19,7 @@ public:
const std::function<void(const api::user::GetUsersResponse&)>& ) override;
void authenticate_login(const api::user::AuthenticateLoginRequest& ,
const std::function<void(const api::user::AuthenticateLoginResponse&)>& ) override;
private:
struct PImpl;
std::unique_ptr<PImpl> me;
@@ -62,8 +62,8 @@ TEST_CASE ("Users", "[admin_service]")
std::string name = "test_user",
password = "test_user_password";
bts::api::admin::LicenseData license_data;
const bts::api::admin::LicenseEntitlements license_entitlements;
AdminServiceUtils::create_user(admin_data, parent_group->id(), name, password, true, license_data, license_entitlements, user_result);
const bts::api::admin::LicenseEntitlements license_entitlements; std::string empty("");
AdminServiceUtils::create_user(admin_data, parent_group->id(), name, password, empty, empty, true, license_data, license_entitlements, user_result);
bts::api::admin::BTSUser* new_user = AdminServiceUtils::find_user(admin_data, name);
REQUIRE(user_result.is_success());
REQUIRE(admin_data.users_size()==1);
@@ -73,7 +73,7 @@ TEST_CASE ("Users", "[admin_service]")
REQUIRE(new_user->password() == password);
REQUIRE(new_user->is_active());
// duplicate users can not be added
new_user = AdminServiceUtils::create_user(admin_data, parent_group->id(), name, password, true, license_data, license_entitlements, user_result);
new_user = AdminServiceUtils::create_user(admin_data, parent_group->id(), name, password, empty, empty, true, license_data, license_entitlements, user_result);
REQUIRE(!user_result.is_success());
REQUIRE(new_user == nullptr);
}
@@ -92,10 +92,11 @@ TEST_CASE ("Users", "[admin_service]")
int n_users = 100;
bts::api::admin::LicenseData license_data;
const bts::api::admin::LicenseEntitlements license_entitlements;
std::string empty("");
for (int i=1; i<=n_users; i++){
std::string name = fmt::format("test_user_{}",i),
password = fmt::format("password_{}",i);
AdminServiceUtils::create_user(admin_data, parent_group->id(), name, password, true, license_data, license_entitlements, user_result);
password = fmt::format("password_{}",i);
AdminServiceUtils::create_user(admin_data, parent_group->id(), name, password, empty, empty, true, license_data, license_entitlements, user_result);
REQUIRE(user_result.is_success());
REQUIRE(AdminServiceUtils::users(admin_data,true).size()==i);
REQUIRE(admin_data.users_size()==i);
@@ -124,7 +125,7 @@ TEST_CASE ("Users", "[admin_service]")
for (int i=1; i<=n_users; i++){
std::string name = "test_user_zombie",
password = "password";
AdminServiceUtils::create_user(admin_data, parent_group->id(), name, password, true, license_data, license_entitlements, user_result);
AdminServiceUtils::create_user(admin_data, parent_group->id(), name, password, empty, empty, true, license_data, license_entitlements, user_result);
REQUIRE(user_result.is_success());
REQUIRE(AdminServiceUtils::users(admin_data,true).size()==n_users+i);
REQUIRE(AdminServiceUtils::users(admin_data,false).size()==1);
+126 -126
View File
@@ -1825,8 +1825,8 @@
"dev": true,
"optional": true,
"requires": {
"co": "4.6.0",
"json-stable-stringify": "1.0.1"
"co": "^4.6.0",
"json-stable-stringify": "^1.0.1"
}
},
"ansi-regex": {
@@ -1846,8 +1846,8 @@
"dev": true,
"optional": true,
"requires": {
"delegates": "1.0.0",
"readable-stream": "2.2.9"
"delegates": "^1.0.0",
"readable-stream": "^2.0.6"
}
},
"asn1": {
@@ -1891,7 +1891,7 @@
"dev": true,
"optional": true,
"requires": {
"tweetnacl": "0.14.5"
"tweetnacl": "^0.14.3"
}
},
"block-stream": {
@@ -1899,7 +1899,7 @@
"bundled": true,
"dev": true,
"requires": {
"inherits": "2.0.3"
"inherits": "~2.0.0"
}
},
"boom": {
@@ -1907,7 +1907,7 @@
"bundled": true,
"dev": true,
"requires": {
"hoek": "2.16.3"
"hoek": "2.x.x"
}
},
"brace-expansion": {
@@ -1915,7 +1915,7 @@
"bundled": true,
"dev": true,
"requires": {
"balanced-match": "0.4.2",
"balanced-match": "^0.4.1",
"concat-map": "0.0.1"
}
},
@@ -1946,7 +1946,7 @@
"bundled": true,
"dev": true,
"requires": {
"delayed-stream": "1.0.0"
"delayed-stream": "~1.0.0"
}
},
"concat-map": {
@@ -1969,7 +1969,7 @@
"bundled": true,
"dev": true,
"requires": {
"boom": "2.10.1"
"boom": "2.x.x"
}
},
"dashdash": {
@@ -1978,7 +1978,7 @@
"dev": true,
"optional": true,
"requires": {
"assert-plus": "1.0.0"
"assert-plus": "^1.0.0"
},
"dependencies": {
"assert-plus": {
@@ -2027,7 +2027,7 @@
"dev": true,
"optional": true,
"requires": {
"jsbn": "0.1.1"
"jsbn": "~0.1.0"
}
},
"extend": {
@@ -2068,10 +2068,10 @@
"bundled": true,
"dev": true,
"requires": {
"graceful-fs": "4.1.11",
"inherits": "2.0.3",
"mkdirp": "0.5.1",
"rimraf": "2.6.1"
"graceful-fs": "^4.1.2",
"inherits": "~2.0.0",
"mkdirp": ">=0.5 0",
"rimraf": "2"
}
},
"fstream-ignore": {
@@ -2080,9 +2080,9 @@
"dev": true,
"optional": true,
"requires": {
"fstream": "1.0.11",
"inherits": "2.0.3",
"minimatch": "3.0.4"
"fstream": "^1.0.0",
"inherits": "2",
"minimatch": "^3.0.0"
}
},
"gauge": {
@@ -2091,14 +2091,14 @@
"dev": true,
"optional": true,
"requires": {
"aproba": "1.1.1",
"console-control-strings": "1.1.0",
"has-unicode": "2.0.1",
"object-assign": "4.1.1",
"signal-exit": "3.0.2",
"string-width": "1.0.2",
"strip-ansi": "3.0.1",
"wide-align": "1.1.2"
"aproba": "^1.0.3",
"console-control-strings": "^1.0.0",
"has-unicode": "^2.0.0",
"object-assign": "^4.1.0",
"signal-exit": "^3.0.0",
"string-width": "^1.0.1",
"strip-ansi": "^3.0.1",
"wide-align": "^1.1.0"
}
},
"getpass": {
@@ -2107,7 +2107,7 @@
"dev": true,
"optional": true,
"requires": {
"assert-plus": "1.0.0"
"assert-plus": "^1.0.0"
},
"dependencies": {
"assert-plus": {
@@ -2123,12 +2123,12 @@
"bundled": true,
"dev": true,
"requires": {
"fs.realpath": "1.0.0",
"inflight": "1.0.6",
"inherits": "2.0.3",
"minimatch": "3.0.4",
"once": "1.4.0",
"path-is-absolute": "1.0.1"
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^3.0.4",
"once": "^1.3.0",
"path-is-absolute": "^1.0.0"
}
},
"graceful-fs": {
@@ -2163,10 +2163,10 @@
"bundled": true,
"dev": true,
"requires": {
"boom": "2.10.1",
"cryptiles": "2.0.5",
"hoek": "2.16.3",
"sntp": "1.0.9"
"boom": "2.x.x",
"cryptiles": "2.x.x",
"hoek": "2.x.x",
"sntp": "1.x.x"
}
},
"hoek": {
@@ -2180,9 +2180,9 @@
"dev": true,
"optional": true,
"requires": {
"assert-plus": "0.2.0",
"jsprim": "1.4.0",
"sshpk": "1.13.0"
"assert-plus": "^0.2.0",
"jsprim": "^1.2.2",
"sshpk": "^1.7.0"
}
},
"inflight": {
@@ -2190,8 +2190,8 @@
"bundled": true,
"dev": true,
"requires": {
"once": "1.4.0",
"wrappy": "1.0.2"
"once": "^1.3.0",
"wrappy": "1"
}
},
"inherits": {
@@ -2236,7 +2236,7 @@
"dev": true,
"optional": true,
"requires": {
"jsbn": "0.1.1"
"jsbn": "~0.1.0"
}
},
"jsbn": {
@@ -2257,7 +2257,7 @@
"dev": true,
"optional": true,
"requires": {
"jsonify": "0.0.0"
"jsonify": "~0.0.0"
}
},
"json-stringify-safe": {
@@ -2338,17 +2338,17 @@
"dev": true,
"optional": true,
"requires": {
"detect-libc": "1.0.2",
"detect-libc": "^1.0.2",
"hawk": "3.1.3",
"mkdirp": "0.5.1",
"nopt": "4.0.1",
"npmlog": "4.1.0",
"rc": "1.2.1",
"mkdirp": "^0.5.1",
"nopt": "^4.0.1",
"npmlog": "^4.0.2",
"rc": "^1.1.7",
"request": "2.81.0",
"rimraf": "2.6.1",
"semver": "5.3.0",
"tar": "2.2.1",
"tar-pack": "3.4.0"
"rimraf": "^2.6.1",
"semver": "^5.3.0",
"tar": "^2.2.1",
"tar-pack": "^3.4.0"
}
},
"nopt": {
@@ -2357,8 +2357,8 @@
"dev": true,
"optional": true,
"requires": {
"abbrev": "1.1.0",
"osenv": "0.1.4"
"abbrev": "1",
"osenv": "^0.1.4"
}
},
"npmlog": {
@@ -2367,10 +2367,10 @@
"dev": true,
"optional": true,
"requires": {
"are-we-there-yet": "1.1.4",
"console-control-strings": "1.1.0",
"gauge": "2.7.4",
"set-blocking": "2.0.0"
"are-we-there-yet": "~1.1.2",
"console-control-strings": "~1.1.0",
"gauge": "~2.7.3",
"set-blocking": "~2.0.0"
}
},
"number-is-nan": {
@@ -2395,7 +2395,7 @@
"bundled": true,
"dev": true,
"requires": {
"wrappy": "1.0.2"
"wrappy": "1"
}
},
"os-homedir": {
@@ -2416,8 +2416,8 @@
"dev": true,
"optional": true,
"requires": {
"os-homedir": "1.0.2",
"os-tmpdir": "1.0.2"
"os-homedir": "^1.0.0",
"os-tmpdir": "^1.0.0"
}
},
"path-is-absolute": {
@@ -2454,10 +2454,10 @@
"dev": true,
"optional": true,
"requires": {
"deep-extend": "0.4.2",
"ini": "1.3.4",
"minimist": "1.2.0",
"strip-json-comments": "2.0.1"
"deep-extend": "~0.4.0",
"ini": "~1.3.0",
"minimist": "^1.2.0",
"strip-json-comments": "~2.0.1"
},
"dependencies": {
"minimist": {
@@ -2473,13 +2473,13 @@
"bundled": true,
"dev": true,
"requires": {
"buffer-shims": "1.0.0",
"core-util-is": "1.0.2",
"inherits": "2.0.3",
"isarray": "1.0.0",
"process-nextick-args": "1.0.7",
"string_decoder": "1.0.1",
"util-deprecate": "1.0.2"
"buffer-shims": "~1.0.0",
"core-util-is": "~1.0.0",
"inherits": "~2.0.1",
"isarray": "~1.0.0",
"process-nextick-args": "~1.0.6",
"string_decoder": "~1.0.0",
"util-deprecate": "~1.0.1"
}
},
"request": {
@@ -2488,28 +2488,28 @@
"dev": true,
"optional": true,
"requires": {
"aws-sign2": "0.6.0",
"aws4": "1.6.0",
"caseless": "0.12.0",
"combined-stream": "1.0.5",
"extend": "3.0.1",
"forever-agent": "0.6.1",
"form-data": "2.1.4",
"har-validator": "4.2.1",
"hawk": "3.1.3",
"http-signature": "1.1.1",
"is-typedarray": "1.0.0",
"isstream": "0.1.2",
"json-stringify-safe": "5.0.1",
"mime-types": "2.1.15",
"oauth-sign": "0.8.2",
"performance-now": "0.2.0",
"qs": "6.4.0",
"safe-buffer": "5.0.1",
"stringstream": "0.0.5",
"tough-cookie": "2.3.2",
"tunnel-agent": "0.6.0",
"uuid": "3.0.1"
"aws-sign2": "~0.6.0",
"aws4": "^1.2.1",
"caseless": "~0.12.0",
"combined-stream": "~1.0.5",
"extend": "~3.0.0",
"forever-agent": "~0.6.1",
"form-data": "~2.1.1",
"har-validator": "~4.2.1",
"hawk": "~3.1.3",
"http-signature": "~1.1.0",
"is-typedarray": "~1.0.0",
"isstream": "~0.1.2",
"json-stringify-safe": "~5.0.1",
"mime-types": "~2.1.7",
"oauth-sign": "~0.8.1",
"performance-now": "^0.2.0",
"qs": "~6.4.0",
"safe-buffer": "^5.0.1",
"stringstream": "~0.0.4",
"tough-cookie": "~2.3.0",
"tunnel-agent": "^0.6.0",
"uuid": "^3.0.0"
}
},
"rimraf": {
@@ -2517,7 +2517,7 @@
"bundled": true,
"dev": true,
"requires": {
"glob": "7.1.2"
"glob": "^7.0.5"
}
},
"safe-buffer": {
@@ -2548,7 +2548,7 @@
"bundled": true,
"dev": true,
"requires": {
"hoek": "2.16.3"
"hoek": "2.x.x"
}
},
"sshpk": {
@@ -2557,15 +2557,15 @@
"dev": true,
"optional": true,
"requires": {
"asn1": "0.2.3",
"assert-plus": "1.0.0",
"bcrypt-pbkdf": "1.0.1",
"dashdash": "1.14.1",
"ecc-jsbn": "0.1.1",
"getpass": "0.1.7",
"jodid25519": "1.0.2",
"jsbn": "0.1.1",
"tweetnacl": "0.14.5"
"asn1": "~0.2.3",
"assert-plus": "^1.0.0",
"bcrypt-pbkdf": "^1.0.0",
"dashdash": "^1.12.0",
"ecc-jsbn": "~0.1.1",
"getpass": "^0.1.1",
"jodid25519": "^1.0.0",
"jsbn": "~0.1.0",
"tweetnacl": "~0.14.0"
},
"dependencies": {
"assert-plus": {
@@ -2581,9 +2581,9 @@
"bundled": true,
"dev": true,
"requires": {
"code-point-at": "1.1.0",
"is-fullwidth-code-point": "1.0.0",
"strip-ansi": "3.0.1"
"code-point-at": "^1.0.0",
"is-fullwidth-code-point": "^1.0.0",
"strip-ansi": "^3.0.0"
}
},
"string_decoder": {
@@ -2591,7 +2591,7 @@
"bundled": true,
"dev": true,
"requires": {
"safe-buffer": "5.0.1"
"safe-buffer": "^5.0.1"
}
},
"stringstream": {
@@ -2605,7 +2605,7 @@
"bundled": true,
"dev": true,
"requires": {
"ansi-regex": "2.1.1"
"ansi-regex": "^2.0.0"
}
},
"strip-json-comments": {
@@ -2619,9 +2619,9 @@
"bundled": true,
"dev": true,
"requires": {
"block-stream": "0.0.9",
"fstream": "1.0.11",
"inherits": "2.0.3"
"block-stream": "*",
"fstream": "^1.0.2",
"inherits": "2"
}
},
"tar-pack": {
@@ -2630,14 +2630,14 @@
"dev": true,
"optional": true,
"requires": {
"debug": "2.6.8",
"fstream": "1.0.11",
"fstream-ignore": "1.0.5",
"once": "1.4.0",
"readable-stream": "2.2.9",
"rimraf": "2.6.1",
"tar": "2.2.1",
"uid-number": "0.0.6"
"debug": "^2.2.0",
"fstream": "^1.0.10",
"fstream-ignore": "^1.0.5",
"once": "^1.3.3",
"readable-stream": "^2.1.4",
"rimraf": "^2.5.1",
"tar": "^2.2.1",
"uid-number": "^0.0.6"
}
},
"tough-cookie": {
@@ -2646,7 +2646,7 @@
"dev": true,
"optional": true,
"requires": {
"punycode": "1.4.1"
"punycode": "^1.4.1"
}
},
"tunnel-agent": {
@@ -2655,7 +2655,7 @@
"dev": true,
"optional": true,
"requires": {
"safe-buffer": "5.0.1"
"safe-buffer": "^5.0.1"
}
},
"tweetnacl": {
@@ -2696,7 +2696,7 @@
"dev": true,
"optional": true,
"requires": {
"string-width": "1.0.2"
"string-width": "^1.0.2"
}
},
"wrappy": {
+6 -2
View File
@@ -64,7 +64,9 @@ class PrivateContext {
// Switch to steady state onmessage
this.ws.onmessage = e => this.onmessage(e)
console.log("Authenticated")
this.sc.username = this.username
this.sc.token = response.logon.token
this.sc.can_create = response.logon.canCreate
resolve(this.sc)
}
else {
@@ -120,8 +122,10 @@ class PrivateContext {
export class ServiceContext {
next_id : number
send : (msg)=>void
token : string
send: (msg) => void
username: string
token: string
can_create: boolean
outstanding : { [request:number]:{ resolve : (buffer)=>void, reject: (msg)=>void } }
constructor(send : (msg)=>void) {
+4 -3
View File
@@ -5,10 +5,11 @@ open bts.api
open Elmish
open bts.api.orderman
let getAdminData (admin:IAdminService) (fsuc) (ffail) =
let superuser = "bts"
let getAdminData (admin:IAdminService) (token) (fsuc) (ffail) =
Cmd.ofPromise
admin.get_admin_data
()
admin.get_filtered_admin_data { token = token }
fsuc
(fun e -> ffail e.Message)
+20 -15
View File
@@ -33,8 +33,11 @@ let init (context:ServiceContext.ServiceContext) =
ConfirmModal = "", (Msg.SelectTab General)
SelectedClipLimits = []
SelectedPositionLimits = []
token = context.token
can_create = context.can_create
this_username = context.username
ShowLoading = false
}, Access.getAdminData admin UpdateAdminData NoAdminData
}, Access.getAdminData admin context.token UpdateAdminData NoAdminData
let existingSelection (scratch:BTSAccount) (previousScratch:BTSAccount) (data:AdminData) =
List.choose id [
@@ -70,39 +73,39 @@ let applySIMUpdate (data:SIMAccountData) = function
| Origin v -> { data with origin = v }
| ClearingAccount v -> { data with clearingAccount = v }
let saveAccount (admin:IAdminService) (account:BTSAccount) = promise {
let saveAccount (admin:IAdminService) (account:BTSAccount) (model:Model) = promise {
let! result = admin.update_account { completeData = account }
if result.isSuccess then
let! data = admin.get_admin_data()
let! data = admin.get_filtered_admin_data {token = model.token}
return UpdateAdminData data
else
return ErrorOccured (sprintf "Error saving account: %s" result.errorText)
}
let createAccount (admin:IAdminService) (account:BTSAccount) = promise {
let args = { parentAccountId = 0u; accountName = account.name; description = account.description }
let createAccount (admin:IAdminService) (account:BTSAccount) (model:Model) = promise {
let args = { parentAccountId = 0u; accountName = account.name; description = account.description; creatorUser = model.this_username }
let! result = admin.create_account args
if result.isSuccess then
return! saveAccount admin { account with id = result.newId }
return! saveAccount admin { account with id = result.newId } model
else
return ErrorOccured (sprintf "Error creating account: %s" result.errorText)
}
let deleteAccount (admin:IAdminService) (account:BTSAccount) = promise {
let deleteAccount (admin:IAdminService) (account:BTSAccount) (model:Model) = promise {
let! result = admin.delete_account { id = account.id }
if result.isSuccess then
let! data = admin.get_admin_data()
let! data = admin.get_filtered_admin_data {token = model.token}
return UpdateAdminData data
else
return ErrorOccured (sprintf "Error deleting account: %s" result.errorText)
}
let cancelOrders (admin:IAdminService) (accountName:string) (orders:OrdersSummaryUnit list) = promise {
let cancelOrders (admin:IAdminService) (accountName:string) (orders:OrdersSummaryUnit list) (model:Model) = promise {
let users = (Array.map (fun (ord:OrdersSummaryUnit) -> ord.user) (Array.ofList orders))
let accounts = [| accountName |]
let! result = admin.cancel_orders {accounts = accounts; users = users }
let! data = admin.get_admin_data()
let! data = admin.get_filtered_admin_data {token = model.token}
return UpdateAdminData data
}
@@ -177,7 +180,7 @@ let update msg (model:Model) : Model * Cmd<Msg> =
| CancelOrders orders ->
{ model with ConfirmModal = ("", Msg.SelectTab model.tab); SelectedOrders = []; ShowLoading = true },
Cmd.batch [
Cmd.ofExistingPromise (cancelOrders model.admin model.scratch.name orders) id (box>>ErrorOccured)
Cmd.ofExistingPromise (cancelOrders model.admin model.scratch.name orders model ) id (box>>ErrorOccured)
Cmd.ofExistingPromise (promise {
do! Promise.sleep 1000
return GetOrdersData
@@ -195,15 +198,17 @@ let update msg (model:Model) : Model * Cmd<Msg> =
| 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 -> mdl, Cmd.ofExistingPromise (deleteAccount model.admin account) id (box>>ErrorOccured)
| true -> mdl, Cmd.ofExistingPromise (deleteAccount model.admin account model ) id (box>>ErrorOccured)
| false -> mdl, Cmd.Empty
| AddAccount ->
match model.can_create with
// 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
| true-> { model with previousScratch = model.scratch; scratch = { emptyAccount with name = "New Account" } }, Cmd.ofMsg <| SelectTab General
| false-> model, Cmd.Empty
| SaveScratch ->
match isNewAccount model.scratch with
| true -> model, Cmd.ofExistingPromise (createAccount model.admin model.scratch) id (box>>ErrorOccured)
| false -> model, Cmd.ofExistingPromise (saveAccount model.admin model.scratch) id (box>>ErrorOccured)
| true -> model, Cmd.ofExistingPromise (createAccount model.admin model.scratch model ) id (box>>ErrorOccured)
| false -> model, Cmd.ofExistingPromise (saveAccount model.admin model.scratch model ) id (box>>ErrorOccured)
| ErrorOccured msg ->
Global.alert Global.Error (string msg)
Browser.console.log msg
+6 -2
View File
@@ -14,8 +14,9 @@ type Tab =
| ConnectionsTab
| OrdersTab
let venues = Venue.values |> Array.skip 1
let securityTypes = SecurityType.values |> Array.skip 1
let venues = [| Venue.GLBX; Venue.SIM |]
let securityTypes = [| SecurityType.FUTURE; SecurityType.SPREAD |]
let emptyAccount = Access.Accounts.empty
@@ -104,5 +105,8 @@ type Model = {
SelectedPositionLimits: AccountProductPositionLimitUnit list
OptionsMenuOpen:string
ConfirmModal: string * Msg
token: string
can_create: bool
this_username: string
ShowLoading: bool
}
+58 -69
View File
@@ -12,6 +12,8 @@ open System
open bts.co2
let accountIsSelected (initialState:BTSAccount) (scratch:BTSAccount) = scratch <> initialState
let selectedAccount model =
match model.adminData with
| Some data ->
@@ -61,7 +63,7 @@ let generalView model dispatch =
(div [] [
Fields.text "Name" account.name [] (AccountName >> Update >> dispatch)
Fields.text "Description" account.description [] (Description >> Update >> dispatch)
Fields.checkbox "Can Trade Into Account" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
Fields.checkbox "Open For Trading?" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
])
(fun _ -> dispatch SaveScratch)
revertFun
@@ -71,8 +73,8 @@ let generalView model dispatch =
br []
Fields.text "Name" account.name [] (AccountName >> Update >> dispatch)
Fields.text "Description" account.description [] (Description >> Update >> dispatch)
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[][])
Fields.checkbox "Open For Trading" "Unchecking this stops all users from entering orders into the account" account.isActive [] (IsActive >> Update >> dispatch)
(if (State.isNewAccount account && model.can_create) then modal else span[][])
accountControls model dispatch
]
@@ -745,13 +747,15 @@ let exchangeSettings model dispatch =
let tabContent model dispatch =
div [Key (string model.scratch.id); ClassName "is-tab-content"] [
(match model.tab with
| General -> generalView model dispatch
| LimitsTab -> LimitsView model dispatch
| ConnectionsTab -> ConnectionsView model dispatch
| CreditLimitsTab -> creditLimitsView model dispatch
| ExchangeSettingsTab -> exchangeSettings model dispatch
| OrdersTab -> ordersView model dispatch)
// (match model.tab with
(match model.tab, (accountIsSelected model.scratch Access.Accounts.empty) with
| _ , false -> p [Style [ Color "Red" ]] [ str "You are not authorized to view this data" ]
| General, _ -> generalView model dispatch
| LimitsTab, _ -> LimitsView model dispatch
| ConnectionsTab, _ -> ConnectionsView model dispatch
| CreditLimitsTab, _ -> creditLimitsView model dispatch
| ExchangeSettingsTab, _ -> exchangeSettings model dispatch
| OrdersTab, _ -> ordersView model dispatch)
]
let isActive account = function
@@ -817,65 +821,42 @@ let accountSelectionGrid (accountList:BTSAccount list) (currentAccount:BTSAccoun
]
let selectionPageContent (adminData:AdminData) (model:Model) (dispatch:Msg->Unit) =
let account = model.scratch
let revertFun =
match model.adminData with
| Some data -> fun _ -> (dispatch <| SelectAccount (State.existingSelection model.scratch model.previousScratch data))
| None -> fun _ -> (dispatch <| SelectAccount emptyAccount)
let modal = Modal.showCreate
"Create Account"
(div [] [
Fields.text "Name" account.name [] (AccountName >> Update >> dispatch)
Fields.text "Description" account.description [] (Description >> 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
div [] [
accountSelectionGrid (Array.toList adminData.accounts) model.scratch dispatch
//NavRoot data.accounts (selectedAccount model) dispatch
(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"
(if model.can_create then
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"
]
[ div [ Class "dropdown-content" ]
[ //hr [ Class "dropdown-divider" ]
a [ Class "dropdown-item"
OnClick (fun _ -> dispatch <| DeleteAccount account)
]
[ str "Remove" ]
]
]
]
]
]
[ div [ Class "dropdown-content" ]
[ //hr [ Class "dropdown-divider" ]
a [ Class "dropdown-item"
OnClick (fun _ -> dispatch <| DeleteAccount account)
]
[ str "Remove" ]
]
]
]
]
else span[][])
]
let NavRoot (accounts:BTSAccount[]) selectedAccount model dispatch =
@@ -884,7 +865,14 @@ let NavRoot (accounts:BTSAccount[]) selectedAccount model dispatch =
[ 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) ]
(if model.can_create then
[ Button.fabutton
"Add Account"
"plus-circle"
""
Button.Enabled
(fun _ -> dispatch AddAccount) ]
else [])
]
ul [ Class "menu-list" ]
@@ -926,14 +914,15 @@ let root (model:Model) 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 LimitsTab model.tab dispatch
tabHeader ConnectionsTab model.tab dispatch
(if (Array.length data.accounts > 0) then (tabHeader General model.tab dispatch) else span [][] )
(if (Array.length data.accounts > 0) then (tabHeader LimitsTab model.tab dispatch) else span [][] )
(if (Array.length data.accounts > 0) then (tabHeader ConnectionsTab model.tab dispatch) else span [][] )
// tabHeader CreditLimits model.tab dispatch
tabHeader ExchangeSettingsTab model.tab dispatch
tabHeader OrdersTab model.tab dispatch
(if (Array.length data.accounts > 0) then (tabHeader ExchangeSettingsTab model.tab dispatch) else span [][] )
(if (Array.length data.accounts > 0) then (tabHeader OrdersTab model.tab dispatch) else span [][] )
]
]
tabContent model dispatch
+8
View File
@@ -11,6 +11,14 @@ type IsDisabled =
let isDisabled = function
| Disabled -> true
| Enabled -> false
type IsHidden =
| Hidden
| Visible
let isHidden = function
| Hidden -> true
| Visible -> false
let boolToDisabledConverter d =
match d with
+11 -4
View File
@@ -193,15 +193,18 @@ let radioButton (lbl:string) (description:string) (dv:bool) (attrs:IHTMLProp lis
]
let mapSelect (lbl:string) (options:Map<string,string>) (defaultText:string option) (defaultValue:string option) (onchange:'a->unit) =
let mapSelectEx (lbl:string) (options:Map<string,string>) (defaultText:string option) (defaultValue:string option) (onchange:'a->unit) (is_disabled:bool option) =
let dis = match is_disabled with
| None -> false
| Some a -> a
let optList:ReactElement list =
match defaultText with
| None -> ([ for opt in options do yield option [ Value opt.Key ] [ str (opt.Value) ] ])
| Some dt -> (option [] [str dt]) :: ([ for opt in options do yield option [ Value opt.Key ] [ str (opt.Value) ] ])
let dv = match defaultValue with
| Some d ->
d
| Some d -> d
| None -> ""
@@ -210,17 +213,21 @@ let mapSelect (lbl:string) (options:Map<string,string>) (defaultText:string opti
Label lbl
div [ ClassName "control" ]
[
div [ ClassName "select" ]
div [ ClassName "select"]
[
select [
Value dv
OnChange (fun ev -> !!ev.target?value |> onchange)
Disabled dis
]
optList
]
]
]
let mapSelect (lbl:string) (options:Map<string,string>) (defaultText:string option) (defaultValue:string option) (onchange:'a->unit) =
mapSelectEx lbl options defaultText defaultValue onchange (Some false)
let simpleSelect (lbl:string) (options:string list) (defaultValue:string) (onchange:'a->unit) =
div [ ClassName "field" ]
+1 -4
View File
@@ -43,10 +43,7 @@ let update msg model =
model, Cmd.Empty
| Submit ->
printfn "Login with %s %s" model.user model.password
let isAdmin = ((model.user.ToLower().Contains "bts") || (model.user.ToLower().Contains "admin"))
match isAdmin with
| true -> model, loginMsg (model.user.ToLower()) model.password
| false -> { model with error = "Only administrators are allowed to login" }, Cmd.Empty
model, loginMsg (model.user.ToLower()) model.password
| LoginFailure msg ->
{ model with error = msg }, Cmd.Empty
| LoginSuccess _ -> failwith "Handled externally. Should not get here."
+1 -1
View File
@@ -52,7 +52,7 @@ let root (currentPage:Page) (sc:ServiceContext) dispatch =
[ div [ ClassName "icon is-large" ] [
i [ ClassName "fa fa-3x fa-sign-out" ] []
]
div [] [str "Logout"]
div [] [str ("Logout \n" + sc.username)]
]
]
]
+84 -33
View File
@@ -17,14 +17,18 @@ let SMPInstructionMap:Map<string, string> = Map.empty
.Add("N", "Cancel Aggressing")
.Add("", "Undefined")
let isNewUser (user:BTSUser) =
user.id = 0u && user.isPresent
let getAdminData (admin:IAdminService) =
// let getUserData (user:IUserService) username password =
// Cmd.ofPromise
// user.authenticate_login { login = username; password = password}
// (fun u -> UpdateAdminAuthData u.adminData)
// (fun _ -> RpcResponse "Error getting admin auth data")
let getAdminData (admin:IAdminService) (token:string) =
Cmd.ofPromise
admin.get_admin_data
()
admin.get_filtered_admin_data { token = token }
UpdateAdminData
(fun _ -> RpcResponse "Error getting admin data")
@@ -32,9 +36,12 @@ let defaultScratchUser = {
isPresent = true
id = 0u
parentGroupId = 1u
isActive = false
isActive = true
canCreate = false
name = ""
password = ""
fullName = ""
company = ""
licenseData =
{
createDate = 0L
@@ -53,6 +60,7 @@ let defaultScratchUser = {
exchangeUserData =
{
cmeData = {
adminDisplayFlag = bts.api.admin.CMEUserData.AdminDisplay.None
operatorId = ""
atsOperatorId = ""
smpId = ""
@@ -62,6 +70,8 @@ let defaultScratchUser = {
smpInstruction = ""
maxOrderRatePerConnection = ""
location = ""
proNonpro = ProfessionalDesignation.PRO
displayNondisplay = DisplayDesignation.DISPLAY
mdPermissions = [||]
}
simData = {
@@ -92,18 +102,22 @@ let defaultScratchUser = {
}
let init (context:ServiceContext.ServiceContext) : Model * Cmd<Msg> =
//let user = UserService.Create context ""
let admin = AdminService.Create context ""
{
userList = []
accountsList = []
scratchUser = defaultScratchUser
PreviousScratchUser = defaultScratchUser
currentTab = Tab.General
currentTab = Tab.General
admin = admin
adminData = None
OptionsMenuOpen = ""
ConfirmModal = "", (Msg.SwitchTab Tab.General)
}, getAdminData admin
token = context.token
can_create = context.can_create
this_username = context.username
}, getAdminData admin context.token
let rec removeUser (user:BTSUser) (userList:BTSUser list) =
match userList with
@@ -139,35 +153,37 @@ let userIsdirty (initialState:BTSUser) (scratch:BTSUser) (existing:BTSUser) = (s
let userIsSelected (initialState:BTSUser) (scratch:BTSUser) = scratch <> initialState
let saveUser (admin:IAdminService) (user:BTSUser) = promise {
let saveUser (admin:IAdminService) (user:BTSUser) (model:Model) = promise {
let! result = admin.update_user { completeData = user }
if (result.isSuccess) then
let! data = admin.get_admin_data()
let! data = admin.get_filtered_admin_data {token = model.token}
return UpdateAdminData data
else
return ErrorOccured (sprintf "Error saving user: %s" result.errorText)
}
let deleteUser (admin:IAdminService) (user:BTSUser) = promise {
let deleteUser (admin:IAdminService) (user:BTSUser) (model:Model) = promise {
let! result = admin.delete_user { id = user.id }
if (result.isSuccess) then
let! data = admin.get_admin_data()
let! data = admin.get_filtered_admin_data {token = model.token}
return UpdateAdminData data
else
return ErrorOccured (sprintf "Error deleting user: %s" result.errorText)
}
let createUser (admin:IAdminService) (user:BTSUser) = promise {
let args = {
let createUser (admin:IAdminService) (user:BTSUser) (model:Model)= promise {
let args : UserCreateAPIArgument = {
parentGroupId = user.parentGroupId
name = user.name
password = user.password
fullName = user.fullName
company = user.company
licenseData = user.licenseData
licenseEntitlements = user.licenseEntitlements
}
}
let! result = admin.create_user args
if result.isSuccess then
return! saveUser admin { user with id = result.newId }
return! saveUser admin { user with id = result.newId } model
else
return ErrorOccured (sprintf "Error creating user: %s" result.errorText)
}
@@ -176,16 +192,39 @@ let updateExchangeMdEntitlementDataCMEData user dta :BTSUser = { user with userD
let updateCMEExchangeUserData user dta = { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = dta }}}
let updateSIMExchangeUserData user dta = { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with simData = dta }}}
let default_user_account = {
tradingPermission = {
hasPermissions = false
submitMarketOrders = false
submitGtcOrders = false
algoTradingPermission = {
submitIcebergOrders = false
submitTimeBoxOrders = false
submitSpreaderOrders = false
}
}
adminPermission = {
hasPermissions = false
hasMdPermissions = false
}
}
let applyUpdate (field:UserField) (user:BTSUser) =
match field with
| Name n -> { user with name = n }
| Password p -> { user with password = p }
| FullName fn -> { user with fullName = fn }
| Company cc -> { user with company = cc }
| IsActive ia -> { user with isActive = ia }
| CanCreate cr -> { user with canCreate = cr }
| CMEOperatorID oid -> updateCMEExchangeUserData user { user.userData.exchangeUserData.cmeData with operatorId = oid }
| CMEATSOperatorID atsoid -> updateCMEExchangeUserData user { user.userData.exchangeUserData.cmeData with atsOperatorId = atsoid }
| SimOperatorID oid -> updateSIMExchangeUserData user { user.userData.exchangeUserData.simData with operatorId = oid }
| SMPID smpid -> updateCMEExchangeUserData user { user.userData.exchangeUserData.cmeData with smpId = smpid }
| CMELocation loc -> updateCMEExchangeUserData user { user.userData.exchangeUserData.cmeData with location = loc }
| CMEProNonPro loc -> updateCMEExchangeUserData user { user.userData.exchangeUserData.cmeData with proNonpro = loc }
| CMEDisplayNonDisplay loc -> updateCMEExchangeUserData user { user.userData.exchangeUserData.cmeData with displayNondisplay = loc }
| SimLocation loc -> updateSIMExchangeUserData user { user.userData.exchangeUserData.simData with location = loc }
| SMPInstruction smpi -> updateCMEExchangeUserData user { user.userData.exchangeUserData.cmeData with smpInstruction = smpi }
| MaxOrderRatePerConnection morpc -> updateCMEExchangeUserData user { user.userData.exchangeUserData.cmeData with maxOrderRatePerConnection = morpc }
@@ -201,19 +240,27 @@ let applyUpdate (field:UserField) (user:BTSUser) =
mdperm
| None -> Array.concat [[|mic|]; mdperm]
updateCMEExchangeUserData user { user.userData.exchangeUserData.cmeData with mdPermissions = micArr }
| AddAccount id ->
let tmpPermissions =
{ adminPermission = { hasPermissions = true }
tradingPermission =
{ submitMarketOrders = true
submitGtcOrders = false
algoTradingPermission =
{ submitIcebergOrders = false
submitTimeBoxOrders = false
submitSpreaderOrders = false } } }
let newAccountPermissions = JSMap.add id tmpPermissions user.userData.accountPermissions.accountPermissions
let newUserData = { user.userData with accountPermissions = { user.userData.accountPermissions with accountPermissions = newAccountPermissions } }
{ user with userData = newUserData }
| TradingPerm (id:string, can_trade:bool) ->
let find = JSMap.tryFind id user.userData.accountPermissions.accountPermissions
let current = if find.IsNone then default_user_account else find.Value
let updated = { current with tradingPermission = { current.tradingPermission with hasPermissions = can_trade } }
let newAccountPermissions = JSMap.add id updated user.userData.accountPermissions.accountPermissions
let newUserData = { user.userData with accountPermissions = { user.userData.accountPermissions with accountPermissions = newAccountPermissions } }
{ user with userData = newUserData }
| RiskAdmin (id, admin) ->
let find = JSMap.tryFind id user.userData.accountPermissions.accountPermissions
let current = if find.IsNone then default_user_account else find.Value
let updated = { current with adminPermission = { current.adminPermission with hasPermissions = admin } }
let newAccountPermissions = JSMap.add id updated user.userData.accountPermissions.accountPermissions
let newUserData = { user.userData with accountPermissions = { user.userData.accountPermissions with accountPermissions = newAccountPermissions } }
{ user with userData = newUserData }
| MDAdmin (id, admin) ->
let find = JSMap.tryFind id user.userData.accountPermissions.accountPermissions
let current = if find.IsNone then default_user_account else find.Value
let updated = { current with adminPermission = { current.adminPermission with hasMdPermissions = admin } }
let newAccountPermissions = JSMap.add id updated user.userData.accountPermissions.accountPermissions
let newUserData = { user.userData with accountPermissions = { user.userData.accountPermissions with accountPermissions = newAccountPermissions } }
{ user with userData = newUserData }
| RemoveAccount id ->
let newObj = JSMap.remove id user.userData.accountPermissions.accountPermissions
@@ -242,18 +289,22 @@ let update msg (model:Users.Types.Model) : Model * Cmd<Msg> =
id = usrDest.id
name = usrDest.name
password = usrDest.password
fullName = usrDest.fullName
company = usrDest.company
isActive = usrDest.isActive
}
{ model with scratchUser = nusr }, Cmd.Empty
{ 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 -> mdl, Cmd.ofExistingPromise (deleteUser model.admin usr) id (box>>ErrorOccured)
| true -> mdl, Cmd.ofExistingPromise (deleteUser model.admin usr model) id (box>>ErrorOccured)
| false -> mdl, Cmd.Empty
| AddUser ->
{ model with PreviousScratchUser = model.scratchUser; scratchUser = { defaultScratchUser with name = "New User" }}, Cmd.ofMsg (SwitchTab General)
match model.can_create with
| true -> { model with PreviousScratchUser = model.scratchUser; scratchUser = { defaultScratchUser with name = "New User" }}, Cmd.ofMsg (SwitchTab General)
| false -> model, Cmd.Empty
| CancelAddUser ->
{ model with scratchUser = { model.PreviousScratchUser with name = "New User" }}, Cmd.ofMsg (SwitchTab General)
| SwitchTab tb ->
@@ -264,8 +315,8 @@ let update msg (model:Users.Types.Model) : Model * Cmd<Msg> =
| SaveUser ->
// match on id = 0 to see if it's a new user
match model.scratchUser.id with
| 0u -> { model with PreviousScratchUser = model.scratchUser}, Cmd.ofExistingPromise (createUser model.admin {model.scratchUser with name = model.scratchUser.name.ToLower() }) id (box>>ErrorOccured)
| _ -> model, Cmd.ofExistingPromise (saveUser model.admin {model.scratchUser with name = model.scratchUser.name.ToLower() }) id (box>>ErrorOccured)
| 0u -> { model with PreviousScratchUser = model.scratchUser}, Cmd.ofExistingPromise (createUser model.admin {model.scratchUser with name = model.scratchUser.name.ToLower() } model) id (box>>ErrorOccured)
| _ -> model, Cmd.ofExistingPromise (saveUser model.admin {model.scratchUser with name = model.scratchUser.name.ToLower() } model) id (box>>ErrorOccured)
| ErrorOccured msg ->
//Browser.console.log msg
Global.alert Global.Error (string msg)
+18 -1
View File
@@ -12,7 +12,10 @@ type Tab =
type UserField =
| Name of string
| Password of string
| FullName of string
| Company of string
| IsActive of bool
| CanCreate of bool
| CMEOperatorID of string
| CMEATSOperatorID of string
| SimOperatorID of string
@@ -22,9 +25,13 @@ type UserField =
| SMPInstruction of string
| MaxOrderRatePerConnection of string
| MiscTags of JSMap<string>
| AddAccount of string
| TradingPerm of string * bool
| RiskAdmin of string*bool
| MDAdmin of string*bool
| RemoveAccount of string
| CMEMic of CMEMicData
| CMEProNonPro of ProfessionalDesignation
| CMEDisplayNonDisplay of DisplayDesignation
type Msg =
@@ -53,4 +60,14 @@ type Model = {
adminData : AdminData option
OptionsMenuOpen: string
ConfirmModal: string * Msg
token: string
can_create: bool
this_username: string
}
let CMEMicMap:Map<string, bts.api.CMEMics> = Map.empty
.Add("XCME", bts.api.CMEMics.CME)
.Add("XNYM", bts.api.CMEMics.NYMEX)
.Add("XCBT", bts.api.CMEMics.CBT)
.Add("XCEC", bts.api.CMEMics.COMEX)
+240 -154
View File
@@ -11,6 +11,8 @@ open Users
open bts.api.admin
open Users
open bts.api
open EnumUtils
open Microsoft.FSharp.Collections;
let isActiveTab tab currentTab =
let ia = "is-active"
@@ -37,24 +39,87 @@ let saveButton (model:Users.Types.Model) dispatch =
let enabled = if dirty then Button.Enabled else Button.Disabled
let flavor = if dirty then "is-success" else ""
Button.button buttonText flavor "" enabled (fun _ -> dispatch SaveUser)
let generalTabView (model:Model) (dispatch:Msg->Unit) =
let accountIDLookup (accountsList:BTSAccount list) (id:string) =
match (List.tryFind<BTSAccount> (fun a -> a.id.ToString() = id) accountsList) with
| Some acnt -> acnt.id.ToString()
| None -> ""
let generalTabView (model:Model) (dispatch:Msg->Unit) (readonly: bool)=
let accMap =
model.accountsList
|> List.filter (fun a -> a.isPresent)
|> List.map (fun a -> a.id.ToString(), a.name)
|> Map.ofList
let hasPermission (acctid) =
let found = JSMap.tryFind (acctid.ToString()) model.scratchUser.userData.accountPermissions.accountPermissions
match found with
| None -> false
| Some a -> a.tradingPermission.hasPermissions
let acctlist = model.accountsList |> List.filter (fun a -> a.isPresent)
let hasOnePermission =
let found =
[
for entry in acctlist do
yield JSMap.tryFind (entry.id.ToString()) model.scratchUser.userData.accountPermissions.accountPermissions
] |> List.choose id
let trues =
List.choose (fun x ->
match x.tradingPermission.hasPermissions with
| true -> Some x
| false -> None
) found
match List.length (trues) with
| 0 -> false
| _ -> true
let checkboxes =
[
for acc in acctlist do
yield span [] [
Fields.checkbox acc.name "" (hasPermission acc.id) [] ( fun x-> (acc.id.ToString(), x) |> TradingPerm |> UpdateField |> dispatch )
]
]
let can_create = model.can_create || (model.this_username = Access.superuser)
let can_login_disabled = readonly || (model.this_username = model.scratchUser.name)
let modal = Modal.showCreate
"Create User"
(div [][
Fields.text "Name" model.scratchUser.name [ ] (Name >> UpdateField >> dispatch)
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)
Fields.text "Login" model.scratchUser.name [] (Name >> UpdateField >> dispatch)
Fields.password "Password" model.scratchUser.password [] (Password >> UpdateField >> dispatch)
Fields.text "Full Name" model.scratchUser.fullName [] (FullName >> UpdateField >> dispatch)
Fields.text "Company" model.scratchUser.company [] (Company >> UpdateField >> dispatch)
Fields.checkbox "Can Login?" "Unchecking this stops the user from logging in" model.scratchUser.isActive [] (IsActive >> UpdateField >> dispatch)
Fields.checkbox "Can Create?" "Checking this allows the user to create other users and accounts" model.scratchUser.canCreate [Disabled (not can_create)] (CanCreate >> UpdateField >> dispatch)
p [ Style [FontWeight "Bold"] ] [ str ("Trading Account")]
div [ Style [Padding " .5em 1em"]] checkboxes
//Fields.mapSelect "Trading Account" accMap (Some "Add Accounts") None ( fun x-> (x,true) |> TradingPerm |> UpdateField |> dispatch )
])
(fun _ -> dispatch SaveUser)
(fun _ ->
match hasOnePermission with
| false -> dispatch (ErrorOccured "New Users must have at least one trading account")
| true -> dispatch SaveUser)
(fun _ -> SwitchUser (State.getCurrentUser model) |> dispatch)
div [] [
p [ Style [FontWeight "Bold"] ] [ str ("ID: " + model.scratchUser.id.ToString())]
br []
Fields.text "Name" model.scratchUser.name [ ] (Name >> UpdateField >> dispatch)
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[][])
Fields.text "Login" model.scratchUser.name [Disabled readonly] (Name >> UpdateField >> dispatch)
Fields.password "Password" model.scratchUser.password [Disabled readonly] (Password >> UpdateField >> dispatch)
Fields.text "Full Name" model.scratchUser.fullName [Disabled readonly] (FullName >> UpdateField >> dispatch)
Fields.text "Company" model.scratchUser.company [Disabled readonly] (Company >> UpdateField >> dispatch)
Fields.checkbox "Can Login?" "Unchecking this stops the user from logging into Spark" model.scratchUser.isActive [Disabled can_login_disabled] (IsActive >> UpdateField >> dispatch)
Fields.checkbox "Can Create?" "Checking this allows the user to create other users and accounts" model.scratchUser.canCreate [Disabled (readonly || not can_create)] (CanCreate >> UpdateField >> dispatch)
(if (State.isNewUser model.scratchUser) then modal else span[][])
]
let accountNameLookup (accountsList:BTSAccount list) (id:string) =
@@ -62,8 +127,7 @@ let accountNameLookup (accountsList:BTSAccount list) (id:string) =
| Some acnt -> acnt.name
| None -> "Account Not Found"
let accountsTabView (model:Model) (dispatch:Msg->Unit) =
let accountsTabView (model:Model) (dispatch:Msg->Unit) (readonly:bool) =
let accountPermissions = model.scratchUser.userData.accountPermissions.accountPermissions
let keys =
@@ -76,7 +140,8 @@ let accountsTabView (model:Model) (dispatch:Msg->Unit) =
|> List.filter (fun a -> a.isPresent)
|> List.map (fun a -> a.id.ToString(), a.name)
|> Map.ofList
let realAccList = model.accountsList |> List.filter (fun a -> a.isPresent)
let headerRow:TableControl.row =
{
@@ -84,40 +149,40 @@ let accountsTabView (model:Model) (dispatch:Msg->Unit) =
[
TableControl.Cell(str "Account")
TableControl.Cell(str "Trading Permission")
TableControl.Cell(str "Admin Permission")
TableControl.Cell(str "Risk Admin Permission")
TableControl.Cell(str "MD Admin Permission")
]
className = ""
header = None
}
let rows:TableControl.row list =
[for acc in accMap do yield {
[for acc in realAccList do
let string_id = acc.id.ToString()
let perm = JSMap.tryFind string_id accountPermissions
let is_bts = model.scratchUser.name = Access.superuser
let hasTradeAdmin = (if perm.IsNone then false else perm.Value.tradingPermission.hasPermissions)
let hasRiskAdmin = is_bts || (if perm.IsNone then false else perm.Value.adminPermission.hasPermissions)
let hasMdAdmin = is_bts || (if perm.IsNone then false else perm.Value.adminPermission.hasMdPermissions)
let update permission value _ = permission (string_id, not value) |> UpdateField |> dispatch
yield {
cells = [
TableControl.Cell(str acc.Value)
{ content = (Fields.checkbox "" "" (
keymap.Contains <| acc.Value)
[]
(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;
colSpan = 0
}
{ content = (Fields.checkbox "" "" (
model.scratchUser.name.Contains "bts" || model.scratchUser.name.Contains "admin")
[Disabled true]
ignore
);
className = "";
isHeader = false;
colSpan = 0
}
TableControl.Cell(str acc.name)
{ content = Fields.checkbox "" "" hasTradeAdmin [Disabled readonly] (update TradingPerm hasTradeAdmin)
className = "";
isHeader = false;
colSpan = 0
}
{ content = Fields.checkbox "" "" hasRiskAdmin [Disabled (is_bts || readonly)] (update RiskAdmin hasRiskAdmin)
className = "";
isHeader = false;
colSpan = 0
}
{ content = Fields.checkbox "" "" hasMdAdmin [Disabled (is_bts || readonly)] (update MDAdmin hasMdAdmin)
className = "";
isHeader = false;
colSpan = 0
}
]
className=""
header = None
@@ -129,7 +194,7 @@ let accountsTabView (model:Model) (dispatch:Msg->Unit) =
TableControl.createSelectorTable (Some headerRow) rows
]
let MarketDataTabView (model:Model) (dispatch:Msg->Unit) =
let MarketDataTabView (model:Model) (dispatch:Msg->Unit) (readonly:bool) =
let cmeData = model.scratchUser.userData.exchangeUserData.cmeData
let findCheckedValue (value:bts.api.CMEMics) =
@@ -137,59 +202,63 @@ let MarketDataTabView (model:Model) (dispatch:Msg->Unit) =
match checkedValue with
| Some t -> true
| None -> false
let micList = [
for micValue in bts.api.CMEMics.values do
yield (
if (micValue = bts.api.CMEMics.UNSET) |> not then
Fields.checkbox
(sprintf "%O" micValue)
""
(findCheckedValue micValue)
[]
(fun chk -> (({enabled = chk; mic = micValue }:CMEMicData) |> (CMEMic >> UpdateField >> dispatch)))
else
str ""
)
]
for micPair in CMEMicMap do
yield (
Fields.checkbox
(sprintf "%O" micPair.Key)
""
(findCheckedValue micPair.Value)
[Disabled readonly]
(fun chk -> (({enabled = chk; mic = micPair.Value}:CMEMicData) |> (CMEMic >> UpdateField >> dispatch)))
)
]
let send = UpdateField>>dispatch
div []
[
h2 [Class "is-size-3"] [ str "CME" ]
h3 [Class "is-size-4"] [ str "Entitlements" ]
div [Style [Padding " .5em 1em"]] micList
]
let orderRoutingTabView (model:Model) (dispatch:Msg->Unit) =
h3 [Class "is-size-4"] [ str "Designations" ]
//Pico recommends we hide this for the ICE
//Fields.enumSelect "Pro / Non-Pro" (toHuman false ProfessionalDesignation.values cmeData.proNonpro) (allToHuman false ProfessionalDesignation.values) [Disabled readonly] (fromHuman ProfessionalDesignation.values>>UserField.CMEProNonPro>>send)
Fields.enumSelect "Display / Non-Display" (toHuman false DisplayDesignation.values cmeData.displayNondisplay) (allToHuman false DisplayDesignation.values) [Disabled readonly] (fromHuman DisplayDesignation.values>>UserField.CMEDisplayNonDisplay>>send)
]
let orderRoutingTabView (model:Model) (dispatch:Msg->Unit) (readonly:bool) =
let cmeData = model.scratchUser.userData.exchangeUserData.cmeData
let simData = model.scratchUser.userData.exchangeUserData.simData
let simData = model.scratchUser.userData.exchangeUserData.simData
div []
[
h2 [Class "is-size-3"] [ str "CME" ]
div []
[
Fields.text "Operator ID" cmeData.operatorId [ MaxLength 18.0 ] (CMEOperatorID >> UpdateField >> dispatch)
//Fields.text "ATS Operator ID" cmeData.atsOperatorId [] (ATSOperatorID >> 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 [] (CMELocation >> UpdateField >> dispatch)
//Fields.text "Max Order Rate Per Connection" cmeData.maxOrderRatePerConnection [] (MaxOrderRatePerConnection >> UpdateField >> dispatch)
//Fields.map "Misc Tag Mapping" cmeData.miscTags [] (MiscTags >> UpdateField >> dispatch)
]
br []
h2 [Class "is-size-3"] [ str "Sim" ]
div []
[
Fields.text "Operator ID" simData.operatorId [ MaxLength 18.0 ] (SimOperatorID >> UpdateField >> dispatch)
Fields.text "Location" simData.location [] (SimLocation >> UpdateField >> dispatch)
[
h2 [Class "is-size-3"] [ str "CME" ]
div []
[
Fields.text "Operator ID" cmeData.operatorId [ MaxLength 18.0 ; Disabled readonly ] (CMEOperatorID >> UpdateField >> dispatch)
//Fields.text "ATS Operator ID" cmeData.atsOperatorId [] (ATSOperatorID >> UpdateField >> dispatch)
Fields.text "SMP ID" cmeData.smpId [Disabled readonly] (SMPID >> UpdateField >> dispatch)
Fields.mapSelectEx "SMP Instruction" State.SMPInstructionMap None (Some cmeData.smpInstruction) (SMPInstruction >> UpdateField >> dispatch) (Some readonly)
Fields.text "Location" cmeData.location [Disabled readonly] (CMELocation >> UpdateField >> dispatch)
//Fields.text "Max Order Rate Per Connection" cmeData.maxOrderRatePerConnection [] (MaxOrderRatePerConnection >> UpdateField >> dispatch)
//Fields.map "Misc Tag Mapping" cmeData.miscTags [] (MiscTags >> UpdateField >> dispatch)
]
br []
h2 [Class "is-size-3"] [ str "Sim" ]
div []
[
Fields.text "Operator ID" simData.operatorId [ MaxLength 18.0 ; Disabled readonly] (SimOperatorID >> UpdateField >> dispatch)
Fields.text "Location" simData.location [Disabled readonly] (SimLocation >> UpdateField >> dispatch)
]
]
]
]
let userControls (model:Model) (dispatch:Msg->Unit) =
let currentUser = State.getCurrentUser model
@@ -202,16 +271,20 @@ let userControls (model:Model) (dispatch:Msg->Unit) =
]
let tabContent (model:Model) (dispatch:Msg->Unit) =
let tabContent (model:Model) (dispatch:Msg->Unit) display_md display_risk =
let mod1 = {
model with currentTab = (if (not display_risk && display_md) then Tab.MarketData else model.currentTab)
}
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 -> generalTabView model dispatch
| Tab.Accounts, true -> accountsTabView model dispatch
| Tab.MarketData, true -> MarketDataTabView model dispatch
| Tab.OrderRouting, true -> orderRoutingTabView model dispatch)
(match mod1.currentTab, ( State.userIsSelected model.scratchUser State.defaultScratchUser) with
| _, false -> p [Style [ Color "Red" ]] [ str "You are not authorized to view this data" ]
| Tab.General, true -> generalTabView model dispatch (not display_risk)
| Tab.Accounts, true -> accountsTabView model dispatch (not display_risk)
| Tab.MarketData, true -> MarketDataTabView model dispatch (not display_md)
| Tab.OrderRouting, true -> orderRoutingTabView model dispatch (not display_risk) )
userControls model dispatch
(if (State.userIsSelected model.scratchUser State.defaultScratchUser) then userControls model dispatch else span[][])
]
let usersMenu (usersList:BTSUser list) (currentUser:BTSUser) (dispatch:Msg->Unit) =
@@ -283,40 +356,43 @@ let menuItem (user:BTSUser) (selectedUser:BTSUser) model 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"
(if model.can_create then
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"
]
[ div [ Class "dropdown-content" ]
[ //hr [ Class "dropdown-divider" ]
a [ Class "dropdown-item"
OnClick (fun _ -> dispatch <| Delete user)
]
[ str "Remove" ]
a [ Class "dropdown-item"
OnClick (fun _ -> dispatch <| CloneUser)
]
[ str "Clone" ]
]
]
]
]
]
[ div [ Class "dropdown-content" ]
[ //hr [ Class "dropdown-divider" ]
a [ Class "dropdown-item"
OnClick (fun _ -> dispatch <| Delete user)
]
[ str "Remove" ]
a [ Class "dropdown-item"
OnClick (fun _ -> dispatch <| CloneUser)
]
[ str "Clone" ]
]
]
]
]
else
span[][])
]
let NavRoot (usersList:BTSUser list) (currentUser:BTSUser) model (dispatch:Msg->Unit) =
@@ -325,10 +401,18 @@ let NavRoot (usersList:BTSUser list) (currentUser:BTSUser) model (dispatch:Msg->
div [ Class "column is-narrow is-sidebar-menu" ]
[ aside [ Class "menu" ]
[ p [ Class "menu-label" ] [
[ 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) ]
span [ Class "is-pulled-right circle-icon" ]
(if model.can_create then
[ Button.fabutton
"Add User"
"plus-circle"
""
Button.Enabled
(fun _ -> dispatch AddUser)
]
else [])
]
ul [ Class "menu-list" ]
@@ -339,21 +423,6 @@ let NavRoot (usersList:BTSUser list) (currentUser:BTSUser) model (dispatch:Msg->
]
]
let selectionPageContent (model:Model) (dispatch:Msg->Unit) =
let modal = Modal.showCreate
"Create User"
(div [][
Fields.text "Name" model.scratchUser.name [ ] (Name >> UpdateField >> dispatch)
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)
])
(fun _ -> dispatch SaveUser)
//(fun _ -> SwitchUser (State.getCurrentUser model) |> dispatch)
(fun _ -> CancelAddUser |> dispatch)
div [] [
userSelectionGrid model.userList model.scratchUser dispatch
(if State.isNewUser model.scratchUser then modal else span[][])
]
let root (model:Model) (dispatch:Msg->Unit) =
(*
@@ -366,6 +435,11 @@ let root (model:Model) (dispatch:Msg->Unit) =
| _, _ -> ()
)
*)
let adminDisplay = model.scratchUser.userData.exchangeUserData.cmeData.adminDisplayFlag
let is_bts = model.this_username = Access.superuser
let display_md = if is_bts then true else (adminDisplay = bts.api.admin.CMEUserData.AdminDisplay.All || adminDisplay = bts.api.admin.CMEUserData.AdminDisplay.MD)
let display_risk = if is_bts then true else (adminDisplay = bts.api.admin.CMEUserData.AdminDisplay.All || adminDisplay = bts.api.admin.CMEUserData.AdminDisplay.Routing)
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)
@@ -386,21 +460,33 @@ let root (model:Model) (dispatch:Msg->Unit) =
div [ ClassName "tabs is-boxed" ]
[ ul [ ]
[
li [ ClassName (isActiveTab Tab.General model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.General)) ]
[ str "General" ] ]
li [ ClassName (isActiveTab Tab.Accounts model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.Accounts)) ]
[ str "Account Permissions" ] ]
li [ ClassName (isActiveTab Tab.MarketData model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.MarketData)) ]
[ str "Market Data" ] ]
li [ ClassName (isActiveTab Tab.OrderRouting model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.OrderRouting)) ]
[ str "Order Routing" ] ]
(if display_risk then
li [ ClassName (isActiveTab Tab.General model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.General)) ]
[ str "General" ] ]
else
span [] [])
(if display_risk then
li [ ClassName (isActiveTab Tab.Accounts model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.Accounts)) ]
[ str "Account Permissions" ] ]
else
span [] [])
(if display_md then
li [ ClassName (isActiveTab Tab.MarketData model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.MarketData)) ]
[ str "Market Data" ] ]
else
span [] [] )
(if display_risk then
li [ ClassName (isActiveTab Tab.OrderRouting model.currentTab) ]
[ a [ OnClick (fun _ -> dispatch (SwitchTab Tab.OrderRouting)) ]
[ str "Order Routing" ] ]
else
span [] [] )
]
]
tabContent model dispatch
tabContent model dispatch display_md display_risk
modal
]
]
+4
View File
@@ -0,0 +1,4 @@
@echo off
pushd %~dp0\..\build\debug\bin\net471\
start spark_excel-addin64.xll
popd