API криптобирж

Обращение к API происходит по адресу: http://api.btcindex.io/crex/?method={method}, где {method} — метод API.

Методы:

method=tickers (по умолчанию)

Параметры:

  • type - тип (список см. в методе ticker_types, поле name)
  • count - кол-во записей (по умолчанию 1000, макс. 1000)
  • tickers - список идентификаторов тикеров, через запятую, макс. 30
  • tm - timestamp в секундах, от которого начать вывод данных, по умолчанию - count последних записей
  • api_key - ключ

Параметр tickers формируется следующим образом: exchange:symbol

Exchange: имя биржи (список см. в методе exchanges)

Symbol: наименование пары токенов (список токенов см. в методе products), например ethbtc, сначала base-токен (который продаем/покупаем), потом quote-токен (в котором указываем цену).

Пример: binance:ethbtc - курс eth к btc на бирже binance

В качестве наименования биржи можно указать “all” - означает “агрегированный курс со всех бирж”.

Если в symbol токены указать через тире, то будет рассчитан кросс-курс через btc, например binance:eth-usdt означает “кросс курс eth к usdt через btc на binance”. Можно также указать кросс-токен, добавив его между base и quote, например: binance:ltc-eth-usdt означает “кросс курс ltc к usdt через eth на binance”.

Пример:

http://api.btcindex.io/crex/?type=1h&count=10&tickers=binance:ethbtc,bitfinex:ethbtc&api_key=


{
    "type": "1h", // запрошенный тип тикера
    "tm": 1534298400, // запрошенный tm
    "dt": "2018-08-15 02:00:00", // запрошенный tm в utc
    "count": 10, // кол-во
    "tickers": {
        1534298400: { // время начала периода
            "dt": "2018-08-15 02:00:00", // время начала периода в utc
            "binance:ethbtc": { // первый тикер
                 "average": 0.04590245, // средневзвешенная цена торгов
                 "buy_volume": 6179.74199828, // объем покупок
                 "sell_volume": 6030.61199786, // объем продаж
                 "open": 0.045414, // цена на начало периода (первая сделка)
                 "high": 0.046369, // максимальная цена за период
                 "low": 0.045403, // минимальная цена за период
                 "close": 0.045713 // цена на конец периода (последняя сделка)
             },
             "bitfinex:ethbtc": { // второй тикер
             }
        }
    }
}

method=ticker_types

Список типов тикеров. Например: 1s - одна секунда, 15m - 15 минут и т.п. Суффикс “a” (1da) означает “скользящее среднее” - т.е. “последние 24 часа”, вместо 1d (за текущие сутки по UTC). 1w - недельные тикеры начинаются в понедельник. 1M - месячные тикеры начинаются первого числа. 1Ma - скользящее среднее за 30 дней.

Пример:

http://api.btcindex.io/crex/?method=ticker_types&api_key=


