Merge branch 'master' of bitbucket.org:bluetradesys/spark
This commit is contained in:
commit
9fc0c55e48
28 files changed
+841
-103
No files matched your search
Vendored
+1
-1
@@ -41,7 +41,7 @@
|
||||
"type": "cppdbg",
|
||||
"request": "launch",
|
||||
"program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd",
|
||||
"args": ["test", "[risklimits]"],
|
||||
"args": ["test", "[position]"],
|
||||
"stopAtEntry": false,
|
||||
"cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/",
|
||||
"environment": [],
|
||||
|
||||
Vendored
+15
-4
@@ -23,10 +23,21 @@
|
||||
"taskName": "server_build",
|
||||
"type": "shell",
|
||||
"command": ".\\tools\\buildsparkd.cmd",
|
||||
|
||||
"problemMatcher": {
|
||||
"base": "$gcc",
|
||||
"fileLocation": "relative"
|
||||
"problemMatcher": {
|
||||
"base": "$gcc",
|
||||
"owner": "cpp",
|
||||
"fileLocation": [
|
||||
"relative",
|
||||
"${workspaceFolder}"
|
||||
],
|
||||
"pattern": {
|
||||
"regexp": "(.?)(home)(.?)(bts)(.?)(spark)(.?)(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)",
|
||||
"file": 8,
|
||||
"line": 9,
|
||||
"column": 10,
|
||||
"severity": 11,
|
||||
"message": 12
|
||||
}
|
||||
},
|
||||
"presentation": {
|
||||
"echo": true,
|
||||
|
||||
+1
-1
Submodule docker/linux updated: d4a32d3259...41523ccab7.
@@ -90,6 +90,8 @@ if (WIN32)
|
||||
else ()
|
||||
target_link_libraries( spark_lib
|
||||
curl
|
||||
ssl
|
||||
crypto
|
||||
fmt
|
||||
tbb
|
||||
boost_system
|
||||
@@ -112,6 +114,3 @@ endif()
|
||||
if (WIN32)
|
||||
include(${CMAKE_SOURCE_DIR}/tools/vs_filters.cmake)
|
||||
endif()
|
||||
|
||||
|
||||
|
||||
@@ -21,6 +21,10 @@ message Account {
|
||||
bool can_trade = 20;
|
||||
AccountBalance balance = 30;
|
||||
|
||||
bool enforce_margin = 40;
|
||||
bool enforce_loss_limit = 50;
|
||||
double loss_limit = 60;
|
||||
|
||||
repeated bts.api.user.OperatorID allowed_operators = 100;
|
||||
map<string, RiskLimit> future_limits = 110;
|
||||
map<string, RiskLimit> spread_limits = 120;
|
||||
|
||||
+1
-1
@@ -136,7 +136,7 @@ void SpreaderWorkingStateWorker::on_hedger_order_update(OrderKey order_key, api:
|
||||
}
|
||||
}
|
||||
void SpreaderWorkingStateWorker::on_external_error(std::string const&)
|
||||
{
|
||||
{
|
||||
_spreader->_cancel_orders (true, true);
|
||||
_spreader->_transform_to_WAITING_FOR_CANCEL_ALL ();
|
||||
}
|
||||
|
||||
@@ -1493,13 +1493,24 @@ TEST_CASE ("spreader_WAITING_FOR_FIRST_CONNECT", "[spreader]")
|
||||
spreader.on_connect ();
|
||||
verify_basic_spreader_state (spreader, SpreaderState::WORKING, spreader_price, spreader_quantity);
|
||||
LOG(OrderMan, Diag, "spreader_WAITING_FOR_FIRST_CONNECT.on_connect_securities_resolved");
|
||||
// validate data
|
||||
// leg 1
|
||||
SpreaderBookkeepingData& spreader_bookkeeping_data = spreader.test_only_func_spreader_full_data ();
|
||||
SpreaderLegData& spreader_leg_1 = spreader_bookkeeping_data.get_leg_data (0);
|
||||
const LegPropertyData& spreader_leg_1_data = spreader_leg_1.leg_property_data ();
|
||||
validate_leg_property_data (spreader_leg_1_data, 0, leg_1, leg_spreader_params_1, api::Side::SIDE_BUY);
|
||||
// leg 2
|
||||
SpreaderLegData& spreader_leg_2 = spreader_bookkeeping_data.get_leg_data (1);
|
||||
const LegPropertyData& spreader_leg_2_data = spreader_leg_2.leg_property_data ();
|
||||
validate_leg_property_data (spreader_leg_2_data, 1, leg_2, leg_spreader_params_2, api::Side::SIDE_SELL);
|
||||
}
|
||||
SECTION("4. on_update")
|
||||
{
|
||||
api::orderman::UpdateSpreaderOrder u; u.set_price(-0.05); u.set_quantity (200);
|
||||
spreader.on_update (u);
|
||||
verify_basic_spreader_state (spreader, SpreaderState::WAITING_FOR_FIRST_CONNECT, Price (-0.05), Quantity (200));
|
||||
verify_basic_spreader_state (spreader, SpreaderState::WAITING_FOR_FIRST_CONNECT, Price (-0.05), Quantity (200));
|
||||
LOG(OrderMan, Diag, "spreader_WAITING_FOR_FIRST_CONNECT.on_update");
|
||||
|
||||
}
|
||||
SECTION("5. on_cancel")
|
||||
{
|
||||
@@ -1540,6 +1551,106 @@ TEST_CASE ("spreader_WAITING_FOR_FIRST_CONNECT", "[spreader]")
|
||||
{
|
||||
}
|
||||
}
|
||||
TEST_CASE ("spreader_WORKING", "[spreader]")
|
||||
{
|
||||
ContractLeg leg_1, leg_2;
|
||||
fill_future_contract_leg (leg_1, 2468, "ES", bts::api::Venue::VENUE_GLBX, 2017, 12, 15, 1.0, api::Side::SIDE_BUY, 1.0, 0.25);
|
||||
fill_future_contract_leg (leg_2, 13579, "ES", bts::api::Venue::VENUE_GLBX, 2018, 3, 15, -1.0, api::Side::SIDE_SELL, 1.0, 0.25);
|
||||
std::vector<ContractLeg> legs;
|
||||
legs.push_back (leg_1);
|
||||
legs.push_back (leg_2);
|
||||
|
||||
QuoteParams qp_1, qp_2;
|
||||
fill_quote_params (qp_1, 1.0);
|
||||
fill_quote_params (qp_2, 1.0);
|
||||
LegSpreaderParams leg_spreader_params_1, leg_spreader_params_2;
|
||||
fill_leg_spreader_params (leg_spreader_params_1, 1.0, true, qp_1);
|
||||
fill_leg_spreader_params (leg_spreader_params_2, -1.0, true, qp_2);
|
||||
std::vector<LegSpreaderParams> leg_spreader_params;
|
||||
leg_spreader_params.push_back (leg_spreader_params_1);
|
||||
leg_spreader_params.push_back (leg_spreader_params_2);
|
||||
|
||||
Price spreader_price = Price (0);
|
||||
Quantity spreader_quantity = Quantity (100);
|
||||
|
||||
api::orderman::CreateOrderRequest cor;
|
||||
fill_create_orderorder (cor, 422, spreader_price, spreader_quantity, api::Side::SIDE_BUY, legs, leg_spreader_params);
|
||||
|
||||
MySecDB db (legs);
|
||||
NativeOrderFactory factory;
|
||||
|
||||
/*****************Creating the order********************/
|
||||
SpreaderOrder spreader (db,factory,OrderKey(1),cor);
|
||||
auto do_nothing = [] (auto const&) {};
|
||||
spreader.init_signals(do_nothing,
|
||||
do_nothing,
|
||||
do_nothing,
|
||||
do_nothing,
|
||||
do_nothing);
|
||||
spreader.init ();
|
||||
spreader.on_connect ();
|
||||
verify_basic_spreader_state (spreader, SpreaderState::WORKING, spreader_price, spreader_quantity);
|
||||
SECTION("1. init")
|
||||
{
|
||||
}
|
||||
SECTION("2. on_connect")
|
||||
{
|
||||
}
|
||||
SECTION("3. on_disconnect")
|
||||
{
|
||||
spreader.on_disconnect ();
|
||||
verify_basic_spreader_state (spreader, SpreaderState::END, spreader_price, spreader_quantity);
|
||||
// all spreaders should be in the end state
|
||||
LOG(OrderMan, Diag, "spreader_WORKING.on_disconnect");
|
||||
}
|
||||
SECTION("4. on_update")
|
||||
{
|
||||
api::orderman::UpdateSpreaderOrder u; u.set_price(-0.05); u.set_quantity (200);
|
||||
spreader.on_update (u);
|
||||
verify_basic_spreader_state (spreader, SpreaderState::WORKING, Price (-0.05), Quantity (200));
|
||||
// check spreader states
|
||||
LOG(OrderMan, Diag, "spreader_WORKING.on_update");
|
||||
}
|
||||
SECTION("5. on_cancel")
|
||||
{
|
||||
api::orderman::CancelSpreaderOrder c;
|
||||
spreader.on_cancel(c);
|
||||
verify_basic_spreader_state (spreader, SpreaderState::WAITING_FOR_CANCEL_ALL, spreader_price, spreader_quantity);
|
||||
// check spreader states
|
||||
LOG(OrderMan, Diag, "spreader_WORKING.on_cancel");
|
||||
}
|
||||
SECTION("6. on_book")
|
||||
{
|
||||
}
|
||||
SECTION("7. on_time")
|
||||
{
|
||||
}
|
||||
SECTION("8. on_quoter_order_error")
|
||||
{
|
||||
}
|
||||
SECTION("9. on_quoter_order_fill")
|
||||
{
|
||||
}
|
||||
SECTION("10. on_quoter_order_status_update")
|
||||
{
|
||||
}
|
||||
SECTION("11. on_hedger_order_error")
|
||||
{
|
||||
}
|
||||
SECTION("12. on_hedger_order_update")
|
||||
{
|
||||
}
|
||||
SECTION("13. on_external_error")
|
||||
{
|
||||
std::string err_msg = "external error";
|
||||
spreader.on_external_error (err_msg);
|
||||
verify_basic_spreader_state (spreader, SpreaderState::WAITING_FOR_CANCEL_ALL, spreader_price, spreader_quantity);
|
||||
LOG(OrderMan, Diag, "spreader_WORKING.on_external_error");
|
||||
}
|
||||
SECTION("14. on_check_termination")
|
||||
{
|
||||
}
|
||||
}
|
||||
class Temp
|
||||
{
|
||||
public:
|
||||
|
||||
@@ -334,6 +334,12 @@ void verify_basic_spreader_state (SpreaderOrder& spreader, SpreaderState state,
|
||||
bts_assert (spreader_data.price() == price);
|
||||
bts_assert (spreader_data.quantity() == quantity);
|
||||
}
|
||||
void validate_leg_property_data (const LegPropertyData& leg_property_data, size_t leg_index, const bts::api::ContractLeg& contract_leg, const bts::spark::LegSpreaderParams&, api::Side trading_side)
|
||||
{
|
||||
bts_assert (leg_property_data.leg_index() == leg_index);
|
||||
bts_assert (google::protobuf::util::MessageDifferencer::Equivalent (leg_property_data.leg_contract(), contract_leg));
|
||||
bts_assert (leg_property_data.trading_side() == trading_side);
|
||||
}
|
||||
/**********************************************************************/
|
||||
/******************************misc************************************/
|
||||
/**********************************************************************/
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#include "IMarginObserver.h"
|
||||
|
||||
namespace bts
|
||||
{
|
||||
namespace position
|
||||
{
|
||||
IMarginObserver::~IMarginObserver() {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include "server/sparkd/orderman/utils/orderman_utils.h"
|
||||
|
||||
namespace bts
|
||||
{
|
||||
namespace position
|
||||
{
|
||||
class MarginResult;
|
||||
class IMarginObserver
|
||||
{
|
||||
public:
|
||||
virtual ~IMarginObserver();
|
||||
virtual void on_margin_change(const orderman::AccountName&, const MarginResult&) = 0;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,17 @@
|
||||
#pragma once
|
||||
|
||||
#include "server/sparkd/orderman/utils/orderman_utils.h"
|
||||
#include "lib/domain_model/common.h"
|
||||
#include <string>
|
||||
|
||||
namespace bts
|
||||
{
|
||||
namespace position
|
||||
{
|
||||
struct Position;
|
||||
class IPositionObserver
|
||||
{
|
||||
public:
|
||||
virtual ~IPositionObserver();
|
||||
virtual void on_position_change(orderman::AccountName, SecurityKey, Quantity) = 0;
|
||||
virtual void on_position_change(const orderman::AccountName&, SecurityKey, double quantity, double avg_price) = 0;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "server/sparkd/orderman/utils/orderman_utils.h"
|
||||
#include "lib/domain_model/Security.pb.h"
|
||||
|
||||
namespace bts
|
||||
{
|
||||
namespace position
|
||||
{
|
||||
struct MarginResult
|
||||
{
|
||||
bool success;
|
||||
std::string settle_indicator;
|
||||
std::string settle_qualifier;
|
||||
std::string portfolio_id;
|
||||
std::string as_of_time;
|
||||
std::string calculation_id;
|
||||
|
||||
double opt_value;
|
||||
double nonopt_value;
|
||||
double maint_margin;
|
||||
double initial_margin;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,35 @@
|
||||
#include "MarginServiceCore.h"
|
||||
|
||||
#include "PositionServiceCore.h"
|
||||
#include "Position.h"
|
||||
#include "MarginResult.h"
|
||||
#include "IMarginObserver.h"
|
||||
#include "server/sparkd/securities/SecurityDB.h"
|
||||
|
||||
#include "lib/config/config.h"
|
||||
#include "lib/api/services/AccountService.pb.h"
|
||||
#include "lib/api/services/UserService.pb.h"
|
||||
|
||||
#include "lib/utils/bts_assert.h"
|
||||
#include "lib/utils/Uuid.h"
|
||||
#include "lib/utils/bts_chrono.h"
|
||||
#include "lib/logging/logging.h"
|
||||
#include "lib/utils/helper_macros.h"
|
||||
|
||||
#include "curl/curl.h"
|
||||
#include "pugixml/pugixml.hpp"
|
||||
|
||||
#include <fmt/format.h>
|
||||
#include <boost/container/flat_map.hpp>
|
||||
#include <utility>
|
||||
|
||||
#define CONSOLE_LOG(...) std::cout , __VA_ARGS__ , std::endl
|
||||
|
||||
template <typename T> std::ostream& operator,(std::ostream& out, const T& t) { out << t; return out; }
|
||||
std::ostream& operator,(std::ostream& out, std::ostream&(*f)(std::ostream&)) { out << f; return out; }
|
||||
#define MARGIN_LOG(subsystem,level,...) \
|
||||
bts::log::_thread_logger.logger->enqueue(bts::log::subsystem,level,__FILE__,__LINE__,__VA_ARGS__); \
|
||||
CONSOLE_LOG(__VA_ARGS__)
|
||||
|
||||
using namespace bts::orderman;
|
||||
|
||||
namespace bts
|
||||
{
|
||||
@@ -18,17 +38,360 @@ namespace position
|
||||
|
||||
struct MarginServiceCore::PImpl
|
||||
{
|
||||
PImpl()
|
||||
securities::SecurityDB& db;
|
||||
PositionServiceCore position_service;
|
||||
IMarginObserver* observer;
|
||||
boost::container::flat_map<orderman::AccountName, std::shared_ptr<MarginResult>> results;
|
||||
|
||||
std::string url_base, core_user, core_password, post_margin_path, get_margin_path;
|
||||
size_t max_iterations;
|
||||
bool verbose;
|
||||
PImpl(securities::SecurityDB& d, IMarginObserver* obs) :
|
||||
db(d), position_service(d), observer(obs), results(),
|
||||
url_base("https://cmecorenr.cmegroup.com/MarginServiceApi/1.4/"), core_user("api_bts1"), core_password("BT5u53r!"),
|
||||
post_margin_path("margins/?complete=true"),
|
||||
get_margin_path("margins/"),
|
||||
max_iterations(20),
|
||||
verbose(false)
|
||||
{
|
||||
auto res = curl_global_init(CURL_GLOBAL_DEFAULT);
|
||||
if(res != CURLE_OK)
|
||||
{
|
||||
MARGIN_LOG(Gen,Error,"curl_global_init() failed: ", std::string(curl_easy_strerror(res)));
|
||||
}
|
||||
}
|
||||
~PImpl()
|
||||
{
|
||||
curl_global_cleanup();
|
||||
}
|
||||
|
||||
struct CurlMsg
|
||||
{
|
||||
std::vector<char> data;
|
||||
};
|
||||
|
||||
static size_t create_reply_callback(void* contents, size_t size, size_t nmemb, void* userp)
|
||||
{
|
||||
size_t realsize = size * nmemb;
|
||||
CurlMsg& mem = *(CurlMsg*)userp;
|
||||
mem.data.reserve(mem.data.size() + realsize + 1);
|
||||
for(size_t i = 0; i < realsize; i++)
|
||||
mem.data.push_back(static_cast<char*>(contents)[i]);
|
||||
mem.data.push_back(0);
|
||||
return realsize;
|
||||
}
|
||||
|
||||
static void dump(const char* text, FILE* stream, unsigned char* ptr, size_t size)
|
||||
{
|
||||
size_t i;
|
||||
size_t c;
|
||||
unsigned int width=0x10;
|
||||
fprintf(stream, "%s, %10.10ld bytes (0x%8.8lx)\n", text, (long)size, (long)size);
|
||||
for(i=0; i<size; i+= width)
|
||||
{
|
||||
fprintf(stream, "%4.4lx: ", (long)i);
|
||||
/* show hex to the left */
|
||||
for(c = 0; c < width; c++)
|
||||
{
|
||||
if(i+c < size)
|
||||
fprintf(stream, "%02x ", ptr[i+c]);
|
||||
else
|
||||
fputs(" ", stream);
|
||||
}
|
||||
/* show data on the right */
|
||||
for(c = 0; (c < width) && (i+c < size); c++)
|
||||
{
|
||||
char x = (ptr[i+c] >= 0x20 && ptr[i+c] < 0x80) ? ptr[i+c] : '.';
|
||||
fputc(x, stream);
|
||||
}
|
||||
fputc('\n', stream); /* newline */
|
||||
}
|
||||
}
|
||||
|
||||
static int debug_callback(CURL*, curl_infotype type, char *data, size_t size, void *userp)
|
||||
{
|
||||
const char *text; UNUSED(userp);
|
||||
switch (type)
|
||||
{
|
||||
case CURLINFO_TEXT:
|
||||
//fprintf(stderr, "== Info: %s", data);
|
||||
text = "=> Info:";
|
||||
break;
|
||||
case CURLINFO_HEADER_OUT:
|
||||
text = "=> Send header";
|
||||
break;
|
||||
case CURLINFO_DATA_OUT:
|
||||
text = "=> Send data";
|
||||
break;
|
||||
case CURLINFO_SSL_DATA_OUT:
|
||||
text = "=> Send SSL data";
|
||||
break;
|
||||
case CURLINFO_HEADER_IN:
|
||||
text = "<= Recv header";
|
||||
break;
|
||||
case CURLINFO_DATA_IN:
|
||||
text = "<= Recv data";
|
||||
break;
|
||||
case CURLINFO_SSL_DATA_IN:
|
||||
text = "<= Recv SSL data";
|
||||
break;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
dump(text, stderr, (unsigned char *)data, size);
|
||||
dump(text, stdout, (unsigned char *)data, size);
|
||||
return 0;
|
||||
}
|
||||
|
||||
struct curl_slist* setup_url_and_headers(CURL* curl, const std::string& xpath)
|
||||
{
|
||||
std::string full_url = url_base + xpath;
|
||||
MARGIN_LOG(Gen,Info,"CORE Margin URL: ",full_url);
|
||||
curl_easy_setopt(curl, CURLOPT_URL, full_url.c_str());
|
||||
//curl_easy_setopt(curl, CURLOPT_URL, "https://cmecorenr.cmegroup.com/MarginServiceApi/1.4/margins/");
|
||||
curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION, debug_callback);
|
||||
if(verbose)
|
||||
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
|
||||
curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1L);
|
||||
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
|
||||
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
|
||||
|
||||
//HEADERS
|
||||
struct curl_slist *chunk = nullptr;
|
||||
chunk = curl_slist_append(chunk, std::string("username:" + core_user).c_str());
|
||||
chunk = curl_slist_append(chunk, std::string("password:" + core_password).c_str());
|
||||
chunk = curl_slist_append(chunk, "content-type:application/xml");
|
||||
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, chunk);
|
||||
curl_easy_setopt(curl, CURLOPT_USERAGENT, "libcurl-agent/1.0");
|
||||
return chunk;
|
||||
}
|
||||
|
||||
bool post(const std::string& xpath, const std::string& payload, CurlMsg& reply)
|
||||
{
|
||||
bool succ = false;
|
||||
CURL* curl = curl_easy_init();
|
||||
if (curl)
|
||||
{
|
||||
struct curl_slist* header = setup_url_and_headers(curl, xpath);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, create_reply_callback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&reply);
|
||||
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload.c_str());
|
||||
|
||||
MARGIN_LOG(Gen,Info,"CORE Margin Payload: ", payload);
|
||||
auto res = curl_easy_perform(curl);
|
||||
if(res == CURLE_OK)
|
||||
{
|
||||
std::string resp(reply.data.begin(), reply.data.end());
|
||||
MARGIN_LOG(Gen,Info,"CORE Margin Post Response: ", resp);
|
||||
succ = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
std::string error(curl_easy_strerror(res));
|
||||
MARGIN_LOG(Gen,Error,"POST curl_easy_perform() failed: ", error);
|
||||
std::cout << fmt::format("CORE Margin CURL Error: ", error);
|
||||
}
|
||||
curl_easy_cleanup(curl);
|
||||
if(header)
|
||||
curl_slist_free_all(header);
|
||||
}
|
||||
else
|
||||
{
|
||||
MARGIN_LOG(Gen,Error,"curl_easy_init() failed\n");
|
||||
}
|
||||
return succ;
|
||||
}
|
||||
|
||||
bool get(const std::string& xpath, CurlMsg& reply)
|
||||
{
|
||||
bool succ = false;
|
||||
CURL* curl = curl_easy_init();
|
||||
if (curl)
|
||||
{
|
||||
struct curl_slist* header = setup_url_and_headers(curl, xpath);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, create_reply_callback);
|
||||
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&reply);
|
||||
|
||||
auto res = curl_easy_perform(curl);
|
||||
if(res == CURLE_OK)
|
||||
{
|
||||
std::string resp(reply.data.begin(), reply.data.end());
|
||||
MARGIN_LOG(Gen,Info,"CORE Margin GET Response: ", resp);
|
||||
succ = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
MARGIN_LOG(Gen,Error,"GET curl_easy_perform() failed: ", std::string(curl_easy_strerror(res)));
|
||||
}
|
||||
curl_easy_cleanup(curl);
|
||||
if(header)
|
||||
curl_slist_free_all(header);
|
||||
}
|
||||
else
|
||||
{
|
||||
MARGIN_LOG(Gen,Error,"curl_easy_init() failed\n");
|
||||
}
|
||||
return succ;
|
||||
}
|
||||
|
||||
//For futures- it is only necessary to populate one of the following: Ticker, or Maturity Code and Clearing Code, or Maturity Code and Product Name.
|
||||
//so Ticker, Net Positions
|
||||
void create_margin_request(const std::string& portfolio_id, pugi::xml_document& doc, pugi::xml_node& trades_node)
|
||||
{
|
||||
auto att = doc.append_attribute("standalone");
|
||||
att.set_value("yes");
|
||||
auto ns = doc.append_child("ns2:marginReq");
|
||||
auto ns2 = ns.append_attribute("xmlns:ns2");
|
||||
ns2.set_value("http://cmegroup.com/schema/core/1.4");
|
||||
auto user = ns.append_attribute("reqUserId");
|
||||
user.set_value(core_user.c_str());
|
||||
|
||||
auto child = ns.append_child("margin");
|
||||
child = child.append_child("transactions");
|
||||
child = child.append_child("transaction");
|
||||
child.append_attribute("type").set_value("TRADE");
|
||||
//this doesn't seem to work, but we are ok with CME assigning a new portfolio id
|
||||
//child.append_attribute("portfolioId").set_value(portfolio_id.c_str());
|
||||
UNUSED(portfolio_id);
|
||||
child = child.append_child("payload");
|
||||
child.append_attribute("format").set_value("CSV");
|
||||
child.append_attribute("encoding").set_value("STRING");
|
||||
trades_node = child.append_child("string");
|
||||
}
|
||||
|
||||
bool parse_margin_response(const CurlMsg& msg, std::string& portfolio_id, std::string& calculation_id)
|
||||
{
|
||||
std::string str(msg.data.begin(), msg.data.end());
|
||||
pugi::xml_document doc;
|
||||
doc.load_string(str.c_str());
|
||||
|
||||
auto child = doc.child("ns2:marginRpt");
|
||||
child = child.child("margin");
|
||||
if(child)
|
||||
{
|
||||
portfolio_id = child.attribute("portfolioId").as_string();
|
||||
calculation_id = child.attribute("id").as_string();
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
void parse_margin_calculation(const CurlMsg& msg, MarginResult& result)
|
||||
{
|
||||
result.success = false;
|
||||
std::string str(msg.data.begin(), msg.data.end());
|
||||
pugi::xml_document doc;
|
||||
doc.load_string(str.c_str());
|
||||
|
||||
auto child = doc.child("ns2:marginRpt");
|
||||
child = child.child("margin");
|
||||
if(child)
|
||||
{
|
||||
result.settle_indicator = child.attribute("settleInd").as_string();
|
||||
result.settle_qualifier = child.attribute("settleQual").as_string();
|
||||
result.portfolio_id = child.attribute("portfolioId").as_string();
|
||||
result.as_of_time = child.attribute("asOfTime").as_string();
|
||||
result.calculation_id = child.attribute("id").as_string();
|
||||
auto val = child.child("amounts");
|
||||
if(val && result.portfolio_id != "")
|
||||
{
|
||||
result.opt_value = child.attribute("optVal").as_double();
|
||||
result.nonopt_value = child.attribute("nonOptVal").as_double();
|
||||
result.maint_margin = child.attribute("maint").as_double();
|
||||
result.initial_margin = child.attribute("init").as_double();
|
||||
result.success = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct xml_string_writer: pugi::xml_writer
|
||||
{
|
||||
std::string& result;
|
||||
xml_string_writer(std::string& res) : result(res) {}
|
||||
virtual void write(const void* data, size_t size)
|
||||
{
|
||||
result.append(static_cast<const char*>(data), size);
|
||||
}
|
||||
};
|
||||
|
||||
bool compute_margin(const std::string& account_name, const std::string& portfolid_id,
|
||||
const std::vector<Position>& pos, MarginResult& margin)
|
||||
{
|
||||
margin.success = false;
|
||||
pugi::xml_document doc;
|
||||
pugi::xml_node trades_node;
|
||||
create_margin_request(portfolid_id, doc, trades_node);
|
||||
std::string request = "\nFirm Id, Acct Id, Ticker Symbol, Net Positions\n";
|
||||
size_t count = 0;
|
||||
for(const auto& i : pos)
|
||||
{
|
||||
if(i.security && i.security->has_glbx())
|
||||
{
|
||||
int p = i.position.value() * (i.side == api::SIDE_SELL ? -1 : 1);
|
||||
request += fmt::format("BTS, {}, {}, {} {}", account_name, i.security->glbx().security_desc(), p, "\n");
|
||||
count++;
|
||||
}
|
||||
}
|
||||
if(count > 0)
|
||||
{
|
||||
trades_node.append_child(pugi::node_pcdata).set_value(request.c_str());
|
||||
std::string xml;
|
||||
xml_string_writer writer(xml);
|
||||
doc.save(writer);
|
||||
|
||||
size_t iters = 0;
|
||||
while(iters++ < max_iterations)
|
||||
{
|
||||
CurlMsg reply;
|
||||
sleep_for(5s);
|
||||
post(post_margin_path, xml, reply);
|
||||
std::string portid_resp, calcid_resp;
|
||||
if(parse_margin_response(reply, portid_resp, calcid_resp))
|
||||
{
|
||||
CurlMsg reply2;
|
||||
sleep_for(2s);
|
||||
if(get(get_margin_path + calcid_resp, reply2))
|
||||
{
|
||||
parse_margin_calculation(reply2, margin);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
MarginServiceCore::MarginServiceCore()
|
||||
: me(new PImpl())
|
||||
MarginServiceCore::MarginServiceCore(securities::SecurityDB& db, IMarginObserver* obs)
|
||||
: me(new PImpl(db, obs))
|
||||
{
|
||||
}
|
||||
|
||||
MarginServiceCore::~MarginServiceCore() {}
|
||||
|
||||
bool MarginServiceCore::query_margin(const orderman::AccountName& acct, MarginResult& margin)
|
||||
{
|
||||
std::vector<Position> pos;
|
||||
me->position_service.query_all_positions(acct, pos);
|
||||
utils::Uuid guid;
|
||||
bool succ = me->compute_margin(orderman::to_str(acct), guid.to_text_string(), pos, margin);
|
||||
if(me->observer)
|
||||
me->observer->on_margin_change(acct, margin);
|
||||
return succ;
|
||||
}
|
||||
|
||||
bool MarginServiceCore::query_margin(const std::vector<Position>& pos, MarginResult& margin)
|
||||
{
|
||||
utils::Uuid guid;
|
||||
std::string str = guid.to_text_string();
|
||||
return me->compute_margin(str.substr(0, 3), str, pos, margin);
|
||||
}
|
||||
|
||||
void MarginServiceCore::set_verbose_debugging(bool verb)
|
||||
{
|
||||
me->verbose = verb;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,30 @@
|
||||
#pragma once
|
||||
|
||||
#include "server/sparkd/orderman/utils/orderman_utils.h"
|
||||
#include "server/sparkd/position/Position.h"
|
||||
#include "lib/domain_model/Security.pb.h"
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
namespace bts
|
||||
{
|
||||
namespace securities { class SecurityDB; }
|
||||
namespace position
|
||||
{
|
||||
struct MarginResult;
|
||||
class IMarginObserver;
|
||||
class MarginServiceCore
|
||||
{
|
||||
BTS_NO_COPY(MarginServiceCore);
|
||||
public:
|
||||
MarginServiceCore();
|
||||
MarginServiceCore(securities::SecurityDB&, IMarginObserver* obs = nullptr);
|
||||
~MarginServiceCore();
|
||||
|
||||
// void query_margin(const std::string& account, std::string& as_of_time,
|
||||
// double& opt_value, double& nonopt_value, double& maint_margin, double& initial_margin)
|
||||
|
||||
void set_verbose_debugging(bool);
|
||||
//This is a blocking call to a WebAPI. Very Slow.
|
||||
bool query_margin(const orderman::AccountName& account, MarginResult&);
|
||||
//This is a blocking call to a WebAPI. Very Slow.
|
||||
bool query_margin(const std::vector<Position>&, MarginResult&);
|
||||
|
||||
private:
|
||||
struct PImpl;
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include "server/sparkd/orderman/utils/orderman_utils.h"
|
||||
#include "lib/domain_model/Security.pb.h"
|
||||
|
||||
namespace bts
|
||||
{
|
||||
namespace position
|
||||
{
|
||||
struct Position
|
||||
{
|
||||
orderman::AccountName account;
|
||||
const api::Security* security;
|
||||
Quantity position;
|
||||
api::Side side;
|
||||
Price avg_price;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,35 +1,141 @@
|
||||
#include "PositionServiceCore.h"
|
||||
|
||||
#include "Position.h"
|
||||
#include "IPositionObserver.h"
|
||||
#include "server/sparkd/orderman/utils/orderman_utils.h"
|
||||
#include "server/sparkd/securities/SecurityDB.h"
|
||||
|
||||
#include "lib/config/config.h"
|
||||
#include "lib/api/services/AccountService.pb.h"
|
||||
#include "lib/api/services/UserService.pb.h"
|
||||
#include "lib/utils/bts_assert.h"
|
||||
#include "lib/logging/logging.h"
|
||||
|
||||
#include <fmt/format.h>
|
||||
|
||||
using namespace bts::orderman;
|
||||
#include <boost/container/flat_map.hpp>
|
||||
#include <utility>
|
||||
|
||||
namespace bts
|
||||
{
|
||||
namespace position
|
||||
{
|
||||
|
||||
template <typename T> int sgn(T val) {
|
||||
return (T(0) < val) - (val < T(0));
|
||||
}
|
||||
|
||||
class BookEntry
|
||||
{
|
||||
public:
|
||||
orderman::AccountName account;
|
||||
SecurityKey security_key;
|
||||
double position;
|
||||
double avg_price;
|
||||
public:
|
||||
BookEntry(const orderman::AccountName& acc, SecurityKey k) :
|
||||
account(acc), security_key(k), position(0.0), avg_price(0.0)
|
||||
{
|
||||
}
|
||||
void add_fill(double last_size, double last_price, api::Side side)
|
||||
{
|
||||
if(side == api::SIDE_SELL)
|
||||
last_size = -last_size;
|
||||
if(position == 0.0 || sgn(position) == sgn(last_size))
|
||||
{
|
||||
double prev = position * avg_price;
|
||||
position += last_size;
|
||||
avg_price = prev + (last_size*last_price) / position;
|
||||
}
|
||||
else
|
||||
position += last_size;
|
||||
}
|
||||
};
|
||||
|
||||
struct PositionServiceCore::PImpl
|
||||
{
|
||||
PImpl()
|
||||
typedef std::pair<orderman::AccountName, SecurityKey> KeyType;
|
||||
boost::container::flat_map<KeyType, std::shared_ptr<BookEntry>> book;
|
||||
IPositionObserver* observer;
|
||||
PImpl(IPositionObserver* obs) : book(), observer(obs)
|
||||
{
|
||||
}
|
||||
|
||||
BookEntry& find_entry(const orderman::AccountName& account, SecurityKey skey)
|
||||
{
|
||||
KeyType key(account, skey);
|
||||
auto& entry = book[key];
|
||||
if(!entry)
|
||||
entry = std::make_shared<BookEntry>(account, skey);
|
||||
return *entry;
|
||||
}
|
||||
|
||||
void book_raw_fill(const orderman::AccountName& account, SecurityKey sec,
|
||||
double last_size, double last_price, api::Side side)
|
||||
{
|
||||
auto& entry = find_entry(account, sec);
|
||||
entry.add_fill(last_size, last_price, side);
|
||||
if(observer)
|
||||
observer->on_position_change(account, sec, entry.position, entry.avg_price);
|
||||
}
|
||||
};
|
||||
|
||||
PositionServiceCore::PositionServiceCore(const securities::SecurityDB&, IPositionObserver*)
|
||||
: me(new PImpl())
|
||||
PositionServiceCore::PositionServiceCore(securities::SecurityDB& db, IPositionObserver* obs)
|
||||
: me(new PImpl(obs)), _db(db)
|
||||
{
|
||||
}
|
||||
|
||||
PositionServiceCore::~PositionServiceCore() {}
|
||||
|
||||
bool PositionServiceCore::query_position(const orderman::AccountName& account, SecurityKey seckey, Position& result)
|
||||
{
|
||||
auto& entry = me->find_entry(account, seckey);
|
||||
auto sec = _db.resolve(entry.security_key);
|
||||
if(sec)
|
||||
{
|
||||
result.account = entry.account;
|
||||
result.avg_price = Price(entry.avg_price);
|
||||
result.position = Quantity(abs(entry.position));
|
||||
result.side = (entry.position < 0.0 ? api::SIDE_SELL : api::SIDE_BUY);
|
||||
result.security = sec;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
void PositionServiceCore::query_all_positions(const orderman::AccountName& account, std::vector<Position>& result)
|
||||
{
|
||||
result.reserve(me->book.size());
|
||||
for(auto& entry : me->book)
|
||||
{
|
||||
if(entry.first.first != account)
|
||||
continue;
|
||||
auto sec = _db.resolve(entry.second->security_key);
|
||||
if(sec)
|
||||
{
|
||||
Position pos;
|
||||
pos.account = entry.second->account;
|
||||
pos.avg_price = Price(entry.second->avg_price);
|
||||
pos.position = Quantity(abs(entry.second->position));
|
||||
pos.side = (entry.second->position < 0.0 ? api::SIDE_SELL : api::SIDE_BUY);
|
||||
pos.security = sec;
|
||||
result.push_back(pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PositionServiceCore::consume_raw_fill(const std::string& account, uint32_t security_key,
|
||||
double last_size, double last_price, api::Side side)
|
||||
{
|
||||
orderman::AccountName acc = orderman::to<orderman::AccountName>(account);
|
||||
SecurityKey skey(security_key);
|
||||
auto sec = _db.resolve(skey);
|
||||
if(sec->Contract_case() == api::Security::ContractCase::kSpread)
|
||||
{
|
||||
//TODO this is wrong; need the leg fills
|
||||
for(int i = 0; i < sec->spread().legs_size(); i++)
|
||||
me->book_raw_fill(acc, SecurityKey(sec->spread().legs(i).security().id()),
|
||||
0.0, 0.0, side);
|
||||
}
|
||||
else
|
||||
me->book_raw_fill(acc, skey, last_size, last_price, side);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
#include "server/sparkd/orderman/utils/orderman_utils.h"
|
||||
#include "lib/domain_model/common.h"
|
||||
#include "lib/domain_model/Security.pb.h"
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
|
||||
#include <memory>
|
||||
#include <functional>
|
||||
#include <vector>
|
||||
|
||||
namespace bts
|
||||
{
|
||||
namespace securities { class SecurityDB; }
|
||||
namespace position
|
||||
{
|
||||
struct Position;
|
||||
class IPositionObserver;
|
||||
class PositionServiceCore
|
||||
{
|
||||
BTS_NO_COPY(PositionServiceCore);
|
||||
public:
|
||||
PositionServiceCore(const securities::SecurityDB&, IPositionObserver* obs = nullptr);
|
||||
PositionServiceCore(securities::SecurityDB&, IPositionObserver* obs = nullptr);
|
||||
~PositionServiceCore();
|
||||
|
||||
void query_position(const orderman::AccountName, SecurityKey sec, Quantity& position);
|
||||
bool query_position(const orderman::AccountName&, SecurityKey, Position&);
|
||||
void query_all_positions(const orderman::AccountName&, std::vector<Position>&);
|
||||
|
||||
private:
|
||||
void consume_raw_fill(const std::string& account, uint32_t security_key,
|
||||
@@ -30,7 +29,8 @@ private:
|
||||
|
||||
private:
|
||||
struct PImpl;
|
||||
std::unique_ptr<PImpl> me;
|
||||
std::unique_ptr<PImpl> me;
|
||||
securities::SecurityDB& _db;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
#include "catch/catch.hpp"
|
||||
|
||||
#include "../MarginServiceCore.h"
|
||||
#include "../PositionServiceCore.h"
|
||||
#include "../Position.h"
|
||||
#include "../MarginResult.h"
|
||||
#include "../IMarginObserver.h"
|
||||
|
||||
#include "server/sparkd/orderman/utils/orderman_utils.h"
|
||||
#include "server/sparkd/securities/SecurityDB.h"
|
||||
#include "server/sparkd/user/AccountServiceServer.h"
|
||||
#include "server/sparkd/user/UserServiceServer.h"
|
||||
|
||||
#include "lib/config/config.h"
|
||||
#include "lib/api/public/ServiceContext.h"
|
||||
#include "lib/api/services/AccountService.client.pb.h"
|
||||
#include "lib/api/services/UserService.client.pb.h"
|
||||
#include "lib/domain_model/Security.pb.h"
|
||||
#include "lib/utils/helper_macros.h"
|
||||
|
||||
#include <future>
|
||||
#include <memory>
|
||||
#include <stdlib.h>
|
||||
|
||||
namespace bts
|
||||
{
|
||||
namespace position
|
||||
{
|
||||
|
||||
TEST_CASE ("Margin API", "[margin]")
|
||||
{
|
||||
securities::SecurityDB _db;
|
||||
MarginServiceCore _margin(_db);
|
||||
|
||||
SECTION("test1")
|
||||
{
|
||||
bts::securities::ISecurityDB::SecurityMap secs = _db.retrieve_all();
|
||||
Position p;
|
||||
for(const auto& i : secs)
|
||||
{
|
||||
if(i.second->has_future() && i.second->symbol() == "ES")
|
||||
p.security = i.second;
|
||||
}
|
||||
auto acct = orderman::to<orderman::AccountName>("TAG1");
|
||||
p.account = acct;
|
||||
p.avg_price = Price(2500.0);
|
||||
p.position = Quantity(1);
|
||||
p.side = api::SIDE_BUY;
|
||||
std::vector<Position> pos;
|
||||
pos.push_back(p);
|
||||
p.position = Quantity(3);
|
||||
p.side = api::SIDE_SELL;
|
||||
pos.push_back(p);
|
||||
|
||||
MarginResult res;
|
||||
//_margin.set_verbose_debugging(true);
|
||||
_margin.query_margin(pos, res);
|
||||
REQUIRE(res.success);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}}
|
||||
|
||||
|
||||
@@ -23,15 +23,15 @@ namespace risklimits
|
||||
{
|
||||
|
||||
SharedLimiterData::SharedLimiterData(const AccountName& acct, const SymbolKey& sym) :
|
||||
account_info({ acct, 0, 1.0, false }),
|
||||
account_name(acct),
|
||||
account_info(api::account::Account::default_instance()),
|
||||
position_info({ sym, 0u, 0u, 0u, 0u }),
|
||||
risk_limit(),
|
||||
info_string()
|
||||
{
|
||||
std::string account, opid;
|
||||
to_str(account_info.account.value(), &account);
|
||||
info_string = " Additional Information: AccountName: " + account
|
||||
+ " Symbol: " + std::get<0>(position_info.symbol);
|
||||
std::string account;
|
||||
to_str(acct.value(), &account);
|
||||
info_string = " Additional Information: AccountName: " + account + " Symbol: " + std::get<0>(position_info.symbol);
|
||||
}
|
||||
|
||||
|
||||
@@ -85,19 +85,26 @@ void AccountRiskLimiter::allowed_operators(std::vector<orderman::OperatorID>& op
|
||||
}
|
||||
|
||||
void AccountRiskLimiter::on_account_update(const api::account::Account& acct)
|
||||
{
|
||||
//TODO This is a little strange-- we update the account, but not the limits,
|
||||
//we break those down above and call down below. Might want to rework this
|
||||
bts_assert(to<AccountName>(acct.tag1()) == me->shared_data.account_info.account);
|
||||
bool prev = me->shared_data.account_info.can_trade;
|
||||
me->shared_data.account_info.can_trade = acct.can_trade();
|
||||
me->shared_data.account_info.cash_position = acct.balance().cash_position();
|
||||
me->shared_data.account_info.leverage_factor = acct.balance().leverage_factor();
|
||||
if(prev != me->shared_data.account_info.can_trade)
|
||||
{
|
||||
bts_assert(acct.tag1() == me->shared_data.account_info.tag1() || me->shared_data.account_info.tag1() == "");
|
||||
me->shared_data.account_info = acct;
|
||||
me->shared_data.risk_limit = api::account::RiskLimit::default_instance();
|
||||
if(me->shared_data.position_info.symbol.second == api::Security::ContractCase::kFuture)
|
||||
{
|
||||
for(const auto& i : me->operator_map)
|
||||
i.second->on_account_update();
|
||||
}
|
||||
auto iter = acct.future_limits().find(me->shared_data.position_info.symbol.first);
|
||||
if(iter != acct.future_limits().end())
|
||||
me->shared_data.risk_limit = iter->second;
|
||||
}
|
||||
else if(me->shared_data.position_info.symbol.second == api::Security::ContractCase::kSpread)
|
||||
{
|
||||
auto iter = acct.spread_limits().find(me->shared_data.position_info.symbol.first);
|
||||
if(iter != acct.spread_limits().end())
|
||||
me->shared_data.risk_limit = iter->second;
|
||||
}
|
||||
else
|
||||
bts_assert_msg(false, "got risk limit for unknown contract type");
|
||||
for(const auto& i : me->operator_map)
|
||||
i.second->notify_subscribers();
|
||||
}
|
||||
|
||||
void AccountRiskLimiter::on_operator_update(const api::user::Operator& oper)
|
||||
@@ -106,9 +113,11 @@ void AccountRiskLimiter::on_operator_update(const api::user::Operator& oper)
|
||||
lim.on_operator_update(oper);
|
||||
}
|
||||
|
||||
void AccountRiskLimiter::on_risk_limit_update(const api::account::RiskLimit& risk)
|
||||
void AccountRiskLimiter::on_margin_update(const position::MarginResult& margin)
|
||||
{
|
||||
me->shared_data.risk_limit = risk;
|
||||
me->shared_data.margin = margin;
|
||||
for(const auto& i : me->operator_map)
|
||||
i.second->notify_subscribers();
|
||||
}
|
||||
|
||||
const api::account::RiskLimit& AccountRiskLimiter::risk_limit()
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#pragma once
|
||||
|
||||
#include "server/sparkd/orderman/utils/orderman_utils.h"
|
||||
#include "SymbolKey.h"
|
||||
#include "server/sparkd/risk_limits/SymbolKey.h"
|
||||
#include "server/sparkd/position/MarginResult.h"
|
||||
#include "lib/api/services/AccountService.pb.h"
|
||||
#include "lib/api/services/UserService.pb.h"
|
||||
#include "lib/utils/bts_no_copy.h"
|
||||
@@ -11,20 +12,6 @@
|
||||
|
||||
namespace bts
|
||||
{
|
||||
namespace api
|
||||
{
|
||||
namespace user
|
||||
{
|
||||
class User;
|
||||
class Operator;
|
||||
}
|
||||
namespace account
|
||||
{
|
||||
class Account;
|
||||
class AccountBalance;
|
||||
class RiskLimit;
|
||||
}
|
||||
}
|
||||
namespace risklimits
|
||||
{
|
||||
class RiskLimitManager;
|
||||
@@ -34,12 +21,13 @@ class SharedLimiterData
|
||||
BTS_NO_COPY(SharedLimiterData);
|
||||
public:
|
||||
SharedLimiterData(const orderman::AccountName&, const SymbolKey&);
|
||||
struct AccountInfo { orderman::AccountName account;
|
||||
int cash_position; double leverage_factor; bool can_trade; } account_info;
|
||||
orderman::AccountName account_name;
|
||||
api::account::Account account_info;
|
||||
struct PositionInfo { SymbolKey symbol;
|
||||
uint32_t long_position; uint32_t short_position;
|
||||
uint32_t long_working; uint32_t short_working; } position_info;
|
||||
api::account::RiskLimit risk_limit;
|
||||
position::MarginResult margin;
|
||||
std::string info_string;
|
||||
};
|
||||
|
||||
@@ -58,8 +46,8 @@ public:
|
||||
protected:
|
||||
friend class RiskLimitManager;
|
||||
void on_account_update(const api::account::Account&);
|
||||
void on_risk_limit_update(const api::account::RiskLimit&);
|
||||
void on_operator_update(const api::user::Operator&);
|
||||
void on_operator_update(const api::user::Operator&);
|
||||
void on_margin_update(const position::MarginResult&);
|
||||
|
||||
protected:
|
||||
friend class RiskLimitsTests;
|
||||
|
||||
@@ -42,8 +42,8 @@ struct OperatorRiskLimiter::PImpl
|
||||
|
||||
void notify()
|
||||
{
|
||||
bool status = operator_can_trade && account.shared_data().account_info.can_trade;
|
||||
RiskLimitState state = { account.shared_data().account_info.account,
|
||||
bool status = operator_can_trade && account.shared_data().account_info.can_trade();
|
||||
RiskLimitState state = { to<AccountName>(account.shared_data().account_info.tag1()),
|
||||
operator_id, status };
|
||||
auto obs = account.manager().observer();
|
||||
if(obs)
|
||||
@@ -82,7 +82,7 @@ void OperatorRiskLimiter::on_operator_update(const api::user::Operator& oper)
|
||||
me->notify();
|
||||
}
|
||||
|
||||
void OperatorRiskLimiter::on_account_update()
|
||||
void OperatorRiskLimiter::notify_subscribers()
|
||||
{
|
||||
me->notify();
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ public:
|
||||
protected:
|
||||
friend class AccountRiskLimiter;
|
||||
void on_operator_update(const api::user::Operator&);
|
||||
void on_account_update();
|
||||
void notify_subscribers();
|
||||
protected:
|
||||
friend class RiskLimitsTests;
|
||||
friend class RiskLimiter;
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
#include "lib/utils/helper_macros.h"
|
||||
|
||||
#include <boost/container/flat_map.hpp>
|
||||
#include <tuple>
|
||||
#include <utility>
|
||||
|
||||
using namespace bts::orderman;
|
||||
|
||||
@@ -21,7 +21,7 @@ namespace bts
|
||||
{
|
||||
namespace risklimits
|
||||
{
|
||||
using KeyType = std::tuple<AccountName, SymbolKey>;
|
||||
using KeyType = std::pair<AccountName, SymbolKey>;
|
||||
using SharedLimiterMap = boost::container::flat_map<KeyType, std::shared_ptr<AccountRiskLimiter>>;
|
||||
|
||||
using OperatorMap = boost::container::flat_map<std::string, api::user::Operator>;
|
||||
@@ -50,7 +50,6 @@ struct RiskLimitManager::PImpl
|
||||
{
|
||||
AccountRiskLimiter& lim = find_limiter(to_accountname(acct), to_symbolkey(j.first, contract_type));
|
||||
lim.on_account_update(acct);
|
||||
lim.on_risk_limit_update(j.second);
|
||||
lim.on_operator_update(allowed->second);
|
||||
}
|
||||
}
|
||||
@@ -110,6 +109,13 @@ RiskLimiter& RiskLimitManager::find_limiter(const AccountName& acctname, const O
|
||||
return sym.find_limiter(opid, key);
|
||||
}
|
||||
|
||||
void RiskLimitManager::on_margin_update(const orderman::AccountName& account, const position::MarginResult& margin)
|
||||
{
|
||||
for(const auto& i : me->limiter_map)
|
||||
if(i.first.first == account)
|
||||
i.second->on_margin_update(margin);
|
||||
}
|
||||
|
||||
AccountRiskLimiter& RiskLimitManager::find_shared_limiter(const AccountName& acctname, const api::Security& security)
|
||||
{
|
||||
AccountRiskLimiter& shared = me->find_limiter(acctname, me->to_symbolkey(security));
|
||||
|
||||
@@ -23,6 +23,7 @@ namespace api
|
||||
class AccountBalance;
|
||||
}
|
||||
}
|
||||
namespace position { struct MarginResult; }
|
||||
namespace risklimits
|
||||
{
|
||||
class IRiskLimitObserver;
|
||||
@@ -34,12 +35,12 @@ class RiskLimitManager
|
||||
public:
|
||||
RiskLimitManager(IRiskLimitObserver* observer = nullptr);
|
||||
~RiskLimitManager();
|
||||
|
||||
RiskLimiter& find_limiter(const orderman::AccountName&, const orderman::OperatorID&,
|
||||
const api::Security&, orderman::OrderKey);
|
||||
|
||||
void initialize(const std::vector<api::account::Account>&, const std::vector<api::user::User>&);
|
||||
RiskLimiter& find_limiter(const orderman::AccountName&, const orderman::OperatorID&,
|
||||
const api::Security&, orderman::OrderKey);
|
||||
void on_margin_update(const orderman::AccountName&, const position::MarginResult&);
|
||||
IRiskLimitObserver* observer();
|
||||
|
||||
protected:
|
||||
friend class RiskLimitsTests;
|
||||
AccountRiskLimiter& find_shared_limiter(const orderman::AccountName&, const api::Security&);
|
||||
|
||||
@@ -38,9 +38,9 @@ struct RiskLimiter::PImpl
|
||||
}
|
||||
bool check_can_trade(std::string& message) const
|
||||
{
|
||||
if(!shared.account_info.can_trade)
|
||||
if(!shared.account_info.can_trade())
|
||||
{
|
||||
std::string acct; to_str(shared.account_info.account.value(), &acct);
|
||||
const std::string& acct = shared.account_info.tag1();
|
||||
message = fmt::format("Account {} does not have permission to trade. {}", acct, shared.info_string);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -97,10 +97,6 @@ public:
|
||||
{
|
||||
shared.on_operator_update(oper);
|
||||
}
|
||||
static void risk_limit_update(AccountRiskLimiter& shared, const api::account::RiskLimit& risk)
|
||||
{
|
||||
shared.on_risk_limit_update(risk);
|
||||
}
|
||||
static void order_state_update(RiskLimiter& lim,api::Side side, Quantity quantity, Quantity filled_quantity)
|
||||
{
|
||||
lim.on_order_state(side,quantity,filled_quantity);
|
||||
@@ -232,7 +228,7 @@ TEST_CASE ("RiskLimits Limits", "[risklimits]")
|
||||
api::Security sec = api::Security::default_instance();
|
||||
setup_security(sec, data.position_info.symbol);
|
||||
OrderKey key(0);
|
||||
RiskLimiter& lim = _manager.find_limiter(data.account_info.account, operators[0], sec, key);
|
||||
RiskLimiter& lim = _manager.find_limiter(to<orderman::AccountName>(data.account_info.tag1()), operators[0], sec, key);
|
||||
auto res = lim.check(Quantity(rand() % limits.max_order_size()), api::SIDE_BUY);
|
||||
REQUIRE(res.success);
|
||||
res = lim.check(Quantity(rand() % limits.max_order_size()), api::SIDE_SELL);
|
||||
@@ -244,7 +240,7 @@ TEST_CASE ("RiskLimits Limits", "[risklimits]")
|
||||
|
||||
{
|
||||
api::account::Account new_account = api::account::Account::default_instance();
|
||||
new_account.set_tag1(to_str(data.account_info.account));
|
||||
new_account.set_tag1(data.account_info.tag1());
|
||||
new_account.set_can_trade(false);
|
||||
RiskLimitsTests::account_update(*i.get(), new_account);
|
||||
bool ok = limits_ok(state);
|
||||
@@ -312,9 +308,9 @@ TEST_CASE ("RiskLimits Limits", "[risklimits]")
|
||||
auto maxorder = limits.max_order_size();
|
||||
|
||||
OrderKey key1(0);
|
||||
RiskLimiter& lim1 = manager.find_limiter(data->account_info.account, operators[0], sec, key1);
|
||||
RiskLimiter& lim1 = manager.find_limiter(to<orderman::AccountName>(data->account_info.tag1()), operators[0], sec, key1);
|
||||
OrderKey key2(1);
|
||||
RiskLimiter& lim2 = manager.find_limiter(data->account_info.account, operators[1], sec, key2);
|
||||
RiskLimiter& lim2 = manager.find_limiter(to<orderman::AccountName>(data->account_info.tag1()), operators[1], sec, key2);
|
||||
lim1.on_order_state(side, Quantity(maxpos), Quantity(maxpos));
|
||||
auto r1 = lim1.check(Quantity(maxorder), side);
|
||||
REQUIRE(!r1.success);
|
||||
@@ -366,13 +362,13 @@ TEST_CASE ("RiskLimits Limits", "[risklimits]")
|
||||
int iters = 2;
|
||||
for(int i = 0; i < iters; i++)
|
||||
{
|
||||
RiskLimiter& lim = observed_manager.find_limiter(data.account_info.account, operators[0], sec, key);
|
||||
RiskLimiter& lim = observed_manager.find_limiter(to<orderman::AccountName>(data.account_info.tag1()), operators[0], sec, key);
|
||||
SharedLimiterData& shared2 = RiskLimitsTests::shared_data(lim);
|
||||
auto limsym = shared2.position_info.symbol.first;
|
||||
auto limtype = shared2.position_info.symbol.second;
|
||||
REQUIRE(limsym == secsym);
|
||||
REQUIRE(type == sectype);
|
||||
REQUIRE(shared2.account_info.account == data.account_info.account);
|
||||
REQUIRE(shared2.account_info.tag1() == data.account_info.tag1());
|
||||
REQUIRE(&shared2 == &data);
|
||||
|
||||
RiskLimiter::RiskLimitResult res;
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "SingleFillHedger.h"
|
||||
#include "SpreaderHedgerData.h"
|
||||
#include "SpreaderOrderUpdateMessage.h"
|
||||
#include <google/protobuf/util/message_differencer.h>
|
||||
|
||||
namespace bts{
|
||||
namespace orderman{
|
||||
|
||||
+1
-1
@@ -3,4 +3,4 @@ setlocal
|
||||
cd %~dp0\..
|
||||
call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\Tools\VsDevCmd.bat" > nul
|
||||
cd %~dp0\..
|
||||
cmd /C start "" "C:\Program Files\Microsoft VS Code\Code.exe"
|
||||
cmd /C start "" "C:\Program Files\Microsoft VS Code\Code.exe" "%*" -n
|
||||
Reference in new issue
Block a user