nautilus-plugin 0.58.0

Plug-in system for the Nautilus trading engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
// -------------------------------------------------------------------------------------------------
//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
//  https://nautechsystems.io
//
//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
//  You may not use this file except in compliance with the License.
//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
// -------------------------------------------------------------------------------------------------

use std::collections::BTreeSet;

use rstest::rstest;

const DATA_ACTOR_SOURCE: &str = include_str!("../../common/src/actor/data_actor.rs");
const STRATEGY_SOURCE: &str = include_str!("../../trading/src/strategy/mod.rs");
const HOST_SOURCE: &str = include_str!("../src/host.rs");
const PLUGIN_ACTOR_SOURCE: &str = include_str!("../src/surfaces/actor.rs");
const PLUGIN_STRATEGY_SOURCE: &str = include_str!("../src/surfaces/strategy.rs");

const PLUGIN_ACTOR_DEFERRED_CALLBACKS: &[&str] = &[
    // State snapshots have no cdylib persistence contract in v1
    "on_save",
    "on_load",
    // DeFi callbacks are outside the v1 actor surface
    "on_block",
    "on_pool",
    "on_pool_swap",
    "on_pool_liquidity_update",
    "on_pool_fee_collect",
    "on_pool_flash",
    // Generic historical data stays out of the vtable; registered plug-in
    // custom data reaches `on_data`.
    "on_historical_data",
];

const PLUGIN_STRATEGY_DEFERRED_CALLBACKS: &[&str] = &[
    // State snapshots have no cdylib persistence contract in v1
    "on_save",
    "on_load",
    // DeFi callbacks are outside the v1 strategy surface
    "on_block",
    "on_pool",
    "on_pool_swap",
    "on_pool_liquidity_update",
    "on_pool_fee_collect",
    "on_pool_flash",
    // Generic historical data stays out of the vtable; registered plug-in
    // custom data reaches `on_data`.
    "on_historical_data",
];

const PLUGIN_STRATEGY_DEFERRED_EXECUTION_METHODS: &[&str] = &[
    // Local state methods mutate host cache state before commands leave the
    // strategy; the host adapter, not the plug-in, is the authority for
    // staging these transitions in v1.
    "mark_order_pending_update",
    "mark_order_pending_cancel",
    "generate_order_pending_update",
    "generate_order_pending_cancel",
];

const PLUGIN_STRATEGY_HOST_OWNED_METHODS: &[&str] = &[
    // StrategyCore access is generated by nautilus_strategy! for in-process strategies
    "core",
    "core_mut",
    // External order claims are reconciliation policy, not a v1 plug-in command
    "external_order_claims",
    // The host owns event routing into plug-in callback slots
    "handle_order_event",
    "handle_position_event",
    // Market-exit and GTD workflows stay inside the host strategy runtime in v1
    "post_market_exit",
    "is_exiting",
    "market_exit",
    "check_market_exit",
    "finalize_market_exit",
    "cancel_market_exit",
    "stop",
    "deny_order",
    "deny_order_list",
    "set_gtd_expiry",
    "cancel_gtd_expiry",
    "has_gtd_expiry_timer",
    "expire_gtd_order",
    "reactivate_gtd_timers",
];

#[rstest]
fn plugin_actor_surface_accounts_for_every_data_actor_callback() {
    let data_actor_callbacks = data_actor_callback_names();
    let plugin_actor_callbacks = plugin_actor_callback_names();
    let deferred_callbacks = PLUGIN_ACTOR_DEFERRED_CALLBACKS
        .iter()
        .map(|name| (*name).to_string())
        .collect::<BTreeSet<_>>();

    let accounted_callbacks = plugin_actor_callbacks
        .union(&deferred_callbacks)
        .cloned()
        .collect::<BTreeSet<_>>();
    let missing_callbacks = data_actor_callbacks
        .difference(&accounted_callbacks)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        missing_callbacks.is_empty(),
        "DataActor callbacks must be added to PluginActor or explicitly deferred: {missing_callbacks:?}",
    );

    let stale_deferred_callbacks = deferred_callbacks
        .difference(&data_actor_callbacks)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        stale_deferred_callbacks.is_empty(),
        "Deferred plug-in actor callbacks are no longer DataActor callbacks: {stale_deferred_callbacks:?}",
    );

    let implemented_deferred_callbacks = deferred_callbacks
        .intersection(&plugin_actor_callbacks)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        implemented_deferred_callbacks.is_empty(),
        "PluginActor now supports callbacks still listed as deferred: {implemented_deferred_callbacks:?}",
    );
}

