exchange/app/Http/Controllers/Api/TradingsController.php

86 lines
3.6 KiB
PHP

<?php
namespace App\Http\Controllers\Api;
use App\Models\Category;
use App\Models\Group;
use App\Models\Trading;
use App\Transformers\TradingTransformer;
class TradingsController extends ApiController
{
public function index()
{
$last_tradings = Group::where("type", "trading")->with("tradings")->latest()->first()->tradings;
foreach($last_tradings as $trading){
$trading->title = trim(strtok($trading->title, '('));;
}
$last_tradings = $last_tradings->unique('title');
$tradings = [];
foreach($last_tradings as $trading){
$title = trim(strtok($trading->title, '('));
$before_last_trading = Trading::where("title",'LIKE', "%{$title}%")->where('group_id', '!=', $trading->group_id)->latest()->first();
$difference = !$before_last_trading ? 0 : $this->getPercentageDifference($trading->price ?? 0, $before_last_trading->price ?? 0);
array_push($tradings, (object)[
'id' => $trading->id,
'title' => $title,
'price' => $trading->price,
'old_price' => !$before_last_trading ? 0 : $before_last_trading->price,
'price_change' => number_format($difference, 1, ".", "")."%",
'currency' => $trading->currency,
]);
}
$tradings = Trading::hydrate($tradings);
return $this->respondWithCollection($tradings, new TradingTransformer);
}
public function selectedTradings($id){
if($id){
$category = Category::with('selectedTradings')->find($id);
if($category){
$selectedTradings = $category->selectedTradings;
$myTradings = array();
foreach ($selectedTradings as $item) {
$tradings = Trading::where("title", 'LIKE', "%{$item->title}%")->orderBy('created_at', 'DESC')->get();
$tradings = $tradings->unique('group_id')->slice(0, 10)->values();
$prices = array();
foreach ($tradings as $trading) {
array_push($prices, (object)[
'price' => $trading->price,
'date' => $trading->created_at->todatetimestring(),
]);
}
$last_trading = $tradings[0];
$before_last_trading = count($tradings) > 1 ? $tradings[1] : null;
$difference = !$before_last_trading ? 0 : $this->getPercentageDifference($last_trading->price ?? 0, $before_last_trading->price ?? 0);
array_push($myTradings, (object)[
'id' => $last_trading->id,
'title' => trim(strtok($last_trading->title, '(')),
'price' => $last_trading->price,
'old_price' => !$before_last_trading ? 0 : $before_last_trading->price,
'price_change' => !$before_last_trading ? '100%' : number_format($difference, 1, ".", "")."%",
'currency' => $last_trading->currency,
'all_prices' => $prices
]);
}
$tradings = Trading::hydrate($myTradings);
return $this->respondWithCollection($tradings, new TradingTransformer('selected'));
}
return $this->errorNotFound();
}
return $this->errorWrongArgs();
}
function getPercentageDifference($new, $old){
return (($new - $old) / abs($old)) * 100;
}
}