?? GreyFile — Mystic File Browser

Current path: home/webdevt/cryptoimpot.fr/module/Application/src/Service/ExchangeService/



?? Go up: /home/webdevt/cryptoimpot.fr/module/Application/src/Service

?? Viewing: HitBTCService.php

<?php

namespace Application\Service\ExchangeService;

/**
 * Description of BittrexService
 *
 * @author jimmy
 * 
  "Date (UTC)","Instrument","Trade ID","Order ID","Side","Quantity","Price","Volume","Fee","Rebate","Total"
  "2017-11-26 20:56:06","ETH/USDT","83248675","7994001204","buy","0.003","462.70","1.3881000","0.0013881","0.0000000","-1.3894881"
  "2017-11-26 20:55:55","ETH/USDT","83248569","7993975689","buy","2.088","462.70","966.1176000","0.0000000","0.0966117","-966.0209883"
  "2017-11-26 20:55:49","ETH/USDT","83248523","7993975689","buy","0.532","462.70","246.1564000","0.0000000","0.0246156","-246.1317844"

 */
class HitBTCService extends BaseService {

    const ERROR_TITLE_CSV_COL_REQUIRED = 'Le csv ne comporte pas les entêtes requis : [REQUIRED_COLUMN]';
    const ERROR_MESSAGE_CSV_COL_REQUIRED = 'Vérifiez que vous êtes sur la bonne page d\'importation. Changez d\'onglet s\'il s\'agit d\'un fichier provenant d\'une autre platteforme que [EXCHANGE].';

    protected $file;
    protected $exchangeName = 'HitBTC';
    protected $requiredColumn = array(
    );
    protected $columnCsv;
    protected $errorMessage;
    protected $contentFile;
    protected $linesArray;
    protected $ledgioMapper;

//    Date (UTC)","Instrument","Trade ID","Order ID","Side","Quantity","Price","Volume","Fee","Rebate","Total"
    protected function getTimeStampIndex() {
        return 0;
    }

    protected function getDatetime($arrayLine) {
        $dateStr = $arrayLine[$this->getTimeStampIndex()];
        // 2017-11-26 20:56:06
        $dateTime = \DateTime::createFromFormat('Y-m-d H:i:s', $dateStr);
        return $dateTime;
    }

    protected function getPairIndex() {
        return $this->columnCsvMapper['Instrument'];
    }

    protected function getPair($arrayLine) {
        // ETH/USDT
        $pairStr = $arrayLine[$this->getPairIndex()];
        $arrayAsset = explode('/', $pairStr);
        return $arrayAsset;
    }

    protected function getOrderTypeIndex() {
        return $this->columnCsvMapper['Side'];
    }

    protected function getType($arrayLine) {
        return $arrayLine[$this->getOrderTypeIndex()];
    }

    protected function getQuantityIndex() {
        return $this->columnCsvMapper['Quantity'];
    }

    protected function getTotalNetIndex() {
        return $this->columnCsvMapper['Total'];
    }

    protected function getTradedAmountNet($arrayLine, $type) {
        if (strtolower($type) == 'sell') {
            $tradedAmount = $arrayLine[$this->getQuantityIndex()];
            //var_dump($price, $tradedAmount); exit;
        } else {
            $tradedAmount = abs($arrayLine[$this->getTotalNetIndex()]);
            //var_dump($tradedAmount, $amount);
        }
        return $tradedAmount;
    }

    protected function getTradedCurrency($arrayLine, $type) {
        $pair = $this->getPair($arrayLine);

        if (strtolower($type) == 'sell') {
            return $pair[0];
        } else {
            return $pair[1];
        }
    }

    protected function getReceivedAmountNet($arrayLine, $type) {


        if (strtolower($type) == 'sell') {
            $amount = abs($arrayLine[$this->getTotalNetIndex()]);
            //var_dump($price, $tradedAmount); exit;
        } else {
            $amount = $arrayLine[$this->getQuantityIndex()];
        }
        return $amount;
    }