#[rstest]
fn plugin_actor_trait_callbacks_match_vtable_slots() {
    let plugin_actor_callbacks = plugin_actor_callback_names();
    let vtable_callbacks = actor_vtable_callback_names();

    let missing_vtable_slots = plugin_actor_callbacks
        .difference(&vtable_callbacks)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        missing_vtable_slots.is_empty(),
        "PluginActor callbacks must have ActorVTable slots: {missing_vtable_slots:?}",
    );

    let missing_trait_callbacks = vtable_callbacks
        .difference(&plugin_actor_callbacks)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        missing_trait_callbacks.is_empty(),
        "ActorVTable callback slots must have PluginActor methods: {missing_trait_callbacks:?}",
    );
}

#[rstest]
fn plugin_strategy_surface_accounts_for_every_upstream_callback() {
    let mut upstream_callbacks = data_actor_callback_names();
    upstream_callbacks.extend(strategy_callback_names());
    let plugin_strategy_callbacks = plugin_strategy_callback_names();
    let deferred_callbacks = PLUGIN_STRATEGY_DEFERRED_CALLBACKS
        .iter()
        .map(|name| (*name).to_string())
        .collect::<BTreeSet<_>>();

    let accounted_callbacks = plugin_strategy_callbacks
        .union(&deferred_callbacks)
        .cloned()
        .collect::<BTreeSet<_>>();
    let missing_callbacks = upstream_callbacks
        .difference(&accounted_callbacks)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        missing_callbacks.is_empty(),
        "DataActor or Strategy callbacks must be added to PluginStrategy or explicitly deferred: {missing_callbacks:?}",
    );

    let stale_deferred_callbacks = deferred_callbacks
        .difference(&upstream_callbacks)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        stale_deferred_callbacks.is_empty(),
        "Deferred plug-in strategy callbacks are no longer DataActor or Strategy callbacks: {stale_deferred_callbacks:?}",
    );

    let implemented_deferred_callbacks = deferred_callbacks
        .intersection(&plugin_strategy_callbacks)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        implemented_deferred_callbacks.is_empty(),
        "PluginStrategy now supports callbacks still listed as deferred: {implemented_deferred_callbacks:?}",
    );
}

#[rstest]
fn plugin_strategy_trait_callbacks_match_vtable_slots() {
    let plugin_strategy_callbacks = plugin_strategy_callback_names();
    let vtable_callbacks = strategy_vtable_callback_names();

    let missing_vtable_slots = plugin_strategy_callbacks
        .difference(&vtable_callbacks)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        missing_vtable_slots.is_empty(),
        "PluginStrategy callbacks must have StrategyVTable slots: {missing_vtable_slots:?}",
    );

    let missing_trait_callbacks = vtable_callbacks
        .difference(&plugin_strategy_callbacks)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        missing_trait_callbacks.is_empty(),
        "StrategyVTable callback slots must have PluginStrategy methods: {missing_trait_callbacks:?}",
    );
}

#[rstest]
fn plugin_strategy_execution_surface_accounts_for_every_strategy_method() {
    let strategy_execution_methods = strategy_execution_method_names();
    let host_vtable_methods = host_vtable_field_names();
    let deferred_methods = PLUGIN_STRATEGY_DEFERRED_EXECUTION_METHODS
        .iter()
        .map(|name| (*name).to_string())
        .collect::<BTreeSet<_>>();

    let accounted_methods = host_vtable_methods
        .union(&deferred_methods)
        .cloned()
        .collect::<BTreeSet<_>>();
    let missing_methods = strategy_execution_methods
        .difference(&accounted_methods)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        missing_methods.is_empty(),
        "Strategy execution methods must be added to HostVTable or explicitly deferred: {missing_methods:?}",
    );

    let stale_deferred_methods = deferred_methods
        .difference(&strategy_execution_methods)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        stale_deferred_methods.is_empty(),
        "Deferred plug-in strategy execution methods are no longer Strategy methods: {stale_deferred_methods:?}",
    );

    let implemented_deferred_methods = deferred_methods
        .intersection(&host_vtable_methods)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        implemented_deferred_methods.is_empty(),
        "HostVTable now supports strategy execution methods still listed as deferred: {implemented_deferred_methods:?}",
    );
}

