Advertisement
Guest User

Poloniex API - PHP Wrapper (Final Tested Code)

a guest
Feb 28th, 2014
82,971
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.     // FINAL TESTED CODE - Created by Compcentral
  3.    
  4.     // NOTE: currency pairs are reverse of what most exchanges use...
  5.     //       For instance, instead of XPM_BTC, use BTC_XPM
  6.  
  7.     class poloniex {
  8.         protected $api_key;
  9.         protected $api_secret;
  10.         protected $trading_url = "https://poloniex.com/tradingApi";
  11.         protected $public_url = "https://poloniex.com/public";
  12.        
  13.         public function __construct($api_key, $api_secret) {
  14.             $this->api_key = $api_key;
  15.             $this->api_secret = $api_secret;
  16.         }
  17.            
  18.         private function query(array $req = array()) {
  19.             // API settings
  20.             $key = $this->api_key;
  21.             $secret = $this->api_secret;
  22.          
  23.             // generate a nonce to avoid problems with 32bit systems
  24.             $mt = explode(' ', microtime());
  25.             $req['nonce'] = $mt[1].substr($mt[0], 2, 6);
  26.          
  27.             // generate the POST data string
  28.             $post_data = http_build_query($req, '', '&');
  29.             $sign = hash_hmac('sha512', $post_data, $secret);
  30.          
  31.             // generate the extra headers
  32.             $headers = array(
  33.                 'Key: '.$key,
  34.                 'Sign: '.$sign,
  35.             );
  36.  
  37.             // curl handle (initialize if required)
  38.             static $ch = null;
  39.             if (is_null($ch)) {
  40.                 $ch = curl_init();
  41.                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  42.                 curl_setopt($ch, CURLOPT_USERAGENT,
  43.                     'Mozilla/4.0 (compatible; Poloniex PHP bot; '.php_uname('a').'; PHP/'.phpversion().')'
  44.                 );
  45.             }
  46.             curl_setopt($ch, CURLOPT_URL, $this->trading_url);
  47.             curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
  48.             curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  49.             curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  50.  
  51.             // run the query
  52.             $res = curl_exec($ch);
  53.  
  54.             if ($res === false) throw new Exception('Curl error: '.curl_error($ch));
  55.             //echo $res;
  56.             $dec = json_decode($res, true);
  57.             if (!$dec){
  58.                 //throw new Exception('Invalid data: '.$res);
  59.                 return false;
  60.             }else{
  61.                 return $dec;
  62.             }
  63.         }
  64.        
  65.         protected function retrieveJSON($URL) {
  66.             $opts = array('http' =>
  67.                 array(
  68.                     'method'  => 'GET',
  69.                     'timeout' => 10
  70.                 )
  71.             );
  72.             $context = stream_context_create($opts);
  73.             $feed = file_get_contents($URL, false, $context);
  74.             $json = json_decode($feed, true);
  75.             return $json;
  76.         }
  77.        
  78.         public function get_balances() {
  79.             return $this->query(
  80.                 array(
  81.                     'command' => 'returnBalances'
  82.                 )
  83.             );
  84.         }
  85.        
  86.         public function get_open_orders($pair) {       
  87.             return $this->query(
  88.                 array(
  89.                     'command' => 'returnOpenOrders',
  90.                     'currencyPair' => strtoupper($pair)
  91.                 )
  92.             );
  93.         }
  94.        
  95.         public function get_my_trade_history($pair) {
  96.             return $this->query(
  97.                 array(
  98.                     'command' => 'returnTradeHistory',
  99.                     'currencyPair' => strtoupper($pair)
  100.                 )
  101.             );
  102.         }
  103.        
  104.         public function buy($pair, $rate, $amount) {
  105.             return $this->query(
  106.                 array(
  107.                     'command' => 'buy',
  108.                     'currencyPair' => strtoupper($pair),
  109.                     'rate' => $rate,
  110.                     'amount' => $amount
  111.                 )
  112.             );
  113.         }
  114.        
  115.         public function sell($pair, $rate, $amount) {
  116.             return $this->query(
  117.                 array(
  118.                     'command' => 'sell',   
  119.                     'currencyPair' => strtoupper($pair),
  120.                     'rate' => $rate,
  121.                     'amount' => $amount
  122.                 )
  123.             );
  124.         }
  125.        
  126.         public function cancel_order($pair, $order_number) {
  127.             return $this->query(
  128.                 array(
  129.                     'command' => 'cancelOrder',
  130.                     'currencyPair' => strtoupper($pair),
  131.                     'orderNumber' => $order_number
  132.                 )
  133.             );
  134.         }
  135.        
  136.         public function withdraw($currency, $amount, $address) {
  137.             return $this->query(
  138.                 array(
  139.                     'command' => 'withdraw',   
  140.                     'currency' => strtoupper($currency),               
  141.                     'amount' => $amount,
  142.                     'address' => $address
  143.                 )
  144.             );
  145.         }
  146.        
  147.         public function get_trade_history($pair) {
  148.             $trades = $this->retrieveJSON($this->public_url.'?command=returnTradeHistory&currencyPair='.strtoupper($pair));
  149.             return $trades;
  150.         }
  151.        
  152.         public function get_order_book($pair) {
  153.             $orders = $this->retrieveJSON($this->public_url.'?command=returnOrderBook&currencyPair='.strtoupper($pair));
  154.             return $orders;
  155.         }
  156.        
  157.         public function get_volume() {
  158.             $volume = $this->retrieveJSON($this->public_url.'?command=return24hVolume');
  159.             return $volume;
  160.         }
  161.    
  162.         public function get_ticker($pair = "ALL") {
  163.             $pair = strtoupper($pair);
  164.             $prices = $this->retrieveJSON($this->public_url.'?command=returnTicker');
  165.             if($pair == "ALL"){
  166.                 return $prices;
  167.             }else{
  168.                 $pair = strtoupper($pair);
  169.                 if(isset($prices[$pair])){
  170.                     return $prices[$pair];
  171.                 }else{
  172.                     return array();
  173.                 }
  174.             }
  175.         }
  176.        
  177.         public function get_trading_pairs() {
  178.             $tickers = $this->retrieveJSON($this->public_url.'?command=returnTicker');
  179.             return array_keys($tickers);
  180.         }
  181.        
  182.         public function get_total_btc_balance() {
  183.             $balances = $this->get_balances();
  184.             $prices = $this->get_ticker();
  185.            
  186.             $tot_btc = 0;
  187.            
  188.             foreach($balances as $coin => $amount){
  189.                 $pair = "BTC_".strtoupper($coin);
  190.            
  191.                 // convert coin balances to btc value
  192.                 if($amount > 0){
  193.                     if($coin != "BTC"){
  194.                         $tot_btc += $amount * $prices[$pair];
  195.                     }else{
  196.                         $tot_btc += $amount;
  197.                     }
  198.                 }
  199.  
  200.                 // process open orders as well
  201.                 if($coin != "BTC"){
  202.                     $open_orders = $this->get_open_orders($pair);
  203.                     foreach($open_orders as $order){
  204.                         if($order['type'] == 'buy'){
  205.                             $tot_btc += $order['total'];
  206.                         }elseif($order['type'] == 'sell'){
  207.                             $tot_btc += $order['amount'] * $prices[$pair];
  208.                         }
  209.                     }
  210.                 }
  211.             }
  212.  
  213.             return $tot_btc;
  214.         }
  215.     }
  216. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement