import json
import os
import random
import time
import traceback

import cv2
from django.utils import timezone

from accounts.models import FifaAccountCurrentItems
from futplus.settings import BASE_DIR
from sbc.public_methods import get_next_price_grade, get_previous_price_grade, set_sbc_status, delete_sold_items, put_item_for_sale, set_sub_log, get_trade_pile, sell_items, set_main_log, \
    put_consumable_for_sale, save_sold_items, save_selling_items, save_quick_sold_item, save_account_request, \
    get_round_price
from accounts.web_login_utils import logout_login
from sbc.sbc_solver import SBCSolver
from trade import console_trade_quality_dict
from trade.models import ConsoleTradeOneCard, ConsoleTradeOneQuality, ConsoleTradeOneHistory
from utils.ea_settings import fifa_23_address
from utils.realy_public_methods import new_print


class ConsoleTradeRunner(SBCSolver):
    # def new_print_2(self, fifa_account: FifaAccount, *args, **kwargs):
    #     text = ''
    #     for i in args:
    #         text += str(i) + ' '
    #     for key, value in kwargs.items():
    #         text += str(key) + ' : ' + str(value) + ' '
    #     ConsoleTradeOneLog.objects.create(fifa_account=fifa_account, description=text)
    bidding_executed = False
    selling_executed = False

    def console_trade_bot_core(self, try_count=0):
        set_sbc_status(self.sbc_worker, f'Trade Start ...')
        # self.new_print_2(self.fifa_account, f'start working , credit : {self.fifa_account.credit}')
        set_main_log(self.sbc_worker, f'start trade mode one')
        set_sub_log(self.sbc_worker, f'opening ultimate')
        self.public_moves.console_open_ultimate(close_game=True, state_set='home_main')
        new_print(self.fifa_account, 'start console trade bot core')
        try:
            self.fifa_account.refresh_from_db()
            self.trade_history = ConsoleTradeOneHistory.objects.filter(fifa_account=self.fifa_account).last()
            if (not self.trade_history or self.trade_history.end_time):
                if (self.fifa_account.console_trade_one_quality_new and
                        self.fifa_account.console_trade_one_quality != self.fifa_account.console_trade_one_quality_new):
                    self.fifa_account.refresh_from_db()
                    self.fifa_account.console_trade_one_quality = self.fifa_account.console_trade_one_quality_new
                    self.fifa_account.console_trade_one_quality_new = None
                    self.fifa_account.save(update_fields=['console_trade_one_quality', 'console_trade_one_quality_new'])
                    new_print(self.fifa_account, 'trade quality changed , ',
                              self.fifa_account.console_trade_one_quality)
                self.trade_history = ConsoleTradeOneHistory.objects.create(fifa_account=self.fifa_account)
            else:
                self.trade_history = ConsoleTradeOneHistory.objects.filter(fifa_account=self.fifa_account).last()
                if (self.fifa_account.console_trade_one_quality_new and
                        self.fifa_account.console_trade_one_quality == self.fifa_account.console_trade_one_quality_new):
                    self.fifa_account.refresh_from_db()
                    self.fifa_account.console_trade_one_quality_new = None
                    self.fifa_account.save(update_fields=['console_trade_one_quality_new'])
                    new_print(self.fifa_account, 'trade quality changed 2 , ',
                              self.fifa_account.console_trade_one_quality)
            self.trade_history.update_time = timezone.localtime()
            self.trade_history.save()
            # self.sbc_worker.refresh_from_db()
            # self.sbc_worker.status = f'login was success'
            # self.sbc_worker.status_change_time = timezone.localtime()
            # self.sbc_worker.save()
            invest_sell_low_price_dict = {
                'bronze1': 300,
                'silver0': 300,
                'silver1': 750,
                'gold0': 600,
                'gold1': 1000,
            }
            if self.fifa_account.is_running_console_trade_one is False:
                self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                web_sell_result = self.web_sell_items()
                if web_sell_result == 'transfer list empty':
                    new_print(self.fifa_account, 'web sell items result : ', web_sell_result, ' , trade continue')
                else:
                    new_print(self.fifa_account, 'transfer list not empty , first clear transfer list')
                    self.console_transfer_list_sell_items(need_get_new_sid=False)
                    self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                    if self.web_check_transfer_list_empty() != 'transfer list empty':
                        new_print(self.fifa_account, 'transfer list not empty , sleep 2 minute')
                        time.sleep(120)
                        return
            if self.fifa_account.console_trade_one_quality:
                trade_quality = ConsoleTradeOneQuality.objects.filter(
                    name=self.fifa_account.console_trade_one_quality).last()
            else:
                raise Exception('Fifa Account not quality set for trade')
            if self.fifa_account.console_trade_one_quality == 'position_modifier' and not trade_quality:
                raise Exception('Need Position Modifier Trade Quality')
            if ((
                    trade_quality and
                    trade_quality.auto_next_create and
                    trade_quality.create_time < (timezone.localtime() - timezone.timedelta(minutes=30))
            ) or not trade_quality) and self.fifa_account.console_trade_one_quality != 'position_modifier':
                set_sbc_status(self.sbc_worker, 'Trade Get Price')
                zero_prices = {'gold1': 550, 'gold0': 300, 'silver1': 250, 'silver0': 150, 'bronze1': 150}
                sell_price, bid_price = self.extract_sell_bid_price(
                    quality=self.fifa_account.console_trade_one_quality,
                    zero_price=zero_prices.get(self.fifa_account.console_trade_one_quality, 150)
                )
                last_trade_quality = ConsoleTradeOneQuality.objects.filter(
                    name=self.fifa_account.console_trade_one_quality).last()
                if (
                        last_trade_quality and
                        last_trade_quality.auto_next_create and
                        last_trade_quality.create_time < (timezone.localtime() - timezone.timedelta(minutes=30)) and
                        sell_price >= zero_prices.get(self.fifa_account.console_trade_one_quality, 1000)
                ) or not last_trade_quality:
                    if sell_price <= 650 and self.fifa_account.console_trade_one_quality == 'gold1':
                        bid_price = 550
                    # elif sell_price < 650 and self.fifa_account.console_trade_one_quality == 'gold1':
                    #     bid_price = 0
                    elif sell_price <= 350 and self.fifa_account.console_trade_one_quality == 'gold0':
                        bid_price = 250
                    # elif sell_price < 350 and self.fifa_account.console_trade_one_quality == 'gold0':
                    #     bid_price = 0
                    elif sell_price <= 300 and self.fifa_account.console_trade_one_quality == 'silver1':
                        bid_price = 200
                    # elif sell_price < 300 and self.fifa_account.console_trade_one_quality == 'silver1':
                    #     bid_price = 0
                    elif sell_price <= 200 and self.fifa_account.console_trade_one_quality == 'silver0':
                        bid_price = 100
                    # elif sell_price < 200 and self.fifa_account.console_trade_one_quality == 'silver0':
                    #     bid_price = 0
                    elif sell_price <= 200 and self.fifa_account.console_trade_one_quality == 'bronze1':
                        bid_price = 100
                    # elif sell_price < 200 and self.fifa_account.console_trade_one_quality == 'bronze1':
                    #     bid_price = 0
                    dynamic_upper_price = False
                    trade_quality.refresh_from_db()
                    invest_sell_low_price = invest_sell_low_price_dict.get(trade_quality.name)
                    invest_bid_high_price = 0
                    if last_trade_quality:
                        # if last_trade_quality.dynamic_upper_price:
                        #     dynamic_upper_price = True
                        # win_histories = ConsoleTradeOneHistory.objects.filter(
                        #     move_items_from_unassigned__gt=timezone.localtime() - timezone.timedelta(hours=1),
                        #     quality_name=last_trade_quality.name
                        # ).exclude(bid_count__lt=10).annotate(
                        #     win_rate=(F('win_count') * 100 / F('bid_count'))
                        # )
                        # if win_histories.count() >= 2:
                        #     win_rate = win_histories.aggregate(win_rate_avg=Avg('win_rate')).get('win_rate_avg')
                        #     if win_rate > 47:
                        #         dynamic_upper_price = False
                        #     elif win_rate < 20:
                        #         dynamic_upper_price = True
                        if last_trade_quality.invest_sell_low_price >= 200:
                            invest_sell_low_price = last_trade_quality.invest_sell_low_price
                        if last_trade_quality.invest_bid_high_price >= 100:
                            invest_bid_high_price = last_trade_quality.invest_bid_high_price

                    if dynamic_upper_price and bid_price:
                        bid_price = get_next_price_grade(bid_price)
                        sell_price = get_next_price_grade(sell_price)
                    # todo : jbayat solution. remove after test complete.
                    if bid_price:
                        bid_price = get_next_price_grade(bid_price)
                    sell_price = get_next_price_grade(sell_price)
                    #
                    trade_quality = ConsoleTradeOneQuality.objects.create(
                        fifa_account=self.fifa_account,
                        name=self.fifa_account.console_trade_one_quality,
                        bid_price=bid_price,
                        sell_price=sell_price,
                        auto_next_create=True,
                        dynamic_upper_price=dynamic_upper_price,
                        invest_bid_low_price=last_trade_quality.invest_bid_low_price,
                        invest_sell_low_price=invest_sell_low_price,
                        invest_bid_high_price=invest_bid_high_price,
                        sell_items=last_trade_quality.sell_items,
                        bid_items=last_trade_quality.bid_items,
                        invest_lowest_credit=last_trade_quality.invest_lowest_credit,
                        invest_highest_stock=last_trade_quality.invest_highest_stock,
                    )
            self.bidding_mode_bid_price = trade_quality.bid_price
            self.selling_mode_price = trade_quality.sell_price
            # invest trade info
            if self.fifa_account.run_console_invest_trade_one is True:
                if self.bidding_mode_bid_price < 150 and self.fifa_account.console_trade_one_quality == 'bronze1':
                    self.bidding_mode_bid_price = 150
                elif self.bidding_mode_bid_price < 150 and self.fifa_account.console_trade_one_quality == 'silver0':
                    self.bidding_mode_bid_price = 150
                elif self.bidding_mode_bid_price < 250 and self.fifa_account.console_trade_one_quality == 'silver1':
                    self.bidding_mode_bid_price = 250
                elif self.bidding_mode_bid_price < 300 and self.fifa_account.console_trade_one_quality == 'gold0':
                    self.bidding_mode_bid_price = 300
                elif self.bidding_mode_bid_price < 600 and self.fifa_account.console_trade_one_quality == 'gold1':
                    self.bidding_mode_bid_price = 600
                if self.bidding_mode_bid_price < trade_quality.invest_bid_low_price:
                    self.bidding_mode_bid_price = trade_quality.invest_bid_low_price

                self.selling_mode_price = trade_quality.sell_price
                if self.selling_mode_price < trade_quality.invest_sell_low_price:
                    self.selling_mode_price = trade_quality.invest_sell_low_price
                # if (self.selling_mode_price < trade_quality.invest_sell_low_price or
                #         trade_quality.invest_sell_low_price <= 200):
                #     self.selling_mode_price = invest_sell_low_price_dict.get(
                #         self.fifa_account.console_trade_one_quality
                #     )
                # self.selling_mode_price = trade_quality.sell_price
                # if self.fifa_account.run_console_invest_trade_one is True:
                #     if self.selling_mode_price < 300 and self.fifa_account.console_trade_one_quality == 'bronze1':
                #         self.selling_mode_price = 300
                #     elif self.selling_mode_price < 750 and self.fifa_account.console_trade_one_quality == 'silver1':
                #         self.selling_mode_price = 750
                #     elif self.selling_mode_price < 600 and self.fifa_account.console_trade_one_quality == 'gold0':
                #         self.selling_mode_price = 600
                #     elif self.selling_mode_price < 1000 and self.fifa_account.console_trade_one_quality == 'gold1':
                #         self.selling_mode_price = 1000
                new_print(
                    self.fifa_account,
                    'run_console_invest_trade_one : ',
                    self.fifa_account.run_console_invest_trade_one,
                    ' bidding_mode_bid_price : ', self.bidding_mode_bid_price,
                    ' selling_mode_price : ', self.selling_mode_price,
                )
            self.trade_history.refresh_from_db()
            self.trade_history.quality_name = trade_quality.name
            self.trade_history.bid_price = self.bidding_mode_bid_price
            self.trade_history.sell_price = trade_quality.sell_price
            self.trade_history.update_time = timezone.localtime()
            self.trade_history.save()
            self.sbc_worker.refresh_from_db()
            self.fifa_account.refresh_from_db()
            sell_with_next_grade_price = False
            # run_sell_first_time = False
            # for iii in range(2):
            bidding_done = False
            account_current_items = FifaAccountCurrentItems.objects.filter(fifa_account=self.fifa_account).last()
            if account_current_items:
                current_stock = account_current_items.__dict__.get(f'club_{trade_quality.name}_tradable_items') or 0
            else:
                current_stock = 0
            new_print(self.fifa_account, 'current stock : ', current_stock)
            if True:
                if (self.fifa_account.credit > 5000 and trade_quality.bid_items and
                        self.fifa_account.run_console_trade_one and
                        trade_quality.invest_lowest_credit < self.fifa_account.credit and
                        trade_quality.invest_highest_stock > current_stock and
                        (not self.fifa_account.console_trade_one_quality_new or
                         self.fifa_account.console_trade_one_quality == self.fifa_account.console_trade_one_quality_new)
                        and
                        ((
                          not self.fifa_account.run_console_invest_trade_one and
                          (self.fifa_account.is_running_console_trade_one is False or
                           self.trade_history.bid_count < 150))
                         or
                         (
                          self.fifa_account.run_console_invest_trade_one and
                          # trade_quality.sell_price < invest_sell_low_price.get(self.trade_history.quality_name, 0) and
                          # (trade_quality.invest_sell_low_price == 0 or (
                          #         trade_quality.invest_sell_low_price and
                          # trade_quality.sell_price < trade_quality.invest_sell_low_price)) and
                          # trade_quality.sell_price < trade_quality.invest_sell_low_price and
                          # self.trade_history.unassigned_full_need_sell_counter < 1 and
                          self.trade_history.transfer_list_duplicate_items_count < 45 and
                          not self.fifa_account.stop_console_trade_one_for_other_bots and
                          (trade_quality.invest_bid_high_price == 0 or
                           (trade_quality.invest_bid_high_price >= 100 and
                            self.bidding_mode_bid_price <= trade_quality.invest_bid_high_price))
                         )
                        )):
                    self.bidding_executed = True
                    set_sbc_status(self.sbc_worker, 'Trade bidding ...')
                    set_sub_log(self.sbc_worker, 'Console Trade One bidding mode start...')
                    new_print(self.fifa_account, 'bidding mode')
                    if self.bidding_mode_bid_price <= 0:
                        new_print(self.fifa_account, 'can`t bid on price 0')
                        set_sub_log(self.sbc_worker, 'Console Trade One bidding mode end. bid price zero')
                        # break
                    # self.new_print_2(self.fifa_account, f'before buying items , credit {self.fifa_account.credit}')
                    else:
                        bidding_done = True
                        if self.trade_history.credit_before == 0:
                            self.trade_history.refresh_from_db()
                            self.trade_history.credit_before = self.fifa_account.credit
                            self.trade_history.update_time = timezone.localtime()
                            self.trade_history.save()
                        self.fifa_account.refresh_from_db()
                        self.fifa_account.is_running_console_trade_one = True
                        self.fifa_account.save(update_fields=['is_running_console_trade_one'])
                        for tt in range(3):
                            set_sub_log(self.sbc_worker, f'Console Trade One bidding mode round {tt}')
                            set_sbc_status(self.sbc_worker, f'Trade bidding {tt}')
                            new_print(self.fifa_account, f'Console Trade One bidding round {tt}')
                            # bid_count = int(self.fifa_account.credit / trade_quality.bid_price)
                            # if bid_count > 50:
                            #     bid_count = 50
                            sell_with_next_grade_price = True
                            bid_count = 49
                            self.bided_count = 0
                            bidding_mode_result = self.biding_mode(
                                bid_price=self.bidding_mode_bid_price,
                                bid_count=bid_count,
                                quality=trade_quality)
                            self.trade_history.refresh_from_db()
                            self.trade_history.bid_count += self.bided_count
                            self.trade_history.update_time = timezone.localtime()
                            self.trade_history.save()
                            self.unassign_bought_items()
                            set_sub_log(self.sbc_worker, 'manage unassign_bought_items end')
                            if bidding_mode_result == 'low credit':
                                new_print(self.fifa_account, 'low credit')
                                # self.new_print_2(self.fifa_account, 'low credit')
                                break
                            if bidding_mode_result == 'unassign full':
                                new_print(self.fifa_account, 'unassign full , break loop')
                                self.trade_history.refresh_from_db()
                                self.trade_history.unassigned_full_need_sell_counter = 10
                                self.trade_history.save()
                                # self.new_print_2(self.fifa_account, 'low credit')
                                break
                            if bidding_mode_result == 'high last remain time':
                                new_print(self.fifa_account, 'high last remain time')
                                break
                            if bidding_mode_result == 'too many busy in trade':
                                new_print(self.fifa_account, 'too many busy in trade')
                                break
                            # bid one time after try one because if unassign full with duplicate
                            if (self.fifa_account.run_console_invest_trade_one and
                                    self.trade_history.transfer_list_duplicate_items_count > 40):
                                break
                            # if (self.fifa_account.run_console_invest_trade_one and
                            #         self.trade_history.list_try_count > 1 and
                            #         self.fifa_account.console_trade_one_quality != 'position_modifier'):
                            #     break
                        self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                        self.manage_bought_items(bought_price=self.bidding_mode_bid_price,
                                                 quality_name=self.trade_history.quality_name)
                        try:
                            self.save_account_items()
                        except:
                            new_print(self.fifa_account, 'exception error 114 : ', traceback.format_exc())
                        set_sub_log(self.sbc_worker, 'Console Trade One bidding mode end')
                        # if self.fifa_account.run_console_invest_trade_one and run_sell_first_time is True:
                        #     break
                # existed_trade_cards = ConsoleTradeOneCard.objects.filter(fifa_account=self.fifa_account, deleted=False)
                last_trade_history = ConsoleTradeOneHistory.objects.filter(
                    fifa_account=self.fifa_account
                ).exclude(id=self.trade_history.id).last()
                trade_quality.refresh_from_db()
                if ((self.fifa_account.is_running_console_trade_one or not self.trade_history.end_time) and
                        trade_quality.sell_items):
                    if last_trade_history:
                        new_print(self.fifa_account, 'last trade history : ',
                                  getattr(last_trade_history,
                                          f'club_{self.fifa_account.console_trade_one_quality}_items'))
                    self.fifa_account.refresh_from_db()
                    self.fifa_account.is_running_console_trade_one = True
                    self.fifa_account.save(update_fields=['is_running_console_trade_one'])
                    # run_sell_first_time = True
                    set_sub_log(self.sbc_worker, 'console trade one selling mode start...')
                    set_sbc_status(self.sbc_worker, 'Trade selling ...')
                    new_print(self.fifa_account, 'selling mode')
                    self.selling_executed = True
                    # self.new_print_2(self.fifa_account,
                    #                  f'selling mode {trade_quality.name} : {trade_quality.bid_price} , {trade_quality.sell_price}')
                    # manage_transfer_target = self.unassign_bought_items()
                    # if manage_transfer_target != 'transfer target empty':
                    #     self.public_moves.console_close_ultimate(need_get_new_sid=False)
                    #     self.manage_bought_items(bought_price=trade_quality.bid_price)
                    if bidding_done:
                        self.unassign_bought_items()
                        set_sub_log(self.sbc_worker, 'manage unassign_bought_items end')
                    self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                    bought_item_result = self.manage_bought_items(bought_price=self.bidding_mode_bid_price,
                                                                  quality_name=self.trade_history.quality_name)
                    try:
                        self.save_account_items()
                    except:
                        new_print(self.fifa_account, 'exception error 113 : ', traceback.format_exc())
                    # if bought_item_result == 'stop console trade one for other bots':
                    if bought_item_result == 'list duplicate with low price':
                        self.selling_mode_price = trade_quality.sell_price
                    if sell_with_next_grade_price and not self.fifa_account.run_console_invest_trade_one:
                        new_print(self.fifa_account, f'sell with next grade : {sell_with_next_grade_price}')
                        self.selling_mode_price = get_next_price_grade(self.selling_mode_price)
                    relist_items = False
                    if (self.selling_mode_price == self.trade_history.current_sell_price and
                            bought_item_result != 'list duplicate with low price' and
                            self.trade_history.transfer_list_items_count > 10):
                        relist_items = True
                    self.trade_history.refresh_from_db()
                    self.trade_history.current_sell_price = self.selling_mode_price
                    self.trade_history.save()
                    if bought_item_result != 'transfer list and unassigned empty':
                        selling_mode_result = self.selling_mode(
                            sell_price=self.selling_mode_price,
                            quality=trade_quality.name,
                            relist_all=relist_items
                        )
                    if bought_item_result == 'transfer list and unassigned empty':
                        new_print(self.fifa_account, 'after selling items , transfer list and unassigned empty')
                        self.fifa_account.refresh_from_db()
                        self.fifa_account.is_running_console_trade_one = False
                        self.fifa_account.save(update_fields=['is_running_console_trade_one'])
                        # self.new_print_2(self.fifa_account, f'after selling items , credit {self.fifa_account.credit}')
                        ConsoleTradeOneCard.objects.filter(fifa_account=self.fifa_account).update(deleted=True)
                        self.trade_history.refresh_from_db()
                        self.trade_history.credit_after = self.fifa_account.credit
                        self.trade_history.end_time = timezone.localtime()
                        self.trade_history.save()
                        if (self.fifa_account.console_trade_one_quality_new and
                                self.fifa_account.console_trade_one_quality !=
                                self.fifa_account.console_trade_one_quality_new and
                                try_count == 0):
                            new_print(self.fifa_account, 'need to change quality and ready')
                            self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                            return self.console_trade_bot_core(try_count=1)
                        # if not self.fifa_account.run_console_invest_trade_one:
                        #     break
                    # elif selling_mode_result == 'transfer list empty':
                    #     new_print(self.fifa_account, 'after selling items , transfer list empty')
                    #     self.fifa_account.refresh_from_db()
                    #     self.fifa_account.is_running_console_trade_one = False
                    #     self.fifa_account.save()
                    #     # self.new_print_2(self.fifa_account, f'after selling items , credit {self.fifa_account.credit}')
                    #     ConsoleTradeOneCard.objects.filter(fifa_account=self.fifa_account).update(deleted=True)
                    #     self.trade_history.refresh_from_db()
                    #     self.trade_history.credit_after = self.fifa_account.credit
                    #     self.trade_history.end_time = timezone.localtime()
                    #     self.trade_history.save()
                    #     # if not self.fifa_account.run_console_invest_trade_one:
                    #     #     break
                    else:
                        # ConsoleTradeOneCard.objects.filter(fifa_account=self.fifa_account, deleted=False).update(
                        #     list_try_count=F('list_try_count') + 1)
                        set_sub_log(self.sbc_worker, 'console trade one selling mode end and not empty')
                        self.trade_history.refresh_from_db()
                        self.trade_history.list_try_count += 1
                        self.trade_history.update_time = timezone.localtime()
                        self.trade_history.save()
                        # if not self.fifa_account.run_console_invest_trade_one:
                        #     break
                if not self.bidding_executed and not self.selling_executed:
                    new_print(self.fifa_account, 'no bidding and selling running , manage bought items')
                    self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
                    self.manage_bought_items(
                        bought_price=self.bidding_mode_bid_price,
                        quality_name=self.trade_history.quality_name
                    )


            self.trade_history.refresh_from_db()
            self.trade_history.update_time = timezone.localtime()
            self.trade_history.save()
            self.public_moves.console_close_ultimate(need_get_new_sid=False, state='home_main')
            new_print(self.fifa_account, f'end working , credit : {self.fifa_account.credit}')
            # self.new_print_2(self.fifa_account, f'end working , credit : {self.fifa_account.credit}')
        except Exception as error:
            new_print(self.fifa_account, 'exception error 93 : ', traceback.format_exc())
            self.public_moves.ps4_buttons.reset_to_default()
            self.sbc_worker.refresh_from_db()
            self.sbc_worker.description = ''
            self.sbc_worker.description_editor = None
            self.sbc_worker.save()
            set_sbc_status(self.sbc_worker, str(error))
            if str(error) == 'console trade found more than 5000 card price':
                time.sleep(10)
            else:
                time.sleep(600)
        set_sbc_status(self.sbc_worker, 'Trade End')
        set_main_log(self.sbc_worker, f'end trade mode one')

    def biding_mode(self, bid_price, bid_count, quality: ConsoleTradeOneQuality):
        new_print(self.fifa_account, 'start bidding mode , bid price : ', bid_price, ' bid count : ', bid_count)
        self.fifa_account.refresh_from_db()
        if not self.fifa_account.run_console_trade_one:
            new_print(self.fifa_account, 'not running console_trade_one , stop biding_mode')
            return False
        bided_count = 0
        try_to_bid = 0
        higher_price_counter = 0
        if False and quality.name == 'position_modifier':
            self.public_moves.go_to_state('transfers', 'search_consumables')
            self.public_moves.ps4_buttons.r3()
            time.sleep(1)
            new_print(self.fifa_account, 'search position change')
            self.public_moves.ps4_buttons.cross()
            time.sleep(1)
            self.public_moves.ps4_buttons.right(sleep_after=.5)
            self.public_moves.ps4_buttons.right(sleep_after=.5)
            self.public_moves.ps4_buttons.right(sleep_after=.5)
            self.public_moves.ps4_buttons.cross(sleep_after=1)
            if not self.public_moves.transfer_list_utils.check_selected_quality(quality.name):
                new_print(self.fifa_account, 'selected position change not fixed')
                return self.biding_mode(bid_price=bid_price, bid_count=bid_count,
                                        quality=quality)
            self.public_moves.ps4_buttons.down(sleep_after=.5)
        else:
            self.public_moves.go_to_state('transfers', 'search_players')
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/player_search_not_found.png'),
                    'screen_shot_tmp.jpg'
            ) or self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/player_search_not_found_start.png'),
                'screen_shot_tmp.jpg'
            ):
                new_print(self.fifa_account, 'already in player search 2 . press circle')
                self.public_moves.ps4_buttons.circle()
                time.sleep(1)
            # need_reset_filter = True
            # if need_reset_filter:
            self.public_moves.ps4_buttons.r3()
            time.sleep(1)
            # if quality:
            new_print(self.fifa_account, 'search player find quality',
                      f'{quality.name}')
            self.public_moves.ps4_buttons.right(sleep_after=.5)
            self.public_moves.ps4_buttons.cross()
            time.sleep(1)
            self.public_moves.transfer_list_utils.find_quality(f'{quality.name}')
            time.sleep(1)
            if not self.public_moves.transfer_list_utils.check_selected_quality(quality.name):
                new_print(self.fifa_account, 'selected quality not fixed')
                return self.biding_mode(bid_price=bid_price, bid_count=bid_count,
                                        quality=quality)
            self.public_moves.ps4_buttons.left(sleep_after=.2)
            self.public_moves.ps4_buttons.down(sleep_after=.5)
        self.public_moves.ps4_buttons.square()
        time.sleep(0.5)
        self.public_moves.ps4_buttons.cross()
        time.sleep(1)
        search_price_res = self.special_search_player_price(
            price=bid_price, price_type='max_start', default_price=150)
        if search_price_res == 'can not find price':
            new_print(self.fifa_account, 'bidding mode error : can not find price')
            self.public_moves.ps4_buttons.circle()
            time.sleep(1)
            self.public_moves.ps4_buttons.circle()
            time.sleep(10)
            return self.biding_mode(bid_price=bid_price, bid_count=bid_count,
                                    quality=quality)
        time.sleep(0.5)
        self.public_moves.ps4_buttons.circle()
        time.sleep(0.5)
        self.public_moves.ps4_buttons.up(sleep_after=0.5)
        self.public_moves.ps4_buttons.triangle()
        time.sleep(1)
        wait_result = self.public_moves.wait_for_images(
            [os.path.join(BASE_DIR,
                          f'utils/{self.fifa_account.platform}_controls/transfer_market_no_search_result.png'),
             os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/live_search_results.png'),
             os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/time_remaining.png'),
             ],
            wait_time=15, check_errors=False)
        if wait_result is False:
            new_print(self.fifa_account, 'bidding mode error : can not find transfer live result')
            time.sleep(10)
            return self.biding_mode(bid_price=bid_price, bid_count=bid_count,
                                    quality=quality)
        if not self.public_moves.has_search_result():
            new_print(self.fifa_account, 'bidding mode error : search has no result')
            self.public_moves.ps4_buttons.cross(sleep_after=1)
            time.sleep(10)
            return self.biding_mode(bid_price=bid_price, bid_count=bid_count,
                                    quality=quality)
        remaining_time = False
        for num in range(2):
            for num2 in range(3):
                try:
                    remaining_time = self.public_moves.transfer_list_utils.get_remaining_time()
                    break
                except:
                    # print(traceback.format_exc())
                    time.sleep(.5)
                    continue
            if remaining_time is False:
                time.sleep(1)
                continue
            if remaining_time > 40:
                break
            self.public_moves.ps4_buttons.r1()
            time.sleep(.5)
        time.sleep(1)
        missed_way_counter = 0
        last_remain_secs = 0
        needs_item_to_next_page_count = 3
        try_low_credit = 0
        next_page_pressed = 0
        high_last_remain_secs = 6 * 60
        while bided_count <= bid_count:
            bid_item_result = self.bid_item(price=bid_price)
            try_to_bid += 1
            if try_to_bid > 2000 or next_page_pressed > 200:
                new_print(self.fifa_account, 'too many busy in trade')
                set_sub_log(self.sbc_worker,
                            f'too many busy in trade :'
                            f' try to bid : {try_to_bid},'
                            f' next page pressed : {next_page_pressed}')
                set_sbc_status(self.sbc_worker, f'bid waiting : {last_remain_secs} secs')
                self.sleep_while_remain(last_remain_secs)
                return 'too many busy in trade'
            if try_to_bid % 50 == 0:
                new_print(self.fifa_account, 'bidding mode , try to bid : ', try_to_bid,
                          'bided count : ', bided_count, ' bid count : ', bid_count)
                if try_to_bid % 300 == 0:
                    set_sbc_status(self.sbc_worker, f'Trade bidding - {try_to_bid / 300}')
            if last_remain_secs > high_last_remain_secs:
                new_print(self.fifa_account, 'high last remain time : ', last_remain_secs, ' but waiting : ', high_last_remain_secs)
                set_sub_log(self.sbc_worker, f'high last remain time : {last_remain_secs}, but waiting : {high_last_remain_secs}')
                set_sbc_status(self.sbc_worker, f'bid waiting : {high_last_remain_secs} secs')
                self.sleep_while_remain(high_last_remain_secs)
                return 'high last remain time'
                # return self.biding_mode(bid_price=bid_price, bid_count=bid_count - bided_count, quality=quality)
            if not bid_item_result:
                new_print(self.fifa_account, 'missed way 2, try again')
                if self.public_moves.just_find_state():
                    # print('ok i find state')
                    return False
                missed_way_counter += 1
                if missed_way_counter > 5:
                    return False
                continue
            elif bid_item_result == 'transfer expired':
                new_print(self.fifa_account, 'transfer expired')
                self.public_moves.ps4_buttons.r1()
                next_page_pressed += 1
                time.sleep(.5)
                # continue
            elif bid_item_result == 'higher price':
                # print('higher price')
                # self.public_moves.ps4_buttons.circle()
                # time.sleep(.5)
                needs_item_to_next_page_count = 6
                # higher_price_counter += 1
                # if higher_price_counter > 5:
                #     higher_price_counter = 0
                #     self.public_moves.ps4_buttons.r1()
                #     time.sleep(.5)
                # else:
                #     self.public_moves.ps4_buttons.right(sleep_after=.5)
                # continue
            elif bid_item_result == 'already bided':
                needs_item_to_next_page_count = 6
            elif bid_item_result == 'low credit':
                new_print(self.fifa_account, 'low credit , end of bidding mode',
                          ' last remain secs : ', last_remain_secs)
                if try_low_credit > 2:
                    set_sub_log(self.sbc_worker, f'low credit last remain secs : {last_remain_secs}')
                    set_sbc_status(self.sbc_worker, f'bid waiting : {last_remain_secs} secs')
                    self.sleep_while_remain(last_remain_secs)
                    return 'low credit'
                else:
                    try_low_credit += 1
            elif bid_item_result == 'unassign full':
                set_sub_log(self.sbc_worker, f'unassign full last remain secs : {last_remain_secs}')
                set_sbc_status(self.sbc_worker, f'bid waiting : {last_remain_secs} secs')
                new_print(self.fifa_account, f'unassign full last remain secs : {last_remain_secs} bided count: ',
                          bided_count)
                self.sleep_while_remain(last_remain_secs)
                return 'unassign full'
            elif bid_item_result == 'miss way':
                new_print(self.fifa_account, 'missed way , try again')
                self.public_moves.ps4_buttons.circle()
                return self.biding_mode(bid_price=bid_price, bid_count=bid_count - bided_count, quality=quality)
            elif bid_item_result == 'can not set price':
                new_print(self.fifa_account, 'can not set price , try again')
                self.public_moves.ps4_buttons.circle()
                time.sleep(1)
                return self.biding_mode(bid_price=bid_price, bid_count=bid_count - bided_count, quality=quality)
            elif bid_item_result is True:
                bided_count += 1
                self.bided_count += 1
                try_low_credit = 0
                ConsoleTradeOneCard.objects.create(
                    fifa_account=self.fifa_account,
                    bid_price=bid_price,
                    quality=quality,
                )
            try:
                if remaining_time < 50:
                    # todo : remove bellow new_print after check work
                    new_print(self.fifa_account, 'remain time less than 50 sec , continue on 3 item')
                    needs_item_to_next_page_count = 3
            except:
                new_print(self.fifa_account, 'cant read remain time , ', traceback.format_exc())
            self.public_moves.ps4_buttons.right(sleep_after=.5)
            if try_to_bid % needs_item_to_next_page_count == 0:
                needs_item_to_next_page_count = 3
                self.public_moves.get_screen_shot()
                # todo : fix and uncomment bellow
                if self.no_bid_success():
                    next_page_count = random.randint(3, 5)
                else:
                    next_page_count = 1
                for nnm in range(next_page_count):
                    self.public_moves.ps4_buttons.r1()
                    next_page_pressed += 1
                    time.sleep(.5)
                remaining_time = False
                for num in range(2):
                    for num2 in range(3):
                        try:
                            remaining_time = self.public_moves.transfer_list_utils.get_remaining_time()
                            break
                        except:
                            time.sleep(.5)
                            # print(traceback.format_exc())
                            continue
                    if remaining_time is False:
                        time.sleep(1)
                        continue
                    if remaining_time > 40:
                        if remaining_time > 5 * 3600:
                            new_print(self.fifa_account, 'unusual remaining time : ', remaining_time)
                            last_remain_secs = 5 * 60
                        elif remaining_time > 60 * 60:
                            new_print(self.fifa_account, 'unusual remaining time : 2', remaining_time)
                            last_remain_secs = 60 * 60
                        else:
                            last_remain_secs = remaining_time
                        break
                    self.public_moves.ps4_buttons.r1()
                    next_page_pressed += 1
                    time.sleep(.5)
                if self.check_compare_price():
                    new_print(self.fifa_account, 'ok i found compare price, going back')
                    self.public_moves.ps4_buttons.circle()
                    time.sleep(1)
                if self.public_moves.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/check_for_inside_bidding.png'),
                        'screen_shot_tmp.jpg') or self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/bid_sign.png'),
                    'screen_shot_tmp.jpg'):
                    new_print(self.fifa_account, 'stock in bidding, get back')
                    if self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/listing_expired.png'),
                            'screen_shot_tmp.jpg'):
                        new_print(self.fifa_account, 'listing expired , press cross')
                        self.public_moves.ps4_buttons.cross()
                        time.sleep(1)
                    self.public_moves.ps4_buttons.circle()
                    time.sleep(2)
        new_print(self.fifa_account, 'last remain secs : ', last_remain_secs, ' bided count : ', bided_count,
                  ' bid count : ', bid_count)
        set_sub_log(self.sbc_worker, f'last remain secs : {last_remain_secs},  bided count : {bided_count}')
        set_sbc_status(self.sbc_worker, f'bid waiting : {last_remain_secs} secs')
        self.sleep_while_remain(last_remain_secs)

    def sleep_while_remain(self, remain_secs: int):
        if remain_secs > 2 * 60:
            for item in range(5):
                new_print(self.fifa_account, 'pressing left and right while waiting for bid done')
                time.sleep(int(remain_secs / 5))
                self.public_moves.ps4_buttons.right()
                time.sleep(1)
                self.public_moves.ps4_buttons.left()
        else:
            new_print(self.fifa_account, 'waiting for bid done but no action , ', remain_secs)
            time.sleep(remain_secs)

    def check_compare_price(self):
        if self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/compare_price.png'),
                'screen_shot_tmp.jpg'):
            for num in range(14):
                self.public_moves.get_screen_shot()
                if not self.public_moves.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/compare_price.png'),
                        'screen_shot_tmp.jpg'):
                    return False
                time.sleep(.5)
            return True
        return False

    def bid_item(self, price):
        # print('bid item , price : ', price)
        self.public_moves.get_screen_shot()
        current_bid_price_image = self.__get_current_bid_price()
        try:
            current_bid_price = self.public_moves.get_screen_text(
                current_bid_price_image, convert=False, convert_type=2)[:-1].replace(',', '').replace('.', '')
            current_bid_price = str(get_round_price(current_bid_price))
        except:
            try:
                current_bid_price = self.public_moves.get_screen_text(
                    current_bid_price_image,
                    config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789',
                    convert=False, convert_type=2)[:-1].replace(',', '').replace('.', '')
                current_bid_price = str(get_round_price(current_bid_price))
            except:
                current_bid_price = 0
                # new_print(self.fifa_account, 'cant read current_bid_price ', current_bid_price,
                #           'trace : ', traceback.format_exc())
        # new_print(self.fifa_account, 'current_bid_price : ', current_bid_price, 'price : ', price)
        if get_next_price_grade(int(current_bid_price)) >= int(price):
            return 'already bided'
        self.public_moves.ps4_buttons.cross(sleep_after=.5)
        self.public_moves.get_screen_shot()
        if self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/bid_sign.png'),
                'screen_shot_tmp.jpg'):
            # print('bid sign found')
            bid_set_price_res = self.bid_set_price(price=price)
            if bid_set_price_res == 'higher price':
                self.public_moves.ps4_buttons.circle()
                time.sleep(.5)
                return 'higher price'
            if bid_set_price_res == 'can not set price':
                return 'can not set price'
            if not bid_set_price_res:
                return False
            self.public_moves.ps4_buttons.cross(sleep_after=.5)
            self.public_moves.ps4_buttons.up(sleep_after=.2)
            # time.sleep(0.5)
            self.public_moves.ps4_buttons.cross(sleep_after=.7)
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/listing_expired.png'),
                    'screen_shot_tmp.jpg'):
                self.public_moves.ps4_buttons.cross()
                time.sleep(1)
                self.public_moves.ps4_buttons.circle()
                time.sleep(1)
                return 'transfer expired'
            elif self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/bid_market_error.png'),
                    'screen_shot_tmp.jpg'):
                time.sleep(1)
                self.public_moves.ps4_buttons.cross()
                time.sleep(1)
                self.public_moves.ps4_buttons.circle()
                time.sleep(1)
                return 'unassign full'
            return True
        else:
            bid_sign_count = 0
            while True:
                if bid_sign_count > 5:
                    self.public_moves.get_screen_shot()
                    if self.public_moves.has_image(os.path.join(
                            BASE_DIR,
                            f'utils/{self.fifa_account.platform}_controls/bid_sign_deactive.png'),
                            'screen_shot_tmp.jpg'):
                        self.public_moves.ps4_buttons.circle()
                        time.sleep(1)
                        # print('low credit 2')
                        return 'low credit'
                    else:
                        return 'miss way'
                self.public_moves.get_screen_shot()
                if not self.public_moves.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/bid_sign.png'),
                        'screen_shot_tmp.jpg'):
                    # print('can not find bid sign')
                    self.public_moves.ps4_buttons.down()
                    time.sleep(1)
                else:
                    # print('bid item again : ', price)
                    return self.bid_item(price=price)
                bid_sign_count += 1

    def bid_set_price(self, price):
        inside_set = False
        count = 0
        while True:
            if count > 20:
                new_print(self.fifa_account, 'cant set price for this one 2')
                self.public_moves.ps4_buttons.circle()
                self.public_moves.go_to_state('transfers', 'home_main')
                return 'can not set price'
                # raise Exception('cant set price for this one error')

            try:
                count += 1
                self.public_moves.get_screen_shot()
                bid_price_image = self.__get_bid_price()
                # new_print(self.fifa_account, 'need to get price from picture')
                try:
                    # new_print(self.fifa_account, 'reading start price')
                    default_number = self.public_moves.get_screen_text(
                        bid_price_image, convert=True, convert_type=2)[:-1].replace(',', '').replace('.', '')
                    default_number = str(get_round_price(default_number))
                except:
                    try:
                        # new_print(self.fifa_account, 'reading start price step 2')
                        default_number = self.public_moves.get_screen_text(
                            bid_price_image,
                            config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789',
                            convert=True, convert_type=2)[:-1].replace(',', '').replace('.', '')
                        default_number = str(get_round_price(default_number))
                    except:
                        return False
                if str(price) == default_number:
                    break
                if int(default_number) > int(price):
                    return 'higher price'
                if count % 5 == 0:
                    new_print(self.fifa_account, 'change default number to some thing else to pass the bug')
                    default_number = str(int(default_number) * 2)
                default_number = ((8 - len(default_number)) * '0') + default_number

                self.public_moves.transfer_list_utils.set_price_with_l_and_r(int(default_number), int(price), use_r1_l1=False)
                return True
            except:
                new_print(self.fifa_account, 'error 105 : ', traceback.format_exc())
                if inside_set:
                    self.public_moves.ps4_buttons.cross()
                time.sleep(2)
        return True

    def __get_bid_price(self):
        result_image_name = 'bid_price_tmp.jpg'
        start_price = self.public_moves.get_image_position(
            os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/bid_sign.png'),
            'screen_shot_tmp.jpg')
        top_left = start_price.get('top_right')
        start_price_width = start_price.get('width')
        start_price_height = start_price.get('height')
        img = cv2.imread("screen_shot_tmp.jpg")

        crop_player_name = img[top_left[1]:top_left[1] + start_price_height,
                           # top_left[0]+ (start_price_width * 10):top_left[0] + (start_price_width * 20)]
                           1550:1750]
        # new_print(self.fifa_account, 'get start price crop codes 2 : ',
        #           [top_left[1], top_left[1] + start_price_height,
        #            top_left[0] + (start_price_width * 10), top_left[0] + (start_price_width * 20)])
        crop_player_name = cv2.cvtColor(crop_player_name, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(result_image_name, crop_player_name)
        return result_image_name

    def get_current_bid_price_test(self):
        return self.__get_current_bid_price()

    def __get_current_bid_price(self):
        result_image_name = 'current_bid_price_tmp.jpg'
        start_price = self.public_moves.get_image_position(
            os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/current_bid_sign.png'),
            'screen_shot_tmp.jpg')
        top_left = start_price.get('top_right')
        # start_price_width = start_price.get('width')
        start_price_height = start_price.get('height')
        img = cv2.imread("screen_shot_tmp.jpg")

        crop_player_name = img[top_left[1]:top_left[1] + start_price_height,
                           # top_left[0]+ (start_price_width * 10):top_left[0] + (start_price_width * 20)]
                           1000:1250]
        crop_player_name = cv2.cvtColor(crop_player_name, cv2.COLOR_BGR2GRAY)
        cv2.imwrite(result_image_name, crop_player_name)
        return result_image_name

    def selling_mode(self, sell_price, quality=None, relist_all=False):
        new_print(self.fifa_account, 'start selling mode , sell price : ', sell_price,
                  ' must relist all : ', relist_all)
        set_sub_log(self.sbc_worker, 'selling items in console start')
        self.public_moves.go_to_state('transfers', 'transfer_list')
        sell_result = self.sell_transfer_list_items(buy_now_price=str(sell_price), relist_all=relist_all)
        set_sub_log(self.sbc_worker, 'selling items in console end')
        if sell_result == 'transfer list empty':
            # ConsoleTradeOneCard.objects.filter(fifa_account=self.fifa_account).update(deleted=True)
            return 'transfer list empty'

    def extract_sell_bid_price(self, quality, zero_price=150, try_counter=0):
        self.public_moves.go_to_state('transfer_market', 'search_players')
        need_reset_filter = True
        if need_reset_filter:
            self.public_moves.ps4_buttons.r3()
            time.sleep(1)
            if quality:
                new_print(self.fifa_account, 'search player find quality',
                          f'{quality}')
                self.public_moves.ps4_buttons.right(sleep_after=.5)
                self.public_moves.ps4_buttons.cross()
                time.sleep(1)
                self.public_moves.transfer_list_utils.find_quality(f'{quality}')
                time.sleep(1)
                if not self.public_moves.transfer_list_utils.check_selected_quality(quality):
                    return self.extract_sell_bid_price(quality=quality, zero_price=zero_price,
                                                       try_counter=try_counter + 1)
                self.public_moves.ps4_buttons.left(sleep_after=.2)
                self.public_moves.ps4_buttons.down(sleep_after=.5)
        self.public_moves.ps4_buttons.square()
        time.sleep(0.5)
        self.public_moves.ps4_buttons.cross()
        time.sleep(1)
        search_price_res = self.public_moves.search_player_price(
            price=zero_price, price_type='max_buy', default_price=150)
        if search_price_res == 'can not find price':
            self.public_moves.ps4_buttons.circle()
            time.sleep(1)
            self.public_moves.ps4_buttons.circle()
            time.sleep(1)
            return self.extract_sell_bid_price(quality=quality, zero_price=zero_price, try_counter=try_counter + 1)
        time.sleep(0.5)
        self.public_moves.ps4_buttons.circle()
        time.sleep(0.5)
        self.public_moves.ps4_buttons.up(sleep_after=0.5)
        self.public_moves.ps4_buttons.triangle()
        time.sleep(1)
        wait_result = self.public_moves.wait_for_image(os.path.join(
            BASE_DIR,
            f'utils/{self.fifa_account.platform}_controls/transfer_market_no_search_result.png'),
            wait_time=15,
            special='live_search_results.png')
        if wait_result is False:
            self.public_moves.ps4_buttons.cross(sleep_after=1)
            return self.extract_sell_bid_price(quality=quality, zero_price=get_next_price_grade(zero_price),
                                               try_counter=try_counter)
        if not self.public_moves.has_search_result():
            self.public_moves.ps4_buttons.cross(sleep_after=1)
            return self.extract_sell_bid_price(quality=quality, zero_price=get_next_price_grade(zero_price),
                                               try_counter=try_counter)
        remaining_time = 60 * 60
        for num in range(10):
            try:
                remaining_time = self.public_moves.transfer_list_utils.get_remaining_time()
                if remaining_time:
                    break
                time.sleep(1)
            except:
                # print(traceback.format_exc())
                time.sleep(.5)
                continue
            time.sleep(5)
        if remaining_time < 60 * 10:
            g_p_p = get_previous_price_grade
            return g_p_p(zero_price), g_p_p(g_p_p(g_p_p(zero_price)))
        return self.extract_sell_bid_price(quality=quality, zero_price=get_next_price_grade(zero_price),
                                           try_counter=try_counter)

    def web_sell_items(self):
        set_sub_log(self.sbc_worker, 'web_sell_items start')
        login_status = logout_login(self, self.sbc_worker, self.fifa_account)
        if login_status.get('status_bool') is False:
            new_print(self.fifa_account, 'login failed : ', login_status)
            if login_status.get('reason') == 'login failed':
                set_sbc_status(self.sbc_worker, 'login failed')
            else:
                set_sbc_status(self.sbc_worker, str(login_status.get('reason')))
            time.sleep(300)
            raise Exception('login failed')
        # if login_status and str(login_status).startswith('Traceback'):
        #     set_sbc_status(self.sbc_worker, 'login failed')
        #     self.fifa_account.refresh_from_db()
        #     # self.fifa_account.stop_for_update_game = True
        #     self.fifa_account.save()
        #     time.sleep(30 * 60)
        #     raise Exception(str('login failed'))
        # if login_status in ['chromedriver needed', 'chromedriver update needed', 'console login', 'problem in login']:
        #     set_sbc_status(self.sbc_worker, login_status)
        #     self.fifa_account.refresh_from_db()
        #     # self.fifa_account.stop_for_update_game = True
        #     self.fifa_account.save()
        #     time.sleep(30 * 60)
        #     raise Exception(str(login_status))
        trade_pile_json = get_trade_pile(self.fifa_account, self.se, self.main_dic).json()
        trade_pile_items = trade_pile_json['auctionInfo']
        for item_data in trade_pile_items:
            item_min_price = item_data['itemData'].get('marketDataMinPrice', 0)
            item_buy_now_price = item_data.get('buyNowPrice', 0)
            item_bid_price = item_data.get('startingBid', -1)
            # last_sale_price = item_data['itemData'].get('lastSalePrice', 0)
            if (item_data.get('tradeState', '') == 'expired' and
                    (int(item_min_price) == get_previous_price_grade(int(item_buy_now_price)) or
                     item_min_price == item_bid_price) and
                    self.fifa_account.run_console_invest_trade_one):
                data_4 = {"itemData": [{"id": item_data['itemData']['id'], "pile": "club"}]}
                move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_4), 0)
                new_print(self.fifa_account,
                          'before sell items , send expired items to club, result : ', move_result.text)

        sell_items(self, self.sbc_worker, self.fifa_account)
        set_sub_log(self.sbc_worker, 'web_sell_items end')
        if len(trade_pile_items) <= 0:
            return 'transfer list empty'

    def web_check_transfer_list_empty(self):
        set_sub_log(self.sbc_worker, 'web_check_transfer_list_empty start')
        new_print(self.fifa_account, 'web_check_transfer_list_empty start')
        login_status = logout_login(self, self.sbc_worker, self.fifa_account)
        if login_status.get('status_bool') is False:
            new_print(self.fifa_account, 'login failed : ', login_status)
            if login_status.get('reason') == 'login failed':
                set_sbc_status(self.sbc_worker, 'login failed')
            else:
                set_sbc_status(self.sbc_worker, str(login_status.get('reason')))
            time.sleep(300)
            raise Exception('login failed')
        # if login_status and str(login_status).startswith('Traceback'):
        #     set_sbc_status(self.sbc_worker, 'login failed')
        #     # self.fifa_account.refresh_from_db()
        #     # self.fifa_account.stop_for_update_game = True
        #     # self.fifa_account.save()
        #     time.sleep(30 * 60)
        #     raise Exception(str('login failed'))
        # if login_status in ['chromedriver needed', 'chromedriver update needed', 'console login', 'problem in login']:
        #     set_sbc_status(self.sbc_worker, login_status)
        #     # self.fifa_account.refresh_from_db()
        #     # self.fifa_account.stop_for_update_game = True
        #     # self.fifa_account.save()
        #     time.sleep(30 * 60)
        #     raise Exception(str(login_status))
        resp = get_trade_pile(self.fifa_account, self.se, self.main_dic)
        try:
            save_sold_items(self.fifa_account, resp.json())
        except:
            new_print(self.fifa_account, 'cant save sold items : ', traceback.format_exc())
        delete_sold_items(self.se, self.main_dic['header'])
        # self.update_credit()
        try:
            json_resp = resp.json()
            trades = []
            for rrmt in json_resp['auctionInfo']:
                if rrmt.get('tradeState') != 'closed':
                    trades.append(rrmt)
            set_sub_log(self.sbc_worker, f'web_check_transfer_list_empty end , trades : {len(trades)}')
            new_print(self.fifa_account, f'web_check_transfer_list_empty end , trades : {len(trades)}')
            if len(trades) < 1:
                return 'transfer list empty'
        except:
            new_print(self.fifa_account, 'exception in get trade pile : ', traceback.format_exc())

    # def console_check_transfer_list_empty(self):
    #     new_print(self.fifa_account, 'check transfer list empty')
    #     self.public_moves.go_to_state('transfers', 'transfer_list')
    #     time.sleep(5)
    #     # self.public_moves.ps4_buttons.l2()
    #     self.public_moves.ps4_buttons.r2()
    #     time.sleep(5)
    #     self.public_moves.get_screen_shot()
    #     if self.public_moves.has_image(os.path.join(
    #             BASE_DIR,
    #             f'utils/{self.fifa_account.platform}_controls/transfer_list_empty.png'),
    #             'screen_shot_tmp.jpg'
    #     ) or self.public_moves.has_image(os.path.join(
    #         BASE_DIR,
    #         f'utils/{self.fifa_account.platform}_controls/transfer_list_empty2.png'),
    #         'screen_shot_tmp.jpg'
    #         # ) or self.public_moves.has_image(os.path.join(
    #         #     BASE_DIR,
    #         #     f'utils/{self.fifa_account.platform}_controls/transfer_list_empty3.png'),
    #         #     'screen_shot_tmp.jpg'
    #     ):
    #         new_print(self.fifa_account, 'transfer list empty')
    #         return 'transfer list empty'

    def sell_transfer_list_items(self, buy_now_price, relist_all=False):
        new_print(self.fifa_account, 'searching transfer list items : ', buy_now_price, ' relist all : ', relist_all)
        # check_transfer_list = self.console_check_transfer_list_empty()
        # if check_transfer_list == 'transfer list empty':
        #     return 'transfer list empty'
        # if relist_all:
        #     new_print(self.fifa_account, 'relist items')
        #     self.public_moves.ps4_buttons.r2()
        #     time.sleep(5)
        #     self.public_moves.ps4_buttons.r2()
        #     time.sleep(5)
        #     self.public_moves.get_screen_shot()
        #     if self.public_moves.has_image(os.path.join(
        #             BASE_DIR,
        #             f'utils/{self.fifa_account.platform}_controls/relist_all_message.png'),
        #             'screen_shot_tmp.jpg'):
        #         self.public_moves.ps4_buttons.up()
        #         time.sleep(5)
        #         self.public_moves.ps4_buttons.cross()
        #         time.sleep(10)
        #         for nnn in range(10):
        #             self.public_moves.ps4_buttons.r1()
        #             time.sleep(2)
        one_more_chance = 0
        relisted_success = False
        for i in range(200):
            self.public_moves.get_screen_shot()
            # todo : relist all has bug. remove bellow after ea fix it.
            if i % 10 == 0 and relist_all and not relisted_success:
                new_print(self.fifa_account, 'relist items. try again , i : ', i)
                # self.public_moves.ps4_buttons.r2()
                # time.sleep(5)
                self.public_moves.ps4_buttons.right(sleep_after=.5)
                self.public_moves.ps4_buttons.r2()
                time.sleep(5)
                self.public_moves.get_screen_shot()
                if self.public_moves.has_image(os.path.join(
                        BASE_DIR,
                        f'utils/{self.fifa_account.platform}_controls/relist_all_message.png'),
                        'screen_shot_tmp.jpg'):
                    relisted_success = True
                    self.public_moves.ps4_buttons.up()
                    time.sleep(5)
                    self.public_moves.ps4_buttons.cross()
                    time.sleep(10)
                    for nnn in range(10):
                        self.public_moves.ps4_buttons.r1()
                        time.sleep(2)
                continue
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/compare_price_icon.png'),
                    'screen_shot_tmp.jpg') or self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/compare_price_icon_2.png'),
                    'screen_shot_tmp.jpg'):

                if not self.list_on_transfer_market(start_price=str(get_previous_price_grade(buy_now_price)),
                                                    buy_now_price=str(buy_now_price)):
                    self.public_moves.errors()
                    self.public_moves.go_to_state('ps4_main', 'transfer_list')
                continue
            self.public_moves.get_screen_shot()
            self.get_transfer_list_cards_position()
            self.public_moves.ps4_buttons.right(sleep_after=.5)
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image('transfer_list_cards_tmp.jpg', 'screen_shot_tmp.jpg', threshold=.99):
                if one_more_chance > 10:
                    new_print(self.fifa_account, 'end of list. no any cards found.')
                    return True
                one_more_chance += 1
                time.sleep(.5)
            else:
                one_more_chance = 0


    def list_on_transfer_market(self, start_price, buy_now_price):
        new_print(self.fifa_account, 'list item on transfer market : ', start_price, buy_now_price)
        self.public_moves.ps4_buttons.cross()
        # time.sleep(.5)
        self.__set_price(start_price)
        self.public_moves.ps4_buttons.down(sleep_after=.4)
        self.public_moves.ps4_buttons.l2()
        # for find list_on_transfer button faster
        self.public_moves.ps4_buttons.down()
        self.public_moves.ps4_buttons.down()

        count = 0
        while True:
            # new_print(self.fifa_account, 'try to find list on transfer the second')
            count += 1
            if count == 10:
                self.public_moves.ps4_buttons.circle()
            if count > 20:
                return False
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    # todo : ps and xbox360 image added. add xboxs image
                    f'utils/{self.fifa_account.platform}_controls/list_on_transfer_market_the_first.png'),
                    'screen_shot_tmp.jpg'
            ):
                break
            # if self.public_moves.has_image(os.path.join(
            #         BASE_DIR,
            #         f'utils/{self.fifa_account.platform}_controls/control_set_price_sign.png'),
            #         'screen_shot_tmp.jpg'):
            #     self.public_moves.ps4_buttons.circle()
            #     time.sleep(0.5)
            self.public_moves.ps4_buttons.down(sleep_after=.5)
        # time.sleep(.5)
        self.public_moves.ps4_buttons.cross()
        time.sleep(.5)
        self.public_moves.wait_for_image(os.path.join(
            BASE_DIR,
            f'utils/{self.fifa_account.platform}_controls/item_transfer_sucess.png'))
        self.public_moves.ps4_buttons.cross(sleep_after=.5)
        return True

    def __set_price(self, price):

        count = 0
        while True:
            if count > 20:
                new_print(self.fifa_account, 'cant set price for this one 3')
                self.public_moves.ps4_buttons.circle()
                self.public_moves.go_to_state('transfers', 'home_main')
                raise Exception('cant set price for this one error')

            try:
                count += 1
                time.sleep(.5)
                self.public_moves.get_screen_shot()
                self.__get_start_price()
                # new_print(self.fifa_account, 'need to get price from picture')
                try:
                    # new_print(self.fifa_account, 'reading start price')
                    default_number = self.public_moves.get_screen_text(
                        'start_price_tmp_2.jpg', convert=True, convert_type=2)[:-1].replace(',', '').replace('.', '')
                    default_number = str(get_round_price(default_number))
                except:
                    try:
                        # new_print(self.fifa_account, 'reading start price step 2')
                        default_number = self.public_moves.get_screen_text(
                            'start_price_tmp_2.jpg',
                            config='--psm 10 --oem 3 -c tessedit_char_whitelist=0123456789',
                            convert=True, convert_type=2)[:-1].replace(',', '').replace('.', '')
                        default_number = str(get_round_price(default_number))
                    except:
                        return False
                if str(price) == default_number:
                    break
                # if int(default_number) > int(price):
                #     return 'higher price'
                if count % 5 == 0:
                    new_print(self.fifa_account, 'change default number to some thing else to pass the bug')
                    default_number = str(int(default_number) * 2)
                    # count = 0
                default_number = ((8 - len(default_number)) * '0') + default_number
                new_print(self.fifa_account, 'default number = ', default_number)
                # time.sleep(0.5)
                self.public_moves.transfer_list_utils.set_price_with_l_and_r(int(default_number), int(price))
                return True
            except:
                new_print(self.fifa_account, 'error 104 : ', traceback.format_exc())
                time.sleep(2)
        return True

    def __get_start_price(self):

        # start_price = self.public_moves.get_image_position(
        #     os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/list_transfer_directions.png'),
        #     'screen_shot_tmp.jpg')
        # top_left = start_price.get('top_right')
        # start_price_width = start_price.get('width')
        # start_price_height = start_price.get('height')
        # img = cv2.imread("screen_shot_tmp.jpg")
        # crop_player_name = img[top_left[1]:top_left[1] + start_price_height,
        #                    top_left[0]:top_left[0] + (start_price_width * 3)]
        # new_print(self.fifa_account, 'get start price crop codes 2 : ',
        #           [top_left[1], top_left[1] + start_price_height,
        #            top_left[0], top_left[0] + (start_price_width * 3)])
        img = cv2.imread("screen_shot_tmp.jpg")
        crop_player_name = img[330:370, 1440:1650]
        crop_player_name = cv2.cvtColor(crop_player_name, cv2.COLOR_BGR2GRAY)
        cv2.imwrite('start_price_tmp_2.jpg', crop_player_name)

    def unassign_bought_items(self):
        set_sub_log(self.sbc_worker, 'manage unassign_bought_items start ...')
        self.public_moves.go_to_state('transfers', 'transfer_targets')
        new_print(self.fifa_account, 'try to empty transfer targets , check for error once.')
        time.sleep(5)
        self.public_moves.errors()
        # if self.public_moves.has_image(os.path.join(
        #         BASE_DIR,
        #         f'utils/{self.fifa_account.platform}_ea_messages/transfer_target.png'),
        #         'screen_shot_tmp.jpg'):
        #     self.public_moves.ps4_buttons.cross()
        #     time.sleep(10)
        self.public_moves.ps4_buttons.r2()
        time.sleep(2)
        # if self.public_moves.just_find_state() == 'transfer_targets':
        # self.public_moves.ps4_buttons.l2()
        # time.sleep(5)
        if self.public_moves.wait_for_images(
                [os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/after_buy_in_list.png'),
                 os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_controls/transfers_keep_items.png')],
                wait_time=3):
            new_print(self.fifa_account, 'keep items found , exit and sort later')
            self.public_moves.ps4_buttons.circle()
            time.sleep(3)
            self.public_moves.ps4_buttons.up(sleep_after=1)
            self.public_moves.ps4_buttons.cross()
            time.sleep(10)
            self.public_moves.go_to_state('transfers', 'transfer_targets')
            self.public_moves.ps4_buttons.r2()
            time.sleep(1)
            self.public_moves.ps4_buttons.r2()
            time.sleep(5)
            self.public_moves.ps4_buttons.circle()
        else:
            new_print(self.fifa_account, 'keep items not found , maybe target is empty')
            self.public_moves.go_to_state('transfers', 'transfer_targets')
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(os.path.join(
                    BASE_DIR,
                    f'utils/{self.fifa_account.platform}_controls/transfer_targets_empty.png'),
                    'screen_shot_tmp.jpg'):
                self.public_moves.ps4_buttons.circle()
                return 'transfer target empty'
            else:
                self.public_moves.ps4_buttons.r2()
            self.public_moves.ps4_buttons.circle()

    def manage_bought_items(self, bought_price, quality_name):
        set_sub_log(self.sbc_worker, 'manage_bought_items start')
        new_print(self.fifa_account, 'manage_bought_items start')
        login_status = logout_login(self, self.sbc_worker, self.fifa_account)
        if login_status.get('status_bool') is False:
            new_print(self.fifa_account, 'login failed : ', login_status)
            if login_status.get('reason') == 'login failed':
                set_sbc_status(self.sbc_worker, 'login failed')
            else:
                set_sbc_status(self.sbc_worker, str(login_status.get('reason')))
            time.sleep(300)
            raise Exception('login failed')
        # if login_status and str(login_status).startswith('Traceback'):
        #     set_sbc_status(self.sbc_worker, 'login failed')
        #     # self.fifa_account.refresh_from_db()
        #     # self.fifa_account.stop_for_update_game = True
        #     # self.fifa_account.save()
        #     time.sleep(30 * 60)
        #     raise Exception(str('login failed'))
        # if login_status in ['chromedriver needed', 'chromedriver update needed', 'console login', 'problem in login']:
        #     set_sbc_status(self.sbc_worker, login_status)
        #     # self.fifa_account.refresh_from_db()
        #     # self.fifa_account.stop_for_update_game = True
        #     # self.fifa_account.save()
        #     time.sleep(30 * 60)
        #     raise Exception(str(login_status))
        # todo : remove bellow after test 2018 done.
        if self.fifa_account.console and self.fifa_account.console.name in list(range(2000, 2018)):
            try:
                resp = self.se.get("https://icanhazip.com/", timeout=120)
                new_print(self.fifa_account, 'test 2018 resp : ', resp.text, ' proxies : ', self.se.proxies)
            except:
                new_print(self.fifa_account, 'exception in test 2018: ', traceback.format_exc())
        trade_pile_json = get_trade_pile(self.fifa_account, self.se, self.main_dic).json()
        trade_pile_items = trade_pile_json['auctionInfo']
        sold_items_count = 0
        for item_data in trade_pile_items:
            if item_data.get('tradeState', '') == 'closed':
                sold_items_count += 1
        time.sleep(2)
        try:
            save_sold_items(self.fifa_account, trade_pile_json)
        except:
            new_print(self.fifa_account, 'cant save sold items : ', traceback.format_exc())
        delete_sold_items(self.se, self.main_dic['header'])
        # self.update_credit()
        # trade_pile_items = get_trade_pile(self.fifa_account, self.se, self.main_dic).json()['auctionInfo']
        # for trade in trade_pile_items:
        #     club_id = trade['itemData']['id']
        #     asset_id = trade['itemData']['assetId']
        #     resource_id = trade['itemData'].get('resourceId', 0)
        #     print()
        # sold_items_count = 0
        self.trade_history.refresh_from_db()
        self.trade_history.bought_items_managed = True
        self.trade_history.save()
        break_and_return_message = None
        for iiii in range(5):
            move_transfer_results = []
            move_to_club_results = []
            win_results_1 = []

            unassigned_items_json = self.get_items().json()
            unassigned_items = unassigned_items_json['itemData']
            # unassigned_player_items = [iii for iii in unassigned_items if iii['itemType'] == 'player']
            trade_pile_json = get_trade_pile(self.fifa_account, self.se, self.main_dic).json()
            trade_pile_items = trade_pile_json['auctionInfo']
            duplicate_transfer_list_ids = [tll['itemId'] for tll in trade_pile_json.get('duplicateItemIdList', [])]
            if self.fifa_account.console_trade_one_quality == 'position_modifier':
                duplicate_transfer_list_ids = []
            duplicate_unassigned_list_ids = [tll['itemId'] for tll in
                                             unassigned_items_json.get('duplicateItemIdList', [])]
            cant_move_items_1 = []
            quality_data = console_trade_quality_dict[quality_name]
            for dddti in unassigned_items:
                item_id = dddti['id']
                item_rating = dddti['rating']
                item_rare_flag = dddti['rareflag']
                item_asset_id = dddti['assetId']
                item_last_sale_price = dddti.get('lastSalePrice', 0)
                item_type = dddti.get('itemType')
                discard_value = dddti.get('discardValue')
                if dddti.get('untradeable') is False:
                    try:
                        save_selling_items(
                            self.fifa_account,
                            item_id=item_id,
                            buy_price=item_last_sale_price or 0,
                            rating=item_rating or 0,
                            rare=item_rare_flag or 0,
                            asset_id=item_asset_id or 0,
                            item_type=item_type,
                            discard_value=discard_value or 0,
                        )
                    except:
                        new_print(self.fifa_account, 'save selling items error : ', traceback.format_exc())
            if ((self.fifa_account.stop_console_trade_one_for_other_bots or
                 len(duplicate_transfer_list_ids) > 40)
                    # len(duplicate_transfer_list_ids) < 1 and
                    # len(unassigned_items) < 1
            ):
                new_print(self.fifa_account, 'duplicate items : ', len(duplicate_transfer_list_ids),
                          'unsigned items : ', len(unassigned_items))
                not_quality_items_price = []
                for nnttu in trade_pile_items:
                    club_id = nnttu['itemData']['id']
                    rating = nnttu['itemData']['rating']
                    rare_flag = nnttu['itemData']['rareflag']
                    last_sale_price = nnttu['itemData'].get('lastSalePrice', 0)
                    market_min_price = nnttu['itemData'].get('marketDataMinPrice', 2000)
                    if (
                            self.fifa_account.console_trade_one_quality in [
                        'bronze1', 'silver0', 'silver1', 'gold0', 'gold1'] and
                            nnttu['itemData']['itemType'] == 'player' and
                            last_sale_price and
                            quality_data[0] <= rating <= quality_data[1] and
                            rare_flag == quality_data[2] and
                            1 < last_sale_price < 1000
                    # ) or (
                    #         self.fifa_account.console_trade_one_quality == 'position_modifier' and
                    #         nnttu['itemData']['itemType'] == 'training' and
                    #         nnttu['itemData']['resourceId'] == 5003181
                    ):
                        data_6 = {"itemData": [{"id": club_id, "pile": "club"}]}
                        move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_6), 0)
                        try:
                            if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                pass
                                # sold_items_count -= 1
                            else:
                                cant_move_items_1.append(club_id)
                                new_print(self.fifa_account, 'error on move 6 : ', move_result.text)
                        except:
                            cant_move_items_1.append(club_id)
                            new_print(self.fifa_account, 'move result 6 error : ', move_result.text)
                        time.sleep(2)
                    # elif last_sale_price > 1000 or (last_sale_price == 0 and market_min_price > 1000) or sum(not_quality_items_price) > 2000:
                    elif last_sale_price > 1000 or (last_sale_price == 0 and market_min_price > 1000):
                        new_print(self.fifa_account, 'in trade found item that has more than 5000 price . stop bot. ',
                                  nnttu['itemData'], ' not qulity list : ', not_quality_items_price)
                        set_sbc_status(self.sbc_worker, 'console trade found more than 5000 card price')
                        time.sleep(10)
                        self.fix_conflict_transfer_items()
                        time.sleep(100)
                        raise Exception('console trade found more than 5000 card price')
                # if len(cant_move_items_1) < 5:
                #     for nntte in cant_move_items_1:
                #         try:
                #             self.se.delete(f'{fifa_23_address}/item/%s' % nntte,
                #                            headers=self.main_dic['header'])
                #         except:
                #             new_print(self.fifa_account, 'can no quick sell item , ', nntte)
                trade_pile_json_3 = get_trade_pile(self.fifa_account, self.se, self.main_dic).json()
                trade_pile_items_3 = trade_pile_json_3['auctionInfo']
                duplicate_transfer_list_ids_3 = [tll['itemId'] for
                                                 tll in trade_pile_json.get('duplicateItemIdList', [])]
                if self.fifa_account.console_trade_one_quality == 'position_modifier':
                    duplicate_transfer_list_ids_3 = []
                # new_print(self.fifa_account, 'stop console trade one for other bots')
                # if len(trade_pile_items_3) > 0:
                #     new_print(self.fifa_account, 'can`t stop console trade , items in transfer list : ',
                #               len(trade_pile_items_3))
                #     set_sbc_status(self.sbc_worker, 'stop trade can`t work.')
                #     time.sleep(600)
                self.trade_history.refresh_from_db()
                self.trade_history.sold_items_count += sold_items_count
                self.trade_history.transfer_list_items_count = len(trade_pile_items_3)
                self.trade_history.transfer_list_duplicate_items_count = len(duplicate_transfer_list_ids_3)
                self.trade_history.save()
                club_players = self.get_bronze_club_players(
                    tradeable=True,
                    players_list=self.special_squad_players_build,
                    get_pages=5
                )
                club_consumables = self.get_club_consumables(resource_id=5003181)
                self.save_club_player_items(club_players, club_consumables)
                return 'list duplicate with low price'
                # return 'stop console trade one for other bots'

            need_move_to_transfer_count = 95 - len(trade_pile_items)
            if need_move_to_transfer_count < 0:
                moved_items_2 = []
                new_print(self.fifa_account, 'need move from transfer list to club : ',
                          abs(need_move_to_transfer_count))
                for mttm in range(abs(need_move_to_transfer_count)):
                    for ntts in trade_pile_items:
                        if (ntts['itemData']['id'] not in duplicate_transfer_list_ids and
                                not ntts['itemData']['id'] in moved_items_2):
                            moved_items_2.append(ntts['itemData']['id'])
                            data_4 = {"itemData": [{"id": ntts['itemData']['id'], "pile": "club"}]}
                            move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_4), 0)
                            try:
                                if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                    move_to_club_results.append(move_result.text)
                                    # sold_items_count -= 1
                                else:
                                    new_print(self.fifa_account, 'error on move 4 : ', move_result.text)
                            except:
                                new_print(self.fifa_account, 'move result 4 error : ', move_result.text)
                            # new_print(self.fifa_account, 'move result 4 : ', move_result.text)
                            time.sleep(2)
                            break
            elif need_move_to_transfer_count > 0 and len(unassigned_items) > 0:
                moved_items_4 = []
                new_print(self.fifa_account, 'need move unassigned to transfer list : ', need_move_to_transfer_count,
                          ' unassigned items : ', len(unassigned_items))
                for nnttm in unassigned_items[:need_move_to_transfer_count]:
                    if nnttm['itemType'] == 'misc':
                        self.handle_misc_items(nnttm['id'])
                        time.sleep(2)
                        continue
                    club_id = nnttm['id']
                    last_sale_price = nnttm.get('lastSalePrice', 0)
                    rare_flag = nnttm['rareflag']
                    rating = nnttm['rating']
                    if (
                            self.fifa_account.console_trade_one_quality in [
                        'bronze1', 'silver0', 'silver1', 'gold0', 'gold1'] and
                            nnttm['itemType'] == 'player' and
                            last_sale_price and
                            quality_data[0] <= rating <= quality_data[1] and
                            rare_flag == quality_data[2] and
                            1 < last_sale_price < 2000 and
                            club_id not in moved_items_4
                    # ) or (
                    #         self.fifa_account.console_trade_one_quality == 'position_modifier' and
                    #         nnttm['itemType'] == 'training' and
                    #         nnttm['resourceId'] == 5003181 and
                    #         nnttm['untradeable'] == False
                    ):
                        moved_items_4.append(nnttm['id'])
                        data_1 = {"itemData": [{"id": nnttm['id'], "pile": "trade"}]}
                        move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_1), 0)
                        try:
                            if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                move_transfer_results.append(move_result.text)
                                win_results_1.append(move_result.text)
                                # sold_items_count += 1
                            else:
                                new_print(self.fifa_account, 'error on move 1 : ', move_result.text)
                        except:
                            new_print(self.fifa_account, 'move result 1 error : ', )
                        # new_print(self.fifa_account, 'move result 1 : ', move_result.text)
                        time.sleep(2)
                    else:
                        if nnttm.get('untradeable', False):
                            try:
                                new_print(self.fifa_account, 'untradable item found, remove it', nnttm)
                                self.se.delete(f'{fifa_23_address}/item/{nnttm["id"]}',
                                               headers=self.main_dic['header'])
                                duplicate_unassigned_list_ids.remove(nnttm)
                            except:
                                new_print(self.fifa_account, 'can no quick sell item 2 , ', nnttm,
                                          'exception : ', traceback.format_exc())
                        else:
                            new_print(self.fifa_account, 'item not in trade type , send it to club ', nnttm)
                            data_5 = {"itemData": [{"id": nnttm['id'], "pile": "club"}]}
                            move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_5), 0)
                            time.sleep(2)
                            # break

            moved_items_0 = []
            if len(trade_pile_items) >= 95:
                new_print(self.fifa_account, 'need move unassigned to club : ', len(unassigned_items))
                for nnttm in unassigned_items:
                    if nnttm['itemType'] == 'misc':
                        self.handle_misc_items(nnttm['id'])
                        time.sleep(2)
                        continue
                    if nnttm['id'] not in duplicate_unassigned_list_ids and not nnttm['id'] in moved_items_0:
                        moved_items_0.append(nnttm['id'])
                        data_1 = {"itemData": [{"id": nnttm['id'], "pile": "club"}]}
                        move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_1), 0)
                        try:
                            if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                move_to_club_results.append(move_result.text)
                                win_results_1.append(move_result.text)
                            else:
                                new_print(self.fifa_account, 'error on move 1 : ', move_result.text)
                        except:
                            new_print(self.fifa_account, 'move result 1 error : ', )
                        # new_print(self.fifa_account, 'move result 1 : ', move_result.text)
                        time.sleep(2)
            time.sleep(2)
            moved_items = []
            new_print(self.fifa_account, 'duplicate in unassigned , send to transfer list : ',
                      len(duplicate_unassigned_list_ids))
            for counter in range(len(duplicate_unassigned_list_ids)):
                for nmm in trade_pile_items:
                    if (nmm['itemData']['id'] not in duplicate_transfer_list_ids and
                            not nmm['itemData']['id'] in moved_items):
                        moved_items.append(nmm['itemData']['id'])
                        data_3 = {"itemData": [{"id": nmm['itemData']['id'], "pile": "club"}]}
                        move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_3), 0)
                        try:
                            if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                move_to_club_results.append(move_result.text)
                                # sold_items_count -= 1
                            else:
                                new_print(self.fifa_account, 'error on move 2 : ', move_result.text)
                        except:
                            new_print(self.fifa_account, 'move result 2 error : ', move_result.text)
                        # new_print(self.fifa_account, 'move result 2 : ', move_result.text)
                        time.sleep(2)
                        break
            time.sleep(2)
            new_print(self.fifa_account, 'duplicate unassigned items : ', len(duplicate_unassigned_list_ids))
            for dup_unass_item in duplicate_unassigned_list_ids:
                data_2 = {"itemData": [{"id": dup_unass_item, "pile": "trade"}]}
                move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_2), 0)
                try:
                    if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                        move_transfer_results.append(move_result.text)
                        win_results_1.append(move_result.text)
                        # sold_items_count += 1
                    else:
                        new_print(self.fifa_account, 'error on move 3 : ', move_result.text)
                except:
                    new_print(self.fifa_account, 'move result 3 error : ', move_result.text)
                # new_print(self.fifa_account, 'move result 3 : ', move_result.text)
                time.sleep(2)
            time.sleep(2)
            club_players = self.get_bronze_club_players(
                tradeable=True,
                players_list=self.special_squad_players_build,
                get_pages=5
            )
            club_consumables = self.get_club_consumables(resource_id=5003181)
            self.save_club_player_items(club_players, club_consumables)
            time.sleep(2)
            trade_pile_json = get_trade_pile(self.fifa_account, self.se, self.main_dic).json()
            trade_pile_items = trade_pile_json['auctionInfo']
            duplicate_transfer_list_ids = [tll['itemId'] for tll in trade_pile_json.get('duplicateItemIdList', [])]
            if self.fifa_account.console_trade_one_quality == 'position_modifier':
                duplicate_transfer_list_ids = []
            if len(trade_pile_items) < 95 and (
                    not self.fifa_account.console_trade_one_quality_new or
                    self.fifa_account.console_trade_one_quality == self.fifa_account.console_trade_one_quality_new):
                new_print(self.fifa_account, 'need move items from club to transfer list , ',
                          95 - len(trade_pile_items))

                moved_items_3 = []
                for counter_2 in range(95 - len(trade_pile_items)):
                    if self.fifa_account.console_trade_one_quality in [
                        'bronze1', 'silver0', 'silver1', 'gold0', 'gold1'
                    ]:
                        for nnntt in club_players:
                            asset_id = nnntt['assetId']
                            club_id = nnntt['id']
                            resource_id = nnntt.get('resourceId', 0)
                            last_sale_price = nnntt.get('lastSalePrice', 0)
                            rare_flag = nnntt['rareflag']
                            rating = nnntt['rating']
                            item_type = nnntt.get('itemType')
                            discard_value = nnntt.get('discardValue')
                            try:
                                save_selling_items(
                                    self.fifa_account,
                                    item_id=club_id,
                                    buy_price=last_sale_price or 0,
                                    rating=rating or 0,
                                    rare=rare_flag or 0,
                                    asset_id=asset_id or 0,
                                    item_type=item_type,
                                    discard_value=discard_value or 0,
                                )
                            except:
                                new_print(self.fifa_account, 'save selling items 2 error : ', traceback.format_exc())
                            if (nnntt['itemType'] == 'player' and
                                    last_sale_price and
                                    quality_data[0] <= rating <= quality_data[1] and
                                    rare_flag == quality_data[2] and
                                    1 < last_sale_price < 2000 and
                                    club_id not in moved_items_3):
                                moved_items_3.append(club_id)
                                data_5 = {"itemData": [{"id": club_id, "pile": "trade"}]}
                                move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_5), 0)
                                try:
                                    if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                        move_transfer_results.append(move_result.text)
                                        # sold_items_count += 1
                                        # pass
                                    else:
                                        new_print(self.fifa_account, 'error on move 5 : ', move_result.text)
                                except:
                                    new_print(self.fifa_account, 'move result 5 error : ', move_result.text)
                                time.sleep(2)
                                break
                    elif self.fifa_account.console_trade_one_quality == 'position_modifier':
                        if club_consumables:
                            resource_id_3 = club_consumables[0]['resourceId']
                            for nnntt in range(club_consumables[0]['count'] - club_consumables[0]['untradeableCount']):
                                moved_items_3.append(resource_id_3)
                                data_5 = {"itemData": [{"id": resource_id_3, "pile": "trade"}]}
                                move_result = put_consumable_for_sale(self.se, self.main_dic['header'], json.dumps(data_5))
                                try:
                                    if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                        move_transfer_results.append(move_result.text)
                                        # sold_items_count += 1
                                        # pass
                                    else:
                                        new_print(self.fifa_account, 'error on move 5 : ', move_result.text)
                                except:
                                    new_print(self.fifa_account, 'move result 5 error : ', move_result.text)
                                time.sleep(2)
                                break

            new_print(self.fifa_account,
                      f'manage_bought_items middle ,'
                      f' unassigned : {len(unassigned_items)} ,'
                      f' transfer list : {len(trade_pile_items)}',
                      f' duplicate transfer list : {len(duplicate_transfer_list_ids)}'
                      )
            if (self.fifa_account.console_trade_one_quality_new and
                    self.fifa_account.console_trade_one_quality_new != self.fifa_account.console_trade_one_quality):
                new_print(self.fifa_account, f'need to change quality  from {self.fifa_account.console_trade_one_quality} to {self.fifa_account.console_trade_one_quality_new}')
                moved_items_5 = []
                trade_pile_json_4 = get_trade_pile(self.fifa_account, self.se, self.main_dic).json()
                trade_pile_items_4 = trade_pile_json_4['auctionInfo']
                duplicate_transfer_list_ids_4 = [tll['itemId'] for tll in trade_pile_json.get('duplicateItemIdList', [])]
                if self.fifa_account.console_trade_one_quality == 'position_modifier':
                    duplicate_transfer_list_ids_4 = []
                if len(duplicate_transfer_list_ids_4) > 5 and self.trade_history.change_quality_list_try_count < 2:
                    for item_data_2 in trade_pile_items_4:
                        moved_items_5.append(item_data_2['itemData']['id'])
                        data_3 = {"itemData": [{"id": item_data_2['itemData']['id'], "pile": "club"}]}
                        move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_3), 0)
                        try:
                            if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                pass
                                # move_to_club_results.append(move_result.text)
                                # sold_items_count -= 1
                            else:
                                new_print(self.fifa_account, 'error on move 8 : ', move_result.text)
                        except:
                            new_print(self.fifa_account, 'move result 8 error : ', move_result.text)
                        time.sleep(2)
                    break_and_return_message = 'list duplicate with low price'
                else:
                    for item_data_2 in trade_pile_items_4:
                        club_id_3 = item_data_2['itemData']['id']
                        moved_items_5.append(item_data_2['itemData']['id'])
                        data_3 = {"itemData": [{"id": club_id_3, "pile": "club"}]}
                        move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_3), 0)
                        try:
                            if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                                pass
                                # move_to_club_results.append(move_result.text)
                                # sold_items_count -= 1
                            else:
                                new_print(self.fifa_account, 'error on move 8 : ',
                                          move_result.text, ' , will quick sell')
                                self.se.delete(f'{fifa_23_address}/item/{club_id_3}',
                                               headers=self.main_dic['header'])
                                save_quick_sold_item(self.fifa_account, item_id=club_id_3,
                                                     discard_value=item_data_2['itemData'].get('discardValue'))
                        except:
                            new_print(self.fifa_account, 'move result 8 error : ', move_result.text)
                        time.sleep(2)
                self.trade_history.refresh_from_db()
                self.trade_history.change_quality_list_try_count += 1
                self.trade_history.save()

            unassigned_items_json_2 = self.get_items().json()
            unassigned_items_2 = unassigned_items_json_2['itemData']
            trade_pile_json_2 = get_trade_pile(self.fifa_account, self.se, self.main_dic).json()
            trade_pile_items_2 = trade_pile_json_2['auctionInfo']
            duplicate_transfer_list_ids_2 = [tll['itemId'] for tll in trade_pile_json.get('duplicateItemIdList', [])]
            if self.fifa_account.console_trade_one_quality == 'position_modifier':
                duplicate_transfer_list_ids_2 = []

            # double check for get cards :
            not_quality_items_price = []
            for tttt in trade_pile_items_2:
                club_id_2 = tttt['itemData']['id']
                resource_id_2 = tttt['itemData']['resourceId']
                last_sale_price_2 = tttt['itemData'].get('lastSalePrice', 0)
                market_min_price = tttt['itemData'].get('marketDataMinPrice', 2000)
                rating_2 = tttt['itemData']['rating']
                rare_flag_2 = tttt['itemData']['rareflag']
                if self.fifa_account.console_trade_one_quality == 'position_modifier' and resource_id_2 == 5003181:
                    continue
                # if last_sale_price_2 > 1000 or (last_sale_price_2 == 0 and market_min_price > 1000) or sum(not_quality_items_price) > 2000:
                if last_sale_price_2 > 1000 or (last_sale_price_2 == 0 and market_min_price > 1000):
                    new_print(self.fifa_account, 'in trade found item that has more than 5000 price . stop bot. ',
                              tttt['itemData'] , ' not qulity list : ', not_quality_items_price)
                    set_sbc_status(self.sbc_worker, 'console trade found more than 5000 card price')
                    time.sleep(10)
                    self.fix_conflict_transfer_items()
                    self.public_moves.go_to_state('transfers', 'home_main')
                    time.sleep(100)
                    raise Exception('console trade found more than 5000 card price')
                elif not (quality_data[0] <= rating_2 <= quality_data[1] and rare_flag_2 == quality_data[2]):
                    data_2 = {"itemData": [{"id": club_id_2, "pile": "club"}]}
                    move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_2), 0)
                    new_print(self.fifa_account, 'item is not match with current quality , not quality list : ',
                              not_quality_items_price,
                              ' rating : ', rating_2, 'rare flag : ', rare_flag_2,
                              ' , move result : ', move_result.text)
                    not_quality_items_price.append(market_min_price)
            time.sleep(2)
            club_players_2 = self.get_bronze_club_players(
                tradeable=True,
                players_list=self.special_squad_players_build,
                get_pages=5
            )
            club_consumables_2 = self.get_club_consumables(resource_id=5003181)
            self.save_club_player_items(club_players_2, club_consumables_2)
            time.sleep(2)
            new_print(self.fifa_account, 'move_to_transfer_list_results : ', move_transfer_results)
            new_print(self.fifa_account, 'move to club list results : ', move_to_club_results)
            time.sleep(2)
            self.trade_history.refresh_from_db()
            # self.trade_history.win_count += len(move_transfer_results) + len(move_to_club_results)
            self.trade_history.win_count += len(win_results_1)
            self.trade_history.move_items_from_unassigned = timezone.localtime()
            self.trade_history.unassigned_full_need_sell_counter -= len(move_transfer_results)
            self.trade_history.current_credit = self.fifa_account.credit
            self.trade_history.unassigned_item_count = len(unassigned_items_2)
            self.trade_history.transfer_list_items_count = len(trade_pile_items_2)
            self.trade_history.transfer_list_duplicate_items_count = len(duplicate_transfer_list_ids_2)
            self.trade_history.sold_items_count += sold_items_count
            self.trade_history.save()
            text_1 = (f'manage_bought_items end ,'
                      f' unassigned : {len(unassigned_items_2)} ,'
                      f' transfer list : {len(trade_pile_items_2)} ,'
                      f' club players : {len(club_players_2)} ,'
                      f' cunsumables : {len(club_consumables_2)}')
            set_sub_log(self.sbc_worker, text_1)
            new_print(self.fifa_account, text_1)
            # # todo : maybe need remove below break
            # if 0 < len(unassigned_items) < 50:
            #     break
            # #
            if break_and_return_message:
                if len(unassigned_items_2) <= 0:
                    return break_and_return_message
                elif iiii < 1:
                    new_print(self.fifa_account, f'{len(unassigned_items_2)} unassigned items found , try again.')
                    continue
                else:
                    return break_and_return_message
            if len(unassigned_items_2) == 0 and len(trade_pile_items_2) == 0:
                return 'transfer list and unassigned empty'

            if (len(unassigned_items_2) == 0 and
                    len(trade_pile_items_2) <= 95 and
                    self.fifa_account.run_console_invest_trade_one):
                break

    def get_transfer_list_cards_position(self):
        # live_search = self.public_moves.get_image_position(os.path.join(
        #     BASE_DIR,
        #     f'utils/{self.fifa_account.platform}_controls/transfer_list.png'),
        #     'screen_shot_tmp.jpg')
        # top_left = live_search.get('bottom_left')
        # transfer_list_width = live_search.get('width')
        # bottom_right = [int(top_left[0] + transfer_list_width * 1.2), int(top_left[1] + transfer_list_width * 4.3)]
        # bottom_right = self.get_image_position(os.path.join(BASE_DIR, 'utils/controls/compare_price_icon.png'),
        #                                        'screen_shot_tmp.jpg').get('top_right')
        img = cv2.imread("screen_shot_tmp.jpg")
        # crop_player_name = img[top_left[0]:bottom_right[0],
        #                    top_left[1]:bottom_right[1]]
        crop_player_name = img[260:600, 150:1850]
        crop_player_name = cv2.cvtColor(crop_player_name, cv2.COLOR_BGR2GRAY)
        cv2.imwrite('transfer_list_cards_tmp.jpg', crop_player_name)

    def special_search_player_price(self, price: int = 0, price_type='max_buy', default_price=0):
        new_print(self.fifa_account, 'search_player_price : ', price, ' -- ', price_type)
        for nm in range(20):
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(
                    os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_search_player_icons/{price_type}.png'),
                    "screen_shot_tmp.jpg"
            ):
                break
            self.public_moves.ps4_buttons.down(sleep_after=.5)
            if nm > 15:
                new_print(self.fifa_account, '** can not find price **')
                return 'can not find price'
        if price:
            if default_price:
                self.public_moves.ps4_buttons.right()
                self.public_moves.transfer_list_utils.set_price_with_l_and_r(default_price, price)
            else:
                self.public_moves.ps4_buttons.cross()
                self.public_moves.transfer_list_utils.search_player_select_price(price)
        # bellow is Special Part
        for nm in range(20):
            self.public_moves.get_screen_shot()
            if self.public_moves.has_image(
                    os.path.join(BASE_DIR, f'utils/{self.fifa_account.platform}_search_player_icons/max_buy.png'),
                    "screen_shot_tmp.jpg"
            ):
                break
            self.public_moves.ps4_buttons.down(sleep_after=.5)
            if nm > 15:
                new_print(self.fifa_account, '** can not find special price **')
                return 'can not find price'
        self.public_moves.ps4_buttons.r2()
        time.sleep(1)
        self.public_moves.transfer_list_utils.set_price_with_l_and_r(15000000, 15000000 - (1000 * random.randint(1, 10)))
        # end of Special Part

    def no_bid_success(self):
        img = cv2.imread("screen_shot_tmp.jpg")
        bid_status_line = img[300:500, 0:-1]
        bid_status_line = cv2.cvtColor(bid_status_line, cv2.COLOR_BGR2GRAY)
        cv2.imwrite('bids_status_line.jpg', bid_status_line)
        time.sleep(.1)
        if self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/bid_success_tick.png'),
                'bids_status_line.jpg'
        ) or self.public_moves.has_image(os.path.join(
                BASE_DIR,
                f'utils/{self.fifa_account.platform}_controls/bid_success_tick_2.png'),
                'bids_status_line.jpg'
        ):
            return False
        return True

    def handle_misc_items(self, club_id):
        data = '{"apply":[]}'
        resp = self.se.post(
            f'{fifa_23_address}/item/{club_id}',
            data=data, headers=self.main_dic['header'])
        save_account_request(
            fifa_account=self.fifa_account,
            link=f'{fifa_23_address}/item/%s'
        )
        try:
            json_resp = resp.json()
            res_id = json_resp['itemData'][0]['resourceId']
            res_rating = 0
            for player_pick_item in json_resp['itemData']:
                if player_pick_item['rating'] > res_rating:
                    res_id = player_pick_item['resourceId']
                    res_rating = player_pick_item['rating']
            resp = self.se.post(
                f'{fifa_23_address}/playerpicks/item/{res_id}/select',
                headers=self.main_dic['header'])
            json_resp = resp.json()
            club_id = json_resp['id']
            data = '{"itemData":[{"id":%s,"pile":"club"}]}' % club_id
            move_result = put_item_for_sale(self.se, self.main_dic['header'], data, 0)
            new_print(self.fifa_account, 'console trade misc item found. send to club result : ', move_result.text)
        except:
            new_print(self.fifa_account, 'console trade misc item.no need to send to club , error 102',
                      traceback.format_exc())

    def save_club_player_items(self, club_players, club_consumables):
        bronze_rare_club_players = [mmmt for mmmt in club_players if
                                    int(mmmt['rareflag']) == 1 and 0 <= int(mmmt['rating']) <= 64]
        silver_common_club_players = [mmmt for mmmt in club_players if
                                    int(mmmt['rareflag']) == 0 and 65 <= int(mmmt['rating']) <= 74]
        silver_rare_club_players = [mmmt for mmmt in club_players if
                                    int(mmmt['rareflag']) == 1 and 65 <= int(mmmt['rating']) <= 74]
        gold_common_club_players = [mmmt for mmmt in club_players if
                                    int(mmmt['rareflag']) == 0 and 75 <= int(mmmt['rating']) <= 100]
        gold_rare_club_players = [mmmt for mmmt in club_players if
                                  int(mmmt['rareflag']) == 1 and 75 <= int(mmmt['rating']) <= 100]
        position_modifier_count = 0
        for item in club_consumables:
            if item['resourceId'] == 5003181:
                position_modifier_count = item['count'] - item['untradeableCount']
        new_print(self.fifa_account, 'club players count : ',
                  ' bronze rare = ', len(bronze_rare_club_players),
                  ' silver common = ', len(silver_common_club_players),
                  ' silver rare = ', len(silver_rare_club_players),
                  ' gold common = ', len(gold_common_club_players),
                  ' gold rare = ', len(gold_rare_club_players),
                  ' position modifier = ', position_modifier_count)
        self.trade_history.refresh_from_db()
        self.trade_history.club_bronze1_items = len(bronze_rare_club_players)
        self.trade_history.club_silver0_items = len(silver_common_club_players)
        self.trade_history.club_silver1_items = len(silver_rare_club_players)
        self.trade_history.club_gold0_items = len(gold_common_club_players)
        self.trade_history.club_gold1_items = len(gold_rare_club_players)
        self.trade_history.club_position_modifier_items = position_modifier_count
        self.trade_history.save()

    def fix_conflict_transfer_items(self):
        trade_pile_json_2 = get_trade_pile(self.fifa_account, self.se, self.main_dic).json()
        trade_pile_items_2 = trade_pile_json_2['auctionInfo']
        for item_1 in trade_pile_items_2:
            resource_id_2 = item_1['itemData']['resourceId']
            last_sale_price_2 = item_1['itemData'].get('lastSalePrice', 0)
            market_min_price = item_1['itemData'].get('marketDataMinPrice', 2000)
            if resource_id_2 == 5003181 or 0 < last_sale_price_2 < 1000:
                data_3 = {"itemData": [{"id": item_1['itemData']['id'], "pile": "club"}]}
                move_result = put_item_for_sale(self.se, self.main_dic['header'], json.dumps(data_3), 0)
                try:
                    if move_result.json().get('itemData', [{}])[0].get('success', False) is True:
                        pass
                        # sold_items_count -= 1
                    else:
                        new_print(self.fifa_account, 'error on move 7 : ', move_result.text)
                except:
                    new_print(self.fifa_account, 'move result 7 error : ', move_result.text)
                # new_print(self.fifa_account, 'move result 2 : ', move_result.text)
                time.sleep(2)
        sell_items(self, self.sbc_worker, self.fifa_account)
        self.console_transfer_list_sell_items(need_get_new_sid=False)
