Git Product home page Git Product logo

Comments (2)

vabka avatar vabka commented on August 11, 2024

Вы можете попробовать в интерактивном режиме поиграться при помощи .NET Interactive Notebooks
https://github.com/dotnet/interactive
Есть и расширение для VS Code, и кернелы для Jupyter

Чтобы начать использовать, достаточно написать вот такой код в первой ячейке:

#r "nuget: Microsoft.Extensions.DependencyInjection, 6.0.0"
#r "nuget: Microsoft.Extensions.DependencyInjection.Abstractions, 6.0.0"
#r "nuget: Tinkoff.InvestApi, 0.1.6"


using Microsoft.Extensions.DependencyInjection;
using Tinkoff.InvestApi;
using Tinkoff.InvestApi.V1;

var token = "ТУТ ТОКЕН";

var serviceCollection = new ServiceCollection();
serviceCollection.AddInvestApiClient((_, settings) =>
{
    settings.AccessToken = token;
});
var serviceProvider = serviceCollection.BuildServiceProvider();
var client = serviceProvider.GetRequiredService<InvestApiClient>();

// Получаем список счетов
var accountsRequest = new GetAccountsRequest {};
var accountsResponse = await client.Users.GetAccountsAsync(accountsRequest);

// Получаем портфель для первого счёта
var portfolioRequest = new PortfolioRequest{
    AccountId = accountsResponse.Accounts[0].Id
};
var portfolioResponse = await client.Operations.GetPortfolioAsync(portfolioRequest);

// Показываем в виде таблички
portfolioResponse.Positions.Display();

PS: Сейчас немного поигрался, и для чуть более красивого отображения портфеля можно написать такой код:

Небольшой утилитарный класс для получения человекочитаемого названия инструмента по figi:

using System.Collections.Concurrent;
public class FormatterCache {
    private Dictionary<string, string> _map = new();
    private InvestApiClient _client;

    public FormatterCache(InvestApiClient client) => this._client = client;
    public async ValueTask<string> GetNameByFigi(string figi){
        if (_map.ContainsKey(figi)) {
            return _map[figi];
        } else {
            // Add concurrency guard to limit requests
            var instrumentRequest = new InstrumentRequest{
                Id = figi,
                IdType = InstrumentIdType.Figi
            };
            var instrument = await _client.Instruments.GetInstrumentByAsync(instrumentRequest);            
            _map[figi] = instrument.Instrument.Name;
            return instrument.Instrument.Name;
        }
    }
}
var formatterCache = new FormatterCache(client);

Код для форматирования инструментов:

var positions = portfolioResponse.Positions;


static string MoneyToString(MoneyValue value){
    var symbol = value.Currency switch {
        "usd" => "$",
        "rub" => "",
        var x => x
    };
    return $"{symbol} {(decimal)value}";
}

var list = new List<object>();

foreach(var e in positions){
    var item = new {
        e.Figi,
        e.InstrumentType,
        InstrumentName = await formatterCache.GetNameByFigi(e.Figi),
        Quantitity = (decimal) e.Quantity,
        AveragePositionPrice = MoneyToString(e.AveragePositionPrice),
        ExpectedYield = (decimal) e.ExpectedYield,
        CurrentNkd = MoneyToString(e.CurrentNkd),
        CurrentPrice = MoneyToString(e.CurrentPrice),
        AveragePositionPriceFifo = MoneyToString(e.AveragePositionPriceFifo),
        QuantityLots = (decimal) e.QuantityLots
    };
    list.Add(item);
}
list.Display();

from invest-api-csharp-sdk.

WhiteBlackGoose avatar WhiteBlackGoose commented on August 11, 2024

Спасибо!

from invest-api-csharp-sdk.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.