feat: Add dump-books/securities cmds to api server cli

This commit is contained in:
John Colvin committed 2023-03-20 13:26:43 -04:00
1 parent 787fb879d2
commit 7bb0951169
6 files changed
+270 -2

No files matched your search

@@ -51,6 +51,11 @@ namespace bts.api.core {
public T GetService<T>(string? qualifier) where T : class, IApiClient =>
locate<T>(qualifier ?? string.Empty);
public async Task<bool> try_login(string username, string password) {
var res = await login(username, password);
return res.success;
}
public async Task<LoginResult> login(string username, string password) {
var auth_service = locate<AuthService>();
var result = await auth_service.authenticate_login_async(new AuthenticateLoginRequest() {
+100
View File
@@ -0,0 +1,100 @@
namespace spark_api_server {
using bts;
using bts.api.core;
using bts.md;
using mbts;
using mbts.spark;
using Spark.Api.MarketData;
using Spark.Api.Server;
using Spark.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;
static class BookDumper {
public static async Task<int> run(DumpBooksOptions opts) {
Log.notnull(opts.user);
Log.notnull(opts.password);
var service_ctx = ServiceContext.create(opts.sparkd);
if (!await service_ctx.try_login(opts.user, opts.password)) {
return 1;
}
var md_source = new MDSource(TimeSpan.FromSeconds(0.5));
var md_client = new MarketDataClient(md_source);
var name_set = opts.securities.empty_if_null().ToHashSet();
var books_src = md_client.books(s => name_set.Contains(s.ToString()))
.Cache().ToObservable();
var sub = books_src.Subscribe(on_books);
await books_src.LastOrDefaultAsync();
return 0;
void on_books(TableUpdate<BookTuple, uint> books) {
var updated_books = books.added.Concat(books.changed);
var desc = "\n".join(updated_books.Select(fmt_book));
Console.WriteLine(desc);
string fmt_book(BookTuple book_tuple) {
var sb = new StringBuilder();
// Write the 2 line header (the security, followed by a separator line)
sb.AppendLine(book_tuple.security.ToString());
var total_width = opts.quantity_width * 2 + opts.price_width + 2;
sb.AppendLine(new string('*', total_width));
// Format the book levels like the ladder. For example (w/ 2 price levels):
// ask_qty ask_price
// ask_qty ask_price
// -------------------------
// bid_price bid_qty
// bid_price bid_qty
var bk = book_tuple.book;
var ask_lines = bk.asks
.TakeWhile((l, i) => i < opts.num_levels && l.size > 0)
.Reverse()
.Select(fmt_ask);
var bid_lines = bk.bids
.TakeWhile((l, i) => i < opts.num_levels && l.size > 0)
.Select(fmt_bid);
foreach (var l in ask_lines) {
sb.AppendLine(l);
}
// write line to separate bids and asks (the length is the sum of col widths:
// qty + 1 + price + 1 + qty (the 1's represent space between cols)
sb.AppendLine(new string('-', total_width));
// Each bid level begins at the price column. Pad accordingly.
var bid_padding = new string(' ', opts.quantity_width + 1);
foreach (var l in bid_lines) {
sb.AppendLine(bid_padding + l);
}
sb.AppendLine();
return sb.ToString();
string fmt_ask(PriceSize ps) {
var qty_text = fmt_qty(ps).PadRight(opts.quantity_width);
var price_text = fmt_price(ps).PadRight(opts.price_width);
return $"{qty_text} {price_text}";
}
string fmt_bid(PriceSize ps) {
var price_text = fmt_price(ps).PadRight(opts.price_width);
var qty_text = fmt_qty(ps).PadRight(opts.quantity_width);
return $"{price_text} {qty_text}";
}
string fmt_price(PriceSize ps) =>
book_tuple.security.spec_or_default().format(ps.price);
string fmt_qty(PriceSize ps) =>
book_tuple.quantity_display.format((double)ps.size);
}
}
}
}
}
@@ -0,0 +1,50 @@
namespace Spark.Api.Server {
using bts.utils;
using CommandLine;
using Spark.Core;
using System.Collections.Generic;
[Verb("dump-books")]
public class DumpBooksOptions {
#if DEBUG
const string _default_user = "bts";
#else
const string _default_user = "";
#endif
[Option("user", Default = _default_user)]
public string? user { get; set; }
[Option("password", Default = "")]
public string? password { get; set; }
[Option("sparkd", MetaValue = "URL", HelpText = "The sparkd server")]
public string? sparkd { get; set; }
[Option("securities", HelpText = "The securities for which to dump books", Separator = ' ')]
public IEnumerable<string>? securities { get; set; }
[Option("num-levels", HelpText = "The number of price levels to show (per side)", Default = 5)]
public int num_levels { get; set; }
[Option("price-width", HelpText = "The price column width", Default = 10)]
public int price_width { get; set; }
[Option("quantity-width", HelpText = "The quantity column width", Default = 10)]
public int quantity_width { get; set; }
public override string ToString() =>
TableFormatter.fmt_table(new (string, object?)[] {
("user", user),
("password", password),
("sparkd", sparkd),
("securities", ", ".join(securities.empty_if_null())),
("num-levels", num_levels),
("price-width", price_width),
("quantity-width", quantity_width),
});
}
}
@@ -0,0 +1,54 @@
namespace Spark.Api.Server {
using bts.api;
using bts.utils;
using CommandLine;
using Spark.Core;
using System;
using System.Collections.Generic;
using System.Text;
[Verb("dump-securities")]
public class DumpSecuritiesOptions {
[Option("user", Default = CommonOptionMetadata.DEFAULT_USER)]
public string? user { get; set; }
[Option("password", Default = CommonOptionMetadata.DEFAULT_PASSWORD)]
public string? password { get; set; }
[Option(
"sparkd",
MetaValue = CommonOptionMetadata.SPARKD_META_VALUE,
HelpText = CommonOptionMetadata.SPARKD_HELP_TEXT)]
public string? sparkd { get; set; }
[Option("types", HelpText = "The types of securities to dump", Separator = ' ')]
public IEnumerable<SecurityType>? types { get; set; }
[Option("venues", HelpText = "The venues to query", Separator = ' ')]
public IEnumerable<Venue>? venues { get; set; }
[Option("assets", HelpText = "The assets to query", Separator = ' ')]
public IEnumerable<string>? assets { get; set; }
[Option("verbose", HelpText = "Whether or not to show verbose output")]
public bool verbose { get; set; }
[Option("timeout", HelpText = "The amount of time to wait for securities")]
public TimeSpan? timeout { get; set; }
public override string ToString() =>
TableFormatter.fmt_table(new (string, object?)[] {
("user", user),
("password", password),
("sparkd", sparkd),
("assets", ", ".join(assets.empty_if_null())),
("venues", ", ".join(venues.empty_if_null())),
("types", ", ".join(types.empty_if_null())),
("verbose", verbose),
("timeout", timeout),
});
}
}
+3 -2
View File
@@ -19,8 +19,9 @@
}
static async Task<int> Main(string[] args) {
var res = Parser.Default.ParseArguments<RunOptions>(args);
return await res.MapResult(_run, errs => Task.FromResult(1));
var res = Parser.Default.ParseArguments<RunOptions, DumpSecuritiesOptions, DumpBooksOptions>(args);
return await res.MapResult<RunOptions, DumpSecuritiesOptions, DumpBooksOptions, Task<int>>(
_run, SecurityDumper.run, BookDumper.run, errs => Task.FromResult(1));
}
static async Task<int> _run(RunOptions opts) {
@@ -0,0 +1,58 @@
namespace spark_api_server {
using bts;
using bts.api;
using bts.api.core;
using bts.md;
using mbts.spark;
using Spark.Api.Server;
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
static class SecurityDumper {
public static async Task<int> run(DumpSecuritiesOptions opts) {
Log.notnull(opts.user);
Log.notnull(opts.password);
var service_ctx = ServiceContext.create(opts.sparkd);
if (!await service_ctx.try_login(opts.user, opts.password)) {
return 1;
}
var md_source = new MDSource(TimeSpan.FromSeconds(0.5));
var md_client = new MarketDataClient(md_source);
var criteria = new SecurityCriteria(
new SecurityCriteriaClause[] {
new(
exchanges: opts.venues?.ToArray(),
security_types: opts.types?.ToArray(),
symbols: opts.assets?.ToArray())
});
var secs_src = md_client.securities_incremental(criteria);
var sub = secs_src.Subscribe(on_securities);
var wait_src = secs_src;
if (opts.timeout.HasValue) {
wait_src = wait_src.StopAfter(opts.timeout.Value);
}
await wait_src.LastOrDefaultAsync();
return 0;
void on_securities(TableUpdate<SecurityImmutable, uint> securities) {
foreach (var sec in securities.added) {
Console.WriteLine(fmt(sec));
}
string fmt(SecurityImmutable sec) {
if (!opts.verbose) {
return sec.ToString();
}
var fmt_settings = Google.Protobuf.JsonFormatter.Settings.Default;
var formatter = new Google.Protobuf.JsonFormatter(fmt_settings);
return formatter.Format(sec.CloneToMutable());
}
}
}
}
}