0% found this document useful (0 votes)
27 views5 pages

New Text Document

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views5 pages

New Text Document

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

import logging

from binance.um_futures import UMFutures


import ta
import pandas as pd
import time

# Configure logging
logging.basicConfig(filename='trading_log.txt', level=logging.INFO, format='%
(asctime)s - %(message)s')

# Binance API credentials


api_key = 'BgiLfMw4ETRiUN0NDtHIaAj1YnsUzZZoajTbqehuobU8yb44bhyuQdsFB0EUCgFT'
api_secret = 'WKvayvC98pCjcFM24EU3l1t7oAIDehAOv02c9k8yY5SQRV5ok60Q3faBVZT3RflX'

# Initialize Binance Futures client


client = UMFutures(api_key, api_secret)

# 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

# Track position state


position_open = False
position_side = None # 'buy' or 'sell'

def get_historical_klines(symbol, interval, limit=500):


"""Fetch historical candlestick data."""
print(f"Fetching historical data for {symbol} on {interval} interval...")
klines = client.klines(symbol=symbol, interval=interval, limit=limit)
df = pd.DataFrame(klines, columns=['timestamp', 'open', 'high', 'low', 'close',
'volume', 'close_time', 'quote_asset_volume', 'num_trades',
'taker_buy_base_asset_volume', 'taker_buy_quote_asset_volume', 'ignore'])
df['open'] = pd.to_numeric(df['open'])
df['high'] = pd.to_numeric(df['high'])
df['low'] = pd.to_numeric(df['low'])
df['close'] = pd.to_numeric(df['close'])
return df

def calculate_indicators(df):
"""Calculate EMA, Stochastic RSI, and ATR."""
print("Calculating indicators (EMA50, Stochastic RSI, ATR)...")

# Calculate EMA instead of SMA


df['EMA50'] = ta.trend.ema_indicator(df['close'], window=sma_period)

# 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]

print(f"Checking signals for the latest data: Close: {last_row['close']},


EMA50: {last_row['EMA50']}, Stoch RSI K: {last_row['Stoch_RSI_K']}, Stoch RSI D:
{last_row['Stoch_RSI_D']}")

# Buy signal: Stoch RSI K crosses above D, price above EMA50


if last_row['close'] > last_row['EMA50'] and last_row['Stoch_RSI_K'] < 20 and
last_row['Stoch_RSI_K'] > last_row['Stoch_RSI_D']:
print("Buy signal detected!")
return 'buy'

# Sell signal: Stoch RSI K crosses below D, price below EMA50


if last_row['close'] < last_row['EMA50'] and last_row['Stoch_RSI_K'] > 80 and
last_row['Stoch_RSI_K'] < last_row['Stoch_RSI_D']:
print("Sell signal detected!")
return 'sell'

print("No trade signal detected.")


return None

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 round_price_and_quantity(price, quantity, price_precision, quantity_precision):


"""Round price and quantity according to the precision rules."""
rounded_price = round(price, price_precision)
rounded_quantity = round(quantity, quantity_precision)
return rounded_price, rounded_quantity

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

def execute_trade(signal, df):


"""Execute a trade on Binance Futures and set stop-loss and take-profit based
on ATR."""
global position_open, position_side

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)

# Fetch current price


price = float(client.ticker_price(symbol=symbol)['price'])
quantity = 0.002 # Example position size

# Round price and quantity based on precision


price, quantity = round_price_and_quantity(price, quantity,
price_precision, quantity_precision)

print(f"Preparing to execute {signal} trade: Price: {price}, Quantity:


{quantity}")

# Calculate ATR-based stop-loss and take-profit


atr_value = df.iloc[-1]['ATR']
stop_loss = price - atr_multiplier * atr_value if signal == 'buy' else
price + atr_multiplier * atr_value
take_profit = price + atr_multiplier * atr_value if signal == 'buy' else
price - atr_multiplier * atr_value

# Round stop-loss and take-profit prices to the nearest tick size


stop_loss = round_price_to_tick_size(stop_loss, tick_size)
take_profit = round_price_to_tick_size(take_profit, tick_size)

# Place buy or sell order


if signal == 'buy':
order = client.new_order(symbol=symbol, side='BUY', type='MARKET',
quantity=quantity)
position_side = 'buy'
elif signal == 'sell':
order = client.new_order(symbol=symbol, side='SELL', type='MARKET',
quantity=quantity)
position_side = 'sell'

position_open = True # Mark that a position is now open


print(f"{signal.capitalize()} order executed at {price}. Stop-loss at
{stop_loss}, take-profit at {take_profit}.")
logging.info(f"{signal.capitalize()} order executed at {price}. Stop-loss
at {stop_loss}, take-profit at {take_profit}.")
# Manual stop-loss and take-profit placement
client.new_order(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY',
type='STOP_MARKET', stopPrice=stop_loss,
quantity=quantity)
client.new_order(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY',
type='LIMIT', price=take_profit, quantity=quantity,
timeInForce='GTC')

print(f"Take-profit at {take_profit}, Stop-loss at {stop_loss}.")


logging.info(f"Take-profit at {take_profit}, Stop-loss at {stop_loss}.")

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

print(f"Closing {position_side} position...")


order_side = 'SELL' if position_side == 'buy' else 'BUY'
client.new_order(symbol=symbol, side=order_side, type='MARKET',
quantity=abs(position_amt))
print(f"{position_side.capitalize()} position closed.")
logging.info(f"{position_side.capitalize()} position closed.")

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)

# Check for buy/sell signals


signal = check_signals(df)
if signal:
execute_trade(signal, df)

# Check if a position needs to be closed


close_position()

# Wait before the next iteration


time.sleep(60)

except Exception as e:
logging.error(f"Error in bot loop: {e}")
print(f"Error in bot loop: {e}")
time.sleep(60)

# Start the trading bot


run_bot()

You might also like