dispatcher implemented

This commit is contained in:
Giulio De Pasquale 2021-01-02 15:22:48 +00:00
parent d4e388154d
commit bf3da0723f
2 changed files with 27 additions and 16 deletions

View File

@ -1,22 +1,26 @@
use std::collections::HashMap;
use std::future::Future;
use bitfinex::positions::Position;
use tokio::task::JoinHandle;
use crate::BoxError;
use crate::pairs::PairStatus;
enum SignalKind {
#[derive(Copy, Clone)]
pub enum SignalKind {
ClosePosition,
OpenPosition,
}
struct EventMetadata {
#[derive(Copy, Clone)]
pub struct EventMetadata {
position_id: Option<u64>,
order_id: Option<u64>,
}
#[derive(PartialEq, Eq, Hash)]
enum EventKind {
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub enum EventKind {
NewMinimum,
NewMaximum,
ReachedLoss,
@ -30,6 +34,7 @@ enum EventKind {
NewTick,
}
#[derive(Copy, Clone)]
pub struct Event {
kind: EventKind,
tick: u64,
@ -51,27 +56,31 @@ impl Event {
}
pub struct EventDispatcher {
event_handlers: HashMap<EventKind, Box<dyn Fn(String) -> JoinHandle<()>>>
event_handlers: HashMap<EventKind, Vec<Box<dyn FnMut(&Position, &PairStatus) -> JoinHandle<()>>>>,
}
impl EventDispatcher {
pub fn new() -> Self {
EventDispatcher {
event_handlers: HashMap::new()
event_handlers: HashMap::new(),
}
}
pub fn call_handler(&self, event: &EventKind) {
self.event_handlers.iter()
.filter(|(e, _)| e == event)
.map(|(_, f)| f("test".into()));
pub fn call_handler(&mut self, event: &EventKind, position: &Position, status: &PairStatus) {
if let Some(callbacks) = self.event_handlers.get_mut(event) {
for f in callbacks {
f(position, status);
}
}
}
pub fn register_event_handler<F: 'static, Fut: 'static>(&mut self, event: EventKind, f: F)
pub fn register_event_handler<F: 'static, Fut: 'static>(&mut self, event: EventKind, mut f: F)
where
F: Fn(String) -> Fut,
Fut: Future<Output=()> + Send,
{
self.event_handlers.insert(event, Box::new(move |args| tokio::spawn(f(args))));
F: FnMut(&Position, &PairStatus) -> Fut,
Fut: Future<Output=()> + Send, {
self.event_handlers
.entry(event)
.or_default()
.push(Box::new(move |p, s| tokio::spawn(f(p, s))));
}
}

View File

@ -1,5 +1,6 @@
use bitfinex::positions::Position;
#[derive(Copy, Clone)]
pub enum PositionState {
Critical,
Loss,
@ -18,6 +19,7 @@ impl PositionState {
}
}
#[derive(Clone)]
pub struct PositionWrapper {
position: Position,
net_pl: f64,