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

This commit is contained in:
Kevin Darby committed 2018-05-29 15:26:55 -04:00
commit 04027ed980
43 files changed
+651 -481

No files matched your search

@@ -58,6 +58,13 @@ namespace mbts.spark {
fill_key_filter.load_state(filters.fill_key);
order_key_filter.load_state(filters.order_key);
security_key_filter.load_state(filters.security_key);
} else {
fill_time_filter.load_state(
new TimeFilterTuple(ui.controls.TimeFilterMode.CMEOpen,
TimeTextTuple.FromDateTime(DateTime.Today),
TimeTextTuple.FromDateTime(DateTime.Today.AddDays(1))
)
);
}
// columns
add_col(Columns.Security, DefaultColumnHeaders.Security, r => r.security.ToString(null), nameof(Row.security), security_filter, DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Security);
@@ -15,25 +15,26 @@ namespace mbts.ui.settings
[Export(typeof(IUserPersistFactory))]
class UISettingsFactory : IUserPersistFactory
{
Task<string[]> _users;
Task<User[]> _users;
readonly PersistenceService _persist;
[ImportingConstructor]
public UISettingsFactory([Import("username")] string current_user, UserService login, [Import("settings")] PersistenceService persist) {
public UISettingsFactory(UserService login, [Import("settings")] PersistenceService persist) {
_persist = persist;
_users = get_users(login);
}
async Task<string[]> get_users(UserService login) {
async Task<User[]> get_users(UserService login) {
var users = await login.get_users_async(null);
if (users.success) return users.value.Users.Select(x => x.Login).ToArray();
else return new string[0];
if (users.success) return users.value.Users.ToArray();
else return new User[0];
}
public IEnumerable<string> users() { return _users.Result; }
public IEnumerable<string> users() { return _users.Result.Select(u => u.Login); }
public IUserPersist get_persist_for(string user) {
return new UserUISettings(user, _persist);
public IUserPersist get_persist_for(string name) {
var user = _users.Result.FirstOrDefault(u => u.Login == name);
return new UserUISettings(user.Id, _persist);
}
}
}
@@ -140,9 +140,9 @@ namespace mbts.persist
string _user;
[ImportingConstructor]
public UserUISettings([Import("username")]string user, [Import("settings")]PersistenceService persist)
public UserUISettings([Import("userid")]uint user, [Import("settings")]PersistenceService persist)
: base(persist) {
_user = user;
_user = $"User {user}";
}
protected override string user() { return _user; }
@@ -150,16 +150,25 @@ namespace mbts.ui.controls {
}
public DIYGrid() {
var sort_map = new Dictionary<string, ColumnBase>();
_sort_descriptions_collection_changed_cb = WPFHelper.create_collection_changed_cb<SortDescription>(
sd => Columns?.ApplyToFirst(c => c.sort_member_path == sd.PropertyName, c => c.SortDirection = sd.Direction),
sd => Columns?.ApplyToFirst(C => C.sort_member_path == sd.PropertyName, c => c.SortDirection = null),
s => {
sd => {
if (Columns.TryGetFirst(c => c.sort_member_path == sd.PropertyName, out ColumnBase col)) {
sort_map[sd.PropertyName] = col;
col.SortDirection = sd.Direction;
}
}, sd => {
if (Columns.TryGetFirst(c => c.sort_member_path == sd.PropertyName, out ColumnBase col)) {
col.SortDirection = null;
sort_map.Remove(sd.PropertyName);
}
}, s => {
sort_map.Clear();
if (Columns is IEnumerable<ColumnBase> cols) {
foreach (var c in cols)
c.SortDirection = null;
}
});
var sort_map = new Dictionary<string, ColumnBase>();
CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, OnCopy, OnCopyCanExecute));
CommandBindings.Add(new CommandBinding(SortCommand, (s, e) => {
if (e.Parameter is GridViewColumnHeader col_header && col_header.Column is ColumnBase cb) {
@@ -177,15 +186,16 @@ namespace mbts.ui.controls {
sort_map.Remove(sd.PropertyName);
}
cv_rows.SortDescriptions.Clear();
cb.SortDirection = next;
cv_rows.SortDescriptions.Add(new SortDescription(path, next));
} else {
var sort_desc = new SortDescription(path, next);
int i = cv_rows.SortDescriptions.IndexOf(sort_desc, EqualityComparer.Create<SortDescription, string>(x => x.PropertyName));
cb.SortDirection = next;
if (i >= 0) {
cv_rows.SortDescriptions[i] = sort_desc;
} else cv_rows.SortDescriptions.Add(new SortDescription(path, next));
}
cb.SortDirection = next;
sort_map[path] = cb;
}
}
@@ -563,10 +573,14 @@ namespace mbts.ui.controls {
public static readonly DependencyProperty RowsProperty =
WPFHelper.create_dp<IEnumerable, DIYGrid>(
nameof(Rows),
(s, oldval, newval) => WPFHelper.manage_collection_change(
(oldval as ICollectionView)?.SortDescriptions,
(newval as ICollectionView)?.SortDescriptions,
s._sort_descriptions_collection_changed_cb),
(s, oldval, newval) => {
WPFHelper.manage_collection_change(
(oldval as ICollectionView)?.SortDescriptions,
(newval as ICollectionView)?.SortDescriptions,
s._sort_descriptions_collection_changed_cb,
old_ncc => s._sort_descriptions_collection_changed_cb(old_ncc, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)),
new_ncc => s._sort_descriptions_collection_changed_cb(new_ncc, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, (IList)new_ncc)));
},
Enumerable.Empty<object>());
public DataTemplate RowTemplate {
@@ -110,7 +110,7 @@ namespace mbts.spark.filters {
selected_items.CollectionChanged += on_selected_items_CollectionChanged;
Action<Action<IObservable<IEnumerable<TValue>>>> ah = cb => _on_state_loaded += cb, rh = cb => _on_state_loaded -= cb;
_resources.Add(Observable.FromEvent(ah, rh).SelectMany(src => src).ObserveOnDispatcher().Subscribe(dsi => {
if (!_override_desired_selection) {
if (!_override_desired_selection && dsi != null) {
var copy = new HashSet<TValue>(_selected_items_set, equality_comparer);
_selected_items_set = new HashSet<TValue>(dsi, equality_comparer);
using (selected_items.SuspendHandler(on_selected_items_CollectionChanged)) {
+27 -17
View File
@@ -30,7 +30,9 @@ namespace mbts.ui.shell
model.provide_services(user, persist);
// await_login pumps the dispatcher but doesn't allow control to return to MEF until the username and workspace are available
model.await_login();
UserName = model.get_username();
var u = model.get_user();
UserName = u.name;
UserId = u.id;
Workspace = model.get_workspace();
model.Dispose();
}
@@ -45,16 +47,24 @@ namespace mbts.ui.shell
[Export("username")]
public string UserName { get; private set; }
[Export("userid")]
public uint UserId { get; private set; }
[Export("workspace")]
public string Workspace { get; private set; }
}
public struct User {
public string name;
public UInt32 id;
}
public class LoginModel : IDisposable
{
// Singleton to help bootstrap the system
private static LoginModel _instance = new LoginModel();
public static LoginModel instance { get { return _instance; } }
private string _username;
private User _user;
private string _workspace;
private PreloginWorkspaceEnumerator _enum_workspace;
@@ -69,18 +79,19 @@ namespace mbts.ui.shell
public event Action Ready;
public string ErrorMessage { get; private set; }
public bool HasFatalError { get; set; }
public string[] UserNames { get; private set; }
public User[] Users { get; private set; }
// The final username
public string get_username() {
Logger.assert_d(!string.IsNullOrEmpty(_username));
return _username;
public User get_user() {
Logger.assert_d(!string.IsNullOrEmpty(_user.name));
return _user;
}
public string get_workspace() {
return _workspace ?? "";
}
public Task<IEnumerable<string>> workspaces_for(string user) {
public Task<IEnumerable<string>> workspaces_for(User user) {
return _enum_workspace.get_workspaces(user);
}
@@ -105,8 +116,7 @@ namespace mbts.ui.shell
_enum_workspace = new PreloginWorkspaceEnumerator(persist);
var response = await _logon.get_users_async(new GetUsersRequest());
if (response.success) {
UserNames = response.value.Users.Select(x => x.Login).ToArray();
Array.Sort(UserNames);
Users = response.value.Users.Select(x => new User { name = x.Login, id = x.Id }).OrderBy(u => u.name).ToArray();
}
else {
ErrorMessage = "Logon: " + response.error_message;
@@ -118,7 +128,7 @@ namespace mbts.ui.shell
#endregion
public async Task<(bool success,string info)> do_login(string username, string workspace, string password) {
if (UserNames.Contains(username)) {
if (Users.Select(u => u.name).Contains(username)) {
var response = await _logon.authenticate_login_async(new AuthenticateLoginRequest() {
Login = username,
Password = password ??""
@@ -126,7 +136,7 @@ namespace mbts.ui.shell
if (response.success) {
if (response.value.IsValid) {
_workspace = workspace;
set_authenticated_user(username);
set_authenticated_user(new User { name =username, id = response.value.UserId});
return (true, "");
}
else {
@@ -140,16 +150,16 @@ namespace mbts.ui.shell
return (false, "Invalid username");
}
private void set_authenticated_user(string name) {
Logger.assert(!string.IsNullOrEmpty(name));
Logger.assert(UserNames.Contains(name));
_username = name;
Environment.SetEnvironmentVariable("BTS_USER", name);
private void set_authenticated_user(User user) {
Logger.assert(!string.IsNullOrEmpty(user.name));
Logger.assert(Users.Select(u => u.name).Contains(user.name));
_user = user;
Environment.SetEnvironmentVariable("BTS_USER", user.name);
_frame.Continue = false;
}
public void await_login() {
if (string.IsNullOrEmpty(_username)) {
if (string.IsNullOrEmpty(_user.name)) {
Dispatcher.PushFrame(_frame);
}
}
@@ -42,7 +42,7 @@ namespace mbts.ui.shell
void _model_Ready() {
_dispatcher.BeginInvoke(() => {
if (!_model.HasFatalError) {
this.UserNames.AddRange(_model.UserNames);
this.UserNames.AddRange(_model.Users.Select(u => u.name));
this.VisualState = "LoginState";
load_username();
LoginCommand.RaiseCanExecuteChanged();
@@ -82,7 +82,8 @@ namespace mbts.ui.shell
private async void update_workspaces(string name) {
Workspaces.Clear();
Workspaces.Add("New workspace...");
var to_add = await _model.workspaces_for(name);
var user = _model.Users.First(u => u.name == name);
var to_add = await _model.workspaces_for(user);
this.SelectedWorkspace = Workspaces.First();
if (to_add != null && name == _name && Workspaces.Count == 1) {
Workspaces.AddRange(to_add);
@@ -12,7 +12,7 @@ namespace mbts.ui.shell
{
class PreloginWorkspaceEnumerator
{
private Dictionary<string, List<string>> _cache = new Dictionary<string, List<string>>();
private Dictionary<uint, List<string>> _cache = new Dictionary<uint, List<string>>();
private PersistenceService _persist;
public PreloginWorkspaceEnumerator(PersistenceService p) {
@@ -27,12 +27,12 @@ namespace mbts.ui.shell
return name;
}
public async Task<IEnumerable<string>> get_workspaces(string username) {
if (!_cache.TryGetValue(username, out List<string> result)) {
using (var svc = new UserUISettings(username, _persist)) {
public async Task<IEnumerable<string>> get_workspaces(User user) {
if (!_cache.TryGetValue(user.id, out List<string> result)) {
using (var svc = new UserUISettings(user.id, _persist)) {
var workspaces = await svc.query<WorkspaceDefinition>(WorkspacesModel.WORKSPACE_NAMESPACE, ".*");
result = workspaces.Select(w => w.key).ToList();
_cache[username] = result;
_cache[user.id] = result;
return result;
}
}
@@ -187,11 +187,11 @@ std::string AdminServiceUtils::find_account_exchange_account (const bts::api::ad
}
return rv;
}
std::map<int,bool> AdminServiceUtils::accounts_map(const bts::api::admin::AdminData& admin_data){
std::map<int,bool> rv;
std::map<uint32_t,bool> AdminServiceUtils::accounts_map(const bts::api::admin::AdminData& admin_data){
std::map<uint32_t,bool> rv;
auto account_ptrs = accounts(admin_data, false);
for(const bts::api::admin::BTSAccount* account_ptr : account_ptrs)
rv.insert(std::pair<int,bool>(account_ptr->id(),account_ptr->is_active()));
rv.insert(std::pair<uint32_t,bool>(account_ptr->id(),account_ptr->is_active()));
return rv;
}
void AdminServiceUtils::validate_account_update (const bts::api::admin::AdminData& admin_data,
@@ -70,7 +70,7 @@ public:
api::Venue exchange,
bts::api::admin::AdminServiceOperationResult& out_result);
// returns a map of the accounts vs their 'is_active'
static std::map<int,bool> accounts_map(const bts::api::admin::AdminData& admin_data);
static std::map<uint32_t,bool> accounts_map(const bts::api::admin::AdminData& admin_data);
// validates that the update to the account is valid
static void validate_account_update (const bts::api::admin::AdminData& admin_data,
const bts::api::admin::BTSAccount& updated_account,
+3
View File
@@ -55,6 +55,9 @@ message GLBXExchangeData {
string security_desc = 20;
string cfi_code = 21;
string cme_symbol = 22;
uint32 main_fraction = 30;
uint32 sub_fraction = 31;
uint32 price_display_format = 32;
}
message CBOEExchangeData {
int64 exchange_id = 10;
+3
View File
@@ -71,6 +71,9 @@ string dump_security(const FixedSecurity& security) {
res << "'display_factor': " << (int)security.display_factor << ", ";
res << "'numeric_id': " << security.numeric_id << ", ";
res << "'cboe_class_key': " << security.cboe_class_key << ", ";
res << "'cme_main_frac': " << (int)security.cme_main_fraction << ", ";
res << "'cme_sub_fract': " << (int)security.cme_sub_fraction << ", ";
res << "'cme_price_dformat': " << (int)security.cme_price_display_format << ", ";
res << "'market_segment': " << security.cme_market_segment_id << ", ";
+6
View File
@@ -157,6 +157,9 @@ void convert_security(const FixedSecurity& source, Security* presult) {
dest.mutable_glbx()->set_security_desc(source.security_desc());
dest.mutable_glbx()->set_cfi_code(source.cfi_code());
dest.mutable_glbx()->set_cme_symbol(source.alt_symbol());
if (source.cme_main_fraction != 0) dest.mutable_glbx()->set_main_fraction(source.cme_main_fraction);
if (source.cme_sub_fraction != 0) dest.mutable_glbx()->set_sub_fraction(source.cme_sub_fraction);
if (source.cme_price_display_format) dest.mutable_glbx()->set_price_display_format(source.cme_price_display_format);
break;
case Venue::VENUE_BTS:
break;
@@ -254,6 +257,9 @@ void convert_security(const Security& src, FixedSecurity& dest, bool set_securit
dest.security_desc(src.glbx().security_desc());
dest.cfi_code(src.glbx().cfi_code());
dest.alt_symbol(src.glbx().cme_symbol());
dest.cme_main_fraction = src.glbx().main_fraction();
dest.cme_sub_fraction = src.glbx().sub_fraction();
dest.cme_price_display_format = src.glbx().price_display_format();
break;
case Security::ExchangeDataCase::kCboe:
dest.cboe_class_key = src.cboe().class_key();
+4
View File
@@ -54,6 +54,10 @@ public:
double high_tick;
double cash_per_point;
uint8_t cme_main_fraction;
uint8_t cme_sub_fraction;
uint8_t cme_price_display_format;
private:
char _symbol[16]; // CME defines this as a char[6] but I'm padding
char _cfi_code[8]; // CME defines this as char[6]
@@ -201,6 +201,10 @@ void set_security_common(const Definition& def, FixedSecurity& fsec) {
// tickRule not present in futures
fsec.cme_market_segment_id = def.marketSegmentId();
fsec.display_factor = def.displayFactor().exponent() + floorlog10(def.displayFactor().mantissa());
def.mainFraction(fsec.cme_main_fraction);
def.subFraction(fsec.cme_sub_fraction);
def.priceDisplayFormat(fsec.cme_price_display_format);
}
void MDP3Listener::onDefinition(onixs::Handler&, const onixs::Security& osec, const onixs::InstrumentDefinitionFutureArgs& def) {
@@ -211,6 +215,7 @@ void MDP3Listener::onDefinition(onixs::Handler&, const onixs::Security& osec, co
bts_assert(exchange_id == osec.id());
FixedFutureSecurity fsec;
set_security_common(sec, fsec);
fsec.price_break = 0;
// low/high tick are stored non-premultiplied and multiplied in conversion to api::Secutity
@@ -55,9 +55,9 @@ ProductLimitTree* LimitStore::_find_product_for_security(const api::Security& se
return _find_product(product);
}
ProductLimitTree* LimitStore::_find_product(const api::Product& product){
for(auto it=_prod_map.begin(); it!= _prod_map.end(); it++)
if(product.exchange() == it->product().exchange() && product.type() == it->product().type() && product.symbol() == it->product().symbol())
return &*it;
for(ProductLimitTree& plt : _prod_map)
if(product.exchange() == plt.product().exchange() && product.type() == plt.product().type() && product.symbol() == plt.product().symbol())
return &plt;
return nullptr;
}
const SecurityLimitNode* LimitStore::test_only_func_find_security_node(AccountID account_id,
+21 -12
View File
@@ -9,14 +9,18 @@
#include "Limiter.h"
#include "ProductLimitTree.h"
#include "SecurityLimitTree.h"
#include "SecurityClipTree.h"
namespace bts {
namespace orderman {
// this is the data unit for a product for an account.
// it contains the limit and the live values
// this contains all the data needed to enforce
// risk limits. all the data derived from the
// AdminData (user account relationships, position
// limits, clip sizes etc) are constant. The non const
// data are the positions
class LimitStore{
private:
// for a single user, contains the trading accounts
// the user can trade in
class UserData {
public:
const bts::api::admin::BTSUser* user;
@@ -31,10 +35,13 @@ private:
};
const bts::api::admin::AdminData _admin_data;
// just an easy way to find accounts
const std::map<int, bool> _account_map;
const std::map<uint32_t, bool> _account_map;
// map of user id's vs the user pointer and acccounts
std::map<uint32_t, UserData> _user_data_map;
std::map<uint32_t,SecurityLimitTree> _sec_map;
// map of securities vs their account limits and positions
std::map<uint32_t, SecurityLimitTree> _sec_map;
// this is passed over to the SecurityLimitTree
// entried (above)
std::vector<ProductLimitTree> _prod_map;
// these are kept here and references passes to each node
const bts::api::admin::AccountProductPositionLimitUnit _zero_product_limit;
@@ -43,13 +50,15 @@ public:
LimitStore(const bts::api::admin::AdminData& admin_data,
const std::map<uint32_t,api::Security const*>& sec_map);
// accessors
////////////
bool has_account (AccountID account_id) const{return _account_map.find(account_id.value()) != _account_map.end();}
bool has_security (uint32_t sec_id) const {return _sec_map.find(sec_id) != _sec_map.end();}
// accessors ///////////////
////////////////////////////
bool has_account (AccountID account_id) const
{return _account_map.find(account_id.value()) != _account_map.end();}
bool has_security (uint32_t sec_id) const
{return _sec_map.find(sec_id) != _sec_map.end();}
const bts::api::admin::AdminData& admin_data () const {return _admin_data;}
// position updates
///////////////////
// position updates ////////
////////////////////////////
void copy_positions_from(LimitStore& source);
void add_position(const api::Security& security,
AccountID account_id, api::Side side,
@@ -87,7 +96,7 @@ public:
//ii. user should be activated
//iii. user should be permitted to trade in the account
//iv. account should be activated
Limiter::LimiterQueryResult can_trade(UserID user_id,
Limiter::LimiterQueryResult can_trade(UserID user_id,
AccountID account_id) const{
Limiter::LimiterQueryResult result; result.ok = true;
auto user_it = _user_data_map.find(user_id.value());
@@ -25,8 +25,8 @@ void Limiter::update(api::admin::AdminData const& admin_data) {
}
void Limiter::add_securities(std::vector<api::Security const*> const& new_securities){
LOG(OrderMan, Info, "Limiter::add_securities {} securities", me->sec_map.size());
for(auto it=new_securities.begin(); it!=new_securities.end(); it++)
_add_security(*it);
for(const api::Security* s : new_securities)
_add_security(s);
_reset(me->limit_store->admin_data());
}
void Limiter::add_security(api::Security const & security) {
@@ -88,8 +88,8 @@ void Limiter::_add_security (const api::Security* sec){
if (!_contains_security(sec)){
me->sec_map.insert(std::pair<uint32_t,const api::Security*>(sec->id(), sec));
if (sec->has_spread())
for(int i=0; i<sec->spread().legs_size(); i++)
_add_security(&(sec->spread().legs(i).security()));
for(const auto& leg : sec->spread().legs())
_add_security(&leg.security());
}
}
@@ -3,8 +3,8 @@
namespace bts{
namespace orderman{
ProductLimitNode::ProductLimitNode(int account_id,
int, // parent_account_id,
ProductLimitNode::ProductLimitNode(uint32_t account_id,
uint32_t, // parent_account_id,
const bts::api::admin::AccountProductPositionLimitUnit& limit)
:
_account_id(account_id),
@@ -18,17 +18,17 @@ namespace orderman{
// clip size.
class ProductLimitNode{
private:
const int _account_id; // , _parent_account_id;
const uint32_t _account_id; // , _parent_account_id;
const bts::api::admin::AccountProductPositionLimitUnit& _limit;
const int _long_pos_limit, _short_pos_limit;
int _net_pos;
public:
ProductLimitNode(int account_id,
int parent_account_id,
ProductLimitNode(uint32_t account_id,
uint32_t parent_account_id,
const bts::api::admin::AccountProductPositionLimitUnit& limit);
// accessors
////////////
int account_id() const {return _account_id;}
uint32_t account_id() const {return _account_id;}
int net_pos() const {return _net_pos;}
// position updates
///////////////////
@@ -6,14 +6,12 @@ namespace orderman{
ProductLimitTree::ProductLimitTree(const api::Product& product,
const bts::api::admin::AdminData& admin_data,
const bts::api::admin::AccountProductPositionLimitUnit& zero_limit)
:
_product (product)
{
for(int i=0; i<admin_data.accounts_size(); i++){
const auto& account = admin_data.accounts(i);
const bts::api::admin::AccountProductPositionLimitUnit* limit = bts::admin::AdminServiceUtils::find_account_product_position_limit(account, _product);
_tree.emplace_back(account.id(), bts::admin::AdminServiceUtils::has_id(account.parent_account_id()) ? account.parent_account_id() : 0, limit != nullptr ? *limit : zero_limit);
}
:
_product (product)
{
for(const auto& account : admin_data.accounts()){
const bts::api::admin::AccountProductPositionLimitUnit* limit = bts::admin::AdminServiceUtils::find_account_product_position_limit(account, _product);
_tree.emplace_back(account.id(), bts::admin::AdminServiceUtils::has_id(account.parent_account_id()) ? account.parent_account_id() : 0, limit != nullptr ? *limit : zero_limit);
}
}
}
}}
@@ -25,10 +25,10 @@ public:
const bts::api::admin::AccountProductPositionLimitUnit& zero_limit);
// accessors
////////////
ProductLimitNode* find_account (int account_id){
for(auto it=_tree.begin(); it!=_tree.end(); it++)
if(it->account_id()==account_id)
return &*it;
ProductLimitNode* find_account (uint32_t account_id){
for(ProductLimitNode& node : _tree)
if(node.account_id()==account_id)
return &node;
return nullptr;
}
const api::Product& product() const {return _product;}
@@ -1,55 +0,0 @@
#pragma once
#include <memory>
#include "lib/api/services/OrderService.pb.h"
#include "server/sparkd/orderman/orderman_utils/orderman_common.h"
#include "lib/domain_model/Security.pb.h"
#include "lib/api/services/AdminService.server.pb.h"
#include "lib/api/service_helpers/AdminServiceUtils.h"
#include "Limiter.h"
namespace bts{
namespace orderman{
class SecurityClipTree{
private:
std::vector<std::pair<int, uint32_t>> _account_clips;
public:
SecurityClipTree (const api::Security& security,
const bts::api::admin::AdminData& admin_data){
for(int i=0; i<admin_data.accounts_size(); i++){
const auto& account = admin_data.accounts(i);
uint32_t clip_size = bts::admin::AdminServiceUtils::find_account_security_clip_size (account, security);
_account_clips.emplace_back(account.id(), clip_size);
}
}
uint32_t find_clip_size(int account_id){
for(auto it=_account_clips.begin(); it!=_account_clips.end(); it++)
if (it->first == account_id)
return it->second;
return 0;
}
Limiter::LimiterQueryResult can_send_new_order(int account_id, uint32_t quantity) const{
Limiter::LimiterQueryResult result;
result.ok = false;
for(auto it=_account_clips.begin(); it!=_account_clips.end(); it++){
if(it->first==account_id){
if(quantity>it->second){
result.ok = false;
result.error_msg = fmt::format("Security Clip Size (Max {} Qty {})", it->second, quantity);
return result;
}
else{
result.ok = true;
return result;
}
}
}
bts_assert(false);
return result;
}
Limiter::LimiterQueryResult can_update_order(int account_id, uint32_t to) const{
return can_send_new_order(account_id, to);
}
};
}}
@@ -3,8 +3,8 @@
namespace bts {
namespace orderman {
SecurityLimitNode::SecurityLimitNode(int account_id,
int, // parent_account_id,
SecurityLimitNode::SecurityLimitNode(uint32_t account_id,
uint32_t, // parent_account_id,
const bts::api::admin::AccountSecurityPositionLimitUnit& limit,
bool apply_sec_position_limits,
ProductLimitNode& product_node,
@@ -20,7 +20,7 @@ namespace orderman{
// node, that is updated as fills come in.
class SecurityLimitNode{
private:
const int _account_id; // , _parent_account_id;
const uint32_t _account_id; // , _parent_account_id;
const bts::api::admin::AccountSecurityPositionLimitUnit& _limit;
const int _long_pos_limit, _short_pos_limit;
const bool _apply_sec_position_limits;
@@ -28,14 +28,14 @@ private:
const uint32_t _clip_size;
int _net_pos;
public:
SecurityLimitNode(int account_id, int parent_account_id,
SecurityLimitNode(uint32_t account_id, uint32_t parent_account_id,
const bts::api::admin::AccountSecurityPositionLimitUnit& limit,
bool apply_sec_position_limits,
ProductLimitNode& product_limit,
uint32_t clip_size);
//accessors
///////////
int account_id() const {return _account_id;}
uint32_t account_id() const {return _account_id;}
int net_pos() const {return _net_pos;}
// position updates
///////////////////
@@ -7,15 +7,14 @@ SecurityLimitTree::SecurityLimitTree(const api::Security& security,
ProductLimitTree& product_tree,
const bts::api::admin::AdminData& admin_data,
const bts::api::admin::AccountSecurityPositionLimitUnit& zero_limit)
{
for(int i=0; i<admin_data.accounts_size(); i++){
const auto& account = admin_data.accounts(i);
ProductLimitNode* product_node_ptr = product_tree.find_account(account.id());
bts_assert(product_node_ptr != nullptr);
const bts::api::admin::AccountSecurityPositionLimitUnit* limit = bts::admin::AdminServiceUtils::find_account_security_position_limit(account, security);
uint32_t clip_size = bts::admin::AdminServiceUtils::find_account_security_clip_size(account, security);
_tree.emplace_back(account.id(), bts::admin::AdminServiceUtils::has_id(account.parent_account_id()) ? account.parent_account_id() : 0,
limit != nullptr ? *limit : zero_limit, limit != nullptr, *product_node_ptr, clip_size);
}
{
for(const auto& account : admin_data.accounts()){
ProductLimitNode* product_node_ptr = product_tree.find_account(account.id());
bts_assert(product_node_ptr != nullptr);
const bts::api::admin::AccountSecurityPositionLimitUnit* limit = bts::admin::AdminServiceUtils::find_account_security_position_limit(account, security);
uint32_t clip_size = bts::admin::AdminServiceUtils::find_account_security_clip_size(account, security);
_tree.emplace_back(account.id(), bts::admin::AdminServiceUtils::has_id(account.parent_account_id()) ? account.parent_account_id() : 0,
limit != nullptr ? *limit : zero_limit, limit != nullptr, *product_node_ptr, clip_size);
}
}
}}
@@ -40,10 +40,10 @@ public:
account_ptr->remove_position(side, quantity.value());
}
void copy_positions_from(SecurityLimitTree& source){
for (auto it=_tree.begin(); it!=_tree.end(); it++){
SecurityLimitNode* source_node_ptr = source._find_account(it->account_id());
for (SecurityLimitNode& node : _tree){
SecurityLimitNode* source_node_ptr = source._find_account(node.account_id());
if(source_node_ptr != nullptr)
it->copy_positions_from(*source_node_ptr);
node.copy_positions_from(*source_node_ptr);
}
}
// risk limit checks
@@ -64,20 +64,20 @@ public:
}
// accessors
////////////
const SecurityLimitNode* find_account (int account_id) const{
const SecurityLimitNode* find_account (uint32_t account_id) const{
return _find_account(account_id);
}
private:
SecurityLimitNode* _find_account (int account_id){
for(auto it=_tree.begin(); it!=_tree.end(); it++)
if(it->account_id()==account_id)
return &*it;
SecurityLimitNode* _find_account (uint32_t account_id){
for(auto& node : _tree)
if(node.account_id()==account_id)
return &node;
return nullptr;
}
const SecurityLimitNode* _find_account (int account_id) const{
for(auto it=_tree.begin(); it!=_tree.end(); it++)
if(it->account_id()==account_id)
return &*it;
const SecurityLimitNode* _find_account (uint32_t account_id) const{
for(const auto& node : _tree)
if(node.account_id()==account_id)
return &node;
return nullptr;
}
};
@@ -5,13 +5,12 @@ namespace bts {
namespace orderman {
class LegPropertyData;
// The SpreaderOrder spawns a bunch of SingleLegQuoters (to quote each active
// leg) and SingleFillHedgers (to hedge each fill), and offers them
// this interface to
// i. get data such as book and leg properties (in O(1) access time)
// ii. place, modify and cancel orders
class ISpreaderManager
{
// The Spreader spawns a bunch of quoters and
// hedgers and hands them this interface to
// i. get data such as book and leg properties
// (in O(1) access time)
// ii. create new quoter order
class ISpreaderManager{
public:
virtual bts::orderman::OrderKey spreader_order_key() const = 0;
virtual bts::TimeStamp current_time() const = 0;
@@ -24,4 +23,4 @@ public:
// and updates the bookkeeping data
virtual void setup_new_quoter_order (size_t leg_index) = 0;
};
}}
}}
@@ -0,0 +1,23 @@
#include "LegPropertyData.h"
#include "ISpreaderManager.h"
#include "SpreaderUtils.h"
namespace bts {
namespace orderman {
LegPropertyData::LegPropertyData(size_t leg_index,
const bts::api::ContractLeg& leg_contract,
const bts::spark::LegSpreaderParams& leg_params,
api::Side trading_side,
const bts::api::orderman::OrderDefinition& quoter_order_definition,
const bts::api::orderman::OrderDefinition& hedger_order_definition)
:
_leg_index(leg_index),
_leg_contract(leg_contract),
_leg_params(leg_params),
_trading_side(trading_side),
_quoter_order_definition (quoter_order_definition),
_hedger_order_definition (hedger_order_definition){
LOG(OrderMan, Info, "LegPropertyData.cons leg_idx: {} sec_key: {} side: {}", leg_index, leg_contract.security().id(), trading_side);
}
}}
@@ -3,11 +3,14 @@
#include "lib/domain_model/Security.pb.h"
#include "lib/sparkproto/SparkProtos.pb.h"
#include "lib/api/services/OrderService.pb.h"
#include "server/sparkd/orderman/orderman_utils/orderman_common.h"
namespace bts {
namespace orderman {
// collection of immutable leg data properties, shared
// between the Spreader, SingleLegQuoter and SingleFillHedger
// collection of immutable leg data.
// this copies all the data (there are
// no refs or pointers to outside this
// class)
class LegPropertyData
{
private:
@@ -17,43 +20,19 @@ private:
const api::Side _trading_side;
const bts::api::orderman::OrderDefinition _quoter_order_definition;
const bts::api::orderman::OrderDefinition _hedger_order_definition;
public:
LegPropertyData(size_t leg_index,
const bts::api::ContractLeg& leg_contract,
const bts::spark::LegSpreaderParams& leg_params,
api::Side trading_side)
:
// copying the values via copy cons
_leg_index(leg_index),
_leg_contract(leg_contract),
_leg_params(leg_params),
_trading_side(trading_side)
{
}
public:
LegPropertyData(size_t leg_index,
const bts::api::ContractLeg& leg_contract,
const bts::spark::LegSpreaderParams& leg_params,
api::Side trading_side,
const bts::api::orderman::OrderDefinition& quoter_order_definition,
const bts::api::orderman::OrderDefinition& hedger_order_definition)
:
// copying the values via copy cons
_leg_index(leg_index),
_leg_contract(leg_contract),
_leg_params(leg_params),
_trading_side(trading_side),
_quoter_order_definition (quoter_order_definition),
_hedger_order_definition (hedger_order_definition)
{
LOG(OrderMan, Info, "LegPropertyData.cons leg_idx: {} sec_key: {} side: {}", leg_index, leg_contract.security().id(), trading_side);
}
const bts::api::orderman::OrderDefinition& hedger_order_definition);
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
SecurityKey leg_security_key() const {return SecurityKey(_leg_contract.security().id());}
//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_contract.price_multiplier(); }
double size_multiplier() const { return _leg_contract.quantity(); }
@@ -0,0 +1,62 @@
#include "SpreaderBookkeepingData.h"
namespace bts{
namespace orderman{
SpreaderBookkeepingData::SpreaderBookkeepingData (ISpreaderManager& spreader_manager,
bts::orderman::OrderKey spreader_order_key,
const api::orderman::OrderDefinition& order_def,
const SpreaderPreActivationOrderServices& spreader_pao_services,
const std::vector<LegPropertyData>& legs)
:
_is_live(spreader_pao_services.is_live()),
_n_legs(legs.size()),
_order_def(order_def){
LOG(OrderMan, Info, "SpreaderBookkeepingData.cons started key: {} n_legs: {}", spreader_order_key.value(), _n_legs);
_quoter_order_builders.reserve(_n_legs);
_hedger_order_builders.reserve(_n_legs);
_quoter_child_order_states.reserve(_n_legs);
_quoters.reserve (_n_legs);
_hedgers.reserve (_n_legs);
_leg_data.reserve (_n_legs);
for (size_t l_idx = 0; l_idx < legs.size(); l_idx++){
const LegPropertyData& leg_property_data = legs[l_idx];
_quoter_order_builders.emplace_back(spreader_order_key, leg_property_data.quoter_order_definition(), spreader_pao_services, 10);
_hedger_order_builders.emplace_back(spreader_order_key, leg_property_data.hedger_order_definition(), spreader_pao_services, 10);
_quoter_child_order_states.emplace_back (_is_live, leg_property_data);
_quoters.emplace_back(spreader_manager, leg_property_data, _n_legs, _quoter_child_order_states.back());
_hedgers.emplace_back ();
_leg_data.emplace_back(leg_property_data, _quoters.back(), _quoter_order_builders.back(), _hedger_order_builders.back(), _hedgers.back (), _quoter_child_order_states.back());
bts_assert (_sec_key_to_index.find(leg_property_data.security_key()) == _sec_key_to_index.end());
_sec_key_to_index.insert(std::pair<uint32_t, size_t>(leg_property_data.security_key(), leg_property_data.leg_index()));
}
LOG(OrderMan, Info, "SpreaderBookkeepingData.cons completed key: {} n_legs: {}", spreader_order_key.value(), _n_legs);
}
void SpreaderBookkeepingData::total_fills (Quantity& out_quantity,
Price& out_price) const{
double avg_price = 0.0;
double fills = std::numeric_limits<double>::max();
for (const SpreaderLegData& leg_data : _leg_data){
Quantity leg_fill_qty; Price leg_fill_price;
leg_data.total_fills(leg_fill_qty, leg_fill_price);
double normalized_qty = std::abs(static_cast<double>(leg_fill_qty.value()) / leg_data.leg_property_data().size_multiplier());
fills = normalized_qty < fills ? normalized_qty : fills;
avg_price += leg_fill_price.value() * leg_data.leg_property_data().price_multiplier();
}
out_quantity = Quantity(fills);
out_price = Price(avg_price);
}
SpreaderHedgerData& SpreaderBookkeepingData::add_new_hedger(ISpreaderManager& spreader_manager,
size_t leg_index,
bts::Price hedge_price,
bts::Quantity hedge_quantity){
LOG(OrderMan, Info, "SpreaderHedgerData::add_new_hedger begin leg_index: {} hedge_price: {} hedge_quantity: {}", leg_index, hedge_price, hedge_quantity);
bts_assert(leg_index < _n_legs);
SpreaderLegData& leg_data = _leg_data[leg_index];
std::vector<SpreaderHedgerData>& leg_hedgers = _hedgers[leg_index];
bts::orderman::ChildOrder hedge_order = leg_data.hedger_order_builder().build();
leg_hedgers.emplace_back (spreader_manager, leg_data.leg_property_data(), hedge_order, _is_live, hedge_price, hedge_quantity);
LOG(OrderMan, Info, "SpreaderHedgerData::add_new_hedger end leg_index: {} hedge_price: {} hedge_quantity: {}", leg_index, hedge_price, hedge_quantity);
return leg_hedgers.back();
}
}}
@@ -12,8 +12,10 @@
namespace bts{
namespace orderman {
class SpreaderHedgerData;
// encapsulates, organizes and provides easy access and lookups
// for data needed by the spreader
// encapsulates, organizes and provides easy access
// and lookups for data needed by the spreader.
// this data includes the book, orders, quoters,
// hedgers, price/qty etc
class SpreaderBookkeepingData
{
private:
@@ -34,108 +36,65 @@ public:
bts::orderman::OrderKey spreader_order_key,
const api::orderman::OrderDefinition& order_def,
const SpreaderPreActivationOrderServices& spreader_pao_services,
const std::vector<LegPropertyData>& legs)
:
_is_live(spreader_pao_services.is_live()),
_n_legs(legs.size()),
_order_def(order_def)
{
LOG(OrderMan, Info, "SpreaderBookkeepingData.cons started key: {} n_legs: {}", spreader_order_key.value(), _n_legs);
_quoter_order_builders.reserve(_n_legs);
_hedger_order_builders.reserve(_n_legs);
_quoter_child_order_states.reserve(_n_legs);
_quoters.reserve (_n_legs);
_hedgers.reserve (_n_legs);
_leg_data.reserve (_n_legs);
for (size_t l_idx = 0; l_idx < legs.size(); l_idx++)
{
const LegPropertyData& leg_property_data = legs[l_idx];
_quoter_order_builders.emplace_back(spreader_order_key, leg_property_data.quoter_order_definition(), spreader_pao_services, 10);
_hedger_order_builders.emplace_back(spreader_order_key, leg_property_data.hedger_order_definition(), spreader_pao_services, 10);
_quoter_child_order_states.emplace_back (_is_live, leg_property_data);
_quoters.emplace_back(spreader_manager, leg_property_data, _n_legs, _quoter_child_order_states.back());
_hedgers.emplace_back ();
_leg_data.emplace_back(leg_property_data, _quoters.back(), _quoter_order_builders.back(), _hedger_order_builders.back(), _hedgers.back (), _quoter_child_order_states.back());
bts_assert (_sec_key_to_index.find(leg_property_data.security_key()) == _sec_key_to_index.end());
_sec_key_to_index.insert(std::pair<uint32_t, size_t>(leg_property_data.security_key(), leg_property_data.leg_index()));
}
LOG(OrderMan, Info, "SpreaderBookkeepingData.cons completed key: {} n_legs: {}", spreader_order_key.value(), _n_legs);
}
const std::vector<LegPropertyData>& legs);
SpreaderBookkeepingData (const SpreaderBookkeepingData&) = delete;
SpreaderBookkeepingData (SpreaderBookkeepingData&&) = delete;
SpreaderBookkeepingData& operator=(const SpreaderBookkeepingData&) = delete;
SpreaderBookkeepingData& operator=(SpreaderBookkeepingData&&) = delete;
SpreaderLegData& get_leg_data (SecurityKey security_key)
{
// accessors ////////////////////
/////////////////////////////////
size_t n_legs() const { return _n_legs; }
bool all_legs_resolved() const {return n_legs() > 0;}
const api::orderman::OrderDefinition& order_def() const {return _order_def;}
Price price () const {return _price;}
Quantity quantity () const {return _quantity;}
// gets leg data from leg's sec key
SpreaderLegData& get_leg_data (SecurityKey security_key){
boost::container::flat_map<uint32_t, size_t>::const_iterator l_it = _sec_key_to_index.find(security_key.value());
bts_assert (l_it != _sec_key_to_index.end());
return _leg_data[l_it->second];
}
SpreaderLegData& get_leg_data(size_t index)
{
// gets leg data from leg index
SpreaderLegData& get_leg_data(size_t index){
bts_assert(index < _leg_data.size());
return _leg_data[index];
}
const SpreaderLegData& get_leg_data (size_t index) const
{
// same as above for const access
const SpreaderLegData& get_leg_data (size_t index) const{
bts_assert(index < _leg_data.size());
return _leg_data[index];
}
size_t n_legs() const { return _n_legs; }
bool all_legs_resolved() const {return n_legs() > 0;}
const api::orderman::OrderDefinition& order_def() const {return _order_def;}
SpreaderLegData* find_leg_from_quoter_orderkey(bts::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->key() == order_key)
return &(*q_it);
// finds the quoter that has the arg order key
SpreaderLegData* find_leg_from_quoter_orderkey(bts::orderman::OrderKey order_key){
for (SpreaderLegData& leg : _leg_data)
if (leg.leg_property_data().is_active_quoting())
if (leg.key() == order_key)
return &leg;
return nullptr;
}
SpreaderHedgerData* find_hedger_from_orderkey(bts::orderman::OrderKey order_key)
{
for (auto l_it = _leg_data.begin(); l_it != _leg_data.end(); ++l_it)
{
SpreaderHedgerData* rv = l_it->find_hedger_from_orderkey (order_key);
// finds the hedger that has the arg order key
SpreaderHedgerData* find_hedger_from_orderkey(bts::orderman::OrderKey order_key){
for (SpreaderLegData& leg : _leg_data){
SpreaderHedgerData* rv = leg.find_hedger_from_orderkey (order_key);
if (rv != nullptr)
return rv;
}
return nullptr;
}
// creates a new hedger for a given leg index,
// adds it to appropriate place in _hedgers,
// and returns a ref to it
// (dont keep pointers to hedgers since the vector
// can resize)
SpreaderHedgerData& add_new_hedger(ISpreaderManager& spreader_manager,
size_t leg_index,
bts::Price hedge_price,
bts::Quantity hedge_quantity)
{
LOG(OrderMan, Info, "SpreaderHedgerData::add_new_hedger begin leg_index: {} hedge_price: {} hedge_quantity: {}", leg_index, hedge_price, hedge_quantity);
bts_assert(leg_index < _n_legs);
SpreaderLegData& leg_data = _leg_data[leg_index];
std::vector<SpreaderHedgerData>& leg_hedgers = _hedgers[leg_index];
bts::orderman::ChildOrder hedge_order = leg_data.hedger_order_builder().build();
leg_hedgers.emplace_back (spreader_manager, leg_data.leg_property_data(), hedge_order, _is_live, hedge_price, hedge_quantity);
LOG(OrderMan, Info, "SpreaderHedgerData::add_new_hedger end leg_index: {} hedge_price: {} hedge_quantity: {}", leg_index, hedge_price, hedge_quantity);
return leg_hedgers.back();
}
void total_fills (Quantity& out_quantity, Price& out_price)
{
double avg_price = 0.0;
double fills = std::numeric_limits<double>::max();
for (auto it = _leg_data.begin(); it != _leg_data.end(); it++)
{
const SpreaderLegData& leg_data = *it;
Quantity leg_fill_qty; Price leg_fill_price;
leg_data.total_fills(leg_fill_qty, leg_fill_price);
double normalized_qty = std::abs(static_cast<double>(leg_fill_qty.value()) / leg_data.leg_property_data().size_multiplier());
fills = normalized_qty < fills ? normalized_qty : fills;
avg_price += leg_fill_price.value() * leg_data.leg_property_data().price_multiplier();
}
out_quantity = Quantity(fills);
out_price = Price(avg_price);
}
Price price () const {return _price;}
Quantity quantity () const {return _quantity;}
void update_order (Price price, Quantity quantity)
{
bts::Quantity hedge_quantity);
// finds the spreader fill, price (ie averages it out, using
// the size and price ratio, across all legs)
void total_fills (Quantity& out_quantity, Price& out_price) const;
// updates the price, qty of the spreader order
void update_order (Price price, Quantity quantity){
_price = price;
_quantity = quantity;
}
@@ -169,10 +169,9 @@ public:
Quantity last_update_filled_quantity () const {return _last_filled_quantity;}
bool terminal_status() const { return SpreaderUtils::order_in_terminal_state(_status); }
bool acknowledged () const {return SpreaderUtils::order_acknowledged (_status);}
void total_fills (Quantity& out_filled, Price& out_price)
{
void total_fills (Quantity& out_filled, Price& out_price) const{
SpreaderUtils::compute_average_price(_base_price, _base_quantity, _filled_price, _filled_quantity, out_price, out_filled);
}
Quantity total_fills() {return Quantity(_base_quantity.value() + _filled_quantity.value());}
Quantity total_fills() const {return Quantity(_base_quantity.value() + _filled_quantity.value());}
};
}}
@@ -0,0 +1,34 @@
#include "SpreaderLegData.h"
namespace bts{
namespace orderman{
SpreaderLegData::SpreaderLegData (const LegPropertyData& leg_property_data,
SingleLegQuoter& quoter,
SpreaderOrderBuilder& quoter_order_builder,
SpreaderOrderBuilder& hedger_order_builder,
std::vector<SpreaderHedgerData>& hedger_data_vector,
SpreaderChildOrderState& quoter_child_order_state)
:
_leg_property_data (leg_property_data),
_quoter(quoter),
_quoter_order_builder (quoter_order_builder),
_hedger_order_builder (hedger_order_builder),
_quoter_child_order_state (quoter_child_order_state),
_hedger_data_vector (hedger_data_vector),
_book()
{}
SpreaderLegData::SpreaderLegData(SpreaderLegData&& other)
:
_leg_property_data (other._leg_property_data),
_quoter (other._quoter),
_quoter_order_builder(other._quoter_order_builder),
_hedger_order_builder(other._hedger_order_builder),
_quoter_child_order_state (other._quoter_child_order_state),
_hedger_data_vector (other._hedger_data_vector),
_book(){
bts_assert (false);
}
}}
@@ -5,19 +5,20 @@
#include "SpreaderHedgerData.h"
#include "SpreaderChildOrderState.h"
#include "server/sparkd/orderman/actors/order_manager/OrderBuilder.h"
#include <google/protobuf/util/message_differencer.h>
#include "server/sparkd/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.h"
namespace bts{
namespace orderman{
// all the data for a leg :
// 1. leg property data
// 2. quoter
// 3. order builders
// 4. quoter child order
// 6. all the hedgers for this leg (ie when fills happens
// on other legs, and they are hedged in this leg)
// the higher level objects are returned by ref to mutate
// their state
// this class is a conveniance per leg wrapper
// on the SpreaderBookkeepingData's data.
// keeping it this way provides easy access
// to the leg data (vs searching for them in
// SpreaderBookkeepingData).
// this class is created (and mantained) by
// SpreaderBookkeeping. all the data except
// for the Book and LegPropertyData
// are references to SpreaderBookkeeping
class SpreaderLegData
{
private:
@@ -34,32 +35,20 @@ public:
SpreaderOrderBuilder& quoter_order_builder,
SpreaderOrderBuilder& hedger_order_builder,
std::vector<SpreaderHedgerData>& hedger_data_vector,
SpreaderChildOrderState& quoter_child_order_state)
: _leg_property_data (leg_property_data),
_quoter(quoter),
_quoter_order_builder (quoter_order_builder),
_hedger_order_builder (hedger_order_builder),
_quoter_child_order_state (quoter_child_order_state),
_hedger_data_vector (hedger_data_vector),
_book()
{
}
SpreaderChildOrderState& quoter_child_order_state);
SpreaderLegData() = delete;
SpreaderLegData(const SpreaderLegData&) = delete;
SpreaderLegData(SpreaderLegData&& other)
: _leg_property_data (other._leg_property_data),
_quoter (other._quoter),
_quoter_order_builder(other._quoter_order_builder),
_hedger_order_builder(other._hedger_order_builder),
_quoter_child_order_state (other._quoter_child_order_state),
_hedger_data_vector (other._hedger_data_vector),
_book()
{
bts_assert (false);
}
SpreaderLegData& operator=(const SpreaderLegData&) = delete;
// this cons is not deleted since for each leg,
// SpreaderLegData is stored in a vector, and
// vectors need either a copy cons or a move cons.
// however, since we dont grow the vector beyond
// the reserved size, this cons will NEVER be called
// and we assert in it.
SpreaderLegData(SpreaderLegData&& other);
SpreaderLegData& operator=(const SpreaderLegData&) = delete;
SpreaderLegData& operator=(SpreaderLegData&&) = delete;
// accessors
// accessors ////////////////////
/////////////////////////////////
const LegPropertyData& leg_property_data() const {return _leg_property_data;}
SingleLegQuoter& quoter() {return _quoter;}
const bts::orderman::Book& book () const {return _book;}
@@ -69,41 +58,42 @@ public:
SpreaderOrderBuilder& quoter_order_builder() {return _quoter_order_builder;}
SpreaderOrderBuilder& hedger_order_builder() {return _hedger_order_builder;}
// returns the number of active hedgers
size_t n_hedgers() { return _hedger_data_vector.size(); }
size_t n_hedgers() const { return _hedger_data_vector.size(); }
// returns the hedger at a given index
SpreaderHedgerData& get_hedger(size_t index) {return _hedger_data_vector[index];}
SpreaderHedgerData& get_hedger(size_t index) {
bts_assert(index<_hedger_data_vector.size());
return _hedger_data_vector[index];
}
// returns a hedger from its order_key
SpreaderHedgerData* find_hedger_from_orderkey(bts::orderman::OrderKey order_key)
{
for (auto h_it = _hedger_data_vector.begin(); h_it != _hedger_data_vector.end(); ++h_it)
if (h_it->order_update_message().order_key() == order_key)
return &(*h_it);
SpreaderHedgerData* find_hedger_from_orderkey(bts::orderman::OrderKey order_key){
for (SpreaderHedgerData& hedger : _hedger_data_vector)
if (hedger.order_update_message().order_key() == order_key)
return &hedger;
return nullptr;
}
std::vector<SpreaderHedgerData>& get_hedgers () {return _hedger_data_vector;}
// mutators
// called for every book update (copied by value)
void update_book(const bts::orderman::Book& book_arg) {_book = book_arg;}
void total_fills (Quantity& out_quantity, Price& out_price) const
{
// computes the total fills and the average price of
// the fills - across the quoter and all the hedgers
void total_fills (Quantity& out_quantity,
Price& out_price) const{
_quoter_child_order_state.total_fills(out_quantity, out_price);
double sum = out_quantity.value() * out_price.value();
for(auto it = _hedger_data_vector.begin(); it != _hedger_data_vector.end(); it++)
{
for (SpreaderHedgerData& hedger : _hedger_data_vector){
Quantity hedger_quantity; Price hedger_price;
SpreaderChildOrderState& hedge_order = it->order_update_message();
hedge_order.total_fills(hedger_quantity, hedger_price);
hedger.order_update_message().total_fills(hedger_quantity, hedger_price);
sum += hedger_quantity.value() * hedger_price.value();
out_quantity = Quantity(out_quantity.value() + hedger_quantity.value());
}
out_price = out_quantity.value() == 0 ? Price(0) : Price(sum / out_quantity.value());
}
Quantity total_fills() const
{
Quantity total_fills() const{
uint32_t rv = _quoter_child_order_state.total_fills().value();
for(auto it = _hedger_data_vector.begin(); it != _hedger_data_vector.end(); it++)
rv += it->order_update_message().total_fills().value();
for (SpreaderHedgerData& hedger : _hedger_data_vector)
rv += hedger.order_update_message().total_fills().value();
return Quantity(rv);
}
// mutators ////////////////////
////////////////////////////////
// called for every book update
void update_book(const bts::orderman::Book& book_arg) {_book = book_arg;}
};
}}
}}
@@ -1,4 +1,8 @@
#include "SpreaderUtils.h"
#include "server/sparkd/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.h"
#include "server/sparkd/orderman/orders/PreActivationOrderServices.h"
#include "server/sparkd/orderman/events/BookUpdateEvent.h"
#include <sstream>
namespace bts{
namespace orderman{
@@ -17,21 +21,16 @@ bool SpreaderUtils::resolve_synthetic_spread (const SpreaderPreActivationOrderSe
bts_assert(order_def.has_custom_def() && order_def.custom_def().has_spreader());
const bts::api::Security* sec_ptr = resolve_synthetic ? spreader_pao_services.resolve (SecurityKey(order_def.security_key())) :
&order_def.custom_def().spreader().security();
if (sec_ptr != nullptr)
{
if (sec_ptr != nullptr){
const spark::ExecutionStrategy& execution_strategy = order_def.custom_def().spreader().execution_strategy();
const bts::api::Security& sec = *sec_ptr;
if (sec.has_synthetic() && sec.synthetic().legs().size() > 0)
{
if (sec.has_synthetic() && sec.synthetic().legs().size() > 0){
size_t leg_idx = 0;
for (auto it = sec.synthetic().legs().begin(); it != sec.synthetic().legs().end(); ++it)
{
for (auto it = sec.synthetic().legs().begin(); it != sec.synthetic().legs().end(); ++it){
const bts::api::ContractLeg& leg = *it;
if (leg.security().has_future() || leg.security().has_spread())
{
if (leg.security().has_future() || leg.security().has_spread()){
const bts::api::Security* leg_sec_ptr = spreader_pao_services.resolve(bts::SecurityKey (leg.security().id()));
if (leg_sec_ptr != nullptr)
{
if (leg_sec_ptr != nullptr){
bts_assert(leg_sec_ptr->id() == leg.security().id());
LOG(OrderMan, Info, "resolve_synthetic_spread resolved leg key {}", leg_sec_ptr->id());
auto leg_exec_strategy_it = execution_strategy.leg_params_map().find(leg.security().id());
@@ -50,28 +49,24 @@ bool SpreaderUtils::resolve_synthetic_spread (const SpreaderPreActivationOrderSe
out_resolved.push_back(leg_property_data);
leg_idx++;
}
else
{
else{
LOG(OrderMan, Error, "resolve_synthetic_spread failure: could not resolve leg key: {}", leg.security().id());
return false;
}
}
else
{
else{
LOG(OrderMan, Error, "resolve_synthetic_spread failure: leg with key: {} was not a future or future spread", leg.security().id());
return false;
}
}
return true;
}
else
{
else{
LOG(OrderMan, Error, "resolve_synthetic_spread failure: no legs in the spread");
return false;
}
}
else
{
else{
LOG(OrderMan, Error, "resolve_synthetic_spread failure: could not resolve synthetic security key: {}", order_def.security_key());
return false;
}
@@ -1,27 +1,21 @@
#pragma once
#include <boost/container/flat_map.hpp>
#include "lib/config/protos/MarketData.pb.h"
#include "lib/utils/bts_chrono.h"
#include "lib/md/PriceSize.h"
#include "lib/domain_model/Security.h"
#include "server/sparkd/orderman/orderman_utils/Book.h"
#include "server/sparkd/orderman/orders/spreader_orders/spreader/LegPropertyData.h"
#include "server/sparkd/orderman/orders/spreader_orders/spreader/QuoteLegPriceQuantityState.h"
#include "server/sparkd/orderman/orders/spreader_orders/spreader/SpreaderUtils.h"
#include "server/sparkd/orderman/orders/spreader_orders/spreader/ISpreaderManager.h"
#include "server/sparkd/orderman/orders/spreader_orders/spreader/quoter/QuoterLegDriverData.h"
#include "server/sparkd/securities/ISecurityDB.h"
#include "lib/api/services/OrderService.pb.h"
#include "server/sparkd/orderman/actors/order_manager/OrderBuilder.h"
#include "server/sparkd/orderman/orders/PreActivationOrderServices.h"
#include "server/sparkd/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.h"
#include "server/sparkd/orderman/events/BookUpdateEvent.h"
#include <sstream>
namespace bts {
namespace orderman {
class SpreaderPreActivationOrderServices;
class BookUpdateEvent;
// collection of helper functions used by the quoter, hedger
// and the spreader glue
class SpreaderUtils
@@ -0,0 +1,36 @@
#include "SpreaderOrderBuilder.h"
namespace bts {
namespace orderman {
SpreaderOrderBuilder::SpreaderOrderBuilder (bts::orderman::OrderKey parent_key,
const api::orderman::OrderDefinition& order_def,
const SpreaderPreActivationOrderServices& spreader_pao_services,
size_t reserve_sz)
:
_is_live(spreader_pao_services.is_live()){
if (_is_live){
LOG(OrderMan, Info, "SpreaderOrderBuilder.cons parent_key: {} sec_key: {}", parent_key, order_def.security_key());
_real_order_builder = bts::orderman::OrderBuilder(parent_key, order_def, spreader_pao_services.pre_services(), reserve_sz);
}
}
SpreaderOrderBuilder::SpreaderOrderBuilder(SpreaderOrderBuilder&&)
:
_is_live(true){
// this cons should never be called. the reason we need this
// is because SpreaderOrderBuilder's are stored in a vector.
// however we know the length of the vector (n of legs), and
// hence can reserve it at construction
bts_assert(false);
}
bts::orderman::ChildOrder SpreaderOrderBuilder::build(){
if (_is_live)
return _real_order_builder.build();
else
return bts::orderman::ChildOrder();
}
void SpreaderOrderBuilder::activate(SpreaderOrderServices& order_services){
if (_is_live)
_real_order_builder.activate(order_services.order_services());
}
}}
@@ -7,85 +7,64 @@
namespace bts {
namespace orderman {
class TestOnlySpreaderPreActivationOrderServices
{
private:
bool _resolve;
const std::vector<bts::api::Security> _secs;
public:
TestOnlySpreaderPreActivationOrderServices (const std::vector<bts::api::Security>& secs)
: _resolve(true),
_secs(secs)
{}
const bts::api::Security* resolve (SecurityKey key) const
{
if (_resolve)
{
for (size_t idx = 0; idx < _secs.size(); idx++)
if (_secs[idx].id() == key.value())
return &_secs[idx];
}
return nullptr;
}
void set_resolve_flag (bool resolve) {_resolve = resolve;}
};
class SpreaderPreActivationOrderServices
{
{
public:
class TestOnlySpreaderPreActivationOrderServices
{
private:
bool _resolve;
const std::vector<bts::api::Security> _secs;
public:
TestOnlySpreaderPreActivationOrderServices (const std::vector<bts::api::Security>& secs)
:
_resolve(true),
_secs(secs)
{}
const bts::api::Security* resolve (SecurityKey key) const{
if (_resolve)
for (const auto& sec : _secs)
if (sec.id() == key.value())
return &sec;
return nullptr;
}
void set_resolve_flag (bool resolve) {_resolve = resolve;}
};
private:
const bts::orderman::PreActivationOrderServices* _pre_services;
const TestOnlySpreaderPreActivationOrderServices* _test_only_pre_services;
public:
SpreaderPreActivationOrderServices (const bts::orderman::PreActivationOrderServices* pre_services)
:
_pre_services(pre_services),
_test_only_pre_services (nullptr)
{}
SpreaderPreActivationOrderServices (TestOnlySpreaderPreActivationOrderServices* test_only_pre_services)
:
_pre_services(nullptr),
_test_only_pre_services (test_only_pre_services)
{}
const bts::api::Security* resolve (SecurityKey key) const
{
if (is_live ())
return _pre_services->sec_db.resolve(key);
else
return _test_only_pre_services->resolve(key);
}
bool is_live () const {return _pre_services != nullptr;}
const bts::orderman::PreActivationOrderServices& pre_services() const
{
bts_assert(is_live ());
return *_pre_services;
}
SpreaderPreActivationOrderServices (const bts::orderman::PreActivationOrderServices* pre_services);
SpreaderPreActivationOrderServices (TestOnlySpreaderPreActivationOrderServices* test_only_pre_services);
const bts::api::Security* resolve (SecurityKey key) const;
bool is_live () const;
const bts::orderman::PreActivationOrderServices& pre_services() const;
};
// SpreaderOrderServices is a thin wrapper around
// OrderServices. The solitary instance of this
// is held in the Spreader.
// (OrderServices is used to report status, sub to
// events etc)
class SpreaderOrderServices
{
private:
const bool _is_live;
bts::orderman::OrderServices* _order_services;
public:
SpreaderOrderServices (bts::orderman::OrderServices* order_services)
:
_is_live(order_services != nullptr),
_order_services(order_services)
{}
bts::orderman::OrderServices& order_services()
{
bts_assert(_is_live);
return *_order_services;
}
void report_state(const api::orderman::OrderState &state)
{
if (is_live())
_order_services->report_state(state);
}
bool is_live() const {return _is_live;}
SpreaderOrderServices (bts::orderman::OrderServices* order_services);
bts::orderman::OrderServices& order_services();
void report_state(const api::orderman::OrderState &state);
bool is_live();
};
// SpreaderOrderBuilder is a thin layer on top of
// OrderBuilder, which is used to build and activate
// orders. This layer is needed so that unit tests
// can be run without actually building the
// OrderBuilder.
// The spreader has 2 SpreaderOrderBuilder for
// each leg, 1 for the quoter and 1 for the hedger
// (cons'ed and housed in SpreaderBookKeepingData)
class SpreaderOrderBuilder
{
private:
@@ -95,43 +74,16 @@ public:
SpreaderOrderBuilder (bts::orderman::OrderKey parent_key,
const api::orderman::OrderDefinition& order_def,
const SpreaderPreActivationOrderServices& spreader_pao_services,
size_t reserve_sz)
:
_is_live(spreader_pao_services.is_live())
{
if (_is_live)
{
LOG(OrderMan, Info, "SpreaderOrderBuilder.cons parent_key: {} sec_key: {}", parent_key, order_def.security_key());
_real_order_builder = bts::orderman::OrderBuilder(parent_key, order_def, spreader_pao_services.pre_services(), reserve_sz);
}
}
size_t reserve_sz);
SpreaderOrderBuilder() = delete;
SpreaderOrderBuilder(const SpreaderOrderBuilder&) = delete;
SpreaderOrderBuilder(SpreaderOrderBuilder&& other)
: _is_live(other._is_live)
{
if (_is_live)
_real_order_builder=std::move(other._real_order_builder);
// this cons should never be called. the reason we need this
// is because SpreaderOrderBuilder's are stored in a vector.
// however we know the length of the vector (n of legs), and
// hence can reserve it at construction
bts_assert(false);
}
SpreaderOrderBuilder(SpreaderOrderBuilder&& other);
SpreaderOrderBuilder& operator=(const SpreaderOrderBuilder) = delete;
SpreaderOrderBuilder& operator=(SpreaderOrderBuilder&& other) = delete;
bts::orderman::ChildOrder build()
{
if (_is_live)
return _real_order_builder.build();
else
return bts::orderman::ChildOrder();
}
void activate(SpreaderOrderServices& order_services)
{
if (_is_live)
_real_order_builder.activate(order_services.order_services());
}
// public functions ////////////////////
////////////////////////////////////////
bts::orderman::ChildOrder build();
void activate(SpreaderOrderServices& order_services);
};
}}
@@ -0,0 +1,22 @@
#include "SpreaderOrderBuilder.h"
namespace bts{
namespace orderman{
SpreaderOrderServices::SpreaderOrderServices (bts::orderman::OrderServices* order_services)
:
_is_live(order_services != nullptr),
_order_services(order_services)
{}
bts::orderman::OrderServices& SpreaderOrderServices::order_services(){
bts_assert(_is_live);
return *_order_services;
}
void SpreaderOrderServices::report_state(const api::orderman::OrderState &state){
if (is_live())
_order_services->report_state(state);
}
bool SpreaderOrderServices::is_live()
{return _is_live;}
}}
@@ -0,0 +1,30 @@
#include "SpreaderOrderBuilder.h"
namespace bts{
namespace orderman{
SpreaderPreActivationOrderServices::SpreaderPreActivationOrderServices (const bts::orderman::PreActivationOrderServices* pre_services)
:
_pre_services(pre_services),
_test_only_pre_services (nullptr)
{}
SpreaderPreActivationOrderServices::SpreaderPreActivationOrderServices (TestOnlySpreaderPreActivationOrderServices* test_only_pre_services)
:
_pre_services(nullptr),
_test_only_pre_services (test_only_pre_services)
{}
const bts::api::Security* SpreaderPreActivationOrderServices::resolve (SecurityKey key) const{
if (is_live ())
return _pre_services->sec_db.resolve(key);
else
return _test_only_pre_services->resolve(key);
}
bool SpreaderPreActivationOrderServices::is_live () const{
return _pre_services != nullptr;
}
const bts::orderman::PreActivationOrderServices& SpreaderPreActivationOrderServices::pre_services() const{
bts_assert(is_live ());
return *_pre_services;
}
}}
@@ -141,7 +141,8 @@ TEST_CASE ("test_leg_quantity_normalization", "[spreader]")
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);
bts::api::orderman::OrderDefinition order_def;
LegPropertyData leg_prop_data (0, leg, lsp, api::Side::SIDE_BUY, order_def, order_def);
Quantity calc_value = SpreaderUtils::get_leg_quantity_from_spreader_quantity (leg_prop_data, Quantity (spr_qty)),
expected_value = Quantity(static_cast<uint32_t> (std::round(std::abs(leg_mult * spr_qty))));
REQUIRE (calc_value == expected_value);
@@ -161,8 +162,9 @@ TEST_CASE ("test_leg_quantity_normalization", "[spreader]")
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);
bts::api::orderman::OrderDefinition order_def;
LegPropertyData leg_prop_data_1 (0, leg_1, lsp_1, api::Side::SIDE_BUY,order_def,order_def);
LegPropertyData leg_prop_data_2 (1, leg_2, lsp_2, api::Side::SIDE_BUY,order_def,order_def);
Quantity calc_value = SpreaderUtils::get_leg_quantity_from_another_leg_quantity (leg_prop_data_1, Quantity(leg_qty), leg_prop_data_2),
expected_value = Quantity(static_cast<uint32_t> (std::round(std::abs(leg_qty * leg_mult_2 / leg_mult_1))));
REQUIRE (calc_value == expected_value);
@@ -265,7 +267,7 @@ TEST_CASE ("spreader bookkeeping data", "[spreader]")
bts::api::orderman::OrderDefinition order_def;
fill_spreader_order_definition(order_def, Side::SIDE_BUY, synthetic_security, spreader_params);
// putting it together in SpreaderBookkeepingData
TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices::TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices pao_services (&testonly_spreader_pao_services);
std::vector<LegPropertyData> leg_props;
SpreaderUtils::resolve_synthetic_spread(pao_services, order_def, leg_props);
@@ -1578,7 +1580,7 @@ TEST_CASE ("spreader_START", "[spreader]")
bts::api::orderman::OrderDefinition order_def;
fill_spreader_order_definition(order_def, Side::SIDE_BUY, synthetic_security, spreader_params);
// putting it together in SpreaderBookkeepingData
TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices::TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices pao_services (&testonly_spreader_pao_services);
std::vector<LegPropertyData> leg_props;
SpreaderUtils::resolve_synthetic_spread(pao_services, order_def, leg_props);
@@ -1634,7 +1636,7 @@ TEST_CASE ("spreader_WORKING", "[spreader]")
bts::api::orderman::OrderDefinition order_def;
fill_spreader_order_definition(order_def, Side::SIDE_BUY, synthetic_security, spreader_params);
// putting it together in SpreaderBookkeepingData
TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices::TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices pao_services (&testonly_spreader_pao_services);
std::vector<LegPropertyData> leg_props;
SpreaderUtils::resolve_synthetic_spread(pao_services, order_def, leg_props);
@@ -1962,7 +1964,7 @@ TEST_CASE ("spreader_WAITING_FOR_CANCEL_ACK", "[spreader]")
bts::api::orderman::OrderDefinition order_def;
fill_spreader_order_definition(order_def, Side::SIDE_BUY, synthetic_security, spreader_params);
// putting it together in SpreaderBookkeepingData
TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices::TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices pao_services (&testonly_spreader_pao_services);
std::vector<LegPropertyData> leg_props;
SpreaderUtils::resolve_synthetic_spread(pao_services, order_def, leg_props);
@@ -2208,7 +2210,7 @@ TEST_CASE ("find_target_price_in_book", "[spreader]"){
Quantity out_level_qty, out_cum_qty;
bts::orderman::Book book;
uint16_t sizes[] = { 12, 91, 5, 24, 33 };
double prices[] = { 100.21875, 100.28125, 101, 101.53125, 101.71875 };
double prices[] = { 100.21875, 100.28125, 101, 101.53125, 101.71875 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL);
// first
bool res = SpreaderUtils::find_qty_at_price_level(book, bts::api::Side::SIDE_SELL, Price(100.21875), 0.03125, out_level_qty, out_cum_qty);
@@ -2241,7 +2243,94 @@ TEST_CASE ("find_target_price_in_book", "[spreader]"){
REQUIRE(out_cum_qty.value()==132);
}
}
TEST_CASE ("prehedge_payless", "[spreader]"){
SECTION("payup_true_abs_threshold"){
bts::orderman::Book book;
Price out_price;
uint16_t sizes[] = { 12, 14, 17, 19, 23 };
double prices[] = { 21.00, 21.05, 21.10, 22, 23 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL);
spark::PreHedgeQuantityBasedPayLessTicks payless_params;
payless_params.set_payless_ticks(1);
payless_params.mutable_quantity_threshold()->set_absolute(25);
auto res = SpreaderUtils::prehedge_quantity_base_payless_ticks_reprice(payless_params, book, api::Side::SIDE_BUY,
0.05, Price(21.05), Quantity(5), out_price);
REQUIRE(res);
REQUIRE(out_price.value()==21.00);
}
SECTION("payup_false_abs_threshold"){
bts::orderman::Book book;
Price out_price;
uint16_t sizes[] = { 10, 14, 17, 19, 23 };
double prices[] = { 21.00, 21.05, 21.10, 22, 23 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL);
spark::PreHedgeQuantityBasedPayLessTicks payless_params;
payless_params.set_payless_ticks(1);
payless_params.mutable_quantity_threshold()->set_absolute(25);
auto res = SpreaderUtils::prehedge_quantity_base_payless_ticks_reprice(payless_params, book, api::Side::SIDE_BUY,
0.05, Price(21.05), Quantity(5), out_price);
REQUIRE(!res);
REQUIRE(out_price.value()==21.05);
}
SECTION("payup_true_ratio_threshold"){
bts::orderman::Book book;
Price out_price;
uint16_t sizes[] = { 11, 14, 26, 19, 23 };
double prices[] = { 21.00, 21.05, 21.10, 22, 23 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL);
spark::PreHedgeQuantityBasedPayLessTicks payless_params;
payless_params.set_payless_ticks(2);
payless_params.mutable_quantity_threshold()->set_ratio(5);
auto res = SpreaderUtils::prehedge_quantity_base_payless_ticks_reprice(payless_params, book, api::Side::SIDE_BUY,
0.05, Price(21.10), Quantity(10), out_price);
REQUIRE(res);
REQUIRE(out_price.value()==21.00);
}
SECTION("payup_true_ratio_threshold"){
bts::orderman::Book book;
Price out_price;
uint16_t sizes[] = { 11, 14, 26, 19, 23 };
double prices[] = { 21.00, 21.05, 21.10, 22, 23 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL);
spark::PreHedgeQuantityBasedPayLessTicks payless_params;
payless_params.set_payless_ticks(2);
payless_params.mutable_quantity_threshold()->set_ratio(6);
auto res = SpreaderUtils::prehedge_quantity_base_payless_ticks_reprice(payless_params, book, api::Side::SIDE_BUY,
0.05, Price(21.10), Quantity(10), out_price);
REQUIRE(!res);
REQUIRE(out_price.value()==21.10);
}
}
TEST_CASE ("prehedge_payup", "[spreader]"){
SECTION("payup_true_abs_threshold"){
bts::orderman::Book book;
Price out_price;
uint16_t sizes[] = { 12, 18, 20, 19, 23 };
double prices[] = { 21.00, 21.05, 21.10, 22, 23 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL);
spark::PreHedgeQuantityBasedPayupTicks payup_params;
payup_params.set_payup_ticks(1);
payup_params.mutable_quantity_threshold()->set_absolute(55);
auto res = SpreaderUtils::prehedge_quantity_base_payup_ticks_reprice(payup_params, book, api::Side::SIDE_BUY,
0.05, Price(21.10), Quantity(5), out_price);
REQUIRE(res);
REQUIRE(bts::securities::test_price_equality(out_price.value(),21.15,0.05));
}
SECTION("payup_false_abs_threshold"){
bts::orderman::Book book;
Price out_price;
uint16_t sizes[] = { 12, 18, 20, 19, 23 };
double prices[] = { 21.00, 21.05, 21.10, 22, 23 };
fill_book (book, prices, sizes, bts::api::Side::SIDE_SELL);
spark::PreHedgeQuantityBasedPayupTicks payup_params;
payup_params.set_payup_ticks(1);
payup_params.mutable_quantity_threshold()->set_absolute(50);
auto res = SpreaderUtils::prehedge_quantity_base_payup_ticks_reprice(payup_params, book, api::Side::SIDE_BUY,
0.05, Price(21.10), Quantity(5), out_price);
REQUIRE(!res);
REQUIRE(bts::securities::test_price_equality(out_price.value(),21.10,0.05));
}
}
// class Temp
// {
// public:
@@ -13,6 +13,7 @@
#include "lib/utils/bts_chrono.h"
#include "server/sparkd/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h"
#include "server/sparkd/orderman/orders/spreader_orders/spreader/external_interfacing/SpreaderOrderBuilder.h"
#include <google/protobuf/util/message_differencer.h>
namespace bts {
namespace orderman {
@@ -206,9 +207,10 @@ LegPropertyData create_leg_property_data (const ContractLeg& leg,
PreHedgeParams pre_hp;
PostHedgeParams post_hp;
fill_leg_spreader_params (lsp, price_multiplier, is_active_quoting, qp, pre_hp, post_hp);
return LegPropertyData (leg_index, leg, lsp, leg.side());
bts::api::orderman::OrderDefinition order_def;
return LegPropertyData (leg_index, leg, lsp, leg.side(),order_def,order_def);
}
TestOnlySpreaderPreActivationOrderServices _create_spreader_pao_services(const Security& synthetic_security)
SpreaderPreActivationOrderServices::TestOnlySpreaderPreActivationOrderServices _create_spreader_pao_services(const Security& synthetic_security)
{
std::vector<Security> rv;
rv.push_back(synthetic_security);
@@ -217,7 +219,7 @@ TestOnlySpreaderPreActivationOrderServices _create_spreader_pao_services(const S
const bts::api::ContractLeg& leg = *it;
rv.push_back(leg.security());
}
TestOnlySpreaderPreActivationOrderServices test_spreader_pao_services(rv);
SpreaderPreActivationOrderServices::TestOnlySpreaderPreActivationOrderServices test_spreader_pao_services(rv);
return test_spreader_pao_services;
}
/**********************************************************************/
@@ -297,7 +299,7 @@ SpreaderManagerForTest* create_spreader_manager_2_legs (bts::orderman::OrderKey
bts::api::orderman::OrderDefinition order_def;
fill_spreader_order_definition(order_def, Side::SIDE_BUY, synthetic_security, spreader_params);
TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices::TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices pao_services (&testonly_spreader_pao_services);
std::vector<LegPropertyData> leg_props;
SpreaderUtils::resolve_synthetic_spread(pao_services, order_def, leg_props);
@@ -314,7 +316,7 @@ SpreaderManagerForTest* create_spreader_manager_n_legs (bts::orderman::OrderKey
bts::api::orderman::OrderDefinition order_def;
fill_spreader_order_definition(order_def, Side::SIDE_BUY, synthetic_security, leg_params);
TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices::TestOnlySpreaderPreActivationOrderServices testonly_spreader_pao_services = _create_spreader_pao_services(synthetic_security);
SpreaderPreActivationOrderServices pao_services (&testonly_spreader_pao_services);
std::vector<LegPropertyData> leg_props;
SpreaderUtils::resolve_synthetic_spread(pao_services, order_def, leg_props);