core/rustybot/src/events.rs

97 lines
2.1 KiB
Rust
Raw Normal View History

2021-01-02 12:16:48 +00:00
use std::collections::HashMap;
use std::future::Future;
2021-01-02 15:22:48 +00:00
use bitfinex::positions::Position;
2021-01-02 12:16:48 +00:00
use tokio::task::JoinHandle;
2021-01-02 14:10:16 +00:00
2021-01-02 12:16:48 +00:00
use crate::BoxError;
2021-01-02 15:22:48 +00:00
use crate::pairs::PairStatus;
2021-01-02 12:16:48 +00:00
2021-01-02 15:22:48 +00:00
#[derive(Copy, Clone)]
pub enum SignalKind {
2021-01-02 12:16:48 +00:00
ClosePosition,
OpenPosition,
}
2021-01-02 15:22:48 +00:00
#[derive(Copy, Clone)]
pub struct EventMetadata {
2021-01-02 12:16:48 +00:00
position_id: Option<u64>,
order_id: Option<u64>,
}
2021-01-02 15:22:48 +00:00
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum EventKind {
2021-01-02 12:16:48 +00:00
NewMinimum,
NewMaximum,
ReachedLoss,
ReachedBreakEven,
ReachedMinProfit,
ReachedGoodProfit,
ReachedMaxLoss,
TrailingStopSet,
TrailingStopMoved,
OrderSubmitted,
NewTick,
}
2021-01-02 15:22:48 +00:00
#[derive(Copy, Clone)]
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 18:34:13 +00:00
pub fn kind(&self) -> EventKind {
self.kind
}
pub fn tick(&self) -> u64 {
self.tick
}
pub fn metadata(&self) -> Option<EventMetadata> {
self.metadata
}
2021-01-02 12:16:48 +00:00
}
2021-01-02 14:10:16 +00:00
pub struct EventDispatcher {
2021-01-02 18:34:13 +00:00
event_handlers: HashMap<EventKind, Vec<Box<dyn FnMut(Event, &PairStatus) -> 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 15:22:48 +00:00
event_handlers: HashMap::new(),
2021-01-02 12:16:48 +00:00
}
}
2021-01-02 18:34:13 +00:00
pub fn call_handler(&mut self, event: &Event, status: &PairStatus) {
if let Some(callbacks) = self.event_handlers.get_mut(&event.kind()) {
2021-01-02 15:22:48 +00:00
for f in callbacks {
2021-01-02 18:34:13 +00:00
f(event.clone(), status);
2021-01-02 15:22:48 +00:00
}
}
2021-01-02 14:10:16 +00:00
}
2021-01-02 15:22:48 +00:00
pub fn register_event_handler<F: 'static, Fut: 'static>(&mut self, event: EventKind, mut f: F)
2021-01-02 12:16:48 +00:00
where
2021-01-02 18:34:13 +00:00
F: FnMut(Event, &PairStatus) -> Fut,
2021-01-02 15:22:48 +00:00
Fut: Future<Output=()> + Send, {
self.event_handlers
.entry(event)
.or_default()
2021-01-02 18:34:13 +00:00
.push(Box::new(move |e, s| tokio::spawn(f(e, s))));
2021-01-02 12:16:48 +00:00
}
2021-01-02 15:22:48 +00:00
}