    protected function getReceivedCurrency($arrayLine, $type) {
        $pair = $this->getPair($arrayLine);

        if (strtolower($type) == 'sell') {
            return $pair[1];
        } else {
            return $pair[0];
        }
    }

    protected function getFeeIndex() {
        return $this->columnCsvMapper['Fee'];
    }

    protected function getFee($arrayLine) {
        $fees = $arrayLine[$this->getFeeIndex()];


        return $fees;
    }

    protected function getTxidIndex() {
        return $this->columnCsvMapper['Trade ID'];
    }

    protected function getTxid($arrayLine) {
        $txId = $arrayLine[$this->getTxidIndex()];
        return $txId;
    }

    public function getEntityManager() {
        return $this->entityManager;
    }

    public function __construct($file, $user, \Doctrine\ORM\EntityManager $em) {
        $this->file = $file;
        $this->user = $user;
        $this->entityManager = $em;
        $this->initColFromCsv();

        $mapperExchange = new \Application\Mapper\ExchangeMapper($em);
        $exchange = $mapperExchange->findByName(strtolower($this->exchangeName));



        //var_dump($exchange);
        if ($this->isValid()) {
            $mapperImport = new \Application\Mapper\ImportMapper($this->getEntityManager());

            $importEntity = new \Application\Entity\Import(
                    array(
                'user' => $user,
                'exchange' => $exchange,
                'sourceType' => 'csv',
                'name' => basename($file),
                'nombreTrade' => 0,
                'datetimeImport' => new \DateTime()
            ));
            $mapperImport->insert($importEntity);
            $this->ledgioMapper = new \Application\Mapper\LedgioMapper($em);
            /* save */
            $start = microtime(true);
            $batchSize = 200;
            //$user = $em->merge($user);
            foreach ($this->linesArray as $index => $row) {
                if (empty($row)) {
                    continue;
                }

                //var_dump($row);
                if ($index != 0) {


                    /* date */
                    $arrayLine = str_getcsv($row);
//                    if (empty($this->getDatetime($arrayLine)) || empty($this->getTradedAmountNet($arrayLine, $type)) || empty($arrayLine[$this->getValueIndex($arrayLine, $type)])) {
//                        continue;
//                    }
//                    var_dump($this->getDatetimeIndex($arrayLine));
//                    var_dump($this->getAmountIndex($arrayLine));
//                    var_dump($this->getValueIndex($arrayLine));
//                    exit;
                    $datetimeTransaction = $this->getDatetime($arrayLine);
                    //var_dump($datetimeTransaction);
                    $type = $this->getType($arrayLine);
//
//                  
                    $pair = $this->getPair($arrayLine);

                    $tradedAmountNet = $this->getTradedAmountNet($arrayLine, $type);
                    $tradedCurrency = $this->getTradedCurrency($arrayLine, $type);

                    $receivedAmountNet = $this->getReceivedAmountNet($arrayLine, $type);
                    $receivedCurrency = $this->getReceivedCurrency($arrayLine, $type);


                    $fees = $this->getFee($arrayLine);

                    $txId = $this->getTxid($arrayLine);





                    $ledgio = new \Application\Entity\Ledgio(array(
                        'datetimeTransaction' => $datetimeTransaction,
                        //'user' => $user,
                        'exchange' => $exchange,
                        'type' => $type,
                        'pair' => $pair[0] . '/' . $pair[1],
                        'tradedAmount' => $tradedAmountNet,
                        'tradedCurrency' => $tradedCurrency,
                        'fees' => '',
                        'receivedAmount' => $receivedAmountNet,
                        'receivedCurrency' => $receivedCurrency,
                        'txId' => $txId,
                        'import' => $importEntity
                    ));



                    $ledgio->setUser($user);

//                    $ledgio->setTradedAmount($tradedAmount);
//                    $ledgio->setReceivedAmount($receivedAmount);
//                    
//                    var_dump('user',$em->contains($ledgio->user));
//            var_dump('ledgio',$em->contains($ledgio));
                    $em->persist($ledgio);
                    $this->countLineRecorded++;

//                    
//                     var_dump('user', $em->contains($ledgio->user));
//            var_dump('ledgio',$em->contains($ledgio));
                    // exit;
                    if (($index % $batchSize) == 0) {
                        $em->flush();
                        //$em->clear('\Application\Entity\Ledgio');
                    }



// flush the remaining objects
// trop long !!!!!!!!
                    //$this->ledgioMapper->insert($entity);
                    // $newDate = new \DateTime();
//                    $newDate->setTimestamp($timestampTransaction);
                    //$newDate = \DateTime::createFromFormat('U', $timestampTransaction);
//                     echo  $newDate->format('Y-m-d H:i:s');
//                    var_dump($timestampTransaction); exit;
//                    $dateTime = new \DateTime($dateStr);
                    //$ledgioEntity = new \Application\Entity\Ledgio();
                }
            }
            $em->flush();

            $importEntity->setNombreTrade($this->countLineRecorded);



            $mapperImport->update($importEntity);
            //$em->clear();
            //$em->clear('\Application\Entity\Ledgio');
            //$time_elapsed_secs = microtime(true) - $start;
//            echo $time_elapsed_secs;
//            exit;
        }
    }

