Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
447d3303d1 | ||
|
|
5693fc4444 | ||
|
|
8896066e2c | ||
|
|
4992f4e0cf | ||
|
|
3503946011 | ||
|
|
d31d8648f1 | ||
|
|
2c15f83c85 | ||
|
|
f9dfb04fca | ||
|
|
680b19b6fb | ||
|
|
f790b8f59b | ||
|
|
fbed8e5428 | ||
|
|
524f3be25a | ||
|
|
9823b44083 | ||
|
|
30feda72bb | ||
|
|
2d0e63546d | ||
|
|
cc02fa1c84 | ||
|
|
6139d53e49 | ||
|
|
7f3c2e75a3 | ||
|
|
0f61e24ae5 | ||
|
|
8da2ebee5c | ||
|
|
a1faf685eb | ||
|
|
9e2b01a723 | ||
|
|
d03c74f270 | ||
|
|
834a28916b | ||
|
|
43ccb4e3e7 |
No files matched your search
@@ -1,6 +1,8 @@
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
project(spark)
|
||||
|
||||
set (USE_ONIX "TRUE")
|
||||
|
||||
if (WIN32)
|
||||
set (platform "windows")
|
||||
else ()
|
||||
@@ -40,6 +42,11 @@ else ()
|
||||
-fPIC -Wall -pedantic -Wextra -Werror \
|
||||
-Wno-missing-braces -Wno-ignored-qualifiers \
|
||||
--std=c++17 -fdiagnostics-color")
|
||||
|
||||
if (${USE_ONIX})
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DUSE_ONIX")
|
||||
endif()
|
||||
|
||||
set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -DNDEBUG -O3")
|
||||
set (CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wno-undef")
|
||||
add_subdirectory(src/server/sparkd)
|
||||
|
||||
@@ -1 +1 @@
|
||||
set(sources /home/eric/spark/doc/user/build.sh;content/_index.md;content/bts_spark/Glossary/_index.md;content/bts_spark/Help/_index.md;content/bts_spark/Help/about_spark.png;content/bts_spark/Help/image39.png;content/bts_spark/Help/image58.png;content/bts_spark/Launcher/_index.md;content/bts_spark/Launcher/image38.png;content/bts_spark/Launcher/image68.png;content/bts_spark/Logging-In-to-the-System/_index.md;content/bts_spark/Logging-In-to-the-System/image3.png;content/bts_spark/Logging-In-to-the-System/image64.png;content/bts_spark/Market/_index.md;content/bts_spark/Market/change_securities.png;content/bts_spark/Market/image11.png;content/bts_spark/Market/image14.png;content/bts_spark/Market/image20.png;content/bts_spark/Market/image21.png;content/bts_spark/Market/image23.png;content/bts_spark/Market/image24.png;content/bts_spark/Market/image34.png;content/bts_spark/Market/image49.png;content/bts_spark/Market/image53.png;content/bts_spark/Market/image66.png;content/bts_spark/Market/image69.png;content/bts_spark/Market/market_view.png;content/bts_spark/Market/settings_icon.png;content/bts_spark/Market/time_and_sales.png;content/bts_spark/My-Windows/_index.md;content/bts_spark/My-Windows/image15.png;content/bts_spark/My-Windows/image16.png;content/bts_spark/My-Windows/image37.png;content/bts_spark/Settings/_index.md;content/bts_spark/Settings/image51.png;content/bts_spark/Settings/image9.png;content/bts_spark/Spreader/_index.md;content/bts_spark/Spreader/image10.png;content/bts_spark/Spreader/image13.png;content/bts_spark/Spreader/image18.png;content/bts_spark/Spreader/image19.png;content/bts_spark/Spreader/image28.png;content/bts_spark/Spreader/image29.png;content/bts_spark/Spreader/image31.png;content/bts_spark/Spreader/image35.png;content/bts_spark/Spreader/image40.png;content/bts_spark/Spreader/image43.png;content/bts_spark/Spreader/image54.png;content/bts_spark/Spreader/image55.png;content/bts_spark/Spreader/image56.png;content/bts_spark/Spreader/image6.png;content/bts_spark/Spreader/image7.png;content/bts_spark/Spreader/image70.png;content/bts_spark/Spreader/image72.png;content/bts_spark/Spreader/image8.png;content/bts_spark/Trading/OrderTypes/index.md;content/bts_spark/Trading/_index.md;content/bts_spark/Trading/algo_studio.png;content/bts_spark/Trading/collapse_all_icon.png;content/bts_spark/Trading/cover_algo_control.png;content/bts_spark/Trading/expand_all_icon.png;content/bts_spark/Trading/image1.png;content/bts_spark/Trading/image17.png;content/bts_spark/Trading/image2.png;content/bts_spark/Trading/image25.png;content/bts_spark/Trading/image27.png;content/bts_spark/Trading/image33.png;content/bts_spark/Trading/image42.png;content/bts_spark/Trading/image44.png;content/bts_spark/Trading/image47.png;content/bts_spark/Trading/image48.png;content/bts_spark/Trading/image5.png;content/bts_spark/Trading/image50.png;content/bts_spark/Trading/image52.png;content/bts_spark/Trading/image57.png;content/bts_spark/Trading/image59.png;content/bts_spark/Trading/image60.png;content/bts_spark/Trading/image61.png;content/bts_spark/Trading/image62.png;content/bts_spark/Trading/image73.png;content/bts_spark/Trading/image74.png;content/bts_spark/Trading/join_algo_control.png;content/bts_spark/Trading/ladder.png;content/bts_spark/Trading/ladder_badges.png;content/bts_spark/Trading/ladder_main_part.png;content/bts_spark/Trading/lean_algo_control.png;content/bts_spark/Trading/mini_orderbook.png;content/bts_spark/Trading/oco_algo_control.png;content/bts_spark/Trading/offset_algo_control.png;content/bts_spark/Trading/pnl_calculation.png;content/bts_spark/Trading/pnl_window.png;content/bts_spark/Trading/recreate_icon.png;content/bts_spark/Trading/settings_icon.png;content/bts_spark/Trading/spark_menu_order_book.png;content/bts_spark/Trading/top_algo_control.png;content/bts_spark/Trading/trigger_algo_control.png;content/bts_spark/_index.md;content/release_notes/_index.md;content/system_requirements/_index.md;static/book.js;static/favicon.ico;static/image.js;templates/index.html;templates/page.html;templates/section.html;templates/shortcodes/back_button.html)
|
||||
set(sources /home/ppinto/Dropbox/bts/spark/doc/user/build.sh;content/_index.md;content/bts_spark/Glossary/_index.md;content/bts_spark/Help/_index.md;content/bts_spark/Help/about_spark.png;content/bts_spark/Help/image39.png;content/bts_spark/Help/image58.png;content/bts_spark/Launcher/_index.md;content/bts_spark/Launcher/image38.png;content/bts_spark/Launcher/image68.png;content/bts_spark/Logging-In-to-the-System/_index.md;content/bts_spark/Logging-In-to-the-System/image3.png;content/bts_spark/Logging-In-to-the-System/image64.png;content/bts_spark/Market/_index.md;content/bts_spark/Market/change_securities.png;content/bts_spark/Market/image11.png;content/bts_spark/Market/image14.png;content/bts_spark/Market/image20.png;content/bts_spark/Market/image21.png;content/bts_spark/Market/image23.png;content/bts_spark/Market/image24.png;content/bts_spark/Market/image34.png;content/bts_spark/Market/image49.png;content/bts_spark/Market/image53.png;content/bts_spark/Market/image66.png;content/bts_spark/Market/image69.png;content/bts_spark/Market/market_view.png;content/bts_spark/Market/settings_icon.png;content/bts_spark/Market/time_and_sales.png;content/bts_spark/My-Windows/_index.md;content/bts_spark/My-Windows/image15.png;content/bts_spark/My-Windows/image16.png;content/bts_spark/My-Windows/image37.png;content/bts_spark/Settings/_index.md;content/bts_spark/Settings/image51.png;content/bts_spark/Settings/image9.png;content/bts_spark/Spreader/_index.md;content/bts_spark/Spreader/image10.png;content/bts_spark/Spreader/image13.png;content/bts_spark/Spreader/image18.png;content/bts_spark/Spreader/image19.png;content/bts_spark/Spreader/image28.png;content/bts_spark/Spreader/image29.png;content/bts_spark/Spreader/image31.png;content/bts_spark/Spreader/image35.png;content/bts_spark/Spreader/image40.png;content/bts_spark/Spreader/image43.png;content/bts_spark/Spreader/image54.png;content/bts_spark/Spreader/image55.png;content/bts_spark/Spreader/image56.png;content/bts_spark/Spreader/image6.png;content/bts_spark/Spreader/image7.png;content/bts_spark/Spreader/image70.png;content/bts_spark/Spreader/image72.png;content/bts_spark/Spreader/image8.png;content/bts_spark/Trading/OrderTypes/index.md;content/bts_spark/Trading/_index.md;content/bts_spark/Trading/algo_studio.png;content/bts_spark/Trading/collapse_all_icon.png;content/bts_spark/Trading/cover_algo_control.png;content/bts_spark/Trading/expand_all_icon.png;content/bts_spark/Trading/image1.png;content/bts_spark/Trading/image17.png;content/bts_spark/Trading/image2.png;content/bts_spark/Trading/image25.png;content/bts_spark/Trading/image27.png;content/bts_spark/Trading/image33.png;content/bts_spark/Trading/image42.png;content/bts_spark/Trading/image44.png;content/bts_spark/Trading/image47.png;content/bts_spark/Trading/image48.png;content/bts_spark/Trading/image5.png;content/bts_spark/Trading/image50.png;content/bts_spark/Trading/image52.png;content/bts_spark/Trading/image57.png;content/bts_spark/Trading/image59.png;content/bts_spark/Trading/image60.png;content/bts_spark/Trading/image61.png;content/bts_spark/Trading/image62.png;content/bts_spark/Trading/image73.png;content/bts_spark/Trading/image74.png;content/bts_spark/Trading/join_algo_control.png;content/bts_spark/Trading/ladder.png;content/bts_spark/Trading/ladder_badges.png;content/bts_spark/Trading/ladder_main_part.png;content/bts_spark/Trading/lean_algo_control.png;content/bts_spark/Trading/mini_orderbook.png;content/bts_spark/Trading/oco_algo_control.png;content/bts_spark/Trading/offset_algo_control.png;content/bts_spark/Trading/pnl_calculation.png;content/bts_spark/Trading/pnl_window.png;content/bts_spark/Trading/recreate_icon.png;content/bts_spark/Trading/settings_icon.png;content/bts_spark/Trading/spark_menu_order_book.png;content/bts_spark/Trading/top_algo_control.png;content/bts_spark/Trading/trigger_algo_control.png;content/bts_spark/_index.md;content/release_notes/_index.md;content/system_requirements/_index.md;static/book.js;static/favicon.ico;static/image.js;templates/index.html;templates/page.html;templates/section.html;templates/shortcodes/back_button.html)
|
||||
@@ -109,6 +109,22 @@ namespace mbts.spark {
|
||||
public AccountTuple? get_default_account() =>
|
||||
_account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).TryFirst();
|
||||
|
||||
public async Task<Result<AdminServiceOperationResult>[]> set_risk_limits(IReadOnlyDictionary<uint, IEnumerable<(uint, RiskLimits)>> state) {
|
||||
var results = await Task.WhenAll(state.Select(impl));
|
||||
return results;
|
||||
async Task<Result<AdminServiceOperationResult>> impl(KeyValuePair<uint, IEnumerable<(uint, RiskLimits)>> kv) {
|
||||
var prlimits = new ProprietaryRiskLimits();
|
||||
foreach (var (sec, lim) in kv.Value) {
|
||||
var api_lim = AccountSecurityRiskLimitsDataHelper.from_client_data(sec, lim);
|
||||
prlimits.SecurityLimits.Add(api_lim);
|
||||
}
|
||||
return await _service.update_proprietary_risk_limits_async(new ProprietaryRiskLimitsAPIArgument {
|
||||
AccountId = kv.Key,
|
||||
ProprietaryRiskLimits = prlimits
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public Task<(bool success, string error_msg)> add_or_update_risk_limits(uint account_key, IEnumerable<(uint security_key, RiskLimits limits)> new_limits) {
|
||||
return _modify_risk_limits("Updating Risk Limits", account_key, add_limits);
|
||||
//
|
||||
@@ -130,9 +146,10 @@ namespace mbts.spark {
|
||||
//
|
||||
ProprietaryRiskLimits remove_secs(ProprietaryRiskLimits prlimits) {
|
||||
var sec_key_set = new HashSet<uint>(security_keys);
|
||||
for (int i = 0; i < prlimits.SecurityLimits.Count; i++) {
|
||||
if (sec_key_set.Contains(prlimits.SecurityLimits[i].SecurityKey))
|
||||
for (int i = 0; i < prlimits.SecurityLimits.Count;) {
|
||||
if (sec_key_set.Contains(prlimits.SecurityLimits[i].SecurityKey)) {
|
||||
prlimits.SecurityLimits.RemoveAt(i);
|
||||
} else i++;
|
||||
}
|
||||
return prlimits;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@ namespace bts.admin.risk {
|
||||
|
||||
public override int GetHashCode() =>
|
||||
EqualityComparer.auto_phase(security.GetHashCode(), account.GetHashCode());
|
||||
|
||||
public static bool operator ==(AccountSecurityKey a, AccountSecurityKey b) => a.Equals(b);
|
||||
public static bool operator !=(AccountSecurityKey a, AccountSecurityKey b) => !a.Equals(b);
|
||||
}
|
||||
|
||||
readonly struct AccountSecurityRiskLimits : IEquatable<AccountSecurityRiskLimits> {
|
||||
@@ -138,9 +141,9 @@ namespace bts.admin.risk {
|
||||
api_data.MinSellPrice,
|
||||
api_data.MaxBuyPrice));
|
||||
|
||||
public static AccountSecurityRiskLimits with(this AccountSecurityRiskLimits cli_data, RiskLimits? limits = null, AccountTuple? account = null, SecurityImmutable? security = null) =>
|
||||
public static AccountSecurityRiskLimits with(this AccountSecurityRiskLimits cli_data, RiskLimits? limits = null, AccountTuple? account = null, SecurityImmutable? security = null, AccountSecurityKey? key = null) =>
|
||||
new AccountSecurityRiskLimits(
|
||||
cli_data.key,
|
||||
key ?? cli_data.key,
|
||||
limits ?? cli_data.limits,
|
||||
account: account ?? new AccountTuple(cli_data.account_key, cli_data.account_name),
|
||||
security: security ?? cli_data.security);
|
||||
|
||||
@@ -114,6 +114,8 @@ namespace bts.shell {
|
||||
public static QuoteInsideMarketDistanceWithTravel QuoteInsideMarketDistanceWithTravel => new QuoteInsideMarketDistanceWithTravel { Priority = RulePriority };
|
||||
public static QuoteInsideMarketDistance QuoteInsideMarketDistance => new QuoteInsideMarketDistance { Priority = RulePriority };
|
||||
public static QuoteInsideMarketDistanceThrottle QuoteInsideMarketDistanceThrottle => new QuoteInsideMarketDistanceThrottle();
|
||||
|
||||
public static QuoteTimeBasedThrottle QuoteTimeBasedThrottle => new QuoteTimeBasedThrottle { DelayToImprove = 0, DelayToRun = 0 };
|
||||
#endregion
|
||||
|
||||
#region PreHedge
|
||||
|
||||
@@ -10,13 +10,13 @@ namespace mbts.spark {
|
||||
public override string man_page { get; } = string.Empty;
|
||||
|
||||
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
|
||||
leg_tup.leg_params.EnableHedging;
|
||||
leg_tup.leg_params.SendHedge is null || leg_tup.leg_params.SendHedge.Val;
|
||||
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, bool value) =>
|
||||
leg_tup.leg_params.EnableHedging = value;
|
||||
|
||||
public override bool has_errors(IReadOnlyCollection<LegSpreaderParamsTuple> leg_tups) =>
|
||||
!leg_tups.Any(lt => lt.leg_params.EnableHedging);
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, bool value) {
|
||||
if (leg_tup.leg_params.SendHedge is null)
|
||||
leg_tup.leg_params.SendHedge = new bts.spark.NullableBoolean();
|
||||
leg_tup.leg_params.SendHedge.Val = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using mbts.ui.spark;
|
||||
using System;
|
||||
|
||||
namespace mbts.spark {
|
||||
partial class SyntheticEditorVM {
|
||||
class LeanOffsetTicksModel : RowModelBase<int> {
|
||||
public override string display_name { get; } = "Lean Offset Ticks";
|
||||
public override string help_text { get; } = "Improvement (in ticks) to the lean market";
|
||||
public override string man_page { get; } = string.Empty;
|
||||
|
||||
public override int get_value(LegSpreaderParamsTuple leg_tup) =>
|
||||
leg_tup.leg_params.QuoteParams?.LeanOffsetTicks ?? 0;
|
||||
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, int value) {
|
||||
if (leg_tup.leg_params.QuoteParams is null)
|
||||
leg_tup.leg_params.QuoteParams = new bts.spark.QuoteParams();
|
||||
leg_tup.leg_params.QuoteParams.LeanOffsetTicks = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
using bts.shell;
|
||||
using bts.spark;
|
||||
using mbts.ui.spark;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace mbts.spark {
|
||||
partial class SyntheticEditorVM {
|
||||
class QuoteTimeThrottleDelayToImproveModel : RowModelBase<uint> {
|
||||
readonly IDictionary<int, uint> _value_store = new Dictionary<int, uint>();
|
||||
|
||||
public override string display_name { get; } = "Delay to Improve (ms)";
|
||||
public override string help_text { get; } = string.Empty;
|
||||
public override string man_page { get; } = string.Empty;
|
||||
public override ParameterSection[] section_path { get; } = new[] { Sections.Quote, Subsections.TimeThrottle };
|
||||
|
||||
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
|
||||
_get_throttle(leg_tup).DelayToImprove = _value_from_store(leg_tup);
|
||||
|
||||
public override uint get_value(LegSpreaderParamsTuple leg_tup) =>
|
||||
_get_throttle(leg_tup) is QuoteTimeBasedThrottle throttle ?
|
||||
throttle.DelayToImprove :
|
||||
_value_from_store(leg_tup);
|
||||
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, uint value) {
|
||||
_value_store[leg_tup.id] = value;
|
||||
if (_get_throttle(leg_tup) is QuoteTimeBasedThrottle throttle)
|
||||
throttle.DelayToImprove = value;
|
||||
}
|
||||
|
||||
protected override bool _get_enabled(LegSpreaderParamsTuple leg_tup) =>
|
||||
_get_throttle(leg_tup) != null;
|
||||
|
||||
QuoteTimeBasedThrottle _get_throttle(LegSpreaderParamsTuple leg_tup) =>
|
||||
leg_tup.leg_params.QuoteParams.TimeBasedThrottle;
|
||||
|
||||
uint _value_from_store(LegSpreaderParamsTuple leg_tup) =>
|
||||
_value_store.GetValueOrDefault(leg_tup.id, _ => SyntheticDataHelper.Defaults.QuoteTimeBasedThrottle.DelayToImprove);
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
using bts.shell;
|
||||
using bts.spark;
|
||||
using mbts.ui.spark;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace mbts.spark {
|
||||
partial class SyntheticEditorVM {
|
||||
class QuoteTimeThrottleDelayToRunModel : RowModelBase<uint> {
|
||||
readonly IDictionary<int, uint> _value_store = new Dictionary<int, uint>();
|
||||
|
||||
public override string display_name { get; } = "Delay To Run (ms)";
|
||||
public override string help_text { get; } = string.Empty;
|
||||
public override string man_page { get; } = string.Empty;
|
||||
public override ParameterSection[] section_path { get; } = new[] { Sections.Quote, Subsections.TimeThrottle };
|
||||
|
||||
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
|
||||
_get_throttle(leg_tup).DelayToRun = _value_from_store(leg_tup);
|
||||
|
||||
public override uint get_value(LegSpreaderParamsTuple leg_tup) =>
|
||||
_get_throttle(leg_tup) is QuoteTimeBasedThrottle throttle ?
|
||||
throttle.DelayToRun :
|
||||
_value_from_store(leg_tup);
|
||||
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, uint value) {
|
||||
_value_store[leg_tup.id] = value;
|
||||
if (_get_throttle(leg_tup) is QuoteTimeBasedThrottle throttle)
|
||||
throttle.DelayToRun = value;
|
||||
}
|
||||
|
||||
protected override bool _get_enabled(LegSpreaderParamsTuple leg_tup) =>
|
||||
_get_throttle(leg_tup) != null;
|
||||
|
||||
QuoteTimeBasedThrottle _get_throttle(LegSpreaderParamsTuple leg_tup) =>
|
||||
leg_tup.leg_params.QuoteParams.TimeBasedThrottle;
|
||||
|
||||
uint _value_from_store(LegSpreaderParamsTuple leg_tup) =>
|
||||
_value_store.GetValueOrDefault(leg_tup.id, _ => SyntheticDataHelper.Defaults.QuoteTimeBasedThrottle.DelayToRun);
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
using bts.shell;
|
||||
using mbts.ui.spark;
|
||||
|
||||
namespace mbts.spark {
|
||||
partial class SyntheticEditorVM {
|
||||
class QuoteTimeThrottleEnabledModel : RowModelBase<bool> {
|
||||
readonly QuoteTimeThrottleDelayToRunModel _delay_to_run;
|
||||
readonly QuoteTimeThrottleDelayToImproveModel _delay_to_improve;
|
||||
|
||||
public QuoteTimeThrottleEnabledModel(QuoteTimeThrottleDelayToRunModel delay_to_run, QuoteTimeThrottleDelayToImproveModel delay_to_improve) {
|
||||
_delay_to_run = delay_to_run;
|
||||
_delay_to_improve = delay_to_improve;
|
||||
}
|
||||
|
||||
public override string display_name { get; } = string.Empty;
|
||||
public override string help_text { get; } = string.Empty;
|
||||
public override string man_page { get; } = string.Empty;
|
||||
public override ParameterSection[] section_path { get; } = new[] { Sections.Quote, Subsections.TimeThrottle };
|
||||
|
||||
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
|
||||
leg_tup.leg_params.QuoteParams.TimeBasedThrottle != null;
|
||||
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, bool value) {
|
||||
if (value) {
|
||||
if (leg_tup.leg_params.QuoteParams.TimeBasedThrottle == null) {
|
||||
leg_tup.leg_params.QuoteParams.TimeBasedThrottle = SyntheticDataHelper.Defaults.QuoteTimeBasedThrottle;
|
||||
_delay_to_run.apply_value(leg_tup);
|
||||
_delay_to_improve.apply_value(leg_tup);
|
||||
}
|
||||
} else {
|
||||
leg_tup.leg_params.QuoteParams.TimeBasedThrottle = null;
|
||||
}
|
||||
_delay_to_run.set_enabled(leg_tup, value);
|
||||
_delay_to_improve.set_enabled(leg_tup, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -108,6 +108,10 @@ namespace mbts.spark {
|
||||
"Reduces re-quoting updates by defining a region on either side " +
|
||||
"of the working quoting order, inside which quote updates will not be sent.");
|
||||
|
||||
public static ParameterSection TimeThrottle =>
|
||||
new ParameterSection("Time Throttle", true,
|
||||
"Reduces re-quoting updates by requiring a minimum amount of time to elapse between quotes.");
|
||||
|
||||
public static ParameterSection Conditional =>
|
||||
new ParameterSection("Conditional", true,
|
||||
"Reduces re-quoting updates by only quoting if N ticks away from the opposite " +
|
||||
|
||||
@@ -196,6 +196,9 @@ namespace mbts.spark {
|
||||
var quote_throttle_outside_ticks = new QuoteThrottleOutsideTicksModel();
|
||||
var quote_throttle_inside_ticks = new QuoteThrottleInsideTicksModel();
|
||||
|
||||
var quote_time_throttle_delay_to_run = new QuoteTimeThrottleDelayToRunModel();
|
||||
var quote_time_throttle_delay_to_improve = new QuoteTimeThrottleDelayToImproveModel();
|
||||
|
||||
var conditional_quoting_ticks = new ConditionalQuotingTicksModel();
|
||||
var conditional_quoting_price_type = new ConditionalQuotingPriceTypeModel();
|
||||
|
||||
@@ -223,17 +226,24 @@ namespace mbts.spark {
|
||||
_quantity_model,
|
||||
_price_mult_model,
|
||||
is_quote_model,
|
||||
//new EnableHedgeModel(), //TAHA_SPREADER
|
||||
new EnableHedgeModel(), //TAHA_SPREADER
|
||||
new HedgeRatioModel(),
|
||||
//new MinLeanQtyModel(), //TAHA_SPREADER
|
||||
new LeanOffsetTicksModel(),
|
||||
//new QuoteHiddenModel(),
|
||||
new QuoteQueueHolderModel(),
|
||||
new MarketDataTypeModel(),
|
||||
new ShowQuantityEnabledModel(show_quantity_quantity),
|
||||
show_quantity_quantity,
|
||||
// Throttle
|
||||
new QuoteThrottleEnabledModel(quote_throttle_inside_ticks, quote_throttle_outside_ticks),
|
||||
quote_throttle_inside_ticks,
|
||||
quote_throttle_outside_ticks,
|
||||
// Time Throttle
|
||||
new QuoteTimeThrottleEnabledModel(quote_time_throttle_delay_to_run, quote_time_throttle_delay_to_improve),
|
||||
quote_time_throttle_delay_to_run,
|
||||
quote_time_throttle_delay_to_improve,
|
||||
|
||||
new ConditionalQuoteEnabledModel(conditional_quoting_ticks, conditional_quoting_price_type),
|
||||
conditional_quoting_ticks,
|
||||
//conditional_quoting_price_type,
|
||||
|
||||
@@ -166,6 +166,10 @@ namespace mbts.spark {
|
||||
|
||||
[ProtoContract]
|
||||
class LadderMarketBreakLine : IEquatable<LadderMarketBreakLine> {
|
||||
public enum RefreshMode {
|
||||
Auto,
|
||||
Manual
|
||||
}
|
||||
// this class is 100% mutable (there are literally 0 readonly members),
|
||||
// so GetHashCode must return the same hash for every instance.
|
||||
static readonly int _type_hash = typeof(LadderMarketBreakLine).GetHashCode();
|
||||
@@ -173,6 +177,8 @@ namespace mbts.spark {
|
||||
public bool show { get; set; }
|
||||
[ProtoMember(2)]
|
||||
public uint color { get; set; }
|
||||
[ProtoMember(3)]
|
||||
public RefreshMode refresh_mode { get; set; }
|
||||
|
||||
public uint? color_nullable {
|
||||
get {
|
||||
@@ -185,7 +191,8 @@ namespace mbts.spark {
|
||||
public bool Equals(LadderMarketBreakLine other) =>
|
||||
other != null &&
|
||||
other.show == show &&
|
||||
other.color == color;
|
||||
other.color == color &&
|
||||
other.refresh_mode == refresh_mode;
|
||||
|
||||
public override bool Equals(object obj) =>
|
||||
Equals(obj as LadderMarketBreakLine);
|
||||
|
||||
@@ -61,9 +61,9 @@ namespace mbts.spark {
|
||||
_bid_mkt_line = new LadderMarketBreakLineVM("Bid"),
|
||||
_ask_mkt_line = new LadderMarketBreakLineVM("Ask"),
|
||||
_mid_mkt_line = new LadderMarketBreakLineVM("Mid"),
|
||||
_session_low_mkt_line = new LadderMarketBreakLineVM("Session Low", 2, 1),
|
||||
_session_high_mkt_line = new LadderMarketBreakLineVM("Session High", 2, 1, false),
|
||||
_session_range_fill = new LadderMarketBreakLineVM("Session Range", 0, 0, false);
|
||||
_session_low_mkt_line = new LadderMarketBreakLineVM("Session Low", 2, 1, can_edit_refresh_mode: false),
|
||||
_session_high_mkt_line = new LadderMarketBreakLineVM("Session High", 2, 1, false, can_edit_refresh_mode: false),
|
||||
_session_range_fill = new LadderMarketBreakLineVM("Session Range", 0, 0, false, can_edit_refresh_mode: false);
|
||||
OrderEntryPanelItemVisibilityVM
|
||||
_zoom_slider_visbility = new OrderEntryPanelItemVisibilityVM("Zoom Slider"),
|
||||
_day_visibility = new OrderEntryPanelItemVisibilityVM("Day Change"),
|
||||
@@ -601,12 +601,14 @@ namespace mbts.spark {
|
||||
public class LadderMarketBreakLineVM : ViewModelBase {
|
||||
readonly Property<Color> _color;
|
||||
readonly Property<bool> _show;
|
||||
LadderMarketBreakLine.RefreshMode _refresh_mode;
|
||||
|
||||
public LadderMarketBreakLineVM(string name, int column_index = 0, int column_span = 5, bool show_session_range = true) {
|
||||
public LadderMarketBreakLineVM(string name, int column_index = 0, int column_span = 5, bool show_session_range = true, bool can_edit_refresh_mode = true) {
|
||||
this.name = name;
|
||||
this.column_index = column_index;
|
||||
this.column_span = column_span;
|
||||
this.show_session_range = show_session_range;
|
||||
this.can_edit_refresh_mode = can_edit_refresh_mode;
|
||||
palettes = new ObservableCollection<ColorPaletteVM>(ColorPalette.all_presets().Select(p => new ColorPaletteVM(p)));
|
||||
_color = backing(nameof(color), Colors.Black);
|
||||
_show = backing(nameof(show), false);
|
||||
@@ -618,17 +620,21 @@ namespace mbts.spark {
|
||||
public Color color { get => _color.Value; set => _color.Value = value; }
|
||||
public bool show { get => _show.Value; set => _show.Value = value; }
|
||||
public bool show_session_range { get; }
|
||||
public bool can_edit_refresh_mode { get; }
|
||||
public LadderMarketBreakLine.RefreshMode refresh_mode { get => _refresh_mode; set => Set(ref _refresh_mode, value); }
|
||||
public ObservableCollection<ColorPaletteVM> palettes { get; }
|
||||
|
||||
public void assign_from(LadderMarketBreakLine settings) {
|
||||
color = settings.color.rgb_color();
|
||||
show = settings.show;
|
||||
refresh_mode = settings.refresh_mode;
|
||||
}
|
||||
|
||||
public LadderMarketBreakLine get_settings() =>
|
||||
new LadderMarketBreakLine {
|
||||
color = new BTSColor(color).ToUint(),
|
||||
show = show
|
||||
show = show,
|
||||
refresh_mode = refresh_mode
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,7 @@ using System.Windows.Media.Animation;
|
||||
namespace mbts.spark {
|
||||
partial class LadderGridHost : Control {
|
||||
const int _min_row_count = 501, _max_row_count = 2001;
|
||||
static readonly bool _show_scrollbar = config.Configuration.get<bts.config.LadderKnobs>().show_scrollbar;
|
||||
|
||||
int _row_count = _min_row_count;
|
||||
|
||||
@@ -82,6 +83,8 @@ namespace mbts.spark {
|
||||
_ordershost = new LadderOrdersHost(this) { HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Stretch };
|
||||
var scrollViewerFactory = new FrameworkElementFactory(typeof(ScrollViewer));
|
||||
scrollViewerFactory.SetValue(FocusableProperty, false);
|
||||
if (!_show_scrollbar)
|
||||
scrollViewerFactory.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Hidden);
|
||||
Template = new ControlTemplate() {
|
||||
VisualTree = scrollViewerFactory
|
||||
};
|
||||
@@ -713,8 +716,10 @@ namespace mbts.spark {
|
||||
// with meticulous attention to detail.
|
||||
_tick_sub = Disposable.Create(() => local_vm.on_tick -= _tick);
|
||||
_vm_sub = Disposable.Create(() => local_vm.request_recenter -= on_request_recenter);
|
||||
void on_request_recenter() =>
|
||||
void on_request_recenter() {
|
||||
RecenterCommand?.ExecuteIfCan(null);
|
||||
_refresh_frozen_mkt_lines();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -783,6 +788,14 @@ namespace mbts.spark {
|
||||
|
||||
#endregion
|
||||
|
||||
void _refresh_frozen_mkt_lines() {
|
||||
if (_price_list is null)
|
||||
return;
|
||||
_mkt_break_lines.refresh_frozen();
|
||||
_refresh_bid_mkt_break();
|
||||
_refresh_ask_mkt_break();
|
||||
_refresh_mid_mkt_break();
|
||||
}
|
||||
|
||||
void _on_vm_disposed(bool obj) =>
|
||||
_dispose_resources();
|
||||
@@ -814,6 +827,7 @@ namespace mbts.spark {
|
||||
} else {
|
||||
_scroll_to_row(_row_count / 2);
|
||||
}
|
||||
_refresh_frozen_mkt_lines();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -888,13 +902,28 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
void _refresh_bid_mkt_break() =>
|
||||
_render_mkt_break(_bid_mkt_break_vis, _mkt_break_lines.bid, _settings.bid_break_line.color);
|
||||
_render_mkt_break(
|
||||
_bid_mkt_break_vis,
|
||||
_settings.bid_break_line.refresh_mode == LadderMarketBreakLine.RefreshMode.Manual ?
|
||||
_mkt_break_lines.frozen_bid :
|
||||
_mkt_break_lines.bid,
|
||||
_settings.bid_break_line.color);
|
||||
|
||||
void _refresh_ask_mkt_break() =>
|
||||
_render_mkt_break(_ask_mkt_break_vis, _mkt_break_lines.ask, _settings.ask_break_line.color);
|
||||
_render_mkt_break(
|
||||
_ask_mkt_break_vis,
|
||||
_settings.ask_break_line.refresh_mode == LadderMarketBreakLine.RefreshMode.Manual ?
|
||||
_mkt_break_lines.frozen_ask :
|
||||
_mkt_break_lines.ask,
|
||||
_settings.ask_break_line.color);
|
||||
|
||||
void _refresh_mid_mkt_break() =>
|
||||
_render_mkt_break(_mid_mkt_break_vis, _mkt_break_lines.mid, _settings.mid_break_line.color);
|
||||
_render_mkt_break(
|
||||
_mid_mkt_break_vis,
|
||||
_settings.mid_break_line.refresh_mode == LadderMarketBreakLine.RefreshMode.Manual ?
|
||||
_mkt_break_lines.frozen_mid :
|
||||
_mkt_break_lines.mid,
|
||||
_settings.mid_break_line.color);
|
||||
|
||||
void _refresh_session_low_line() {
|
||||
if (_settings.session_low_line.show && _mkt_break_lines.low_render_index.HasValue)
|
||||
@@ -1170,6 +1199,7 @@ namespace mbts.spark {
|
||||
}
|
||||
}
|
||||
}
|
||||
_refresh_frozen_mkt_lines();
|
||||
_visualHost.AddVisualChild(_mid_mkt_break_vis);
|
||||
_visualHost.AddVisualChild(_ask_mkt_break_vis);
|
||||
_visualHost.AddVisualChild(_bid_mkt_break_vis);
|
||||
@@ -1265,7 +1295,8 @@ namespace mbts.spark {
|
||||
// Note: The values contained here do NOT necessarily represent true data, as they will be NaN/null if their respective visual is hidden in LadderSettings
|
||||
class MarketBreakLines {
|
||||
readonly LadderGridHost _owner;
|
||||
double _bid, _ask, _mid, _origin, _session_low, _session_high;
|
||||
double _bid = double.NaN, _ask = double.NaN, _mid = double.NaN, _origin, _session_low, _session_high;
|
||||
double _frozen_bid = double.NaN, _frozen_ask = double.NaN, _frozen_mid = double.NaN, _frozen_origin = double.NaN;
|
||||
int? _low_index, _high_index;
|
||||
|
||||
public MarketBreakLines(LadderGridHost owner) =>
|
||||
@@ -1279,6 +1310,11 @@ namespace mbts.spark {
|
||||
public bool session_range_dirty => session_low_dirty || session_high_dirty;
|
||||
public bool origin_dirty { get; private set; }
|
||||
|
||||
public double frozen_bid => double.IsNaN(_frozen_bid) ? (_frozen_bid = _bid) : _frozen_bid;
|
||||
public double frozen_ask => double.IsNaN(_frozen_ask) ? (_frozen_ask = _ask) : _frozen_ask;
|
||||
public double frozen_mid => double.IsNaN(_frozen_mid) ? (_frozen_mid = _mid) : _frozen_mid;
|
||||
public double frozen_origin => double.IsNaN(_frozen_origin) ? (_frozen_origin = _origin) : _frozen_origin;
|
||||
|
||||
public double bid => _bid;
|
||||
public double ask => _ask;
|
||||
public double mid => _mid;
|
||||
@@ -1322,7 +1358,14 @@ namespace mbts.spark {
|
||||
|
||||
LadderSettings _settings => _owner._settings;
|
||||
|
||||
public void refresh_frozen() {
|
||||
_refresh(true);
|
||||
}
|
||||
|
||||
public void refresh() {
|
||||
_refresh(false);
|
||||
}
|
||||
void _refresh(bool update_frozen) {
|
||||
bid_dirty = ConvertUtils.update_value_type(ref _bid, _settings.bid_break_line.show ? _owner._get_bid_market_break() : double.NaN);
|
||||
ask_dirty = ConvertUtils.update_value_type(ref _ask, _settings.ask_break_line.show ? _owner._get_ask_market_break() : double.NaN);
|
||||
mid_dirty = ConvertUtils.update_value_type(ref _mid, _settings.mid_break_line.show ? _owner._get_mid_market_break() : double.NaN);
|
||||
@@ -1342,6 +1385,11 @@ namespace mbts.spark {
|
||||
if (double.IsNaN(new_origin))
|
||||
new_origin = _owner._get_bid_market_break();
|
||||
origin_dirty = ConvertUtils.update_value_type(ref _origin, new_origin);
|
||||
if (update_frozen) {
|
||||
_frozen_bid = _bid;
|
||||
_frozen_ask = _ask;
|
||||
_frozen_mid = _mid;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,18 @@
|
||||
<cv:KeyValue Key="{u:Int 0}" Value="{u:Visibility Collapsed}"/>
|
||||
</cv:ValueMap>
|
||||
<c:BadgeTextLinesConverter x:Key="BadgeTextLinesConverter"/>
|
||||
<cv:ValueMap x:Key="RefreshModeToBooleanConverter">
|
||||
<cv:KeyValue Key="{x:Static Manual, MemberType={u:Nested sp:LadderMarketBreakLine.RefreshMode}}">
|
||||
<cv:KeyValue.Value>
|
||||
<sys:Boolean>false</sys:Boolean>
|
||||
</cv:KeyValue.Value>
|
||||
</cv:KeyValue>
|
||||
<cv:KeyValue Key="{x:Static Auto, MemberType={u:Nested sp:LadderMarketBreakLine.RefreshMode}}">
|
||||
<cv:KeyValue.Value>
|
||||
<sys:Boolean>true</sys:Boolean>
|
||||
</cv:KeyValue.Value>
|
||||
</cv:KeyValue>
|
||||
</cv:ValueMap>
|
||||
|
||||
<Style x:Key="ColumnBackground" TargetType="Rectangle">
|
||||
<Setter Property="Grid.RowSpan" Value="3"/>
|
||||
@@ -525,10 +537,12 @@
|
||||
<ColumnDefinition SharedSizeGroup="c2"/>
|
||||
<ColumnDefinition SharedSizeGroup="c3"/>
|
||||
<ColumnDefinition SharedSizeGroup="c4"/>
|
||||
<ColumnDefinition SharedSizeGroup="c5"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock Grid.Column="1" HorizontalAlignment="Center" Margin="6,0" Text="Show" VerticalAlignment="Center"/>
|
||||
<TextBlock Grid.Column="2" HorizontalAlignment="Center" Margin="6,0" Text="Color" VerticalAlignment="Center"/>
|
||||
<TextBlock Grid.Column="3" Grid.ColumnSpan="2" HorizontalAlignment="Center" Margin="6,0" Text="Sample" VerticalAlignment="Center"/>
|
||||
<TextBlock Grid.Column="2" HorizontalAlignment="Center" Margin="6,0" Text="Auto Refresh" VerticalAlignment="Center"/>
|
||||
<TextBlock Grid.Column="3" HorizontalAlignment="Center" Margin="6,0" Text="Color" VerticalAlignment="Center"/>
|
||||
<TextBlock Grid.Column="4" Grid.ColumnSpan="2" HorizontalAlignment="Center" Margin="6,0" Text="Sample" VerticalAlignment="Center"/>
|
||||
</Grid>
|
||||
<ItemsControl Grid.Row="1" ItemsSource="{Binding mkt_break_items}" Margin="8,0">
|
||||
<ItemsControl.ItemTemplate>
|
||||
@@ -540,20 +554,28 @@
|
||||
<ColumnDefinition SharedSizeGroup="c2"/>
|
||||
<ColumnDefinition SharedSizeGroup="c3"/>
|
||||
<ColumnDefinition SharedSizeGroup="c4"/>
|
||||
<ColumnDefinition SharedSizeGroup="c5"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Border Grid.Column="0" Background="{u:BTSColor header}" Padding="6,3">
|
||||
<TextBlock VerticalAlignment="Center" Text="{Binding name}" Foreground="{u:BTSColor header_text}"/>
|
||||
</Border>
|
||||
<CheckBox Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" IsChecked="{Binding show}"/>
|
||||
<c:ColorPickerPopup
|
||||
<CheckBox
|
||||
Grid.Column="2"
|
||||
HorizontalAlignment="Center"
|
||||
VerticalAlignment="Center"
|
||||
IsChecked="{Binding refresh_mode, Converter={StaticResource RefreshModeToBooleanConverter}, Mode=TwoWay}"
|
||||
IsEnabled="{Binding can_edit_refresh_mode}"
|
||||
/>
|
||||
<c:ColorPickerPopup
|
||||
Grid.Column="3"
|
||||
BorderBrush="Transparent"
|
||||
BorderThickness="0"
|
||||
PopupPlacement="Left"
|
||||
Palettes="{Binding palettes}"
|
||||
SelectedColor="{Binding color}"
|
||||
/>
|
||||
<Grid Grid.Column="3" Grid.ColumnSpan="2" Height="27">
|
||||
<Grid Grid.Column="4" Grid.ColumnSpan="2" Height="27">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition/>
|
||||
<ColumnDefinition/>
|
||||
@@ -623,7 +645,7 @@
|
||||
</Rectangle.Fill>
|
||||
</Rectangle>
|
||||
</Grid>
|
||||
<Rectangle Grid.Column="1" Grid.ColumnSpan="5" Fill="DimGray" Height="1" HorizontalAlignment="Stretch" VerticalAlignment="Bottom"/>
|
||||
<Rectangle Grid.Column="1" Grid.ColumnSpan="6" Fill="DimGray" Height="1" HorizontalAlignment="Stretch" VerticalAlignment="Bottom"/>
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
using bts.admin.risk;
|
||||
using bts.api.core;
|
||||
using bts.collections;
|
||||
using mbts;
|
||||
using mbts.ui;
|
||||
using mbts.ui.utility;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using Component = bts.shell.risk_management.RiskLimitsImportConflictsView.RiskLimitsComponent;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
static class RiskLimitsImporter {
|
||||
/// <summary>
|
||||
/// Parses the specified file and passes the results to the <paramref name="on_parsed"/> delegate.
|
||||
/// If the parser encounters improperly formatted values, a dialog is automatically opened
|
||||
/// </summary>
|
||||
/// <returns>An IDisposable that will close the import-conflicts-dialog (if it was launched).</returns>
|
||||
public static IDisposable import_limits(string file_name, IReadOnlyDictionary<uint, SecurityMD> security_map, IReadOnlyDictionary<uint, string> account_map, Action<IEnumerable<ParsedRiskLimits>> on_parsed) {
|
||||
if (string.IsNullOrEmpty(file_name))
|
||||
throw new ArgumentException("File name is null or empty.", nameof(file_name));
|
||||
if (security_map is null)
|
||||
throw new ArgumentNullException(nameof(security_map));
|
||||
if (account_map is null)
|
||||
throw new ArgumentNullException(nameof(account_map));
|
||||
if (on_parsed is null)
|
||||
throw new ArgumentNullException(nameof(on_parsed));
|
||||
IReadOnlyList<ParsedRiskLimits> parsed_limit_items;
|
||||
try {
|
||||
parsed_limit_items = RiskLimitsParser.parse_rows(
|
||||
File.ReadAllLines(file_name),
|
||||
MappedDictionary.create(security_map, sec_md => sec_md.security),
|
||||
account_map)
|
||||
.ToList();
|
||||
} catch (Exception ex) {
|
||||
BTSMessageBox.Error($"Error importing limits: {ex}.", RiskManagementWindow.window_type_display_name);
|
||||
return null;
|
||||
}
|
||||
var conflicts = RiskLimitsParser.get_conflicts(parsed_limit_items);
|
||||
if (conflicts.Count > 0) {
|
||||
// init vm
|
||||
var vm = new RiskLimitsImportVM(parsed_limit_items.Count) {
|
||||
security_map = security_map
|
||||
};
|
||||
// add rows
|
||||
foreach (var kv in conflicts) {
|
||||
var resolve_del = RiskLimitsParser.assign_component(kv.Key);
|
||||
foreach (var text_groups in kv.Value) {
|
||||
var eval = get_error_value(kv.Key);
|
||||
var row = new RiskLimitsImportVM.Row(kv.Key, text_groups.Key, text_groups.Value, eval, eval);
|
||||
vm.rows.Add(row);
|
||||
vm.import_request += () => {
|
||||
foreach (var pmf in text_groups.Value) {
|
||||
if (resolve_del(pmf.result, row.value) is AccountSecurityRiskLimits resolved)
|
||||
pmf.result = resolved;
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
var win = new RiskLimitsImportConflictsDialog {
|
||||
DataContext = vm,
|
||||
Title = RiskManagementWindow.window_type_display_name,
|
||||
Topmost = true
|
||||
};
|
||||
IDisposable dispose = null;
|
||||
vm.RequestClose += (s, e) => Disposable.dispose(ref dispose);
|
||||
vm.import_request += () => {
|
||||
on_parsed(parsed_limit_items);
|
||||
Disposable.dispose(ref dispose);
|
||||
};
|
||||
Disposable.dispose(ref dispose);
|
||||
vm.accounts.SetItems(account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).Cast<AccountTuple?>());
|
||||
dispose = Disposable.Create(
|
||||
vm,
|
||||
Disposable.Create(close));
|
||||
win.move_to_mouse(-200, -75);
|
||||
win.Show();
|
||||
return dispose;
|
||||
|
||||
void close() => WindowUtilities.force_close(win);
|
||||
object get_error_value(Component component) {
|
||||
switch (component) {
|
||||
case Component.MaxNetLongPosition:
|
||||
case Component.MaxNetShortPosition:
|
||||
case Component.ClipLimit:
|
||||
return 0;
|
||||
case Component.MinPrice:
|
||||
case Component.MaxPrice:
|
||||
return double.NaN;
|
||||
case Component.IsPositionLimitEnabled:
|
||||
case Component.IsClipLimitEnabled:
|
||||
case Component.IsPriceLimitEnabled:
|
||||
return false;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
on_parsed(parsed_limit_items);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
using bts.admin.risk;
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
using bts.utils;
|
||||
using mbts.ui.utility;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using RiskLimitsComponent = bts.shell.risk_management.RiskLimitsImportConflictsView.RiskLimitsComponent;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
class ParsedRiskLimits {
|
||||
public readonly Guid unpersisted_id = Guid.NewGuid();
|
||||
public AccountSecurityRiskLimits result { get; set; }
|
||||
|
||||
public (string text, bool success) security { get; set; }
|
||||
public (string text, bool success) account { get; set; }
|
||||
public (string text, bool success) max_long_position { get; set; }
|
||||
public (string text, bool success) max_short_position { get; set; }
|
||||
public (string text, bool success) is_position_limit_enabled { get; set; }
|
||||
public (string text, bool success) clip_limit { get; set; }
|
||||
public (string text, bool success) is_clip_limit_enabled { get; set; }
|
||||
public (string text, bool success) min_price { get; set; }
|
||||
public (string text, bool success) max_price { get; set; }
|
||||
public (string text, bool success) is_price_limit_enabled { get; set; }
|
||||
|
||||
public bool Equals(ParsedRiskLimits other) => other != null && unpersisted_id == other.unpersisted_id;
|
||||
public override bool Equals(object obj) => Equals(obj as ParsedRiskLimits);
|
||||
public override int GetHashCode() => unpersisted_id.GetHashCode();
|
||||
}
|
||||
|
||||
static class RiskLimitsParser {
|
||||
public const string file_extension = "csv";
|
||||
|
||||
public static Func<AccountSecurityRiskLimits, object, object> assign_component(RiskLimitsComponent component) {
|
||||
switch (component) {
|
||||
case RiskLimitsComponent.Security: return (mf, val) => mf.with(key: new AccountSecurityKey(mf.account_key, ConvertUtils.try_convert<SecurityImmutable?>(val)?.Id ?? 0));
|
||||
case RiskLimitsComponent.Account: return (mf, val) => mf.with(key: new AccountSecurityKey(ConvertUtils.try_convert<AccountTuple?>(val)?.id ?? 0, mf.key.security));
|
||||
case RiskLimitsComponent.MaxNetLongPosition: return (mf, val) => mf.with(mf.limits.with(max_long_position: ConvertUtils.try_convert<uint>(val)));
|
||||
case RiskLimitsComponent.MaxNetShortPosition: return (mf, val) => mf.with(mf.limits.with(max_short_position: ConvertUtils.try_convert<uint>(val)));
|
||||
case RiskLimitsComponent.IsPositionLimitEnabled: return (mf, val) => mf.with(mf.limits.with(is_price_limit_enabled: ConvertUtils.try_convert<bool>(val)));
|
||||
case RiskLimitsComponent.ClipLimit: return (mf, val) => mf.with(mf.limits.with(clip_limit: ConvertUtils.try_convert<uint>(val)));
|
||||
case RiskLimitsComponent.IsClipLimitEnabled: return (mf, val) => mf.with(mf.limits.with(is_price_limit_enabled: ConvertUtils.try_convert<bool>(val)));
|
||||
case RiskLimitsComponent.MinPrice: return (mf, val) => mf.with(mf.limits.with(min_price: ConvertUtils.try_convert(val, double.NaN)));
|
||||
case RiskLimitsComponent.MaxPrice: return (mf, val) => mf.with(mf.limits.with(max_price: ConvertUtils.try_convert(val, double.NaN)));
|
||||
case RiskLimitsComponent.IsPriceLimitEnabled: return (mf, val) => mf.with(mf.limits.with(is_price_limit_enabled: ConvertUtils.try_convert<bool>(val)));
|
||||
default: throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
|
||||
public static ImmutableDictionary<RiskLimitsComponent, ImmutableDictionary<string, ImmutableList<ParsedRiskLimits>>> get_conflicts(IEnumerable<ParsedRiskLimits> parsed_limits) {
|
||||
// Add all the components up front (a simple optimizatino since there aren't many),
|
||||
// so there is no need to check for there existence as various conflicts are added.
|
||||
// After all conflicts have been added, remove the empty entries.
|
||||
var missing_components = EnumHelper.get_values<RiskLimitsComponent>()
|
||||
.ToImmutableDictionary(c => c, c => ImmutableDictionary<string, ImmutableList<ParsedRiskLimits>>.Empty)
|
||||
.ToBuilder();
|
||||
foreach (var pmf in parsed_limits) {
|
||||
if (!pmf.security.success) {
|
||||
add_missing(RiskLimitsComponent.Security, pmf.security.text, pmf);
|
||||
}
|
||||
if (!pmf.account.success) {
|
||||
add_missing(RiskLimitsComponent.Account, pmf.account.text, pmf);
|
||||
}
|
||||
if (!pmf.max_long_position.success) {
|
||||
add_missing(RiskLimitsComponent.MaxNetLongPosition, pmf.max_long_position.text, pmf);
|
||||
}
|
||||
if (!pmf.max_short_position.success) {
|
||||
add_missing(RiskLimitsComponent.MaxNetShortPosition, pmf.max_short_position.text, pmf);
|
||||
}
|
||||
if (!pmf.is_position_limit_enabled.success) {
|
||||
add_missing(RiskLimitsComponent.IsPositionLimitEnabled, pmf.is_position_limit_enabled.text, pmf);
|
||||
}
|
||||
if (!pmf.clip_limit.success) {
|
||||
add_missing(RiskLimitsComponent.ClipLimit, pmf.clip_limit.text, pmf);
|
||||
}
|
||||
if (!pmf.is_clip_limit_enabled.success) {
|
||||
add_missing(RiskLimitsComponent.IsClipLimitEnabled, pmf.is_clip_limit_enabled.text, pmf);
|
||||
}
|
||||
if (!pmf.min_price.success) {
|
||||
add_missing(RiskLimitsComponent.MinPrice, pmf.min_price.text, pmf);
|
||||
}
|
||||
if (!pmf.max_price.success) {
|
||||
add_missing(RiskLimitsComponent.MaxPrice, pmf.max_price.text, pmf);
|
||||
}
|
||||
if (!pmf.is_price_limit_enabled.success) {
|
||||
add_missing(RiskLimitsComponent.IsPriceLimitEnabled, pmf.is_price_limit_enabled.text, pmf);
|
||||
}
|
||||
}
|
||||
// remove empty component conflicts
|
||||
var empty_keys = missing_components.Where(kv => kv.Value.Count == 0).Select(kv => kv.Key).ToList();
|
||||
missing_components.RemoveRange(empty_keys);
|
||||
return missing_components.ToImmutable();
|
||||
// local methods
|
||||
void add_missing(RiskLimitsComponent component, string text, ParsedRiskLimits prl) {
|
||||
if (!missing_components.TryGetValue(component, out var conflicts)) {
|
||||
conflicts = ImmutableDictionary<string, ImmutableList<ParsedRiskLimits>>.Empty;
|
||||
}
|
||||
if (!conflicts.TryGetValue(text, out var affected)) {
|
||||
affected = ImmutableList<ParsedRiskLimits>.Empty;
|
||||
}
|
||||
missing_components[component] = conflicts.SetItem(text, affected.Add(prl));
|
||||
}
|
||||
}
|
||||
|
||||
// This implementation prioritizes simplicity over speed.
|
||||
// The security desc lookup could be better optimized, but the speed at which limits are imported is probably not a paramount concern.
|
||||
public static IEnumerable<ParsedRiskLimits> parse_rows(IEnumerable<string> rows, IReadOnlyDictionary<uint, SecurityImmutable> security_map, IReadOnlyDictionary<uint, string> account_map) =>
|
||||
parse_rows(rows,
|
||||
reverse_lookup(MappedDictionary.create(security_map, s => s.ToString())),
|
||||
reverse_lookup(account_map));
|
||||
|
||||
public static IEnumerable<ParsedRiskLimits> parse_rows(IEnumerable<string> rows, Func<string, uint> security_id_lookup, Func<string, uint> account_id_lookup) {
|
||||
var columns = new[] {
|
||||
(Headers.Security, Cells.security(security_id_lookup)),
|
||||
(Headers.Account, Cells.account(account_id_lookup)),
|
||||
(Headers.MaxNetLongPosition, Cells.max_long_position),
|
||||
(Headers.MaxNetShortPosition, Cells.max_short_position),
|
||||
(Headers.IsPositionLimitEnabled, Cells.is_position_limit_enabled),
|
||||
(Headers.ClipLimit, Cells.clip_limit),
|
||||
(Headers.IsClipLimitEnabled, Cells.is_clip_limit_enabled),
|
||||
(Headers.MinPrice, Cells.min_price),
|
||||
(Headers.MaxPrice, Cells.max_price),
|
||||
(Headers.IsPriceLimitEnabled, Cells.is_price_limit_enabled)
|
||||
}.ToDictionary(col => col.Item1, col => col.Item2.with_null_check());
|
||||
return RowParser.parse_rows(rows, columns, Cells.delimiter);
|
||||
}
|
||||
|
||||
public static Func<string, TKey> reverse_lookup<TKey>(IReadOnlyDictionary<TKey, string> map) {
|
||||
var lookup = map.ToLookup(kv => kv.Value, kv => kv.Key);
|
||||
return cell_text => lookup.Contains(cell_text) ? lookup[cell_text].First() : default;
|
||||
}
|
||||
|
||||
static class Headers {
|
||||
public const string
|
||||
Security = "Security",
|
||||
Account = "Account",
|
||||
MaxNetLongPosition = "Max Long",
|
||||
MaxNetShortPosition = "Max Short",
|
||||
IsPositionLimitEnabled = "Enforce Position",
|
||||
ClipLimit = "Clip",
|
||||
IsClipLimitEnabled = "Enforce Clip",
|
||||
MinPrice = "Min Price",
|
||||
MaxPrice = "Max Price",
|
||||
IsPriceLimitEnabled = "Enforce Price";
|
||||
}
|
||||
|
||||
static class Cells {
|
||||
public const char delimiter = ',';
|
||||
|
||||
public static RowParser.AssignColumnValue<ParsedRiskLimits> security(Func<string, uint> reverse_id_lookup) {
|
||||
return impl;
|
||||
void impl(ref ParsedRiskLimits pmf, string text) {
|
||||
pmf.result = pmf.result.with(key: new AccountSecurityKey(pmf.result.key.account, reverse_id_lookup(text)));
|
||||
pmf.security = (text, pmf.result.key.security != 0);
|
||||
}
|
||||
}
|
||||
|
||||
public static RowParser.AssignColumnValue<ParsedRiskLimits> account(Func<string, uint> reverse_id_lookup) {
|
||||
return impl;
|
||||
void impl(ref ParsedRiskLimits pmf, string text) {
|
||||
pmf.result = pmf.result.with(key: new AccountSecurityKey(reverse_id_lookup(text), pmf.result.key.security));
|
||||
pmf.account = (text, pmf.result.key.account != 0);
|
||||
}
|
||||
}
|
||||
|
||||
public static void max_long_position(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (uint.TryParse(cell_text, out uint v)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(max_long_position: v));
|
||||
pmf.max_long_position = (cell_text, true);
|
||||
} else {
|
||||
pmf.max_long_position = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void max_short_position(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (uint.TryParse(cell_text, out uint v)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(max_short_position: v));
|
||||
pmf.max_short_position = (cell_text, true);
|
||||
} else {
|
||||
pmf.max_short_position = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void is_position_limit_enabled(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (_try_parse_yes_no(cell_text, out var result)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(is_position_limit_enabled: result));
|
||||
pmf.is_position_limit_enabled = (cell_text, true);
|
||||
} else {
|
||||
pmf.is_position_limit_enabled = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void clip_limit(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (uint.TryParse(cell_text, out uint v)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(clip_limit: v));
|
||||
pmf.clip_limit = (cell_text, true);
|
||||
} else {
|
||||
pmf.clip_limit = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void is_clip_limit_enabled(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (_try_parse_yes_no(cell_text, out var result)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(is_clip_limit_enabled: result));
|
||||
pmf.is_clip_limit_enabled = (cell_text, true);
|
||||
} else {
|
||||
pmf.is_clip_limit_enabled = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
static bool _try_parse_yes_no(string text, out bool result) {
|
||||
switch (text?.Trim()?.ToLower()) {
|
||||
case "y": result = true; break;
|
||||
case "n": result = false; break;
|
||||
default: result = default; return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void min_price(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (double.TryParse(cell_text, out var v)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(min_price: v));
|
||||
pmf.min_price = (cell_text, true);
|
||||
} else {
|
||||
pmf.min_price = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void max_price(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (double.TryParse(cell_text, out var v)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(max_price: v));
|
||||
pmf.max_price = (cell_text, true);
|
||||
} else {
|
||||
pmf.max_price = (cell_text, false);
|
||||
}
|
||||
}
|
||||
|
||||
public static void is_price_limit_enabled(ref ParsedRiskLimits pmf, string cell_text) {
|
||||
if (_try_parse_yes_no(cell_text, out var result)) {
|
||||
pmf.result = pmf.result.with(pmf.result.limits.with(is_price_limit_enabled: result));
|
||||
pmf.is_price_limit_enabled = (cell_text, true);
|
||||
} else {
|
||||
pmf.is_price_limit_enabled = (cell_text, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
using bts.admin.risk;
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
using bts.spark;
|
||||
using bts.view;
|
||||
using mbts;
|
||||
using mbts.persist;
|
||||
using mbts.spark;
|
||||
@@ -18,15 +20,15 @@ using System.Windows.Data;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
class RiskManagementWindow : SparkWindow<RiskManagementSettings>, ISharedWindow {
|
||||
const string
|
||||
_window_type_id = "RiskManagement",
|
||||
_window_type_display_name = "Risk Management";
|
||||
public const string
|
||||
window_type_id = "RiskManagement",
|
||||
window_type_display_name = "Risk Management";
|
||||
|
||||
readonly IWindowSettingsManager<GridSettings> _settings_manager;
|
||||
readonly AdminModel _model;
|
||||
FrameworkElement _view;
|
||||
IReadOnlyList<SparkCommand> _commands;
|
||||
IDisposable _settings_sub, _securities_sub;
|
||||
IDisposable _settings_sub, _securities_sub, _cmd_subscriptions;
|
||||
RiskManagementSettings _settings;
|
||||
RiskManagementVM _vm;
|
||||
SimpleGridSettingsManagerVM<RiskManagementControl.Columns> _grid_settings_manager => _vm.grid_settings_manager;
|
||||
@@ -39,17 +41,17 @@ namespace bts.shell.risk_management {
|
||||
IWindowSettingsManager<GridSettings> settings_manager,
|
||||
ISaveWindow<RiskManagementSettings> isw,
|
||||
RiskManagementSettings settings)
|
||||
: base(_window_type_display_name, bus, isw, Icons.Risk) {
|
||||
: base(window_type_display_name, bus, isw, Icons.Risk) {
|
||||
//
|
||||
_settings_manager = settings_manager;
|
||||
_settings = settings;
|
||||
_model = model;
|
||||
thread_id = mbts.config.Configuration.get<bts.config.MultiThreadedWindows>().risk_management ? "OrderBook" : null;
|
||||
thread_id = mbts.config.Configuration.get<bts.config.MultiThreadedWindows>().risk_management ? window_type_id : null;
|
||||
_securities_sub = bus.subscribe(SparkTags.SecuritiesTag).Subscribe(sec_map => _security_map = sec_map);
|
||||
}
|
||||
|
||||
public override IEnumerable<SparkCommand> Commands => _commands;
|
||||
public override string window_type => _window_type_id;
|
||||
public override string window_type => window_type_id;
|
||||
|
||||
public override RiskManagementSettings SaveState =>
|
||||
(_vm?.create() ?? RiskManagementSettings.Default).with(menu_display: _menu_display_vm.safe_create());
|
||||
@@ -65,6 +67,7 @@ namespace bts.shell.risk_management {
|
||||
public string thread_id { get; }
|
||||
|
||||
public override void Dispose() {
|
||||
Disposable.dispose(ref _cmd_subscriptions);
|
||||
_commands.empty_if_null().OfType<IDisposable>().DisposeAll();
|
||||
Disposable.dispose(ref _securities_sub);
|
||||
Disposable.dispose(ref _settings_sub);
|
||||
@@ -79,31 +82,42 @@ namespace bts.shell.risk_management {
|
||||
Log.assert(_settings_sub == null, "Grid settings subscription has already been initialized.");
|
||||
// initialize everything: menu_display_vm, vm, settings subscription, and view
|
||||
_menu_display_vm = _init_menu_display_vm(_settings.menu_display);
|
||||
_vm = _init_vm(_model, _settings);
|
||||
_vm = _init_vm(_bus.subscribe(SparkTags.SecuritiesTag), _model, _settings);
|
||||
_settings_sub = _settings_manager.subscribe_current()
|
||||
.OnDispatcher()
|
||||
.Subscribe(gs => _vm.load_from(gs));
|
||||
_commands = new List<SparkCommand>(_mk_commands());
|
||||
(_commands, _cmd_subscriptions) = _mk_commands();
|
||||
_view = new RiskManagementControl { DataContext = _vm };
|
||||
}
|
||||
|
||||
protected override void OnParentViewCreated(SparkWindowView parent_view) =>
|
||||
_menu_display_vm.safe_bind_to_view(parent_view);
|
||||
|
||||
static SparkMenuDisplayVM _init_menu_display_vm(SparkMenuDisplaySettings settings) {
|
||||
var vm = new SparkMenuDisplayVM();
|
||||
vm.load_from(settings);
|
||||
return vm;
|
||||
}
|
||||
|
||||
static RiskManagementVM _init_vm(AdminModel model, RiskManagementSettings settings) {
|
||||
static RiskManagementVM _init_vm(IObservable<IReadOnlyDictionary<uint, SecurityMD>> securities_source, AdminModel model, RiskManagementSettings settings) {
|
||||
var vm = new RiskManagementVM(model.account_security_risk_limits, model.on_account_tuples);
|
||||
vm.request_update_limit += update_limit;
|
||||
vm.load_from(settings);
|
||||
var vm_sec_sub = securities_source.OnDispatcher().Subscribe(sec_map => vm.security_map = sec_map);
|
||||
vm.OnDisposed += _ => Disposable.dispose(ref vm_sec_sub);
|
||||
return vm;
|
||||
void update_limit(AccountSecurityRiskLimits lim) =>
|
||||
model.add_or_update_risk_limits(lim.account_key, new[] { (lim.security_key, lim.limits) }).ignore();
|
||||
void update_limit(AccountSecurityRiskLimits lim) {
|
||||
model.set_risk_limits(
|
||||
MappedDictionary.create(
|
||||
vm.build_account_limits_map(), acc_sec_lims => acc_sec_lims.Select(asl => (asl.security_key, asl.limits))))
|
||||
.ignore();
|
||||
}
|
||||
}
|
||||
|
||||
IEnumerable<SparkCommand> _mk_commands() {
|
||||
yield return new SparkCommandCommand("Add New Limits", Icons.AddBoxes, new DialogCommand(() => {
|
||||
(List<SparkCommand> cmds, IDisposable subscriptions) _mk_commands() {
|
||||
var subs = new List<IDisposable>();
|
||||
var cmds = new List<SparkCommand>();
|
||||
cmds.Add(new SparkCommandCommand("Add New Limits", Icons.AddBoxes, new DialogCommand(() => {
|
||||
if (_vm is null)
|
||||
return null;
|
||||
var account_id = _vm.selected_account?.id ?? 0;
|
||||
@@ -122,33 +136,60 @@ namespace bts.shell.risk_management {
|
||||
}
|
||||
}
|
||||
}
|
||||
}));
|
||||
var edit_selected_rows_cmd = new DialogCommand(() => {
|
||||
})));
|
||||
var edit_cmd = new DialogCommand(() => {
|
||||
if (!(_vm?.selected_account).HasValue)
|
||||
return null;
|
||||
var account_id = _vm.selected_account.Value.id;
|
||||
var targets = _vm.selected_rows.Select(r => r.create()).ToList();
|
||||
var targets = _vm.selected_rows.Select(r => r.data).ToList();
|
||||
var init_state = RiskLimitsModification.aggregate_common_props(targets);
|
||||
return mk_row_editor_dialog(init_state, commit, false);
|
||||
void commit(RiskLimitsModification mod) =>
|
||||
_model.add_or_update_risk_limits(account_id, targets.Select(r => (r.security_key, mod.apply(r.limits)))).ignore();
|
||||
_vm.modify_rows(targets.WrapSelector(t => t.key, null), mod);
|
||||
}, () => _vm.selected_rows.Count > 0, true, off_x: -300, off_y: -60);
|
||||
_vm.selected_rows_changed += edit_selected_rows_cmd.RaiseCanExecuteChanged;
|
||||
yield return new SparkCommandCommand("Edit Selected Rows", Icons.ModifyOrder, edit_selected_rows_cmd);
|
||||
_vm.selected_rows_changed += edit_cmd.RaiseCanExecuteChanged;
|
||||
cmds.Add(new SparkCommandCommand("Edit Selected Rows", Icons.ModifyOrder, edit_cmd));
|
||||
var revert_selected_rows_cmd = ObservantCommand.create(() => _vm?.revert(_vm.selected_rows), out var revert_selected_rows_observer);
|
||||
subs.Add(_vm.subscribe_selected_rows()
|
||||
.Select(srs => srs.Count > 0)
|
||||
.And(_vm.subscribe_has_dirty_rows())
|
||||
.OnDispatcher()
|
||||
.Subscribe(revert_selected_rows_observer));
|
||||
cmds.Add(new SparkCommandCommand("Revert Selected Rows", Icons.UndoCircular, revert_selected_rows_cmd));
|
||||
|
||||
var delete_selected_rows_cmd = new DelegateCommand(() => {
|
||||
cmds.Add(new SparkCommandCommand("Import Limits", Icons.Import,
|
||||
FileDialogCommand.open_file(file => _vm?.import_limits(file), extensions: RiskLimitsParser.file_extension)));
|
||||
|
||||
var save_cmd = new SparkCommandCommand("Save", Icons.Disk, ObservantCommand.create(() => {
|
||||
//_vm.selected_account.Value.id, _vm.rows.Where(r => r.)
|
||||
var lims = _vm.build_account_limits_map();
|
||||
var mlims = MappedDictionary.create(lims, l => l.Select(lim => (lim.security_key, lim.limits)));
|
||||
_model.set_risk_limits(mlims).ignore();
|
||||
}, out var save_observer));
|
||||
cmds.Add(save_cmd);
|
||||
subs.Add(_vm.subscribe_has_dirty_rows().OnDispatcher().Subscribe(save_observer));
|
||||
|
||||
var delete_cmd = new DelegateCommand(() => {
|
||||
if (!(_vm?.selected_account).HasValue)
|
||||
return;
|
||||
var selected_rows = _vm.selected_rows;
|
||||
var to_remove = _vm.selected_rows;
|
||||
var account_id = _vm.selected_account.Value.id;
|
||||
if (BTSMessageBox.Confirm($"Are you sure you want to delete the selected limits ({selected_rows.Count})?", "Delete Limits"))
|
||||
_model.delete_risk_limits(account_id, selected_rows.Select(r => r.security_key)).ignore();
|
||||
if (BTSMessageBox.Confirm($"Are you sure you want to delete the selected limits ({to_remove.Count})?", "Delete Limits")) {
|
||||
// remove unpersisted limits first (i.e., imports), then delete the persisted ones.
|
||||
foreach (var r in to_remove) {
|
||||
if (!r.is_persisted) {
|
||||
_vm.rows.RemoveSorted(r, _vm.row_comparer);
|
||||
to_remove = to_remove.Remove(r);
|
||||
}
|
||||
}
|
||||
_model.delete_risk_limits(account_id, to_remove.Select(r => r.security_key)).ignore();
|
||||
}
|
||||
}, () => _vm.selected_rows.Count > 0);
|
||||
_vm.selected_rows_changed += delete_selected_rows_cmd.RaiseCanExecuteChanged;
|
||||
_vm.selected_rows_changed += delete_cmd.RaiseCanExecuteChanged;
|
||||
|
||||
yield return new SparkCommandCommand("Delete", Icons.Trash, delete_selected_rows_cmd);
|
||||
cmds.Add(new SparkCommandCommand("Delete", Icons.Trash, delete_cmd));
|
||||
// wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes
|
||||
yield return SparkCommands.window_settings_command(new DialogCommand(() => {
|
||||
cmds.Add(SparkCommands.window_settings_command(new DialogCommand(() => {
|
||||
if (_vm is null)
|
||||
return null;
|
||||
_settings_manager.instance_settings = _vm.create().grid;
|
||||
@@ -162,8 +203,9 @@ namespace bts.shell.risk_management {
|
||||
var dialog = new ShellSettingsDialog { DataContext = settings_vm };
|
||||
settings_vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog);
|
||||
return dialog;
|
||||
}));
|
||||
yield return _menu_display_vm.spark_cmd;
|
||||
})));
|
||||
cmds.Add(_menu_display_vm.spark_cmd);
|
||||
return (cmds, Disposable.wrap_collection(subs));
|
||||
|
||||
// although only the api only requires security keys,
|
||||
// the actual securities are used in this method so the user can see them in the view
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
using mbts;
|
||||
using mbts.collections;
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Input;
|
||||
using Component = bts.shell.risk_management.RiskLimitsImportConflictsView.RiskLimitsComponent;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
class RiskLimitsImportVM : DisposableViewModelBase, IRequestViewClose {
|
||||
readonly RefCountMap<ParsedRiskLimits> _conflicts = new RefCountMap<ParsedRiskLimits>();
|
||||
IReadOnlyDictionary<uint, SecurityMD> _security_map = DictionaryHelper.empty<uint, SecurityMD>();
|
||||
|
||||
public RiskLimitsImportVM(int num_limits) {
|
||||
rows_view = CollectionViewSource.GetDefaultView(rows);
|
||||
ok_cmd = new DelegateCommand(() => import_request?.Invoke());
|
||||
cancel_cmd = new DelegateCommand(() => RequestClose?.Invoke(this, new EventArgs()));
|
||||
this.num_limits = num_limits;
|
||||
_dispose = ObservableAutoWrapper.connect_item_hooks(rows, r =>
|
||||
r.subscribe_has_error().Subscribe(has_error => {
|
||||
if (has_error) {
|
||||
if (r.affected_limits.Count(_conflicts.increment_adds_key) == 0)
|
||||
return;
|
||||
} else if (r.affected_limits.Count(_conflicts.decrement_removes_key) == 0)
|
||||
return;
|
||||
RaisePropertyChanged(nameof(num_successfully_parsed_limits));
|
||||
}));
|
||||
}
|
||||
|
||||
public event Action import_request;
|
||||
public event EventHandler RequestClose;
|
||||
|
||||
public ObservableCollection<Row> rows { get; } = new ObservableCollection<Row>();
|
||||
public ICollectionView rows_view { get; }
|
||||
public int num_limits { get; }
|
||||
public int num_successfully_parsed_limits => num_limits - _conflicts.Count;
|
||||
// misc items sources
|
||||
public IEnumerable<Side> sides => new[] { Side.Buy, Side.Sell };
|
||||
public ObservableCollection<AccountTuple?> accounts { get; } = new ObservableCollection<AccountTuple?>();
|
||||
public IReadOnlyDictionary<uint, SecurityMD> security_map {
|
||||
get => _security_map;
|
||||
set {
|
||||
if (!ReferenceEquals(_security_map, value)) {
|
||||
_security_map = value;
|
||||
_resolve_securities();
|
||||
RaisePropertyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
// commands
|
||||
public ICommand ok_cmd { get; }
|
||||
public ICommand cancel_cmd { get; }
|
||||
|
||||
void _resolve_securities() {
|
||||
if (_security_map == null)
|
||||
return;
|
||||
var reverse_lookup = RiskLimitsParser.reverse_lookup(MappedDictionary.create(_security_map, v => v.security.ToString()));
|
||||
foreach (var r in rows) {
|
||||
if (r.component == Component.Security && r.has_error) {
|
||||
var id = reverse_lookup(r.text);
|
||||
if (id != 0 && _security_map.TryGetValue(id, out var smd))
|
||||
r.value = smd.security;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class Row : ViewModelBase, ITemplateSelectorKey {
|
||||
readonly DelegateProperty<bool> _has_error;
|
||||
object _value;
|
||||
string _text;
|
||||
|
||||
public Row(Component component, string text, IReadOnlyCollection<ParsedRiskLimits> affected_limits, object error_value, object value) {
|
||||
this.component = component;
|
||||
this.text = text;
|
||||
this.affected_limits = affected_limits;
|
||||
_value = value;
|
||||
_has_error = backing(nameof(has_error), () => Equals(this.value, error_value));
|
||||
}
|
||||
|
||||
public Component component { get; }
|
||||
public string text { get => _text; set => Set(ref _text, value); }
|
||||
public IReadOnlyCollection<ParsedRiskLimits> affected_limits { get; }
|
||||
public object value {
|
||||
get => _value;
|
||||
set {
|
||||
if (Set(ref _value, value))
|
||||
_has_error.refresh();
|
||||
}
|
||||
}
|
||||
public bool has_error => _has_error.Value;
|
||||
string ITemplateSelectorKey.key => component.ToString();
|
||||
|
||||
public IObservable<bool> subscribe_has_error() => _has_error.observe_current(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -87,6 +87,7 @@ namespace bts.shell.risk_management {
|
||||
public RiskLimitsModification(
|
||||
SecurityImmutable? security = null,
|
||||
SecurityCriteria security_criteria = null,
|
||||
AccountTuple? account = null,
|
||||
uint? max_long_position = null,
|
||||
uint? max_short_position = null,
|
||||
bool? is_position_limit_enabled = null,
|
||||
@@ -98,6 +99,7 @@ namespace bts.shell.risk_management {
|
||||
//
|
||||
this.security = security;
|
||||
this.security_criteria = security_criteria;
|
||||
this.account = account;
|
||||
this.max_long_position = max_long_position;
|
||||
this.max_short_position = max_short_position;
|
||||
this.is_position_limit_enabled = is_position_limit_enabled;
|
||||
@@ -110,6 +112,7 @@ namespace bts.shell.risk_management {
|
||||
|
||||
public SecurityImmutable? security { get; }
|
||||
public SecurityCriteria security_criteria { get; }
|
||||
public AccountTuple? account { get; }
|
||||
// position
|
||||
public uint? max_long_position { get; }
|
||||
public uint? max_short_position { get; }
|
||||
@@ -126,6 +129,7 @@ namespace bts.shell.risk_management {
|
||||
new RiskLimitsModification(
|
||||
_common_value(limit_items, l => l.security, s => s),
|
||||
null,
|
||||
_common_value(limit_items, l => new AccountTuple(l.account_key, l.account_name)),
|
||||
_common_value(limit_items, l => l.limits.max_long_position),
|
||||
_common_value(limit_items, l => l.limits.max_short_position),
|
||||
_common_value(limit_items, l => l.limits.is_position_limit_enabled),
|
||||
@@ -146,8 +150,25 @@ namespace bts.shell.risk_management {
|
||||
min_price: min_price ?? target.min_price,
|
||||
max_price: max_price ?? target.max_price);
|
||||
|
||||
public RiskLimitsModification with(RiskLimitsModification other_mod) =>
|
||||
with(
|
||||
other_mod.security.HasValue ? other_mod.security.Value : security,
|
||||
other_mod.account.HasValue ? other_mod.account.Value : account,
|
||||
security_criteria: other_mod.security_criteria ?? security_criteria,
|
||||
max_long_position: other_mod.max_long_position ?? max_long_position,
|
||||
max_short_position: other_mod.max_short_position ?? max_short_position,
|
||||
is_position_limit_enabled: other_mod.is_position_limit_enabled ?? is_position_limit_enabled,
|
||||
clip_limit: other_mod.clip_limit ?? clip_limit,
|
||||
is_clip_limit_enabled: other_mod.is_clip_limit_enabled ?? is_clip_limit_enabled,
|
||||
min_price: other_mod.min_price ?? min_price,
|
||||
max_price: other_mod.max_price ?? max_price,
|
||||
is_price_limit_enabled: other_mod.is_price_limit_enabled ?? is_price_limit_enabled);
|
||||
//new RiskLimitsModification(security: other_mod.security ?? security,
|
||||
// security_criteria: other_mod.security ?? security);
|
||||
|
||||
public RiskLimitsModification with(
|
||||
OptionalNullable<SecurityImmutable>? security = null,
|
||||
OptionalNullable<AccountTuple>? account = null,
|
||||
SecurityCriteria security_criteria = null,
|
||||
OptionalNullable<uint>? max_long_position = null,
|
||||
OptionalNullable<uint>? max_short_position = null,
|
||||
@@ -161,6 +182,7 @@ namespace bts.shell.risk_management {
|
||||
new RiskLimitsModification(
|
||||
security.HasValue ? security.Value.value : this.security,
|
||||
security_criteria ?? this.security_criteria,
|
||||
account.HasValue ? account.Value.value : this.account,
|
||||
max_long_position.HasValue ? max_long_position.Value.value : this.max_long_position,
|
||||
max_short_position.HasValue ? max_short_position.Value.value : this.max_short_position,
|
||||
is_position_limit_enabled.HasValue ? is_position_limit_enabled.Value.value : this.is_position_limit_enabled,
|
||||
|
||||
@@ -1,89 +1,114 @@
|
||||
using bts.admin.risk;
|
||||
using bts.api;
|
||||
using bts.utils;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
class RiskLimitsVM : ViewModelBase, IValueFactory<AccountSecurityRiskLimits> {
|
||||
readonly DeferrableActionWrapper _result_changed;
|
||||
// The user can modify some props directly in the grid.
|
||||
// However, the sorting relies on immutable data
|
||||
// (binary search may break if the applicable comparisons change,
|
||||
// depending on the current sorting criteria).
|
||||
// As a work-around, the rows are sorted by the committed_data.
|
||||
// Any modifications made through the prop setters are assumed to be 'user-changes'
|
||||
// (as the props are bound to the view),
|
||||
/// and the committed data is only changed through <see cref="load_from(AccountSecurityRiskLimits)"/>.
|
||||
AccountSecurityRiskLimits _committed_data, _mutable_data;
|
||||
class RiskLimitsVM : ViewModelBase, IEquatable<RiskLimitsVM> {
|
||||
RiskLimitsVM(AccountSecurityKey id) =>
|
||||
this.id = id;
|
||||
|
||||
public RiskLimitsVM() =>
|
||||
_result_changed = new DeferrableActionWrapper(() => result_changed?.Invoke());
|
||||
public event Action request_commit;
|
||||
|
||||
public RiskLimitsVM(AccountSecurityRiskLimits data) : this() {
|
||||
_committed_data = data;
|
||||
_mutable_data = data;
|
||||
}
|
||||
/// The user can modify some props directly in the grid,
|
||||
/// which may or may not give the row a new sort-position.
|
||||
/// For this reason, the owner-viewmodel (<see cref="RiskManagementVM"/>)
|
||||
/// is notified both immediately before, and after the changes are reflected in <see cref="data"/>.
|
||||
/// By responding to those events, the owner-viewmodel can safely process any
|
||||
/// sorting-changes without breaking binary search functionality.
|
||||
/// <see cref="value_changing"/>, <see cref="value_changed"/>
|
||||
|
||||
public event Action result_changed;
|
||||
/// <summary>
|
||||
/// This event is raised just before a new value is assigned to <see cref="data"/>.
|
||||
/// </summary>
|
||||
public event Action<(AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value)> value_changing;
|
||||
/// <summary>
|
||||
/// This event is raised immediately after a new value is assigned to <see cref="data"/>.
|
||||
/// </summary>
|
||||
public event Action<(AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value)> value_changed;
|
||||
public event Action is_dirty_changed;
|
||||
|
||||
public SecurityImmutable? security => _committed_data.security;
|
||||
public uint security_key => _committed_data.security_key;
|
||||
public string account_name => _committed_data.account_name;
|
||||
public uint account_key => _committed_data.account_key;
|
||||
public AccountSecurityKey id { get; }
|
||||
public SecurityImmutable? security => data.security;
|
||||
public string security_text => is_persisted ? security.ToString() : $"*{security}";
|
||||
public uint security_key => data.security_key;
|
||||
public string account_name => data.account_name;
|
||||
public uint account_key => data.key.account;
|
||||
// position limit
|
||||
public bool is_position_limit_enabled { get => _mutable_limits.is_position_limit_enabled; set => _set_limits(_mutable_limits.with(is_position_limit_enabled: value)); }
|
||||
public uint max_long_position { get => _mutable_limits.max_long_position; set => _set_limits(_mutable_limits.with(max_long_position: value)); }
|
||||
public uint max_short_position { get => _mutable_limits.max_short_position; set => _set_limits(_mutable_limits.with(max_short_position: value)); }
|
||||
public bool is_position_limit_enabled { get => _limits.is_position_limit_enabled; set => _modify(new RiskLimitsModification(is_position_limit_enabled: value)); }
|
||||
public uint max_long_position { get => _limits.max_long_position; set => _modify(new RiskLimitsModification(max_long_position: value)); }
|
||||
public uint max_short_position { get => _limits.max_short_position; set => _modify(new RiskLimitsModification(max_short_position: value)); }
|
||||
// clip limit
|
||||
public bool is_clip_limit_enabled { get => _mutable_limits.is_clip_limit_enabled; set => _set_limits(_mutable_limits.with(is_clip_limit_enabled: value)); }
|
||||
public uint clip_limit { get => _mutable_limits.clip_limit; set => _set_limits(_mutable_limits.with(clip_limit: value)); }
|
||||
public bool is_clip_limit_enabled { get => _limits.is_clip_limit_enabled; set => _modify(new RiskLimitsModification(is_clip_limit_enabled: value)); }
|
||||
public uint clip_limit { get => _limits.clip_limit; set => _modify(new RiskLimitsModification(clip_limit: value)); }
|
||||
// price limit
|
||||
public bool is_price_limit_enabled { get => _mutable_limits.is_price_limit_enabled; set => _set_limits(_mutable_limits.with(is_price_limit_enabled: value)); }
|
||||
public double max_price { get => _mutable_limits.max_price; set => _set_limits(_mutable_limits.with(max_price: value)); }
|
||||
public double min_price { get => _mutable_limits.min_price; set => _set_limits(_mutable_limits.with(min_price: value)); }
|
||||
public AccountSecurityKey row_id => new AccountSecurityKey(account_key, security_key);
|
||||
public AccountSecurityRiskLimits committed_data => _committed_data;
|
||||
public bool is_price_limit_enabled { get => _limits.is_price_limit_enabled; set => _modify(new RiskLimitsModification(is_price_limit_enabled: value)); }
|
||||
public double min_price { get => _limits.min_price; set => _modify(new RiskLimitsModification(min_price: value)); }
|
||||
public double max_price { get => _limits.max_price; set => _modify(new RiskLimitsModification(max_price: value)); }
|
||||
|
||||
RiskLimits _mutable_limits {
|
||||
get => _mutable_data.limits;
|
||||
set => _mutable_data = _mutable_data.with(limits: value);
|
||||
public bool is_persisted => committed_data.HasValue;
|
||||
public bool is_dirty => !committed_data.HasValue || !committed_data.Value.Equals(data);
|
||||
|
||||
public AccountSecurityRiskLimits data { get; private set; }
|
||||
public AccountSecurityRiskLimits? committed_data { get; private set; }
|
||||
RiskLimits _limits => data.limits;
|
||||
|
||||
public static RiskLimitsVM create_placeholder(AccountSecurityRiskLimits state) {
|
||||
var vm = new RiskLimitsVM(state.key);
|
||||
vm.load(state, false);
|
||||
return vm;
|
||||
}
|
||||
|
||||
public AccountSecurityRiskLimits create() => _mutable_data;
|
||||
public static RiskLimitsVM create_persisted(AccountSecurityRiskLimits state) {
|
||||
var vm = new RiskLimitsVM(state.key);
|
||||
vm.load(state, true);
|
||||
return vm;
|
||||
}
|
||||
|
||||
public void load_from(AccountSecurityRiskLimits value) {
|
||||
using (_result_changed.defer_execution())
|
||||
public void load(AccountSecurityRiskLimits new_state, bool is_committed) {
|
||||
using (detect_property_changes()) {
|
||||
_committed_data = value;
|
||||
_mutable_data = value;
|
||||
bool was_dirty = is_dirty;
|
||||
if (is_committed)
|
||||
committed_data = new_state;
|
||||
if (!data.Equals(new_state)) {
|
||||
value_changing?.Invoke((data, new_state));
|
||||
var orig_state = data;
|
||||
data = new_state;
|
||||
value_changed?.Invoke((orig_state, new_state));
|
||||
}
|
||||
if (is_dirty != was_dirty)
|
||||
is_dirty_changed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public void apply_modifications(RiskLimitsModification m) =>
|
||||
load_from(_committed_data.with(
|
||||
_committed_data.limits.with(m.is_position_limit_enabled,
|
||||
m.max_long_position,
|
||||
m.max_short_position,
|
||||
m.is_clip_limit_enabled,
|
||||
m.clip_limit,
|
||||
m.is_price_limit_enabled,
|
||||
m.min_price,
|
||||
m.max_short_position),
|
||||
new AccountTuple(_committed_data.account_key, _committed_data.account_name),
|
||||
m.security));
|
||||
public bool Equals(RiskLimitsVM other) =>
|
||||
other != null && id == other.id;
|
||||
|
||||
void _set_limits(RiskLimits new_limits, [CallerMemberName] string prop = "") =>
|
||||
_set_limits(new_limits, new[] { prop });
|
||||
public override bool Equals(object obj) =>
|
||||
Equals(obj as RiskLimitsVM);
|
||||
|
||||
void _set_limits(RiskLimits new_limits, params string[] invalidate_props) {
|
||||
if (!_mutable_limits.Equals(new_limits)) {
|
||||
_mutable_limits = new_limits;
|
||||
RaisePropertyChanged(invalidate_props);
|
||||
_result_changed.execute();
|
||||
public override int GetHashCode() =>
|
||||
id.GetHashCode();
|
||||
|
||||
void _modify(RiskLimitsModification mod) {
|
||||
var new_value = data.with(limits: mod.apply(data.limits));
|
||||
if (committed_data.HasValue) {
|
||||
// if the user just toggled one of the limits on/off, request an immediate update to persist the change
|
||||
// (the on/off toggles are the only props that can be edited directly in the grid,
|
||||
// the user might find it annoying if they have to click 'Save' just to turn the limits on/off.
|
||||
var clims = committed_data.Value.limits;
|
||||
load(new_value, false);
|
||||
var revert_mod = new RiskLimitsModification(is_position_limit_enabled: clims.is_position_limit_enabled, is_clip_limit_enabled: clims.is_clip_limit_enabled, is_price_limit_enabled: clims.is_price_limit_enabled);
|
||||
var reverted_lims = new_value = new_value.with(limits: revert_mod.apply(new_value.limits));
|
||||
if (reverted_lims.limits.Equals(clims)) {
|
||||
// since only the limit toggle props were reverted,
|
||||
// the above equality indicates that only the limit toggle props were modified.
|
||||
request_commit?.Invoke();
|
||||
}
|
||||
} else {
|
||||
load(new_value, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,27 +36,32 @@ namespace bts.shell.risk_management {
|
||||
.wrap<AccountSecurityKey, AccountSecurityRiskLimits>(r => r.key);
|
||||
|
||||
static IComparer<RiskLimitsVM> _row_id_comparer =>
|
||||
_data_row_id_comparer.wrap<AccountSecurityRiskLimits, RiskLimitsVM>(r => r.committed_data);
|
||||
_data_row_id_comparer.wrap<AccountSecurityRiskLimits, RiskLimitsVM>(r => r.data);
|
||||
|
||||
readonly DeferrableActionWrapper _result_changed, _refresh_filter_changed, _selected_rows_changed;
|
||||
readonly DeferrableActionWrapper _refresh_filter_changed, _selected_rows_changed, _dirty_rows_changed;
|
||||
readonly ColumnSortManager _sort_manager;
|
||||
readonly ObservableCollection<RiskManagementColumnModel> _columns = new ObservableCollection<RiskManagementColumnModel>();
|
||||
readonly Dictionary<Columns, RiskManagementColumnModel> _column_map = new Dictionary<Columns, RiskManagementColumnModel>();
|
||||
readonly SelectorVM<AccountTuple?, uint> _accounts_vm = new SelectorVM<AccountTuple?, uint>(acc => acc?.id ?? 0) { comparer = Comparer<AccountTuple>.Default.to_nullable() };
|
||||
IReadOnlyDictionary<AccountSecurityKey, AccountSecurityRiskLimits> _cache = DictionaryHelper.empty<AccountSecurityKey, AccountSecurityRiskLimits>();
|
||||
ImmutableSortedSet<RiskLimitsVM> _selected_rows = ImmutableSortedSet.Create(_row_id_comparer);
|
||||
IList<AccountSecurityRiskLimits> _data_rows;
|
||||
ImmutableSortedSet<RiskLimitsVM> _selected_rows = ImmutableSortedSet.Create(_row_id_comparer);
|
||||
IComparer<AccountSecurityRiskLimits> _data_comparer = _data_row_id_comparer;
|
||||
IComparer<RiskLimitsVM> _row_comparer;
|
||||
IDisposable _import_limits_op;
|
||||
ImmutableDictionary<AccountSecurityKey, RiskLimitsVM> _dirty_rows = ImmutableDictionary<AccountSecurityKey, RiskLimitsVM>.Empty;
|
||||
Dictionary<AccountSecurityKey, RiskLimitsVM> _imported_row_map = new Dictionary<AccountSecurityKey, RiskLimitsVM>();
|
||||
Dictionary<AccountSecurityKey, RiskLimitsVM> _row_cache = new Dictionary<AccountSecurityKey, RiskLimitsVM>();
|
||||
|
||||
public RiskManagementVM(IObservable<TableUpdate<AccountSecurityRiskLimits, AccountSecurityKey>> data_source, IObservable<IReadOnlyList<AccountTuple>> accounts_source) {
|
||||
_result_changed = new DeferrableActionWrapper(() => result_changed?.Invoke());
|
||||
_selected_rows_changed = new DeferrableActionWrapper(() => selected_rows_changed?.Invoke());
|
||||
_refresh_filter_changed = new DeferrableActionWrapper(() => _filter_changed?.Invoke(_mk_filter()));
|
||||
_dirty_rows_changed = new DeferrableActionWrapper(() => dirty_rows_changed?.Invoke(dirty_rows));
|
||||
_sort_manager = new ColumnSortManager(_columns.OfType<ISortableDIYGridColumn>(), null);
|
||||
_data_rows = rows.WrapSelector(r => r.committed_data, lim => new RiskLimitsVM(lim));
|
||||
_sort_manager.active_sorting_changed += () =>
|
||||
data_comparer = _sort_manager.BuildComparer(id => _find_column(id)?.row_comparer, _data_comparer);
|
||||
_data_rows = rows.WrapSelector(r => r.data, null);
|
||||
_accounts_vm.selected_item_changed += () => {
|
||||
RaisePropertyChanged(nameof(selected_account));
|
||||
_result_changed.execute();
|
||||
_refresh_filter_changed.execute();
|
||||
};
|
||||
column_map = FunctionalIndex.create<string, RiskManagementColumnModel>(_find_column);
|
||||
@@ -66,7 +71,6 @@ namespace bts.shell.risk_management {
|
||||
throw new InvalidOperationException();
|
||||
}, c => c.id.ToString(), cs => cs.id);
|
||||
}, null);
|
||||
_refresh_filter_changed = new DeferrableActionWrapper(() => _filter_changed?.Invoke(_mk_filter()));
|
||||
/////////////////
|
||||
// Columns
|
||||
/////////////////
|
||||
@@ -155,6 +159,7 @@ namespace bts.shell.risk_management {
|
||||
}).to_comparer();
|
||||
_column_map = _columns.ToDictionary(c => c.id);
|
||||
columns = ObservableAutoWrapper.SelectObservable(_columns, c => c);
|
||||
|
||||
var filter_source =
|
||||
Observable.FromEvent<Func<AccountSecurityRiskLimits, bool>>(cb => _filter_changed += cb, cb => _filter_changed -= cb)
|
||||
.StartWith(_mk_filter);
|
||||
@@ -166,6 +171,7 @@ namespace bts.shell.risk_management {
|
||||
f.filter_changed += _refresh_filter_changed.execute;
|
||||
return Disposable.Create(() => f.filter_changed -= _refresh_filter_changed.execute);
|
||||
}).ToList();
|
||||
_accounts_vm.selected_item_changed += on_selected_account_changed;
|
||||
_dispose = Disposable.Create(
|
||||
ObservableAutoWrapper.connect_item_hooks(rows, subscribe_row_changes),
|
||||
accounts_source.OnDispatcher().Subscribe(on_accounts),
|
||||
@@ -209,13 +215,31 @@ namespace bts.shell.risk_management {
|
||||
return col;
|
||||
}
|
||||
|
||||
IDisposable subscribe_row_changes(RiskLimitsVM r) {
|
||||
r.result_changed += on_limits_changed;
|
||||
return Disposable.Create(() => r.result_changed -= on_limits_changed);
|
||||
void on_limits_changed() {
|
||||
var lim = r.create();
|
||||
if (_cache.TryGetValue(lim.key, out var curr_lim) && !lim.Equals(curr_lim))
|
||||
request_update_limit?.Invoke(lim);
|
||||
IDisposable subscribe_row_changes(RiskLimitsVM row) {
|
||||
row.value_changing += on_value_changing;
|
||||
row.value_changed += on_value_changed;
|
||||
row.request_commit += on_request_commit;
|
||||
check_dirty();
|
||||
return Disposable.Create(() => {
|
||||
row.value_changing -= on_value_changing;
|
||||
row.value_changed -= on_value_changed;
|
||||
row.request_commit -= on_request_commit;
|
||||
});
|
||||
|
||||
void on_value_changing((AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value) change) =>
|
||||
on_row_data_changed(new Change<AccountSecurityRiskLimits>(change.old_value, change.new_value), false);
|
||||
|
||||
void on_value_changed((AccountSecurityRiskLimits old_value, AccountSecurityRiskLimits new_value) change) =>
|
||||
check_dirty();
|
||||
|
||||
void on_request_commit() =>
|
||||
request_update_limit?.Invoke(row.data);
|
||||
|
||||
void check_dirty() {
|
||||
int dr_count = _dirty_rows.Count;
|
||||
_dirty_rows = row.is_dirty ? _dirty_rows.Add(row.id, row) : _dirty_rows.Remove(row.id);
|
||||
if (dr_count != _dirty_rows.Count)
|
||||
_dirty_rows_changed.execute();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -223,22 +247,85 @@ namespace bts.shell.risk_management {
|
||||
_accounts_vm.update_items(new_accounts.Cast<AccountTuple?>());
|
||||
|
||||
void on_data(TableUpdate<AccountSecurityRiskLimits, AccountSecurityKey> table) {
|
||||
_cache = table.state;
|
||||
var comp = data_comparer;
|
||||
_data_rows.RemoveSorted(table.removed.Concat(table.changes.Old()), comp);
|
||||
_data_rows.InsertSorted(table.added.Concat(table.changes.New()), comp);
|
||||
using (_dirty_rows_changed.defer_execution())
|
||||
using (_selected_rows_changed.defer_execution()) {
|
||||
foreach (var lim in table.removed) {
|
||||
if (_row_cache.TryGetValue(lim.key, out var row)) {
|
||||
_data_rows.RemoveSorted(row.data, data_comparer);
|
||||
if (row.committed_data.HasValue)
|
||||
_row_cache.Remove(lim.key);
|
||||
}
|
||||
}
|
||||
foreach (var ch in table.changes) {
|
||||
on_row_data_changed(ch, true);
|
||||
}
|
||||
foreach (var lim in table.added) {
|
||||
if (_row_cache.TryGetValue(lim.key, out var row)) {
|
||||
// if row is already here, it must be an import
|
||||
// overwrite the import with the persisted row (this probably won't happen in practice)
|
||||
rows.RemoveSorted(row, row_comparer);
|
||||
_imported_row_map.Remove(lim.key);
|
||||
}
|
||||
var new_row = RiskLimitsVM.create_persisted(lim);
|
||||
_row_cache[lim.key] = new_row;
|
||||
rows.InsertSorted(new_row, row_comparer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void on_row_data_changed(Change<AccountSecurityRiskLimits> change, bool is_persisted) {
|
||||
Log.assert(_row_cache.TryGetValue(change.Old.key, out var row));
|
||||
int old_index = CollectionHelper.binary_search(rows, row, row_comparer);
|
||||
Log.assert(old_index >= 0);
|
||||
int new_index = CollectionHelper.binary_search(_data_rows, change.New, _data_comparer);
|
||||
// if the change came from the server (i.e., a persisted change that the row-vm doesn't already know about),
|
||||
// load the new data (current modifications will be overwritten).
|
||||
// Otherwise, the change is presumably the result of an uncommitted user-edit, which the row must already know about.
|
||||
if (is_persisted) {
|
||||
row.load(change.New, true);
|
||||
if (_dirty_rows.Remove(row.id, out _dirty_rows))
|
||||
_dirty_rows_changed.execute();
|
||||
}
|
||||
if (new_index < 0)
|
||||
new_index = ~new_index;
|
||||
if (Math.Abs(new_index - old_index) > 1) {
|
||||
if (new_index > old_index)
|
||||
new_index--;
|
||||
rows.Move(old_index, new_index);
|
||||
}
|
||||
}
|
||||
|
||||
void on_selected_account_changed() {
|
||||
foreach (var ir in _imported_row_map.Values) {
|
||||
if (ir.account_key == selected_account?.id) {
|
||||
rows.InsertOrReplaceSorted(ir, row_comparer);
|
||||
} else {
|
||||
rows.RemoveSorted(ir, row_comparer);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public event Action result_changed, selected_rows_changed;
|
||||
public event Action selected_rows_changed;
|
||||
public event Action<AccountSecurityRiskLimits> request_update_limit;
|
||||
public event Action<ImmutableDictionary<AccountSecurityKey, RiskLimitsVM>> dirty_rows_changed;
|
||||
event Action<Func<AccountSecurityRiskLimits, bool>> _filter_changed;
|
||||
|
||||
public IReadOnlyIndex<string, RiskManagementColumnModel> column_map { get; }
|
||||
public bool has_unpersisted_limits => false;
|
||||
// this collection is needed to control the column order
|
||||
public IReadOnlyObservableCollection<IDIYGridColumn> columns { get; }
|
||||
public ObservableCollection<RiskLimitsVM> rows { get; } = new ObservableCollection<RiskLimitsVM>();
|
||||
public IReadOnlyList<RiskLimitsVM> selected_rows => _selected_rows;
|
||||
/// <summary>
|
||||
/// The selected rows are provided as an <see cref="ImmutableSortedSet{T}"/> so they can be observed/accessed on different threads.
|
||||
/// <see cref="RiskManagementVMExtensions.subscribe_selected_rows(RiskManagementVM)"/>.
|
||||
/// </summary>
|
||||
public ImmutableSortedSet<RiskLimitsVM> selected_rows => _selected_rows;
|
||||
/// <summary>
|
||||
/// The dirty rows are provided as an <see cref="ImmutableDictionary{TKey, TValue}"/> so they can be observed/accessed on different threads.
|
||||
/// <see cref="RiskManagementVMExtensions.subscribe_has_dirty_rows(RiskManagementVM)(RiskManagementVM)"/>.
|
||||
/// </summary>
|
||||
public ImmutableDictionary<AccountSecurityKey, RiskLimitsVM> dirty_rows => _dirty_rows;
|
||||
public IReadOnlyObservableCollection<AccountTuple?> accounts => _accounts_vm.items;
|
||||
public AccountTuple? selected_account {
|
||||
get => _accounts_vm.selected_item ?? default;
|
||||
@@ -251,13 +338,20 @@ namespace bts.shell.risk_management {
|
||||
if (value != null) {
|
||||
_data_comparer = value;
|
||||
_row_comparer = null;
|
||||
_data_rows.sync_with(_data_rows.Ordered(value).ToList());
|
||||
rows.sync_with(rows.Ordered(row_comparer));
|
||||
_selected_rows = _selected_rows.WithComparer(row_comparer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public IComparer<RiskLimitsVM> row_comparer =>
|
||||
_row_comparer ?? (_row_comparer = data_comparer?.wrap<AccountSecurityRiskLimits, RiskLimitsVM>(r => r.committed_data));
|
||||
_row_comparer ?? (_row_comparer = data_comparer?.wrap<AccountSecurityRiskLimits, RiskLimitsVM>(r => r.data));
|
||||
|
||||
public IReadOnlyDictionary<uint, SecurityMD> security_map { get; set; } = DictionaryHelper.empty<uint, SecurityMD>();
|
||||
|
||||
public IReadOnlyDictionary<uint, IEnumerable<AccountSecurityRiskLimits>> build_account_limits_map() =>
|
||||
_data_rows.GroupBy(dr => dr.account_key)
|
||||
.ToDictionary(g => g.Key, g => g.AsEnumerable());
|
||||
|
||||
public RiskManagementSettings create() {
|
||||
var grid = grid_settings_manager.create();
|
||||
@@ -268,9 +362,10 @@ namespace bts.shell.risk_management {
|
||||
public void load_from(RiskManagementSettings settings) {
|
||||
if (settings is null)
|
||||
throw new ArgumentNullException(nameof(settings));
|
||||
using (_result_changed.defer_execution()) {
|
||||
if (settings.grid != null)
|
||||
grid_settings_manager.load_from(settings.grid);
|
||||
if (settings.grid != null)
|
||||
grid_settings_manager.load_from(settings.grid);
|
||||
_sort_manager.SortingCriteria = settings.sorting_criteria;
|
||||
using (_refresh_filter_changed.defer_execution()) {
|
||||
foreach (var col in _columns)
|
||||
col.load_from(null, settings.filters);
|
||||
_accounts_vm.try_select(settings.account_id, true);
|
||||
@@ -280,8 +375,49 @@ namespace bts.shell.risk_management {
|
||||
public void load_from(GridSettings grid) {
|
||||
if (grid is null)
|
||||
throw new ArgumentNullException(nameof(grid));
|
||||
using (_result_changed.defer_execution())
|
||||
grid_settings_manager.load_from(grid);
|
||||
grid_settings_manager.load_from(grid);
|
||||
}
|
||||
|
||||
public void modify_rows(IEnumerable<AccountSecurityKey> targets, RiskLimitsModification mod) {
|
||||
foreach (var key in targets) {
|
||||
if (_row_cache.TryGetValue(key, out var row)) {
|
||||
var new_data = row.data.with(limits: mod.apply(row.data.limits));
|
||||
row.load(new_data, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void revert(IEnumerable<RiskLimitsVM> targets) {
|
||||
foreach (var row in targets) {
|
||||
if (row.committed_data.HasValue)
|
||||
row.load(row.committed_data.Value, true);
|
||||
}
|
||||
}
|
||||
|
||||
public void import_limits(string file_name) {
|
||||
Disposable.dispose(ref _import_limits_op);
|
||||
_import_limits_op = RiskLimitsImporter.import_limits(file_name,
|
||||
security_map,
|
||||
accounts.Where(a => a.HasValue)
|
||||
.ToDictionary(a => a.Value.id, a => a.Value.name),
|
||||
add_imported_rows);
|
||||
|
||||
void add_imported_rows(IEnumerable<ParsedRiskLimits> imported_rows) {
|
||||
foreach (var ir in imported_rows) {
|
||||
var res = ir.result;
|
||||
if (!res.security.HasValue && security_map.TryGetValue(res.security_key, out var sec_md))
|
||||
res = res.with(security: sec_md.security);
|
||||
if (string.IsNullOrEmpty(res.account_name) && accounts.TryGetFirst(a => a?.id == res.account_key, out var acc))
|
||||
res = res.with(account: acc);
|
||||
if (_row_cache.TryGetValue(res.key, out var old_row))
|
||||
rows.RemoveSorted(old_row, row_comparer);
|
||||
var new_row = RiskLimitsVM.create_placeholder(res);
|
||||
_row_cache[res.key] = new_row;
|
||||
_imported_row_map[res.key] = new_row;
|
||||
if (new_row.account_key == selected_account?.id)
|
||||
rows.InsertSorted(new_row, row_comparer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void IHandleRowSelection.row_selection_changed(SelectionChangedEventArgs e) {
|
||||
@@ -293,7 +429,7 @@ namespace bts.shell.risk_management {
|
||||
|
||||
void IHandleGridSorting.on_sorting(object sender, DIYGridSortingEventArgs e) {
|
||||
_sort_manager.OnColumnClick(e.Column, KeyboardExtensions.IsShiftDown());
|
||||
data_comparer = _sort_manager.BuildComparer(id => _find_column(id)?.row_comparer, _data_comparer);
|
||||
e.Handled = true;
|
||||
}
|
||||
|
||||
RiskManagementColumnModel _find_column(string key_str) =>
|
||||
@@ -310,4 +446,33 @@ namespace bts.shell.risk_management {
|
||||
return lim => lim.account_key == acc_id && (col_filter_pred is null || col_filter_pred(lim));
|
||||
}
|
||||
}
|
||||
|
||||
static class RiskManagementVMExtensions {
|
||||
public static IObservable<ImmutableSortedSet<RiskLimitsVM>> subscribe_selected_rows(this RiskManagementVM vm) =>
|
||||
vm is null ?
|
||||
throw new ArgumentNullException(nameof(vm)) :
|
||||
Observable.Create<ImmutableSortedSet<RiskLimitsVM>>(o => {
|
||||
o.OnNext(vm.selected_rows);
|
||||
vm.selected_rows_changed += on_selected_rows_changed;
|
||||
return Disposable.Create(() => vm.selected_rows_changed -= on_selected_rows_changed);
|
||||
void on_selected_rows_changed() =>
|
||||
o.OnNext(vm.selected_rows);
|
||||
})
|
||||
.SubscribeOnDispatcher();
|
||||
|
||||
public static IObservable<bool> subscribe_has_dirty_rows(this RiskManagementVM vm) =>
|
||||
vm is null ?
|
||||
throw new ArgumentNullException(nameof(vm)) :
|
||||
Observable.Create<bool>(o => {
|
||||
bool last_fired = vm.dirty_rows.Count > 0;
|
||||
o.OnNext(last_fired);
|
||||
vm.dirty_rows_changed += on_dirty_rows_changed;
|
||||
return Disposable.Create(() => vm.dirty_rows_changed -= on_dirty_rows_changed);
|
||||
void on_dirty_rows_changed(ImmutableDictionary<AccountSecurityKey, RiskLimitsVM> drs) {
|
||||
if (last_fired != drs.Count > 0)
|
||||
o.OnNext(last_fired = !last_fired);
|
||||
}
|
||||
})
|
||||
.SubscribeOnDispatcher();
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
<Window
|
||||
x:Class="bts.shell.risk_management.RiskLimitsImportConflictsDialog"
|
||||
x:ClassModifier="internal"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:risk="clr-namespace:bts.shell.risk_management"
|
||||
xmlns:u="clr-namespace:mbts.ui"
|
||||
xmlns:c="clr-namespace:mbts.ui.controls"
|
||||
u:WindowStyle.AllowResize="True"
|
||||
u:WindowStyle.SizeToContent="WidthAndHeight"
|
||||
u:WindowStyle.TitleContent="Import Limits Conflicts"
|
||||
Style="{StaticResource BTSDialogTitleTemplate}"
|
||||
>
|
||||
<u:WindowStyle.TitleContentTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
|
||||
<Image Height="12" Margin="5,2" Source="{x:Static u:Icons.Import}"/>
|
||||
<TextBlock Margin="4,0,0,0" Text="{Binding}"/>
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</u:WindowStyle.TitleContentTemplate>
|
||||
<Window.Content>
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="*"/>
|
||||
<RowDefinition Height="Auto"/>
|
||||
</Grid.RowDefinitions>
|
||||
<risk:RiskLimitsImportConflictsView Margin="12,10,12,8"/>
|
||||
<c:DialogSkirt Grid.Row="1">
|
||||
<c:DialogSkirt.RightItems>
|
||||
<x:Array Type="{x:Type Button}">
|
||||
<Button Command="{Binding ok_cmd}">Continue</Button>
|
||||
<Button Command="{Binding cancel_cmd}" IsCancel="True">Cancel</Button>
|
||||
</x:Array>
|
||||
</c:DialogSkirt.RightItems>
|
||||
</c:DialogSkirt>
|
||||
</Grid>
|
||||
</Window.Content>
|
||||
</Window>
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
using System.Windows;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
/// <summary>
|
||||
/// Interaction logic for RiskLimitsImportConflictsDialog.xaml
|
||||
/// </summary>
|
||||
partial class RiskLimitsImportConflictsDialog : Window {
|
||||
public RiskLimitsImportConflictsDialog() =>
|
||||
InitializeComponent();
|
||||
}
|
||||
}
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
<UserControl
|
||||
x:Class="bts.shell.risk_management.RiskLimitsImportConflictsView"
|
||||
x:ClassModifier="internal"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:risk="clr-namespace:bts.shell.risk_management"
|
||||
xmlns:u="clr-namespace:mbts.ui"
|
||||
xmlns:c="clr-namespace:mbts.ui.controls"
|
||||
xmlns:cv="clr-namespace:mbts.ui.converters"
|
||||
MinWidth="400"
|
||||
>
|
||||
<UserControl.Resources>
|
||||
<Style x:Key="VerticallyCenteredText" TargetType="TextBlock">
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
</Style>
|
||||
<DataTemplate x:Key="UIntTemplate">
|
||||
<c:TickUpDownUInt Value="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
|
||||
</DataTemplate>
|
||||
<DataTemplate x:Key="DoubleTemplate">
|
||||
<c:TickUpDownDouble Value="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
|
||||
</DataTemplate>
|
||||
<DataTemplate x:Key="BooleanTemplate">
|
||||
<CheckBox IsChecked="{Binding value}"/>
|
||||
</DataTemplate>
|
||||
<DataTemplate x:Key="PriceReadTemplate">
|
||||
<TextBlock Text="{Binding value, Converter={StaticResource DoubleTextConverter}}" VerticalAlignment="Center"/>
|
||||
</DataTemplate>
|
||||
<!--Value Cell Template Selector-->
|
||||
<u:KeyedTemplateSelector x:Key="ValueCellTemplateSelector">
|
||||
<u:KeyedTemplateSelector.Default>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding value}" VerticalAlignment="Center"/>
|
||||
</DataTemplate>
|
||||
</u:KeyedTemplateSelector.Default>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MinPrice, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource PriceReadTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MaxPrice, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource PriceReadTemplate}"/>
|
||||
</u:KeyedTemplateSelector>
|
||||
<!--Value Cell Editing Template Selector-->
|
||||
<u:KeyedTemplateSelector x:Key="ValueCellEditingTemplateSelector">
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static Security, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}">
|
||||
<DataTemplate>
|
||||
<c:ContractPickerPopup
|
||||
HorizontalAlignment="Stretch"
|
||||
VerticalAlignment="Stretch"
|
||||
CloseOnCancel="True"
|
||||
CloseOnOK="True"
|
||||
Header="{Binding value}"
|
||||
IsEditMode="False"
|
||||
IsLazy="True"
|
||||
SecurityMap="{Binding DataContext.security_map, RelativeSource={RelativeSource AncestorType=DataGrid}, Mode=OneWay}"
|
||||
SelectedSecurity="{Binding value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
|
||||
ShowDialogSkirt="True"
|
||||
/>
|
||||
</DataTemplate>
|
||||
</u:TemplateSelectorKeyValue>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static Account, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}">
|
||||
<DataTemplate>
|
||||
<ComboBox ItemsSource="{Binding DataContext.accounts, RelativeSource={RelativeSource AncestorType=DataGrid}}" SelectedItem="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
|
||||
</DataTemplate>
|
||||
</u:TemplateSelectorKeyValue>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MaxNetLongPosition, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource UIntTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MaxNetShortPosition, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource UIntTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static IsPositionLimitEnabled, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource BooleanTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static ClipLimit, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource UIntTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static IsClipLimitEnabled, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource BooleanTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MinPrice, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource DoubleTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static MaxPrice, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource DoubleTemplate}"/>
|
||||
<u:TemplateSelectorKeyValue Key="{x:Static IsPriceLimitEnabled, MemberType={u:Nested risk:RiskLimitsImportConflictsView.RiskLimitsComponentNames}}" Value="{StaticResource BooleanTemplate}"/>
|
||||
</u:KeyedTemplateSelector>
|
||||
</UserControl.Resources>
|
||||
<!--Content-->
|
||||
<Grid x:Name="content_root">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto"/>
|
||||
<RowDefinition Height="*"/>
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="Auto"/>
|
||||
<ColumnDefinition Width="*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<Image VerticalAlignment="Center" Margin="0,0,8,0">
|
||||
<Image.Source>
|
||||
<Binding Source="{x:Static MessageBoxImage.Exclamation}">
|
||||
<Binding.Converter>
|
||||
<cv:SystemIconConverter/>
|
||||
</Binding.Converter>
|
||||
</Binding>
|
||||
</Image.Source>
|
||||
</Image>
|
||||
<Canvas x:Name="text_canvas" Grid.Column="1" HorizontalAlignment="Stretch"/>
|
||||
<TextBlock Grid.Column="1" TextWrapping="Wrap" Width="{Binding ActualWidth, ElementName=text_canvas}">
|
||||
<Run Text="{Binding num_successfully_parsed_limits, Mode=OneWay}"/>
|
||||
<Run Text="/"/>
|
||||
<Run Text="{Binding num_limits, Mode=OneWay}"/>
|
||||
<Run Text=" limit items have been successfully converted."/>
|
||||
<Run Text="Resolve conflicts below by selecting a value to assign each affected limit item,"/>
|
||||
<Run Text="or modify individual limit items in the main window."/>
|
||||
<LineBreak/>
|
||||
<LineBreak/>
|
||||
<Run Text="Click 'Continue' to proceed to the main window."/>
|
||||
</TextBlock>
|
||||
<DataGrid
|
||||
x:Name="data_grid"
|
||||
u:DataGridBehavior.SingleClickEdit="True"
|
||||
Grid.Row="1"
|
||||
Grid.ColumnSpan="2"
|
||||
AutoGenerateColumns="False"
|
||||
CanUserAddRows="False"
|
||||
CanUserDeleteRows="False"
|
||||
CanUserReorderColumns="False"
|
||||
CanUserSortColumns="True"
|
||||
HeadersVisibility="All"
|
||||
ItemsSource="{Binding rows_view}"
|
||||
Margin="0,8,0,0"
|
||||
MinRowHeight="17"
|
||||
RowHeaderWidth="22"
|
||||
>
|
||||
<DataGrid.CellStyle>
|
||||
<Style TargetType="DataGridCell" BasedOn="{StaticResource DataGridCellBaseStyle}">
|
||||
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
|
||||
</Style>
|
||||
</DataGrid.CellStyle>
|
||||
<DataGrid.RowStyle>
|
||||
<Style TargetType="DataGridRow">
|
||||
<Setter Property="IsSelected" Value="{Binding is_selected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource Self}}" Value="True">
|
||||
<Setter Property="Background" Value="{StaticResource SelectedRowBackground}"/>
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</DataGrid.RowStyle>
|
||||
<DataGrid.Columns>
|
||||
<DataGridTextColumn Header="Component" Binding="{Binding component}" ElementStyle="{StaticResource VerticallyCenteredText}" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="Text" Binding="{Binding text}" ElementStyle="{StaticResource VerticallyCenteredText}" IsReadOnly="True"/>
|
||||
<DataGridTextColumn Header="Affected Limit Items" Binding="{Binding affected_limits.Count}" ElementStyle="{StaticResource VerticallyCenteredText}" IsReadOnly="True"/>
|
||||
<DataGridTemplateColumn Header="Value" CellTemplateSelector="{StaticResource ValueCellTemplateSelector}" CellEditingTemplateSelector="{StaticResource ValueCellEditingTemplateSelector}"/>
|
||||
</DataGrid.Columns>
|
||||
</DataGrid>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace bts.shell.risk_management {
|
||||
/// <summary>
|
||||
/// Interaction logic for RiskLimitsImportConflictsView.xaml
|
||||
/// </summary>
|
||||
partial class RiskLimitsImportConflictsView : UserControl {
|
||||
public RiskLimitsImportConflictsView() =>
|
||||
InitializeComponent();
|
||||
|
||||
public enum RiskLimitsComponent {
|
||||
Security,
|
||||
Account,
|
||||
MaxNetLongPosition,
|
||||
MaxNetShortPosition,
|
||||
IsPositionLimitEnabled,
|
||||
ClipLimit,
|
||||
IsClipLimitEnabled,
|
||||
MinPrice,
|
||||
MaxPrice,
|
||||
IsPriceLimitEnabled
|
||||
}
|
||||
|
||||
public static class RiskLimitsComponentNames {
|
||||
public static readonly string
|
||||
Security = RiskLimitsComponent.Security.ToString(),
|
||||
Account = RiskLimitsComponent.Account.ToString(),
|
||||
MaxNetLongPosition = RiskLimitsComponent.MaxNetLongPosition.ToString(),
|
||||
MaxNetShortPosition = RiskLimitsComponent.MaxNetShortPosition.ToString(),
|
||||
IsPositionLimitEnabled = RiskLimitsComponent.IsPositionLimitEnabled.ToString(),
|
||||
ClipLimit = RiskLimitsComponent.ClipLimit.ToString(),
|
||||
IsClipLimitEnabled = RiskLimitsComponent.IsClipLimitEnabled.ToString(),
|
||||
MinPrice = RiskLimitsComponent.MinPrice.ToString(),
|
||||
MaxPrice = RiskLimitsComponent.MaxPrice.ToString(),
|
||||
IsPriceLimitEnabled = RiskLimitsComponent.IsPriceLimitEnabled.ToString();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,14 @@
|
||||
Background="{StaticResource CommonBackground}"
|
||||
>
|
||||
<UserControl.Resources>
|
||||
<cv:BooleanToObjectConverter x:Key="IsDirtyOpacityConverter">
|
||||
<cv:BooleanToObjectConverter.ValueForFalse>
|
||||
<sys:Double>1.0</sys:Double>
|
||||
</cv:BooleanToObjectConverter.ValueForFalse>
|
||||
<cv:BooleanToObjectConverter.ValueForTrue>
|
||||
<sys:Double>0.6</sys:Double>
|
||||
</cv:BooleanToObjectConverter.ValueForTrue>
|
||||
</cv:BooleanToObjectConverter>
|
||||
<Style x:Key="TextCell" TargetType="c:TextCell">
|
||||
<Setter Property="VerticalAlignment" Value="Center"/>
|
||||
<Setter Property="Padding" Value="2,0"/>
|
||||
@@ -27,6 +35,7 @@
|
||||
<Setter Property="FontFamily" Value="{Binding Path='(c:DIYGrid.Column).font_family', RelativeSource={RelativeSource Self}}"/>
|
||||
<Setter Property="FontWeight" Value="{Binding Path='(c:DIYGrid.Column).font_weight', RelativeSource={RelativeSource Self}}"/>
|
||||
<Setter Property="FontSize" Value="{Binding Path='(c:DIYGrid.Column).font_size', RelativeSource={RelativeSource Self}}"/>
|
||||
<Setter Property="Opacity" Value="{Binding is_dirty, Converter={StaticResource IsDirtyOpacityConverter}}"/>
|
||||
</Style>
|
||||
<Style x:Key="CellBorder" TargetType="Border">
|
||||
<Setter Property="HorizontalAlignment" Value="Stretch"/>
|
||||
@@ -84,7 +93,7 @@
|
||||
<c:TextCell
|
||||
c:DIYGrid.ColumnKey="Security"
|
||||
c:DIYGrid.Column="{Binding Path='DataContext.column_map[Security]', RelativeSource={RelativeSource AncestorType=c:DIYGrid}}"
|
||||
Text="{Binding security}"
|
||||
Text="{Binding security_text}"
|
||||
Style="{StaticResource TextCell}"
|
||||
/>
|
||||
<c:TextCell
|
||||
@@ -156,6 +165,13 @@
|
||||
Style="{StaticResource LimitToggleSwitch}"
|
||||
/>
|
||||
</Border>
|
||||
<!--<Border
|
||||
c:DIYGrid.ColumnKey="IsDirty"
|
||||
c:DIYGrid.Column="{Binding Path='DataContext.column_map[IsDirty]', RelativeSource={RelativeSource AncestorType=c:DIYGrid}}"
|
||||
Style="{StaticResource CellBorder}"
|
||||
>
|
||||
<Image Source="{x:Static u:Icons.CheckMark}" Visibility="{Binding is_persisted, Converter={StaticResource BooleanToVisibilityConverter}}"/>
|
||||
</Border>-->
|
||||
</Grid>
|
||||
</DataTemplate>
|
||||
</c:DIYGrid.RowTemplate>
|
||||
|
||||
@@ -242,7 +242,8 @@ namespace mbts.ui.utility {
|
||||
}
|
||||
if (_map.Count != this.items.Count)
|
||||
throw new InvalidOperationException("Map and items are out of sync (different item counts).");
|
||||
try_select(target_key, _is_pending_selection || _items.Count == 0);
|
||||
if (try_select(target_key, _is_pending_selection || _items.Count == 0) && _is_pending_selection)
|
||||
_is_pending_selection = false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -265,6 +265,10 @@ namespace mbts.ui.controls {
|
||||
get => GetValue(SortDirectionProperty) as ListSortDirection?;
|
||||
set => SetValue(SortDirectionProperty, value);
|
||||
}
|
||||
ListSortDirection? ISortableDIYGridColumn.SortDirection {
|
||||
get => SortDirection;
|
||||
set => SetCurrentValue(SortDirectionProperty, value);
|
||||
}
|
||||
|
||||
#region IsVisible
|
||||
public static readonly DependencyProperty IsVisibleProperty =
|
||||
@@ -323,6 +327,7 @@ namespace mbts.ui.controls {
|
||||
model.width = Width;
|
||||
width_changed += on_width_changed;
|
||||
model.width_changed += on_model_width_changed;
|
||||
model.result_changed += on_result_changed;
|
||||
_model_hooks = Disposable.Create(() => {
|
||||
width_changed -= on_width_changed;
|
||||
model.width_changed -= on_model_width_changed;
|
||||
@@ -336,6 +341,8 @@ namespace mbts.ui.controls {
|
||||
model.width = value;
|
||||
model.width_changed += on_model_width_changed;
|
||||
}
|
||||
void on_result_changed() =>
|
||||
load_from(model.create());
|
||||
}
|
||||
|
||||
/// important: don't access any dependency props in here.
|
||||
@@ -370,7 +377,6 @@ namespace mbts.ui.controls {
|
||||
original_width = settings.width;
|
||||
SetCurrentValue(WidthProperty, original_width);
|
||||
}
|
||||
//
|
||||
}
|
||||
|
||||
// 'fallback' font-params (aka 'grid-level' font-params)
|
||||
|
||||
@@ -6,7 +6,6 @@ using mbts.ui.shell;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
@@ -22,19 +21,20 @@ namespace mbts.ui.controls {
|
||||
}
|
||||
}
|
||||
|
||||
interface IDIYGridColumnModel : DIYGrid.IFilterableColumn {
|
||||
interface IDIYGridColumnModel : DIYGrid.IFilterableColumn, IValueFactoryVM<GridColumnSettings> {
|
||||
string id { get; }
|
||||
string column_template { get; }
|
||||
IComparer row_comparer { get; }
|
||||
double width { get; set; }
|
||||
event Action<double> width_changed;
|
||||
event Action result_changed;
|
||||
}
|
||||
|
||||
interface IDIYGridColumnFactory {
|
||||
DIYGrid.ColumnBase create_view();
|
||||
}
|
||||
|
||||
class DIYGridColumnModel<TKey> : ViewModelBase, IDIYGridColumnModel, ISortableDIYGridColumn<TKey>, ISortableDIYGridColumn, IValueFactory<GridColumnSettings> where TKey : struct {
|
||||
class DIYGridColumnModel<TKey> : ViewModelBase, IDIYGridColumnModel, ISortableDIYGridColumn<TKey>, ISortableDIYGridColumn, IValueFactoryVM<GridColumnSettings> where TKey : struct {
|
||||
readonly DeferrableActionWrapper _result_changed;
|
||||
|
||||
FontWeight _fallback_font_weight;
|
||||
@@ -96,15 +96,6 @@ namespace mbts.ui.controls {
|
||||
width_changed?.Invoke(value);
|
||||
}
|
||||
}
|
||||
double _actual_width;
|
||||
public double actual_width {
|
||||
get => _actual_width;
|
||||
set {
|
||||
_actual_width = value;
|
||||
width = value;
|
||||
RaisePropertyChanged(nameof(actual_width));
|
||||
}
|
||||
}
|
||||
public bool is_visible { get => _is_visible; set => _set(ref _is_visible, value); }
|
||||
public ListSortDirection? sort_direction { get => _sort_direction; set => Set(ref _sort_direction, value); }
|
||||
public Color? background_color_override { get => _background_color_override; set => _set(ref _background_color_override, value); }
|
||||
@@ -144,6 +135,31 @@ namespace mbts.ui.controls {
|
||||
}
|
||||
}
|
||||
|
||||
public void load_from(GridColumnSettings value) {
|
||||
if (!value.strong_id<TKey>().Equals(id))
|
||||
throw new ArgumentException("Column id in settings object does not match the column model's id.", nameof(value));
|
||||
using (_result_changed.defer_execution())
|
||||
using (_detect_result_changed())
|
||||
using (detect_property_changes(nameof(font_color), nameof(font_weight), nameof(background_color))) {
|
||||
display_name = value.display_name;
|
||||
is_visible = value.is_visible;
|
||||
font_color_override = value.font_color_override;
|
||||
font_weight_override = value.font_weight_override;
|
||||
background_color_override = value.background_color_override;
|
||||
width = value.width;
|
||||
horizontal_alignment = value.horizontal_alignment;
|
||||
}
|
||||
}
|
||||
|
||||
IDisposable _detect_result_changed() {
|
||||
var orig_state = create();
|
||||
return Disposable.Create(() => {
|
||||
var curr_state = create();
|
||||
if (!orig_state.Equals(curr_state))
|
||||
result_changed?.Invoke();
|
||||
});
|
||||
}
|
||||
|
||||
bool _set<T>(ref T backing, T new_value, [CallerMemberName]string prop = null) =>
|
||||
_set(ref backing, new_value, EqualityComparer<T>.Default, prop);
|
||||
|
||||
@@ -161,20 +177,6 @@ namespace mbts.ui.controls {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void load_from(GridColumnSettings value) {
|
||||
if (!value.strong_id<TKey>().Equals(id))
|
||||
throw new ArgumentException("Column id in settings object does not match the column model's id.", nameof(value));
|
||||
using (_result_changed.defer_execution()) {
|
||||
display_name = value.display_name;
|
||||
is_visible = value.is_visible;
|
||||
font_color_override = value.font_color_override;
|
||||
font_weight_override = value.font_weight_override;
|
||||
background_color_override = value.background_color_override;
|
||||
width = value.width;
|
||||
horizontal_alignment = value.horizontal_alignment;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DIYGridColumnModel<TKey, TRow, TGridFilter> : DIYGridColumnModel<TKey> where TKey : struct {
|
||||
|
||||
@@ -905,7 +905,7 @@ namespace mbts.ui.controls {
|
||||
if (cb is null) {
|
||||
cb = new DIYGridColumn { id = cm.id };
|
||||
BindingOperations.SetBinding(cb, ColumnBase.HeaderProperty, new Binding(nameof(DIYGridColumnModel<int>.header)) { Source = cm });
|
||||
BindingOperations.SetBinding(cb, ColumnBase.SortDirectionProperty, new Binding(nameof(DIYGridColumnModel<int>.sort_direction)) { Source = cm });
|
||||
BindingOperations.SetBinding(cb, ColumnBase.SortDirectionProperty, new Binding(nameof(DIYGridColumnModel<int>.sort_direction)) { Source = cm, Mode = BindingMode.TwoWay });
|
||||
cb.set_model(cm);
|
||||
BindingOperations.SetBinding(cb, ColumnBase.IsVisibleProperty, new Binding(nameof(DIYGridColumnModel<int>.is_visible)) { Source = cm });
|
||||
if (cm is IFilterableColumn fc) {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Collections.Immutable;
|
||||
|
||||
namespace bts.collections {
|
||||
static class ImmutableDictionaryExtensions {
|
||||
/// <summary>
|
||||
/// Adds the specified key/value pair if the dictionary does not already contain the key, otherwise replaces the value for that key.
|
||||
/// </summary>
|
||||
/// <returns><see cref="true"/> if a new key was added; otherwise <see cref="false"/>.</returns>
|
||||
public static bool AddOrSet<TKey, TValue>(this ImmutableDictionary<TKey, TValue> dictionary, TKey key, TValue value, out ImmutableDictionary<TKey, TValue> result) {
|
||||
int orig_count = dictionary.Count;
|
||||
result = dictionary.SetItem(key, value);
|
||||
return result.Count != orig_count;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Removes the entry with specified key.
|
||||
/// </summary>
|
||||
/// <returns><see cref="true"/> if the entry was removed; otherwise <see cref="false"/>.</returns>
|
||||
public static bool Remove<TKey, TValue>(this ImmutableDictionary<TKey, TValue> dictionary, TKey key, out ImmutableDictionary<TKey, TValue> result) {
|
||||
result = dictionary.Remove(key);
|
||||
return result.Count != dictionary.Count;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,5 +25,21 @@ namespace bts.collections {
|
||||
bd.Remove(v);
|
||||
return bd.ToImmutable();
|
||||
}
|
||||
|
||||
public static bool Add<T>(this ImmutableHashSet<T> source, T value, out ImmutableHashSet<T> result) {
|
||||
int orig_count = source.Count;
|
||||
result = source.Add(value);
|
||||
return result.Count != orig_count;
|
||||
}
|
||||
|
||||
public static ImmutableHashSet<T> AddRange<T>(this ImmutableHashSet<T> source, IEnumerable<T> value) {
|
||||
if (source is null)
|
||||
throw new ArgumentNullException(nameof(source));
|
||||
if (value is null)
|
||||
throw new ArgumentNullException(nameof(value));
|
||||
var bd = source.ToBuilder();
|
||||
bd.AddRange(value);
|
||||
return bd.ToImmutable();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,15 @@ namespace bts.collections {
|
||||
list.Insert(i < 0 ? ~i : i, value);
|
||||
}
|
||||
|
||||
public static void InsertOrReplaceSorted<T>(this IList<T> list, T item, IComparer<T> comparer) {
|
||||
int i = CollectionHelper.binary_search(list, item, comparer);
|
||||
if (i < 0) {
|
||||
list.Insert(~i, item);
|
||||
} else {
|
||||
list[i] = item;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool RemoveSorted<T>(this IList<T> list, T item, IComparer<T> comparer) {
|
||||
int i = CollectionHelper.binary_search(list, item, comparer);
|
||||
if (i < 0)
|
||||
|
||||
@@ -6,6 +6,9 @@ using System.Threading.Tasks;
|
||||
|
||||
namespace System.Reactive.Linq {
|
||||
public static class ObservableExtensions {
|
||||
public static IObservable<bool> And(this IObservable<bool> source1, IObservable<bool> source2) =>
|
||||
source1.CombineLatest(source2).Select(tup => tup.Item1 && tup.Item2);
|
||||
|
||||
/// <summary>
|
||||
/// <para>Creates an "Observable Heartbeat" that will publish true/false to indicate whether or not the heartbeat is detected, it will only send updates when the 'heartbeat status' has changed.</para>
|
||||
/// <para>Whenever the source produces an update, the heartbeat evaluates to true and the heartbeat duration clock is reset.</para>
|
||||
|
||||
@@ -1 +1 @@
|
||||
set(sources files/cert_secure_logon.txt;files/futures.coconut.xz;files/onixs_ice/ConnectivityConfiguration.APITest.xml;files/onixs_ice/ConnectivityConfiguration.PerfTest.xml;files/onixs_ice/ConnectivityConfiguration.Production.xml;files/perf_trace/compiled.css;files/perf_trace/index.html;files/perf_trace/jquery-3.3.1.min.js;files/perf_trace/main.js;files/perf_trace/perf_log.sql;files/perf_trace/perf_trace_analysis.sql;files/perf_trace/plotly-latest.min.js)
|
||||
set(sources files/cert_secure_logon.txt;files/futures.coconut.xz;files/onixs_ice/ConnectivityConfiguration.APITest.xml;files/onixs_ice/ConnectivityConfiguration.APITest.xml.orig;files/onixs_ice/ConnectivityConfiguration.PerfTest.xml;files/onixs_ice/ConnectivityConfiguration.Production.xml;files/perf_trace/compiled.css;files/perf_trace/index.html;files/perf_trace/jquery-3.3.1.min.js;files/perf_trace/main.js;files/perf_trace/perf_log.sql;files/perf_trace/perf_trace_analysis.sql;files/perf_trace/plotly-latest.min.js)
|
||||
@@ -1 +1 @@
|
||||
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/service_helpers/PositionUtilities.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/BasePositionService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/MarketDataService.proto;api/services/MoneyFileService.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/position_cfg.conf;config/defaults/span.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/AlgoTypes.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/position_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spreader.proto;config/protos/subprocess.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/sod.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/Product.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/service/MarketDataServiceServer.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;md/vendor/OnixsUtils.cpp;mercury/actors/IPollableActor.cpp;mercury/broker/Broker.cpp;mercury/broker/BrokerProxy.cpp;mercury/broker/ILocalBroker.cpp;mercury/broker/IRemoteBroker.cpp;mercury/common/mercury_common.cpp;mercury/events/TimerEvent.cpp;mercury/executor/Executor.cpp;mercury/topics/Topic.cLine truncated
|
||||
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/service_helpers/PositionUtilities.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/BasePositionService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/MarketDataService.proto;api/services/MoneyFileService.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/position_cfg.conf;config/defaults/span.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/AlgoTypes.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/position_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spreader.proto;config/protos/subprocess.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/sod.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/Product.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/service/MarketDataServiceServer.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;md/vendor/OnixsUtils.cpp;mercury/actors/IPollableActor.cpp;mercury/broker/Broker.cpp;mercury/broker/BrokerProxy.cpp;mercury/broker/ILocalBroker.cpp;mercury/broker/IRemoteBroker.cpp;mercury/common/mercury_common.cpp;mercury/events/TimerEvent.cpp;mercury/executor/Executor.cpp;mercury/topics/Topic.cLine truncated
|
||||
@@ -6,6 +6,7 @@ MarketDataConfig {
|
||||
rule: "DeploymentType.type == 'PROD'"
|
||||
value {
|
||||
use_sim: false
|
||||
use_onix: false
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
#nusers: 1
|
||||
#allow concurrent : true
|
||||
#expires: 2021-Jan-01 00:00:00 637450560000000000
|
||||
#generation_time: 2020-Apr-03 18:39:31.010863 5248901378137496534
|
||||
|
||||
|
||||
#nusers: 100000
|
||||
#allow concurrent : false
|
||||
#expires: 3020-May-18 00:00:00 952822656000000000
|
||||
#generation_time: 2020-Aug-11 14:19:03.379579 5249013541861183694
|
||||
EncryptedKeyCode {
|
||||
value {
|
||||
keycode: "BJBQWsbdTXWa/iLmOf3ekE8vP/NYkf0Q/nUsp/rJ78Ze3W9pNXICCMabmmsr1xOM7aqRIclPgZd955uSSfvFkdNWFTxwPQ5IfnDGopj3QdhUVxhzgVLaXHN+vC0H/MWrDQ5K4WY5J/6VXgUn1LSN/2HNb5iR2sKXeh3Alamg87YtCWEi+scelffE7HK5ERT/3A3Y/e0pqUFhP6xouIjHRhC2FRBb6OoJQVvFwVDADSuKZNo9B6GhC3H0YdHqjFhGDoky5ecgzeKIX8uWJEQNnQXQJ0iTgQ95+YR5IMU+XWdlVfSrc0fuTmj3YWcBQ8Kl2ItEcobyZzJYega3tu6Ftw=="
|
||||
keycode: "hrelQBN4n0kURYKYLwp2nzYTaxeyJZoGs//hN9rkyyVTgp1EQpyOnZHo7klNF8r9Ci8QV8aD0Yp66FvhtWqLFkNWCZ4pp48HzC34pdRzVbXjTmyEMK6iz/nBLE/VuYtBoXihlxIqOjTwnv4sNeAgboSOadVvGY3mRb3b9tMEIRTSbuq+KdPuTM2y/swL8fg53PNLclkqzU9f6mI/250RmnCvWzZf7Liu6TBWfQAI2RfGKP1+blewONFHqkeSA/fVkGfdiZy7cJOqak9VrxzLsJwqAK5DGMNv/kk4jceT3mF3xaSzoEzbge3ekk/SxXkuAKFrT6fxrr/v381SeHoHSw=="
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -72,6 +72,7 @@ message LadderKnobs {
|
||||
optional bool open_algo_popup_on_select = 6 [default = false];
|
||||
optional bool use_algo_param_grid = 7 [default = true];
|
||||
optional uint32 max_mbo_orders = 8 [default = 200];
|
||||
optional bool show_scrollbar = 9 [default = false];
|
||||
}
|
||||
|
||||
message OrderBookOptions {
|
||||
|
||||
@@ -248,14 +248,13 @@ inline bool is_strip(const bts::api::Security& sec){
|
||||
}
|
||||
|
||||
inline bool is_spread_of_strips(const bts::api::Security& sec){
|
||||
if(sec.has_spread())
|
||||
if (sec.has_ice()){
|
||||
const auto& spr = sec.spread();
|
||||
for (const auto& l : spr.legs())
|
||||
// assumption : either all legs are strips or none
|
||||
return is_strip(l.security());
|
||||
}
|
||||
return false;
|
||||
bool all_legs_strip = false;
|
||||
if(is_spread(sec)){
|
||||
all_legs_strip = true;
|
||||
for (const auto& l : sec.spread().legs())
|
||||
all_legs_strip = all_legs_strip && is_strip(l.security());
|
||||
}
|
||||
return all_legs_strip;
|
||||
}
|
||||
|
||||
inline bool is_strip_with_no_leg_fills(const bts::api::Security& sec){
|
||||
|
||||
@@ -60,13 +60,28 @@ struct ICEExecutionGateway::PImpl
|
||||
md::SecurityOracle sec_oracle;
|
||||
};
|
||||
|
||||
void from_exchange_qty (const api::Security& sec, bts::orderman::ExecutionReport* exec_rep){
|
||||
void from_exchange_qty (const api::Security& sec, bts::orderman::ExecutionReport* exec_rep){
|
||||
LOG(OrderMan, Info, "ICEExecutionGateway::from_exchange_qty "
|
||||
"sec:{} mult:{} "
|
||||
"leg_sec:{} leg_sec_mult:{}"
|
||||
"qty:{} filled_qty:{} last_shares:{} max_show:{} "
|
||||
"price:{} last_price:{} avg_price:{}",
|
||||
sec.id(), sec.ice().exchange_qty_mult(),
|
||||
exec_rep->leg_security == nullptr ? 0 : exec_rep->leg_security->id(),
|
||||
exec_rep->leg_security == nullptr ? os::nan() : exec_rep->leg_security->ice().exchange_qty_mult(),
|
||||
exec_rep->quantity, exec_rep->filled_quantity,
|
||||
exec_rep->last_shares, exec_rep->max_show,
|
||||
exec_rep->price, exec_rep->last_price, exec_rep->avg_price);
|
||||
exec_rep->quantity = bts::securities::from_exchange_qty(
|
||||
exec_rep->quantity,sec);
|
||||
exec_rep->filled_quantity = bts::securities::from_exchange_qty(
|
||||
exec_rep->filled_quantity,sec);
|
||||
// this is specific to the leg
|
||||
const api::Security& last_shr_sec = exec_rep->leg_security == nullptr ? sec :
|
||||
*exec_rep->leg_security;
|
||||
exec_rep->last_shares = bts::securities::from_exchange_qty(
|
||||
exec_rep->last_shares,sec);
|
||||
exec_rep->last_shares,
|
||||
last_shr_sec);
|
||||
exec_rep->max_show = bts::securities::from_exchange_qty(
|
||||
exec_rep->max_show,sec);
|
||||
}
|
||||
@@ -431,8 +446,7 @@ void ICEExecutionGateway::on_exe_report(const jetfix::fix::ICEExecutionReportMsg
|
||||
|
||||
data->last_shares = msg.has<fix::LastShares>()
|
||||
? Quantity(msg.get<fix::LastShares>())
|
||||
: Quantity(0);
|
||||
from_exchange_qty(*sec,data);
|
||||
: Quantity(0);
|
||||
auto last_px_sec = data->leg_security ? data->leg_security : sec;
|
||||
data->last_price = msg.has<fix::LastPx>()
|
||||
? securities::decode_exchange_price(*last_px_sec, Price(msg.get<fix::LastPx>()))
|
||||
@@ -457,6 +471,7 @@ void ICEExecutionGateway::on_exe_report(const jetfix::fix::ICEExecutionReportMsg
|
||||
data->cfg = &me->cfg;
|
||||
data->msg = text_msg;
|
||||
data->exchange = api::Venue::VENUE_ICE;
|
||||
from_exchange_qty(*sec,data);
|
||||
me->on_exe_report(*data, msg.trace());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,376 +0,0 @@
|
||||
#include "DormanAlgo.h"
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/logging/logging.h"
|
||||
#include "lib/orderman/order_factory/IOrderFactory.h"
|
||||
#include "lib/orderman/orderman_utils/Book.h"
|
||||
#include "lib/orderman/orders/algo/IAlgoServices.h"
|
||||
#include "lib/utils/PBUtils.h"
|
||||
#include "lib/orderman/orderman_utils/orderman_utils.h"
|
||||
#include "lib/orderman/orders/algo/utils/Accumulator.h"
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace dorman {
|
||||
|
||||
using namespace api::orderman;
|
||||
|
||||
struct FutureQty {
|
||||
Quantity size;
|
||||
TimeStamp when;
|
||||
};
|
||||
|
||||
struct DormanAlgo::Impl {
|
||||
IAlgoServices *algo = nullptr;
|
||||
AlgoParams params;
|
||||
api::Side side;
|
||||
Quantity exposed_qty = {};
|
||||
std::optional<FutureQty> next_size;
|
||||
|
||||
OrderDefinition splitter_definition;
|
||||
OrderKey child_id;
|
||||
ChildState child_state;
|
||||
|
||||
uint32_t fills ={};
|
||||
|
||||
std::vector<OrderKey> profit_orders;
|
||||
std::optional<Accumulator> trade_accumulator;
|
||||
|
||||
std::optional<TimeStamp> pause_until;
|
||||
};
|
||||
|
||||
DormanAlgo::DormanAlgo() :
|
||||
me(new Impl())
|
||||
{ }
|
||||
DormanAlgo::~DormanAlgo() { }
|
||||
|
||||
OrderOpResult DormanAlgo::do_before_launch(IBeforeLaunchAlgoServices& ibl) {
|
||||
const auto& def = ibl.definition();
|
||||
// Validation
|
||||
bts_assert(def.has_custom_def());
|
||||
bts_assert(def.custom_def().has_dynamic());
|
||||
|
||||
auto params = to_dorman_params(def.custom_def().dynamic());
|
||||
if (auto error = std::get_if<OrderOpResult>(¶ms)) {
|
||||
return *error;
|
||||
}
|
||||
me->params = std::get<AlgoParams>(params);
|
||||
me->side = def.side();
|
||||
if (me->side != api::Side::SIDE_BUY && me->side != api::Side::SIDE_SELL) {
|
||||
return OrderOpResult { ORDER_ERROR_INVALID_ORDER_DEFINITON, "Invalid side" };
|
||||
}
|
||||
|
||||
if (me->params.trade_accumulation) {
|
||||
auto& t = me->params.trade_accumulation.value();
|
||||
me->trade_accumulator = {Accumulator {t.contracts, t.seconds, ibl.get_time()}};
|
||||
}
|
||||
|
||||
CustomOrderDefinition default_order;
|
||||
default_order.mutable_limit();
|
||||
auto child_def =
|
||||
get_if<CustomOrderDefinition>(def.custom_def().dynamic().order_params(), "Child")
|
||||
.value_or(default_order);
|
||||
|
||||
update_child_template(ibl, child_def);
|
||||
|
||||
if (ibl.is_attaching()) {
|
||||
return OrderOpResult{ORDER_ERROR_OP_NOT_SUPPORTED,
|
||||
"This algo does not support attach."};
|
||||
}
|
||||
|
||||
return {/*ok*/};
|
||||
}
|
||||
|
||||
|
||||
void DormanAlgo::do_launch(IAlgoServices& algo) {
|
||||
me->algo = &algo;
|
||||
auto skey = SecurityKey(algo.security().id());
|
||||
algo.subscribe_book(skey);
|
||||
algo.subscribe_timer();
|
||||
if (me->trade_accumulator) {
|
||||
algo.subscribe_ticker(skey);
|
||||
}
|
||||
}
|
||||
|
||||
void DormanAlgo::do_launch_attached(IAlgoServices&, OrderKey, ChildState) {
|
||||
bts_assert(false);
|
||||
}
|
||||
void DormanAlgo::do_update(const api::orderman::Update& update) {
|
||||
LOG(OrderMan, Diag, "Dorman order {} receiving update: {}",
|
||||
algo().order_key().value(), utils::pb::to_string(update));
|
||||
|
||||
if (update.has_custom()) {
|
||||
if (!update.custom().has_dynamic()) {
|
||||
algo().cancel("Update cannot change order type");
|
||||
return;
|
||||
}
|
||||
auto params = to_dorman_params(update.custom().dynamic());
|
||||
|
||||
if (auto error = std::get_if<OrderOpResult>(¶ms)) {
|
||||
algo().cancel(error->error_msg);
|
||||
}
|
||||
|
||||
me->params = std::get<AlgoParams>(params);
|
||||
auto skey = SecurityKey(algo().security().id());
|
||||
if (me->params.trade_accumulation && !me->trade_accumulator) {
|
||||
algo().subscribe_ticker(skey);
|
||||
auto& t = me->params.trade_accumulation.value();
|
||||
me->trade_accumulator = {Accumulator {t.contracts, t.seconds, algo().get_time()}};
|
||||
}
|
||||
else if (!me->params.trade_accumulation && me->trade_accumulator) {
|
||||
algo().unsubscribe_ticker(skey);
|
||||
me->trade_accumulator = std::nullopt;
|
||||
}
|
||||
else if (me->params.trade_accumulation &&
|
||||
me->trade_accumulator &&
|
||||
(me->trade_accumulator.value().threshold != me->params.trade_accumulation.value().contracts ||
|
||||
me->trade_accumulator.value().bucket_interval != std::chrono::seconds(me->params.trade_accumulation.value().seconds))
|
||||
) {
|
||||
// accumulator params have changed
|
||||
auto& t = me->params.trade_accumulation.value();
|
||||
me->trade_accumulator = {Accumulator {t.contracts, t.seconds, algo().get_time()}};
|
||||
}
|
||||
|
||||
// Check for child
|
||||
auto child = get_if<CustomOrderDefinition>(update.custom().dynamic().order_params(), "Child");
|
||||
if (child) {
|
||||
update_child_template(algo(), child.value());
|
||||
}
|
||||
}
|
||||
|
||||
if (me->fills >= update.quantity()) {
|
||||
complete();
|
||||
}
|
||||
else {
|
||||
// In case of price/qty change always update the child
|
||||
// NOTE: it might be useful to cache the available market data size
|
||||
// and update based on that if the update contains a size table change
|
||||
update_child(me->exposed_qty);
|
||||
}
|
||||
}
|
||||
|
||||
void DormanAlgo::on_child_change(OrderKey key, const ChildState& state) {
|
||||
if (key != me->child_id) return;
|
||||
|
||||
if (state.status == ChildStatus::CANCELED && !is_paused()) {
|
||||
algo().cancel("Unexpected child cancel");
|
||||
return;
|
||||
}
|
||||
|
||||
auto delta = state.total_fills.value() - me->child_state.total_fills.value();
|
||||
if (delta != 0) {
|
||||
me->fills += delta;
|
||||
algo().update_fill_state(Quantity {me->fills}, state.last_price);
|
||||
send_profit_order(state.last_price, Quantity {delta});
|
||||
}
|
||||
me->child_state = state;
|
||||
|
||||
if (me->params.scratch &&
|
||||
me->fills >= me->params.scratch.value().max_overfill) {
|
||||
do_scratch();
|
||||
}
|
||||
|
||||
if (me->fills >= algo().quantity().value() || state.status == ChildStatus::COMPLETED) {
|
||||
complete();
|
||||
}
|
||||
}
|
||||
|
||||
void DormanAlgo::on_book(SecurityKey key, const Book& book) {
|
||||
if (key.value() != me->algo->security().id()) { return; }
|
||||
auto price = me->algo->price();
|
||||
auto tick = me->algo->security().contract_spec().low_tick();
|
||||
|
||||
// Determine available size on the market
|
||||
auto& side = book.side(me->side);
|
||||
uint32_t available = 0;
|
||||
for (const auto& level : side) {
|
||||
if (securities::test_price_equality(level.price(), price.value(), tick)) {
|
||||
available += level.size();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Check the step_table
|
||||
auto target = Quantity {0};
|
||||
if (available > 0) {
|
||||
for (const auto& entry : me->params.steps.step_table) {
|
||||
if (std::get<0>(entry) > available) {
|
||||
break;
|
||||
}
|
||||
else {
|
||||
target = Quantity { std::get<1>(entry) };
|
||||
}
|
||||
}
|
||||
}
|
||||
target = Quantity { std::min(target.value(), me->params.steps.maximum) };
|
||||
|
||||
// First on_book
|
||||
if (!child_active()) {
|
||||
update_child(target);
|
||||
}
|
||||
// See if we need to adjust
|
||||
else {
|
||||
if (target == me->exposed_qty) {
|
||||
me->next_size = std::nullopt;
|
||||
}
|
||||
// If target < size reduce immediately
|
||||
else if (target < me->exposed_qty) {
|
||||
update_child(target);
|
||||
me->next_size = std::nullopt;
|
||||
}
|
||||
// if target > size schedule increase
|
||||
else if (target > me->exposed_qty) {
|
||||
if (me->next_size) {
|
||||
// already planning to increase, update the target
|
||||
me->next_size.value().size = target;
|
||||
}
|
||||
else {
|
||||
// no existing scheduled increase, create one now
|
||||
me->next_size = { FutureQty { target, me->algo->get_time() + std::chrono::seconds(me->params.steps.trail_seconds) } };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
void DormanAlgo::on_timer() {
|
||||
// Check for pending size changes
|
||||
auto now = algo().get_time();
|
||||
if (me->pause_until &&
|
||||
now >= me->pause_until.value()) {
|
||||
|
||||
resume();
|
||||
}
|
||||
if (me->next_size &&
|
||||
now >= me->next_size.value().when) {
|
||||
auto size = me->next_size.value().size;
|
||||
update_child(size);
|
||||
me->next_size = std::nullopt;
|
||||
}
|
||||
}
|
||||
void DormanAlgo::on_ticker(SecurityKey, const TradeVector& vec) {
|
||||
if (me->trade_accumulator) {
|
||||
size_t contracts = 0;
|
||||
for (const auto& t : vec) {
|
||||
contracts += t.quantity.value();
|
||||
}
|
||||
auto& acc = me->trade_accumulator.value();
|
||||
acc.push_back(algo().get_time(), contracts);
|
||||
if (acc.exceeded()) {
|
||||
auto delay = std::chrono::seconds(me->params.trade_accumulation.value().sleep_seconds);
|
||||
pause_for(delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
IAlgoOrder::OnCancelResponse DormanAlgo::on_cancel() {
|
||||
// detach any remaining profit orders so they keep running
|
||||
for(const auto& key : me->profit_orders) {
|
||||
algo().detach_child(key);
|
||||
}
|
||||
return OnCancelResponse::HONOR;
|
||||
}
|
||||
|
||||
IAlgoServices& DormanAlgo::algo() const { return *me->algo; }
|
||||
|
||||
//
|
||||
// private
|
||||
|
||||
void DormanAlgo::update_child(Quantity exposed) {
|
||||
auto& splitter = *me->splitter_definition.mutable_custom_def()->mutable_splitter();
|
||||
splitter.set_max_order_qty(me->params.clip_limit);
|
||||
me->exposed_qty = exposed;
|
||||
splitter.set_exposed_qty(is_paused() ? 0 : exposed.value());
|
||||
|
||||
if (!child_active()) {
|
||||
// launch child
|
||||
me->child_id = algo().launch_child(me->splitter_definition, algo().price(), algo().quantity());
|
||||
}
|
||||
else {
|
||||
Update update;
|
||||
update.set_price(algo().price().value());
|
||||
update.set_quantity(algo().quantity().value());
|
||||
*update.mutable_custom()->mutable_splitter() = splitter;
|
||||
algo().update_child(me->child_id, update);
|
||||
}
|
||||
}
|
||||
|
||||
void DormanAlgo::update_child_template(IBeforeLaunchAlgoServices& ibl, const CustomOrderDefinition& child) {
|
||||
auto child_def = ibl.definition();
|
||||
// Insert a spliter between this and the configured child definition.
|
||||
api::orderman::SplitterOrderDefinition& splitter_def = *child_def.mutable_custom_def()->mutable_splitter();
|
||||
*splitter_def.mutable_child() = child;
|
||||
me->splitter_definition = child_def;
|
||||
}
|
||||
|
||||
Quantity DormanAlgo::exposed_qty() const { return me->exposed_qty; }
|
||||
|
||||
bool DormanAlgo::child_active() const { return me->child_id.value() != 0; }
|
||||
|
||||
void DormanAlgo::do_scratch() {
|
||||
// When the # of fills exceeds the max overfill quantity
|
||||
// We enter fills opposite fills at the fill price and terminate
|
||||
// Use a splitter to bypass clip limit if necessary
|
||||
|
||||
OrderDefinition def = me->splitter_definition;
|
||||
def.set_side(securities::other_side(me->side));
|
||||
def.mutable_custom_def()->mutable_splitter()->set_exposed_qty(me->fills);
|
||||
|
||||
auto price = me->child_state.last_price;
|
||||
auto scratch_id = algo().launch_child(def, price, Quantity { me->fills }, false);
|
||||
|
||||
algo().detach_child(scratch_id);
|
||||
complete();
|
||||
}
|
||||
|
||||
void DormanAlgo::send_profit_order(Price p, Quantity q) {
|
||||
if (me->params.profit_orders) {
|
||||
auto side = securities::other_side(me->side);
|
||||
Price offset =
|
||||
Price { algo().security().contract_spec().low_tick() * me->params.profit_orders.value().ticks_away };
|
||||
auto price =
|
||||
securities::worsen_price(side, p, offset);
|
||||
|
||||
OrderDefinition def = me->splitter_definition;
|
||||
// BTS Simulator does not currently support GTC
|
||||
// Note: This could be made a configurable order type in the algo parameters
|
||||
def.set_time_in_force(TimeInForce::TIME_IN_FORCE_DAY);
|
||||
def.set_side(side);
|
||||
def.mutable_custom_def()->mutable_limit();
|
||||
me->profit_orders.push_back(
|
||||
algo().launch_child(def, price, q, false));
|
||||
}
|
||||
}
|
||||
|
||||
void DormanAlgo::complete() {
|
||||
// Allow profit orders to keep running
|
||||
if (me->params.profit_orders) {
|
||||
for(const auto& key : me->profit_orders) {
|
||||
algo().detach_child(key);
|
||||
}
|
||||
}
|
||||
algo().complete();
|
||||
}
|
||||
|
||||
|
||||
void DormanAlgo::pause_for(Duration d) {
|
||||
if (me->params.trade_accumulation) {
|
||||
if (is_paused()) {
|
||||
me->pause_until = std::max(me->pause_until.value(), { algo().get_time() + d });
|
||||
}
|
||||
else {
|
||||
me->pause_until = { algo().get_time() + d };
|
||||
// When paused child update will always expose 0
|
||||
update_child(me->exposed_qty);
|
||||
}
|
||||
}
|
||||
}
|
||||
bool DormanAlgo::is_paused() const {
|
||||
return (bool)(me->pause_until);
|
||||
}
|
||||
void DormanAlgo::resume() {
|
||||
if (is_paused()) {
|
||||
me->pause_until = std::nullopt;
|
||||
update_child(me->exposed_qty);
|
||||
}
|
||||
}
|
||||
|
||||
}}} //namespace
|
||||
@@ -1,96 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/orderman/orders/algo/IAlgoOrder.h"
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <variant>
|
||||
#include <map>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace dorman {
|
||||
|
||||
//
|
||||
// Algo parameters
|
||||
//
|
||||
|
||||
// This defines the market quantity vs the order quantity
|
||||
struct StepParams {
|
||||
std::vector<std::tuple<uint32_t, uint32_t>> step_table;
|
||||
// This is the cap on the maximum quantity,
|
||||
// even though the step table can allow for higher quantities (depending on the
|
||||
// clip size this could be divided across multiple exchange orders)
|
||||
uint32_t maximum;
|
||||
// If the market increases don't follow until it has stayed high for trail_seconds;
|
||||
uint32_t trail_seconds;
|
||||
};
|
||||
|
||||
// If the number of accumulated fills (net of profit orders) touches or goes beyond
|
||||
// this, the fills will be scratched by entering opposite orders at the fill price
|
||||
struct ScratchParams {
|
||||
uint32_t max_overfill;
|
||||
};
|
||||
// If this is enabled, then as fills accumulate, profit GTC orders are
|
||||
// immediately sent N ticks away on the opposite side.
|
||||
struct ProfitOrderParams {
|
||||
uint32_t ticks_away;
|
||||
};
|
||||
// If N contracts trade in T seconds, then the algo is paused (ie child exchange order
|
||||
// is/are cancelled) for X seconds. Once the condition clears order is reentered.
|
||||
struct TradeAccumulationParams {
|
||||
uint32_t contracts;
|
||||
uint32_t seconds;
|
||||
uint32_t sleep_seconds;
|
||||
};
|
||||
struct AlgoParams {
|
||||
StepParams steps;
|
||||
uint32_t clip_limit;
|
||||
std::optional<ScratchParams> scratch;
|
||||
std::optional<ProfitOrderParams> profit_orders;
|
||||
std::optional<TradeAccumulationParams> trade_accumulation;
|
||||
};
|
||||
|
||||
|
||||
class DormanAlgo : public IAlgoOrder {
|
||||
struct Impl;
|
||||
std::unique_ptr<Impl> me;
|
||||
IAlgoServices& algo() const;
|
||||
|
||||
public:
|
||||
DormanAlgo();
|
||||
~DormanAlgo();
|
||||
|
||||
OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override;
|
||||
void do_launch(IAlgoServices &) override;
|
||||
void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override;
|
||||
void do_update(api::orderman::Update const &) override;
|
||||
void on_child_change(OrderKey, ChildState const &) override;
|
||||
void on_book(SecurityKey, const Book&) override;
|
||||
void on_timer() override;
|
||||
void on_ticker(SecurityKey, const TradeVector&) override;
|
||||
IAlgoOrder::OnCancelResponse on_cancel() override;
|
||||
|
||||
Quantity exposed_qty() const;
|
||||
|
||||
private:
|
||||
//
|
||||
// Child management
|
||||
void update_child_template(IBeforeLaunchAlgoServices&, const api::orderman::CustomOrderDefinition&);
|
||||
void update_child(Quantity exposed);
|
||||
bool child_active() const;
|
||||
|
||||
void do_scratch();
|
||||
void send_profit_order(Price, Quantity);
|
||||
void complete();
|
||||
|
||||
void pause_for(Duration);
|
||||
bool is_paused() const;
|
||||
void resume();
|
||||
|
||||
};
|
||||
|
||||
template <class OK,class ERR>
|
||||
using Result = std::variant<OK,ERR>;
|
||||
Result<AlgoParams,OrderOpResult> to_dorman_params(const api::orderman::DynamicOrderDefinition&);
|
||||
|
||||
}}} //namespace
|
||||
@@ -1,401 +0,0 @@
|
||||
#include "lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.h"
|
||||
#include "lib/sparkproto/SparkProtos.pb.h"
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/orderman/order_factory/IOrderFactory.h"
|
||||
#include "lib/orderman/orderman_utils/orderman_utils.h"
|
||||
#include "lib/orderman/orders/algo/IAlgoServices.h"
|
||||
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h"
|
||||
#include "lib/os/os.h"
|
||||
#include "lib/utils/PBUtils.h"
|
||||
#include "lib/orderman/orders/algo/utils/DynamicOrderAdapter.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h"
|
||||
#include <map>
|
||||
#include <limits>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
|
||||
#define DEFAULT_LOG_LEVEL Info
|
||||
|
||||
#define SUMMARIZE_TRANSACTION_BEGIN(id, type, ...) Summary __LOG_TRANS(this, id, Formatter::fmt(__VA_ARGS__), type, DEFAULT_LOG_LEVEL)
|
||||
|
||||
#define SUMMARIZE_TRANSACTION(id, type) Summary __LOG_TRANS(this, id, "", type, DEFAULT_LOG_LEVEL)
|
||||
#define SUMMARIZE SUMMARIZE_TRANSACTION(__FUNCTION__, SummaryType::StatusChange)
|
||||
|
||||
// define 'PRINT_SUMMARIES' to print all logs to the console
|
||||
// (assuming logs are made with the MSG/MSG_LEVEL macros)
|
||||
#ifdef PRINT_SUMMARIES
|
||||
#define _PRINT_MSG(x) std::cout << x << std::endl;
|
||||
#else
|
||||
#define _PRINT_MSG(x)
|
||||
#endif
|
||||
|
||||
#define _MSG(level, msg) \
|
||||
_PRINT_MSG(msg); \
|
||||
LOG(OrderMan, level, "{}", msg)
|
||||
|
||||
#define MSG_LEVEL(level, ...) _MSG(level, (Formatter::fmt(__VA_ARGS__)))
|
||||
// these automatically prepend log_header() to the args
|
||||
#define MSG(...) MSG_LEVEL(DEFAULT_LOG_LEVEL, log_header(), " ", __VA_ARGS__)
|
||||
#define DIAG(...) MSG_LEVEL(Diag, log_header(), " ", __VA_ARGS__)
|
||||
#define INFO(...) MSG_LEVEL(Info, log_header(), " ", __VA_ARGS__)
|
||||
#define WARN(...) MSG_LEVEL(Warn, log_header(), " ", __VA_ARGS__)
|
||||
#define ERROR(...) MSG_LEVEL(Error, log_header(), " ", __VA_ARGS__)
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
using namespace api::orderman;
|
||||
using namespace bts::orderman::limit_cover::utils;
|
||||
using Adapter = bts::orderman::LimitCoverAdapter;
|
||||
|
||||
namespace limit_cover {
|
||||
namespace utils {
|
||||
void init_delete_and_cover(OrderDefinition& target, const DeleteAndCoverDefinition& def) {
|
||||
if (!target.has_custom_def())
|
||||
*target.mutable_custom_def() = CustomOrderDefinition();
|
||||
init_delete_and_cover(*target.mutable_custom_def(), def);
|
||||
}
|
||||
|
||||
void init_delete_and_cover(CustomOrderDefinition& target, const DeleteAndCoverDefinition& def) {
|
||||
if (!target.has_delete_and_cover()) {
|
||||
*target.mutable_delete_and_cover() = DeleteAndCoverDefinition(def);
|
||||
} else {
|
||||
target.mutable_delete_and_cover()->CopyFrom(def);
|
||||
}
|
||||
}
|
||||
|
||||
void init_child_update(Update& target, uint32_t qty, double price, const DeleteAndCoverDefinition& def) {
|
||||
target.set_quantity(qty);
|
||||
target.set_price(price);
|
||||
init_delete_and_cover(*target.mutable_custom(), def);
|
||||
}
|
||||
|
||||
#define INVALID_DEF(x) OrderOpResult(api::orderman::ORDER_ERROR_INVALID_ORDER_DEFINITON, x)
|
||||
|
||||
OrderOpResult validate_custom_def(const CustomOrderDefinition& custom_def) {
|
||||
if (!custom_def.has_dynamic())
|
||||
return INVALID_DEF("DynamicOrderDefinition is undefined");
|
||||
return Adapter::validate_proto(custom_def.dynamic());
|
||||
}
|
||||
OrderOpResult validate_def(const OrderDefinition& def) {
|
||||
if (def.attach_target_order_key() != 0) {
|
||||
return INVALID_DEF("Attach not supported.");
|
||||
} else if (def.has_custom_def()) {
|
||||
return validate_custom_def(def.custom_def());
|
||||
} else {
|
||||
return INVALID_DEF("CustomOrderDefinition is undefined.");
|
||||
}
|
||||
}
|
||||
|
||||
OrderOpResult validate_update(const Update& upd) {
|
||||
return upd.has_custom() ?
|
||||
validate_custom_def(upd.custom()) : OrderOpResult();
|
||||
}
|
||||
} // namespace utils
|
||||
} // namespace limit_cover
|
||||
|
||||
struct LimitCoverAlgo::PImpl {
|
||||
IAlgoServices *algo = nullptr;
|
||||
Status status = Status::WAITING_TO_DEPLOY;
|
||||
OrderKey child_key = null_order_key();
|
||||
double child_price = os::nan();
|
||||
uint32_t child_qty = 0;
|
||||
Book book;
|
||||
uint32_t limit_volume = 0;
|
||||
std::map<uint32_t, LimitCoverGate> gates;
|
||||
double settlement = os::nan();
|
||||
double price_offset_from_settle = 0;
|
||||
double limit_price = os::nan();
|
||||
};
|
||||
|
||||
struct LimitCoverAlgo::Summary {
|
||||
Summary(LimitCoverAlgo* owner, std::string transaction_id, std::string begin_tag = {}, SummaryType type = SummaryType::StatusChange, log::Level level = DEFAULT_LOG_LEVEL)
|
||||
: _owner(owner), _transaction_id(transaction_id), _original_status(owner->me->status), _type(type), _level(level) {
|
||||
if (_owner != nullptr && !_transaction_id.empty()) {
|
||||
std::stringstream str;
|
||||
str << owner->log_header() << " begin " << transaction_id << ".";
|
||||
if (!begin_tag.empty()) {
|
||||
str << " " << begin_tag << ".";
|
||||
}
|
||||
if (type == SummaryType::FullState) {
|
||||
str << " Algo State: " << _owner->fmt_state() << ".";
|
||||
}
|
||||
MSG_LEVEL(level, str.str());
|
||||
}
|
||||
}
|
||||
|
||||
~Summary() {
|
||||
std::stringstream msg_str;
|
||||
if (!_transaction_id.empty()) {
|
||||
msg_str << " end " << _transaction_id << ".";
|
||||
}
|
||||
switch (_type) {
|
||||
case SummaryType::StatusChange:
|
||||
if (_owner->me->status != _original_status)
|
||||
msg_str << " Status changed from " << _original_status << " to " << _owner->me->status << ".";
|
||||
break;
|
||||
case SummaryType::FullState:
|
||||
msg_str << " Algo State: " << _owner->fmt_state() << ".";
|
||||
break;
|
||||
}
|
||||
auto msg = msg_str.str();
|
||||
if (!msg.empty()) {
|
||||
MSG_LEVEL(_level, _owner->log_header(), msg);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
LimitCoverAlgo *_owner;
|
||||
std::string _transaction_id;
|
||||
Status _original_status;
|
||||
SummaryType _type;
|
||||
log::Level _level;
|
||||
};
|
||||
|
||||
LimitCoverAlgo::LimitCoverAlgo() : me(new PImpl()) {}
|
||||
LimitCoverAlgo::~LimitCoverAlgo() {}
|
||||
|
||||
OrderOpResult
|
||||
LimitCoverAlgo::do_before_launch(IBeforeLaunchAlgoServices &balgo) {
|
||||
SUMMARIZE;
|
||||
bts_assert(me->status == Status::WAITING_TO_DEPLOY);
|
||||
bts_assert(me->gates.empty());
|
||||
auto vd = validate_def(balgo.definition());
|
||||
if (vd.ok()) {
|
||||
auto lcdef = Adapter::from_proto(balgo.definition());
|
||||
me->price_offset_from_settle = lcdef.price_offset();
|
||||
me->gates = lcdef.normal_gates();
|
||||
}
|
||||
return vd;
|
||||
}
|
||||
|
||||
void LimitCoverAlgo::do_launch(IAlgoServices& algo) {
|
||||
SUMMARIZE;
|
||||
bts_assert(me->status == Status::WAITING_TO_DEPLOY);
|
||||
me->algo = &algo;
|
||||
me->child_qty = algo.quantity().value();
|
||||
algo.subscribe_book(SecurityKey(algo.security().id()));
|
||||
algo.subscribe_settlement(SecurityKey(algo.security().id()));
|
||||
}
|
||||
|
||||
void LimitCoverAlgo::do_update(Update const &upd) {
|
||||
SUMMARIZE_TRANSACTION_BEGIN(__FUNCTION__, SummaryType::StatusChange, utils::pb::to_string(upd));
|
||||
auto vup = validate_update(upd);
|
||||
if (!vup.ok()) {
|
||||
me->status = Status::DONE;
|
||||
algo().terminate_error(Formatter::fmt("Invalid update: ", vup.error_msg, "."));
|
||||
return;
|
||||
}
|
||||
if (upd.has_custom()) {
|
||||
auto lcdef = Adapter::from_proto(upd.custom());
|
||||
if (me->status == Status::WAITING_TO_DEPLOY) {
|
||||
me->price_offset_from_settle = lcdef.price_offset();
|
||||
recompute_limit_price();
|
||||
recompute_limit_volume();
|
||||
}
|
||||
me->gates = lcdef.normal_gates();
|
||||
if (me->status == Status::WORKING)
|
||||
recompute_gate();
|
||||
}
|
||||
switch (me->status) {
|
||||
case Status::WAITING_TO_DEPLOY:
|
||||
try_deploy();
|
||||
break;
|
||||
case Status::WORKING: {
|
||||
// don't change the child price; the price param is irrelevant to this algo.
|
||||
if (upd.has_custom() || me->child_qty != upd.quantity())
|
||||
update_child(upd.quantity());
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void LimitCoverAlgo::on_book(SecurityKey, Book const &b) {
|
||||
SUMMARIZE_TRANSACTION_BEGIN(__FUNCTION__, SummaryType::StatusChange, "BBO: ", Formatter::to_string(b));
|
||||
me->book = b;
|
||||
recompute_limit_volume();
|
||||
switch (me->status) {
|
||||
case Status::WAITING_TO_DEPLOY:
|
||||
try_deploy();
|
||||
break;
|
||||
case Status::WORKING: {
|
||||
if (recompute_gate())
|
||||
update_child(me->child_qty);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void LimitCoverAlgo::update_child(uint32_t qty) {
|
||||
bts_assert(me->algo != nullptr);
|
||||
bts_assert(me->status == Status::WORKING);
|
||||
me->child_qty = qty;
|
||||
Update upd;
|
||||
init_child_update(upd, qty, me->child_price, curr_gate().definition());
|
||||
MSG("updating algo child: ", utils::pb::to_string(upd));
|
||||
me->algo->update_child(me->child_key, upd);
|
||||
}
|
||||
|
||||
void LimitCoverAlgo::on_child_change(OrderKey key, ChildState const& state) {
|
||||
bts_assert(key == me->child_key);
|
||||
SUMMARIZE_TRANSACTION_BEGIN(__FUNCTION__, SummaryType::FullState, "Child State: ", Formatter::to_string(state));
|
||||
algo().update_fill_state(state.total_fills, state.last_price);
|
||||
me->child_price = state.price.value();
|
||||
switch (me->status) {
|
||||
case Status::WORKING:
|
||||
switch (state.status) {
|
||||
case ChildStatus::WORKING:
|
||||
break;
|
||||
case ChildStatus::CANCELED: {
|
||||
auto msg = Formatter::fmt("main child (", key, ") canceled unexpectedly.");
|
||||
MSG(msg, ". ", fmt_state());
|
||||
me->status = Status::DONE;
|
||||
algo().terminate_error(msg);
|
||||
break;
|
||||
}
|
||||
case ChildStatus::COMPLETED:
|
||||
me->status = Status::DONE;
|
||||
algo().complete();
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case Status::DONE:
|
||||
break;
|
||||
default:
|
||||
bts_assert_msg(false, Formatter::fmt(log_header(), " unexpected status: ", me->status));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void LimitCoverAlgo::on_settlement(SecurityKey, Price settlement) {
|
||||
if (me->status == Status::WAITING_TO_DEPLOY) {
|
||||
MSG("updating settlement from ", me->settlement, " to ", settlement);
|
||||
me->settlement = settlement.value();
|
||||
DIAG("recomputing limit price...");
|
||||
recompute_limit_price();
|
||||
DIAG("limit price is ", me->limit_price);
|
||||
DIAG("recomputing limit volume...");
|
||||
recompute_limit_volume();
|
||||
DIAG("limit volume is ", me->limit_volume);
|
||||
try_deploy();
|
||||
} else {
|
||||
MSG("ignored settlement update to ", settlement,
|
||||
": settlement updates are only processed while the algo is ", Status::WAITING_TO_DEPLOY,
|
||||
". Settlement at time of deploy was ", me->settlement);
|
||||
}
|
||||
}
|
||||
|
||||
void LimitCoverAlgo::try_deploy() {
|
||||
MSG("trying to deploy. ", fmt_state());
|
||||
bts_assert(me->status == Status::WAITING_TO_DEPLOY);
|
||||
bts_assert(me->algo != nullptr);
|
||||
// this is probably redundant (better safe than sorry tho).
|
||||
bts_assert(me->child_key == null_order_key());
|
||||
if (os::is_nan(me->settlement)) {
|
||||
MSG("still waiting for settle.");
|
||||
} else if (me->limit_volume < activation_threshold()) {
|
||||
MSG("still waiting for limit volume (", me->limit_volume, ") to breech activation threshold (", activation_threshold(), ").");
|
||||
} else {
|
||||
bts_assert(!os::is_nan(me->limit_price));
|
||||
recompute_gate();
|
||||
OrderDefinition child_def;
|
||||
bts_assert(!me->gates.empty());
|
||||
child_def.CopyFrom(algo().definition());
|
||||
init_delete_and_cover(child_def, curr_gate().definition());
|
||||
bts_assert(child_def.custom_def().has_delete_and_cover());
|
||||
MSG("deploying child order: ", utils::pb::to_string(child_def));
|
||||
me->child_key = algo().launch_child(child_def, Price(me->limit_price), algo().quantity());
|
||||
me->status = Status::WORKING;
|
||||
algo().set_ladder_visibility(false);
|
||||
}
|
||||
}
|
||||
|
||||
template<class T>
|
||||
bool did_change(T& backing, T new_value) {
|
||||
if (backing == new_value)
|
||||
return false;
|
||||
backing = new_value;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool LimitCoverAlgo::recompute_gate() {
|
||||
if (me->gates.empty())
|
||||
return false;
|
||||
auto orig_sz = me->gates.size();
|
||||
auto it = me->gates.lower_bound(me->limit_volume);
|
||||
if (it == me->gates.end() || (it != me->gates.begin() && it->first > me->limit_volume))
|
||||
it--;
|
||||
me->gates.erase(me->gates.begin(), it);
|
||||
return me->gates.size() < orig_sz;
|
||||
}
|
||||
|
||||
// limit price
|
||||
double LimitCoverAlgo::compute_limit_price() const {
|
||||
return os::is_nan(me->settlement) ? os::nan() :
|
||||
securities::improve_price(side(), Price(me->settlement), Price(me->price_offset_from_settle))
|
||||
.value();
|
||||
}
|
||||
bool LimitCoverAlgo::recompute_limit_price() {
|
||||
return did_change(me->limit_price, compute_limit_price());
|
||||
}
|
||||
|
||||
// limit volume
|
||||
uint32_t LimitCoverAlgo::compute_limit_volume() const {
|
||||
return me->algo == nullptr ? 0 :
|
||||
BookUtils::volume_at_or_better(me->book, side(), me->limit_price);
|
||||
}
|
||||
bool LimitCoverAlgo::recompute_limit_volume() {
|
||||
return did_change(me->limit_volume, compute_limit_volume());
|
||||
}
|
||||
|
||||
// pseudo properties (const state accessors)
|
||||
IAlgoServices &LimitCoverAlgo::algo() const { return *me->algo; }
|
||||
|
||||
api::Side LimitCoverAlgo::side() const {
|
||||
return me->algo == nullptr ? api::SIDE_UNDEFINED : me->algo->definition().side();
|
||||
}
|
||||
|
||||
const LimitCoverGate& LimitCoverAlgo::curr_gate() const {
|
||||
bts_assert(!me->gates.empty());
|
||||
return me->gates.begin()->second;
|
||||
}
|
||||
|
||||
uint32_t LimitCoverAlgo::activation_threshold() const {
|
||||
return me->gates.empty() ? std::numeric_limits<uint32_t>::max() : me->gates.begin()->first;
|
||||
}
|
||||
|
||||
std::string LimitCoverAlgo::log_header() const {
|
||||
std::stringstream ostr;
|
||||
ostr << "LimitCoverAlgo";
|
||||
if (me->algo != nullptr) {
|
||||
ostr << "(" << me->algo->order_key().value() << ")";
|
||||
}
|
||||
ostr << "[" << fmt_status(me->status) << "]";
|
||||
return ostr.str();
|
||||
}
|
||||
|
||||
std::string LimitCoverAlgo::fmt_state() const {
|
||||
std::stringstream ostr;
|
||||
if (me->algo != nullptr) {
|
||||
ostr << " [" << fmt_status(me->status) << "]"
|
||||
<< Formatter::to_string(side()) << " " << me->algo->quantity().value()
|
||||
<< " @ " << me->algo->price().value()
|
||||
<< " (" << me->price_offset_from_settle
|
||||
<< " away from settle).";
|
||||
if (me->child_key != null_order_key()) {
|
||||
ostr << " Main child key: " << me->child_key << ", ";
|
||||
}
|
||||
ostr << " Settle: " << me->settlement
|
||||
<< ", Limit Price: " << me->limit_price
|
||||
<< ", BBO: " << Formatter::to_string(me->book);
|
||||
} else {
|
||||
ostr << "(initializing)";
|
||||
}
|
||||
return ostr.str();
|
||||
}
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,94 +0,0 @@
|
||||
#pragma once
|
||||
#include "lib/orderman/orderman_utils/BookUtils.h"
|
||||
#include "lib/orderman/orderman_utils/Formatter.h"
|
||||
#include "lib/orderman/orders/algo/IAlgoOrder.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverGate.h"
|
||||
#include <map>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
class LimitCoverAlgo : public IAlgoOrder {
|
||||
public:
|
||||
LimitCoverAlgo();
|
||||
~LimitCoverAlgo();
|
||||
|
||||
OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override;
|
||||
void do_launch(IAlgoServices &) override;
|
||||
void do_update(api::orderman::Update const &) override;
|
||||
void on_book(SecurityKey, Book const &) override;
|
||||
void on_settlement(SecurityKey, Price settlement) override;
|
||||
void on_child_change(OrderKey, ChildState const &) override;
|
||||
|
||||
enum class Status {
|
||||
WAITING_TO_DEPLOY,
|
||||
WORKING,
|
||||
DONE
|
||||
};
|
||||
using Status = bts::orderman::LimitCoverAlgo::Status;
|
||||
|
||||
enum SummaryType {
|
||||
StatusChange,
|
||||
FullState
|
||||
};
|
||||
|
||||
private:
|
||||
struct PImpl;
|
||||
struct Summary;
|
||||
std::unique_ptr<PImpl> me;
|
||||
|
||||
IAlgoServices &algo() const;
|
||||
api::Side side() const;
|
||||
std::string log_header() const;
|
||||
std::string fmt_state() const;
|
||||
// returns the first gate in gates (asserts that gates isn't empty).
|
||||
// Note: after the child is deployed, gates with lower thresholds are
|
||||
// removed when the limit volume passes the next gates' thresh.
|
||||
const LimitCoverGate& curr_gate() const;
|
||||
/// On the compute/recompute methods:
|
||||
/// compute_blah just returns the result (doesn't mutate any state),
|
||||
/// while recompute_blah assigns the result to the appropriate field,
|
||||
/// and returns a bool indicating whether or not the value changed.
|
||||
// limit price
|
||||
double compute_limit_price() const;
|
||||
bool recompute_limit_price();
|
||||
// limit volume
|
||||
uint32_t compute_limit_volume() const;
|
||||
bool recompute_limit_volume();
|
||||
// recomputes the current gate (i.e., the one with the
|
||||
// highest activation thresh that is still less than
|
||||
// the limit volume) then removes all gates with lower threshs.
|
||||
bool recompute_gate();
|
||||
uint32_t activation_threshold() const;
|
||||
//
|
||||
void try_deploy();
|
||||
void update_child(uint32_t qty);
|
||||
};
|
||||
|
||||
namespace limit_cover {
|
||||
namespace utils {
|
||||
inline std::string fmt_status(LimitCoverAlgo::Status status) {
|
||||
switch (status) {
|
||||
case LimitCoverAlgo::Status::WAITING_TO_DEPLOY: return "WAITING_TO_DEPLOY";
|
||||
case LimitCoverAlgo::Status::WORKING: return "WORKING";
|
||||
case LimitCoverAlgo::Status::DONE: return "DONE";
|
||||
default: return Formatter::fmt("STATUS_", static_cast<int>(status));
|
||||
}
|
||||
}
|
||||
void init_delete_and_cover(api::orderman::OrderDefinition& target, const api::orderman::DeleteAndCoverDefinition& def);
|
||||
void init_delete_and_cover(api::orderman::CustomOrderDefinition& target, const api::orderman::DeleteAndCoverDefinition& def);
|
||||
void init_child_update(api::orderman::Update& target, uint32_t qty, double price, const api::orderman::DeleteAndCoverDefinition& def);
|
||||
OrderOpResult validate_def(const api::orderman::OrderDefinition&);
|
||||
OrderOpResult validate_custom_def(const api::orderman::CustomOrderDefinition&);
|
||||
OrderOpResult validate_update(const api::orderman::Update&);
|
||||
} // namespace utils
|
||||
} // namespace limit_cover
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& ostr, const LimitCoverAlgo::Status& status) {
|
||||
ostr << limit_cover::utils::fmt_status(status);
|
||||
return ostr;
|
||||
}
|
||||
|
||||
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <google/protobuf/util/time_util.h>
|
||||
#include <boost/tokenizer.hpp>
|
||||
#include <stdint.h>
|
||||
#include "lib/plugin/SparkServices.h"
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
@@ -242,6 +243,8 @@ void OnSignalAlgo::_switch_state (State new_state){
|
||||
static_cast<int>(new_state));
|
||||
me->state = new_state;
|
||||
}
|
||||
extern "C" void init_spark_plugin(bts::SparkServices &) {
|
||||
}
|
||||
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
} // namespace bts
|
||||
@@ -1,584 +0,0 @@
|
||||
#include "lib/orderman/orders/algo/algo_orders/PyramidAlgo.h"
|
||||
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/orderman/order_factory/IOrderFactory.h"
|
||||
#include "lib/orderman/orderman_utils/Book.h"
|
||||
#include "lib/orderman/orderman_utils/orderman_utils.h"
|
||||
#include "lib/orderman/orders/algo/IAlgoServices.h"
|
||||
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h"
|
||||
#include "lib/os/os.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/utils/PBUtils.h"
|
||||
#include <stdint.h>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
|
||||
using namespace api::orderman;
|
||||
|
||||
enum class PyramidAlgo::Status { WAITING_FOR_MD, WAITING_FOR_MD_ATTACH, WORKING, DONE };
|
||||
enum class PyramidAlgo::ExitPath { CANCEL, ERR, COMPLETE };
|
||||
|
||||
struct LegData{
|
||||
const size_t index;
|
||||
const SecurityKey sec_key;
|
||||
const double tick_size;
|
||||
const api::Side side; //trading side
|
||||
ChildTemplate* order_template = nullptr;
|
||||
OrderKey order_key;
|
||||
ChildState order_state;
|
||||
bool recv_book;
|
||||
Book book;
|
||||
Quantity top_delete; // this will be DONTCARE for covers
|
||||
Quantity cover_payup;// this will be DONTCARE for top
|
||||
LegData (size_t index_a,
|
||||
SecurityKey sec_key_a,
|
||||
double tick_size_a,
|
||||
api::Side side_a,
|
||||
ChildTemplate* order_template_a,
|
||||
Quantity qty)
|
||||
:
|
||||
index (index_a),
|
||||
sec_key (sec_key_a),
|
||||
tick_size(tick_size_a),
|
||||
side (side_a),
|
||||
order_template (order_template_a),
|
||||
order_key(null_order_key()),
|
||||
order_state(),
|
||||
recv_book(false),
|
||||
book(),
|
||||
top_delete(index == 0 ? qty.value() : 0),
|
||||
cover_payup(index == 0 ? 0 : qty.value())
|
||||
{
|
||||
}
|
||||
const BookSide& opp_md() const{
|
||||
return book.side(SpreaderUtils::invert_side(side));
|
||||
}
|
||||
bool is_top_spread() const{
|
||||
return index == 0;
|
||||
}
|
||||
void set_book (const Book& book_a){
|
||||
recv_book = true;
|
||||
book = book_a;
|
||||
}
|
||||
};
|
||||
|
||||
struct PyramidAlgo::PImpl {
|
||||
Status state = Status::WAITING_FOR_MD;
|
||||
IAlgoServices* algo_services = nullptr;
|
||||
IBeforeLaunchAlgoServices* bl_algo_services;
|
||||
PyramidAlgo::PyramidAlgoParams params;
|
||||
std::vector<LegData> legs;
|
||||
api::Side side;
|
||||
Price out_price;
|
||||
Quantity out_qty;
|
||||
PImpl(){
|
||||
}
|
||||
LegData* find_leg_from_sec (SecurityKey sec_key){
|
||||
for (auto& l : legs)
|
||||
if(l.sec_key == sec_key)
|
||||
return &l;
|
||||
return nullptr;
|
||||
}
|
||||
LegData* find_leg_from_ord_key (OrderKey ord_key){
|
||||
for (auto& l : legs)
|
||||
if(l.order_key == ord_key)
|
||||
return &l;
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
PyramidAlgo::PyramidAlgo() : me(new PImpl()) {}
|
||||
PyramidAlgo::~PyramidAlgo() {}
|
||||
IAlgoServices& PyramidAlgo::_algo() const { return *me->algo_services; }
|
||||
|
||||
// initialization /////////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
OrderOpResult PyramidAlgo::do_before_launch(IBeforeLaunchAlgoServices& serv) {
|
||||
me->bl_algo_services = &serv;
|
||||
auto& def = serv.definition();
|
||||
if (def.has_custom_def() && def.custom_def().has_dynamic()){
|
||||
auto conv_res = _get_creation_params(def.custom_def(), serv);
|
||||
if (std::get<1>(conv_res)){
|
||||
// params are good
|
||||
me->params = std::get<0>(conv_res);
|
||||
me->side = def.side();
|
||||
// top spread
|
||||
auto* t = _create_top_order_template(serv);
|
||||
double tick_size = serv.lookup_security(me->params.top_spread)->contract_spec().low_tick();
|
||||
me->legs.emplace_back(0, me->params.top_spread, tick_size, def.side(), t,
|
||||
me->params.top_delete);
|
||||
// covers
|
||||
size_t i = 0;
|
||||
for (SecurityKey key : me->params.cover_spreads){
|
||||
auto side = SpreaderUtils::invert_side(def.side());
|
||||
auto* t = _create_hedge_order_template(serv,i);
|
||||
double tick_size = serv.lookup_security(key)->contract_spec().low_tick();
|
||||
me->legs.emplace_back(i+1, key, tick_size, side, t, me->params.cover_payups[i]);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
else
|
||||
return {OrderError::ORDER_ERROR_INVALID_PARAMETER,
|
||||
std::get<2>(conv_res)};
|
||||
}
|
||||
else
|
||||
return {OrderError::ORDER_ERROR_INVALID_PARAMETER,
|
||||
std::string("Missing parameters")};
|
||||
return {};
|
||||
}
|
||||
void PyramidAlgo::do_launch(IAlgoServices& algo_services) {
|
||||
me->algo_services = &algo_services;
|
||||
me->out_price = algo_services.price();
|
||||
me->out_qty = algo_services.quantity();
|
||||
for (const LegData& l : me->legs)
|
||||
algo_services.subscribe_book(l.sec_key);
|
||||
}
|
||||
void PyramidAlgo::do_launch_attached(IAlgoServices& algo_services,
|
||||
OrderKey key,
|
||||
ChildState c) {
|
||||
me->algo_services = &algo_services;
|
||||
if(c.quantity != algo_services.quantity() ||
|
||||
!bts::securities::is_same(c.price, algo_services.price())){
|
||||
_cxl_and_end(ExitPath::ERR,
|
||||
"Pyramid price or quantity did not match the working order",
|
||||
true);
|
||||
}
|
||||
else{
|
||||
me->legs[0].order_key = key;
|
||||
me->out_price = c.price;
|
||||
me->out_qty = c.quantity;
|
||||
for (const LegData& l : me->legs)
|
||||
algo_services.subscribe_book(l.sec_key);
|
||||
_switch_state(PyramidAlgo::Status::WAITING_FOR_MD_ATTACH);
|
||||
on_child_change(key,c);
|
||||
}
|
||||
}
|
||||
// updates ////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
void PyramidAlgo::do_update(const api::orderman::Update& update) {
|
||||
LOG(OrderMan, Diag, "PyramidAlgo::do_update order:{} state:{} "
|
||||
"receiving update: {}",
|
||||
_algo().order_key().value(),
|
||||
static_cast<int>(me->state),
|
||||
utils::pb::to_string(update));
|
||||
auto conv_res = _get_update_params(update, me->params);
|
||||
if (!std::get<1>(conv_res)){
|
||||
LOG(OrderMan, Warn, "PyramidAlgo::do_update order:{} bad update, ignoring",
|
||||
_algo().order_key().value());
|
||||
return;
|
||||
}
|
||||
const PyramidAlgoParams& algo_params = std::get<0>(conv_res);
|
||||
Price price = Price(update.price());
|
||||
Quantity qty = Quantity(update.quantity());
|
||||
switch(me->state){
|
||||
case PyramidAlgo::Status::WAITING_FOR_MD:
|
||||
case PyramidAlgo::Status::WAITING_FOR_MD_ATTACH:
|
||||
LOG(OrderMan, Info, "PyramidAlgo::do_update order:{} state:{} ignored",
|
||||
_algo().order_key().value(),static_cast<int>(me->state));
|
||||
break;
|
||||
case PyramidAlgo::Status::WORKING:{
|
||||
bool pq_changed = _copy_update(algo_params, price, qty);
|
||||
if(_target_reached()){
|
||||
_cxl_and_end (PyramidAlgo::ExitPath::CANCEL, "Target reached");
|
||||
return;
|
||||
}
|
||||
if (_working_state_met()){
|
||||
if(pq_changed)
|
||||
_modify_top_spread_order();
|
||||
}
|
||||
else
|
||||
_cxl_and_end(PyramidAlgo::ExitPath::CANCEL,
|
||||
"Order cancelled (Cover prices not met)");
|
||||
break;
|
||||
}
|
||||
case PyramidAlgo::Status::DONE:
|
||||
break;
|
||||
}
|
||||
}
|
||||
// callbacks //////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
void PyramidAlgo::on_book(SecurityKey key, const Book& book) {
|
||||
LegData* leg_data = me->find_leg_from_sec(key);
|
||||
if(leg_data != nullptr){
|
||||
leg_data->set_book(book);
|
||||
_analyze_md_and_act();
|
||||
}
|
||||
}
|
||||
// this only gets called on am explicit algo cancel
|
||||
// from the outside
|
||||
IAlgoOrder::OnCancelResponse PyramidAlgo::on_cancel(){
|
||||
// cancel top spread, let hedges work, cancel algo
|
||||
switch(me->state){
|
||||
case PyramidAlgo::Status::WAITING_FOR_MD:
|
||||
case PyramidAlgo::Status::WAITING_FOR_MD_ATTACH:
|
||||
case PyramidAlgo::Status::WORKING:
|
||||
_cxl_and_end(PyramidAlgo::ExitPath::CANCEL,"Algo cancelled");
|
||||
break;
|
||||
case PyramidAlgo::Status::DONE:
|
||||
break;
|
||||
}
|
||||
return IAlgoOrder::OnCancelResponse::IGNORE;
|
||||
}
|
||||
void PyramidAlgo::on_child_change(OrderKey key, const ChildState &st) {
|
||||
LOG(OrderMan, Info,
|
||||
"PyramidAlgo::on_child_change key:{} child_key:{} state:{} status:{} "
|
||||
"total_fills:{} last_price:{}",
|
||||
_algo().order_key(),
|
||||
key,
|
||||
static_cast<int>(me->state),
|
||||
static_cast<int>(st.status),
|
||||
st.total_fills,
|
||||
st.last_price);
|
||||
LegData* leg = me->find_leg_from_ord_key (key);
|
||||
if (me->legs[0].order_key == key){
|
||||
switch(me->state){
|
||||
case PyramidAlgo::Status::WAITING_FOR_MD:
|
||||
bts_assert_msg (false, "No child orders");
|
||||
break;
|
||||
case PyramidAlgo::Status::WAITING_FOR_MD_ATTACH:
|
||||
leg->order_state = st;
|
||||
_algo().update_fill_state(st.total_fills, st.avg_price);
|
||||
_check_for_completion();
|
||||
break;
|
||||
case PyramidAlgo::Status::WORKING:
|
||||
leg->order_state = st;
|
||||
_algo().update_fill_state(st.total_fills, st.avg_price);
|
||||
_send_hedges(st.last_fills);
|
||||
_check_for_completion();
|
||||
break;
|
||||
case PyramidAlgo::Status::DONE:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// stateless conversion ///////////////////////////////////////////////////////
|
||||
|
||||
PyramidAlgo::PyramidAlgoParams PyramidAlgo::_convert_params (
|
||||
const CustomOrderDefinition& cod){
|
||||
const DynamicOrderDefinition& def = cod.dynamic();
|
||||
const auto& params = def.order_params();
|
||||
PyramidAlgoParams rv;
|
||||
// top contract
|
||||
auto r = get_if<uint32_t>(params, "Top Spread");
|
||||
rv.top_spread = r.has_value() ? SecurityKey(r.value()) : SecurityKey(0);
|
||||
// top delete
|
||||
r = get_if<uint32_t>(params, "Delete");
|
||||
rv.top_delete = Quantity(r.has_value() ? r.value() : UINT32_MAX);
|
||||
for (size_t i = 0; i < 5; i++){
|
||||
auto idx = std::to_string(i+1);
|
||||
auto b = get_if<uint32_t>(params, "Spread " + idx);
|
||||
if (b.has_value() && b.value() != 0){
|
||||
rv.cover_spreads.emplace_back(b.value());
|
||||
auto pu = get_if<uint32_t>(params, "Spread " + idx + " Payup");
|
||||
rv.cover_payups.emplace_back(pu.has_value() ? pu.value() : UINT32_MAX);
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
std::tuple<PyramidAlgo::PyramidAlgoParams,bool,std::string>
|
||||
PyramidAlgo::_get_creation_params(const CustomOrderDefinition& cod,
|
||||
IBeforeLaunchAlgoServices& serv){
|
||||
PyramidAlgo::PyramidAlgoParams rv = _convert_params(cod);
|
||||
// error checking
|
||||
if(rv.top_spread.value() != serv.security().id())
|
||||
return std::make_tuple(rv,false,
|
||||
"Algo can only be launched from the Top Spread");
|
||||
if(rv.cover_spreads.size() < 2)
|
||||
return std::make_tuple(rv,false,
|
||||
"Not enough cover spreads");
|
||||
if (rv.cover_spreads[0].value() == 0 ||
|
||||
rv.cover_spreads[1].value() == 0)
|
||||
return std::make_tuple(rv,false,
|
||||
"Not enough cover spreads");
|
||||
return std::make_tuple(rv,true,std::string(""));
|
||||
}
|
||||
|
||||
std::tuple<PyramidAlgo::PyramidAlgoParams,bool,std::string>
|
||||
PyramidAlgo::_get_update_params(const Update& update,
|
||||
const PyramidAlgoParams& curr_params){
|
||||
if(update.has_custom() && update.custom().has_dynamic()){
|
||||
// means there is a params change
|
||||
PyramidAlgoParams new_params = _convert_params(update.custom());
|
||||
if(new_params.top_spread != curr_params.top_spread ||
|
||||
new_params.cover_spreads.size() != curr_params.cover_spreads.size())
|
||||
return std::make_tuple(new_params,false,"Contracts can not be updated");
|
||||
for (size_t i=0; i < curr_params.cover_spreads.size(); i++)
|
||||
if(new_params.cover_spreads[i] != curr_params.cover_spreads[i])
|
||||
return std::make_tuple(new_params,false,"Contracts can not be updated");
|
||||
return std::make_tuple(new_params,true,std::string(""));
|
||||
}
|
||||
else
|
||||
return std::make_tuple(curr_params,true,std::string(""));
|
||||
}
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// order template creation/////////////////////////////////////////////////////
|
||||
|
||||
ChildTemplate* PyramidAlgo::_create_top_order_template (
|
||||
IBeforeLaunchAlgoServices& serv) const{
|
||||
OrderDefinition order_def = serv.definition();
|
||||
order_def.set_security_key (me->params.top_spread.value());
|
||||
order_def.set_side(me->side);
|
||||
order_def.mutable_custom_def()->mutable_limit()->MergeFrom (
|
||||
LimitOrderDefinition());
|
||||
return &(serv.make_child_template(order_def));
|
||||
}
|
||||
|
||||
ChildTemplate* PyramidAlgo::_create_hedge_order_template (
|
||||
IBeforeLaunchAlgoServices& serv,
|
||||
size_t hedge_idx) const{
|
||||
OrderDefinition order_def = serv.definition();
|
||||
order_def.set_attach_target_order_key(null_order_key().value());
|
||||
order_def.set_security_key (me->params.cover_spreads[hedge_idx].value());
|
||||
order_def.set_side(SpreaderUtils::invert_side(me->side));
|
||||
order_def.set_sub_type(ORDER_SUB_TYPE_HEDGING_LEG);
|
||||
LeanOrderDefinition lean;
|
||||
lean.mutable_cross_threshold()->set_absolute(me->params.cover_payups[hedge_idx].value());
|
||||
lean.set_max_chase_ticks(1);
|
||||
lean.set_trade_toward_behavior(LeanOrderDefinition::NO_CHANGE);
|
||||
lean.mutable_child()->mutable_limit()->MergeFrom (
|
||||
LimitOrderDefinition());
|
||||
order_def.mutable_custom_def()->mutable_lean()->MergeFrom (lean);
|
||||
return &(serv.make_child_template(order_def));
|
||||
}
|
||||
|
||||
void PyramidAlgo::_analyze_md_and_act(){
|
||||
switch(me->state){
|
||||
case PyramidAlgo::Status::WAITING_FOR_MD:
|
||||
if(!_md_recvd())
|
||||
return;
|
||||
// received data for the first time
|
||||
if (_working_state_met()){
|
||||
// enter order, and switch state
|
||||
LegData& top_leg = me->legs[0];
|
||||
// this is the only place top spread order is sent (once)
|
||||
top_leg.order_key = _algo().launch_child(
|
||||
*top_leg.order_template,
|
||||
me->out_price,
|
||||
me->out_qty);
|
||||
LOG(OrderMan, Info,"PyramidAlgo::_analyze_md_and_act launching order key:{} "
|
||||
"child_key:{} price:{} qty:{}",
|
||||
_algo().order_key(),
|
||||
top_leg.order_key,
|
||||
me->out_price,
|
||||
me->out_qty);
|
||||
_switch_state(PyramidAlgo::Status::WORKING);
|
||||
}
|
||||
else
|
||||
_cxl_and_end(PyramidAlgo::ExitPath::CANCEL,
|
||||
"Order cancelled (Cover prices not met)");
|
||||
break;
|
||||
case PyramidAlgo::Status::WAITING_FOR_MD_ATTACH:
|
||||
if(!_md_recvd())
|
||||
return;
|
||||
// received data for the first time
|
||||
if (_working_state_met())
|
||||
_switch_state(PyramidAlgo::Status::WORKING);
|
||||
else
|
||||
_cxl_and_end(PyramidAlgo::ExitPath::CANCEL,
|
||||
"Order detached (Cover prices not met)",
|
||||
true);
|
||||
break;
|
||||
case PyramidAlgo::Status::WORKING:
|
||||
if (!_working_state_met())
|
||||
_cxl_and_end(PyramidAlgo::ExitPath::CANCEL,
|
||||
"Order cancelled (Cover prices not met)");
|
||||
break;
|
||||
case PyramidAlgo::Status::DONE:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void PyramidAlgo::_switch_state(Status new_state){
|
||||
switch(new_state){
|
||||
case (PyramidAlgo::Status::WAITING_FOR_MD):
|
||||
bts_assert(false);
|
||||
break;
|
||||
case (PyramidAlgo::Status::WAITING_FOR_MD_ATTACH):
|
||||
bts_assert(me->state == PyramidAlgo::Status::WAITING_FOR_MD);
|
||||
break;
|
||||
case (PyramidAlgo::Status::WORKING):
|
||||
bts_assert(me->state == PyramidAlgo::Status::WAITING_FOR_MD ||
|
||||
me->state == PyramidAlgo::Status::WAITING_FOR_MD_ATTACH);
|
||||
break;
|
||||
case (PyramidAlgo::Status::DONE):
|
||||
bts_assert(
|
||||
// when an order is entered and the criteria is not met
|
||||
me->state == PyramidAlgo::Status::WAITING_FOR_MD ||
|
||||
// when an order is attached and the market conditions are not met
|
||||
me->state == PyramidAlgo::Status::WAITING_FOR_MD_ATTACH ||
|
||||
// when the child order gets into an unexpected state
|
||||
me->state == PyramidAlgo::Status::WORKING);
|
||||
break;
|
||||
}
|
||||
LOG(OrderMan, Info,"PyramidAlgo::_switch_state key:{} {}->{} ",
|
||||
_algo().order_key(),
|
||||
static_cast<int>(me->state),
|
||||
static_cast<int>(new_state));
|
||||
me->state = new_state;
|
||||
}
|
||||
|
||||
void PyramidAlgo::_send_hedges (Quantity filled_qty){
|
||||
if (filled_qty.value() > 0)
|
||||
for (auto& l : me->legs)
|
||||
if(!l.is_top_spread()){
|
||||
const auto& inside_md = l.opp_md()[0];
|
||||
Price hedge_price = Price(inside_md.price());
|
||||
uint32_t inside_md_qty = inside_md.size();
|
||||
if (l.cover_payup.value() != 0 &&
|
||||
inside_md_qty > l.cover_payup.value())
|
||||
hedge_price = securities::worsen_price(l.side, hedge_price, Price(l.tick_size));
|
||||
// check payup
|
||||
l.order_key = _algo().launch_child(
|
||||
*l.order_template,
|
||||
hedge_price,
|
||||
filled_qty);
|
||||
_algo().detach_child(l.order_key);
|
||||
}
|
||||
}
|
||||
|
||||
void PyramidAlgo::_modify_top_spread_order(){
|
||||
Update child_update;
|
||||
child_update.set_price(me->out_price.value());
|
||||
child_update.set_quantity(me->out_qty.value());
|
||||
LOG(OrderMan, Info,"PyramidAlgo::_modify_top_spread_order modifying order key:{} "
|
||||
"child_key:{} price:{} qty:{}",
|
||||
_algo().order_key(),
|
||||
me->legs[0].order_key,
|
||||
me->out_price,
|
||||
me->out_qty);
|
||||
_algo().update_child(me->legs[0].order_key, child_update);
|
||||
}
|
||||
// copies the params, price and qty to the state
|
||||
// retuns true is the price or qty has changed
|
||||
bool PyramidAlgo::_copy_update(const PyramidAlgoParams& algo_params,
|
||||
Price price, Quantity qty){
|
||||
// copy input params (which are stored seperately)
|
||||
me->params.top_delete = algo_params.top_delete;
|
||||
size_t cov_idx = 0;
|
||||
for (Quantity payup : algo_params.cover_payups)
|
||||
me->params.cover_payups[cov_idx++] = payup;
|
||||
// copy leg data
|
||||
cov_idx = 0;
|
||||
me->legs[0].top_delete = algo_params.top_delete;
|
||||
for (Quantity pu : algo_params.cover_payups){
|
||||
LegData& cover_leg = me->legs[cov_idx+1];
|
||||
if(cover_leg.cover_payup != pu){
|
||||
cover_leg.cover_payup = pu;
|
||||
cover_leg.order_template = _create_hedge_order_template(
|
||||
*me->bl_algo_services,
|
||||
cov_idx);
|
||||
}
|
||||
cov_idx++;
|
||||
}
|
||||
// copy price and qty (returns true is they have changed)
|
||||
bool pq_changed = me->out_qty.value() != qty.value() ||
|
||||
!bts::securities::is_same(me->out_price, price);
|
||||
me->out_price = price;
|
||||
me->out_qty = qty;
|
||||
return pq_changed;
|
||||
}
|
||||
// if the top spread order is in a final state, the algo
|
||||
// algo goes to the final state
|
||||
void PyramidAlgo::_check_for_completion(){
|
||||
const ChildState& top_ord = me->legs[0].order_state;
|
||||
switch (top_ord.status){
|
||||
case (ChildStatus::WORKING):
|
||||
break;
|
||||
case (ChildStatus::COMPLETED):
|
||||
_cxl_and_end(PyramidAlgo::ExitPath::ERR,"");
|
||||
break;
|
||||
case (ChildStatus::CANCELED):
|
||||
_cxl_and_end(PyramidAlgo::ExitPath::ERR,
|
||||
"Top spread unexpectedly cancelled");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void PyramidAlgo::_cxl_and_end(PyramidAlgo::ExitPath exit_path,
|
||||
const std::string& msg,
|
||||
bool detach_top){
|
||||
if(me->legs[0].order_key != null_order_key()){
|
||||
const ChildState& top_ord_state = me->legs[0].order_state;
|
||||
if(top_ord_state.status == ChildStatus::WORKING){
|
||||
if(detach_top)
|
||||
_algo().detach_child(me->legs[0].order_key);
|
||||
else
|
||||
_algo().cancel_child(me->legs[0].order_key);
|
||||
}
|
||||
}
|
||||
switch(exit_path){
|
||||
case PyramidAlgo::ExitPath::ERR:
|
||||
_algo().terminate_error(msg);
|
||||
break;
|
||||
case PyramidAlgo::ExitPath::CANCEL:
|
||||
_algo().cancel(msg);
|
||||
break;
|
||||
case PyramidAlgo::ExitPath::COMPLETE:
|
||||
_algo().complete();
|
||||
break;
|
||||
}
|
||||
_switch_state(PyramidAlgo::Status::DONE);
|
||||
}
|
||||
// true the out qty is changed it be below
|
||||
// the filled qty
|
||||
bool PyramidAlgo::_target_reached() const{
|
||||
return me->legs[0].order_state.total_fills.value() >=
|
||||
me->out_qty.value();
|
||||
}
|
||||
|
||||
bool PyramidAlgo::_md_recvd() const{
|
||||
for (const LegData& l : me->legs)
|
||||
if(!l.recv_book)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool gr_than_eq(double p1, double p2){
|
||||
return securities::test_price_equality(p1,p2) || p1 > p2;
|
||||
}
|
||||
|
||||
bool less_than_eq(double p1, double p2){
|
||||
return securities::test_price_equality(p1,p2) || p1 < p2;
|
||||
}
|
||||
|
||||
bool PyramidAlgo::_working_state_met() const{
|
||||
double cover_sum = 0.0;
|
||||
size_t i = 0;
|
||||
for (const auto& l : me->legs)
|
||||
if (i++ > 0)
|
||||
cover_sum += l.opp_md()[0].price();
|
||||
bool rv = !os::is_nan(cover_sum) &&
|
||||
(
|
||||
(
|
||||
me->side == api::Side::SIDE_BUY &&
|
||||
less_than_eq(me->out_price.value(),cover_sum)
|
||||
)
|
||||
||
|
||||
(
|
||||
me->side == api::Side::SIDE_SELL &&
|
||||
gr_than_eq(me->out_price.value(),cover_sum)
|
||||
)
|
||||
);
|
||||
if (!rv && !os::is_nan(cover_sum)){
|
||||
// price condition is not met, but if the
|
||||
// cum qty at the top leg price is > threashold
|
||||
// then the condition is met ()
|
||||
const auto& top_leg = me->legs[0];
|
||||
Quantity cumm_level_qty;
|
||||
SpreaderUtils::find_qty_upto_price_level(top_leg.book,
|
||||
top_leg.side,
|
||||
Price(me->out_price),
|
||||
0.0,
|
||||
cumm_level_qty);
|
||||
rv = cumm_level_qty.value() > top_leg.top_delete.value();
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,74 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/orderman/orders/algo/IAlgoOrder.h"
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
|
||||
class ChildTemplate;
|
||||
struct LegData;
|
||||
|
||||
class PyramidAlgo : public IAlgoOrder {
|
||||
public:
|
||||
PyramidAlgo();
|
||||
~PyramidAlgo();
|
||||
struct PyramidAlgoParams{
|
||||
// first one is the top
|
||||
SecurityKey top_spread;
|
||||
Quantity top_delete;
|
||||
std::vector<SecurityKey> cover_spreads;
|
||||
std::vector<Quantity> cover_payups;
|
||||
};
|
||||
public:
|
||||
OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override;
|
||||
void do_launch(IAlgoServices &) override;
|
||||
void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override;
|
||||
void do_update(api::orderman::Update const &) override;
|
||||
void on_book(SecurityKey, Book const &) override;
|
||||
void on_child_change(OrderKey, ChildState const &) override;
|
||||
IAlgoOrder::OnCancelResponse on_cancel() override;
|
||||
|
||||
private:
|
||||
enum class Status;
|
||||
enum class ExitPath;
|
||||
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> me;
|
||||
private:
|
||||
IAlgoServices& _algo() const ;
|
||||
// converts parameters from the CustomOrderDefinition::dynamic
|
||||
// to PyramidAlgoParams
|
||||
static PyramidAlgoParams _convert_params (
|
||||
const bts::api::orderman::CustomOrderDefinition&);
|
||||
static std::tuple<PyramidAlgoParams,bool,std::string> _get_creation_params(
|
||||
const bts::api::orderman::CustomOrderDefinition&,
|
||||
IBeforeLaunchAlgoServices&);
|
||||
static std::tuple<PyramidAlgoParams,bool,std::string> _get_update_params(
|
||||
const api::orderman::Update&,
|
||||
const PyramidAlgoParams& curr_params);
|
||||
ChildTemplate* _create_top_order_template (IBeforeLaunchAlgoServices&) const;
|
||||
ChildTemplate* _create_hedge_order_template (IBeforeLaunchAlgoServices&,
|
||||
size_t) const;
|
||||
// acts on md, cognizant of the state
|
||||
void _analyze_md_and_act();
|
||||
void _switch_state (Status new_status);
|
||||
void _send_hedges (Quantity filled_qty);
|
||||
void _modify_top_spread_order();
|
||||
// returns true is the price, qty changes
|
||||
bool _copy_update(const PyramidAlgoParams& algo_params,
|
||||
Price price, Quantity qty);
|
||||
void _check_for_completion();
|
||||
// cxl's the working top leg order (if any), detaches
|
||||
// all hedges. if is_error then terminates algo, is
|
||||
// is_cxl then cxl's algo, otherwise completes it
|
||||
void _cxl_and_end(ExitPath exit_path,
|
||||
const std::string& err_txt,
|
||||
bool detach_top = false);
|
||||
bool _target_reached() const;
|
||||
// true is all legs have recvd md
|
||||
bool _md_recvd() const;
|
||||
bool _working_state_met() const;
|
||||
};
|
||||
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,253 +0,0 @@
|
||||
|
||||
#include "lib/plugin/SparkServices.h"
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/logging/logging.h"
|
||||
#include "lib/orderman/orderman_utils/orderman_utils.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.h"
|
||||
#include "lib/config/protos/toggles.pb.h"
|
||||
#include "lib/config/config.h"
|
||||
#include "DormanAlgo.h"
|
||||
#include "PyramidAlgo.h"
|
||||
#include "TASAlgo.h"
|
||||
#include "TASCounterAlgo.h"
|
||||
#include "OnSignalAlgo.h"
|
||||
|
||||
using namespace bts;
|
||||
using namespace api::orderman;
|
||||
using namespace orderman::dorman;
|
||||
using namespace orderman;
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace dorman {
|
||||
|
||||
template <class OK,class ERR>
|
||||
using Result = std::variant<OK,ERR>;
|
||||
Result<AlgoParams,OrderOpResult> bad_definition(const char* msg) { return {OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON, msg}}; }
|
||||
|
||||
// Validate DynamicOrderDefinition and construct parameter object
|
||||
Result<AlgoParams,OrderOpResult> to_dorman_params(const api::orderman::DynamicOrderDefinition& def) {
|
||||
const auto& params = def.order_params();
|
||||
AlgoParams res;
|
||||
|
||||
//
|
||||
// Step Table
|
||||
for (size_t x = 0; x < 5; ++x) {
|
||||
auto xs = std::to_string(x+1);
|
||||
auto mq = get_if<uint32_t>(params, "Market Quantity " + xs).value_or(0);
|
||||
auto oq = get_if<uint32_t>(params, "Order Quantity " + xs).value_or(0);
|
||||
if (mq && oq) {
|
||||
res.steps.step_table.push_back({ mq, oq });
|
||||
}
|
||||
}
|
||||
std::sort(res.steps.step_table.begin(), res.steps.step_table.end());
|
||||
res.steps.maximum = get_if<uint32_t>(params, "Max Size").value_or(-1);
|
||||
res.steps.trail_seconds = get_if<uint32_t>(params, "Trail Seconds").value_or(0);
|
||||
|
||||
//
|
||||
// Clip limit
|
||||
res.clip_limit = get_if<uint32_t>(params, "Clip Size").value_or(0);
|
||||
|
||||
//
|
||||
// scratch
|
||||
auto enable_scratch = get_if<bool>(params, "Enable Scratch");
|
||||
if (enable_scratch && enable_scratch.value()) {
|
||||
auto overfill = get_if<uint32_t>(params, "Max Overfill");
|
||||
if (!overfill) return bad_definition("Missing 'Max Overfill'");
|
||||
res.scratch = { overfill.value() };
|
||||
}
|
||||
|
||||
//
|
||||
// profit orders
|
||||
auto enable_profit_orders = get_if<bool>(params, "Profit Orders");
|
||||
if (enable_profit_orders && enable_profit_orders.value()) {
|
||||
auto ticks = get_if<uint32_t>(params, "Ticks Away");
|
||||
if (!ticks) return bad_definition("Missing 'Ticks Away'");
|
||||
res.profit_orders = { ticks.value() };
|
||||
}
|
||||
|
||||
//
|
||||
// trade accumulation
|
||||
auto trade_acc = get_if<bool>(params, "Trade Accumulation").value_or(false);
|
||||
if (trade_acc) {
|
||||
TradeAccumulationParams tap;
|
||||
|
||||
auto contracts = get_if<uint32_t>(params, "Trade Contracts");
|
||||
if (!contracts) return bad_definition("Missing 'Trade Accumulation # Contracts'");
|
||||
tap.contracts = contracts.value();
|
||||
|
||||
auto interval = get_if<uint32_t>(params, "Trade Interval (seconds)");
|
||||
if (!interval) return bad_definition("Missing 'Trade Accumulation Interval'");
|
||||
tap.seconds = interval.value();
|
||||
|
||||
auto sleep = get_if<uint32_t>(params, "Trade Sleep (seconds)");
|
||||
if (!sleep) return bad_definition("Missing 'Trade Accumulation Sleep'");
|
||||
tap.sleep_seconds = sleep.value();
|
||||
|
||||
res.trade_accumulation = {tap};
|
||||
}
|
||||
|
||||
return {res};
|
||||
}
|
||||
|
||||
extern "C" void init_dorman_plugin(bts::SparkServices &srv) {
|
||||
DynamicOrderDescriptor join_desc;
|
||||
|
||||
join_desc.set_dynamic_order_type("Dorman");
|
||||
|
||||
*join_desc.add_param_desc() = param_array("what", param_double("").param_type());
|
||||
|
||||
|
||||
*join_desc.add_param_desc() = param_uint32("Market Quantity 1");
|
||||
*join_desc.add_param_desc() = param_uint32("Order Quantity 1");
|
||||
*join_desc.add_param_desc() = param_uint32("Market Quantity 2");
|
||||
*join_desc.add_param_desc() = param_uint32("Order Quantity 2");
|
||||
*join_desc.add_param_desc() = param_uint32("Market Quantity 3");
|
||||
*join_desc.add_param_desc() = param_uint32("Order Quantity 3");
|
||||
*join_desc.add_param_desc() = param_uint32("Market Quantity 4");
|
||||
*join_desc.add_param_desc() = param_uint32("Order Quantity 4");
|
||||
*join_desc.add_param_desc() = param_uint32("Market Quantity 5");
|
||||
*join_desc.add_param_desc() = param_uint32("Order Quantity 5");
|
||||
|
||||
*join_desc.add_param_desc() = param_uint32("Max Size");
|
||||
*join_desc.add_param_desc() = param_uint32("Trail Seconds");
|
||||
*join_desc.add_param_desc() = param_uint32("Clip Size");
|
||||
*join_desc.add_param_desc() = param_bool("Enable Scratch");
|
||||
*join_desc.add_param_desc() = param_uint32("Max Overfill");
|
||||
*join_desc.add_param_desc() = param_bool("Profit Orders");
|
||||
*join_desc.add_param_desc() = param_uint32("Ticks Away");
|
||||
|
||||
*join_desc.add_param_desc() = param_bool("Trade Accumulation");
|
||||
*join_desc.add_param_desc() = param_uint32("Trade Contracts");
|
||||
*join_desc.add_param_desc() = param_uint32("Trade Interval (seconds)");
|
||||
*join_desc.add_param_desc() = param_uint32("Trade Sleep (seconds)");
|
||||
|
||||
srv.register_dynamic_algo_order(join_desc, []() { return std::make_unique<DormanAlgo>(); });
|
||||
}
|
||||
|
||||
extern "C" void init_pyramid_plugin(bts::SparkServices& srv) {
|
||||
DynamicOrderDescriptor join_desc;
|
||||
|
||||
join_desc.set_dynamic_order_type("Pyramid");
|
||||
|
||||
*join_desc.add_param_desc() = param_security_key("Top Spread");
|
||||
*join_desc.add_param_desc() = param_uint32("Delete");
|
||||
*join_desc.add_param_desc() = param_security_key("Spread 1");
|
||||
*join_desc.add_param_desc() = param_uint32("Spread 1 Payup");
|
||||
*join_desc.add_param_desc() = param_order("Spread 1 Order");
|
||||
*join_desc.add_param_desc() = param_security_key("Spread 2");
|
||||
*join_desc.add_param_desc() = param_uint32("Spread 2 Payup");
|
||||
*join_desc.add_param_desc() = param_order("Spread 2 Order");
|
||||
*join_desc.add_param_desc() = param_security_key("Spread 3");
|
||||
*join_desc.add_param_desc() = param_uint32("Spread 3 Payup");
|
||||
*join_desc.add_param_desc() = param_order("Spread 3 Order");
|
||||
*join_desc.add_param_desc() = param_security_key("Spread 4");
|
||||
*join_desc.add_param_desc() = param_uint32("Spread 4 Payup");
|
||||
*join_desc.add_param_desc() = param_order("Spread 4 Order");
|
||||
*join_desc.add_param_desc() = param_security_key("Spread 5");
|
||||
*join_desc.add_param_desc() = param_uint32("Spread 5 Payup");
|
||||
*join_desc.add_param_desc() = param_order("Spread 5 Order");
|
||||
|
||||
srv.register_dynamic_algo_order(join_desc, []() { return std::make_unique<orderman::PyramidAlgo>(); });
|
||||
}
|
||||
|
||||
extern "C" void init_tascounter_plugin(bts::SparkServices& srv) {
|
||||
DynamicOrderDescriptor join_desc;
|
||||
|
||||
join_desc.set_dynamic_order_type("TASCounter");
|
||||
// all 6 contracts. They can theoretically be inferred from the front month
|
||||
// since T1 are calendars 1 month apart starting from the front month
|
||||
// ex Mar-May, May-Jul, Jul-Sep being T1 front, second and third respectively
|
||||
// (assuming Mar is the front month)
|
||||
*join_desc.add_param_desc() = param_security_key("T1 Front");
|
||||
*join_desc.add_param_desc() = param_security_key("T1 Second");
|
||||
*join_desc.add_param_desc() = param_security_key("T1 Third");
|
||||
*join_desc.add_param_desc() = param_security_key("T2 Front");
|
||||
*join_desc.add_param_desc() = param_security_key("T2 Second");
|
||||
*join_desc.add_param_desc() = param_security_key("T3 Front");
|
||||
// tas contracts (could have been derived)
|
||||
*join_desc.add_param_desc() = param_security_key("T1 Front TAS");
|
||||
*join_desc.add_param_desc() = param_security_key("T1 Second TAS");
|
||||
*join_desc.add_param_desc() = param_security_key("T1 Third TAS");
|
||||
// automatic orders
|
||||
*join_desc.add_param_desc() = param_uint32("T1 Front Time");
|
||||
*join_desc.add_param_desc() = param_uint32("T1 Front Qty");
|
||||
*join_desc.add_param_desc() = param_bool("T1 Front Order Enabled");
|
||||
|
||||
*join_desc.add_param_desc() = param_uint32("T1 Second Time");
|
||||
*join_desc.add_param_desc() = param_uint32("T1 Second Qty");
|
||||
*join_desc.add_param_desc() = param_bool("T1 Second Order Enabled");
|
||||
|
||||
*join_desc.add_param_desc() = param_uint32("T1 Third Time");
|
||||
*join_desc.add_param_desc() = param_uint32("T1 Third Qty");
|
||||
*join_desc.add_param_desc() = param_bool("T1 Third Order Enabled");
|
||||
// settlement time
|
||||
*join_desc.add_param_desc() = param_uint32("Settlement Start Hour");
|
||||
*join_desc.add_param_desc() = param_uint32("Settlement Start Minutes");
|
||||
*join_desc.add_param_desc() = param_uint32("Settlement Start Seconds");
|
||||
*join_desc.add_param_desc() = param_uint32("Settlement Period (seconds)");
|
||||
|
||||
srv.register_dynamic_algo_order(join_desc, []() { return std::make_unique<orderman::TASCounterAlgo>(); });
|
||||
}
|
||||
|
||||
extern "C" void init_tas_plugin(bts::SparkServices& srv) {
|
||||
DynamicOrderDescriptor tas_desc;
|
||||
|
||||
tas_desc.set_dynamic_order_type("TAS");
|
||||
|
||||
size_t n_child_ords = 8;
|
||||
for (size_t i=0; i< n_child_ords; i++){
|
||||
auto idx = std::to_string(i+1);
|
||||
*tas_desc.add_param_desc() = param_double("Order " + idx + " Price");
|
||||
*tas_desc.add_param_desc() = param_uint32("Order " + idx + " Quantity");
|
||||
*tas_desc.add_param_desc() = param_bool("Order " + idx + " Buy?");
|
||||
}
|
||||
srv.register_dynamic_algo_order(tas_desc, []() { return std::make_unique<orderman::TASAlgo>(); });
|
||||
}
|
||||
|
||||
extern "C" void init_limit_cover(bts::SparkServices & srv) {
|
||||
DynamicOrderDescriptor lc_desc;
|
||||
lc_desc.set_dynamic_order_type("LimitCover");
|
||||
LimitCoverAdapter::define_proto(lc_desc);
|
||||
srv.register_dynamic_algo_order(lc_desc, []() { return std::make_unique<orderman::LimitCoverAlgo>(); });
|
||||
}
|
||||
|
||||
extern "C" void init_on_signal_plugin(bts::SparkServices& srv) {
|
||||
DynamicOrderDescriptor on_signal;
|
||||
on_signal.set_dynamic_order_type("OnSignal");
|
||||
*on_signal.add_param_desc() = param_uint32("Time Hours");
|
||||
*on_signal.add_param_desc() = param_uint32("Time Minutes");
|
||||
*on_signal.add_param_desc() = param_uint32("Time Seconds");
|
||||
*on_signal.add_param_desc() = param_bool("Preopen");
|
||||
*on_signal.add_param_desc() = param_bool("Open");
|
||||
// contracts who's signals have to be received to send the algo
|
||||
*on_signal.add_param_desc() = param_security_key("Signal Contract 1");
|
||||
size_t n_child_ords = 10;
|
||||
for (size_t i=0; i< n_child_ords; i++){
|
||||
auto idx = std::to_string(i+1);
|
||||
*on_signal.add_param_desc() = param_security_key("Order " + idx + " Contract");
|
||||
*on_signal.add_param_desc() = param_order("Order " + idx);
|
||||
*on_signal.add_param_desc() = param_double("Order " + idx + " Price");
|
||||
*on_signal.add_param_desc() = param_int32("Order " + idx + " Quantity");
|
||||
}
|
||||
srv.register_dynamic_algo_order(on_signal, []() { return std::make_unique<orderman::OnSignalAlgo>(); });
|
||||
}
|
||||
|
||||
extern "C" void init_spark_plugin(bts::SparkServices &srv) {
|
||||
auto& dyn_algo_config = config::get<config::toggles::DynamicAlgos>();
|
||||
if(dyn_algo_config.enable_dorman())
|
||||
init_dorman_plugin(srv);
|
||||
if(dyn_algo_config.enable_pyramid())
|
||||
init_pyramid_plugin(srv);
|
||||
if(dyn_algo_config.enable_tas())
|
||||
init_tas_plugin(srv);
|
||||
if(dyn_algo_config.enable_tascounter())
|
||||
init_tascounter_plugin(srv);
|
||||
if (dyn_algo_config.enable_limit_cover())
|
||||
init_limit_cover(srv);
|
||||
if (dyn_algo_config.enable_onsignal())
|
||||
init_on_signal_plugin(srv);
|
||||
}
|
||||
|
||||
}}}
|
||||
@@ -1,222 +0,0 @@
|
||||
#include "lib/orderman/orders/algo/algo_orders/TASAlgo.h"
|
||||
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/orderman/order_factory/IOrderFactory.h"
|
||||
#include "lib/orderman/orderman_utils/Book.h"
|
||||
#include "lib/orderman/orderman_utils/orderman_utils.h"
|
||||
#include "lib/orderman/orders/algo/IAlgoServices.h"
|
||||
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h"
|
||||
#include "lib/os/os.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/utils/PBUtils.h"
|
||||
#include "lib/utils/datetime.h"
|
||||
#include <stdint.h>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
|
||||
using namespace api::orderman;
|
||||
|
||||
enum class TASAlgo::Status { WAITING_FOR_SIGNAL, WORKING, DONE };
|
||||
|
||||
struct TASLegData{
|
||||
api::Side side; //trading side
|
||||
Price price;
|
||||
Quantity quantity;
|
||||
ChildTemplate* order_template = nullptr;
|
||||
OrderKey order_key;
|
||||
ChildState order_state;
|
||||
TASLegData (api::Side side,
|
||||
Price price,
|
||||
Quantity quantity,
|
||||
ChildTemplate* order_template)
|
||||
:
|
||||
side (side),
|
||||
price(price),
|
||||
quantity(quantity),
|
||||
order_template (order_template),
|
||||
order_key(null_order_key()),
|
||||
order_state(){
|
||||
order_state.status = ChildStatus::WORKING;
|
||||
}
|
||||
};
|
||||
|
||||
struct TASAlgo::PImpl {
|
||||
Status state = Status::WAITING_FOR_SIGNAL;
|
||||
IAlgoServices* algo_services = nullptr;
|
||||
SecurityKey sec_key = SecurityKey(0);
|
||||
TASAlgo::TASAlgoParams algo_params;
|
||||
std::vector<TASLegData> legs;
|
||||
bts::datetime::PTime start_time = bts::datetime::local_now();
|
||||
PImpl(){
|
||||
}
|
||||
TASLegData* find_leg_from_ord_key (OrderKey ord_key){
|
||||
for (auto& l : legs)
|
||||
if(l.order_key == ord_key)
|
||||
return &l;
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
TASAlgo::TASAlgo() : me(new PImpl()) {}
|
||||
TASAlgo::~TASAlgo() {}
|
||||
// initialization /////////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
OrderOpResult TASAlgo::do_before_launch(IBeforeLaunchAlgoServices& serv) {
|
||||
auto& def = serv.definition();
|
||||
if (def.has_custom_def() && def.custom_def().has_dynamic()){
|
||||
const auto& sec = serv.security();
|
||||
me->sec_key = SecurityKey(sec.id());
|
||||
me->algo_params = _convert_params(def.custom_def());
|
||||
if (me->algo_params.child_orders.size() > 0){
|
||||
for (const auto& t : me->algo_params.child_orders){
|
||||
Price price = std::get<0>(t);
|
||||
Quantity quantity = std::get<1>(t);
|
||||
api::Side side = std::get<2>(t);
|
||||
auto* ordt = _create_order_template(
|
||||
serv,
|
||||
SecurityKey(sec.id()),
|
||||
side);
|
||||
me->legs.emplace_back(side,
|
||||
price,
|
||||
quantity,
|
||||
ordt);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
}
|
||||
return {OrderError::ORDER_ERROR_INVALID_PARAMETER,
|
||||
std::string("Parameters are not well formed")};
|
||||
}
|
||||
void TASAlgo::do_launch(IAlgoServices& algo_services) {
|
||||
me->algo_services = &algo_services;
|
||||
_algo().subscribe_status(me->sec_key);
|
||||
//_algo().subscribe_timer();
|
||||
}
|
||||
void TASAlgo::do_launch_attached(IAlgoServices& algo_services,
|
||||
OrderKey,
|
||||
ChildState) {
|
||||
me->algo_services = &algo_services;
|
||||
_cxl_and_end(true, "TAS Algo can not be attached to working orders");
|
||||
}
|
||||
// updates ////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
void TASAlgo::do_update(const api::orderman::Update&) {
|
||||
LOG(OrderMan, Warn, "TASAlgo::do_update order:{} state:{} update not allowed ",
|
||||
_algo().order_key().value(),
|
||||
static_cast<int>(me->state));
|
||||
}
|
||||
// callbacks //////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
void TASAlgo::on_book(SecurityKey, const Book&) {
|
||||
}
|
||||
void TASAlgo::on_child_change(OrderKey key,
|
||||
ChildState const &st){
|
||||
LOG(OrderMan, Info,
|
||||
"TASAlgo::on_child_change key:{} child_key:{} state:{} status:{} "
|
||||
"total_fills:{} last_price:{}",
|
||||
_algo().order_key(),
|
||||
key,
|
||||
static_cast<int>(me->state),
|
||||
static_cast<int>(st.status),
|
||||
st.total_fills,
|
||||
st.last_price);
|
||||
TASLegData* ld_ptr = me->find_leg_from_ord_key(key);
|
||||
if (ld_ptr != nullptr)
|
||||
ld_ptr->order_state = st;
|
||||
for (const auto& l : me->legs)
|
||||
if(l.order_state.status == ChildStatus::WORKING)
|
||||
return;
|
||||
_cxl_and_end(false,"");
|
||||
}
|
||||
void TASAlgo::on_status(SecurityKey key, co2::TradingStatus status){
|
||||
if(key == me->sec_key &&
|
||||
status == co2::TradingStatus::TRADINGSTATUS_PRE_OPEN){
|
||||
switch (me->state){
|
||||
case TASAlgo::Status::WAITING_FOR_SIGNAL:
|
||||
for (auto& l : me->legs){
|
||||
l.order_key = _algo().launch_child(
|
||||
*l.order_template,
|
||||
l.price,
|
||||
l.quantity);
|
||||
LOG(OrderMan, Info,"TASAlgo::on_status launching order key:{} "
|
||||
"child_key:{} price:{} qty:{}",
|
||||
_algo().order_key(),
|
||||
l.order_key,
|
||||
l.price,
|
||||
l.quantity);
|
||||
}
|
||||
_switch_state(TASAlgo::Status::WORKING);
|
||||
break;
|
||||
case TASAlgo::Status::WORKING:
|
||||
case TASAlgo::Status::DONE:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
void TASAlgo::on_timer(){
|
||||
if (bts::datetime::msecs_since(me->start_time) > 10000)
|
||||
on_status(me->sec_key,co2::TradingStatus::TRADINGSTATUS_PRE_OPEN);
|
||||
}
|
||||
IAlgoServices& TASAlgo::_algo() const { return *me->algo_services; }
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// stateless conversion ///////////////////////////////////////////////////////
|
||||
TASAlgo::TASAlgoParams TASAlgo::_convert_params (
|
||||
const bts::api::orderman::CustomOrderDefinition& cod){
|
||||
const DynamicOrderDefinition& def = cod.dynamic();
|
||||
const auto& params = def.order_params();
|
||||
TASAlgo::TASAlgoParams rv;
|
||||
for (size_t i = 0; i < 1024; i++){
|
||||
auto idx = std::to_string(i+1);
|
||||
auto price = get_if<double>(params, "Order " + idx + " Price");
|
||||
auto qty = get_if<uint32_t>(params, "Order " + idx + " Quantity");
|
||||
auto is_buy = get_if<bool>(params, "Order " + idx + " Buy?");
|
||||
if(price.has_value() && qty.has_value() && qty.value() != 0){
|
||||
api::Side side = is_buy.has_value() ?
|
||||
(is_buy.value() ? api::Side::SIDE_BUY : api::Side::SIDE_SELL) :
|
||||
api::Side::SIDE_SELL;
|
||||
rv.child_orders.emplace_back(Price(price.value()), Quantity(qty.value()), side);
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
ChildTemplate* TASAlgo::_create_order_template (
|
||||
IBeforeLaunchAlgoServices& serv,
|
||||
SecurityKey key,
|
||||
api::Side side){
|
||||
OrderDefinition order_def = serv.definition();
|
||||
order_def.set_security_key (key.value());
|
||||
order_def.set_side(side);
|
||||
order_def.mutable_custom_def()->mutable_limit()->MergeFrom (
|
||||
api::orderman::LimitOrderDefinition());
|
||||
return &(serv.make_child_template(order_def));
|
||||
}
|
||||
void TASAlgo::_switch_state(TASAlgo::Status new_state){
|
||||
switch (new_state){
|
||||
case (TASAlgo::Status::WAITING_FOR_SIGNAL):
|
||||
bts_assert(false);
|
||||
break;
|
||||
case (TASAlgo::Status::WORKING):
|
||||
bts_assert(me->state == TASAlgo::Status::WAITING_FOR_SIGNAL);
|
||||
break;
|
||||
case (TASAlgo::Status::DONE):
|
||||
bts_assert(me->state != TASAlgo::Status::DONE);
|
||||
break;
|
||||
}
|
||||
LOG(OrderMan, Info,"TASAlgo::_switch_state key:{} {}->{} ",
|
||||
_algo().order_key(),
|
||||
static_cast<int>(me->state),
|
||||
static_cast<int>(new_state));
|
||||
me->state = new_state;
|
||||
}
|
||||
|
||||
void TASAlgo::_cxl_and_end (bool is_error, const std::string& err_msg){
|
||||
if(is_error)
|
||||
_algo().terminate_error(err_msg);
|
||||
else
|
||||
_algo().complete();
|
||||
_switch_state(TASAlgo::Status::DONE);
|
||||
}
|
||||
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,45 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/orderman/orders/algo/IAlgoOrder.h"
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
|
||||
class ChildTemplate;
|
||||
struct LegData;
|
||||
|
||||
class TASAlgo : public IAlgoOrder {
|
||||
public:
|
||||
TASAlgo();
|
||||
~TASAlgo();
|
||||
struct TASAlgoParams{
|
||||
std::vector<std::tuple<Price, Quantity, api::Side>> child_orders;
|
||||
};
|
||||
public:
|
||||
OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override;
|
||||
void do_launch(IAlgoServices &) override;
|
||||
void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override;
|
||||
void do_update(api::orderman::Update const &) override;
|
||||
void on_book(SecurityKey, Book const &) override;
|
||||
void on_child_change(OrderKey, ChildState const &) override;
|
||||
void on_status(SecurityKey, co2::TradingStatus) override;
|
||||
void on_timer() override;
|
||||
|
||||
private:
|
||||
enum class Status;
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> me;
|
||||
private:
|
||||
IAlgoServices& _algo() const ;
|
||||
static TASAlgoParams _convert_params (
|
||||
const bts::api::orderman::CustomOrderDefinition&);
|
||||
static ChildTemplate* _create_order_template (IBeforeLaunchAlgoServices&,
|
||||
SecurityKey,
|
||||
api::Side);
|
||||
// acts on md, cognizant of the state
|
||||
void _switch_state (Status new_status);
|
||||
void _cxl_and_end (bool is_error, const std::string& err_msg);
|
||||
};
|
||||
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,490 +0,0 @@
|
||||
#include "lib/orderman/orders/algo/algo_orders/TASCounterAlgo.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/orderman/order_factory/IOrderFactory.h"
|
||||
#include "lib/orderman/orderman_utils/Book.h"
|
||||
#include "lib/orderman/orderman_utils/orderman_utils.h"
|
||||
#include "lib/orderman/orders/algo/IAlgoServices.h"
|
||||
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderUtils.h"
|
||||
#include "lib/os/os.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/utils/PBUtils.h"
|
||||
#include "lib/utils/datetime.h"
|
||||
#include <google/protobuf/timestamp.pb.h>
|
||||
#include "lib/orderman/actors/SODPosition.h"
|
||||
#include <google/protobuf/util/time_util.h>
|
||||
#include <stdint.h>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
|
||||
using namespace api::orderman;
|
||||
using namespace google::protobuf;
|
||||
|
||||
enum class TASCounterAlgo::Status { WORKING, DONE };
|
||||
|
||||
// book and trade data for each of the 6 contracts as well as the TAS contracts
|
||||
// (the vwap of the TAS contracts is not used, but for uniformity is kept in the
|
||||
// the same structure)
|
||||
struct ContractMarketData{
|
||||
uint32_t tot_vol = 0;
|
||||
double running_sum = 0;
|
||||
Book book;
|
||||
double estimated_settle = 0.0;
|
||||
void on_trade (const TickerUpdateEvent::Trade& t){
|
||||
tot_vol += t.quantity.value();
|
||||
running_sum += t.price.value()*t.quantity.value();
|
||||
}
|
||||
const double vwap(){
|
||||
return tot_vol == 0 ? os::nan() : running_sum/tot_vol;
|
||||
}
|
||||
};
|
||||
// the input for the t1 front, second and third orders, as well as the template
|
||||
// and working order key are kept here
|
||||
struct ContractAutoOrder{
|
||||
// inputs
|
||||
uint32_t n_secs = 0;
|
||||
uint32_t qty = 0;
|
||||
bool enabled = false;
|
||||
// dont know yet which side will be sent
|
||||
ChildTemplate* buy_ord = nullptr;
|
||||
ChildTemplate* sell_ord = nullptr;
|
||||
// computed input
|
||||
// the is AlgoData::settle_stop - n_secs
|
||||
Timestamp algo_start;
|
||||
// output
|
||||
std::optional<OrderKey> tas_order = std::nullopt;
|
||||
};
|
||||
|
||||
struct AlgoData{
|
||||
double tick_size;
|
||||
Timestamp settle_start;
|
||||
Timestamp settle_stop;
|
||||
ContractMarketData t1_front,
|
||||
t1_second,
|
||||
t1_third,
|
||||
t2_front,
|
||||
t2_second,
|
||||
t3_front;
|
||||
ContractMarketData t1_front_tas,
|
||||
t1_second_tas,
|
||||
t1_third_tas;
|
||||
ContractAutoOrder t1_front_order,
|
||||
t1_second_order,
|
||||
t1_third_order;
|
||||
DynamicOrderState out_state;
|
||||
};
|
||||
|
||||
struct TASCounterAlgo::PImpl {
|
||||
// reporting
|
||||
uint16_t reporting_period_msecs = 500;
|
||||
bts::datetime::PTime last_report_time = bts::datetime::now();
|
||||
// immutable state
|
||||
IAlgoServices* algo_services = nullptr;
|
||||
// mutable state
|
||||
AlgoData data;
|
||||
// to avoid lookups on md and ticker callbacks
|
||||
std::map<SecurityKey,ContractMarketData*> md_map;
|
||||
Status state = Status::WORKING;
|
||||
};
|
||||
|
||||
//fwd decls
|
||||
void _copy_output(AlgoData&);
|
||||
bool _copy_settle_times (AlgoData&,const Map<std::string,DynamicOrderParam>&);
|
||||
void _copy_order_data (AlgoData&,const Map<std::string,DynamicOrderParam>&);
|
||||
bool _setup_data(IBeforeLaunchAlgoServices&, AlgoData&,
|
||||
std::map<SecurityKey,ContractMarketData*>&);
|
||||
double round_to_nearest(double price, double tick_size);
|
||||
long long t1_minus_t2_usecs (const Timestamp&, const Timestamp&);
|
||||
long long t_minus_now_usecs (const google::protobuf::Timestamp&);
|
||||
bool trade_within_time_win (const Timestamp&, const Timestamp&,
|
||||
const TickerUpdateEvent::Trade& t);
|
||||
bool now_within_time_win (const Timestamp&, const Timestamp&);
|
||||
|
||||
|
||||
TASCounterAlgo::TASCounterAlgo() : me(new PImpl()) {}
|
||||
TASCounterAlgo::~TASCounterAlgo() {}
|
||||
// initialization /////////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
OrderOpResult TASCounterAlgo::do_before_launch(IBeforeLaunchAlgoServices& serv) {
|
||||
if(_setup_data(serv,me->data,me->md_map))
|
||||
return {};
|
||||
return {OrderError::ORDER_ERROR_INVALID_PARAMETER,
|
||||
std::string("Parameters are not well formed")};
|
||||
}
|
||||
void TASCounterAlgo::do_launch(IAlgoServices& algo_services) {
|
||||
me->algo_services = &algo_services;
|
||||
algo_services.subscribe_timer();
|
||||
for (const auto& kp : me->md_map){
|
||||
algo_services.subscribe_book(kp.first);
|
||||
algo_services.subscribe_ticker(kp.first);
|
||||
}
|
||||
}
|
||||
void TASCounterAlgo::do_launch_attached(
|
||||
IAlgoServices& algo_services,
|
||||
OrderKey,
|
||||
ChildState) {
|
||||
// not allowed
|
||||
me->algo_services = &algo_services;
|
||||
}
|
||||
// updates ////////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
void TASCounterAlgo::do_update(const api::orderman::Update& u) {
|
||||
if(me->state == Status::DONE)
|
||||
return;
|
||||
const auto& p = u.custom().dynamic().order_params();
|
||||
// only order data change is allowed
|
||||
_copy_order_data(me->data,p);
|
||||
_check_and_send_order();
|
||||
}
|
||||
// callbacks //////////////////////////////////////////////////////////////////
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
void TASCounterAlgo::on_book(SecurityKey k, const Book& b) {
|
||||
if(me->state == Status::DONE)
|
||||
return;
|
||||
const auto& it = me->md_map.find(k);
|
||||
if(it != me->md_map.end()){
|
||||
it->second->book = b;
|
||||
_check_and_send_order();
|
||||
}
|
||||
}
|
||||
void TASCounterAlgo::on_ticker(SecurityKey k, const TradeVector& v){
|
||||
if(me->state == Status::DONE)
|
||||
return;
|
||||
const auto& it = me->md_map.find(k);
|
||||
if(it != me->md_map.end()){
|
||||
auto contract_md = it->second;
|
||||
for (const auto& t : v)
|
||||
if (_within_settle()){
|
||||
contract_md->on_trade(t);
|
||||
}
|
||||
_check_and_send_order();
|
||||
}
|
||||
}
|
||||
|
||||
// this only gets called on an explicit algo cancel
|
||||
// from the outside
|
||||
TASCounterAlgo::OnCancelResponse TASCounterAlgo::on_cancel(){
|
||||
return IAlgoOrder::OnCancelResponse::HONOR;
|
||||
}
|
||||
|
||||
void TASCounterAlgo::on_timer(){
|
||||
if(me->state == Status::DONE)
|
||||
return;
|
||||
_check_and_send_order();
|
||||
if(bts::datetime::msecs_since(me->last_report_time) >=
|
||||
me->reporting_period_msecs){
|
||||
me->last_report_time = bts::datetime::now();
|
||||
_report_state();
|
||||
}
|
||||
// check for end and exit
|
||||
if (t1_minus_t2_usecs(util::TimeUtil::GetCurrentTime(),
|
||||
me->data.settle_stop) > 0){
|
||||
std::string msg = "session over";
|
||||
_cxl_and_end(false,msg);
|
||||
}
|
||||
}
|
||||
|
||||
IAlgoServices& TASCounterAlgo::_algo() const { return *me->algo_services; }
|
||||
|
||||
void TASCounterAlgo::_switch_state(TASCounterAlgo::Status new_state){
|
||||
switch (new_state){
|
||||
case (TASCounterAlgo::Status::WORKING):
|
||||
bts_assert(false);
|
||||
break;
|
||||
case (TASCounterAlgo::Status::DONE):
|
||||
bts_assert(me->state == TASCounterAlgo::Status::WORKING);
|
||||
break;
|
||||
}
|
||||
LOG(OrderMan, Info,"TASCounterAlgo::_switch_state key:{} {}->{} ",
|
||||
_algo().order_key(),
|
||||
static_cast<int>(me->state),
|
||||
static_cast<int>(new_state));
|
||||
me->state = new_state;
|
||||
}
|
||||
|
||||
void TASCounterAlgo::_cxl_and_end (bool is_error, const std::string& err_msg){
|
||||
if(me->state == Status::DONE)
|
||||
return;
|
||||
if(is_error)
|
||||
_algo().terminate_error(err_msg);
|
||||
else
|
||||
_algo().complete();
|
||||
_switch_state(TASCounterAlgo::Status::DONE);
|
||||
}
|
||||
|
||||
void TASCounterAlgo::_compute_settles(){
|
||||
AlgoData& d = me->data;
|
||||
d.t1_front.estimated_settle = d.t1_front.vwap();
|
||||
d.t1_second.estimated_settle = d.t2_front.vwap() - d.t1_front.vwap();
|
||||
d.t1_third.estimated_settle = d.t3_front.vwap() - d.t1_front.vwap() -
|
||||
d.t1_second.vwap();
|
||||
// round to closest value
|
||||
d.t1_front.estimated_settle = round_to_nearest(
|
||||
d.t1_front.estimated_settle,me->data.tick_size);
|
||||
d.t1_second.estimated_settle = round_to_nearest(
|
||||
d.t1_second.estimated_settle,me->data.tick_size);
|
||||
d.t1_third.estimated_settle = round_to_nearest(
|
||||
d.t1_third.estimated_settle,me->data.tick_size);
|
||||
}
|
||||
|
||||
// the decision to send an order can be caused by
|
||||
// 1. change in settings (=> time window, enabling orders etc)
|
||||
// 2. book update (=> TAS book can result in order)
|
||||
// 3. ticker (=> new estimated settlement)
|
||||
// 4. time passing (=> in the window now)
|
||||
void TASCounterAlgo::_check_and_send_order(){
|
||||
_compute_settles();
|
||||
auto should_send_tas_order =
|
||||
[](const ContractMarketData& c,
|
||||
const ContractAutoOrder& o,
|
||||
const ContractMarketData& tas_c,
|
||||
bool is_buy,
|
||||
double& out_price,
|
||||
uint32_t& out_qty) -> bool {
|
||||
// buying the tas at the offer or selling it at the bid
|
||||
const auto& tas_opp_top = is_buy ? tas_c.book.ask()[0] : tas_c.book.bid()[0];
|
||||
const auto& c_same_top = is_buy ? c.book.bid()[0] : c.book.ask()[0];
|
||||
if(tas_opp_top.size() > 0 && c_same_top.size() > 0){
|
||||
// delivery price as defined by where the TAS order is traded
|
||||
double tas_delv_price = c.estimated_settle + tas_opp_top.price();
|
||||
// if the delv price for the buy order is <= contract bid or
|
||||
// or the delv price for the sell order is >= contract offer
|
||||
// then we are buying at the bid or selling at the offer
|
||||
double c_price = c_same_top.price();
|
||||
if((is_buy && tas_delv_price <= c_price) ||
|
||||
(!is_buy && tas_delv_price >= c_price)){
|
||||
out_qty = std::min(o.qty,tas_opp_top.size());
|
||||
out_price = tas_opp_top.price();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
auto _send_order_tn = [&](
|
||||
const ContractMarketData& c,
|
||||
ContractAutoOrder& o,
|
||||
const ContractMarketData& tas_c) -> void {
|
||||
if(o.enabled && o.n_secs > 0 && o.qty > 0 &&
|
||||
!o.tas_order.has_value() &&
|
||||
now_within_time_win(o.algo_start,me->data.settle_stop)){
|
||||
double price;
|
||||
uint32_t qty;
|
||||
if(should_send_tas_order(c,o,tas_c,true,price,qty)){
|
||||
o.tas_order = _algo().launch_child(*o.buy_ord,
|
||||
Price(price),
|
||||
Quantity(qty));
|
||||
}
|
||||
else if(should_send_tas_order(c,o,tas_c,false,price,qty)){
|
||||
o.tas_order = _algo().launch_child(*o.sell_ord,
|
||||
Price(price),
|
||||
Quantity(qty));
|
||||
}
|
||||
}
|
||||
};
|
||||
_send_order_tn(me->data.t1_front,me->data.t1_front_order,me->data.t1_front_tas);
|
||||
_send_order_tn(me->data.t1_second,me->data.t1_second_order,me->data.t1_second_tas);
|
||||
_send_order_tn(me->data.t1_third,me->data.t1_third_order,me->data.t1_third_tas);
|
||||
}
|
||||
|
||||
void TASCounterAlgo::_report_state(){
|
||||
_compute_settles();
|
||||
_copy_output(me->data);
|
||||
_algo().update_custom_state(me->data.out_state);
|
||||
}
|
||||
|
||||
bool TASCounterAlgo::_within_settle() const{
|
||||
return now_within_time_win(me->data.settle_start,me->data.settle_stop);
|
||||
}
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// stateless conversion ///////////////////////////////////////////////////////
|
||||
|
||||
// stateless helpers
|
||||
ChildTemplate* _create_order_template (IBeforeLaunchAlgoServices& serv,
|
||||
SecurityKey key,
|
||||
api::Side side){
|
||||
OrderDefinition order_def = serv.definition();
|
||||
order_def.set_security_key (key.value());
|
||||
order_def.set_side(side);
|
||||
order_def.mutable_custom_def()->mutable_limit()->MergeFrom (
|
||||
api::orderman::LimitOrderDefinition());
|
||||
return &(serv.make_child_template(order_def));
|
||||
}
|
||||
// copies output into the dynamic state for publishing
|
||||
void _copy_output(AlgoData& d){
|
||||
auto& m = *(d.out_state.mutable_custom_state());
|
||||
// we can safely assume its within int32
|
||||
auto secs_to_settle = static_cast<int>(t_minus_now_usecs(d.settle_start)/1000000);
|
||||
// if its in settle (-ve value), its set to 0
|
||||
secs_to_settle = std::max(secs_to_settle,0);
|
||||
m["Seconds To Settle"].set_as_int32(secs_to_settle);
|
||||
m["VWAP T1-Front"].set_as_double(d.t1_front.vwap());
|
||||
m["VWAP T1-Second"].set_as_double(d.t1_second.vwap());
|
||||
m["VWAP T1-Third"].set_as_double(d.t1_third.vwap());
|
||||
m["VWAP T2-Front"].set_as_double(d.t2_front.vwap());
|
||||
m["VWAP T2-Second"].set_as_double(d.t2_second.vwap());
|
||||
m["VWAP T3-Front"].set_as_double(d.t3_front.vwap());
|
||||
m["T1-Front Projected Settle"].set_as_double(d.t1_front.estimated_settle);
|
||||
m["T1-Second Projected Settle"].set_as_double(d.t1_second.estimated_settle);
|
||||
m["T1-Third Projected Settle"].set_as_double(d.t1_third.estimated_settle);
|
||||
}
|
||||
// copies the settle time/period part of the input data
|
||||
bool _copy_settle_times (AlgoData& d,
|
||||
const Map<std::string,DynamicOrderParam>& params){
|
||||
auto hh = get_if<uint32_t>(params, "Settlement Start Hour");
|
||||
auto mm = get_if<uint32_t>(params, "Settlement Start Minutes");
|
||||
auto ss = get_if<uint32_t>(params, "Settlement Start Seconds");
|
||||
auto settle_period_secs = get_if<uint32_t>(params, "Settlement Period (seconds)");
|
||||
if (hh.has_value() && mm.has_value() &&
|
||||
ss.has_value() && settle_period_secs.has_value() &&
|
||||
hh.value() <= 23 && mm.value() <= 59 && ss.value() <= 59){
|
||||
d.settle_start = SODPosition::today_local_time_to_utc_timestamp(
|
||||
hh.value(),
|
||||
mm.value(),
|
||||
ss.value(),
|
||||
true,
|
||||
false);
|
||||
d.settle_stop = SODPosition::add_seconds(d.settle_start,
|
||||
settle_period_secs.value());
|
||||
auto settle_start_txt = util::TimeUtil::ToString(d.settle_start);
|
||||
auto settle_stop_txt = util::TimeUtil::ToString(d.settle_stop);
|
||||
LOG(OrderMan, Info, "TASCounterAlgo::_copy_settle_times "
|
||||
"settle_start:{} settle_stop:{} ",
|
||||
settle_start_txt,
|
||||
settle_stop_txt);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// copies the order execution part of the input data
|
||||
void _copy_order_data (AlgoData& out_d,
|
||||
const Map<std::string,DynamicOrderParam>& params){
|
||||
auto copy_o = [&](ContractAutoOrder& out_order,
|
||||
std::string time_name,
|
||||
std::string qty_name,
|
||||
std::string enabled_name
|
||||
) -> bool {
|
||||
out_order.enabled = false;
|
||||
auto time = get_if<uint32_t>(params, time_name);
|
||||
auto qty = get_if<uint32_t>(params, qty_name);
|
||||
auto enabled = get_if<bool>(params, enabled_name);
|
||||
if(time.has_value() && qty.has_value() && enabled.has_value()){
|
||||
out_order.n_secs = time.value();
|
||||
out_order.qty = qty.value();
|
||||
out_order.enabled = enabled.value();
|
||||
out_order.algo_start = SODPosition::add_seconds(out_d.settle_stop,
|
||||
-1 * out_order.n_secs);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
copy_o(out_d.t1_front_order,
|
||||
"T1 Front Time",
|
||||
"T1 Front Qty",
|
||||
"T1 Front Order Enabled");
|
||||
copy_o(out_d.t1_second_order,
|
||||
"T1 Second Time",
|
||||
"T1 Second Qty",
|
||||
"T1 Second Order Enabled");
|
||||
copy_o(out_d.t1_third_order,
|
||||
"T1 Third Time",
|
||||
"T1 Third Qty",
|
||||
"T1 Third Order Enabled");
|
||||
}
|
||||
// copies all of the input params (in the algo) into proper structures
|
||||
bool _setup_data(IBeforeLaunchAlgoServices& serv,
|
||||
AlgoData& out_d,
|
||||
std::map<SecurityKey,ContractMarketData*>& out_md_map){
|
||||
auto& def = serv.definition();
|
||||
// [ captures ] (parameters) -> returnTypesDeclaration { lambdaStatements; }
|
||||
auto init_contract_bk = [&out_md_map](auto& out_contract_md,
|
||||
const auto& params,
|
||||
auto param_name) -> void {
|
||||
auto k = get_if<uint32_t>(params, param_name);
|
||||
if(k.has_value()){
|
||||
out_contract_md.book = Book(SecurityKey(k.value()));
|
||||
out_md_map[out_contract_md.book.security_key()] = &out_contract_md;
|
||||
}
|
||||
};
|
||||
if (def.has_custom_def() && def.custom_def().has_dynamic()){
|
||||
out_d.tick_size = serv.security().contract_spec().low_tick();
|
||||
const auto& p = def.custom_def().dynamic().order_params();
|
||||
// settlement time
|
||||
if(!_copy_settle_times(out_d,p))
|
||||
return false;
|
||||
// main contracts
|
||||
init_contract_bk(out_d.t1_front, p,"T1 Front");
|
||||
init_contract_bk(out_d.t1_second, p,"T1 Second");
|
||||
init_contract_bk(out_d.t1_third, p,"T1 Third");
|
||||
init_contract_bk(out_d.t2_front, p,"T2 Front");
|
||||
init_contract_bk(out_d.t2_second, p,"T2 Second");
|
||||
init_contract_bk(out_d.t3_front, p,"T3 Front");
|
||||
// TAS contracts
|
||||
init_contract_bk(out_d.t1_front_tas, p,"T1 Front TAS");
|
||||
init_contract_bk(out_d.t1_second_tas, p,"T1 Second TAS");
|
||||
init_contract_bk(out_d.t1_third_tas, p,"T1 Third TAS");
|
||||
// auto orders
|
||||
_copy_order_data(out_d,p);
|
||||
// order template
|
||||
out_d.t1_front_order.buy_ord = _create_order_template(serv,
|
||||
out_d.t1_front_tas.book.security_key(),api::Side::SIDE_BUY);
|
||||
out_d.t1_front_order.sell_ord = _create_order_template(serv,
|
||||
out_d.t1_front_tas.book.security_key(),api::Side::SIDE_SELL);
|
||||
out_d.t1_second_order.buy_ord = _create_order_template(serv,
|
||||
out_d.t1_second_tas.book.security_key(),api::Side::SIDE_BUY);
|
||||
out_d.t1_second_order.sell_ord = _create_order_template(serv,
|
||||
out_d.t1_second_tas.book.security_key(),api::Side::SIDE_SELL);
|
||||
out_d.t1_third_order.buy_ord = _create_order_template(serv,
|
||||
out_d.t1_third_tas.book.security_key(),api::Side::SIDE_BUY);
|
||||
out_d.t1_third_order.sell_ord = _create_order_template(serv,
|
||||
out_d.t1_third_tas.book.security_key(),api::Side::SIDE_SELL);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
double round_to_nearest(double price, double tick_size){
|
||||
if(os::is_nan(price))
|
||||
return price;
|
||||
auto buy_price = bts::securities::raw_round_to_quote_price(
|
||||
price,
|
||||
tick_size,
|
||||
api::Side::SIDE_BUY);
|
||||
auto sell_price = buy_price + tick_size;
|
||||
return std::abs(price-buy_price) < std::abs(sell_price-price) ? buy_price :
|
||||
sell_price;
|
||||
}
|
||||
// time helpers
|
||||
// converts std::chrono::system_clock::time_point to google timestamp
|
||||
google::protobuf::Timestamp to_pf_ts (const bts::TimeStamp& ts){
|
||||
auto ts_us = std::chrono::time_point_cast<std::chrono::microseconds>(ts);
|
||||
auto ts_us_val = ts_us.time_since_epoch();
|
||||
auto usecs = ts_us_val.count();
|
||||
return google::protobuf::util::TimeUtil::MicrosecondsToTimestamp(usecs);
|
||||
}
|
||||
long long t1_minus_t2_usecs (const Timestamp& t1,const Timestamp& t2){
|
||||
return util::TimeUtil::TimestampToMicroseconds(t1) -
|
||||
util::TimeUtil::TimestampToMicroseconds(t2);
|
||||
}
|
||||
long long t_minus_now_usecs (const Timestamp& t){
|
||||
auto now = util::TimeUtil::GetCurrentTime();
|
||||
return t1_minus_t2_usecs(t,now);
|
||||
}
|
||||
bool within_time_win (const Timestamp& beg, const Timestamp& end,
|
||||
const Timestamp& ts){
|
||||
return t1_minus_t2_usecs(ts,beg)>=0 &&
|
||||
t1_minus_t2_usecs(ts,end)<=0;
|
||||
}
|
||||
// if current time is within time window
|
||||
bool now_within_time_win (const Timestamp& beg,
|
||||
const Timestamp& end){
|
||||
return within_time_win(beg,end,util::TimeUtil::GetCurrentTime());
|
||||
}
|
||||
bool trade_within_time_win (const Timestamp& beg, const Timestamp& end,
|
||||
const TickerUpdateEvent::Trade& t){
|
||||
auto ts = to_pf_ts(t.ts);
|
||||
return within_time_win(beg,end,ts);
|
||||
}
|
||||
|
||||
} // namespace orderman
|
||||
|
||||
} // namespace bts
|
||||
@@ -1,41 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "lib/orderman/orders/algo/IAlgoOrder.h"
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
|
||||
class ChildTemplate;
|
||||
|
||||
class TASCounterAlgo : public IAlgoOrder {
|
||||
public:
|
||||
TASCounterAlgo();
|
||||
~TASCounterAlgo();
|
||||
struct TASCounterAlgoParams{
|
||||
};
|
||||
public:
|
||||
OrderOpResult do_before_launch(IBeforeLaunchAlgoServices &) override;
|
||||
void do_launch(IAlgoServices &) override;
|
||||
void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override;
|
||||
void do_update(api::orderman::Update const &) override;
|
||||
void on_book(SecurityKey, Book const &) override;
|
||||
void on_ticker(SecurityKey, TradeVector const&) override;
|
||||
IAlgoOrder::OnCancelResponse on_cancel() override;
|
||||
void on_timer() override;
|
||||
private:
|
||||
enum class Status;
|
||||
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> me;
|
||||
private:
|
||||
IAlgoServices& _algo() const ;
|
||||
void _switch_state (Status new_status);
|
||||
void _cxl_and_end (bool is_error, const std::string& err_msg);
|
||||
void _check_and_send_order();
|
||||
void _compute_settles ();
|
||||
void _report_state();
|
||||
bool _within_settle() const;
|
||||
};
|
||||
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,152 +0,0 @@
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h"
|
||||
#include "lib/orderman/orders/OrderOpResult.h"
|
||||
#include "lib/orderman/orders/algo/utils/DynamicOrderAdapter.h"
|
||||
#include <utility>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
template<typename T>
|
||||
using Param = bts::orderman::dynamic_adapter::ParamKey<bts::orderman::LimitCoverDefinition, T>;
|
||||
using DynamicOrderEnumerated = bts::api::orderman::DynamicOrderEnumerated;
|
||||
using OnToward = bts::api::orderman::LeanOnToward;
|
||||
using LimitCoverDefinition = bts::orderman::LimitCoverDefinition;
|
||||
using namespace bts::api::orderman;
|
||||
#define ON_TOWARD_NAME_PAIR(x) std::make_pair(x, #x)
|
||||
|
||||
template<uint32_t gate_num>
|
||||
std::string gate_param_name(std::string name) {
|
||||
return Formatter::fmt("Gate ", gate_num, " ", name);
|
||||
}
|
||||
|
||||
template<>
|
||||
std::string gate_param_name<0>(std::string name) {
|
||||
return Formatter::fmt("Initial ", name);
|
||||
}
|
||||
|
||||
struct PriceOffset : public Param<double> {
|
||||
PriceOffset() : Param<double>(std::string("Limit"),
|
||||
[](const LimitCoverDefinition& def) { return def.price_offset(); },
|
||||
[](LimitCoverDefinition& def, double v) { def.price_offset(v); }) {}
|
||||
};
|
||||
|
||||
template<uint32_t gate_num>
|
||||
struct ActivationThreshold : public Param<uint32_t> {
|
||||
ActivationThreshold() : Param<uint32_t>(gate_param_name<gate_num>("Activation Threshold"),
|
||||
[](const LimitCoverDefinition& def) { return def.gate(gate_num).activation_threshold(); },
|
||||
[](LimitCoverDefinition& def, uint32_t v) { def.mgate(gate_num).activation_threshold(v); }) { }
|
||||
};
|
||||
|
||||
template<uint32_t gate_num>
|
||||
struct CoverThreshold : public Param<uint32_t> {
|
||||
CoverThreshold() : Param<uint32_t>(gate_param_name<gate_num>("Cover Threshold"),
|
||||
[](const LimitCoverDefinition& def) { return def.gate(gate_num).cover_threshold(); },
|
||||
[](LimitCoverDefinition& def, uint32_t v) { def.mgate(gate_num).cover_threshold(v); }) { }
|
||||
};
|
||||
|
||||
template<uint32_t gate_num>
|
||||
struct DeleteThreshold : public Param<uint32_t> {
|
||||
DeleteThreshold() : Param<uint32_t>(gate_param_name<gate_num>("Delete Threshold"),
|
||||
[](const LimitCoverDefinition& def) { return def.gate(gate_num).delete_threshold(); },
|
||||
[](LimitCoverDefinition& def, uint32_t v) { def.mgate(gate_num).delete_threshold(v); }) { }
|
||||
};
|
||||
|
||||
template<uint32_t gate_num>
|
||||
struct HedgeTicks : public Param<uint32_t> {
|
||||
HedgeTicks() : Param<uint32_t>(gate_param_name<gate_num>("Hedge Ticks"),
|
||||
[](const LimitCoverDefinition& def) { return def.gate(gate_num).hedge_ticks(); },
|
||||
[](LimitCoverDefinition& def, uint32_t v) { def.mgate(gate_num).hedge_ticks(v); }) { }
|
||||
};
|
||||
|
||||
template<uint32_t gate_num>
|
||||
struct TopTicksOff : public Param<uint32_t> {
|
||||
TopTicksOff() : Param<uint32_t>(gate_param_name<gate_num>("Top Ticks Offset"),
|
||||
[](const LimitCoverDefinition& def) { return def.gate(gate_num).top_ticks_offset(); },
|
||||
[](LimitCoverDefinition& def, uint32_t v) { def.mgate(gate_num).top_ticks_offset(v); }) { }
|
||||
};
|
||||
|
||||
template<uint32_t gate_num>
|
||||
struct MaxChaseTicks : public Param<uint32_t> {
|
||||
MaxChaseTicks() : Param<uint32_t>(gate_param_name<gate_num>("Max Chase Ticks"),
|
||||
[](const LimitCoverDefinition& def) { return def.gate(gate_num).max_chase_ticks(); },
|
||||
[](LimitCoverDefinition& def, uint32_t v) { def.mgate(gate_num).max_chase_ticks(v); }) { }
|
||||
};
|
||||
|
||||
template<uint32_t gate_num>
|
||||
struct TradeTowardBehavior : public dynamic_adapter::EnumParamKey<LimitCoverDefinition, OnToward> {
|
||||
TradeTowardBehavior() : EnumParamKey<LimitCoverDefinition, OnToward>(
|
||||
gate_param_name<gate_num>("Trade Toward Behavior"), {
|
||||
ON_TOWARD_NAME_PAIR(NO_CHANGE),
|
||||
ON_TOWARD_NAME_PAIR(CANCEL),
|
||||
ON_TOWARD_NAME_PAIR(DETACH),
|
||||
ON_TOWARD_NAME_PAIR(REPRICE)
|
||||
},
|
||||
[](const LimitCoverDefinition& def) { return def.gate(gate_num).on_toward(); },
|
||||
[](LimitCoverDefinition& def, OnToward v) { def.mgate(gate_num).on_toward(v); })
|
||||
{}
|
||||
};
|
||||
|
||||
template<>
|
||||
struct ActivationThreshold<0> : public Param<uint32_t> {
|
||||
ActivationThreshold() : Param<uint32_t>(std::string("Entry Threshold"),
|
||||
[](const LimitCoverDefinition& def) { return def.gate(0).activation_threshold(); },
|
||||
[](LimitCoverDefinition& def, uint32_t v) {
|
||||
auto& g = def.mgate(0);
|
||||
g.activation_threshold(v);
|
||||
g.cover_threshold(v);
|
||||
g.delete_threshold(v);
|
||||
}) {}
|
||||
};
|
||||
|
||||
using Adapter = dynamic_adapter::DynamicOrderAdapter<LimitCoverDefinition,
|
||||
PriceOffset,
|
||||
// [gate 0]
|
||||
ActivationThreshold<0>,
|
||||
HedgeTicks<0>,
|
||||
TopTicksOff<0>,
|
||||
MaxChaseTicks<0>,
|
||||
TradeTowardBehavior<0>,
|
||||
// gate 1
|
||||
ActivationThreshold<1>,
|
||||
CoverThreshold<1>,
|
||||
DeleteThreshold<1>,
|
||||
HedgeTicks<1>,
|
||||
TopTicksOff<1>,
|
||||
MaxChaseTicks<1>,
|
||||
TradeTowardBehavior<1>,
|
||||
// gate 2
|
||||
ActivationThreshold<2>,
|
||||
CoverThreshold<2>,
|
||||
DeleteThreshold<2>,
|
||||
HedgeTicks<2>,
|
||||
TopTicksOff<2>,
|
||||
MaxChaseTicks<2>,
|
||||
TradeTowardBehavior<2>>;
|
||||
|
||||
LimitCoverDefinition LimitCoverAdapter::from_proto(const api::orderman::OrderDefinition& order) {
|
||||
if (order.has_custom_def())
|
||||
return from_proto(order.custom_def());
|
||||
return LimitCoverDefinition();
|
||||
}
|
||||
LimitCoverDefinition LimitCoverAdapter::from_proto(const api::orderman::CustomOrderDefinition& custom_def) {
|
||||
LimitCoverDefinition rv;
|
||||
if (custom_def.has_dynamic())
|
||||
Adapter().from_proto(custom_def.dynamic(), rv);
|
||||
return rv;
|
||||
}
|
||||
|
||||
#define INVALID_DEF(x) OrderOpResult(api::orderman::ORDER_ERROR_INVALID_ORDER_DEFINITON, x)
|
||||
|
||||
OrderOpResult LimitCoverAdapter::validate_proto(const api::orderman::DynamicOrderDefinition& dyn) {
|
||||
return Adapter().validate_proto(dyn) ?
|
||||
OrderOpResult() :
|
||||
INVALID_DEF("One or more dynamic parameters are missing or invalid.");
|
||||
}
|
||||
void LimitCoverAdapter::init_proto(const LimitCoverDefinition& def, api::orderman::DynamicOrderDefinition& dyn) {
|
||||
Adapter().to_proto(dyn, def);
|
||||
}
|
||||
|
||||
void LimitCoverAdapter::define_proto(api::orderman::DynamicOrderDescriptor& desc) {
|
||||
Adapter().define_proto(desc);
|
||||
}
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,15 +0,0 @@
|
||||
#pragma once
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h"
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
struct LimitCoverAdapter {
|
||||
static LimitCoverDefinition from_proto(const api::orderman::OrderDefinition& order);
|
||||
static LimitCoverDefinition from_proto(const api::orderman::CustomOrderDefinition& custom_def);
|
||||
static OrderOpResult validate_proto(const api::orderman::DynamicOrderDefinition& order);
|
||||
static void init_proto(const LimitCoverDefinition& def, api::orderman::DynamicOrderDefinition& dyn);
|
||||
static void define_proto(api::orderman::DynamicOrderDescriptor& desc);
|
||||
};
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,71 +0,0 @@
|
||||
#pragma once
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverGate.h"
|
||||
#include "lib/orderman/orderman_utils/Formatter.h"
|
||||
#include <ostream>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace limit_cover {
|
||||
// The exclusive maximum number of gates.
|
||||
// Note: the limit cover spec called for 3 gates (2 gates explicitly,
|
||||
// plus an initial activation threshold, which is treated as another gate).
|
||||
const uint32_t max_num_gates = 4;
|
||||
}
|
||||
struct LimitCoverDefinition {
|
||||
// price offset
|
||||
double price_offset() const {
|
||||
return _price_offset;
|
||||
}
|
||||
void price_offset(double value) {
|
||||
_price_offset = value;
|
||||
}
|
||||
|
||||
LimitCoverGate gate(uint32_t index) const {
|
||||
return _gate_or_default(index);
|
||||
}
|
||||
LimitCoverGate& mgate(uint32_t index) {
|
||||
return _ensure_gate(index);
|
||||
}
|
||||
void gate(uint32_t index, LimitCoverGate value) {
|
||||
_ensure_gate(index) = value;
|
||||
}
|
||||
|
||||
// The original LimitAlgo spec called for an initial activation thresh, and 2 gates
|
||||
// (fyi a gate has 3 members: activation thresh, cover thresh, and delete thresh).
|
||||
// The initial activation thresh serves as the initial cover, and delete threshes as well.
|
||||
// In this sense, the activation threshold can be considered as an 'initial gate' itself.
|
||||
// 'normal_gates' does just that: returns a map of both gates plus the 'initial gate.'
|
||||
std::map<uint32_t, LimitCoverGate> normal_gates() const {
|
||||
std::map<uint32_t, LimitCoverGate> m;
|
||||
for (auto g : _gates)
|
||||
m.insert(std::make_pair(g.activation_threshold(), g));
|
||||
return m;
|
||||
}
|
||||
private:
|
||||
double _price_offset;
|
||||
std::vector<LimitCoverGate> _gates;
|
||||
|
||||
LimitCoverGate& _ensure_gate(uint32_t index) {
|
||||
bts_assert(index < limit_cover::max_num_gates);
|
||||
while (_gates.size() <= index)
|
||||
_gates.push_back(LimitCoverGate());
|
||||
return _gates[index];
|
||||
}
|
||||
|
||||
LimitCoverGate _gate_or_default(uint32_t index) const {
|
||||
return _gates.size() > index ? _gates[index] : LimitCoverGate();
|
||||
}
|
||||
};
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& ostr, const LimitCoverDefinition& lcd) {
|
||||
auto ngates = lcd.normal_gates();
|
||||
ostr << "Price Offset: " << lcd.price_offset()
|
||||
<< ", Activation Thresh: " << lcd.gate(0).activation_threshold()
|
||||
<< ", Gates: " << Formatter::fmt_values(ngates);
|
||||
return ostr;
|
||||
}
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,87 +0,0 @@
|
||||
#pragma once
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/sparkproto/SparkProtos.pb.h"
|
||||
#include "lib/utils/PBUtils.h"
|
||||
#include <ostream>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
struct LimitCoverGate {
|
||||
LimitCoverGate() : LimitCoverGate(0, 0, 0) {}
|
||||
|
||||
LimitCoverGate(const LimitCoverGate& other)
|
||||
: _activation_threshold(other._activation_threshold), _definition(other._definition) {}
|
||||
|
||||
LimitCoverGate(uint32_t activation_thresh, uint32_t cover_thresh, uint32_t delete_thresh)
|
||||
: _activation_threshold(activation_thresh), _definition() {
|
||||
cover_threshold(cover_thresh);
|
||||
delete_threshold(delete_thresh);
|
||||
}
|
||||
|
||||
// activation threshold
|
||||
uint32_t activation_threshold() const { return _activation_threshold; }
|
||||
void activation_threshold(uint32_t value) { _activation_threshold = value; }
|
||||
|
||||
// cover threshold
|
||||
uint32_t cover_threshold() const {
|
||||
return _definition.has_cross_threshold() ? _get_absolute(_definition.cross_threshold()) : 0;
|
||||
}
|
||||
void cover_threshold(uint32_t value) {
|
||||
if (!_definition.has_cross_threshold()) {
|
||||
*_definition.mutable_cross_threshold() = bts::spark::QuantityMeasure();
|
||||
}
|
||||
_definition.mutable_cross_threshold()->set_absolute(value);
|
||||
}
|
||||
|
||||
// delete threshold
|
||||
uint32_t delete_threshold() const {
|
||||
return _definition.has_top_threshold() ? _get_absolute(_definition.top_threshold()) : 0;
|
||||
}
|
||||
void delete_threshold(uint32_t value) {
|
||||
if (!_definition.has_top_threshold()) {
|
||||
*_definition.mutable_top_threshold() = bts::spark::QuantityMeasure();
|
||||
}
|
||||
_definition.mutable_top_threshold()->set_absolute(value);
|
||||
}
|
||||
|
||||
// hedge ticks
|
||||
uint32_t hedge_ticks() const { return _definition.hedge_ticks(); }
|
||||
void hedge_ticks(uint32_t value) { _definition.set_hedge_ticks(value); }
|
||||
// top ticks offset
|
||||
uint32_t top_ticks_offset() const { return _definition.ticks_off(); }
|
||||
void top_ticks_offset(uint32_t value) { _definition.set_ticks_off(value); }
|
||||
// max chase ticks
|
||||
uint32_t max_chase_ticks() const { return _definition.max_chase_ticks(); }
|
||||
void max_chase_ticks(uint32_t value) { _definition.set_max_chase_ticks(value); }
|
||||
// on toward
|
||||
api::orderman::LeanOnToward on_toward() const { return _definition.trade_toward_behavior(); }
|
||||
void on_toward(api::orderman::LeanOnToward value) { _definition.set_trade_toward_behavior(value); }
|
||||
// definition
|
||||
const api::orderman::DeleteAndCoverDefinition& definition() const { return _definition; }
|
||||
api::orderman::DeleteAndCoverDefinition& mdefinition() { return _definition; }
|
||||
void definition(api::orderman::DeleteAndCoverDefinition value) { _definition = value; }
|
||||
|
||||
api::orderman::CustomOrderDefinition custom_def() const {
|
||||
api::orderman::CustomOrderDefinition cod;
|
||||
*(cod.mutable_delete_and_cover()) = definition();
|
||||
return cod;
|
||||
}
|
||||
void custom_def(const api::orderman::CustomOrderDefinition &cod) {
|
||||
if (cod.has_delete_and_cover())
|
||||
definition(cod.delete_and_cover());
|
||||
}
|
||||
private:
|
||||
uint32_t _activation_threshold;
|
||||
api::orderman::DeleteAndCoverDefinition _definition;
|
||||
|
||||
static inline uint32_t _get_absolute(spark::QuantityMeasure qty_measure, uint32_t fallback_value = 0) {
|
||||
return qty_measure.quantity_case() == spark::QuantityMeasure::kAbsolute ? qty_measure.absolute() : fallback_value;
|
||||
}
|
||||
};
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& ostr, const LimitCoverGate& g) {
|
||||
ostr << "Activation Thresh: " << g.activation_threshold() << ", Definition: " << utils::pb::to_string(g.custom_def());
|
||||
return ostr;
|
||||
}
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,196 +0,0 @@
|
||||
#include "lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/tests/AlgoTestDriver.h"
|
||||
#include "catch/catch.hpp"
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/orderman/orderman_utils/Book.h"
|
||||
#include "lib/orderman/orderman_utils/BookUtils.h"
|
||||
#include "lib/orderman/orderman_utils/Formatter.h"
|
||||
#include "lib/orderman/orderman_utils/PriceComp.h"
|
||||
#include "lib/orderman/orderman_utils/orderman_utils.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/tests/limit_cover/LimitCoverState.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/tests/limit_cover/LimitCoverTestUtils.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/tests/limit_cover/TestSteps.h"
|
||||
#include "lib/sparkproto/SparkProtos.pb.h"
|
||||
#include "lib/utils/PBUtils.h"
|
||||
#include <iostream>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <array>
|
||||
#include <random>
|
||||
#include <variant>
|
||||
#include <cmath>
|
||||
|
||||
// for some reason, intellisense poops its pants without 'using namespace std.'
|
||||
// std::optional<T>, and std::unordered_map<T>, in particular, break intellisense for the whole document.
|
||||
using namespace std;
|
||||
using namespace bts::api::orderman;
|
||||
using namespace bts::orderman::limit_cover::utils;
|
||||
//#define PRINT_SUMMARIES
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace test {
|
||||
namespace limit_cover {
|
||||
// Glossary:
|
||||
// * limit-price:
|
||||
// The price at which the main child is deployed (computed as a tick offset from the settlement).
|
||||
// * limit-volume:
|
||||
// The same-side market volume at or better than the limit price.
|
||||
// This is recomputed whenever the book changes (obviously).
|
||||
// * volume-gate:
|
||||
// * volume-gate: a simple struct with 3 fields:
|
||||
// 1) activation_threshold (uint)
|
||||
// 2) cover_threshold (uint) must be <= activation_thresh
|
||||
// 3) delete_threshold (uint) must be <= activation_thresh
|
||||
// * current-volume-gate:
|
||||
// The volume gate with the highest activation threshold that is still
|
||||
// <= the limit-volume. This is recomputed whenever the book changes
|
||||
// (obviously).
|
||||
// * volume-gates:
|
||||
// A series of volume gates, sorted by 'activation_threshold.'
|
||||
// Initially, the current-volume-gate is one with the lowest activation threshold.
|
||||
// The main child is not deployed until the limit-volume reaches that threshold.
|
||||
// After that, the algo continues to observe the limit-volume, removing gates with lower
|
||||
// thresholds when the volume breeches the next gate's thresh.
|
||||
|
||||
// Test Assertions:
|
||||
// * child is not launched until the limit-volume reaches the initial activation threshold.
|
||||
// * limit-volume is always correct (verify whenever the book changes).
|
||||
// * current-volume-gate is always correct (verify whenever the book changes).
|
||||
|
||||
// Test Design:
|
||||
// * expectations of the limit cover algo's state are stored in an instance of 'LimitCoverState.'
|
||||
// The actual LimitCoverAlgo does not use this class; the tests just use it as a means
|
||||
// to validate the actual LimitCoverAlgo's state, and to wrap calls to the LimitCoverAlgo
|
||||
// with validation checks.
|
||||
|
||||
// * each test implementation should be executed 6 times:
|
||||
// 2 x 3 = test both sides, with each of the following termination steps:
|
||||
// 1) Fill to completion
|
||||
// 2) Cancel the algo
|
||||
// 3) Cancel the child
|
||||
|
||||
// * Restrictions on the parameters:
|
||||
// - the spec explicitly called for 3 volume gates, and specified that the 3 thresholds
|
||||
// (activation, cover, and delete) be the same for the first gate
|
||||
// (technically, the spec described 2 gates and an 'entry threshold').
|
||||
// - the algo should immediately cancel itself if these parameters are not the case.
|
||||
// while it would most likely not cause a problem, these assumptions allow the tests to focus
|
||||
// on a narrow range of inputs (and of course, such restrictions naturally decrease the
|
||||
// chance of a bug slipping through).
|
||||
|
||||
LimitCoverState init_state(
|
||||
OrderDefinition& mdef,
|
||||
Side side,
|
||||
uint32_t quantity,
|
||||
double price,
|
||||
double price_offset,
|
||||
std::vector<LimitCoverGate> gates,
|
||||
bool cancel_hedges_on_cancel = true,
|
||||
bool cancel_on_external_hedge_cancel = false) {
|
||||
//
|
||||
REQUIRE(!gates.empty());
|
||||
for (auto& g : gates) {
|
||||
g.mdefinition().set_cancel_hedges_on_cancel(cancel_hedges_on_cancel);
|
||||
g.mdefinition().set_cancel_on_external_hedge_cancel(cancel_on_external_hedge_cancel);
|
||||
}
|
||||
LimitCoverDefinition lc_def;
|
||||
lc_def.price_offset(price_offset);
|
||||
uint32_t gate_pos = 0;
|
||||
for (auto g : gates) {
|
||||
lc_def.gate(gate_pos++, g);
|
||||
}
|
||||
DynamicOrderDefinition dyn_def;
|
||||
LimitCoverAdapter::init_proto(lc_def, dyn_def);
|
||||
*(mdef.mutable_custom_def()->mutable_dynamic()) = dyn_def;
|
||||
mdef.set_side(side);
|
||||
return LimitCoverState(mdef, quantity, price);
|
||||
}
|
||||
|
||||
template<typename... Steps>
|
||||
inline void test_impl(Side side, uint32_t qty, double price_offset, double settle, std::vector<LimitCoverGate> gates, Steps... steps) {
|
||||
std::cout << std::endl << std::endl;
|
||||
std::cout << "*************************************************************************************************************************" << std::endl;
|
||||
std::cout << "=========================================================================================================================" << std::endl;
|
||||
int step_count = 1;
|
||||
std::cout << "Test " << "[" << Formatter::to_string(side) << " Order]" << std::endl << "\t1. "
|
||||
<< Formatter::join([&]() {
|
||||
return Formatter::fmt("\n\t", ++step_count, ". ");
|
||||
}, steps...)
|
||||
<< std::endl;
|
||||
std::cout << "=========================================================================================================================" << std::endl;
|
||||
std::cout << "*************************************************************************************************************************" << std::endl;
|
||||
std::cout << std::endl;
|
||||
OrderDefinition def;
|
||||
// price is irrelevant
|
||||
auto state = init_state(def, side, qty, -99999, price_offset, gates);
|
||||
state.settlement(settle);
|
||||
(steps.execute(state), ...);
|
||||
}
|
||||
|
||||
template<typename... Steps>
|
||||
inline void test_permutations(
|
||||
uint32_t qty,
|
||||
double settle,
|
||||
std::vector<LimitCoverGate> gates,
|
||||
Steps... steps) {
|
||||
std::vector<double> price_offsets { 0.0, 0.75, 1.25, -0.75, -1.25 };
|
||||
for (auto po : price_offsets) {
|
||||
// complete
|
||||
test_impl(api::SIDE_BUY, qty, po, settle, gates, steps..., test_steps::Complete());
|
||||
test_impl(api::SIDE_SELL, qty, po, settle, gates, steps..., test_steps::Complete());
|
||||
// cancel child
|
||||
test_impl(api::SIDE_BUY, qty, po, settle, gates, steps..., test_steps::CancelChild());
|
||||
test_impl(api::SIDE_SELL, qty, po, settle, gates, steps..., test_steps::CancelChild());
|
||||
// cancel algo
|
||||
test_impl(api::SIDE_BUY, qty, po, settle, gates, steps..., test_steps::CancelAlgo());
|
||||
test_impl(api::SIDE_SELL, qty, po, settle, gates, steps..., test_steps::CancelAlgo());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("test_activation_thresholds.", "[algo][limit_cover]") {
|
||||
SECTION("Activate 1st gate.") {
|
||||
test_permutations(25, 100, {
|
||||
LimitCoverGate(4, 4, 4),
|
||||
LimitCoverGate(10, 7, 5),
|
||||
LimitCoverGate(15, 12, 11),
|
||||
},
|
||||
// test steps
|
||||
test_steps::BeginLaunch(),
|
||||
test_steps::Launch(),
|
||||
test_steps::BreechActivationThresh());
|
||||
}
|
||||
SECTION("Activate 1st then 2nd gate.") {
|
||||
test_permutations(25, 100, {
|
||||
LimitCoverGate(4, 4, 4),
|
||||
LimitCoverGate(10, 7, 5),
|
||||
LimitCoverGate(15, 12, 11),
|
||||
},
|
||||
// test steps
|
||||
test_steps::BeginLaunch(),
|
||||
test_steps::Launch(),
|
||||
test_steps::BreechActivationThresh(),
|
||||
test_steps::Fill([](const auto& state) { return test_params::fills::child(state, 8); }),
|
||||
test_steps::BreechActivationThresh(),
|
||||
test_steps::Fill([](const auto& state) { return test_params::fills::child(state, 2); }),
|
||||
test_steps::BreechActivationThresh());
|
||||
}
|
||||
SECTION("Activate 2nd gate.") {
|
||||
test_permutations(25, 100, {
|
||||
LimitCoverGate(4, 4, 4),
|
||||
LimitCoverGate(10, 7, 5),
|
||||
LimitCoverGate(15, 12, 11),
|
||||
},
|
||||
// test steps
|
||||
test_steps::BeginLaunch(),
|
||||
test_steps::Launch(),
|
||||
test_steps::BreechActivationThresh(1, 1),
|
||||
test_steps::Fill([](const auto& state) { return test_params::fills::child(state, 8); }));
|
||||
}
|
||||
}
|
||||
} // namespace limit_cover
|
||||
} // namespace test
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,743 +0,0 @@
|
||||
#include "catch/catch.hpp"
|
||||
#include "../DormanAlgo.h"
|
||||
#include "AlgoTestDriver.h"
|
||||
#include "lib/orderman/orderman_utils/Book.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/orderman/orderman_utils/orderman_utils.h"
|
||||
#include <optional>
|
||||
#include <variant>
|
||||
#include <random>
|
||||
|
||||
using namespace std;
|
||||
using namespace bts::orderman::dorman;
|
||||
using namespace bts::api::orderman;
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace test {
|
||||
|
||||
/* STATE
|
||||
|
||||
struct OrderState {
|
||||
Price desired_price;
|
||||
Quantity exposed_qty;
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
/* TEST ASPECTS
|
||||
|
||||
order_qty vs market quantity
|
||||
order_qty reduce when market changes
|
||||
order_qty increase (w/ delay) when market changes
|
||||
order_qty maximum
|
||||
|
||||
overfill [under/over] max with auto-scratch [on/off]
|
||||
Profit orders
|
||||
- test that orders are sent
|
||||
- test that away order are at the right price
|
||||
|
||||
Trade Accumulation
|
||||
- accumulator goes [on/off]
|
||||
- Dorman goes to sleep when it goes 'on' and wakes up when it goes 'off'
|
||||
|
||||
Market Moves
|
||||
- Available size increases
|
||||
- Available size decreases
|
||||
|
||||
clip size pseudo-order
|
||||
- change clip size
|
||||
- immidiate effect?
|
||||
- don't have to cancel if clip size goes down?
|
||||
- change order size [up/down]
|
||||
- suspend/resume
|
||||
- cancels all
|
||||
|
||||
|
||||
*/
|
||||
|
||||
api::orderman::DynamicOrderDefinition to_dynamic_order_params(const AlgoParams& input) {
|
||||
api::orderman::DynamicOrderDefinition result;
|
||||
result.set_dynamic_order_type("Dorman");
|
||||
auto& map = *result.mutable_order_params();
|
||||
|
||||
for (size_t x = 0; x < input.steps.step_table.size(); ++x) {
|
||||
std::string xs = std::to_string(x+1);
|
||||
map["Market Quantity " + xs] = dynamic_parameter( std::get<0>(input.steps.step_table[x]));
|
||||
map["Order Quantity " + xs] = dynamic_parameter(std::get<1>(input.steps.step_table[x]));
|
||||
}
|
||||
|
||||
map["Max Size"] = dynamic_parameter(input.steps.maximum);
|
||||
map["Trail Seconds"] = dynamic_parameter(input.steps.trail_seconds);
|
||||
map["Clip Size"] = dynamic_parameter(input.clip_limit);
|
||||
|
||||
// scratch
|
||||
map["Enable Scratch"] = dynamic_parameter((bool)(input.scratch));
|
||||
if (input.scratch) {
|
||||
map["Max Overfill"] = dynamic_parameter(input.scratch.value().max_overfill);
|
||||
}
|
||||
//
|
||||
// profit orders
|
||||
map["Profit Orders"] = dynamic_parameter((bool)input.profit_orders);
|
||||
if (input.profit_orders) {
|
||||
map["Ticks Away"] = dynamic_parameter(input.profit_orders.value().ticks_away);
|
||||
}
|
||||
|
||||
//
|
||||
// trade accumulator
|
||||
map["Trade Accumulation"] = dynamic_parameter((bool)input.trade_accumulation);
|
||||
if (input.trade_accumulation) {
|
||||
auto& a = input.trade_accumulation.value();
|
||||
map[("Trade Contracts")] = dynamic_parameter(a.contracts);
|
||||
map["Trade Interval (seconds)"] = dynamic_parameter(a.seconds);
|
||||
map["Trade Sleep (seconds)"] = dynamic_parameter(a.sleep_seconds);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void check_round_trip(const AlgoParams& input) {
|
||||
auto d1 = to_dynamic_order_params(input);
|
||||
auto ap1 = to_dorman_params(d1);
|
||||
if (std::holds_alternative<OrderOpResult>(ap1)) {
|
||||
std::cout << std::get<OrderOpResult>(ap1).error_msg;
|
||||
}
|
||||
REQUIRE(std::holds_alternative<AlgoParams>(ap1));
|
||||
auto d2 = to_dynamic_order_params(std::get<AlgoParams>(ap1));
|
||||
|
||||
REQUIRE(d2.DebugString() == d1.DebugString());
|
||||
}
|
||||
|
||||
TEST_CASE("dorman_round_trip_params", "[algo][dorman]") {
|
||||
|
||||
SECTION("a") {
|
||||
AlgoParams input;
|
||||
input.steps = {
|
||||
{ {500, 250},
|
||||
{1000, 400} },
|
||||
1024, 5
|
||||
};
|
||||
check_round_trip(input);
|
||||
}
|
||||
|
||||
SECTION("b") {
|
||||
AlgoParams input;
|
||||
input.steps = {
|
||||
{ {500, 250},
|
||||
{1000, 400}
|
||||
},
|
||||
1024, 5
|
||||
};
|
||||
input.scratch = { 500 };
|
||||
input.profit_orders = { 42 };
|
||||
input.clip_limit = 220;
|
||||
check_round_trip(input);
|
||||
}
|
||||
|
||||
SECTION("c") {
|
||||
AlgoParams input;
|
||||
input.steps = {
|
||||
{ {500, 250},
|
||||
{1000, 400}
|
||||
},
|
||||
1024, 5
|
||||
};
|
||||
input.profit_orders = { 42 };
|
||||
input.trade_accumulation = {
|
||||
100, 200, 300
|
||||
};
|
||||
check_round_trip(input);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
struct ExpectedSize {
|
||||
uint32_t input;
|
||||
uint32_t expected;
|
||||
};
|
||||
constexpr auto some_price = md::IntPrice { 128000, -3 };
|
||||
|
||||
|
||||
template <class CB>
|
||||
size_t count_x(const std::vector<ChildOrder>& child_orders, CB fn) {
|
||||
return std::accumulate(
|
||||
child_orders.begin(),
|
||||
child_orders.end(), 0,
|
||||
[&](uint32_t acc, const auto& child) {
|
||||
return acc + fn(child);
|
||||
});
|
||||
}
|
||||
|
||||
size_t count_exposed(const std::vector<ChildOrder>& child_orders) {
|
||||
return count_x(child_orders, [](const ChildOrder& child) {
|
||||
REQUIRE(child.def);
|
||||
if (child.cstate.status == ChildStatus::CANCELED) return 0u;
|
||||
else return child.def.value().custom_def().splitter().exposed_qty() + child.cstate.total_fills.value();
|
||||
});
|
||||
}
|
||||
|
||||
size_t count_fills(const std::vector<ChildOrder>& child_orders) {
|
||||
return count_x(child_orders, [](const ChildOrder& child) {
|
||||
return child.def.value().custom_def().splitter().exposed_qty() + child.cstate.total_fills.value();
|
||||
});
|
||||
}
|
||||
size_t count_status(const std::vector<ChildOrder>& child_orders, ChildStatus status) {
|
||||
size_t match = 0;
|
||||
for (const auto& child : child_orders) {
|
||||
if (child.cstate.status == status) match += 1;
|
||||
}
|
||||
return match;
|
||||
}
|
||||
|
||||
TEST_CASE("dorman_order_size", "[algo][dorman]") {
|
||||
// create a table of various sizes
|
||||
// send market state to the algo
|
||||
AlgoParams input;
|
||||
input.steps.step_table = {
|
||||
{500, 250},
|
||||
{1000, 400},
|
||||
{2000, 600},
|
||||
{3500, 750},
|
||||
{10000, 999}
|
||||
};
|
||||
input.steps.maximum = 800;
|
||||
input.steps.trail_seconds = 5;
|
||||
input.clip_limit = 100;
|
||||
|
||||
api::orderman::OrderDefinition def;
|
||||
def.set_side(api::SIDE_BUY);
|
||||
def.mutable_custom_def()->mutable_dynamic()->CopyFrom(to_dynamic_order_params(input));
|
||||
|
||||
SECTION("initial size vs market") {
|
||||
std::vector<ExpectedSize> test_sizes {
|
||||
{ 10, 0 },
|
||||
{ 200, 0 },
|
||||
{ 250, 0 },
|
||||
{ 500, 250 },
|
||||
{ 999, 250 },
|
||||
{ 2500, 600 },
|
||||
{ 9999, 750 },
|
||||
{ 20002, 800 },
|
||||
};
|
||||
|
||||
for (auto& s : test_sizes)
|
||||
{
|
||||
AlgoTestDriver<DormanAlgo> state(def, some_price, Quantity {10});
|
||||
auto secid = SecurityKey(state.security().id());
|
||||
Book book(secid);
|
||||
|
||||
// order size is driven by the available market size
|
||||
book.bid()[0] = { some_price, s.input };
|
||||
state.update_book(book);
|
||||
|
||||
REQUIRE(state.before_launch().ok());
|
||||
state.launch();
|
||||
REQUIRE(state.algo().exposed_qty().value() == s.expected);
|
||||
REQUIRE(s.expected == count_exposed(state.child_orders()));
|
||||
}
|
||||
}
|
||||
SECTION("Reduce qty on market shrink (immidiate)") {
|
||||
AlgoTestDriver<DormanAlgo> state(def, some_price, Quantity {10});
|
||||
auto secid = SecurityKey(state.security().id());
|
||||
Book book(secid);
|
||||
book.bid()[0] = { some_price, 505 };
|
||||
state.update_book(book);
|
||||
REQUIRE(state.before_launch().ok());
|
||||
state.launch();
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(250));
|
||||
|
||||
// Check that orders were created
|
||||
REQUIRE(250 == count_exposed(state.child_orders()));
|
||||
for(const auto& ch : state.child_orders()) {
|
||||
REQUIRE(ch.cstate.quantity == state.quantity());
|
||||
}
|
||||
|
||||
// Reduce market
|
||||
book.bid()[0] = { some_price, 405 };
|
||||
state.update_book(book);
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(0));
|
||||
REQUIRE(
|
||||
0 == count_exposed(state.child_orders()));
|
||||
}
|
||||
|
||||
SECTION("Increase qty w/ delay when market grows") {
|
||||
AlgoTestDriver<DormanAlgo> state(def, some_price, Quantity {10});
|
||||
auto secid = SecurityKey(state.security().id());
|
||||
Book book(secid);
|
||||
book.bid()[0] = { some_price, 505 };
|
||||
state.update_book(book);
|
||||
REQUIRE(state.before_launch().ok());
|
||||
state.launch();
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(250));
|
||||
|
||||
// Check that orders were created
|
||||
REQUIRE(
|
||||
250 == count_exposed(state.child_orders()));
|
||||
|
||||
// INCREASE market
|
||||
book.bid()[0] = { some_price, 1001 };
|
||||
state.update_book(book);
|
||||
// NOTE: that the orders do not follow the market instantly
|
||||
// so this is still 250
|
||||
REQUIRE(
|
||||
250 == count_exposed(state.child_orders()));
|
||||
|
||||
// Still 250 after the timer ticks but not enough time has passed
|
||||
state.advance_time(std::chrono::seconds());
|
||||
REQUIRE(
|
||||
250 == count_exposed(state.child_orders()));
|
||||
|
||||
state.advance_time(std::chrono::seconds(input.steps.trail_seconds));
|
||||
REQUIRE(
|
||||
400 == count_exposed(state.child_orders()));
|
||||
|
||||
}
|
||||
SECTION("Respect maximum") {
|
||||
AlgoTestDriver<DormanAlgo> state(def, some_price, Quantity {10});
|
||||
auto secid = SecurityKey(state.security().id());
|
||||
Book book(secid);
|
||||
book.bid()[0] = { some_price, 10505 };
|
||||
state.update_book(book);
|
||||
REQUIRE(state.before_launch().ok());
|
||||
state.launch();
|
||||
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(input.steps.maximum));
|
||||
|
||||
// Check that orders were created
|
||||
REQUIRE(
|
||||
input.steps.maximum == count_exposed(state.child_orders()));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Dorman fills", "[algo][dorman]") {
|
||||
AlgoParams input;
|
||||
input.steps.step_table = {
|
||||
{500, 250},
|
||||
{1000, 450},
|
||||
{2000, 650},
|
||||
{3500, 750},
|
||||
};
|
||||
input.steps.maximum = 750;
|
||||
input.steps.trail_seconds = 2;
|
||||
input.clip_limit = 100;
|
||||
api::orderman::OrderDefinition def;
|
||||
def.set_side(api::SIDE_BUY);
|
||||
def.mutable_custom_def()->mutable_dynamic()->CopyFrom(to_dynamic_order_params(input));
|
||||
auto price = Price { some_price.price() };
|
||||
|
||||
SECTION("complete when filled") {
|
||||
// Send out some orders
|
||||
// Fill them
|
||||
// Expect order state to become finished
|
||||
AlgoTestDriver<DormanAlgo> state(def, some_price, Quantity {10});
|
||||
auto secid = SecurityKey(state.security().id());
|
||||
Book book(secid);
|
||||
book.bid()[0] = { some_price, 501 };
|
||||
state.update_book(book);
|
||||
REQUIRE(state.before_launch().ok());
|
||||
state.launch();
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(250));
|
||||
|
||||
for (const auto& order : state.child_orders()) {
|
||||
state.fill(order.key, price, order.cstate.quantity);
|
||||
}
|
||||
|
||||
REQUIRE(state.state() == AlgoState::COMPLETED);
|
||||
}
|
||||
|
||||
// Test cases for transitions w/ fills
|
||||
//
|
||||
|
||||
SECTION("Complete by update") {
|
||||
// target = 500, exposed = 650
|
||||
// Fill 400
|
||||
// Change target to 350
|
||||
// expect completion
|
||||
AlgoTestDriver<DormanAlgo> state(def, some_price, Quantity {500});
|
||||
auto secid = SecurityKey(state.security().id());
|
||||
Book book(secid);
|
||||
book.bid()[0] = { some_price, 1999 };
|
||||
state.update_book(book);
|
||||
REQUIRE(state.before_launch().ok());
|
||||
state.launch();
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(450));
|
||||
REQUIRE(state.quantity() == Quantity {500});
|
||||
|
||||
// Fill 400
|
||||
state.fill(price, Quantity { 400 });
|
||||
Update update;
|
||||
update.set_quantity(350);
|
||||
state.do_update(update);
|
||||
REQUIRE(state.state() == AlgoState::COMPLETED);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Dorman overfill", "[algo][dorman]") {
|
||||
AlgoParams input;
|
||||
input.steps.step_table = {
|
||||
{500, 250},
|
||||
{1000, 450},
|
||||
{2000, 650},
|
||||
{3500, 750},
|
||||
};
|
||||
input.steps.maximum = 750;
|
||||
input.steps.trail_seconds = 2;
|
||||
input.clip_limit = 100;
|
||||
|
||||
SECTION("auto-scratch ON") {
|
||||
input.scratch = {{ 500 }};
|
||||
}
|
||||
SECTION("auto-scratch OFF") {
|
||||
// both sections will run
|
||||
input.scratch = std::nullopt;
|
||||
}
|
||||
|
||||
api::orderman::OrderDefinition def;
|
||||
def.set_side(api::SIDE_BUY);
|
||||
def.mutable_custom_def()->mutable_dynamic()->CopyFrom(to_dynamic_order_params(input));
|
||||
auto price = Price { some_price.price() };
|
||||
|
||||
AlgoTestDriver<DormanAlgo> state(def, some_price, Quantity {100});
|
||||
state.allow_overfill();
|
||||
auto secid = SecurityKey(state.security().id());
|
||||
Book book(secid);
|
||||
book.bid()[0] = { some_price, 1999 };
|
||||
state.update_book(book);
|
||||
REQUIRE(state.before_launch().ok());
|
||||
state.launch();
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(450));
|
||||
REQUIRE(state.quantity() == Quantity {100});
|
||||
REQUIRE(state.child_orders().size() == 1);
|
||||
|
||||
state.fill(state.child_orders().begin()->key, price, Quantity {500});
|
||||
REQUIRE(state.state() == AlgoState::COMPLETED);
|
||||
|
||||
if (input.scratch) {
|
||||
// check that we scratched
|
||||
REQUIRE(state.detached_orders().size() > 0);
|
||||
}
|
||||
else {
|
||||
// check that we *did not* scratch
|
||||
REQUIRE(state.detached_orders().size() == 0);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
TEST_CASE("Dorman profit-orders", "[algo][dorman]") {
|
||||
AlgoParams input;
|
||||
input.steps.step_table = {
|
||||
{500, 250},
|
||||
{1000, 450},
|
||||
{2000, 650},
|
||||
{3500, 750},
|
||||
};
|
||||
input.steps.maximum = 750;
|
||||
input.steps.trail_seconds = 2;
|
||||
input.clip_limit = 100;
|
||||
|
||||
bool test_cancel = true;
|
||||
|
||||
SECTION("Profit Orders ON - Cancel") {
|
||||
// Send profit orders 3 ticks away
|
||||
input.profit_orders = {{ 3 }};
|
||||
}
|
||||
SECTION("Profit Orders ON - Complete") {
|
||||
// Send profit orders 3 ticks away
|
||||
input.profit_orders = {{ 3 }};
|
||||
test_cancel = false;
|
||||
}
|
||||
SECTION("Profit Orders OFF") {
|
||||
input.profit_orders = std::nullopt;
|
||||
}
|
||||
SECTION("Profit Orders OFF - complete") {
|
||||
input.profit_orders = std::nullopt;
|
||||
test_cancel = false;
|
||||
}
|
||||
|
||||
api::orderman::OrderDefinition def;
|
||||
def.set_side(api::SIDE_BUY);
|
||||
def.mutable_custom_def()->mutable_dynamic()->CopyFrom(to_dynamic_order_params(input));
|
||||
auto price = Price { some_price.price() };
|
||||
|
||||
AlgoTestDriver<DormanAlgo> state(def, some_price, Quantity {100});
|
||||
auto secid = SecurityKey(state.security().id());
|
||||
auto tick = state.security().contract_spec().low_tick();
|
||||
Book book(secid);
|
||||
book.bid()[0] = { some_price, 1999 };
|
||||
state.update_book(book);
|
||||
REQUIRE(state.before_launch().ok());
|
||||
state.launch();
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(450));
|
||||
REQUIRE(state.quantity() == Quantity {100});
|
||||
REQUIRE(state.child_orders().size() == 1);
|
||||
|
||||
state.fill(state.child_orders().begin()->key, price, Quantity {20});
|
||||
|
||||
if (input.profit_orders) {
|
||||
// We're testing the bid side so we expect 3 ticks up
|
||||
auto expected_price = Price {
|
||||
price.value() + (tick * input.profit_orders.value().ticks_away) };
|
||||
REQUIRE(state.child_orders().size() > 1);
|
||||
REQUIRE(state.detached_orders().empty());
|
||||
size_t profit_order_count = 0;
|
||||
for (const auto& order : state.child_orders()) {
|
||||
if (order.def.value().side() == api::SIDE_SELL) {
|
||||
profit_order_count += 1;
|
||||
REQUIRE(order.cstate.quantity.value() == 20);
|
||||
REQUIRE(securities::is_same(order.cstate.price, expected_price));
|
||||
}
|
||||
}
|
||||
REQUIRE(profit_order_count == 1);
|
||||
}
|
||||
else {
|
||||
REQUIRE(state.child_orders().size() == 1);
|
||||
REQUIRE(state.detached_orders().empty());
|
||||
}
|
||||
|
||||
state.fill(state.child_orders().begin()->key, price, Quantity {42});
|
||||
|
||||
if (input.profit_orders) {
|
||||
auto expected_price = Price {
|
||||
price.value() + (tick * input.profit_orders.value().ticks_away) };
|
||||
REQUIRE(state.child_orders().size() > 1);
|
||||
REQUIRE(state.detached_orders().empty());
|
||||
bool got_20 = false;
|
||||
bool got_42 = false;
|
||||
for (const auto& order : state.child_orders()) {
|
||||
if (order.def.value().side() == api::SIDE_SELL) {
|
||||
if (order.cstate.quantity.value() == 20) got_20 = true;
|
||||
if (order.cstate.quantity.value() == 42) got_42 = true;
|
||||
REQUIRE(securities::is_same(order.cstate.price, expected_price));
|
||||
}
|
||||
}
|
||||
REQUIRE(got_42);
|
||||
REQUIRE(got_20);
|
||||
}
|
||||
else {
|
||||
REQUIRE(state.child_orders().size() == 1);
|
||||
REQUIRE(state.detached_orders().empty());
|
||||
}
|
||||
|
||||
if (test_cancel) {
|
||||
// Profit orders should detach on cancel
|
||||
state.cancel();
|
||||
REQUIRE(state.state() == AlgoState::CANCELED);
|
||||
if (input.profit_orders) {
|
||||
REQUIRE(state.detached_orders().size() > 0);
|
||||
}
|
||||
}
|
||||
else {
|
||||
state.fill(state.child_orders().begin()->key, price, Quantity {38});
|
||||
REQUIRE(state.state() == AlgoState::COMPLETED);
|
||||
if (input.profit_orders) {
|
||||
REQUIRE(state.detached_orders().size() > 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TEST_CASE("Dorman detaches profit orders when completed by scratch", "[algo][dorman][!hide]") {
|
||||
// Idea for future test
|
||||
// }
|
||||
|
||||
TickerUpdateEvent::Trade mkTrade(Price p, Quantity q) {
|
||||
return {
|
||||
Timer::now(),
|
||||
p,
|
||||
q,
|
||||
Quantity { q.value() + 9999 },
|
||||
co2::AGGRESSOR_SIDE_NONE
|
||||
};
|
||||
}
|
||||
|
||||
TradeVector mkTrades(Price p, Quantity total) {
|
||||
std::random_device rd;
|
||||
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
|
||||
|
||||
uint32_t remaining = total.value();
|
||||
TradeVector result;
|
||||
while(remaining > 0) {
|
||||
std::uniform_real_distribution<> dis(1, remaining);
|
||||
auto qty = (uint32_t)dis(gen);
|
||||
remaining -= qty;
|
||||
result.push_back(mkTrade(p, Quantity {qty}));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
TEST_CASE("Dorman trade accumulation", "[algo][dorman]") {
|
||||
// Start algo with trade accumulation enabled
|
||||
// If 100 trades in 5 seconds pause for 6 seconds
|
||||
// Exceed Limits
|
||||
// Check that child was canceled and re-created
|
||||
// Disable accumulator
|
||||
// attempt to exceed limits
|
||||
// Check that algo does not turn off
|
||||
// re-enable accumulator
|
||||
// Check that algo turns off
|
||||
// Change parameters
|
||||
// Check that the algo turns off based on the *new* params
|
||||
|
||||
AlgoParams input;
|
||||
input.steps.step_table = {
|
||||
{225, 32},
|
||||
{362, 64},
|
||||
{589, 128},
|
||||
{697, 5000},
|
||||
};
|
||||
input.steps.maximum = 9999;
|
||||
input.clip_limit = 8;
|
||||
// If 100 trades in 5 seconds pause for 6 seconds
|
||||
input.trade_accumulation = {TradeAccumulationParams { 100, 5, 6 } };
|
||||
|
||||
api::orderman::OrderDefinition def;
|
||||
def.set_side(api::SIDE_BUY);
|
||||
def.mutable_custom_def()->mutable_dynamic()->CopyFrom(to_dynamic_order_params(input));
|
||||
auto price = Price { some_price.price() };
|
||||
|
||||
AlgoTestDriver<DormanAlgo> state(def, some_price, Quantity {2500});
|
||||
auto secid = SecurityKey(state.security().id());
|
||||
Book book(secid);
|
||||
book.bid()[0] = { some_price, 1999 };
|
||||
state.update_book(book);
|
||||
REQUIRE(state.before_launch().ok());
|
||||
state.launch();
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(5000));
|
||||
REQUIRE(state.child_orders().size() == 1);
|
||||
|
||||
state.advance_time(std::chrono::seconds(1));
|
||||
|
||||
// Need 100 trades in 5 seconds,
|
||||
// The algorithm we're using has a margin of error so
|
||||
// lets do 25 trades per second for 5 seconds which should be comfortably over
|
||||
// send_trades(state, Quantity { 120 }, std::chrono::seconds(5));
|
||||
for (auto t = 0; t < 5; ++t) {
|
||||
state.update_ticker(secid, mkTrades(price, Quantity { 25 }));
|
||||
state.advance_time(std::chrono::milliseconds(1001), 3);
|
||||
}
|
||||
REQUIRE(count_exposed(state.child_orders()) == 0);
|
||||
|
||||
state.advance_time(std::chrono::seconds(4));
|
||||
// Check that it hasn't jumped the gun
|
||||
REQUIRE(count_exposed(state.child_orders()) == 0);
|
||||
state.advance_time(std::chrono::seconds(3));
|
||||
|
||||
// Sleep time has expired so we should re-join the market
|
||||
REQUIRE(count_exposed(state.child_orders()) == 5000);
|
||||
|
||||
|
||||
// Disable the accumulator
|
||||
Update update;
|
||||
input.trade_accumulation = std::nullopt;
|
||||
update.mutable_custom()->mutable_dynamic()->CopyFrom(to_dynamic_order_params(input));
|
||||
update.set_quantity(5000);
|
||||
state.do_update(update);
|
||||
|
||||
// Attempt to exceed again
|
||||
for (auto t = 0; t < 5; ++t) {
|
||||
state.update_ticker(secid, mkTrades(price, Quantity { 25 }));
|
||||
state.advance_time(std::chrono::milliseconds(1001), 9);
|
||||
}
|
||||
// Still working
|
||||
REQUIRE(count_exposed(state.child_orders()) == 5000);
|
||||
|
||||
// re-enable accumulator
|
||||
input.trade_accumulation = {TradeAccumulationParams { 100, 5, 6 } };
|
||||
update.mutable_custom()->mutable_dynamic()->CopyFrom(to_dynamic_order_params(input));
|
||||
state.do_update(update);
|
||||
|
||||
for (auto t = 0; t < 5; ++t) {
|
||||
state.update_ticker(secid, mkTrades(price, Quantity { 25 }));
|
||||
state.advance_time(std::chrono::milliseconds(1001), 4);
|
||||
}
|
||||
// turned off?
|
||||
REQUIRE(count_exposed(state.child_orders()) == 0);
|
||||
state.advance_time(std::chrono::seconds(10));
|
||||
// back on!
|
||||
REQUIRE(count_exposed(state.child_orders()) == 5000);
|
||||
|
||||
// Change the accumulator params without disabling it
|
||||
input.trade_accumulation = {TradeAccumulationParams { 1000, 5, 6 } };
|
||||
update.mutable_custom()->mutable_dynamic()->CopyFrom(to_dynamic_order_params(input));
|
||||
state.do_update(update);
|
||||
|
||||
// Attempt to trigger based on the old settings.
|
||||
for (auto t = 0; t < 5; ++t) {
|
||||
state.update_ticker(secid, mkTrades(price, Quantity { 35 }));
|
||||
state.advance_time(std::chrono::milliseconds(1001), 7);
|
||||
}
|
||||
// Still working?
|
||||
REQUIRE(count_exposed(state.child_orders()) == 5000);
|
||||
|
||||
// Attempt to trigger based on new settings
|
||||
for (auto t = 0; t < 5; ++t) {
|
||||
state.update_ticker(secid, mkTrades(price, Quantity { 500 }));
|
||||
state.advance_time(std::chrono::milliseconds(1001), 5);
|
||||
}
|
||||
REQUIRE(count_exposed(state.child_orders()) == 0);
|
||||
|
||||
// complete while paused (fills can arrive after requested cancel)
|
||||
ChildOrder latest_order = {};
|
||||
for (auto& order : state.child_orders()) {
|
||||
if (order.key > latest_order.key) latest_order = order;
|
||||
}
|
||||
state.fill(latest_order.key, price, latest_order.cstate.quantity);
|
||||
REQUIRE(state.state() == AlgoState::COMPLETED);
|
||||
|
||||
}
|
||||
|
||||
TEST_CASE("Dorman updates child", "[algo][dorman]") {
|
||||
// When updating the Dorman price the price of the child should also update
|
||||
}
|
||||
|
||||
TEST_CASE("Dorman market move up then back down", "[algo][dorman]") {
|
||||
// Start dorman algo
|
||||
// Move market up so we plan to increase the exposed qty after trail_seconds
|
||||
// Move market back down before trail_seconds elapses
|
||||
// check that algo does *not* increase exposure
|
||||
|
||||
AlgoParams input;
|
||||
input.steps.step_table = {
|
||||
{500, 250},
|
||||
{1000, 450},
|
||||
{2000, 650},
|
||||
{3500, 750},
|
||||
};
|
||||
input.steps.maximum = 750;
|
||||
input.steps.trail_seconds = 30;
|
||||
input.clip_limit = 100;
|
||||
api::orderman::OrderDefinition def;
|
||||
def.set_side(api::SIDE_BUY);
|
||||
def.mutable_custom_def()->mutable_dynamic()->CopyFrom(to_dynamic_order_params(input));
|
||||
// auto price = Price { some_price.price() };
|
||||
|
||||
AlgoTestDriver<DormanAlgo> state(def, some_price, Quantity {1337});
|
||||
auto secid = SecurityKey(state.security().id());
|
||||
|
||||
Book book(secid);
|
||||
book.bid()[0] = { some_price, 1350 };
|
||||
state.update_book(book);
|
||||
REQUIRE(state.before_launch().ok());
|
||||
state.launch();
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(450));
|
||||
REQUIRE(state.child_orders().size() == 1);
|
||||
state.advance_time(std::chrono::seconds(1));
|
||||
|
||||
// Update book sets future quantity = 650
|
||||
book.bid()[0] = { some_price, 2219 };
|
||||
state.update_book(book);
|
||||
state.advance_time(std::chrono::seconds(10));
|
||||
// Algo does not increase exposure after 10 second
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(450));
|
||||
|
||||
book.bid()[0] = { some_price, 1425 };
|
||||
state.update_book(book);
|
||||
state.advance_time(std::chrono::seconds(40));
|
||||
// Algo does not increase exposure after trail_seconds
|
||||
REQUIRE(state.algo().exposed_qty() == Quantity(450));
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}}}//namespace
|
||||
|
||||
@@ -1,199 +0,0 @@
|
||||
#include "lib/orderman/orders/algo/algo_orders/tests/limit_cover/LimitCoverState.h"
|
||||
#include "catch/catch.hpp"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/md/IntPrice.h"
|
||||
#include "lib/orderman/order_factory/IOrderFactory.h"
|
||||
#include "lib/orderman/orderman_utils/BookUtils.h"
|
||||
#include "lib/orderman/orderman_utils/Formatter.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverAdapter.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/tests/limit_cover/LimitCoverTestUtils.h"
|
||||
|
||||
#define VALIDATE Validation __VALIDATION(this)
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace test {
|
||||
namespace limit_cover {
|
||||
using namespace std;
|
||||
using namespace bts::api::orderman;
|
||||
using namespace bts::orderman::limit_cover::utils;
|
||||
using Size = bts::md::Size;
|
||||
using Side = bts::api::Side;
|
||||
|
||||
LimitCoverState::LimitCoverState(
|
||||
const OrderDefinition& def,
|
||||
uint32_t quantity,
|
||||
double price)
|
||||
: driver(def, int_price(price), Quantity(quantity)), _definition(def), _gates(), _book(SecurityKey(security().id())) {
|
||||
auto ngs = limit_cover().normal_gates();
|
||||
_gates.insert(ngs.begin(), ngs.end());
|
||||
// attach callbacks
|
||||
driver.on_child_launching([&](OrderKey key, Quantity child_qty, Price child_price) {
|
||||
// should never deploy twice
|
||||
REQUIRE(_child == null_order_key());
|
||||
REQUIRE(key != null_order_key());
|
||||
_child = key;
|
||||
// qty should match the algo's, but price must be the limit price
|
||||
// (the algo's price is irrelevant)
|
||||
REQUIRE(child_qty.value() == driver.quantity().value());
|
||||
REQUIRE(child_price.value() == limit_price());
|
||||
// todo: verify delete and cover def matches the current gate
|
||||
//REQUIRE(child_def.custom_def().delete_and_cover())
|
||||
REQUIRE(limit_volume() >= activation_threshold());
|
||||
});
|
||||
driver.on_child_changed([&](const ChildOrder&, const ChildOrder& new_state) {
|
||||
REQUIRE(new_state.key == _child);
|
||||
REQUIRE(new_state.def.has_value());
|
||||
REQUIRE(new_state.def.value().has_custom_def());
|
||||
REQUIRE(new_state.def.value().custom_def().has_delete_and_cover());
|
||||
});
|
||||
driver.after_child_changed([&](const ChildOrder&, const ChildOrder& new_state) {
|
||||
REQUIRE(driver.total_fills().value() == new_state.cstate.total_fills.value());
|
||||
});
|
||||
}
|
||||
|
||||
uint32_t LimitCoverState::quantity() const {
|
||||
return driver.quantity().value();
|
||||
}
|
||||
double LimitCoverState::price() const {
|
||||
return driver.price().value();
|
||||
}
|
||||
const api::Security& LimitCoverState::security() const {
|
||||
return driver.security();
|
||||
}
|
||||
const bts::api::orderman::OrderDefinition& LimitCoverState::def() const {
|
||||
return _definition;
|
||||
}
|
||||
LimitCoverDefinition LimitCoverState::limit_cover() const {
|
||||
return LimitCoverAdapter::from_proto(def());
|
||||
}
|
||||
uint32_t LimitCoverState::limit_volume() const {
|
||||
return _limit_volume;
|
||||
}
|
||||
double LimitCoverState::limit_price() const {
|
||||
return _limit_price;
|
||||
}
|
||||
OrderKey LimitCoverState::child() const {
|
||||
return _child;
|
||||
}
|
||||
optional<ChildOrder> LimitCoverState::child_state() const {
|
||||
if (has_been_deployed()) {
|
||||
return ChildOrder(*driver.child_orders().begin());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
void LimitCoverState::update_child(const Update& u) {
|
||||
driver.update_child(child(), u);
|
||||
}
|
||||
bool LimitCoverState::has_been_deployed() const {
|
||||
return _child != null_order_key();
|
||||
}
|
||||
bool LimitCoverState::is_terminated() const {
|
||||
switch (driver.state()) {
|
||||
case AlgoState::CANCELED:
|
||||
case AlgoState::TERMINATED:
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const std::map<uint32_t, LimitCoverGate>& LimitCoverState::gates() const {
|
||||
return _gates;
|
||||
}
|
||||
const LimitCoverGate& LimitCoverState::curr_gate() const {
|
||||
REQUIRE(!gates().empty());
|
||||
return gates().begin()->second;
|
||||
}
|
||||
uint32_t LimitCoverState::activation_threshold() const {
|
||||
return gates().empty() ? std::numeric_limits<uint32_t>::max() : gates().begin()->first;
|
||||
}
|
||||
// settlement
|
||||
double LimitCoverState::settlement() const { return _settlement; }
|
||||
void LimitCoverState::settlement(double value) {
|
||||
VALIDATE;
|
||||
// the algo is not supposed to disregard settlement changes
|
||||
// after the child has been deployed
|
||||
if (!has_been_deployed()) {
|
||||
_settlement = value;
|
||||
recompute_all();
|
||||
}
|
||||
driver.update_settlement(SecurityKey(security().id()), Price(value));
|
||||
}
|
||||
|
||||
// book
|
||||
const Book& LimitCoverState::book() const { return _book; }
|
||||
void LimitCoverState::book(Book value) {
|
||||
VALIDATE;
|
||||
_book = value;
|
||||
recompute_all();
|
||||
driver.update_book(value);
|
||||
}
|
||||
|
||||
OrderOpResult LimitCoverState::before_launch() {
|
||||
_gates.clear();
|
||||
auto ngs = limit_cover().normal_gates();
|
||||
_gates.insert(ngs.begin(), ngs.end());
|
||||
return driver.before_launch();
|
||||
}
|
||||
void LimitCoverState::launch() {
|
||||
VALIDATE;
|
||||
_is_initialized = true;
|
||||
recompute_all();
|
||||
driver.launch();
|
||||
}
|
||||
void LimitCoverState::do_update(const Update& upd) {
|
||||
REQUIRE(!is_terminated());
|
||||
// updates should not affect the child's price (after it has been launched).
|
||||
// this is bc the literal 'price' parameter is irrelevant to this algo,
|
||||
// for all intents and purposes, its price is the tick offset from settlement.
|
||||
auto upd_valid = validate_update(upd);
|
||||
// keep definition in sync with update
|
||||
if (upd.has_custom() && upd_valid.ok()) {
|
||||
*(_definition.mutable_custom_def()) = upd.custom();
|
||||
}
|
||||
driver.do_update(upd);
|
||||
if (upd_valid.ok()) {
|
||||
recompute_all();
|
||||
} else {
|
||||
REQUIRE(driver.state() == AlgoState::TERMINATED);
|
||||
}
|
||||
}
|
||||
|
||||
void LimitCoverState::recompute_limit_price() {
|
||||
_limit_price = os::is_nan(settlement()) ? os::nan() :
|
||||
securities::improve_price(side(), Price(settlement()), Price(limit_cover().price_offset()))
|
||||
.value();
|
||||
}
|
||||
|
||||
void LimitCoverState::recompute_limit_volume() {
|
||||
_limit_volume = os::is_nan(settlement()) ? os::nan() :
|
||||
BookUtils::volume_at_or_better(_book, side(), limit_price());
|
||||
}
|
||||
|
||||
void LimitCoverState::recompute_all() {
|
||||
recompute_limit_price();
|
||||
recompute_limit_volume();
|
||||
if (_is_initialized)
|
||||
recompute_gate();
|
||||
}
|
||||
|
||||
void LimitCoverState::recompute_gate() {
|
||||
if (gates().empty())
|
||||
return;
|
||||
auto it = _gates.lower_bound(limit_volume());
|
||||
if (it->first > limit_volume() && it != _gates.begin())
|
||||
it--;
|
||||
_gates.erase(_gates.begin(), it);
|
||||
}
|
||||
|
||||
LimitCoverState::ValidateDeployment::ValidateDeployment(LimitCoverState* state) :
|
||||
_state(state), _had_been_deployed(state->has_been_deployed()) { }
|
||||
|
||||
LimitCoverState::ValidateDeployment::~ValidateDeployment() {
|
||||
if (!_had_been_deployed && _state->limit_volume() >= _state->activation_threshold())
|
||||
REQUIRE(_state->has_been_deployed());
|
||||
}
|
||||
} // namespace limit_cover
|
||||
} // namespace test
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,121 +0,0 @@
|
||||
#pragma once
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/domain_model/Security.h"
|
||||
#include "lib/orderman/orderman_utils/Book.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/LimitCoverAlgo.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/limit_cover/LimitCoverDefinition.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/tests/AlgoTestDriver.h"
|
||||
#include "lib/sparkproto/SparkProtos.pb.h"
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <optional>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace test {
|
||||
namespace limit_cover {
|
||||
struct LimitCoverState {
|
||||
AlgoTestDriver<LimitCoverAlgo> driver;
|
||||
|
||||
LimitCoverState(
|
||||
const api::orderman::OrderDefinition& def,
|
||||
uint32_t quantity,
|
||||
double price);
|
||||
|
||||
const api::orderman::OrderDefinition& def() const;
|
||||
uint32_t quantity() const;
|
||||
double price() const;
|
||||
const api::Security& security() const;
|
||||
LimitCoverDefinition limit_cover() const;
|
||||
api::Side side() const { return def().side(); }
|
||||
uint32_t activation_threshold() const;
|
||||
// main child
|
||||
OrderKey child() const;
|
||||
std::optional<ChildOrder> child_state() const;
|
||||
// gates/curr gate
|
||||
const std::map<uint32_t, LimitCoverGate>& gates() const;
|
||||
const LimitCoverGate& curr_gate() const;
|
||||
// book
|
||||
const Book& book() const;
|
||||
void book(Book new_book);
|
||||
//
|
||||
bool has_been_deployed() const;
|
||||
// settle
|
||||
double settlement() const;
|
||||
void settlement(double value);
|
||||
// limit price
|
||||
double limit_price() const;
|
||||
// limit volume
|
||||
uint32_t limit_volume() const;
|
||||
bool is_terminated() const;
|
||||
OrderOpResult before_launch();
|
||||
void launch();
|
||||
void do_update(const api::orderman::Update&);
|
||||
void update_child(const api::orderman::Update&);
|
||||
|
||||
private:
|
||||
api::orderman::OrderDefinition _definition;
|
||||
uint32_t _limit_volume = 0;
|
||||
OrderKey _child;
|
||||
double _limit_price = os::nan();
|
||||
double _settlement = os::nan();
|
||||
bool _is_initialized = false;
|
||||
std::map<uint32_t, LimitCoverGate> _gates;
|
||||
Book _book;
|
||||
|
||||
void recompute_limit_price();
|
||||
void recompute_limit_volume();
|
||||
void recompute_all();
|
||||
void recompute_gate();
|
||||
|
||||
struct ValidateDeployment {
|
||||
ValidateDeployment(LimitCoverState* state);
|
||||
~ValidateDeployment();
|
||||
|
||||
private:
|
||||
LimitCoverState* _state;
|
||||
bool _had_been_deployed;
|
||||
};
|
||||
|
||||
struct Validation : public ValidateDeployment {
|
||||
Validation(LimitCoverState* state)
|
||||
: ValidateDeployment(state) {}
|
||||
|
||||
~Validation() {}
|
||||
};
|
||||
};
|
||||
|
||||
// custom formatting uses 1 line (unlike pb::to_string).
|
||||
inline std::ostream& operator<<(std::ostream& ostr, const bts::spark::QuantityMeasure& qm) {
|
||||
switch (qm.quantity_case()) {
|
||||
case bts::spark::QuantityMeasure::kAbsolute:
|
||||
ostr << "[absolute] " << qm.absolute();
|
||||
break;
|
||||
case bts::spark::QuantityMeasure::kRatio:
|
||||
ostr << "[ratio] " << qm.ratio();
|
||||
break;
|
||||
default:
|
||||
ostr << "[quantity_case_" << static_cast<int>(qm.quantity_case()) << "]";
|
||||
break;
|
||||
}
|
||||
return ostr;
|
||||
}
|
||||
|
||||
inline std::ostream& operator<<(std::ostream& ostr, const LimitCoverState& lcs) {
|
||||
ostr << "qty: " << lcs.quantity() << std::endl;
|
||||
ostr << "limit price: " << lcs.limit_price() << std::endl;
|
||||
ostr << "limit volume: " << lcs.limit_volume() << std::endl;
|
||||
ostr << "activation/curr gate thresh: " << lcs.activation_threshold() << std::endl;
|
||||
ostr << "settlement: " << lcs.settlement() << std::endl;
|
||||
ostr << "bbo: " << Formatter::to_string(lcs.book()) << std::endl;
|
||||
ostr << "has been deployed: " << lcs.has_been_deployed() << std::endl;
|
||||
ostr << "status: " << lcs.driver.state() << std::endl;
|
||||
ostr << "child: " << lcs.child() << std::endl;
|
||||
ostr << "child qty: " << (lcs.child_state().has_value() ? lcs.child_state().value().cstate.quantity.value() : 0) << std::endl;
|
||||
ostr << "filled qty: " << lcs.driver.total_fills().value() << std::endl;
|
||||
return ostr;
|
||||
}
|
||||
} // namespace limit_cover
|
||||
} // namespace test
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,44 +0,0 @@
|
||||
#pragma once
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/md/IntPrice.h"
|
||||
#include "lib/orderman/orderman_utils/Formatter.h"
|
||||
#include "lib/sparkproto/SparkProtos.pb.h"
|
||||
#include <iostream>
|
||||
|
||||
#define SUMMARIZE(...) Summary __summary__ (Formatter::fmt(__VA_ARGS__))
|
||||
|
||||
using Side = bts::api::Side;
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace test {
|
||||
namespace limit_cover {
|
||||
using namespace std;
|
||||
inline bts::md::IntPrice int_price(double value) {
|
||||
return bts::md::IntPrice_from_double<8>(value);
|
||||
}
|
||||
inline bts::md::PriceSize price_size(double price, uint32_t size) {
|
||||
return bts::md::PriceSize(int_price(price), size);
|
||||
}
|
||||
inline bts::spark::QuantityMeasure qty_measure(uint32_t abs) {
|
||||
bts::spark::QuantityMeasure qm;
|
||||
qm.set_absolute(abs);
|
||||
return qm;
|
||||
}
|
||||
|
||||
struct Summary {
|
||||
Summary(std::string header)
|
||||
: _header(header) {
|
||||
std::cout << "Begin " << header << std::endl;
|
||||
}
|
||||
~Summary() {
|
||||
std::cout << "End " << _header << std::endl;
|
||||
}
|
||||
private:
|
||||
std::string _header;
|
||||
};
|
||||
|
||||
} // namespace limit_cover
|
||||
} // namespace test
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,221 +0,0 @@
|
||||
#include "lib/orderman/orders/algo/algo_orders/tests/limit_cover/TestSteps.h"
|
||||
#include "catch/catch.hpp"
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/orderman/order_factory/IOrderFactory.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/tests/limit_cover/LimitCoverTestUtils.h"
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace test {
|
||||
namespace limit_cover {
|
||||
|
||||
std::string ITestStep::name() const { return "step with no name"; }
|
||||
void ITestStep::execute(LimitCoverState &state) const {
|
||||
SUMMARIZE(name());
|
||||
assert_pre_conditions(state);
|
||||
_execute(state);
|
||||
assert_post_conditions(state);
|
||||
}
|
||||
void ITestStep::assert_pre_conditions_core(const LimitCoverState &) const {}
|
||||
void ITestStep::execute_core(LimitCoverState &) const { bts_assert(false); }
|
||||
void ITestStep::assert_post_conditions_core(const LimitCoverState &) const {}
|
||||
void ITestStep::assert_pre_conditions(const LimitCoverState &state) const {
|
||||
// SUMMARIZE("Asserting Pre-conditions (", name(), ")...");
|
||||
assert_pre_conditions_core(state);
|
||||
}
|
||||
void ITestStep::assert_post_conditions(const LimitCoverState &state) const {
|
||||
// SUMMARIZE("Asserting Post-conditions (", name(), ")...");
|
||||
assert_post_conditions_core(state);
|
||||
}
|
||||
void ITestStep::_execute(LimitCoverState &state) const {
|
||||
// SUMMARIZE("Executing (", name(), ")...");
|
||||
execute_core(state);
|
||||
}
|
||||
|
||||
std::ostream& operator<<(std::ostream& ostr, const ITestStep& ts) {
|
||||
ostr << ts.name();
|
||||
return ostr;
|
||||
}
|
||||
|
||||
LimitCoverState& operator<<(LimitCoverState& state, const ITestStep& ts) {
|
||||
SUMMARIZE(ts.name());
|
||||
ts.execute(state);
|
||||
return state;
|
||||
}
|
||||
|
||||
/////////////////////
|
||||
// Test Params
|
||||
/////////////////////
|
||||
namespace test_params {
|
||||
namespace fills {
|
||||
Fill child(const LimitCoverState& state, std::optional<uint32_t> qty, std::optional<double> price) {
|
||||
if (!qty.has_value()) {
|
||||
REQUIRE(state.child_state().value().active_qty() > 0);
|
||||
}
|
||||
if (!price.has_value()) {
|
||||
REQUIRE(state.child_state().has_value());
|
||||
}
|
||||
return test_params::Fill(
|
||||
qty.has_value() ? qty.value() : state.child_state().value().active_qty(),
|
||||
price.has_value() ? price.value() : state.child_state().value().cstate.price.value());
|
||||
}
|
||||
} // namespace fills
|
||||
} // namespace test_params
|
||||
|
||||
/////////////////////
|
||||
// Order Selectors
|
||||
/////////////////////
|
||||
namespace order_selectors {
|
||||
std::vector<OrderKey> child(const LimitCoverState& state) {
|
||||
std::vector<OrderKey> rv;
|
||||
if (state.has_been_deployed()) {
|
||||
rv.push_back(state.child());
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
std::vector<OrderKey> self(const LimitCoverState&) {
|
||||
std::vector<OrderKey> rv;
|
||||
rv.push_back(null_order_key());
|
||||
return rv;
|
||||
}
|
||||
} // namespace order_selectors
|
||||
|
||||
/////////////////////////
|
||||
// Order Ops (step impls)
|
||||
/////////////////////////
|
||||
namespace ops {
|
||||
void begin_launch(LimitCoverState& state) {
|
||||
REQUIRE(state.driver.before_launch().ok());
|
||||
}
|
||||
|
||||
void launch(LimitCoverState& state) {
|
||||
state.driver.launch();
|
||||
}
|
||||
|
||||
void breech_activation_thresh(LimitCoverState& state, uint32_t thresh_count, int offset) {
|
||||
auto book = state.book();
|
||||
REQUIRE(!os::is_nan(state.limit_price()));
|
||||
auto gate_it = state.gates().upper_bound(state.limit_volume());
|
||||
REQUIRE(gate_it != state.gates().end());
|
||||
while (thresh_count-- > 0 && gate_it != state.gates().end())
|
||||
gate_it++;
|
||||
auto thresh = gate_it->first + offset;
|
||||
int gi = 1;
|
||||
auto& bs = book.side(state.side());
|
||||
if (bs[0].size() == 0) {
|
||||
bs[0] = price_size(state.limit_price(), thresh);
|
||||
} else if (BookUtils::price_comp(state.side())(state.limit_price(), bs[0].price())) {
|
||||
// shift existing levels down 1 index,
|
||||
// put the limit volume at the top
|
||||
for (int i = bs.size() - 1; i > 0; i--) {
|
||||
bs[i] = bs[i - 1];
|
||||
}
|
||||
bs[0] = price_size(state.limit_price(), thresh);
|
||||
} else {
|
||||
// add the difference to the qty for the best price
|
||||
bs[0] = price_size(bs[0].price(), bs[0].size() + thresh - state.limit_volume());
|
||||
}
|
||||
state.book(book);
|
||||
}
|
||||
|
||||
void fill_child(LimitCoverState& state, uint32_t qty, double price, bool allow_overfill) {
|
||||
SUMMARIZE("filling child: ", Formatter::fmt_order(state.side(), qty, price));
|
||||
bts_assert(os::is_finite(price));
|
||||
bts_assert(qty > 0);
|
||||
REQUIRE(state.has_been_deployed());
|
||||
REQUIRE(!state.is_terminated());
|
||||
uint32_t orig_filled_qty = state.driver.total_fills().value();
|
||||
if (state.child_state().has_value()) {
|
||||
auto cs = state.child_state().value();
|
||||
REQUIRE(((cs.cstate.total_fills.value() - cs.cstate.fills_at_attach_time.value()) == orig_filled_qty));
|
||||
if (!allow_overfill) {
|
||||
REQUIRE(cs.active_qty() >= qty);
|
||||
}
|
||||
} else {
|
||||
REQUIRE(orig_filled_qty == 0);
|
||||
}
|
||||
state.driver.fill(state.child(), Price(price), Quantity(qty));
|
||||
}
|
||||
|
||||
void fill_child(LimitCoverState& lcs, uint32_t qty, bool allow_overfill) {
|
||||
fill_child(lcs, qty, lcs.limit_price(), allow_overfill);
|
||||
}
|
||||
|
||||
void cancel_child(LimitCoverState& state) {
|
||||
REQUIRE(state.has_been_deployed());
|
||||
REQUIRE(!state.is_terminated());
|
||||
state.driver.cancel_child(state.child());
|
||||
REQUIRE(state.driver.state() == AlgoState::TERMINATED);
|
||||
}
|
||||
|
||||
void complete(LimitCoverState& state) {
|
||||
REQUIRE(state.has_been_deployed());
|
||||
REQUIRE(!state.is_terminated());
|
||||
REQUIRE(state.driver.quantity().value() > state.driver.total_fills().value());
|
||||
fill_child(state, state.driver.quantity().value() - state.driver.total_fills().value());
|
||||
REQUIRE(state.driver.state() == AlgoState::COMPLETED);
|
||||
}
|
||||
} // namespace ops
|
||||
|
||||
/////////////////////
|
||||
// Test Steps
|
||||
/////////////////////
|
||||
namespace test_steps {
|
||||
// Begin Launch
|
||||
std::string BeginLaunch::name() const { return "Begin Launch"; }
|
||||
void BeginLaunch::execute_core(LimitCoverState &state) const { ops::begin_launch(state); }
|
||||
|
||||
// Launch
|
||||
std::string Launch::name() const { return "Launch"; }
|
||||
void Launch::execute_core(LimitCoverState &state) const { ops::launch(state); }
|
||||
|
||||
// Breech Activation Threshold
|
||||
std::string BreechActivationThresh::name() const {
|
||||
std::stringstream title;
|
||||
title << "Breech Activation Threshold " << (thresh_count + 1);
|
||||
if (offset > 0) {
|
||||
title << " (+" << offset << ")";
|
||||
} else if (offset < 0) {
|
||||
title << " (" << offset << ")";
|
||||
}
|
||||
return title.str();
|
||||
}
|
||||
void BreechActivationThresh::execute_core(LimitCoverState &state) const {
|
||||
ops::breech_activation_thresh(state, thresh_count, offset);
|
||||
}
|
||||
|
||||
// Fill
|
||||
std::string Fill::name() const { return "Fill"; }
|
||||
void Fill::execute_core(LimitCoverState &state) const {
|
||||
auto p = get_params(state);
|
||||
ops::fill_child(state, p.quantity, p.price);
|
||||
}
|
||||
|
||||
// Complete
|
||||
std::string Complete::name() const { return "Complete"; }
|
||||
void Complete::execute_core(LimitCoverState &state) const {
|
||||
ops::complete(state);
|
||||
}
|
||||
|
||||
// Cancel Child
|
||||
std::string CancelChild::name() const { return "Cancel Child"; }
|
||||
void CancelChild::execute_core(LimitCoverState& state) const {
|
||||
ops::cancel_child(state);
|
||||
}
|
||||
|
||||
// Cancel Algo
|
||||
std::string CancelAlgo::name() const { return "Cancel Algo"; }
|
||||
void CancelAlgo::execute_core(LimitCoverState& state) const {
|
||||
state.driver.cancel();
|
||||
REQUIRE(state.driver.state() == AlgoState::CANCELED);
|
||||
}
|
||||
} // namespace test_steps
|
||||
} // namespace limit_cover
|
||||
} // namespace test
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -1,126 +0,0 @@
|
||||
#pragma once
|
||||
#include "catch/catch.hpp"
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/orderman/orders/algo/algo_orders/tests/limit_cover/LimitCoverState.h"
|
||||
#include <functional>
|
||||
#include <iostream>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
namespace test {
|
||||
namespace limit_cover {
|
||||
// In Visual Studio, intellisense and syntax highlighting don't work (at all)
|
||||
// when <optional> is included, unless 'using namespace std;' is specified.
|
||||
using namespace std;
|
||||
|
||||
struct ITestStep {
|
||||
virtual std::string name() const;
|
||||
void execute(LimitCoverState& state) const;
|
||||
protected:
|
||||
virtual void assert_pre_conditions_core(const LimitCoverState&) const;
|
||||
virtual void execute_core(LimitCoverState&) const;
|
||||
virtual void assert_post_conditions_core(const LimitCoverState&) const;
|
||||
private:
|
||||
void assert_pre_conditions(const LimitCoverState& state) const;
|
||||
void assert_post_conditions(const LimitCoverState& state) const;
|
||||
void _execute(LimitCoverState& state) const;
|
||||
};
|
||||
|
||||
std::ostream& operator<<(std::ostream& ostr, const ITestStep& ts);
|
||||
LimitCoverState& operator<<(LimitCoverState& state, const ITestStep& ts);
|
||||
|
||||
namespace order_selectors {
|
||||
std::vector<OrderKey> child(const LimitCoverState &lcs);
|
||||
std::vector<OrderKey> self(const LimitCoverState &);
|
||||
} // namespace order_selectors
|
||||
|
||||
namespace ops {
|
||||
void begin_launch(LimitCoverState& lcs);
|
||||
void launch(LimitCoverState& lcs);
|
||||
void breech_activation_thresh(LimitCoverState& lcs, uint32_t thresh_count = 0, int offset = 0);
|
||||
|
||||
void fill_child(LimitCoverState& lcs, uint32_t qty, double price, bool allow_overfill = false);
|
||||
void fill_child(LimitCoverState& lcs, uint32_t qty, bool allow_overfill = false);
|
||||
|
||||
void cancel_child(LimitCoverState& state);
|
||||
void complete(LimitCoverState& lcs);
|
||||
}
|
||||
|
||||
namespace test_params {
|
||||
struct Fill {
|
||||
uint32_t quantity;
|
||||
double price;
|
||||
|
||||
Fill(uint32_t quantity, double price)
|
||||
: quantity(quantity), price(price) {}
|
||||
};
|
||||
|
||||
namespace fills {
|
||||
Fill child(const LimitCoverState& state, optional<uint32_t> qty = {}, optional<double> price = {});
|
||||
} // namespace fills
|
||||
} // namespace test_params
|
||||
namespace test_steps {
|
||||
struct BeginLaunch : public ITestStep {
|
||||
std::string name() const override;
|
||||
void execute_core(LimitCoverState& state) const override;
|
||||
};
|
||||
|
||||
struct Launch : public ITestStep {
|
||||
std::string name() const override;
|
||||
void execute_core(LimitCoverState& state) const override;
|
||||
};
|
||||
|
||||
struct BreechActivationThresh : public ITestStep {
|
||||
uint32_t thresh_count;
|
||||
int offset;
|
||||
|
||||
BreechActivationThresh(uint32_t thresh_count = 0, int offset = 0)
|
||||
: thresh_count(thresh_count), offset(offset) { }
|
||||
|
||||
std::string name() const override;
|
||||
void execute_core(LimitCoverState& state) const override;
|
||||
};
|
||||
|
||||
struct Fill : public ITestStep {
|
||||
std::function<test_params::Fill(const LimitCoverState&)> get_params;
|
||||
|
||||
Fill(std::function<test_params::Fill(const LimitCoverState&)> get_params)
|
||||
: get_params(get_params) {}
|
||||
|
||||
std::string name() const override;
|
||||
void execute_core(LimitCoverState& state) const override;
|
||||
};
|
||||
|
||||
struct Complete : public ITestStep {
|
||||
std::string name() const override;
|
||||
void execute_core(LimitCoverState& state) const override;
|
||||
};
|
||||
|
||||
struct CancelChild : public ITestStep {
|
||||
std::string name() const override;
|
||||
void execute_core(LimitCoverState& state) const override;
|
||||
};
|
||||
|
||||
struct CancelAlgo : public ITestStep {
|
||||
std::string name() const override;
|
||||
void execute_core(LimitCoverState& state) const override;
|
||||
};
|
||||
|
||||
struct Custom : public ITestStep {
|
||||
Custom(std::string name, std::function<void(LimitCoverState&)> impl)
|
||||
: _name(name), _impl(impl) { }
|
||||
|
||||
std::string name() const override { return _name; }
|
||||
void execute_core(LimitCoverState& state) const override { _impl(state); }
|
||||
private:
|
||||
std::string _name;
|
||||
std::function<void(LimitCoverState&)> _impl;
|
||||
};
|
||||
} // namespace test_steps
|
||||
} // namespace limit_cover
|
||||
} // namespace test
|
||||
} // namespace orderman
|
||||
} // namespace bts
|
||||
@@ -37,6 +37,14 @@ public:
|
||||
double size_multiplier() const { return _leg_contract.quantity(); }
|
||||
double tick_size() const { return _leg_contract.security().contract_spec().low_tick(); }
|
||||
bool is_active_quoting() const {return _leg_params.is_active_quoting();}
|
||||
bool send_hedge() const {
|
||||
// for backwards compat, if its unset, then hedges are sent
|
||||
return !_leg_params.has_send_hedge() || _leg_params.send_hedge().val();
|
||||
}
|
||||
// if both quoting and hedging are turned off, this results false, else true
|
||||
bool is_active_trading() const{
|
||||
return is_active_quoting() || send_hedge();
|
||||
}
|
||||
bool is_net_change() const{
|
||||
return _price_calc==bts::api::SyntheticContract::PRICECALC_NET_CHANGE;
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ _hidden_order(this_leg_property.leg_params().has_quote_params() &&
|
||||
this_leg_property.leg_params().quote_params().has_quote_hidden()),
|
||||
_force_show_qty(this_leg_property.n_queue_holder_orders()==0 &&
|
||||
this_leg_property.has_show_qty()),
|
||||
_last_price_improve_time(google::protobuf::util::TimeUtil::GetEpoch()),
|
||||
_last_price_run_time(google::protobuf::util::TimeUtil::GetEpoch()),
|
||||
_is_permenantly_cancelled (false),
|
||||
_irrecoverable_error(false),
|
||||
_n_spreader_legs (n_spreader_legs),
|
||||
@@ -162,7 +164,8 @@ bool SingleLegQuoter::accept_modifications() const {
|
||||
_worker->state() == QuoterState::WORKING;
|
||||
}
|
||||
void SingleLegQuoter::_incorporate_other_leg_fill (size_t, Quantity hedge_reduction){
|
||||
_price_quantity_state.add_hedged_reduction (hedge_reduction);
|
||||
if(_this_leg_data.send_hedge())
|
||||
_price_quantity_state.add_hedged_reduction (hedge_reduction);
|
||||
}
|
||||
void SingleLegQuoter::_compute_quote(
|
||||
Quantity target_qty,
|
||||
|
||||
@@ -20,6 +20,8 @@
|
||||
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h"
|
||||
#include "lib/orderman/orders/spreader_orders/spreader/quoter/QuoteDriverSetHistory.h"
|
||||
#include <sstream>
|
||||
#include <google/protobuf/timestamp.pb.h>
|
||||
#include <google/protobuf/util/time_util.h>
|
||||
|
||||
|
||||
namespace bts {
|
||||
@@ -43,6 +45,8 @@ private:
|
||||
// if this is set to true, _compute_price_quantity
|
||||
// will use LegPropertyData::show_qty()
|
||||
const bool _force_show_qty;
|
||||
google::protobuf::Timestamp _last_price_improve_time,
|
||||
_last_price_run_time;
|
||||
bool _is_permenantly_cancelled;
|
||||
bool _irrecoverable_error;
|
||||
// this is a config constant. if the quoter
|
||||
@@ -177,6 +181,13 @@ private:
|
||||
_spreader.current_time());
|
||||
}
|
||||
void _modify_order (Price price, Quantity quantity) {
|
||||
auto now = google::protobuf::util::TimeUtil::GetCurrentTime();
|
||||
if(bts::securities::is_equal_or_better(_this_leg_data.trading_side(),
|
||||
price,
|
||||
_price_quantity_state.out_price()))
|
||||
_last_price_improve_time = now;
|
||||
else
|
||||
_last_price_run_time = now;
|
||||
_child_order_state.modify_order(price, quantity);
|
||||
}
|
||||
void _cancel_order () {_child_order_state.cancel_order();}
|
||||
|
||||
@@ -79,6 +79,8 @@ void SpreaderBookkeepingData::total_fills (Quantity& out_quantity,
|
||||
double avg_price = 0.0;
|
||||
double fills = std::numeric_limits<double>::max();
|
||||
for (const SpreaderLegData& leg_data : _leg_data){
|
||||
if(!leg_data.leg_property_data().is_active_trading())
|
||||
continue;
|
||||
Quantity leg_fill_qty; Price leg_fill_price;
|
||||
leg_data.total_fills(leg_fill_qty, leg_fill_price);
|
||||
double leg_normalized_qty = static_cast<double>(leg_fill_qty.value()) /
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
#include "lib/orderman/actors/order_manager/OrderBuilder.h"
|
||||
#include "lib/os/os.h"
|
||||
#include <google/protobuf/timestamp.pb.h>
|
||||
#include <google/protobuf/util/time_util.h>
|
||||
#include <random>
|
||||
|
||||
namespace bts {
|
||||
@@ -290,6 +292,8 @@ public:
|
||||
const Book& qbook,
|
||||
api::Side quote_side,
|
||||
double tick_size,
|
||||
google::protobuf::Timestamp last_price_improve_time,
|
||||
google::protobuf::Timestamp last_price_run_time,
|
||||
const bts::spark::QuoteParams& quote_params){
|
||||
|
||||
bool reject =
|
||||
@@ -305,7 +309,16 @@ public:
|
||||
qbook.side(quote_side)[0].price(),
|
||||
quote_side,
|
||||
tick_size,
|
||||
quote_params.quote_inside_market_distance_throttle()));
|
||||
quote_params.quote_inside_market_distance_throttle())) ||
|
||||
(quote_params.has_time_based_throttle() &&
|
||||
is_time_throttle_reject(quote_side,
|
||||
current_price,
|
||||
new_price,
|
||||
last_price_improve_time,
|
||||
last_price_run_time,
|
||||
quote_params.time_based_throttle().delay_to_improve(),
|
||||
quote_params.time_based_throttle().delay_to_run()));
|
||||
|
||||
return reject;
|
||||
}
|
||||
|
||||
@@ -344,6 +357,32 @@ public:
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool is_time_throttle_reject(api::Side side,
|
||||
double current_price,
|
||||
double new_price,
|
||||
google::protobuf::Timestamp last_price_improve_time,
|
||||
google::protobuf::Timestamp last_price_run_time,
|
||||
uint32_t delay_to_improve,
|
||||
uint32_t delay_to_run){
|
||||
auto now = google::protobuf::util::TimeUtil::GetCurrentTime();
|
||||
if(bts::securities::is_equal_or_better(side,
|
||||
Price(new_price),
|
||||
Price(current_price))){
|
||||
// improvement
|
||||
int64_t ms_diff =
|
||||
google::protobuf::util::TimeUtil::TimestampToMilliseconds(now)-
|
||||
google::protobuf::util::TimeUtil::TimestampToMilliseconds(last_price_improve_time);
|
||||
return ms_diff < static_cast<int64_t>(delay_to_improve);
|
||||
}
|
||||
else{
|
||||
// run
|
||||
int64_t ms_diff =
|
||||
google::protobuf::util::TimeUtil::TimestampToMilliseconds(now)-
|
||||
google::protobuf::util::TimeUtil::TimestampToMilliseconds(last_price_run_time);
|
||||
return ms_diff < static_cast<int64_t>(delay_to_run);
|
||||
}
|
||||
}
|
||||
|
||||
static bool conditional_quoting(Price quoting_price,
|
||||
Quantity quoting_qty,
|
||||
@@ -727,6 +766,7 @@ public:
|
||||
Quantity hedge_qty;
|
||||
compute_driver(quote_target,quote_leg_data,hedge_leg_data,hedge_leg_book,
|
||||
hedge_price,hedge_qty,quote_qty);
|
||||
hedge_price = Price(offset_driver_price(hedge_price.value(),hedge_leg_data));
|
||||
double out_price = (target_spread_price.value() - hedge_price.value() * hedge_leg_data.price_multiplier())/quote_leg_data.price_multiplier();
|
||||
out_price = bts::securities::raw_round_to_quote_price (out_price, quote_leg_data.tick_size(), quote_leg_data.trading_side());
|
||||
quote_price = Price(out_price);
|
||||
@@ -784,6 +824,15 @@ public:
|
||||
out_driver_vector[idx].set (hedge_price, hedge_qty, quote_qty);
|
||||
}
|
||||
}
|
||||
static double offset_driver_price (double driver_price,
|
||||
const LegPropertyData& driver_lp){
|
||||
int offset_ticks = driver_lp.leg_params().quote_params().lean_offset_ticks();
|
||||
double offset_price = offset_ticks * driver_lp.tick_size();
|
||||
if(driver_lp.trading_side() == api::Side::SIDE_BUY)
|
||||
return driver_price + offset_price;
|
||||
else
|
||||
return driver_price - offset_price;
|
||||
}
|
||||
// computes the quoting price from the leg drivers
|
||||
// ie (spreader_price - sum (price_mult * price))/quoting_leg_mult
|
||||
static Price compute_quoting_price_from_drivers(Price target_spread_price,
|
||||
@@ -794,8 +843,11 @@ public:
|
||||
size_t n_legs = driver_vector.size();
|
||||
double sum = 0;
|
||||
for (size_t idx = 0; idx < n_legs; idx++)
|
||||
if (idx != quoting_leg_index)
|
||||
sum += driver_vector[idx].driver_price().value() * spreader.get_leg_data (idx).price_multiplier();
|
||||
if (idx != quoting_leg_index){
|
||||
double driver_price = driver_vector[idx].driver_price().value();
|
||||
driver_price = offset_driver_price(driver_price,spreader.get_leg_data(idx));
|
||||
sum += driver_price * spreader.get_leg_data(idx).price_multiplier();
|
||||
}
|
||||
double rv = (target_spread_price.value() - sum)/quoting_leg_data.price_multiplier();
|
||||
rv = bts::securities::raw_round_to_quote_price (rv, quoting_leg_data.tick_size(), quoting_leg_data.trading_side());
|
||||
return Price(rv);
|
||||
|
||||
+7
-3
@@ -16,10 +16,14 @@ void HedgerStartStateWorker::on_transition (){
|
||||
void HedgerStartStateWorker::init (Price price,
|
||||
Quantity quantity){
|
||||
_hedger->_price_quantity_state.re_init(price,quantity);
|
||||
if(quantity.value() > 0){
|
||||
_hedger->_place_order (price, quantity);
|
||||
_hedger->transform_to_WAITING_FOR_FIRST_ACK ();
|
||||
if(_hedger->_leg_property_data.send_hedge()){
|
||||
if(quantity.value() > 0){
|
||||
_hedger->_place_order (price, quantity);
|
||||
_hedger->transform_to_WAITING_FOR_FIRST_ACK ();
|
||||
}
|
||||
}
|
||||
else
|
||||
_hedger->cancel_hedge();
|
||||
}
|
||||
void HedgerStartStateWorker::on_order_update(const SpreaderChildOrderState&){
|
||||
bts_assert_msg (false, "HedgerStartStateWorker::on_order_update "
|
||||
|
||||
+4
-1
@@ -41,7 +41,8 @@ void QuoterWorkingStateWorker::cancel(){
|
||||
void QuoterWorkingStateWorker::terminate(){
|
||||
_quoter->_transform_to_END ();
|
||||
}
|
||||
void QuoterWorkingStateWorker::on_time(const TimeStamp&){
|
||||
void QuoterWorkingStateWorker::on_time(const TimeStamp&){
|
||||
_longpath_analyze_and_act();
|
||||
}
|
||||
void QuoterWorkingStateWorker::on_other_leg_quoter_fill (size_t leg_index,
|
||||
Quantity filled_quantity){
|
||||
@@ -92,6 +93,8 @@ void QuoterWorkingStateWorker::_longpath_analyze_and_act ()
|
||||
book,
|
||||
_quoter->_this_leg_data.trading_side(),
|
||||
_quoter->_this_leg_data.tick_size(),
|
||||
_quoter->_last_price_improve_time,
|
||||
_quoter->_last_price_run_time,
|
||||
_quoter->_this_leg_data.leg_params().quote_params());
|
||||
bool reprice = !throttle_reject;
|
||||
reprice = reprice && !(_quoter->_spreader.in_cache_warming_cycle());
|
||||
|
||||
@@ -19,6 +19,9 @@ message QuantityMeasure
|
||||
message NullableQuantity{
|
||||
uint32 quantity = 10;
|
||||
}
|
||||
message NullableBoolean{
|
||||
bool val = 10;
|
||||
}
|
||||
// /*************************************************************************************************/
|
||||
// /*************************************************************************************************/
|
||||
// /*************************************Spreader Parameters*****************************************/
|
||||
@@ -46,7 +49,8 @@ message LegSpreaderParams
|
||||
PreHedgeParams pre_hedge_params = 50;
|
||||
PostHedgeParams post_hedge_params = 60;
|
||||
MarketDataType market_data_type = 70;
|
||||
//reserve LegMarketDataCalculation leg_md_calc = 80;
|
||||
//reserve LegMarketDataCalculation leg_md_calc = 80;
|
||||
NullableBoolean send_hedge = 90;
|
||||
}
|
||||
|
||||
// /*************************************************************************************************
|
||||
@@ -76,6 +80,8 @@ message QuoteParams
|
||||
uint32 n_queue_holder_orders=2000;
|
||||
// this is the show quantity on the quoter order
|
||||
NullableQuantity show_quantity = 2010;
|
||||
int32 lean_offset_ticks = 2020;
|
||||
QuoteTimeBasedThrottle time_based_throttle = 2030;
|
||||
}
|
||||
|
||||
/*************************************Quote MuteZone***********************************
|
||||
@@ -134,7 +140,10 @@ message QuoteInsideMarketDistanceThrottle
|
||||
{
|
||||
uint32 on_toward_distance = 10;
|
||||
}
|
||||
|
||||
message QuoteTimeBasedThrottle{
|
||||
uint32 delay_to_run = 10;
|
||||
uint32 delay_to_improve = 20;
|
||||
}
|
||||
/*************************************Quote RepriceThrottled (unused)*******************************
|
||||
(Stellar's sensitivity)
|
||||
This parameter defines regions (wrt their distance from the inside market)
|
||||
|
||||
@@ -19,17 +19,21 @@ target_include_directories( sparkd PUBLIC ${CMAKE_SOURCE_DIR}/src ${CMAKE_BINARY
|
||||
set_source_files_properties(exchange_sim/ExchangeSim.cpp PROPERTIES COMPILE_FLAGS --std=c++14)
|
||||
set_source_files_properties(exchange_sim/ExchangeSimApplication.cpp PROPERTIES COMPILE_FLAGS --std=c++14)
|
||||
|
||||
if (${USE_ONIX})
|
||||
set(ONIX_LIBS onixs-cmemdh-all-4.8.0 OnixS.IceImpactMulticastPriceFeedHandlerCpp ACE)
|
||||
else()
|
||||
set(ONIX_LIBS "")
|
||||
endif()
|
||||
|
||||
# linking
|
||||
target_link_libraries( sparkd
|
||||
libspark
|
||||
ssl
|
||||
cryptopp
|
||||
tbb
|
||||
onixs-cmemdh-all-4.8.0
|
||||
OnixS.IceImpactMulticastPriceFeedHandlerCpp
|
||||
ACE
|
||||
quickfix
|
||||
benchmark
|
||||
${ONIX_LIBS}
|
||||
lttng-ust
|
||||
-static-libgcc
|
||||
-static-libstdc++
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#ifdef USE_ONIX
|
||||
|
||||
#include "ICEListener.h"
|
||||
#include "lib/utils/datetime.h"
|
||||
#include <vector>
|
||||
@@ -453,3 +455,4 @@ void ICEListener::update_all_status(CoconutSecurityStatus status)
|
||||
}}} //namespace
|
||||
|
||||
|
||||
#endif
|
||||
@@ -1,3 +1,4 @@
|
||||
#ifdef USE_ONIX
|
||||
#include "ICEMain.h"
|
||||
|
||||
#include "lib/md/ice/ICEUtils.h"
|
||||
@@ -247,3 +248,4 @@ unique_ptr<ICEListener> ICEMain::prepare_listener(onixs_ice::Handler& handler, c
|
||||
|
||||
}}} //namespace
|
||||
|
||||
#endif
|
||||
@@ -1,3 +1,4 @@
|
||||
#ifdef USE_ONIX
|
||||
#include "MDP3Listener.h"
|
||||
#include "lib/utils/datetime.h"
|
||||
#include <vector>
|
||||
@@ -302,3 +303,4 @@ md::MDP3Listener::BookData::BookData(MDProducerHandle & handle) : handle(handle)
|
||||
}}//namespace
|
||||
|
||||
|
||||
#endif
|
||||
@@ -1,3 +1,4 @@
|
||||
#ifdef USE_ONIX
|
||||
#include "MDP3Main.h"
|
||||
|
||||
#include "lib/md/cme/MDP3Utils.h"
|
||||
@@ -365,3 +366,4 @@ unique_ptr<MDP3Listener> MDP3Main::prepare_listener(onixs::Handler& handler, con
|
||||
|
||||
}}//namespace
|
||||
|
||||
#endif
|
||||
@@ -10,8 +10,12 @@
|
||||
#include "lib/md/Diag/ShmDumper.h"
|
||||
#include "lib/md/Diag/MDPeriodicDumper.h"
|
||||
#include "lib/md/cme/MDP3Utils.h"
|
||||
|
||||
#ifdef USE_ONIX
|
||||
#include "platforms/mdp3_onixs/MDP3Main.h"
|
||||
#include "platforms/ice_onixs/ICEMain.h"
|
||||
#endif
|
||||
|
||||
#include "platforms/IMDPlatform.h"
|
||||
#include "lib/md/SecurityDB.h"
|
||||
#include "server/sparkd/exchange_sim/ExchangeSim.h"
|
||||
@@ -71,6 +75,10 @@ void run_replay() {
|
||||
}
|
||||
|
||||
void run_onixs(MBOWriter* mbo) {
|
||||
(void) mbo;
|
||||
|
||||
|
||||
#ifdef USE_ONIX
|
||||
std::vector<std::shared_ptr<IMDPlatform>> platforms;
|
||||
// get all glbx symbols
|
||||
std::vector<UserSymbol> cme_symbols;
|
||||
@@ -104,6 +112,7 @@ void run_onixs(MBOWriter* mbo) {
|
||||
heartbeat_timer.start();
|
||||
|
||||
disp.run();
|
||||
#endif
|
||||
}
|
||||
|
||||
void run_cleanup() {
|
||||
|
||||
@@ -1 +1 @@
|
||||
set(sources ../../externals/linux/include/google/protobuf/descriptor.proto;../../externals/linux/include/google/protobuf/timestamp.proto;../lib/api/apicore.proto;../lib/api/apigateway.proto;../lib/api/apioptions.proto;../lib/api/services/AdminService.proto;../lib/api/services/AlgoDefinitionService.proto;../lib/api/services/AlgoService.proto;../lib/api/services/ApiUnitTestService.proto;../lib/api/services/AuthService.proto;../lib/api/services/BasePositionService.proto;../lib/api/services/ErrorReportService.proto;../lib/api/services/HelloService.proto;../lib/api/services/MBOService.proto;../lib/api/services/MarginService.proto;../lib/api/services/MarketDataAuxiliaryService.proto;../lib/api/services/MarketDataRelay.proto;../lib/api/services/MarketDataService.proto;../lib/api/services/MoneyFileService.proto;../lib/api/services/OrderService.proto;../lib/api/services/OutOfProcessURLListener.proto;../lib/api/services/PersistenceService.proto;../lib/api/services/PositionService.proto;../lib/api/services/ShellDiagnosticService.proto;../lib/api/services/ShellLatencyService.proto;../lib/api/services/SyntheticSecurityService.proto;../lib/domain_model/Security.proto;../lib/md/protos/co2.proto;../lib/sparkproto/SparkProtos.proto;api/build.sh;api/node_modules/exit/test/fixtures/create-files.sh;api/node_modules/object.assign/test.sh;api/node_modules/protobufjs/cli/node_modules/acorn-jsx/node_modules/acorn/bin/update_authors.sh;api/node_modules/watch/release.sh;api/quiet_build.sh;api/src/DynamicService.ts;api/src/ServiceContext.ts;api/src/bts_assert.ts;ui/src/Access.fs;ui/src/Accounts/ClipLimits.fs;ui/src/Accounts/ProductLimits.fs;ui/src/Accounts/SecurityLimits.fs;ui/src/Accounts/State.fs;ui/src/Accounts/Types.fs;ui/src/Accounts/View.fs;ui/src/App.fs;ui/src/Cmd.fs;ui/src/Controls/Button.fs;ui/src/Controls/DataGrid.fs;ui/src/Controls/Fields.fs;ui/src/Controls/Modal.fs;ui/src/Controls/ReactGrid.fs;ui/src/Controls/Table.fs;ui/src/Controls/nbsp.fs;ui/src/Global.fs;ui/src/Imports.fs;ui/src/Lens.fs;ui/src/Login/Login.fs;ui/src/Nav.fs;ui/src/State.fs;ui/src/Types.fs;ui/src/Users/State.fs;ui/src/Users/Types.fs;ui/src/Users/View.fs;ui/src/Util/EnumUtils.fs;ui/src/Util/JSMap.fs;ui/src/Util/StreamUtils.fs)
|
||||
set(sources ../../externals/linux/include/google/protobuf/descriptor.proto;../../externals/linux/include/google/protobuf/timestamp.proto;../lib/api/apicore.proto;../lib/api/apigateway.proto;../lib/api/apioptions.proto;../lib/api/services/AdminService.proto;../lib/api/services/AlgoDefinitionService.proto;../lib/api/services/AlgoService.proto;../lib/api/services/ApiUnitTestService.proto;../lib/api/services/AuthService.proto;../lib/api/services/BasePositionService.proto;../lib/api/services/ErrorReportService.proto;../lib/api/services/HelloService.proto;../lib/api/services/MBOService.proto;../lib/api/services/MarginService.proto;../lib/api/services/MarketDataAuxiliaryService.proto;../lib/api/services/MarketDataRelay.proto;../lib/api/services/MarketDataService.proto;../lib/api/services/MoneyFileService.proto;../lib/api/services/OrderService.proto;../lib/api/services/OutOfProcessURLListener.proto;../lib/api/services/PersistenceService.proto;../lib/api/services/PositionService.proto;../lib/api/services/ShellDiagnosticService.proto;../lib/api/services/ShellLatencyService.proto;../lib/api/services/SyntheticSecurityService.proto;../lib/domain_model/Security.proto;../lib/md/protos/co2.proto;../lib/sparkproto/SparkProtos.proto;api/build.sh;api/quiet_build.sh;api/src/DynamicService.ts;api/src/ServiceContext.ts;api/src/bts_assert.ts;ui/src/Access.fs;ui/src/Accounts/ClipLimits.fs;ui/src/Accounts/ProductLimits.fs;ui/src/Accounts/SecurityLimits.fs;ui/src/Accounts/State.fs;ui/src/Accounts/Types.fs;ui/src/Accounts/View.fs;ui/src/App.fs;ui/src/Cmd.fs;ui/src/Controls/Button.fs;ui/src/Controls/DataGrid.fs;ui/src/Controls/Fields.fs;ui/src/Controls/Modal.fs;ui/src/Controls/ReactGrid.fs;ui/src/Controls/Table.fs;ui/src/Controls/nbsp.fs;ui/src/Global.fs;ui/src/Imports.fs;ui/src/Lens.fs;ui/src/Login/Login.fs;ui/src/Nav.fs;ui/src/State.fs;ui/src/Types.fs;ui/src/Users/State.fs;ui/src/Users/Types.fs;ui/src/Users/View.fs;ui/src/Util/EnumUtils.fs;ui/src/Util/JSMap.fs;ui/src/Util/StreamUtils.fs;ui/src/obj/Debug/netstandard2.0/ui.AssemblyInfo.fs)
|
||||
@@ -1,56 +0,0 @@
|
||||
Test Author: Kevin
|
||||
If it breaks: Kevin
|
||||
|
||||
This will test our ability to generate and enforce keycodes.
|
||||
|
||||
1) Find spark_private.pem and spark_public.pem in bts\spark\src\lib\utils\crypto copy them to your sparkd binary location
|
||||
|
||||
2) Now generate a keycode to a file:
|
||||
|
||||
./sparkd keycode encode -keyfile:spark_private.pem -pass:BT5u53r -users:1 -expiration:2020-05-18 > test.pem
|
||||
|
||||
3) Now decode the keycode
|
||||
|
||||
./sparkd keycode decode -keyfile:spark_public.pem -source:test.pem
|
||||
|
||||
You should see keycode details printed to screen
|
||||
|
||||
4) Now test concurrent logins. Start a sparkd. Make sure bts_2 and bts_3 have market data permission
|
||||
a) Start a spark -multiple login as bts and go to where you would see some market data
|
||||
b) Start another spark -multiple but log in as bts_2 and display some data
|
||||
c) Start a third spark -multiple, log in as bts_2 and display some data.
|
||||
|
||||
-You should see the data zero out on the first instance logged in as bts_2 and data ticking on the bts instance as well as
|
||||
the second bts_2 instance
|
||||
|
||||
d) Kill your sparkd but leave your shells open
|
||||
e) bring sparkd back up, you should see market data in the shell logged in as bts AND one of the other shells
|
||||
|
||||
4.5) For extra credit generate a keycode with -allow_concurrent and make sure we don't zero the market data for concurrent logins
|
||||
|
||||
5) Test expiration. Generate a keycode in the past:
|
||||
|
||||
./sparkd keycode encode -keyfile:spark_private.pem -pass:BT5u53r -users:1 -expiration:2018-05-18 > ~/sparkdata/conf/keycode.conf
|
||||
|
||||
a) start sparkd again.
|
||||
b) Start a spark -multiple login as bts_2 and go to where you would see some market data. You should NOT see data
|
||||
c) Start a spark -multiple login as bts, you should see data.
|
||||
d) remove the expired keycode you just generated by:
|
||||
rm ~/sparkdata/conf/keycode.conf
|
||||
e) restart sparkd, you should see data as normal in bts_2
|
||||
|
||||
6) Test admin vs trading logins
|
||||
Note that an admin login is one that does not have trading permission in any account
|
||||
AND does not have the ability to see any market data
|
||||
|
||||
a) start sparkd again. make sure bts_2 and bts_3 have market data and trading permissions in webui
|
||||
b) Start a spark -multiple login as bts_2 and go to where you would see some market data. You should see data
|
||||
c) Start a webui and log in as bts_3, you should see data
|
||||
d) close your shell and log out of web ui, now log in bts_3 into the webui and log in bts_2 in a shell (
|
||||
this is the reverse of the previous order), you should see a message in the shell about keycodes, but it will let you log in, just not see market data
|
||||
e) from the webui, de-permission bts_3 from trading AND market data,
|
||||
f) exit shell, log out of webui and kill sparkd, restart sparkd
|
||||
|
||||
g)now try d again-- you should not get the same shell error
|
||||
|
||||
|
||||
Reference in new issue
Block a user