fn: added close_position to broker.rs

This commit is contained in:
Khizar Imran
2026-06-04 00:25:08 +01:00
parent 35a6f8dc00
commit 7d19b1d519
2 changed files with 26 additions and 0 deletions
+25
View File
@@ -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 {
+1
View File
@@ -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,