dzhdmitry / tinkoff-invest-api
PHP client for Tinkoff Invest API
0.2.3
2022-01-30 08:46 UTC
Requires
- php: ^7.4
- ext-json: *
- amphp/websocket-client: ^1.0
- guzzlehttp/guzzle: ^7.0
- psr/log: ^1.1
- symfony/property-access: ^5.1
- symfony/serializer: ^5.1
Requires (Dev)
- phpunit/phpunit: ^9.3
- vimeo/psalm: ^4.9
README
Позволяет делать запросы к OpenAPI сервиса Тинькофф Инвестиции на языке PHP. Формат данных, получаемых по REST API, полностью соответствует схеме, указанной в документации для REST API.
В REST-клиенте реализованы следующие методы REST API:
- sandbox
- ✔ POST /sandbox/register
- ✔ POST /sandbox/currencies/balance
- ✔ POST /sandbox/positions/balance
- ✔ POST /sandbox/remove
- ✔ POST /sandbox/clear
- orders
- ✔ GET /orders
- ✔ POST /orders/limit-order
- ✔ POST /orders/market-order
- ✔ POST /orders/cancel
- portfolio
- ✔ GET /portfolio
- ✔ GET /portfolio/currencies
- market
- ✔ GET /market/stocks
- ✔ GET /market/bonds
- ✔ GET /market/etfs
- ✔ GET /market/currencies
- ✔ GET /market/orderbook
- ✔ GET /market/candles
- ✔ GET /market/search/by-figi
- ✔ GET /market/search/by-ticker
- operations
- ✔ GET /operations
- user
- ✔ GET /user/accounts
Также реализованы подписки на потоки данных по streaming протоколу:
- ✔ candle
- ✔ orderbook
- ✔ instrument_info
Требования
- PHP 7.4+
- Composer
Установка
- Установить клиент:
composer require dzhdmitry/tinkoff-invest-api
- Выполнить авторизацию, выпустить токены OpenAPI для биржи и Sandbox
Использование
// Пример 1. Получение списка акций use Dzhdmitry\TinkoffInvestApi\Rest\ClientFactory; // Создать клиент с токеном $client = (new ClientFactory())->create('YOUR_TRADE_TOKEN'); // Сделать запрос на получение списка акций $response = $client->market()->getStocks(); foreach ($response->getPayload()->getInstruments() as $instrument) { echo $instrument->getTicker() . "\n"; echo $instrument->getName() . "\n"; echo $instrument->getCurrency() . "\n"; }
// Пример 2. Получение портфеля клиента use Dzhdmitry\TinkoffInvestApi\Rest\ClientFactory; // Создать клиент с токеном $client = (new ClientFactory())->create('YOUR_TRADE_TOKEN'); $brokerAccountId = 'your-broker-account-id'; // Сделать запрос на получение портфеля клиента по счету $brokerAccountId $response = $client->portfolio()->get($brokerAccountId); foreach ($response->getPayload()->getPositions() as $position) { echo $position->getInstrumentType() . "\n"; echo $position->getTicker() . "\n"; echo $position->getName() . "\n"; echo $position->getBalance() . "\n"; }
// Пример 3. Создание лимитной заявки use Dzhdmitry\TinkoffInvestApi\Rest\ClientFactory; use Dzhdmitry\TinkoffInvestApi\Rest\Schema\Request\LimitOrderRequest; use Dzhdmitry\TinkoffInvestApi\Rest\Schema\Enum\OperationType; // Создать клиент с токеном $client = (new ClientFactory())->create('YOUR_TRADE_TOKEN'); // Сделать запрос на создание лимитной заявки на счете "Тинькофф" (Заявка на покупку 5 лотов USD по цене 75.20) $response = $client->orders()->postLimitOrder( 'BBG0013HGFT4', new LimitOrderRequest(5, OperationType::BUY, 75.20) ); $order = $response->getPayload(); echo $order->getOrderId() . "\n"; echo $order->getOperation() . "\n"; echo $order->getStatus() . "\n"; echo $order->getRequestedLots() . "\n"; echo $order->getExecutedLots() . "\n";
// Пример 4. Протокол Streaming use Dzhdmitry\TinkoffInvestApi\Streaming\ResponseDeserializerFactory; use Dzhdmitry\TinkoffInvestApi\Streaming\Schema\Payload\ErrorPayload; use Dzhdmitry\TinkoffInvestApi\Streaming\Schema\Payload\Orderbook; use Dzhdmitry\TinkoffInvestApi\Streaming\Schema\Request\OrderbookRequest; use Dzhdmitry\TinkoffInvestApi\Streaming\Schema\Response\AbstractResponse; use Dzhdmitry\TinkoffInvestApi\Streaming\Connection; use Dzhdmitry\TinkoffInvestApi\Streaming\WebsocketConnectionFactory; \Amp\Loop::run(function () { // Объект ResponseDeserializer можно использовать для десериализации ответов сервера $deserializer = (new ResponseDeserializerFactory())->create(); // Connection предоставляет упрощенный доступ к управлению подписками на потоки данных $connection = new Connection(yield WebsocketConnectionFactory::create('YOUR_TRADE_TOKEN')); // Подписка на информацию биржевой стакан по акциям Apple $connection->subscribe(new OrderbookRequest('BBG000B9XRY4', 4)); $i = 0; while ($message = yield $connection->receive()) { /** @var \Amp\Websocket\Message $message полученное из WebSocket сообщение */ /** @var AbstractResponse $response десериализованное тело сообщения */ $response = $deserializer->deserialize(yield $message->buffer()); echo $response->getEvent() . ' at ' . $response->getTime()->format(DATE_RFC3339) . "\n"; if ($response->getPayload() instanceof ErrorPayload) { echo ' - error: ' . $response->getPayload()->getError() . "\n"; } elseif ($response->getPayload() instanceof Orderbook) { echo ' - figi: ' . $response->getPayload()->getFigi() . "\n"; echo ' - bids: ' . count($response->getPayload()->getBids()) . "\n"; echo ' - asks: ' . count($response->getPayload()->getAsks()) . "\n"; } if (++$i >= 4) { // Закрыть соединение при получении 4 ответов $connection->close(); break; } // Получать каждое сообщение с интервалом в 1 сек yield \Amp\delay(1000); } });
Лицензия
Распространяется под лицензией MIT