Неверно работает функция
Получается, когда загоняешь в процесс 2 аккаунта или более, для первого аккаунта все нормально, а для второго аккаунта подцепляется все с первого. То есть весь прайс кеш и тд, и функция крашится из-за того, что нет тех предметов, которые он пытается выставить. (на втором, третьем и других аккаунтах в потоке выдается "Не удалось найти ордеры для следующих предметов: AVIATOR CRATE, Toxic - S1897")
В чем заключается проблема - не понимаю. ГПТ не помогает
Суть всей функции: Получаем предметы с БД аккаунта, получаем инвентарь определенной игры на аккаунте, проверяем, есть ли предмет из инвентаря в базе данных, если да то рассчитываем: получаем цену всех 10 лотов. Проверяем, если расхождение между 1 лотом и остальными условно меньше 3-4% (ну как в ситуации с ясенем) то мы можем взять цену первого лота, отнять копейку и выставить свой, перед этим проверим, что то, сколько мы получим не меньше или равно закупочной цены
Если разницы уже больше 3-4% то рассчитываем среднее арифметическое первых 10 лотов (либо 9, если первый лот со слишком большой разницей отошел от средней арифметической), после проверяем, что то, сколько мы получим не меньше или равно закупочной цене
P.s. использую aiosteampy
async def market_sell(self, login: str, game_name: str, min_deviation: float = 1.0, max_deviation: float = 5.0) -> None:
price_cache = {} #for cache prices
items_not_in_database = []
error_count = 0
sync = {query[0]: int(query[2]) for query in Database(base_adress_generator(login)).execute("SELECT * FROM orders WHERE game = ?", (game_name, )).fetchall()}
async with SteamClientManager(login) as client:
if await client.is_session_alive() is True:
try:
inventory, count, _ = await client.get_inventory(AppContext[game_name])
ser = {item.asset_id: serialize_inventory_item(item) for item in inventory}
result_json = {
"inventory": ser,
"total_count": count
}
with open(f"{Constants.INFO_FOLDER}\\inventories\\{game_name}_{login}.json", "w", encoding="utf-8") as file:
json.dump(result_json, file, ensure_ascii=False, indent=4)
except Exception as e:
return
data = result_json
items = data.get("inventory", {})
if not items or len(items) == 0:
return
for item_id, item in items.items():
id = int(item_id)
name = item.get("market_hash_name", "Unknown item")
if name in sync:
buy_price = int(sync[name])
if name in price_cache:
price = price_cache[name]
else:
price = None
if not price:
try:
name_id = await client.get_item_name_id(obj = name, app = App[game_name])
histogram, ltmd = await client.get_item_orders_histogram(name_id)
market_prices = [order.price / 100 for order in histogram.sell_order_graph[:10]]
first_lot_price = market_prices[0]
except Exception as e:
error_count += 1
if error_count >= 10:
return
await asyncio.sleep(6)
continue
try:
average_price_10 = sum(market_prices) / len(market_prices)
deviation = abs(first_lot_price - average_price_10) / average_price_10 * 100
deviation = round(deviation, 2)
if deviation <= max_deviation:
price = first_lot_price - 1
else:
average_price_9 = sum(market_prices[1:]) / 9
deviation_9_10 = abs(average_price_10 - average_price_9) / average_price_10 * 100
deviation_9_10 = round(deviation_9_10, 2)
if deviation_9_10 > 5: # 5%
price = average_price_9
else:
price = average_price_10
except Exception as e:
error_count += 1
if error_count >= 10:
return
continue
price = int(price * 100)
price_cache[name] = int(price)
sell_price = price_cache[name]
to_receive = buyer_pays_to_receive(sell_price)[2]
if to_receive > buy_price and to_receive > 0:
if isSelling(login, name):
if game_name == "PUBG":
count_pubg = 0
if count_pubg > 20:
break
else:
count_pubg += 1
try:
#await client.place_sell_listing(
# obj = id, #id предмета
# app_context = AppContext[game_name],
# price = sell_price
#)
make_log("debug", f"Market.market_sell[{login}]", f"Продажа предмета {name} | продажа: {price / 100} руб. (к получению: {to_receive / 100} руб.), закупочная: {buy_price / 100} руб.")
#await asyncio.sleep(6)
except Exception as e:
error_count += 1
if error_count >= 10:
return
await asyncio.sleep(6)
continue
else:
make_log("debug", f"Market.market_sell[{login}]", f"У предмета {name} отключена продажа")
else:
make_log("warning", "market", f"Какая то хуйня с ценой. {price} ({to_receive})")
else:
if name not in items_not_in_database:
items_not_in_database.append(name)
continue
if items_not_in_database:
make_log("warning", f"Market.market_sell[{login}]", f"Не удалось найти ордеры для следующих предметов: {', '.join(items_not_in_database)}")