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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
// -------------------------------------------------------------------------------------------------
//  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.
// -------------------------------------------------------------------------------------------------

//! Actor plug point.
//!
//! Plug-in authors implement [`PluginActor`] on their struct; the generated
//! [`ActorVTable`] adapts that trait to the C-ABI boundary so the host's
//! `DataActor`-shaped engine can dispatch callbacks into the cdylib.
//!
//! # Boundary shape
//!
//! Data-bearing callbacks cross the boundary as `*const T` borrowed
//! pointers into the host's already-`#[repr(C)]` model types. The host
//! keeps the value alive for the duration of the call; the plug-in's
//! thunk dereferences once and hands an `&T` to the trait method. No
//! serialisation, no allocation per event.
//!
//! Lifecycle callbacks (`on_start`, `on_stop`, ...) carry no payload.
//!
//! # Scope (v1)
//!
//! Phase 1 covers the lifecycle callbacks plus the data callbacks whose
//! payload types are `#[repr(C)]`-clean end-to-end:
//!
//! - Lifecycle: `start`, `stop`, `resume`, `reset`, `dispose`, `degrade`, `fault`
//! - Market data: instruments
//!   (via [`crate::surfaces::instrument::InstrumentAnyHandle`]),
//!   book snapshots (via [`crate::surfaces::book::OrderBookHandle`]),
//!   book deltas (via [`crate::surfaces::book::OrderBookDeltasHandle`]),
//!   quotes, trades, bars, mark/index/funding prices, option greeks, option chain slices
//!   (via [`crate::surfaces::option_chain::OptionChainSliceHandle`]),
//!   instrument status, and instrument close
//! - Historical market data: bulk historical book deltas, book depth,
//!   quotes, trades, bars, mark prices, index prices, funding rates
//!   delivered as [`crate::boundary::Slice`] payloads
//! - Order events: filled, canceled
//! - Custom data: values registered through `PluginCustomData`, including
//!   historical custom-data responses routed through `on_data`
//! - Other: signal, time event
//!
//! Deferred: generic non-plugin `on_historical_data` (`&dyn Any` payload),
//! DeFi pool/block events. The authoritative list lives in
//! `tests/surface_alignment.rs`.

#![allow(unsafe_code)]

use std::marker::PhantomData;

use nautilus_common::{signal::Signal, timer::TimeEvent};
use nautilus_model::{
    data::{
        Bar, FundingRateUpdate, IndexPriceUpdate, InstrumentClose, InstrumentStatus,
        MarkPriceUpdate, OptionChainSlice, OptionGreeks, OrderBookDelta, OrderBookDeltas,
        OrderBookDepth10, QuoteTick, TradeTick,
    },
    events::{OrderCanceled, OrderFilled},
    instruments::InstrumentAny,
    orderbook::OrderBook,
};

use crate::{
    boundary::{BorrowedStr, PluginError, PluginErrorCode, PluginResult, Slice},
    host::{HostContext, HostVTable},
    normalize::BoundaryNormalize,
    panic::{guard, guard_infallible},
    surfaces::{
        book::{OrderBookDeltasHandle, OrderBookHandle},
        custom_data::PluginCustomDataRef,
        instrument::InstrumentAnyHandle,
        option_chain::OptionChainSliceHandle,
    },
};

/// Opaque handle to a plug-in actor instance owned by the cdylib.
///
/// The host never deref's this pointer; it only passes it back to the vtable
/// through the lifecycle and data callbacks until releasing it via `drop`.
#[repr(C)]
pub struct PluginActorHandle {
    _opaque: [u8; 0],
}

/// Function table for a single plug-in actor type.
///
/// One static vtable per concrete type, generated by
/// [`nautilus_plugin!`](crate::nautilus_plugin) via the `Tag<T>` pattern that
/// also powers [`custom_data_vtable`](crate::surfaces::custom_data::custom_data_vtable).
///
/// Every callback that returns [`PluginResult<()>`] runs inside
/// [`crate::panic::guard`]. The infallible `create`/`drop` callbacks run
/// inside [`crate::panic::guard_infallible`], which aborts the host on
/// panic since their signatures cannot carry an error.
///
/// Slots are nullable at the ABI type level so the host can reject malformed
/// manifests with null callbacks before constructing an actor. Macro-generated
/// vtables fill every required slot.
#[repr(C)]
pub struct ActorVTable {
    /// Constructs a fresh actor instance bound to the supplied host vtable
    /// and instance context, and returns a non-null handle.
    ///
    /// `config_json` carries the per-instance configuration the host
    /// constructed from the user's TOML or builder API. Empty when the
    /// host has no instance-specific configuration to pass.
    pub create: Option<
        unsafe extern "C" fn(
            host: *const HostVTable,
            ctx: *const HostContext,
            config_json: BorrowedStr<'_>,
        ) -> *mut PluginActorHandle,
    >,

    /// Drops the actor instance and releases all of its resources.
    pub drop_handle: Option<unsafe extern "C" fn(handle: *mut PluginActorHandle)>,

    /// Returns the canonical type name for this actor.
    pub type_name: Option<unsafe extern "C" fn() -> BorrowedStr<'static>>,

    pub on_start: Option<unsafe extern "C" fn(handle: *mut PluginActorHandle) -> PluginResult<()>>,
    pub on_stop: Option<unsafe extern "C" fn(handle: *mut PluginActorHandle) -> PluginResult<()>>,
    pub on_resume: Option<unsafe extern "C" fn(handle: *mut PluginActorHandle) -> PluginResult<()>>,
    pub on_reset: Option<unsafe extern "C" fn(handle: *mut PluginActorHandle) -> PluginResult<()>>,
    pub on_dispose:
        Option<unsafe extern "C" fn(handle: *mut PluginActorHandle) -> PluginResult<()>>,
    pub on_degrade:
        Option<unsafe extern "C" fn(handle: *mut PluginActorHandle) -> PluginResult<()>>,
    pub on_fault: Option<unsafe extern "C" fn(handle: *mut PluginActorHandle) -> PluginResult<()>>,

    pub on_time_event: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            event: *const TimeEvent,
        ) -> PluginResult<()>,
    >,
    pub on_data: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            data: PluginCustomDataRef,
        ) -> PluginResult<()>,
    >,

    pub on_instrument: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            instrument: *const InstrumentAnyHandle,
        ) -> PluginResult<()>,
    >,
    pub on_book_deltas: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            deltas: *const OrderBookDeltasHandle,
        ) -> PluginResult<()>,
    >,
    pub on_book: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            book: *const OrderBookHandle,
        ) -> PluginResult<()>,
    >,
    pub on_quote: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            quote: *const QuoteTick,
        ) -> PluginResult<()>,
    >,
    pub on_trade: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            trade: *const TradeTick,
        ) -> PluginResult<()>,
    >,
    pub on_bar: Option<
        unsafe extern "C" fn(handle: *mut PluginActorHandle, bar: *const Bar) -> PluginResult<()>,
    >,
    pub on_mark_price: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            mark_price: *const MarkPriceUpdate,
        ) -> PluginResult<()>,
    >,
    pub on_index_price: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            index_price: *const IndexPriceUpdate,
        ) -> PluginResult<()>,
    >,
    pub on_funding_rate: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            funding_rate: *const FundingRateUpdate,
        ) -> PluginResult<()>,
    >,
    pub on_option_greeks: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            greeks: *const OptionGreeks,
        ) -> PluginResult<()>,
    >,
    pub on_option_chain: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            chain: *const OptionChainSliceHandle,
        ) -> PluginResult<()>,
    >,
    pub on_instrument_status: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            status: *const InstrumentStatus,
        ) -> PluginResult<()>,
    >,
    pub on_instrument_close: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            close: *const InstrumentClose,
        ) -> PluginResult<()>,
    >,

    pub on_order_filled: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            event: *const OrderFilled,
        ) -> PluginResult<()>,
    >,
    pub on_order_canceled: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            event: *const OrderCanceled,
        ) -> PluginResult<()>,
    >,

    pub on_signal: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            signal: *const Signal,
        ) -> PluginResult<()>,
    >,

    pub on_historical_book_deltas: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            deltas: Slice<'_, OrderBookDelta>,
        ) -> PluginResult<()>,
    >,
    pub on_historical_book_depth: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            depths: Slice<'_, OrderBookDepth10>,
        ) -> PluginResult<()>,
    >,
    pub on_historical_quotes: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            quotes: Slice<'_, QuoteTick>,
        ) -> PluginResult<()>,
    >,
    pub on_historical_trades: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            trades: Slice<'_, TradeTick>,
        ) -> PluginResult<()>,
    >,
    pub on_historical_bars: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            bars: Slice<'_, Bar>,
        ) -> PluginResult<()>,
    >,
    pub on_historical_mark_prices: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            mark_prices: Slice<'_, MarkPriceUpdate>,
        ) -> PluginResult<()>,
    >,
    pub on_historical_index_prices: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            index_prices: Slice<'_, IndexPriceUpdate>,
        ) -> PluginResult<()>,
    >,
    pub on_historical_funding_rates: Option<
        unsafe extern "C" fn(
            handle: *mut PluginActorHandle,
            funding_rates: Slice<'_, FundingRateUpdate>,
        ) -> PluginResult<()>,
    >,
}

/// Author-facing trait for a plug-in actor.
///
/// Every callback has a no-op default; authors override the ones they care
/// about. Callbacks receive borrowed references to host-owned values; the
/// references are only valid for the duration of the call.
pub trait PluginActor: 'static + Send + Sized {
    /// Canonical type name. Must be unique across a Nautilus deployment.
    const TYPE_NAME: &'static str;

    /// Constructs a fresh actor instance bound to the supplied host vtable
    /// and instance context.
    ///
    /// `config_json` is the per-instance JSON configuration the host
    /// constructed from the user's TOML or builder API. The string is
    /// empty when no instance-specific configuration is supplied.
    fn new(host: *const HostVTable, ctx: *const HostContext, config_json: &str) -> Self;

    #[allow(unused_variables)]
    fn on_start(&mut self) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_stop(&mut self) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_resume(&mut self) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_reset(&mut self) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_dispose(&mut self) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_degrade(&mut self) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_fault(&mut self) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_time_event(&mut self, event: &TimeEvent) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_data(&mut self, data: PluginCustomDataRef) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_instrument(&mut self, instrument: &InstrumentAny) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_book_deltas(&mut self, deltas: &OrderBookDeltas) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_book(&mut self, book: &OrderBook) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_quote(&mut self, quote: &QuoteTick) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_trade(&mut self, trade: &TradeTick) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_bar(&mut self, bar: &Bar) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_mark_price(&mut self, mark_price: &MarkPriceUpdate) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_index_price(&mut self, index_price: &IndexPriceUpdate) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_funding_rate(&mut self, funding_rate: &FundingRateUpdate) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_option_greeks(&mut self, greeks: &OptionGreeks) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_option_chain(&mut self, chain: &OptionChainSlice) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_instrument_status(&mut self, status: &InstrumentStatus) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_instrument_close(&mut self, close: &InstrumentClose) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_order_filled(&mut self, event: &OrderFilled) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_order_canceled(&mut self, event: &OrderCanceled) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_signal(&mut self, signal: &Signal) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_historical_book_deltas(&mut self, deltas: &[OrderBookDelta]) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_historical_book_depth(&mut self, depths: &[OrderBookDepth10]) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_historical_quotes(&mut self, quotes: &[QuoteTick]) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_historical_trades(&mut self, trades: &[TradeTick]) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_historical_bars(&mut self, bars: &[Bar]) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_historical_mark_prices(&mut self, mark_prices: &[MarkPriceUpdate]) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_historical_index_prices(
        &mut self,
        index_prices: &[IndexPriceUpdate],
    ) -> anyhow::Result<()> {
        Ok(())
    }

    #[allow(unused_variables)]
    fn on_historical_funding_rates(
        &mut self,
        funding_rates: &[FundingRateUpdate],
    ) -> anyhow::Result<()> {
        Ok(())
    }
}

/// Returns a `*const ActorVTable` for the given [`PluginActor`] type.
///
/// One static vtable per monomorphisation via the `Tag<T>`-shaped pattern
/// proven by [`custom_data_vtable`](crate::surfaces::custom_data::custom_data_vtable).
#[must_use]
pub fn actor_vtable<T>() -> *const ActorVTable
where
    T: PluginActor,
{
    &VTableTag::<T>::VTABLE
}

struct VTableTag<T>(PhantomData<T>);

impl<T> VTableTag<T>
where
    T: PluginActor,
{
    const VTABLE: ActorVTable = ActorVTable {
        create: Some(create_thunk::<T>),
        drop_handle: Some(drop_handle_thunk::<T>),
        type_name: Some(type_name_thunk::<T>),
        on_start: Some(on_start_thunk::<T>),
        on_stop: Some(on_stop_thunk::<T>),
        on_resume: Some(on_resume_thunk::<T>),
        on_reset: Some(on_reset_thunk::<T>),
        on_dispose: Some(on_dispose_thunk::<T>),
        on_degrade: Some(on_degrade_thunk::<T>),
        on_fault: Some(on_fault_thunk::<T>),
        on_time_event: Some(on_time_event_thunk::<T>),
        on_data: Some(on_data_thunk::<T>),
        on_instrument: Some(on_instrument_thunk::<T>),
        on_book_deltas: Some(on_book_deltas_thunk::<T>),
        on_book: Some(on_book_thunk::<T>),
        on_quote: Some(on_quote_thunk::<T>),
        on_trade: Some(on_trade_thunk::<T>),
        on_bar: Some(on_bar_thunk::<T>),
        on_mark_price: Some(on_mark_price_thunk::<T>),
        on_index_price: Some(on_index_price_thunk::<T>),
        on_funding_rate: Some(on_funding_rate_thunk::<T>),
        on_option_greeks: Some(on_option_greeks_thunk::<T>),
        on_option_chain: Some(on_option_chain_thunk::<T>),
        on_instrument_status: Some(on_instrument_status_thunk::<T>),
        on_instrument_close: Some(on_instrument_close_thunk::<T>),
        on_order_filled: Some(on_order_filled_thunk::<T>),
        on_order_canceled: Some(on_order_canceled_thunk::<T>),
        on_signal: Some(on_signal_thunk::<T>),
        on_historical_book_deltas: Some(on_historical_book_deltas_thunk::<T>),
        on_historical_book_depth: Some(on_historical_book_depth_thunk::<T>),
        on_historical_quotes: Some(on_historical_quotes_thunk::<T>),
        on_historical_trades: Some(on_historical_trades_thunk::<T>),
        on_historical_bars: Some(on_historical_bars_thunk::<T>),
        on_historical_mark_prices: Some(on_historical_mark_prices_thunk::<T>),
        on_historical_index_prices: Some(on_historical_index_prices_thunk::<T>),
        on_historical_funding_rates: Some(on_historical_funding_rates_thunk::<T>),
    };
}

unsafe extern "C" fn create_thunk<T: PluginActor>(
    host: *const HostVTable,
    ctx: *const HostContext,
    config_json: BorrowedStr<'_>,
) -> *mut PluginActorHandle {
    guard_infallible("actor::create", || {
        // SAFETY: host promises `config_json` borrows storage that is live
        // for the duration of this call.
        let cfg = unsafe { config_json.as_str() };
        Box::into_raw(Box::new(T::new(host, ctx, cfg))).cast::<PluginActorHandle>()
    })
}

