Class: BudaApi::AuthenticatedClient

Inherits:
PublicClient show all
Defined in:
lib/buda_api/authenticated_client.rb

Overview

Authenticated API client for endpoints that require API key authentication

Constant Summary

Constants inherited from Client

Client::DEFAULT_OPTIONS

Instance Attribute Summary collapse

Attributes inherited from Client

#base_url, #debug_mode, #retries, #timeout

Instance Method Summary collapse

Methods inherited from PublicClient

#average_prices_report, #candlestick_report, #market_details, #markets, #order_book, #quotation, #quotation_limit, #quotation_market, #ticker, #trades

Constructor Details

#initialize(api_key:, api_secret:, **options) ⇒ AuthenticatedClient

Initialize an authenticated client

Examples:

client = BudaApi::AuthenticatedClient.new(
  api_key: "your_api_key",
  api_secret: "your_api_secret",
  debug_mode: true
)

Parameters:

  • api_key (String) —

    your API key

  • api_secret (String) —

    your API secret

  • options (Hash) —

    additional options



19
20
21
22
23
24
25
26
27
28
# File 'lib/buda_api/authenticated_client.rb', line 19

def initialize(api_key:, api_secret:, **options)
  validate_credentials(api_key, api_secret)
  
  @api_key = api_key
  @api_secret = api_secret
  
  super(options)
  
  BudaApi::Logger.info("Authenticated client initialized")
end

Instance Attribute Details

#api_key ⇒ Object (readonly)

Returns the value of attribute api_key.



6
7
8
# File 'lib/buda_api/authenticated_client.rb', line 6

def api_key
  @api_key
end

#api_secret ⇒ Object (readonly)

Returns the value of attribute api_secret.



6
7
8
# File 'lib/buda_api/authenticated_client.rb', line 6

def api_secret
  @api_secret
end

Instance Method Details

#balance(currency) ⇒ Balance

Get balance for a specific currency

Examples:

balance = client.balance("BTC")
puts "Available: #{balance.available_amount}"
puts "Frozen: #{balance.frozen_amount}"

Parameters:

  • currency (String) —

    currency code

Returns:

  • (Balance) —

    current balance information



38
39
40
41
42
43
44
45
46
# File 'lib/buda_api/authenticated_client.rb', line 38

def balance(currency)
  validate_required_params({ currency: currency }, [:currency])
  validate_param_values({ currency: currency }, { currency: Currency::ALL })

  BudaApi::Logger.info("Fetching balance for #{currency}")
  
  response = get("balances/#{currency}")
  Balance.new(response["balance"])
end

#balance_events(currencies:, event_names:, page: nil, per_page: nil, relevant: nil) ⇒ Hash

Get balance events with pagination

Parameters:

  • currencies (Array<String>) —

    list of currencies to filter by

  • event_names (Array<String>) —

    list of event types to filter by

  • page (Integer, nil) (defaults to: nil) —

    page number

  • per_page (Integer, nil) (defaults to: nil) —

    items per page

  • relevant (Boolean, nil) (defaults to: nil) —

    filter for relevant events only

Returns:

  • (Hash) —

    balance events with pagination info



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/buda_api/authenticated_client.rb', line 56

def balance_events(currencies:, event_names:, page: nil, per_page: nil, relevant: nil)
  validate_required_params({ 
    currencies: currencies, 
    event_names: event_names 
  }, [:currencies, :event_names])

  # Validate currency and event parameters
  currencies.each do |currency|
    validate_param_values({ currency: currency }, { currency: Currency::ALL })
  end
  
  event_names.each do |event|
    validate_param_values({ event: event }, { event: BalanceEvent::ALL })
  end

  params = normalize_params({
    "currencies[]" => currencies,
    "event_names[]" => event_names,
    page: page,
    per: per_page,
    relevant: relevant
  })

  BudaApi::Logger.info("Fetching balance events with params: #{params}")
  
  response = get("balance_events", params)
  {
    events: response["balance_events"] || [],
    total_count: response["total_count"]
  }
end

#batch_orders(cancel_orders: [], place_orders: []) ⇒ Hash

Batch order operations (cancel and/or place multiple orders)

Examples:

# Cancel some orders and place new ones atomically
result = client.batch_orders(
  cancel_orders: [123, 456],
  place_orders: [
    { type: "Bid", price_type: "limit", amount: "0.001", limit: "50000" }
  ]
)

Parameters:

  • cancel_orders (Array<Integer>) (defaults to: []) —

    list of order IDs to cancel

  • place_orders (Array<Hash>) (defaults to: []) —

    list of order specifications to place

Returns:

  • (Hash) —

    batch operation results



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/buda_api/authenticated_client.rb', line 217

def batch_orders(cancel_orders: [], place_orders: [])
  diff_operations = []

  cancel_orders.each do |order_id|
    diff_operations << { mode: "cancel", order_id: order_id }
  end

  place_orders.each do |order_spec|
    diff_operations << { mode: "place", order: order_spec }
  end

  if diff_operations.empty?
    raise ValidationError, "At least one cancel or place operation must be specified"
  end

  BudaApi::Logger.info("Executing batch order operations: #{diff_operations.length} operations")
  
  response = post("orders", body: { diff: diff_operations })
  response