    protected function initColFromCsv() {
        $this->contentFile = file_get_contents($this->file);
        //var_dump($content);
        $this->linesArray = explode("\n", $this->contentFile);


        //var_dump($lines);
        //$this->columnCsv = explode(',', $lines[0]);
        $this->columnCsv = str_getcsv($this->linesArray[0]);
        $this->columnCsvMapper = array_flip($this->columnCsv);
//        var_dump($lines[0]);
//        exit;
        //echo $exchange;
//        foreach ($lines as $nbLine => $line) {
//            $csv_row = str_getcsv($line);
//
//            if ($nbLine == 0) {
//
//
//
//                foreach ($csv_row as $index => $nameCol) {
//
//                    //var_dump($nameCol);
//                    //var_dump($mapperFileExchange);
//                    if (in_array($nameCol, array_values($mapperFileExchange))) {
//                        $mapperFile[$nameCol] = $index;
//                    }
//                }
//            } else {
//                //if (empty($csv_row[$mapperFile['asset']])) continue;
//                if (!isset($mapperFile[$mapperFileExchange['time']])) {
////                            @todo
//                    //echo $nbLine;
//                    //echo $exchange;
//                    //var_dump($csv_row);
//                    // exit;
//                }
//                //var_dump($mapperFile);
//                //exit;
//                if (empty($csv_row[$mapperFile[$mapperFileExchange['time']]]))
//                    continue;
//
//
//                if (!array_key_exists($csv_row[$mapperFile[$mapperFileExchange['time']]], $ledgio))
//                    $ledgio[$csv_row[$mapperFile[$mapperFileExchange['time']]]] = [];
//
//
//                $ledgio[$csv_row[$mapperFile[$mapperFileExchange['time']]]][] = array('data' => $csv_row, 'exchange' => $exchange, 'mapperFile' => $mapperFile);
//                // exit;
//            }
//            //var_dump($mapperFile); exit;
//            //save data into database
//            //----
//        }
    }

    protected function setErrorMessage($errorMessage) {
        $this->errorMessage = $errorMessage;
    }

    public function getErrorMessage() {
        return $this->errorMessage;
    }

    public function isValid() {
        //var_dump($this->requiredColumn);
        //var_dump($this->columnCsv);
        $arrayDiff = array_diff($this->requiredColumn, $this->columnCsv);
        $colIsValid = !$arrayDiff;
        if ($colIsValid === false) {
            $this->setErrorMessage(array(
                'header' => str_replace('[REQUIRED_COLUMN]', implode(', ', $arrayDiff), SELF::ERROR_TITLE_CSV_COL_REQUIRED),
                'body' => str_replace('[EXCHANGE]', $this->exchangeName, SELF::ERROR_MESSAGE_CSV_COL_REQUIRED),
                'footer' => '')
            );
        }
        return $colIsValid;
    }

}


??

??