def execute_trade(pair_contract, token0_address, token1_address, token0_price_usdt, token1_price_usdt, token0_symbol, token1_symbol, exchange_name,
token0_price_1, token1_price_1, token0_symbol_1, token1_symbol_1, exchange_name_1, price_ratio_1, price_percentage_1):
# INVEST ----------------->"the amount of USDT to use for trading"
pdb.set_trace()
usdt_amount = 10 # Adjust the amount as per your preference
# Calculate the token amounts to buy and sell
token0_amount = usdt_amount / token0_price_usdt
token1_amount = usdt_amount / token1_price_usdt
# Convert token amounts to uint256
token0_amount_uint = Web3.to_wei(token0_amount, 'ether')
token1_amount_uint = Web3.to_wei(token1_amount, 'ether')
# Approve the pair contract to spend USDT from your account
usdt_contract = web3M.eth.contract(address='0xdAC17F958D2ee523a2206206994597C13D831ec7', abi=usdt_abi)
nonce = web3M.eth.get_transaction_count(account_address)+1
approve_tx = usdt_contract.functions.approve(pair_contract.address, usdt_amount).build_transaction({
'from': account_address,
'gas': 200000,
'gasPrice': web3M.to_wei('50', 'gwei'),
'nonce': nonce,
'chainId': 1 # Replace with the actual chain ID
})
signed_approve_tx = web3M.eth.account.sign_transaction(approve_tx, private_key=private_key)
approve_tx_hash = None
try:
if signed_approve_tx.rawTransaction:
approve_tx_hash = web3M.eth.send_raw_transaction(signed_approve_tx.rawTransaction)
print(f"Approve transaction sent. Transaction Hash: {web3M.to_hex(approve_tx_hash)}")
else:
print("Error: The raw transaction is None. Please check the signing process.")
return
except ValueError as e:
if "already known" in str(e):
print("Transaction already known. Skipping approval.")
else:
print("Error sending approve transaction:", e)
return
# Add a delay before checking the transaction receipt
time.sleep(40)
while True:
try:
if approve_tx_hash:
receipt = web3M.eth.get_transaction(approve_tx_hash)
if receipt:
print("Transaction receipt found.")
break
else:
print("Error: The transaction hash is None. Skipping receipt retrieval.")
break
except ValueError as e:
print("Error retrieving transaction receipt:", e)
break
except Exception as e:
print("Unexpected error occurred while retrieving transaction receipt:", e)
break
print("Approve transaction mined.")
# Buy token on the exchange with the lowest token price
if token0_price_usdt <= token1_price_usdt:
buy_token_address = token0_address
buy_token_amount = token0_amount_uint
min_token_price = token0_price_usdt
else:
buy_token_address = token1_address
buy_token_amount = token1_amount_uint
min_token_price = token1_price_usdt
# Check if the price conditions for the first exchange are met
if token0_price_usdt == token0_price and token1_price_usdt == token1_price:
nonce = web3M.eth.get_transaction_count(account_address) + 1
# Perform the trade on the first exchange
buy_tx = pair_contract.functions.swap(buy_token_amount, 0, buy_token_address, b'').build_transaction({
'from': account_address,
'gas': 200000,
'gasPrice': web3M.to_wei('100', 'gwei'),
'nonce': nonce,
'chainId': 1# Replace with the actual chain ID
})
signed_buy_tx = web3M.eth.account.sign_transaction(buy_tx, private_key=private_key)
buy_tx_hash = web3M.eth.send_raw_transaction(signed_buy_tx.rawTransaction)
print(f"Buy transaction sent. Transaction Hash: {web3M.to_hex(buy_tx_hash)}")
time.sleep(60)
max_retries = 3
retry_interval = 10 # seconds
retry_count = 0
# Wait for the buy transaction to be mined
while retry_count < max_retries:
try:
receipt = web3M.eth.get_transaction_receipt(buy_tx_hash)
if receipt is not None:
break
except TransactionNotFound:
pass
retry_count += 1
print(f"Fetching..{retry_count}/{max_retries} - Waiting for transaction to be mined...")
time.sleep(retry_interval)
if receipt is not None:
print("Buy transaction mined.")
else:
print("Buy transaction not mined after maximum retries.")
# Check if the price conditions for the second exchange are met
elif token0_price_usdt == token0_price_1 and token1_price_usdt == token1_price_1:
nonce = web3M.eth.get_transaction_count(account_address) + 1
# Perform the trade on the second exchang
buy_tx = pair_contract.functions.swap(buy_token_amount, 0, buy_token_address, b'').build_transaction({
'from': account_address,
'gas': 200000,
'gasPrice': web3M.to_wei('60', 'gwei'),
'nonce': nonce,
'chainId': 1# Replace with the actual chain ID
})
signed_buy_tx = web3M.eth.account.sign_transaction(buy_tx, private_key=private_key)
buy_tx_hash = web3M.eth.send_raw_transaction(signed_buy_tx.rawTransaction)
print(f"Buy transaction sent. Transaction Hash: {web3M.to_hex(buy_tx_hash)}")
time.sleep(60)
# Wait for the buy transaction to be mined with retry
max_retries = 3
retry_interval = 10 # seconds
retry_count = 0
# Wait for the buy transaction to be mined
while retry_count < max_retries:
try:
receipt = web3M.eth.get_transaction_receipt(buy_tx_hash)
if receipt is not None:
break
except TransactionNotFound:
pass
retry_count += 1
print(f"Fetching.. {retry_count}/{max_retries} - Waiting for transaction to be mined...")
time.sleep(retry_interval)
if receipt is not None:
print("Buy transaction mined.")
else:
print("Buy transaction not mined after maximum retries.")
# Sell token on the exchange with the highest token price
if token0_price_usdt >= token1_price_usdt:
sell_token_address = token0_address
sell_token_amount = token0_amount
max_token_price = token0_price_usdt
else:
sell_token_address = token1_address
sell_token_amount = token1_amount
max_token_price = token1_price_usdt
# Check if the price conditions for the first exchange are met
if token0_price_usdt == token0_price and token1_price_usdt == token1_price:
nonce = web3M.eth.get_transaction_count(account_address)
# Perform the trade on the first exchange
sell_tx = pair_contract.functions.swap(token0_amount_uint, 0, sell_token_address, to_bytes(text='')).build_transaction({
'from': account_address,
'gas': 200000,
'gasPrice': web3M.to_wei('60', 'gwei'),
'nonce': nonce,
'chainId': 1# Replace with the actual chain ID
})
signed_sell_tx = web3M.eth.account.sign_transaction(sell_tx, private_key=private_key)
sell_tx_hash = web3M.eth.send_raw_transaction(signed_sell_tx.rawTransaction)
print(f"Sell transaction sent. Transaction Hash: {web3M.to_hex(sell_tx_hash)}")
time.sleep(60)
# Wait for the buy transaction to be mined with retry
max_retries = 3
retry_interval = 10 # seconds
retry_count = 0
# Wait for the sell transaction to be mined
while retry_count < max_retries:
try:
receipt = web3M.eth.get_transaction_receipt(sell_tx_hash)
if receipt is not None:
break
except TransactionNotFound:
pass
retry_count += 1
print(f"Fetching.. {retry_count}/{max_retries} - Waiting for transaction to be mined...")
time.sleep(retry_interval)
if receipt is not None:
print("Buy transaction mined.")
else:
print("Buy transaction not mined after maximum retries.")
# Check if the price conditions for the second exchange are met
elif token0_price_usdt == token0_price_1 and token1_price_usdt == token1_price_1:
# Retrieve the transaction count for the sender's address
nonce = web3M.eth.get_transaction_count(account_address)
# Perform the trade on the second exchange
sell_tx = pair_contract.functions.swap(sell_token_amount, 0, sell_token_address, b'').build_transaction({
'from': account_address,
'gas': 200000,
'gasPrice': web3M.to_wei('60', 'gwei'),
'nonce': nonce,
'chainId': 1 # Replace with the actual chain ID
})
signed_sell_tx = web3M.eth.account.sign_transaction(sell_tx, private_key=private_key)
sell_tx_hash = web3M.eth.send_raw_transaction(signed_sell_tx.rawTransaction)
print(f"Sell transaction sent. Transaction Hash: {web3M.to_hex(sell_tx_hash)}")
time.sleep(60)
# Wait for the buy transaction to be mined with retry
max_retries = 3
retry_interval = 10 # seconds
retry_count = 0
# Wait for the sell transaction to be mined
while retry_count < max_retries:
try:
receipt = web3M.eth.get_transaction_receipt(sell_tx_hash)
if receipt is not None:
break
except TransactionNotFound:
pass
retry_count += 1
print(f"Fetching.. {retry_count}/{max_retries} - Waiting for transaction to be mined...")
time.sleep(retry_interval)
if receipt is not None:
print("Buy transaction mined.")
else:
print("Buy transaction not mined after maximum retries.")
else:
# No suitable exchange found
print("No suitable exchange found for the specified price conditions.")
# Print the trade details
print(f"Buy {buy_token_amount:.6f} {token0_symbol if token0_symbol != 'USDT' else token1_symbol} for {usdt_amount:.2f} USDT at {min_token_price:.6f} USDT/{token0_symbol if token0_symbol != 'USDT' else token1_symbol}")
print(f"Sell {sell_token_amount:.6f} {token0_symbol if token0_symbol != 'USDT' else token1_symbol} for {usdt_amount:.2f} USDT at {max_token_price:.6f} USDT/{token0_symbol if token0_symbol != 'USDT' else token1_symbol}")
此代码在测试网上运行良好,但在主网上运行时出现错误:
“ValueError: {'code': -32000, 'message': 'replacement transaction underpriced'}” .So I had also seen its solution on the internet, to increase the gas price or to increase the nonce.But the code started showing these error{‘code': -32000, 'message': 'exceeds block gas limit’}.So I went back to just reducing the gas price but that same error started coming back .“ValueError: {'code': -32000, 'message': 'replacement transaction underpriced’}”. i solved all this error but after incresing gwei it giving me new error - ValueError: {'code': -32000, 'message': 'transaction would cause overdraft'}
我希望批准交易买卖
只需重新安装元掩码钱包或在新的浏览器窗口中添加新的钱包扩展,然后将代币从旧钱包转移到新钱包并使用新钱包的私钥来部署合约。 可以的,我试过了