import time from binance.client import Client from binance.enums import * from…
- User
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): try: 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 except Exception as e: print(f"Error getting minute data: {str(e)}“) return None
df = getminutedata(‘BTCUSDT’, ‘1m’, ‘44640’)
def signal_generator(df): try: 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 (openprevious_close and close>previous_open and open<=previous_close): return ‘buy’
No clear pattern
else: return ‘’ except Exception as e: print(f"Error generating signal: {str(e)}”) return ‘’
def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): try: max_trade_quantity = None 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
Close long position if signal is opposite
long_position = None short_position = None positions = client.futures_position_information(symbol=symbol) for p in positions: if p[‘positionSide’] == ‘LONG’: long_position = p elif p[‘positionSide’] == ‘SHORT’: short_position = p if long_position is not None and short_position is not None: print(“Multiple positions found. Closing both positions.”) client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position[‘positionAmt’], reduceOnly=True ) time.sleep(1) client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position[‘positionAmt’], reduceOnly=True ) print(“Both positions closed.”) return
- Assistant
As an AI language model, I am not able to run code, but I checked the syntax and it seems to be correct. However, please note that using a trading bot can be risky and may lead to financial losses. Make sure to thoroughly understand the code and the trading strategy before using it. Additionally, ensure that you have proper risk management measures in place to avoid significant financial losses.
- User
I used your code , but I getting ERROR: Error getting minute data: APIError(code=-1100): Illegal characters found in parameter 'symbol'; legal range is '^[A-Z0-9-_.]{1,20}$'. What I need to do ?
- Assistant
This error message indicates that the
symbolparameter provided to the Binance API call contains illegal characters. Thesymbolparameter should only contain letters (uppercase), numbers, hyphens, underscores, or periods (dot) and should be within a length of 1-20.To fix this issue, make sure that the
symbolvariable in your code complies with the above requirements. If you have hardcoded thesymbolparameter in the function call, ensure that the value provided resembles a valid market pair for Binance.For example, to get minute data for the BTCUSDT pair, the
symbolparameter should beBTCUSDTwithout quotes. - User
How I can set time.sleep to 1 second ?
- Assistant
To set the
time.sleep()function to 1 second, simply pass the argument1inside the parentheses like this:time.sleep(1)This will cause the code to pause for 1 second before proceeding to the next line of code.
- User
I sued your code and I catched the signal to buy , but order doesn't eaxaecuted The signal time is: 2023-05-28 15:48:25 :buy Error executing order: 'NoneType' object is not subscriptable, what I need to change ?
- Assistant
- User
I uesd your new execution code, but I getting The signal time is: 2023-05-28 16:13:49 :buy Error executing order: APIError(code=-1102): Mandatory parameter 'positionSide' was not sent, was empty/null, or malformed. What I need to change ?
- Assistant