Added daemon main file with separation of terminal

This commit is contained in:
2026-07-22 00:34:30 +02:00
parent 335c0b0e09
commit 2df381d334
6 changed files with 11 additions and 0 deletions
+29
View File
@@ -0,0 +1,29 @@
use crate::{PulseTradeApp, types::EventLog};
impl PulseTradeApp {
pub async fn execute_command(&mut self, ctx: &pulse_ui::state::Context, command: &str) {
if command.is_empty() {
return;
}
let (command, _args) = if let Some((command, args)) = command.split_once(" ") {
(command, args.split(" ").collect())
} else {
(command, Vec::new())
};
match command {
"exit" | "quit" | "leave" => {
ctx.close().await;
}
_ => {
self.logs.lock().await.push(EventLog {
kind: crate::types::LogKind::Err,
name: "cmd",
message: format!("Command '{}' not found", command),
});
}
}
}
}
+258
View File
@@ -0,0 +1,258 @@
use crate::types::{
ActivePosition, Alert, AlertLevel, EventLog, InspectTarget, LogKind, MarketOverview, Signal,
SignalKind, Status, WatchListItem,
};
pub trait Formatted {
fn get_formatted(&self) -> Vec<String>;
}
impl Formatted for InspectTarget {
fn get_formatted(&self) -> Vec<String> {
match self {
Self::None => vec!["\x1b[2mnothing to inspect\x1b[0m".to_string()],
Self::Symbol(boxed) => {
let (watch, overview) = &**boxed;
vec![
Property("Symbol", format!("\x1b[35m{}\x1b[0m", watch.symbol)),
Property("Price", format!("\x1b[96m{}\x1b[0m", format_f64(watch.price))),
Property("Trend", format!("{}", format_f64(watch.trend))),
Property("Market", format!("{}", overview.trend)),
Property("Volatility", format!("{}", overview.volatility)),
Property(
"Pressure",
format!("{:+.2}%", overview.pressure * 100.0),
),
Property("Alerts", format!("{}", overview.alerts.len())),
]
.get_formatted()
}
Self::Position(pos) => vec![
Property("Symbol", format!("\x1b[35m{}\x1b[0m", pos.symbol)),
Property("Profit", format!("{:+.2}", pos.profit)),
Property("Amount", format!("{}", pos.amount)),
]
.get_formatted(),
Self::Signal(sig) => vec![
Property("Type", format!("{}", sig.kind)),
Property("Symbol", format!("\x1b[35m{}\x1b[0m", sig.symbol)),
Property("Parameter", format!("{}", sig.param)),
Property("Price", format!("\x1b[96m{}\x1b[0m", format_f64(sig.price))),
]
.get_formatted(),
Self::Alert(alert) => vec![
Property("Level", format!("{}", alert.level)),
Property("Message", alert.message.clone()),
]
.get_formatted(),
}
}
}
impl Formatted for Alert {
fn get_formatted(&self) -> Vec<String> {
vec![
format!(
"{}{}\x1b[0m",
match &self.level {
AlertLevel::Low => "\x1b[34m",
AlertLevel::Medium => "\x1b[33m",
AlertLevel::High => "\x1b[31m",
},
self.level
),
self.message.clone(),
]
}
}
impl Formatted for EventLog {
fn get_formatted(&self) -> Vec<String> {
vec![
format!(
"{}{}\x1b[0m",
match &self.kind {
LogKind::Info => "\x1b[34m",
LogKind::Debug => "\x1b[36m",
LogKind::Err => "\x1b[31m",
LogKind::Warn => "\x1b[33m",
},
self.kind
),
format!("(\x1b[37m{}\x1b[0m)", self.name),
self.message.clone(),
]
}
}
impl Formatted for Signal {
fn get_formatted(&self) -> Vec<String> {
vec![
if matches!(self.kind, SignalKind::Buy) {
format!("\x1b[32m{}\x1b[0m", self.kind)
} else {
format!("\x1b[31m{}\x1b[0m", self.kind)
},
format!("\x1b[35m{}\x1b[0m", self.symbol),
format!("\x1b[34m{}\x1b[0m", self.param),
format_f64(self.price),
]
}
}
impl Formatted for WatchListItem {
fn get_formatted(&self) -> Vec<String> {
vec![
format!("\x1b[35m{}\x1b[0m", self.symbol),
format_f64(self.price),
format!(
"{} {}",
if self.trend.is_sign_positive() {
"\x1b[32m▲\x1b[0m"
} else {
"\x1b[31m▼\x1b[0m"
},
format_f64(self.trend.abs())
),
]
}
}
impl Formatted for ActivePosition {
fn get_formatted(&self) -> Vec<String> {
vec![
format!("\x1b[35m{}\x1b[0m", self.symbol),
format_f64(self.amount),
format!(
"{} {}",
if self.profit.is_sign_positive() {
"\x1b[32m▲\x1b[0m"
} else {
"\x1b[31m▼\x1b[0m"
},
format_f64(self.profit.abs())
),
]
}
}
struct Property(&'static str, String);
impl Formatted for MarketOverview {
fn get_formatted(&self) -> Vec<String> {
vec![
Property("TREND", format!("{}", self.trend)),
Property("VOLATILITY", format!("{}", self.volatility)),
Property(
"PRESSURE",
if self.pressure.is_sign_positive() {
format!("\x1b[32m{:.3}\x1b[0m", self.pressure)
} else {
format!("\x1b[31m{:.3}\x1b[0m", self.pressure)
},
),
]
.get_formatted()
}
}
impl Formatted for Status {
fn get_formatted(&self) -> Vec<String> {
vec![
Property("Feed", format!("{:?}", self.feed)),
Property("Exchange", self.exchange.clone()),
Property("DEX", self.dex.clone()),
Property("Latency", format!("{} ms", self.latency)),
]
.get_formatted()
}
}
impl Formatted for Property {
fn get_formatted(&self) -> Vec<String> {
vec![format!("\x1b[91m{}\x1b[0m", self.0), self.1.clone()]
}
}
impl<T: Formatted> Formatted for Vec<T> {
fn get_formatted(&self) -> Vec<String> {
let mut output = Vec::new();
let rows: Vec<Vec<String>> = self.iter().map(|v| v.get_formatted()).collect();
if rows.is_empty() {
return output;
}
let column_count = rows.iter().map(|r| r.len()).max().unwrap_or(0);
let mut widths = vec![0; column_count];
for row in &rows {
for (i, col) in row.iter().enumerate() {
widths[i] = widths[i].max(col.len());
}
}
for row in rows {
let mut row_out = String::new();
for (col_idx, col) in row.iter().enumerate() {
let width = widths[col_idx];
row_out.push_str(&format!("{:<width$}", col, width = width));
if col_idx + 1 != row.len() {
row_out.push_str(" ");
}
}
output.push(row_out);
}
output
}
}
pub fn apply_padding(mut items: Vec<String>) -> Vec<String> {
for item in &mut items {
item.insert(0, ' ');
}
items
}
pub fn format_f64(value: f64) -> String {
let val = value.to_string();
let parts: Vec<&str> = val.split('.').collect();
let int = parts[0].to_string();
let negative = int.starts_with('-');
let start = if negative { 1 } else { 0 };
let mut result = String::new();
for (i, c) in int[start..].chars().rev().enumerate() {
if i > 0 && i % 3 == 0 {
result.push(',');
}
result.push(c);
}
let mut formatted: String = result.chars().rev().collect();
if negative {
formatted.insert(0, '-');
}
if parts.len() > 1 {
formatted.push('.');
formatted.push_str(parts[1]);
}
formatted
}
+298
View File
@@ -0,0 +1,298 @@
pub mod command;
pub mod formatting;
pub mod types;
use std::any::Any;
use chrono::{Local, Utc};
use pulse_ui::{
App,
layout::{LayoutItem, layout},
state::{Refresh, State},
unit::Size,
widget::{
align::End,
input::{Input, InputState},
outline::{Outline, VLine},
spaced::SpacedColumns,
},
};
use crate::{
formatting::{Formatted, apply_padding},
types::{
ActivePosition, Alert, EventLog, InspectTarget, MarketOverview, Signal, Status,
WatchListItem,
},
};
pub struct PulseTradeApp {
command: State<InputState>,
watch_list: State<Vec<WatchListItem>>,
active_positions: State<Vec<ActivePosition>>,
logs: State<Vec<EventLog>>,
signals: State<Vec<Signal>>,
market_overview: State<MarketOverview>,
status: State<Status>,
inspect: State<InspectTarget>,
}
impl App for PulseTradeApp {
async fn init(&mut self, _ctx: &pulse_ui::state::Context) {
let mut watch_list = self.watch_list.lock().await;
watch_list.push(WatchListItem {
symbol: "BTC".to_string(),
price: 118_402.12,
trend: 0.82,
});
watch_list.push(WatchListItem {
symbol: "ETH".to_string(),
price: 3_912.48,
trend: -0.41,
});
watch_list.push(WatchListItem {
symbol: "SOL".to_string(),
price: 182.91,
trend: 2.18,
});
watch_list.push(WatchListItem {
symbol: "XRP".to_string(),
price: 2.84,
trend: 1.22,
});
let mut active_positions = self.active_positions.lock().await;
active_positions.push(ActivePosition {
symbol: "BTC".to_string(),
profit: 125.50,
amount: 0.25,
});
active_positions.push(ActivePosition {
symbol: "ETH".to_string(),
profit: -32.75,
amount: 1.0,
});
active_positions.push(ActivePosition {
symbol: "SOL".to_string(),
profit: 84.20,
amount: 5.0,
});
active_positions.push(ActivePosition {
symbol: "XRP".to_string(),
profit: 12.30,
amount: 0.75,
});
let mut signals = self.signals.lock().await;
signals.push(Signal {
kind: types::SignalKind::Buy,
symbol: "BTC".to_string(),
param: types::SignalParameter::Lim,
price: 118_800.0,
});
signals.push(Signal {
kind: types::SignalKind::Buy,
symbol: "BTC".to_string(),
param: types::SignalParameter::Tap,
price: 120_000.0,
});
signals.push(Signal {
kind: types::SignalKind::Buy,
symbol: "BTC".to_string(),
param: types::SignalParameter::Stl,
price: 118_000.0,
});
let mut logs = self.logs.lock().await;
logs.push(EventLog {
kind: types::LogKind::Warn,
name: "pulse.init",
message: "We're still not done yet ;)".to_string(),
});
let mut market_overview = self.market_overview.lock().await;
market_overview.alerts.push(Alert {
level: types::AlertLevel::High,
message: "BTC funding rate elevated".to_string(),
});
market_overview.alerts.push(Alert {
level: types::AlertLevel::Medium,
message: "Market volatility increasing".to_string(),
});
market_overview.alerts.push(Alert {
level: types::AlertLevel::Low,
message: "ETH volatility returning to normal".to_string(),
});
}
async fn update(&mut self, ctx: &pulse_ui::state::Context, event: Box<dyn Any + Send + Sync>) {
if let Some(Refresh) = event.downcast_ref() {
return;
}
if let Some(event) = event.downcast_ref() {
if self.command.value.lock().await.handle_event(event) {
return;
} else if let crossterm::event::Event::Key(key) = event {
if key.code.is_enter() {
let mut command = self.command.lock().await;
let command_text = command.text.clone();
command.cursor = 0;
command.text.clear();
drop(command);
self.execute_command(ctx, command_text.trim()).await;
}
}
}
}
async fn layout(&self) -> pulse_ui::layout::LayoutItem {
LayoutItem::Frame {
padding: 1,
item: Box::new(layout(vec![
LayoutItem::Columns {
unit: Size::Fixed(1),
items: vec![
LayoutItem::Widget(Size::Flex(1)),
LayoutItem::Widget(Size::Flex(1)),
LayoutItem::Widget(Size::Flex(1)),
],
},
// Account status
LayoutItem::Spacing(Size::Fixed(1)),
LayoutItem::Widget(Size::Flex(1)),
// Live status
LayoutItem::Spacing(Size::Fixed(1)),
LayoutItem::Widget(Size::Flex(1)),
// Event logs
LayoutItem::Spacing(Size::Fixed(1)),
LayoutItem::Widget(Size::Fill),
// Input
LayoutItem::Spacing(Size::Fixed(1)),
LayoutItem::Widget(Size::Fixed(1)),
])),
}
}
async fn render(&mut self, layout: pulse_ui::layout::Allocation) {
layout.draw_frame(0, Outline);
layout.draw(
0,
format!("  PULSE TRADER v{}", env!("CARGO_PKG_VERSION")),
);
// layout.draw(1, Center("LIVE".to_string()));
layout.draw(
2,
End(format!(
"{} UTC ({} Local)",
Utc::now().format("%H:%M"),
Local::now().format("%H:%M")
)),
);
layout.draw_frame(3, VLine);
layout.draw_frame(4, VLine);
layout.draw_frame(5, VLine);
layout.draw_frame(6, VLine);
layout.draw(
3,
SpacedColumns(vec![
(
LayoutItem::Widget(Size::Flex(1)),
Box::new(format!(
" WATCHLIST\n{}",
apply_padding(self.watch_list.lock().await.get_formatted()).join("\n")
)),
),
(
LayoutItem::Widget(Size::Flex(1)),
Box::new(format!(
" ACTIVE POSITIONS\n{}",
apply_padding(self.active_positions.lock().await.get_formatted())
.join("\n")
)),
),
(LayoutItem::Widget(Size::Flex(1)), {
let mo = self.market_overview.lock().await;
Box::new(format!(
" MARKET OVERVIEW\n{}\n\n{}",
apply_padding(mo.get_formatted()).join("\n"),
apply_padding(mo.alerts.get_formatted()).join("\n")
))
}),
]),
);
layout.draw(
4,
SpacedColumns(vec![
(
LayoutItem::Widget(Size::Flex(1)),
Box::new(format!(
" SIGNALS\n{}",
apply_padding(self.signals.lock().await.get_formatted()).join("\n")
)),
),
(
LayoutItem::Widget(Size::Flex(1)),
Box::new(format!(
" INSPECTOR\n{}",
apply_padding(self.inspect.lock().await.get_formatted()).join("\n")
)),
),
(
LayoutItem::Widget(Size::Flex(1)),
Box::new(format!(
" STATUS\n{}",
apply_padding(self.status.lock().await.get_formatted()).join("\n")
)),
),
]),
);
layout.draw(
5,
format!(
" EVENT LOGS\n{}",
apply_padding(self.logs.lock().await.get_formatted()).join("\n")
),
);
layout.draw(6, Input(" > ", &*self.command.lock().await));
}
}
#[tokio::main]
async fn main() {
pulse_ui::run(|ctx| PulseTradeApp {
command: ctx.use_state(InputState::new()),
watch_list: ctx.use_state(Vec::new()),
active_positions: ctx.use_state(Vec::new()),
signals: ctx.use_state(Vec::new()),
logs: ctx.use_state(Vec::new()),
inspect: ctx.use_state(InspectTarget::None),
market_overview: ctx.use_state(MarketOverview {
trend: types::MarketTrend::Bullish,
volatility: types::Volatility::High,
pressure: 0.324,
alerts: Vec::new(),
}),
status: ctx.use_state(Status {
feed: types::Feed::Connected,
exchange: "Binance".to_string(),
dex: "DEX SCREENER".to_string(),
latency: 18,
}),
})
.await;
}
+171
View File
@@ -0,0 +1,171 @@
#[derive(Debug, Clone)]
pub struct WatchListItem {
pub symbol: String,
pub price: f64,
pub trend: f64,
}
#[derive(Debug, Clone)]
pub struct ActivePosition {
pub symbol: String,
pub profit: f64,
pub amount: f64,
}
#[derive(Debug, Clone, Copy)]
pub enum MarketTrend {
Bullish,
Bearish,
Neutral,
}
impl std::fmt::Display for MarketTrend {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Bullish => write!(f, "Bullish"),
Self::Bearish => write!(f, "Bearish"),
Self::Neutral => write!(f, "Neutral"),
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum Volatility {
Low,
Medium,
High,
}
impl std::fmt::Display for Volatility {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Low => write!(f, "Low"),
Self::Medium => write!(f, "Medium"),
Self::High => write!(f, "High"),
}
}
}
#[derive(Debug, Clone)]
pub struct MarketOverview {
pub trend: MarketTrend,
pub volatility: Volatility,
pub pressure: f64,
pub alerts: Vec<Alert>,
}
#[derive(Debug, Clone, Copy)]
pub enum Feed {
Connected,
Disconnected,
Connecting,
Failed,
}
pub struct Status {
pub feed: Feed,
pub exchange: String,
pub dex: String,
pub latency: u16,
}
#[derive(Debug, Clone, Copy)]
pub enum SignalKind {
Buy,
Sell,
}
impl std::fmt::Display for SignalKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Buy => write!(f, "BUY"),
Self::Sell => write!(f, "SELL"),
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum SignalParameter {
Lim,
Stl,
Tap,
Chk,
}
impl std::fmt::Display for SignalParameter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Lim => write!(f, "LIM"),
Self::Stl => write!(f, "STL"),
Self::Tap => write!(f, "TAP"),
Self::Chk => write!(f, "CHK"),
}
}
}
#[derive(Debug, Clone)]
pub struct Signal {
pub kind: SignalKind,
pub symbol: String,
pub param: SignalParameter,
pub price: f64,
}
#[derive(Debug, Clone, Copy)]
pub enum LogKind {
Info,
Warn,
Err,
Debug,
}
impl std::fmt::Display for LogKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Info => write!(f, "INFO"),
Self::Warn => write!(f, "WARN"),
Self::Err => write!(f, "ERR"),
Self::Debug => write!(f, "DEBUG"),
}
}
}
#[derive(Debug, Clone)]
pub struct EventLog {
pub kind: LogKind,
pub name: &'static str,
pub message: String,
}
#[derive(Debug, Clone, Copy)]
pub enum AlertLevel {
High,
Medium,
Low,
}
impl std::fmt::Display for AlertLevel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::High => write!(f, "H"),
Self::Medium => write!(f, "M"),
Self::Low => write!(f, "L"),
}
}
}
#[derive(Debug, Clone)]
pub struct Alert {
pub level: AlertLevel,
pub message: String,
}
#[derive(Debug, Clone)]
pub enum InspectTarget {
None,
Symbol(Box<(WatchListItem, MarketOverview)>),
Position(ActivePosition),
Signal(Signal),
Alert(Alert),
}