My friend.
thanks for your answer.
So I decided to store the data on a JSON file and use it later on.
The reasons I am fetching those two particular indicators is I want to compare them later as in the code below.
Now I believe I’ve got an issue with ws.run_forever()
Where should I place it? or what is incorrect? Because it looks like the code is stuck at the websocket loop.
min_price = {}
compare_coins = "compare_coins.json"
# if saved compare coins json file exists then load it
if os.path.isfile(compare_coins):
with open(compare_coins) as file:
min_price = json.load(file)
# coins that bought by the bot since its start
coins_bought = {}
# path to the saved coins_bought file
coins_bought_file_path = "coins_bought.json"
# if saved coins_bought json file exists then load it
if os.path.isfile(coins_bought_file_path):
with open(coins_bought_file_path) as file:
coins_bought = json.load(file)
def on_open(ws):
print("open")
def on_message(ws,message):
json_message = json.loads(message)
cs = json_message
for coin in cs:
min_price[coin["s"]] = { "lastPrice": coin["c"], "lowPrice": coin["l"]}
with open(compare_coins, "w") as file:
json.dump(min_price, file, indent=4)
is_candle_closed = candle['x']
if is_candle_closed:
print(json.dumps(candle, indent=2))
def on_close(ws, close_status_code, close_msg):
print("closed")
SOCK = "wss://fstream.binance.com/ws/!miniTicker@arr"
ws = websocket.WebSocketApp(SOCK, on_open=on_open,on_close=on_close, on_message=on_message)
ws.run_forever()
def check_below():
volatile_coins = {}
for coin in min_price:
if float(min_price[coin]["lastPrice"])>=float(min_price[coin]["lowPrice"]):
volatile_coins[coin] = min_price[coin]["lastPrice"]
return volatile_coins, len(volatile_coins), min_price
def convert_volume():
#Converts the volume given in QUANTITY from USDT to the each coin’s volume’’’
volatile_coins, number_of_coins, min_price = check_below()
lot_size = {}
volume = {}
for coin in volatile_coins:
info = client.futures_exchange_info()
lot_size = next((filter["quantityPrecision"] for filter in info["symbols"] if filter["symbol"] == coin), None)
leverage_real = client.futures_change_leverage(symbol=coin, leverage=20)
# calculate the volume in coin from QUANTITY in USDT (default)
volume[coin] = round(float(QUANTITY) / float(min_price[coin]["lastPrice"]),lot_size)
return volume, min_price
print(convert_volume())
def trade():
#Place Buy market orders for each volatile coin found’’’
volume, min_price = convert_volume()
orders = {}
for coin in volume:
# only buy if the there are no active trades on the coin
if coin not in coins_bought or coins_bought[coin] == None:
print(f" preparing to buy {volume[coin]} {coin}")
info = client.futures_exchange_info()
lot_size = next((filter["pricePrecision"] for filter in info["symbols"] if filter["symbol"] == coin), None)
if lot_size is None:
raise Exception("PRICE_FILTER tick size not found")
# try to create a real order if the test orders did not raise an exception
try:
buy_limit = client.futures_create_order(
symbol=coin,
side="BUY",
type="LIMIT",
price =round(float(min_price[coin]["lastPrice"])*0.965,lot_size-1),
timeInForce="GTC",
quantity=round(volume[coin],lot_size)
)
# error handling here in case position cannot be placed
except Exception as e:
print(e)
else:
print(f"Signal detected, but there is already an active trade on {coin}")
return orders, min_price, volume
def update_porfolio(orders, min_price, volume):
#add every coin bought to our portfolio for tracking/selling later’’’
for coin in orders:
coins_bought[coin] = {
"symbol": orders[coin][0]["symbol"],
"orderid": orders[coin][0]["orderId"],
"timestamp": orders[coin][0]["time"],
"bought_at": orders[coin][0]["price"],
"volume": volume[coin],
"status": orders[coin][0]["status"],
"side": orders[coin][0]["side"]
}
# save the coins in a json file in the same directory
with open(coins_bought_file_path, "w") as file:
json.dump(coins_bought, file, indent=4)
def sell_coins():
#sell coins that have reached the STOP LOSS or TAKE PROFIT thershold’’’
for coin in coins_bought:
if coins_bought[coin]["status"] == "NEW":
# define stop loss and take profit
TP = float(coins_bought[coin]["bought_at"]) + (float(coins_bought[coin]["bought_at"]) * TAKE_PROFIT) / 100
SL = float(coins_bought[coin]["bought_at"]) - (float(coins_bought[coin]["bought_at"]) * STOP_LOSS) / 100
# check that the price is above the take profit or below the stop loss
if float(min_price[coin]["lastPrice"]) > TP or float(min_price[coin]["lastPrice"]) < SL:
print("TP or SL reached selling", {coins_bought[coin]["volume"]}, {coin})
sell_limit = client.futures_create_order(
symbol=coin,
side="SELL",
type="MARKET",
quantity=coins_bought[coin]["volume"])
# error handling here in case position cannot be placed
else:
coins_bought[coin] = None
with open(coins_bought_file_path, "w") as file:
json.dump(coins_bought, file, indent=4)
print("No additional coin to buy or to sell")
else:
print("No additional coin to buy or to sell")
if __name__ == "__main__":
print("Press Ctrl-Q to stop the script")
for i in count():
orders, min_price, volume = trade()
update_porfolio(orders, min_price, volume)
sell_coins()