Unofficial Buda API Ruby SDK
A comprehensive Ruby SDK for Buda.com cryptocurrency exchange API with built-in debugging, error handling, and extensive examples.

Features
- β
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
Installation
Add this line to your application's Gemfile:
gem 'buda_api'
And then execute:
$ bundle install
Or install it yourself as:
$ gem install buda_api
For AI features, also install:
$ gem install ruby_llm
Quick Start
Public API (No Authentication Required)
require 'buda_api'
client = BudaApi.public_client
markets = client.markets
puts "Available markets: #{markets.map(&:id).join(', ')}"
ticker = client.ticker("BTC-CLP")
puts "BTC-CLP price: #{ticker.last_price}"
puts "24h change: #{ticker.price_variation_24h}%"
order_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}%"
Authenticated API (Trading)
require 'buda_api'
client = BudaApi.authenticated_client(
api_key: "your_api_key",
api_secret: "your_api_secret"
)
balance = client.balance("BTC")
puts "Available BTC: #{balance.available_amount}"
order = client.place_order("BTC-CLP", "Bid", "limit", 0.001, 50000000)
puts "Order placed: #{order.id}"
cancelled = client.cancel_order(order.id)
puts "Order cancelled: #{cancelled.state}"
Configuration
Configure the SDK globally:
BudaApi.configure do |config|
config.debug_mode = true
config.timeout = 30
config.retries = 3
config.logger_level = :info
config.base_url = "https://www.buda.com/api/v2/"
end
API Reference
Public API Methods
Markets
markets = client.markets
market = client.market_details("BTC-CLP")
Market Data
ticker = client.ticker("BTC-CLP")
order_book = client.order_book("BTC-CLP")
trades = client.trades("BTC-CLP", limit: 50)
Quotations
quote = client.quotation("BTC-CLP", "bid_given_size", 0.1)
quote = client.quotation_limit("BTC-CLP", "ask_given_size", 0.1, 60000000)
Reports
start_time = Time.now - 86400
avg_prices = client.average_prices_report("BTC-CLP", start_at: start_time)
candles = client.candlestick_report("BTC-CLP", start_at: start_time)
Authenticated API Methods
Account Information
balance = client.balance("BTC")
events = client.balance_events(
currencies: ["BTC", "CLP"],
event_names: ["deposit_confirm", "withdrawal_confirm"],
page: 1,
per_page: 50
)
Trading
buy_order = client.place_order("BTC-CLP", "Bid", "limit", 0.001, 50000000)
sell_order = client.place_order("BTC-CLP", "Ask", "market", 0.001)
orders = client.orders("BTC-CLP", page: 1, per_page: 100, state: "traded")
order = client.order_details(12345)
cancelled = client.cancel_order(12345)
result = client.batch_orders(
cancel_orders: [123, 456],
place_orders: [
{ type: "Bid", price_type: "limit", amount: "0.001", limit: "50000" }
]
)
Transfers
withdrawals = client.withdrawals("BTC", page: 1, per_page: 20)
deposits = client.deposits("BTC", page: 1, per_page: 20)
simulation = client.simulate_withdrawal("BTC", 0.01)
withdrawal = client.withdrawal("BTC", 0.01, "destination_address")
Error Handling
The SDK provides comprehensive error handling with specific exception classes:
begin
ticker = client.ticker("INVALID-MARKET")
rescue BudaApi::ValidationError => e
puts "Validation failed: #{e.message}"
rescue BudaApi::NotFoundError => e
puts "Resource not found: #{e.message}"
rescue BudaApi::AuthenticationError => e
puts "Authentication failed: #{e.message}"
rescue BudaApi::RateLimitError => e
puts "Rate limit exceeded: #{e.message}"
rescue BudaApi::ServerError => e
puts "Server error: #{e.message}"
rescue BudaApi::ConnectionError => e
puts "Connection failed: #{e.message}"
rescue BudaApi::ApiError => e
puts "API error: #{e.message}"
puts "Status: #{e.status_code}"
puts "Response: #{e.response_body}"
end
Exception Hierarchy
BudaApi::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
Debugging
Enable debug mode to see detailed HTTP request/response logs:
BudaApi.configure do |config|
config.debug_mode = true
config.logger_level = :debug
end
Data Models
All API responses are wrapped in rich data model objects with helper methods:
Market Model
market = client.market_details("BTC-CLP")
market.id
market.name
market.base_currency
market.quote_currency
market.minimum_order_amount
Ticker Model
ticker = client.ticker("BTC-CLP")
ticker.last_price
ticker.min_ask
ticker.max_bid
ticker.volume
ticker.price_variation_24h
ticker.price_variation_7d
OrderBook Model
order_book = client.order_book("BTC-CLP")
order_book.asks
order_book.bids
order_book.best_ask
order_book.best_bid
order_book.spread
order_book.spread_percentage
Order Model
order = client.order_details(12345)
order.id
order.state
order.type
order.amount
order.limit
order.traded_amount
order.filled_percentage
order.is_filled?
order.is_active?
order.is_cancelled?
Balance Model
balance = client.balance("BTC")
balance.currency
balance.amount
balance.available_amount
balance.frozen_amount
balance.pending_withdraw_amount
Examples
The SDK includes comprehensive examples in the examples/ directory:
Basic Examples
Advanced Examples
AI-Enhanced Examples
Running Examples
- Copy the environment file:
cp examples/.env.example examples/.env
- Edit
.env and add your API credentials:
BUDA_API_KEY=your_api_key_here
BUDA_API_SECRET=your_api_secret_here
ruby examples/public_api_example.rb
ruby examples/ai/trading_assistant_example.rb
ruby examples/authenticated_api_example.rb
ruby examples/error_handling_example.rb
ruby examples/trading_bot_example.rb BTC-CLP
Constants
The SDK provides convenient constants for all supported values:
BudaApi::Constants::Currency::BTC
BudaApi::Constants::Currency::ALL
BudaApi::Constants::Market::BTC_CLP
BudaApi::Constants::Market::ALL
BudaApi::Constants::OrderType::BID
BudaApi::Constants::OrderType::ASK
BudaApi::Constants::PriceType::MARKET
BudaApi::Constants::PriceType::LIMIT
BudaApi::Constants::OrderState::PENDING
BudaApi::Constants::OrderState::TRADED
BudaApi::Constants::OrderState::CANCELED
Rate Limiting
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
RateLimitError is raised
You can configure retry behavior:
BudaApi.configure do |config|
config.retries = 5
config.timeout = 60
end
Security
API Key Security
- 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
HMAC Authentication
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
AI Features
The BudaApi Ruby SDK includes powerful AI enhancements through RubyLLM integration:
Trading Assistant
assistant = BudaApi.trading_assistant(client)
analysis = assistant.analyze_market("BTC-CLP")
puts analysis[:ai_recommendation][:action]
puts analysis[:ai_recommendation][:confidence]
strategy = assistant.suggest_trading_strategy(
market_id: "BTC-CLP",
risk_tolerance: "medium",
investment_horizon: "short_term"
)
Natural Language Trading
nl_trader = BudaApi.natural_language_trader(client)
result = 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")
Risk Management
risk_manager = BudaApi::AI::RiskManager.new(client)
portfolio_risk = risk_manager.analyze_portfolio_risk(
include_ai_insights: true
)
trade_risk = risk_manager.evaluate_trade_risk(
"BTC-CLP", "buy", 0.001
)
Anomaly Detection
detector = BudaApi::AI::AnomalyDetector.new(client)
anomalies = detector.detect_market_anomalies(
markets: ["BTC-CLP", "ETH-CLP"],
include_ai_analysis: true
)
Report Generation
reporter = BudaApi::AI::ReportGenerator.new(client)
report = reporter.generate_portfolio_summary(
format: "markdown",
include_ai: true
)
custom_report = reporter.generate_custom_report(
"Analyze market trends and provide investment recommendations",
[:portfolio, :market]
)
Contributing
- 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
Development Setup
git clone https://github.com/PabloB07/buda-api-ruby.git
cd buda-api-ruby
bundle install
bundle exec rspec
Running Tests
bundle exec rspec
bundle exec rspec --format documentation
bundle exec rspec spec/client_spec.rb
Changelog
Version 1.0.0
- 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
License
The gem is available as open source under the terms of the MIT License.
Disclaimer
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.
Support
Related Projects