I have this code :
active_signal = None
orderId = None
clientOrderId = None
buy_entry_price = None
sell_entry_price = None
orderId = None
import binance
def calculate_percentage_difference_buy(entry_price, exit_price):
result = exit_price - entry_price
price_result = entry_price / 100
final_result = result / price_result
result = final_result * 40
return result
def calculate_percentage_difference_sell(sell_entry_price, sell_exit_price):
percentage_difference = sell_entry_price - sell_exit_price
price_result = sell_entry_price / 100 # price result = 1%
price_percent_difference = percentage_difference / price_result
result = price_percent_difference * 40
return result
while True:
if df is not None:
# Get balance function
balance = client.balance()
#Get USDT balance function
for asset in balance:
if asset['asset'] == 'USDT':
balance_usdt = float(asset['balance'])
balance_usdt_futures = balance_usdt * 40
code
Assistant
User
Will this code execut order ?
Assistant
I apologize for the confusion in my previous response. The code I provided was only a suggested modification to incorporate the execution of the cancel_order and close_order commands. However, in order to actually execute the orders, you will need to use the appropriate functions or methods provided by the binance library or API you are using.
Since I am not familiar with the specific library or API you are using, I cannot provide the exact code to execute the orders. You will need to refer to the documentation or examples provided by the library or API you are using to understand the correct syntax and usage for executing orders.
Please consult the documentation or resources provided by the binance library or API you are using to identify the specific functions or methods required to execute orders, and then incorporate those functions or methods into your code accordingly.
User
Comand to execute order: client.cancel_order(symbol=symbol, orderId=orderId, origClientOrderId=clientOrderId)
Assistant
To execute the client.cancel_order command and close an existing order, you can modify the code as follows:
python
User
Give me full code with order execution and cancel order
Assistant
User
Where is code which will get orderId and clientOrderId ?
Assistant
I apologize for the confusion. To obtain the orderId and clientOrderId after placing
#Constant
price_bch = mark_price
dollars = balance_usdt_futures
#Counting Balance : BCH price
bch_amount = dollars / price_bch
bch_amount_rounded = round(bch_amount, 2)
quantity = bch_amount_rounded / 2
signals = signal_generator(df)
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
if signals == ['buy'] or signals == ['sell']:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Price {mark_price} - Signals: {signals}")
if 'buy' in signals and active_signal != 'buy':
try:
buy_entry_price = mark_price
print(f"Buy Entry Price: {buy_entry_price}")
print(f"Long order executed!")
except binance.error.ClientError as e:
print(f"Error executing long order: ")
if sell_entry_price is not None and buy_entry_price is not None:
sell_exit_price = mark_price
difference_sell = calculate_percentage_difference_sell(sell_entry_price, sell_exit_price)
profit_sell = difference_sell
total_profit_sell = profit_sell
profit_sell_percent = total_profit_sell - 4
print(f"sell entry price {sell_entry_price}, sell exit price {sell_exit_price} , Sell P&L: {round(total_profit_sell, 2)}% with fee {round(profit_sell_percent, 2)}%")
else:
print("Sell Entry price or Buy Entry price is not defined.")
israel = []
depth_data = client.depth(symbol=symbol)
bid_depth = depth_data['bids']
ask_depth = depth_data['asks']
buy_price = float(bid_depth[0][0]) if bid_depth else 0.0
sell_price = float(ask_depth[0][0]) if ask_depth else 0.0
buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0
sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0
executed_orders_buy = 0.0
for order in bid_depth:
if float(order[0]) == mark_price:
executed_orders_buy += float(order[1])
else:
break
buy_result = buy_qty - executed_orders_buy
executed_orders_sell = 0.0
for order in ask_depth:
if float(order[0]) == mark_price:
executed_orders_sell += float(order[1])
else:
break
sell_result = sell_qty - executed_orders_sell
# Subtract executed order quantity from sell_qty
buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0
buy_price = float(bid_depth[0][0]) if bid_depth else 0.0
sell_price = float(ask_depth[0][0]) if ask_depth else 0.0
if signals == ['buy_exit']:
active_signal = None
israel.append("Long !!! EXIT !!!")
if buy_entry_price is not None and israel is not None:
buy_exit_price = mark_price
difference_buy = calculate_percentage_difference_buy(buy_entry_price, buy_exit_price)
profit_buy = difference_buy
total_profit_buy = profit_buy
profit_buy_percent = total_profit_buy - 4
try:
client.cancel_open_orders(symbol=symbol)
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
except binance.error.ClientError as e:
print(f"Long position successfully exited! ")
print(" !!! EXIT !!! ")
print(f"Time was : {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} buy entry price {buy_entry_price}, buy exit price: {mark_price}, Buy P&L: {round(total_profit_buy, 2)}% with fee {round(profit_buy_percent, 2)}%")
buy_entry_price = None
buy_exit_price = None
else:
print("Buy Entry price or Sell Entry price is not defined.") # Print israel when condition is met
else:
israel.append('')
elif 'sell' in signals and active_signal != 'sell':
try:
active_signal = 'sell'
sell_entry_price = mark_price # Record the sell entry price
print(f"Sell Entry Price: {sell_entry_price}")
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
client.new_order(symbol=symbol, side='SELL', type='MARKET', quantity=quantity)
print("Short order executed!")
except binance.error.ClientError as e:
print(f"Error executing short order: ")
if buy_entry_price is not None and sell_entry_price is not None:
buy_exit_price = mark_price
difference_buy = calculate_percentage_difference_buy(buy_entry_price, buy_exit_price)
profit_buy = difference_buy
total_profit_buy = profit_buy
profit_buy_percent = total_profit_buy - 4
print(f"buy entry price {buy_entry_price}, buy exit price: {sell_entry_price}, Buy P&L: {round(total_profit_buy, 2)}% with fee {round(profit_buy_percent, 2)}%")
else:
print("Buy Entry price or Sell Entry price is not defined.")
jerusalem = []
depth_data = client.depth(symbol=symbol)
bid_depth = depth_data['bids']
ask_depth = depth_data['asks']
buy_price = float(bid_depth[0][0]) if bid_depth else 0.0
sell_price = float(ask_depth[0][0]) if ask_depth else 0.0
buy_qty = float(bid_depth[0][1]) if bid_depth else 0.0
sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0
executed_orders_buy = 0.0
for order in bid_depth:
if float(order[0]) == mark_price:
executed_orders_buy += float(order[1])
else:
break
buy_result = buy_qty - executed_orders_buy
executed_orders_sell = 0.0
for order in ask_depth:
if float(order[0]) == mark_price:
executed_orders_sell += float(order[1])
else:
break
sell_result = sell_qty - executed_orders_sell
# Subtract executed order quantity from sell_qty
sell_qty = float(ask_depth[0][1]) if ask_depth else 0.0
sell_price = float(ask_depth[0][0]) if ask_depth else 0.0
buy_price = float(bid_depth[0][0]) if bid_depth else 0.0
if signals == ['sell_exit']:
active_signal = None
jerusalem.append("Short !!! EXIT !!!")
if sell_entry_price is not None and jerusalem is not None:
sell_exit_price = mark_price
difference_sell = calculate_percentage_difference_buy(sell_entry_price, sell_exit_price)
profit_sell = difference_sell
total_profit_sell = profit_sell
profit_sell_percent = total_profit_sell - 4
try:
client.new_order(symbol=symbol, side='BUY', type='MARKET', quantity=quantity)
except binance.error.ClientError as e:
print(f"Short position successfully exited!")
print(" !!! EXIT !!! ")
print(f"Time was : {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')} sell entry price {sell_entry_price}, sell exit price: {mark_price}, Sell P&L: {round(total_profit_sell, 2)}% with fee {round(profit_sell_percent, 2)}%")
sell_entry_price = None
sell_exit_price = None
else:
print("Buy Entry price or Sell Entry price is not defined.") # Print israel when condition is met
else:
jerusalem.append('')
time.sleep(1)
In this code you need to add my algorithm : if if 'buy' in signals and active_signal != 'buy'
it need to execute order via this comand: client.cancel_order(symbol=symbol, orderId=orderId, origClientOrderId=clientOrderId) and get orderId and clientOrderId after it, if 'sell' in signals and active_signal != 'sell': firstly it need to close buy trade through this comand : close_order(symbol=symbol, orderId= order, clientOrderId= clientOrderId )
To execute the client.cancel_order command and get the orderId and clientOrderId when the condition if 'buy' in signals and active_signal != 'buy' is met, you can modify the code as follows:
python
# Add these variables at the beginning of your code
order_id = None
client_order_id = None
# Inside the if condition 'buy' in signals and active_signal != 'buy':
if 'buy' in signals and active_signal != 'buy':
try:
buy_entry_price = mark_price
print(f"Buy Entry Price: {buy_entry_price}")
# Cancel existing order and get the order details
if order_id and client_order_id:
client.cancel_order(symbol=symbol, orderId=order_id, origClientOrderId=client_order_id)
# Place new order and get the new order id and client order id
order = client.new_order(symbol=symbol, side='BUY', type='LIMIT', quantity=quantity, price=mark_price)
order_id = order['orderId']
client_order_id = order['clientOrderId']
print(f"Long order executed!")
except binance.error.ClientError as e:
print(f"Error executing long order: ")
This will cancel the existing order and place a new order, updating the order_id and client_order_id.
Similarly, to close the buy trade and place a sell order when the condition if 'sell' in signals and active_signal != 'sell': is met, you can modify the code as follows:
python
# Add these variables at the beginning of your code
close_order_id = None
close_client_order_id = None
# Inside the if condition 'sell' in signals and active_signal != 'sell':
if 'sell' in signals and active_signal != 'sell':
try:
active_signal = 'sell'
sell_entry_price = mark_price # Record the sell entry price
print(f"Sell Entry Price: {sell_entry_price}")
# Close existing buy trade
if close_order_id and close_client_order_id:
client.close_order(symbol=symbol, orderId=close_order_id, origClientOrderId=close_client_order_id)
# Place new sell order and get the order details
order = client.new_order(symbol=symbol, side='SELL', type='LIMIT', quantity=quantity, price=mark_price)
close_order_id = order['orderId']
close_client_order_id = order['clientOrderId']
print("Short order executed!")
except binance.error.ClientError as e:
print(f"Error executing short order: ")
This will close the existing buy trade by executing the client.close_order command and placing a new sell order, updating the close_order_id and close_client_order_id.
Please note that you might need to adjust the order type (e.g., 'MARKET', 'LIMIT') and other parameters as per your specific requirements.
# Inside the if condition 'buy' in signals and active_signal != 'buy':
if 'buy' in signals and active_signal != 'buy':
try:
buy_entry_price = mark_price
print(f"Buy Entry Price: {buy_entry_price}")
# Cancel existing order
if orderId and clientOrderId:
client.cancel_order(symbol=symbol, orderId=orderId, origClientOrderId=clientOrderId)
# Place new order
# ... Place your new order code here ...
print(f"Long order executed!")
except binance.error.ClientError as e:
print(f"Error executing long order: ")
Similarly, in the if condition if 'sell' in signals and active_signal != 'sell': to execute the client.close_order command and close a buy trade, you can modify the code as follows:
python
# Inside the if condition 'sell' in signals and active_signal != 'sell':
if 'sell' in signals and active_signal != 'sell':
try:
active_signal = 'sell'
sell_entry_price = mark_price # Record the sell entry price
print(f"Sell Entry Price: {sell_entry_price}")
# Close existing buy trade
if order and clientOrderId:
client.close_order(symbol=symbol, orderId=order, clientOrderId=clientOrderId)
# Place new sell order
# ... Place your new sell order code here ...
print("Short order executed!")
except binance.error.ClientError as e:
print(f"Error executing short order: ")
In the above code snippets, orderId and clientOrderId should be the values obtained from previous orders. Make sure to replace symbol, orderId, and clientOrderId with their actual values.
Please note that the actual syntax and usage of the cancel_order and close_order commands may vary depending on the specific binance library or API you are using. It's important to consult the documentation or examples provided by the library or API to correctly utilize these commands.
Certainly! Below is the modified code with order execution and cancel order:
python
import time
import binance
active_signal = None
orderId = None
clientOrderId = None
buy_entry_price = None
sell_entry_price = None
# Set up your other code here
while True:
if df is not None:
# Get balance function
balance = client.balance()
# Get USDT balance function
for asset in balance:
if asset['asset'] == 'USDT':
balance_usdt = float(asset['balance'])
balance_usdt_futures = balance_usdt * 40
# Constant
price_bch = mark_price
dollars = balance_usdt_futures
# Counting Balance: BCH price
bch_amount = dollars / price_bch
bch_amount_rounded = round(bch_amount, 2)
quantity = bch_amount_rounded / 2
signals = signal_generator(df)
mark_price_data = client.ticker_price(symbol=symbol)
mark_price = float(mark_price_data['price']) if 'price' in mark_price_data else 0.0
if signals == ['buy'] or signals == ['sell']:
print(f"The signal time is: {dt.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Price {mark_price} - Signals: {signals}")
if 'buy' in signals and active_signal != 'buy':
try:
buy_entry_price = mark_price
print(f"Buy Entry Price: {buy_entry_price}")
# Cancel existing order
if orderId and clientOrderId:
client.cancel_order(symbol=symbol, orderId=orderId, origClientOrderId=clientOrderId)
# Place new order
# ... Place your new order code here ...
print(f"Long order executed!")
except binance.error.ClientError as e:
print(f"Error executing long order: ")
elif 'sell' in signals and active_signal != 'sell':
try:
active_signal = 'sell'
sell_entry_price = mark_price # Record the sell entry price
print(f"Sell Entry Price: {sell_entry_price}")
# Close existing buy trade
if orderId and clientOrderId:
client.cancel_order(symbol=symbol, orderId=orderId, origClientOrderId=clientOrderId)
# Place new sell order
# ... Place your new sell order code here ...
print("Short order executed!")
except binance.error.ClientError as e:
print(f"Error executing short order: ")
time.sleep(1)
Please note that you need to replace symbol, orderId, and clientOrderId with the actual values obtained from previous orders. Additionally, you need to fill in the placeholder code for placing new orders with the appropriate code according to the API or library you are using to interact with the Binance exchange.