Files
spark/src/lib/md/HandleIndex.h
T

110 lines
2.8 KiB
C++

#pragma once
#ifndef _WIN32
#include "lib/domain_model/Security.h"
#include "lib/md/MDConsumerHandle.h"
#include "lib/md/MDClient.h"
#include "lib/md/ExchangeOrderKey.h"
#include "lib/utils/LockBox.h"
#include <tuple>
#include <vector>
#include <unordered_map>
#include <optional>
#include <functional>
namespace bts {
namespace md {
security_key default_key(const MDConsumerHandle& h)
{
auto&& key = h.key();
return key;
}
std::string desc_key(const MDConsumerHandle& h)
{
auto&& sec = h.get_normalized_security();
auto&& desc = securities::descriptor(sec);
return desc;
}
template<auto Key_Func>
class HandleIndex
{
MDClient& _client;
int _sub;
std::optional<MDConsumer> _consumer;
public:
typedef decltype( Key_Func(std::declval<MDConsumerHandle>()) ) KeyType;
utils::LockBox<std::unordered_map<KeyType,MDConsumerHandle>> handle_index;
utils::LockBox<std::unordered_map<KeyType,SecurityPtr>> security_index;
HandleIndex(md::MDClient& client) :
_client(client),
_sub(0),
_consumer(std::nullopt),
handle_index(),
security_index()
{
_sub = _client.on_consumer().subscribe([=](const MDConsumer& c) { on_consumer(c); });
on_consumer( _client.current_consumer() );
}
virtual ~HandleIndex()
{
_client.on_consumer().unsubscribe(_sub);
}
private:
void on_consumer(const MDConsumer& c)
{
MDConsumer temp(c);
if (temp.all_heartbeats_ok())
{
auto existing = _consumer ? _consumer->id() : 0;
LOG(md,Info, "Updating HandleIndex MDConsumer. Old {} new {}", existing, temp.id());
// clear the index
handle_index.lock([](auto& index) { index.clear(); });
security_index.lock([](auto& index) { index.clear(); });
// Swap to new consumer
if (_consumer)
{
_consumer->swap(temp);
}
else
{
_consumer = temp;
}
// Subscribe to on_security
auto id = _consumer->id();
_consumer->on_security([this,id](const SecurityPtr& sec, MDConsumerHandle handle)
{
if (_consumer->id() == id)
{
handle_index.lock([this, handle](auto& index)
{
auto key = Key_Func(handle);
index[ key ] = handle;
});
security_index.lock([this, handle, &sec](auto& index)
{
auto key = Key_Func(handle);
index[ key ] = sec;
});
}
});
}
}
};
typedef HandleIndex<default_key> KeyHandleIndex;
typedef HandleIndex<desc_key> DescHandleIndex;
}}
#endif