PHP code example of street-yo / tinkoff-invest-api

1. Go to this page and download the library: Download street-yo/tinkoff-invest-api library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

street-yo / tinkoff-invest-api example snippets


// Пример 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);
    }
});