Advertisement
Dieton

coinbase sandbox buy crypto test 1.py

May 21st, 2025 (edited)
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.08 KB | Cryptocurrency | 0 0
  1. import time
  2. from datetime import datetime
  3. from cdp import CdpClient
  4. from config import API_CREDENTIALS
  5. import sys
  6.  
  7. class SingleTradeBot:
  8.     def __init__(self):
  9.         print("\n" + "="*50)
  10.         print("BTC Single Trade Executor")
  11.         print("="*50 + "\n")
  12.        
  13.         self.client = self._initialize_client()
  14.         self.target_btc_amount = 0.01387977
  15.        
  16.     def _initialize_client(self):
  17.         """Initialize and verify API connection with corrected parameter names"""
  18.         print("[1/5] Initializing API connection...")
  19.         try:
  20.             client = CdpClient(
  21.                 api_key_id=API_CREDENTIALS['api_key_name'],  # Changed from api_key_name
  22.                 api_secret_key=API_CREDENTIALS['api_secret'],  # Changed from api_secret
  23.                 passphrase=API_CREDENTIALS['passphrase'],
  24.                 sandbox_mode=API_CREDENTIALS['sandbox_mode']  # Changed from sandbox
  25.             )
  26.             # Test connection
  27.             client.ping()
  28.             print("✓ API connection established")
  29.             return client
  30.         except Exception as e:
  31.             self._exit_with_error(f"API connection failed: {str(e)}")
  32.  
  33.     def _exit_with_error(self, message):
  34.         """Handle critical errors and exit gracefully"""
  35.         print(f"\n! ERROR: {message}")
  36.         print("Exiting...")
  37.         sys.exit(1)
  38.  
  39.     def _log_step(self, step_number, message):
  40.         """Log each step with clear numbering"""
  41.         timestamp = datetime.now().strftime("%H:%M:%S")
  42.         print(f"[{step_number}] [{timestamp}] {message}")
  43.  
  44.     def get_btc_price(self):
  45.         """Get current BTC price"""
  46.         self._log_step("2/5", "Fetching current BTC price...")
  47.         try:
  48.             ticker = self.client.evm_client.get_token_price("BTC")
  49.             price = float(ticker["price"])
  50.             print(f"✓ Current BTC price: ${price:,.2f}")
  51.             return price
  52.         except Exception as e:
  53.             self._exit_with_error(f"Failed to get BTC price: {str(e)}")
  54.  
  55.     def execute_buy_order(self):
  56.         """Execute the BTC buy order"""
  57.         self._log_step("3/5", f"Preparing to buy {self.target_btc_amount:.8f} BTC...")
  58.        
  59.         btc_price = self.get_btc_price()
  60.         usd_value = self.target_btc_amount * btc_price
  61.        
  62.         print(f"• USD equivalent: ${usd_value:,.2f}")
  63.         print("• Verifying funds...")
  64.        
  65.         try:
  66.             order_info = {
  67.                 "market": "BTC/USDT",
  68.                 "side": "buy",
  69.                 "amount": self.target_btc_amount,
  70.                 "order_type": "market"
  71.             }
  72.            
  73.             self._log_step("4/5", "Executing buy order...")
  74.             order = self.client.evm_client.place_order(**order_info)
  75.            
  76.             print("✓ Buy order executed successfully")
  77.             print(f"• Purchased: {self.target_btc_amount:.8f} BTC")
  78.             print(f"• At price: ${btc_price:,.2f}")
  79.             print(f"• Total cost: ${usd_value:,.2f}")
  80.            
  81.             return order
  82.         except Exception as e:
  83.             self._exit_with_error(f"Buy order failed: {str(e)}")
  84.  
  85.     def verify_balance(self):
  86.         """Verify the BTC balance after purchase"""
  87.         self._log_step("5/5", "Verifying new BTC balance...")
  88.         try:
  89.             balance = self.client.evm_server_account.get_token_balance("BTC")
  90.             btc_balance = float(balance["balance"])
  91.             print(f"✓ Current BTC balance: {btc_balance:.8f}")
  92.            
  93.             if btc_balance < self.target_btc_amount * 0.99:  # Allow 1% tolerance
  94.                 print("! Warning: Balance is less than expected purchase amount")
  95.         except Exception as e:
  96.             print(f"! Balance check failed: {str(e)} (but purchase completed)")
  97.  
  98.     def run(self):
  99.         """Execute the single trade operation"""
  100.         self.execute_buy_order()
  101.         self.verify_balance()
  102.        
  103.         print("\n" + "="*50)
  104.         print("Trade completed successfully")
  105.         print("="*50 + "\n")
  106.  
  107. if __name__ == "__main__":
  108.     bot = SingleTradeBot()
  109.     bot.run()
Tags: coinbase
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement