Files
spark/src/client/spark_websocket/Core/WebsocketRestHandler.cs
T
2024-04-01 07:48:36 -04:00

522 lines
25 KiB
C#

namespace bts.websocket_core {
using bts.api;
using bts.api.admin;
using bts.api.core;
using bts.api.orderman;
using mbts;
using Microsoft.VisualBasic;
using mbts.spark;
using Newtonsoft.Json.Linq;
using Spark.Api.Orders;
using System;
using System.Diagnostics.CodeAnalysis;
using bts.spark;
using bts.utils;
public class WebsocketRestHandler {
public static (bool,DynamicOrderParam?,string) TryGetDynamicParam(JObject custom,string key, DynamicOrderParamDescriptor descriptor, IReadOnlyDictionary<string, DynamicOrderDescriptor> Dynamic_Descriptors) {
var rv = new DynamicOrderParam();
string error = "";
switch (descriptor.ParamType.DescriptorCase) {
case DynamicOrderTypeDescriptor.DescriptorOneofCase.Array:
if (custom[key] is not JArray arr_obj) {
return (false, null, key + " not correct");
}
rv.AsArray = new DynamicOrderArray();
foreach (var p in arr_obj.ToList()){
var child_key = key+"_child";
DynamicOrderParamDescriptor child_descriptor=new() {
ParamName = child_key,
ParamType = descriptor.ParamType.Array.ElementType
};
JObject child = new() {
[child_key] = p
};
(bool suc, DynamicOrderParam? param, error) = TryGetDynamicParam(child,child_key,child_descriptor,Dynamic_Descriptors);
if(!suc){
return (suc,null,error);
}
rv.AsArray.Element.Add(param);
}
return (true,rv,error);
case DynamicOrderTypeDescriptor.DescriptorOneofCase.Enumerated:
return (false,null,key+"Enumerated DynamicOrderTypeDescriptors not enabled on api");
case DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive:
switch (descriptor.ParamType.Primitive) {
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveBool:
if (!WebsocketJsonParsers.TryParse<bool>(custom, key, out bool? b, out error) || b == null) {
return (false, null, error);
}
rv.AsBool = (bool)b;
return (true,rv,error);
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveDouble:
if (!WebsocketJsonParsers.TryParse<double>(custom, key, out double? d, out error) || d == null) {
return (false, null, error);
}
rv.AsDouble = (double)d;
return (true,rv,error);
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveInt:
if (!WebsocketJsonParsers.TryParse<int>(custom, key, out int? i, out error) || i == null) {
return (false, null, error);
}
rv.AsInt32 = (int)i;
return (true,rv,error);
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef:
if (custom[key] is not JObject child_custom) {
return (false, null, key + " not correct");
}
(bool suc,var child_custom_def,error) = TryGetCustomDef(child_custom,Dynamic_Descriptors);
if(!suc || child_custom_def==null){
return (false,null,error);
}
rv.AsOrderDef = child_custom_def;
return(true,rv,error);
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveString:
if (!WebsocketJsonParsers.TryParse<WebsocketJsonParsers.StringWrapper>(custom,key,out WebsocketJsonParsers.StringWrapper? s,out error)|| s == null) {
return (false, null, error);
}
rv.AsString = s.Value.Val;
return (true,rv,error);
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveSecurityKey:
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveUint:
if (!WebsocketJsonParsers.TryParse<uint>(custom, key, out uint? u, out error) || u == null) {
return (false, null, error);
}
rv.AsUint32 = (uint)u;
return (true,rv,error);
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveQuantity:
if (WebsocketJsonParsers.TryParse<uint>(custom, key, out uint? q, out error) && q != null) {
rv.AsQuantity = new QuantityMeasure() {
Absolute = (uint)q
};
return (true, rv, error);
} else if (WebsocketJsonParsers.TryParse<double>(custom, key, out double? qd, out error) && qd != null){
rv.AsQuantity = new QuantityMeasure() {
Ratio = (double)qd
};
return (true, rv, error);
}
else{
return (false,null,key+" not correct");
}
}
return (false,null,key+" not correct");
case DynamicOrderTypeDescriptor.DescriptorOneofCase.Structure:
if (custom[key] is not JObject obj) {
return (false, null, key + " not correct");
}
rv.AsStruct = new DynamicOrderStruct();
foreach (var prop in obj.Properties()) {
var child_key = prop.Name;
var check = descriptor.ParamType.Structure.Field.TryGetFirst(v => v?.ParamName == child_key,out DynamicOrderParamDescriptor? p);
if(!check || p == null){
return (false,null,key+" "+child_key+" not correct");
}
var child_descriptor = new DynamicOrderParamDescriptor {
ParamName = child_key,
ParamType = p.ParamType
};
(bool success, DynamicOrderParam? param, error) = TryGetDynamicParam(obj, child_key, child_descriptor, Dynamic_Descriptors);
if (!success) {
return (success, null, error);
}
rv.AsStruct.Field[child_key] = param;
}
return (true,rv,error);
}
return (false,null,key+" not correct");
}
readonly static Lazy<AdminService> _admin = new Lazy<AdminService>(() => Locator.locate<AdminService>(), true);
private static (bool, CustomOrderDefinition?, string) TryGetCustomDef(WebsocketRequest req, IReadOnlyDictionary<string, DynamicOrderDescriptor> Dynamic_Descriptors){
if (req.parameters["options"] is not JObject custom) {
return (false, null, "options not correct");
}
return TryGetCustomDef(custom,Dynamic_Descriptors);
}
private static (bool, CustomOrderDefinition?, string) TryGetCustomDef(JObject custom, IReadOnlyDictionary<string, DynamicOrderDescriptor> Dynamic_Descriptors) {
CustomOrderDefinition customdef;
if (!WebsocketJsonParsers.TryParse<CustomOrderDefinition.CustomOneofCase>(custom, "order_type", out CustomOrderDefinition.CustomOneofCase? order_type, out string status) || order_type == null) {
return (false, null, status);
}
switch (order_type) {
case CustomOrderDefinition.CustomOneofCase.Stop:{
customdef = new CustomOrderDefinition() {
Stop = new StopOrderDefinition()
};
break;
}
case CustomOrderDefinition.CustomOneofCase.StopLimit:{
if (!WebsocketJsonParsers.TryParse<double>(custom, "stop_price", out double? sp, out status) || sp == null) {
return (false, null, status);
}
customdef = new CustomOrderDefinition() {
StopLimit = new StopLimitOrderDefinition(){
StopPrice=(double)sp
}
};
break;
}
case CustomOrderDefinition.CustomOneofCase.Iceberg: {
if (!WebsocketJsonParsers.TryParse<double>(custom, "show_quantity", out double? sq, out status) || sq == null) {
return (false, null, status);
}
if (custom["child"] is not JObject child) {
return (false, null, "Iceberg child not correct");
}
(var check, var childdef, status) = TryGetCustomDef(child,Dynamic_Descriptors);
if(!check){
return (false, null, status);
}
// mbts.spark.utilities.OrderDataHelper
customdef = new CustomOrderDefinition() {
Iceberg = new IcebergOrderDefinition() {
ShowQuantity = (double)sq,
Child = childdef
}
};
break;
}
case CustomOrderDefinition.CustomOneofCase.TimeBox:{
return (false,null,"timebox not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Spreader: {
// if (custom == null) {
// message = "custom not present";
// return false;
// }
return (false,null,"spreaders not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Tick:{
return (false,null,"Ticks not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Lean:{
return (false,null,"Lean not enabled on api");
// if (!WebsocketJsonParsers.TryParse<double>(custom, "", out double? sq, out status) || sq == null) {
// return (false, null, status);
// }
// if (custom["child"] is not JObject child) {
// return (false, null, "Lean child not correct");
// }
// (var check, var childdef, status) = TryGetCustomDef(child,Dynamic_Descriptors);
// if(!check){
// return (false, null, status);
// }
// customdef = new CustomOrderDefinition() {
// Lean = new LeanOrderDefinition(){
// DetachOnToward = false,
// CrossThreshold = 0,
// MaxChaseTicks = 0,
// Child = childdef
// }
// };
}
case CustomOrderDefinition.CustomOneofCase.Join:{
return (false,null,"join not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Top:{
return (false,null,"top not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Trigger:{
return (false,null,"trigger not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Cover: {
if (
!WebsocketJsonParsers.TryParse<uint>( custom, "hedge_ticks", out uint? ht, out status) || ht == null ||
!WebsocketJsonParsers.TryParse<bool>(custom, "cancel_on_external_hedge_cancel", out bool? coehc, out status) || coehc == null ||
!WebsocketJsonParsers.TryParse<bool>(custom, "cancel_hedges_on_cancel", out bool? choc, out status) || choc == null ||
!WebsocketJsonParsers.TryParse<bool>(custom, "detach_hedges", out bool? dh, out status) || dh == null
) {
return (false, null, status);
}
if (custom["child"] is not JObject child) {
return (false, null, "Cover child not correct");
}
(var check, var childdef, status) = TryGetCustomDef(child,Dynamic_Descriptors);
if(!check){
return (false, null, status);
}
if (custom["hedge"] is not JObject hedge) {
return (false, null, "Cover hedge not correct");
}
(check, var hedgedef, status) = TryGetCustomDef(hedge,Dynamic_Descriptors);
if(!check){
return (false, null, status);
}
customdef = new CustomOrderDefinition() {
Cover = new CoverOrderDefinition() {
HedgeTicks = (uint)ht,
CancelOnExternalHedgeCancel = (bool)coehc,
CancelHedgesOnCancel = (bool)choc,
DetachHedges = (bool)dh,
Hedge = hedgedef,
Child = childdef
}
};
break;
}
case CustomOrderDefinition.CustomOneofCase.Offset:{
if (!WebsocketJsonParsers.TryParse<uint>(custom, "tick_offset", out uint? to, out status) || to == null) {
return (false, null, status);
}
if (custom["child"] is not JObject child) {
return (false, null, "offset child not correct");
}
(var check, var childdef, status) = TryGetCustomDef(child,Dynamic_Descriptors);
if(!check){
return (false, null, status);
}
// mbts.spark.utilities.OrderDataHelper
customdef = new CustomOrderDefinition() {
Offset = new OffsetOrderDefinition() {
TickOffsetOnDeploy = (uint)to,
Child = childdef
}
};
break;
}
case CustomOrderDefinition.CustomOneofCase.Oco:{
return (false,null,"Oco not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Pricer:{
return (false,null,"pricer not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Composite:{
return (false,null,"Composite not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.GlbxIceberg:{
if (!WebsocketJsonParsers.TryParse<uint>(custom, "max_show_quantity", out uint? msq, out status) || msq == null) {
return (false, null, status);
}
// mbts.spark.utilities.OrderDataHelper
customdef = new CustomOrderDefinition() {
GlbxIceberg = new GLBXIcebergOrderDefinition() {
MaxShowQuantity = (uint)msq,
}
};
break;
}
case CustomOrderDefinition.CustomOneofCase.Splitter:{
return (false,null,"splitter not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.QueueHolder:{
return (false,null,"QueueHolder not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Scratch:{
return (false,null,"Scratch not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Prorata:{
return (false,null,"Prorata not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.DeleteAndCover:{
return (false,null,"DeleteAndCover not enabled on api");
}
case CustomOrderDefinition.CustomOneofCase.Limit: {
customdef = new CustomOrderDefinition() {
Limit = new LimitOrderDefinition()
};
break;
}
case CustomOrderDefinition.CustomOneofCase.Dynamic: {
if (custom == null) {
return (false, null, "custom not present");
}
if(!WebsocketJsonParsers.TryParse<WebsocketJsonParsers.StringWrapper>(custom, "dynamic_order_type", out WebsocketJsonParsers.StringWrapper? dynamic_order_type, out status) || dynamic_order_type == null ||
!Dynamic_Descriptors.TryGetValue(dynamic_order_type.Value.Val, out var desc)){
return (false, null, status);
}
var def = new DynamicOrderDefinition() {
DynamicOrderType = desc.DynamicOrderType
};
foreach (var p in desc.ParamDesc) {
(bool suc, var d, var error)=TryGetDynamicParam(custom,p.ParamName,p,Dynamic_Descriptors);
if(!suc){
return (suc,null,error);
}
def.OrderParams[p.ParamName] = d;
}
customdef = new CustomOrderDefinition() {
Dynamic = def
};
break;
}
case CustomOrderDefinition.CustomOneofCase.Market: {
customdef = new CustomOrderDefinition() {
Market = new MarketOrderDefinition()
};
break;
}
default: {
return (false, null, "order_type not correct");
}
};
return (true, customdef, status);
}
private async static Task<(bool, OrderDefinition?, string)> TryGetOrderDefAsync(WebsocketRequest req, IReadOnlyDictionary<uint, SecurityMD> securities, IReadOnlyDictionary<string, DynamicOrderDescriptor> Dynamic_Descriptors) {
if (req.parameters == null) {
return (false, null, "parameters not present");
}
if (
!WebsocketJsonParsers.TryParse<WebsocketJsonParsers.StringWrapper>(req.parameters,"user",out WebsocketJsonParsers.StringWrapper? usr,out string status) || usr == null ||
!WebsocketJsonParsers.TryParse<Venue>(req.parameters, "venue", out Venue? exchange, out status) || exchange == null ||
!WebsocketJsonParsers.TryParse<WebsocketJsonParsers.StringWrapper>(req.parameters, "account", out WebsocketJsonParsers.StringWrapper? act, out status) || act == null ||
!WebsocketJsonParsers.TryParse<Side>(req.parameters, "side", out Side? side, out status) || side == null ||
!WebsocketJsonParsers.TryParse<WebsocketJsonParsers.StringWrapper>(req.parameters, "exchange_security_name", out WebsocketJsonParsers.StringWrapper? exchange_securty_name, out status) || exchange_securty_name == null
) {
return (false, null, status);
}
Result<AdminData> adminResult = await _admin.Value.get_admin_data_async(new VoidMessage());
uint user_id;
uint account_id;
if (!adminResult.success || adminResult.value == null) {
return (false, null, adminResult.error_message);
}
AdminData admin = adminResult.value;
string username = usr.Value.Val;
string accountname = act.Value.Val;
BTSUser? user = admin.Users.FirstOrDefault(x => username != null ? x.Name.ToLowerInvariant() == username.ToLowerInvariant() : true);
if (user == null) {
return (false, null, "user not correct");
}
user_id = (uint)user.Id;
BTSAccount? account = admin.Accounts.FirstOrDefault(x => x.Name.ToLowerInvariant() == accountname.ToLowerInvariant());
if (account == null) {
return (false, null, "account not correct");
}
account_id = (uint)account.Id;
var _securites = securities;
if (!_securites.Values.TryGetFirst(sc_md =>
(
sc_md.security.Exchange == exchange &&
sc_md.security.ToString() == exchange_securty_name.Value.Val),
out SecurityMD sc_md
)) {
return (false, null, "security not found");
}
(var check, var customdef, status) = TryGetCustomDef(req, Dynamic_Descriptors);
if (check == false) {
return (false, null, status);
}
return (true, new OrderDefinition {
TimeInForce = TimeInForce.Day,
SecurityKey = sc_md.id,
Side = (Side)side,
UserId = user_id,
AccountId = account_id,
CustomDef = customdef,
Account = account.Name,
User = user.Name
}, status);
}
static bool TryGetPoints(WebsocketRequest req, [NotNullWhen(true)] out List<PrecomputedTheoPoint>? theos, out string message, IReadOnlyDictionary<uint, SecurityMD> securities) {
theos = null;
if (!WebsocketJsonParsers.TryParse<WebsocketJsonParsers.PrecomputedTheoPointWrapper>(req.parameters, "points", out WebsocketJsonParsers.PrecomputedTheoPointWrapper[]? wrapper_theos, out message) || wrapper_theos == null) {
return false;
}
theos = wrapper_theos.Select(wrapper => {
if (WebsocketJsonParsers.PrecomputedTheoPointWrapper.GetTheoPoint(wrapper, out PrecomputedTheoPoint? point, securities)) {
return point;
}
return null;
})
.Where(p => p != null)
.Cast<PrecomputedTheoPoint>()
.ToList();
return true;
}
public static async Task<(bool success, uint? id, string status)> SetTheosAsync(WebsocketRequest req, OrdersClient oc, IReadOnlyDictionary<uint, SecurityMD> securities) {
if (req.parameters == null) {
return (false, null, "parameters not present");
}
var log_txt = $"SetTheosAsync req {req.ToString()}";
bts.Log.Gen.warn(log_txt);
var _securites = securities;
if (!TryGetPoints(req, out List<PrecomputedTheoPoint>? theos, out string message, _securites)) {
return (false, null, message);
}
Response res = await oc.TrySetPrecomputedTheosAsync(theos);
return (res.ErrorCode != OrderError.Ok, null, res.Msg);
}
public static async Task<(bool success, uint? id, string status)> DeleteOrderAsync(WebsocketRequest req, OrdersClient oc) {
if (req.parameters == null) {
return (false, null, "parameters not present");
}
if (!WebsocketJsonParsers.TryParse<uint>(req.parameters, "order_key", out uint? key, out string status) || key == null) {
return (false, null, status);
}
Response res = await oc.TryDeleteOrderAsync((uint)key);
status = res.ErrorCode.ToString();
return (res.ErrorCode != OrderError.Ok, null, status);
}
public static async Task<(bool success, uint? id, string status)> UpdateOrderAsync(WebsocketRequest request, OrdersClient oc, IReadOnlyDictionary<string, DynamicOrderDescriptor> Dynamic_Descriptors) {
if (request.parameters == null) {
return (false, null, "parameters not present");
}
if (
!WebsocketJsonParsers.TryParse<uint>(request.parameters, "order_key", out uint? key, out string status) || key == null ||
!WebsocketJsonParsers.TryParse(request.parameters, "quantity", out double? quantity, out status) || quantity == null ||
!WebsocketJsonParsers.TryParse(request.parameters, "price", out double? price, out status) || price == null
) {
return (false, null, status);
}
(var check, var customdef, status) = TryGetCustomDef(request, Dynamic_Descriptors);
if (check == false || customdef == null) {
return (false, null, status);
}
Response res = await oc.TryUpdateOrderAsync(customdef, (double)price, (double)quantity, (uint)key);
status = res.ErrorCode.ToString();
return (res.ErrorCode != OrderError.Ok, null, status);
}
public static async Task<(bool success, uint? orderId, string status)> EnterOrderAsync(
WebsocketRequest request, OrdersClient ordersClient, IReadOnlyDictionary<uint, SecurityMD> securities, IReadOnlyDictionary<string, DynamicOrderDescriptor> Dynamic_Descriptors) {
OrderDefinition? orderDefinition = null;
uint? orderId = null;
string status = string.Empty;
(bool success, orderDefinition, status) = await TryGetOrderDefAsync(request, securities, Dynamic_Descriptors);
if (
!success || orderDefinition == null ||
!WebsocketJsonParsers.TryParse(request.parameters, "quantity", out double? quantity, out status) || quantity == null ||
!WebsocketJsonParsers.TryParse(request.parameters, "price", out double? price, out status) || price == null ) {
return (false, null, status);
}
var result = await ordersClient.TryEnterOrderAsync(orderDefinition, (uint)price, (double)quantity);
if (result.ErrorCode != OrderError.Ok) {
return (false, null, result.ErrorCode.ToString());
}
orderId = result.OrderKey;
status = result.ErrorCode.ToString();
return (true, orderId, status);
}
}
}