The personal finance app for everyone (by everyone)
Ruby
fix(binance): correct base_url for futures api endpoint, start_time param (#2839)
UnamedRus8c52e2090687
diff --git a/app/models/binance_account/processor.rb b/app/models/binance_account/processor.rbindex 21306f2753..5e67dbaf75 100644--- a/app/models/binance_account/processor.rb+++ b/app/models/binance_account/processor.rb@@ -8,6 +8,18 @@ class BinanceAccount::Processor# the most common pairs are tried first and rate-limit weight is front-loaded.TRADE_QUOTE_CURRENCIES = %w[USDT BUSD FDUSD BTC ETH BNB].freeze+ # Binance caps the startTime/endTime span per trade-history endpoint: 24h for+ # spot myTrades, 7 days for futures userTrades. Because fromId cannot be+ # combined with startTime/endTime, the initial history sync walks forward one+ # window at a time from the configured start date.+ TRADE_WINDOW_MS = { spot: 24 * 60 * 60 * 1000, futures: 7 * 24 * 60 * 60 * 1000 }.freeze++ # Futures userTrades only serves the past 6 months, so the initial window walk+ # is clamped to that lookback regardless of the configured start date.+ FUTURES_MAX_LOOKBACK_MS = 6 * 30 * 24 * 60 * 60 * 1000++ TRADE_PAGE_LIMIT = 1000+attr_reader :binance_accountdef initialize(binance_account)@@ -119,29 +131,31 @@ class BinanceAccount::Processorend# Fetches only trades newer than what is already cached for the given pair.- # On the first sync (no cached trades) fetches the most recent page.- # On subsequent syncs starts from max_cached_id + 1 and paginates forward.+ # On subsequent syncs (trades already cached) it paginates forward by trade id+ # from max_cached_id + 1. On the first sync it walks forward through Binance's+ # per-endpoint time windows from the configured start date, because fromId+ # cannot be combined with startTime/endTime.def fetch_new_trades(provider, pair, cached_trades, market_type)- limit = 1000max_cached_id = cached_trades&.map { |t| t["id"].to_i }&.max- from_id = max_cached_id ? max_cached_id + 1 : nil- start_time = nil- unless max_cached_id- start_time = binance_account.binance_item&.sync_start_date&.to_time&.to_i&.*(1000)+ if max_cached_id+ fetch_trades_from_id(provider, pair, market_type, max_cached_id + 1)+ else+ fetch_trades_in_windows(provider, pair, market_type)end+ end++ # Incremental sync: fromId alone is a supported Binance combination, so we+ # paginate forward by id until a partial page signals the end.+ def fetch_trades_from_id(provider, pair, market_type, from_id)all_new = []loop do- page = if market_type == :spot- provider.get_spot_trades(pair, limit: limit, from_id: from_id, startTime: start_time)- else- provider.get_futures_trades(pair, limit: limit, from_id: from_id, startTime: start_time)- end+ page = request_trades(provider, pair, market_type, from_id: from_id)break if page.blank?all_new.concat(page)- break if page.size < limit+ break if page.size < TRADE_PAGE_LIMITfrom_id = page.map { |t| t["id"].to_i }.max + 1end@@ -149,6 +163,51 @@ class BinanceAccount::Processorall_newend+ # Initial sync: walk forward from the configured start date in fixed windows+ # (24h spot / 7d futures). If a window yields a full page there may be more+ # trades inside it, so we advance the cursor past the last trade and re-scan+ # the same window before moving on.+ def fetch_trades_in_windows(provider, pair, market_type)+ window = TRADE_WINDOW_MS[market_type]+ now_ms = Time.current.to_i * 1000++ configured_start = binance_account.binance_item&.sync_start_date&.to_time&.to_i+ cursor = configured_start ? configured_start * 1000 : now_ms - window++ # Futures history is only available for the last 6 months.+ if market_type == :futures+ cursor = [ cursor, now_ms - FUTURES_MAX_LOOKBACK_MS ].max+ end++ all_new = []++ while cursor <= now_ms+ window_end = [ cursor + window - 1, now_ms ].min+ page = request_trades(provider, pair, market_type, start_time: cursor, end_time: window_end)++ if page.present?+ all_new.concat(page)++ if page.size >= TRADE_PAGE_LIMIT+ cursor = page.map { |t| t["time"].to_i }.max + 1+ next+ end+ end++ cursor = window_end + 1+ end++ all_new+ end++ def request_trades(provider, pair, market_type, from_id: nil, start_time: nil, end_time: nil)+ if market_type == :spot+ provider.get_spot_trades(pair, limit: TRADE_PAGE_LIMIT, from_id: from_id, start_time: start_time, end_time: end_time)+ else+ provider.get_futures_trades(pair, limit: TRADE_PAGE_LIMIT, from_id: from_id, start_time: start_time, end_time: end_time)+ end+ end+def fetch_new_p2p_trades(provider, cached_p2p)# Binance P2P history endpoint only supports max 30-day windows.# If no cache exists, we fetch back to sync_start_date (or default 30 days).diff --git a/app/models/provider/binance.rb b/app/models/provider/binance.rbindex 683b660fcf..ad8833a107 100644--- a/app/models/provider/binance.rb+++ b/app/models/provider/binance.rb@@ -82,9 +82,13 @@ class Provider::Binance# Signed trade history for a single symbol, e.g. "BTCUSDT".# Pass from_id to fetch only trades with id >= from_id (for incremental sync).- def get_spot_trades(symbol, limit: 1000, from_id: nil)+ # Pass start_time/end_time (epoch ms) to fetch a bounded window instead; Binance+ # rejects from_id combined with start_time/end_time, so callers use one or the other.+ def get_spot_trades(symbol, limit: 1000, from_id: nil, start_time: nil, end_time: nil)params = { "symbol" => symbol, "limit" => limit.to_s }params["fromId"] = from_id.to_s if from_id+ params["startTime"] = start_time.to_s if start_time+ params["endTime"] = end_time.to_s if end_timesigned_get("/api/v3/myTrades", extra_params: params)end@@ -94,9 +98,11 @@ class Provider::Binanceend# Futures trade history for a single symbol- def get_futures_trades(symbol, limit: 1000, from_id: nil)+ def get_futures_trades(symbol, limit: 1000, from_id: nil, start_time: nil, end_time: nil)params = { "symbol" => symbol, "limit" => limit.to_s }params["fromId"] = from_id.to_s if from_id+ params["startTime"] = start_time.to_s if start_time+ params["endTime"] = end_time.to_s if end_timesigned_get("/fapi/v1/userTrades", extra_params: params, base_url: FUTURES_BASE_URL)end@@ -141,10 +147,9 @@ class Provider::Binanceparams = timestamp_params.merge(extra_params)query_string = URI.encode_www_form(params.sort)- full_url = "#{base_url}#{path}"-response = self.class.get(- full_url,+ path,+ base_uri: base_url,query: "#{query_string}&signature=#{sign(query_string)}",headers: auth_headers)diff --git a/test/models/binance_account/processor_test.rb b/test/models/binance_account/processor_test.rbindex 0e363508e5..2747fa586b 100644--- a/test/models/binance_account/processor_test.rb+++ b/test/models/binance_account/processor_test.rb@@ -98,11 +98,12 @@ class BinanceAccount::ProcessorTest < ActiveSupport::TestCaseprovider.stubs(:get_spot_price).returns("50000.0")provider.stubs(:get_all_p2p_trades).returns([]) # Skip P2P- # Mock futures trades- provider.stubs(:get_futures_trades).returns([])- provider.stubs(:get_futures_trades).with("BTCUSDT", limit: 1000, from_id: nil, startTime: nil).returns([- { "id" => 1, "time" => 1610000000000, "qty" => "0.1", "price" => "40000.0", "quoteQty" => "4000.0", "commission" => "0.0", "commissionAsset" => "USDT", "buyer" => true }- ])+ # No cached trades -> initial sync walks time windows. First window returns+ # the trade, every later window/pair returns nothing.+ provider.stubs(:get_futures_trades).returns(+ [ { "id" => 1, "time" => 1610000000000, "qty" => "0.1", "price" => "40000.0", "quoteQty" => "4000.0", "commission" => "0.0", "commissionAsset" => "USDT", "buyer" => true } ],+ []+ )Security.create!(ticker: "CRYPTO:BTC", name: "Bitcoin", price_provider: "binance_public")@@ -113,6 +114,73 @@ class BinanceAccount::ProcessorTest < ActiveSupport::TestCaseassert @account.entries.exists?(external_id: "binance_futures_BTCUSDT_1")end+ test "initial futures sync walks multiple 7-day windows from sync_start_date" do+ @family.update!(currency: "USD")+ @item.update!(sync_start_date: 20.days.ago)+ @ba.update!(raw_payload: { "assets" => [ { "symbol" => "BTC", "total" => "1.0" } ] })++ provider = mock+ @item.stubs(:binance_provider).returns(provider)+ @ba.stubs(:binance_item).returns(@item)+ provider.stubs(:get_spot_trades).returns([])+ provider.stubs(:get_spot_price).returns("50000.0")+ provider.stubs(:get_all_p2p_trades).returns([])++ trade = ->(id) {+ { "id" => id, "time" => 1610000000000, "qty" => "0.1", "price" => "40000.0", "quoteQty" => "4000.0", "commission" => "0.0", "commissionAsset" => "USDT", "buyer" => true }+ }++ # A 20-day span splits into three consecutive 7-day windows; each returns a+ # distinct trade, then all remaining windows/pairs return nothing.+ provider.stubs(:get_futures_trades).returns([ trade.call(1) ], [ trade.call(2) ], [ trade.call(3) ], [])++ Security.create!(ticker: "CRYPTO:BTC", name: "Bitcoin", price_provider: "binance_public")++ assert_difference "Entry.count", 3 do+ BinanceAccount::Processor.new(@ba).process+ end++ assert @account.entries.exists?(external_id: "binance_futures_BTCUSDT_1")+ assert @account.entries.exists?(external_id: "binance_futures_BTCUSDT_2")+ assert @account.entries.exists?(external_id: "binance_futures_BTCUSDT_3")+ end++ test "incremental sync paginates by fromId across full pages" do+ @family.update!(currency: "USD")+ @ba.update!(+ raw_payload: { "assets" => [ { "symbol" => "BTC", "total" => "1.0" } ] },+ raw_transactions_payload: {+ "futures" => { "BTCUSDT" => [ { "id" => 100, "time" => 1610000000000 } ] }+ }+ )++ provider = mock+ @item.stubs(:binance_provider).returns(provider)+ @ba.stubs(:binance_item).returns(@item)+ provider.stubs(:get_spot_trades).returns([])+ provider.stubs(:get_spot_price).returns("50000.0")+ provider.stubs(:get_all_p2p_trades).returns([])++ full_page = (101..1100).map do |id|+ { "id" => id, "time" => 1610000000000, "qty" => "0.1", "price" => "40000.0", "quoteQty" => "4000.0", "commission" => "0.0", "commissionAsset" => "USDT", "buyer" => true }+ end+ last_page = [ { "id" => 1101, "time" => 1610000000000, "qty" => "0.1", "price" => "40000.0", "quoteQty" => "4000.0", "commission" => "0.0", "commissionAsset" => "USDT", "buyer" => true } ]++ # First BTCUSDT futures call returns a full 1000-row page (triggers a second+ # fromId request); the follow-up returns the final partial page. Other pairs+ # have no cached trades, so their window scans return nothing.+ provider.stubs(:get_futures_trades).returns(full_page, last_page, [])++ Security.create!(ticker: "CRYPTO:BTC", name: "Bitcoin", price_provider: "binance_public")++ assert_difference "Entry.count", 1001 do+ BinanceAccount::Processor.new(@ba).process+ end++ assert @account.entries.exists?(external_id: "binance_futures_BTCUSDT_101")+ assert @account.entries.exists?(external_id: "binance_futures_BTCUSDT_1101")+ end+test "processes P2P BUY trades with double-entry logic and exact native fiat" do@family.update!(currency: "USD")@account.update!(currency: "USD")