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

This commit is contained in:
Kevin Darby committed 2017-11-17 17:53:37 -05:00
commit bf6dfba165
16 files changed
+889 -92

No files matched your search

+47 -1
View File
@@ -130,6 +130,52 @@
"sourceFileMap": {
"/bts/": "${workspaceRoot}"
}
}
},
{
"name": "Docker Launch",
"type": "cppdbg",
"request": "launch",
"program": "/bts/build/gcc_debug/src/server/sparkd/sparkd",
"args": ["test"],
"stopAtEntry": false,
"cwd": "/bts/build/gcc_debug/src/server/sparkd",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": ["-p 2000","root@localhost"],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/bts/": "${workspaceRoot}"
}
},
{
"name": "Docker attach",
"type": "cppdbg",
"request": "attach",
"program": "/bts/build/gcc_debug/src/server/sparkd/sparkd",
"processId": "${command:pickRemoteProcess}",
"MIMode": "gdb",
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": ["-p 2000","root@localhost"],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/bts/": "${workspaceRoot}"
}
}
]
}
+1 -1
View File
@@ -20,7 +20,7 @@ namespace bts.core
if (inst.TryGetValue(tag, out ISubject<T> result)) {
return result;
}
result = new Subject<T>();
result = new ReplaySubject<T>(1);
inst[tag] = result;
return result;
}
@@ -0,0 +1,97 @@
using bts.api;
using bts.spark;
using mbts.co2;
using mbts.collections;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using static mbts.spark.SparkTags;
using mbts.collections.extensions;
using System.Collections.ObjectModel;
namespace mbts.spark {
internal class ContractPickerModel : ViewModelBase {
public ContractPickerModel(IBus bus) {
_bus = bus;
_subs.Add(_bus.subscribe(SecuritiesTag).Subscribe(on_securities_changed));
}
private readonly IBus _bus;
private IList<IDisposable> _subs = new List<IDisposable>();
internal void exchange_selection_changed(IEnumerable<Venue> exchanges)
{
selected_exchanges = exchanges.ToList();
symbols.sync_with(UserSymbol.get_all()
.Where(s => exchanges.Contains(s.exchange))
.Select(s => s.symbol)
.Distinct()
.ToList());
_update_securities();
}
internal void security_type_selection_changed(IEnumerable<SecurityType> security_types)
{
selected_security_types = security_types.ToList();
_update_securities();
}
internal void symbol_selection_changed(IEnumerable<string> symbols)
{
selected_symbols = symbols.ToList();
_update_securities();
}
private void on_securities_changed(IReadOnlyDictionary<uint, SecurityMD> changed_securities)
{
all_securities = changed_securities;
securities.sync_with(changed_securities
.Select(entry => entry.Value.security)
);
_update_securities();
}
public List<Venue> all_exchanges { get; } = new List<Venue> { Venue.Glbx, Venue.Cboe };//UserSymbol.get_all().Select(x => x.exchange).Distinct().ToList();
public List<Venue> selected_exchanges = new List<Venue>();
public IEnumerable<SecurityType> security_types { get; } = EnumHelper.get_values_except(SecurityType.Option, SecurityType.Unset);
public List<SecurityType> selected_security_types = new List<SecurityType>();
public ObservableCollection<string> symbols { get; } = new ObservableCollection<string>(UserSymbol.get_all().Select(s => s.symbol).Distinct());
public List<string> selected_symbols = new List<string>();
private IReadOnlyDictionary<uint, SecurityMD> all_securities = new Dictionary<uint, SecurityMD>();
public ObservableCollection<SecurityImmutable> securities { get; } = new ObservableCollection<SecurityImmutable>();
private void _update_securities()
{
securities.sync_with(all_securities
.Select(all => all.Value.security)
// exchange filtering
.Where(sec => selected_exchanges.Count == 0 || selected_exchanges
.Any(exchange => exchange == sec.Exchange))
// type filtering
.Where(sec => selected_security_types.Count == 0 || selected_security_types
.Any(sec_type => sec_type == sec.security_type()))
// symbol filtering
.Where(sec => selected_symbols.Count == 0 || selected_symbols
.Any(sym => sym == sec.Symbol))
);
}
public void Dispose()
{
Disposable.dispose(_subs);
}
}
}
@@ -0,0 +1,29 @@
<UserControl x:Class="mbts.spark.ContractPickerView"
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"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
x:ClassModifier="internal"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid Grid.IsSharedSizeScope="True" HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="share_col_width" Width="Auto" />
<ColumnDefinition SharedSizeGroup="share_col_width" Width="Auto" />
<ColumnDefinition SharedSizeGroup="share_col_width" Width="Auto" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Content="Exchanges"/>
<Label Grid.Row="0" Grid.Column="1" Content="Types"/>
<Label Grid.Row="0" Grid.Column="2" Content="Symbols"/>
<Label Grid.Row="0" Grid.Column="3" Content="Instruments"/>
<ListBox x:Name="_exchanges" Grid.Row ="1" Grid.Column="0" SelectionMode="Extended" ItemsSource="{Binding all_exchanges}" ></ListBox>
<ListBox x:Name="_security_types" Grid.Row ="1" Grid.Column="1" SelectionMode="Extended" ItemsSource="{Binding security_types}"></ListBox>
<ListBox x:Name="_symbols" Grid.Row ="1" Grid.Column="2" SelectionMode="Extended" ItemsSource="{Binding symbols}"></ListBox>
<ListBox x:Name="_securities" Grid.Row ="1" Grid.Column="3" SelectionMode="Extended" ItemsSource="{Binding securities}"></ListBox>
</Grid>
</UserControl>
@@ -0,0 +1,96 @@
using mbts.ui;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using bts.api;
using System.ComponentModel.Composition;
namespace mbts.spark
{
/// <summary>
/// Interaction logic for ContractPickerView.xaml
/// </summary>
partial class ContractPickerView : UserControl
{
public ContractPickerView(ContractPickerModel context)
{
InitializeComponent();
this.DataContext = context;
_exchanges.SelectionChanged += exchanges_changed;
_security_types.SelectionChanged += security_types_changed;
_symbols.SelectionChanged += symbols_changed;
}
private void symbols_changed(object sender, SelectionChangedEventArgs e)
{
((ContractPickerModel)DataContext).symbol_selection_changed(_symbols.SelectedItems.Cast<string>());
}
private void security_types_changed(object sender, SelectionChangedEventArgs e)
{
((ContractPickerModel)DataContext).security_type_selection_changed(_security_types.SelectedItems.Cast<SecurityType>());
}
private void exchanges_changed(object sender, SelectionChangedEventArgs e)
{
((ContractPickerModel)DataContext).exchange_selection_changed(_exchanges.SelectedItems.Cast<Venue>());
}
}
//[Export (typeof(IShellModule))]
public class TempModule : IShellModule {
private IBus _bus;
[ImportingConstructor]
public TempModule(IBus bus) {
_bus = bus;
}
public ImageSource icon => Icons.Abacus;
public string name => "test";
public int priority => 1;
public IShellWindow launch_ui => null;
public Task<IShellWindow> create(Stream load_stream) {
return null;
}
public void Dispose() {
//throw new NotImplementedException();
}
public void get_state(Stream save_here) {
//throw new NotImplementedException();
}
public void load_state(Stream state = null) {
//throw new NotImplementedException();
}
public void start() {
var x = new Window {
Content = new ContractPickerView(new ContractPickerModel(_bus))
};
x.Show();
}
}
}
@@ -32,6 +32,11 @@ namespace bts.api {
public int CompareTo(SecurityImmutable other) {
return Id.CompareTo(other.Id);
}
public override string ToString()
{
return this.ToString("");
}
public string ToString(string format, IFormatProvider formatProvider=null) {
return Format(this, string.IsNullOrEmpty(format) ? _standard_format : Parse(format));
}
@@ -132,7 +132,7 @@ const orderman::Book& SpreaderOrder::get_book(size_t leg_index) const
}
const LegPropertyData& SpreaderOrder::get_leg_data(size_t leg_index) const
{
return _bookkeeping_data.get_leg_data(leg_index).leg_property_data;
return _bookkeeping_data.get_leg_data(leg_index).leg_property_data();
}
void SpreaderOrder::_transform_to_START()
{
@@ -171,7 +171,7 @@ void SpreaderOrder::_cancel_orders(bool cancel_quotes, bool cancel_hedges)
SpreaderLegData& leg_data = _bookkeeping_data.get_leg_data(q_idx);
if (cancel_quotes)
{
if (leg_data.leg_property_data.is_active_quoting())
if (leg_data.leg_property_data().is_active_quoting())
leg_data.quoter().cancel_order();
}
if (cancel_hedges)
@@ -187,7 +187,7 @@ bool SpreaderOrder::_all_quoter_orders_in_terminal_state()
for (size_t q_idx = 0; q_idx < _bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& leg_data = _bookkeeping_data.get_leg_data(q_idx);
if (leg_data.leg_property_data.is_active_quoting())
if (leg_data.leg_property_data().is_active_quoting())
if (!leg_data.quoter().is_terminal_state())
return false;
}
@@ -233,7 +233,7 @@ bool SpreaderOrder::_quoters_can_accept_modification ()
for (size_t q_idx = 0; q_idx < _bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& leg_data = _bookkeeping_data.get_leg_data(q_idx);
if (leg_data.leg_property_data.is_active_quoting())
if (leg_data.leg_property_data().is_active_quoting())
if (!leg_data.quoter().accept_modifications())
return false;
}
@@ -247,9 +247,9 @@ void SpreaderOrder::_send_hedge(size_t filled_leg_index, Price filled_price, Qua
SpreaderLegData& leg_data = _bookkeeping_data.get_leg_data (hedge_leg_index);
_compute_hedge_price_quantity (filled_leg_index, filled_price, filled_quantity, hedge_leg_index,
hedge_price, hedge_quantity);
bts::orderman::SpreaderOrderBase::ChildOrder new_hedge_order = _get_new_order (leg_data.leg_property_data, false);
SpreaderHedgerData& hedger_data = leg_data.add_new_hedger (*this, new_hedge_order, hedge_price, hedge_quantity,leg_data.leg_property_data.trading_side);
hedger_data.hedger().init ();
bts::orderman::SpreaderOrderBase::ChildOrder new_hedge_order = _get_new_order (leg_data.leg_property_data(), false);
SpreaderHedgerData& hedger_data = leg_data.add_new_hedger (*this, new_hedge_order, hedge_price, hedge_quantity,leg_data.leg_property_data().trading_side());
hedger_data.hedger().init ();
}
void SpreaderOrder::_compute_hedge_price_quantity(size_t filled_leg_index,
Price fill_price, Quantity fill_quantity,
@@ -260,8 +260,8 @@ void SpreaderOrder::_compute_hedge_price_quantity(size_t filled_leg_index,
if (_bookkeeping_data.count() == 2)
{
SpreaderUtils::compute_hedge_price_size_2_legs (_bookkeeping_data.price(),
_bookkeeping_data.get_leg_data (filled_leg_index).leg_property_data, fill_price, fill_quantity,
_bookkeeping_data.get_leg_data (hedge_leg_index).leg_property_data, hedge_price, hedge_quantity);
_bookkeeping_data.get_leg_data (filled_leg_index).leg_property_data(), fill_price, fill_quantity,
_bookkeeping_data.get_leg_data (hedge_leg_index).leg_property_data(), hedge_price, hedge_quantity);
}
else
{
@@ -287,7 +287,7 @@ bts::orderman::SpreaderOrderBase::ChildOrder SpreaderOrder::_get_new_order (cons
bts::SecurityKey sec_key = bts::SecurityKey (leg_property_data.security_key());
api::Security const* db_sec = _db().resolve (sec_key);
api::orderman::ChildOrderKind order_type = is_quote_order ? api::orderman::ChildOrderKind::COK_SPREADER_QUOTING : api::orderman::ChildOrderKind::COK_SPREADER_HEDGING;
bts::orderman::SpreaderOrderBase::ChildFactory child_factory = get_child_factory(*db_sec, leg_property_data.trading_side, order_type);
bts::orderman::SpreaderOrderBase::ChildFactory child_factory = get_child_factory(*db_sec, leg_property_data.trading_side(), order_type);
return child_factory();
}
/*******************************************************************************/
@@ -90,7 +90,7 @@ void SpreaderWaitingForFirstConnStateWorker::_init_quoters ()
for (size_t index = 0; index < _spreader->_bookkeeping_data.count(); index++)
{
SpreaderLegData& leg_data = _spreader->_bookkeeping_data.get_leg_data(index);
if (leg_data.leg_property_data.is_active_quoting())
if (leg_data.leg_property_data().is_active_quoting())
leg_data.quoter().init();
}
}
@@ -126,7 +126,7 @@ void SpreaderWaitingForFirstConnStateWorker::_subscribe_to_marketdata()
for (size_t index = 0; index < _spreader->_bookkeeping_data.count(); index++)
{
SpreaderLegData& leg_data = _spreader->_bookkeeping_data.get_leg_data(index);
bts::SecurityKey leg_key = bts::SecurityKey (leg_data.leg_property_data.security_key());
bts::SecurityKey leg_key = bts::SecurityKey (leg_data.leg_property_data().security_key());
api::Security const* db_sec = _spreader->_db().resolve (leg_key);
_spreader->subscribe_to_md (*db_sec);
}
@@ -36,7 +36,7 @@ void SpreaderWorkingStateWorker::on_update(const api::orderman::UpdateSpreaderOr
for (size_t q_idx = 0; q_idx < _spreader->_bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& leg_data = _spreader->_bookkeeping_data.get_leg_data(q_idx);
if (leg_data.leg_property_data.is_active_quoting())
if (leg_data.leg_property_data().is_active_quoting())
leg_data.quoter().update_order_price_quantity (price, quantity);
}
}
@@ -57,8 +57,8 @@ void SpreaderWorkingStateWorker::on_book(TickToTradeCorID cid, const Book& book)
for (size_t q_idx = 0; q_idx < bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& d = bookkeeping_data.get_leg_data(q_idx);
if (d.leg_property_data.is_active_quoting())
d.quoter().on_book(cid, md_leg.leg_property_data.leg_index, book);
if (d.leg_property_data().is_active_quoting())
d.quoter().on_book(cid, md_leg.leg_property_data().leg_index(), book);
}
// send md to hedgers hedging this security only
for (size_t h_idx = 0; h_idx < md_leg.n_hedgers(); h_idx++)
@@ -70,7 +70,7 @@ void SpreaderWorkingStateWorker::on_time(const TimeStamp& ts)
for (size_t q_idx = 0; q_idx < bookkeeping_data.count(); q_idx++)
{
SpreaderLegData& leg_data = bookkeeping_data.get_leg_data(q_idx);
if (leg_data.leg_property_data.is_active_quoting())
if (leg_data.leg_property_data().is_active_quoting())
{
leg_data.quoter().on_time(ts);
for (size_t h_idx = 0; h_idx < leg_data.n_hedgers(); h_idx++)
@@ -99,14 +99,14 @@ void SpreaderWorkingStateWorker::on_quoter_order_fill(bts::orderman::SpreaderLeg
for (size_t q_idx = 0; q_idx < _spreader->_bookkeeping_data.count(); q_idx++)
{
bts::orderman::SpreaderLegData other_leg_data = _spreader->_bookkeeping_data.get_leg_data (q_idx);
if (q_idx != leg_data.leg_property_data.leg_index)
if (q_idx != leg_data.leg_property_data().leg_index())
{
// if it is an actively quoting leg, inform the quoter about it
// so it can decrease the proportional size
if (other_leg_data.leg_property_data.is_active_quoting())
other_leg_data.quoter().update_other_leg_fills(leg_data.leg_property_data.leg_index, filled_quantity);
if (other_leg_data.leg_property_data().is_active_quoting())
other_leg_data.quoter().update_other_leg_fills(leg_data.leg_property_data().leg_index(), filled_quantity);
// a hedge is sent regardless
_spreader->_send_hedge (leg_data.leg_property_data.leg_index, average_price, filled_quantity, q_idx);
_spreader->_send_hedge (leg_data.leg_property_data().leg_index(), average_price, filled_quantity, q_idx);
}
}
}
@@ -32,6 +32,32 @@ struct MySecDB : public securities::ISecurityDB
{return secs;}
};
class SpreaderManagerForTest : public ISpreaderManager
{
private:
std::vector<LegPropertyData> _legs;
std::vector<Book> _books;
public:
SpreaderManagerForTest (const std::vector<LegPropertyData> legs,
const std::vector<Book> books)
:
_legs (legs),
_books (books)
{
}
const bts::orderman::Book& get_book(size_t leg_index) const override
{
return _books[leg_index];
}
// the caller can keep a reference to the returned type forever. the
// data in the returned type is all const, so nothing will change
// beneath it
const LegPropertyData& get_leg_data(size_t leg_index) const override
{
return _legs[leg_index];
}
};
const char *fut1 =
"id: 1\n"
"symbol: \"ES\"\n"
@@ -179,8 +205,74 @@ const char *fut2 =
result.mutable_spreader()->MergeFrom(create_order);
return result;
}
/**********************************************************************/
/*****************creating sample data for tests***********************/
/**********************************************************************/
void fill_leg_spreader_params (bts::spark::LegSpreaderParams& sp, double price_multiplier, bool is_active_quoting, bts::spark::QuoteParams& qp)
{
sp.set_price_multiplier (price_multiplier);
sp.set_is_active_quoting (is_active_quoting);
sp.mutable_quote_params()->MergeFrom (qp);
void _fill_book(Book& book, double inside_market, double tick_size, uint16_t* sizes, bts::api::Side side)
}
void fill_quote_params (bts::spark::QuoteParams& qp, double lean_ratio)
{
qp.set_lean_quantity_ratio (lean_ratio);
}
void fill_future_security (Security& sec, uint32_t key, const std::string& symbol, Venue exchange,
uint32_t expiration_year, uint32_t expiration_month, uint32_t expiration_day,
double tick_size)
{
sec.set_id (key);
sec.set_symbol (symbol);
sec.set_exchange (exchange);
FutureContract fc;
fc.set_expiration_year(expiration_year);
fc.set_expiration_month(expiration_month);
fc.set_expiration_day(expiration_day);
sec.mutable_future()->MergeFrom (fc);
ContractSpecification c_spec;
c_spec.set_low_tick (tick_size);
c_spec.set_high_tick (tick_size);
sec.mutable_contract_spec()->MergeFrom (c_spec);
}
void fill_contract_leg (ContractLeg& leg, const Security& sec, double leg_quantity, Side side, double leg_delta)
{
leg.mutable_security()->MergeFrom (sec);
leg.set_quantity (leg_quantity);
leg.set_side (side);
leg.set_leg_delta (leg_delta);
}
void fill_future_contract_leg (ContractLeg& leg,
uint32_t key, const std::string& symbol, Venue exchange,
uint32_t year, uint32_t month, uint32_t day,
double leg_quantity, Side side, double leg_delta,
double tick_size)
{
Security sec;
fill_future_security (sec, key, symbol, exchange, year, month, day, tick_size);
fill_contract_leg (leg, sec, leg_quantity, side, leg_delta);
}
void fill_synthetic_contract (SyntheticContract& sc, const std::string& name, const std::vector<ContractLeg>& legs)
{
sc.set_name (name);
for (auto it = legs.begin(); it != legs.end(); it++)
sc.mutable_legs()->Add()->MergeFrom(*it);
}
void fill_execution_strategy (SyntheticExecutionStrategy& s_exs, const Security& sec, const std::vector<LegSpreaderParams>& leg_params)
{
size_t l_idx = 0;
ExecutionStrategy exs;
for (auto it = sec.synthetic().legs().begin(); it != sec.synthetic().legs().end(); it++)
{
const ContractLeg& leg = *it;
exs.mutable_leg_params_map()->insert(google::protobuf::MapPair<unsigned int, bts::spark::LegSpreaderParams>(leg.security().id(), leg_params[l_idx]));
l_idx++;
}
s_exs.mutable_security()->MergeFrom (sec);
s_exs.mutable_execution_strategy()->MergeFrom (exs);
}
void fill_book(Book& book, double inside_market, double tick_size, uint16_t* sizes, bts::api::Side side)
{
BookSide& bookside = book.side(side);
for (size_t i = 0; i < book.n_levels(); i++)
@@ -192,6 +284,35 @@ void _fill_book(Book& book, double inside_market, double tick_size, uint16_t* si
inside_market += tick_size;
}
}
void fill_book(Book& book, double* prices, uint16_t* sizes, bts::api::Side side)
{
BookSide& bookside = book.side(side);
for (size_t i = 0; i < book.n_levels(); i++)
bookside[i] = md2::PriceSize::from_double<2>(prices[i], sizes[i]);
}
void fill_book(Book& book, double* bid_prices, uint16_t* bid_sizes,
double* ask_prices, uint16_t* ask_sizes)
{
BookSide& bidside = book.side(api::Side::SIDE_BUY);
BookSide& askside = book.side(api::Side::SIDE_SELL);
for (size_t i = 0; i < book.n_levels(); i++)
{
bidside[i] = md2::PriceSize::from_double<2>(bid_prices[i], bid_sizes[i]);
askside[i] = md2::PriceSize::from_double<2>(ask_prices[i], ask_sizes[i]);
}
}
void fill_book_temp (std::vector<double>){}
/**********************************************************************/
/**************************misc helpers********************************/
/**********************************************************************/
double gen_rand (double min, double max)
{
double f = (double)rand() / RAND_MAX;
return min + f * (max - min);
}
/**********************************************************************/
/**********************************************************************/
/**********************************************************************/
// QuoteLegPriceQuantityState is used by the quoter
// to keep the state of the order state, ie
@@ -199,25 +320,416 @@ void _fill_book(Book& book, double inside_market, double tick_size, uint16_t* si
// filled qty
// reduced quantity due to other legs
// output price, qty
void test_QuoteLegPriceQuantityState ()
{
TEST_CASE ("quoter price quantity state", "[spreader]")
{
// construction
QuoteLegPriceQuantityState s (Price (-1.0), Quantity (200));
REQUIRE (s.target_spread_price() == Price (-1.0));
REQUIRE (s.target_leg_quantity() == Quantity (200));
REQUIRE (s.aggregated_filled_quantity() == Quantity (0));
REQUIRE (s.aggregated_hedged_reduction() == Quantity (0));
REQUIRE (s.remaining_to_fill() == Quantity (200));
REQUIRE (s.out_price() == Price (0.0));
REQUIRE (s.out_quantity() == Quantity (0));
// add fills
s.add_filled_quantity (Quantity(10));
s.add_filled_quantity (Quantity(15));
REQUIRE (s.target_spread_price() == Price (-1.0));
REQUIRE (s.target_leg_quantity() == Quantity (200));
REQUIRE (s.aggregated_filled_quantity() == Quantity (25));
REQUIRE (s.aggregated_hedged_reduction() == Quantity (0));
REQUIRE (s.remaining_to_fill() == Quantity (175));
REQUIRE (s.out_price() == Price (0.0));
REQUIRE (s.out_quantity() == Quantity (0));
// add hedged reduction
s.add_hedged_reduction (Quantity(15));
s.add_hedged_reduction (Quantity(5));
s.add_hedged_reduction (Quantity(30));
REQUIRE (s.target_spread_price() == Price (-1.0));
REQUIRE (s.target_leg_quantity() == Quantity (200));
REQUIRE (s.aggregated_filled_quantity() == Quantity (25));
REQUIRE (s.aggregated_hedged_reduction() == Quantity (50));
REQUIRE (s.remaining_to_fill() == Quantity (125));
REQUIRE (s.out_price() == Price (0.0));
REQUIRE (s.out_quantity() == Quantity (0));
// set out price and quantity
s.update_out_price_quantity (Price (-0.35), Quantity (123));
REQUIRE (s.target_spread_price() == Price (-1.0));
REQUIRE (s.target_leg_quantity() == Quantity (200));
REQUIRE (s.aggregated_filled_quantity() == Quantity (25));
REQUIRE (s.aggregated_hedged_reduction() == Quantity (50));
REQUIRE (s.remaining_to_fill() == Quantity (125));
REQUIRE (s.out_price() == Price (-0.35));
REQUIRE (s.out_quantity() == Quantity (123));
// change target price / quantity
s.update_target_leg_quantity (Quantity (105));
REQUIRE (s.target_spread_price() == Price (-1.0));
REQUIRE (s.target_leg_quantity() == Quantity (105));
REQUIRE (s.aggregated_filled_quantity() == Quantity (25));
REQUIRE (s.aggregated_hedged_reduction() == Quantity (50));
REQUIRE (s.remaining_to_fill() == Quantity (30));
REQUIRE (s.out_price() == Price (-0.35));
REQUIRE (s.out_quantity() == Quantity (123));
// make the hedges go over
s.add_hedged_reduction (Quantity(35));
REQUIRE (s.target_spread_price() == Price (-1.0));
REQUIRE (s.target_leg_quantity() == Quantity (105));
REQUIRE (s.aggregated_filled_quantity() == Quantity (25));
REQUIRE (s.aggregated_hedged_reduction() == Quantity (85));
REQUIRE (s.remaining_to_fill() == Quantity (0));
REQUIRE (s.out_price() == Price (-0.35));
REQUIRE (s.out_quantity() == Quantity (123));
// make the fills go over
s.add_filled_quantity (Quantity(15));
REQUIRE (s.target_spread_price() == Price (-1.0));
REQUIRE (s.target_leg_quantity() == Quantity (105));
REQUIRE (s.aggregated_filled_quantity() == Quantity (40));
REQUIRE (s.aggregated_hedged_reduction() == Quantity (85));
REQUIRE (s.remaining_to_fill() == Quantity (0));
REQUIRE (s.out_price() == Price (-0.35));
REQUIRE (s.out_quantity() == Quantity (123));
}
// tests spread_qty -> leg_qty and leg_2_qty -> leg_1_qty
void test_leg_quantity_normalization ()
{
TEST_CASE ("test_leg_quantity_normalization", "[spreader]")
{
int n_runs = 20;
for (int i = 0; i < n_runs; i++)
{
double leg_mult = gen_rand(-5.0, 2.0);
uint32_t spr_qty = gen_rand(0, 100);
std::string symbol = "ES";
ContractLeg leg;
fill_future_contract_leg (leg, 0, symbol, bts::api::Venue::VENUE_GLBX, 2018, 12, 15, leg_mult, api::Side::SIDE_BUY, 1.0, 0.25);
QuoteParams qp;
fill_quote_params(qp, 1.0);
LegSpreaderParams lsp;
fill_leg_spreader_params (lsp, 1.0, true, qp);
LegPropertyData leg_prop_data (0, leg, lsp, api::Side::SIDE_BUY);
double calc_value = SpreaderUtils::get_leg_quantity_from_spreader_quantity (leg_prop_data, Quantity (spr_qty)),
expected_value = std::round(std::abs(leg_mult * spr_qty));
REQUIRE (calc_value == expected_value);
}
for (int i = 0; i < n_runs; i++)
{
double leg_mult_1 = gen_rand(-5.0, 2.0),
leg_mult_2 = gen_rand(-5.0, 2.0);
uint32_t leg_qty = gen_rand(0, 100);
std::string symbol = "ES";
ContractLeg leg_1, leg_2;
fill_future_contract_leg (leg_1, 0, symbol, bts::api::Venue::VENUE_GLBX, 2017, 12, 15, leg_mult_1, api::Side::SIDE_BUY, 1.0, 0.25);
fill_future_contract_leg (leg_2, 1, symbol, bts::api::Venue::VENUE_GLBX, 2018, 3, 15, leg_mult_2, api::Side::SIDE_SELL, 1.0, 0.25);
QuoteParams qp_1, qp_2;
fill_quote_params(qp_1, 1.0);
fill_quote_params(qp_2, 1.0);
LegSpreaderParams lsp_1, lsp_2;
fill_leg_spreader_params (lsp_1, 1.0, true, qp_1);
fill_leg_spreader_params (lsp_2, 1.0, true, qp_2);
LegPropertyData leg_prop_data_1 (0, leg_1, lsp_1, api::Side::SIDE_BUY);
LegPropertyData leg_prop_data_2 (1, leg_2, lsp_2, api::Side::SIDE_BUY);
double calc_value = SpreaderUtils::get_equivelant_size (leg_prop_data_1, Quantity(leg_qty), leg_prop_data_2),
expected_value = std::round(std::abs(leg_qty * leg_mult_2 / leg_mult_1));
REQUIRE (calc_value == expected_value);
}
}
// given a qty, traverses the book to find the level
// where the accumulated qty >= given qty
void test_book_traversal ()
TEST_CASE ("book traversal", "[spreader]")
{
Price calc_price;
Quantity calc_quantity;
SECTION("test level 1 sell")
{
Book book;
uint16_t sizes[] = { 11, 13, 17, 19, 23 };
double prices[] = { 2500.25, 2500.50, 2501, 2502, 2503 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL);
SpreaderUtils::traverse_depth_for_quantity (book, bts::api::Side::SIDE_SELL, Quantity (7), calc_price, calc_quantity);
REQUIRE (calc_price == Price (2500.25));
REQUIRE (calc_quantity == Quantity (7));
SpreaderUtils::traverse_depth_for_quantity (book, bts::api::Side::SIDE_BUY, Quantity (7), calc_price, calc_quantity);
REQUIRE (calc_quantity == Quantity (0));
}
SECTION("test level 2 sell")
{
Book book;
uint16_t sizes[] = { 23, 1, 17, 19, 23 };
double prices[] = { 2500.25, 2500.75, 2501, 2502, 2503 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL);
SpreaderUtils::traverse_depth_for_quantity (book, bts::api::Side::SIDE_SELL, Quantity (24), calc_price, calc_quantity);
REQUIRE (calc_price == Price (2500.75));
REQUIRE (calc_quantity == Quantity (24));
SpreaderUtils::traverse_depth_for_quantity (book, bts::api::Side::SIDE_BUY, Quantity (7), calc_price, calc_quantity);
REQUIRE (calc_quantity == Quantity (0));
}
SECTION("test req_qty == book sell")
{
Book book;
uint16_t sizes[] = { 23, 1, 16, 33, 27 };
double prices[] = { 2500.25, 2500.75, 2501, 2502, 2503 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL);
SpreaderUtils::traverse_depth_for_quantity (book, bts::api::Side::SIDE_SELL, Quantity (100), calc_price, calc_quantity);
REQUIRE (calc_price == Price (2503));
REQUIRE (calc_quantity == Quantity (100));
SpreaderUtils::traverse_depth_for_quantity (book, bts::api::Side::SIDE_BUY, Quantity (7), calc_price, calc_quantity);
REQUIRE (calc_quantity == Quantity (0));
}
SECTION("test req_qty > book buy")
{
Book book;
uint16_t sizes[] = { 13, 11, 16, 33, 27 };
double prices[] = { 2500.25, 2500, 2499, 2498, 2497};
fill_book (book, prices, sizes, bts::api::Side::SIDE_BUY);
SpreaderUtils::traverse_depth_for_quantity (book, bts::api::Side::SIDE_BUY, Quantity (200), calc_price, calc_quantity);
REQUIRE (calc_price == Price (2497));
REQUIRE (calc_quantity == Quantity (100));
SpreaderUtils::traverse_depth_for_quantity (book, bts::api::Side::SIDE_SELL, Quantity (7), calc_price, calc_quantity);
REQUIRE (calc_quantity == Quantity (0));
}
SECTION("test_5 buy")
{
// empty book
Book book;
uint16_t sizes[] = { 0, 0, 0, 0, 0 };
double prices[] = { 2500.00, 2500.25, 2500.50, 2500.75, 2501 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_BUY);
SpreaderUtils::traverse_depth_for_quantity (book, bts::api::Side::SIDE_BUY, Quantity (1), calc_price, calc_quantity);
REQUIRE (calc_quantity == Quantity (0));
SpreaderUtils::traverse_depth_for_quantity (book, bts::api::Side::SIDE_SELL, Quantity (7), calc_price, calc_quantity);
REQUIRE (calc_quantity == Quantity (0));
}
}
void verify_leg_data (SpreaderLegData& l, OrderKey order_key, size_t leg_index, uint32_t sec_key, uint32_t exp_yr, uint32_t exp_m, uint32_t exp_day, const std::string& symbol, double leg_mult, double price_mult, api::Side side)
{
REQUIRE(l.order_key() == order_key);
REQUIRE(l.leg_property_data().leg_index() == leg_index);
REQUIRE(l.leg_property_data().security_key() == sec_key);
REQUIRE(l.leg_property_data().leg_contract().security().future().expiration_year() == exp_yr);
REQUIRE(l.leg_property_data().leg_contract().security().future().expiration_month() == exp_m);
REQUIRE(l.leg_property_data().leg_contract().security().future().expiration_day() == exp_day);
REQUIRE(l.leg_property_data().leg_contract().security().symbol() == symbol);
REQUIRE(l.leg_property_data().size_multiplier() == leg_mult);
REQUIRE(l.leg_property_data().price_multiplier() == price_mult);
REQUIRE(l.leg_property_data().trading_side() == side);
}
// this is how the spreader organizes the data
void test_SpreaderBookkeepingData ()
TEST_CASE ("spreader bookkeeping data", "[spreader]")
{
// constants
double leg_mult_1 = -1.25, leg_mult_2 = 3.33, leg_mult_3 = -1.75;
std::string symbol_1 = "ES", symbol_2 = "ZN", symbol_3 = "GC";
uint32_t sec_key_1 = 1111, sec_key_2 = 2222, sec_key_3 = 3333;
double lean_ratio_1 = 1.33, lean_ratio_2 = 5.0, lean_ratio_3 = 2.75;
double price_mult_1 = -2.5, price_mult_2 = 5.0, price_mult_3 = -3.33;
Price spread_price (-0.35);
Quantity spread_quantity (125);
OrderKey order_key_1 (4), order_key_2 (22), order_key_3 (2007);
// leg property data
ContractLeg leg_1, leg_2, leg_3;
fill_future_contract_leg (leg_1, sec_key_1, symbol_1, bts::api::Venue::VENUE_GLBX, 2017, 12, 15, leg_mult_1, api::Side::SIDE_SELL, 1.0, 0.25);
fill_future_contract_leg (leg_2, sec_key_2, symbol_2, bts::api::Venue::VENUE_GLBX, 2018, 3, 15, leg_mult_2, api::Side::SIDE_BUY, 1.0, 0.03125);
fill_future_contract_leg (leg_3, sec_key_3, symbol_3, bts::api::Venue::VENUE_GLBX, 2018, 6, 15, leg_mult_3, api::Side::SIDE_SELL, 1.0, 0.05);
QuoteParams qp_1, qp_2, qp_3;
fill_quote_params(qp_1, lean_ratio_1);
fill_quote_params(qp_2, lean_ratio_2);
fill_quote_params(qp_3, lean_ratio_3);
LegSpreaderParams lsp_1, lsp_2, lsp_3;
fill_leg_spreader_params (lsp_1, price_mult_1, true, qp_1);
fill_leg_spreader_params (lsp_2, price_mult_2, true, qp_2);
fill_leg_spreader_params (lsp_3, price_mult_3, true, qp_3);
LegPropertyData leg_prop_data_1 (0, leg_1, lsp_1, api::Side::SIDE_SELL);
LegPropertyData leg_prop_data_2 (1, leg_2, lsp_2, api::Side::SIDE_BUY);
LegPropertyData leg_prop_data_3 (2, leg_3, lsp_3, api::Side::SIDE_SELL);
Book book1, book2, book3;
// SpreaderManager
std::vector<LegPropertyData> legs;
legs.push_back (leg_prop_data_1);legs.push_back (leg_prop_data_2);legs.push_back (leg_prop_data_3);
std::vector<Book> books;
books.push_back (book1);books.push_back (book2);books.push_back (book3);
SpreaderManagerForTest spreader_manager (legs, books);
// quoter
SingleLegQuoter quoter_1 (spreader_manager, leg_prop_data_1, 3, spread_price , spread_quantity, bts::orderman::SpreaderOrderBase::ChildOrder());
SingleLegQuoter quoter_2 (spreader_manager, leg_prop_data_2, 3, spread_price , spread_quantity, bts::orderman::SpreaderOrderBase::ChildOrder());
SingleLegQuoter quoter_3 (spreader_manager, leg_prop_data_3, 3, spread_price , spread_quantity, bts::orderman::SpreaderOrderBase::ChildOrder());
// bookkeeping data
std::vector<SpreaderLegData> leg_data_v;
leg_data_v.push_back (SpreaderLegData (leg_prop_data_1, quoter_1, order_key_1));
leg_data_v.push_back (SpreaderLegData (leg_prop_data_2, quoter_2, order_key_2));
leg_data_v.push_back (SpreaderLegData (leg_prop_data_3, quoter_3, order_key_3));
SpreaderBookkeepingData bookkeeping_data (leg_data_v, spread_price, spread_quantity);
SECTION("verify security key access")
{
SpreaderLegData res_3 = bookkeeping_data.get_leg_data (SecurityKey (sec_key_3));
verify_leg_data (res_3, order_key_3, 2, sec_key_3, 2018, 6, 15, symbol_3, leg_mult_3, price_mult_3, api::Side::SIDE_SELL);
SpreaderLegData res_2 = bookkeeping_data.get_leg_data (SecurityKey (sec_key_2));
verify_leg_data (res_2, order_key_2, 1, sec_key_2, 2018, 3, 15, symbol_2, leg_mult_2, price_mult_2, api::Side::SIDE_BUY);
SpreaderLegData res_1 = bookkeeping_data.get_leg_data (SecurityKey (sec_key_1));
verify_leg_data (res_1, order_key_1, 0, sec_key_1, 2017, 12, 15, symbol_1, leg_mult_1, price_mult_1, api::Side::SIDE_SELL);
}
SECTION("verify index access")
{
SpreaderLegData res_3 = bookkeeping_data.get_leg_data (2);
verify_leg_data (res_3, order_key_3, 2, sec_key_3, 2018, 6, 15, symbol_3, leg_mult_3, price_mult_3, api::Side::SIDE_SELL);
SpreaderLegData res_2 = bookkeeping_data.get_leg_data (1);
verify_leg_data (res_2, order_key_2, 1, sec_key_2, 2018, 3, 15, symbol_2, leg_mult_2, price_mult_2, api::Side::SIDE_BUY);
SpreaderLegData res_1 = bookkeeping_data.get_leg_data (0);
verify_leg_data (res_1, order_key_1, 0, sec_key_1, 2017, 12, 15, symbol_1, leg_mult_1, price_mult_1, api::Side::SIDE_SELL);
}
SECTION("verify order key access")
{
SpreaderLegData* res_3 = bookkeeping_data.find_leg_from_quoter_orderkey (order_key_3);
REQUIRE (res_3 != nullptr);
verify_leg_data (*res_3, order_key_3, 2, sec_key_3, 2018, 6, 15, symbol_3, leg_mult_3, price_mult_3, api::Side::SIDE_SELL);
SpreaderLegData* res_2 = bookkeeping_data.find_leg_from_quoter_orderkey (order_key_2);
REQUIRE (res_2 != nullptr);
verify_leg_data (*res_2, order_key_2, 1, sec_key_2, 2018, 3, 15, symbol_2, leg_mult_2, price_mult_2, api::Side::SIDE_BUY);
SpreaderLegData* res_1 = bookkeeping_data.find_leg_from_quoter_orderkey (order_key_1);
REQUIRE (res_1 != nullptr);
verify_leg_data (*res_1, order_key_1, 0, sec_key_1, 2017, 12, 15, symbol_1, leg_mult_1, price_mult_1, api::Side::SIDE_SELL);
}
}
LegPropertyData create_leg_property_data (const ContractLeg& leg,
size_t leg_index, double price_multiplier, bool is_active_quoting, double lean_mult)
{
QuoteParams qp;
fill_quote_params(qp, lean_mult);
LegSpreaderParams lsp;
fill_leg_spreader_params (lsp, price_multiplier, is_active_quoting, qp);
return LegPropertyData (leg_index, leg, lsp, leg.side());
}
// quote price and quantity for a 2 legged spread
void test_quote_price_quantity_2_legged()
{
TEST_CASE ("compute quoting price quantity 2 legs", "[spreader]")
{
Price spreader_price (1.0); Quantity spreader_quantity (10);
Price out_price; Quantity out_quantity;
// simple buy 1 sell 1 spreader (same ratio)
ContractLeg leg_1, leg_2;
SECTION("basic ")
{
fill_future_contract_leg (leg_1, 0, "ES", bts::api::Venue::VENUE_GLBX, 2017, 12, 15, 1, api::Side::SIDE_BUY, 1.0, 0.25);
fill_future_contract_leg (leg_2, 0, "ES", bts::api::Venue::VENUE_GLBX, 2017, 3, 15, -1, api::Side::SIDE_SELL, 1.0, 0.25);
LegPropertyData leg_prop_data_1 = create_leg_property_data (leg_1, 0, 1.0, true, 2.0);
LegPropertyData leg_prop_data_2 = create_leg_property_data (leg_2, 1, -1.0, true, 2.0);
// md
Book book_1, book_2;
double bid_prices_1[] = {2500.0, 2499.75, 2499.5, 2499, 2498};
uint16_t bid_sizes_1[] = {11, 25, 45, 6, 99};
double ask_prices_1[] = {2500.25, 2500.50, 2500.75, 2501, 2502};
uint16_t ask_sizes_1[] = {13, 12, 45, 5, 15};
double bid_prices_2[] = {2505.0, 2504.75, 2504, 2503.00, 2502.75};
uint16_t bid_sizes_2[] = {1, 4, 5, 20, 20};
double ask_prices_2[] = {2505.25, 2506.50, 2507, 2507.5, 2508};
uint16_t ask_sizes_2[] = {10, 4, 6, 20, 15};
fill_book (book_1, bid_prices_1, bid_sizes_1, ask_prices_1, ask_sizes_1);
fill_book (book_2, bid_prices_2, bid_sizes_2, ask_prices_2, ask_sizes_2);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, spreader_quantity, leg_prop_data_1, leg_prop_data_2, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 2504.00);
REQUIRE (out_quantity.value() == 10);
}
SECTION("lean mult")
{
spreader_quantity = Quantity(5);
spreader_price = Price (-0.5);
double lean_mult = 1.0;
fill_future_contract_leg (leg_1, 0, "ES", bts::api::Venue::VENUE_GLBX, 2017, 12, 15, 1, api::Side::SIDE_BUY, 1.0, 0.25);
fill_future_contract_leg (leg_2, 0, "ES", bts::api::Venue::VENUE_GLBX, 2017, 3, 15, -1, api::Side::SIDE_SELL, 1.0, 0.25);
LegPropertyData leg_prop_data_1 = create_leg_property_data (leg_1, 0, 1.0, true, 1.0);
LegPropertyData leg_prop_data_2 = create_leg_property_data (leg_2, 1, -1.0, true, lean_mult);
// md
Book book_2;
double bid_prices_2[] = {2505.0, 2504.75, 2504, 2503.00, 2502.75}; uint16_t bid_sizes_2[] = {5, 10, 5, 10, 20};
double ask_prices_2[] = {2505.25, 2506.50, 2507, 2507.5, 2508}; uint16_t ask_sizes_2[] = {0, 0, 0, 0, 0};
fill_book (book_2, bid_prices_2, bid_sizes_2, ask_prices_2, ask_sizes_2);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, spreader_quantity, leg_prop_data_1, leg_prop_data_2, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 2504.5);
REQUIRE (out_quantity.value() == 5);
// changing lean mult
lean_mult = 2.0;
LegPropertyData leg_prop_data_2_lm_2 = create_leg_property_data (leg_2, 1, -1.0, true, lean_mult);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, spreader_quantity, leg_prop_data_1, leg_prop_data_2_lm_2, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 2504.25);
REQUIRE (out_quantity.value() == 5);
lean_mult = 5.0;
LegPropertyData leg_prop_data_2_lm_5 = create_leg_property_data (leg_2, 1, -1.0, true, lean_mult);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, spreader_quantity, leg_prop_data_1, leg_prop_data_2_lm_5, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 2502.5);
REQUIRE (out_quantity.value() == 5);
lean_mult = 9.0;
LegPropertyData leg_prop_data_2_lm_9 = create_leg_property_data (leg_2, 1, -1.0, true, lean_mult);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, spreader_quantity, leg_prop_data_1, leg_prop_data_2_lm_9, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 2502.25);
REQUIRE (out_quantity.value() == 5);
lean_mult = 10.0;
LegPropertyData leg_prop_data_2_lm_10 = create_leg_property_data (leg_2, 1, -1.0, true, lean_mult);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, spreader_quantity, leg_prop_data_1, leg_prop_data_2_lm_10, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 2502.25);
REQUIRE (out_quantity.value() == 5);
// with a large lean mult, make the leg 2 qty req exhaust the book
lean_mult = 20.0;
LegPropertyData leg_prop_data_2_lm_20 = create_leg_property_data (leg_2, 1, -1.0, true, lean_mult);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, spreader_quantity, leg_prop_data_1, leg_prop_data_2_lm_20, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 2502.25);
REQUIRE (out_quantity.value() == 2);
// fractional leg mults
lean_mult = 1.5;
LegPropertyData leg_prop_data_2_lm_1_5 = create_leg_property_data (leg_2, 1, -1.0, true, lean_mult);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, spreader_quantity, leg_prop_data_1, leg_prop_data_2_lm_1_5, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 2504.25);
REQUIRE (out_quantity.value() == 5);
lean_mult = 4.3333;
LegPropertyData leg_prop_data_2_lm_3_33 = create_leg_property_data (leg_2, 1, -1.0, true, lean_mult);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, spreader_quantity, leg_prop_data_1, leg_prop_data_2_lm_3_33, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 2502.5);
REQUIRE (out_quantity.value() == 5);
}
SECTION("fractional leg mult ")
{
spreader_quantity = Quantity(10);
spreader_price = Price (0.5);
double mult_1 = 0.25, mult_2 = -1.1; // same used for price and qty
double lean_mult = 1.0;
fill_future_contract_leg (leg_1, 0, "ES", bts::api::Venue::VENUE_GLBX, 2017, 12, 15, mult_1, api::Side::SIDE_BUY, 1.0, 0.25);
fill_future_contract_leg (leg_2, 0, "ES", bts::api::Venue::VENUE_GLBX, 2017, 3, 15, mult_2, api::Side::SIDE_SELL, 1.0, 0.25);
LegPropertyData leg_prop_data_1 = create_leg_property_data (leg_1, 0, mult_1, true, lean_mult);
LegPropertyData leg_prop_data_2 = create_leg_property_data (leg_2, 1, mult_2, true, lean_mult);
// md
Book book_1, book_2;
double bid_prices_2[] = {2500.0, 2499.75, 2499.5, 2499, 2498};uint16_t bid_sizes_2[] = {5, 4, 1, 6, 99};
double ask_prices_2[] = {2500.25, 2500.50, 2500.75, 2501, 2502};uint16_t ask_sizes_2[] = {13, 12, 45, 5, 15};
fill_book (book_2, bid_prices_2, bid_sizes_2, ask_prices_2, ask_sizes_2);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, Quantity(3), leg_prop_data_1, leg_prop_data_2, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 10997.5);
REQUIRE (out_quantity.value() == 3);
}
SECTION("price mult")
{
spreader_quantity = Quantity(10);
spreader_price = Price (0.5);
double size_mult_1 = 0.25, size_mult_2 = -1.1, // same used for price and qty
price_mult_1 = 0.35, price_mult_2 = -1.5;
double lean_mult = 1.0;
fill_future_contract_leg (leg_1, 0, "ES", bts::api::Venue::VENUE_GLBX, 2017, 12, 15, size_mult_1, api::Side::SIDE_BUY, 1.0, 0.25);
fill_future_contract_leg (leg_2, 0, "ES", bts::api::Venue::VENUE_GLBX, 2017, 3, 15, size_mult_2, api::Side::SIDE_SELL, 1.0, 0.25);
LegPropertyData leg_prop_data_1 = create_leg_property_data (leg_1, 0, price_mult_1, true, lean_mult);
LegPropertyData leg_prop_data_2 = create_leg_property_data (leg_2, 1, price_mult_2, true, lean_mult);
// md
Book book_1, book_2;
double bid_prices_2[] = {2500.0, 2499.75, 2499.5, 2499, 2498};uint16_t bid_sizes_2[] = {5, 4, 1, 6, 99};
double ask_prices_2[] = {2500.25, 2500.50, 2500.75, 2501, 2502};uint16_t ask_sizes_2[] = {13, 12, 45, 5, 15};
fill_book (book_2, bid_prices_2, bid_sizes_2, ask_prices_2, ask_sizes_2);
SpreaderUtils::compute_price_quantity_2_legs (spreader_price, Quantity(3), leg_prop_data_1, leg_prop_data_2, book_2, out_price, out_quantity);
REQUIRE (out_price.value() == 10711.25);
REQUIRE (out_quantity.value() == 3);
}
}
// hedge price and quantity for a 2 legged spread
void test_hedge_price_quantity_2_legged()
@@ -253,7 +765,7 @@ void disabled_temp()
db.secs[SecurityKey(sec2.second.id())] = &sec2.second;
SECTION("test")
{
{
api::orderman::CreateOrderRequest cor = make_spreader_order_create_request (api::Side::SIDE_BUY, Price (0), Quantity (100));
/*****************Creating the order********************/
SpreaderOrder order (db,factory,OrderKey(1),cor);
@@ -277,7 +789,7 @@ void disabled_temp()
/*********************Market*********************/
Book book;
uint16_t book_sizes_1[] = { 11, 13, 17, 19, 23 };
_fill_book (book, 2500, 0.25, book_sizes_1, bts::api::Side::SIDE_SELL);
fill_book (book, 2500, 0.25, book_sizes_1, bts::api::Side::SIDE_SELL);
book = Book (bts::SecurityKey(cor.spreader().security().synthetic().legs(0).security().id()), book.side (api::Side::SIDE_BUY), book.side (api::Side::SIDE_SELL));
for (int i = 0; i < 100; i++)
{
+20 -15
View File
@@ -9,30 +9,35 @@ namespace orderman {
// between the Spreader, SingleLegQuoter and SingleFillHedger
class LegPropertyData
{
private:
const size_t _leg_index;
const bts::api::ContractLeg _leg_contract;
const bts::spark::LegSpreaderParams _leg_params;
const api::Side _trading_side;
public:
const size_t leg_index;
const bts::api::ContractLeg leg_contract;
const bts::spark::LegSpreaderParams leg_params;
const api::Side trading_side;
LegPropertyData(size_t leg_index_arg,
const bts::api::ContractLeg& leg_contract_arg,
const bts::spark::LegSpreaderParams& leg_params_arg,
api::Side trading_side_arg)
:
// copying the values via copy cons
leg_index(leg_index_arg),
leg_contract(leg_contract_arg),
leg_params(leg_params_arg),
trading_side(trading_side_arg)
_leg_index(leg_index_arg),
_leg_contract(leg_contract_arg),
_leg_params(leg_params_arg),
_trading_side(trading_side_arg)
{
}
uint32_t security_key() const { return leg_contract.security().id(); } // TODO: use seckey
//const bts::SecurityKey& security_key() const {return bts::SecurityKey (leg_contract.security().id());}
const bts::api::Security& security() const { return leg_contract.security(); }
double price_multiplier() const { return leg_params.price_multiplier(); }
double size_multiplier() const { return leg_contract.quantity(); }
double tick_size() const { return leg_contract.security().contract_spec().low_tick(); }
bool is_active_quoting() const {return leg_params.is_active_quoting();}
size_t leg_index() const {return _leg_index;}
const bts::api::ContractLeg& leg_contract() const {return _leg_contract;}
const bts::spark::LegSpreaderParams& leg_params () const {return _leg_params;}
api::Side trading_side() const {return _trading_side;}
uint32_t security_key() const { return _leg_contract.security().id(); } // TODO: use seckey
//const bts::SecurityKey& security_key() const {return bts::SecurityKey (_leg_contract.security().id());}
const bts::api::Security& security() const { return _leg_contract.security(); }
double price_multiplier() const { return _leg_params.price_multiplier(); }
double size_multiplier() const { return _leg_contract.quantity(); }
double tick_size() const { return _leg_contract.security().contract_spec().low_tick(); }
bool is_active_quoting() const {return _leg_params.is_active_quoting();}
};
}}
@@ -92,7 +92,7 @@ void SingleLegQuoter::_compute_price_quantity(Price& price, Quantity& quantity)
{
if (_two_legged)
{
size_t other_leg_index = _this_leg_data.leg_index == 0 ? 1 : 0;
size_t other_leg_index = _this_leg_data.leg_index() == 0 ? 1 : 0;
SpreaderUtils::compute_price_quantity_2_legs (_price_quantity_state.target_spread_price(), _price_quantity_state.target_leg_quantity(),
_this_leg_data, _spreader.get_leg_data(other_leg_index), _spreader.get_book(other_leg_index),
price, quantity);
@@ -104,15 +104,15 @@ void SingleLegQuoter::_compute_price_quantity_n_legs(Price& price, Quantity& qua
size_t min_quoter_leg_quantity_index = 0;
for (size_t idx = 0; idx < _n_spreader_legs; idx++)
{
if (idx != _this_leg_data.leg_index)
if (idx != _this_leg_data.leg_index())
{
const orderman::Book& other_leg_book = _spreader.get_book(idx);
const LegPropertyData& other_leg_data = _spreader.get_leg_data(idx);
Price other_leg_calc_price; Quantity other_leg_calc_quantity, this_leg_calc_quantity;
Quantity this_leg_target_quantity = _price_quantity_state.remaining_to_fill();
double other_leg_total_lean_ratio = other_leg_data.leg_params.quote_params().lean_quantity_ratio() * other_leg_data.size_multiplier() / _this_leg_data.size_multiplier();
double other_leg_total_lean_ratio = other_leg_data.leg_params().quote_params().lean_quantity_ratio() * other_leg_data.size_multiplier() / _this_leg_data.size_multiplier();
double other_leg_target_quantity = this_leg_target_quantity.value() * other_leg_total_lean_ratio;
SpreaderUtils::traverse_depth_for_quantity(other_leg_book, SpreaderUtils::invert_side (other_leg_data.trading_side), Quantity(other_leg_target_quantity), other_leg_calc_price, other_leg_calc_quantity);
SpreaderUtils::traverse_depth_for_quantity(other_leg_book, SpreaderUtils::invert_side (other_leg_data.trading_side()), Quantity(other_leg_target_quantity), other_leg_calc_price, other_leg_calc_quantity);
this_leg_calc_quantity = Quantity(static_cast<uint32_t>(1.0 /*TODOit->lean_ratio*/ * other_leg_calc_quantity.value()));
PQPair& leg_price_quantity = _aux_comp_data.at(idx);
leg_price_quantity.set(other_leg_calc_price, other_leg_calc_quantity, this_leg_calc_quantity);
@@ -128,7 +128,7 @@ Price SingleLegQuoter::_compute_leg_price_n_legs(const std::vector<PQPair>& leg_
double sum = 0;
for (size_t idx = 0; idx < _n_spreader_legs; idx++)
{
if (idx != _this_leg_data.leg_index)
if (idx != _this_leg_data.leg_index())
{
const PQPair& leg_pq_pair = leg_values[idx];
const LegPropertyData& leg_data = _spreader.get_leg_data (idx);
@@ -30,7 +30,7 @@ public:
_quantity (quantity)
{
for (auto it = leg_data.begin(); it != leg_data.end(); ++it)
_sec_key_to_index.insert(std::pair<uint32_t, size_t>(it->leg_property_data.security_key(), it->leg_property_data.leg_index));
_sec_key_to_index.insert(std::pair<uint32_t, size_t>(it->leg_property_data().security_key(), it->leg_property_data().leg_index()));
}
SpreaderLegData& get_leg_data (SecurityKey security_key)
{
@@ -49,11 +49,10 @@ public:
return _leg_data[index];
}
size_t count() { return _leg_data.size(); }
SpreaderLegData* find_leg_from_quoter_orderkey(orderman::OrderKey order_key)
{
for (auto q_it = _leg_data.begin(); q_it != _leg_data.end(); q_it++)
if (q_it->leg_property_data.is_active_quoting())
if (q_it->leg_property_data().is_active_quoting())
if (q_it->order_key() == order_key)
return &(*q_it);
return nullptr;
+9 -9
View File
@@ -18,9 +18,8 @@ namespace orderman{
// their state
class SpreaderLegData
{
public:
const LegPropertyData leg_property_data;
private:
const LegPropertyData _leg_property_data;
SingleLegQuoter _quoter;
orderman::Book _book;
SpreaderOrderUpdateMessage _order_update_message;
@@ -30,17 +29,15 @@ public:
SingleLegQuoter quoter_arg,
orderman::OrderKey order_key)
:
leg_property_data(leg_property_data_arg),
_leg_property_data(leg_property_data_arg),
_quoter (quoter_arg),
_book(),
_order_update_message (SpreaderOrderUpdateMessage (order_key)),
_hedger_data_vector() {}
// accessors
const LegPropertyData& leg_property_data() const {return _leg_property_data;}
SingleLegQuoter& quoter() {return _quoter;}
const orderman::Book& book () const {return _book;}
// called for every book update. the values
// are copied by value
void set_book(const orderman::Book& book_arg) {_book = book_arg;}
const orderman::Book& book () const {return _book;}
SpreaderOrderUpdateMessage& order_update_message () {return _order_update_message;}
orderman::OrderKey order_key() {return _order_update_message.order_key;}
// returns the number of active hedgers
@@ -55,6 +52,9 @@ public:
return &(*h_it);
return nullptr;
}
// mutators
// called for every book update (copied by value)
void set_book(const orderman::Book& book_arg) {_book = book_arg;}
// adds a new hedger with the given values
SpreaderHedgerData& add_new_hedger(ISpreaderManager& spreader_manager,
bts::orderman::SpreaderOrderBase::ChildOrder order,
@@ -63,7 +63,7 @@ public:
api::Side hedge_side)
{
SpreaderOrderUpdateMessage hedger_order_update (order.order_key());
SingleFillHedger hedger(spreader_manager, leg_property_data, order, hedge_price, hedge_quantity, hedge_side);
SingleFillHedger hedger(spreader_manager, _leg_property_data, order, hedge_price, hedge_quantity, hedge_side);
SpreaderHedgerData hedger_data(hedger, hedger_order_update);
_hedger_data_vector.push_back(hedger_data);
return _hedger_data_vector.back();
+32 -24
View File
@@ -3,6 +3,7 @@
#include <boost/container/flat_map.hpp>
#include "lib/config/protos/MarketData.pb.h"
#include "lib/md/Structure/PriceSize.h"
#include "lib/domain_model/Security.h"
#include "server/sparkd/orderman/md/Book.h"
#include "server/sparkd/spreader/LegPropertyData.h"
#include "server/sparkd/spreader/QuoteLegPriceQuantityState.h"
@@ -78,24 +79,6 @@ public:
}
bts_assert(false);
}
// finds the size of the target leg based on the size of the source leg
// (to keep their relative ratios intact)
// ex: for a spread s1.l1+s2.l2, size N in l2 (so l2 is the source)
// corresponds to s1 * N / s2 size on l1 (target).
// so if we get an N lot fill in l2, we send a hedge on l1
// sized s1 * N / s2
static double get_equivelant_size (const LegPropertyData& source_leg, Quantity source_leg_quantity,
const LegPropertyData& target_leg)
{
return target_leg.size_multiplier () * source_leg_quantity.value () / source_leg.size_multiplier ();
}
// given the quantity of the spreader order, determines the quality
// of the leg
static double get_leg_quantity_from_spreader_quantity(const LegPropertyData& leg, Quantity spreader_order_quantity)
{
return leg.size_multiplier () * spreader_order_quantity.value();
}
/**********************************************************************/
/*******************************Orders*********************************/
/**********************************************************************/
@@ -196,8 +179,29 @@ public:
return false;
}
/**********************************************************************/
/**********************Quoting Pricing Calculation*********************/
/**************************Price/Size Calculation**********************/
/**********************************************************************/
// finds the size of the target leg based on the size of the source leg
// (to keep their relative ratios intact)
// ex: for a spread s1.l1+s2.l2, size N in l2 (so l2 is the source)
// corresponds to s1 * N / s2 size on l1 (target).
// so if we get an N lot fill in l2, we send a hedge on l1
// sized s1 * N / s2
static double get_equivelant_size (const LegPropertyData& source_leg, Quantity source_leg_quantity,
const LegPropertyData& target_leg)
{
double rv = std::abs(target_leg.size_multiplier () * source_leg_quantity.value () / source_leg.size_multiplier ());
rv = std::round(rv);
return rv;
}
// given the quantity of the spreader order, determines the quality
// of the leg
static double get_leg_quantity_from_spreader_quantity(const LegPropertyData& leg, Quantity spreader_order_quantity)
{
double rv = std::abs (leg.size_multiplier () * spreader_order_quantity.value());
rv = std::round (rv);
return rv;
}
// calculates the computed price and quantity for a quoting
// leg given the data for the other leg
static void compute_price_quantity_2_legs(Price target_spread_price, Quantity this_leg_target_quantity,
@@ -209,11 +213,15 @@ public:
// from traversing the other book, for the requires size
Price other_leg_price; Quantity other_leg_quantity;
// this is the size ratio of the other leg vs this leg
double size_ratio = abs(other_leg_data.size_multiplier() / this_leg_data.size_multiplier());
double other_leg_target_quantity = size_ratio * other_leg_data.leg_params.quote_params().lean_quantity_ratio() * this_leg_target_quantity.value();
SpreaderUtils::traverse_depth_for_quantity(other_leg_book, SpreaderUtils::invert_side (other_leg_data.trading_side), Quantity(other_leg_target_quantity), other_leg_price, other_leg_quantity);
quantity = Quantity (static_cast<double>(other_leg_quantity.value())/size_ratio);
price = Price((target_spread_price.value() - other_leg_price.value() * other_leg_data.price_multiplier())/this_leg_data.price_multiplier());
double effective_mult = other_leg_data.leg_params().quote_params().lean_quantity_ratio() * abs(other_leg_data.size_multiplier() / this_leg_data.size_multiplier());
// to be conservative round the required size up
double other_leg_target_quantity = std::round(effective_mult * this_leg_target_quantity.value());
SpreaderUtils::traverse_depth_for_quantity(other_leg_book, SpreaderUtils::invert_side (other_leg_data.trading_side()), Quantity(other_leg_target_quantity), other_leg_price, other_leg_quantity);
double out_quantity = std::round(other_leg_quantity.value() / effective_mult);
quantity = Quantity (out_quantity);
double out_price = (target_spread_price.value() - other_leg_price.value() * other_leg_data.price_multiplier())/this_leg_data.price_multiplier();
out_price = bts::securities::raw_round_to_quote_price (out_price, this_leg_data.tick_size(), this_leg_data.trading_side());
price = Price(out_price);
}
static void compute_hedge_price_size_2_legs (Price spread_price,
const LegPropertyData& quote_filled_leg, Price quote_fill_price, Quantity quote_fill_quantity,
@@ -86,9 +86,9 @@ void QuoterWorkingStateWorker::_longpath_analyze_and_act (bts::orderman::TickToT
else
{
bool reprice = true;
if (_quoter->_this_leg_data.leg_params.quote_params().has_quote_mute_zone())
reprice = SpreaderUtils::reprice_quote_mute_zone(_quoter->_price_quantity_state.out_price().value(), new_price.value(), _quoter->_this_leg_data.trading_side,
_quoter->_this_leg_data.tick_size(), _quoter->_this_leg_data.leg_params.quote_params().quote_mute_zone());
if (_quoter->_this_leg_data.leg_params().quote_params().has_quote_mute_zone())
reprice = SpreaderUtils::reprice_quote_mute_zone(_quoter->_price_quantity_state.out_price().value(), new_price.value(), _quoter->_this_leg_data.trading_side(),
_quoter->_this_leg_data.tick_size(), _quoter->_this_leg_data.leg_params().quote_params().quote_mute_zone());
if (reprice)
{
_quoter->_price_quantity_state.update_out_price_quantity(new_price, new_quantity);