定义交易所和交易对
exchange = ccxt.binance({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_SECRET', }) symbol = 'ETH/USDT'
定义获取历史K线数据的函数
def fetch_ohlcv(symbol, timeframe, limit): ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=limit) df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') df.set_index('timestamp', inplace=True) return} df
定义交易策略
def strategy(df): if df.iloc[-1]['close'] > df.iloc[-2]['close']: return 'buy' elif df.iloc[-1]['close'] < df.iloc[-2]['close']: return 'sell' else: return 'hold'
定义交易函数
def trade(side, amount): if side == 'buy': order = exchange.create_market_buy_order(symbol, amount) elif side == 'sell': order = exchange.create_market_sell_order(symbol, amount) else: return return order