unsafe extern "C" fn drop_handle_thunk<T: PluginActor>(handle: *mut PluginActorHandle) {
    if handle.is_null() {
        return;
    }
    guard_infallible("actor::drop", || {
        // SAFETY: handle was allocated via `Box::into_raw(Box::new(T))`.
        unsafe {
            drop(Box::from_raw(handle.cast::<T>()));
        }
    });
}

unsafe extern "C" fn type_name_thunk<T: PluginActor>() -> BorrowedStr<'static> {
    BorrowedStr::from_str(T::TYPE_NAME)
}

fn handle_as_mut<'a, T: PluginActor>(handle: *mut PluginActorHandle) -> &'a mut T {
    // SAFETY: handle is non-null and originates from a `Box::into_raw` of a
    // `T`. The host promises exclusive access while a callback is running.
    unsafe { &mut *handle.cast::<T>() }
}

fn ok_or_err<E: ::core::fmt::Display>(r: Result<(), E>) -> Result<(), PluginError> {
    r.map_err(|e| PluginError::new(PluginErrorCode::Generic, e.to_string()))
}

macro_rules! lifecycle_thunk {
    ($name:ident, $method:ident) => {
        unsafe extern "C" fn $name<T: PluginActor>(
            handle: *mut PluginActorHandle,
        ) -> PluginResult<()> {
            guard(|| {
                let actor = handle_as_mut::<T>(handle);
                ok_or_err(actor.$method())
            })
        }
    };
}

lifecycle_thunk!(on_start_thunk, on_start);
lifecycle_thunk!(on_stop_thunk, on_stop);
lifecycle_thunk!(on_resume_thunk, on_resume);
lifecycle_thunk!(on_reset_thunk, on_reset);
lifecycle_thunk!(on_dispose_thunk, on_dispose);
lifecycle_thunk!(on_degrade_thunk, on_degrade);
lifecycle_thunk!(on_fault_thunk, on_fault);

macro_rules! event_thunk {
    ($name:ident, $method:ident, $ty:ty) => {
        unsafe extern "C" fn $name<T: PluginActor>(
            handle: *mut PluginActorHandle,
            value: *const $ty,
        ) -> PluginResult<()> {
            guard(|| {
                // SAFETY: host keeps `value` live for the duration of the call;
                // the plug-in only borrows it for the trait-method invocation.
                let v = unsafe { &*value }.boundary_normalized();
                let actor = handle_as_mut::<T>(handle);
                ok_or_err(actor.$method(&v))
            })
        }
    };
}

event_thunk!(on_time_event_thunk, on_time_event, TimeEvent);

unsafe extern "C" fn on_data_thunk<T: PluginActor>(
    handle: *mut PluginActorHandle,
    data: PluginCustomDataRef,
) -> PluginResult<()> {
    guard(|| {
        let actor = handle_as_mut::<T>(handle);
        ok_or_err(actor.on_data(data))
    })
}

unsafe extern "C" fn on_instrument_thunk<T: PluginActor>(
    handle: *mut PluginActorHandle,
    instrument: *const InstrumentAnyHandle,
) -> PluginResult<()> {
    guard(|| {
        // SAFETY: host keeps the handle live for the duration of the call;
        // the plug-in only borrows the wrapped instrument via the trait method.
        let v: InstrumentAny = unsafe { (*instrument).instrument() }.boundary_normalized();
        let actor = handle_as_mut::<T>(handle);
        ok_or_err(actor.on_instrument(&v))
    })
}

unsafe extern "C" fn on_book_deltas_thunk<T: PluginActor>(
    handle: *mut PluginActorHandle,
    deltas: *const OrderBookDeltasHandle,
) -> PluginResult<()> {
    guard(|| {
        // SAFETY: host keeps the handle live for the duration of the call;
        // the plug-in only borrows the wrapped deltas via the trait method.
        let v: OrderBookDeltas = unsafe { (*deltas).deltas() }.boundary_normalized();
        let actor = handle_as_mut::<T>(handle);
        ok_or_err(actor.on_book_deltas(&v))
    })
}

