core/rustybot/src/events.rs

77 lines
1.6 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;
2021-01-02 14:10:16 +00:00
2021-01-02 12:16:48 +00:00
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,
}
2021-01-02 14:10:16 +00:00
pub struct Event {
2021-01-02 12:16:48 +00:00
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()
}
}
2021-01-02 14:10:16 +00:00
pub struct EventDispatcher {
event_handlers: HashMap<EventKind, Box<dyn Fn(String) -> JoinHandle<()>>>
2021-01-02 12:16:48 +00:00
}
2021-01-02 14:10:16 +00:00
impl EventDispatcher {
2021-01-02 12:16:48 +00:00
pub fn new() -> Self {
2021-01-02 14:10:16 +00:00
EventDispatcher {
2021-01-02 12:16:48 +00:00
event_handlers: HashMap::new()
}
}
2021-01-02 14:10:16 +00:00
pub fn call_handler(&self, event: &EventKind) {
self.event_handlers.iter()
.filter(|(e, _)| e == event)
.map(|(_, f)| f("test".into()));
}
pub fn register_event_handler<F: 'static, Fut: 'static>(&mut self, event: EventKind, f: F)
2021-01-02 12:16:48 +00:00
where
2021-01-02 14:10:16 +00:00
F: Fn(String) -> Fut,
Fut: Future<Output=()> + Send,
2021-01-02 12:16:48 +00:00
{
self.event_handlers.insert(event, Box::new(move |args| tokio::spawn(f(args))));
}
}