This commit is contained in:
Giulio De Pasquale 2021-01-02 18:34:13 +00:00
parent bf3da0723f
commit a03e0bc574
3 changed files with 48 additions and 9 deletions

View File

@ -53,10 +53,20 @@ impl Event {
fn has_metadata(&self) -> bool {
self.metadata.is_some()
}
pub fn kind(&self) -> EventKind {
self.kind
}
pub fn tick(&self) -> u64 {
self.tick
}
pub fn metadata(&self) -> Option<EventMetadata> {
self.metadata
}
}
pub struct EventDispatcher {
event_handlers: HashMap<EventKind, Vec<Box<dyn FnMut(&Position, &PairStatus) -> JoinHandle<()>>>>,
event_handlers: HashMap<EventKind, Vec<Box<dyn FnMut(Event, &PairStatus) -> JoinHandle<()>>>>,
}
impl EventDispatcher {
@ -66,21 +76,21 @@ impl EventDispatcher {
}
}
pub fn call_handler(&mut self, event: &EventKind, position: &Position, status: &PairStatus) {
if let Some(callbacks) = self.event_handlers.get_mut(event) {
pub fn call_handler(&mut self, event: &Event, status: &PairStatus) {
if let Some(callbacks) = self.event_handlers.get_mut(&event.kind()) {
for f in callbacks {
f(position, status);
f(event.clone(), status);
}
}
}
pub fn register_event_handler<F: 'static, Fut: 'static>(&mut self, event: EventKind, mut f: F)
where
F: FnMut(&Position, &PairStatus) -> Fut,
F: FnMut(Event, &PairStatus) -> Fut,
Fut: Future<Output=()> + Send, {
self.event_handlers
.entry(event)
.or_default()
.push(Box::new(move |p, s| tokio::spawn(f(p, s))));
.push(Box::new(move |e, s| tokio::spawn(f(e, s))));
}
}

View File

@ -1,6 +1,8 @@
use std::collections::HashMap;
use crate::events::{EventDispatcher, Event};
use bitfinex::positions::Position;
use crate::events::{Event, EventDispatcher};
use crate::positions::PositionWrapper;
use crate::strategy::Strategy;
@ -27,4 +29,31 @@ impl PairStatus {
strategy,
}
}
pub fn add_position(&mut self, position: Position) {
let (pw, events) = {
match &self.strategy {
Some(strategy) => {
strategy.position_on_new_tick(position)
},
None => (PositionWrapper::new(position.clone(), position.pl(), position.pl_perc(), None), vec![])
}
};
self.positions
.entry(self.current_tick)
.or_default()
.push(pw.clone());
// self.dispatcher.call_state_handlers(pw);
for e in events {
self.add_event(e);
}
}
pub fn add_event(&mut self, event: Event) {
self.events.push(event);
// self.dispatcher.call_handler(&event);
}
}

View File

@ -24,11 +24,11 @@ pub struct PositionWrapper {
position: Position,
net_pl: f64,
net_pl_perc: f64,
state: PositionState,
state: Option<PositionState>,
}
impl PositionWrapper {
pub fn new(position: Position, net_pl: f64, net_pl_perc: f64, state: PositionState) -> Self {
pub fn new(position: Position, net_pl: f64, net_pl_perc: f64, state: Option<PositionState>) -> Self {
PositionWrapper {
position,
net_pl,