I used your updated code: import time from binance.client import Client from…
- User
I used your updated 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 ''def order_execution(symbol, signal, max_trade_quantity_percentage, leverage): 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.") if long_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=long_position['positionAmt'], reduceOnly=True ) time.sleep(1) if short_position is not None: client.futures_create_order( symbol=symbol, side=SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=short_position['positionAmt'], reduceOnly=True ) time.sleep(1) print("Both positions closed.") if signal == 'buy': position_side = POSITION_SIDE_LONG opposite_position = short_position elif signal == 'sell': position_side = POSITION_SIDE_SHORT opposite_position = long_position else: print("Invalid signal. No order placed.") order_quantity = 0 if opposite_position is not None: order_quantity = min(max_trade_quantity, abs(float(opposite_position['positionAmt']))) if opposite_position is not None and opposite_position['positionSide'] != position_side: print("Opposite position found. Closing position before placing order.") client.futures_create_order( symbol=symbol, side=SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=True, positionSide=opposite_position['positionSide'] ) time.sleep(1) opposite_side = None if opposite_position is not None: opposite_side = (SIDE_SELL if opposite_position['positionSide'] == POSITION_SIDE_LONG else SIDE_BUY) else: print("No opposite position found.") order = client.futures_create_order( symbol=symbol, side=SIDE_BUY if signal == 'buy' else SIDE_SELL, type=ORDER_TYPE_MARKET, quantity=order_quantity, reduceOnly=False, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side, leverage=leverage ) if order is None: print("Order not placed successfully. Skipping setting stop loss and take profit orders.") order_id = order['orderId'] print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") time.sleep(1) # Set stop loss and take profit orders # Get the order details to determine the order price order_info = client.futures_get_order(symbol=symbol, orderId=order_id) if order_info is None: print("Error getting order information. Skipping setting stop loss and take profit orders.") else: order_price = float(order_info['avgPrice']) # Set stop loss and take profit orders stop_loss_price = order_price * (1 + STOP_LOSS_PERCENTAGE / 100) if signal == 'sell' else order_price * (1 - STOP_LOSS_PERCENTAGE / 100) take_profit_price = order_price * (1 + TAKE_PROFIT_PERCENTAGE / 100) if signal == 'buy' else order_price * (1 - TAKE_PROFIT_PERCENTAGE / 100) stop_loss_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_STOP_LOSS, quantity=order_quantity, stopPrice=stop_loss_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side ) take_profit_order = client.futures_create_order( symbol=symbol, side=SIDE_SELL if signal == 'buy' else SIDE_BUY, type=ORDER_TYPE_LIMIT, quantity=order_quantity, price=take_profit_price, reduceOnly=True, timeInForce=TIME_IN_FORCE_GTC, positionSide=position_side ) # Print order creation confirmation messages print(f"Placed {signal} order with order ID {order_id} and quantity {order_quantity}") 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) - Assistant
- User
I used your updated code, but I getting ERROR: The signal time is: 2023-05-29 19:26:00 :buy Both positions closed. Traceback (most recent call last): File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 201, in order_execution('BTCUSDT', current_signal, max_trade_quantity_percentage, leverage) File "c:\Users\Alan.vscode\jew_bot\jew_bot\jew_bot.py", line 141, in order_execution order = client.futures_create_order( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\client.py", line 6209, in futures_create_order return self._request_futures_api('post', 'order', True, data=params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\client.py", line 382, in _request_futures_api
return self._request(method, uri, signed, True, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\client.py", line 358, in _request return self._handle_response(self.response) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\Alan\AppData\Roaming\Python\Python311\site-packages\binance\client.py", line 367, in _handle_response raise BinanceAPIException(response, response.status_code, response.text) binance.exceptions.BinanceAPIException: APIError(code=-1102): Mandatory parameter 'positionSide' was not sent, was empty/null, or malformed. - Assistant
Sorry about that error. It seems like the
positionSideparameter was not sent to the API. You can try adding thepositionSideparameter when creating the stop loss and take profit orders, similar to how it was done when creating the main order, as shown below: