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