Merge branch 'master' of bitbucket.org:bluetradesys/spark into excel_algos

This commit is contained in:
Kevin Darby committed 2019-07-31 16:17:39 -04:00
commit 5609b8d80d
60 files changed
+3947 -317

No files matched your search

+34 -34
View File
@@ -1,35 +1,35 @@
nohup.out
build/
cmake-build-debug/
.idea/
.dir-locals.el
*.pyc
.vscode/*
!.vscode/*.json
.vs
obj/
*.csproj.user
*.vspx
*.psess
msbuild.log
*.orig
vcxproj.user
src/client/spark/Properties/launchSettings.json
compile_commands.json
.cquery_cached_index/
src/client/sparkcmd/Properties/launchSettings.json
node_modules
paket-files
project.lock.json
src/server/sparkd/orderman/perf_analysis/data
src/server/sparkd/orderman/perf_analysis/logs/
src/server/sparkd/orderman/perf_analysis/trace_data/
.fake
*.fsx.lock
*.code-workspace
src/lib/orderman/perf_analysis/logs/latency_data/
trace_data/
/src/lib/orderman/perf_analysis/last_pretty_log.csv
/src/lib/orderman/perf_analysis/log.csv
/doc/user/public/*
nohup.out
build/
cmake-build-debug/
.idea/
.dir-locals.el
*.pyc
.vscode/*
!.vscode/*.json
.vs
obj/
*.csproj.user
*.vspx
*.psess
msbuild.log
*.orig
vcxproj.user
src/client/spark/Properties/launchSettings.json
compile_commands.json
.cquery_cached_index/
src/client/sparkcmd/Properties/launchSettings.json
node_modules
paket-files
project.lock.json
src/server/sparkd/orderman/perf_analysis/data
src/server/sparkd/orderman/perf_analysis/logs/
src/server/sparkd/orderman/perf_analysis/trace_data/
.fake
*.fsx.lock
*.code-workspace
src/lib/orderman/perf_analysis/logs/latency_data/
trace_data/
/src/lib/orderman/perf_analysis/last_pretty_log.csv
/src/lib/orderman/perf_analysis/log.csv
/doc/user/public/*
.ionide/*
+1 -1
View File
@@ -250,7 +250,7 @@
"program": "/home/bts/spark/build/ninja_debug/server/sparkd",
"args": [
"test",
"SingleWriterConcurrentVector"
"[algo]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/server/",
@@ -1,11 +1,11 @@
+++
title = "BTS Basic Algos"
weight = 10
title = "Basic Algos"
weight = 1
sort_by = "weight"
insert_anchor_links = "right"
aliases = ["./bts_spark/Algos/"]
+++
## Lean
The goal of the lean order is to watch the opposite-inside market size and cross when that size goes below the threshold (this also implies a cross if that size goes to zero and the market trades away from you) If the market trades toward you, you can opt into several different behaviors
@@ -43,4 +43,13 @@ An OCO order creates a relationship between a child order and a 'stop' or 'other
Composing this order with Cover simulates scalping functionality
##### Parameters
* Stop Ticks - ticks below or above main order to place stop / other order
* Stop Ticks - ticks below or above main order to place stop / other order
## Splitter
The splitter is useful for pro-rata markets where you want to vary your exposure independent of the order quantity that you want to fill. The splitter will complete when the number of fills reaches or exceeds the order quantity but it will put exposed_qty total size on the market. Splitter favors order size over queue position.
If exposed_qty is set to 0 the splitter will continue to exist in the Order Book but will cancel all of its child orders. This makes it a useful building block for custom algos that need to implement a 'paused' state.
##### Parameters
* exposed_qty - The total quantity to expose on the market.
* max_order_qty - The maximum size of a single order.
+19 -2
View File
@@ -4,6 +4,23 @@ weight = 3
sort_by = "weight"
insert_anchor_links = "right"
+++
## 2.7.2
### User Visible Changes
- Changed the login dialog to avoid leaking workspace names from other users.
- Added new Splitter algo. From the manual: The splitter is useful
for pro-rata markets where you want to vary your exposure
independent of the order quantity that you want to fill. The
splitter will complete when the number of fills reaches or exceeds
the order quantity but it will put exposed_qty total size on the
market. Splitter favors order size over queue position.
### Internal Changes
- Made spark more resilient to lack of connectivity to the CME web site for downloading of templates.
## 2.7.1
### User Visible Changes
- Fixed some issues with the Cover algo, where in some circumstances
it would erroneously cancel launched hedges on completion.
## 2.7.0
### User Visible Changes
- Allowed algos to process "in-flight" fills while shutting down
@@ -207,7 +224,7 @@ insert_anchor_links = "right"
- Integrated stunnel into UI to make VPN setup unnecessary in unsecured environments.
## 1.5.7
### User Visible Changes
- New videos have been added to the manual describing the [Algo Studio](./bts_spark/Trading/index.md#algo-studio) and [Spreader](./bts_spark/Spreader/index.md)
- New videos have been added to the manual describing the [Algo Studio](./bts_spark/Trading/_index.md#algo-studio) and [Spreader](./bts_spark/Spreader/_index.md)
- Fixed a bug that occasionally would cause windows to be position outside the visible screen on startup
- Fixed a bug in the order book form that would occasionally cause the Recreate Order option to be unavailable
- Added a confirmation step to Cancel All, Cancel Buys and Cancel Sells commands
@@ -330,7 +347,7 @@ insert_anchor_links = "right"
- The zoom slider can be enabled from Ladder Form -> Settings button -> Left Pane tab -> check Zoom Slider checkbox
- The zoom functionality can also be performed via hotkey and mouse wheel combinations
- Zoom In = CTRL + Mouse wheel up
- Zoom Out = CTRL + Mouse wheel down
- Zoom Out = CTRL + Mouse wheel down␍
- Reset zoom = CTRL + Mouse wheel click or double click on the zoom slider
### Exchange simulator
- Improved the exchange simulator to track real market data more closely
+11 -2
View File
@@ -212,6 +212,7 @@ namespace mbts.spark.utilities {
public TriggerOrderDefinition trigger_order() => OrderDataHelper.Defaults.TriggerOrderDefinition();
public DynamicOrderDefinition dynamic_order() => OrderDataHelper.Defaults.DynamicOrderDefinition();
public SpreaderOrderDefinition spreader_order() => OrderDataHelper.Defaults.SpreaderOrderDefinition();
public SplitterOrderDefinition splitter_order() => OrderDataHelper.Defaults.SplitterOrderDefinition();
public SpreaderOrderDefinition spreader_order(SecurityImmutable security, ExecutionStrategyImmutable strategy) =>
new SpreaderOrderDefinition {
Security = security.CloneToMutable(),
@@ -242,6 +243,7 @@ namespace mbts.spark.utilities {
case CustomOrderDefinition.CustomOneofCase.Offset: rv.Offset = offset_order(); break;
case CustomOrderDefinition.CustomOneofCase.Trigger: rv.Trigger = trigger_order(); break;
case CustomOrderDefinition.CustomOneofCase.Spreader: rv.Spreader = spreader_order(); break;
case CustomOrderDefinition.CustomOneofCase.Splitter: rv.Splitter = splitter_order(); break;
case CustomOrderDefinition.CustomOneofCase.Dynamic: rv.Dynamic = dynamic_order(); break;
//case CustomOrderDefinition.CustomOneofCase.QueueHolder: rv.QueueHolder = queue_holder_order(); break;
}
@@ -269,6 +271,7 @@ namespace mbts.spark.utilities {
case CustomOrderDefinition.CustomOneofCase.Offset: return new OrderMetadata { KeyBinding = "O", Color = BTSColors.Orders.off_order };
case CustomOrderDefinition.CustomOneofCase.Trigger: return new OrderMetadata { KeyBinding = "T", Color = BTSColors.Orders.trigger_order };
case CustomOrderDefinition.CustomOneofCase.Spreader: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.spreader_order };
// case CustomOrderDefinition.CustomOneofCase.Splitter: return new OrderMetadata { KeyBinding = "", Color = BTSColors.orange.rgb_color() };
case CustomOrderDefinition.CustomOneofCase.Dynamic: return new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.top_order };
case CustomOrderDefinition.CustomOneofCase.None: goto default;
//case CustomOrderDefinition.CustomOneofCase.QueueHolder: return new OrderMetadata { KeyBinding = "Q", Color = BTSColors.purple.rgb_color() };
@@ -592,6 +595,8 @@ namespace mbts.spark.utilities {
// The following standard types are not yet ready for production use:
// CustomOrderDefinition.CustomOneofCase.Tick,
// CustomOrderDefinition.CustomOneofCase.Dynamic,
// exchange_order_types are the types which can be submitted on an exchange security
exchange_order_types = new[] {
CustomOrderDefinition.CustomOneofCase.Market,
CustomOrderDefinition.CustomOneofCase.Limit,
@@ -603,7 +608,8 @@ namespace mbts.spark.utilities {
CustomOrderDefinition.CustomOneofCase.Join,
CustomOrderDefinition.CustomOneofCase.Cover,
CustomOrderDefinition.CustomOneofCase.Top,
CustomOrderDefinition.CustomOneofCase.Offset
CustomOrderDefinition.CustomOneofCase.Offset,
CustomOrderDefinition.CustomOneofCase.Splitter,
},
// The following spreader types are not yet ready for production use:
// CustomOrderDefinition.CustomOneofCase.Dynamic,
@@ -613,7 +619,8 @@ namespace mbts.spark.utilities {
CustomOrderDefinition.CustomOneofCase.Lean,
CustomOrderDefinition.CustomOneofCase.Join,
CustomOrderDefinition.CustomOneofCase.Cover,
CustomOrderDefinition.CustomOneofCase.Top
CustomOrderDefinition.CustomOneofCase.Top,
CustomOrderDefinition.CustomOneofCase.Splitter,
},
attachable_order_types = new[] {
CustomOrderDefinition.CustomOneofCase.Iceberg,
@@ -1032,6 +1039,8 @@ namespace mbts.spark.utilities {
public static TriggerOrderDefinition TriggerOrderDefinition() => new TriggerOrderDefinition { Child = CustomOrderDefinition(), TriggerCondition = new TriggerCondition(), TriggerAction = new TriggerAction(), };
public static DynamicOrderDefinition DynamicOrderDefinition() => new DynamicOrderDefinition();
public static SpreaderOrderDefinition SpreaderOrderDefinition() => new SpreaderOrderDefinition { ExecutionStrategy = new ExecutionStrategy() };
public static SplitterOrderDefinition SplitterOrderDefinition() => new SplitterOrderDefinition();
}
}
}
@@ -57,6 +57,8 @@ namespace mbts.spark {
public static IAlgoVM iceberg(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new IcebergOrderVM(key, display_name, editing_permissions);
public static IAlgoVM spreader(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions) => new SpreaderOrderVM(key, display_name, editing_permissions);
public static IAlgoVM dynamic(AlgoKey key, string display_name, string dynamic_type, AlgoEditingPermissions editing_permissions) => new DynamicOrderVM(key, dynamic_type, display_name, editing_permissions);
public static IAlgoVM splitter(AlgoKey key, string display_name, AlgoEditingPermissions permissions) =>
new SplitterAlgoVM(key, display_name, permissions);
public static IAlgoVM create(AlgoData def_data, AlgoEditingPermissions editing_permissions = default_editing_permissions, bool is_expanded = false) {
if (def_data.value.CustomCase == AlgoType.Composite) {
@@ -88,6 +90,7 @@ namespace mbts.spark {
case AlgoType.Iceberg: vm = iceberg(key, name, editing_permissions); break;
case AlgoType.Spreader: vm = spreader(key, name, editing_permissions); break;
case AlgoType.Dynamic: vm = dynamic(key, name, name, editing_permissions); break;
case AlgoType.Splitter: vm = splitter(key,name,editing_permissions); break;
case AlgoType.None: vm = new DefaultAlgoVM(); break;
default: throw new NotImplementedException();
}
@@ -0,0 +1,24 @@
using bts.api.orderman;
using mbts.ui.shell;
namespace mbts.spark
{
static partial class OrderTypeVMFactory {
class SplitterAlgoVM : OrderTypeVMBase<SplitterOrderDefinition, SplitterOrderDefinitionImmutable>
{
readonly Property<uint> _clip, _exposed;
public SplitterAlgoVM(AlgoKey id, string display_name, AlgoEditingPermissions editing_permissions)
: base(id, display_name, editing_permissions)
{
_clip = add_property<uint>(nameof(max_order_qty), SplitterOrderDefinition.MaxOrderQtyFieldNumber);
_exposed = add_property<uint>(nameof(exposed), SplitterOrderDefinition.ExposedQtyFieldNumber);
}
public uint max_order_qty { get => _clip.Value; set => _clip.set(value); }
public uint exposed { get => _exposed.Value; set => _exposed.set(value); }
}
}
}
@@ -505,8 +505,11 @@
<c:HelpButton Margin="{StaticResource Margin.LP1}" ToolTip="If the order is at the top of book, the quantity remaining below which the order will be canceled."/>
</StackPanel>
<uag:QuantityMeasureControl x:Name="PART_TopThreshold_QuantityMeasureControl" Grid.Column="2" QuantityMeasure="{Binding top_threshold}"/>
<TextBlock Grid.Row="2">Ticks Off</TextBlock>
<c:TickUpDownUInt Grid.Row="2" Grid.Column="2" Value="{Binding ticks_off}"/>
<StackPanel Grid.Row="2" Orientation="Horizontal">
<TextBlock>Ticks Off</TextBlock>
<c:HelpButton Margin="{StaticResource Margin.LP1}" ToolTip="Maximum distance the order can be from the top of the book or 0 for any distance"/>
</StackPanel>
<c:TickUpDownUInt Grid.Row="2" Grid.Column="2" Value="{Binding ticks_off}" />
<uag:AlgoPickerNodeView
x:Name="PART_Child_AlgoPickerNodeView"
Grid.Row="4"
@@ -1011,6 +1014,37 @@
</Grid>
</DataTemplate>
</usp:AlgoContentTemplateSelector.SpreaderTemplate>
<usp:AlgoContentTemplateSelector.SplitterTemplate>
<DataTemplate>
<Grid x:Name="ContentRoot">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush3}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush1}}" MaxWidth="{Binding Source={StaticResource HorizontalPush1}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="{StaticResource Margin.LP3}">Expose Quantity</TextBlock>
<c:TickUpDownUInt Grid.Column="2" HorizontalAlignment="Stretch" Value="{Binding exposed}"/>
<TextBlock Grid.Row="1" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="{StaticResource Margin.LP3}">Max Order Quantity</TextBlock>
<c:TickUpDownUInt Grid.Row="1" Grid.Column="2" HorizontalAlignment="Stretch" Value="{Binding max_order_qty}"/>
<uag:AlgoPickerNodeView
x:Name="PART_Child_AlgoPickerNodeView"
Grid.Row="3"
Grid.ColumnSpan="3"
ItemsSource="{Binding children_vm.child.algos_view}"
SelectedItem="{Binding children_vm.child.selected_algo}"
ContentTemplateSelector="{DynamicResource AlgoTemplateSelector}"
OrderKind="{x:Static usp:AlgoContentTemplateSelector.ChildKind}"
OrderKindTemplate="{StaticResource OrderKindTemplate}"
/>
</Grid>
</DataTemplate>
</usp:AlgoContentTemplateSelector.SplitterTemplate>
<usp:AlgoContentTemplateSelector.DynamicOrderTemplate>
<DataTemplate>
<Grid Grid.IsSharedSizeScope="True">
@@ -43,6 +43,7 @@ namespace mbts.ui.spark {
public DataTemplate GLBXIcebergOrderTemplate { get; set; }
public DataTemplate IcebergOrderTemplate { get; set; }
public DataTemplate SpreaderTemplate { get; set; }
public DataTemplate SplitterTemplate { get; set; }
public DataTemplate DynamicOrderTemplate { get; set; }
public DataTemplate DefaultOrderTemplate { get; set; }
@@ -66,6 +67,7 @@ namespace mbts.ui.spark {
case CustomOrderDefinition.CustomOneofCase.GlbxIceberg: return GLBXIcebergOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Iceberg: return IcebergOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Spreader: return SpreaderTemplate;
case CustomOrderDefinition.CustomOneofCase.Splitter: return SplitterTemplate;
case CustomOrderDefinition.CustomOneofCase.Dynamic: return DynamicOrderTemplate;
}
}
+257 -135
View File
@@ -1,143 +1,265 @@
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
x:Class="mbts.ui.shell.LoginView"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ui="clr-namespace:mbts.ui"
xmlns:uicore="clr-namespace:mbts.ui"
xmlns:converters="clr-namespace:mbts.ui.converters"
xmlns:autocomplete="clr-namespace:WPFTextBoxAutoComplete;assembly=WPFTextBoxAutoComplete"
mc:Ignorable="d" MouseDown="Window_MouseDown"
Width="500" Height="309" WindowStyle="None" ResizeMode="NoResize" WindowStartupLocation="CenterScreen"
ui:StateManager.VisualState="{Binding VisualState}">
<Window.Resources>
<ResourceDictionary>
<converters:BooleanToVisibilityConverter x:Key="InverseBoolToVisibility" VisibilityForFalse="Visible" VisibilityForTrue="Collapsed" />
<converters:StringToBrushConverter x:Key="ErrorStringToBrush" />
<converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter" VisibilityForNull="Hidden" />
</ResourceDictionary>
</Window.Resources>
<Window
x:Class="mbts.ui.shell.LoginView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:mbts.ui"
xmlns:uicore="clr-namespace:mbts.ui"
xmlns:shell="clr-namespace:mbts.ui.shell"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:converters="clr-namespace:mbts.ui.converters"
xmlns:autocomplete="clr-namespace:WPFTextBoxAutoComplete;assembly=WPFTextBoxAutoComplete"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Name="_login_view"
Width="460"
Height="254"
WindowStyle="None"
ResizeMode="NoResize"
WindowStartupLocation="CenterScreen"
MouseDown="Window_MouseDown"
>
<ui:StateManager.Groups>
<ui:StateGroupsManager>
<ui:StateDefinitionCollection>
<ui:StateDefinition State="{Binding DataContext.login_status, Source={ui:DirectReference _login_view}, Converter={x:Static shell:LoginView.LoginStatusVisualStateConverter}}"/>
<ui:StateDefinition State="{Binding DataContext.SelectedWorkspace, Source={ui:DirectReference _login_view}, Converter={x:Static shell:LoginView.WorkspaceVisualStateConverter}}"/>
</ui:StateDefinitionCollection>
</ui:StateGroupsManager>
</ui:StateManager.Groups>
<Window.Resources>
<ResourceDictionary>
<sys:Double x:Key="LoginControlPaddingLeft">40</sys:Double>
<sys:Double x:Key="LoginControlPaddingTop">10</sys:Double>
<sys:Double x:Key="LoginControlPaddingRight">22</sys:Double>
<converters:BooleanToVisibilityConverter x:Key="InverseBoolToVisibility" VisibilityForFalse="Visible" VisibilityForTrue="Collapsed"/>
<converters:StringToBrushConverter x:Key="ErrorStringToBrush"/>
<converters:NullToVisibilityConverter x:Key="NullToVisibilityConverter" VisibilityForNull="Hidden"/>
</ResourceDictionary>
</Window.Resources>
<Window.Background>
<StaticResource ResourceKey="CommonBackground"/>
</Window.Background>
<Window.Background>
<StaticResource ResourceKey="CommonBackground"/>
</Window.Background>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal" />
<VisualState x:Name="LoginState">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="_login_controls" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.5" />
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="_login_controls" Storyboard.TargetProperty="IsHitTestVisible">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="ErrorState">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="_error_control" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.5" />
</Storyboard>
</VisualState>
<VisualState x:Name="Loading">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="_login_controls" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.5" />
<DoubleAnimation Storyboard.TargetName="_loading_control" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.5" BeginTime="0:0:0.5" />
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="login_button" Storyboard.TargetProperty="IsEnabled" >
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="False" />
</BooleanAnimationUsingKeyFrames>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="cancel_button" Storyboard.TargetProperty="IsEnabled" >
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="False" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup x:Name="LoginError">
<VisualState x:Name="BadPassword">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="_password" Storyboard.TargetProperty="BorderBrush" >
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Brushes.Red}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="{x:Static GroupName, MemberType={ui:Nested shell:LoginView.VisualStateNames.LoginStatus}}">
<VisualState Name="{x:Static Initializing, MemberType={ui:Nested shell:LoginView.VisualStateNames.LoginStatus}}"/>
<VisualState Name="{x:Static Ready, MemberType={ui:Nested shell:LoginView.VisualStateNames.LoginStatus}}">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="_login_controls" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.5"/>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="_login_controls" Storyboard.TargetProperty="IsHitTestVisible">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static Error, MemberType={ui:Nested shell:LoginView.VisualStateNames.LoginStatus}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="_error_control" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Storyboard.TargetName="_error_control" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.5"/>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static Loading, MemberType={ui:Nested shell:LoginView.VisualStateNames.LoginStatus}}">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="_login_controls" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.5"/>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="_loading_control" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
<DoubleAnimation Storyboard.TargetName="_loading_control" Storyboard.TargetProperty="Opacity" From="0" To="1" Duration="0:0:0.5" BeginTime="0:0:0.5"/>
<DoubleAnimation Storyboard.TargetName="_login_button" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.5"/>
<DoubleAnimation Storyboard.TargetName="_cancel_button" Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.5"/>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="_dialog_skirt" Storyboard.TargetProperty="IsHitTestVisible">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="_dialog_skirt" Storyboard.TargetProperty="IsHitTestVisible">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static Rejected, MemberType={ui:Nested shell:LoginView.VisualStateNames.LoginStatus}}">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="_login_controls" Storyboard.TargetProperty="Opacity" To="1" Duration="0"/>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="_login_controls" Storyboard.TargetProperty="IsHitTestVisible">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True" />
</BooleanAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="_username" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Brushes.Red}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="_password" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0:0:0" Value="{x:Static Brushes.Red}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="_reject_message" Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup Name="{x:Static GroupName, MemberType={ui:Nested shell:LoginView.VisualStateNames.Workspace}}">
<VisualState Name="{x:Static Active, MemberType={ui:Nested shell:LoginView.VisualStateNames.Workspace}}"/>
<VisualState Name="{x:Static Inactive, MemberType={ui:Nested shell:LoginView.VisualStateNames.Workspace}}">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="_resume_workspace_checkbox" Storyboard.TargetProperty="(ToggleButton.IsChecked)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="_resume_workspace_checkbox" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border BorderBrush="{x:Static uicore:BTSColors.form_border_brush}" BorderThickness="1">
<Grid ClipToBounds="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border BorderBrush="{x:Static uicore:BTSColors.form_border_brush}" BorderThickness="1">
<Grid ClipToBounds="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<!-- Login details -->
<Grid Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center" x:Name="_login_controls" Opacity="0" IsHitTestVisible="False">
<Grid.RowDefinitions>
<RowDefinition /> <!-- User -->
<RowDefinition /> <!-- Workspace -->
<RowDefinition /> <!-- Pass -->
<RowDefinition Height="Auto" /> <!-- message -->
<RowDefinition /><!-- buttons -->
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<!-- Login details -->
<Grid
x:Name="_login_controls"
Grid.Column="1"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Opacity="0"
IsHitTestVisible="False"
>
<Grid.Margin>
<Thickness Left="{StaticResource LoginControlPaddingLeft}" Top="30" Right="{StaticResource LoginControlPaddingRight}"/>
</Grid.Margin>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="{Binding Source={StaticResource LoginControlPaddingTop}}"/>
<!-- User -->
<RowDefinition/>
<RowDefinition Height="{Binding Source={StaticResource LoginControlPaddingTop}}"/>
<!-- Workspace -->
<RowDefinition/>
<RowDefinition Height="{Binding Source={StaticResource LoginControlPaddingTop}}"/>
<!-- Pass -->
<RowDefinition/>
<RowDefinition Height="{Binding Source={StaticResource LoginControlPaddingTop}}"/>
<!-- message -->
<RowDefinition/>
<!-- buttons -->
</Grid.RowDefinitions>
<TextBox
Grid.ColumnSpan="2"
autocomplete:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding KnownUsers}"
Margin="10"
Width="160"
Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
/>
<ComboBox ItemsSource="{Binding Workspaces}" Grid.Row="1" Grid.ColumnSpan="2" Margin="10" SelectedItem="{Binding SelectedWorkspace, Mode=TwoWay}" Width="160" MaxWidth="160" />
<TextBox
x:Name="_username"
autocomplete:AutoCompleteBehavior.AutoCompleteItemsSource="{Binding KnownUsers}"
HorizontalAlignment="Stretch"
Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
>
</TextBox>
<!--Password-->
<PasswordBox
x:Name="_password"
Grid.Row="2"
HorizontalAlignment="Stretch"
VerticalAlignment="Center"
Style="{DynamicResource PasswordBoxStyle1}"
PasswordChanged="_passwordChanged"
>
<PasswordBox.BorderBrush>
<LinearGradientBrush EndPoint="0,20" MappingMode="Absolute" StartPoint="0,0">
<GradientStop Color="#ABADB3" Offset="0.05"/>
<GradientStop Color="#E2E3EA" Offset="0.07"/>
<GradientStop Color="#E3E9EF" Offset="1"/>
</LinearGradientBrush>
</PasswordBox.BorderBrush>
</PasswordBox>
<TextBlock
x:Name="_pw_mark"
Grid.Row="2"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="4,0,0,0"
IsHitTestVisible="False"
Opacity="0.5"
Text="Password"
Visibility="{Binding IsFocused, Converter={StaticResource InverseBoolToVisibility}, ElementName=_password}"
/>
<PasswordBox Grid.Row="2" Margin="10" MinWidth="120" Grid.ColumnSpan="2" x:Name="_password" PasswordChanged="_passwordChanged" Style="{DynamicResource PasswordBoxStyle1}" Width="160">
<PasswordBox.BorderBrush>
<LinearGradientBrush EndPoint="0,20" MappingMode="Absolute" StartPoint="0,0">
<GradientStop Color="#ABADB3" Offset="0.05"/>
<GradientStop Color="#E2E3EA" Offset="0.07"/>
<GradientStop Color="#E3E9EF" Offset="1"/>
</LinearGradientBrush>
</PasswordBox.BorderBrush>
</PasswordBox>
<TextBlock Text="Password" Grid.Row="2" Grid.ColumnSpan="2" Margin="15,10,10,10" Opacity="0.5"
IsHitTestVisible="False" HorizontalAlignment="Left" x:Name="_pw_mark"
Visibility="{Binding IsFocused, Converter={StaticResource InverseBoolToVisibility}, ElementName=_password}" />
<CheckBox x:Name="_resume_workspace_checkbox" Grid.Row="4" HorizontalAlignment="Left" IsChecked="{Binding resume_workspace}" IsEnabled="True" ToolTip="{Binding SelectedWorkspace}">
Load last workspace
</CheckBox>
<Button Content="Cancel" x:Name="cancel_button" Grid.Row="4" Grid.Column="0" MinWidth="60" Margin="10" IsCancel="True" Command="{Binding CancelCommand}" />
<Button Content="Login" x:Name="login_button" Grid.Row="4" Grid.Column="1" MinWidth="60" Margin="10" IsDefault="True" Command="{Binding LoginCommand}" />
<!-- Background="{StaticResource CommonBackground}"-->
<Border Grid.Row="3" Grid.ColumnSpan="2" Visibility="{Binding WarningMessage, Converter={StaticResource NullToVisibilityConverter}}">
<TextBlock Text="{Binding WarningMessage}" HorizontalAlignment="Center" Foreground="Firebrick" FontWeight="Bold" TextWrapping="Wrap" Margin="5" MaxWidth="160" />
</Border>
</Grid>
<!-- Fatal error display -->
<StackPanel Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center" x:Name="_error_control" Margin="10" Opacity="0" Visibility="{Binding ErrorMessage, Converter={StaticResource NullToVisibilityConverter}}">
<TextBlock Text="The application is currently unavailable." FontWeight="Bold" TextWrapping="Wrap" Margin="0,0,0,10" />
<TextBlock TextWrapping="Wrap">
<Run>Please call BTS Support at </Run>
<Run FontWeight="Bold">(919) 913-0860</Run>
<Run>or email</Run>
<Hyperlink CommandParameter="mailto:support@bluetradingsystems.com" Command="{Binding EmailCommand}">support@bluetradingsystems.com</Hyperlink>
</TextBlock>
<TextBlock Text="Error Details:" Margin="0,10,0,0" />
<TextBlock Text="{Binding ErrorMessage}" TextWrapping="Wrap" Margin="5" />
</StackPanel>
<!-- Loading -->
<StackPanel Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" x:Name="_loading_control" IsHitTestVisible="False" Opacity="0">
<ui:BusySpinner Width="64" Height="64" />
<TextBlock Text="Loading..." HorizontalAlignment="Center" />
</StackPanel>
<!-- logo -->
<Image Grid.ColumnSpan="2" HorizontalAlignment="Left" Source="/Images/Icons/BTS.png" Width="220" Stretch="Uniform" SnapsToDevicePixels="True" RenderOptions.BitmapScalingMode="HighQuality" x:Name="_logo" Margin="32,0,0,0" />
<Button Grid.ColumnSpan="2" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="5" Command="{Binding CancelCommand}" Style="{StaticResource RoundCloseButton}" />
<TextBlock
x:Name="_reject_message"
Grid.Row="6"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{Binding WarningMessage}"
Foreground="Firebrick"
FontWeight="Bold"
TextWrapping="Wrap"
Visibility="Hidden"
/>
</Grid>
</Border>
</Window>
<!-- Fatal error display -->
<StackPanel
x:Name="_error_control"
Grid.Column="1"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Visibility="Hidden"
Opacity="0"
>
<TextBlock Text="The application is currently unavailable." FontWeight="Bold" TextWrapping="Wrap" Margin="0,0,0,10" />
<TextBlock TextWrapping="Wrap">
<Run>Please call BTS Support at </Run>
<Run FontWeight="Bold">(919) 913-0860</Run>
<Run>or email</Run>
<Hyperlink CommandParameter="mailto:support@bluetradingsystems.com" Command="{Binding EmailCommand}">support@bluetradingsystems.com</Hyperlink>
</TextBlock>
<TextBlock Text="Error Details:" Margin="0,10,0,0" />
<TextBlock Text="{Binding ErrorMessage}" TextWrapping="Wrap" Margin="5" />
</StackPanel>
<!-- Loading -->
<StackPanel
x:Name="_loading_control"
Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
IsHitTestVisible="False"
Opacity="0"
Visibility="Hidden"
>
<ui:BusySpinner Width="64" Height="64"/>
<TextBlock Text="Loading..." HorizontalAlignment="Center"/>
</StackPanel>
<!-- logo -->
<Image
x:Name="_logo"
RenderOptions.BitmapScalingMode="HighQuality"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="32,0,0,0"
Width="220"
Source="/Images/Icons/BTS.png"
Stretch="Uniform"
SnapsToDevicePixels="True"
/>
<Button Grid.Column="1" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="5" Command="{Binding CancelCommand}" Style="{StaticResource RoundCloseButton}"/>
<c:DialogSkirt x:Name="_dialog_skirt" Grid.Row="1" Grid.ColumnSpan="2" HorizontalAlignment="Stretch" VerticalAlignment="Bottom">
<c:DialogSkirt.RightItems>
<x:Array Type="{x:Type Button}">
<Button x:Name="_login_button" Width="60" Margin="10" IsDefault="True" IsHitTestVisible="True" Command="{Binding LoginCommand}">
Login
</Button>
<Button x:Name="_cancel_button" Width="60" Margin="10" IsCancel="True" IsHitTestVisible="True" Command="{Binding CancelCommand}">
Cancel
</Button>
</x:Array>
</c:DialogSkirt.RightItems>
</c:DialogSkirt>
</Grid>
</Border>
</Window>
@@ -1,15 +1,43 @@
using System;
using bts;
using mbts.ui.converters;
using mbts.ui.native;
using mbts.utils;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using mbts.ui.native;
using bts;
namespace mbts.ui.shell {
public partial class LoginView : Window
{
public partial class LoginView : Window {
public enum LoginStatus {
Initializing,
Ready,
Error,
Rejected,
LoggingIn
}
public static IValueConverter WorkspaceVisualStateConverter =>
ValueConverter.create<string, string>(workspace =>
!string.IsNullOrEmpty(workspace) && workspace != LoginViewModel.NEW_WORKSPACE_NAME ?
VisualStateNames.Workspace.Active :
VisualStateNames.Workspace.Inactive);
public static IValueConverter LoginStatusVisualStateConverter =>
ValueConverter.create<LoginStatus, string>(status => {
switch (status) {
case LoginStatus.Initializing: return VisualStateNames.LoginStatus.Initializing;
case LoginStatus.Ready: return VisualStateNames.LoginStatus.Ready;
case LoginStatus.LoggingIn: return VisualStateNames.LoginStatus.Loading;
case LoginStatus.Rejected: return VisualStateNames.LoginStatus.Rejected;
case LoginStatus.Error: return VisualStateNames.LoginStatus.Error;
default: throw ExceptionBuilder.Argument.unexpected_case(status, nameof(status));
}
});
public LoginView(LoginViewModel model) {
this.DataContext = model;
if (model is IRequestViewClose) {
@@ -65,6 +93,24 @@ namespace mbts.ui.shell {
return IntPtr.Zero;
}
}
public static class VisualStateNames {
public static class LoginStatus {
public const string GroupName = nameof(LoginStatus);
public static readonly string
Initializing = $"{GroupName}{nameof(Initializing)}",
Ready = $"{GroupName}{nameof(Ready)}",
Loading = $"{GroupName}{nameof(Loading)}",
Rejected = $"{GroupName}{nameof(Rejected)}",
Error = $"{GroupName}{nameof(Error)}";
}
}
public static class Workspace {
public const string GroupName = nameof(Workspace);
public static readonly string
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}";
}
}
}
}
@@ -2,16 +2,15 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using LoginStatus = mbts.ui.shell.LoginView.LoginStatus;
namespace mbts.ui.shell
{
namespace mbts.ui.shell {
public class LoginViewModel : ViewModelBase, IRequestViewClose
{
public const string NEW_WORKSPACE_NAME = "New workspace...";
private LoginModel _model;
private Dispatcher _dispatcher;
public LoginViewModel(LoginModel model, Dispatcher disp) {
@@ -42,7 +41,7 @@ namespace mbts.ui.shell
void _model_Ready() {
_dispatcher.BeginInvoke(() => {
if (!_model.HasFatalError) {
this.VisualState = "LoginState";
login_status = LoginStatus.Ready;
load_username();
if (!string.IsNullOrEmpty(_name))
KnownUsers.Add(_name);
@@ -50,16 +49,21 @@ namespace mbts.ui.shell
}
else {
ErrorMessage = _model.ErrorMessage;
VisualState = "ErrorState";
login_status = LoginStatus.Error;
}
});
}
private string _vstate = "Normal";
public string VisualState { get { return _vstate; } set { _vstate = value; RaisePropertyChanged("VisualState"); } }
LoginStatus _login_status;
public LoginStatus login_status { get => _login_status; private set => Set(ref _login_status, value); }
/// <see cref="KnownUsers"/> should only contain the user-name of the last login (if none exists, it should be empty).
public ObservableCollection<string> KnownUsers { get; } = new ObservableCollection<string>();
bool _resume_workspace = true;
public bool resume_workspace {
get => _resume_workspace;
set => Set(ref _resume_workspace, value);
}
private string _name;
public string Name {
get { return _name; }
@@ -82,7 +86,7 @@ namespace mbts.ui.shell
public string SelectedWorkspace { get; set; }
private async void update_workspaces(string name) {
Workspaces.Clear();
Workspaces.Add("New workspace...");
Workspaces.Add(NEW_WORKSPACE_NAME);
SelectedWorkspace = Workspaces.First();
if (_model.try_get_user(name, out var user)) {
var to_add = await _model.workspaces_for(user);
@@ -136,15 +140,13 @@ namespace mbts.ui.shell
private async void OnLogin(object arg) {
save_selection();
string selected_workspace = SelectedWorkspace;
if (selected_workspace == "New workspace...") {
selected_workspace = null;
}
string selected_workspace = _resume_workspace && SelectedWorkspace != NEW_WORKSPACE_NAME ?
SelectedWorkspace : null;
var result = await _model.do_login(Name, selected_workspace, Password);
if (result.success) { VisualState = "Loading"; }
if (result.success) { login_status = LoginStatus.LoggingIn; }
if (!result.success && !string.IsNullOrEmpty(result.reason)) {
WarningMessage = result.reason;
VisualState = "BadPassword";
login_status = LoginStatus.Rejected;
}
else if (!string.IsNullOrEmpty(result.reason)) {
// Login was successful but we have a message for the user
@@ -253,15 +253,18 @@ namespace mbts.ui {
sd.StateChanged += on_state_changed;
return Disposable.Create(() => sd.StateChanged -= on_state_changed);
void on_state_changed(string oldval, string newval) => transition(newval);
async void transition(string state) {
void transition(string state) {
version++;
if (target.IsLoaded)
StateManager.GoToState(target, state);
else {
int v = version;
await target.LoadedAsync();
if (v == version)
StateManager.GoToState(target, state);
target.Loaded += on_loaded;
void on_loaded(object sender, RoutedEventArgs e) {
target.Loaded -= on_loaded;
if (v == version)
StateManager.GoToState(target, state);
}
}
}
});
+1 -1
View File
@@ -169,7 +169,7 @@ namespace bts.tests
var second_short_order_def = create_order_def(second_sec.Id, Side.Sell, test_account, test_user);
uint short_no_limit_order_key;
await Task.Delay(10000);
Result<Response> short_no_limit_order_result = await OrderUtilities.send_order(_order_service, first_short_order_def, 50000, 7);
short_no_limit_order_key = short_no_limit_order_result.value.OrderKey;
+1 -1
View File
@@ -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/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.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/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/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/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/quickbus_cfg.proto;config/protos/span.proto;config/protos/spreader.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/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/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.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/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;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.cpp;metrics/metrics.cpp;metrics/system_metrics.cpp;orderman/actors/AsyncFactory.cpp;orderman/actors/ExecutionGateway.cpp;orderman/actors/FillStore.cpp;orderman/actors/MDSupplementarySource.cpp;orderman/actors/OrderStore.cpp;orderman/actors/SODPosition.cpp;orderman/actors/SecuritySrc.cpp;orderman/actors/ServiceBridge.cpp;orderman/actors/order_manager/OrderBuilder.cpp;orderman/actors/order_manager/OrderMLine 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/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.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/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/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/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/quickbus_cfg.proto;config/protos/span.proto;config/protos/spreader.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/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/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.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/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;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.cpp;metrics/metrics.cpp;metrics/system_metrics.cpp;orderman/actors/AsyncFactory.cpp;orderman/actors/ExecutionGateway.cpp;orderman/actors/FillStore.cpp;orderman/actors/MDSupplementarySource.cpp;orderman/actors/OrderStore.cpp;orderman/actors/SODPosition.cpp;orderman/actors/SecuritySrc.cpp;orderman/actors/ServiceBridge.cpp;orderman/actors/order_manager/OrderBuilder.cpp;orderman/actors/order_manager/OrderMLine truncated
+10 -1
View File
@@ -101,6 +101,7 @@ message CustomOrderDefinition
OCOOrderDefinition oco = 25;
PricerOrderDefinition pricer = 26;
CompositeOrderDefinition composite = 27;
SplitterOrderDefinition splitter = 29;
DynamicOrderDefinition dynamic = 1000;
}
@@ -204,6 +205,12 @@ message CompositeOrderDefinition {
uint32 algo_template_key = 1;
CustomOrderDefinition definition = 2;
}
message SplitterOrderDefinition {
uint32 max_order_qty = 1;
uint32 exposed_qty = 2;
// uint32 target_qty = 3;
CustomOrderDefinition child = 10;
}
message DynamicOrderDefinition {
string dynamic_order_type = 1;
map<string, DynamicOrderParam> order_params = 2;
@@ -253,9 +260,10 @@ message OrderState {
TriggerOrderState trigger = 21;
CoverOrderState cover = 22;
OffsetOrderState offset = 24;
QueueHolderState queue_holder = 30;
OCOOrderState oco = 25;
PricerOrderState pricer = 26;
QueueHolderState queue_holder = 30;
SplitterOrderState splitter = 31;
DynamicOrderState dynamic = 255; // do not use anything bigger than 255, or things will break
}
@@ -334,6 +342,7 @@ message OCOOrderState {}
message PricerOrderState {}
message DynamicOrderState {}
message QueueHolderState {}
message SplitterOrderState {}
enum OrderStatus {
+7
View File
@@ -9,6 +9,13 @@ MarketDataConfig {
}
}
PublisherOptions {
rule: "DeploymentType.type == 'dev'"
value {
disable_heartbeat: true
}
}
PlatformMap {
value {
glbx_platform: "PLATFORM_MDP3ONIXS"
+3 -3
View File
@@ -34,9 +34,9 @@ class IntPrice {
#endif
public:
IntPrice() : _mantissa(0), _exponent(127) {/*nan*/}
IntPrice(int64_t mantissa, int8_t exponent) : _mantissa(mantissa), _exponent(exponent) {}
IntPrice(const IntPrice& other) : _mantissa(other._mantissa), _exponent(other._exponent) {}
constexpr IntPrice() : _mantissa(0), _exponent(127) {/*nan*/}
constexpr IntPrice(int64_t mantissa, int8_t exponent) : _mantissa(mantissa), _exponent(exponent) {}
constexpr IntPrice(const IntPrice& other) : _mantissa(other._mantissa), _exponent(other._exponent) {}
bool operator==(const IntPrice& other) const {
if(_exponent == other._exponent) {
+1 -1
View File
@@ -77,7 +77,7 @@ public:
extern PriceSize NO_MARKET;
static_assert(sizeof(PriceSize) == 16, "PriceSize should be small");
template <uint8_t PRECISION>
template <uint8_t PRECISION=11>
PriceSize PriceSize_from_double(double price, Size size) {
if (size == 0 || os::is_nan(price)) return NO_MARKET;
return { IntPrice_from_double<PRECISION>(price), size };
+4
View File
@@ -13,6 +13,7 @@
#include <boost/filesystem.hpp>
#include <pugixml/pugixml.hpp>
#include <mutex>
using namespace std;
@@ -56,6 +57,8 @@ bool check_file_exists_with_instructions(const string& filename, const string& u
bool is_pow_two_or_0(uint32_t x) { return (x & (~x + 1)) == x; }
void await_cme_config() {
static std::mutex config_mutex;
std::lock_guard<std::mutex> guard(config_mutex);
std::string config_url;
std::string templates_url;
@@ -112,6 +115,7 @@ const std::vector<CMEChannel> get_configured_cme_channels() {
return parse_channels(symbols);
}
const vector<CMEChannel> parse_channels(const vector<UserSymbol>& symbols) {
await_cme_config();
vector<CMEChannel> result;
bool skip_options = config::get<PublisherOptions>().skip_options();
+42 -9
View File
@@ -11,6 +11,7 @@
#include "lib/md/protos/co2.pb.h"
#include "lib/md/SecurityIDRecorder.h"
#include "lib/config/protos/system.pb.h"
#include "lib/config/protos/MarketData.pb.h"
#include "lib/utils/bts_chrono.h"
#include <boost/filesystem.hpp>
@@ -173,7 +174,7 @@ void replay_file(const std::string& filename, IRelayWriter& writer, int32_t nagg
} while (loop);
}
void replay_url(const std::string& url, IRelayWriter& writer, int32_t naggle_ms) {
bool replay_url(const std::string& url, IRelayWriter& writer, int32_t naggle_ms, bool loop) {
// split up url parts
size_t http_len = BTS_ARRAYSIZE("http://") - 1;
auto after_host = url.find('/', http_len);
@@ -184,21 +185,53 @@ void replay_url(const std::string& url, IRelayWriter& writer, int32_t naggle_ms)
filename = os::sparkdata_path("data/replay/") + filename;
utils::download_file_if_newer(host, path, filename);
if (boost::filesystem::exists(filename)) {
replay_file(filename, writer, naggle_ms, true);
replay_file(filename, writer, naggle_ms, loop);
return true;
}
return false;
}
void replay_url_with_fallback(const std::string& url, IRelayWriter& writer, int32_t naggle_ms, bool loop) {
if (!replay_url(url, writer, naggle_ms, loop)) {
const auto fallback = config::get<ReplayOptions>().fallback();
if (boost::filesystem::exists(fallback)) {
replay_file(fallback, writer, naggle_ms, loop);
}
}
}
void replay_url_with_fallback(const std::string& url, IRelayWriter& writer, int32_t naggle_ms) {
// loops forever
replay_url(url, writer, naggle_ms);
// If it returns it means it failed to download or play cached
const auto fallback = config::get<ReplayOptions>().fallback();
if (boost::filesystem::exists(fallback)) {
replay_file(fallback, writer, naggle_ms);
struct SecurityExtractorDone : public std::bad_exception {};
struct SecurityExtractor : public IRelayWriter {
size_t _count;
std::function<void(const api::Security&)> _cb;
std::set<uint32_t> _keys;
SecurityExtractor(std::function<void(const api::Security&)>& cb, size_t count)
: _count(count), _cb(cb), _keys() { }
~SecurityExtractor() override {};
void write(const co2::MDReply& data, bool*) override {
for (auto const &ch : data.channels()) {
for (auto const &cr : ch.updates()) {
if (cr.has_security() && _keys.find(cr.security().id()) == _keys.end()) {
_keys.insert(cr.security().id());
_cb(cr.security());
}
}
}
if (_keys.size() >= _count) {
throw SecurityExtractorDone();
}
}
};
void get_securities_from_replay(std::function<void(const api::Security&)> cb) {
SecurityExtractor extractor(cb, 100);
auto url = config::get<ReplayOptions>().url();
try {
replay_url_with_fallback(url, extractor, 0, false);
} catch(const SecurityExtractorDone&) { }
}
shared_ptr<IRelayWriter> mkrelayproducer(bool shared);
/*this is the public one*/
+3 -2
View File
@@ -29,9 +29,10 @@ void print_recording(const std::string&);
void unprint_recording(const std::string& src, const std::string& dest);
void trace_recording(const std::string& file, security_key key);
void replay_recording(const std::string&, int32_t delay_ms, const std::string fallback="");
void replay_url(const std::string& url, IRelayWriter& writer, int32_t naggle_ms);
void replay_url_with_fallback(const std::string& url, IRelayWriter& writer, int32_t naggle_ms);
bool replay_url(const std::string& url, IRelayWriter& writer, int32_t naggle_ms, bool loop=true);
void replay_url_with_fallback(const std::string& url, IRelayWriter& writer, int32_t naggle_ms, bool loop=true);
void replay_file(const std::string& filename, IRelayWriter& writer, int32_t naggle_ms, bool loop=false);
void get_securities_from_replay(std::function<void(const api::Security&)>);
}}//namespace
@@ -153,6 +153,9 @@ class OrderStateUpdateEvent : public mercury::Event<OrderStateUpdateEvent> {
case api::orderman::OrderState::kDynamic:
result.mutable_dynamic();
break;
case api::orderman::OrderState::kSplitter:
result.mutable_splitter();
break;
case api::orderman::OrderState::CUSTOM_NOT_SET:
break;
}
+3 -1
View File
@@ -6,6 +6,7 @@
#include "lib/orderman/orderman_utils/orderman_common.h"
#include "lib/utils/bts_chrono.h"
#include "lib/md/protos/co2.pb.h"
#include "boost/container/small_vector.hpp"
namespace bts {
namespace orderman {
@@ -27,9 +28,10 @@ class TickerUpdateEvent : public mercury::Event<TickerUpdateEvent> {
co2::AggressorSide aggressor_side;
};
boost::container::small_vector<Trade,5> trades;
boost::container::small_vector<TickerUpdateEvent::Trade,5> trades;
TickerUpdateEvent(SecurityKey key) : _key(key), trades() {}
};
typedef boost::container::small_vector<TickerUpdateEvent::Trade,5> TradeVector;
}
}
@@ -19,6 +19,7 @@
#include "lib/orderman/orders/algo/algo_orders/TopAlgo.h"
#include "lib/orderman/orders/algo/algo_orders/IcebergAlgo.h"
#include "lib/orderman/orders/algo/algo_orders/LeanAlgo.h"
#include "lib/orderman/orders/algo/algo_orders/SplitterAlgo.h"
#include "lib/orderman/orders/algo/algo_orders/OffsetAlgo.h"
#include "lib/orderman/orders/book_algos/OCOOrder.h"
#include "lib/orderman/orders/book_algos/PricerOrder.h"
@@ -208,8 +209,12 @@ Order &OrderFactory::allocate(OrderKey k, OrderKey pk,
case CustomOrderDefinition::kComposite:
order_ptr.reset(new orderman::CompositeOrder());
break;
case CustomOrderDefinition::kSplitter:
order_ptr.reset(
new orderman::AlgoWrapperOrder(std::make_unique<splitter::SplitterAlgo>()));
break;
case CustomOrderDefinition::CUSTOM_NOT_SET:
bts_assert(false);
bts_assert_msg(false, "Cannot create order with unknown type");
break;
}
order_ptr->_key = k;
@@ -54,5 +54,127 @@ bool should_forward_attachment(
}
}
api::orderman::DynamicOrderParam dynamic_parameter(int32_t v) {
api::orderman::DynamicOrderParam res;
res.set_as_int32(v);
return res;
}
api::orderman::DynamicOrderParam dynamic_parameter(uint32_t v) {
api::orderman::DynamicOrderParam res;
res.set_as_uint32(v);
return res;
}
api::orderman::DynamicOrderParam dynamic_parameter(double v) {
api::orderman::DynamicOrderParam res;
res.set_as_double(v);
return res;
}
api::orderman::DynamicOrderParam dynamic_parameter(std::string v) {
api::orderman::DynamicOrderParam res;
res.set_as_string(v);
return res;
}
api::orderman::DynamicOrderParam dynamic_parameter(bool v) {
api::orderman::DynamicOrderParam res;
res.set_as_bool(v);
return res;
}
api::orderman::DynamicOrderParam dynamic_parameter(const api::orderman::CustomOrderDefinition& v) {
api::orderman::DynamicOrderParam res;
res.mutable_as_order_def()->CopyFrom(v);
return res;
}
api::orderman::DynamicOrderParam dynamic_parameter(const api::orderman::DynamicOrderArray& v) {
api::orderman::DynamicOrderParam res;
res.mutable_as_array()->CopyFrom(v);
return res;
}
api::orderman::DynamicOrderParam dynamic_parameter(const api::orderman::DynamicOrderStruct& v) {
api::orderman::DynamicOrderParam res;
res.mutable_as_struct()->CopyFrom(v);
return res;
}
api::orderman::DynamicOrderParam dynamic_parameter(const api::orderman::DynamicOrderEnumerated& v) {
api::orderman::DynamicOrderParam res;
res.mutable_as_enumerated()->CopyFrom(v);
return res;
}
api::orderman::DynamicOrderParam dynamic_array(const std::vector<api::orderman::DynamicOrderParam>& v) {
api::orderman::DynamicOrderArray a;
for (const auto& item : v) {
a.add_element()->CopyFrom(item);
}
return dynamic_parameter(a);
}
api::orderman::DynamicOrderParam dynamic_map(
const std::vector<std::tuple<std::string,api::orderman::DynamicOrderParam>>& v) {
DynamicOrderStruct res;
auto& map = *res.mutable_field();
for (const auto& tup : v) {
map[std::get<std::string>(tup)] = std::get<1>(tup);
}
return dynamic_parameter(res);
}
//
// Registration
api::orderman::DynamicOrderParamDescriptor param_int32(const std::string& name) {
api::orderman::DynamicOrderParamDescriptor doap;
doap.set_param_name(name);
doap.mutable_param_type()->set_primitive(api::orderman::DYNAMIC_ORDER_PRIMITIVE_INT);
return doap;
}
api::orderman::DynamicOrderParamDescriptor param_uint32(const std::string& name) {
api::orderman::DynamicOrderParamDescriptor doap;
doap.set_param_name(name);
doap.mutable_param_type()->set_primitive(api::orderman::DYNAMIC_ORDER_PRIMITIVE_UINT);
return doap;
}
api::orderman::DynamicOrderParamDescriptor param_double(const std::string& name) {
api::orderman::DynamicOrderParamDescriptor doap;
doap.set_param_name(name);
doap.mutable_param_type()->set_primitive(api::orderman::DYNAMIC_ORDER_PRIMITIVE_DOUBLE);
return doap;
}
api::orderman::DynamicOrderParamDescriptor param_string(const std::string& name) {
api::orderman::DynamicOrderParamDescriptor doap;
doap.set_param_name(name);
doap.mutable_param_type()->set_primitive(api::orderman::DYNAMIC_ORDER_PRIMITIVE_STRING);
return doap;
}
api::orderman::DynamicOrderParamDescriptor param_bool(const std::string& name) {
api::orderman::DynamicOrderParamDescriptor doap;
doap.set_param_name(name);
doap.mutable_param_type()->set_primitive(api::orderman::DYNAMIC_ORDER_PRIMITIVE_BOOL);
return doap;
}
api::orderman::DynamicOrderParamDescriptor param_order(const std::string& name) {
api::orderman::DynamicOrderParamDescriptor doap;
doap.set_param_name(name);
doap.mutable_param_type()->set_primitive(api::orderman::DYNAMIC_ORDER_PRIMITIVE_ORDER_DEF);
return doap;
}
api::orderman::DynamicOrderParamDescriptor param_array(const std::string& name, const DynamicOrderTypeDescriptor& entry) {
api::orderman::DynamicOrderParamDescriptor doap;
doap.set_param_name(name);
doap.mutable_param_type()->mutable_array()->mutable_element_type()->CopyFrom(entry);
return doap;
}
api::orderman::DynamicOrderParamDescriptor param_struct(const std::string& name, const std::vector<DynamicOrderParamDescriptor>& entries) {
api::orderman::DynamicOrderParamDescriptor doap;
doap.set_param_name(name);
api::orderman::DynamicOrderStructDescriptor& dstruct = *doap.mutable_param_type()->mutable_structure();
for (const auto& field : entries) {
*dstruct.add_field() = field;
}
return doap;
}
} // namespace orderman
} // namespace bts
@@ -1,4 +1,6 @@
#include "lib/api/services/OrderService.pb.h"
#include <optional>
#include <variant>
namespace bts {
namespace orderman {
@@ -30,5 +32,74 @@ inline bool is_parent_order(const bts::api::orderman::OrderRecord &ord) {
bool should_forward_attachment(const api::orderman::CustomOrderDefinition &def);
bool can_consume_attachment(api::orderman::CustomOrderDefinition::CustomCase) ;
api::orderman::DynamicOrderParam dynamic_parameter(int32_t);
api::orderman::DynamicOrderParam dynamic_parameter(uint32_t);
api::orderman::DynamicOrderParam dynamic_parameter(double);
api::orderman::DynamicOrderParam dynamic_parameter(std::string);
api::orderman::DynamicOrderParam dynamic_parameter(bool);
api::orderman::DynamicOrderParam dynamic_parameter(const api::orderman::CustomOrderDefinition&);
api::orderman::DynamicOrderParam dynamic_parameter(const api::orderman::DynamicOrderArray&);
api::orderman::DynamicOrderParam dynamic_parameter(const api::orderman::DynamicOrderStruct&);
api::orderman::DynamicOrderParam dynamic_parameter(const api::orderman::DynamicOrderEnumerated&);
api::orderman::DynamicOrderParam dynamic_array(const std::vector<api::orderman::DynamicOrderParam>&);
api::orderman::DynamicOrderParam dynamic_map( const std::vector<std::tuple<std::string,api::orderman::DynamicOrderParam>>&);
template <class T>
std::optional<T> get_if(const api::orderman::DynamicOrderParam&) { return nullptr; }
template <>
inline std::optional<int32_t> get_if(const api::orderman::DynamicOrderParam& p) {
return p.value_case() == api::orderman::DynamicOrderParam::kAsInt32 ? std::optional<int32_t>{p.as_int32()} : std::nullopt;
}
template <>
inline std::optional<uint32_t> get_if(const api::orderman::DynamicOrderParam& p) {
return p.value_case() == api::orderman::DynamicOrderParam::kAsUint32 ? std::optional<uint32_t>{p.as_uint32()} : std::nullopt;
}
template <>
inline std::optional<double> get_if(const api::orderman::DynamicOrderParam& p) {
return p.value_case() == api::orderman::DynamicOrderParam::kAsDouble ? std::optional<double>{p.as_double()} : std::nullopt;
}
template <>
inline std::optional<bool> get_if(const api::orderman::DynamicOrderParam& p) {
return p.value_case() == api::orderman::DynamicOrderParam::kAsBool ? std::optional<bool>{p.as_bool()} : std::nullopt;
}
template <>
inline std::optional<api::orderman::CustomOrderDefinition> get_if(const api::orderman::DynamicOrderParam& p) {
return p.value_case() == api::orderman::DynamicOrderParam::kAsOrderDef ? std::optional<api::orderman::CustomOrderDefinition>{p.as_order_def()} : std::nullopt;
}
template <>
inline std::optional<api::orderman::DynamicOrderArray> get_if(const api::orderman::DynamicOrderParam& p) {
return p.value_case() == api::orderman::DynamicOrderParam::kAsArray ? std::optional<api::orderman::DynamicOrderArray>{p.as_array()} : std::nullopt;
}
template <>
inline std::optional<api::orderman::DynamicOrderStruct> get_if(const api::orderman::DynamicOrderParam& p) {
return p.value_case() == api::orderman::DynamicOrderParam::kAsStruct ? std::optional<api::orderman::DynamicOrderStruct>{p.as_struct()} : std::nullopt;
}
template <>
inline std::optional<api::orderman::DynamicOrderEnumerated> get_if(const api::orderman::DynamicOrderParam& p) {
return p.value_case() == api::orderman::DynamicOrderParam::kAsEnumerated ? std::optional<api::orderman::DynamicOrderEnumerated>{p.as_enumerated()} : std::nullopt;
}
template <class T>
std::optional<T> get_if(const google::protobuf::Map<std::string,api::orderman::DynamicOrderParam>& map, const std::string& key) {
auto c = map.find(key);
if (c != map.end()) {
return get_if<T>(c->second);
}
return std::nullopt;
}
api::orderman::DynamicOrderParamDescriptor param_int32(const std::string& name);
api::orderman::DynamicOrderParamDescriptor param_uint32(const std::string& name);
api::orderman::DynamicOrderParamDescriptor param_double(const std::string& name);
api::orderman::DynamicOrderParamDescriptor param_string(const std::string& name);
api::orderman::DynamicOrderParamDescriptor param_bool(const std::string& name);
api::orderman::DynamicOrderParamDescriptor param_order(const std::string& name);
api::orderman::DynamicOrderParamDescriptor param_array(const std::string& name, const api::orderman::DynamicOrderTypeDescriptor&);
api::orderman::DynamicOrderParamDescriptor param_struct(const std::string& name, const std::vector<api::orderman::DynamicOrderParamDescriptor>&);
} // namespace orderman
} // namespace bts
@@ -55,6 +55,7 @@ struct AlgoWrapperOrder::PImpl {
OrderState const &state() const { return _state; }
Map<SecurityKey, OrderServices::BookSubID> book_subs;
Map<SecurityKey, OrderServices::TickerSubID> ticker_subs;
Map<OrderKey, ChildRecord> children;
bool has_timer_sub = false;
@@ -382,6 +383,24 @@ void AlgoWrapperOrder::unsubscribe_book(SecurityKey k) {
me->services->unsubscribe_from_book(it->second);
}
void AlgoWrapperOrder::subscribe_ticker(SecurityKey k) {
if (!is_working()) return;
bts_assert(me->ticker_subs.find(k) == me->ticker_subs.end());
me->ticker_subs[k] = me->services->subscribe_to_ticker(
k, [this,k](const auto& ev) {
ReportStateGuard _(*this);
me->algo->on_ticker(k, ev.trades);
});
}
void AlgoWrapperOrder::unsubscribe_ticker(SecurityKey k) {
if (!is_working()) return;
bts_assert(me->ticker_subs.find(k) != me->ticker_subs.end());
if (auto it = me->ticker_subs.find(k); it != me->ticker_subs.end())
me->services->unsubscribe_from_ticker(it->second);
}
void AlgoWrapperOrder::subscribe_child_change(OrderKey k) {
if (!is_working())
return;
@@ -47,6 +47,8 @@ class AlgoWrapperOrder : public Order,
void unsubscribe_child_change(OrderKey) override;
void subscribe_timer() override;
void unsubscribe_timer() override;
void subscribe_ticker(SecurityKey) override;
void unsubscribe_ticker(SecurityKey) override;
OrderKey launch_child(ChildTemplate &, Price, Quantity,
bool subscribe = true) override;
OrderKey launch_child(api::orderman::OrderDefinition const &, Price,
+5 -1
View File
@@ -1,6 +1,7 @@
#pragma once
#include "lib/orderman/orders/Order.h"
#include "lib/orderman/events/TickerUpdateEvent.h"
#include <memory>
namespace bts {
@@ -36,7 +37,10 @@ class IAlgoOrder {
// The book for the specified security has changed
virtual void on_book(SecurityKey, Book const &) {}
// A period timer has run out
// Trades stream for the specified security
virtual void on_ticker(SecurityKey, TradeVector const&) {};
// A periodic timer has fired
virtual void on_timer() {}
// --------------------------------------------------------------
+6 -3
View File
@@ -25,8 +25,7 @@ class IAlgoServices : public IBeforeLaunchAlgoServices {
// algo is shutting down any requests to create, update or cancel
// child orders will be ignored.
virtual bool is_shutting_down() const = 0;
// --------------------------------------------------------------
// Event Subscriptions
// --------------------------------------------------------------
@@ -45,6 +44,10 @@ class IAlgoServices : public IBeforeLaunchAlgoServices {
virtual void subscribe_timer() = 0;
virtual void unsubscribe_timer() = 0;
// Subscribe to trade ticker
virtual void subscribe_ticker(SecurityKey) = 0;
virtual void unsubscribe_ticker(SecurityKey) = 0;
// --------------------------------------------------------------
// Child management
// --------------------------------------------------------------
@@ -93,7 +96,7 @@ class IAlgoServices : public IBeforeLaunchAlgoServices {
// Set wheter this algo instance should be displayed in the Spark UI ladder
virtual void set_ladder_visibility(bool is_visible) = 0;
// Update this algos's filled quantity and last price
virtual void update_fill_state(Quantity total_fills, Price last_price) = 0;
};
@@ -1 +1,8 @@
#include "lib/orderman/orders/algo/IBeforeLaunchAlgoServices.h"
namespace bts {
namespace orderman {
TimeStamp IBeforeLaunchAlgoServices::get_time() const { return Timer::now(); }
} // namespace orderman
} // namespace bts
@@ -3,6 +3,7 @@
#include "lib/api/services/OrderService.pb.h"
#include "lib/domain_model/SecurityKey.h"
#include "lib/orderman/orderman_utils/orderman_common.h"
#include "lib/utils/bts_chrono.h"
namespace bts {
namespace orderman {
@@ -42,6 +43,8 @@ class IBeforeLaunchAlgoServices {
virtual ChildTemplate &
make_child_template(api::orderman::OrderDefinition const &child_def,
size_t reserve = 1) = 0;
virtual TimeStamp get_time() const;
};
} // namespace orderman
@@ -127,12 +127,12 @@ void CoverAlgo::on_covered_change(ChildState const &st) {
algo().order_key().value());
algo().set_ladder_visibility(false);
me->status = Status::WAITING_FOR_HEDGES;
check_terminate();
terminate_if_hedges_complete();
break;
case ChildStatus::CANCELED:
LOG(OrderMan, Info, "CoverAlgo {}. Child was canceled, terminating",
LOG(OrderMan, Info, "CoverAlgo {}. Child was unexpectadly canceled, terminating",
algo().order_key().value());
me->status = Status::DONE;
on_done();
algo().terminate_error("Unexpected child cancel");
break;
}
@@ -145,7 +145,7 @@ void CoverAlgo::on_covered_change(ChildState const &st) {
case ChildStatus::COMPLETED:
LOG(OrderMan, Info, "CoverAlgo {}. Shutdown complete",
algo().order_key().value());
me->status = Status::DONE;
on_done();
algo().cancel();
break;
}
@@ -170,7 +170,7 @@ void CoverAlgo::on_hedge_change(OrderKey k, ChildState const &st) {
if (me->cancel_on_external_hedge_cancel) {
LOG(OrderMan, Info, "CoverAlgo {}. Hedge was canceled, terminating",
algo().order_key().value());
me->status = Status::DONE;
on_done();
algo().terminate_error("Unexpected child cancel");
return;
} else
@@ -180,14 +180,14 @@ void CoverAlgo::on_hedge_change(OrderKey k, ChildState const &st) {
}
// Now if we are waiting for hedges to complete, bail
check_terminate();
terminate_if_hedges_complete();
}
void CoverAlgo::on_child_change(OrderKey k, ChildState const &st) {
if (k == me->child_key)
on_covered_change(st);
else
on_hedge_change(k,st);
on_hedge_change(k, st);
}
void CoverAlgo::do_update(api::orderman::Update const &update) {
@@ -244,7 +244,7 @@ void CoverAlgo::update_definition(
cover.cancel_on_external_hedge_cancel();
}
void CoverAlgo::check_terminate() {
void CoverAlgo::terminate_if_hedges_complete() {
LOG(OrderMan, Diag,
"CoverAlgo {} check_terminate. State: {} Hedge count: {}",
algo().order_key(), log::CharPtrWrapper{status_name(me->status)},
@@ -253,6 +253,7 @@ void CoverAlgo::check_terminate() {
if (me->status == Status::WAITING_FOR_HEDGES && me->hedges.empty()) {
LOG(OrderMan, Info, "CoverAlgo {}. Last hedge completed, terminating",
algo().order_key().value());
on_done();
algo().complete();
}
}
@@ -260,13 +261,10 @@ void CoverAlgo::check_terminate() {
IAlgoOrder::OnCancelResponse CoverAlgo::on_cancel() {
switch (me->status) {
case Status::WORKING: {
if (!me->cancel_hedges_on_cancel)
for (auto &k : me->hedges)
algo().detach_child(k);
algo().cancel_child(me->child_key);
LOG(OrderMan, Info,
"CoverAlgo {} received cancel. Canceling child and waiting for an ack",
"CoverAlgo {} received cancel. Canceling child and waiting for an "
"ack",
algo().order_key());
me->status = Status::CANCELING;
return IAlgoOrder::OnCancelResponse::IGNORE;
@@ -274,6 +272,7 @@ IAlgoOrder::OnCancelResponse CoverAlgo::on_cancel() {
case Status::CANCELING:
return IAlgoOrder::OnCancelResponse::IGNORE;
case Status::WAITING_FOR_HEDGES:
maybe_detach_hedges();
return IAlgoOrder::OnCancelResponse::HONOR;
case Status::DONE:
bts_assert(false);
@@ -284,6 +283,19 @@ IAlgoOrder::OnCancelResponse CoverAlgo::on_cancel() {
return IAlgoOrder::OnCancelResponse::HONOR;
}
void CoverAlgo::on_done()
{
me->status = Status::DONE;
maybe_detach_hedges();
}
void CoverAlgo::maybe_detach_hedges() {
if (!me->cancel_hedges_on_cancel)
for (auto &k : me->hedges)
algo().detach_child(k);
}
const char *CoverAlgo::status_name(Status st) {
switch (st) {
case Status::WORKING:
@@ -30,11 +30,13 @@ private:
api::orderman::CoverOrderDefinition const &);
void init_hedge_template(IBeforeLaunchAlgoServices &,
api::orderman::CustomOrderDefinition const &);
void check_terminate();
void terminate_if_hedges_complete();
void on_hedge_change(OrderKey hedge, ChildState const&) ;
void on_covered_change(ChildState const&);
const char *status_name(Status st);
void maybe_detach_hedges();
void on_done();
};
} // namespace orderman
@@ -0,0 +1,374 @@
#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>(&params)) {
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>(&params)) {
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) {
target = Quantity { std::get<1>(entry) };
if (std::get<0>(entry) > available) {
break;
}
}
}
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
@@ -0,0 +1,96 @@
#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
@@ -0,0 +1,118 @@
#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 "DormanAlgo.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_spark_plugin(bts::SparkServices &srv) {
DynamicOrderDescriptor join_desc;
join_desc.set_dynamic_order_type("Dorman");
*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>(); });
}
}}}
@@ -0,0 +1,268 @@
#include "SplitterAlgo.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/orderman_utils.h"
#include "lib/orderman/orders/algo/IAlgoServices.h"
#include <algorithm>
#include <tuple>
namespace bts {
namespace orderman {
namespace splitter {
using namespace api::orderman;
struct ChildOrderState {
OrderKey key;
ChildStatus status;
Price price;
Quantity quantity;
Quantity fills;
uint32_t min_qty() const { return fills.value(); }
};
struct SplitterAlgo::Impl {
IAlgoServices* algo = nullptr;
ChildTemplate* child_template = nullptr;
uint32_t clip = 0;
uint32_t exposed_qty = 0;
uint32_t target_qty = 0;
bool is_terminated = false;
Quantity total_fills = {};
Price last_fill_price = {};
std::vector<ChildOrderState> orders;
};
SplitterAlgo::SplitterAlgo() : me(new Impl()) { }
SplitterAlgo::~SplitterAlgo() {}
OrderOpResult SplitterAlgo::do_before_launch(IBeforeLaunchAlgoServices& ibl) {
// Validate and store parameters
auto& def = ibl.definition();
bts_assert(def.has_custom_def());
bts_assert(def.custom_def().has_splitter());
auto& splitter = def.custom_def().splitter();
me->clip = splitter.max_order_qty();
me->exposed_qty = splitter.exposed_qty();
if (me->clip == 0) {
return OrderOpResult{ORDER_ERROR_INVALID_ORDER_DEFINITON,
"max_order_qty must be greater than 0"};
}
update_child_template(ibl);
me->orders.reserve(me->exposed_qty / me->clip + 1);
if (ibl.is_attaching()) {
return OrderOpResult{ORDER_ERROR_OP_NOT_SUPPORTED,
"Splitter does not support attach."};
}
return {};
}
void SplitterAlgo::do_launch(IAlgoServices& ias) {
me->algo = &ias;
me->target_qty = ias.quantity().value();
// launches initial child orders
sync_orders();
}
void SplitterAlgo::do_launch_attached(IAlgoServices &, OrderKey, ChildState) {
// rejected in before_launch
bts_assert(false);
}
void SplitterAlgo::do_update(const api::orderman::Update& update) {
const CustomOrderDefinition* new_child_def = nullptr;
if (update.has_custom() && update.custom().has_splitter()) {
auto& splitter = update.custom().splitter();
if (splitter.max_order_qty() > 0) {
me->clip = splitter.max_order_qty();
}
me->exposed_qty = splitter.exposed_qty();
if (splitter.has_child()) {
update_child_template(algo());
new_child_def = &splitter.child();
}
}
me->target_qty = update.quantity();
sync_orders(new_child_def);
}
void SplitterAlgo::on_child_change(OrderKey key, ChildState const & state) {
for (auto& child : me->orders) {
if (child.key == key) {
// If we got an error or cancel that we did not expect we need to cancel
if (state.status == ChildStatus::CANCELED &&
child.status != ChildStatus::CANCELED) {
algo().cancel("Unexpected child cancel");
}
if (state.status != ChildStatus::WORKING) {
child.status = state.status;
}
auto delta = state.total_fills.value() - child.fills.value();
if (delta != 0) {
child.fills = state.total_fills;
me->total_fills = Quantity { me->total_fills.value() + delta };
me->last_fill_price = state.last_price;
algo().update_fill_state(me->total_fills, me->last_fill_price);
}
sync_orders();
break;
}
}
}
// TEST case:
// total = 300, clip = 100
// constraints: 50,50,50,50
void compute_desired_sizes(uint32_t total, uint32_t clip, const std::vector<MinMax>& constraints, std::vector<Quantity>* results) {
bts_assert(results);
results->clear();
uint32_t irreducible = 0;
for (const auto& mm : constraints) irreducible += mm.min;
// total > overfills ?
auto citer = constraints.begin();
while(total > 0) {
auto current = std::min(total, clip);
// fit to constraint
if (citer != constraints.end()) {
irreducible -= citer->min;
if (current > citer->max) current = citer->max;
if (current < citer->min) current = citer->min;
// I can't be higher than (total - irreducible)
if (current > (total - irreducible)) current = (total-irreducible);
citer++;
}
results->push_back(Quantity{current});
total -= current;
}
}
void get_constraints(const std::vector<ChildOrderState>& orders, std::vector<MinMax>* constraints) {
bts_assert(constraints);
for (const auto& order : orders) {
//Note: to maintain queue position set max to current quantity. This will cause more orders to be added to the end if size increases
constraints->push_back(MinMax {
order.fills.value(),
order.status == ChildStatus::WORKING ?
std::numeric_limits<uint32_t>::max() : order.fills.value()
});
}
}
bool SplitterAlgo::is_complete() const {
uint32_t fills = 0;
for (const auto& o : me->orders) { fills += o.fills.value(); }
return fills >= me->target_qty;
}
void SplitterAlgo::terminate() const {
algo().complete();
for (auto& o : me->orders) {
if (o.status == ChildStatus::WORKING) {
o.status = ChildStatus::CANCELED;
algo().cancel_child(o.key);
}
}
me->is_terminated = true;
}
void SplitterAlgo::update_child_template(IBeforeLaunchAlgoServices& ibl) {
// Create child template
auto child_def = ibl.definition();
bts_assert(child_def.has_custom_def());
bts_assert(child_def.custom_def().has_splitter());
auto& splitter = child_def.custom_def().splitter();
if (splitter.has_child()) {
// Copy child before mutabing child_def because splitter is a reference
auto child = splitter.child();
*child_def.mutable_custom_def() = child;
}
else {
child_def.mutable_custom_def()->mutable_limit();
}
me->child_template = &ibl.make_child_template(child_def);
}
void SplitterAlgo::sync_orders(const api::orderman::CustomOrderDefinition* new_child_def) {
if (me->is_terminated) return;
if (is_complete()) {
terminate();
return;
}
std::sort(me->orders.begin(), me->orders.end(), [](auto& a, auto b) { return b.min_qty() < a.min_qty(); });
std::vector<MinMax> constraints;
get_constraints(me->orders, &constraints);
std::vector<Quantity> desired;
compute_desired_sizes(me->exposed_qty, me->clip, constraints, &desired);
auto oiter = me->orders.begin();
// iterate to the current number of orders, don't consider orders that we're adding
auto order_count = me->orders.size();
auto price = algo().price();
for (const auto& qty : desired) {
if (order_count == 0) {
// Ran out of existing orders, time to add more
auto key = algo().launch_child(*me->child_template, price, qty);
// Assume the order begins successfully. Hopefully we get back some sort of NACK otherwise
me->orders.push_back({});
me->orders.back().key = key;
me->orders.back().price = price;
me->orders.back().quantity = Quantity { qty };
me->orders.back().status = ChildStatus::WORKING;
}
else {
// Check the current order's quantity and modify it to match desired qty
if (oiter->status == ChildStatus::WORKING) {
if (oiter->price != price ||
oiter->quantity != qty ||
new_child_def != nullptr) {
Update update;
update.set_quantity(qty.value());
oiter->quantity = qty;
update.set_price(price.value());
oiter->price = price;
if (new_child_def != nullptr) {
*update.mutable_custom() = *new_child_def;
}
algo().update_child(oiter->key, update);
}
}
oiter++;
order_count -= 1;
}
}
// cancel any orders past desired
if (desired.size() < me->orders.size()) {
for (size_t x = desired.size(); x < me->orders.size(); ++x) {
auto& order= me->orders[x];
if (order.status == ChildStatus::WORKING) {
order.status = ChildStatus::CANCELED;
algo().cancel_child(order.key);
}
}
}
}
IAlgoServices& SplitterAlgo::algo() const { bts_assert(me->algo); return *me->algo; }
}}} //namespace
@@ -0,0 +1,60 @@
#pragma once
#include "lib/orderman/orders/algo/IAlgoOrder.h"
namespace bts {
namespace orderman {
namespace splitter {
/*
SplitterAlgo
Parameters:
max_order_qty
-- Clip size. No single order can exceed this quantity.
exposed_qty
-- The total quantity we want visible on the exchange.
-- This will typically be higher than the quantity which helps capture fills in pro-rata algorithms
price, quantity
-- Common to all orders.
-- Splitter is filled when it reaches (or exceeds) quantity not exposed_qty
SplitterAlgo acts as a single order to its parent but actually divides the total exposure
by the clip size and working several orders at once.
- It completes when the quantity is matched or exceeded.
- It tries to maximize the size of the orders and it may sacrifice queue position to do that.
- It reacts to fills and parameter changes and adjusts it's children appropriately.
- See splitter_tests.cpp for examples
- Future work: By constraining maximum size we can force this algorithm to maintain queue position.
*/
class SplitterAlgo : public IAlgoOrder
{
struct Impl;
std::unique_ptr<Impl> me;
public:
SplitterAlgo();
~SplitterAlgo();
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;
private:
IAlgoServices& algo() const;
void sync_orders(const api::orderman::CustomOrderDefinition* new_child_def = nullptr);
bool is_complete() const;
void terminate() const;
void update_child_template(IBeforeLaunchAlgoServices&);
};
// exposed for unit testing purposes.
struct MinMax {uint32_t min, max;};
void compute_desired_sizes(uint32_t , uint32_t ,
const std::vector<MinMax>& , std::vector<Quantity>* );
}}} //namespace
@@ -0,0 +1,441 @@
#include "AlgoTestDriver.h"
#include "lib/md/relay/RelayRecorder.h"
#include "catch/catch.hpp"
#include "lib/api/services/OrderService.pb.h"
#include "lib/orderman/orderman_utils/Book.h"
#include "lib/logging/logging.h"
#include <optional>
#include <queue>
namespace bts {
namespace orderman {
namespace test {
using namespace api::orderman;
constexpr bool has_flag(ATDFlags prop, ATDFlags flag) {
return ((uint32_t)prop & (uint32_t)flag) == (uint32_t)flag;
}
const std::map<SecurityKey, api::Security>& get_some_securities() {
static std::map<SecurityKey, api::Security> results;
if (results.empty()) {
md::get_securities_from_replay([&](const api::Security& s) {
results.insert(std::make_pair(SecurityKey(s.id()), s));
});
}
return results;
}
struct RecursionCounter {
size_t depth = 0;
virtual void flush() = 0;
virtual ~RecursionCounter() {}
};
struct RecursionGuard {
RecursionGuard(RecursionCounter& c) : counter(c) {
counter.depth += 1;
REQUIRE(counter.depth < 100);
}
~RecursionGuard() {
counter.depth -= 1;
if (counter.depth == 0) { counter.flush(); }
}
private:
RecursionCounter& counter;
};
struct AlgoTestDriverBase::Impl : public RecursionCounter {
IAlgoOrder& algo;
api::orderman::OrderDefinition definition;
Price price;
Quantity size;
ATDFlags flags;
TimeStamp now;
api::Security security;
OrderKey order_key, parent_key;
std::tuple<Quantity, Price> fill_state;
AlgoState state;
std::vector<ChildOrder> orders;
std::vector<ChildOrder> detached_orders;
std::map<SecurityKey, Book> books;
std::map<SecurityKey, bool> book_subs;
std::map<SecurityKey, bool> ticker_subs;
bool sub_timer = false;
// Callbacks
std::vector<std::function<void(OrderKey)>> on_child_launching;
std::vector<std::function<void(const ChildOrder&)>> on_child_changing;
std::vector<std::function<void(const ChildOrder&, const ChildOrder&)>> on_child_changed;
bool allow_overfill = false;
Impl(IAlgoOrder& o) : algo(o) {}
OrderKey next_order() {
_next_order.value() += 1;
return _next_order;
}
RecursionGuard recusion_guard() { return {*this}; }
void flush() override;
bool flushing = false;
// child changes must be asyncronous
std::vector<std::tuple<OrderKey, ChildState>> deferred;
void defer_child_change(OrderKey k, ChildState cs) { deferred.push_back(std::make_tuple(k,cs)); }
private:
OrderKey _next_order = OrderKey(99);
};
void AlgoTestDriverBase::Impl::flush() {
if(flushing) return;
flushing = true;
for (const auto& update : deferred) {
algo.on_child_change(std::get<OrderKey>(update), std::get<ChildState>(update));
}
deferred.clear();
flushing = false;
}
AlgoTestDriverBase::AlgoTestDriverBase(
IAlgoOrder& algo,
const api::orderman::OrderDefinition& def,
Price price, Quantity size,
ATDFlags flags)
: me(new Impl(algo)) {
me->definition = def;
me->price = price;
me->size = size;
me->flags = flags;
me->now = Timer::now();
me->state = AlgoState::CREATED;
auto securities = get_some_securities();
REQUIRE(securities.size() > 0);
me->security = securities.begin()->second;
me->order_key = me->next_order();
if (has_flag(flags, ATDFlags::HAS_PARENT)) {
me->parent_key = me->next_order();
}
}
AlgoTestDriverBase::~AlgoTestDriverBase() {}
OrderOpResult AlgoTestDriverBase::before_launch() {
REQUIRE(me->state == AlgoState::CREATED);
me->state = AlgoState::READY;
return me->algo.do_before_launch(*this);
}
void AlgoTestDriverBase::launch() {
REQUIRE(me->state == AlgoState::READY);
me->algo.do_launch(*this);
me->state = AlgoState::RUNNING;
}
void AlgoTestDriverBase::launch_attached(OrderKey key, ChildState state) {
REQUIRE(me->state == AlgoState::READY);
me->algo.do_launch_attached(*this, key, state);
me->state = AlgoState::RUNNING;
}
void AlgoTestDriverBase::do_update(const api::orderman::Update& update) {
auto guard = me->recusion_guard();
REQUIRE(me->state == AlgoState::RUNNING);
me->algo.do_update(update);
}
void AlgoTestDriverBase::update_book(const Book& book) {
auto key = book.security_key();
me->books[key] = book;
auto iter = me->book_subs.find(key);
if (iter != me->book_subs.end()) {
me->algo.on_book(key, book);
}
}
void AlgoTestDriverBase::update_ticker(SecurityKey key, const TradeVector& data) {
auto iter = me->ticker_subs.find(key);
if (iter != me->ticker_subs.end() && iter->second) {
me->algo.on_ticker(key, data);
}
}
void AlgoTestDriverBase::advance_time(Duration d, uint32_t steps) {
Duration dprime = d / steps;
for (uint32_t s = 0; s < steps; ++s) {
me->now += dprime;
if (me->sub_timer) {
me->algo.on_timer();
}
}
}
IAlgoOrder::OnCancelResponse AlgoTestDriverBase::cancel() {
auto r = me->algo.on_cancel();
if (r == IAlgoOrder::OnCancelResponse::HONOR) {
me->state = AlgoState::CANCELED;
for (auto& o : me->orders) {
o.cstate.status = ChildStatus::CANCELED;
}
}
return r;
}
const std::vector<ChildOrder>& AlgoTestDriverBase::child_orders() const {
return me->orders;
}
const std::vector<ChildOrder>& AlgoTestDriverBase::detached_orders() const {
return me->detached_orders;
}
AlgoState AlgoTestDriverBase::state() const {
return me->state;
}
void AlgoTestDriverBase::fill(OrderKey k, Price price, Quantity qty) {
auto guard = me->recusion_guard();
for (auto& child : me->orders) {
if (child.key == k) {
if (!me->allow_overfill) REQUIRE(child.cstate.quantity.value() - child.cstate.total_fills.value() >= qty.value());
for (const auto& cb : me->on_child_changing) cb(child);
auto old = child;
auto total_price = child.cstate.avg_price.value() * child.cstate.total_fills.value();
total_price += price.value() * qty.value();
child.cstate.last_fills = qty;
child.cstate.total_fills.value() += qty.value();
child.cstate.last_price = price;
child.cstate.avg_price = Price { total_price / child.cstate.total_fills.value() };
if (child.cstate.quantity.value() <= child.cstate.total_fills.value()) {
child.cstate.status = ChildStatus::COMPLETED;
}
for (const auto& cb : me->on_child_changed) cb(old, child);
// No defer because this is called from outside
if (child.subscribed) me->algo.on_child_change(k, child.cstate);
break;
}
}
}
const ChildOrder* largest_order(const std::vector<ChildOrder>& orders) {
uint32_t sz = 0;
const ChildOrder* result = nullptr;
for (const auto& order : orders) {
auto available =
order.cstate.quantity.value() - order.cstate.total_fills.value();
if (order.cstate.status == ChildStatus::WORKING &&
available > sz) {
sz = available;
result = &order;
}
}
return result;
}
void AlgoTestDriverBase::fill(Price p, Quantity q) {
auto to_fill = q.value();
while(to_fill > 0) {
auto order = largest_order(this->child_orders());
REQUIRE(order);
auto available = (order->cstate.quantity.value() - order->cstate.total_fills.value());
if (available >= to_fill) {
this->fill(order->key, p, Quantity {to_fill});
return;
}
else {
this->fill(order->key, p, Quantity {available});
to_fill -= available;
}
}
}
void AlgoTestDriverBase::on_child_launching(std::function<void(OrderKey)>&& cb) {
me->on_child_launching.push_back(cb);
}
void AlgoTestDriverBase::on_child_changing(std::function<void(const ChildOrder&)>&& cb) {
me->on_child_changing.push_back(cb);
}
void AlgoTestDriverBase::on_child_changed(std::function<void(const ChildOrder&, const ChildOrder&)>&& cb) {
me->on_child_changed.push_back(cb);
}
bool AlgoTestDriverBase::allow_overfill() const { return me->allow_overfill; }
void AlgoTestDriverBase::allow_overfill(bool value) { me->allow_overfill = value; }
//
// Utility
ChildOrder mkchild(OrderKey key, Price price, Quantity qty, bool sub) {
ChildOrder result = {};
result.key = key;
result.cstate.price = price;
result.cstate.quantity = qty;
result.subscribed = sub;
return result;
}
//
// IBeforeLaunch
const api::orderman::OrderDefinition& AlgoTestDriverBase::definition() const { return me->definition; }
const api::Security& AlgoTestDriverBase::security() const { return me->security; }
OrderKey AlgoTestDriverBase::order_key() const { return me->order_key; }
OrderKey AlgoTestDriverBase::parent_order_key() const { return me->parent_key; }
const api::Security* AlgoTestDriverBase::lookup_security(SecurityKey key) const {
auto s = get_some_securities();
auto iter = s.find(key);
if (iter != s.end()) {
return &iter->second;
}
return nullptr;
}
bool AlgoTestDriverBase::is_attaching() const { return has_flag(me->flags, ATDFlags::IS_ATTACHING); }
ChildTemplate& AlgoTestDriverBase::make_child_template(const api::orderman::OrderDefinition& def, size_t) {
REQUIRE(def.custom_def().custom_case() != CustomOrderDefinition::CUSTOM_NOT_SET);
ChildTemplate* t = nullptr;
return *t;
}
TimeStamp AlgoTestDriverBase::get_time() const { return me->now; }
//
// IAlgoServices
Price AlgoTestDriverBase::price() const { return me->price; }
Quantity AlgoTestDriverBase::quantity() const { return me->size; }
Quantity AlgoTestDriverBase::total_fills() const {
return std::get<Quantity>(me->fill_state);
}
bool AlgoTestDriverBase::is_shutting_down() const {
return false;
}
void AlgoTestDriverBase::subscribe_book(SecurityKey key){
me->book_subs[key] = true;
auto iter = me->books.find(key);
if (iter != me->books.end()) {
me->algo.on_book(key, iter->second);
}
}
void AlgoTestDriverBase::unsubscribe_book(SecurityKey key) {
me->book_subs.erase(key);
}
void AlgoTestDriverBase::subscribe_ticker(SecurityKey key) {
me->ticker_subs[key] = true;
}
void AlgoTestDriverBase::unsubscribe_ticker(SecurityKey key) {
me->ticker_subs.erase(key);
}
void AlgoTestDriverBase::subscribe_child_change(OrderKey k) {
for (auto& child : me->orders) {
if (child.key == k) {
child.subscribed = true;
}
}
}
void AlgoTestDriverBase::unsubscribe_child_change(OrderKey k) {
for (auto& child : me->orders) {
if (child.key == k) {
child.subscribed = false;
}
}
}
void AlgoTestDriverBase::subscribe_timer() { me->sub_timer = true; }
void AlgoTestDriverBase::unsubscribe_timer() { me->sub_timer = false; }
OrderKey AlgoTestDriverBase::launch_child(ChildTemplate&, Price price, Quantity qty, bool sub) {
OrderKey key = me->next_order();
me->orders.push_back(
mkchild(key, price, qty, sub));
for(const auto& cb : me->on_child_launching) cb(key);
return key;
}
OrderKey AlgoTestDriverBase::launch_child(api::orderman::OrderDefinition const & def, Price price, Quantity qty, bool sub) {
OrderKey key = me->next_order();
me->orders.push_back(
mkchild(key, price, qty, sub));
me->orders.back().def = {def};
for(const auto& cb : me->on_child_launching) cb(key);
return key;
}
void AlgoTestDriverBase::update_child(OrderKey key, api::orderman::Update const & update) {
auto guard = me->recusion_guard();
for (auto& child : me->orders) {
if (child.key == key) {
// Note: Algo may have sent this update before it was notified that the child was filled/canceled
// REQUIRE(child.cstate.status == ChildStatus::WORKING);
for (const auto& cb : me->on_child_changing) cb(child);
auto old = child;
if (update.price() != 0) {
child.cstate.price = Price(update.price());
}
if (update.quantity() != 0) {
child.cstate.quantity = Quantity(update.quantity());
}
if (child.cstate.quantity.value() <= child.cstate.total_fills.value()) {
child.cstate.status = ChildStatus::COMPLETED;
}
if (update.has_custom()) {
if (!child.def) {
child.def = {api::orderman::OrderDefinition()};
}
*child.def.value().mutable_custom_def() = update.custom();
}
for (const auto& cb : me->on_child_changed) cb(old, child);
if (child.subscribed) {
me->defer_child_change(key, child.cstate);
}
}
}
}
void AlgoTestDriverBase::cancel_child(OrderKey key) {
auto guard = me->recusion_guard();
for (auto& child : me->orders) {
if (child.key == key) {
REQUIRE(child.cstate.status != ChildStatus::CANCELED);
for (const auto& cb : me->on_child_changing) cb(child);
auto before = child;
child.cstate.status = ChildStatus::CANCELED;
for (const auto& cb : me->on_child_changed) cb(before, child);
if(child.subscribed) {
me->defer_child_change(key, child.cstate);
}
break;
}
}
}
void AlgoTestDriverBase::detach_child(OrderKey key) {
for (auto iter = me->orders.begin(); iter != me->orders.end(); ++iter) {
auto order = *iter;
if (order.key == key) {
me->detached_orders.push_back(order);
me->orders.erase(iter);
break;
}
}
}
void AlgoTestDriverBase::detach_all_children() {
for (const auto& order : me->orders) me->detached_orders.push_back(order);
me->orders.clear();
}
void AlgoTestDriverBase::cancel(std::string const &) {
cancel();
}
void AlgoTestDriverBase::terminate_error(std::string const &) {
me->state = AlgoState::TERMINATED;
}
void AlgoTestDriverBase::complete() {
me->state = AlgoState::COMPLETED;
}
void AlgoTestDriverBase::set_ladder_visibility(bool) { /* whatever, ok */ }
void AlgoTestDriverBase::update_fill_state(Quantity q, Price p) { me->fill_state = { q, p }; }
}}}//namespace
@@ -0,0 +1,151 @@
#pragma once
#include "lib/orderman/orders/algo/IAlgoOrder.h"
#include "lib/orderman/orders/algo/IAlgoServices.h"
#include "lib/orderman/events/TickerUpdateEvent.h"
#include "lib/md/IntPrice.h"
#include <memory>
#include <vector>
#include <string>
namespace bts {
namespace orderman {
namespace test {
const std::map<SecurityKey, api::Security>& get_some_securities();
enum class ATDFlags {
NONE = 0,
IS_ATTACHING = 1,
HAS_PARENT = 2,
};
enum class AlgoState {
CREATED,
// before_Launch() ->
READY,
// launch() ->
RUNNING,
CANCELED,
TERMINATED,
COMPLETED
};
struct ChildOrder {
OrderKey key;
bool subscribed;
ChildState cstate;
std::optional<api::orderman::OrderDefinition> def;
uint32_t active_qty() const {
return cstate.status == ChildStatus::WORKING ?
cstate.quantity.value() - cstate.total_fills.value() : 0;
}
};
class AlgoTestDriverBase : private IAlgoServices {
struct Impl;
std::unique_ptr<Impl> me;
public:
AlgoTestDriverBase(
IAlgoOrder& algo,
const api::orderman::OrderDefinition& def,
Price price, Quantity size,
ATDFlags flags=ATDFlags::NONE);
~AlgoTestDriverBase();
//
// Expose some things from IAlgoServices
const api::Security& security() const override;
Price price() const override;
Quantity quantity() const override;
Quantity total_fills() const override;
bool is_shutting_down() const override;
//
// Change state
OrderOpResult before_launch();
void launch();
void launch_attached(OrderKey, ChildState);
void do_update(const api::orderman::Update&);
void update_book(const Book&);
void update_ticker(SecurityKey, const TradeVector&);
void advance_time(Duration, uint32_t steps=1);
IAlgoOrder::OnCancelResponse cancel();
//
// Inspection methods
const std::vector<ChildOrder>& child_orders() const;
const std::vector<ChildOrder>& detached_orders() const;
AlgoState state() const;
// Fills for this specific order
void fill(OrderKey, Price, Quantity);
// Fill this quantity, start with the largest child order
void fill(Price, Quantity);
void on_child_launching(std::function<void(OrderKey)>&&);
void on_child_changing(std::function<void(const ChildOrder&)>&&);
void on_child_changed(std::function<void(const ChildOrder&, const ChildOrder&)>&&);
//
// Tweak internal REQUIRE
bool allow_overfill() const;
void allow_overfill(bool=true);
private:
//
// IBeforeLaunchAlgoServices
const api::orderman::OrderDefinition& definition() const override;
// const api::Security& security() const override;
OrderKey order_key() const override;
OrderKey parent_order_key() const override;
const api::Security* lookup_security(SecurityKey) const override;
bool is_attaching() const override;
ChildTemplate& make_child_template(const api::orderman::OrderDefinition& child_def, size_t reserve = 1) override;
TimeStamp get_time() const override;
//
// IAlgoServices
void subscribe_book(SecurityKey)override;
void unsubscribe_book(SecurityKey) override;
void subscribe_child_change(OrderKey) override;
void unsubscribe_child_change(OrderKey) override;
void subscribe_timer() override;
void unsubscribe_timer() override;
void subscribe_ticker(SecurityKey) override;
void unsubscribe_ticker(SecurityKey) override;
OrderKey launch_child(ChildTemplate &, Price, Quantity, bool) override;
OrderKey launch_child(api::orderman::OrderDefinition const &, Price,
Quantity, bool) override;
void update_child(OrderKey , api::orderman::Update const &) override;
void cancel_child(OrderKey) override;
void detach_child(OrderKey) override;
void detach_all_children() override;
void cancel(std::string const &) override;
void terminate_error(std::string const &) override;
void complete() override;
void set_ladder_visibility(bool) override;
void update_fill_state(Quantity , Price) override;
};
template <class Algo>
struct AlgoTestDriver : public AlgoTestDriverBase
{
// Avoids mutual ownership problem
Algo _algo;
AlgoTestDriver(
const api::orderman::OrderDefinition& def,
const md::IntPrice& price, Quantity size,
ATDFlags flags=ATDFlags::NONE)
: AlgoTestDriverBase(_algo, def, Price {price.price()}, size, flags), _algo()
{ }
const Algo& algo() const { return _algo; }
};
}}}//namespace
@@ -0,0 +1,743 @@
#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, 250 },
{ 200, 250 },
{ 250, 250 },
{ 500, 400 },
{ 999, 400 },
{ 2500, 750 },
{ 9999, 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(400));
// Check that orders were created
REQUIRE(400 == 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(250));
REQUIRE(
250 == 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(400));
// Check that orders were created
REQUIRE(
400 == 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 400
REQUIRE(
400 == count_exposed(state.child_orders()));
// Still 400 after the timer ticks but not enough time has passed
state.advance_time(std::chrono::seconds());
REQUIRE(
400 == count_exposed(state.child_orders()));
state.advance_time(std::chrono::seconds(input.steps.trail_seconds));
REQUIRE(
600 == 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(450));
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(650));
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(650));
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(650));
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, 350 };
state.update_book(book);
REQUIRE(state.before_launch().ok());
state.launch();
REQUIRE(state.algo().exposed_qty() == Quantity(250));
REQUIRE(state.child_orders().size() == 1);
state.advance_time(std::chrono::seconds(1));
// Update book sets future quantity = 450
book.bid()[0] = { some_price, 999 };
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(250));
book.bid()[0] = { some_price, 425 };
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(250));
}
}}}//namespace
@@ -0,0 +1,727 @@
#include "../SplitterAlgo.h"
#include "AlgoTestDriver.h"
#include "catch/catch.hpp"
#include "lib/orderman/orderman_utils/Book.h"
#include "lib/utils/bts_chrono.h"
#include <ctime>
#include <optional>
#include <tuple>
#include <variant>
#include <set>
using namespace std;
using namespace bts::orderman::splitter;
using namespace bts::api::orderman;
namespace bts {
namespace orderman {
namespace test {
/*
- max/exposed, assert correct # of orders on the market
- completes on target_qty reached
- completes on target_qty exceeded
- send fills, check order state
- send fills, then change target_qty
*/
constexpr auto some_price = md::IntPrice{128000, -3};
using ExpectedCount = utils::ValueWrapper<struct ExpectedCountTag, uint32_t>;
struct SimpleCase {
ExpectedCount expected_orders;
Quantity target;
SplitterOrderDefinition sod;
};
SimpleCase mkSimple(ExpectedCount expected, uint32_t max_size, uint32_t exposed,
uint32_t target) {
SimpleCase result;
result.expected_orders = expected;
result.target = Quantity{target};
result.sod.set_max_order_qty(max_size);
result.sod.set_exposed_qty(exposed);
return result;
}
TEST_CASE("compute_desired_sizes fuzzing", "[algo][splitter]") {
srand((unsigned)time(0));
auto start = Timer::now();
while (sec_diff(Timer::now(),start) < 5) {
uint32_t total = rand() % 100 + 1;
uint32_t clip = rand() % 4 + 1;
std::vector<MinMax> constraints(rand() % 10);
std::vector<Quantity> result;
uint32_t all_fills = 0;
for (auto &mm : constraints) {
uint32_t order_working = rand() % 2;
uint32_t fills = rand() % 2 * clip;
all_fills += fills;
mm = {fills, order_working ? fills + rand() % clip + 1 : fills};
}
if (all_fills < total) {
compute_desired_sizes(total, clip, constraints, &result);
uint32_t exposed_qty = 0;
for (auto q : result)
exposed_qty += q.value();
bool clip_size_honored = true;
for (auto q : result)
clip_size_honored = clip_size_honored && (q.value() <= clip);
if (exposed_qty != total || !clip_size_honored) {
std::cout << "total: " << total << "\n"
<< "clip: " << clip << "\n{ ";
for (auto mm : constraints)
std::cout << "{" << mm.min << "," << mm.max << "},";
std::cout << " }\n";
}
REQUIRE(clip_size_honored);
REQUIRE(exposed_qty == total);
}
}
}
TEST_CASE("initial orders", "[algo][splitter]") {
std::vector<SimpleCase> cases;
cases.push_back(mkSimple(ExpectedCount{10}, 10, 100, 50));
cases.push_back(mkSimple(ExpectedCount{11}, 10, 105, 50));
cases.push_back(mkSimple(ExpectedCount{5}, 10, 50, 50));
cases.push_back(mkSimple(ExpectedCount{5}, 10, 50, 150));
for (const auto &tcase : cases) {
auto expected = tcase.expected_orders.value();
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
*def.mutable_custom_def()->mutable_splitter() = tcase.sod;
AlgoTestDriver<SplitterAlgo> state(def, some_price, tcase.target);
REQUIRE(state.before_launch().ok());
state.launch();
REQUIRE(state.child_orders().size() == expected);
REQUIRE(state.state() == AlgoState::RUNNING);
}
}
TEST_CASE("completes on target", "[algo][splitter]") {
std::vector<SimpleCase> cases;
cases.push_back(mkSimple(ExpectedCount{3}, 30, 90, 50));
cases.push_back(mkSimple(ExpectedCount{10}, 10, 100, 50));
cases.push_back(mkSimple(ExpectedCount{11}, 10, 105, 50));
cases.push_back(mkSimple(ExpectedCount{5}, 10, 50, 50));
cases.push_back(mkSimple(ExpectedCount{5}, 10, 50, 150));
cases.push_back(mkSimple(ExpectedCount{4}, 13, 50, 150));
cases.push_back(mkSimple(ExpectedCount{12}, 13, 150, 50));
for (const auto &tcase : cases) {
auto expected = tcase.expected_orders.value();
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
*def.mutable_custom_def()->mutable_splitter() = tcase.sod;
AlgoTestDriver<SplitterAlgo> state(def, some_price, tcase.target);
REQUIRE(state.before_launch().ok());
state.launch();
REQUIRE(state.child_orders().size() == expected);
REQUIRE(state.state() == AlgoState::RUNNING);
SECTION("Fill completely") {
auto orders = state.child_orders();
// Fill the order
size_t filled = 0;
size_t iterations = 0;
while (state.state() == AlgoState::RUNNING) {
// loop to allow more orders to be added
++iterations;
REQUIRE(iterations < 999);
for (const auto &order : orders) {
state.fill(order.key, Price(some_price.price()),
order.cstate.quantity);
filled += order.cstate.quantity.value();
REQUIRE(filled == state.total_fills().value());
if (filled >= tcase.target.value()) {
REQUIRE(state.state() == AlgoState::COMPLETED);
break;
} else {
REQUIRE(state.state() == AlgoState::RUNNING);
}
}
}
}
SECTION("fill one by one") {
const auto &orders = state.child_orders();
// Fill 1 per iteration.
// Algo should add more orders if not enough are visible initially
size_t filled = 0;
size_t iterations = 0;
while (state.state() == AlgoState::RUNNING) {
++iterations;
REQUIRE(iterations < 999); // not making progress
for (const auto &order : orders) {
if (order.cstate.status == ChildStatus::WORKING) {
auto price = Price{some_price.price()};
state.fill(order.key, price, Quantity{1});
filled += 1;
REQUIRE(filled == state.total_fills().value());
// Fills should never cause new orders to get added
REQUIRE(state.child_orders().size() == expected);
if (filled >= tcase.target.value()) {
REQUIRE(state.state() == AlgoState::COMPLETED);
break;
} else {
REQUIRE(state.state() == AlgoState::RUNNING);
}
}
}
}
}
}
}
TEST_CASE("updates", "[algo][splitter]") {
// Start in state 0, update to state 1
std::vector<std::tuple<SimpleCase, std::vector<uint32_t>, SimpleCase>> cases;
// reduce max order size, increase # orders
cases.push_back({mkSimple(ExpectedCount{10} /*order count*/, 10 /*max*/,
100 /*exposed*/, 50 /*target*/),
{},
mkSimple(ExpectedCount{20}, 5, 100, 50)});
/// reduce max order size, keep # orders constant
cases.push_back({mkSimple(ExpectedCount{10}, 10, 100, 50),
{},
mkSimple(ExpectedCount{10}, 5, 50, 50)});
cases.push_back({mkSimple(ExpectedCount{10}, 10, 100, 50),
{5, 5},
mkSimple(ExpectedCount{8}, 5, 50, 40)});
cases.push_back({mkSimple(ExpectedCount{10}, 10, 100, 50),
{5, 5},
mkSimple(ExpectedCount{18}, 5, 100, 50)});
for (const auto &tcase : cases) {
auto case_init = std::get<0>(tcase);
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
*def.mutable_custom_def()->mutable_splitter() = case_init.sod;
AlgoTestDriver<SplitterAlgo> state(def, some_price, case_init.target);
REQUIRE(state.before_launch().ok());
state.launch();
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == case_init.expected_orders.value());
for (const auto &o : state.child_orders()) {
if (o.cstate.status == ChildStatus::WORKING) {
REQUIRE(o.cstate.quantity.value() <= case_init.sod.exposed_qty());
}
}
uint32_t fills = 0;
for (auto q : std::get<1>(tcase)) {
state.fill({}, Quantity{q});
fills += q;
}
REQUIRE(state.total_fills().value() == fills);
Update update;
auto case_next = std::get<2>(tcase);
update.set_price(some_price.price());
update.set_quantity(case_next.target.value());
*def.mutable_custom_def()->mutable_splitter() = case_next.sod;
*update.mutable_custom() = def.custom_def();
state.do_update(update);
REQUIRE(state.state() == AlgoState::RUNNING);
size_t working = 0;
for (const auto &c : state.child_orders())
if (c.cstate.status == ChildStatus::WORKING)
working += 1;
REQUIRE(working == case_next.expected_orders.value());
for (const auto &o : state.child_orders()) {
if (o.cstate.status == ChildStatus::WORKING) {
REQUIRE(o.cstate.quantity.value() <= case_next.sod.exposed_qty());
}
}
}
}
TEST_CASE("Reduction with fills", "[algo][splitter]") {
// Fills represent a floor on how much a trade can be reduced
// IF we have expose:400, clip: 100 we get
// 100,100,100,100
// Receive fills
// 100/50, 100/50, 100/50, 100/50
// Change expose to 300
// naive: 100, 100, 100 but we *can't* reduce the last to 0
// expected: 100, 100, 50, 50
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
auto *splitter = def.mutable_custom_def()->mutable_splitter();
splitter->set_max_order_qty(100);
splitter->set_exposed_qty(400);
AlgoTestDriver<SplitterAlgo> state(def, some_price, Quantity{300});
REQUIRE(state.before_launch().ok());
state.launch();
// check initial state
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == 4);
for (const auto &c : state.child_orders()) {
REQUIRE(c.cstate.quantity.value() == 100);
}
// Add fills
for (const auto &order : state.child_orders()) {
state.fill(order.key, {}, Quantity{50});
}
// Reduce exposed quantity
Update update;
update.set_quantity(300);
update.mutable_custom()->mutable_splitter()->set_exposed_qty(300);
state.do_update(update);
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == 4);
size_t total = 0;
for (const auto &order : state.child_orders()) {
total += order.cstate.quantity.value();
}
REQUIRE(total == 300);
// need this to be 100,100,50,50 not 100,100,100
std::set<uint32_t> actual, expected{100, 100, 50, 50};
for (const auto &order : state.child_orders()) {
actual.insert(order.cstate.quantity.value());
}
REQUIRE(actual == expected);
REQUIRE(state.total_fills().value() == 200);
}
TEST_CASE("Reduction with fills 2", "[algo][splitter]") {
// Fills represent a floor on how much a trade can be reduced
// IF we have expose:400, clip: 100 we get
// 100,100,100,100
// Receive fills
// 100/35, 100/45, 100/55, 100/65
// Change expose to 300
// naive: 100, 100, 100 but we *can't* reduce the last to 0
// expected: 100, 100, 65, 35
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
auto *splitter = def.mutable_custom_def()->mutable_splitter();
splitter->set_max_order_qty(100);
splitter->set_exposed_qty(400);
AlgoTestDriver<SplitterAlgo> state(def, some_price, Quantity{300});
REQUIRE(state.before_launch().ok());
state.launch();
// check initial state
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == 4);
for (const auto &c : state.child_orders()) {
REQUIRE(c.cstate.quantity.value() == 100);
}
// Add fills
state.fill({}, Quantity{35});
state.fill({}, Quantity{45});
state.fill({}, Quantity{55});
state.fill({}, Quantity{65});
// Reduce exposed quantity
Update update;
update.set_quantity(300);
update.mutable_custom()->mutable_splitter()->set_exposed_qty(300);
state.do_update(update);
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == 4);
size_t total = 0;
for (const auto &order : state.child_orders()) {
total += order.cstate.quantity.value();
}
REQUIRE(total == 300);
// need this to be 100,100,50,50 not 100,100,100
std::set<uint32_t> actual, expected{100, 100, 65, 35};
for (const auto &order : state.child_orders()) {
actual.insert(order.cstate.quantity.value());
}
REQUIRE(actual == expected);
}
TEST_CASE("Reduction with fills 3", "[algo][splitter]") {
// Fills represent a floor on how much a trade can be reduced
// IF we have expose:400, clip: 100 we get
// 100,100,100,100
// Receive fills
// 100/35, 100/45, 100/55, 100/65
// Change expose to 201
// naive: 100, 100, 1 but we *can't* reduce the last to 0
// expected: 66, 55, 45, 35
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
auto *splitter = def.mutable_custom_def()->mutable_splitter();
splitter->set_max_order_qty(100);
splitter->set_exposed_qty(400);
AlgoTestDriver<SplitterAlgo> state(def, some_price, Quantity{300});
REQUIRE(state.before_launch().ok());
state.launch();
// check initial state
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == 4);
for (const auto &c : state.child_orders()) {
REQUIRE(c.cstate.quantity.value() == 100);
}
// Add fills
state.fill({}, Quantity{35});
state.fill({}, Quantity{45});
state.fill({}, Quantity{55});
state.fill({}, Quantity{65});
// Reduce exposed quantity
Update update;
update.set_quantity(201);
update.mutable_custom()->mutable_splitter()->set_exposed_qty(201);
state.do_update(update);
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == 4);
size_t total = 0;
for (const auto &order : state.child_orders()) {
total += order.cstate.quantity.value();
}
REQUIRE(total == 201);
std::set<uint32_t> actual, expected{66, 55, 45, 35};
for (const auto &order : state.child_orders()) {
actual.insert(order.cstate.quantity.value());
}
REQUIRE(actual == expected);
}
TEST_CASE("reduce to completion", "[algo][splitter]") {
// Fills represent a floor on how much a trade can be reduced
// IF we have expose:400, clip: 100 we get
// 100,100,100,100
// Receive fills
// 100/100, 100/100, 100/0, 100/00
// Change expose to 200
// expected: algo transitions to copmleted state canceling 2 orders
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
auto *splitter = def.mutable_custom_def()->mutable_splitter();
splitter->set_max_order_qty(100);
splitter->set_exposed_qty(400);
AlgoTestDriver<SplitterAlgo> state(def, some_price, Quantity{300});
REQUIRE(state.before_launch().ok());
state.launch();
// check initial state
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == 4);
for (const auto &c : state.child_orders()) {
REQUIRE(c.cstate.quantity.value() == 100);
}
// Add fills
state.fill({}, Quantity{100});
state.fill({}, Quantity{100});
// Reduce exposed quantity
Update update;
update.set_quantity(200);
def.mutable_custom_def()->mutable_splitter()->set_exposed_qty(200);
state.do_update(update);
REQUIRE(state.state() == AlgoState::COMPLETED);
size_t total = 0;
for (const auto &order : state.child_orders()) {
if (order.cstate.status == ChildStatus::WORKING) {
total += order.cstate.quantity.value();
} else {
total += order.cstate.total_fills.value();
}
}
REQUIRE(total == 200);
}
TEST_CASE("reduce to completion 2", "[algo][splitter]") {
// Fills represent a floor on how much a trade can be reduced
// IF we have expose:400, clip: 100 we get
// 100,100,100,100
// Receive fills
// 100/100, 100/100, 100/0, 100/00
// Change expose to 200
// expected: algo transitions to copmleted state canceling 2 orders
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
auto *splitter = def.mutable_custom_def()->mutable_splitter();
splitter->set_max_order_qty(100);
splitter->set_exposed_qty(400);
AlgoTestDriver<SplitterAlgo> state(def, some_price, Quantity{300});
REQUIRE(state.before_launch().ok());
state.launch();
// check initial state
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == 4);
for (const auto &c : state.child_orders()) {
REQUIRE(c.cstate.quantity.value() == 100);
}
// Add fills
state.fill({}, Quantity{100});
state.fill({}, Quantity{50});
state.fill({}, Quantity{50});
// Reduce exposed quantity
Update update;
update.set_quantity(200);
state.do_update(update);
REQUIRE(state.state() == AlgoState::COMPLETED);
}
TEST_CASE("Async Fills", "[algo][splitter]") {
// OK, NOW it gets tricky because we're going to test the asyncronous stuff
// Start with 4 orders size 20 outstanding (80 total exposed)
// Change exposure to 64 so one of the four will be reduced to 5
// Before the change is confirmed fill the one that is reducing by 7
// which would constitute an overfill
// Algo must reduce a second order to compensate
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
auto *splitter = def.mutable_custom_def()->mutable_splitter();
splitter->set_max_order_qty(20);
splitter->set_exposed_qty(80);
AlgoTestDriver<SplitterAlgo> state(def, some_price, Quantity{80});
REQUIRE(state.before_launch().ok());
state.launch();
// check initial state
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == 4);
for (const auto &c : state.child_orders()) {
REQUIRE(c.cstate.quantity.value() == 20);
}
// Set up some instant fills
bool applied_fills = false;
state.on_child_changing([&](const auto &) {
if (applied_fills) return;
applied_fills = true;
// 7 fills on the last order which is has a size reduction in flight
state.fill(state.child_orders().rbegin()->key, {}, Quantity{7});
});
Update update;
update.set_price(state.price().value());
update.set_quantity(65);
update.mutable_custom()->mutable_splitter()->set_exposed_qty(65);
// This should trigger 1 order to be reduced to size 5 from 20
// in the meantime we'll trigger fills of size 7
// This results in an overfill for the 5 lot order
// And the
state.do_update(update);
// expected result:
// 7 fills, exposed_qty 65 = 58 active
uint32_t active = 0;
for (const auto &o : state.child_orders())
active += o.active_qty();
REQUIRE(active == 58);
}
TEST_CASE("Increase then decrease", "[algo][splitter]") {
// Start with 3 orders of size 100
// Increase the size to 400 so we launch a 4th order
// Then instantly send another update to 350
// NOTE: this test is not very good due to limitations in the test driver
// I'm leaving it in because it passes but if it starts failing in the future
// it's probably OK to disable it
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
auto *splitter = def.mutable_custom_def()->mutable_splitter();
splitter->set_max_order_qty(100);
splitter->set_exposed_qty(300);
AlgoTestDriver<SplitterAlgo> state(def, some_price, Quantity{300});
REQUIRE(state.before_launch().ok());
state.launch();
// check initial state
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == 3);
for (const auto &c : state.child_orders()) {
REQUIRE(c.cstate.quantity.value() == 100);
}
Update update;
update.set_price(state.price().value());
update.set_quantity(state.quantity().value());
update.mutable_custom()->mutable_splitter()->set_exposed_qty(400);
// Set up some instant fills
bool applied_second_update = false;
state.on_child_launching([&, update](const auto &) mutable {
if (!applied_second_update) {
applied_second_update = true;
update.mutable_custom()->mutable_splitter()->set_exposed_qty(350);
state.do_update(update);
}
});
state.do_update(update);
// expected result:
// 350 exposed, NOT 450
uint32_t quantity = 0;
for (const auto &o : state.child_orders())
quantity += o.active_qty();
REQUIRE(quantity == 350);
}
std::multiset<uint32_t> order_set(const std::vector<ChildOrder>& orders, ChildStatus status, const uint32_t* clip) {
std::multiset<uint32_t> res;
for (const auto &c : orders) {
if (c.cstate.status == status) {
res.insert(c.cstate.quantity.value());
}
if (clip) {
REQUIRE(c.cstate.quantity.value() <= *clip);
}
}
return res;
}
TEST_CASE("exposed < target", "[algo][splitter]") {
// Test various scenarios where exposed < target
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
auto *splitter = def.mutable_custom_def()->mutable_splitter();
uint32_t clip = 100, exposed = 200, target = 300;
splitter->set_max_order_qty(clip);
splitter->set_exposed_qty(exposed);
AlgoTestDriver<SplitterAlgo> state(def, some_price, Quantity{target});
REQUIRE(state.before_launch().ok());
state.launch();
// check initial state
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().size() == exposed/clip);
{
std::multiset<uint32_t>
expected { 100, 100 },
actual = order_set(state.child_orders(), ChildStatus::WORKING, &clip);
REQUIRE(expected == actual);
}
auto update = [&state](uint32_t clip, uint32_t exposed, uint32_t target) {
Update update;
update.set_price(state.price().value());
update.set_quantity(target);
update.mutable_custom()->mutable_splitter()->set_exposed_qty(exposed);
update.mutable_custom()->mutable_splitter()->set_max_order_qty(clip);
state.do_update(update);
};
// update exposure to 100
// expect 1 order @ 100
{
update(100u,100u,100u);
std::multiset<uint32_t>
expected { 100 },
actual = order_set(state.child_orders(), ChildStatus::WORKING, &clip);
REQUIRE(expected == actual);
REQUIRE(state.state() == AlgoState::RUNNING);
}
// update exposed to 400 (exposed > target) and clip to 50
// expect 8 orders
{
update(50u,400u,300u);
std::multiset<uint32_t>
expected { 50, 50, 50, 50,
50, 50, 50, 50},
actual = order_set(state.child_orders(), ChildStatus::WORKING, &clip);
REQUIRE(expected == actual);
REQUIRE(state.state() == AlgoState::RUNNING);
}
// update target to 450 (exposed < target)
// expect 4 order
{
update(100,400,450u);
std::multiset<uint32_t>
expected { 100, 100, 100, 100 },
actual = order_set(state.child_orders(), ChildStatus::WORKING, &clip);
REQUIRE(expected == actual);
REQUIRE(state.state() == AlgoState::RUNNING);
}
// fill 400
// expect 0 working children but order not complete
state.fill(Price {some_price.price()}, Quantity {400});
REQUIRE(state.state() == AlgoState::RUNNING);
// Expect there to be *NO* working orders at this point, we're still running though
std::multiset<uint32_t>
expected {},
actual = order_set(state.child_orders(), ChildStatus::WORKING, &clip);
REQUIRE(expected == actual);
// Raise the exposed qty to 450
// So that we can get the last 50 filled
// and complete the order
{
update(100,450,450u);
std::multiset<uint32_t>
expected { 50 },
actual = order_set(state.child_orders(), ChildStatus::WORKING, &clip);
REQUIRE(expected == actual);
REQUIRE(state.state() == AlgoState::RUNNING);
state.fill(Price {some_price.price()}, Quantity {50});
REQUIRE(state.state() == AlgoState::COMPLETED);
}
}
TEST_CASE("Initial exposed = 0", "[algo][splitter]") {
// Test various scenarios where exposed < target
api::orderman::OrderDefinition def;
def.set_side(api::SIDE_BUY);
auto *splitter = def.mutable_custom_def()->mutable_splitter();
splitter->set_max_order_qty(100);
splitter->set_exposed_qty(0);
AlgoTestDriver<SplitterAlgo> state(def, some_price, Quantity{300});
REQUIRE(state.before_launch().ok());
state.launch();
// check initial state
REQUIRE(state.state() == AlgoState::RUNNING);
REQUIRE(state.child_orders().empty());
}
} // namespace test
} // namespace orderman
} // namespace bts
@@ -0,0 +1,48 @@
#pragma once
#include "lib/utils/bts_chrono.h"
#include <vector>
namespace bts {
namespace orderman {
struct Accumulator {
uint32_t threshold;
TimeStamp top;
Duration bucket_interval = std::chrono::seconds(1);
std::vector<size_t> buckets;
uint32_t current_bucket = 0;
Accumulator(uint32_t threshold, uint32_t window_seconds, TimeStamp start) : threshold(threshold), top(start) {
buckets.resize(window_seconds);
}
void push_back(TimeStamp now, size_t contracts) {
// If current time is within bucket increment the count
// Otherwise advance to the next bucket and clear it
// by the number of 'bucket_intervals' that have passed and set that bucket
auto delta = (now - top);
while(delta > bucket_interval) {
delta -= bucket_interval;
current_bucket = (current_bucket+1) % buckets.size();
buckets[current_bucket] = 0;
top += bucket_interval;
}
buckets[current_bucket] += contracts;
}
size_t total() const {
size_t count= 0;
for (const auto& b : buckets) {
count += b;
}
return count;
}
bool exceeded() const {
return total() >= threshold;
}
};
}} //namespace
+60 -2
View File
@@ -1,5 +1,6 @@
#include "SparkServices.h"
#include "lib/orderman/order_factory/DynamicOrderRegistry.h"
#include "lib/logging/logging.h"
namespace bts {
@@ -21,10 +22,67 @@ void SparkServices::register_dynamic_order(
me->dyn_order_registry.register_dynamic_order(desc, builder);
}
void SparkServices::register_dynamic_algo_order(
bool validate_param(const api::orderman::DynamicOrderParamDescriptor& param);
bool validate_type(const std::string name, const api::orderman::DynamicOrderTypeDescriptor& type) {
switch(type.descriptor_case()) {
case api::orderman::DynamicOrderTypeDescriptor::DescriptorCase::kPrimitive: break;
case api::orderman::DynamicOrderTypeDescriptor::DescriptorCase::kArray:
if (!type.array().has_element_type()) {
LOG(OrderMan, Error, "Array parameter {} missing element type", name);
return false;
}
if (!validate_type(name + "::array", type.array().element_type())) return false;
break;
case api::orderman::DynamicOrderTypeDescriptor::DescriptorCase::kStructure:
for(const auto& field : type.structure().field()) {
if (!validate_param(field)) return false;
}
break;
case api::orderman::DynamicOrderTypeDescriptor::DescriptorCase::kEnumerated:
if (type.enumerated().element_size() == 0) {
LOG(OrderMan, Error, "Enumerated parameter {} missing options list", name);
return false;
}
case api::orderman::DynamicOrderTypeDescriptor::DescriptorCase::DESCRIPTOR_NOT_SET:
break;
}
return true;
}
bool validate_param(const api::orderman::DynamicOrderParamDescriptor& param) {
if (param.param_name().empty()) {
LOG(OrderMan, Error, "Parameter missing param_name");
return false;
}
if (!param.has_param_type()) {
LOG(OrderMan, Error, "Parameter {} missing type", param.param_name());
return false;
}
return validate_type(param.param_name(), param.param_type());
return true;
}
bool validate_descriptor(const api::orderman::DynamicOrderDescriptor& desc) {
if (desc.dynamic_order_type().empty()) {
LOG(OrderMan, Error, "Algo missing 'dynamic_order_type'");
return false;
}
for (const auto& param : desc.param_desc()) {
if (!validate_param(param)) {
return false;
}
}
return true;
}
AlgoRegistrationResult SparkServices::register_dynamic_algo_order(
api::orderman::DynamicOrderDescriptor const &desc,
std::function<std::unique_ptr<orderman::IAlgoOrder>()> const &builder) {
me->dyn_order_registry.register_dynamic_algo_order(desc, builder);
if (validate_descriptor(desc)) {
me->dyn_order_registry.register_dynamic_algo_order(desc, builder);
return AlgoRegistrationResult::SUCCESS;
}
return AlgoRegistrationResult::ERROR;
}
extern "C" void initialize_spark_plugin(SparkServices &) {}
+6 -1
View File
@@ -13,6 +13,11 @@ class IAlgoOrder;
class DynamicOrderRegistry;
} // namespace orderman
enum class AlgoRegistrationResult {
SUCCESS,
ERROR
};
class SparkServices {
public:
SparkServices(orderman::DynamicOrderRegistry &);
@@ -22,7 +27,7 @@ class SparkServices {
api::orderman::DynamicOrderDescriptor const &desc,
std::function<std::unique_ptr<orderman::Order>()> const &builder);
void register_dynamic_algo_order(
AlgoRegistrationResult register_dynamic_algo_order(
api::orderman::DynamicOrderDescriptor const &desc,
std::function<std::unique_ptr<orderman::IAlgoOrder>()> const &builder);
private:
+1
View File
@@ -24,6 +24,7 @@ public:
bool operator==(ValueWrapper const&v) const {return _v == v._v;}
bool operator!=(ValueWrapper const&v) const {return _v != v._v;}
bool operator<(ValueWrapper const&v) const {return _v < v._v;}
bool operator>(ValueWrapper const&v) const {return _v > v._v;}
ValueT const& value() const {return _v;}
ValueT & value() {return _v;}
private:
+7 -1
View File
@@ -324,8 +324,14 @@ extern "C" void init_spark_plugin(bts::SparkServices &serv) {
// Associate the descriptor with a builder function and register
// that with the Spark server.
serv.register_dynamic_algo_order(
auto result =
serv.register_dynamic_algo_order(
join_desc, []() { return std::make_unique<DynamicJoin>(); });
if (result != bts::AlgoRegistrationResult::SUCCESS) {
// The join_desc has errors
// Check the error log for more details
}
}
} // namespace order_example
-47
View File
@@ -1,60 +1,13 @@
#include "QuickTest.h"
#include "ICmd.h"
#include "lib/tracing/PerfLog.h"
#include "lib/orderman/orders/algo/IAlgoServices.h"
#include <iostream>
namespace bts {
namespace cmd {
using namespace bts::orderman;
struct Proxy : public IAlgoServices {
api::orderman::OrderDefinition def;
api::Security sec;
api::orderman::OrderDefinition const &definition() const { return def; }
api::Security const &security() const { return sec; }
OrderKey order_key() const { return OrderKey(0); }
OrderKey parent_order_key() const { return OrderKey(0); }
api::Security const *lookup_security(SecurityKey) const { return nullptr; }
bool is_attaching() const { return false; }
ChildTemplate &make_child_template(api::orderman::OrderDefinition const &,
size_t) {
ChildTemplate *p = nullptr;
return *p;
}
Price price() const { return Price(0); }
Quantity quantity() const { return Quantity(0); }
Quantity total_fills() const { return Quantity(0); }
bool is_shutting_down() const {return false;}
void subscribe_book(SecurityKey){};
void unsubscribe_book(SecurityKey) {}
void subscribe_child_change(OrderKey) {}
void unsubscribe_child_change(OrderKey) {}
void subscribe_timer() {}
void unsubscribe_timer() {}
OrderKey launch_child(ChildTemplate &, Price, Quantity, bool) { return {}; }
OrderKey launch_child(api::orderman::OrderDefinition const &, Price,
Quantity, bool) {
return {};
}
void update_child(OrderKey , api::orderman::Update const &) {}
void cancel_child(OrderKey) {}
void detach_child(OrderKey) {}
void detach_all_children() {}
void cancel(std::string const &) {}
void terminate_error(std::string const &) {}
void complete() {}
void update_fill_state(Quantity , Price ) {}
void set_ladder_visibility(bool) {}
};
int QuickTest::execute(std::vector<std::string> const &) {
Proxy p;
auto t = &(p.make_child_template(api::orderman::OrderDefinition(),2));
auto k = p.launch_child(*t,Price(1),Quantity(2),false);
std::cout << k.value() << "\n";
return 0;
}
@@ -1,3 +1,14 @@
This needs sim market data **not** to be merged with replay (or
cert), so we can create our own markets. Use the following key to set
market data up:
ExchangeSim {
value {
merge_with_md: false
forward_implied: false
}
}
Algo Studio lets you combine algos together and save it as an order type:
To test this, we will create a common algo combination and test to make sure it's working as desired.
@@ -6,42 +17,32 @@ To test this, we will create a common algo combination and test to make sure it'
Let's start by creating the Algo:
Launch Algo Studio
Click on top right icon to "add algo"
Click on top left icon to "add algo"
Give it a name, call it T_C and give the abbrev a title of T_C as well.
Create a Top with Cover, so the very top algos with be a "top" (top thresh 10) and it's child will be a cover (Hedge Ticks 2)
Leave both Hedge and Child as limits of the child
Use a very liquid market with recorded data to test, I suggest something like ES or CL.
On the ladder, go to settings, then algo favorites and click add and choose your T_C algo.
This will display it on the ladder for quick deployment
click on algo, then enter an order on the best bid
1.) Create a 20 lot bid/ask market 1 tick apart.
2.) Place a 5 lot T_C (top cover algo) buy order on the best bid market.
3.) Place another 5 lot buy limit order on the best bid
4.) Place a 25 lot sell limit order on the best bid, filling the orders placed in 1 and 2
5.) Verify that the cover order was deployed.
wait until it fills, once fills, it should submit the cover order 2 ticks above the price you got filled at.
try this with a sell order following the same procedure.
Repeat steps 1 through 5 with a sell order.
Additionally, we will add a "lean" into the mix as the child of the cover.
go back to your algo studio, and change the hedge of the cover to be that of lean.
What will happen is once the cover order is submitted, it will include the lean logic on that cover order. Meaning, it'll lean into the market and cross once the cross thresh is reach.
Set the parameters to a cross thresh of 10, max chase ticks 0 and on toward no change
save the algo, and send an order and wait for it to be filled.
Once filled, it will remain working until the market flips, which means it ticks up a level. Once it flips and there is 1 remaining, the order should cross.
Go back to your algo studio, and change the hedge of the cover to be that of lean.
What will happen is once the cover order is submitted, it will include the lean logic on that cover order.
Set the parameters to a cross thresh of 10, max chase ticks 0 and on toward no change.
Save the algo, and repeat steps 1 through 5 again.
This time the hedge should get filled immediately, as it will lean into the market that we just reduced below it's threshold size.