<?php

namespace App\Console\Commands\Market;

use App\Events\MarketStatsLiteUpdated;
use App\Models\Market\Market;
use App\Models\Order\FuturesContract;
use App\Services\Liquidity\Binance\BinanceApi;
use App\Services\Market\MarketService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class MarketLiquidationWatcherCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'market-watcher:liquidation';

    protected $markets;

    protected $initialMarkets;

    protected $lastMarkets;

    protected $quoteMarkets;

    protected $baseMarkets;

    protected $lastRefreshed;

    protected $iteration = 0;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        while(true) {

            $futures = FuturesContract::where('status', 'active')->get();


            foreach ($futures as $future) {

                $marketPrice = market_get_stats($future->market_id, 'last');

                if($future->is_long) {
                    // If market price less or equal liquidation price
                    if(math_compare($marketPrice, $future->liquidation_price) <= 0) {
                        $future->status = 'liquidated';
                        $future->save();
                    }
                } else {

                    // If market price less or equal liquidation price
                    if(math_compare($marketPrice, $future->liquidation_price) >= 0) {
                        $future->status = 'liquidated';
                        $future->save();
                    }

                }
            }

            sleep(2);
        }
    }
}

