Skip to content

Commit

Permalink
Checkpoint 3
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenewald committed Oct 4, 2024
1 parent abd9785 commit 3570147
Show file tree
Hide file tree
Showing 24 changed files with 97 additions and 56 deletions.
2 changes: 1 addition & 1 deletion docker/dev/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ services:
- GF_AUTH_ANONYMOUS_ORG_NAME=MAIN
- GF_AUTH_ANONYMOUS_ORG_ROLE=Viewer
volumes:
- ../../exchange/docker/sandbox/grafana_data:/var/lib/grafana
- ../../exchange/docker/dev/grafana_data:/var/lib/grafana
# - /var/lib/grafana/grafana.db
# - /var/lib/grafana/alerting

Expand Down
2 changes: 1 addition & 1 deletion exchange/docker/dev/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ services:
user: "${UID}:${GID}"

ports:
- "3001:3001"
- "3000:3000"
environment:
- GF_SECURITY_ALLOW_EMBEDDING=true
- GF_AUTH_ANONYMOUS_ENABLED=true
Expand Down
Binary file modified exchange/docker/dev/grafana_data/grafana.db
Binary file not shown.
Binary file modified exchange/docker/sandbox/grafana_data/grafana.db
Binary file not shown.
5 changes: 3 additions & 2 deletions exchange/src/exchange/bots/bot_container.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
namespace nutc::exchange {

void
BotContainer::generate_orders(common::decimal_price midprice)
BotContainer::generate_orders(
common::decimal_price midprice, common::decimal_price theo
)
{
auto theo = fabs(theo_generator_.generate_next_magnitude());
variance_calculator_.record_price(midprice);

decimal_price cumulative_interest_limit{};
Expand Down
17 changes: 3 additions & 14 deletions exchange/src/exchange/bots/bot_container.hpp
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#pragma once
#include "common/types/decimal.hpp"
#include "exchange/config/dynamic/ticker_config.hpp"
#include "exchange/theo/brownian.hpp"
#include "exchange/traders/trader_container.hpp"
#include "exchange/traders/trader_types/bot_trader.hpp"
#include "shared_bot_state.hpp"
Expand All @@ -14,28 +13,18 @@ namespace nutc::exchange {
*/
class BotContainer {
using BotVector = std::vector<std::shared_ptr<BotTrader>>;
BrownianMotion theo_generator_;
VarianceCalculator variance_calculator_;

BotVector bots_{};

public:
void generate_orders(common::decimal_price midprice);
void generate_orders(common::decimal_price midprice, common::decimal_price theo);

BotContainer(
common::Ticker ticker, common::decimal_price starting_price,
TraderContainer& trader_container, bot_config bots
) :
theo_generator_(starting_price),
bots_(create_bots(trader_container, ticker, bots))
common::Ticker ticker, TraderContainer& trader_container, bot_config bots
) : bots_(create_bots(trader_container, ticker, bots))
{}

common::decimal_price
get_theo() const
{
return theo_generator_.get_magnitude();
}

double
get_variance() const
{
Expand Down
18 changes: 10 additions & 8 deletions exchange/src/exchange/bots/bot_types/market_maker.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,19 +22,20 @@ struct price_level {

// TODO: parameterize
constexpr double BASE_SPREAD = 0.16;
constexpr uint8_t LEVELS = 3;
constexpr uint8_t LEVELS = 4;
constexpr std::array<price_level, LEVELS> PRICE_LEVELS{
price_level{BASE_SPREAD + .00, 1.0 / 2},
price_level{BASE_SPREAD + .05, 1.0 / 3},
price_level{BASE_SPREAD + .10, 1.0 / 6}
price_level{BASE_SPREAD + .00, 1.0 / 2 },
price_level{BASE_SPREAD + .05, 1.0 / 3 },
price_level{BASE_SPREAD + .10, 1.0 / 8 },
price_level{BASE_SPREAD + .15, 1.0 / 24}
};

} // namespace

namespace nutc::exchange {

void
MarketMakerBot::place_orders(Side side, decimal_price theo, decimal_price spread_offset)
MarketMakerBot::place_orders_(Side side, decimal_price theo, decimal_price spread_offset)
{
// Approximation
common::decimal_quantity total_quantity = {
Expand Down Expand Up @@ -82,9 +83,10 @@ MarketMakerBot::take_action(const shared_bot_state& state)
decimal_price spread_offset = 0.0;

decimal_price lean = calculate_lean_percent(state);
decimal_price theo = state.THEO - (lean * 10.0) + generate_gaussian_noise(0, .05);

place_orders(Side::buy, theo, spread_offset);
place_orders(Side::sell, theo, spread_offset);
decimal_price theo = state.THEO - (lean * 1.0) + generate_gaussian_noise(0, .05);

place_orders_(Side::buy, theo, spread_offset);
place_orders_(Side::sell, theo, spread_offset);
}
} // namespace nutc::exchange
4 changes: 2 additions & 2 deletions exchange/src/exchange/bots/bot_types/market_maker.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,11 @@ class MarketMakerBot : public BotTrader {
return TYPE;
}

decimal_price calculate_lean_percent(const shared_bot_state& state);
static decimal_price calculate_lean_percent(const shared_bot_state& state);

private:
void
place_orders(common::Side side, decimal_price theo, decimal_price spread_offset);
place_orders_(common::Side side, decimal_price theo, decimal_price spread_offset);
};

} // namespace nutc::exchange
2 changes: 1 addition & 1 deletion exchange/src/exchange/bots/bot_types/retail.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ namespace nutc::exchange {
void
RetailBot::take_action(const shared_bot_state& state)
{
static std::uniform_real_distribution<> dis{0.0, 1.0};
static std::uniform_real_distribution<> dis{0.0, 1};

auto p_trade = common::decimal_price{1.0} - get_capital_utilization();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,15 @@ class SandboxMatchingCycle : public DevMatchingCycle {

private:
void
before_cycle_(uint64_t) override
before_cycle_(uint64_t tick) override
{
auto traders = CrowServer::get_instance().get_and_clear_pending_traders();

std::for_each(traders.begin(), traders.end(), [this](auto&& trader) {
get_traders().add_trader(trader);
});

DevMatchingCycle::before_cycle_(tick);
}
};
} // namespace nutc::exchange
13 changes: 11 additions & 2 deletions exchange/src/exchange/metrics/on_tick_metrics.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,14 @@ TickerMetricsPusher::report_ticker_stats(TickerContainer& tickers)
}
};

auto log_theo = [&](common::Ticker ticker, TickerData& info) {
ticker_theo
.Add({
{"ticker", common::to_string(ticker)}
})
.Set(double{(info.get_theo())});
};

// auto log_variance = [&](common::Ticker ticker, const TickerData& info) {
// ticker_midprice_variance_gauge
// .Add({
Expand All @@ -92,6 +100,7 @@ TickerMetricsPusher::report_ticker_stats(TickerContainer& tickers)
for (auto [ticker, info] : tickers) {
log_midprice(ticker, info);
log_best_ba(ticker, info);
log_theo(ticker, info);
// log_variance(ticker, info);
}
}
Expand Down Expand Up @@ -153,14 +162,14 @@ TickerMetricsPusher::report_trader_stats(const TickerContainer& tickers)

per_trader_pnl_gauge
.Add({
{"trader_type", trader.get_type()},
{"id", trader.get_id() },
{"trader_type", trader.get_type()},
})
.Set(pnl);
per_trader_capital_gauge
.Add({
{"trader_type", trader.get_type()},
{"id", trader.get_id() },
{"trader_type", trader.get_type()},
})
.Set(capital);
};
Expand Down
1 change: 1 addition & 0 deletions exchange/src/exchange/metrics/on_tick_metrics.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class TickerMetricsPusher {
Gauge ticker_midprice_gauge = create_gauge_("ticker_midprice");
Gauge best_ba_gauge = create_gauge_("best_ba");
Gauge ticker_midprice_variance_gauge = create_gauge_("ticker_midprice_variance");
Gauge ticker_theo = create_gauge_("ticker_theo");
Counter matches_quantity_counter = create_counter_("matches_quantity_total");
Counter orders_quantity_counter = create_counter_("orders_quantity_total");
Counter cancellation_counter = create_counter_("order_cancellations_total");
Expand Down
18 changes: 16 additions & 2 deletions exchange/src/exchange/orders/ticker_container.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#include "ticker_container.hpp"

#include "common/types/ticker.hpp"

namespace nutc::exchange {

TickerContainer::TickerContainer(
Expand Down Expand Up @@ -110,9 +112,21 @@ TickerContainer::create_tickers(
const std::vector<ticker_config>& configs, TraderContainer& traders
)
{
std::vector<TickerData> result = create_tickers();
std::vector<TickerData> result;
// this is really bad. fix soon
std::unordered_map<std::size_t, TickerData> ticker_map;
for (const auto& config : configs) {
result[std::to_underlying(config.TICKER)].set_bot_config(traders, config);
ticker_map.emplace(
std::piecewise_construct,
std::forward_as_tuple(std::to_underlying(config.TICKER)),
std::forward_as_tuple(traders, config)
);
}
for (std::size_t ticker = 0; ticker < common::TICKERS.size(); ticker++) {
if (ticker_map.contains(ticker))
result.emplace_back(ticker_map.at(ticker));
else
result.emplace_back(static_cast<common::Ticker>(ticker));
}
return result;
}
Expand Down
4 changes: 3 additions & 1 deletion exchange/src/exchange/orders/ticker_container.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ class TickerContainer {
std::vector<TickerData> tickers;

public:
TickerContainer(const std::vector<ticker_config>& configs, TraderContainer& traders);
TickerContainer(
const std::vector<ticker_config>& configs, TraderContainer& traders
);

TickerContainer();

Expand Down
25 changes: 15 additions & 10 deletions exchange/src/exchange/orders/ticker_data.hpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
#pragma once
#include "common/types/decimal.hpp"
#include "common/types/ticker.hpp"
#include "exchange/bots/bot_container.hpp"
#include "exchange/config/dynamic/ticker_config.hpp"
#include "exchange/orders/orderbook/composite_orderbook.hpp"
#include "exchange/theo/brownian.hpp"
#include "exchange/traders/trader_container.hpp"

#include <absl/hash/hash.h>
Expand All @@ -15,9 +17,15 @@ namespace nutc::exchange {
*/
class TickerData {
CompositeOrderBook limit_orderbook_;
BrownianMotion theo_generator_; // NOLINT
std::vector<BotContainer> bot_containers_;

public:
explicit TickerData(TraderContainer& traders, const ticker_config& config) :
limit_orderbook_{config.TICKER}, theo_generator_{config.STARTING_PRICE},
bot_containers_{create_bot_containers(traders, config.TICKER, config.BOTS)}
{}

explicit TickerData(common::Ticker ticker) : limit_orderbook_{ticker} {}

CompositeOrderBook&
Expand All @@ -36,32 +44,29 @@ class TickerData {
generate_bot_orders()
{
auto midprice = get_orderbook().get_midprice();
auto theo = fabs(theo_generator_.generate_next_magnitude());
std::ranges::for_each(bot_containers_, [&](auto& bot_container) {
bot_container.generate_orders(midprice);
bot_container.generate_orders(midprice, theo);
});
}

void
set_bot_config(TraderContainer& traders, const ticker_config& config)
common::decimal_price
get_theo() const
{
bot_containers_ = create_bot_containers(
traders, config.TICKER, config.STARTING_PRICE, config.BOTS
);
return theo_generator_.get_magnitude();
}

private:
static std::vector<BotContainer>
create_bot_containers(
TraderContainer& trader_container, common::Ticker ticker,
common::decimal_price starting_price, const std::vector<bot_config>& configs
const std::vector<bot_config>& configs
)
{
std::vector<BotContainer> bot_containers;
bot_containers.reserve(configs.size());
for (const bot_config& bot_config : configs) {
bot_containers.emplace_back(
ticker, starting_price, trader_container, bot_config
);
bot_containers.emplace_back(ticker, trader_container, bot_config);
}
return bot_containers;
}
Expand Down
14 changes: 9 additions & 5 deletions exchange/src/exchange/theo/brownian.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ BrownianMotion::generate_market_tick_()
return delta;
}

bool
BrownianMotion::market_event_ongoing_() const
{
return event_ticks_remaining_ > 0;
}

double
BrownianMotion::generate_nonmarket_tick_()
{
Expand All @@ -85,21 +91,19 @@ BrownianMotion::should_start_new_market_event_()
double
BrownianMotion::generate_next_magnitude()
{
bool market_event_ongoing = event_ticks_remaining_ > 0;

if (!market_event_ongoing && should_start_new_market_event_()) {
if (!market_event_ongoing_() && should_start_new_market_event_()) {
config_new_market_event_();
market_event_ongoing = true;
}

if (market_event_ongoing) {
if (market_event_ongoing_()) {
event_ticks_remaining_--;
cur_magnitude_ += generate_market_tick_();
return fabs(cur_magnitude_);
}

// Handle as a normal tick
cur_magnitude_ += generate_nonmarket_tick_();
assert(fabs(cur_magnitude_) < 1000);
return fabs(cur_magnitude_);
}

Expand Down
1 change: 1 addition & 0 deletions exchange/src/exchange/theo/brownian.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ class BrownianMotion {
generate_norm_(double mean, double stdev, Signedness sign = Signedness::Either);
double generate_uniform_(double low, double high);
bool generate_bool_(double probability_of_true);
bool market_event_ongoing_() const;

double
generate_brownian_motion_(double mean, Signedness direction = Signedness::Either);
Expand Down
6 changes: 6 additions & 0 deletions exchange/src/wrapper/messaging/exchange_communicator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ ExchangeCommunicator::consume_algorithm()
return algorithm;
}

common::tick_update
ExchangeCommunicator::consume_tick_update()
{
return consume_message<common::tick_update>();
}

template <typename T>
T
ExchangeCommunicator::consume_message()
Expand Down
7 changes: 5 additions & 2 deletions exchange/src/wrapper/messaging/exchange_communicator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ class ExchangeCommunicator {

algorithm_content consume_algorithm();

template <typename T>
T consume_message();
common::tick_update consume_tick_update();

static void publish_message(const std::string& message);

Expand All @@ -54,6 +53,10 @@ class ExchangeCommunicator {
LimitOrderFunction place_limit_order();
MarketOrderFunction place_market_order();
CancelOrderFunction cancel_order();

private:
template <typename T>
T consume_message();
};

} // namespace nutc::wrapper
Loading

0 comments on commit 3570147

Please sign in to comment.