KrakenBridge
A comprehensive Ruby gem for seamless integration with Kraken cryptocurrency exchange APIs. Supports both REST and WebSocket protocols for public market data and authenticated trading operations.
Features
- ✅ Complete REST API Support: Public and private endpoints
- ✅ WebSocket Real-time Feeds: Ticker, trades, OHLC/Klines, and spread data
- ✅ Automatic Nonce Generation: Millisecond-precision timestamps
- ✅ Signature Generation: HMAC-SHA512 authentication per Kraken specs
- ✅ Rate Limiting: Built-in request rate limiting
- ✅ Automatic Retries: Configurable retry logic with exponential backoff
- ✅ Error Handling: Comprehensive error classes and logging
- ✅ 2FA Support: Optional OTP parameter for two-factor-authenticated accounts
Installation
Add this line to your application's Gemfile:
gem 'kraken_bridge'Then execute:
bundle installOr install it yourself:
gem install kraken_bridgeQuick Start
Basic Usage - Public API
require 'kraken_bridge'
client = KrakenBridge::Client.new
# Get server time
time = client.market_data.time
puts time.data
# Get ticker data
ticker = client.market_data.ticker(['XBTUSD', 'ETHUSD'])
puts ticker.data
# Get OHLC data
ohlc = client.market_data.ohlc('XBTUSD', interval: 1)
puts ohlc.dataAuthenticated Requests - Private API
require 'kraken_bridge'
client = KrakenBridge::Client.new(
api_key: ENV['KRAKEN_API_KEY'],
api_secret: ENV['KRAKEN_API_SECRET']
)
# Get account balance
balance = client.account.balance
puts balance.data
# Place a buy order
order = client.trading.add_order(
pair: 'XBTUSD',
type: 'buy',
ordertype: 'limit',
volume: 0.01,
price: 25000
)
puts order.dataWebSocket - Real-time Data
require 'kraken_bridge'
client = KrakenBridge::Client.new
# Connect to WebSocket
client.connect_websocket do |message|
puts "Raw message: #{message.inspect}"
end
# Subscribe to ticker
client.subscribe_ticker(['XBTUSD']) do |data|
puts "Ticker: #{data}"
end
# Subscribe to trades
client.subscribe_trades(['XBTUSD']) do |data|
puts "Trade: #{data}"
end
# Subscribe to OHLC/Klines
client.subscribe_ohlc(['XBTUSD'], interval: 1) do |data|
puts "OHLC: #{data}"
end
# Let it run for 30 seconds
sleep(30)
# Disconnect
client.disconnect_websocketConfiguration
Environment Variables
export KRAKEN_API_KEY="your_public_api_key"
export KRAKEN_API_SECRET="your_base64_encoded_private_key"
export KRAKEN_API_URL="https://api.kraken.com" # Optional
export KRAKEN_WEBSOCKET_URL="wss://ws.kraken.com" # OptionalProgrammatic Configuration
client = KrakenBridge::Client.new(
api_key: 'your_api_key',
api_secret: 'your_api_secret',
timeout: 60,
open_timeout: 10,
rate_limit_enabled: true,
retry_enabled: true,
max_retries: 3,
log_level: Logger::DEBUG
)API Reference
Market Data (Public)
client.market_data.time
client.market_data.system_status
client.market_data.assets(assets: ['BTC', 'ETH'])
client.market_data.asset_pairs(pairs: ['XBTUSD', 'ETHUSD'])
client.market_data.ticker(['XBTUSD', 'ETHUSD'])
client.market_data.ohlc('XBTUSD', interval: 1)
client.market_data.order_book('XBTUSD')
client.market_data.trades('XBTUSD')
client.market_data.spread('XBTUSD')Account (Private)
client.account.balance
client.account.extended_balance
client.account.trade_balance
client.account.open_orders
client.account.closed_orders
client.account.query_orders(txid: 'order_id')
client.account.trades_history
client.account.query_trades(txid: 'trade_id')
client.account.open_positions
client.account.ledger
client.account.query_ledger(id: 'entry_id')
client.account.trade_volume
client.account.request_export_report(description: 'Report', report: 'trades')
client.account.get_export_report(report: 'trades')Trading (Private)
client.trading.add_order(pair: 'XBTUSD', type: 'buy', ordertype: 'limit', volume: 0.01, price: 25000)
client.trading.edit_order(txid: 'order_id', volume: 0.02, price: 26000)
client.trading.cancel_order('order_id')
client.trading.cancel_all_orders
client.trading.cancel_all_orders_after(timeout: 300)WebSocket (Public Feeds)
client.connect_websocket { |msg| puts msg }
client.subscribe_ticker(['XBTUSD']) { |data| puts data }
client.subscribe_trades(['XBTUSD']) { |data| puts data }
client.subscribe_ohlc(['XBTUSD'], interval: 1) { |data| puts data }
client.subscribe_spread(['XBTUSD']) { |data| puts data }
client.disconnect_websocketError Handling
begin
balance = client.account.balance
rescue KrakenBridge::Errors::AuthenticationError => e
puts "Authentication failed: #{e.message}"
rescue KrakenBridge::Errors::RateLimitError => e
puts "Rate limited: #{e.message}"
rescue KrakenBridge::Errors::ConnectionError => e
puts "Connection failed: #{e.message}"
end2FA (Two-Factor Authentication)
otp = '123456'
client.account.balance(otp: otp)
client.trading.add_order(pair: 'XBTUSD', type: 'buy', ordertype: 'limit', volume: 0.01, price: 25000, otp: otp)Testing
bundle exec rspecSecurity Recommendations
⚠️ Important:
- Never commit API keys to version control
- Use environment variables or secrets manager
- Enable IP whitelisting on API keys
- Use 2FA on your Kraken account
- Rotate API keys regularly
- Use read-only keys where possible
Troubleshooting
"EAPI:Invalid key"
- Verify API key and secret are correct
- Ensure API secret is base64 encoded
- Check system clock is synchronized
"EAPI:Invalid nonce"
- Sync system clock with NTP
- Use separate API keys for different processes
Rate Limit Exceeded
- Use WebSocket for real-time data
- Increase time between requests
- Enable automatic retries (enabled by default)
Contributing
Bug reports and pull requests are welcome on GitHub.
License
The gem is available as open source under the terms of the MIT License.