?? 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: BitstampService.php

<?php

namespace Application\Service\ExchangeService;

/**
 * Description of BittrexService
 *
 * @author jimmy
 * 
 * Type,Datetime,Account,Amount,Value,Rate,Fee,Sub Type
  Deposit,"Aug. 20, 2019, 06:10 PM",Main Account,0.00500000 ETH,,,,
  Deposit,"Aug. 20, 2019, 06:35 PM",Main Account,121.26100800 XRP,,,,
  Market,"Aug. 20, 2019, 07:48 PM",Main Account,60.63050400 XRP,0.00153880 BTC,0.00002538 BTC,0.00000800 BTC,Sell
 */
class BitstampService 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 = 'Bitstamp';
    protected $requiredColumn = array(
        'Type',
        'Datetime',
        'Account',
        'Amount',
        'Value',
        'Rate',
        'Fee',
        'Sub Type'
    );
//    protected $mapperCurrency = array(
//        'XDAO' => 'DAO',
//        'XETC' => 'ETC',
//        'XETH' => 'ETH',
//        'XLTC' => 'LTC',
//        'XMLN' => 'MLN',
//        'XNMC' => 'NMC',
//        'XREP' => 'REP',
//        'XXVN' => 'XVN',
//        'XICN' => 'ICN',
//        'XXBT' => 'BTC',
//        'XXDG' => 'XDG',
//        'XXLM' => 'XLM',
//        'XXMR' => 'XMR',
//        'XXTZ' => 'XTZ',
//        'XXRP' => 'XRP',
//        'XZEC' => 'ZEC',
//        'ZCAD' => 'CAD',
//        'ZEUR' => 'EUR',
//        'ZGBP' => 'GBP',
//        'ZJPY' => 'JPY',
//        'ZKRW' => 'KRW',
//        'ZUSD' => 'USD');
    protected $columnCsv;
    protected $errorMessage;
    protected $contentFile;
    protected $linesArray;
    protected $ledgioMapper;

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

    protected function getDatetime($arrayLine) {
        $dateStr = $arrayLine[$this->getDatetimeIndex()];
        //Aug. 20, 2019, 07:48 PM
        $dateTime = \DateTime::createFromFormat('M. d, Y, H:i a', $dateStr);
        return $dateTime;
    }

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

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

        return $explodeFee[0];
    }

    protected function getFeeCurrency($arrayLine) {
        $fees = $arrayLine[$this->getFeeIndex()];
        $explodeFee = explode(' ', $fees);

        return $explodeFee[1];
    }

    protected function getTypeIndex() {
        return $this->columnCsvMapper['Sub Type'];
    }

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

    protected function getTradedAmount($arrayLine) {
        if (strtolower($arrayLine[$this->getTypeIndex()]) == 'buy') {
            $amount = $arrayLine[$this->getValueIndex()];
        } else {
            $amount = $arrayLine[$this->getAmountIndex()];
        }
        $explodeAmount = explode(' ', $amount);
        return $explodeAmount[0];
    }

    protected function getTradedCurrency($arrayLine) {
        if (strtolower($arrayLine[$this->getTypeIndex()]) == 'buy') {
            $amount = $arrayLine[$this->getValueIndex()];
        } else {
            $amount = $arrayLine[$this->getAmountIndex()];
        }
        $explodeAmount = explode(' ', $amount);

        return $explodeAmount[1];
    }

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

    protected function getReceivedAmount($arrayLine) {
        if (strtolower($arrayLine[$this->getTypeIndex()]) == 'buy') {
            $amount = $arrayLine[$this->getAmountIndex()];
        } else {
            $amount = $arrayLine[$this->getValueIndex()];
        }
        $explodeAmount = explode(' ', $amount);
        return $explodeAmount[0];
    }

    protected function getReceivedCurrency($arrayLine) {
        if (strtolower($arrayLine[$this->getTypeIndex()]) == 'buy') {
            $amount = $arrayLine[$this->getAmountIndex()];
        } else {
            $amount = $arrayLine[$this->getValueIndex()];
        }
        $explodeAmount = explode(' ', $amount);
        return $explodeAmount[1];
    }

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

    public function __construct($file, $user, \Doctrine\ORM\EntityManager $em) {
        $this->file = $file;
        $this->user = $user;
        $this->entityManager = $em;
        
        // Mapper Devise
        $mapperDeviseBitstamp = new \Application\Mapper\DeviseBitstampMapper($this->entityManager);
        $this->arrayMapper = $mapperDeviseBitstamp->getArrayMapper();

        $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($arrayLine[$this->getDatetimeIndex($arrayLine)]) || empty($arrayLine[$this->getAmountIndex($arrayLine)]) || empty($arrayLine[$this->getValueIndex($arrayLine)])) {
                        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);
                    $fees = $this->getFee($arrayLine);

                    $feesCurrency = $this->getFeeCurrency($arrayLine);


                    $tradedAmount = $this->getTradedAmount($arrayLine);


                    $tradedCurrency = $this->getTradedCurrency($arrayLine);

                    if (!empty($this->arrayMapper[$tradedCurrency])) {
                        $tradedDevise = $this->arrayMapper[$tradedCurrency];
                    } else {
                        mail('jimmykurc@gmail.com', 'Devise Bitstamp non reconnue', 'Devise Bitstamp non reconnue : ' . $tradedCurrency);
                    }


                    $receivedAmount = $this->getReceivedAmount($arrayLine);
                    $receivedCurrency = $this->getReceivedCurrency($arrayLine);
                    
                     if (!empty($this->arrayMapper[$receivedCurrency])) {
                        $receivedDevise = $this->arrayMapper[$receivedCurrency];
                    } else {
                        
                        mail('jimmykurc@gmail.com', 'Devise Bitfinex non reconnue', 'Devise Bitfinex non reconnue : ' . $receivedCurrency);
                    }
                    //$txId = $this->getTxid($arrayLine);
//                    var_dump($datetimeTransaction, $type, $pair, $fees, $tradedAmount, $tradedCurrency, $receivedAmount, $receivedCurrency);
//                    exit;
                    //var_dump($feesCurrency, $tradedCurrency);
                    //if ($feesCurrency == $tradedCurrency) {
                    //echo 'buy fees trade trade';

                    if ($feesCurrency == $tradedCurrency) {
                        $tradedAmountNet = $tradedAmount + $fees;
//                        var_dump($tradedAmountNet, $tradedAmount);
                        $receivedAmountNet = $receivedAmount;
                    } else {
                        $tradedAmountNet = $tradedAmount;
                        $receivedAmountNet = $receivedAmount - $fees;
//                        var_dump($receivedAmountNet, $tradedAmount);
                    }


//                    - $fees;
                    //($tradedAmount, $tradedAmountNet, $receivedAmount, $receivedAmountNet, $fees); exit;
//                    } else {
//                        if (strtolower($type) == 'buy') {
//                            //echo 'buy fees received';
//                            $tradedAmountNet = $tradedAmount;
//                            $receivedAmountNet = $receivedAmount - abs($fees);
//                        } else {
//                            //echo 'sell trade';
//                            $tradedAmountNet = $tradedAmount;
//                            $receivedAmountNet = $receivedAmount - abs($fees);
//                        }
//
//                        //$tradedAmountNet = $tradedAmount;
//                        // var_dump($tradedAmount, $tradedAmountNet, $receivedAmount, $receivedAmountNet, $fees); exit;
//                    }
//var_dump($tradedAmount);
//var_dump($tradedAmountNet);
//                    var_dump($receivedAmount);
//                    var_dump($receivedAmountNet);




                    $ledgio = new \Application\Entity\Ledgio(array(
                        'datetimeTransaction' => $datetimeTransaction,
                        //'user' => $user,
                        'exchange' => $exchange,
                        'type' => '',
                        'pair' => '',
                        'tradedAmount' => $tradedAmountNet,
                        'tradedCurrency' => $tradedCurrency,
                         'tradedDevise' => $tradedDevise->getDevise(),
                        'fees' => '',
                        'receivedAmount' => $receivedAmountNet,
                        'receivedCurrency' => $receivedCurrency,
                        'receivedDevise' => $receivedDevise->getDevise(),
                        '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;
    }

}


??

??