end

#cancel_order(order_id) ⇒ Order

Cancel an order

Examples:

cancelled_order = client.cancel_order(123456)
puts "Order #{cancelled_order.id} is now #{cancelled_order.state}"

Parameters:

  • order_id (Integer) —

    order ID to cancel

Returns:

  • (Order) —

    updated order with canceling state



195
196
197
198
199
200
201
202
# File 'lib/buda_api/authenticated_client.rb', line 195

def cancel_order(order_id)
  validate_required_params({ order_id: order_id }, [:order_id])

  BudaApi::Logger.info("Cancelling order #{order_id}")
  
  response = put("orders/#{order_id}", body: { state: OrderState::CANCELING })
  Order.new(response["order"])
end

#deposits(currency, page: nil, per_page: nil, state: nil) ⇒ Hash

Get deposits with pagination

Examples:

deposits = client.deposits("BTC", page: 1, per_page: 20)

Parameters:

  • currency (String) —

    currency code

  • page (Integer, nil) (defaults to: nil) —

    page number

  • per_page (Integer, nil) (defaults to: nil) —

    deposits per page

  • state (String, nil) (defaults to: nil) —

    filter by deposit state

Returns:

  • (Hash) —

    deposits with pagination metadata



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# File 'lib/buda_api/authenticated_client.rb', line 279

def deposits(currency, page: nil, per_page: nil, state: nil)
  validate_required_params({ currency: currency }, [:currency])
  validate_param_values({ currency: currency }, { currency: Currency::ALL })

  if per_page && per_page > Limits::TRANSFERS_PER_PAGE
    raise ValidationError, "per_page cannot exceed #{Limits::TRANSFERS_PER_PAGE}"
  end

  params = normalize_params({
    per: per_page,
    page: page,
    state: state
  })

  BudaApi::Logger.info("Fetching deposits for #{currency} with params: #{params}")
  
  response = get("currencies/#{currency}/deposits", params)
  {
    deposits: (response["deposits"] || []).map { |d| Deposit.new(d) },
    meta: PaginationMeta.new(response["meta"] || {})
  }
end

#order_details(order_id) ⇒ Order

Get specific order details

Examples:

order = client.order_details(123456)
puts "Order state: #{order.state}"
puts "Filled: #{order.filled_percentage}%"

Parameters:

  • order_id (Integer) —

    order ID

Returns:

  • (Order) —

    order details



179
180
181
182
183
184
185
186
# File 'lib/buda_api/authenticated_client.rb', line 179

def order_details(order_id)
  validate_required_params({ order_id: order_id }, [:order_id])

  BudaApi::Logger.info("Fetching details for order #{order_id}")
  
  response = get("orders/#{order_id}")
  Order.new(response["order"])
end

#orders(market_id, page: nil, per_page: nil, state: nil, minimum_exchanged: nil) ⇒ OrderPages

Get orders with pagination

Examples:

orders = client.orders("BTC-CLP", page: 1, per_page: 50, state: "traded")
puts "Found #{orders.count} orders on page #{orders.meta.current_page}"

Parameters:

  • market_id (String) —

    market identifier

  • page (Integer, nil) (defaults to: nil) —

    page number

  • per_page (Integer, nil) (defaults to: nil) —

    orders per page (max 300)

  • state (String, nil) (defaults to: nil) —

    filter by order state

  • minimum_exchanged (Float, nil) (defaults to: nil) —

    minimum exchanged amount filter

Returns:



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/buda_api/authenticated_client.rb', line 148

def orders(market_id, page: nil, per_page: nil, state: nil, minimum_exchanged: nil)
  validate_required_params({ market_id: market_id }, [:market_id])
  validate_param_values({ market_id: market_id }, { market_id: Market::ALL })

  if per_page && per_page > Limits::ORDERS_PER_PAGE
    raise ValidationError, "per_page cannot exceed #{Limits::ORDERS_PER_PAGE}"
  end

  validate_param_values({ state: state }, { state: OrderState::ALL }) if state

  params = normalize_params({
    per: per_page,
    page: page,
    state: state,
    minimum_exchanged: minimum_exchanged
  })

  BudaApi::Logger.info("Fetching orders for #{market_id} with params: #{params}")
  
  response = get("markets/#{market_id}/orders", params)
  OrderPages.new(response["orders"] || [], response["meta"])
end

#place_order(market_id, order_type, price_type, amount, limit = nil) ⇒ Order

Place a new order

Examples:

# Place a limit buy order
order = client.place_order("BTC-CLP", "Bid", "limit", 0.001, 50000000)

# Place a market sell order
order = client.place_order("BTC-CLP", "Ask", "market", 0.001)

Parameters:

  • market_id (String) —

    market identifier

  • order_type (String) —

    "Ask" (sell) or "Bid" (buy)

  • price_type (String) —

    "market" or "limit"

  • amount (Float) —

    amount to trade

  • limit (Float, nil) (defaults to: nil) —

    limit price (required for limit orders)

Returns:

  • (Order) —

    created order



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/buda_api/authenticated_client.rb', line 102

def place_order(market_id, order_type, price_type, amount, limit = nil)
  validate_required_params({
    market_id: market_id,
    order_type: order_type, 
    price_type: price_type,
    amount: amount
  }, [:market_id, :order_type, :price_type, :amount])

  validate_param_values({
    market_id: market_id,
    order_type: order_type,
    price_type: price_type
  }, {
    market_id: Market::ALL,
    order_type: OrderType::ALL,
    price_type: PriceType::ALL
  })

  if price_type == PriceType::LIMIT && limit.nil?
    raise ValidationError, "Limit price is required for limit orders"
  end

  order_payload = {
    type: order_type,
    price_type: price_type,
    amount: amount.to_s
  }
  order_payload[:limit] = limit.to_s if limit

  BudaApi::Logger.info("Placing #{order_type} #{price_type} order for #{amount} on #{market_id}")
  
  response = post("markets/#{market_id}/orders", body: order_payload)
  Order.new(response["order"])
end

#simulate_withdrawal(currency, amount, amount_includes_fee: true) ⇒ Withdrawal

Simulate a withdrawal (without executing)

Examples:

simulation = client.simulate_withdrawal("BTC", 0.01)
puts "Withdrawal fee: #{simulation.fee}"
puts "You will receive: #{simulation.amount.amount - simulation.fee.amount}"

Parameters:

  • currency (String) —

    currency to withdraw

  • amount (Float) —

    amount to withdraw

  • amount_includes_fee (Boolean) (defaults to: true) —

    whether amount includes the fee

Returns:

  • (Withdrawal) —

    simulated withdrawal with fee information



353
354
355
# File 'lib/buda_api/authenticated_client.rb', line 353

def simulate_withdrawal(currency, amount, amount_includes_fee: true)
  withdrawal(currency, amount, nil, amount_includes_fee: amount_includes_fee, simulate: true)
end

#withdrawal(currency, amount, target_address, amount_includes_fee: true, simulate: false) ⇒ Withdrawal

Create a withdrawal

Examples:

# Simulate a withdrawal first
simulation = client.withdrawal("BTC", 0.01, "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa", simulate: true)
puts "Fee would be: #{simulation.fee}"

# Execute the actual withdrawal
withdrawal = client.withdrawal("BTC", 0.01, "1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa")

Parameters:

  • currency (String) —

    currency to withdraw

  • amount (Float) —

    amount to withdraw

  • target_address (String) —

    destination address

  • amount_includes_fee (Boolean) (defaults to: true) —

    whether amount includes the fee

  • simulate (Boolean) (defaults to: false) —

    whether to simulate the withdrawal (not execute)

Returns:



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/buda_api/authenticated_client.rb', line 317

def withdrawal(currency, amount, target_address, amount_includes_fee: true, simulate: false)
  validate_required_params({
    currency: currency,
    amount: amount,
    target_address: target_address
  }, [:currency, :amount, :target_address])
  
  validate_param_values({ currency: currency }, { currency: Currency::ALL })

  withdrawal_payload = {
    withdrawal_data: {
      target_address: target_address
    },
    amount: amount.to_s,
    currency: currency,
    simulate: simulate,
    amount_includes_fee: amount_includes_fee
  }

  action = simulate ? "Simulating" : "Creating"
  BudaApi::Logger.info("#{action} withdrawal: #{amount} #{currency} to #{target_address}")
  
  response = post("currencies/#{currency}/withdrawals", body: withdrawal_payload)
  Withdrawal.new(response["withdrawal"])
end

#withdrawals(currency, page: nil, per_page: nil, state: nil) ⇒ Hash

Get withdrawals with pagination

Examples:

withdrawals = client.withdrawals("BTC", page: 1, per_page: 20)

Parameters:

  • currency (String) —

    currency code

  • page (Integer, nil) (defaults to: nil) —

    page number

  • per_page (Integer, nil) (defaults to: nil) —

    withdrawals per page

  • state (String, nil) (defaults to: nil) —

    filter by withdrawal state

Returns:

  • (Hash) —

    withdrawals with pagination metadata



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/buda_api/authenticated_client.rb', line 247

def withdrawals(currency, page: nil, per_page: nil, state: nil)
  validate_required_params({ currency: currency }, [:currency])
  validate_param_values({ currency: currency }, { currency: Currency::ALL })

  if per_page && per_page > Limits::TRANSFERS_PER_PAGE
    raise ValidationError, "per_page cannot exceed #{Limits::TRANSFERS_PER_PAGE}"
  end

  params = normalize_params({
    per: per_page,
    page: page,
    state: state
  })

  BudaApi::Logger.info("Fetching withdrawals for #{currency} with params: #{params}")
  
  response = get("currencies/#{currency}/withdrawals", params)
  {
    withdrawals: (response["withdrawals"] || []).map { |w| Withdrawal.new(w) },
    meta: PaginationMeta.new(response["meta"] || {})
  }
end