New Text Document
New Text Document
# Configure logging
logging.basicConfig(filename='trading_log.txt', level=logging.INFO, format='%
(asctime)s - %(message)s')
# Parameters
symbol = 'BTCUSDT'
interval = '1m' # 1-minute timeframe for Futures
sma_period = 50 # Period for EMA
stoch_rsi_period = 14 # Period for Stochastic RSI
atr_period = 14 # ATR period
atr_multiplier = 2 # Multiplier for ATR to set TP and SL
def calculate_indicators(df):
"""Calculate EMA, Stochastic RSI, and ATR."""
print("Calculating indicators (EMA50, Stochastic RSI, ATR)...")
# Stochastic RSI
df['Stoch_RSI'] = ta.momentum.stochrsi(df['close'], window=stoch_rsi_period)
df['Stoch_RSI_K'] = ta.momentum.stochrsi_k(df['close'],
window=stoch_rsi_period)
df['Stoch_RSI_D'] = ta.momentum.stochrsi_d(df['close'],
window=stoch_rsi_period)
# ATR
df['ATR'] = ta.volatility.average_true_range(df['high'], df['low'],
df['close'], window=atr_period)
return df
def check_signals(df):
"""Generate buy/sell signals based on indicators."""
last_row = df.iloc[-1]
def get_symbol_info(symbol):
"""Fetch the symbol's precision and quantity limits from Binance exchange
info."""
exchange_info = client.exchange_info()
for s in exchange_info['symbols']:
if s['symbol'] == symbol:
return {
'pricePrecision': s['pricePrecision'],
'quantityPrecision': s['quantityPrecision'],
'minQty': float(s['filters'][2]['minQty']),
'stepSize': float(s['filters'][2]['stepSize']),
}
return None
def get_symbol_tick_size(symbol):
"""Fetch tick size for the trading symbol in Binance Futures."""
try:
exchange_info = client.exchange_info()
for s in exchange_info['symbols']:
if s['symbol'] == symbol:
for f in s['filters']:
if f['filterType'] == 'PRICE_FILTER':
return float(f['tickSize'])
return None
except Exception as e:
logging.error(f"Error fetching tick size: {e}")
return None
def round_price_to_tick_size(price, tick_size):
"""Round the price to the nearest tick size."""
return round(price / tick_size) * tick_size
if position_open:
print(f"Position already open ({position_side}). No new trades will be
executed until the current position is closed.")
return
try:
# Fetch symbol precision and limits
symbol_info = get_symbol_info(symbol)
price_precision = symbol_info['pricePrecision']
quantity_precision = symbol_info['quantityPrecision']
tick_size = get_symbol_tick_size(symbol)
except Exception as e:
logging.error(f"Error executing trade: {e}")
print(f"Error executing trade: {e}")
def close_position():
"""Check and close an open position if it hits take-profit or stop-loss."""
global position_open, position_side
if not position_open:
print("No position open to close.")
return
try:
# Fetch the position details and check if it needs to be closed
positions = client.get_position_risk(symbol=symbol)
position_amt = float(positions[0]['positionAmt'])
if position_amt == 0:
print("Position has already been closed.")
logging.info("Position has already been closed.")
position_open = False
position_side = None
return
position_open = False
position_side = None
except Exception as e:
logging.error(f"Error closing position: {e}")
print(f"Error closing position: {e}")
def run_bot():
"""Main function to run the bot in a loop."""
while True:
try:
# Fetch and process market data
df = get_historical_klines(symbol, interval)
df = calculate_indicators(df)
except Exception as e:
logging.error(f"Error in bot loop: {e}")
print(f"Error in bot loop: {e}")
time.sleep(60)