### Get User Info - Python Example Source: https://developer.tbank.ru/invest/api/users-service-get-info This Python example demonstrates how to call the GetInfo endpoint to retrieve user data. It shows the necessary imports and client setup. ```python import grpc from tinkoff.invest.api.contract.v1 import users_pb2 from tinkoff.invest.api.contract.v1 import users_pb2_grpc def get_user_info(): channel = grpc.insecure_channel('invest-public-api.tbank.ru:443') client = users_pb2_grpc.UsersServiceStub(channel) metadata = [ ('authorization', 'Bearer ') ] request = users_pb2.GetInfoRequest() try: response = client.GetInfo(request, metadata=metadata) print(response) except grpc.RpcError as e: print(f"Error: {e.code()} - {e.details()}") if __name__ == '__main__': get_user_info() ``` -------------------------------- ### Get User Info - Node.js Example Source: https://developer.tbank.ru/invest/api/users-service-get-info This Node.js example shows how to fetch user information using the GetInfo method. It covers setting up the client and making the request. ```javascript const grpc = require('@grpc/grpc-js'); const protoLoader = require('@grpc/proto-loader'); const PROTO_PATH = __dirname + '/users.proto'; // Assuming users.proto is in the same directory const packageDefinition = protoLoader.loadSync(PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }); const protoDescriptor = grpc.loadPackageDefinition(packageDefinition); const users = protoDescriptor.tinkoff.public.invest.api.contract.v1.UsersService; const client = new users.UsersService('invest-public-api.tbank.ru:443', grpc.credentials.createInsecure()); const metadata = new grpc.Metadata(); metadata.add('authorization', 'Bearer '); client.getInfo({}, metadata, (error, response) => { if (error) { console.error('Error:', error); } else { console.log('User Info:', response); } }); ``` -------------------------------- ### Get User Info - Response Example Source: https://developer.tbank.ru/invest/api/users-service-get-info This is an example of a successful (200 OK) response from the GetInfo endpoint, detailing the structure of the returned user information. ```json { "qualifiedForWorkWith": [ "qualifiedForWorkWith", "qualifiedForWorkWith" ], "riskLevelCode": "riskLevelCode", "qualStatus": true, "premStatus": true, "tariff": "tariff", "userId": "userId" } ``` -------------------------------- ### GetBrandBy Go Request Example Source: https://developer.tbank.ru/invest/api/instruments-service-get-brand-by Example of how to make a GetBrandBy request using Go. This demonstrates setting up the request with the necessary headers and body. ```go package main import ( "bytes" "fmt" "net/http" ) func main() { url := "https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/GetBrandBy" payload := []byte(`{ "id": "string" }`) // Replace "string" with actual ID req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer ") // Replace with your token client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() // Handle response body here fmt.Println("Status Code:", res.StatusCode) } ``` -------------------------------- ### Get User Bank Accounts (PHP) Source: https://developer.tbank.ru/invest/api/users-service-get-bank-accounts Example of how to call the GetBankAccounts endpoint using PHP. This snippet includes the necessary gRPC client setup. ```php $client = new UsersServiceClient('invest-public-api.tbank.ru:443', [ 'credentials' => grpc::createInsecure(), ]); $request = new GetBankAccountsRequest(); list($element, $status) = $client->getBankAccounts($request)->wait(); if ($status->code !== GrpcSTATUS_OK) { echo "Error: " . $status->details . " "; exit(1); } echo $element; ``` -------------------------------- ### OptionsBy Request Example (Go) Source: https://developer.tbank.ru/invest/api/instruments-service-options-by Example of how to make a POST request to the OptionsBy endpoint using Go. This snippet demonstrates setting up the request body and headers. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { url := "https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/OptionsBy" payload := map[string]string{ "basicAssetUid": "string", "basicAssetPositionUid": "string", "basicInstrumentId": "string", } payloadBytes, err := json.Marshal(payload) if err != nil { fmt.Println("Error marshaling payload:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Authorization", "Bearer ") req.Header.Set("Content-Type", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() fmt.Println("Status Code:", res.StatusCode) // Process response body here } ``` -------------------------------- ### GetInstrumentBy Request Example (Go) Source: https://developer.tbank.ru/invest/api/instruments-service-get-instrument-by Example of how to make a GetInstrumentBy request using Go. This includes setting up the client and constructing the request. ```go package main import ( "context" "fmt" "log" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/wrapperspb" investapi "github.com/TinkoffInvestAPI/invest-api-go-sdk/proto" ) func main() { ctx := context.Background() // Replace with your actual token and sandbox URL conn, err := grpc.DialContext(ctx, "sandbox-api.tinkoff.com:8024", grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() instrumentsClient := investapi.NewInstrumentsServiceClient(conn) // Example: Get instrument by FIGI figi := "BBG000B9XW57" // Example FIGI for Apple Inc. resp, err := instrumentsClient.GetInstrumentBy(ctx, &investapi.InstrumentRequest{ idType: investapi.InstrumentIdType_INSTRUMENT_ID_TYPE_FIGI, id: figi, }) if err != nil { log.Fatalf("GetInstrumentBy error: %v", err) } fmt.Printf("Instrument: %+v\n", resp.GetInstrument()) } ``` -------------------------------- ### Get Candles Response Example Source: https://developer.tbank.ru/invest/api/market-data-service-get-candles Example of a successful response when retrieving candlestick data. ```APIDOC ## Get Candles Response Example ### Description This is an example of a successful response (200 OK) for the get candles endpoint, detailing the structure of the returned candlestick data. ### Response #### Success Response (200) - **candles** (array) - An array of candle objects. - **volume** (string) - The trading volume for the period. - **high** (object) - The highest price during the period. - **nano** (integer) - Nanoparts of the price. - **units** (string) - The main units of the price. - **low** (object) - The lowest price during the period. - **nano** (integer) - Nanoparts of the price. - **units** (string) - The main units of the price. - **volumeBuy** (string) - The volume of buy orders. - **volumeSell** (string) - The volume of sell orders. - **time** (string) - The timestamp of the candle in ISO 8601 format. - **close** (object) - The closing price during the period. - **nano** (integer) - Nanoparts of the price. - **units** (string) - The main units of the price. - **open** (object) - The opening price during the period. - **nano** (integer) - Nanoparts of the price. - **units** (string) - The main units of the price. - **isComplete** (boolean) - Indicates if the candle is complete. ### Response Example ```json { "candles": [ { "volume": "volume", "high": { "nano": 6, "units": "units" }, "low": { "nano": 6, "units": "units" }, "volumeBuy": "volumeBuy", "volumeSell": "volumeSell", "time": "2000-01-23T04:56:07.000Z", "close": { "nano": 6, "units": "units" }, "open": { "nano": 6, "units": "units" }, "isComplete": true }, { "volume": "volume", "high": { "nano": 6, "units": "units" }, "low": { "nano": 6, "units": "units" }, "volumeBuy": "volumeBuy", "volumeSell": "volumeSell", "time": "2000-01-23T04:56:07.000Z", "close": { "nano": 6, "units": "units" }, "open": { "nano": 6, "units": "units" }, "isComplete": true } ] } ``` ``` -------------------------------- ### ReplaceSandboxOrder Node.js Example Source: https://developer.tbank.ru/invest/api/sandbox-service-replace-sandbox-order This Node.js example demonstrates how to make a POST request to the ReplaceSandboxOrder endpoint using the 'node-fetch' library. It shows how to set headers and send the JSON payload. Ensure you have 'node-fetch' installed (`npm install node-fetch`). ```javascript const fetch = require('node-fetch'); async function replaceOrder() { const url = 'https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.SandboxService/ReplaceSandboxOrder'; const token = 'YOUR_API_TOKEN'; // Replace with your actual token const payload = { accountId: 'string', orderIdType: 'ORDER_ID_TYPE_UNSPECIFIED', orderId: 'string', idempotencyKey: 'string', quantity: 'string', price: { nano: 6, units: 'units' }, priceType: 'PRICE_TYPE_UNSPECIFIED', confirmMarginTrade: true }; try { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify(payload) }); const data = await response.json(); console.log('Status Code:', response.status); console.log('Response Data:', data); } catch (error) { console.error('Error:', error); } } replaceOrder(); ``` -------------------------------- ### GetOrderBook Go Example Source: https://developer.tbank.ru/invest/api/market-data-service-get-order-book Example of how to make a GetOrderBook request using Go. This snippet demonstrates setting up the request and handling the response. ```go package main import ( "context" "fmt" "log" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/timestamppb" pb "tinkoff-invest-api-client/investAPI" ) func main() { // Replace with your actual token and endpoint token := "YOUR_API_TOKEN" endpoint := "invest-public-api.tbank.ru:443" conn, err := grpc.Dial(endpoint, grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() marketDataClient := pb.NewMarketDataServiceClient(conn) // Example instrument ID instrumentID := "BBG004730N72" // Example FIGI req := &pb.GetOrderBookRequest{ InstrumentId: instrumentID, depth: 10, // Example depth } orderBook, err := marketDataClient.GetOrderBook(context.Background(), req) if err != nil { log.Fatalf("GetOrderBook error: %v", err) } fmt.Printf("Order Book for %s:\n", instrumentID) fmt.Printf(" Bids: %+v\n", orderBook.Bids) fmt.Printf(" Asks: %+v\n", orderBook.Asks) fmt.Printf(" Last Price: %+v\n", orderBook.LastPrice) fmt.Printf(" Timestamp: %s\n", orderBook.OrderbookTs.AsTime()) } ``` -------------------------------- ### GetOrderState Java Request Example Source: https://developer.tbank.ru/invest/api/orders-service-get-order-state Example of how to make a GetOrderState request using Java. This snippet illustrates the client setup and request parameters. ```java var orders = ordersService.GetOrderState(GetOrderStateRequest.newBuilder() .setAccountId("string") .setOrderId("string") .setPriceType(PriceType.PRICE_TYPE_UNSPECIFIED) .setOrderIdType(OrderIdType.ORDER_ID_TYPE_UNSPECIFIED) .build()); ``` -------------------------------- ### PositionsStream Go Client Example Source: https://developer.tbank.ru/invest/api/operations-stream-service-positions-stream Illustrates how to set up a PositionsStream client in Go. This involves creating a client, defining the request payload, and handling the streaming response. ```go package main import ( "context" "fmt" "log" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" pb "tinkoff-invest-api-client/operations" ) func main() { conn, err := grpc.Dial("dns:///invest-public-api.tbank.ru:443", grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() client := pb.NewOperationsStreamServiceClient(conn) ctx, cancel := context.WithCancel(context.Background()) defer cancel() stream, err := client.PositionsStream(ctx, &pb.PositionsStreamRequest{ Accounts: []string{"string"}, WithInitialPositions: true, PingSettings: &pb.PingDelaySettings{ PingDelayMs: 0, }, }) if err != nil { log.Fatalf("could not subscribe to positions: %v", err) } for { response, err := stream.Recv() if err != nil { log.Printf("error receiving update: %v", err) break } fmt.Printf("Received: %+v\n", response) } } ``` -------------------------------- ### GetWithdrawLimits Request Example (Python) Source: https://developer.tbank.ru/invest/api/operations-service-get-withdraw-limits Example of how to call the GetWithdrawLimits operation using Python. This snippet illustrates the client setup and request execution. ```python import grpc from tinkoff.invest import operations_pb2, operations_pb2_grpc channel = grpc.secure_channel('invest-public-api.tbank.ru:443', grpc.ssl_channel_credentials()) operations_client = operations_pb2_grpc.OperationsServiceStub(channel) request = operations_pb2.GetWithdrawLimitsRequest( account_id='string' ) response = operations_client.GetWithdrawLimits(request) print(f'Withdraw Limits: {response}') ``` -------------------------------- ### GetWithdrawLimits Request Example (Node.js) Source: https://developer.tbank.ru/invest/api/operations-service-get-withdraw-limits Example of how to use the GetWithdrawLimits operation in Node.js. This snippet includes the necessary client setup and request execution. ```javascript const { OperationsServiceClient } = require('@tinkoff/invest-api-node-sdk'); const { Empty } = require('google-protobuf/google/protobuf/empty_pb'); async function getWithdrawLimits() { const client = new OperationsServiceClient({ // ... client options }); const request = new proto.GetWithdrawLimitsRequest(); request.setAccountId('string'); client.getWithdrawLimits(request, (err, response) => { if (err) { console.error('Error getting withdraw limits:', err); return; } console.log('Withdraw Limits:', response.toObject()); }); } getWithdrawLimits(); ``` -------------------------------- ### PortfolioStream Go Request Example Source: https://developer.tbank.ru/invest/api/operations-stream-service-portfolio-stream Example of initiating a PortfolioStream request in Go. This snippet demonstrates setting up the request body and headers for the API call. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { url := "https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.OperationsStreamService/PortfolioStream" token := "YOUR_API_TOKEN" payload := map[string]interface{}{ "accounts": []string{"string"}, "pingSettings": map[string]int{ "pingDelayMs": 0, }, } payloadBytes, err := json.Marshal(payload) if err != nil { fmt.Println("Error marshaling payload:", err) return } headers := map[string]string{ "Authorization": "Bearer " + token, "Content-Type": "application/json", } req, err := http.NewRequest("POST", url, bytes.NewBuffer(payloadBytes)) if err != nil { fmt.Println("Error creating request:", err) return } for key, value := range headers { req.Header.Set(key, value) } client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() fmt.Println("Status Code:", res.StatusCode) // Process the response body here } ``` -------------------------------- ### GetWithdrawLimits Request Example (Java) Source: https://developer.tbank.ru/invest/api/operations-service-get-withdraw-limits Example of how to make a GetWithdrawLimits request using Java. This code demonstrates the client setup and method invocation. ```java import ru.tinkoff.invest.openapi.v1.OperationsServiceGrpc; import ru.tinkoff.invest.openapi.v1.OperationsServiceOuterClass; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; public class GetWithdrawLimitsExample { public static void main(String[] args) { ManagedChannel channel = ManagedChannelBuilder.forAddress("invest-public-api.tbank.ru", 443) .useTransportSecurity() .build(); OperationsServiceGrpc.OperationsServiceBlockingStub stub = OperationsServiceGrpc.newBlockingStub(channel); OperationsServiceOuterClass.GetWithdrawLimitsRequest request = OperationsServiceOuterClass.GetWithdrawLimitsRequest.newBuilder() .setAccountId("string") .build(); OperationsServiceOuterClass.WithdrawLimitsResponse response = stub.getWithdrawLimits(request); System.out.println("Withdraw Limits Response: " + response); channel.shutdown(); } } ``` -------------------------------- ### GetTradingStatus PHP Request Example Source: https://developer.tbank.ru/invest/api/market-data-service-get-trading-status Example of how to make a GetTradingStatus request using PHP. This snippet demonstrates the client setup and the API call. ```php null, ]); $header = new Grpc\Metadata(); $header->set('authorization', $token); $request = new GetTradingStatusRequest(); $request->setInstrumentId('BBG004730N35'); list($response, $status) = $client->GetTradingStatus($request, $header)->wait(); if ($status->code !== Grpc\StatusCode::OK) { echo "Error: " . $status->details . PHP_EOL; } else { echo "Trading Status: " . print_r($response, true) . PHP_EOL; } $client->close(); ``` -------------------------------- ### GetFavorites Request Example (Go) Source: https://developer.tbank.ru/invest/api/instruments-service-get-favorites Example of how to make a GetFavorites request using Go. This snippet demonstrates setting up the request and handling the response. ```go package main import ( "context" "fmt" "log" "google.golang.org/grpc" "google.golang.org/grpc/credentials/oauth" investapi "github.com/TinkoffCreditSystems/invest-api-go-sdk/proto/investapi" ) func main() { ctx := context.Background() // Replace with your token token := "YOUR_API_TOKEN" // Replace with the sandbox endpoint if needed endpoint := "invest-public-api.tbank.ru:443" // Set up gRPC connection conn, err := grpc.DialContext(ctx, endpoint, grpc.WithTransportCredentials(oauth.NewOauthClient(token))) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() instrumentsClient := investapi.NewInstrumentsServiceClient(conn) // Replace with your groupId groupId := "string" req := &investapi.GetFavoritesRequest{ GroupId: groupId, } resp, err := instrumentsClient.GetFavorites(ctx, req) if err != nil { log.Fatalf("GetFavorites error: %v", err) } fmt.Println("Favorite Instruments:") for _, fav := range resp.FavoriteInstruments { fmt.Printf("- FIGI: %s, Ticker: %s, Name: %s\n", fav.Figi, fav.Ticker, fav.Name) } } ``` -------------------------------- ### Indicatives Service Request Example (Go) Source: https://developer.tbank.ru/invest/api/instruments-service-indicatives This Go code snippet demonstrates how to call the Indicatives Service. It includes setting up the request with the appropriate headers and body. ```go package main import ( "bytes" "fmt" "net/http" ) func main() { url := "https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/Indicatives" payload := []byte("{}") req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload)) if err != nil { fmt.Printf("Error creating request: %s\n", err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer ") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Printf("Error sending request: %s\n", err) return } defer res.Body.Close() fmt.Printf("Status Code: %d\n", res.StatusCode) // Process response body here } ``` -------------------------------- ### GetAssetBy Request Example (PHP) Source: https://developer.tbank.ru/invest/api/instruments-service-get-asset-by Example of how to perform a GetAssetBy request using PHP. This snippet shows the necessary setup and method call. ```php setEndpoint('invest-public-api.tbank.ru:443'); $request = new AssetRequest(); $request->setId('string'); // TODO: Call the method // $response = $client->instrumentsService()->getAssetBy($request); // print_r($response); ?> ``` -------------------------------- ### GetPortfolio Go Request Example Source: https://developer.tbank.ru/invest/api/operations-service-get-portfolio Example of how to make a GetPortfolio request using Go. This demonstrates setting up the request body and making the POST call. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { url := "https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.OperationsService/GetPortfolio" requestBody, err := json.Marshal(map[string]string{ "accountId": "string", "currency": "RUB", }) if err != nil { fmt.Println("Error marshalling request body:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Authorization", "Bearer ") req.Header.Set("Content-Type", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() fmt.Println("Status Code:", res.StatusCode) // Process response body here } ``` -------------------------------- ### GetAssetBy Request Example (Java) Source: https://developer.tbank.ru/invest/api/instruments-service-get-asset-by Example of how to make a GetAssetBy request using Java. This snippet includes the necessary imports and client setup. ```java import ru.tinkoff.invest.openapi.InvestApi; import ru.tinkoff.invest.openapi.model.rest.AssetRequest; import java.util.UUID; public class GetAssetByExample { public static void main(String[] args) { // TODO: Initialize client // InvestApi investApi = new InvestApi("YOUR_API_TOKEN"); // TODO: Set sandbox environment // investApi.setHost("invest-public-api.tbank.ru"); AssetRequest request = new AssetRequest(); request.setId("string"); // TODO: Call the method // investApi.getInstrumentsService().getAssetBy(request) // .thenAccept(response -> { // System.out.println(response); // }); } } ``` -------------------------------- ### GetSandboxWithdrawLimits Go Example Source: https://developer.tbank.ru/invest/api/sandbox-service-get-sandbox-withdraw-limits Example of how to call the GetSandboxWithdrawLimits endpoint using Go. This requires setting up the client and request body. ```go package main import ( "fmt" "log" "google.golang.org/grpc" "google.golang.org/protobuf/types/known/wrapperspb" pb "invest-public-api/tinkoff/public/invest/api/contract/v1" ) func main() { conn, err := grpc.Dial("invest-public-api.tbank.ru:443", grpc.WithInsecure()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() sclient := pb.NewSandboxServiceClient(conn) ctx := context.Background() res, err := client.GetSandboxWithdrawLimits(ctx, &pb.GetSandboxWithdrawLimitsRequest{ AccountId: "string", }) if err != nil { log.Fatalf("GetSandboxWithdrawLimits error: %v", err) } fmt.Println(res) } ``` -------------------------------- ### GetForecastBy cURL Request Example Source: https://developer.tbank.ru/invest/api/instruments-service-get-forecast-by Example of how to make a GET request to the GetForecastBy endpoint using cURL. Replace 'YOUR_API_TOKEN' with your actual API token. ```bash curl -X 'POST' \ 'https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/GetForecastBy' \ -H 'accept: application/json' \ -H 'Authorization: Bearer YOUR_API_TOKEN' \ -H 'Content-Type: application/json' \ -d '{ "instrumentId": "string" }' ``` -------------------------------- ### Get User Info - Go Example Source: https://developer.tbank.ru/invest/api/users-service-get-info This Go code snippet shows how to call the GetInfo endpoint to retrieve user details. It includes setting up the request and handling the response. ```go package main import ( "fmt" "log" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" "github.com/Tinkoff/invest-api-go-sdk/proto/users" ) func main() { conn, err := grpc.Dial("invest-public-api.tbank.ru:443", grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() client := users.NewUsersServiceClient(conn) ctx := context.Background() req := &users.GetInfoRequest{} resp, err := client.GetInfo(ctx, req) if err != nil { log.Fatalf("GetInfo error: %v", err) } fmt.Println(resp) } ``` -------------------------------- ### GetAccounts Go Example Source: https://developer.tbank.ru/invest/api/users-service-get-accounts Example of how to call the GetAccounts endpoint using Go. This snippet demonstrates making a POST request with a JSON body. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { url := "https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.UsersService/GetAccounts" token := "" payload := map[string]string{ "status": "ACCOUNT_STATUS_UNSPECIFIED", } jsonPayload, err := json.Marshal(payload) if err != nil { fmt.Println("Error marshaling JSON:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonPayload)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Content-Type", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() fmt.Println("Status Code:", res.StatusCode) // You would typically decode the response body here } ``` -------------------------------- ### Get Futures Margin Request Example (Node.js) Source: https://developer.tbank.ru/invest/api/instruments-service-get-futures-margin Example of how to call the GetFuturesMargin endpoint using Node.js. This snippet demonstrates the structure for making the request. ```javascript const { InstrumentsServiceClient } = require("@tinkoff/invest-api"); const client = new InstrumentsServiceClient({ token: "YOUR_API_TOKEN", // ... other options }); client.getFuturesMargin({ instrumentId: "string", }).then(response => { console.log(response); }).catch(error => { console.error(error); }); ``` -------------------------------- ### Get Futures Margin Request Example (cURL) Source: https://developer.tbank.ru/invest/api/instruments-service-get-futures-margin Example of how to call the GetFuturesMargin endpoint using cURL. Replace 'string' with a valid instrument identifier. ```bash curl -X POST \ https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.InstrumentsService/GetFuturesMargin \ -H 'Authorization: Bearer ' \ -H 'Content-Type: application/json' \ -d '{ "instrumentId": "string" }' ``` -------------------------------- ### OpenSandboxAccount Go Example Source: https://developer.tbank.ru/invest/api/sandbox-service-open-sandbox-account Example of how to call the OpenSandboxAccount endpoint using Go. This snippet demonstrates setting up the request and handling the response. ```go package main import ( "context" "fmt" "log" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" pb "invest-public-api/tinkoff/public/invest/api/contract/v1" ) func main() { conn, err := grpc.Dial("sandbox-api.tinkoffinvest.ru:80", grpc.WithTransportCredentials(insecure.NewCredentials())) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() client := pb.NewSandboxServiceClient(conn) ctx := context.Background() resp, err := client.OpenSandboxAccount(ctx, &pb.OpenSandboxAccountRequest{ "name": "string", }) if err != nil { log.Fatalf("OpenSandboxAccount error: %v", err) } fmt.Printf("OpenSandboxAccount Response: %+v\n", resp) } ``` -------------------------------- ### Go Request Example for GetBrokerReport Source: https://developer.tbank.ru/invest/api/operations-service-get-broker-report Example of how to call the GetBrokerReport API using Go. This snippet demonstrates constructing the request body and making the POST request. ```go package main import ( "bytes" "encoding/json" "fmt" "net/http" ) func main() { url := "https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.OperationsService/GetBrokerReport" requestBody := map[string]interface{}{ "generateBrokerReportRequest": map[string]string{ "accountId": "string", "from": "2026-05-12T09:13:47.813Z", "to": "2026-05-12T09:13:47.813Z" }, "getBrokerReportRequest": map[string]interface{}{ "taskId": "string", "page": 0 } } requestBodyBytes, err := json.Marshal(requestBody) if err != nil { fmt.Println("Error marshaling JSON:", err) return } req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBodyBytes)) if err != nil { fmt.Println("Error creating request:", err) return } req.Header.Set("Authorization", "Bearer ") req.Header.Set("Content-Type", "application/json") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println("Error sending request:", err) return } defer res.Body.Close() fmt.Println("Status Code:", res.StatusCode) // Process response body here } ``` -------------------------------- ### Cancel Stop Order Java Example Source: https://developer.tbank.ru/invest/api/stop-orders-service-cancel-stop-order Example of how to cancel a stop order using Java. This snippet shows the basic setup for interacting with the StopOrdersService. ```java package ru.tbank.invest.api.contract.v1; public class StopOrdersServiceGrpc { private StopOrdersServiceGrpc() {} public static final io.grpc.MethodDescriptor getCancelStopOrderMethodDescriptor() { io.grpc.MethodDescriptor.BuildernewBuilder() .setType(io.grpc.MethodDescriptor.MethodType.UNARY) .setFullMethodName(generateFullMethodName(SERVICE_NAME, "CancelStopOrder")) .setSampledToLocalTracing(true) .setRequestMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( ru.tbank.invest.api.contract.v1.CancelStopOrderRequest.getDefaultInstance())) .setResponseMarshaller(io.grpc.protobuf.ProtoUtils.marshaller( ru.tbank.invest.api.contract.v1.StopOrderResponse.getDefaultInstance())) .setSchemaDescriptor(new StopOrdersServiceMethodDescriptorSupplier("CancelStopOrder")) .build(); return getCancelStopOrderMethodDescriptor; } static final io.grpc.MethodDescriptor getCancelStopOrder = getCancelStopOrderMethodDescriptor; private static volatile io.grpc.MethodDescriptor getCancelStopOrderMethodDescriptor; public static final io.grpc.ServiceDescriptor SERVICE_DESCRIPTOR = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) .setSchemaDescriptor(new StopOrdersServiceFileDescriptorSupplier()) .addMethod(getCancelStopOrderMethodDescriptor()) .build(); static final String SERVICE_NAME = "tinkoff.public.invest.api.contract.v1.StopOrdersService"; private static void addMethodFileDescriptor( com.google.protobuf.Descriptors.FileDescriptor file) { // file is already known to be in the dependency graph } private static final class StopOrdersServiceMethodDescriptorSupplier implements io.grpc.protobuf.ProtoMethodDescriptorSupplier { private final String methodName; StopOrdersServiceMethodDescriptorSupplier(String methodName) { this.methodName = methodName; } @java.lang.Override public com.google.protobuf.Descriptors.MethodDescriptor getMethodDescriptor() { return getFileDescriptor().findMethodByName(methodName); } private static volatile com.google.protobuf.Descriptors.FileDescriptor file; private static final com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { if (file == null) { synchronized (StopOrdersServiceGrpc.class) { if (file == null) { file = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(java.lang.String.join( "\n", java.util.Arrays.asList( "\n", "// Use the following examples to learn how to use the API. The examples are in different languages.", "\n", "// CancelStopOrder — отменить стоп-заявку", "\n", "syntax \"proto3\";", "\n", "package tinkoff.public.invest.api.contract.v1;", "\n", "import \"google/protobuf/timestamp.proto\";", "\n", "option go_package = \"invest-public-api/tinkoff/public/invest/api/contract/v1\";", "\n", "service StopOrdersService {", "\n", " // Отмена стоп-заявки", " rpc CancelStopOrder(CancelStopOrderRequest) returns (StopOrderResponse) {}", "\n", " // Получение статуса стоп-заявки", " rpc GetStopOrderState(GetStopOrderStateRequest) returns (StopOrderResponse) {}", "\n", " // Получение списка стоп-заявок", " rpc GetStopOrders(GetStopOrdersRequest) returns (GetStopOrdersResponse) {}", "\n", " // Постановка стоп-заявки", " rpc PostStopOrder(PostStopOrderRequest) returns (PostStopOrderResponse) {}", "\n", "}", "\n", "// Запрос отмены стоп-заявки", "message CancelStopOrderRequest {", "\n", " // Идентификатор счета клиента.", " string account_id = 1;", "\n", " // Уникальный идентификатор стоп-заявки.", " string stop_order_id = 2;", "\n", "}", "\n", "// Ответ на операцию со стоп-заявкой", "message StopOrderResponse {", "\n", " // Время ответа сервера.", " google.protobuf.Timestamp time = 1;", "\n", "}", "\n", "// Запрос получения статуса стоп-заявки", "message GetStopOrderStateRequest {", "\n", " // Идентификатор счета клиента.", " string account_id = 1;", "\n", " // Уникальный идентификатор стоп-заявки.", " string stop_order_id = 2;", "\n", "}", "\n", "// Запрос получения списка стоп-заявок", "message GetStopOrdersRequest {", "\n", " // Идентификатор счета клиента.", " string account_id = 1;", "\n", " // Тип стоп-заявки.", " StopOrderDirection direction = 2;", "\n", " // Инструмент.", " string order_id = 3;", "\n", "}", "\n", "// Ответ на получение списка стоп-заявок", "message GetStopOrdersResponse {", "\n", " repeated StopOrder orders = 1;", "\n", "}", "\n", "// Стоп-заявка", "message StopOrder {", "\n", " // Идентификатор инструмента.", " string order_id = 1;", "\n", " // Цена заявки.", " string price = 2;", "\n", " // Количество лотов.", " string lot_size = 3;", "\n", " // Тип стоп-заявки.", " StopOrderDirection direction = 4;", "\n", " // Тип стоп-заявки.", " StopOrderType order_type = 5;", "\n", " // Дата и время жизни заявки.", " google.protobuf.Timestamp expire_date = 6;", "\n", " // Статус стоп-заявки.", " StopOrderStatus status = 7;", "\n", " // Компенсация.", " string payoff = 8;", "\n", "}", "\n", "// Запрос на выставление стоп-заявки", "message PostStopOrderRequest {", "\n", " // Идентификатор счета клиента.", " string account_id = 1;", "\n", " // Параметры заявки.", " // Обязательное поле.", " // Тип заявки.", " StopOrderType order_type = 2;", "\n", " // Инструмент.", " // Обязательное поле.", " string order_id = 3;", "\n", " // Количество лотов.", " // Обязательное поле.", " string lot_size = 4;", "\n", " // Цена заявки.", " // Обязательное поле.", " string price = 5;", "\n", " // Стоп-цена.", " // Обязательное поле.", " string stop_price = 6;", "\n", " // Направление заявки.", " // Обязательное поле.", " StopOrderDirection direction = 7;", "\n", " // Дата и время жизни заявки.", " google.protobuf.Timestamp expire_date = 8;", "\n", " // Компенсация.", " string payoff = 9;", "\n", "}", "\n", "// Ответ на выставление стоп-заявки", "message PostStopOrderResponse {", "\n", " // Идентификатор операции.", " string stop_order_id = 1;", "\n", " // Время ответа сервера.", " google.protobuf.Timestamp time = 2;", "\n", "}", "\n", "// Тип стоп-заявки", "enum StopOrderType {", "\n", " STOP_ORDER_TYPE_UNSPECIFIED = 0;", "\n", " // Stop Limit заявка.", " STOP_ORDER_TYPE_LIMIT = 1;", "\n", " // Stop Market заявка.", " STOP_ORDER_TYPE_MARKET = 2;", "\n", "}", "\n", "// Направление стоп-заявки", "enum StopOrderDirection {", "\n", " STOP_ORDER_DIRECTION_UNSPECIFIED = 0;", "\n", " // Покупка.", " STOP_ORDER_DIRECTION_BUY = 1;", "\n", " // Продажа.", " STOP_ORDER_DIRECTION_SELL = 2;", "\n", "}", "\n", "// Статус стоп-заявки", "enum StopOrderStatus {", "\n", " STOP_ORDER_STATUS_UNSPECIFIED = 0;", "\n", " // Активна.", " STOP_ORDER_STATUS_ACTIVE = 1;", "\n", " // Исполнена.", " STOP_ORDER_STATUS_EXECUTED = 2;", "\n", " // Отменена.", " STOP_ORDER_STATUS_CANCELED = 3;", "\n", " // Удалена.", " STOP_ORDER_STATUS_REJECTED = 4;", "\n", "}", "\n", "}" )) file = file; } } } return file; } } private static final class StopOrdersServiceFileDescriptorSupplier implements io.grpc.protobuf.ProtoFileDescriptorSupplier { StopOrdersServiceFileDescriptorSupplier() {} @java.lang.Override public com.google.protobuf.Descriptors.FileDescriptor getFileDescriptor() { return StopOrdersServiceGrpc.getFileDescriptor(); } } } ``` -------------------------------- ### Get Bank Accounts Response Example Source: https://developer.tbank.ru/invest/api/users-service-get-bank-accounts Example of a successful 200 OK response from the GetBankAccounts endpoint. It includes details about opened accounts, money, and identifiers. ```json { "bankAccounts": [{ "openedDate": "2000-01-23T04:56:07.000Z", "money": [{ "nano": 5, "currency": "currency", "units": "units" }, { "nano": 5, "currency": "currency", "units": "units" } ], "name": "name", "id": "id" }, { "openedDate": "2000-01-23T04:56:07.000Z", "money": [{ "nano": 5, "currency": "currency", "units": "units" }, { "nano": 5, "currency": "currency", "units": "units" } ], "name": "name", "id": "id" } ] } ``` -------------------------------- ### PayIn Request Example (Go) Source: https://developer.tbank.ru/invest/api/users-service-pay-in Example of how to make a PayIn request using Go. This snippet demonstrates the structure for sending the request body. ```go package main import ( "fmt" "bytes" "net/http" "io/ioutil" ) func main() { url := "https://invest-public-api.tbank.ru/rest/tinkoff.public.invest.api.contract.v1.UsersService/PayIn" payload := []byte(`{ "fromAccountId": "string", "toAccountId": "string", "amount": { "nano": 5, "currency": "currency", "units": "units" } }`) req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload)) if err != nil { fmt.Println(err) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer YOUR_API_TOKEN") client := &http.Client{} res, err := client.Do(req) if err != nil { fmt.Println(err) return } defer res.Body.Close() body, err := ioutil.ReadAll(res.Body) if err != nil { fmt.Println(err) return } fmt.Println(string(body)) } ```