This commit is contained in:
Pedro Pinto committed 2017-09-27 12:48:28 -04:00
commit a1fda81277
12 files changed
+552 -186

No files matched your search

@@ -2,6 +2,7 @@
using mbts.ui.spark;
using System;
using System.Collections.Generic;
using System.Linq;
namespace mbts.spark
{
@@ -37,7 +38,8 @@ namespace mbts.spark
public virtual IReadOnlyCollection<SyntheticEditor2.IParameter> sub_items { get; }
public abstract T get_value(LegSpreaderParamsTuple leg_tup);
public abstract void set_value(LegSpreaderParamsTuple leg_tup, T value);
public object create_cell(LegSpreaderParamsTuple leg_tup) { return new ParameterRowCell<T>(this, leg_tup); }
public virtual bool has_errors(IReadOnlyCollection<LegSpreaderParamsTuple> leg_tups) { return false; }
public SyntheticEditor2.ICell create_cell(LegSpreaderParamsTuple leg_tup) { return new ParameterRowCell<T>(this, leg_tup); }
}
internal class SizeRowModel : ParameterBase<double> {
@@ -67,6 +69,7 @@ namespace mbts.spark
public override void set_value(LegSpreaderParamsTuple leg_tup, bool value) { leg_tup.leg_params.IsActiveQuoting = value; }
public override string display_name { get; } = "Is Active Quote";
public override string[] section_path { get; } = new[] { SectionNames.Quote };
public override bool has_errors(IReadOnlyCollection<LegSpreaderParamsTuple> leg_tups) { return !leg_tups.Any(lt => lt.leg_params.IsActiveQuoting); }
}
#region Quote
@@ -180,7 +183,7 @@ namespace mbts.spark
}
#endregion
internal class ParameterRowCell<T> {
internal class ParameterRowCell<T> : SyntheticEditor2.ICell {
public ParameterRowCell(IParameter<T> model, LegSpreaderParamsTuple leg_tup) {
_model = model;
_leg_tup = leg_tup;
@@ -189,7 +192,15 @@ namespace mbts.spark
private readonly IParameter<T> _model;
private readonly LegSpreaderParamsTuple _leg_tup;
public T value { get => _model.get_value(_leg_tup); set => _model.set_value(_leg_tup, value); }
public T value {
get => _model.get_value(_leg_tup);
set {
_model.set_value(_leg_tup, value);
value_changed?.Invoke();
}
}
public event Action value_changed;
}
}
}
@@ -112,8 +112,8 @@
SnapsToDevicePixels="True">
<SelectiveScrollingGrid Margin="{Binding section_count, Converter={StaticResource ReverseRowHeaderGroupIndentConverter}}">
<SelectiveScrollingGrid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</SelectiveScrollingGrid.ColumnDefinitions>
<DataGridRowHeader SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
Background="Transparent"
@@ -124,9 +124,18 @@
<DataGridCellsPresenter Grid.Column="1" ItemsPanel="{TemplateBinding ItemsPanel}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</SelectiveScrollingGrid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="usp:SyntheticEditor2.RowHasErrors" Value="True">
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="1"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<Style x:Key="DataGridRowStyle" TargetType="DataGridRow">
<Setter Property="BorderThickness" Value="1,0"/>
<Setter Property="BorderBrush" Value="Transparent"/>
<Setter Property="Template" Value="{StaticResource DataGridRowTemplate}"/>
<Setter Property="usp:SyntheticEditor2.RowHasErrors" Value="{Binding has_errors}"/>
</Style>
<ControlTemplate x:Key="SyntheticEditor2Template" TargetType="usp:SyntheticEditor2">
<Border BorderBrush="{TemplateBinding BorderBrush}"
@@ -25,7 +25,13 @@ namespace mbts.ui.spark
{
string display_name { get; }
string[] section_path { get; }
object create_cell(LegSpreaderParamsTuple leg_tup);
bool has_errors(IReadOnlyCollection<LegSpreaderParamsTuple> leg_tups);
ICell create_cell(LegSpreaderParamsTuple leg_tup);
}
public interface ICell
{
event Action value_changed;
}
#region SyntheticName
@@ -79,16 +85,25 @@ namespace mbts.ui.spark
internal class ParameterRow : DataGridExRow<Security>
{
public ParameterRow(IParameter model, IReadOnlyCollection<LegSpreaderParamsTuple> legs) {
_cells = new ReadOnlyDictionary<Security, object>(legs.ToDictionary(l => l.leg.Security, model.create_cell));
_has_errors = backing(nameof(has_errors), false);
_cells = new ReadOnlyDictionary<Security, ICell>(legs.ToDictionary(l => l.leg.Security, model.create_cell));
foreach(var c in _cells.Values) {
_has_errors.set(model.has_errors(legs));
c.value_changed += () => _has_errors.set(model.has_errors(legs));
}
display_name = model.display_name;
section_path = model.section_path;
}
private readonly IReadOnlyDictionary<Security, object> _cells;
private readonly IReadOnlyDictionary<Security, ICell> _cells;
private readonly Property<bool> _has_errors;
public string display_name { get; }
public string[] section_path { get; }
public int section_count => section_path.Length;
public override object get_cell(Security col_key) { return _cells[col_key]; }
public string this[string section_no] => int.TryParse(section_no, out int i) && i < section_path.Length ? section_path[i] : null;
public bool has_errors => _has_errors.Value;
}
#endregion
@@ -113,6 +128,12 @@ namespace mbts.ui.spark
public DataTemplateSelector ParameterCellEditingTemplateSelector { get => GetValue(ParameterCellEditingTemplateSelectorProperty) as DataTemplateSelector; set => SetValue(ParameterCellEditingTemplateSelectorProperty, value); }
#endregion
#region RowHasError
public static readonly DependencyProperty RowHasErrorsProperty = DependencyProperty.RegisterAttached("RowHasErrors", typeof(bool), typeof(SyntheticEditor2), new PropertyMetadata(false));
public static bool GetRowHasErrors(DependencyObject d) { return (bool)d.GetValue(RowHasErrorsProperty); }
public static void SetRowHasErrors(DependencyObject d, bool value) { d.SetValue(RowHasErrorsProperty, value); }
#endregion
private static void GenerateParameterRows(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var parameters = d.GetValue(ParametersProperty) as IReadOnlyCollection<IParameter>;
var legs = d.GetValue(LegTuplesProperty) as IReadOnlyCollection<LegSpreaderParamsTuple>;
+1 -1
View File
@@ -1 +1 @@
set(sources ;event_grid/EventNode.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/store_tests.cpp;main.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/MDP3Utils.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;orderman/components/Gateway.cpp;orderman/components/MDSource.cpp;orderman/components/NativeOrderMan.cpp;orderman/components/OrderRecorder.cpp;orderman/events/ExecutionReport.cpp;orderman/events/NativeOrderStateChange.cpp;orderman/events/TimeChange.cpp;orderman/native_orders/NativeOrder.cpp;orderman/persistence/FillDB.cpp;orderman/persistence/OrderDB.cpp;orderman/service/OrderServiceServer.cpp;orderman/utils/fix_order_codec.cpp;orderman/utils/orderman_utils.cpp;persistence/IStore.cpp;persistence/PersistenceServiceServer.cpp;persistence/SqliteStore.cpp;persistence/tests/PersistenceServiceTests.cpp;risk_limits/IRiskLimitObserver.cpp;risk_limits/RiskLimitManager.cpp;risk_limits/RiskLimiter.cpp;risk_limits/SharedRiskLimiter.cpp;risk_limits/SymbolKey.cpp;risk_limits/tests/RiskLimitsTests.cpp;securities/SecurityDB.cpp;spreader/QuoteLegPriceQuantityState.cpp;spreader/SimpleSpreader.cpp;spreader/SingleLegQuoter.cpp;spreader/SpreaderBase.cpp;testing/catch_test_runner.cpp;user/UserServiceServer.cpp)
set(sources ;grid/Node.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/store_tests.cpp;main.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/MDP3Utils.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;orderman/components/Gateway.cpp;orderman/components/MDSource.cpp;orderman/components/NativeOrderMan.cpp;orderman/events/TimeChange.cpp;orderman/native_orders/NativeOrder.cpp;orderman/utils/fix_order_codec.cpp;orderman/utils/orderman_utils.cpp;persistence/IStore.cpp;persistence/PersistenceServiceServer.cpp;persistence/SqliteStore.cpp;persistence/tests/PersistenceServiceTests.cpp;risk_limits/IRiskLimitObserver.cpp;risk_limits/RiskLimitManager.cpp;risk_limits/RiskLimiter.cpp;risk_limits/SharedRiskLimiter.cpp;risk_limits/SymbolKey.cpp;risk_limits/tests/RiskLimitsTests.cpp;securities/SecurityDB.cpp;spreader/QuoteLegPriceQuantityState.cpp;spreader/SimpleSpreader.cpp;spreader/SingleFillHedger.cpp;spreader/SingleLegQuoter.cpp;spreader/SpreaderBase.cpp;testing/catch_test_runner.cpp;user/UserServiceServer.cpp)
+3
View File
@@ -58,6 +58,7 @@
<ClCompile Include="setup\ServiceHostActor.cpp" />
<ClCompile Include="spreader\QuoteLegPriceQuantityState.cpp" />
<ClCompile Include="spreader\SimpleSpreader.cpp" />
<ClCompile Include="spreader\SingleFillHedger.cpp" />
<ClCompile Include="spreader\SingleLegQuoter.cpp" />
<ClCompile Include="spreader\SpreaderBase.cpp" />
<ClCompile Include="testing\catch_test_runner.cpp" />
@@ -138,9 +139,11 @@
<ClInclude Include="spreader\ISpreaderInternalOrderBridge.h" />
<ClInclude Include="spreader\QuoteLegPriceQuantityState.h" />
<ClInclude Include="spreader\SimpleSpreader.h" />
<ClInclude Include="spreader\SingleFillHedger.h" />
<ClInclude Include="spreader\SingleLegQuoter.h" />
<ClInclude Include="spreader\Spreader.h" />
<ClInclude Include="spreader\SpreaderBase.h" />
<ClInclude Include="spreader\SpreaderUtils.h" />
<ClInclude Include="testing\catch_test_runner.h" />
<ClInclude Include="user\UserServiceServer.h" />
</ItemGroup>
+12
View File
@@ -61,6 +61,9 @@
<Filter Include="orderman\doc">
<UniqueIdentifier>{7c15123a-161f-41d0-8c67-351ba12ed261}</UniqueIdentifier>
</Filter>
<Filter Include="spreader\hedger">
<UniqueIdentifier>{0a189ff2-332a-45cc-bffe-a2d16a62ab11}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="algo_man\AlgoManServiceServer.cpp">
@@ -214,6 +217,9 @@
<ClCompile Include="risk_limits\SymbolKey.cpp">
<Filter>risk_limits</Filter>
</ClCompile>
<ClCompile Include="spreader\SingleFillHedger.cpp">
<Filter>spreader\hedger</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<ClInclude Include="algo_man\AlgoManServiceServer.h">
@@ -453,6 +459,12 @@
<ClInclude Include="risk_limits\SymbolKey.h">
<Filter>risk_limits</Filter>
</ClInclude>
<ClInclude Include="spreader\SingleFillHedger.h">
<Filter>spreader\hedger</Filter>
</ClInclude>
<ClInclude Include="spreader\SpreaderUtils.h">
<Filter>spreader</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<None Include="jetfix\tests\sample_fix.dat">
@@ -1,16 +1,14 @@
#pragma once
namespace bts
namespace bts {
namespace spreader {
class ISpreaderInternalOrderBridge
{
namespace spreader
{
class ISpreaderInternalOrderBridge
{
public:
virtual int get_id(const api::Security& security, api::BuySell side) = 0;
virtual void send_limit_order(int client_id, bts::Price price, bts::Quantity quantity) = 0;
virtual void update_order(int client_id, bts::Price price, bts::Quantity quantity) = 0;
virtual void cancel_order(int client_id) = 0;
};
}
}
public:
virtual int get_id(const api::Security& security, api::BuySell side) = 0;
virtual void send_limit_order(int client_id, bts::Price price, bts::Quantity quantity) = 0;
virtual void send_market_order(int client_id, bts::Quantity quantity) = 0;
virtual void update_order(int client_id, bts::Price price, bts::Quantity quantity) = 0;
virtual void cancel_order(int client_id) = 0;
};
}}
@@ -1,109 +1,67 @@
#include "QuoteLegPriceQuantityState.h"
namespace bts
namespace bts {
namespace spreader {
QuoteLegPriceQuantityState::QuoteLegPriceQuantityState(Price target_spread_price, Quantity target_leg_quantity)
:
_in_target_spread_price(target_spread_price),
_in_target_leg_quantity(target_leg_quantity),
_aggregated_filled_quantity(0),
_aggregated_hedged_reduction(0),
_computed_quantity(0),
_out_quantity(0)
{}
void QuoteLegPriceQuantityState::update_target_spread_price(Price new_target_spread_price)
{
namespace spreader
{
QuoteLegPriceQuantityState::QuoteLegPriceQuantityState(Price target_spread_price, Quantity target_leg_quantity)
:
_in_target_spread_price(target_spread_price),
_in_target_leg_quantity(target_leg_quantity),
_aggregated_filled_quantity(0),
_aggregated_hedged_reduction(0),
_computed_quantity(0),
_out_quantity(0)
{ }
_in_target_spread_price = new_target_spread_price;
}
void QuoteLegPriceQuantityState::add_filled_quantity(Quantity filled_qty)
{
_aggregated_filled_quantity = Quantity(_aggregated_filled_quantity.value() + filled_qty.value());
_recompute_output();
}
void QuoteLegPriceQuantityState::update_target_leg_quantity(Quantity new_target_leg_quantity)
{
_in_target_leg_quantity = new_target_leg_quantity;
}
void QuoteLegPriceQuantityState::add_hedged_reduction(Quantity normalized_hedge_reduction)
{
_aggregated_hedged_reduction = Quantity (_aggregated_hedged_reduction.value() + normalized_hedge_reduction.value());
_recompute_output();
}
void QuoteLegPriceQuantityState::add_filled_quantity(Quantity filled_qty)
{
_aggregated_filled_quantity = Quantity(_aggregated_filled_quantity.value() + filled_qty.value());
}
void QuoteLegPriceQuantityState::update_target_leg_quantity(Quantity new_target_leg_quantity)
{
_in_target_leg_quantity = new_target_leg_quantity;
_recompute_output();
}
void QuoteLegPriceQuantityState::add_hedged_reduction(Quantity normalized_hedge_reduction)
{
_aggregated_hedged_reduction = Quantity(_aggregated_hedged_reduction.value() + normalized_hedge_reduction.value());
}
void QuoteLegPriceQuantityState::update_target_spread_price(Price new_target_spread_price)
{
_in_target_spread_price = new_target_spread_price;
_recompute_output();
}
void QuoteLegPriceQuantityState::update_computed_price_quantity(Price new_computed_price, Quantity new_computed_quantity)
{
_computed_price = new_computed_price;
_computed_quantity = new_computed_quantity;
}
void QuoteLegPriceQuantityState::update_computed_price_quantity(Price new_computed_price, Quantity new_computed_quantity)
{
_computed_price = new_computed_price;
_computed_quantity = new_computed_quantity;
_recompute_output();
}
void QuoteLegPriceQuantityState::synchronize_out_price_quantity()
{
_out_price = _computed_price;
_out_quantity = _computed_quantity;
}
void QuoteLegPriceQuantityState::synchronize_out_price_quantity()
{
_out_price = _computed_price;
_out_quantity = _computed_quantity;
_recompute_output();
}
bool QuoteLegPriceQuantityState::out_quantity_synchronized() { return _out_quantity == _computed_quantity; }
bool QuoteLegPriceQuantityState::out_quantity_synchronized() { return _out_quantity == _computed_quantity; }
bool QuoteLegPriceQuantityState::out_price_synchronized() { return _out_price == _computed_price; }
bool QuoteLegPriceQuantityState::out_price_synchronized() { return _out_price == _computed_price; }
Quantity QuoteLegPriceQuantityState::remaining_to_fill()
{
if (_aggregated_hedged_reduction.value() >= _in_target_leg_quantity.value())
{
return Quantity(0);
}
else
{
Quantity hedge_reduced_target_quantity = Quantity(_in_target_leg_quantity.value() - _aggregated_hedged_reduction.value());
if (_aggregated_filled_quantity.value() >= hedge_reduced_target_quantity.value())
return Quantity(0);
else
return Quantity(hedge_reduced_target_quantity.value() - _aggregated_filled_quantity.value());
}
}
void QuoteLegPriceQuantityState::_recompute_output()
{
/*if (_aggregated_filled_qty >= _target_leg_qty)
{
_computed_qty = 0;
_computed_price = Double.NaN;
}
else
{
uint hedge_adjusted_qty = _target_leg_qty - _aggregated_filled_qty;
if (_aggregated_filled_qty >= hedge_adjusted_qty)
{
_computed_qty = 0;
_computed_price = Double.NaN;
}
else
{
uint remainder_to_get_qty = hedge_adjusted_qty - _aggregated_filled_qty;
Tuple<double, uint> price_qty = _price_qty_evaluator(remainder_to_get_qty);
if (price_qty.Item2 == 0)
{
_computed_qty = 0;
_computed_price = Double.NaN;
}
else
{
_computed_qty = price_qty.Item2 + _aggregated_filled_qty;
_computed_price = price_qty.Item1;
}
}
}*/
}
}
}
Quantity QuoteLegPriceQuantityState::remaining_to_fill()
{
if (_aggregated_hedged_reduction.value() >= _in_target_leg_quantity.value())
{
return Quantity(0);
}
else
{
Quantity hedge_reduced_target_quantity = Quantity(_in_target_leg_quantity.value() - _aggregated_hedged_reduction.value());
if (_aggregated_filled_quantity.value() >= hedge_reduced_target_quantity.value())
return Quantity(0);
else
return Quantity(hedge_reduced_target_quantity.value() - _aggregated_filled_quantity.value());
}
}
}}
@@ -7,70 +7,72 @@
#include "lib/api/services/OrderService.pb.h"
#include "lib/utils/bts_chrono.h"
namespace bts
namespace bts {
namespace spreader {
// this class is used to mantain the price and quantity
// state of the leg quoter
class QuoteLegPriceQuantityState
{
namespace spreader
{
class QuoteLegPriceQuantityState
{
private:
// Spread price set by the user. As the user updates
// the spread price, this is set to the new value
Price _in_target_spread_price;
// This is total desired leg quantity set by the user.
// It is simply the spread leg qty * leg_ratio.
Quantity _in_target_leg_quantity;
// This is sum of the fills for this leg
Quantity _aggregated_filled_quantity;
// As fills happen in other legs, the "equivelant part"
// is deducted from the quoted quantity and sent over
// to the hedger. This is the sum of those of those
// "equivelant parts".
Quantity _aggregated_hedged_reduction;
// Theoretically computed price
Price _computed_price;
// Theoretically computed quantity
Quantity _computed_quantity;
// Price of the last order sent
Price _out_price;
// Quantity of the last order sent
Quantity _out_quantity;
private:
void _recompute_output();
protected:
public:
QuoteLegPriceQuantityState(Price target_spread_price, Quantity target_leg_quantity);
// Called when a fill happens for this leg. This is increases the filled counter.
// This is needed to know the "remainder quantity" needed to price this leg
void add_filled_quantity(Quantity filled_qty);
// When a fill happens in one of the other quoting legs. This is reduced from
// the target quantity
void add_hedged_reduction(Quantity normalized_hedge_qty);
// When a the target quantity of the spreader order is changed by the user. This results
// in the target quantity of thos leg to be changed
void update_target_leg_quantity(Quantity new_target_leg_quantity);
// When the user changes the spread price
void update_target_spread_price(Price new_target_spread_price);
// To update the computed price and quantity
void update_computed_price_quantity(Price new_computed_price, Quantity new_computed_quantity);
// This sets the out price/quantity to the computed price/quantity
void synchronize_out_price_quantity();
// Tells if if the out pice is the same as computed price
bool out_quantity_synchronized();
// Tell if the out quantity is the same as computed quantity
bool out_price_synchronized();
// Accessor functions
Price target_spread_price() { return _in_target_spread_price; }
Quantity target_leg_quantity() { return _in_target_leg_quantity; }
Quantity aggregated_filled_quantity() { return _aggregated_filled_quantity; }
Quantity aggregated_hedged_reduction() { return _aggregated_hedged_reduction; }
Price computed_price() { return _computed_price; }
Quantity computed_quantity() { return _computed_quantity; }
Price out_price() { return _out_price; }
Quantity out_quantity() { return _out_quantity; }
bool computed_price_is_higher() { return _computed_price.value() > _out_price.value(); }
Price change_in_computed_price() { return Price(_computed_price.value() - _out_price.value()); }
Quantity remaining_to_fill();
};
}
}
private:
// this is spread price set by the user. this is
// modified only when the user explicitely
// modifies the price of the spread order
Price _in_target_spread_price;
// this is total desired leg quantity set by the user.
// it is simply the spread leg qty * leg_ratio
Quantity _in_target_leg_quantity;
// sum of the fills for this leg. as fills come in
// this increases
Quantity _aggregated_filled_quantity;
// when fills happen for the other legs, the "equivelant part"
// is deducted from the quoted quantity and sent over
// to the hedger. This is the sum of those of those "equivelant parts".
// for example with with a a*leg_1 - b*leg_2, spread an N lot sized
// fill on leg_2 will will result in N*a/b added to _aggregated_hedged_reduction
Quantity _aggregated_hedged_reduction;
// theoretically computed price. this might be different from
// _out_price because of the state of the quoter. eventually
// they should converge
Price _computed_price;
// theoretically computed quantity. similiar behaviour to
// _computed_price
Quantity _computed_quantity;
// price of the last order sent.
Price _out_price;
// quantity of the last order sent
Quantity _out_quantity;
public:
QuoteLegPriceQuantityState(Price target_spread_price, Quantity target_leg_quantity);
// called when the user changes the spread price
void update_target_spread_price(Price new_target_spread_price);
// called when the target quantity of the spreader order is changed.
// this is only called as a result of the user user changing the
// spreader order qty
void update_target_leg_quantity(Quantity new_target_leg_quantity);
// called when a fill happens for this leg. this increases the filled counter.
// this is needed to know the "remainder quantity" needed to price this leg
void add_filled_quantity(Quantity filled_qty);
// called when a fill happens in one of the other quoting legs.
void add_hedged_reduction(Quantity normalized_hedge_qty);
// updates the computed price and quantity
void update_computed_price_quantity(Price new_computed_price, Quantity new_computed_quantity);
// this sets the out price/quantity to the computed price/quantity
void synchronize_out_price_quantity();
// returns true when the out pice is the same as computed price
bool out_quantity_synchronized();
// Tell if the out quantity is the same as computed quantity
bool out_price_synchronized();
// Accessor functions
Price target_spread_price() { return _in_target_spread_price; }
Quantity target_leg_quantity() { return _in_target_leg_quantity; }
Quantity aggregated_filled_quantity() { return _aggregated_filled_quantity; }
Quantity aggregated_hedged_reduction() { return _aggregated_hedged_reduction; }
Price computed_price() { return _computed_price; }
Quantity computed_quantity() { return _computed_quantity; }
Price out_price() { return _out_price; }
Quantity out_quantity() { return _out_quantity; }
bool computed_price_is_higher() { return _computed_price.value() > _out_price.value(); }
Price change_in_computed_price() { return Price(_computed_price.value() - _out_price.value()); }
Quantity remaining_to_fill();
};
}}
@@ -0,0 +1,178 @@
#include <memory>
#include "SingleFillHedger.h"
#include "ISpreaderInternalOrderBridge.h"
#include "SpreaderUtils.h"
namespace bts {
namespace spreader {
SingleFillHedger::SingleFillHedger(ISpreaderInternalOrderBridge* order_bridge,
int order_client_id,
bts::api::ContractLeg const& this_leg,
const bts::spark::ExecutionStrategy& execution_strategy,
bts::Price hedge_price,
bts::Quantity hedge_quantity,
api::BuySell hedge_side)
:
_tick_size(this_leg.security().contract_spec().low_tick()),
_order_client_id(order_client_id),
_contract_leg(this_leg),
_post_hedge_params(SpreaderUtils::get_leg_params(execution_strategy, this_leg).post_hedge_params()),
_hedge_side(hedge_side),
_price_quantity_state(hedge_price, hedge_quantity),
_state(HedgerState::START),
_order_bridge(order_bridge)
{
}
bool SingleFillHedger::is_active() { return _state != HedgerState::START && _state != HedgerState::END; }
Quantity SingleFillHedger::remaining_to_fill() { return _price_quantity_state.remaining_to_fill(); }
void SingleFillHedger::update_order_status(const OrderState& order_state)
{
bool filled, terminal_state, encountered_error;
SpreaderUtils::parse_order(order_state, filled, terminal_state, encountered_error);
ExternalHedgerEvents ex_ev = ExternalHedgerEvents::OrderStatusError;
if (terminal_state) ex_ev = ExternalHedgerEvents::OrderStatusTerminal;
else
{
if (encountered_error) ex_ev = ExternalHedgerEvents::OrderStatusError;
else ex_ev = ExternalHedgerEvents::OrderStatusNormal;
}
_fire_event(ex_ev);
}
void SingleFillHedger::update_md(Book const&b)
{
_book = b;
_fire_event(ExternalHedgerEvents::MDUpdate);
}
void SingleFillHedger::modify_hedge_price(Price new_hedge_price)
{
_price_quantity_state.udpate_target_price(new_hedge_price);
// working state will check the out price vs target price
// and modify the price to target price
_fire_event(ExternalHedgerEvents::UserHedgePriceChange);
}
void SingleFillHedger::cancel_hedge()
{
_fire_event(ExternalHedgerEvents::HedgeCancel);
}
void SingleFillHedger::_fire_event(ExternalHedgerEvents ex_ev)
{
if (_state == HedgerState::WORKING)
_handle_events_in_WORKING(ex_ev);
if (_state == HedgerState::START)
_handle_events_in_START(ex_ev);
else if (_state == HedgerState::WAITING_FOR_FIRST_ACK)
_handle_events_in_WAITING_FOR_FIRST_ACK(ex_ev);
else if (_state == HedgerState::WAITING_FOR_CANCEL_ACK)
_handle_events_in_WAITING_FOR_CANCEL_ACK(ex_ev);
else if (_state == HedgerState::END)
_handle_events_in_END(ex_ev);
}
void SingleFillHedger::_handle_events_in_START(ExternalHedgerEvents)
{
bts_assert(false);
}
void SingleFillHedger::_handle_events_in_WAITING_FOR_FIRST_ACK(ExternalHedgerEvents ex_ev)
{
if (ex_ev == ExternalHedgerEvents::OrderStatusNormal)
_change_state(HedgerState::WORKING);
else if (ex_ev == ExternalHedgerEvents::OrderStatusError)
_change_state(HedgerState::WAITING_FOR_CANCEL_ACK);
else if (ex_ev == ExternalHedgerEvents::OrderStatusTerminal)
_change_state(HedgerState::END);
else if (ex_ev == ExternalHedgerEvents::MDUpdate)
//for now we are only going to implement a time based post hedge rule, so
//market data is not needed
{
}
else if (ex_ev == ExternalHedgerEvents::UserHedgePriceChange)
// when the hedger goes to WORKING, the out price is checked vs the computed price
// and price adjustments are made if necessary
{
}
else if (ex_ev == ExternalHedgerEvents::HedgeCancel)
_change_state(HedgerState::WAITING_FOR_CANCEL_ACK);
}
void SingleFillHedger::_handle_events_in_WORKING(ExternalHedgerEvents ex_ev)
{
if (ex_ev == ExternalHedgerEvents::OrderStatusNormal)
{
// the order might be changing non terminal states (ex from 'waiting_for_ack' to
// 'ack_received' but there is nothing to do as a response*/
}
else if (ex_ev == ExternalHedgerEvents::OrderStatusError)
// any error means we cancel
_change_state(HedgerState::WAITING_FOR_CANCEL_ACK);
else if (ex_ev == ExternalHedgerEvents::OrderStatusTerminal)
// either it was cancelled externally, filled, rejected etc
_change_state(HedgerState::END);
else if (ex_ev == ExternalHedgerEvents::MDUpdate)
{
}
else if (ex_ev == ExternalHedgerEvents::UserHedgePriceChange)
{
if (!_price_quantity_state.prices_synced())
{
_price_quantity_state.sync_out_price();
_order_bridge->update_order(_order_client_id, _price_quantity_state.target_price(), _price_quantity_state.target_quantity());
}
}
else if (ex_ev == ExternalHedgerEvents::HedgeCancel)
_change_state(HedgerState::WAITING_FOR_CANCEL_ACK);
}
void SingleFillHedger::_handle_events_in_WAITING_FOR_CANCEL_ACK(ExternalHedgerEvents ex_ev)
{
// waiting for the cancel to take place (or, conincidentally a terminal state
// through other means
if (ex_ev == ExternalHedgerEvents::OrderStatusTerminal)
_change_state(HedgerState::END);
}
void SingleFillHedger::_handle_events_in_END(ExternalHedgerEvents ex_ev)
{
bts_assert(ex_ev != ExternalHedgerEvents::OrderStatusNormal);
bts_assert(ex_ev != ExternalHedgerEvents::OrderStatusError);
bts_assert(ex_ev != ExternalHedgerEvents::OrderStatusTerminal);
}
void SingleFillHedger::_change_state(HedgerState new_state)
{
HedgerState curr_state = _state;
_state = new_state;
if (new_state == HedgerState::START)
bts_assert(false);
else if (new_state == HedgerState::WAITING_FOR_FIRST_ACK)
{
bts_assert(curr_state == HedgerState::START);
// The order is sent for the only and only time here
// TODO check for market orders pre hedge rule
_price_quantity_state.sync_out_price();
_order_bridge->send_limit_order(_order_client_id, _price_quantity_state.target_price(), _price_quantity_state.target_quantity());
}
else if (new_state == HedgerState::WORKING)
{
// If while in WAITING_FOR_FIRST_ACK, the price was changed
// we adjust it here.
// We could also have made the main spreader query this class
// and reject the change if the Hedger's state != Working
// (this will be much easier and maybe worth it)
_handle_events_in_WORKING(ExternalHedgerEvents::UserHedgePriceChange);
}
else if (new_state == HedgerState::WAITING_FOR_CANCEL_ACK)
{
bts_assert(curr_state == HedgerState::WAITING_FOR_FIRST_ACK || curr_state == HedgerState::WORKING);
_order_bridge->cancel_order(_order_client_id);
}
}
}}
@@ -0,0 +1,136 @@
#pragma once
#include <memory>
#include "SpreaderBase.h"
#include "QuoteLegPriceQuantityState.h"
#include <boost/container/flat_map.hpp>
namespace bts {
namespace spreader {
class ISpreaderInternalOrderBridge;
class SingleFillHedger
{
enum class ExternalHedgerEvents
{
// normal order status event from the exchange (this is a non terminal
// order status)
OrderStatusNormal = 0,
// error report from the exchange (this could be a temporary error,
// however the state machine will cancel the order)
OrderStatusError,
// terminal order status even from the exchange
OrderStatusTerminal,
// timer event from the spreader engine
Timer,
// market data update from the exchange
MDUpdate,
// user modification of the hedger price
UserHedgePriceChange,
// cancel of this hedge order
HedgeCancel,
};
enum class HedgerState
{
START,
WAITING_FOR_FIRST_ACK,
WORKING,
WAITING_FOR_CANCEL_ACK,
END
};
// price and quantity state for the hedger is kept here
class HedgePriceQuantityState
{
private:
Price _target_price;
// this can never be modified
const Quantity _target_quantity;
// the price of the "active" hedger order
Price _out_price;
Quantity _aggregated_filled_quantity;
public:
HedgePriceQuantityState(Price target_price, Quantity target_quantity)
:
_target_price(target_price),
_target_quantity(target_quantity),
_out_price(0.0),
_aggregated_filled_quantity(0)
{
}
// called when the user updates a working hedge order price
void udpate_target_price(Price new_target_price) { _target_price = new_target_price; }
// called as the hedge order gets filled
void update_fill(Quantity fill_quantity)
{
_aggregated_filled_quantity = Quantity(_aggregated_filled_quantity.value() + fill_quantity.value());
}
// sets the outprice to the target price
void sync_out_price() { _out_price = _target_price; }
Price target_price() { return _target_price; }
const Quantity target_quantity() { return _target_quantity; }
Price out_price() { return _out_price; }
Quantity aggregated_filled_quantity() { return _aggregated_filled_quantity; }
// tells if the out_price and target_price are in sync
bool prices_synced() { return _out_price.value() == _target_price.value(); }
// this is the order quantity net of the fills
Quantity remaining_to_fill()
{
uint32_t rv = _aggregated_filled_quantity.value() >= _target_quantity.value() ? 0 : _target_quantity.value() - _aggregated_filled_quantity.value();
return Quantity(rv);
}
};
private:
const double _tick_size;
const int _order_client_id;
const bts::api::ContractLeg& _contract_leg;
const bts::spark::PostHedgeParams& _post_hedge_params;
const api::BuySell _hedge_side;
HedgePriceQuantityState _price_quantity_state;
HedgerState _state;
ISpreaderInternalOrderBridge* _order_bridge;
Book _book;
private:
void _fire_event(ExternalHedgerEvents events);
void _handle_events_in_START (ExternalHedgerEvents events);
void _handle_events_in_WAITING_FOR_FIRST_ACK(ExternalHedgerEvents events);
void _handle_events_in_WORKING(ExternalHedgerEvents events);
void _handle_events_in_WAITING_FOR_CANCEL_ACK(ExternalHedgerEvents events);
void _handle_events_in_END(ExternalHedgerEvents events);
// all state machine state changes occur here. also all actions
// performed at the transition edges also are called from within
// this function
void _change_state(HedgerState new_state);
public:
SingleFillHedger(ISpreaderInternalOrderBridge* order_bridge,
int order_client_id,
bts::api::ContractLeg const& this_leg,
const bts::spark::ExecutionStrategy& execution_strategy,
bts::Price hedge_price,
bts::Quantity hedge_quantity,
api::BuySell hedge_side);
// true if the hedger has an active working order
bool is_active();
// this is the order quantity net of the fills (qty - filled_qty)
Quantity remaining_to_fill();
// called by the spreader when there is an order update
// reported by the exchange
void update_order_status(OrderState const& state);
// called when the market data associated
// with this security is changed
void update_md(Book const&b);
// called when a user changed the price of a working
// hedge order
void modify_hedge_price(Price new_hedge_price);
// called when the hedge order is cancelled, either
// manually or automatically
void cancel_hedge();
};
}}
@@ -0,0 +1,38 @@
#pragma once
#include <memory>
#include "SpreaderBase.h"
#include "QuoteLegPriceQuantityState.h"
#include <boost/container/flat_map.hpp>
namespace bts {
namespace spreader {
class SpreaderUtils
{
public:
// finds the LegSpreaderParams for the leg specifies in arg 2
const static bts::spark::LegSpreaderParams& get_leg_params(const bts::spark::ExecutionStrategy& execution_strategy,
const bts::api::ContractLeg& this_leg)
{
auto it = execution_strategy.leg_params_map().find(this_leg.security().id());
bts_assert(it != execution_strategy.leg_params_map().end());
const bts::spark::LegSpreaderParams& rv = it->second;
return rv;
}
void static parse_order(const OrderState& order_state,
bool& filled,
bool& terminal_state,
bool& encountered_error)
{
filled = order_state.status == api::orderman::OrderStatus::OS_FILLED;
terminal_state = order_state.status == api::orderman::OrderStatus::OS_CANCELED ||
order_state.status == api::orderman::OrderStatus::OS_DONE ||
order_state.status == api::orderman::OrderStatus::OS_EXPIRED ||
order_state.status == api::orderman::OrderStatus::OS_FILLED ||
order_state.status == api::orderman::OrderStatus::OS_REJECTED ||
order_state.status == api::orderman::OrderStatus::OS_STOPPED;
encountered_error = !order_state.error_msg.empty();
}
};
}}