A comprehensive Ruby SDK for Buda.com cryptocurrency exchange API with built-in debugging, error handling, and extensive examples.
- ✅ Complete API Coverage - All public and authenticated endpoints
- 🛡️ Robust Error Handling - Comprehensive exception handling with detailed error context
- 🔍 Debug Mode - Detailed HTTP request/response logging for development
- 📊 Rich Data Models - Object-oriented response models with helper methods
- 🔐 Secure Authentication - HMAC-SHA384 authentication with automatic signature generation
- ⚡ Automatic Retries - Built-in retry logic for transient failures
- 📖 Extensive Documentation - Complete API reference and examples
- 🧪 Comprehensive Examples - Real-world usage examples including a trading bot
- 🤖 AI-Powered Trading - Advanced AI features with RubyLLM integration
Add this line to your application's Gemfile:
gem'buda_api'And then execute:
$ bundle installOr install it yourself as:
$ gem install buda_apiFor AI features, also install:
$ gem install ruby_llmrequire'buda_api'# Create a public clientclient=BudaApi.public_client# Get all marketsmarkets=client.marketsputs"Available markets: #{markets.map(&:id).join(', ')}"# Get ticker informationticker=client.ticker("BTC-CLP")puts"BTC-CLP price: #{ticker.last_price}"puts"24h change: #{ticker.price_variation_24h}%"# Get order bookorder_book=client.order_book("BTC-CLP")puts"Best ask: #{order_book.best_ask.price}"puts"Best bid: #{order_book.best_bid.price}"puts"Spread: #{order_book.spread_percentage}%"require'buda_api'# Create authenticated clientclient=BudaApi.authenticated_client(api_key: "your_api_key",api_secret: "your_api_secret")# Check your balancebalance=client.balance("BTC")puts"Available BTC: #{balance.available_amount}"# Place a limit buy orderorder=client.place_order("BTC-CLP","Bid","limit",0.001,50000000)puts"Order placed: #{order.id}"# Cancel the ordercancelled=client.cancel_order(order.id)puts"Order cancelled: #{cancelled.state}"Configure the SDK globally:
BudaApi.configuredo |config|
config.debug_mode=true# Enable debug loggingconfig.timeout=30# Request timeout in seconds config.retries=3# Number of retry attemptsconfig.logger_level=:info# Logging levelconfig.base_url="https://www.buda.com/api/v2/"# API base URLend# Get all available marketsmarkets=client.markets# Returns: Array<BudaApi::Models::Market># Get specific market details market=client.market_details("BTC-CLP")# Returns: BudaApi::Models::Market# Get ticker informationticker=client.ticker("BTC-CLP")# Returns: BudaApi::Models::Ticker# Get order bookorder_book=client.order_book("BTC-CLP")# Returns: BudaApi::Models::OrderBook# Get recent tradestrades=client.trades("BTC-CLP",limit: 50)# Returns: BudaApi::Models::Trades# Get price quotation for buying 0.1 BTC at market pricequote=client.quotation("BTC-CLP","bid_given_size",0.1)# Returns: BudaApi::Models::Quotation# Get price quotation with limit pricequote=client.quotation_limit("BTC-CLP","ask_given_size",0.1,60000000)# Returns: BudaApi::Models::Quotation# Get average price reportstart_time=Time.now - 86400# 24 hours agoavg_prices=client.average_prices_report("BTC-CLP",start_at: start_time)# Returns: Array<BudaApi::Models::AveragePrice># Get candlestick datacandles=client.candlestick_report("BTC-CLP",start_at: start_time)# Returns: Array<BudaApi::Models::Candlestick># Get balance for specific currencybalance=client.balance("BTC")# Returns: BudaApi::Models::Balance# Get balance events with filteringevents=client.balance_events(currencies: ["BTC","CLP"],event_names: ["deposit_confirm","withdrawal_confirm"],page: 1,per_page: 50)# Returns: Hash with :events and :total_count# Place ordersbuy_order=client.place_order("BTC-CLP","Bid","limit",0.001,50000000)sell_order=client.place_order("BTC-CLP","Ask","market",0.001)# Get order historyorders=client.orders("BTC-CLP",page: 1,per_page: 100,state: "traded")# Returns: BudaApi::Models::OrderPages# Get specific order detailsorder=client.order_details(12345)# Returns: BudaApi::Models::Order# Cancel ordercancelled=client.cancel_order(12345)# Returns: BudaApi::Models::Order# Batch operations (cancel multiple, place multiple)result=client.batch_orders(cancel_orders: [123,456],place_orders: [{type: "Bid",price_type: "limit",amount: "0.001",limit: "50000"}])# Get withdrawalswithdrawals=client.withdrawals("BTC",page: 1,per_page: 20)# Returns: Hash with :withdrawals and :meta# Get deposits deposits=client.deposits("BTC",page: 1,per_page: 20)# Returns: Hash with :deposits and :meta# Simulate withdrawal (calculate fees without executing)simulation=client.simulate_withdrawal("BTC",0.01)# Returns: BudaApi::Models::Withdrawal# Execute withdrawalwithdrawal=client.withdrawal("BTC",0.01,"destination_address")# Returns: BudaApi::Models::WithdrawalThe SDK provides comprehensive error handling with specific exception classes:
beginticker=client.ticker("INVALID-MARKET")rescueBudaApi::ValidationError=>eputs"Validation failed: #{e.message}"rescueBudaApi::NotFoundError=>eputs"Resource not found: #{e.message}"rescueBudaApi::AuthenticationError=>eputs"Authentication failed: #{e.message}"rescueBudaApi::RateLimitError=>eputs"Rate limit exceeded: #{e.message}"rescueBudaApi::ServerError=>eputs"Server error: #{e.message}"rescueBudaApi::ConnectionError=>eputs"Connection failed: #{e.message}"rescueBudaApi::ApiError=>eputs"API error: #{e.message}"puts"Status: #{e.status_code}"puts"Response: #{e.response_body}"endBudaApi::ApiError (base class)
├── BudaApi::AuthenticationError # 401 errors
├── BudaApi::AuthorizationError # 403 errors ├── BudaApi::BadRequestError # 400 errors
├── BudaApi::NotFoundError # 404 errors
├── BudaApi::RateLimitError # 429 errors
├── BudaApi::ServerError # 5xx errors
├── BudaApi::ConnectionError # Network issues
├── BudaApi::TimeoutError # Request timeouts
└── BudaApi::InvalidResponseError # Invalid response format
BudaApi::ValidationError # Parameter validation
BudaApi::ConfigurationError # SDK configuration issues
Enable debug mode to see detailed HTTP request/response logs:
BudaApi.configuredo |config|
config.debug_mode=trueconfig.logger_level=:debugend# All requests will now show detailed logs:# → GET https://www.buda.com/api/v2/markets/BTC-CLP/ticker# → Headers: {"User-Agent"=>"BudaApi Ruby SDK 1.0.0"} # ← 200# ← Headers: {"content-type"=>"application/json"}# ← Body: {"ticker": {...}}# ← Duration: 150msAll API responses are wrapped in rich data model objects with helper methods:
market=client.market_details("BTC-CLP")market.id# => "BTC-CLP"market.name# => "Bitcoin/Chilean Peso" market.base_currency# => "BTC"market.quote_currency# => "CLP"market.minimum_order_amount# => #<BudaApi::Models::Amount>ticker=client.ticker("BTC-CLP")ticker.last_price# => #<BudaApi::Models::Amount>ticker.min_ask# => #<BudaApi::Models::Amount>ticker.max_bid# => #<BudaApi::Models::Amount> ticker.volume# => #<BudaApi::Models::Amount>ticker.price_variation_24h# => -2.5 (percentage)ticker.price_variation_7d# => 10.3 (percentage)order_book=client.order_book("BTC-CLP")order_book.asks# => Array<BudaApi::Models::OrderBookEntry>order_book.bids# => Array<BudaApi::Models::OrderBookEntry>order_book.best_ask# => #<BudaApi::Models::OrderBookEntry>order_book.best_bid# => #<BudaApi::Models::OrderBookEntry>order_book.spread# => 50000.0 (price difference)order_book.spread_percentage# => 0.12 (percentage)order=client.order_details(12345)order.id# => 12345order.state# => "traded" order.type# => "Bid"order.amount# => #<BudaApi::Models::Amount>order.limit# => #<BudaApi::Models::Amount>order.traded_amount# => #<BudaApi::Models::Amount>order.filled_percentage# => 100.0order.is_filled?# => trueorder.is_active?# => falseorder.is_cancelled?# => falsebalance=client.balance("BTC")balance.currency# => "BTC"balance.amount# => #<BudaApi::Models::Amount> (total)balance.available_amount# => #<BudaApi::Models::Amount>balance.frozen_amount# => #<BudaApi::Models::Amount> balance.pending_withdraw_amount# => #<BudaApi::Models::Amount>The SDK includes comprehensive examples in the examples/ directory:
public_api_example.rb- Public API usageauthenticated_api_example.rb- Authenticated API usageerror_handling_example.rb- Error handling and debugging
trading_bot_example.rb- Simple trading bot with price monitoring
ai/trading_assistant_example.rb- Comprehensive AI trading assistantai/natural_language_trading.rb- Conversational trading interfaceai/risk_management_example.rb- AI-powered risk analysisai/anomaly_detection_example.rb- Market anomaly detectionai/report_generation_example.rb- Automated trading reports
- Copy the environment file:
cp examples/.env.example examples/.env- Edit
.envand add your API credentials:
BUDA_API_KEY=your_api_key_here
BUDA_API_SECRET=your_api_secret_here- Run the examples:
# Public API example (no credentials needed)
ruby examples/public_api_example.rb
# AI-enhanced trading assistant
ruby examples/ai/trading_assistant_example.rb
# Authenticated API example (requires credentials)
ruby examples/authenticated_api_example.rb
# Error handling example
ruby examples/error_handling_example.rb
# Trading bot example (requires credentials)
ruby examples/trading_bot_example.rb BTC-CLPThe SDK provides convenient constants for all supported values:
# CurrenciesBudaApi::Constants::Currency::BTC# => "BTC"BudaApi::Constants::Currency::ALL# => ["BTC", "ETH", "CLP", ...]# Markets BudaApi::Constants::Market::BTC_CLP# => "BTC-CLP"BudaApi::Constants::Market::ALL# => ["BTC-CLP", "ETH-CLP", ...]# Order typesBudaApi::Constants::OrderType::BID# => "Bid" (buy)BudaApi::Constants::OrderType::ASK# => "Ask" (sell)# Price typesBudaApi::Constants::PriceType::MARKET# => "market"BudaApi::Constants::PriceType::LIMIT# => "limit"# Order statesBudaApi::Constants::OrderState::PENDING# => "pending"BudaApi::Constants::OrderState::TRADED# => "traded"BudaApi::Constants::OrderState::CANCELED# => "canceled"The SDK automatically handles rate limiting with exponential backoff retry logic. When rate limits are hit:
- The request is automatically retried after a delay
- The delay increases exponentially for subsequent retries
- After maximum retries, a
RateLimitErroris raised
You can configure retry behavior:
BudaApi.configuredo |config|
config.retries=5# Maximum retry attemptsconfig.timeout=60# Request timeoutend- Never commit API keys to version control
- Use environment variables or secure configuration management
- Rotate API keys regularly
- Use API keys with minimal required permissions
The SDK automatically handles HMAC-SHA384 signature generation:
- Generates a unique nonce for each request
- Creates signature using HTTP method, path, body, and nonce
- Includes proper headers:
X-SBTC-APIKEY,X-SBTC-NONCE,X-SBTC-SIGNATURE
The BudaApi Ruby SDK includes powerful AI enhancements through RubyLLM integration:
# Initialize AI trading assistantassistant=BudaApi.trading_assistant(client)# Get AI market analysisanalysis=assistant.analyze_market("BTC-CLP")putsanalysis[:ai_recommendation][:action]# "buy", "sell", or "hold"putsanalysis[:ai_recommendation][:confidence]# Confidence percentage# Get trading strategy recommendationsstrategy=assistant.suggest_trading_strategy(market_id: "BTC-CLP",risk_tolerance: "medium",investment_horizon: "short_term")# Create conversational trading interfacenl_trader=BudaApi.natural_language_trader(client)# Execute commands in natural languageresult=nl_trader.execute_command("Check my Bitcoin balance")result=nl_trader.execute_command("What's the current price of Ethereum?")result=nl_trader.execute_command("Buy 0.001 BTC at market price")# Initialize AI risk managerrisk_manager=BudaApi::AI::RiskManager.new(client)# Analyze portfolio risk with AI insightsportfolio_risk=risk_manager.analyze_portfolio_risk(include_ai_insights: true)# Evaluate individual trade risktrade_risk=risk_manager.evaluate_trade_risk("BTC-CLP","buy",0.001)# Create market anomaly detectordetector=BudaApi::AI::AnomalyDetector.new(client)# Detect market anomalies with AI analysisanomalies=detector.detect_market_anomalies(markets: ["BTC-CLP","ETH-CLP"],include_ai_analysis: true)# Generate AI-powered reportsreporter=BudaApi::AI::ReportGenerator.new(client)# Portfolio summary with AI insightsreport=reporter.generate_portfolio_summary(format: "markdown",include_ai: true)# Custom AI analysiscustom_report=reporter.generate_custom_report("Analyze market trends and provide investment recommendations",[:portfolio,:market])- Fork it (https://github.com/PabloB07/buda-api-ruby/fork)
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request
git clone https://github.com/PabloB07/buda-api-ruby.git
cd buda-api-ruby
bundle install
bundle exec rspec# Run all tests
bundle exec rspec
# Run with coverage
bundle exec rspec --format documentation
# Run specific test file
bundle exec rspec spec/client_spec.rb- Initial release
- Complete public and authenticated API coverage
- Comprehensive error handling
- Debug logging and monitoring
- Rich data models with helper methods
- Automatic retries and rate limit handling
- Extensive documentation and examples
The gem is available as open source under the terms of the MIT License.
This SDK is provided "as is" without warranty. Trading cryptocurrencies involves substantial risk of loss. Always test thoroughly in a staging environment before using in production. Never risk more than you can afford to lose.
The authors and contributors are not responsible for any financial losses incurred through the use of this SDK.
- Buda Python SDK - Official Python wrapper
- Buda API Documentation - Official API docs