From 7d19b1d51991e7895d7f1acf86b24e0a5d2a473d Mon Sep 17 00:00:00 2001 From: Khizar Imran Date: Thu, 4 Jun 2026 00:25:08 +0100 Subject: [PATCH] fn: added close_position to broker.rs --- src/broker.rs | 25 +++++++++++++++++++++++++ src/types.rs | 1 + 2 files changed, 26 insertions(+) diff --git a/src/broker.rs b/src/broker.rs index df0f7d7..5cfa535 100644 --- a/src/broker.rs +++ b/src/broker.rs @@ -18,6 +18,7 @@ impl Broker { pub fn buy(&mut self, price: f64, lot_size: f64, timestamp: i64) { // needs to modify the broker with new position. (.push works with the Vec::) self.positions.push(Position { + id: 0, entry_price: price, lot_size, is_long: true, @@ -27,6 +28,7 @@ impl Broker { pub fn sell(&mut self, price: f64, lot_size: f64, timestamp: i64) { // needs to modify the broker with new position. (.push works with the Vec::) self.positions.push(Position { + id : 0, entry_price: price, lot_size, is_long: false, @@ -34,6 +36,29 @@ impl Broker { }); } + pub fn close_position (&mut self, id: u64, price:f64, timestamp:i64) { + if let Some(index) = self.positions.iter().position(|p| p.id == id) { + let position = self.positions.remove(index); + + let pnl = if position.is_long { + (price - position.entry_price) * position.lot_size + } else { + (position.entry_price - price) * position.lot_size + }; + + self.cash += pnl; + self.trade_history.push(Trade { + entry_price: position.entry_price, + lot_size: position.lot_size, + is_long: position.is_long, + pnl, + entry_timestamp: position.entry_timestamp, + exit_timestamp: timestamp, + exit_price: price + }); + } + } + pub fn close_all (&mut self, price:f64, timestamp: i64) { // Instead of .push it uses drain to calculate the close all positions for position in self.positions.drain(..) { let pnl = if position.is_long { diff --git a/src/types.rs b/src/types.rs index 3f1b7fd..83adac7 100644 --- a/src/types.rs +++ b/src/types.rs @@ -10,6 +10,7 @@ pub struct Bar { // Initialises the interface for the bar #[derive(Debug, Clone)] pub struct Position { // this is for the trading position + pub id: u64, pub entry_price: f64, pub lot_size: f64, pub is_long: bool,