copy_trading/position/
process_sell_tx_confirmation.rs

1use crate::types::position::Position;
2use crate::types::position_status::PositionStatus;
3use solana_central::constants::LAMPORTS_PER_SOL;
4use solana_central::SwapTx;
5use solana_sdk::pubkey::Pubkey;
6use std::collections::HashMap;
7use std::sync::Arc;
8use std::sync::Mutex;
9use std::time::{SystemTime, UNIX_EPOCH};
10
11impl Position {
12  /// Process confirmation of a sell transaction, finalizing the position. Records exit price,
13  /// calculates PNL, marks position as Closed, and removes it from the open positions map.
14  pub fn process_sell_tx_confirmation(
15    position: &mut Position,
16    open_positions: &mut HashMap<Pubkey, Arc<Mutex<Position>>>,
17    swap_tx: &SwapTx,
18  ) {
19    /*
20    This can come up on manual sell. Still close position out to avoid resell logic loop and not
21    buying again. But indicate its being sold manually.
22    */
23    if position.status != PositionStatus::Closing {
24      println!("POSITION: Manual sell, token: {}", position.token_address);
25    }
26
27    /*
28    The exit price is the execution price of the sell. It is recorded as the amount of SOL received
29    / amount of token sold. So it would be amount out / amount in.
30    */
31    position.exit_price_lp =
32      swap_tx.swapped_amount_received as u128 * LAMPORTS_PER_SOL / swap_tx.swapped_amount_in as u128;
33    position.sell_confirmation_time = SystemTime::now()
34      .duration_since(UNIX_EPOCH)
35      .unwrap()
36      .as_millis() as u64;
37    position.sell_amount_lp = swap_tx.swapped_amount_received;
38
39    // Update status to Closed
40    position.status = PositionStatus::Closed;
41
42    // Remove position from open positions map
43    open_positions.remove(&position.pool_address);
44
45    let pnl = (position.exit_price_lp as f64 - position.entry_price_lp as f64)
46      / position.entry_price_lp as f64
47      * 100.0;
48    println!(
49      "POSITION: Confirm Close, token: {}, PNL: {}%",
50      position.token_address, pnl
51    );
52  }
53}