{
    "types": {
        "1s": {
            "id": 1,
            "name": "1s", // название
            "update_period": 1 // периодичность пересчета, в секундах
        },
        "15s": {
            "id": 2,
            "name": "15s",
            "update_period": 3
        },
}

method=exchanges

Список бирж.

Пример:

http://api.btcindex.io/crex/?method=exchanges&api_key=


method=products

Список токенов.

Пример:

http://api.btcindex.io/crex/?method=products&api_key=

API через Websocket

Обращение к API происходит по адресу: wss://btcindex.io/ws

Для получения тикеров в реальном времени отправляем json:


{
    "method": "subscribe", // подписка на обновления
    "type": "1s", // тип, см. ticker_types выше)
    "ticker": "binance:ethbtc" // биржа+пара
}

Описание формата параметра ticker см. выше.

Для подписки на несколько тикеров отправляем несколько подписок.

В ответ получаем:


{
    "method":"subscribed", // подписан
    "type":"1s",
    "ticker":"binance:ethbtc"
}

Далее при каждом пересчете тикера получаем сообщение:


{
    "method":"data", // данные
    "type":"1s", // тип тикера
    "ticker":"binance:ethbtc", // наименование
    "timestamp":1534329887, // время начала периода
    "datetime":"2018-08-15 10:44:47", // время начала периода в UTC
    // описание полей см. выше
    "average":0.04471875,
    "buy_volume":0.186,
    "sell_volume":0.132,
    "open":0.044717,
    "high":0.04472,
    "low":0.044717,
    "close":0.044717
}

На каждый timestamp сервер отправляет несколько сообщений (при каждом пересчете данных за период).


Database Exception – yii\db\Exception
Copied! Copy Stacktrace Search Stackoverflow Search Google Exception

Database Exceptionyii\db\Exception

SQLSTATE[HY000] [2002] Connection refused

  • 1. in /raid/1/www/2yachts/vendor/yiisoft/yii2/db/Connection.php at line 649
    640641642643644645646647648649650651652653654655656657658
     
                if ($enableProfiling) {
                    Yii::endProfile($token, __METHOD__);
                }
            } catch (\PDOException $e) {
                if ($enableProfiling) {
                    Yii::endProfile($token, __METHOD__);
                }
     
                throw new Exception($e->getMessage(), $e->errorInfo, (int) $e->getCode(), $e);
            }
        }
     
        /**
         * Closes the currently active DB connection.
         * It does nothing if the connection is already closed.
         */
        public function close()
        {
    
  • 2. in /raid/1/www/2yachts/vendor/yiisoft/yii2/db/Connection.php at line 1063 yii\db\Connection::open()
    1057105810591060106110621063106410651066106710681069
         * Returns the PDO instance for the currently active master connection.
         * This method will open the master DB connection and then return [[pdo]].
         * @return PDO the PDO instance for the currently active master connection.
         */
        public function getMasterPdo()
        {
            $this->open();
            return $this->pdo;
        }
     
        /**
         * Returns the currently active slave connection.
         * If this method is called for the first time, it will try to open a slave connection when [[enableSlaves]] is true.
    
  • 3. in /raid/1/www/2yachts/vendor/yiisoft/yii2/db/Connection.php at line 1050 yii\db\Connection::getMasterPdo()
    1044104510461047104810491050105110521053105410551056
         * is available and `$fallbackToMaster` is false.
         */
        public function getSlavePdo($fallbackToMaster = true)
        {
            $db = $this->getSlave(false);
            if ($db === null) {
                return $fallbackToMaster ? $this->getMasterPdo() : null;
            }
     
            return $db->pdo;
        }
     
        /**
    
  • 4. in /raid/1/www/2yachts/vendor/yiisoft/yii2/db/Schema.php at line 463 yii\db\Connection::getSlavePdo()
    457458459460461462463464465466467468469
        public function quoteValue($str)
        {
            if (!is_string($str)) {
                return $str;
            }
     
            if (mb_stripos($this->db->dsn, 'odbc:') === false && ($value = $this->db->getSlavePdo()->quote($str)) !== false) {
                return $value;
            }
     
            // the driver doesn't support quote (e.g. oci)
            return "'" . addcslashes(str_replace("'", "''", $str), "\000\n\r\\\032") . "'";
        }
    
  • 5. in /raid/1/www/2yachts/vendor/yiisoft/yii2/db/Connection.php at line 942 yii\db\Schema::quoteValue('3164a899ce3604f0d425edfc2a8cdabf')
    936937938939940941942943944945946947948
         * @param string $value string to be quoted
         * @return string the properly quoted string
         * @see https://secure.php.net/manual/en/pdo.quote.php
         */
        public function quoteValue($value)
        {
            return $this->getSchema()->quoteValue($value);
        }
     
        /**
         * Quotes a table name for use in a query.
         * If the table name contains schema prefix, the prefix will also be properly quoted.
         * If the table name is already quoted or contains special characters including '(', '[[' and '{{',
    
  • 6. in /raid/1/www/2yachts/vendor/yiisoft/yii2/db/Command.php at line 211 yii\db\Connection::quoteValue('3164a899ce3604f0d425edfc2a8cdabf')
    205206207208209210211212213214215216217
            $params = [];
            foreach ($this->params as $name => $value) {
                if (is_string($name) && strncmp(':', $name, 1)) {
                    $name = ':' . $name;
                }
                if (is_string($value) || $value instanceof Expression) {
                    $params[$name] = $this->db->quoteValue((string)$value);
                } elseif (is_bool($value)) {
                    $params[$name] = ($value ? 'TRUE' : 'FALSE');
                } elseif ($value === null) {
                    $params[$name] = 'NULL';
                } elseif (!is_object($value) && !is_resource($value)) {
                    $params[$name] = $value;
    
  • 7. in /raid/1/www/2yachts/vendor/yiisoft/yii2/db/Command.php at line 1126 yii\db\Command::getRawSql()
    1120112111221123112411251126112711281129113011311132
         * @return array array of two elements, the first is boolean of whether profiling is enabled or not.
         * The second is the rawSql if it has been created.
         */
        protected function logQuery($category)
        {
            if ($this->db->enableLogging) {
                $rawSql = $this->getRawSql();
                Yii::info($rawSql, $category);
            }
            if (!$this->db->enableProfiling) {
                return [false, isset($rawSql) ? $rawSql : null];
            }
     
    
  • 8. in /raid/1/www/2yachts/vendor/yiisoft/yii2/db/Command.php at line 1147 yii\db\Command::logQuery('yii\db\Command::query')
    1141114211431144114511461147114811491150115111521153
         * @return mixed the method execution result
         * @throws Exception if the query causes any problem
         * @since 2.0.1 this method is protected (was private before).
         */
        protected function queryInternal($method, $fetchMode = null)
        {
            list($profile, $rawSql) = $this->logQuery('yii\db\Command::query');
     
            if ($method !== '') {
                $info = $this->db->getQueryCacheInfo($this->queryCacheDuration, $this->queryCacheDependency);
                if (is_array($info)) {
                    /* @var $cache \yii\caching\CacheInterface */
                    $cache = $info[0];
    
  • 9. in /raid/1/www/2yachts/vendor/yiisoft/yii2/db/Command.php at line 424 yii\db\Command::queryInternal('fetch', null)
    418419420421422423424425426427428429430
         * @return array|false the first row (in terms of an array) of the query result. False is returned if the query
         * results in nothing.
         * @throws Exception execution failed
         */
        public function queryOne($fetchMode = null)
        {
            return $this->queryInternal('fetch', $fetchMode);
        }
     
        /**
         * Executes the SQL statement and returns the value of the first column in the first row of data.
         * This method is best used when only a single value is needed for a query.
         * @return string|int|null|false the value of the first column in the first row of the query result.
    
  • 10. in /raid/1/www/2yachts/api/modules/widget/components/WidgetController.php at line 61 yii\db\Command::queryOne()
    55565758596061626364656667
                'SELECT `offset`
                FROM api_widget_page
                WHERE `hash`=:hash AND type=:type', [
                    ':hash' => $hash,
                    ':type' => $type,
                ]
            )->queryOne();
     
            if (is_array($offset)) return $offset['offset'];
     
            return null;
        }
     
    
  • 11. in /raid/1/www/2yachts/api/modules/widget/controllers/EntityController.php at line 37 – api\modules\widget\components\WidgetController::findOffset('region_rent')
    31323334353637383940414243
     
            $cache = YII_ENV != 'dev' ? Yii::$app->cache->get($cache_name) : null;
            if (!$cache) {
                $list = [];
     
                // Регионы чартера
                $offset = $this->findOffset('region_rent');
                if (!$offset) {
                    $offset = SeoRegion::calcOffsetRegionType('rent', $this->page);
                    $this->setOffset('region_rent', $offset);
                }
                $region_charter = SeoRegion::getRegionTypeByPage('rent', $offset);
                $region_charter = $this->getRegionData($region_charter);
    
  • 12. api\modules\widget\controllers\EntityController::actionIndex()
  • 13. in /raid/1/www/2yachts/vendor/yiisoft/yii2/base/InlineAction.php at line 57 – call_user_func_array([api\modules\widget\controllers\EntityController, 'actionIndex'], [])
    515253545556575859
            $args = $this->controller->bindActionParams($this, $params);
            Yii::debug('Running action: ' . get_class($this->controller) . '::' . $this->actionMethod . '()', __METHOD__);
            if (Yii::$app->requestedParams === null) {
                Yii::$app->requestedParams = $args;
            }
     
            return call_user_func_array([$this->controller, $this->actionMethod], $args);
        }
    }
    
  • 14. in /raid/1/www/2yachts/vendor/yiisoft/yii2/base/Controller.php at line 181 yii\base\InlineAction::runWithParams(['/api/widget/entity' => '', 'direction' => 'horizontal', 'lang' => 'ru', 'page' => '3164a899ce3604f0d425edfc2a8cdabf'])
    175176177178179180181182183184185186187
            }
     
            $result = null;
     
            if ($runAction && $this->beforeAction($action)) {
                // run the action
                $result = $action->runWithParams($params);
     
                $result = $this->afterAction($action, $result);
     
                // call afterAction on modules
                foreach ($modules as $module) {
                    /* @var $module Module */
    
  • 15. in /raid/1/www/2yachts/vendor/yiisoft/yii2/base/Module.php at line 534 yii\base\Controller::runAction('', ['/api/widget/entity' => '', 'direction' => 'horizontal', 'lang' => 'ru', 'page' => '3164a899ce3604f0d425edfc2a8cdabf'])
    528529530531532533534535536537538539540
            $parts = $this->createController($route);
            if (is_array($parts)) {
                /* @var $controller Controller */
                list($controller, $actionID) = $parts;
                $oldController = Yii::$app->controller;
                Yii::$app->controller = $controller;
                $result = $controller->runAction($actionID, $params);
                if ($oldController !== null) {
                    Yii::$app->controller = $oldController;
                }
     
                return $result;
            }
    
  • 16. in /raid/1/www/2yachts/vendor/yiisoft/yii2/web/Application.php at line 104 yii\base\Module::runAction('widget/entity', ['/api/widget/entity' => '', 'direction' => 'horizontal', 'lang' => 'ru', 'page' => '3164a899ce3604f0d425edfc2a8cdabf'])
    9899100101102103104105106107108109110
                $params = $this->catchAll;
                unset($params[0]);
            }
            try {
                Yii::debug("Route requested: '$route'", __METHOD__);
                $this->requestedRoute = $route;
                $result = $this->runAction($route, $params);
                if ($result instanceof Response) {
                    return $result;
                }
     
                $response = $this->getResponse();
                if ($result !== null) {
    
  • 17. in /raid/1/www/2yachts/vendor/yiisoft/yii2/base/Application.php at line 392 yii\web\Application::handleRequest(yii\web\Request)
    386387388389390391392393394395396397398
        {
            try {
                $this->state = self::STATE_BEFORE_REQUEST;
                $this->trigger(self::EVENT_BEFORE_REQUEST);
     
                $this->state = self::STATE_HANDLING_REQUEST;
                $response = $this->handleRequest($this->getRequest());
     
                $this->state = self::STATE_AFTER_REQUEST;
                $this->trigger(self::EVENT_AFTER_REQUEST);
     
                $this->state = self::STATE_SENDING_RESPONSE;
                $response->send();
    
  • 18. in /raid/1/www/2yachts/public_html/api/index.php at line 20 yii\base\Application::run()
    14151617181920
        require __DIR__ . '/../../common/config/main.php',
        require __DIR__ . '/../../common/config/main-local.php',
        require __DIR__ . '/../../api/config/main.php',
        require __DIR__ . '/../../api/config/main-local.php'
    );
     
    (new yii\web\Application($config))->run();
    
$_GET = [
    '/api/widget/entity' => '',
    'direction' => 'horizontal',
    'lang' => 'ru',
    'page' => '3164a899ce3604f0d425edfc2a8cdabf',
];