unsafe extern "C" fn on_book_thunk<T: PluginActor>(
    handle: *mut PluginActorHandle,
    book: *const OrderBookHandle,
) -> PluginResult<()> {
    guard(|| {
        // SAFETY: host keeps the handle live for the duration of the call;
        // the plug-in only borrows the wrapped book via the trait method.
        let v: OrderBook = unsafe { (*book).book() }.boundary_normalized();
        let actor = handle_as_mut::<T>(handle);
        ok_or_err(actor.on_book(&v))
    })
}

event_thunk!(on_quote_thunk, on_quote, QuoteTick);
event_thunk!(on_trade_thunk, on_trade, TradeTick);
event_thunk!(on_bar_thunk, on_bar, Bar);
event_thunk!(on_mark_price_thunk, on_mark_price, MarkPriceUpdate);
event_thunk!(on_index_price_thunk, on_index_price, IndexPriceUpdate);
event_thunk!(on_funding_rate_thunk, on_funding_rate, FundingRateUpdate);
event_thunk!(on_option_greeks_thunk, on_option_greeks, OptionGreeks);

unsafe extern "C" fn on_option_chain_thunk<T: PluginActor>(
    handle: *mut PluginActorHandle,
    chain: *const OptionChainSliceHandle,
) -> PluginResult<()> {
    guard(|| {
        // SAFETY: host keeps the handle live for the duration of the call;
        // the plug-in only borrows the wrapped chain via the trait method.
        let v: OptionChainSlice = unsafe { (*chain).chain() }.boundary_normalized();
        let actor = handle_as_mut::<T>(handle);
        ok_or_err(actor.on_option_chain(&v))
    })
}

event_thunk!(
    on_instrument_status_thunk,
    on_instrument_status,
    InstrumentStatus
);
event_thunk!(
    on_instrument_close_thunk,
    on_instrument_close,
    InstrumentClose
);
event_thunk!(on_order_filled_thunk, on_order_filled, OrderFilled);
event_thunk!(on_order_canceled_thunk, on_order_canceled, OrderCanceled);
event_thunk!(on_signal_thunk, on_signal, Signal);

macro_rules! slice_thunk {
    ($name:ident, $method:ident, $ty:ty) => {
        unsafe extern "C" fn $name<T: PluginActor>(
            handle: *mut PluginActorHandle,
            values: Slice<'_, $ty>,
        ) -> PluginResult<()> {
            guard(|| {
                // SAFETY: host keeps the slice storage live for the call;
                // the plug-in only borrows it for the trait-method invocation.
                let v: Vec<$ty> = unsafe { values.as_slice() }
                    .iter()
                    .map(BoundaryNormalize::boundary_normalized)
                    .collect();
                let actor = handle_as_mut::<T>(handle);
                ok_or_err(actor.$method(&v))
            })
        }
    };
}

slice_thunk!(
    on_historical_book_deltas_thunk,
    on_historical_book_deltas,
    OrderBookDelta
);
slice_thunk!(
    on_historical_book_depth_thunk,
    on_historical_book_depth,
    OrderBookDepth10
);
slice_thunk!(on_historical_quotes_thunk, on_historical_quotes, QuoteTick);
slice_thunk!(on_historical_trades_thunk, on_historical_trades, TradeTick);
slice_thunk!(on_historical_bars_thunk, on_historical_bars, Bar);
slice_thunk!(
    on_historical_mark_prices_thunk,
    on_historical_mark_prices,
    MarkPriceUpdate
);
slice_thunk!(
    on_historical_index_prices_thunk,
    on_historical_index_prices,
    IndexPriceUpdate
);
slice_thunk!(
    on_historical_funding_rates_thunk,
    on_historical_funding_rates,
    FundingRateUpdate
);