Skip to content

Add Binance testnet API integration#7

Merged
mayankjanmejay merged 5 commits into
mainfrom
claude/add-binance-testnet-api-oKaCO
Dec 29, 2025
Merged

Add Binance testnet API integration#7
mayankjanmejay merged 5 commits into
mainfrom
claude/add-binance-testnet-api-oKaCO

Conversation

@mayankjanmejay
Copy link
Copy Markdown
Owner

@mayankjanmejay mayankjanmejay commented Dec 29, 2025

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced Demo Trading API as an alternative test environment
    • Added support for advanced order types: OCO, OTO, and OTOCO
    • Enabled WebSocket streaming for test environments
    • Significantly expanded test environment endpoints and functionality
  • Bug Fixes

    • Improved thread-safety in rate limiting
    • Enhanced error handling for invalid API responses
  • Improvements

    • Added order parameter validation and normalization
    • Implemented resource cleanup mechanism

✏️ Tip: You can customize this high-level summary in your review settings.

- Add TestnetWebSocket for testnet market streams
  (wss://stream.testnet.binance.vision:9443)
- Add TestnetSpot.dispose() for proper resource cleanup
- Add comprehensive market data endpoints:
  - ping(), getExchangeInfo() with filters
  - getUIKlines(), getTradingDayTicker()
  - getRollingWindowTicker() for rolling window stats
  - Proper weight tracking for all endpoints
- Add advanced order types for testnet trading:
  - OCO (One-Cancels-Other) orders
  - OTO (One-Triggers-Other) orders
  - OTOCO (One-Triggers-OCO) orders
  - Cancel-Replace operations
- Add testnet failover endpoints in BinanceBase
  (api1.testnet.binance.vision)
- Add Demo Trading API support as alternative testnet:
  - DemoSpot, DemoTrading, DemoMarket classes
  - DemoFuturesUsd for futures demo trading
  - DemoWebSocket (wss://demo-stream.binance.com)
  - Base URL: https://demo-api.binance.com
- Add Binance.demo() factory constructor
- Update testnet example with new features documentation
Add comprehensive COIN-M (inverse) futures testnet integration:

- TestnetFuturesCoinM class for COIN-margined delivery futures
- TestnetFuturesCoinMMarket with full market data endpoints:
  - ping, getServerTime, getExchangeInfo
  - getOrderBook, getRecentTrades, getHistoricalTrades, getAggTrades
  - getKlines, getContinuousKlines, getIndexPriceKlines, getMarkPriceKlines
  - getPremiumIndex, getFundingRate, get24HrTicker
  - getTickerPrice, getBookTicker, getOpenInterest, getOpenInterestHist
- TestnetFuturesCoinMTrading with all trading operations:
  - placeOrder, placeBatchOrders
  - getOrder, cancelOrder, cancelAllOrders, cancelBatchOrders
  - setAutoCancel, getCurrentOpenOrder, getOpenOrders, getAllOrders
  - getBalance, getAccountInfo
  - changeInitialLeverage, changeMarginType
  - modifyIsolatedPositionMargin, getPositionMarginHistory
  - getPositionRisk, getUserTrades, getIncomeHistory
  - getLeverageBracket, changePositionMode, getPositionMode
  - getForceOrders, getAdlQuantile, getCommissionRate
- TestnetFuturesCoinMUserDataStream for user data streaming
- Updated example with COIN-M futures documentation

COIN-M futures are settled in cryptocurrency (BTC, ETH) rather than
USDT, using /dapi/ endpoints on testnet.binancefuture.com.
Major fixes based on comprehensive code review:

Security Fixes:
- Make API credentials private (_apiKey, _apiSecret) to prevent exposure
- Remove public accessors that could leak sensitive data

Reliability Fixes:
- Add thread-safe locking to TokenBucket rate limiter
- Add server time sync locking to prevent race conditions
- Add bounded buffer (10k messages) to WebSocket to prevent memory leaks
- Fix JSON parsing with proper FormatException handling for WAF/CDN errors
- Complete dispose() method to clean up all resources

Financial Precision Fixes:
- Change order quantity/price from double to String for exact precision
- Prevents floating-point rounding errors in financial calculations

Parameter Validation:
- Add comprehensive order parameter validation (side, type, required fields)
- Validate LIMIT orders require price and timeInForce
- Validate STOP orders require stopPrice
- Normalize inputs (uppercase symbols, sides, types)

Code Quality:
- Remove dead code (Awesome class)
- Improve error messages for debugging

These fixes address CRITICAL and HIGH severity issues from:
- Principal Test Engineer review (15 critical, 24 high)
- Principal Developer #1 review (5 critical, 10 high)
- Principal Developer #2 review (8 critical, 6 high)
Critical fix for financial precision issues across all trading endpoints:
- FuturesTrading.placeOrder: quantity, price, stopPrice now String
- FuturesTrading.changePositionMargin: amount now String
- MarginTrading.marginBorrow/marginRepay: amount now String
- MarginTrading.placeMarginOrder: quantity, price now String
- TestnetTrading: placeOrder, testOrder, cancelReplace, OCO, OTO, OTOCO
- TestnetFuturesUsdTrading.placeOrder: all financial params String
- TestnetFuturesCoinMTrading.placeOrder: all financial params String
- DemoTrading.placeOrder/testOrder: all financial params String
- DemoFuturesUsdTrading.placeOrder: all financial params String

Added input validation for side/type parameters with helpful error messages.
Added isOrder flag for proper rate limiting on order endpoints.
Fixes the remaining precision issue in COIN-M futures margin modification
endpoint. The amount parameter now uses String instead of double to prevent
precision loss in cryptocurrency margin operations.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Dec 29, 2025

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

This pull request substantially expands testnet and demo trading capabilities, introduces demo endpoints (DemoSpot, DemoFutures), adds WebSocket support to testnet environments, refactors credential handling with private fields and thread-safe locking, converts numeric parameter types from double to String across trading methods, and enhances error handling and buffer management.

Changes

Cohort / File(s) Summary
Demo Trading & Testnet API Expansion
lib/src/testnet.dart, lib/src/babel_binance_base.dart
Added WebSocket support to TestnetSpot; introduced complete Demo Trading API infrastructure (DemoSpot, DemoMarket, DemoTrading, DemoFuturesUsd) with parallel endpoints to testnet; expanded Market/Trading/Futures endpoints for testnet environments; added factory Binance.demo() and new public fields (testnetFuturesCoinM, demoSpot, demoFutures); introduced async dispose() method for resource cleanup.
Numeric Parameter Standardization & Order Validation
lib/src/futures_usd.dart, lib/src/margin.dart, lib/src/spot.dart
Changed parameter types from double to String for quantity/price/amount across trading methods; added input validation for order sides/types; introduced uppercase normalization for symbol/side/type/timeInForce; added new placeOrder() method to Spot Trading with enhanced validation and optional stopPrice/newClientOrderId.
Credential Security & Server Synchronization
lib/src/binance_base.dart
Refactored apiKey/apiSecret to private fields (_apiKey, _apiSecret) with public getters; added hasCredentials boolean getter; introduced locking mechanism (_serverTimeSyncLock) to prevent concurrent server time synchronization; enhanced JSON/error parsing in sendRequest with try-catch and descriptive error messages for invalid responses.
Thread-Safe Token Bucket & Rate Limiting
lib/src/rate_limiting/token_bucket.dart
Made token consumption asynchronous; converted tryConsume() to return Future<bool>; added thread-safe lock-based synchronization; introduced async variants: getAvailableTokens(), reset(), and synchronous tryConsumeSync() for backward compatibility; added locking around wait-time calculations.
WebSocket Buffer Management
lib/src/websocket/websocket_stream.dart
Introduced high-water mark buffer mechanism with maxBufferSize constant (10000); added tracking for dropped messages (_droppedMessages counter); implemented overflow protection to drop messages when buffer is full; exposed droppedMessages getter for monitoring.
Documentation & Example Updates
example/testnet_integration_example.dart
Expanded documentation with multiple testnet environments; reworded feature descriptions; reorganized demo flow: renamed step5_BestPractices() to step5_DemoTradingApi() and added step6_BestPractices(); updated print statements for clarity; added code examples for OCO/OTO/OTOCO orders and WebSocket streaming; standardized setup messaging and API key guidance.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Poem

🐰 A demo trading burrow so bright,
With testnet tunnels extending right,
Thread-safe tokens hop with care,
WebSocket streams float through the air,
Credentials snug in private affairs! 🥬


📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5667268 and 3302e86.

📒 Files selected for processing (9)
  • example/testnet_integration_example.dart
  • lib/src/babel_binance_base.dart
  • lib/src/binance_base.dart
  • lib/src/futures_usd.dart
  • lib/src/margin.dart
  • lib/src/rate_limiting/token_bucket.dart
  • lib/src/spot.dart
  • lib/src/testnet.dart
  • lib/src/websocket/websocket_stream.dart

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@mayankjanmejay mayankjanmejay merged commit 4fbbb0b into main Dec 29, 2025
1 check was pending
@mayankjanmejay mayankjanmejay deleted the claude/add-binance-testnet-api-oKaCO branch December 29, 2025 18:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants