I used this code: import time from binance.client import Client from binance.enums…
- User
I used this code: import time from binance.client import Client from binance.enums import * from binance.exceptions import BinanceAPIException import pandas as pd import requests import json import numpy as np import pytz import datetime as dt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date)
url = "https://api.binance.com/api/v1/time" t = time.time()*1000 r = requests.get(url) result = json.loads(r.content)
API keys and other configuration
API_KEY = '' API_SECRET = ''
client = Client(API_KEY, API_SECRET)
STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 MAX_TRADE_QUANTITY_PERCENTAGE = 100 POSITION_SIDE_SHORT = 'SELL' POSITION_SIDE_LONG = 'BUY' symbol = 'BTCUSDT' quantity = 1 order_type = 'MARKET' leverage = 125 max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
def getminutedata(symbol, interval, lookback): frame = pd.DataFrame(client.get_historical_klines(symbol, interval, lookback+'min ago UTC')) frame = frame.iloc[:60,:6] frame.columns = ['Time','Open','High','Low','Close','Volume'] frame = frame.set_index('Time') today = dt.date.today() frame.index = pd.to_datetime(frame.index, unit='ms').tz_localize('UTC').tz_convert('Etc/GMT+3').strftime(f"{today} %H:%M:%S") frame = frame.astype(float) return frame
df = getminutedata('BTCUSDT', '1m', '44640')
def signal_generator(df): open = df.Open.iloc[-1] close = df.Close.iloc[-1] previous_open = df.Open.iloc[-2] previous_close = df.Close.iloc[-2]
#Bearish pattern if (open>close and previous_open<previous_close and close<previous_open and open>=previous_close): return 'sell' #Bullish pattern elif (open<close and previous_open>previous_close and close>previous_open and open<=previous_close): return 'buy' #No clear pattern else: return ''signal = ["" for i in range(len(df))] # initialize signal as a list of empty strings for i in range(1, len(df)): df_temp = df[i-1:i+1] signal[i] = signal_generator(df_temp) df["signal"] = signal
def order_execution(symbol, signal, max_trade_quantity_percentage): max_trade_quantity_percentage = 10 buy = signal == "buy" sell = signal == "sell" signal = buy or sell symbol = 'BTCUSDT'
account_balance = client.futures_account_balance() usdt_balance = float([x['balance'] for x in account_balance if x['asset'] == 'USDT'][0]) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100 STOP_LOSS_PERCENTAGE = -50 TAKE_PROFIT_PERCENTAGE = 100 POSITION_SIDE_SHORT = SIDE_SELL POSITION_SIDE_LONG = SIDE_BUY long_position = POSITION_SIDE_LONG short_position = POSITION_SIDE_SHORT symbol = 'BTCUSDT' positions = client.futures_position_information(symbol=symbol) order_quantity = 0 # initialize order_quantity with a default value of 0 long_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'LONG'), None) if long_position: # Close long position if signal is opposite if signal == "sell": order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) print(f"Closed long position with order ID {order['orderId']}") time.sleep(1) else: if long_position is not None: order_quantity = min(max_trade_quantity, abs(float(long_position['positionAmt']))) else: print("No long position found") order = client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT, leverage=leverage ) print(f"Placed short order with order ID {order['orderId']} and quantity {order_quantity})") time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order['avgPrice'] * (1 + STOP_LOSS_PERCENTAGE / 100) take_profit_price = order['avgPrice'] * (1 + TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_SHORT ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}") time.sleep(1) order_quantity = 0 # initialize order_quantity with a default value of 0 short_position = next((p for p in positions if p['symbol'] == symbol and p['positionSide'] == 'SHORT'), None) if short_position: # Close short position if signal is opposite if signal == "buy": order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) print(f"Closed short position with order ID {order['orderId']}") time.sleep(1) else: if short_position is not None: order_quantity = min(max_trade_quantity, float(short_position['maxNotionalValue']) / leverage) else: print("No short position found") order = client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG, leverage=leverage ) print(f"Placed long order with order ID {order['orderId']} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders stop_loss_price = order['avgPrice'] * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order['avgPrice'] * (1 - TAKE_PROFIT_PERCENTAGE / 100) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=POSITION_SIDE_LONG ) print(f"Set stop loss at {stop_loss_price} and take profit at {take_profit_price}") time.sleep(1) - Assistant
This code is a trading bot that uses the Binance API to analyze market data and execute trades based on a signal generated by a simple technical analysis algorithm. The code imports several external libraries and modules, including pandas, numpy, requests, and datetime.
The main function of the code is divided into three parts: getting minute data for a given symbol using the Binance API, generating a trading signal based on the minute data, and executing a buy or sell order based on the signal.
The trading signal is generated by comparing the current candlestick pattern to the previous, and looking for bullish or bearish patterns. If a signal is found, the bot executes a market order for a predetermined percentage of the available balance for that asset.
The code appears designed to be run continuously, as it includes an infinite while loop that runs the signal generation and order execution functions repeatedly with a delay of one second between iterations.
It's important to note that this code should only be used for educational purposes and not for actual trading without proper testing and modifications. The strategy used may not be effective in all market conditions and could result in significant losses.