Facebook
From Aboozar Rezaee, 2 Weeks ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 117
  1. import os
  2. import time
  3. import requests  # Import for fetching prices from CoinMarketCap
  4.  
  5. from web3 import Web3
  6. from web3.eth.abi import ABICodec
  7. from web3.eth.transaction import Transaction
  8.  
  9. # Information to connect to the exchange
  10. WETH_ADDRESS = "0x7083609f3831a52b0b7277e62b900c3338d282e0"
  11. PANCAKESWAP_ROUTER_ADDRESS = "0x1755777577917882b5b0873e7e5e664d4ed8a763"
  12.  
  13. # Contract ABI
  14. PANCAKESWAP_ROUTER_ABI = [
  15.     {
  16.         "inputs": [
  17.             {"name": "amountIn", "type": "uint256"},
  18.             {"name": "tokenIn", "type": "address"},
  19.             {"name": "tokenOut", "type": "address"},
  20.             {"name": "swap", "type": "bool"},
  21.         ],
  22.         "name": "swapExactTokensForTokens",
  23.         "outputs": [
  24.             {"name": "amountOut", "type": "uint256"},
  25.         ],
  26.         "stateMutability": "payable",
  27.         "type": "function",
  28.     },
  29. ]
  30.  
  31. # Minimum spread percentage (adjustable)
  32. MIN_SPREAD_PERCENT = 3
  33.  
  34. # Web3 provider URL (replace with your provider)
  35. WEB3_PROVIDER_URL = "https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID"  # Example
  36.  
  37. # CoinMarketCap API endpoint (replace with your API key)
  38. CMC_API_URL = "https://api.coinmarketcap.com/v1/ticker/"
  39. CMC_API_KEY = "YOUR_CMC_API_KEY"  # Example
  40.  
  41.  
  42. def get_price(coin_symbol):
  43.     """Fetches the current price of a coin from CoinMarketCap."""
  44.     url = f"{CMC_API_URL}{coin_symbol}"
  45.     headers = {"X-CMC_API_KEY": CMC_API_KEY}
  46.     response = requests.get(url, headers=headers)
  47.     data = response.json()
  48.     if data["status"]["error_code"] == 0:
  49.         return float(data["data"][0]["price_usd"])
  50.     else:
  51.         print(f"Error fetching price for {coin_symbol}: {data['status']['error_message']}")
  52.         return None
  53.  
  54.  
  55. def main():
  56.     # Connect to the exchange
  57.     web3 = Web3(Web3.HTTPProvider(WEB3_PROVIDER_URL))
  58.  
  59.     # Create contract object
  60.     router_contract = web3.eth.contract(address=PANCAKESWAP_ROUTER_ADDRESS, abi=PANCAKESWAP_ROUTER_ABI)
  61.  
  62.     # Minimum spread amount (calculated based on percentage)
  63.     min_spread = MIN_SPREAD_PERCENT * 0.01  # Convert percentage to decimal
  64.  
  65.     while True:
  66.         # Get prices of currency pairs
  67.         weth_price = get_price("weth")
  68.         busd_price = get_price("busd")
  69.  
  70.         # Calculate price difference
  71.         weth_busd_spread = busd_price - weth_price
  72.  
  73.         # If price difference is greater than minimum spread, perform trade
  74.         if weth_busd_spread > min_spread:
  75.             # Amount to trade (adjustable)
  76.             amount = 100
  77.  
  78.             # Build transaction to buy WETH
  79.             swap_weth_tx = router_contract.functions.swapExactTokensForTokens(
  80.                 amount,
  81.                 BUSD_ADDRESS,
  82.                 WETH_ADDRESS,
  83.                 True,
  84.             ).build_Transaction()
  85.  
  86.             # Estimate gas cost for the transaction
  87.             gas_estimate = web3.eth.gas_estimate(swap_weth_tx)
  88.  
  89.             try:
  90.                 # Send transaction to buy WETH
  91.                 swap_weth_tx.send(gas=gas_estimate)
  92.  
  93.                 # Wait for transaction confirmation
  94.                 tx_receipt = swap_weth_tx.wait_for_receipt()
  95.  
  96.                 # Check transaction status
  97.                 if tx_receipt.status != 1:
  98.                     print(f"Error: Transaction failed with status {tx_receipt.status}")
  99.                     continue
  100.  
  101.                 # Build transaction to sell BUSD (completed)
  102.                 swap_busd
  103.             # Get the amount of WETH acquired
  104.             amount_weth = tx_receipt.logs[0].args["amountOut"]
  105.  
  106.             # Build transaction to sell WETH
  107.             swap_busd_tx = router_contract.functions.swapExactTokensForTokens(
  108.                 amount_weth,
  109.                 WETH_ADDRESS,
  110.                 BUSD_ADDRESS,
  111.                 True,
  112.             ).build_transaction()
  113.  
  114.             # Estimate gas cost for the transaction
  115.             gas_estimate = web3.eth.gas_estimate(swap_busd_tx)
  116.  
  117.             # Send transaction to sell BUSD
  118.             swap_busd_tx.send(gas=gas_estimate)
  119.  
  120.             # Wait for transaction confirmation
  121.             tx_receipt = swap_busd_tx.wait_for_receipt()
  122.  
  123.             # Check transaction status
  124.             if tx_receipt.status != 1:
  125.                 print(f"Error: Transaction failed with status {tx_receipt.status}")
  126.                 continue
  127.  
  128.             # Calculate profit (if any)
  129.             profit = busd_price * tx_receipt.logs[0].args["amountOut"] - amount
  130.  
  131.             # Print trade results
  132.             print(f"Successfully traded WETH for BUSD!")
  133.             print(f"Amount of BUSD acquired: {tx_receipt.logs[0].args['amountOut']}")
  134.             print(f"Profit: {profit}")
  135.  
  136.         else:
  137.             print(f"Price difference is below minimum spread ({min_spread}). No trade performed.")
  138.  
  139.         # Wait for a few seconds before next iteration
  140.         time.sleep(5)
  141.  
  142.  
  143. if __name__ == "__main__":
  144.     main()
  145.