Skip to content

Commit

Permalink
Checkpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
stevenewald committed Oct 14, 2024
1 parent 9539713 commit f8fbceb
Show file tree
Hide file tree
Showing 35 changed files with 294 additions and 213 deletions.
59 changes: 17 additions & 42 deletions exchange/src/common/messages_exchange_to_wrapper.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@

#include "common/types/decimal.hpp"
#include "common/types/position.hpp"
#include "common/types/ticker.hpp"
#include "util.hpp"

#include <fmt/format.h>
#include <glaze/glaze.hpp>

#include <chrono>

namespace nutc::common {

/**
Expand All @@ -16,52 +16,28 @@ namespace nutc::common {
*/

struct start_time {
int64_t start_time_ns;
std::int64_t start_time_ns;

start_time() = default;

explicit start_time(int64_t stns) : start_time_ns(stns) {}
};

/*f
* @brief Sent by exchange to a client to indicate a match has occurred
*/
struct match {
common::position position;
std::string buyer_id;
std::string seller_id;
common::decimal_price buyer_capital;
common::decimal_price seller_capital;
std::string match_type{};

match() = default;

match(
common::Ticker ticker, common::Side side, decimal_quantity quantity,
common::decimal_price price, std::string bid, std::string sid,
common::decimal_price bcap, common::decimal_price scap
) :
position{ticker, side, quantity, price}, buyer_id(std::move(bid)),
seller_id(std::move(sid)), buyer_capital(bcap), seller_capital(scap)
explicit start_time(std::chrono::high_resolution_clock::time_point stns) :
start_time_ns(stns.time_since_epoch().count())
{}
};

match(
const common::position& position, std::string bid, std::string sid,
common::decimal_price bcap, common::decimal_price scap
) :
position(position), buyer_id(std::move(bid)), seller_id(std::move(sid)),
buyer_capital(bcap), seller_capital(scap)
{}
struct account_update {
common::position trade;
common::decimal_price available_capital;
};

struct tick_update {
std::vector<common::position> ob_updates;
std::vector<match> matches;
std::vector<common::position> matches;

tick_update() = default;

explicit tick_update(
std::vector<common::position> ob_updates, std::vector<match> matches
std::vector<common::position> ob_updates, std::vector<common::position> matches
) : ob_updates(std::move(ob_updates)), matches(std::move(matches))
{}
};
Expand All @@ -71,7 +47,8 @@ struct algorithm_content {

algorithm_content() = default;

explicit algorithm_content(std::string algorithm) : algorithm_content_str(algorithm)
explicit algorithm_content(std::string algorithm) :
algorithm_content_str(std::move(algorithm))
{}
};

Expand All @@ -86,12 +63,10 @@ struct glz::meta<nutc::common::tick_update> {

/// \cond
template <>
struct glz::meta<nutc::common::match> {
using t = nutc::common::match;
static constexpr auto value = object(
"match", &t::position, &t::buyer_id, &t::seller_id, &t::buyer_capital,
&t::seller_capital
);
struct glz::meta<nutc::common::account_update> {
using t = nutc::common::account_update;
static constexpr auto value =
object("account_update", &t::trade, &t::available_capital);
};

/// \cond
Expand Down
6 changes: 6 additions & 0 deletions exchange/src/common/messages_wrapper_to_exchange.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@ struct cancel_order {
order_id_t order_id;
std::uint64_t timestamp = get_time();

cancel_order(Ticker ticker, order_id_t order_id) :
ticker{ticker}, order_id{order_id}
{}

cancel_order() = default;

bool
operator==(const cancel_order& other) const
{
Expand Down
3 changes: 2 additions & 1 deletion exchange/src/exchange/algos/dev_mode/dev_mode.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ DevModeAlgoInitializer::initialize_trader_container(
traders.add_trader<AlgoTrader>(algo, start_capital);
}

int64_t start_time = get_start_time(WAIT_SECS);
auto start_time = get_start_time(WAIT_SECS);
std::for_each(traders.begin(), traders.end(), [start_time](auto& trader) {
send_start_time(trader, start_time);
});
std::this_thread::sleep_until(start_time);
}

void
Expand Down
7 changes: 4 additions & 3 deletions exchange/src/exchange/algos/normal_mode/normal_mode.cpp
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#include "normal_mode.hpp"

#include "common/logging/logging.hpp"
#include "common/util.hpp"
#include "exchange/curl/curl.hpp"
#include "common/logging/logging.hpp"
#include "exchange/traders/trader_types/algo_trader.hpp"
#include "exchange/wrappers/creation/rmq_wrapper_init.hpp"

Expand Down Expand Up @@ -40,18 +40,19 @@ NormalModeAlgoInitializer::initialize_trader_container(
std::string algo_id = user["latestAlgoId"].get<std::string>();

try {
// TODO: add back
// TODO: add back
// traders.add_trader<AlgoTrader>(common::RemoteAlgorithm{}, start_capital);
log_i(main, "Created user");
} catch (const std::runtime_error& err) {
log_w(main, "Failed to create user {}", user_id);
}
}

int64_t start_time = get_start_time(WAIT_SECS);
auto start_time = get_start_time(WAIT_SECS);
std::for_each(traders.begin(), traders.end(), [start_time](auto& trader) {
send_start_time(trader, start_time);
});
std::this_thread::sleep_until(start_time);
}

glz::json_t::object_t
Expand Down
24 changes: 12 additions & 12 deletions exchange/src/exchange/matching/engine.cpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#include "engine.hpp"

#include "common/messages_exchange_to_wrapper.hpp"
#include "common/types/decimal.hpp"
#include "common/util.hpp"
#include "exchange/orders/orderbook/limit_orderbook.hpp"
Expand All @@ -9,10 +8,9 @@
namespace nutc::exchange {

enum class MatchFailure { buyer_failure, seller_failure, done_matching };
using match = nutc::common::match;

template <common::Side AggressiveSide, typename OrderPairT>
glz::expected<match, bool>
glz::expected<tagged_match, bool>
match_orders_(
OrderPairT& orders, CompositeOrderBook& orderbook, common::decimal_price order_fee
)
Expand All @@ -38,7 +36,7 @@ match_orders_(
}

template <common::Side AggressiveSide, TaggedOrder OrderT>
glz::expected<match, bool>
glz::expected<tagged_match, bool>
match_incoming_order_(
OrderT& aggressive_order, LimitOrderBook::stored_limit_order passive_order,
CompositeOrderBook& orderbook, common::decimal_price order_fee
Expand Down Expand Up @@ -73,7 +71,7 @@ total_order_cost_(
}

template <common::Side AggressiveSide, typename OrderPairT>
glz::expected<match, MatchFailure>
glz::expected<tagged_match, MatchFailure>
attempt_match_(OrderPairT& orders, common::decimal_price order_fee)
{
auto price_opt = orders.potential_match_price();
Expand All @@ -92,10 +90,12 @@ attempt_match_(OrderPairT& orders, common::decimal_price order_fee)
GenericTrader* buyer = buy_order.trader;
GenericTrader* seller = sell_order.trader;

if (!buyer->can_leverage() && buyer->get_portfolio().get_capital() < total_price) [[unlikely]]
if (!buyer->can_leverage() && buyer->get_portfolio().get_capital() < total_price)
[[unlikely]]
return glz::unexpected(MatchFailure::buyer_failure);
if (!seller->can_leverage()
&& seller->get_portfolio().get_holdings(buy_order.ticker) < match_quantity) [[unlikely]]
&& seller->get_portfolio().get_holdings(buy_order.ticker) < match_quantity)
[[unlikely]]
return glz::unexpected(MatchFailure::seller_failure);
if (buyer == seller) [[unlikely]] {
return glz::unexpected(MatchFailure::buyer_failure);
Expand All @@ -104,7 +104,7 @@ attempt_match_(OrderPairT& orders, common::decimal_price order_fee)
}

template <TaggedOrder OrderT>
glz::expected<match, bool>
glz::expected<tagged_match, bool>
match_incoming_order_(
OrderT& aggressive_order, CompositeOrderBook& orderbook,
common::decimal_price order_fee
Expand All @@ -128,12 +128,12 @@ match_incoming_order_(
}

template <TaggedOrder OrderT>
std::vector<match>
std::vector<tagged_match>
match_order(
OrderT order, CompositeOrderBook& orderbook, common::decimal_price order_fee
)
{
std::vector<match> matches;
std::vector<tagged_match> matches;

while (order.quantity != 0.0) {
auto match_opt = match_incoming_order_(order, orderbook, order_fee);
Expand All @@ -152,9 +152,9 @@ match_order(
return matches;
}

template std::vector<match>
template std::vector<tagged_match>
match_order<>(tagged_limit_order, CompositeOrderBook&, common::decimal_price);

template std::vector<match>
template std::vector<tagged_match>
match_order<>(tagged_market_order, CompositeOrderBook&, common::decimal_price);
} // namespace nutc::exchange
3 changes: 1 addition & 2 deletions exchange/src/exchange/matching/engine.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#pragma once

#include "common/messages_exchange_to_wrapper.hpp"
#include "exchange/orders/orderbook/composite_orderbook.hpp"

#include <glaze/util/expected.hpp>
Expand All @@ -10,7 +9,7 @@
namespace nutc::exchange {

template <TaggedOrder OrderT>
std::vector<common::match> match_order(
std::vector<tagged_match> match_order(
OrderT order, CompositeOrderBook& orderbook, common::decimal_price order_fee = 0.0
);

Expand Down
30 changes: 9 additions & 21 deletions exchange/src/exchange/matching/order_pair.hpp
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#pragma once

#include "common/messages_exchange_to_wrapper.hpp"
#include "common/types/decimal.hpp"
#include "common/util.hpp"
#include "exchange/orders/orderbook/composite_orderbook.hpp"
Expand Down Expand Up @@ -101,24 +100,13 @@ class OrderPair {
}

template <common::Side AggressiveSide>
common::match
tagged_match
create_match(common::decimal_quantity quantity, common::decimal_price price) const
{
auto& buyer = get_underlying_order<side::buy>();
auto& seller = get_underlying_order<side::sell>();
common::position position{buyer.ticker, AggressiveSide, quantity, price};
// TODO: match_type is pretty bad, we should have a better way of tracking this.
// It's only used for metrics
std::string match_type =
fmt::format("{}->{}", seller.trader->get_type(), buyer.trader->get_type());
// TODO: can just use TraderPortfolio instead of entire trader
common::match match{
position, buyer.trader->get_id(), seller.trader->get_id(),
buyer.trader->get_portfolio().get_capital(),
seller.trader->get_portfolio().get_capital()
};
match.match_type = match_type;
return match;
return {buyer.trader, seller.trader, position};
}

common::decimal_quantity
Expand All @@ -131,21 +119,21 @@ class OrderPair {

void
handle_match(
const common::match& match, common::decimal_price order_fee,
const tagged_match& match, common::decimal_price order_fee,
CompositeOrderBook& orderbook
)
{
get_underlying_order<side::buy>().trader->get_portfolio().notify_match(
{match.position.ticker, common::Side::buy, match.position.quantity,
match.position.price * (common::decimal_price{1.0} + order_fee)}
{match.ticker, common::Side::buy, match.quantity,
match.price * (common::decimal_price{1.0} + order_fee)}
);
get_underlying_order<side::sell>().trader->get_portfolio().notify_match(
{match.position.ticker, common::Side::sell, match.position.quantity,
match.position.price * (common::decimal_price{1.0} - order_fee)}
{match.ticker, common::Side::sell, match.quantity,
match.price * (common::decimal_price{1.0} - order_fee)}
);

change_order_quantity(seller, -match.position.quantity, orderbook);
change_order_quantity(buyer, -match.position.quantity, orderbook);
change_order_quantity(seller, -match.quantity, orderbook);
change_order_quantity(buyer, -match.quantity, orderbook);
}

private:
Expand Down
Loading

0 comments on commit f8fbceb

Please sign in to comment.