The personal finance app for everyone (by everyone)
Ruby
fix(tinkoff): resolve the tradeable listing and price bonds via BondBy (#2413)
Artem Danilovc65f4828dd06
diff --git a/app/models/provider/tinkoff_invest.rb b/app/models/provider/tinkoff_invest.rbindex 9f1ba03b6b..d6313816cf 100644--- a/app/models/provider/tinkoff_invest.rb+++ b/app/models/provider/tinkoff_invest.rb@@ -77,6 +77,7 @@ class Provider::TinkoffInvest < Providernext [] if query.empty?find_instruments(query).filter_map do |row|+ next nil unless row["apiTradeAvailableFlag"] # only surface instruments the API can actually pricenext nil unless surfaced_kind(row["instrumentType"])Provider::SecurityConcept::Security.new(@@ -137,26 +138,34 @@ class Provider::TinkoffInvest < Providerbond = short["instrumentType"].to_s == "bond"currency = short["currency"].to_s.upcasemic = 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}"+ nominal = nil+ amortizing = false+ if bond+ info = bond_info(uid)+ nominal = info[:nominal]+ amortizing = info[:amortizing]+ raise InvalidSecurityPriceError, "Missing or invalid T-Invest bond nominal for #{symbol}" if nominal.nil? || nominal <= 0end- 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+ ticker = short["ticker"].to_s+ build = ->(date, raw) { Price.new(symbol: ticker, date: date, price: (bond ? (raw / 100) * nominal : raw), currency: currency, exchange_operating_mic: mic) }++ # BondBy returns only the CURRENT nominal. For an amortizing bond the par+ # shrinks over time, so applying today's nominal to historical percent-of-+ # par closes would underprice them — skip the candle history and return+ # just the live price. Fixed-par bonds and equities use full history.+ prices = (bond && amortizing) ? [] : candle_closes(uid, start_date, end_date).map { |date, close| build.call(date, close) }# The candle endpoint lags the live session; append the last price for a# range reaching today.if end_date >= Date.currentlast = last_price(uid)if last- value = bond ? (last / 100) * nominal : lastprices.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)+ prices << build.call(Date.current, last)endend@@ -220,30 +229,49 @@ class Provider::TinkoffInvest < Provider# Instruments# ================================+ # Users (and the MoexPublic resolver) paste exchange-suffixed tickers like+ # "T.MOEX"/"SBER.ME"; T-Invest only knows the bare SECID, so strip the suffix+ # before querying.+ SUFFIX = /\.(ME|MOEX|MISX|MCX)\z/i+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)+ q = query.to_s.strip.sub(SUFFIX, "")+ Rails.cache.fetch("tinkoff_invest:find:#{q.downcase}", expires_in: SEARCH_CACHE_TTL) do+ # Return all matches (not just apiTradeAvailableFlag) — a ticker can have+ # several non-tradeable listings plus one tradeable board; resolve_short+ # ranks the tradeable one first while keeping a fallback for instruments+ # Tinkoff lists but can't trade via API.+ body = post("InstrumentsService", "FindInstrument", query: q)body["instruments"] || []endend- # Best FindInstrument hit for a ticker/ISIN: exact ticker (or ISIN) match,- # preferring a requested MIC, then a surfaced kind, then any result.+ # Best FindInstrument hit for a ticker/ISIN. A ticker like SBER returns many+ # listings (TQBR, SPB, dark boards). When the caller supplied a MIC, honor it+ # FIRST so a security is never priced off another exchange's listing; then+ # prefer the API-tradeable board (the one with live prices), then an exact+ # ticker/ISIN match.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+ key = symbol.to_s.strip.sub(SUFFIX, "")+ # skip_nil so a transient empty/no-match response isn't cached as "unknown"+ # for the full 24h TTL.+ Rails.cache.fetch("tinkoff_invest:short:#{key.downcase}:#{exchange_operating_mic}", expires_in: INSTRUMENT_CACHE_TTL, skip_nil: true) dorows = find_instruments(key)up = key.upcaseexact = 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+ typed = pool.select { |r| surfaced_kind(r["instrumentType"]) }+ pool = typed if typed.any?+ next nil if pool.empty?++ mic = exchange_operating_mic.to_s.upcase+ pool.min_by do |r|+ [+ (mic.present? && mic_for(r["classCode"], r["exchange"]) == mic) ? 0 : 1,+ r["apiTradeAvailableFlag"] ? 0 : 1,+ (r["ticker"].to_s.upcase == up || r["isin"].to_s.upcase == up) ? 0 : 1+ ]endendend@@ -256,8 +284,13 @@ class Provider::TinkoffInvest < Providerendend- def instrument_nominal(uid)- quotation_to_d(instrument_detail(uid)["nominal"])+ # Bond nominal + amortization flag from BondBy (the generic GetInstrumentBy+ # omits nominal). `nominal` is the current (possibly amortized) par;+ # `amortizing` tells the price path that historical par differs from today's.+ def bond_info(uid)+ body = post("InstrumentsService", "BondBy", idType: "INSTRUMENT_ID_TYPE_UID", id: uid)+ ins = body["instrument"] || {}+ { nominal: quotation_to_d(ins["nominal"]), amortizing: ins["amortizationFlag"] == true }end# ================================diff --git a/test/models/provider/tinkoff_invest_test.rb b/test/models/provider/tinkoff_invest_test.rbindex 7430669e1c..64ad247a8b 100644--- a/test/models/provider/tinkoff_invest_test.rb+++ b/test/models/provider/tinkoff_invest_test.rb@@ -88,7 +88,7 @@ class Provider::TinkoffInvestTest < ActiveSupport::TestCasetest "fetch_security_prices converts bond percent-of-par to money via nominal" dotravel_to Date.new(2026, 6, 18) dostub_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 }))+ stub_bond_by("uid-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)@@ -104,7 +104,7 @@ class Provider::TinkoffInvestTest < ActiveSupport::TestCasetest "fetch_security_prices fails (no zero price) when a bond nominal is missing" dotravel_to Date.new(2026, 6, 18) dostub_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+ stub_bond_by("uid-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" => [])@@ -115,6 +115,32 @@ class Provider::TinkoffInvestTest < ActiveSupport::TestCaseendend+ test "fetch_security_prices returns only the live price for an amortizing bond" 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_bond_by("uid-bond", { "nominal" => { "units" => "417", "nano" => 710_000_000 }, "amortizationFlag" => true })+ @provider.stubs(:post).with("MarketDataService", "GetCandles", anything).returns("candles" => [ candle("2026-06-10", units: 105, nano: 0) ])+ @provider.stubs(:post).with("MarketDataService", "GetLastPrices", anything).returns("lastPrices" => [ { "price" => { "units" => "103", "nano" => 0 } } ])++ response = @provider.fetch_security_prices(symbol: "RU000A10AAQ4", exchange_operating_mic: "MISX", start_date: Date.new(2026, 6, 10), end_date: Date.new(2026, 6, 18))++ # The historical candle is skipped (today's nominal must not reprice old par);+ # only the live price remains, converted with the current nominal.+ assert_equal [ Date.new(2026, 6, 18) ], response.data.map(&:date)+ assert_equal (BigDecimal("103") / 100 * BigDecimal("417.71")), response.data.first.price+ end+ end++ test "resolve strips an exchange suffix before querying T-Invest" do+ stub_find("T", [ instrument_short(ticker: "T", type: "share", class_code: "TQBR", uid: "uid-t") ])+ stub_instrument_by("uid-t", instrument_full(name: "T-Tech", logo_name: "tcs2.png"))++ response = @provider.fetch_security_info(symbol: "T.MOEX", exchange_operating_mic: "MISX")++ assert response.success?+ assert_equal "https://invest-brands.cdn-tinkoff.ru/tcs2x160.png", response.data.logo_url+ end+test "fetch_security_prices skips incomplete candles" dotravel_to Date.new(2026, 6, 18) dostub_find("SBER", [ instrument_short(ticker: "SBER", type: "share", class_code: "TQBR", uid: "uid-sber", currency: "rub") ])@@ -143,10 +169,16 @@ class Provider::TinkoffInvestTest < ActiveSupport::TestCase.returns("instrument" => instrument)end- def instrument_short(ticker:, type:, class_code:, name: nil, uid: "uid", isin: "", currency: "rub", country: "RU", exchange: "moex")+ def stub_bond_by(uid, instrument)+ @provider.stubs(:post)+ .with("InstrumentsService", "BondBy", 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", tradeable: true){"ticker" => ticker, "name" => name || ticker, "instrumentType" => type,- "classCode" => class_code, "uid" => uid, "isin" => isin,+ "classCode" => class_code, "uid" => uid, "isin" => isin, "apiTradeAvailableFlag" => tradeable,"currency" => currency, "countryOfRisk" => country, "exchange" => exchange}end