Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import time
- from datetime import datetime
- from cdp import CdpClient
- from config import API_CREDENTIALS
- import sys
- class SingleTradeBot:
- def __init__(self):
- print("\n" + "="*50)
- print("BTC Single Trade Executor")
- print("="*50 + "\n")
- self.client = self._initialize_client()
- self.target_btc_amount = 0.01387977
- def _initialize_client(self):
- """Initialize and verify API connection with corrected parameter names"""
- print("[1/5] Initializing API connection...")
- try:
- client = CdpClient(
- api_key_id=API_CREDENTIALS['api_key_name'], # Changed from api_key_name
- api_secret_key=API_CREDENTIALS['api_secret'], # Changed from api_secret
- passphrase=API_CREDENTIALS['passphrase'],
- sandbox_mode=API_CREDENTIALS['sandbox_mode'] # Changed from sandbox
- )
- # Test connection
- client.ping()
- print("✓ API connection established")
- return client
- except Exception as e:
- self._exit_with_error(f"API connection failed: {str(e)}")
- def _exit_with_error(self, message):
- """Handle critical errors and exit gracefully"""
- print(f"\n! ERROR: {message}")
- print("Exiting...")
- sys.exit(1)
- def _log_step(self, step_number, message):
- """Log each step with clear numbering"""
- timestamp = datetime.now().strftime("%H:%M:%S")
- print(f"[{step_number}] [{timestamp}] {message}")
- def get_btc_price(self):
- """Get current BTC price"""
- self._log_step("2/5", "Fetching current BTC price...")
- try:
- ticker = self.client.evm_client.get_token_price("BTC")
- price = float(ticker["price"])
- print(f"✓ Current BTC price: ${price:,.2f}")
- return price
- except Exception as e:
- self._exit_with_error(f"Failed to get BTC price: {str(e)}")
- def execute_buy_order(self):
- """Execute the BTC buy order"""
- self._log_step("3/5", f"Preparing to buy {self.target_btc_amount:.8f} BTC...")
- btc_price = self.get_btc_price()
- usd_value = self.target_btc_amount * btc_price
- print(f"• USD equivalent: ${usd_value:,.2f}")
- print("• Verifying funds...")
- try:
- order_info = {
- "market": "BTC/USDT",
- "side": "buy",
- "amount": self.target_btc_amount,
- "order_type": "market"
- }
- self._log_step("4/5", "Executing buy order...")
- order = self.client.evm_client.place_order(**order_info)
- print("✓ Buy order executed successfully")
- print(f"• Purchased: {self.target_btc_amount:.8f} BTC")
- print(f"• At price: ${btc_price:,.2f}")
- print(f"• Total cost: ${usd_value:,.2f}")
- return order
- except Exception as e:
- self._exit_with_error(f"Buy order failed: {str(e)}")
- def verify_balance(self):
- """Verify the BTC balance after purchase"""
- self._log_step("5/5", "Verifying new BTC balance...")
- try:
- balance = self.client.evm_server_account.get_token_balance("BTC")
- btc_balance = float(balance["balance"])
- print(f"✓ Current BTC balance: {btc_balance:.8f}")
- if btc_balance < self.target_btc_amount * 0.99: # Allow 1% tolerance
- print("! Warning: Balance is less than expected purchase amount")
- except Exception as e:
- print(f"! Balance check failed: {str(e)} (but purchase completed)")
- def run(self):
- """Execute the single trade operation"""
- self.execute_buy_order()
- self.verify_balance()
- print("\n" + "="*50)
- print("Trade completed successfully")
- print("="*50 + "\n")
- if __name__ == "__main__":
- bot = SingleTradeBot()
- bot.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement