Files
spark/src/cs/Bts.Spark.Api/Position/PositionModel.cs
T

203 lines
8.3 KiB
C#

#nullable enable
namespace Spark.Trading {
using bts;
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.api.position;
using bts.collections;
using bts.shell.pnl;
using mbts;
using mbts.analytics;
using Spark.Api.Admin;
using Spark.Api.Data;
using Spark.Api.MarketData;
using Spark.Api.Orders;
using Spark.Api.Position;
using Spark.Api.Reactive;
using Spark.Core;
using Spark.Core.Data;
using Spark.Core.Disposables;
using Spark.Core.Reactive;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading.Tasks;
public class PositionModel : IPositionModel, IDisposable {
readonly PositionService _position_service;
readonly TableUpdateDemuxer<(SecurityImmutable?, PositionUnitImmutable), int, uint> _security_positions_demuxer;
ThreadSafeDisposable? _dispose;
public PositionModel(
IAdminClient admin_model,
IMarketDataClient mdClient,
IObservable<TableUpdate<TableUpdateGrouping<OrderRecordTuple, uint, AccountSecurityKey>, AccountSecurityKey>> working_account_security_orders,
ISecurityResolver sec_resolver,
PositionService position_service,
OrderService order_service,
IObservable<PNLData> pnlDataSource,
ISecurityMetadataStore sec_meta_store) {
var scheduler = ThreadPoolScheduler.Instance;
var interval = TimeSpan.FromMilliseconds(100);
var bootstraps = new DisposableBuilder();
_position_service = position_service ?? throw new ArgumentNullException(nameof(position_service));
_security_positions_demuxer = new TableUpdateDemuxer<(SecurityImmutable?, PositionUnitImmutable pos), int, uint>(
o => o.pos.RecordId, p => p.pos.SecurityId);
on_exchange_positions = bootstraps.emplace(
order_service.subscribei_exchange_positions()
.Filter(ep => ep.SecurityKey != 0)
.SelectKeyValue(ep => ep, ep => new AccountSecurityKey(ep.AccountId, ep.SecurityKey))
.join(sec_resolver, ep => ep.SecurityKey)
.Table()
.Cache()
.ToObservable());
var raw_fills = admin_model
.permission_filter(
order_service.subscribei_fills().Naggle(interval, scheduler),
f => f.Account)
.Table();
var raw_manual_fills = admin_model
.permission_filter(
_position_service.subscribei_manual_fills().Naggle(interval, scheduler),
f => f.AccountId)
.Table();
on_positions = bootstraps.emplace(
ComputedPositionsDataSource.create(raw_fills, raw_manual_fills)
.join_table(sec_resolver, pos => pos.SecurityId)
.Cache()
.ToObservable());
var users = admin_model.Users
.Select(t => t.Index.ToDictionary(kv => kv.Key, kv => new UserTuple(kv.Key, kv.Value.Name)));
day_fills = bootstraps.emplace(
DayFillsDataSource.create(users, pnlDataSource, sec_resolver).Cache().ToObservable());
pnl = pnlDataSource
.Select(d => d.position_data.ToDictionary(u => u.id(), PNLRowData.from_pnl_unit))
.Table(PNLRowData.key_fn)
.LeftJoin(
mdClient.Books(),
rd => rd.key,
b => b.security_id,
rd => rd.key.security_id,
(pnlRow, pnlKey, book, secId) => {
var bbo = book.bbo;
return pnlRow.with(bid_price: bbo.BidPrice, ask_price: bbo.AskPrice);
},
(pnlRow, pnlKey, secId) => pnlRow,
PNLRowData.key_fn)
.FullJoin(
working_account_security_orders,
PNLRowData.key_fn,
acc_orders => acc_orders.group_key,
(row, acc_orders, pnl_key) => row.with(working: WorkingOrderData.Create(
acc_orders.table.Index.Values.Select(t => t.order), row.qty_conversion)),
(row, pnl_id) => row,
(acc_orders, pnl_id) => {
var (security, account_id, account) =
acc_orders.table.Index.Values.TryGetFirst(out var tup) ?
(tup.security, tup.order.account_id(), tup.order.account()) :
(null, 0, null);
return new PNLRowData(pnl_id,
security: security,
account_id: account_id,
account_name: account,
working: WorkingOrderData.Create(
acc_orders.table.Index.Values.Select(t => t.order),
new(
sec_meta_store.get_qty_display_divisor(security),
QuantityConversionOpType.DivideActual)));
},
PNLRowData.key_fn)
.Where(t => t.has_changes())
.Cache()
.ToObservable();
merged_positions = bootstraps.emplace(
ReconcileReportDataSource.create(
on_exchange_positions, on_positions.Filter(tup => !(tup.Item1?.HasSpread ?? false)))
.Cache()
.ToObservable());
_dispose = new(Disposable.Create(
on_positions.Subscribe(_security_positions_demuxer),
bootstraps));
}
public IObservable<TableUpdate<(SecurityImmutable? sec, RetrievedExchangePositionImmutable exch_pos), AccountSecurityKey>> on_exchange_positions { get; }
public IObservable<TableUpdate<(SecurityImmutable?, PositionUnitImmutable), int>> on_positions { get; }
public IObservable<TableUpdate<PNLRowData, AccountSecurityKey>> pnl { get; }
public IObservable<TableUpdate<ReconcileReportRowData, AccountSecurityKey>> merged_positions { get; }
public IObservable<TableUpdate<DayFillsRowData, DayFillsRowKey>> day_fills { get; }
public IObservable<TableUpdate<(SecurityImmutable?, PositionUnitImmutable), int>> on_security_positions(uint security) =>
_security_positions_demuxer.subscribe(security);
public Task<bool> override_cpp_async(IEnumerable<(uint security_key, double cpp)> cpp_overrides) {
var sec_params_batch_op = new SecurityParametersBatchOp();
sec_params_batch_op.OpParams.AddRange(cpp_overrides.Select(tup => new SecurityParameters {
SecurityKey = tup.security_key,
CppOverride = new CppOverride { Value = tup.cpp }
}));
return safe_execute(
Console.WriteLine,
() => _position_service.update_security_parameters_async(sec_params_batch_op),
r => r.Ok,
r => r.Msg,
(v, success) => success,
"override cpp");
}
public Task<IReadOnlyList<PositionServiceOpResponseImmutable>> reset_positions(
ResetPositionParametersImmutable new_positions) =>
safe_execute(
Console.WriteLine,
() => _position_service.reset_position_async(new_positions),
reply => reply.Response.All(r => r.Ok),
reply => "\n".join(reply.Response.Select(r => r.Msg)),
(v, success) => success ?
v.Response
.WrapSelectorRO(r => new PositionServiceOpResponseImmutable(r))
.ToReadOnlyList() :
Array.Empty<PositionServiceOpResponseImmutable>(),
"reset positions");
public void Dispose() =>
Disposable.dispose(ref _dispose);
public static async Task<TResult> safe_execute<T, TResult>(
Action<string> reportError,
Func<Task<Result<T>>> execute,
Func<T, bool> get_success,
Func<T, string> get_error_msg,
Func<T, bool, TResult> result_selector,
string desc) {
//
try {
var result = await execute();
if (!result.success) {
reportError(result.error_message);
} else if (!get_success(result.value)) {
reportError(get_error_msg(result.value));
} else {
return result_selector(result.value, true);
}
} catch (Exception ex) {
reportError(ex.ToString());
}
return result_selector(default!, false);
}
}
}