Skip to content

Commit

Permalink
09/10/2023 10:47:05 PM 💻
Browse files Browse the repository at this point in the history
  • Loading branch information
alloc33 committed Sep 10, 2023
1 parent ce5374a commit e1a9a6f
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 33 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ Cargo.lock

/target
.env
config.toml
strategies.toml
config/
4 changes: 3 additions & 1 deletion market/src/app_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@ pub struct Database {
#[derive(Debug, Deserialize, Clone)]
pub struct Alpaca {
pub apca_api_key_id: String,
pub apca_api_secret_key: String
pub apca_api_secret_key: String,
pub apca_api_base_url: String
}

#[derive(Debug, Clone, Deserialize)]
pub struct AppConfig {
pub api_key: String,
pub database: Database,
pub alpaca: Alpaca
}

impl AppConfig {
Expand Down
11 changes: 6 additions & 5 deletions market/src/events/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ use tokio::sync::{
};
use tracing::error;

use crate::{api::alert::AlertData, strategy_manager::trade_error::TradeError};
use crate::{
api::alert::AlertData,
strategy_manager::{trade_error::TradeError, StrategyManagerError},
};

#[derive(Clone, Debug)]
pub struct EventBus {
Expand All @@ -19,10 +22,8 @@ pub struct EventBus {
pub enum HandleEventError {
#[error(transparent)]
TradeError(#[from] TradeError),
#[error("Unknown exchange - {0}")]
UnknownExchange(String),
#[error("Unknown strategy - {0}")]
UnknownStrategy(String),
#[error(transparent)]
StrategyManagerError(#[from] StrategyManagerError),
}

#[axum::async_trait]
Expand Down
2 changes: 1 addition & 1 deletion market/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ async fn main() -> Result<(), Box<dyn Error>> {
// Setup trading related components
let trade_executor = TradeExecutor;

let strategy_manager = Arc::new(StrategyManager::new(Arc::clone(&state), trade_executor));
let strategy_manager = Arc::new(StrategyManager::new(Arc::clone(&state), trade_executor)?);

// Start event dispatcher
tokio::spawn(dispatch_events(events.receiver, strategy_manager));
Expand Down
3 changes: 1 addition & 2 deletions market/src/strategy_manager/broker.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
use serde::Deserialize;

use super::{trade_error::TradeError, Order, TradingClient};
use crate::api::alert::AlertData;

use super::{TradingClient, Order, trade_error::TradeError};

#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Broker {
Expand Down
66 changes: 44 additions & 22 deletions market/src/strategy_manager/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ pub mod trade_error;

use std::sync::Arc;

use apca::Client as AlpacaClient
use apca::{ApiInfo, Client as AlpacaClient};
use config::{Config, ConfigError, File};
use serde::Deserialize;
use thiserror::Error as ThisError;
use tokio::time::{sleep, Duration};
use tracing::{error, info};
use trade_error::TradeError;
Expand Down Expand Up @@ -46,6 +47,18 @@ pub struct StrategyManager {
trade_executor: TradeExecutor,
}

#[derive(Debug, ThisError)]
pub enum StrategyManagerError {
#[error(transparent)]
ConfigError(#[from] ConfigError),
#[error(transparent)]
AlpacaClientError(#[from] apca::Error),
#[error("Unknown strategy - {0}")]
UnknownStrategy(String),
#[error("Unknown exchange - {0}")]
UnknownExchange(String),
}

#[derive(Debug)]
pub struct Order {
id: Uuid,
Expand All @@ -58,16 +71,26 @@ impl std::fmt::Display for Order {
}

impl StrategyManager {
pub fn new(app_state: Arc<App>, trade_executor: TradeExecutor) -> Result<Self, ConfigError> {
let config = Config::builder()
pub fn new(
app_state: Arc<App>,
trade_executor: TradeExecutor,
) -> Result<Self, StrategyManagerError> {
let strategies = Config::builder()
.add_source(File::with_name("market/strategies.toml"))
.build()?;
.build()
.map_err(StrategyManagerError::ConfigError)?
.try_deserialize::<Vec<Strategy>>()?;

let strategies = config.try_deserialize::<Vec<Strategy>>()?;
let alpaca_client = AlpacaClient::new(ApiInfo::from_parts(
&app_state.config.alpaca.apca_api_base_url,
&app_state.config.alpaca.apca_api_key_id,
&app_state.config.alpaca.apca_api_secret_key,
)?);

Ok(Self {
app_state,
strategies,
alpaca_client,
trade_executor,
})
}
Expand All @@ -87,29 +110,28 @@ impl EventHandler for StrategyManager {
if let Some(strategy) = self.find_strategy(event.strategy_id) {
let mut retries = 0;

let order = strategy.broker.create_order(event);
// let order = strategy.broker.create_order(event);

loop {
let trade_result = self.trade_executor.execute_order(&order).await;
// loop {
// let trade_result = self.trade_executor.execute_order(&order).await;

if trade_result.is_ok() {
info!("Order successfully executed");
return Ok(());
}
// if trade_result.is_ok() {
// info!("Order successfully executed");
// return Ok(());
// }

retries += 1;
// retries += 1;

if retries >= strategy.max_event_retries {
error!("Max event retries reached, giving up.");
return Err(TradeError::MaxRetriesReached(order).into());
}
// if retries >= strategy.max_event_retries {
// error!("Max event retries reached, giving up.");
// return Err(TradeError::MaxRetriesReached(order).into());
// }

tokio::time::sleep(Duration::from_secs_f64(strategy.event_retry_delay)).await;
}
// tokio::time::sleep(Duration::from_secs_f64(strategy.event_retry_delay)).await;
// }
Ok(())
} else {
Err(HandleEventError::UnknownStrategy(
event.strategy_id.to_string(),
))
Err(StrategyManagerError::UnknownStrategy(event.strategy_id.to_string()).into())
}
}
}
2 changes: 1 addition & 1 deletion market/src/trade_executor/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use uuid::Uuid;
use crate::{
api::alert::AlertData,
strategy_manager::{trade_error::TradeError, Order},
App
App,
};

pub mod alpaca_client;
Expand Down

0 comments on commit e1a9a6f

Please sign in to comment.