如何实现仅在新K线开盘时触发交易及相关Python编码问题求助
Hey there, let's tackle your three main issues one by one with practical, actionable fixes:
1. Fixing the "'DataFrame' object has no attribute 'Time'" Error
Looking at your getdata function, you’re setting the Time column as the DataFrame index with frame.set_index('Time', inplace=True). That means Time is no longer a regular column—you can’t access it with df.Time anymore.
If you want to keep Time as a column while still using it as the index, adjust your function like this:
def getdata(symbol): frame = pd.DataFrame(client.get_historical_klines(symbol, '1m', '100 minutes UTC')) frame = frame.iloc[:,:6] frame.columns = ['Time', 'Open', 'High', 'Low', 'Close', 'Price'] # Convert timestamp to datetime first frame['Time'] = pd.to_datetime(frame['Time'], unit='ms') # Keep Time as a column while setting it as index frame.set_index('Time', inplace=True, drop=False) frame.Price = frame.Price.astype(float) frame = frame.astype(float) return frame
Or if you just need to access time values, use the index directly:
# Get the latest kline's timestamp latest_kline_time = df.index[-1]
2. Tracking Kline Time to Limit Trades to New Candles
To only execute trades when a new 1-minute Kline arrives, you need to track the last processed Kline time. Here’s how to implement this logic:
First, initialize a variable outside your main loop to store the last handled Kline time:
last_processed_time = None
Then, in your data fetching/trading loop:
import time while True: df = getdata('BTCBUSD') # Grab the timestamp of the most recent Kline current_latest_time = df.index[-1] # Check if this is a brand new Kline we haven't processed yet if current_latest_time != last_processed_time: print(f"New 1m Kline detected at {current_latest_time}") # Run your trading logic here # (See section 3 for using the Open price instead of real-time) execute_trade_strategy(df) # Update the last processed time to avoid re-running on the same Kline last_processed_time = current_latest_time # Add a delay to respect Binance API rate limits (adjust as needed) time.sleep(30)
This ensures your trading code only triggers when a fresh Kline is available.
3. Trading at the Kline's Open Price Instead of Real-Time Price
Instead of fetching live market prices, pull the Open value directly from the latest Kline in your DataFrame:
def execute_trade_strategy(df): # Get the open price of the most recent Kline entry_price = df['Open'].iloc[-1] print(f"Placing order at Kline open price: {entry_price}") # Use this entry_price in your Binance order API call # Example: client.create_order(..., price=str(entry_price), ...)
Replace your real-time price fetch with this value to ensure you’re using the Kline’s opening price for trades.
Quick Pro Tips:
- Wrap your API calls in
try/exceptblocks to handle network glitches or Binance error responses. - Adjust the loop delay based on Binance’s rate limits—avoid spamming
get_historical_klinestoo frequently.
内容的提问来源于stack exchange,提问作者B0R

