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 BittrexService
*
* @author jimmy
*/
class BinanceAPIService {
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 $api;
protected $file;
protected $exchangeName = 'Binance';
protected $requiredColumn = array(
'Uuid',
'Exchange',
'TimeStamp',
'OrderType',
'Limit',
'Quantity',
'QuantityRemaining',
'Commission',
'Price',
'PricePerUnit',
'IsConditional',
'Condition',
'ConditionTarget',
'ImmediateOrCancel',
'Closed'
);
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 getTimeStampIndex() {
return $this->columnCsvMapper['TimeStamp'];
}
protected function getDatetime($arrayLine) {
$dateStr = $arrayLine[$this->getTimeStampIndex()];
$dateTime = \DateTime::createFromFormat('m/d/Y H:i:s a', $dateStr);
return $dateTime;
}
protected function getPairIndex() {
return $this->columnCsvMapper['Exchange'];
}
protected function getPair($arrayLine) {
$pairStr = $arrayLine[$this->getPairIndex()];
$arrayAsset = explode('-', $pairStr);
return $arrayAsset;
}
protected function getOrderTypeIndex() {
return $this->columnCsvMapper['OrderType'];
}
protected function getType($arrayLine) {
$orderType = $arrayLine[$this->getOrderTypeIndex()];
if ($orderType == 'LIMIT_SELL') {
$type = 'sell';
} else if ($orderType == 'LIMIT_BUY') {
$type = 'buy';
}
return $type;
}
protected function getAmountIndex() {
return $this->columnCsvMapper['Quantity'];
}
protected function getTradedAmount($arrayLine, $type) {
if (strtolower($type) == 'buy') {
$tradedAmount = $arrayLine[$this->getPriceIndex()];
//var_dump($price, $tradedAmount); exit;
} else {
$tradedAmount = $arrayLine[$this->getAmountIndex()];
//var_dump($tradedAmount, $amount);
}
return $tradedAmount;
}
protected function getPriceIndex() {
return $this->columnCsvMapper['Price'];
}
protected function getFeesIndex() {
return $this->columnCsvMapper['Commission'];
}
protected function getTxidIndex() {
return $this->columnCsvMapper['Uuid'];
}
//https://api.bitfinex.com/v1/symbols recupere les paires autorisées
// Bittrex date
protected function getFees($arrayLine) {
$fees = $arrayLine[$this->getFeesIndex()];
return $fees;
}
protected function getTradedCurrency($pair, $type) {
if (strtolower($type) == 'buy') {
return $pair[0];
} else {
return $pair[1];
}
}
protected function getReceivedAmount($arrayLine, $type) {
if (strtolower($type) == 'buy') {
$receivedAmount = $arrayLine[$this->getAmountIndex()];
//var_dump($price, $tradedAmount); exit;
} else {
$receivedAmount = $arrayLine[$this->getPriceIndex()];
//var_dump($tradedAmount, $amount);
}
return $receivedAmount;
}
protected function getReceivedCurrency($pair, $type) {
if (strtolower($type) == 'buy') {
return $pair[1];
} else {
return $pair[0];
}
}
protected function getTxid($arrayLine) {
$txId = $arrayLine[$this->getTxidIndex()];
return $txId;
}
public function __construct($data, $user, $exchange, \Doctrine\ORM\EntityManager $entityManager) {
//$this->file = $file;
//var_dump($user->getId());
$this->user = $user;
$this->exchange = $exchange;
$this->entityManager = $entityManager;
$this->api = new \Application\ExchangeAPI\BinanceAPI($data['public'], $data['private']);
// echo $time_elapsed_secs;
// exit;
//}
}
public function getEntityManager() {
return $this->entityManager;
}
public function getUser() {
return $this->user;
}
public function getExchange() {
return $this->exchange;
}
public function importTradesHistory() {
// delete all trade
$ledgioMapper = new \Application\Mapper\LedgioMapper($this->getEntityManager());
$query = $this->getEntityManager()->createQuery("DELETE FROM Application\Entity\Ledgio l WHERE l.user = " . $this->getUser()->getId() . ' AND l.exchange = ' . $this->getExchange()->getId());
$query->execute();
$query2 = $this->getEntityManager()->createQuery("DELETE FROM Application\Entity\Import l WHERE l.user = " . $this->getUser()->getId() . ' AND l.exchange = ' . $this->getExchange()->getId());
$query2->execute();
$exchangeInfos = $this->api->exchangeInfo();
$listOfPair = $exchangeInfos['symbols'];
//echo '<pre>';
// var_dump($listOfPair);
$i = 0;
$index = 0;
$batchSize = 50;
$mapperExchange = new \Application\Mapper\ExchangeMapper($this->getEntityManager());
$exchange = $mapperExchange->findByName(strtolower($this->exchangeName));
$importEntity = new \Application\Entity\Import(
array(
'user' => $this->getUser(),
'exchange' => $exchange,
'sourceType' => 'api',
'name' => 'API ' . $exchange->getName(),
'nombreTrade' => 0,
'datetimeImport' => new \DateTime()
));
$mapperImport = new \Application\Mapper\ImportMapper($this->getEntityManager());
$mapperImport->insert($importEntity);
foreach ($listOfPair as $pairInfo) {
// var_dump($this->api->history($pairInfo['symbol']));
// var_dump($pairInfo);
// exit;
file_put_contents('/Users/jimmy/Sites/ledgio2/data/logjob.txt', date('Y-m-d H:i:s') . PHP_EOL, FILE_APPEND | LOCK_EX);
file_put_contents('/Users/jimmy/Sites/ledgio2/data/logjob.txt', $pairInfo['symbol'] . PHP_EOL, FILE_APPEND | LOCK_EX);
$arrayTrades = $this->api->history($pairInfo['symbol']);
file_put_contents('/Users/jimmy/Sites/ledgio2/data/logjob.txt', print_r($arrayTrades) . PHP_EOL, FILE_APPEND | LOCK_EX);
//file_put_contents('/Users/jimmy/Sites/ledgio2/data/logjob.txt', print_r($arrayTrades) . PHP_EOL, FILE_APPEND | LOCK_EX);
if (!empty($arrayTrades)) {
foreach ($arrayTrades as $tradeInfos) {
file_put_contents('/Users/jimmy/Sites/ledgio2/data/logjob.txt', 'trades:' . print_r($arrayTrades) . PHP_EOL, FILE_APPEND | LOCK_EX);
//$datetimeTransaction = \DateTime::createFromFormat('U', $tradeInfos['time']);
//var_dump($tradeInfos['time']); exit;
$datetimeTransaction = new \DateTime();
$datetimeTransaction->setTimestamp($tradeInfos['time'] / 1000);
$commissionAsset = $tradeInfos['commissionAsset'];
$commision = $tradeInfos['commission'];
$pair = $pairInfo['symbol'];
$tradedAmountNet = $tradeInfos['qty'];
$tradedCurrency = str_replace($commissionAsset, '', $pair);
$receivedAmountNet = $tradeInfos['quoteQty'] - $tradeInfos['commission'];
$receivedCurrency = $commissionAsset;
$txId = $tradeInfos['id'];
$ledgio = new \Application\Entity\Ledgio(array(
'datetimeTransaction' => $datetimeTransaction,
//'user' => $user,
'exchange' => $exchange,
'type' => 'test',
'pair' => 'test2',
'tradedAmount' => $tradedAmountNet ? $tradedAmountNet : 0,
'tradedCurrency' => $tradedCurrency,
'fees' => $commision,
'receivedAmount' => $receivedAmountNet,
'receivedCurrency' => $receivedCurrency,
'txId' => $txId,
'import' => $importEntity
));
file_put_contents('/Users/jimmy/Sites/ledgio2/data/logjob.txt', print_r($tradeInfos) . PHP_EOL, FILE_APPEND | LOCK_EX);
//var_dump($ledgio);
$ledgio->setUser($this->getUser());
// var_dump($ledgio);
// exit;
$this->getEntityManager()->persist($ledgio);
$this->countLineRecorded++;
//$this->getEntityManager()->merge($this->getUser());
if (($index % $batchSize) == 0) {
$this->getEntityManager()->flush();
//$em->clear('\Application\Entity\Ledgio');
}
}
} else {
echo 'pas de transaction' . $pairInfo['symbol'];
}
// "symbol": "BNBBTC",
// "id": 28457,
// "orderId": 100234,
// "price": "4.00000100",
// "qty": "12.00000000",
// "quoteQty": "48.000012",
// "commission": "10.10000000",
// "commissionAsset": "BNB",
// "time": 1499865549590,
// "isBuyer": true,
// "isMaker": false,
// "isBestMatch": true
// if ($i++ == 3) {
// exit;
// }
}
$this->getEntityManager()->flush();
$importEntity->setNombreTrade($this->countLineRecorded);
$mapperImport->update($importEntity);
//$em->clear();
//$em->clear('\Application\Entity\Ledgio');
//$time_elapsed_secs = microtime(true) - $start;
}
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;
// }
}