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
use std::{
sync::{Arc, Mutex},
time::Duration,
};
use async_trait::async_trait;
use tokio::{
sync::{OnceCell, broadcast::error::RecvError, mpsc},
time,
};
use crate::{
signal::Signal,
trade::{LiveTradeEngine, LiveTradeReceiver, LiveTradeUpdate},
util::AbortOnDropHandle,
};
use super::{
config::TuiConfig,
core::{self, TuiControllerShutdown, TuiLogger},
error::{Result, TuiError},
status::{TuiStatus, TuiStatusManager, TuiStatusStopped},
terminal::TuiTerminal,
};
mod view;
use view::LiveTuiView;
#[derive(Debug)]
pub enum LiveUiMessage {
LogEntry(String),
SummaryUpdate(String),
TradesUpdate(String),
ShutdownCompleted,
}
/// Terminal user interface for live trading operations.
///
/// `LiveTui` provides a visual interface for monitoring live trading activity, including signals,
/// orders, trading state, and position updates. It must be coupled with a [`LiveTradeEngine`]
/// before trading begins.
pub struct LiveTui {
event_check_interval: Duration,
shutdown_timeout: Duration,
status_manager: Arc<TuiStatusManager<LiveTuiView>>,
// Ownership ensures the `TuiTerminal` destructor is executed when `LiveTui` is dropped
tui_terminal: Arc<TuiTerminal>,
ui_tx: mpsc::Sender<LiveUiMessage>,
// Explicitly aborted on drop, to ensure the terminal is restored before
// `LiveTui`'s drop is completed.
ui_task_handle: Arc<Mutex<Option<AbortOnDropHandle<()>>>>,
_shutdown_listener_handle: AbortOnDropHandle<()>,
live_controller: Arc<OnceCell<Arc<dyn TuiControllerShutdown>>>,
live_update_listener_handle: OnceCell<AbortOnDropHandle<()>>,
}
impl LiveTui {
/// Launches a new live trading TUI with the specified configuration.
///
/// Optionally writes TUI logs to a file if `log_file_path` is provided.
pub async fn launch(config: TuiConfig, log_file_path: Option<&str>) -> Result<Arc<Self>> {
let log_file = core::open_log_file(log_file_path)?;
let (ui_tx, ui_rx) = mpsc::channel::<LiveUiMessage>(1_000);
let (shutdown_tx, shutdown_rx) = mpsc::channel::<()>(1);
let tui_terminal = TuiTerminal::new()?;
let tui_view = LiveTuiView::new(config.max_tui_log_len(), log_file);
let status_manager = TuiStatusManager::new_running(tui_view.clone());
let ui_task_handle = core::spawn_ui_task(
config.event_check_interval(),
tui_view,
status_manager.clone(),
tui_terminal.clone(),
ui_rx,
shutdown_tx,
);
let live_controller = Arc::new(OnceCell::new());
let _shutdown_listener_handle = core::spawn_shutdown_signal_listener(
config.shutdown_timeout(),
status_manager.clone(),
shutdown_rx,
ui_task_handle.clone(),
{
let ui_tx = ui_tx.clone();
|| async move { ui_tx.send(LiveUiMessage::ShutdownCompleted).await }
},
live_controller.clone(),
);
Ok(Arc::new(Self {
event_check_interval: config.event_check_interval(),
shutdown_timeout: config.shutdown_timeout(),
status_manager,
tui_terminal,
ui_tx,
ui_task_handle,
_shutdown_listener_handle,
live_controller,
live_update_listener_handle: OnceCell::new(),
}))
}
/// Returns the current [`TuiStatus`] as a snapshot.
pub fn status(&self) -> TuiStatus {
self.status_manager.status()
}
fn spawn_live_update_listener<S: Signal>(
status_manager: Arc<TuiStatusManager<LiveTuiView>>,
mut live_rx: LiveTradeReceiver<S>,
ui_tx: mpsc::Sender<LiveUiMessage>,
) -> AbortOnDropHandle<()> {
tokio::spawn(async move {
async fn send_ui_msg(
ui_tx: &mpsc::Sender<LiveUiMessage>,
ui_msg: LiveUiMessage,
) -> Result<()> {
ui_tx
.send(ui_msg)
.await
.map_err(|e| TuiError::LiveTuiSendFailed(Box::new(e)))
}
let mut running_trades_table;
let mut closed_trades_table = "No closed trades.".to_string();
let mut closed_len = 0;
loop {
match live_rx.recv().await {
Ok(live_update) => {
let result = match live_update {
LiveTradeUpdate::Status(live_status) => {
send_ui_msg(
&ui_tx,
LiveUiMessage::LogEntry(format!("Live status: {live_status}")),
)
.await
}
LiveTradeUpdate::Signal(signal) => {
let signal_str = signal.to_string();
if !signal_str.is_empty() {
send_ui_msg(&ui_tx, LiveUiMessage::LogEntry(signal_str)).await
} else {
Ok(())
}
}
LiveTradeUpdate::Order(order) => {
send_ui_msg(
&ui_tx,
LiveUiMessage::LogEntry(format!("Order: {order}")),
)
.await
}
LiveTradeUpdate::TradingState(trading_state) => {
let summary_result = send_ui_msg(
&ui_tx,
LiveUiMessage::SummaryUpdate(format!(
"\n{}",
trading_state.summary()
)),
)
.await;
if summary_result.is_err() {
summary_result
} else {
running_trades_table = trading_state.running_trades_table();
if trading_state.closed_len() > closed_len {
closed_len = trading_state.closed_len();
closed_trades_table =
trading_state.closed_history().to_table();
}
let tables = format!(
"\nRunning Trades\n\n{running_trades_table}\n\n\nClosed Trades\n\n{closed_trades_table}"
);
send_ui_msg(&ui_tx, LiveUiMessage::TradesUpdate(tables)).await
}
}
LiveTradeUpdate::ClosedTrade(trade) => {
send_ui_msg(
&ui_tx,
LiveUiMessage::LogEntry(format!("Closed Trade: {trade}")),
)
.await
}
};
if let Err(e) = result {
status_manager.set_crashed(e);
return;
}
}
Err(RecvError::Lagged(skipped)) => {
let log_msg = format!("Live updates lagged by {skipped} messages");
if let Err(e) =
send_ui_msg(&ui_tx, LiveUiMessage::LogEntry(log_msg)).await
{
status_manager.set_crashed(e);
return;
}
// Keep trying to receive
}
Err(e) => {
// `live_rx` is expected to be dropped during shutdown
let status = status_manager.status();
if status.is_shutdown_initiated() || status.is_shutdown() {
return;
}
status_manager.set_crashed(TuiError::LiveRecv(e));
return;
}
}
}
})
.into()
}
/// Couples a [`LiveTradeEngine`] to this TUI instance.
///
/// This method starts the live trade engine and begins listening for trading updates. It can
/// only be called once per TUI instance.
///
/// Returns an error if a live trade engine has already been coupled or if the engine fails to
/// start.
pub async fn couple<S: Signal>(&self, engine: LiveTradeEngine<S>) -> Result<()> {
if self.live_controller.initialized() {
return Err(TuiError::LiveTradeEngineAlreadyCoupled);
}
let live_rx = engine.update_receiver();
let live_update_listener_handle = Self::spawn_live_update_listener(
self.status_manager.clone(),
live_rx,
self.ui_tx.clone(),
);
let live_controller = engine
.start()
.await
.map_err(TuiError::LiveTradeEngineStartFailed)?;
self.live_controller
.set(live_controller)
.map_err(|_| TuiError::LiveTradeEngineAlreadyCoupled)?;
self.live_update_listener_handle
.set(live_update_listener_handle)
.map_err(|_| TuiError::LiveTradeEngineAlreadyCoupled)?;
Ok(())
}
/// Performs a graceful shutdown of the live trading TUI.
///
/// This method shuts down the coupled live trade engine and stops the UI task. If shutdown
/// does not complete within the configured timeout, the task is aborted.
///
/// Returns an error if the TUI is not running or if shutdown fails.
pub async fn shutdown(&self) -> Result<()> {
self.status_manager.require_running()?;
let live_controller = self.live_controller.get().cloned();
core::shutdown_inner(
self.shutdown_timeout,
self.status_manager.clone(),
self.ui_task_handle.clone(),
|| self.ui_tx.send(LiveUiMessage::ShutdownCompleted),
live_controller,
)
.await
}
/// Waits until the TUI has stopped and returns the final stopped status.
///
/// This method blocks until the TUI reaches a stopped state, either through graceful shutdown
/// or a crash.
///
/// The terminal is automatically restored before this method returns.
pub async fn until_stopped(&self) -> Arc<TuiStatusStopped> {
loop {
if let TuiStatus::Stopped(status_stopped) = self.status() {
let _ = self.tui_terminal.restore();
return status_stopped;
}
time::sleep(self.event_check_interval).await;
}
}
/// Logs a message to the TUI.
///
/// Returns an error if the TUI is not running or if sending the log entry fails.
pub async fn log(&self, text: String) -> Result<()> {
self.status_manager.require_running()?;
// An error here would be an edge case
self.ui_tx
.send(LiveUiMessage::LogEntry(text))
.await
.map_err(|e| TuiError::LiveTuiSendFailed(Box::new(e)))
}
/// Returns this TUI as a [`TuiLogger`] trait object.
///
/// This is useful for passing the TUI to components that accept a generic logger.
pub fn as_logger(self: &Arc<Self>) -> Arc<dyn TuiLogger> {
self.clone()
}
}
#[async_trait]
impl TuiLogger for LiveTui {
async fn log(&self, log_entry: String) -> Result<()> {
self.log(log_entry).await
}
}
impl Drop for LiveTui {
fn drop(&mut self) {
if let Some(ui_handle) = self
.ui_task_handle
.lock()
.expect("`ui_task_handle` mutex can't be poisoned")
.take()
{
ui_handle.abort();
};
}
}