docs(cursor): add uv rules, formatting

This commit is contained in:
smypmsa
2025-07-18 12:03:00 +00:00
parent a5a92fbf4b
commit 536a5dd6a5
28 changed files with 2746 additions and 784 deletions
+113 -58
View File
@@ -82,10 +82,12 @@ class TokenBuyer(Trader):
# Skip the wait and directly calculate the amount
token_amount = self.extreme_fast_token_amount
token_price_sol = self.amount / token_amount
#logger.info(f"EXTREME FAST Mode: Buying {token_amount} tokens.")
# logger.info(f"EXTREME FAST Mode: Buying {token_amount} tokens.")
else:
# Regular behavior with RPC call
curve_state = await self.curve_manager.get_curve_state(token_info.bonding_curve)
curve_state = await self.curve_manager.get_curve_state(
token_info.bonding_curve
)
token_price_sol = curve_state.calculate_price()
token_amount = self.amount / token_price_sol
@@ -114,16 +116,20 @@ class TokenBuyer(Trader):
if success:
# Get actual execution data from bonding curve balance changes
actual_price, actual_tokens = await self._get_actual_execution_price(tx_signature, token_info)
actual_price, actual_tokens = await self._get_actual_execution_price(
tx_signature, token_info
)
logger.info(f"Buy transaction confirmed: {tx_signature}")
logger.info(f"Actual price paid to bonding curve: {actual_price:.8f} SOL per token")
logger.info(
f"Actual price paid to bonding curve: {actual_price:.8f} SOL per token"
)
return TradeResult(
success=True,
tx_signature=tx_signature,
amount=actual_tokens, # Actual tokens received
price=actual_price, # Actual price based on bonding curve SOL flow
amount=actual_tokens, # Actual tokens received
price=actual_price, # Actual price based on bonding curve SOL flow
)
else:
return TradeResult(
@@ -196,7 +202,7 @@ class TokenBuyer(Trader):
self.wallet.pubkey,
self.wallet.pubkey,
token_info.mint,
SystemAddresses.TOKEN_PROGRAM
SystemAddresses.TOKEN_PROGRAM,
)
# Prepare buy instruction data
@@ -222,129 +228,178 @@ class TokenBuyer(Trader):
logger.error(f"Buy transaction failed: {e!s}")
raise
async def _get_actual_execution_price(self, tx_signature: str, token_info: TokenInfo) -> tuple[float, float]:
async def _get_actual_execution_price(
self, tx_signature: str, token_info: TokenInfo
) -> tuple[float, float]:
"""Get actual execution price from bonding curve SOL balance changes."""
try:
client = await self.client.get_client()
tx_response = await client.get_transaction(
tx_signature,
tx_signature,
encoding="jsonParsed",
commitment="confirmed",
max_supported_transaction_version=0
max_supported_transaction_version=0,
)
if not tx_response.value or not tx_response.value.transaction:
raise ValueError("Transaction not found")
meta = tx_response.value.transaction.meta
if not meta or not meta.pre_balances or not meta.post_balances:
raise ValueError("Transaction balance data not found")
# Get accounts - they're ParsedAccountTxStatus objects, need to extract pubkey
accounts = tx_response.value.transaction.transaction.message.account_keys
# Find bonding curve account index in the transaction
bonding_curve_index = None
for i, account in enumerate(accounts):
# Extract pubkey from ParsedAccountTxStatus object
account_pubkey = str(account.pubkey) if hasattr(account, 'pubkey') else str(account)
account_pubkey = (
str(account.pubkey) if hasattr(account, "pubkey") else str(account)
)
if account_pubkey == str(token_info.bonding_curve):
bonding_curve_index = i
break
if bonding_curve_index is None:
raise ValueError("Bonding curve not found in transaction accounts")
pre_balance_lamports = meta.pre_balances[bonding_curve_index]
post_balance_lamports = meta.post_balances[bonding_curve_index]
sol_sent_to_curve = (post_balance_lamports - pre_balance_lamports) / LAMPORTS_PER_SOL
sol_sent_to_curve = (
post_balance_lamports - pre_balance_lamports
) / LAMPORTS_PER_SOL
if sol_sent_to_curve <= 0:
raise ValueError(f"No SOL sent to bonding curve: {sol_sent_to_curve}")
tokens_received = await self._get_tokens_received_from_tx(tx_response, token_info)
tokens_received = await self._get_tokens_received_from_tx(
tx_response, token_info
)
if tokens_received == 0:
raise ValueError("Cannot compute execution price: zero tokens received")
actual_price = sol_sent_to_curve / tokens_received
logger.info(f"Bonding curve received: {sol_sent_to_curve:.6f} SOL")
logger.info(f"We received: {tokens_received:.6f} tokens")
logger.info(f"Actual execution price: {actual_price:.8f} SOL per token")
return actual_price, tokens_received
except Exception as e:
logger.warning(f"Failed to get actual execution price from bonding curve: {e}")
logger.warning(
f"Failed to get actual execution price from bonding curve: {e}"
)
# Fallback to EXTREME_FAST estimate
tokens_received = self.extreme_fast_token_amount if self.extreme_fast_mode else self.amount / await self.curve_manager.calculate_price(token_info.bonding_curve)
tokens_received = (
self.extreme_fast_token_amount
if self.extreme_fast_mode
else self.amount
/ await self.curve_manager.calculate_price(token_info.bonding_curve)
)
if tokens_received == 0:
logger.error("Fallback failed unable to determine tokens received")
return 0.0, 0.0
logger.error("Fallback failed unable to determine tokens received")
return 0.0, 0.0
return self.amount / tokens_received, tokens_received
async def _get_tokens_received_from_tx(self, tx_response, token_info: TokenInfo) -> float:
async def _get_tokens_received_from_tx(
self, tx_response, token_info: TokenInfo
) -> float:
"""Extract tokens received from transaction token balance changes."""
meta = tx_response.value.transaction.meta
pre_token_balance = 0
post_token_balance = 0
wallet_str = str(self.wallet.pubkey)
mint_str = str(token_info.mint)
if meta.pre_token_balances:
for balance in meta.pre_token_balances:
# Convert to string for comparison
balance_owner = str(balance.owner) if hasattr(balance, 'owner') else str(getattr(balance, 'owner', ''))
balance_mint = str(balance.mint) if hasattr(balance, 'mint') else str(getattr(balance, 'mint', ''))
balance_owner = (
str(balance.owner)
if hasattr(balance, "owner")
else str(getattr(balance, "owner", ""))
)
balance_mint = (
str(balance.mint)
if hasattr(balance, "mint")
else str(getattr(balance, "mint", ""))
)
if balance_owner == wallet_str and balance_mint == mint_str:
try:
# Try multiple ways to get the amount
if hasattr(balance, 'ui_token_amount'):
if hasattr(balance, "ui_token_amount"):
amount_obj = balance.ui_token_amount
if hasattr(amount_obj, 'amount') and amount_obj.amount is not None:
if (
hasattr(amount_obj, "amount")
and amount_obj.amount is not None
):
pre_token_balance = int(amount_obj.amount)
elif hasattr(amount_obj, 'ui_amount') and amount_obj.ui_amount is not None:
pre_token_balance = int(float(amount_obj.ui_amount) * (10**TOKEN_DECIMALS))
elif (
hasattr(amount_obj, "ui_amount")
and amount_obj.ui_amount is not None
):
pre_token_balance = int(
float(amount_obj.ui_amount) * (10**TOKEN_DECIMALS)
)
except (ValueError, TypeError) as e:
logger.warning(f"Error parsing pre-token balance: {e}")
break
# Check post-token balances
# Check post-token balances
if meta.post_token_balances:
for balance in meta.post_token_balances:
# Convert to string for comparison
balance_owner = str(balance.owner) if hasattr(balance, 'owner') else str(getattr(balance, 'owner', ''))
balance_mint = str(balance.mint) if hasattr(balance, 'mint') else str(getattr(balance, 'mint', ''))
balance_owner = (
str(balance.owner)
if hasattr(balance, "owner")
else str(getattr(balance, "owner", ""))
)
balance_mint = (
str(balance.mint)
if hasattr(balance, "mint")
else str(getattr(balance, "mint", ""))
)
if balance_owner == wallet_str and balance_mint == mint_str:
try:
# Try multiple ways to get the amount
if hasattr(balance, 'ui_token_amount'):
if hasattr(balance, "ui_token_amount"):
amount_obj = balance.ui_token_amount
if hasattr(amount_obj, 'amount') and amount_obj.amount is not None:
if (
hasattr(amount_obj, "amount")
and amount_obj.amount is not None
):
post_token_balance = int(amount_obj.amount)
elif hasattr(amount_obj, 'ui_amount') and amount_obj.ui_amount is not None:
post_token_balance = int(float(amount_obj.ui_amount) * (10**TOKEN_DECIMALS))
elif (
hasattr(amount_obj, "ui_amount")
and amount_obj.ui_amount is not None
):
post_token_balance = int(
float(amount_obj.ui_amount) * (10**TOKEN_DECIMALS)
)
except (ValueError, TypeError) as e:
logger.warning(f"Error parsing post-token balance: {e}")
break
# Calculate tokens received
if pre_token_balance == 0 and post_token_balance > 0:
tokens_received_raw = post_token_balance
else:
tokens_received_raw = post_token_balance - pre_token_balance
if tokens_received_raw <= 0:
logger.warning("Token balance search failed. Using fallback from EXTREME_FAST estimate.")
logger.warning(
"Token balance search failed. Using fallback from EXTREME_FAST estimate."
)
# Fallback: use the amount we know we bought
if self.extreme_fast_mode and self.extreme_fast_token_amount > 0:
return self.extreme_fast_token_amount
@@ -352,4 +407,4 @@ class TokenBuyer(Trader):
logger.error("Cannot determine tokens received from transaction")
return 0.0
return tokens_received_raw / 10**TOKEN_DECIMALS
return tokens_received_raw / 10**TOKEN_DECIMALS
+27 -26
View File
@@ -11,6 +11,7 @@ from solders.pubkey import Pubkey
class ExitReason(Enum):
"""Reasons for position exit."""
TAKE_PROFIT = "take_profit"
STOP_LOSS = "stop_loss"
MAX_HOLD_TIME = "max_hold_time"
@@ -20,27 +21,27 @@ class ExitReason(Enum):
@dataclass
class Position:
"""Represents an active trading position."""
# Token information
mint: Pubkey
symbol: str
# Position details
entry_price: float
quantity: float
entry_time: datetime
# Exit conditions
take_profit_price: float | None = None
stop_loss_price: float | None = None
max_hold_time: int | None = None # seconds
# Status
is_active: bool = True
exit_reason: ExitReason | None = None
exit_price: float | None = None
exit_time: datetime | None = None
@classmethod
def create_from_buy_result(
cls,
@@ -53,7 +54,7 @@ class Position:
max_hold_time: int | None = None,
) -> "Position":
"""Create a position from a successful buy transaction.
Args:
mint: Token mint address
symbol: Token symbol
@@ -62,18 +63,18 @@ class Position:
take_profit_percentage: Take profit percentage (0.5 = 50% profit)
stop_loss_percentage: Stop loss percentage (0.2 = 20% loss)
max_hold_time: Maximum hold time in seconds
Returns:
Position instance
"""
take_profit_price = None
if take_profit_percentage is not None:
take_profit_price = entry_price * (1 + take_profit_percentage)
stop_loss_price = None
if stop_loss_percentage is not None:
stop_loss_price = entry_price * (1 - stop_loss_percentage)
return cls(
mint=mint,
symbol=symbol,
@@ -84,38 +85,38 @@ class Position:
stop_loss_price=stop_loss_price,
max_hold_time=max_hold_time,
)
def should_exit(self, current_price: float) -> tuple[bool, ExitReason | None]:
"""Check if position should be exited based on current conditions.
Args:
current_price: Current token price
Returns:
Tuple of (should_exit, exit_reason)
"""
if not self.is_active:
return False, None
# Check take profit
if self.take_profit_price and current_price >= self.take_profit_price:
return True, ExitReason.TAKE_PROFIT
# Check stop loss
if self.stop_loss_price and current_price <= self.stop_loss_price:
return True, ExitReason.STOP_LOSS
# Check max hold time
if self.max_hold_time:
elapsed_time = (datetime.utcnow() - self.entry_time).total_seconds()
if elapsed_time >= self.max_hold_time:
return True, ExitReason.MAX_HOLD_TIME
return False, None
def close_position(self, exit_price: float, exit_reason: ExitReason) -> None:
"""Close the position with exit details.
Args:
exit_price: Price at which position was exited
exit_reason: Reason for exit
@@ -124,27 +125,27 @@ class Position:
self.exit_price = exit_price
self.exit_reason = exit_reason
self.exit_time = datetime.utcnow()
def get_pnl(self, current_price: float | None = None) -> dict:
"""Calculate profit/loss for the position.
Args:
current_price: Current price (uses exit_price if position is closed)
Returns:
Dictionary with PnL information
"""
if self.is_active and current_price is None:
raise ValueError("current_price required for active position")
price_to_use = self.exit_price if not self.is_active else current_price
if price_to_use is None:
raise ValueError("No price available for PnL calculation")
price_change = price_to_use - self.entry_price
price_change_pct = (price_change / self.entry_price) * 100
unrealized_pnl = price_change * self.quantity
return {
"entry_price": self.entry_price,
"current_price": price_to_use,
@@ -153,7 +154,7 @@ class Position:
"unrealized_pnl_sol": unrealized_pnl,
"quantity": self.quantity,
}
def __str__(self) -> str:
"""String representation of position."""
if self.is_active:
@@ -162,4 +163,4 @@ class Position:
status = f"CLOSED ({self.exit_reason.value})"
else:
status = "CLOSED (UNKNOWN)"
return f"Position({self.symbol}: {self.quantity:.6f} @ {self.entry_price:.8f} SOL - {status})"
return f"Position({self.symbol}: {self.quantity:.6f} @ {self.entry_price:.8f} SOL - {status})"
+3 -1
View File
@@ -175,7 +175,9 @@ class TokenSeller(Trader):
pubkey=SystemAddresses.PROGRAM, is_signer=False, is_writable=False
),
AccountMeta(
pubkey=token_info.creator_vault, is_signer=False, is_writable=True,
pubkey=token_info.creator_vault,
is_signer=False,
is_writable=True,
),
AccountMeta(
pubkey=SystemAddresses.TOKEN_PROGRAM, is_signer=False, is_writable=False
+134 -107
View File
@@ -39,6 +39,7 @@ logger = get_logger(__name__)
class PumpTrader:
"""Coordinates trading operations for pump.fun tokens with focus on freshness."""
def __init__(
self,
rpc_endpoint: str,
@@ -52,37 +53,31 @@ class PumpTrader:
geyser_api_token: str | None = None,
geyser_auth_type: str = "x-token",
pumpportal_url: str = "wss://pumpportal.fun/api/data",
extreme_fast_mode: bool = False,
extreme_fast_token_amount: int = 30,
# Exit strategy configuration
exit_strategy: str = "time_based",
take_profit_percentage: float | None = None,
stop_loss_percentage: float | None = None,
max_hold_time: int | None = None,
price_check_interval: int = 10,
# Priority fee configuration
enable_dynamic_priority_fee: bool = False,
enable_fixed_priority_fee: bool = True,
fixed_priority_fee: int = 200_000,
extra_priority_fee: float = 0.0,
hard_cap_prior_fee: int = 200_000,
# Retry and timeout settings
max_retries: int = 3,
wait_time_after_creation: int = 15, # here and further - seconds
wait_time_after_creation: int = 15, # here and further - seconds
wait_time_after_buy: int = 15,
wait_time_before_new_token: int = 15,
max_token_age: int | float = 0.001,
token_wait_timeout: int = 30,
# Cleanup settings
cleanup_mode: str = "disabled",
cleanup_force_close_with_burn: bool = False,
cleanup_with_priority_fee: bool = False,
# Trading filters
match_string: str | None = None,
bro_address: str | None = None,
@@ -129,7 +124,7 @@ class PumpTrader:
cleanup_mode: Cleanup mode ("disabled", "auto", or "manual")
cleanup_force_close_with_burn: Whether to force close with burn during cleanup
cleanup_with_priority_fee: Whether to use priority fees during cleanup
match_string: Optional string to match in token name/symbol
bro_address: Optional creator address to filter by
marry_mode: If True, only buy tokens and skip selling
@@ -155,7 +150,7 @@ class PumpTrader:
buy_slippage,
max_retries,
extreme_fast_token_amount,
extreme_fast_mode
extreme_fast_mode,
)
self.seller = TokenSeller(
self.solana_client,
@@ -165,30 +160,34 @@ class PumpTrader:
sell_slippage,
max_retries,
)
# Initialize the appropriate listener type
listener_type = listener_type.lower()
if listener_type == "geyser":
if not geyser_endpoint or not geyser_api_token:
raise ValueError("Geyser endpoint and API token are required for geyser listener")
raise ValueError(
"Geyser endpoint and API token are required for geyser listener"
)
self.token_listener = GeyserListener(
geyser_endpoint,
geyser_endpoint,
geyser_api_token,
geyser_auth_type,
PumpAddresses.PROGRAM
geyser_auth_type,
PumpAddresses.PROGRAM,
)
logger.info("Using Geyser listener for token monitoring")
elif listener_type == "logs":
self.token_listener = LogsListener(wss_endpoint, PumpAddresses.PROGRAM)
logger.info("Using logsSubscribe listener for token monitoring")
elif listener_type == "pumpportal":
self.token_listener = PumpPortalListener(PumpAddresses.PROGRAM, pumpportal_url)
self.token_listener = PumpPortalListener(
PumpAddresses.PROGRAM, pumpportal_url
)
logger.info("Using PumpPortal listener for token monitoring")
else:
self.token_listener = BlockListener(wss_endpoint, PumpAddresses.PROGRAM)
logger.info("Using blockSubscribe listener for token monitoring")
# Trading parameters
self.buy_amount = buy_amount
self.buy_slippage = buy_slippage
@@ -196,21 +195,21 @@ class PumpTrader:
self.max_retries = max_retries
self.extreme_fast_mode = extreme_fast_mode
self.extreme_fast_token_amount = extreme_fast_token_amount
# Exit strategy parameters
self.exit_strategy = exit_strategy.lower()
self.take_profit_percentage = take_profit_percentage
self.stop_loss_percentage = stop_loss_percentage
self.max_hold_time = max_hold_time
self.price_check_interval = price_check_interval
# Timing parameters
self.wait_time_after_creation = wait_time_after_creation
self.wait_time_after_buy = wait_time_after_buy
self.wait_time_before_new_token = wait_time_before_new_token
self.max_token_age = max_token_age
self.token_wait_timeout = token_wait_timeout
# Cleanup parameters
self.cleanup_mode = cleanup_mode
self.cleanup_force_close_with_burn = cleanup_force_close_with_burn
@@ -221,26 +220,36 @@ class PumpTrader:
self.bro_address = bro_address
self.marry_mode = marry_mode
self.yolo_mode = yolo_mode
# State tracking
self.traded_mints: set[Pubkey] = set()
self.token_queue: asyncio.Queue = asyncio.Queue()
self.processing: bool = False
self.processed_tokens: set[str] = set()
self.token_timestamps: dict[str, float] = {}
async def start(self) -> None:
"""Start the trading bot and listen for new tokens."""
logger.info("Starting pump.fun trader")
logger.info(f"Match filter: {self.match_string if self.match_string else 'None'}")
logger.info(f"Creator filter: {self.bro_address if self.bro_address else 'None'}")
logger.info(
f"Match filter: {self.match_string if self.match_string else 'None'}"
)
logger.info(
f"Creator filter: {self.bro_address if self.bro_address else 'None'}"
)
logger.info(f"Marry mode: {self.marry_mode}")
logger.info(f"YOLO mode: {self.yolo_mode}")
logger.info(f"Exit strategy: {self.exit_strategy}")
if self.exit_strategy == "tp_sl":
logger.info(f"Take profit: {self.take_profit_percentage * 100 if self.take_profit_percentage else 'None'}%")
logger.info(f"Stop loss: {self.stop_loss_percentage * 100 if self.stop_loss_percentage else 'None'}%")
logger.info(f"Max hold time: {self.max_hold_time if self.max_hold_time else 'None'} seconds")
logger.info(
f"Take profit: {self.take_profit_percentage * 100 if self.take_profit_percentage else 'None'}%"
)
logger.info(
f"Stop loss: {self.stop_loss_percentage * 100 if self.stop_loss_percentage else 'None'}%"
)
logger.info(
f"Max hold time: {self.max_hold_time if self.max_hold_time else 'None'} seconds"
)
logger.info(f"Max token age: {self.max_token_age} seconds")
try:
@@ -253,19 +262,23 @@ class PumpTrader:
# Choose operating mode based on yolo_mode
if not self.yolo_mode:
# Single token mode: process one token and exit
logger.info("Running in single token mode - will process one token and exit")
logger.info(
"Running in single token mode - will process one token and exit"
)
token_info = await self._wait_for_token()
if token_info:
await self._handle_token(token_info)
logger.info("Finished processing single token. Exiting...")
else:
logger.info(f"No suitable token found within timeout period ({self.token_wait_timeout}s). Exiting...")
logger.info(
f"No suitable token found within timeout period ({self.token_wait_timeout}s). Exiting..."
)
else:
# Continuous mode: process tokens until interrupted
logger.info("Running in continuous mode - will process tokens until interrupted")
processor_task = asyncio.create_task(
self._process_token_queue()
logger.info(
"Running in continuous mode - will process tokens until interrupted"
)
processor_task = asyncio.create_task(self._process_token_queue())
try:
await self.token_listener.listen_for_tokens(
@@ -281,28 +294,28 @@ class PumpTrader:
await processor_task
except asyncio.CancelledError:
pass
except Exception as e:
logger.error(f"Trading stopped due to error: {e!s}")
finally:
await self._cleanup_resources()
logger.info("Pump trader has shut down")
async def _wait_for_token(self) -> TokenInfo | None:
"""Wait for a single token to be detected.
Returns:
TokenInfo or None if timeout occurs
"""
# Create a one-time event to signal when a token is found
token_found = asyncio.Event()
found_token = None
async def token_callback(token: TokenInfo) -> None:
nonlocal found_token
token_key = str(token.mint)
# Only process if not already processed and fresh
if token_key not in self.processed_tokens:
# Record when the token was discovered
@@ -310,7 +323,7 @@ class PumpTrader:
found_token = token
self.processed_tokens.add(token_key)
token_found.set()
listener_task = asyncio.create_task(
self.token_listener.listen_for_tokens(
token_callback,
@@ -318,15 +331,19 @@ class PumpTrader:
self.bro_address,
)
)
# Wait for a token with a timeout
try:
logger.info(f"Waiting for a suitable token (timeout: {self.token_wait_timeout}s)...")
logger.info(
f"Waiting for a suitable token (timeout: {self.token_wait_timeout}s)..."
)
await asyncio.wait_for(token_found.wait(), timeout=self.token_wait_timeout)
logger.info(f"Found token: {found_token.symbol} ({found_token.mint})")
return found_token
except TimeoutError:
logger.info(f"Timed out after waiting {self.token_wait_timeout}s for a token")
logger.info(
f"Timed out after waiting {self.token_wait_timeout}s for a token"
)
return None
finally:
listener_task.cancel()
@@ -341,28 +358,26 @@ class PumpTrader:
try:
logger.info(f"Cleaning up {len(self.traded_mints)} traded token(s)...")
await handle_cleanup_post_session(
self.solana_client,
self.wallet,
list(self.traded_mints),
self.solana_client,
self.wallet,
list(self.traded_mints),
self.priority_fee_manager,
self.cleanup_mode,
self.cleanup_with_priority_fee,
self.cleanup_force_close_with_burn
self.cleanup_force_close_with_burn,
)
except Exception as e:
logger.error(f"Error during cleanup: {e!s}")
old_keys = {k for k in self.token_timestamps if k not in self.processed_tokens}
for key in old_keys:
self.token_timestamps.pop(key, None)
await self.solana_client.close()
async def _queue_token(
self, token_info: TokenInfo
) -> None:
async def _queue_token(self, token_info: TokenInfo) -> None:
"""Queue a token for processing if not already processed.
Args:
token_info: Token information to queue
"""
@@ -413,9 +428,7 @@ class PumpTrader:
finally:
self.token_queue.task_done()
async def _handle_token(
self, token_info: TokenInfo
) -> None:
async def _handle_token(self, token_info: TokenInfo) -> None:
"""Handle a new token creation event.
Args:
@@ -456,7 +469,7 @@ class PumpTrader:
self, token_info: TokenInfo, buy_result: TradeResult
) -> None:
"""Handle successful token purchase.
Args:
token_info: Token information
buy_result: The result of the buy operation
@@ -470,7 +483,7 @@ class PumpTrader:
buy_result.tx_signature,
)
self.traded_mints.add(token_info.mint)
# Choose exit strategy
if not self.marry_mode:
if self.exit_strategy == "tp_sl":
@@ -486,28 +499,28 @@ class PumpTrader:
self, token_info: TokenInfo, buy_result: TradeResult
) -> None:
"""Handle failed token purchase.
Args:
token_info: Token information
buy_result: The result of the buy operation
"""
logger.error(
f"Failed to buy {token_info.symbol}: {buy_result.error_message}"
)
logger.error(f"Failed to buy {token_info.symbol}: {buy_result.error_message}")
# Close ATA if enabled
await handle_cleanup_after_failure(
self.solana_client,
self.wallet,
token_info.mint,
self.solana_client,
self.wallet,
token_info.mint,
self.priority_fee_manager,
self.cleanup_mode,
self.cleanup_with_priority_fee,
self.cleanup_force_close_with_burn
self.cleanup_force_close_with_burn,
)
async def _handle_tp_sl_exit(self, token_info: TokenInfo, buy_result: TradeResult) -> None:
async def _handle_tp_sl_exit(
self, token_info: TokenInfo, buy_result: TradeResult
) -> None:
"""Handle take profit/stop loss exit strategy.
Args:
token_info: Token information
buy_result: Result from the buy operation
@@ -517,30 +530,28 @@ class PumpTrader:
mint=token_info.mint,
symbol=token_info.symbol,
entry_price=buy_result.price, # type: ignore
quantity=buy_result.amount, # type: ignore
quantity=buy_result.amount, # type: ignore
take_profit_percentage=self.take_profit_percentage,
stop_loss_percentage=self.stop_loss_percentage,
max_hold_time=self.max_hold_time,
)
logger.info(f"Created position: {position}")
if position.take_profit_price:
logger.info(f"Take profit target: {position.take_profit_price:.8f} SOL")
if position.stop_loss_price:
logger.info(f"Stop loss target: {position.stop_loss_price:.8f} SOL")
# Monitor position until exit condition is met
await self._monitor_position_until_exit(token_info, position)
async def _handle_time_based_exit(self, token_info: TokenInfo) -> None:
"""Handle legacy time-based exit strategy.
Args:
token_info: Token information
"""
logger.info(
f"Waiting for {self.wait_time_after_buy} seconds before selling..."
)
logger.info(f"Waiting for {self.wait_time_after_buy} seconds before selling...")
await asyncio.sleep(self.wait_time_after_buy)
logger.info(f"Selling {token_info.symbol}...")
@@ -557,52 +568,62 @@ class PumpTrader:
)
# Close ATA if enabled
await handle_cleanup_after_sell(
self.solana_client,
self.wallet,
token_info.mint,
self.solana_client,
self.wallet,
token_info.mint,
self.priority_fee_manager,
self.cleanup_mode,
self.cleanup_with_priority_fee,
self.cleanup_force_close_with_burn
self.cleanup_force_close_with_burn,
)
else:
logger.error(
f"Failed to sell {token_info.symbol}: {sell_result.error_message}"
)
async def _monitor_position_until_exit(self, token_info: TokenInfo, position: Position) -> None:
async def _monitor_position_until_exit(
self, token_info: TokenInfo, position: Position
) -> None:
"""Monitor a position until exit conditions are met.
Args:
token_info: Token information
position: Position to monitor
"""
logger.info(f"Starting position monitoring (check interval: {self.price_check_interval}s)")
logger.info(
f"Starting position monitoring (check interval: {self.price_check_interval}s)"
)
while position.is_active:
try:
# Get current price from bonding curve
current_price = await self.curve_manager.calculate_price(token_info.bonding_curve)
current_price = await self.curve_manager.calculate_price(
token_info.bonding_curve
)
# Check if position should be exited
should_exit, exit_reason = position.should_exit(current_price)
if should_exit and exit_reason:
logger.info(f"Exit condition met: {exit_reason.value}")
logger.info(f"Current price: {current_price:.8f} SOL")
# Log PnL before exit
pnl = position.get_pnl(current_price)
logger.info(f"Position PnL: {pnl['price_change_pct']:.2f}% ({pnl['unrealized_pnl_sol']:.6f} SOL)")
logger.info(
f"Position PnL: {pnl['price_change_pct']:.2f}% ({pnl['unrealized_pnl_sol']:.6f} SOL)"
)
# Execute sell
sell_result = await self.seller.execute(token_info)
if sell_result.success:
# Close position with actual exit price
position.close_position(sell_result.price, exit_reason) # type: ignore
logger.info(f"Successfully exited position: {exit_reason.value}")
logger.info(
f"Successfully exited position: {exit_reason.value}"
)
self._log_trade(
"sell",
token_info,
@@ -610,41 +631,47 @@ class PumpTrader:
sell_result.amount, # type: ignore
sell_result.tx_signature,
)
# Log final PnL
final_pnl = position.get_pnl()
logger.info(f"Final PnL: {final_pnl['price_change_pct']:.2f}% ({final_pnl['unrealized_pnl_sol']:.6f} SOL)")
logger.info(
f"Final PnL: {final_pnl['price_change_pct']:.2f}% ({final_pnl['unrealized_pnl_sol']:.6f} SOL)"
)
# Close ATA if enabled
await handle_cleanup_after_sell(
self.solana_client,
self.wallet,
token_info.mint,
self.solana_client,
self.wallet,
token_info.mint,
self.priority_fee_manager,
self.cleanup_mode,
self.cleanup_with_priority_fee,
self.cleanup_force_close_with_burn
self.cleanup_force_close_with_burn,
)
else:
logger.error(f"Failed to exit position: {sell_result.error_message}")
logger.error(
f"Failed to exit position: {sell_result.error_message}"
)
# Keep monitoring in case sell can be retried
break
else:
# Log current status
pnl = position.get_pnl(current_price)
logger.debug(f"Position status: {current_price:.8f} SOL ({pnl['price_change_pct']:+.2f}%)")
logger.debug(
f"Position status: {current_price:.8f} SOL ({pnl['price_change_pct']:+.2f}%)"
)
# Wait before next price check
await asyncio.sleep(self.price_check_interval)
except Exception as e:
logger.error(f"Error monitoring position: {e}")
await asyncio.sleep(self.price_check_interval) # Continue monitoring despite errors
await asyncio.sleep(
self.price_check_interval
) # Continue monitoring despite errors
async def _save_token_info(
self, token_info: TokenInfo
) -> None:
async def _save_token_info(self, token_info: TokenInfo) -> None:
"""Save token information to a file.
Args:
@@ -694,4 +721,4 @@ class PumpTrader:
with open("trades/trades.log", "a") as log_file:
log_file.write(json.dumps(log_entry) + "\n")
except Exception as e:
logger.error(f"Failed to log trade information: {e!s}")
logger.error(f"Failed to log trade information: {e!s}")