The personal finance app for everyone (by everyone)
Ruby
feat(prices): add T-Invest (T-Bank) securities + brand-logo provider (#2408)
Artem Danilov9de9a23ce210
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rbindex 6db240b89c..11f0b1c720 100644--- a/app/controllers/settings/hostings_controller.rb+++ b/app/controllers/settings/hostings_controller.rb@@ -31,6 +31,10 @@ class Settings::HostingsController < ApplicationController@show_tiingo_settings = enabled_securities.include?("tiingo")@show_eodhd_settings = enabled_securities.include?("eodhd")@show_alpha_vantage_settings = enabled_securities.include?("alpha_vantage")+ # T-Invest doubles as a brand-logo source consulted regardless of the price+ # provider, so its token is useful even when it's not enabled for prices.+ # Always surface the token field, decoupled from the securities checklist.+ @show_tinkoff_invest_settings = true# Only fetch provider data if we're showing the sectionif @show_twelve_data_settings@@ -110,6 +114,7 @@ class Settings::HostingsController < ApplicationControllerupdate_encrypted_setting(:tiingo_api_key)update_encrypted_setting(:eodhd_api_key)update_encrypted_setting(:alpha_vantage_api_key)+ update_encrypted_setting(:tinkoff_invest_api_key)if hosting_params.key?(:syncs_include_pending)Setting.syncs_include_pending = hosting_params[:syncs_include_pending] == "1"@@ -274,7 +279,7 @@ class Settings::HostingsController < ApplicationControllerprivatedef hosting_paramsreturn ActionController::Parameters.new unless params.key?(:setting)- params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_agent_id, securities_providers: [])+ params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_agent_id, securities_providers: [])enddef update_assistant_typediff --git a/app/models/provider/moex_public.rb b/app/models/provider/moex_public.rbindex d96c562a95..2a69ccc39b 100644--- a/app/models/provider/moex_public.rb+++ b/app/models/provider/moex_public.rb@@ -113,7 +113,10 @@ class Provider::MoexPublic < ProviderSecurityInfo.new(symbol: instrument[:secid],name: instrument[:name],- links: "https://www.moex.com/en/issue.aspx?code=#{instrument[:secid]}",+ # Deliberately no website: moex.com is the exchange, not the issuer, so+ # persisting it as website_url makes Brandfetch render the exchange logo+ # for every instrument and shadows the real per-issuer brand logo.+ links: nil,logo_url: nil,description: nil,kind: instrument[:kind],diff --git a/app/models/provider/registry.rb b/app/models/provider/registry.rbindex 1c4947db43..ebe3d615b8 100644--- a/app/models/provider/registry.rb+++ b/app/models/provider/registry.rb@@ -144,6 +144,14 @@ class Provider::Registrydef moex_publicProvider::MoexPublic.newend++ def tinkoff_invest+ api_key = ENV["TINKOFF_INVEST_API_KEY"].presence || Setting.tinkoff_invest_api_key # pipelock:ignore++ return nil unless api_key.present?++ Provider::TinkoffInvest.new(api_key)+ endenddef initialize(concept)@@ -176,7 +184,7 @@ class Provider::Registrywhen :exchange_rates%i[twelve_data yahoo_finance moex_public]when :securities- %i[twelve_data yahoo_finance tiingo eodhd alpha_vantage mfapi binance_public moex_public]+ %i[twelve_data yahoo_finance tiingo eodhd alpha_vantage mfapi binance_public moex_public tinkoff_invest]when :llm%i[openai anthropic]elsediff --git a/app/models/provider/tinkoff_invest.rb b/app/models/provider/tinkoff_invest.rbnew file mode 100644index 0000000000..9f1ba03b6b--- /dev/null+++ b/app/models/provider/tinkoff_invest.rb@@ -0,0 +1,345 @@+# T-Bank (Tinkoff) Invest API securities provider, built on the token-based REST+# gateway (https://invest-public-api.tinkoff.ru/rest) over the public gRPC+# contract. Mirrors the keyed providers (Tiingo/TwelveData) for auth and the+# keyless market providers (MoexPublic/BinancePublic) for SslConfigurable ++# RateLimitable plumbing.+#+# Why it exists: ISS (MoexPublic) prices Russian instruments but carries no+# logos. T-Invest is the authoritative source of instrument *brand logos*+# (shares, ETF/БПИФ, bonds) via its CDN, and can also serve prices for those+# instruments when MOEX is not the selected provider. The app therefore uses it+# two ways:+# 1. As a securities price/search provider (when enabled in settings).+# 2. As a brand-logo source consulted by Security#import_provider_details+# regardless of which provider prices the security (see Security::Provided),+# so MOEX-priced holdings still get real logos.+#+# REST shape: every call is POST to+# /tinkoff.public.invest.api.contract.v1.<Service>/<Method>+# with a JSON body, Bearer-token auth, and a JSON response. Money is encoded as+# Quotation { units: "<int>", nano: <int> } => units + nano/1e9.+class Provider::TinkoffInvest < Provider+ include SecurityConcept, RateLimitable+ extend SslConfigurable++ Error = Class.new(Provider::Error)+ InvalidSecurityPriceError = Class.new(Error)+ RateLimitError = Class.new(Error)++ # T-Invest unary REST limits are generous (hundreds/min); space calls lightly.+ MIN_REQUEST_INTERVAL = 0.1++ # gRPC-over-REST service path prefix.+ API_NS = "tinkoff.public.invest.api.contract.v1".freeze++ # Brand-logo CDN. The API returns brand.logoName like "SBER.png"; the image is+ # served at <CDN>/<logoName without extension><size>.png — sizes x160/x320/x640.+ LOGO_CDN = "https://invest-brands.cdn-tinkoff.ru".freeze+ LOGO_SIZE = "x160".freeze++ # ISO 10383 operating MICs we surface. T-Invest mostly covers MOEX; SPB Exchange+ # instruments map to XSPX. Anything else stays nil (resolver wildcard).+ MOEX_MIC = "MISX".freeze+ SPB_MIC = "XSPX".freeze++ # GetCandles caps the window per request by interval; for daily candles we page+ # in ~1-year chunks and bound the loop defensively.+ CANDLE_CHUNK_DAYS = 360+ MAX_CANDLE_PAGES = 60++ INSTRUMENT_CACHE_TTL = 24.hours+ SEARCH_CACHE_TTL = 5.minutes++ def initialize(api_key)+ @api_key = api_key # pipelock:ignore+ end++ def healthy?+ with_provider_response do+ post("InstrumentsService", "FindInstrument", query: "SBER", instrumentKind: "INSTRUMENT_TYPE_SHARE")+ true+ end+ end++ def usage+ with_provider_response do+ UsageData.new(used: nil, limit: nil, utilization: nil, plan: "Token (read-only)")+ end+ end++ # ================================+ # Securities+ # ================================++ def search_securities(symbol, country_code: nil, exchange_operating_mic: nil)+ with_provider_response do+ query = symbol.to_s.strip+ next [] if query.empty?++ find_instruments(query).filter_map do |row|+ next nil unless surfaced_kind(row["instrumentType"])++ Provider::SecurityConcept::Security.new(+ symbol: row["ticker"].to_s,+ name: (row["name"].presence || row["ticker"]).to_s,+ logo_url: nil, # FindInstrument carries no brand; logos come from #fetch_security_info+ exchange_operating_mic: mic_for(row["classCode"], row["exchange"]),+ country_code: row["countryOfRisk"].presence,+ currency: row["currency"].to_s.upcase.presence+ )+ end.uniq { |s| [ s.symbol, s.exchange_operating_mic ] }+ end+ end++ def fetch_security_info(symbol:, exchange_operating_mic:)+ with_provider_response do+ short = resolve_short(symbol, exchange_operating_mic)+ raise Error, "Unknown T-Invest instrument: #{symbol}" if short.nil?++ detail = instrument_detail(short["uid"])++ SecurityInfo.new(+ symbol: short["ticker"].to_s,+ name: (detail["name"].presence || short["name"]).to_s,+ links: nil, # T-Invest exposes no issuer website+ logo_url: logo_url(detail.dig("brand", "logoName")),+ description: nil,+ kind: surfaced_kind(short["instrumentType"]),+ exchange_operating_mic: mic_for(short["classCode"], detail["exchange"])+ )+ end+ end++ def fetch_security_price(symbol:, exchange_operating_mic:, date:)+ with_provider_response do+ historical = fetch_security_prices(+ symbol: symbol,+ exchange_operating_mic: exchange_operating_mic,+ start_date: date,+ end_date: date+ )++ raise historical.error if historical.error.present?+ raise InvalidSecurityPriceError, "No T-Invest price for #{symbol} on #{date}" if historical.data.blank?++ historical.data.find { |p| p.date == date } ||+ historical.data.select { |p| p.date <= date }.max_by(&:date) ||+ historical.data.first+ end+ end++ def fetch_security_prices(symbol:, exchange_operating_mic:, start_date:, end_date:)+ with_provider_response do+ short = resolve_short(symbol, exchange_operating_mic)+ raise Error, "Unknown T-Invest instrument: #{symbol}" if short.nil?++ uid = short["uid"]+ bond = short["instrumentType"].to_s == "bond"+ currency = short["currency"].to_s.upcase+ mic = mic_for(short["classCode"], short["exchange"])+ # Bonds quote in % of par; multiply by nominal to get a money price. A+ # missing/invalid nominal is a provider-data failure, not a zero price.+ nominal = bond ? instrument_nominal(uid) : nil+ if bond && (nominal.nil? || nominal <= 0)+ raise InvalidSecurityPriceError, "Missing or invalid T-Invest bond nominal for #{symbol}"+ end++ prices = candle_closes(uid, start_date, end_date).map do |date, close|+ value = bond ? (close / 100) * nominal : close+ Price.new(symbol: short["ticker"].to_s, date: date, price: value, currency: currency, exchange_operating_mic: mic)+ end++ # The candle endpoint lags the live session; append the last price for a+ # range reaching today.+ if end_date >= Date.current+ last = last_price(uid)+ if last+ value = bond ? (last / 100) * nominal : last+ prices.reject! { |p| p.date == Date.current }+ prices << Price.new(symbol: short["ticker"].to_s, date: Date.current, price: value, currency: currency, exchange_operating_mic: mic)+ end+ end++ prices.sort_by(&:date)+ end+ end++ def max_history_days+ nil # GetCandles serves the instrument's full daily history (paged).+ end++ private++ attr_reader :api_key++ # ================================+ # HTTP / parsing+ # ================================++ def base_url+ ENV["TINKOFF_INVEST_URL"].presence || "https://invest-public-api.tinkoff.ru/rest"+ end++ def post(service, method, body)+ throttle_request+ response = client.post("#{base_url}/#{API_NS}.#{service}/#{method}") do |req|+ req.body = body.to_json+ end+ JSON.parse(response.body)+ end++ def client+ @client ||= Faraday.new(url: base_url, ssl: self.class.faraday_ssl_options) do |faraday|+ faraday.options.open_timeout = 5+ faraday.options.timeout = 20++ faraday.request(:retry, {+ max: 3,+ interval: 0.5,+ interval_randomness: 0.5,+ backoff_factor: 2,+ exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [ Faraday::ConnectionFailed ]+ })++ faraday.headers["Authorization"] = "Bearer #{api_key}"+ faraday.headers["Content-Type"] = "application/json"+ faraday.headers["Accept"] = "application/json"+ faraday.response :raise_error+ end+ end++ # Quotation { units, nano } -> BigDecimal. Absent/blank -> nil.+ def quotation_to_d(q)+ return nil if q.blank?+ units = BigDecimal(q["units"].to_s.presence || "0")+ nano = BigDecimal(q["nano"].to_s.presence || "0")+ units + (nano / BigDecimal("1000000000"))+ end++ # ================================+ # Instruments+ # ================================++ def find_instruments(query)+ Rails.cache.fetch("tinkoff_invest:find:#{query.downcase}", expires_in: SEARCH_CACHE_TTL) do+ body = post("InstrumentsService", "FindInstrument", query: query, apiTradeAvailableFlag: false)+ body["instruments"] || []+ end+ end++ # Best FindInstrument hit for a ticker/ISIN: exact ticker (or ISIN) match,+ # preferring a requested MIC, then a surfaced kind, then any result.+ def resolve_short(symbol, exchange_operating_mic)+ key = symbol.to_s.strip+ Rails.cache.fetch("tinkoff_invest:short:#{key.downcase}:#{exchange_operating_mic}", expires_in: INSTRUMENT_CACHE_TTL) do+ rows = find_instruments(key)+ up = key.upcase++ exact = rows.select { |r| r["ticker"].to_s.upcase == up || r["isin"].to_s.upcase == up }+ pool = exact.any? ? exact : rows+ pool = pool.select { |r| surfaced_kind(r["instrumentType"]) } if pool.any? { |r| surfaced_kind(r["instrumentType"]) }++ if exchange_operating_mic.present?+ preferred = pool.find { |r| mic_for(r["classCode"], r["exchange"]) == exchange_operating_mic.upcase }+ preferred || pool.first+ else+ pool.first+ end+ end+ end++ # GetInstrumentBy(uid) — full instrument incl. brand/logo, exchange, nominal.+ def instrument_detail(uid)+ Rails.cache.fetch("tinkoff_invest:detail:#{uid}", expires_in: INSTRUMENT_CACHE_TTL) do+ body = post("InstrumentsService", "GetInstrumentBy", idType: "INSTRUMENT_ID_TYPE_UID", id: uid)+ body["instrument"] || {}+ end+ end++ def instrument_nominal(uid)+ quotation_to_d(instrument_detail(uid)["nominal"])+ end++ # ================================+ # Prices+ # ================================++ def candle_closes(uid, start_date, end_date)+ return [] if start_date > end_date++ closes = {}+ window_start = start_date+ pages = 0++ while window_start <= end_date && pages < MAX_CANDLE_PAGES+ window_end = [ window_start + CANDLE_CHUNK_DAYS, end_date ].min+ body = post(+ "MarketDataService", "GetCandles",+ instrumentId: uid,+ interval: "CANDLE_INTERVAL_DAY",+ from: "#{window_start}T00:00:00Z",+ to: "#{window_end}T23:59:59Z"+ )++ (body["candles"] || []).each do |c|+ next unless c["isComplete"]+ date = parse_time(c["time"])+ close = quotation_to_d(c["close"])+ closes[date] = close if date && close && close > 0+ end++ pages += 1+ window_start = window_end + 1+ end++ closes.sort.to_h.map { |date, close| [ date, close ] }+ end++ def last_price(uid)+ body = post("MarketDataService", "GetLastPrices", instrumentId: [ uid ])+ row = (body["lastPrices"] || []).first+ return nil unless row+ value = quotation_to_d(row["price"])+ value if value && value > 0+ end++ # ================================+ # Helpers+ # ================================++ def logo_url(logo_name)+ return nil if logo_name.blank?+ "#{LOGO_CDN}/#{logo_name.to_s.sub(/\.png\z/i, '')}#{LOGO_SIZE}.png"+ end++ # T-Invest instrumentType -> the security kinds we surface (skip futures,+ # currencies, options, etc.).+ def surfaced_kind(instrument_type)+ case instrument_type.to_s.downcase+ when "share" then "stock"+ when "etf" then "fund"+ when "bond" then "bond"+ end+ end++ def mic_for(class_code, exchange)+ ex = exchange.to_s.downcase+ return MOEX_MIC if class_code.to_s.start_with?("TQ") || ex.include?("moex")+ return SPB_MIC if ex.include?("spb")+ nil+ end++ def parse_time(raw)+ return nil if raw.blank?+ Date.parse(raw.to_s)+ rescue Date::Error+ nil+ end++ # Preserve TinkoffInvest::Error subclasses through with_provider_response,+ # mirroring MoexPublic/BinancePublic.+ def default_error_transformer(error)+ return error if error.is_a?(self.class::Error)+ super+ end+enddiff --git a/app/models/security.rb b/app/models/security.rbindex 40ae6b969d..46ffd4f124 100644--- a/app/models/security.rb+++ b/app/models/security.rb@@ -87,15 +87,20 @@ class Security < ApplicationRecordnilend- # Single source of truth for which logo URL the UI should render. Crypto- # and stocks share the same shape: prefer a freshly computed Brandfetch- # URL (honors current client_id + size) and fall back to any stored- # logo_url for the provider-returns-its-own-URL case (e.g. Tiingo S3).+ # Single source of truth for which logo URL the UI should render.+ # - Crypto keeps its dedicated Brandfetch-crypto shape.+ # - When a website domain is known, Brandfetch (consistent client_id + size)+ # wins, falling back to any stored logo_url.+ # - With no domain, a stored provider logo (e.g. T-Invest's CDN for MOEX+ # instruments) is authoritative and beats the ticker-only Brandfetch+ # lettermark placeholder.def display_logo_urlif crypto?self.class.brandfetch_crypto_url(crypto_base_asset).presence || logo_url.presence- else+ elsif website_url.present?brandfetch_icon_url.presence || logo_url.presence+ else+ logo_url.presence || brandfetch_icon_url.presenceendenddiff --git a/app/models/security/provided.rb b/app/models/security/provided.rbindex 1d78054223..71d517aac4 100644--- a/app/models/security/provided.rb+++ b/app/models/security/provided.rb@@ -221,38 +221,80 @@ module Security::Providedreturnend- if self.name.present? && (self.logo_url.present? || self.website_url.present?) && !clear_cache- return+ # Price-provider metadata (name/website/logo). Skip the refetch only when we+ # already have a name plus a logo or website. This gate must be evaluated+ # before any brand-logo enrichment, otherwise setting logo_url first would+ # trip it and skip website_url backfill from providers that return links.+ unless self.name.present? && (self.logo_url.present? || self.website_url.present?) && !clear_cache+ response = price_data_provider.fetch_security_info(+ symbol: ticker,+ exchange_operating_mic: exchange_operating_mic+ )++ if response.success?+ # Only overwrite fields the provider actually returned, so providers that+ # don't support metadata (e.g. Alpha Vantage) won't blank existing values.+ attrs = {}+ attrs[:name] = response.data.name if response.data.name.present?+ attrs[:logo_url] = response.data.logo_url if response.data.logo_url.present?+ attrs[:website_url] = response.data.links if response.data.links.present?+ update(attrs) if attrs.any?+ else+ Rails.logger.warn("Failed to fetch security info for #{ticker} from #{price_data_provider.class.name}: #{response.error.message}")+ DebugLogEntry.capture(+ category: "security_metadata_fetch",+ level: "warn",+ message: "Failed to get security info",+ source: self.class.name,+ provider: price_data_provider,+ metadata: {+ security_id: self.id,+ ticker: ticker,+ provider_error: response.error.message+ }+ )+ endend- response = price_data_provider.fetch_security_info(- symbol: ticker,- exchange_operating_mic: exchange_operating_mic+ # Brand logo, sourced independently of the price provider, so a security+ # priced by a logo-less provider (e.g. MOEX/ISS) still gets a real logo.+ # Runs after metadata so it never short-circuits website_url backfill.+ import_brand_logo(clear_cache: clear_cache)+ end++ # Enriches the security with a brand logo from a dedicated logo provider+ # (T-Invest), independent of which provider supplies prices. No-op when the+ # logo is already set, for crypto (own logo path), or when no logo provider /+ # token is configured. Runs every details import while the logo is missing.+ def import_brand_logo(clear_cache: false)+ return if crypto?+ return if logo_url.present? && !clear_cache++ provider = brand_logo_provider+ return unless provider++ response = provider.fetch_security_info(symbol: ticker, exchange_operating_mic: exchange_operating_mic)+ return unless response.success? && response.data.logo_url.present?++ update(logo_url: response.data.logo_url)+ rescue => e+ DebugLogEntry.capture(+ category: "security_metadata_fetch",+ level: "warn",+ message: "Brand logo fetch failed",+ source: self.class.name,+ provider: brand_logo_provider,+ metadata: { security_id: self.id, ticker: ticker, provider_error: e.message })+ end- if response.success?- # Only overwrite fields the provider actually returned, so providers that- # don't support metadata (e.g. Alpha Vantage) won't blank existing values.- attrs = {}- attrs[:name] = response.data.name if response.data.name.present?- attrs[:logo_url] = response.data.logo_url if response.data.logo_url.present?- attrs[:website_url] = response.data.links if response.data.links.present?- update(attrs) if attrs.any?- else- Rails.logger.warn("Failed to fetch security info for #{ticker} from #{price_data_provider.class.name}: #{response.error.message}")- DebugLogEntry.capture(- category: "security_metadata_fetch",- level: "warn",- message: "Failed to get security info",- source: self.class.name,- provider: price_data_provider,- metadata: {- security_id: self.id,- ticker: ticker,- provider_error: response.error.message- }- )- end+ # The provider consulted for brand logos regardless of price provider. Returns+ # nil unless a T-Invest token is configured. Uses the class-level lookup so it+ # doesn't depend on (or interfere with) per-instance Registry expectations.+ def brand_logo_provider+ Provider::Registry.get_provider(:tinkoff_invest)+ rescue Provider::Registry::Error+ nilenddef import_provider_prices(start_date:, end_date:, clear_cache: false)diff --git a/app/models/setting.rb b/app/models/setting.rbindex e6879ed8df..142e603186 100644--- a/app/models/setting.rb+++ b/app/models/setting.rb@@ -59,6 +59,7 @@ class Setting < RailsSettings::Basefield :tiingo_api_key, type: :string, default: ENV["TIINGO_API_KEY"]field :eodhd_api_key, type: :string, default: ENV["EODHD_API_KEY"]field :alpha_vantage_api_key, type: :string, default: ENV["ALPHA_VANTAGE_API_KEY"]+ field :tinkoff_invest_api_key, type: :string, default: ENV["TINKOFF_INVEST_API_KEY"]# Transparent encryption for API key fields. The `field` macro defines the# raw getter/setter on the class. By prepending this module we intercept@@ -73,6 +74,7 @@ class Setting < RailsSettings::Basetiingo_api_keyeodhd_api_keyalpha_vantage_api_key+ tinkoff_invest_api_keyopenai_access_tokenanthropic_access_tokenexternal_assistant_tokendiff --git a/app/views/settings/hostings/_provider_selection.html.erb b/app/views/settings/hostings/_provider_selection.html.erbindex 4f91c53acd..f27d377f72 100644--- a/app/views/settings/hostings/_provider_selection.html.erb+++ b/app/views/settings/hostings/_provider_selection.html.erb@@ -53,6 +53,7 @@["mfapi", t(".providers.mfapi"), t(".mfapi_hint")],["binance_public", t(".providers.binance_public"), t(".binance_public_hint")],["moex_public", t(".providers.moex_public"), t(".moex_public_hint")],+ ["tinkoff_invest", t(".providers.tinkoff_invest"), t(".tinkoff_invest_hint")],].each do |value, label, hint| %><label class="flex items-center gap-2 cursor-pointer"><input type="checkbox"diff --git a/app/views/settings/hostings/_tinkoff_invest_settings.html.erb b/app/views/settings/hostings/_tinkoff_invest_settings.html.erbnew file mode 100644index 0000000000..670c5d1da0--- /dev/null+++ b/app/views/settings/hostings/_tinkoff_invest_settings.html.erb@@ -0,0 +1,39 @@+<div class="space-y-4">+ <div>+ <h2 class="font-medium mb-1"><%= t(".title") %></h2>+ <% if ENV["TINKOFF_INVEST_API_KEY"].present? %>+ <p class="text-sm text-secondary"><%= t(".env_configured_message") %></p>+ <% else %>+ <div class="text-secondary text-sm mb-4">+ <span><%= t(".description") %></span>+ <%= render DS::Disclosure.new(variant: :inline) do |disclosure| %>+ <% disclosure.with_summary_content do %>+ <span class="font-medium text-secondary underline"><%= t(".show_details") %></span>+ <% end %>+ <ol class="text-sm text-secondary mt-2 list-decimal ml-6 space-y-2">+ <li><%= t(".step_1") %></li>+ <li><%= t(".step_2") %></li>+ <li><%= t(".step_3") %></li>+ </ol>+ <% end %>+ </div>+ <% end %>+ </div>++ <%= styled_form_with model: Setting.new,+ url: settings_hosting_path,+ method: :patch,+ data: {+ controller: "auto-submit-form",+ "auto-submit-form-trigger-event-value": "blur"+ } do |form| %>+ <% has_key = ENV["TINKOFF_INVEST_API_KEY"].present? || Setting.tinkoff_invest_api_key.present? %>+ <%= form.text_field :tinkoff_invest_api_key,+ label: t(".label"),+ type: "password",+ placeholder: t(".placeholder"),+ value: has_key ? "********" : "",+ disabled: ENV["TINKOFF_INVEST_API_KEY"].present?,+ data: { "auto-submit-form-target": "auto" } %>+ <% end %>+</div>diff --git a/app/views/settings/hostings/show.html.erb b/app/views/settings/hostings/show.html.erbindex 2921bd4a1d..a5cf082f63 100644--- a/app/views/settings/hostings/show.html.erb+++ b/app/views/settings/hostings/show.html.erb@@ -36,6 +36,9 @@<% if @show_alpha_vantage_settings %><%= render "settings/hostings/alpha_vantage_settings" %><% end %>+ <% if @show_tinkoff_invest_settings %>+ <%= render "settings/hostings/tinkoff_invest_settings" %>+ <% end %></div><% end %><%= settings_section title: t(".sync_settings") do %>diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.ymlindex 692e602c23..ed07e24371 100644--- a/config/locales/views/settings/hostings/en.yml+++ b/config/locales/views/settings/hostings/en.yml@@ -45,6 +45,7 @@ en:mfapi_hint: free, no API key -- Indian mutual funds onlybinance_public_hint: free, no API key -- crypto only (BTC, ETH, etc.)moex_public_hint: free, no API key -- Russian stocks, funds & bonds (MOEX), incl. RUB FX+ tinkoff_invest_hint: requires read-only token -- Russian stocks/funds/bonds prices + brand logosproviders:twelve_data: Twelve Datayahoo_finance: Yahoo Finance@@ -54,6 +55,7 @@ en:mfapi: MFAPI.inbinance_public: Binancemoex_public: MOEX+ tinkoff_invest: T-Invest (T-Bank)assistant_settings:title: AI Assistantdescription: Choose how the chat assistant responds. Builtin uses your configured LLM provider directly. External delegates to a remote AI agent that can call back to Sure's financial tools via MCP.@@ -155,6 +157,16 @@ en:step_1_html: 'Visit <a href="https://www.tiingo.com" target="_blank" rel="noopener noreferrer" class="underline">tiingo.com</a> and create a free account.'step_2_html: 'Go to the <a href="https://www.tiingo.com/account/api/token" target="_blank" rel="noopener noreferrer" class="underline">API Token</a> page.'step_3: Copy your API token and paste it below.+ tinkoff_invest_settings:+ title: T-Invest (T-Bank)+ description: Enter a read-only T-Invest API token. Used to fetch brand logos for securities (incl. funds and bonds, even when MOEX prices them) and, when enabled above, prices for Russian instruments.+ env_configured_message: Successfully configured through the TINKOFF_INVEST_API_KEY environment variable.+ label: API Token+ placeholder: Enter your T-Invest API token here+ show_details: "(show details)"+ step_1: Open T-Bank investments, then Settings, then API tokens (requires an open T-Bank brokerage account).+ step_2: Create a token with read-only access.+ step_3: Copy the token and paste it below.eodhd_settings:title: EODHDdescription: Enter the API token provided by EODHD. Supports EU ETFs on LSE, XETRA, and other international exchanges.diff --git a/test/models/provider/moex_public_test.rb b/test/models/provider/moex_public_test.rbindex 562c1e4020..e74ccc657e 100644--- a/test/models/provider/moex_public_test.rb+++ b/test/models/provider/moex_public_test.rb@@ -146,7 +146,7 @@ class Provider::MoexPublicTest < ActiveSupport::TestCase# Security info# ================================- test "fetch_security_info maps kind and a MOEX issue link" do+ test "fetch_security_info maps kind and omits an exchange website" do@provider.stubs(:resolve_instrument).returns(bond_instrument)response = @provider.fetch_security_info(symbol: "SU26238RMFS4", exchange_operating_mic: "MISX")@@ -154,7 +154,9 @@ class Provider::MoexPublicTest < ActiveSupport::TestCaseassert response.success?assert_equal "bond", response.data.kindassert_equal "MISX", response.data.exchange_operating_mic- assert_match(/moex\.com/, response.data.links)+ # No issuer website: moex.com is the exchange, not the issuer, and would make+ # Brandfetch render the exchange logo for every instrument.+ assert_nil response.data.linksend# ================================diff --git a/test/models/provider/tinkoff_invest_test.rb b/test/models/provider/tinkoff_invest_test.rbnew file mode 100644index 0000000000..7430669e1c--- /dev/null+++ b/test/models/provider/tinkoff_invest_test.rb@@ -0,0 +1,164 @@+require "test_helper"++class Provider::TinkoffInvestTest < ActiveSupport::TestCase+ setup do+ @provider = Provider::TinkoffInvest.new("test-token")+ @provider.stubs(:throttle_request)+ Rails.cache.clear+ end++ # ----- search -----++ test "search_securities maps a share to a stock with MOEX MIC" do+ stub_find("SBER", [ instrument_short(ticker: "SBER", name: "Sberbank", type: "share", class_code: "TQBR", currency: "rub", country: "RU") ])++ response = @provider.search_securities("SBER")++ assert response.success?+ sec = response.data.first+ assert_equal "SBER", sec.symbol+ assert_equal "Sberbank", sec.name+ assert_equal "MISX", sec.exchange_operating_mic+ assert_equal "RU", sec.country_code+ assert_equal "RUB", sec.currency+ assert_nil sec.logo_url, "search results carry no brand; logos come from fetch_security_info"+ end++ test "search_securities skips unsupported instrument kinds (futures, currency)" do+ stub_find("X", [+ instrument_short(ticker: "FUT", name: "Future", type: "futures", class_code: "SPBFUT"),+ instrument_short(ticker: "USD000UTSTOM", name: "Dollar", type: "currency", class_code: "CETS")+ ])++ response = @provider.search_securities("X")++ assert_empty response.data+ end++ # ----- info / logo -----++ test "fetch_security_info builds the CDN logo url from brand.logoName" do+ stub_find("SBER", [ instrument_short(ticker: "SBER", type: "share", class_code: "TQBR", uid: "uid-sber") ])+ stub_instrument_by("uid-sber", instrument_full(name: "Sberbank", logo_name: "SBER.png", exchange: "moex_mrng_evng_e_wknd_dlr"))++ response = @provider.fetch_security_info(symbol: "SBER", exchange_operating_mic: "MISX")++ assert response.success?+ assert_equal "Sberbank", response.data.name+ assert_equal "https://invest-brands.cdn-tinkoff.ru/SBERx160.png", response.data.logo_url+ assert_equal "MISX", response.data.exchange_operating_mic+ assert_equal "stock", response.data.kind+ end++ test "fetch_security_info returns a nil logo when brand is absent" do+ stub_find("XXX", [ instrument_short(ticker: "XXX", type: "share", class_code: "TQBR", uid: "uid-x") ])+ stub_instrument_by("uid-x", instrument_full(name: "No Brand", logo_name: nil))++ response = @provider.fetch_security_info(symbol: "XXX", exchange_operating_mic: nil)++ assert_nil response.data.logo_url+ end++ # ----- prices -----++ test "fetch_security_prices parses daily candle closes and appends the live last price" do+ travel_to Date.new(2026, 6, 18) do+ stub_find("SBER", [ instrument_short(ticker: "SBER", type: "share", class_code: "TQBR", uid: "uid-sber", currency: "rub") ])+ @provider.stubs(:post).with("MarketDataService", "GetCandles", anything).returns(+ "candles" => [+ candle("2026-06-16", units: 300, nano: 500_000_000),+ candle("2026-06-17", units: 305, nano: 0)+ ]+ )+ @provider.stubs(:post).with("MarketDataService", "GetLastPrices", anything).returns(+ "lastPrices" => [ { "price" => { "units" => "310", "nano" => 250_000_000 } } ]+ )++ response = @provider.fetch_security_prices(symbol: "SBER", exchange_operating_mic: "MISX", start_date: Date.new(2026, 6, 16), end_date: Date.new(2026, 6, 18))++ assert response.success?+ by_date = response.data.index_by(&:date)+ assert_equal BigDecimal("300.5"), by_date[Date.new(2026, 6, 16)].price+ assert_equal BigDecimal("305"), by_date[Date.new(2026, 6, 17)].price+ assert_equal BigDecimal("310.25"), by_date[Date.new(2026, 6, 18)].price, "today should use the live last price"+ assert_equal "RUB", by_date[Date.new(2026, 6, 16)].currency+ end+ end++ test "fetch_security_prices converts bond percent-of-par to money via nominal" do+ travel_to Date.new(2026, 6, 18) do+ stub_find("RU000A10AAQ4", [ instrument_short(ticker: "RU000A10AAQ4", isin: "RU000A10AAQ4", type: "bond", class_code: "TQCB", uid: "uid-bond", currency: "rub") ])+ stub_instrument_by("uid-bond", instrument_full(name: "Bond", nominal: { "units" => "1000", "nano" => 0 }))+ @provider.stubs(:post).with("MarketDataService", "GetCandles", anything).returns(+ "candles" => [ candle("2026-06-17", units: 103, nano: 700_000_000) ] # 103.7% of par+ )+ @provider.stubs(:post).with("MarketDataService", "GetLastPrices", anything).returns("lastPrices" => [])++ response = @provider.fetch_security_prices(symbol: "RU000A10AAQ4", exchange_operating_mic: "MISX", start_date: Date.new(2026, 6, 17), end_date: Date.new(2026, 6, 17))++ price = response.data.first+ assert_equal BigDecimal("1037"), price.price, "103.7% of 1000 nominal = 1037"+ end+ end++ test "fetch_security_prices fails (no zero price) when a bond nominal is missing" do+ travel_to Date.new(2026, 6, 18) do+ stub_find("RU000A10AAQ4", [ instrument_short(ticker: "RU000A10AAQ4", type: "bond", class_code: "TQCB", uid: "uid-bond", currency: "rub") ])+ stub_instrument_by("uid-bond", instrument_full(name: "Bond")) # no nominal+ @provider.stubs(:post).with("MarketDataService", "GetCandles", anything).returns("candles" => [ candle("2026-06-17", units: 103, nano: 0) ])+ @provider.stubs(:post).with("MarketDataService", "GetLastPrices", anything).returns("lastPrices" => [])++ response = @provider.fetch_security_prices(symbol: "RU000A10AAQ4", exchange_operating_mic: "MISX", start_date: Date.new(2026, 6, 17), end_date: Date.new(2026, 6, 17))++ assert_not response.success?+ assert_kind_of Provider::TinkoffInvest::InvalidSecurityPriceError, response.error+ end+ end++ test "fetch_security_prices skips incomplete candles" do+ travel_to Date.new(2026, 6, 18) do+ stub_find("SBER", [ instrument_short(ticker: "SBER", type: "share", class_code: "TQBR", uid: "uid-sber", currency: "rub") ])+ @provider.stubs(:post).with("MarketDataService", "GetCandles", anything).returns(+ "candles" => [ candle("2026-06-17", units: 305, nano: 0, complete: false) ]+ )+ @provider.stubs(:post).with("MarketDataService", "GetLastPrices", anything).returns("lastPrices" => [])++ response = @provider.fetch_security_prices(symbol: "SBER", exchange_operating_mic: "MISX", start_date: Date.new(2026, 6, 17), end_date: Date.new(2026, 6, 17))++ assert_empty response.data+ end+ end++ private++ def stub_find(query, instruments)+ @provider.stubs(:post)+ .with("InstrumentsService", "FindInstrument", has_entry(query: query))+ .returns("instruments" => instruments)+ end++ def stub_instrument_by(uid, instrument)+ @provider.stubs(:post)+ .with("InstrumentsService", "GetInstrumentBy", has_entry(id: uid))+ .returns("instrument" => instrument)+ end++ def instrument_short(ticker:, type:, class_code:, name: nil, uid: "uid", isin: "", currency: "rub", country: "RU", exchange: "moex")+ {+ "ticker" => ticker, "name" => name || ticker, "instrumentType" => type,+ "classCode" => class_code, "uid" => uid, "isin" => isin,+ "currency" => currency, "countryOfRisk" => country, "exchange" => exchange+ }+ end++ def instrument_full(name:, logo_name: nil, exchange: "moex", nominal: nil)+ h = { "name" => name, "exchange" => exchange }+ h["brand"] = { "logoName" => logo_name } unless logo_name.nil?+ h["nominal"] = nominal if nominal+ h+ end++ def candle(date, units:, nano:, complete: true)+ { "time" => "#{date}T00:00:00Z", "close" => { "units" => units.to_s, "nano" => nano }, "isComplete" => complete }+ end+enddiff --git a/test/models/security_test.rb b/test/models/security_test.rbindex 0c83483ee7..dfbcf6428a 100644--- a/test/models/security_test.rb+++ b/test/models/security_test.rb@@ -160,6 +160,19 @@ class SecurityTest < ActiveSupport::TestCaseassert_equal "https://example.com/aapl.png", sec.display_logo_urlend+ test "display_logo_url for non-crypto with no website prefers stored logo over brandfetch lettermark" do+ Setting.stubs(:brand_fetch_client_id).returns("test-client-id")+ Setting.stubs(:brand_fetch_logo_size).returns(120)++ sec = Security.new(+ ticker: "SBER",+ exchange_operating_mic: "MISX",+ logo_url: "https://invest-brands.cdn-tinkoff.ru/SBERx160.png"+ )++ assert_equal "https://invest-brands.cdn-tinkoff.ru/SBERx160.png", sec.display_logo_url+ end+test "before_save writes the /crypto/{base} URL to logo_url for new crypto securities" doSetting.stubs(:brand_fetch_client_id).returns("test-client-id")Setting.stubs(:brand_fetch_logo_size).returns(120)