Your IP : 216.73.216.79


Current Path : /var/www/html/dosmv2/backend/modules/cryptoaverage/controllers/
Upload File :
Current File : /var/www/html/dosmv2/backend/modules/cryptoaverage/controllers/CryptoAverageController.php

<?php
namespace backend\modules\cryptoaverage\controllers;

//binance class
include dirname(__DIR__) . '/exchange/test.php';

use Yii;
use backend\modules\cryptoaverage\models\CryptoAverage;
use backend\modules\cryptoaverage\models\CryptoAverageSearch;
use backend\modules\cryptoaverage\models\CryptoParameter;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;
use backend\modules\cryptoaverage\exchange\Binance;
use Intervention\Image\Exception\NotFoundException;

/**
 * CryptoAverageController implements the CRUD actions for CryptoAverage model.
 */
class CryptoAverageController extends Controller
{

    /**
     *
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => [
                        'POST'
                    ]
                ]
            ]
        ];
    }

    /**
     * Formula
     *
     * @return array[][]
     */
    public function formula()
    {
        return [
            'buy' => '=BUY(ROW())',
            'sell' => '=SELL(ROW())',
            'net' => '=NET(ROW())',
            'cum' => '=CUM(ROW())',
            'buyprice' => '=BUY_PRICE(ROW())',
            'buyqty' => '=BUY_QTY(ROW())',
            'average' => '=CAVERAGE(ROW())',
            'profitloss' => '=PROFIT(ROW())'
        ];
    }

