Bitstamp API的PHP实现

时间:2013-10-19 20:18:23

标签: php api bitcoin

我正在尝试通过将PHP代码放在crontab中来实现PHP API以进行bitstamp以执行重新发生的事务。

我试图让API与bitstamp通信,每次执行购买X量的BTC(然后从crontab控制频率),这应该是基本实现的定义。

这是快乐,我绝对不是PHP编码器。 BX Media的人很好,可以在github上发布他们的PHP框架:(https://github.com/willmoss/bitstamp-php-api)。

但是,我理解他们所做的是我必须创建“父”PHP然后包含他们的API代码,其中也包括我的凭据

所以我把最基本的PHP代码放在一起

<?php
require('bitstamp.php');
$KEY = 'XXXXXXXXXXXXXXXX';
$SECRET = 'XXXXXXXXXXXXXXXX';
$CLIENT_ID = 'XXXXX';

$bs = new Bitstamp("KEY","SECRET","CLIENT_ID");

// print_r($bs->ticker());

$bs->buyBTC(0.01); // buy 0.01 bitcoins at ask price
//$bs->bitstamp_query("buy", array('amount'=>'0.05','price'=>'50')); 


?>

注意:“bitstamp.php”位于同一目录中,目前在Github上。

<?php

/**
 * @package Bitstamp API
 * @author https://bxmediaus.com - BX MEDIA - PHP + Bitcoin. We are ready to work on your next bitcoin project. Only high quality coding. https://bxmediaus.com
 * @version 0.1
 * @access public
 * @license http://www.opensource.org/licenses/LGPL-3.0
 */

class Bitstamp
{
    private $key;
    private $secret;
    private $client_id;
    public $redeemd;  // Redeemed code information
    public $withdrew; // Withdrawal information
    public $info;     // Result from getInfo()
    public $ticker;   // Current ticker (getTicker())
    public $eurusd;   // Current eur/usd
    /**
     * Bitstamp::__construct()
     * Sets required key and secret to allow the script to function
     * @param Bitstamp API Key $key
     * @param Bitstamp Secret $secret
     * @return
     */
    public function __construct($key, $secret, $client_id)
    {
        if (isset($secret) && isset($key) && isset($client_id))
        {
            $this->key = $key;
            $this->secret = $secret;
            $this->client_id = $client_id;
        } else
            die("NO KEY/SECRET/CLIENT ID");
    }
    /**
     * Bitstamp::bitstamp_query()
     * 
     * @param API Path $path
     * @param POST Data $req
     * @return Array containing data returned from the API path
     */
    public function bitstamp_query($path, array $req = array())
    {
        // API settings
        $key = $this->key;

        // generate a nonce as microtime, with as-string handling to avoid problems with 32bits systems
        $mt = explode(' ', microtime());
        $req['nonce'] = $mt[1] . substr($mt[0], 2, 6);
        $req['key'] = $key;
        $req['signature'] = $this->get_signature($req['nonce']);


        // generate the POST data string
        $post_data = http_build_query($req, '', '&');

        // any extra headers
        $headers = array();

        // our curl handle (initialize if required)
        static $ch = null;
        if (is_null($ch))
        {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_USERAGENT,
                'Mozilla/4.0 (compatible; MtGox PHP client; ' . php_uname('s') . '; PHP/' .
                phpversion() . ')');
        }
        curl_setopt($ch, CURLOPT_URL, 'https://www.bitstamp.net/api/' . $path .'/');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // run the query
        $res = curl_exec($ch);
        if ($res === false)
            throw new \Exception('Could not get reply: ' . curl_error($ch));
        $dec = json_decode($res, true);
        if (!$dec)
            throw new \Exception('Invalid data received, please make sure connection is working and requested API exists');
        return $dec;
    }

    /**
     * Bitstamp::ticker()
     * Returns current ticker from Bitstamp
     * @return $ticker
     */
    function ticker() {
        $ticker = $this->bitstamp_query('ticker');
        $this->ticker = $ticker; // Another variable to contain it.
        return $ticker;
    }

    /**
     * Bitstamp::eurusd()
     * Returns current EUR/USD rate from Bitstamp
     * @return $ticker
     */
    function eurusd() {
        $eurusd = $this->bitstamp_query('eur_usd');
        $this->eurusd = $eurusd; // Another variable to contain it.
        return $eurusd;
    }

    /**
    * Bitstamp::buyBTC()
    *
    * @param float $amount
    */
    function buyBTC($amount){

      if (!isset($ticker))
        $this->ticker();

      $ticker = $this->ticker;

        return $this->bitstamp_query('buy', array('amount' => $amount, 'price' => $ticker['ask']));

    }

    /**
    * Bitstamp::sellBTC()
    *
    * @param float $amount
    * @param float $price
    * @param string $currency
    */
    function sellBTC($amount){

      if (!isset($ticker))
        $this->ticker();

      $ticker = $this->ticker;

        return $this->bitstamp_query('sell', array('amount' => $amount, 'price' => $ticker['bid']));

    }


    /**
    * Bitstamp::get_signature()
    * Compute bitstamp signature
    * @param float $nonce
    */
    private function get_signature($nonce)
    {

      $message = $nonce.$this->client_id.$this->key;

      return strtoupper(hash_hmac('sha256', $message, $this->secret));

    }
}

我的执行失败了。由于Bitstamp API的作者显然与他的客户合作,我认为错误是在我的“父”PHP代码上。 (注意:我在本地版本上使用真正的密钥和秘密)。

任何人对此API或一般情况或建议有任何经验吗?

2 个答案:

答案 0 :(得分:2)

我不确定这只是匿名还是实际代码,所以如果我有错误,请告诉我,但你有这一行:

$bs = new Bitstamp("KEY","SECRET","CLIENT_ID");

这将实际字符串“KEY”,“SECRET”和“CLIENT_ID”传递给函数;你想要做的是传递你在上面的行上定义的变量,如下所示:

$bs = new Bitstamp($KEY,$SECRET,$CLIENT_ID);

答案 1 :(得分:1)

作为这个api的作者(我是Bx Media的首席执行官):

你需要像这样重构构造函数:

$bs = new Bitstamp("put your key here","put your secret here","put your client ID here");

IE中。你实际上把你的密钥/秘密/ ID放在了语音标记之间。

在PHP中,当你输入$符号时,它会将某些内容设置为变量。

在此处查看更多信息:http://www.w3schools.com/php/php_variables.asp

如果您想使用变量,您也可以使用IMSoP的解决方案。

请注意,我们今晚还更新了图书馆的一些新功能。因此,请将您的repo更新为最新提交以获取新代码。

干杯!