copy_trading/position/
process_buy_tx_confirmation.rs

1use crate::types::position::Position;
2use crate::types::position_manager::PositionManager;
3use crate::types::position_status::PositionStatus;
4use solana_central::SwapTx;
5use solana_central::constants::LAMPORTS_PER_SOL;
6use std::sync::{Arc, Mutex};
7use std::time::{SystemTime, UNIX_EPOCH};
8
9impl Position {
10  /// Process confirmation of a buy transaction, transitioning position from Opening to Open.
11  /// Records entry price, tokens purchased, and initializes stop-loss thresholds. Starts the
12  /// hold-time task to automatically close the position after the configured hold duration.
13  pub fn process_buy_tx_confirmation(
14    position: &mut Position,
15    position_arc: &Arc<Mutex<Position>>,
16    swap_tx: &SwapTx,
17    position_manager: &Arc<PositionManager>,
18  ) {
19    // Only process if we're in the opening state
20    if position.status != PositionStatus::Opening {
21      println!(
22        "POSITION: Received tx confirmation for position not in Opening state. Status: {:?}, Market: {}",
23        position.status, position.pool_address
24      );
25      return;
26    }
27
28    // The entry price is the execution price of the buy
29    position.entry_price_lp =
30      swap_tx.swapped_amount_in as u128 * LAMPORTS_PER_SOL / swap_tx.swapped_amount_received as u128;
31    position.buy_confirmation_time = SystemTime::now()
32      .duration_since(UNIX_EPOCH)
33      .unwrap()
34      .as_millis() as u64;
35    position.tokens_purchased = swap_tx.swapped_amount_received;
36    // println!("Tokens purchased: {}", swap_tx.amount_out);
37
38    // Initialize stop loss price if using stop loss
39    if position.config.use_stop_loss {
40      position.stop_loss_price_lp = position.entry_price_lp;
41      position.lowest_acceptable_price_lp = position.entry_price_lp
42        * (LAMPORTS_PER_SOL - position.config.stop_loss_threshold_lp as u128)
43        / LAMPORTS_PER_SOL;
44    }
45
46    // Update status to Open
47    position.status = PositionStatus::Open;
48
49    println!("POSITION: Confirm Open, Token: {}", position.token_address);
50
51    // Start the hold time task
52    Position::start_hold_time_task(
53      position_arc.clone(),
54      position.config.hold_time_ms,
55      position.token_address,
56      position_manager.clone(),
57    );
58  }
59}