diff --git a/doc/user/content/release_notes/_index.md b/doc/user/content/release_notes/_index.md index f8bf3f960..45c69c4ce 100644 --- a/doc/user/content/release_notes/_index.md +++ b/doc/user/content/release_notes/_index.md @@ -21,7 +21,7 @@ insert_anchor_links = "right" - The escape key now closes the floating order book #### Bug Fixes - Fixed the "Since Open" time filter to use the exchange open time rather than 8:30 AM - - Fixed a bug in the order book where sometimes parent orders whould not update their last message column. + - Fixed a bug in the order book where sometimes parent orders would not update their last message column. #### Algos - Added OCO Algo diff --git a/src/client/spark_api/md/MarketDataClient.cs b/src/client/spark_api/md/MarketDataClient.cs index 34909805d..87749fcee 100644 --- a/src/client/spark_api/md/MarketDataClient.cs +++ b/src/client/spark_api/md/MarketDataClient.cs @@ -17,9 +17,9 @@ using SecurityKey = System.UInt32; namespace bts.md { - public class MarketDataClient : IDisposable + public class MarketDataClient : IDisposable { - static uint naggle_ms = 100; + static uint naggle_ms = 100; readonly static bts.md.MDSource _subscription = new MDSource(naggle_ms); readonly ConcurrentDictionary _data = new ConcurrentDictionary(); @@ -68,8 +68,8 @@ namespace bts.md { return _subscribe(filter, update_interval, scheduler); } - - IObservable> _subscribe(Func filter, + + IObservable> _subscribe(Func filter, TimeSpan? update_interval = null, IScheduler scheduler = null) where T : IMDData, IMDUpdate, new() { List> slots = new List>(); int data_size = 0; @@ -77,7 +77,7 @@ namespace bts.md { //if the number of securities has changed, or this is the first call if (data_size != _data.Count) - { + { slots = _data.Values.Where(x => filter(x.security)).Select(xx => new Slot(xx)).ToList(); data_size = _data.Count; } @@ -116,7 +116,7 @@ namespace bts.md return _subscribe(ids, update_interval, scheduler); } - IObservable> _subscribe(IEnumerable ids, TimeSpan? update_interval = null, + IObservable> _subscribe(IEnumerable ids, TimeSpan? update_interval = null, IScheduler scheduler = null) where T : IMDData, IMDUpdate, new() { List> slots = ids.Where(ii => _data.TryGetValue(ii, out SecurityMD _)).Select(x => @@ -132,13 +132,13 @@ namespace bts.md bool did_update = slot.data.update(slot.secmd, ref slot.last_update_time); //if (slot.last_update_time > last_timer_tick) if(did_update) - updates.Add(slot.data); + updates.Add(slot.data); } if(updates.Count > 0) observer.OnNext(updates); }, update_interval, scheduler); - } + } class Slot where T : IMDData, IMDUpdate, new() { @@ -151,7 +151,7 @@ namespace bts.md public SecurityMD secmd; public ulong last_update_time; public T data; - } + } IObservable timer_pump(Action> tick, TimeSpan? interval, IScheduler scheduler = null) { @@ -159,14 +159,14 @@ namespace bts.md interval = TimeSpan.FromMilliseconds(_default_pump_ms); ulong last_update_time = 0; return Observable.Create(observer => - { + { return Observable.Timer(interval.Value, interval.Value, scheduler ?? Scheduler.Default).Subscribe(_ => { tick(last_update_time, observer); last_update_time = (ulong)DateTime.UtcNow.Ticks; }); }); - } + } public void Dispose() { @@ -227,17 +227,17 @@ namespace bts.md } CancellationTokenSource src = new CancellationTokenSource(timeout.Value); SecurityImmutable? security = await Task.Run(async () => - { - SecurityImmutable? sec = null; - do - { - sec = find_security(filter); - if (sec == null) - await Task.Delay(500); - } - while (sec == null); - return sec; - }, src.Token); + { + SecurityImmutable? sec = null; + do + { + sec = find_security(filter); + if (sec == null) + await Task.Delay(500); + } + while (sec == null); + return sec; + }, src.Token); return security ?? throw new KeyNotFoundException("Can't find security for filter"); ; } diff --git a/src/client/spark_core/TestRunner/InProcessTestRunner.cs b/src/client/spark_core/TestRunner/InProcessTestRunner.cs index 9abf0f187..871f06b58 100644 --- a/src/client/spark_core/TestRunner/InProcessTestRunner.cs +++ b/src/client/spark_core/TestRunner/InProcessTestRunner.cs @@ -5,13 +5,14 @@ using bts.api.test; using System; using System.Collections.Generic; using System.Threading.Tasks; +using System.Diagnostics; namespace bts.test { public static class InProcessTestRunner { public static void run_test_synchronously(string v, TestEnumerator enumerator, Action report) { foreach (var t in enumerator.find(v)) { - run_test_synchronously(t, report); + run_test_synchronously(t, report); } } public static void run_test_synchronously(TestMethod test, Action report) { @@ -36,11 +37,11 @@ namespace bts.test { live.Dispose(); result.Status = TestResult.Types.Step.Pass; } - catch (AssertFailture af) { + catch (AssertFailure af) { result.Message = $"Assertion Failure:\n{af.Message}\nLocation:{af._filename}:{af._line}"; } catch (Exception ue) { - if (ue.InnerException is AssertFailture af) { + if (ue.InnerException is AssertFailure af) { result.Message = $"Assertion Failure:\n{af.Message}\nLocation:{af._filename}:{af._line}"; } else if (ue.InnerException != null) { diff --git a/src/client/spark_core/TestRunner/TestAssert.cs b/src/client/spark_core/TestRunner/TestAssert.cs index 0306073cc..1e5e106ac 100644 --- a/src/client/spark_core/TestRunner/TestAssert.cs +++ b/src/client/spark_core/TestRunner/TestAssert.cs @@ -4,21 +4,21 @@ using System.Linq; using System.Runtime.CompilerServices; namespace bts.test { - public class AssertFailture : Exception { + public class AssertFailure : Exception { public readonly string _filename; public readonly int _line; - public AssertFailture(string msg, string filename, int line) : base(msg.Trim()) { + public AssertFailure(string msg, string filename, int line) : base(msg.Trim()) { _filename = filename; _line = line; } } public static class Assert { public static void Failure(string msg="", [CallerFilePath] string file="", [CallerLineNumber] int line=0) { - throw new AssertFailture(msg, file, line); + throw new AssertFailure(msg, file, line); } public static void IsTrue(bool test, string msg="", [CallerFilePath] string file="", [CallerLineNumber] int line=0) { if (!test) { - throw new AssertFailture($"Expected: 'true' got 'false'. {msg}", file, line); + throw new AssertFailure($"Expected: 'true' got 'false'. {msg}", file, line); } } public static void That(bool test, string msg = "", [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { @@ -26,17 +26,17 @@ namespace bts.test { } public static void IsFalse(bool test, string msg="", [CallerFilePath] string file="", [CallerLineNumber] int line=0) { if (test) { - throw new AssertFailture($"Expected: 'false' got 'true'. {msg}", file, line); + throw new AssertFailure($"Expected: 'false' got 'true'. {msg}", file, line); } } public static void IsNaN(double value, string msg = "", [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) { if (!double.IsNaN(value)) { - throw new AssertFailture($"Expected: NaN got {value}", file, line); + throw new AssertFailure($"Expected: NaN got {value}", file, line); } } public static void AreEqual(T a, T b, string msg="", [CallerFilePath] string file="", [CallerLineNumber] int line=0) { if (!a.Equals(b)) { - throw new AssertFailture( + throw new AssertFailure( $"Expected: '{a}' == '{b}'. {msg}", file, line); } } @@ -44,16 +44,16 @@ namespace bts.test { if (!a.SequenceEqual(b)) { var aa = string.Join(", ", a); var bb = string.Join(", ", b); - throw new AssertFailture( + throw new AssertFailure( $"Expected: [{aa}]\nGot: [{bb}]. {msg}", file, line); } } - - public static void IsNotNull(T a, string msg="", [CallerFilePath] string file="", [CallerLineNumber] int line=0) + + public static void IsNotNull(T a, string msg="", [CallerFilePath] string file="", [CallerLineNumber] int line=0) where T : class { if (a == null) { - throw new AssertFailture( + throw new AssertFailure( $"Expected non-null {typeof(T).Name}. {msg}", file, line); } } @@ -61,7 +61,7 @@ namespace bts.test { public static void Contains(IEnumerable items, T item, string msg="", [CallerFilePath] string file="", [CallerLineNumber] int line=0) { if (!items.Contains(item)) { var aa = string.Join(", ", items); - throw new AssertFailture( + throw new AssertFailure( $"Expected: {item} in [{aa}]. {msg}", file, line); } } @@ -75,12 +75,12 @@ namespace bts.test { threw = true; } catch (Exception e) { - throw new AssertFailture( + throw new AssertFailure( $"Expected '{typeof(T).Name}' but threw '{e.GetType().Name}'", file, line); } if (!threw) { - throw new AssertFailture( + throw new AssertFailure( msg ?? $"Expected '{typeof(T).Name}' exception but ran successfully.", file, line); } diff --git a/src/client/spark_core/TestRunner/TestAttributes.cs b/src/client/spark_core/TestRunner/TestAttributes.cs index 67728d29a..ebe5b25c3 100644 --- a/src/client/spark_core/TestRunner/TestAttributes.cs +++ b/src/client/spark_core/TestRunner/TestAttributes.cs @@ -12,9 +12,12 @@ namespace bts.test { this.TestType = TestType.Unit; } public TestType TestType; + public string ConfigPath; + } [AttributeUsage(AttributeTargets.Method)] public class TestAttribute : Attribute { + public uint Timeout = 10; } // Use constructor for setup diff --git a/src/client/spark_core/TestRunner/TestEnumerator.cs b/src/client/spark_core/TestRunner/TestEnumerator.cs index 727ca392d..e18c9b838 100644 --- a/src/client/spark_core/TestRunner/TestEnumerator.cs +++ b/src/client/spark_core/TestRunner/TestEnumerator.cs @@ -15,6 +15,7 @@ namespace bts.test { .Select(t => new TestClass(t, t.GetCustomAttribute().TestType, + t.GetCustomAttribute().ConfigPath, t.GetMethods() .Where(m => m.GetCustomAttribute() != null) .Select(m => new TestMethod(t, m)) @@ -52,15 +53,17 @@ namespace bts.test { public class TestClass { - public TestClass(Type type, TestType test_type, IEnumerable methods) { + public TestClass(Type type, TestType test_type, string config_path, IEnumerable methods) { this.type = type; this.test_type = test_type; + this.config_path = config_path; this.methods = methods; } public string name => type.Name; public Assembly assembly => type.Assembly; public Type type { get; } public TestType test_type { get; } + public string config_path { get; } public IEnumerable methods { get; } public override string ToString() { return $"[TestGroup:{name}]"; @@ -81,6 +84,9 @@ namespace bts.test { public override string ToString() { return $"[Test:{full_name}]"; } + + public uint timeout => method.GetCustomAttribute().Timeout; + public string config_path => owner.GetCustomAttribute().ConfigPath; public LiveTest setup() { return new LiveTest(this); } public class LiveTest : IDisposable { diff --git a/src/client/spark_core/TestRunner/TestRunner.cs b/src/client/spark_core/TestRunner/TestRunner.cs index 9a1e6f436..4de8733e7 100644 --- a/src/client/spark_core/TestRunner/TestRunner.cs +++ b/src/client/spark_core/TestRunner/TestRunner.cs @@ -16,16 +16,16 @@ namespace bts.test { public TestRunner() { } const int TIMEOUT = -1; - public int run_tests(IEnumerable tests, uint timeout) { + public int run_tests(IEnumerable tests, uint timeout, bool self_contained) { using (var trr = new TestResultReceiver(false)) { var listening = trr.listen(); trr.print_begin(); foreach (var t in tests) { int count = trr.ResultCount; - var res = run_one(t, TimeSpan.FromSeconds(timeout)); + var res = run_one(t, timeout, self_contained); if (res == TIMEOUT) { trr.print_result(new TestResult() { - TestName = t, + TestName = t.full_name, Status = TestResult.Types.Step.Timeout }); } @@ -33,7 +33,7 @@ namespace bts.test { // If we didn't time out and no results were reported we crashed or something if (count == trr.ResultCount) { trr.print_result(new TestResult() { - TestName = t, + TestName = t.full_name, Status = TestResult.Types.Step.Crash }); } @@ -44,23 +44,51 @@ namespace bts.test { } } - int run_one(string test, TimeSpan timeout) { + int run_one(TestMethod test, uint timeout, bool self_contained) { + TimeSpan time_out = timeout == 0u ? TimeSpan.FromSeconds(test.timeout) : TimeSpan.FromSeconds(timeout); + + Process sparkd = new Process(); + if(self_contained){ + //if insular (selfcontained) start sparkd + sparkd.StartInfo.FileName = "sparkd"; + sparkd.StartInfo.Arguments = test.config_path != null ? "run " + test.config_path : "run"; + sparkd.Start(); + } + + string filename = Environment.GetCommandLineArgs().First(); + string args = $"test {test.full_name}"; + + if(filename.Substring(filename.Length - 3) == "dll") { + args = filename + " " + args; + filename = "dotnet"; + + } var psi = new ProcessStartInfo(); - psi.FileName = Environment.GetCommandLineArgs().First(); - psi.Arguments = $"test {test}"; + psi.FileName = filename; + psi.Arguments = args; psi.CreateNoWindow = true; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; psi.UseShellExecute = false; - var p = Process.Start(psi); - p.WaitForExit((int)timeout.TotalMilliseconds); - if (p.HasExited) { - return 0; + + try{ + var p = Process.Start(psi); + p.WaitForExit((int)time_out.TotalMilliseconds); + if (p.HasExited) { + return 0; + } + while (!p.HasExited) { + p.Kill(); + System.Threading.Thread.Sleep(100); + } } - while (!p.HasExited) { - System.Threading.Thread.Sleep(100); - p.Kill(); + finally { + if(self_contained){ + sparkd.Kill(); + } } + + //ConsoleEx.WriteLine("Stdout: ", ConsoleColor.Magenta); //ConsoleEx.WriteLine(p.StandardOutput.ReadToEnd(), ConsoleColor.Magenta); //ConsoleEx.WriteLine("Stderr: ", ConsoleColor.Magenta); diff --git a/src/client/spark_test/System/LimitsTests.cs b/src/client/spark_test/System/LimitsTests.cs index 36a2235fe..562234dd8 100644 --- a/src/client/spark_test/System/LimitsTests.cs +++ b/src/client/spark_test/System/LimitsTests.cs @@ -21,6 +21,8 @@ namespace bts.tests ServiceContext _context; OrderService _order_service; AdminService _admin_service; + IDisposable _order_subscription; + Update _orders; public LimitsTests (){ _context = new ServiceContext(); @@ -29,6 +31,12 @@ namespace bts.tests var auth = _context.login("bts",""); auth.Wait(3000); + + _order_subscription = _order_service.subscribei_orders().Subscribe(ords => + { + _orders = ords; + }); + } public void Dispose() { @@ -70,7 +78,135 @@ namespace bts.tests return securities; } - [Test] + [Test(Timeout = 30)] + public async Task test_position_limits() { + string test_symbol = "CL"; + + var test_user = ( name: "bts", id: 0u ); + var test_account = ( name: "ACC A", id: 0u ); + + BTSAccountImmutable? account_data = await AdminUtilities.get_account_data(_admin_service, test_account.name); + Assert.IsTrue(account_data.HasValue); + test_account.id = account_data.Value.Id; + + var user_data = await AdminUtilities.get_user_data(_admin_service, test_user.name); + Assert.IsTrue(user_data.HasValue); + test_user.id = user_data.Value.Id; + + var clip_set_success = await AdminUtilities.set_clip_limit(_admin_service, 10000, account_data, test_symbol); + Assert.IsTrue(clip_set_success, "Failed to set clip limit "); + + var all_securities = await all_futures(test_symbol); + List security_list = all_securities.ToList(); + + Assert.IsTrue(all_securities.Count() >= 2); + SecurityImmutable first_sec = security_list[0]; + SecurityImmutable second_sec = security_list[1]; + + await AdminUtilities.remove_position_limit(_admin_service, test_account.name, test_symbol); + + var first_order_def = create_order_def(first_sec.Id, Side.Buy, test_account, test_user); + var second_order_def = create_order_def(second_sec.Id, Side.Buy, test_account, test_user); + + + Result no_limit_order_result = await send_order(first_order_def, 5, 1); + + IEnumerable no_limit_filtered_orders = await get_filtered_orders(x => x.Key == no_limit_order_result.value.OrderKey); + + Assert.IsTrue(no_limit_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "'Absent Limit' Order is not 'Rejected by Spark'"); + + bool position_set_success = await AdminUtilities.set_position_limit(_admin_service, test_account.name, test_symbol, 60, 120); + Assert.IsTrue(position_set_success); + + List> orders_response_list = new List>(); + + for(int i = 0; i <3; i++){ + orders_response_list.Add(await send_order(first_order_def, 5, 10)); + } + + for(int i = 0; i <3; i++){ + orders_response_list.Add(await send_order(second_order_def, 5, 10)); + } + + foreach(var i in orders_response_list){ + var iret = await get_filtered_orders(x => x.Key == i.value.OrderKey); + Assert.IsTrue(iret.First().State.Status == OrderStatus.Working, "This order should have been 'working'"); + } + + var fail_order_result = await send_order(first_order_def, 5, 1); + var fail_order_filtered_orders = await get_filtered_orders(x => x.Key == fail_order_result.value.OrderKey); + Assert.IsTrue(fail_order_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "This order should have been 'Rejected by Spark'"); + + bool position_increase_success = await AdminUtilities.set_position_limit(_admin_service, test_account.name, test_symbol, 70, 120); + Assert.IsTrue(position_increase_success); + + var increased_order_result = await send_order(first_order_def, 5, 10); + var increased_order_filtered_orders = await get_filtered_orders(x => x.Key == increased_order_result.value.OrderKey); + Assert.IsTrue(increased_order_filtered_orders.First().State.Status == OrderStatus.Working, "This order should have been 'Working'"); + + var second_fail_order_result = await send_order(first_order_def, 5, 10); + var second_fail_filtered_orders = await get_filtered_orders(x => x.Key == second_fail_order_result.value.OrderKey); + Assert.IsTrue(second_fail_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "This order should have been 'Rejected by Spark'"); + + /* Test Short Position Limit */ + + Assert.IsTrue(await cancel_orders(), "Unable to cancel orders"); + + await AdminUtilities.remove_position_limit(_admin_service, test_account.name, test_symbol); + + var rw = await AdminUtilities.get_position_limit_row(_admin_service, test_account.name, test_symbol); + Assert.IsTrue(rw == null, "Deleted row still exists"); + + var first_short_order_def = create_order_def(first_sec.Id, Side.Sell, test_account, test_user); + var second_short_order_def = create_order_def(second_sec.Id, Side.Sell, test_account, test_user); + + uint short_no_limit_order_key; + + Result short_no_limit_order_result = await send_order(first_short_order_def, 50000, 7); + + short_no_limit_order_key = short_no_limit_order_result.value.OrderKey; + IEnumerable short_no_limit_filtered_orders = await get_filtered_orders(x => x.Key == short_no_limit_order_key); + var stats = short_no_limit_filtered_orders.First().State.Status; + Assert.IsTrue(short_no_limit_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "'Absent Limit' Order is not 'Rejected by Spark'"); + + bool short_position_set_success = await AdminUtilities.set_position_limit(_admin_service, test_account.name, test_symbol, 120, 60); + Assert.IsTrue(position_set_success); + + List> short_orders_response_list = new List>(); + + for(int i = 0; i <3; i++){ + short_orders_response_list.Add(await send_order(first_short_order_def, 50000, 10)); + } + + for(int i = 0; i <3; i++){ + short_orders_response_list.Add(await send_order(second_short_order_def, 50000, 10)); + } + + foreach(var i in short_orders_response_list){ + var iret = await get_filtered_orders(x => x.Key == i.value.OrderKey); + Assert.IsTrue(iret.First().State.Status == OrderStatus.Working, "This order should have been 'working'"); + } + + var short_fail_order_result = await send_order(first_short_order_def, 50000, 1); + var short_fail_order_filtered_orders = await get_filtered_orders(x => x.Key == short_fail_order_result.value.OrderKey); + Assert.IsTrue(short_fail_order_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "This order should have been 'Rejected by Spark'"); + + bool short_position_increase_success = await AdminUtilities.set_position_limit(_admin_service, test_account.name, test_symbol, 120, 70); + Assert.IsTrue(short_position_increase_success); + + var short_increased_order_result = await send_order(first_short_order_def, 50000, 10); + var short_increased_order_filtered_orders = await get_filtered_orders(x => x.Key == short_increased_order_result.value.OrderKey); + Assert.IsTrue(short_increased_order_filtered_orders.First().State.Status == OrderStatus.Working, "This order should have been 'Working'"); + + var short_second_fail_order_result = await send_order(first_short_order_def, 50000, 10); + var short_second_fail_filtered_orders = await get_filtered_orders(x => x.Key == short_second_fail_order_result.value.OrderKey); + Assert.IsTrue(short_second_fail_filtered_orders.First().State.Status == OrderStatus.RejectedBySpark, "This order should have been 'Rejected by Spark'"); + + Assert.IsTrue(await cancel_orders(), "Unable to cancel orders"); + } + + + [Test(Timeout = 10)] public async Task test_clip_limits() { //Get and set limit values from the admin service @@ -124,32 +260,19 @@ namespace bts.tests over_limit_order_key = over_limit_order_result.value.OrderKey; no_limit_order_key = no_limit_order_result.value.OrderKey; - bool waiting_for_orders = true; + IEnumerable filtered_orders = await get_filtered_orders(x => x.Key == under_limit_order_key || x.Key == over_limit_order_key || x.Key == no_limit_order_key); - var orders = _order_service.subscribei_orders().Subscribe(ords => + foreach(var o in filtered_orders) { - waiting_for_orders = false; - - IEnumerable filtered_orders = ords.all.Where(x => x.Key == under_limit_order_key || x.Key == over_limit_order_key || x.Key == no_limit_order_key); - - Assert.IsTrue(filtered_orders.Count() == 3, "There should be 3 matching orders... there are not"); - - foreach(var o in filtered_orders) - { - if(o.Key == under_limit_order_key) { - Assert.IsTrue(o.State.Status == OrderStatus.Working, "Under Limit Order is not 'Working'"); - } - else if(o.Key == over_limit_order_key) { - Assert.IsTrue(o.State.Status == OrderStatus.RejectedBySpark, "Over Limit Order is not 'RejectedBySpark'"); - } - else if(o.Key == no_limit_order_key) { - Assert.IsTrue(o.State.Status == OrderStatus.RejectedBySpark, "No Limit Order is not 'RejectedBySpark'"); - } + if(o.Key == under_limit_order_key) { + Assert.IsTrue(o.State.Status == OrderStatus.Working, "'Under Limit' Order is not 'Working'"); + } + else if(o.Key == over_limit_order_key) { + Assert.IsTrue(o.State.Status == OrderStatus.RejectedBySpark, "'Over Limit' Order is not 'RejectedBySpark'"); + } + else if(o.Key == no_limit_order_key) { + Assert.IsTrue(o.State.Status == OrderStatus.RejectedBySpark, "'Absent Limit' Order is not 'RejectedBySpark'"); } - }); - - while(waiting_for_orders) { - await Task.Delay(100); } // Restore the Limits to the original values @@ -163,25 +286,74 @@ namespace bts.tests } Assert.IsTrue(success, "Failed to restore Limit"); - - } + + private async Task> get_filtered_orders(Func predicate, int count = 1) + { + int current_count = 0; + int it = 0; + do{ + if(_orders != null){ + var ords = _orders.all.Where(predicate); + current_count = ords.Count(); + + if(current_count >= count){ + return ords; + } + it ++; + } + await Task.Delay(100); + } + while(it < 100 &&(_orders == null || current_count < count)); + + return null; + + } + + + public async Task> send_order(OrderDefinition order_def, double price, uint size){ + return await _order_service.create_order_async(new Create() { + NewOrder = order_def, + Price = price, + Quantity = size + }); + } + + public async Task cancel_orders(uint key = 0){ + if (key > 0) { + Result resp = await _order_service.cancel_order_async(new Cancel() { OrderKey = key }); + return resp.success; + } + else { + bool suc = true; + var working_orders = await get_filtered_orders(x => x.State.Status == OrderStatus.Working); + if(working_orders != null){ + foreach (var o in working_orders){ + Result resp = await _order_service.cancel_order_async(new Cancel() { OrderKey = o.Key }); + suc &= resp.success; + } + return suc; + } + return true;// there are no working orders... so true enough + } + } + public OrderDefinition create_order_def(uint security_id, Side side, (String name, uint id) account, (String name, uint id) user){ - return new OrderDefinition { - SecurityKey = security_id, - Side = Side.Buy, - TimeInForce = TimeInForce.Day, - CustomDef = new CustomOrderDefinition { Limit = new LimitOrderDefinition { } }, - CtiCode = CTICode.CtiCode1, - CustomerOrFirm = CustomerOrFirm.Firm, - ManualOrderIndicator = ManualOrderIndicator.Yes, - Account = account.name, - AccountId = account.id, - User = user.name, - UserId = user.id - }; - } + return new OrderDefinition { + SecurityKey = security_id, + Side = side, + TimeInForce = TimeInForce.Day, + CustomDef = new CustomOrderDefinition { Limit = new LimitOrderDefinition { } }, + CtiCode = CTICode.CtiCode1, + CustomerOrFirm = CustomerOrFirm.Firm, + ManualOrderIndicator = ManualOrderIndicator.Yes, + Account = account.name, + AccountId = account.id, + User = user.name, + UserId = user.id + }; + } } @@ -200,6 +372,18 @@ namespace bts.tests return null; } + public static async Task get_user_data (AdminService admin_service, string user_name) + { + Update update = await admin_service.subscribei_admin_data().FirstAsync(); + + foreach (var usr in update.all.First().Users) { + if(usr.Name == user_name) { + return usr; + } + } + return null; + } + public static AccountSecurityClipLimitUnitImmutable? get_clip_limit_row(BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { IEnumerable clip_limit_rows = account_data.Value.SecurityClipLimits.Limit.Where( r => r.Security.SecuritySymbol == symbol @@ -253,6 +437,22 @@ namespace bts.tests return update_ret.success; } + public static async Task clear_all_limits(AdminService admin_service, string account_name) { + var account_data = await get_account_data(admin_service, account_name); + return await clear_all_limits(admin_service, account_data); + } + + public static async Task clear_all_limits(AdminService admin_service, BTSAccountImmutable? account_data) { + var new_account_data = account_data.Value.with(security_clip_limits: new AccountSecurityClipLimits(), product_position_limits: new List()); + + var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { + CompleteData = new_account_data.CloneToMutable() + }); + + return update_ret.success; + } + + public static async Task remove_clip_limit(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { var account_data = await get_account_data(admin_service, account_name); return await remove_clip_limit(admin_service, account_data, symbol, security_type, venue); @@ -282,6 +482,92 @@ namespace bts.tests } + public static async Task get_position_limit_row(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + var account_data = await get_account_data(admin_service, account_name); + return get_position_limit_row(account_data, symbol, security_type, venue); + } + + public static AccountProductPositionLimitUnitImmutable? get_position_limit_row(BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + IEnumerable limit_rows = account_data.Value.ProductPositionLimits.Where( + r => r.Product.SecuritySymbol == symbol + && r.Product.Exchange == venue + && r.Product.SecurityType == security_type); + return limit_rows.Any() ? limit_rows.First() : (AccountProductPositionLimitUnitImmutable?) null; + + } + + public static async Task remove_position_limit(AdminService admin_service, string account_name, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + var account_data = await get_account_data(admin_service, account_name); + return await remove_position_limit(admin_service, account_data, symbol, security_type, venue); + } + + public static async Task remove_position_limit(AdminService admin_service, BTSAccountImmutable? account_data, string symbol, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + + AccountProductPositionLimitUnitImmutable? origin_limit_row = get_position_limit_row(account_data,symbol,security_type,venue); + List limits_list = account_data.Value.ProductPositionLimits.ToList(); + + if(origin_limit_row.HasValue) { + limits_list.Remove(origin_limit_row.Value); + List temp_plu = new List(); + temp_plu.AddRange(limits_list.Select(x => x.CloneToMutable())); + var new_account_data = account_data.Value.with(product_position_limits: temp_plu); + + var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { + CompleteData = new_account_data.CloneToMutable() + }); + + return update_ret.success; + } + else + { + return false; + } + } + + public static async Task set_position_limit(AdminService admin_service, string account_name, string symbol, uint long_limit, uint short_limit, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + var account_data = await get_account_data(admin_service, account_name); + return await set_position_limit(admin_service, account_data, symbol, long_limit, short_limit, security_type, venue); + } + + public static async Task set_position_limit(AdminService admin_service, BTSAccountImmutable? account_data, string symbol, uint long_limit, uint short_limit, SecurityType security_type = SecurityType.Future, Venue venue = Venue.Sim) { + + AccountProductPositionLimitUnitImmutable? limit_row = get_position_limit_row(account_data,symbol,security_type,venue); + List limits_list = account_data.Value.ProductPositionLimits.ToList(); + + if(limit_row.HasValue) { + // update the row + limits_list.Remove(limit_row.Value); + limit_row = limit_row.Value.with(long_position_limit: long_limit, short_position_limit: short_limit); + } + else { + // create a new row + AccountProductPositionLimitUnit acplu = new AccountProductPositionLimitUnit(); + acplu.LongPositionLimit = long_limit; + acplu.ShortPositionLimit = short_limit; + acplu.Product = new ProductScope { + SecuritySymbol = symbol, + SecurityType = security_type, + Exchange = venue + }; + + limit_row = acplu; + } + + limits_list.Add(limit_row.Value); + + List temp_plu = new List(); + temp_plu.AddRange(limits_list.Select(x => x.CloneToMutable())); + + var new_account_data = account_data.Value.with(product_position_limits: temp_plu); + + var update_ret = await admin_service.update_account_async(new AccountUpdateAPIArgument { + CompleteData = new_account_data.CloneToMutable() + }); + + return update_ret.success; + } + + } diff --git a/src/client/sparkcmd/Cmd/TestCommand.cs b/src/client/sparkcmd/Cmd/TestCommand.cs index f5950bd5e..b8a0f790c 100644 --- a/src/client/sparkcmd/Cmd/TestCommand.cs +++ b/src/client/sparkcmd/Cmd/TestCommand.cs @@ -17,6 +17,8 @@ namespace sparkcmd { TestType test_type = TestType.Unit; + bool self_contained = false; + public TestCommand() { IsCommand("test", "Run managed unit tests"); // i comes thorugh as "t" which seems daft. @@ -26,6 +28,7 @@ namespace sparkcmd { HasOption("unit","Run unit tests", _ => test_type = TestType.Unit); HasOption("system","Run system tests", _ => test_type = TestType.System); HasOption("shell","Run shell tests", _ => test_type = TestType.Shell); + HasOption("i|insular|selfcontained", "Tests run sparkd and use their own config (if specified)", _ => self_contained = true); HasAdditionalArguments(null, " [Test List]"); } @@ -37,7 +40,7 @@ namespace sparkcmd { //Configuration.initialize_for_test(); - if (_timeout == 0 && tests.Length == 1) { + if (_timeout == 0 && tests.Length == 1 && !self_contained) { //System.Threading.Thread.Sleep(5000); using (var trr = new TestResultReceiver(true)) { InProcessTestRunner.run_test_synchronously(tests[0], Enumerator, trr.get_reporter()); @@ -46,20 +49,20 @@ namespace sparkcmd { } } else if (tests.Length > 0) { - return run_tests(Enumerator.match(tests).Select(t => t.name)); + return run_tests(Enumerator.match(tests)); } else { - return run_tests(Enumerator.get_of_type(test_type).Select(t => t.full_name)); + return run_tests(Enumerator.get_of_type(test_type)); } } Lazy _enumerator = new Lazy(() => new TestEnumerator("spark_test")); TestEnumerator Enumerator => _enumerator.Value; - int run_tests(IEnumerable tests) { + int run_tests(IEnumerable tests) { var runner = new TestRunner(); // waits for all child processes to exit or time out - return runner.run_tests(tests, Math.Max(_timeout,10)); + return runner.run_tests(tests, _timeout, self_contained); } void list_tests() { diff --git a/tools/run_sparkcmd_test_Linux.cmd b/tools/run_sparkcmd_test_Linux.cmd new file mode 100644 index 000000000..c36fb6f69 --- /dev/null +++ b/tools/run_sparkcmd_test_Linux.cmd @@ -0,0 +1,22 @@ +@echo off +@setlocal +SETLOCAL +if [%3] == [r] ( + set build_type=release +) else ( + set build_type=debug +) +echo %build_type% +if "%SPARKVM_PORT%"=="" set SPARKVM_PORT=22 +echo. + +pushd %~dp0\..\src\client\sparkcmd + +dotnet publish -f netcoreapp2.1 +cd ..\..\..\build\Debug\bin\netcoreapp2.1\publish +bash -c "scp * bts@sparkvm:~/spark/build/ninja_%build_type%/server/" + +ssh bts@sparkvm -p %SPARKVM_PORT% -o StrictHostKeyChecking=no -t "cd /home/bts/spark/build/ninja_%build_type%/server && dotnet sparkcmd.dll test %1 %2" +ENDLOCAL + +popd