#[rstest]
fn plugin_strategy_surface_classifies_every_strategy_method() {
    let strategy_methods = strategy_method_names();
    let host_vtable_methods = host_vtable_field_names();
    let plugin_strategy_callbacks = plugin_strategy_callback_names();
    let deferred_callbacks = PLUGIN_STRATEGY_DEFERRED_CALLBACKS
        .iter()
        .map(|name| (*name).to_string())
        .collect::<BTreeSet<_>>();
    let deferred_execution_methods = PLUGIN_STRATEGY_DEFERRED_EXECUTION_METHODS
        .iter()
        .map(|name| (*name).to_string())
        .collect::<BTreeSet<_>>();
    let host_owned_methods = PLUGIN_STRATEGY_HOST_OWNED_METHODS
        .iter()
        .map(|name| (*name).to_string())
        .collect::<BTreeSet<_>>();

    let mut classified_methods = host_vtable_methods
        .union(&plugin_strategy_callbacks)
        .cloned()
        .collect::<BTreeSet<_>>();
    classified_methods.extend(deferred_callbacks);
    classified_methods.extend(deferred_execution_methods);
    classified_methods.extend(host_owned_methods.iter().cloned());

    let unclassified_methods = strategy_methods
        .difference(&classified_methods)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        unclassified_methods.is_empty(),
        "Strategy methods must be backed by the plug-in surface or explicitly classified: {unclassified_methods:?}",
    );

    let stale_host_owned_methods = host_owned_methods
        .difference(&strategy_methods)
        .cloned()
        .collect::<Vec<_>>();
    assert!(
        stale_host_owned_methods.is_empty(),
        "Host-owned plug-in strategy methods are no longer Strategy methods: {stale_host_owned_methods:?}",
    );
}

fn data_actor_callback_names() -> BTreeSet<String> {
    callback_names_between(
        DATA_ACTOR_SOURCE,
        "pub trait DataActor:",
        "    /// Handles a received time event.",
    )
}

fn strategy_callback_names() -> BTreeSet<String> {
    callback_names_between(
        STRATEGY_SOURCE,
        "pub trait Strategy: DataActor",
        "#[cfg(test)]",
    )
}

fn strategy_method_names() -> BTreeSet<String> {
    method_names_between(
        STRATEGY_SOURCE,
        "pub trait Strategy: DataActor",
        "\nfn publish_order_initialized",
    )
}

fn strategy_execution_method_names() -> BTreeSet<String> {
    method_names_between(
        STRATEGY_SOURCE,
        "    /// Submits an order.",
        "    /// Handles an order event",
    )
}

fn plugin_actor_callback_names() -> BTreeSet<String> {
    callback_names_between(
        PLUGIN_ACTOR_SOURCE,
        "pub trait PluginActor:",
        "/// Returns a `*const ActorVTable`",
    )
}

fn plugin_strategy_callback_names() -> BTreeSet<String> {
    callback_names_between(
        PLUGIN_STRATEGY_SOURCE,
        "pub trait PluginStrategy:",
        "/// Returns a `*const StrategyVTable`",
    )
}

fn actor_vtable_callback_names() -> BTreeSet<String> {
    vtable_callback_names(PLUGIN_ACTOR_SOURCE)
}

fn strategy_vtable_callback_names() -> BTreeSet<String> {
    vtable_callback_names(PLUGIN_STRATEGY_SOURCE)
}

fn host_vtable_field_names() -> BTreeSet<String> {
    field_names_between(HOST_SOURCE, "pub struct HostVTable {", "impl HostVTable {")
}

fn vtable_callback_names(source: &str) -> BTreeSet<String> {
    source
        .lines()
        .filter_map(|line| {
            let line = line.trim_start().strip_prefix("pub on_")?;
            let (name, _) = line.split_once(':')?;
            Some(format!("on_{name}"))
        })
        .collect()
}

fn method_names_between(source: &str, start_marker: &str, stop_marker: &str) -> BTreeSet<String> {
    let section = source_between(source, start_marker, stop_marker);

    section.lines().filter_map(method_name).collect()
}

fn callback_names_between(source: &str, start_marker: &str, stop_marker: &str) -> BTreeSet<String> {
    let section = source_between(source, start_marker, stop_marker);

    section.lines().filter_map(callback_name).collect()
}

fn field_names_between(source: &str, start_marker: &str, stop_marker: &str) -> BTreeSet<String> {
    let section = source_between(source, start_marker, stop_marker);

    section
        .lines()
        .filter_map(|line| {
            let line = line.trim_start().strip_prefix("pub ")?;
            let (name, _) = line.split_once(':')?;
            Some(name.to_string())
        })
        .collect()
}

fn source_between<'a>(source: &'a str, start_marker: &str, stop_marker: &str) -> &'a str {
    let (_, after_start) = source
        .split_once(start_marker)
        .expect("surface start marker must exist");
    let (section, _) = after_start
        .split_once(stop_marker)
        .expect("surface stop marker must exist");

    section
}

fn method_name(line: &str) -> Option<String> {
    let line = line.trim_start().strip_prefix("fn ")?;
    let (name, _) = line.split_once('(')?;
    Some(name.to_string())
}

fn callback_name(line: &str) -> Option<String> {
    method_name(line).filter(|name| name.starts_with("on_"))
}