import os import time import requests # Import for fetching prices from CoinMarketCap from web3 import Web3 from web3.eth.abi import ABICodec from web3.eth.transaction import Transaction # Information to connect to the exchange WETH_ADDRESS = "0x7083609f3831a52b0b7277e62b900c3338d282e0" PANCAKESWAP_ROUTER_ADDRESS = "0x1755777577917882b5b0873e7e5e664d4ed8a763" # Contract ABI PANCAKESWAP_ROUTER_ABI = [ { "inputs": [ {"name": "amountIn", "type": "uint256"}, {"name": "tokenIn", "type": "address"}, {"name": "tokenOut", "type": "address"}, {"name": "swap", "type": "bool"}, ], "name": "swapExactTokensForTokens", "outputs": [ {"name": "amountOut", "type": "uint256"}, ], "stateMutability": "payable", "type": "function", }, ] # Minimum spread percentage (adjustable) MIN_SPREAD_PERCENT = 3 # Web3 provider URL (replace with your provider) WEB3_PROVIDER_URL = "https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID" # Example # CoinMarketCap API endpoint (replace with your API key) CMC_API_URL = "https://api.coinmarketcap.com/v1/ticker/" CMC_API_KEY = "YOUR_CMC_API_KEY" # Example def get_price(coin_symbol): """Fetches the current price of a coin from CoinMarketCap.""" url = f"{CMC_API_URL}{coin_symbol}" headers = {"X-CMC_API_KEY": CMC_API_KEY} response = requests.get(url, headers=headers) data = response.json() if data["status"]["error_code"] == 0: return float(data["data"][0]["price_usd"]) else: print(f"Error fetching price for {coin_symbol}: {data['status']['error_message']}") return None def main(): # Connect to the exchange web3 = Web3(Web3.HTTPProvider(WEB3_PROVIDER_URL)) # Create contract object router_contract = web3.eth.contract(address=PANCAKESWAP_ROUTER_ADDRESS, abi=PANCAKESWAP_ROUTER_ABI) # Minimum spread amount (calculated based on percentage) min_spread = MIN_SPREAD_PERCENT * 0.01 # Convert percentage to decimal while True: # Get prices of currency pairs weth_price = get_price("weth") busd_price = get_price("busd") # Calculate price difference weth_busd_spread = busd_price - weth_price # If price difference is greater than minimum spread, perform trade if weth_busd_spread > min_spread: # Amount to trade (adjustable) amount = 100 # Build transaction to buy WETH swap_weth_tx = router_contract.functions.swapExactTokensForTokens( amount, BUSD_ADDRESS, WETH_ADDRESS, True, ).build_Transaction() # Estimate gas cost for the transaction gas_estimate = web3.eth.gas_estimate(swap_weth_tx) try: # Send transaction to buy WETH swap_weth_tx.send(gas=gas_estimate) # Wait for transaction confirmation tx_receipt = swap_weth_tx.wait_for_receipt() # Check transaction status if tx_receipt.status != 1: print(f"Error: Transaction failed with status {tx_receipt.status}") continue # Build transaction to sell BUSD (completed) swap_busd # Get the amount of WETH acquired amount_weth = tx_receipt.logs[0].args["amountOut"] # Build transaction to sell WETH swap_busd_tx = router_contract.functions.swapExactTokensForTokens( amount_weth, WETH_ADDRESS, BUSD_ADDRESS, True, ).build_transaction() # Estimate gas cost for the transaction gas_estimate = web3.eth.gas_estimate(swap_busd_tx) # Send transaction to sell BUSD swap_busd_tx.send(gas=gas_estimate) # Wait for transaction confirmation tx_receipt = swap_busd_tx.wait_for_receipt() # Check transaction status if tx_receipt.status != 1: print(f"Error: Transaction failed with status {tx_receipt.status}") continue # Calculate profit (if any) profit = busd_price * tx_receipt.logs[0].args["amountOut"] - amount # Print trade results print(f"Successfully traded WETH for BUSD!") print(f"Amount of BUSD acquired: {tx_receipt.logs[0].args['amountOut']}") print(f"Profit: {profit}") else: print(f"Price difference is below minimum spread ({min_spread}). No trade performed.") # Wait for a few seconds before next iteration time.sleep(5) if __name__ == "__main__": main()