    /**
     * Lists all CryptoAverage models.
     *
     * @return mixed
     */
    public function actionIndex($coin = null)
    {
        $coin = ! empty($coin) ? preg_replace('#\W#', '', $coin) : '';

        $searchModel = new CryptoAverageSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->where([
            'coin' => $coin
        ]);
        
        $formula = $this->formula();
        $data = $dataProvider->getModels();
        $arrdata = [];

        for ($i = 0; $i < count($data); $i ++) {
            $arrdata[] = [
                $data[$i]->datetime,
                $data[$i]->price,
                $data[$i]->qty,
                $data[$i]->type,
                $formula['buy'],
                $formula['sell'],
                $formula['net'],
                $formula['cum'],
                $formula['buyprice'],
                $formula['buyqty'],
                $formula['average'],
                $formula['profitloss'],
                $data[$i]->id,
                $data[$i]->orderid,
            ];
        }
            
//         if(empty($data)) {
//             $arrdata = [
//                 [
//                     date('d-m-y H:i:s'),
//                     '',
//                     '',
//                     '',
//                     $formula['buy'],
//                     $formula['sell'],
//                     $formula['net'],
//                     $formula['cum'],
//                     $formula['buyprice'],
//                     $formula['buyqty'],
//                     $formula['average'],
//                     $formula['profitloss'],
//                     '',
//                     ''
//                 ]
//             ];
//         }

        // die('<pre>' . json_encode($arrdata, true) . '</pre>');
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'data' => json_encode($arrdata, true),
            'coin' => $coin
        ]);
    }


    /**
     * Creates a new CryptoAverage model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     *
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new CryptoAverage();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect([
                'view',
                'id' => $model->id
            ]);
        }

        return $this->render('create', [
            'model' => $model
        ]);
    }

    /**
     * Updates an existing CryptoAverage model.
     * If update is successful, the browser will be redirected to the 'view' page.
     *
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = CryptoParameter::findOne($id);
        
        if(!$model){
            throw new NotFoundException();
        }
        
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect([
                'list-setting',
            ]);
        }

        return $this->render('setting', [
            'model' => $model
        ]);
    }

    /**
     * Deletes an existing CryptoAverage model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     *
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect([
            'index'
        ]);
    }

    public function actionFormulaTemplate($row, $prev, $max)
    {
        $formula = $this->formula();
        $data = [
            date('Y-m-d H:i:s'),
            0,
            0,
            '',
            $formula['buy'],
            $formula['sell'],
            $formula['net'],
            $formula['cum'],
            $formula['buyprice'],
            $formula['buyqty'],
            $formula['average'],
            $formula['profitloss'],
            0
        ];
        $this->asJson($data);
    }
    
    /**
     * Save data from spread according tu coin type
     */
    public function actionSaveSpread($coin) {
        $post = Yii::$app->request->post();
        $data = json_decode($post['data']);
        try {
            foreach($data as $d) {
            
                if(!isset($d[12]) || !$d[12]) {
                    $model = new CryptoAverage();
                } else {
                    $model = CryptoAverage::findOne($d[12]);
                }

                $datetime = \DateTime::createFromFormat('d/m/Y H:i', $d[0]);
                $date = $datetime->format('Y-m-d H:i');
                $model->datetime = $date;
                $model->coin = $coin;
                $model->price = $d[1];
                $model->qty = $d[2];
                $model->type = $d[3];
                $model->buy = $d[4];
                $model->sell = $d[5];
                $model->netqty = $d[6];
                $model->cumalative = $d[7];
                $model->buyprice = $d[8];
                $model->buyqty = $d[9];
                $model->average = $d[10];
                $model->profitloss = $d[11];
                $model->orderid = $d[13];
                $model->userid = Yii::$app->user->id;
                
                if(!$model->save()) {
                    throw new \Exception(json_encode($model->errors));
                }
            }

        } catch(\Throwable $t) {
            
            return $this->asJson([
                'success' => false,
                'message' => $t->getMessage(),
                'datetime' => date('Y-m-d H:i:s')
            ]);
        }
        
        return $this->asJson([
            'success' => true,
            'datetime' => date('Y-m-d H:i:s')
        ]);
    }
    
    public function actionApi($symbol){
        try {
            //$data = json_decode(file_get_contents('php://input'));
            $key    = CryptoParameter::find()->where(['userid' => Yii::$app->user->id, 'code' => 'API_KEY'])->one();
            $secret = CryptoParameter::find()->where(['userid' => Yii::$app->user->id, 'code' => 'API_SECRET'])->one();
            
            if(!$secret || !$key) {
                throw new \Exception('Missing key and secret');
            }
            
            $bconf  = (object) [
                'binance' => (object) [
                    'API_KEY' => $key->value,
                    'API_SECRET' => $secret->value,
                    'BASE_URL' => 'https://api.binance.com'
                ]
            ];
            
            $binance = new Binance($bconf);
            //$data = $binance->time();
            $obj = (object) [
                'symbol' => $symbol,
//                 'startTime' => strtotime($data->startTime) * 1000, //microtime
//                 'endTime' => strtotime($data->endTime) * 1000, //microtime
                'limit' => '500'
            ];

            //$result = $obj;
            //$result = $binance->allOrders($obj);
            $result = $binance->myTrades($obj);
            //$json = '[{"symbol":"REEFUSDT","id":9338447,"orderId":51801473,"orderListId":-1,"price":"0.03106300","qty":"1663.00000000","quoteQty":"51.65776900","commission":"0.05165777","commissionAsset":"USDT","time":1614421692695,"isBuyer":false,"isMaker":false,"isBestMatch":true},{"symbol":"REEFUSDT","id":9358591,"orderId":51963581,"orderListId":-1,"price":"0.03094400","qty":"675.00000000","quoteQty":"20.88720000","commission":"0.02088720","commissionAsset":"USDT","time":1614436980479,"isBuyer":false,"isMaker":false,"isBestMatch":true},{"symbol":"REEFUSDT","id":9422622,"orderId":52430354,"orderListId":-1,"price":"0.03084800","qty":"355.00000000","quoteQty":"10.95104000","commission":"0.35500000","commissionAsset":"REEF","time":1614478952094,"isBuyer":true,"isMaker":true,"isBestMatch":true},{"symbol":"REEFUSDT","id":9424191,"orderId":52445815,"orderListId":-1,"price":"0.03063800","qty":"340.00000000","quoteQty":"10.41692000","commission":"0.34000000","commissionAsset":"REEF","time":1614480516068,"isBuyer":true,"isMaker":false,"isBestMatch":true},{"symbol":"REEFUSDT","id":9427363,"orderId":52461273,"orderListId":-1,"price":"0.02993600","qty":"358.00000000","quoteQty":"10.71708800","commission":"0.35800000","commissionAsset":"REEF","time":1614481991496,"isBuyer":true,"isMaker":false,"isBestMatch":true},{"symbol":"REEFUSDT","id":9551393,"orderId":53500842,"orderListId":-1,"price":"0.02938700","qty":"512.00000000","quoteQty":"15.04614400","commission":"0.51200000","commissionAsset":"REEF","time":1614571373816,"isBuyer":true,"isMaker":false,"isBestMatch":true},{"symbol":"REEFUSDT","id":9553603,"orderId":53516600,"orderListId":-1,"price":"0.02864900","qty":"538.00000000","quoteQty":"15.41316200","commission":"0.53800000","commissionAsset":"REEF","time":1614572480614,"isBuyer":true,"isMaker":true,"isBestMatch":true},{"symbol":"REEFUSDT","id":12510641,"orderId":69650680,"orderListId":-1,"price":"0.04487600","qty":"710.00000000","quoteQty":"31.86196000","commission":"0.03186196","commissionAsset":"USDT","time":1615600329727,"isBuyer":false,"isMaker":true,"isBestMatch":true},{"symbol":"REEFUSDT","id":13399406,"orderId":73706318,"orderListId":-1,"price":"0.05187300","qty":"469.00000000","quoteQty":"24.32843700","commission":"0.02432844","commissionAsset":"USDT","time":1615765039642,"isBuyer":false,"isMaker":false,"isBestMatch":true},{"symbol":"REEFUSDT","id":13590082,"orderId":74579575,"orderListId":-1,"price":"0.05386000","qty":"237.00000000","quoteQty":"12.76482000","commission":"0.01276482","commissionAsset":"USDT","time":1615787283265,"isBuyer":false,"isMaker":false,"isBestMatch":true}]';
            //$result = json_decode($json);

            //descending
            //rsort($result);

            $process = [];
            foreach ($result as $res) {
                $res->time = date('Y-m-d H:i:s', ($res->time / 1000));
                $process[] = $res;
            }

        } catch (\Throwable $t) {
            return $this->asJson(['success' => false, 'message' => $t->getMessage()]);
        }
        
        return $this->asJson(['success' => true, 'data' => $process]);
    }
    
    /**
     * Setting action list
     */
    public function actionListSetting() {        
        $query = CryptoParameter::find();
        
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);
        
        return $this->render('list-setting', [
            'dataProvider' => $dataProvider
        ]);
    }
    
    /**
     * Crypto setting action
     */
    public function actionSetting() {
        
        $model = new CryptoParameter();
        
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect([
                'list-setting',
            ]);
        }
        
        return $this->render('setting', [
            'model' => $model
        ]);
    }
    
    /**
     * Crypto setting action
     */
    public function actionDeleteSetting($id) {
        
        $model = CryptoParameter::findOne($id);
        
        if ($model) {
            $model->delete();
        }
        
        return $this->redirect(['list-setting']);
    }

    /**
     * Finds the CryptoAverage model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     *
     * @param integer $id
     * @return CryptoAverage the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = CryptoAverage::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }
}