docs(cursor): add uv rules, formatting
This commit is contained in:
+134
-107
@@ -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}")
|
||||
|
||||
Reference in New Issue
Block a user