Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
371 changes: 371 additions & 0 deletions servers/rust-server/Cargo.lock

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions servers/rust-server/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,6 @@ uuid = "1.18.1"
num-traits = "0.2.19"
charming = {version = "0.6.0", features = ["html"]}
clap = { version = "4.5.51", features = ["derive"] }
utoipa = { version = "5.4.0", features = ["axum_extras"] }
utoipa-axum = "0.2.0"
utoipa-swagger-ui = { version = "9.0.2", features = ["axum", "reqwest"] }
1 change: 1 addition & 0 deletions servers/rust-server/src/bot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use axum::{
};
use entity::{bot, wallet, orderbook};
use sea_orm::{DatabaseConnection, EntityTrait, ColumnTrait, QueryFilter};

use crate::{error::AppError, state::AppState};

#[derive(Template)]
Expand Down
10 changes: 9 additions & 1 deletion servers/rust-server/src/clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,16 @@ pub fn start_clock(clock: SharedClock) {
});
}

#[utoipa::path(
get,
path = "/api/time",
description = "Get the current time of the financial market simulation clock.",
responses(
(status = 200, description = "Succesfully retrieved market time"),
)
)]
pub async fn time(State(state): State<AppState>) -> Result<impl IntoResponse, AppError> {
let clock = state.clock.read().await;
let time_str = clock.current_time().format("%Y-%m-%d %H:%M:%S").to_string();
Ok(time_str)
}
}
14 changes: 13 additions & 1 deletion servers/rust-server/src/enroll.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,24 @@ use sea_orm::{ActiveValue::Set, prelude::Decimal};
use crate::{error::AppError, state::AppState};
use entity::{bot, wallet};
use sea_orm::ActiveModelTrait;
use serde::{Serialize, Deserialize};
use utoipa::ToSchema;

#[derive(serde::Deserialize)]
#[derive(Serialize, Deserialize, ToSchema, Debug, Clone)]
pub struct EnrollPayload {
pub name: String,
}

#[utoipa::path(
post,
path = "/api/enroll",
description = "Enroll a new bot to the market. Each bot must have a unique name.",
request_body(content = EnrollPayload, content_type = "application/json"),
responses(
(status = 200, description = "New bot enrolled successfully", body = String),
(status = 406, description = "Bot with same name already exists", body = String),
),
)]
pub async fn enroll(
State(state): State<AppState>, Json(payload): Json<EnrollPayload>,
) -> Result<String, AppError> {
Expand Down
21 changes: 21 additions & 0 deletions servers/rust-server/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ use std::sync::Arc;
use tokio::sync::RwLock;
use tower_http::services::ServeDir;
use tower_http::trace::TraceLayer;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
use tracing::Level;
use tracing::event;

Expand Down Expand Up @@ -46,6 +48,24 @@ async fn main() -> Result<(), Error> {
cli::run().await
}

#[derive(OpenApi)]
#[openapi(
info(title = "FinWar Market API"),
paths(
enroll::enroll,
clock::time,
trade::buy,
trade::sell,
trade::price,
),
components(
schemas(enroll::EnrollPayload),
schemas(trade::BuyOrderInput),
schemas(trade::SellOrderInput),
),
)]
struct ApiDoc;

/// Start the HTTP server. Separated out so `main` can dispatch to either
/// the server or other management subcommands (like `migrate`).
pub async fn run_server(db: DatabaseConnection) -> Result<(), Error> {
Expand Down Expand Up @@ -88,6 +108,7 @@ pub async fn run_server(db: DatabaseConnection) -> Result<(), Error> {
.route("/api/sell", post(sell))
.route("/api/price", get(price))
.nest_service("/static", ServeDir::new("static"))
.merge(SwaggerUi::new("/swagger-ui").url("/api-doc/openapi.json", ApiDoc::openapi()))
.fallback(|| async { AppError::NotFound })
.with_state(state)
.layer(TraceLayer::new_for_http());
Expand Down
34 changes: 32 additions & 2 deletions servers/rust-server/src/trade.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,31 @@ use sea_orm::ColumnTrait;
use sea_orm::prelude::*;
use sea_orm::{DatabaseConnection, EntityTrait, QueryFilter, QueryOrder, ActiveModelTrait, Set};
use uuid::Uuid;
use serde::{Serialize, Deserialize};
use utoipa::ToSchema;

#[derive(serde::Deserialize)]
#[derive(Serialize, Deserialize, ToSchema, Debug, Clone)]
pub struct BuyOrderInput {
pub bot_uuid: String,
pub investment: f64,
}

#[derive(serde::Deserialize)]
#[derive(Serialize, Deserialize, ToSchema, Debug, Clone)]
pub struct SellOrderInput {
pub bot_uuid: String,
pub quantity: i32,
}

#[utoipa::path(
post,
path = "/api/buy",
description = "Buy the maximum amount of stock at market price for the given investment.",
request_body(content = BuyOrderInput, content_type = "application/json"),
responses(
(status = 200, description = "Succesfully buy stock", body = BuyOrderInput),
(status = 400, description = "Bad request"),
)
)]
pub async fn buy(
State(state): State<AppState>, Json(payload): Json<BuyOrderInput>,
) -> Result<impl IntoResponse, AppError> {
Expand Down Expand Up @@ -63,6 +75,16 @@ pub async fn buy(
Ok(format!("Bought {} shares for ${:.2}", shares_to_buy, actual_cost))
}

#[utoipa::path(
post,
path = "/api/sell",
request_body(content = SellOrderInput, content_type = "application/json"),
description = "Sell the defined number of stocks at market price.",
responses(
(status = 200, description = "Successfully sold stock", body = String),
(status = 400, description = "Bad request"),
)
)]
pub async fn sell(
State(state): State<AppState>, Json(payload): Json<SellOrderInput>,
) -> Result<impl IntoResponse, AppError> {
Expand Down Expand Up @@ -119,6 +141,14 @@ async fn get_current_price(state: &AppState) -> Result<f64, AppError> {
Ok(price_mean)
}

#[utoipa::path(
get,
path = "/api/price",
description = "Get the current market price of the tracked stock.",
responses(
(status = 200, description = "Succesfully retrieved stock price", body = String),
)
)]
pub async fn price(
State(state): State<AppState>,
) -> Result<impl IntoResponse, AppError> {
Expand Down
2 changes: 1 addition & 1 deletion servers/rust-server/templates/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ <h1>Finwar</h1>
<br />
The <a href="/leaderboard">Leaderboard</a> tracks the best.
<br />
The <a href="/docs">Documentation</a> helps you get started building your bot.
The <a href="/swagger-ui">Documentation</a> helps you get started building your bot.
<br />
<br />
Below is some recent market activity that the bots may work with.
Expand Down