core/rustybot/src/events.rs

70 lines
1.4 KiB
Rust
Raw Normal View History

2021-01-02 12:16:48 +00:00
use std::collections::HashMap;
use std::future::Future;
use tokio::task::JoinHandle;
use crate::BoxError;
enum SignalKind {
ClosePosition,
OpenPosition,
}
struct EventMetadata {
position_id: Option<u64>,
order_id: Option<u64>,
}
#[derive(PartialEq, Eq, Hash)]
enum EventKind {
NewMinimum,
NewMaximum,
ReachedLoss,
ReachedBreakEven,
ReachedMinProfit,
ReachedGoodProfit,
ReachedMaxLoss,
TrailingStopSet,
TrailingStopMoved,
OrderSubmitted,
NewTick,
}
struct Event {
kind: EventKind,
tick: u64,
metadata: Option<EventMetadata>,
}
impl Event {
pub fn new(kind: EventKind, tick: u64, metadata: Option<EventMetadata>) -> Self {
Event {
kind,
tick,
metadata,
}
}
fn has_metadata(&self) -> bool {
self.metadata.is_some()
}
}
pub struct Dispatcher {
event_handlers: HashMap<EventKind, Box<dyn FnMut(String) -> JoinHandle<()>>>
}
impl Dispatcher {
pub fn new() -> Self {
Dispatcher {
event_handlers: HashMap::new()
}
}
pub fn register_event_handler<F: 'static, Fut: 'static>(&mut self, event: EventKind, mut f: F)
where
F: FnMut(String) -> Fut,
Fut: Future<Output = ()> + Send,
{
self.event_handlers.insert(event, Box::new(move |args| tokio::spawn(f(args))));
}
}