09/08/2025
# buy_and_withdraw_eth.py
import ccxt
import time
import decimal
# ====== CONFIG ======
API_KEY = 'YOUR_BINANCE_API_KEY'
API_SECRET = 'YOUR_BINANCE_SECRET'
EXCHANGE_ID = 'binance' # change to 'coinbase' etc. supported by ccxt
QUOTE_SYMBOL = 'USDT' # currency you'll use to buy ETH (USDT, USD, AUD)
SPEND_QUOTE_AMOUNT = 100 # how much quote-currency to spend to buy ETH (e.g., 100 USDT)
TARGET_WALLET = '0x5A35f21F522cDe63e750752C8C32aa5F74B8279F'
NETWORK = 'ERC20' # network param, change if your exchange supports other networks
# ======================
def main():
exchange_class = getattr(ccxt, EXCHANGE_ID)
exchange = exchange_class({
'apiKey': API_KEY,
'secret': API_SECRET,
'enableRateLimit': True,
})
exchange.load_markets()
symbol = 'ETH/' + QUOTE_SYMBOL
# 1) fetch ticker price
ticker = exchange.fetch_ticker(symbol)
price = decimal.Decimal(str(ticker['last']))
print(f"Market price {symbol}: {price}")
# 2) compute amount of ETH to buy for SPEND_QUOTE_AMOUNT (market buy)
spend = decimal.Decimal(str(SPEND_QUOTE_AMOUNT))
eth_amount = (spend / price).quantize(decimal.Decimal('0.00000001')) # 8+ precision
print(f"Will buy approx {eth_amount} ETH for {spend} {QUOTE_SYMBOL}")
# 3) create market buy order (some exchanges need amount in base asset)
try:
order = exchange.create_market_buy_order(symbol, float(eth_amount))
print("Buy order placed:", order)
except Exception as e:
print("Buy order failed:", e)
return
# small wait to let exchange settle / update balances
time.sleep(5)
# 4) fetch available ETH balance
balance = exchange.fetch_balance()
eth_free = balance.get('ETH', {}).get('free') or balance.get('eth', {}).get('free') or 0
print("ETH free balance:", eth_free)
withdraw_amount = float(eth_free)
if withdraw_amount