Current path: home/webdevt/cryptoimpot.fr/module/Application/src/Service/ExchangeService/
?? Go up: /home/webdevt/cryptoimpot.fr/module/Application/src/Service
<?php
namespace Application\Service\ExchangeService;
/**
* Description of BitfinexService
*
* @author jimmy
*/
class BitfinexService 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 = 'Bitfinex';
protected $requiredColumn = array(
'#',
'PAIR',
'AMOUNT',
'PRICE',
'FEE',
'FEE CURRENCY',
'DATE',
'ORDER ID'
);
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 getTimeIndex() {
return $this->columnCsvMapper['DATE'];
}
protected function getPairIndex() {
return $this->columnCsvMapper['PAIR'];
}
protected function getAmountIndex() {
return $this->columnCsvMapper['AMOUNT'];
}
protected function getPriceIndex() {
return $this->columnCsvMapper['PRICE'];
}
protected function getFeesIndex() {
return $this->columnCsvMapper['FEE'];
}
protected function getFeesCurrencyIndex() {
return $this->columnCsvMapper['FEE CURRENCY'];
}
protected function getTxidIndex() {
return $this->columnCsvMapper['#'];
}
//https://api.bitfinex.com/v1/symbols recupere les paires autorisées
protected function getTimestamp($arrayLine) {
$dateStr = $arrayLine[$this->getTimeIndex()];
$dateTime = new \DateTime($dateStr);
return $dateTime->getTimestamp();
}
// Bitfinex date
protected function getDatetime($arrayLine) {
// var_dump($arrayLine); exit;
$dateStr = $arrayLine[$this->getTimeIndex()];
$dateTime = new \DateTime($dateStr);
// var_dump($arrayLine);
// var_dump($dateStr);
// var_dump($dateTime);
return $dateTime;
}
protected function getPair($arrayLine) {
$pairStr = $arrayLine[$this->getPairIndex()];
$arrayAsset = explode('/', $pairStr);
return $arrayAsset;
}
protected function getType($arrayLine) {
$amount = $arrayLine[$this->getAmountIndex()];
if ($amount > 0) {
$type = 'buy';
} else {
$type = 'sell';
}
//$type = $arrayLine[$this->getTypeIndex()];
// return $type;
return $type;
}
protected function getFees($arrayLine) {
$fees = $arrayLine[$this->getFeesIndex()];
$feesCurrency = $arrayLine[$this->getFeesCurrencyIndex()];
if ($feesCurrency !== 'EUR') {
// if (\Application\Tool\CurrencyTool::isFiat($feesCurrency)) {
//
// }
}
return $fees;
}
protected function getFeesCurrency($arrayLine) {
return $arrayLine[$this->getFeesCurrencyIndex()];
}
protected function getTradedAmount($arrayLine, $type) {
$amount = $arrayLine[$this->getAmountIndex()];
$price = $arrayLine[$this->getPriceIndex()];
if (strtolower($type) == 'buy') {
$tradedAmount = abs($amount) * $price;
//var_dump($price, $tradedAmount); exit;
} else {
$tradedAmount = abs($amount);
//var_dump($tradedAmount, $amount);
}
return $tradedAmount;
}
protected function getTradedCurrency($pair, $type) {
if (strtolower($type) == 'buy') {
return $pair[1];
} else {
return $pair[0];
}
}
protected function getReceivedAmount($arrayLine, $type) {
$amount = $arrayLine[$this->getAmountIndex()];
$price = $arrayLine[$this->getPriceIndex()];
// var_dump($type);
if (strtolower($type) == 'buy') {
$receivedAmount = abs($amount);
} else {
$receivedAmount = abs($amount) * $price;
}
return $receivedAmount;
}
protected function getReceivedCurrency($pair, $type) {
if (strtolower($type) == 'buy') {
return $pair[0];
} else {
return $pair[1];
}
}
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;
// Mapper Devise
$mapperDeviseBitfinex = new \Application\Mapper\DeviseBitfinexMapper($this->entityManager);
$this->arrayMapper = $mapperDeviseBitfinex->getArrayMapper();
//$this->updateDeviseAvailable(); exit;
$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());
$mapperDevise = new \Application\Mapper\DeviseMapper($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);
$datetimeTransaction = $this->getDatetime($arrayLine);
$type = $this->getType($arrayLine);
$pair = $this->getPair($arrayLine);
$fees = $this->getFees($arrayLine);
$feesCurrency = $this->getFeesCurrency($arrayLine);
$tradedAmount = $this->getTradedAmount($arrayLine, $type);
$tradedCurrency = $this->getTradedCurrency($pair, $type);
if (!empty($this->arrayMapper[$tradedCurrency])) {
$tradedDevise = $this->arrayMapper[$tradedCurrency];
} else {
mail('jimmykurc@gmail.com', 'Devise Bitfinex non reconnue', 'Devise Bitfinex non reconnue : ' . $tradedCurrency);
}
$receivedAmount = $this->getReceivedAmount($arrayLine, $type);
$receivedCurrency = $this->getReceivedCurrency($pair, $type);
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($feesCurrency, $tradedCurrency);
if ($feesCurrency == $tradedCurrency) {
if (strtolower($type) == 'buy') {
//echo 'buy fees trade trade';
$tradedAmountNet = $tradedAmount + abs($fees);
$receivedAmountNet = $receivedAmount;
} else {
//echo 'sell trade';
$tradedAmountNet = $tradedAmount;
$receivedAmountNet = $receivedAmount + abs($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' => $type,
'pair' => implode('-', $pair),
'tradedAmount' => $tradedAmountNet,
'tradedCurrency' => $tradedCurrency,
'tradedDevise' => $tradedDevise->getDevise(),
'fees' => $fees,
'receivedAmount' => $receivedAmountNet,
'receivedCurrency' => $receivedCurrency,
'receivedDevise' => $receivedDevise->getDevise(),
'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 updateDeviseAvailable() {
$urlApi = 'https://api.bitfinex.com/v1/symbols';
// fetch data
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $urlApi);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$rawData = curl_exec($curl);
curl_close($curl);
// decode to array
$data = json_decode($rawData, true);
//var_dump($data); exit;
$mapperDevise = new \Application\Mapper\DeviseMapper($this->entityManager);
$mapperDeviseBitfinex = new \Application\Mapper\DeviseBitfinexMapper($this->entityManager);
$serviceCMC = new \Application\Service\CMCService();
foreach($data as $pair){
$code1 = substr($pair, 0, 3);
$findDevise1 = $mapperDeviseBitfinex->findByCode(strtoupper($code1));
// var_dump($findDevise1);
$code2 = substr($pair, 3, 3);
$findDevise2 = $mapperDeviseBitfinex->findByCode(strtoupper($code2));
// var_dump($findDevise2);
if ($findDevise1 && $findDevise2) {
$entity1 = new \Application\Entity\DeviseBitfinex();
$entity1->devise = $findDevise1;
$entity1->nom = $findDevise1->getNom();
$entity1->setCode(strtoupper($code1));
$findBitfinex1 = $mapperDeviseBitfinex->findByCode(strtoupper($code1));
if (!$findBitfinex1) {
$mapperDeviseBitfinex->insert($entity1);
}
$entity2 = new \Application\Entity\DeviseBitfinex();
$entity2->devise = $findDevise2;
$entity2->nom = $findDevise2->getNom();
$entity2->setCode(strtoupper($code2));
$findBitfinex2 = $mapperDeviseBitfinex->findByCode(strtoupper($code2));
if (!$findBitfinex2) {
$mapperDeviseBitfinex->insert($entity2);
}
} else {
//var_dump($pair);
// exit;
// $code1 = substr($pair, 0, 3);
// $findDevise1 = $mapperDeviseBitfinex->findByCode(strtoupper($code1));
// if (!$findDevise1) {
// $infos = $serviceCMC->getInfoByCode(strtoupper($code1));
// }
//$infos = $serviceCMC->getInfoByCode('EURS');
// exit;
// $code2 = substr($pair, 2, 3);
// $findDevise2 = $mapperDevise->findByCode($code2);
// if (!$findDevise2) {
// $infos = $serviceCMC->getInfoByCode($code2);
// }
}
}
}
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;
}
}