This commit is contained in:
Taha Afzal committed 2020-09-21 14:40:31 -04:00
commit 4a6b14caa4
43 files changed
+896 -527

No files matched your search

Binary file not shown.
+1 -1
View File
@@ -76,7 +76,7 @@ drop table if exists securities;
CREATE TABLE securities(
sid numeric,
symbol TEXT,
"group" TEXT,
sec_group TEXT,
asset TEXT,
last_t numeric
);
+1 -1
View File
@@ -1 +1 @@
set(sources algo/AlgoDefinitionServiceServer.cpp;cmds/AdminReport.cpp;cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CMECertCmd.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/FIXSim.cpp;cmds/Help.cpp;cmds/KeyCode.cpp;cmds/Md.cpp;cmds/ParseHistoricalFIX.cpp;cmds/PrintHedgeOrders.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/Span.cpp;cmds/Spartan.cpp;cmds/Test.cpp;cmds/Web.cpp;cmds/spartan/algo/RunTAS.cpp;cmds/spartan/algo/TASOrderReactor.cpp;cmds/spartan/algo/TASTriggerDef.cpp;cmds/spartan/md/mdp3/back_testing/matcher/FifoPriceLevelMatcher.cpp;cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.cpp;cmds/spartan/md/mdp3/back_testing/simulator/AlgoEventSequencer.cpp;cmds/spartan/md/mdp3/back_testing/simulator/IAlgoModel.cpp;cmds/spartan/md/mdp3/back_testing/simulator/ISimServices.cpp;cmds/spartan/md/mdp3/back_testing/simulator/Sim.cpp;cmds/spartan/md/mdp3/back_testing/simulator/SimEventSequencer.cpp;cmds/spartan/md/mdp3/back_testing/simulator/SimInput.cpp;cmds/spartan/md/mdp3/common/InstrumentSnapshot.cpp;cmds/spartan/md/mdp3/feed_control/IFeedController.cpp;cmds/spartan/md/mdp3/handler/ChannelHandler.cpp;cmds/spartan/md/mdp3/parsing/MDP3MsgBox.cpp;cmds/spartan/md/mdp3/realtime/RealTimeHandler.cpp;cmds/spartan/md/mdp3/recovery/BookSnapshot.cpp;cmds/spartan/md/mdp3/recovery/DefinitionSnapshot.cpp;cmds/spartan/md/mdp3/recovery/IncrementalQueue.cpp;cmds/spartan/md/mdp3/recovery/RecoveryHandler.cpp;cmds/spartan/md/mdp3/tests/spartan_md_tests.cpp;cmds/spartan/md/mdp3/utils/mdp3_utils.cpp;cmds/spartan/util/MCastReceiver.cpp;cmds/spartan/util/PCapReader.cpp;cmds/spartan/util/SecurityDB.cpp;dspark/mirage/quick_queue/quick_queue.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/MultipartFormDecoder.cpp;http/WebServer.cpp;http/tests/MultiPartFormTests.cpp;main.cpp;md/ChannelVolume.cpp;md/MarketDataAuxiliaryServiceServer.cpp;md/VolumeAtPriceState.cpp;md/platforms/IMDPlatform.cpp;md/platforms/ice_onixs/ICEListener.cpp;md/platforms/ice_onixs/ICEMain.cpp;md/platforms/ice_onixs/tests/ice_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;position/IPositionObserver.cpp;position/MarginServiceCore.cpp;position/MarginServiceServer.cpp;position/PositionAggregator.cpp;position/PositionMap.cpp;position/PositionServicePNLHelper.cpp;position/PositionServiceServer.cpp;position/import/BasePositionServiceServer.cpp;position/import/DownloadCommonStateMachine.cpp;position/import/DownloadWindow.cpp;position/import/MoneyFileServiceServer.cpp;position/import/parsing/gmi_parser.cpp;position/import/parsing/money_parser.cpp;position/import/parsing/parser_common.cpp;position/tests/PositionTests.cpp;position/tests/position_tests_internal.cpp;subprocess/SubProcessRunner.cpp;support/ErrorReportService.cpp;support/ShellLatencyServer.cpp;user/AdminServiceDB.cpp;user/AdminServiceServer.cpp;user/AuthServiceServer.cpp;user/tests/admin_service_tests.cpp)
set(sources algo/AlgoDefinitionServiceServer.cpp;cmds/AdminReport.cpp;cmds/AutoCert.cpp;cmds/Benchmark.cpp;cmds/CMECertCmd.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/FIXSim.cpp;cmds/Help.cpp;cmds/KeyCode.cpp;cmds/Md.cpp;cmds/ParseHistoricalFIX.cpp;cmds/PrintHedgeOrders.cpp;cmds/QuickTest.cpp;cmds/Run.cpp;cmds/Span.cpp;cmds/Spartan.cpp;cmds/Test.cpp;cmds/Web.cpp;cmds/spartan/algo/RunTAS.cpp;cmds/spartan/algo/TASOrderReactor.cpp;cmds/spartan/algo/TASTriggerDef.cpp;cmds/spartan/md/mdp3/back_testing/matcher/FifoPriceLevelMatcher.cpp;cmds/spartan/md/mdp3/back_testing/matcher/FifoSecurityMatcher.cpp;cmds/spartan/md/mdp3/back_testing/matcher/Matcher.cpp;cmds/spartan/md/mdp3/back_testing/simulator/ExchangeSim.cpp;cmds/spartan/md/mdp3/back_testing/simulator/IAlgoModel.cpp;cmds/spartan/md/mdp3/back_testing/simulator/ISimServices.cpp;cmds/spartan/md/mdp3/back_testing/simulator/SimInput.cpp;cmds/spartan/md/mdp3/back_testing/simulator/agents/AlgoAgent.cpp;cmds/spartan/md/mdp3/back_testing/simulator/agents/GatewayAgent.cpp;cmds/spartan/md/mdp3/back_testing/simulator/agents/TimerAgent.cpp;cmds/spartan/md/mdp3/back_testing/simulator/algos/SimSpreader.cpp;cmds/spartan/md/mdp3/back_testing/simulator/core/AgentBase.cpp;cmds/spartan/md/mdp3/back_testing/simulator/core/Simulator.cpp;cmds/spartan/md/mdp3/back_testing/simulator/core/tests/test_simulator_core.cpp;cmds/spartan/md/mdp3/back_testing/simulator/events/SimEvents.cpp;cmds/spartan/md/mdp3/common/InstrumentSnapshot.cpp;cmds/spartan/md/mdp3/feed_control/IFeedController.cpp;cmds/spartan/md/mdp3/handler/ChannelHandler.cpp;cmds/spartan/md/mdp3/parsing/MDP3MsgBox.cpp;cmds/spartan/md/mdp3/realtime/RealTimeHandler.cpp;cmds/spartan/md/mdp3/recovery/BookSnapshot.cpp;cmds/spartan/md/mdp3/recovery/DefinitionSnapshot.cpp;cmds/spartan/md/mdp3/recovery/IncrementalQueue.cpp;cmds/spartan/md/mdp3/recovery/RecoveryHandler.cpp;cmds/spartan/md/mdp3/tests/spartan_md_tests.cpp;cmds/spartan/md/mdp3/utils/mdp3_utils.cpp;cmds/spartan/util/MCastReceiver.cpp;cmds/spartan/util/PCapReader.cpp;cmds/spartan/util/SecurityDB.cpp;dspark/mirage/quick_queue/quick_queue.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/book/Book.cpp;exchange_sim/book/ExchangeSim.proto;exchange_sim/book/Order.cpp;exchange_sim/book/OrderMatcher.cpp;exchange_sim/book/book_transform.cpp;exchange_sim/tests/test_book_transform.cpp;http/ApiGateway.cpp;http/MultipartFormDecoder.cpp;http/WebServer.cpp;http/tests/MultiPartFormTests.cpp;main.cpp;md/ChannelVolume.cpp;md/MarketDataAuxiliaryServiceServer.cpp;md/VolumeAtPriceState.cpp;md/platforms/IMDPlatform.cpp;md/platforms/ice_onixs/ICEListener.cpp;md/platforms/ice_onixs/ICEMain.cpp;md/platforms/ice_onixs/tests/ice_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;position/IPositionObserver.cpp;position/MarginServiceCore.cpp;position/MarginServiceServer.cpp;position/PositionAggregator.cpp;position/PositionMap.cpp;position/PositionServicePNLHelper.cpp;position/PositionServiceServer.cpp;position/import/BasePositionServiceServer.cpp;position/import/DownloadCommonStateMachine.cpp;position/import/DownloadWindow.cpp;position/import/MoneyFileServiceServer.cpp;position/import/parsing/gmi_parser.cpp;position/import/parsing/money_parser.cpp;position/import/parsing/parser_common.cpp;position/tests/PositionTests.cpp;position/tests/position_tests_internal.cpp;subprocess/SubProcessRunner.cpp;support/ErrorReportService.cpp;support/ShellLatencyServer.cpp;user/AdminServiceDB.cpp;user/AdminServiceServer.cpp;user/AuthServiceServer.cpp;user/tests/admin_service_tests.cpp)
+1 -65
View File
@@ -29,71 +29,7 @@
namespace bts {
namespace cmd {
int QuickTest::execute(std::vector<std::string> const &args) {
auto cfg = config::get<config::Logging>();
cfg.mutable_console()->set_default_level("Fatal");
log::configure_logging(cfg);
auto file = args[0];
using namespace bts::spartan::mdp3;
struct Obs : IChannelObserver {
Orders previous_orders;
size_t event_id = 0;
void on_recovery_complete(
std::vector<InstrumentSnapshot const *> const &secs) override {
previous_orders.clear();
for (auto s : secs)
for (auto const &o : s->orders())
previous_orders[o.first] = o.second;
}
void on_real_time_event(MDP3Event const &ev) override {
event_id++;
for (auto s : ev.affected_securities) {
if (s->trading_status() ==
::mdp3::SecurityTradingStatus::ReadyToTrade) {
for (auto f : s->fills()) {
if (f.aggressor != MDP3Fill::THIS_BUY &&
f.aggressor != MDP3Fill::THIS_SELL) {
auto it = previous_orders.find(f.key);
bts_assert(it != previous_orders.end());
it->second.quantity.value() -= f.quantity.value();
if (it->second.quantity.value() < 0) {
std::cout << " Hidden sizes in order. "
<< " eid: " << event_id
<< " Event: " << ev
<< " Order: " << it->first
<< " Fill tid: " << f.trade_entry_id
<< std::endl;
}
}
}
}
for (auto const &ch : s->order_changes()) {
switch (ch.change) {
case OrderChange::added:
case OrderChange::updated:
previous_orders[ch.order.key] = ch.order;
break;
case OrderChange::removed:
previous_orders.erase(ch.order.key);
break;
}
}
}
}
void on_real_time_channel_loss() override {
std::cout << "Observed loss, resetting\n";
}
} obs;
spartan::mdp3::observe_channel(file, obs);
int QuickTest::execute(std::vector<std::string> const &) {
return 0;
}
@@ -67,6 +67,8 @@ FifoPriceLevelMatcher::_one_pass_cross_order(MDP3OrderKey cross_ord_key,
o.total_qty().value() > 0 ?
OrderUpdate::Status::PARTIALLY_FILLED :
OrderUpdate::Status::FILLED,
MDP3SecurityID {0},
api::SIDE_BUY,
MDP3Quantity(filled),
_price
};
@@ -77,6 +79,8 @@ FifoPriceLevelMatcher::_one_pass_cross_order(MDP3OrderKey cross_ord_key,
cross_ord_qty.value() > 0 ?
OrderUpdate::Status::PARTIALLY_FILLED :
OrderUpdate::Status::FILLED,
MDP3SecurityID {0},
api::SIDE_BUY,
MDP3Quantity(filled),
_price
};
@@ -200,7 +204,9 @@ void FifoPriceLevelMatcher::on_order_remove(MDP3OrderKey k,
bts_assert(ord_p != nullptr);
_logically_delete(*ord_p);
_compress();
OrderUpdate o = {k,OrderUpdate::Status::CANCELED,MDP3Quantity(0),_price};
OrderUpdate o = {k,OrderUpdate::Status::CANCELED,
MDP3SecurityID{0},api::SIDE_BUY,
MDP3Quantity(0),_price};
if(res != nullptr)
res->push_back(o);
}
@@ -215,4 +221,4 @@ MDP3Quantity FifoPriceLevelMatcher::on_new_opp_order(
rv = _one_pass_cross_order(opp_ord_key, std::get<1>(rv), res);
return std::get<1>(rv);
}
} // namespace bts::spartan::mdp3
} // namespace bts::spartan::mdp3
@@ -224,8 +224,7 @@ void FifoSecurityMatcher::_on_order_remove(MDP3OrderKey key,
///////////////////////////////////////////////////////////////////////////////
FifoSecurityMatcher::FifoSecurityMatcher(size_t event_id)
: _bid_book(), _ask_book(),
_search_tok(md::IntPrice(), api::Side::SIDE_BUY, Trace()), _n_unique_ords(0),
_event_id(event_id), _trace() {}
_search_tok(md::IntPrice(), api::Side::SIDE_BUY, Trace()), _event_id(event_id), _trace() {}
FifoSecurityMatcher::FifoSecurityMatcher(size_t event_id, Orders const &orders)
: FifoSecurityMatcher(event_id) {
@@ -17,7 +17,6 @@ public:
// are sorted lowest to highest
boost::container::flat_set<FifoPriceLevelMatcher> _bid_book, _ask_book;
FifoPriceLevelMatcher _search_tok;
uint32_t _n_unique_ords;
const size_t _event_id;
const Trace _trace;
private:
@@ -9,7 +9,6 @@ struct AlgoRecord;
struct AlgoAction {
MDP3TimeStamp transact_time;
AlgoRecord *algo;
OrderChange change;
};
@@ -20,6 +20,8 @@ struct OrderUpdate {
MDP3OrderKey key;
enum Status { FILLED, PARTIALLY_FILLED, CANCELED };
Status status;
MDP3SecurityID security_id;
api::Side side;
MDP3Quantity last_fills;
md::IntPrice last_price;
};
@@ -27,7 +29,7 @@ struct OrderUpdate {
using MatchEffect =
std::variant<MBPUpdate,OrderUpdate>;
struct AlgoEvent {
struct AlgoNotification {
MDP3TimeStamp transact_time;
MDP3TimeStamp observable_time;
std::variant<MBPUpdate,OrderUpdate> event;
@@ -1,59 +0,0 @@
#include "AlgoEventSequencer.h"
#include "AlgoEvent.h"
#include <queue>
namespace bts::spartan::mdp3 {
struct AlgoEventSequencer::PImpl {
struct EventSort {
bool operator()(const AlgoEvent &l, const AlgoEvent &r) const {
return l.observable_time.value() < r.observable_time.value();
}
};
using AlgoEventQueue =
std::priority_queue<AlgoEvent, std::vector<AlgoEvent>, EventSort>;
AlgoEventQueue order_updates;
AlgoEventQueue mbp_updates;
};
AlgoEventSequencer::AlgoEventSequencer() : me(new PImpl{}) {}
AlgoEventSequencer::~AlgoEventSequencer() {}
AlgoEventSequencer &AlgoEventSequencer::operator=(AlgoEventSequencer &&src) {
me = std::move(src.me);
return *this;
}
void AlgoEventSequencer::push(AlgoEvent const &ev) {
std::visit(
overloaded{[&](OrderUpdate const &) { me->order_updates.push(ev); },
[&](MBPUpdate const &) { me->mbp_updates.push(ev); }},
ev.event);
}
std::optional<AlgoEvent> AlgoEventSequencer::pop() {
if (me->order_updates.empty() ||
me->mbp_updates.empty())
return {};
else {
auto &mbp_update = me->mbp_updates.top();
auto &order_update = me->order_updates.top();
if (mbp_update.observable_time.value() <=
order_update.observable_time.value()) {
auto ev = mbp_update;
me->mbp_updates.pop();
return ev;
}
else {
auto ev = order_update;
me->order_updates.pop();
return ev;
}
}
}
} // namespace bts::spartan::mdp3
@@ -1,25 +0,0 @@
#pragma once
#include <optional>
#include <memory>
namespace bts::spartan::mdp3 {
struct AlgoEvent;
class AlgoEventSequencer {
public:
AlgoEventSequencer();
AlgoEventSequencer& operator=(AlgoEventSequencer&&);
~AlgoEventSequencer();
void push(AlgoEvent const&);
size_t size() const;
std::optional<AlgoEvent> pop();
private:
struct PImpl;
std::unique_ptr<PImpl> me;
};
}
@@ -0,0 +1,111 @@
#include "ExchangeSim.h"
#include "agents/AlgoAgent.h"
#include "agents/GatewayAgent.h"
#include "agents/TimerAgent.h"
#include "core/Simulator.h"
#include <queue>
namespace bts::spartan::mdp3 {
struct ExchangeSim::RunState {
RunState(SimOptions const &o)
: simulator(), options(o), timer(), gateways(), algos() {}
sim::Simulator simulator;
SimOptions options;
// Agents: timer, gateways and algos
TimerAgent timer;
std::vector<GatewayAgent> gateways;
std::vector<AlgoAgent> algos;
};
struct ExchangeSim::PImpl {
PImpl(std::initializer_list<SimInput> i)
: inputs(i), max_order_id(0), run_state() {
bts_assert(i.size());
for (auto &i : inputs) {
max_order_id.value() = std::max(i.max_order_id, max_order_id.value());
for (auto &i : i.instruments)
all_definitions.push_back(&i);
}
bts_assert(all_definitions.size());
}
std::vector<SimInput> inputs;
MDP3OrderKey max_order_id;
std::vector<InstrumentDefinition const *> all_definitions;
std::optional<RunState> run_state;
};
ExchangeSim::ExchangeSim(std::initializer_list<SimInput> inputs)
: me(new PImpl(inputs)) {}
ExchangeSim::~ExchangeSim() {}
double ExchangeSim::run(IAlgoModel &algo, const SimOptions &options) {
return run({&algo}, options)[0];
}
void ExchangeSim::prepare_run(std::vector<IAlgoModel *> const &algos,
const SimOptions &options) {
bts_assert(algos.size());
// Setup
me->run_state.emplace(options);
// Add timer to simulator
me->run_state->simulator.add_agent(me->run_state->timer);
// Init gateways, add them to the simulator
for (auto &i : me->inputs) {
me->run_state->gateways.emplace_back(i.instruments, options);
me->run_state->simulator.add_agent(me->run_state->gateways.back());
}
// Init algos, add them to simulator
for (auto algo : algos) {
me->run_state->algos.emplace_back(me->all_definitions, &me->max_order_id,
options, *algo);
me->run_state->simulator.add_agent(me->run_state->algos.back());
}
// Load up all the recorded events in the simulator
for (auto &i : me->inputs)
for (auto &rev : i.events)
me->run_state->simulator.emit_event<RecordedOrderChangeEvent>(
rev.transact_time.value(), rev);
bts_assert(me->run_state->simulator.pending_events_count());
// Inject a single timer event so that the timer can get started
auto first_ev_ts = me->run_state->simulator.pending_event_time();
bts_assert(first_ev_ts);
me->run_state->simulator.emit_event<TimerEvent>(first_ev_ts.value() - 1);
}
std::vector<double> ExchangeSim::run(std::vector<IAlgoModel *> const &algos,
const SimOptions &options) {
prepare_run(algos, options);
while (has_work())
do_work();
std::vector<double> pandl;
for (auto &a : me->run_state->algos)
pandl.push_back(a.pandl());
return pandl;
}
bool ExchangeSim::has_work() const {
bts_assert(me->run_state);
return me->run_state->simulator.pending_events_count() >
1; // There is always one timer event queued
}
void ExchangeSim::do_work() {
bts_assert(me->run_state);
me->run_state->simulator.run_once();
}
} // namespace bts::spartan::mdp3
@@ -0,0 +1,42 @@
#pragma once
#include "../../common/mdp3_common.h"
#include "SimInput.h"
#include "SimOptions.h"
#include <memory>
#include <vector>
namespace bts::spartan::mdp3 {
struct SimInput;
class IAlgoModel;
struct AlgoRecord;
class ExchangeSim {
public:
// Cache a set of recorded inputs to use for later running multiple
// algos.
ExchangeSim(std::initializer_list<SimInput> inputs);
~ExchangeSim();
// Run a single algo through all the SimInput events and return its
// profit and loss.
double run(IAlgoModel &, const SimOptions & = SimOptions());
// Run a set of algos and return the corresponding the profit and
// loss.
std::vector<double> run(std::vector<IAlgoModel *> const &,
const SimOptions & = SimOptions());
private:
struct PImpl;
struct RunState;
void prepare_run(std::vector<IAlgoModel *> const &, const SimOptions &);
bool has_work() const;
void do_work();
std::unique_ptr<PImpl> me;
};
} // namespace bts::spartan::mdp3
@@ -11,7 +11,8 @@ class IAlgoModel {
public:
virtual ~IAlgoModel();
virtual void init(ISimServices &) = 0;
virtual void on_event(AlgoEvent const&) = 0;
virtual void on_time(MDP3TimeStamp) {}
virtual void on_notification(AlgoNotification const&) = 0;
};
}
@@ -9,10 +9,11 @@ class InstrumentDefinition;
class ISimServices {
public:
virtual ~ISimServices();
virtual std::vector<InstrumentDefinition> const &instruments() const = 0;
virtual MDP3TimeStamp time() const = 0;
virtual std::vector<InstrumentDefinition const*> const &instruments() const = 0;
virtual MDP3OrderKey generate_order_key() = 0;
virtual void send(OrderChange const &, size_t latency_ns = 0) = 0;
virtual MDP3TimeStamp now() const = 0;
virtual void wait(uint64_t ns) = 0;
virtual void send(OrderChange const &, uint64_t propagation_delay = 0) = 0;
};
} // namespace bts::spartan::mdp3
@@ -4,7 +4,7 @@
namespace bts::spartan::mdp3 {
struct RecordedInputEvent {
struct RecordedOrderChange {
size_t event_id;
MDP3TimeStamp transact_time;
MDP3TimeStamp first_packet_send_time;
@@ -1,160 +0,0 @@
#include "Sim.h"
#include "../matcher/Matcher.h"
#include "AlgoEvent.h"
#include "AlgoEventSequencer.h"
#include "IAlgoModel.h"
#include "ISimServices.h"
#include "SimEventSequencer.h"
#include "SimInput.h"
#include "lib/utils/overloaded.h"
#include <queue>
namespace bts::spartan::mdp3 {
struct Sim::PImpl {
PImpl(SimInput const &i) : input(i) { reset(RunOptions{}); }
void reset(RunOptions const &o) {
last_order_key = input.max_order_id;
algos.clear();
matcher = Matcher{input.instruments};
order_owners = {};
simulator_time = MDP3TimeStamp{0};
options = o;
input_sequencer = SimEventSequencer{input};
output_sequencer = {};
}
SimInput const &input;
size_t last_order_key;
std::vector<std::unique_ptr<AlgoRecord>> algos;
Matcher matcher;
std::unordered_map<MDP3OrderKey, AlgoRecord *> order_owners;
MDP3TimeStamp simulator_time;
RunOptions options;
SimEventSequencer input_sequencer;
AlgoEventSequencer output_sequencer;
};
struct AlgoRecord : ISimServices {
Sim &owner;
IAlgoModel &algo;
uint64_t pandl;
MDP3TimeStamp last_send_time;
std::unordered_set<MDP3OrderKey> my_orders;
AlgoRecord(Sim &owner, IAlgoModel &algo)
: owner(owner), algo(algo), pandl(0), last_send_time(0), my_orders{} {
algo.init(*this);
}
std::vector<InstrumentDefinition> const &instruments() const override {
return owner.me->input.instruments;
}
MDP3OrderKey generate_order_key() override {
return MDP3OrderKey{++owner.me->last_order_key};
}
MDP3TimeStamp time() const override { return last_send_time; }
void send(OrderChange const &change, size_t latency_ns) override {
my_orders.insert(change.order.key);
owner.me->input_sequencer.push(AlgoAction{
MDP3TimeStamp{last_send_time.value() +
owner.me->options.base_algo_latency_ns + latency_ns},
this, change});
}
void deliver(AlgoEvent const &algo_event) {
last_send_time = algo_event.observable_time;
std::visit(
overloaded{[&](const MBPUpdate &) { algo.on_event(algo_event); },
[&](const OrderUpdate &update) {
if (my_orders.count(update.key))
algo.on_event(algo_event);
}},
algo_event.event);
}
};
Sim::Sim(SimInput const &input) : me(new PImpl{input}) {}
Sim::~Sim() {}
int64_t Sim::run(IAlgoModel &algo, const RunOptions &options) {
return run({&algo}, options)[0];
}
std::vector<uint64_t> Sim::run(std::vector<IAlgoModel *> const &algos,
const RunOptions &options) {
me->reset(options);
for (auto algo : algos)
me->algos.push_back(std::make_unique<AlgoRecord>(*this, *algo));
while (has_work())
do_work();
std::vector<uint64_t> pandl;
for (auto &ar : me->algos)
pandl.push_back(ar->pandl);
return pandl;
}
bool Sim::has_work() const { return me->input_sequencer.size(); }
void Sim::do_work() {
auto sim_event = me->input_sequencer.pop();
if (sim_event) {
std::vector<Matcher::MatchEffect> effects;
// Calculate the effects of the event
auto transact_time = std::visit(
overloaded{[&](RecordedInputEvent const &iev) {
me->matcher.match(Matcher::SIMULATOR_INPUT,
iev.order_changes, &effects);
me->simulator_time.value() =
std::max(iev.last_packet_send_time.value(),
me->simulator_time.value() + 1);
return iev.transact_time;
},
[&](AlgoAction const &algo_action) {
me->matcher.match(Matcher::ALGO, {algo_action.change},
&effects);
me->simulator_time.value() =
me->simulator_time.value() +
me->options.transaction_latency_ns;
return algo_action.transact_time;
}},
sim_event.value());
// Calculate the algo event from the effects
for (auto const &ef : effects) {
std::visit(
overloaded{
[&](MBPUpdate const &mbp) {
me->output_sequencer.push(
{transact_time,
MDP3TimeStamp{me->simulator_time.value() +
me->options.mbp_update_delay_ns},
mbp});
},
[&](OrderUpdate const &update) {
me->output_sequencer.push(
{transact_time,
MDP3TimeStamp{me->simulator_time.value() +
me->options.order_update_delay_ns},
update});
}},
ef);
}
}
while (auto algo_event = me->output_sequencer.pop()) {
for (auto &a : me->algos)
a->deliver(algo_event.value());
}
}
} // namespace bts::spartan::mdp3
@@ -1,57 +0,0 @@
#pragma once
#include "../../common/mdp3_common.h"
#include <memory>
#include <vector>
namespace bts::spartan::mdp3 {
struct SimInput;
class IAlgoModel;
struct AlgoRecord;
class Sim {
public:
// Cache a set of recorded inputs to use for later running multiple
// algos.
Sim(SimInput const &);
~Sim();
struct RunOptions {
RunOptions()
: base_algo_latency_ns(0), order_update_delay_ns(0),
mbp_update_delay_ns(0), transaction_latency_ns(0) {}
// The base latency added to all algo actions
size_t base_algo_latency_ns = 0;
// The extra time it takes for an order update to be observable
// by an algo after a sim transaction.
uint64_t order_update_delay_ns = 0;
// The extra time it takes for a book update to be observable
// by an algo after a sim transaction.
uint64_t mbp_update_delay_ns = 0;
// The latency we use to process algo actions
size_t transaction_latency_ns = 50000;
};
// Run a single algo through all the SimInput events and return its
// profit and loss.
int64_t run(IAlgoModel &, const RunOptions & = RunOptions());
// Run a set of algos and return the corresponding the profit and
// loss.
std::vector<uint64_t> run(std::vector<IAlgoModel *> const &,
const RunOptions & = RunOptions());
private:
struct PImpl;
friend struct AlgoRecord;
bool has_work() const;
void do_work();
std::unique_ptr<PImpl> me;
};
} // namespace bts::spartan::mdp3
@@ -1,11 +0,0 @@
#pragma once
#include "RecordedInputEvent.h"
#include "AlgoAction.h"
namespace bts::spartan::mdp3 {
using SimEvent = std::variant<RecordedInputEvent, AlgoAction>;
}
@@ -1,76 +0,0 @@
#include "SimEventSequencer.h"
#include "AlgoAction.h"
#include "SimInput.h"
#include "SimEvent.h"
#include <queue>
namespace bts::spartan::mdp3 {
struct SimEventSequencer::PImpl {
SimInput const *input;
size_t next_input_event;
struct ActionSort {
bool operator()(const AlgoAction &l, const AlgoAction &r) const {
return l.transact_time.value() > r.transact_time.value();
}
};
std::priority_queue<AlgoAction, std::vector<AlgoAction>, ActionSort>
pending_algo_actions;
};
SimEventSequencer::SimEventSequencer()
: me()
{}
SimEventSequencer::SimEventSequencer(SimInput const &input)
: me(new PImpl{&input, 0, {}}) {}
SimEventSequencer&SimEventSequencer::operator= (SimEventSequencer&&rhs) {
me = std::move(rhs.me);
return *this;
}
SimEventSequencer::~SimEventSequencer() {}
size_t SimEventSequencer::size() const {
return
me->input->events.size() - me->next_input_event +
me->pending_algo_actions.size();
}
void SimEventSequencer::push(AlgoAction const &action) {
me->pending_algo_actions.push(action);
}
std::optional<SimEvent> SimEventSequencer::pop() {
if (me->next_input_event != me->input->events.size() &&
me->pending_algo_actions.size()) {
// Both input events and algo actions are available, pick the
// earliest
auto &top_input_event = me->input->events[me->next_input_event];
auto &top_algo_action = me->pending_algo_actions.top();
if (top_input_event.last_packet_send_time.value() <=
top_algo_action.transact_time.value()) {
// Input queue has it
return SimEvent{me->input->events[me->next_input_event++]};
} else {
auto result = SimEvent {top_algo_action};
me->pending_algo_actions.pop();
return result;
}
} else if (me->next_input_event != me->input->events.size()) {
// Only have simulator events
return SimEvent{me->input->events[me->next_input_event++]};
} else if (me->pending_algo_actions.size()) {
// Only have algo actions
auto result = me->pending_algo_actions.top();
me->pending_algo_actions.pop();
return result;
} else
return {};
}
} // namespace bts::spartan::mdp3
@@ -1,30 +0,0 @@
#pragma once
#include "../../common/mdp3_common.h"
#include "SimEvent.h"
#include <optional>
namespace bts::spartan::mdp3 {
struct SimInput;
struct AlgoAction;
class SimEventSequencer {
public:
SimEventSequencer();
SimEventSequencer(SimInput const&);
SimEventSequencer& operator=(SimEventSequencer &&);
~SimEventSequencer();
size_t size() const;
void push(AlgoAction const&);
std::optional<SimEvent> pop();
private:
struct PImpl;
struct OrderChangeRec;
std::unique_ptr<PImpl> me;
};
}
@@ -5,34 +5,13 @@
namespace bts::spartan::mdp3 {
void SimInput::merge_with(SimInput const &other) {
instruments.reserve(instruments.size() + other.instruments.size());
instruments.insert(instruments.end(), other.instruments.begin(),
other.instruments.end());
events.reserve(events.size() + other.events.size());
events.insert(events.end(), other.events.begin(), other.events.end());
std::sort(events.begin(), events.end(),
[](auto const &ev1, auto const &ev2) {
return ev1.transact_time.value() < ev2.transact_time.value();
});
max_order_id = std::max(max_order_id, other.max_order_id);
}
SimInput make_sim_input(std::vector<std::string> const&pcaps) {
auto result = SimInput ();
for (auto const &f : pcaps)
result.merge_with(make_sim_input(f));
return result;
}
SimInput make_sim_input(std::string const &pcap) {
struct Obs : IChannelObserver {
SimInput result;
std::unordered_map<MDP3SecurityID, InstrumentDefinition> instruments;
std::vector<RecordedInputEvent> events;
std::vector<RecordedOrderChange> events;
std::unordered_set<MDP3SecurityID> ready_secs;
void on_recovery_complete(
@@ -1,19 +1,16 @@
#pragma once
#include "../../common/InstrumentDefinition.h"
#include "RecordedInputEvent.h"
#include "RecordedOrderChange.h"
namespace bts::spartan::mdp3 {
struct SimInput {
std::vector<InstrumentDefinition> instruments;
std::vector<RecordedInputEvent> events;
std::vector<RecordedOrderChange> events;
size_t max_order_id = 0;
void merge_with(SimInput const&);
};
SimInput make_sim_input(std::string const&pcap);
SimInput make_sim_input(std::vector<std::string> const&);
}
@@ -0,0 +1,27 @@
#pragma once
#include <stdlib.h>
namespace bts::spartan::mdp3 {
struct SimOptions {
SimOptions()
: base_algo_latency_ns(0), order_update_delay_ns(0),
mbp_update_delay_ns(0), transaction_latency_ns(0) {}
// The base latency added to all algo actions
size_t base_algo_latency_ns = 0;
// The extra time it takes for an order update to be observable
// by an algo after a sim transaction.
uint64_t order_update_delay_ns = 0;
// The extra time it takes for a book update to be observable
// by an algo after a sim transaction.
uint64_t mbp_update_delay_ns = 0;
// The latency we use to process algo actions
size_t transaction_latency_ns = 50000;
};
} // namespace bts::spartan::mdp3
@@ -0,0 +1,82 @@
#include "AlgoAgent.h"
#include "../IAlgoModel.h"
#include "../SimOptions.h"
namespace bts::spartan::mdp3 {
struct AlgoAgent::PImpl {
std::vector<InstrumentDefinition const *> const &definitions;
MDP3OrderKey *last_order_key;
SimOptions options;
IAlgoModel &algo;
std::unordered_set<MDP3OrderKey> my_orders = {};
std::vector<OrderUpdate> my_fills = {};
};
AlgoAgent::AlgoAgent(
std::vector<InstrumentDefinition const *> const &instruments,
MDP3OrderKey *next_order_key, SimOptions const &options, IAlgoModel &algo)
: me(new PImpl{instruments, next_order_key, options, algo}) {}
AlgoAgent::AlgoAgent(AlgoAgent &&src) : me () {
operator=(std::move(src));
}
AlgoAgent& AlgoAgent::operator=(AlgoAgent &&src) {
me = std::move(src.me);
return *this;
}
void AlgoAgent::init() { me->algo.init(*this); }
double AlgoAgent::pandl() const {
double result = 0;
for (auto f : me->my_fills) {
auto flow = (f.last_fills.value() * f.last_price.price());
if (f.side == api::SIDE_BUY)
result -= flow;
else
result += flow;
}
return result;
}
void AlgoAgent::handle(sim::Event const &ev) {
if (dynamic_cast<TimerEvent const *>(&ev)) {
me->algo.on_time(MDP3TimeStamp{time()});
} else if (auto n = dynamic_cast<AlgoNotificationEvent const *>(&ev); n) {
std::visit(overloaded{[&](const MBPUpdate &) {
me->algo.on_notification(n->ev);
},
[&](const OrderUpdate &update) {
if (me->my_orders.count(update.key)) {
if (update.last_fills.value())
me->my_fills.push_back(update);
me->algo.on_notification(n->ev);
}
}},
n->ev.event);
}
}
AlgoAgent::~AlgoAgent() {}
std::vector<InstrumentDefinition const*> const &AlgoAgent::instruments() const {
return me->definitions;
}
MDP3OrderKey AlgoAgent::generate_order_key() {
return MDP3OrderKey{++me->last_order_key->value()};
}
MDP3TimeStamp AlgoAgent::now() const { return MDP3TimeStamp{time()}; }
void AlgoAgent::wait(uint64_t ns) { forward_clock_by(ns); }
void AlgoAgent::send(OrderChange const &change, uint64_t propagation_delay) {
me->my_orders.insert(change.order.key);
emit_delayed_event<AlgoActionEvent>(
propagation_delay, AlgoAction{MDP3TimeStamp{time()}, change});
}
} // namespace bts::spartan::mdp3
@@ -0,0 +1,36 @@
#pragma once
#include "../core/AgentBase.h"
#include "../ISimServices.h"
#include "../events/SimEvents.h"
#include <memory>
#include <vector>
namespace bts::spartan::mdp3 {
struct SimOptions;
class InstrumentDefinition;
class AlgoAgent : ISimServices, public sim::AgentBase {
public:
AlgoAgent(std::vector<InstrumentDefinition const*> const &,
MDP3OrderKey *next_order,
SimOptions const&,
IAlgoModel &);
AlgoAgent(AlgoAgent &&);
~AlgoAgent();
AlgoAgent &operator=(AlgoAgent &&);
double pandl() const;
void init() override;
void handle(sim::Event const &) override;
private:
std::vector<InstrumentDefinition const*> const &instruments() const override;
MDP3OrderKey generate_order_key() override;
MDP3TimeStamp now() const override ;
void wait (uint64_t ns) override;
void send(OrderChange const &, uint64_t propagation_delay) override;
struct PImpl;
std::unique_ptr<PImpl> me;
};
} // namespace bts::spartan::mdp3
@@ -0,0 +1,116 @@
#include "GatewayAgent.h"
#include "../../../common/InstrumentDefinition.h"
#include "../../../common/mdp3_common.h"
#include "../../matcher/Matcher.h"
#include "../events/SimEvents.h"
#include "../SimOptions.h"
#include <unordered_set>
namespace bts::spartan::mdp3 {
struct GatewayAgent::PImpl {
std::unordered_set<MDP3SecurityID> my_securities;
SimOptions options;
Matcher matcher;
};
GatewayAgent::GatewayAgent(std::vector<InstrumentDefinition> const &defs,
SimOptions const &options)
: me(new PImpl()) {
for (auto const &d : defs)
me->my_securities.insert(d.security_id());
me->options = options;
}
GatewayAgent::GatewayAgent(GatewayAgent&&src) : me () {
operator=(std::move(src));
}
GatewayAgent& GatewayAgent::operator=(GatewayAgent&&src) {
me = std::move(src.me);
return *this;
}
GatewayAgent::~GatewayAgent() {}
void GatewayAgent::handle(const sim::Event &ev) {
// Recorded event
if (auto rec_ev = dynamic_cast<RecordedOrderChangeEvent const *>(&ev);
rec_ev)
_handle(*rec_ev);
else if (auto aa = dynamic_cast<AlgoActionEvent const *>(&ev); aa)
_handle(*aa);
}
// Handle a recorded order change, that is an order change we got from
// a pcap recording of the market data
void GatewayAgent::_handle(RecordedOrderChangeEvent const &e) {
auto const &ev = e.ev;
bts_assert(ev.order_changes.size());
auto &first_change = ev.order_changes[0];
if (me->my_securities.count(first_change.order.security)) {
// Advance our clock either to the send time in the recording
// (unless we are already ahead of that time, possibly because
// we got delayed processing algo operations).
auto send_time = ev.last_packet_send_time.value();
if (send_time > time())
forward_clock_by(send_time - time());
else
forward_clock_by(me->options.transaction_latency_ns);
// Now match the recorded orders and send out their effects as
// algo notification events
std::vector<Matcher::MatchEffect> effects;
me->matcher.match(Matcher::SIMULATOR_INPUT, ev.order_changes, &effects);
for (auto const &ef : effects)
std::visit(overloaded{[&](MBPUpdate const &mbp) {
emit_delayed_event<AlgoNotificationEvent>(
me->options.mbp_update_delay_ns,
AlgoNotification{ev.transact_time,
MDP3TimeStamp{time()},
mbp});
},
[&](OrderUpdate const &order_update) {
emit_delayed_event<AlgoNotificationEvent>(
me->options.order_update_delay_ns,
AlgoNotification{ev.transact_time,
MDP3TimeStamp{time()},
order_update});
}},
ef);
}
}
// Handle an algo order change, that is an order change requested by
// one of the algos under test.
void GatewayAgent::_handle(AlgoActionEvent const &e) {
auto const &algo_action = e.ev;
std::vector<Matcher::MatchEffect> effects;
me->matcher.match(Matcher::ALGO, {algo_action.change}, &effects);
for (auto const &ef : effects)
std::visit(overloaded{[&](MBPUpdate const &mbp) {
emit_delayed_event<AlgoNotificationEvent>(
me->options.mbp_update_delay_ns,
AlgoNotification{algo_action.transact_time,
MDP3TimeStamp{time()},
mbp});
},
[&](OrderUpdate const &order_update) {
emit_delayed_event<AlgoNotificationEvent>(
me->options.order_update_delay_ns,
AlgoNotification{algo_action.transact_time,
MDP3TimeStamp{time()},
order_update});
}},
ef);
}
} // namespace bts::spartan::mdp3
@@ -0,0 +1,30 @@
#pragma once
#include "../core/AgentBase.h"
#include "../events/SimEvents.h"
#include <memory>
#include <vector>
namespace bts::spartan::mdp3 {
struct SimOptions;
class InstrumentDefinition;
class GatewayAgent : public sim::AgentBase {
public:
GatewayAgent(std::vector<InstrumentDefinition> const &, SimOptions const &);
GatewayAgent(GatewayAgent&&);
GatewayAgent& operator=(GatewayAgent&&);
~GatewayAgent();
void handle(sim::Event const &) override;
private:
void _handle(RecordedOrderChangeEvent const&);
void _handle(AlgoActionEvent const&);
struct PImpl;
std::unique_ptr<PImpl> me;
};
} // namespace bts::spartan::mdp3
@@ -0,0 +1,16 @@
#include "TimerAgent.h"
#include "../events/SimEvents.h"
namespace bts::spartan::mdp3 {
TimerAgent::TimerAgent (uint64_t period_ms) : _period_ms(period_ms) {}
void TimerAgent::handle(sim::Event const &ev) {
if (dynamic_cast<TimerEvent const*> (&ev)) {
forward_clock_by(_period_ms * 1000 * 1000);
emit_event<TimerEvent> ();
}
}
}
@@ -0,0 +1,16 @@
#pragma once
#include "../core/AgentBase.h"
namespace bts::spartan::mdp3 {
class TimerAgent : public sim::AgentBase {
public:
TimerAgent (uint64_t period_ms = 100);
void handle(sim::Event const &) override;
private:
uint64_t _period_ms;
};
}
@@ -69,7 +69,8 @@ void SimSpreader::init(ISimServices& sim_services){
me->spreader.test_only_on_init_new (me->order_def,
me->pao_services);
}
void SimSpreader::on_event(AlgoEvent const& ev) {
void SimSpreader::on_notification(AlgoNotification const& ev) {
if(std::holds_alternative<MBPUpdate>(ev.event)){
// book update
const MBPUpdate& bk = std::get<MBPUpdate>(ev.event);
@@ -20,7 +20,7 @@ public:
SimSpreader(const bts::api::orderman::OrderDefinition&,
const bts::api::Security&);
void init(ISimServices&) override;
void on_event(AlgoEvent const&) override;
void on_notification(AlgoNotification const&) override;
};
}
}
@@ -0,0 +1,60 @@
#include "AgentBase.h"
#include "lib/utils/bts_assert.h"
#include <queue>
namespace bts::spartan::sim {
struct AgentBase::Self {
Simulator *simulator = nullptr;
std::queue<Event const*> pending_events;
TimeStamp agent_time = 0;
};
AgentBase::AgentBase() : self(new Self {}) {}
AgentBase::~AgentBase() {}
void AgentBase::init(Simulator &sim) {
bts_assert(self->simulator == nullptr);
self->simulator = &sim;
}
void AgentBase::enqueue(Event const& e) {
bts_assert(self->simulator);
self->pending_events.push(&e);
}
TimeStamp AgentBase::process(TimeStamp now) {
bts_assert(self->simulator);
if (self->agent_time>now)
return self->agent_time;
else
self->agent_time = now;
while (self->pending_events.size()) {
auto ev = self->pending_events.front();
self->pending_events.pop();
handle(*ev);
}
if (self->agent_time == now)
return EndOfTime;
else
return self->agent_time;
}
void AgentBase::forward_clock_by(TimeDelta delta) {
self->agent_time += delta;
}
Simulator& AgentBase::simulator() {
bts_assert(self->simulator);
return *self->simulator;
}
TimeStamp AgentBase::time() const {
return self->agent_time;
}
}
@@ -0,0 +1,40 @@
#pragma once
#include "IAgent.h"
#include "Simulator.h"
#include <memory>
namespace bts::spartan::sim {
class AgentBase : public IAgent {
protected:
AgentBase();
~AgentBase();
template <class EV,typename... Args>
void emit_event(Args &&... args) {
emit_delayed_event<EV>(0,std::forward<Args>(args)...);
}
template <class EV,typename... Args>
void emit_delayed_event(TimeDelta delay,Args &&... args) {
simulator().emit_event<EV>(time()+delay,std::forward<Args>(args)...);
}
void forward_clock_by(TimeDelta);
TimeStamp time() const;
virtual void handle(Event const&) = 0;
virtual void init() {}
private:
Simulator& simulator();
void init(Simulator &) override;
void enqueue(Event const&) override;
TimeStamp process(TimeStamp now) override;
struct Self;
std::unique_ptr<Self> self;
};
} // namespace bts::spartan::sim
@@ -0,0 +1,13 @@
#pragma once
#include "simulator_common.h"
namespace bts::spartan::sim {
class Event {
public:
virtual ~Event() {}
TimeStamp observable_time;
};
} // namespace bts::spartan::sim
@@ -0,0 +1,18 @@
#pragma once
#include "simulator_common.h"
namespace bts::spartan::sim {
class Simulator;
class Event;
class IAgent {
public:
virtual ~IAgent() {};
virtual void init(Simulator&) = 0;
virtual void enqueue(Event const&) = 0;
virtual TimeStamp process(TimeStamp now) = 0;
};
}
@@ -0,0 +1,92 @@
#include "Simulator.h"
#include "Event.h"
#include "IAgent.h"
#include "lib/utils/bts_assert.h"
#include <queue>
namespace bts::spartan::sim {
struct EventSort {
bool operator()(Event const *l, Event const *r) const {
return l->observable_time < r->observable_time;
}
};
using FutureEventQueue =
std::priority_queue<Event const *, std::vector<Event const *>, EventSort>;
struct Simulator::PImpl {
std::vector<IAgent *> agents;
std::vector<std::unique_ptr<Event>> events;
FutureEventQueue pending_events;
TimeStamp time = 0;
};
Simulator::Simulator() : me(new PImpl()) {}
Simulator::~Simulator() {}
TimeStamp Simulator::simulation_time() { return me->time; }
std::optional<TimeStamp> Simulator::pending_event_time() const {
if (me->pending_events.size())
return me->pending_events.top()->observable_time;
else
return {};
}
size_t Simulator::pending_events_count() const {
return me->pending_events.size();
}
bool Simulator::run_once() {
prepare();
if (me->pending_events.top()->observable_time <= me->time) {
auto current_ev = me->pending_events.top();
me->pending_events.pop();
for (auto &a : me->agents)
a->enqueue(*current_ev);
}
// Give all agents a chance to process their queued events
auto next_agent_interesting_time = EndOfTime;
for (auto &a : me->agents) {
auto next_ready = a->process(me->time);
next_agent_interesting_time =
std::min(next_ready, next_agent_interesting_time);
}
if (me->pending_events.empty())
return false;
else {
me->time = std::min(next_agent_interesting_time,
me->pending_events.top()->observable_time);
return true;
}
}
void Simulator::run() {
while (run_once())
;
}
void Simulator::prepare() {
bts_assert(me->agents.size());
bts_assert(me->events.size());
if (me->time == 0)
me->time = me->pending_events.top()->observable_time;
}
void Simulator::add_agent(IAgent &a) {
me->agents.emplace_back(&a);
a.init(*this);
}
void Simulator::_emit_event(TimeStamp ts, Event *ev) {
bts_assert(ts >= simulation_time());
ev->observable_time = ts;
me->events.emplace_back(ev);
me->pending_events.push(ev);
}
} // namespace bts::spartan::sim
@@ -0,0 +1,43 @@
#pragma once
#include <memory>
#include <optional>
#include "simulator_common.h"
namespace bts::spartan::sim {
class IAgent;
class Event;
class Simulator {
public:
Simulator();
~Simulator();
void add_agent(IAgent &);
template <class EV,typename... Args>
void emit_event(TimeStamp observable_time,
Args &&... args) {
_emit_event(observable_time,new EV(std::forward<Args>(args)...));
}
TimeStamp simulation_time();
std::optional<TimeStamp> pending_event_time() const;
size_t pending_events_count() const;
bool run_once();
void run();
private:
void reset();
void prepare();
void _emit_event(TimeStamp,Event*);
struct PImpl;
std::unique_ptr<PImpl> me;
};
}
@@ -0,0 +1,13 @@
#pragma once
#include <cstdint>
#include <limits>
namespace bts::spartan::sim {
using TimeStamp = uint64_t;
using TimeDelta = uint64_t;
inline const TimeStamp EndOfTime = std::numeric_limits<uint64_t>::max();
inline const TimeStamp BeginOfTime = 0;
}
@@ -0,0 +1,77 @@
// #include "../../RecordedInputEvent.h"
// #include "../../SimInput.h"
// #include "../AgentBase.h"
// #include "../Event.h"
// #include "../simulator_common.h"
// #include <catch/catch.hpp>
// #include <stdlib.h>
// namespace bts::spartan::sim::tests {
// using namespace bts::spartan::mdp3;
// struct TestEvent1 : Event {
// TestEvent1 (RecordedInputEvent const&e) : ev(e) {}
// RecordedInputEvent ev;
// };
// struct TestEvent2 : Event {
// TestEvent2 (RecordedInputEvent const&e) : ev(e) {}
// RecordedInputEvent ev;
// };
// struct RunOptions {
// RunOptions()
// : base_algo_latency_ns(0), order_update_delay_ns(0),
// mbp_update_delay_ns(0), transaction_latency_ns(0) {}
// // The base latency added to all algo actions
// size_t base_algo_latency_ns = 0;
// // The extra time it takes for an order update to be observable
// // by an algo after a sim transaction.
// uint64_t order_update_delay_ns = 0;
// // The extra time it takes for a book update to be observable
// // by an algo after a sim transaction.
// uint64_t mbp_update_delay_ns = 0;
// // The latency we use to process algo actions
// size_t transaction_latency_ns = 50000;
// };
// struct TestAgent : AgentBase {
// RunOptions options;
// void handle(Event const&e) {
// auto recorded_ev = dynamic_cast<TestEvent1 const*>(&e);
// if (recorded_ev) {
// auto send_time = recorded_ev->ev.last_packet_send_time.value();
// if (send_time > time())
// forward_clock_by(send_time - time());
// else
// forward_clock_by(options.transaction_latency_ns);
// emit_event<TestEvent2> (recorded_ev->ev);
// }
// }
// };
// TEST_CASE("Simulator Core Tests", "[simcore]") {
// auto pcap = os::sparkd_wd() + "/data_files/small_es.pcap";
// auto sim_input = make_sim_input(pcap);
// SECTION("smoke_test") {
// REQUIRE(sim_input.events.size() > 0);
// Simulator sim;
// for (auto &ev : sim_input.events)
// sim.emit_event<TestEvent1> (ev.transact_time.value(),ev);
// sim.add_agent<TestAgent>();
// while (sim.run_once())
// ;
// REQUIRE(sim.simulation_time()>0);
// }
// }
// } // namespace bts::spartan::sim::tests
@@ -0,0 +1,3 @@
#include "SimEvents.h"
@@ -0,0 +1,21 @@
#pragma once
#include "../../../common/mdp3_common.h"
#include "../AlgoEvent.h"
#include "../AlgoAction.h"
#include "../RecordedOrderChange.h"
#include "../core/Event.h"
namespace bts::spartan::mdp3 {
template <class EV> struct EventWrapper : sim::Event {
EventWrapper(EV const &e) : ev(e) {}
EV ev;
};
using RecordedOrderChangeEvent = EventWrapper<RecordedOrderChange>;
using AlgoActionEvent = EventWrapper<AlgoAction>;
using AlgoNotificationEvent = EventWrapper<AlgoNotification>;
struct TimerEvent : sim::Event {};
} // namespace bts::spartan::mdp3
+11
View File
@@ -0,0 +1,11 @@
#!/bin/bash
DIR="$(dirname "$(readlink -f "$0")")"
COMPILE_CMDS=$DIR/../../compile_commands.json
rc -J $COMPILE_CMDS
inotifywait -q -m -e close_write --format %e $COMPILE_CMDS |
while read events; do
echo Changed detected, running rc -J $COMPILE_CMDS
rc -J $COMPILE_CMDS
done