-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNFT_Trader_sol.py
144 lines (129 loc) · 5.44 KB
/
NFT_Trader_sol.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
import requests
import time
from solana.rpc.api import Client
from solana.rpc.types import TxOpts
from solana.transaction import Transaction
from solana.keypair import Keypair
from base64 import b64decode
import logging
# Logging config
logging.basicConfig(filename="nft_mev_wallet_bot.log", level=logging.INFO, format="%(asctime)s - %(message)s")
# Constants
MAGIC_EDEN_API = "https://api-mainnet.magiceden.dev/v2"
SOLANA_RPC = "https://api.mainnet-beta.solana.com"
CONTRACT_ADDRESS = "Your_Collection_Contract_Address" # Replace with actual contract address
BUY_THRESHOLD = 0.85 # Buy if price < 85% of floor price
PROFIT_THRESHOLD = 1.2 # Sell if price > 120% of purchase price
MAX_SPENDING_LIMIT_SOL = 10 # Maximum SOL the bot is allowed to spend
# Initialize Solana client
solana_client = Client(SOLANA_RPC)
# Load wallet keypair securely
WALLET_PRIVATE_KEY = "your_private_key_base64" # Replace with actual private key in base64 format
wallet_keypair = Keypair.from_secret_key(b64decode(WALLET_PRIVATE_KEY))
WALLET_PUBLIC_KEY = str(wallet_keypair.public_key)
# Fetch collection stats (including floor price)
def fetch_collection_stats(contract_address):
url = f"{MAGIC_EDEN_API}/collections/{contract_address}/stats"
response = requests.get(url)
if response.status_code == 200:
data = response.json()
return {
"floor_price": data.get("floorPrice", 0) / 10**9, # Convert lamports to SOL
"volume_24h": data.get("volume24hr", 0),
}
else:
logging.error(f"Error fetching collection stats: {response.text}")
return {"floor_price": None, "volume_24h": 0}
# Fetch new listings for the collection
def fetch_new_listings(contract_address):
url = f"{MAGIC_EDEN_API}/collections/{contract_address}/listings"
response = requests.get(url)
if response.status_code == 200:
listings = response.json()
return [
listing for listing in listings
if listing.get("price") and listing.get("price") > 0
] # Filter valid listings
else:
logging.error(f"Error fetching listings: {response.text}")
return []
# Monitor wallet balance
def check_wallet_balance():
balance = solana_client.get_balance(wallet_keypair.public_key)["result"]["value"]
return balance / 10**9 # Convert lamports to SOL
# Purchase NFT
def purchase_nft(mint_address, price):
try:
wallet_balance = check_wallet_balance()
if wallet_balance < price:
logging.warning(f"Insufficient balance to purchase NFT: {mint_address} at {price} SOL")
return False
logging.info(f"Attempting to buy NFT: {mint_address} at {price} SOL")
tx = Transaction()
tx.add(
transfer(
from_pubkey=wallet_keypair.public_key,
to_pubkey=PublicKey(mint_address),
lamports=int(price * 10**9),
)
)
response = solana_client.send_transaction(
tx, wallet_keypair, opts=TxOpts(skip_confirmation=False)
)
logging.info(f"Purchase successful: {response}")
return True
except Exception as e:
logging.error(f"Error purchasing NFT {mint_address}: {str(e)}")
return False
# List NFT for sale
def list_nft_for_sale(mint_address, sell_price):
try:
logging.info(f"Listing NFT for sale: {mint_address} at {sell_price} SOL")
# Implement listing logic here using Magic Eden's API or custom transaction
url = f"{MAGIC_EDEN_API}/listings"
payload = {
"mintAddress": mint_address,
"price": sell_price,
"walletAddress": WALLET_PUBLIC_KEY
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
logging.info(f"NFT listed successfully: {mint_address} at {sell_price} SOL")
return True
else:
logging.error(f"Error listing NFT: {response.text}")
return False
except Exception as e:
logging.error(f"Error listing NFT {mint_address} for sale: {str(e)}")
return False
# Entry & Exit Strategy
def trading_strategy(contract_address):
stats = fetch_collection_stats(contract_address)
if stats["floor_price"] is None:
logging.error("Unable to fetch floor price. Skipping strategy.")
return
floor_price = stats["floor_price"]
logging.info(f"Floor price: {floor_price} SOL")
# Fetch new listings
listings = fetch_new_listings(contract_address)
for nft in listings:
price = nft.get("price", 0)
mint_address = nft.get("mintAddress")
# Entry Logic: Buy if the price is below the threshold
if price < floor_price * BUY_THRESHOLD:
logging.info(f"Undervalued NFT detected: {mint_address} at {price} SOL")
if purchase_nft(mint_address, price):
# Exit Logic: List the NFT at a profit margin
sell_price = price * PROFIT_THRESHOLD
logging.info(f"Preparing to list NFT at {sell_price} SOL")
list_nft_for_sale(mint_address, sell_price)
# Main loop
if __name__ == "__main__":
logging.info("Starting NFT MEV wallet bot with enhanced logic...")
try:
while True:
trading_strategy(CONTRACT_ADDRESS)
time.sleep(5) # Adjust frequency for real-time monitoring
except KeyboardInterrupt:
logging.info("Bot stopped by user.")