I used your code: import time from binance.client import Client from binance.enums…
- User
I used your 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 import ccxt
date = dt.datetime.now().strftime("%m/%d/%Y %H:%M:%S") print(date)
t = int(time.time()*1000 - 1000) url = f"https://api.binance.com/api/v1/time?timestamp={t}" 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 = 100 max_trade_quantity_percentage = 1
client = Client(API_KEY, API_SECRET)
binance_futures = ccxt.binance({ 'apiKey': '', 'secret': '', 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True } }) balance = binance_futures.fetch_balance()
def get_klines(symbol, interval, lookback): url = "https://fapi.binance.com/fapi/v1/klines" start_time = (dt.datetime.now() - dt.timedelta(minutes=lookback)) end_time = dt.datetime.now() query_params = f"?symbol={symbol}&interval={interval}&startTime={start_time}&endTime={end_time}" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36' } try: response = requests.get(url + query_params, headers=headers) response.raise_for_status() data = response.json() if not data: # if data is empty, return None print('No data found for the given timeframe and symbol') return None ohlc = [] for d in data: timestamp = dt.datetime.fromtimestamp(d[0]/1000).strftime('%Y-%m-%d %H:%M:%S') ohlc.append({ 'Open time': timestamp, 'Open': float(d[1]), 'High': float(d[2]), 'Low': float(d[3]), 'Close': float(d[4]), 'Volume': float(d[5]) }) df = pd.DataFrame(ohlc) df.set_index('Open time', inplace=True) return df except requests.exceptions.RequestException as e: print(f'Error in get_klines: {e}') return None df = get_klines('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 ""df = get_klines('BTCUSDT', '1m', 44640) def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): max_trade_quantity = None account_balance = binance_futures.fetch_balance() usdt_balance = 0 for b in account_balance['assets']: if b['asset'] == 'USDT': usdt_balance = float(b['balance']) max_trade_quantity = usdt_balance * max_trade_quantity_percentage/100
# Close long position if signal is opposite long_position = None short_position = None # Get current positions positions = binance_futures.fapiPrivateGetPositionRisk() for p in positions: if p['symbol'] == symbol and p['positionSide'] == 'LONG': long_position = p elif p['symbol'] == symbol and p['positionSide'] == 'SHORT': short_position = p # Close positions if long_position is not None: binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL', type='MARKET', quantity=long_position['positionAmt'], positionSide='LONG', reduceOnly=True) time.sleep(1) if short_position is not None: binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='BUY', type='MARKET', quantity=short_position['positionAmt'], positionSide='SHORT', reduceOnly=True) time.sleep(1) print("Both positions closed.") # Place new order quantity = max_trade_quantity if signal == 'buy': position_side = 'BOTH' opposite_position = short_position elif signal == 'sell': position_side = 'BOTH' opposite_position = long_position else: print("Invalid signal. No order placed.") return if opposite_position is not None: quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) price = None if signal == 'buy': order_type = 'TAKE_PROFIT_MARKET' price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price'] elif signal == 'sell': order_type = 'STOP_MARKET' price = binance_futures.fapiPublicGetTickerPrice({'symbol': symbol})['price'] stop_price = price * (1 + STOP_LOSS_PERCENTAGE / 100) order = binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='BUY' if signal == 'buy' else 'SELL', type=order_type, quantity=quantity, price=price, stopPrice=stop_price, reduceOnly=False, positionSide=position_side, timeInForce='GTC', leverage=str(leverage)) order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price if signal == 'buy': take_profit_price = price * (1 + TAKE_PROFIT_PERCENTAGE / 100) stop_loss_price = price * (1 - STOP_LOSS_PERCENTAGE / 100) elif signal == 'sell': take_profit_price = price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_price = price * (1 + STOP_LOSS_PERCENTAGE / 100) # Set stop loss and take profit orders binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='TAKE_PROFIT_MARKET', quantity=quantity, price=take_profit_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None) time.sleep(1) binance_futures.fapiPrivatePOSTOrder(symbol=symbol, side='SELL' if signal == 'buy' else 'BUY', type='STOP_MARKET', quantity=quantity, price=stop_loss_price, reduceOnly=True, positionSide=position_side, timeInForce='GTC', stopPrice=None) # Print order creation confirmation messages print(f"Placed stop loss order with stop loss price {stop_loss_price}") print(f"Placed take profit order with take profit price {take_profit_price}") time.sleep(1)while True: df = get_klines('BTCUSDT', '1m', 44640) if df is not None: signal = signal_generator(df) if signal: print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} :{signal}") order_execution('BTCUSDT', signal, MAX_TRADE_QUANTITY_PERCENTAGE, leverage) time.sleep(1) But fapiPrivatePOSTOrder is undefined
- Assistant
It seems that the ccxt library might not be properly installed or imported. Make sure that you have installed the latest version of ccxt library and imported it correctly in your code. You can try adding the import statement for ccxt at the beginning of your code as follows:
import ccxt binance_futures = ccxt.binance({ 'apiKey': '', 'secret': '', 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True } })Also, make sure that you have provided the correct API keys for your Binance account. Double-check your keys and try again.
- User
But I did it
- Assistant
If you have imported the ccxt library and provided the correct API keys, then it's possible that the issue might be with the API endpoint. Please verify that you are using the correct URL for the API endpoint.
You can also try checking the official documentation for the Binance API to see if there have been any changes made to the API endpoint or the parameters used in the API call.
If the issue persists, you can try reaching out to the Binance support team for further assistance.
- User
How I can find fapiPrivatePOSTOrder ?
- Assistant
fapiPrivatePOSTOrderis a method in the Binance Futures API that allows you to place an order on Binance futures. To use this method, you need to have the proper API key and secret for your Binance account.Here is an example usage of the
fapiPrivatePOSTOrdermethod using the ccxt Python library:import ccxt binance_futures = ccxt.binance({ 'apiKey': 'YOUR_API_KEY', 'secret': 'YOUR_API_SECRET', 'enableRateLimit': True, # enable rate limitation 'options': { 'defaultType': 'future', 'adjustForTimeDifference': True } }) order = binance_futures.fapiPrivatePOSTOrder( symbol='BTCUSDT', # symbol you want to trade side='BUY', # 'BUY' or 'SELL' type='LIMIT', # 'LIMIT', 'MARKET', 'STOP', or 'TAKE_PROFIT' quantity=0.01, # quantity of the order price=50000, # price of the order reduceOnly=False, # reduceOnly flag timeInForce='GTC', # time in force of the order, 'GTC' (Good Til Canceled) by default positionSide='BOTH', # 'LONG', 'SHORT', or 'BOTH' stopPrice=None, # stop price for STOP or TAKE_PROFIT order closePosition=None, # close position flag workingType=None, # working type of the order priceProtect=None, # price protection flag newClientOrderId=None, # client order ID recvWindow=None, # receive window timestamp=None # timestamp of the order ) print(order)In the example above, we are placing a Limit Buy Order on the BTCUSDT trading pair with quantity
0.01, price50000, andreduceOnly=False, which means that it will open a new position and not reduce any existing positions.You can modify these parameters to fit your trading strategy and use the
fapiPrivatePOSTOrdermethod to place orders on Binance Futures. Be sure to check the official Binance Futures API documentation for the full list of available parameters and their descriptions.