Slick Trader 0.11.0
Multi-broker algorithmic trading engine with plugin strategies and a live web dashboard
Loading...
Searching...
No Matches
strategy_loader.cpp
Go to the documentation of this file.
3#include <slick/logger.hpp>
4#include <format>
5
6#ifdef _WIN32
7 #include <windows.h>
8#else
9 #include <dlfcn.h>
10#endif
11
12namespace slick::trader {
13
17
18std::shared_ptr<IStrategy> StrategyLoader::load(const std::string& library_path) {
19 // Unload any existing strategy first
20 if (is_loaded()) {
21 LOG_WARN("StrategyLoader: Unloading existing strategy before loading new one");
22 unload();
23 }
24
25 library_path_ = library_path;
26 last_error_.clear();
27
28#ifdef _WIN32
29 // Windows: LoadLibrary
30 handle_ = LoadLibrary(library_path.c_str());
31 if (!handle_) {
32 DWORD error = GetLastError();
33 LOG_ERROR("StrategyLoader: Failed to load library: {} (error: {})", library_path, std::to_string(error));
34 return nullptr;
35 }
36
37 // Get function pointers
38 auto get_api_version_func = reinterpret_cast<GetApiVersionFunc>(GetProcAddress(static_cast<HMODULE>(handle_), "get_strategy_api_version"));
39 create_func_ = reinterpret_cast<CreateStrategyFunc>(GetProcAddress(static_cast<HMODULE>(handle_), "create_strategy"));
40 destroy_func_ = reinterpret_cast<DestroyStrategyFunc>(GetProcAddress(static_cast<HMODULE>(handle_), "destroy_strategy"));
41 auto get_name_func = reinterpret_cast<GetNameFunc>(GetProcAddress(static_cast<HMODULE>(handle_), "get_strategy_name"));
42 auto get_version_func = reinterpret_cast<GetVersionFunc>(GetProcAddress(static_cast<HMODULE>(handle_), "get_strategy_version"));
43 auto set_logger_func = reinterpret_cast<SetLoggerFunc>(GetProcAddress(static_cast<HMODULE>(handle_), "set_logger_instance"));
44 auto set_broker_status_func = reinterpret_cast<SetBrokerStatusFunc>(GetProcAddress(static_cast<HMODULE>(handle_), "set_broker_status_registry"));
45
46#else
47 // Unix: dlopen
48 handle_ = dlopen(library_path.c_str(), RTLD_LAZY | RTLD_LOCAL);
49 if (!handle_) {
50 LOG_ERROR("StrategyLoader: Failed to load library: {} (error: {})", library_path, std::string(dlerror()));
51 return nullptr;
52 }
53
54 // Clear any existing errors
55 dlerror();
56
57 // Get function pointers
58 auto get_api_version_func = reinterpret_cast<GetApiVersionFunc>(dlsym(handle_, "get_strategy_api_version"));
59 create_func_ = reinterpret_cast<CreateStrategyFunc>(dlsym(handle_, "create_strategy"));
60 destroy_func_ = reinterpret_cast<DestroyStrategyFunc>(dlsym(handle_, "destroy_strategy"));
61 auto get_name_func = reinterpret_cast<GetNameFunc>(dlsym(handle_, "get_strategy_name"));
62 auto get_version_func = reinterpret_cast<GetVersionFunc>(dlsym(handle_, "get_strategy_version"));
63 auto set_logger_func = reinterpret_cast<SetLoggerFunc>(dlsym(handle_, "set_logger_instance"));
64 auto set_broker_status_func = reinterpret_cast<SetBrokerStatusFunc>(dlsym(handle_, "set_broker_status_registry"));
65#endif
66
67 // Verify required functions exist
68 if (!create_func_ || !destroy_func_) {
69 LOG_ERROR("StrategyLoader: Library missing required functions (create_strategy/destroy_strategy)");
70 unload();
71 return nullptr;
72 }
73
74 // Built against another interface, the plugin would call and index this host's types by its
75 // own layout of them: refused here rather than crashing on the first call.
76 const uint32_t api_version = get_api_version_func ? get_api_version_func() : 0;
77 if (api_version != STRATEGY_API_VERSION) {
78 last_error_ = api_version == 0
79 ? std::format("built before plugins named their API version; this host takes version {}. "
80 "Rebuild it against this slick-trader", STRATEGY_API_VERSION)
81 : std::format("built against strategy API version {}; this host takes version {}. "
82 "Rebuild it against this slick-trader", api_version, STRATEGY_API_VERSION);
83 LOG_ERROR("StrategyLoader: {} {}", library_path, last_error_);
84 unload();
85 return nullptr;
86 }
87
88 // Forward host logger to plugin so LOG_* macros in the plugin route to the
89 // same initialized logger instance rather than the plugin-local singleton.
90 if (set_logger_func) {
91 set_logger_func(&slick::logger::Logger::instance());
92 }
93
94 // Same problem, same fix: the plugin statically links slick-trader-core and so owns
95 // a private BrokerStatusRegistry that nothing writes. Without this the plugin reads
96 // an all-false registry and silently skips every order it tries to submit.
97 if (set_broker_status_func) {
98 set_broker_status_func(&BrokerStatusRegistry::instance());
99 } else {
100 LOG_WARN("StrategyLoader: {} exports no set_broker_status_registry() -- rebuild it against "
101 "SLICK_TRADER_EXPORT_STRATEGY; it will see all brokers as disconnected and place no orders",
102 library_path);
103 }
104
105 // Log strategy info if available
106 if (get_name_func && get_version_func) {
107 LOG_INFO("StrategyLoader: Loading strategy '{}' v{} from {}",
108 get_name_func(), get_version_func(), library_path);
109 } else {
110 LOG_INFO("StrategyLoader: Loading strategy from {}", library_path);
111 }
112
113 // Create strategy instance
114 IStrategy* raw_strategy = create_func_();
115 if (!raw_strategy) {
116 last_error_ = "create_strategy() returned nullptr";
117 LOG_ERROR("StrategyLoader: {}", last_error_);
118 unload();
119 return nullptr;
120 }
121
122 // Wrap in shared_ptr with custom deleter
123 // The deleter keeps a reference to the DLL handle to prevent premature unloading
124 std::shared_ptr<IStrategy> strategy(raw_strategy, StrategyDeleter{destroy_func_, handle_});
125
126 LOG_INFO("StrategyLoader: Successfully loaded strategy '{}' v{}",
127 strategy->name(), strategy->version());
128
129 // Clear handle_ so unload() won't free the library
130 // The library will remain loaded until the process exits
131 handle_ = nullptr;
132
133 return strategy;
134}
135
137 if (!handle_) {
138 return;
139 }
140
141 LOG_INFO("StrategyLoader: Releasing library handle for {}", library_path_);
142
143 // Note: We only free the library if handle_ is still set
144 // If a strategy was successfully loaded, handle_ is transferred to the deleter
145#ifdef _WIN32
146 FreeLibrary(static_cast<HMODULE>(handle_));
147#else
148 dlclose(handle_);
149#endif
150
151 handle_ = nullptr;
152 create_func_ = nullptr;
153 destroy_func_ = nullptr;
154 library_path_.clear();
155}
156
157} // namespace slick::trader
static BrokerStatusRegistry & instance()
std::shared_ptr< IStrategy > load(const std::string &library_path)
constexpr uint32_t STRATEGY_API_VERSION
Definition istrategy.hpp:30