Class: Poloniex::API

Inherits:
Object
  • Object
show all
Defined in:
lib/poloniex.rb

Overview

The Poloniex Object

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key = false, secret = false, timeout = 3, json_nums = false) ⇒ API



78
79
80
81
82
83
84
85
86
87
# File 'lib/poloniex.rb', line 78

def initialize(key = false, secret = false, timeout = 3, json_nums = false)
  self.logger = Logger.new(STDOUT)

  # create nonce
  self._nonce = nonce_time
  self.json_nums = json_nums
  self.key = key
  self.secret = secret
  self.timeout = timeout
end

Instance Attribute Details

#keyObject

Returns the value of attribute key.



72
73
74
# File 'lib/poloniex.rb', line 72

def key
  @key
end

#secretObject

Returns the value of attribute secret.



72
73
74
# File 'lib/poloniex.rb', line 72

def secret
  @secret
end

Instance Method Details

#buy(currency_pair, rate, amount, order_type = false) ⇒ Object

Places a limit buy order in a given market. Required parameters are

"currencyPair", "rate", and "amount". You may optionally set "orderType"
to "fillOrKill", "immediateOrCancel" or "postOnly". A fill-or-kill order
will either fill in its entirety or be completely aborted. An
immediate-or-cancel order can be partially or completely filled, but
any portion of the order that cannot be filled immediately will be
canceled rather than left on the order book. A post-only order will
only be placed if no portion of it fills immediately; this guarantees
you will never pay the taker fee on any part of the order that fills.
    If successful, the method will return the order number.


407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
# File 'lib/poloniex.rb', line 407

def buy(currency_pair, rate, amount, order_type = false)
  args = {
      'currencyPair' => currency_pair.to_s.upcase,
      'rate' => rate.to_s,
      'amount' => amount.to_s
  }
  # Order type specified?
  if order_type
    # Check type
    unless POSITION_TYPES.include? order_type
      raise Poloniex::PoloniexError.new('Invalid order type.')
    end
    args[order_type] = 1
  end
  return self.call('buy', args)
end

#call(command, args = {}) ⇒ Object

“”“ Main Api Function

- encodes and sends <command> with optional [args] to Poloniex api
- raises 'poloniex.PoloniexError' if an api key or secret is missing
  (and the command is 'private'), if the <command> is not valid, or
    if an error is returned from poloniex.com
- returns decoded json api message """


95
96
97
98
99
100
101
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/poloniex.rb', line 95

def call(command, args = {})
  puts command
  # Get command type
  cmd_type = self.check_command(command)

  problems = []

  # Pass the command
  args['command'] = command
  payload = {}
  payload['timeout'] = self.timeout

  # private?
  if cmd_type == 'Private'
    payload['uri'] = PRIVATE_API_BASE

    # Set nonce
    args['nonce'] = self.nonce

    # Add args to payload
    payload['data'] = args

    digest = OpenSSL::Digest.new(SHA512)
    # Sign data with secret key
    sign = OpenSSL::HMAC.hexdigest(
                            digest,
                            secret.encode(UTF_8),
                            URI.encode_www_form(args).encode(UTF_8)
    )

    # Add headers to payload
    payload['headers'] = {
        'Content-Type' => 'application/x-www-form-urlencoded',
        'Sign' => sign,
        'Key' => key
    }

    RETRY_DELAYS.each do |delay|
      begin
        # attempt call
        # Send the call
        ret = _post(PRIVATE_API_BASE, args, payload['headers'])

        # Return the data
        return self.handle_returned(ret.body)
      rescue Poloniex::RequestException => problem
        problems.push problem
        if delay == RETRY_DELAYS.last
          raise Poloniex::RetryException.new "Retry delays exhausted #{problem}"
        else
          self.logger.debug(problem)
          self.logger.info("-- delaying for #{delay} seconds")
          sleep(delay)
        end
      end


    end
  end
  if cmd_type == 'Public'

    # Encode URL
    payload['url'] = PUBLIC_API_BASE + URI.encode_www_form(args)

    RETRY_DELAYS.each do |delay|
      begin
        # Send the call
        ret = _get(payload['url'])

        return self.handle_returned(ret)
      rescue Poloniex::RequestException => problem
        problems.push problem
        if delay == RETRY_DELAYS.last
          raise Poloniex::RetryException.new "Retry delays exhausted #{problem}"
        else
          self.logger.debug(problem)
          self.logger.info("-- delaying for #{delay} seconds")
          sleep(delay)
        end
      end
    end
  end
end

#cancel_loan_offer(order_number) ⇒ Object

Cancels a loan offer specified by the “orderNumber” parameter.



624
625
626
627
628
629
# File 'lib/poloniex.rb', line 624

def cancel_loan_offer(order_number)
  args = {
      'orderNumber' => order_number.to_s
  }
  return self.call('cancelLoanOffer', args)
end

#cancel_order(order_number) ⇒ Object

Cancels an order you have placed in a given market. Required

parameter is "order_number".


445
446
447
448
449
450
# File 'lib/poloniex.rb', line 445

def cancel_order(order_number)
  args = {
      'orderNumber' => order_number.to_s
  }
  return self.call('cancelOrder', args)
end

#check_command(command) ⇒ Object

Returns if the command is private of public, raises PoloniexError

if command is not found


181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/poloniex.rb', line 181

def check_command(command)
  if PRIVATE_COMMANDS.include? command
    # Check for keys
    unless self.key && self.secret
      raise Poloniex::PoloniexError.new "An API key and Secret Key are required!"
    end
    return 'Private'
  end
  if PUBLIC_COMMANDS.include? command
    return 'Public'
  end
  raise Poloniex::PoloniexError.new "Invalid command: #{command}"
end

#close_margin_position(currency_pair) ⇒ Object

Closes your margin position in a given market (specified by the

"currencyPair" parameter) using a market order. This call will also
return success if you do not have an open position in the specified
market.


602
603
604
605
606
607
# File 'lib/poloniex.rb', line 602

def close_margin_position(currency_pair)
  args = {
      'currencyPair' => currency_pair.to_s_upcase
  }
  return self.call('currencyPair', args)
end

#create_loan_offer(currency, amount, lending_rate, auto_renew = 0, duration = 2) ⇒ Object

Creates a loan offer for a given currency. Required parameters are

"currency", "amount", "lendingRate", "duration" (num of days, defaults
to 2), "autoRenew" (0 or 1, defaults to 0 'off').


612
613
614
615
616
617
618
619
620
621
# File 'lib/poloniex.rb', line 612

def create_loan_offer(currency, amount, lending_rate, auto_renew = 0, duration = 2)
  args = {
      'currency' => currency.to_s.upcase,
      'amount' => amount.to_s,
      'duration' => duration.to_s,
      'autoRenew' => auto_renew.to_s,
      'lendingRate' => lending_rate.to_s
  }
  return self.call('createLoanOffer', args)
end

#generate_new_address(currency) ⇒ Object

Generates a new deposit address for the currency specified by the

"currency" parameter.


332
333
334
335
336
337
# File 'lib/poloniex.rb', line 332

def generate_new_address(currency)
  args = {
      'currency' => currency.to_s.upcase
  }
  return self.call('generateNewAddress', args)
end

#get_margin_position(currency_pair = 'all') ⇒ Object

Returns information about your margin position in a given market,

specified by the "currencyPair" parameter. You may set
"currencyPair" to "all" if you wish to fetch all of your margin
positions at once. If you have no margin position in the specified
market, "type" will be set to "none". "liquidationPrice" is an
estimate, and does not necessarily represent the price at which an
actual forced liquidation will occur. If you have no liquidation price,
the value will be -1. (defaults to 'all')


591
592
593
594
595
596
# File 'lib/poloniex.rb', line 591

def get_margin_position(currency_pair = 'all')
  args = {
      'currencyPair' => currency_pair.to_s.upcase
  }
  return self.call('getMarginPosition', args)
end

#handle_returned(data) ⇒ Object

Handles the returned data from Poloniex



196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/poloniex.rb', line 196

def handle_returned(data)
  begin
    unless self.json_nums
      out = JSON.parse(data)
    else
      out = JSON.parse(data, parse_float = self.json_nums, parse_int = self.json_nums)
    end
  rescue
    self.logger.error(data)
    raise Poloniex::PoloniexError.new "Invalid json response returned!"
  end

  if out.include? 'error'

    # update nonce if we fell behind
    if out['error'].include? "Nonce must be greater"
      nonce
      # raise RequestException so we try again
      raise Poloniex::RequestException.new("PoloniexError #{out['error']}")
    end

    if out['error'].downcase.include? "please try again"
      # Raise RequestException so we try again
      raise Poloniex::RequestException.new("PoloniexError #{out['error']}")
    end

    raise Poloniex::PoloniexError.new(out['error'])
  end
  return out
end

#margin_buy(currency_pair, rate, amount, lending_rate = 2) ⇒ Object

Places a margin buy order in a given market. Required parameters are

"currencyPair", "rate", and "amount". You may optionally specify a
maximum lending rate using the "lendingRate" parameter (defaults to 2).
If successful, the method will return the order number and any trades
immediately resulting from your order.

TODO: UNTESTED



561
562
563
564
565
566
567
568
569
# File 'lib/poloniex.rb', line 561

def margin_buy(currency_pair, rate, amount, lending_rate = 2)
  args = {
      'currencyPair' => currency_pair.to_s.upcase,
      'rate' => rate.to_s,
      'amount' => amount.to_s,
      'lendingRate' => lending_rate.to_s
  }
  return self.call('marginBuy', args)
end

#margin_sell(currency_pair, rate, amount, lending_rate = 2) ⇒ Object

Places a margin sell order in a given market. Parameters and output

are the same as for the marginBuy method.


573
574
575
576
577
578
579
580
581
# File 'lib/poloniex.rb', line 573

def margin_sell(currency_pair, rate, amount, lending_rate = 2)
  args = {
      'currencyPair' => currency_pair.to_s.upcase,
      'rate' => rate.to_s,
      'amount' => amount.to_s,
      'lendingRate' => lending_rate.to_s
  }
  self.call('marginSell', args)
end

#market_trade_hist(currency_pair, _start: false, _end: false) ⇒ Object

Returns the past 200 trades for a given market, or up to 50,000 trades between a range specified in UNIX timestamps by the “start” and “end” parameters.



253
254
255
256
257
258
259
260
261
262
263
264
265
# File 'lib/poloniex.rb', line 253

def market_trade_hist(currency_pair, _start: false, _end: false)
  args = {
      "currencyPair" => currency_pair.to_s.upcase
  }
  if _start
    args['start'] = _start
  end
  if _end
    args['end'] = _end
  end

  self.call('returnTradeHistory', args)
end

#move_order(order_number, rate, amount = false, order_type = false) ⇒ Object

Cancels an order and places a new one of the same type in a single

atomic transaction, meaning either both operations will succeed or both
will fail. Required parameters are "orderNumber" and "rate"; you may
optionally specify "amount" if you wish to change the amount of the new
order. "postOnly" or "immediateOrCancel" may be specified as the
"orderType" param for exchange orders, but will have no effect on
margin orders.


459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# File 'lib/poloniex.rb', line 459

def move_order(order_number, rate, amount = false, order_type = false )
  args = {
      'orderNumber' => order_number.to_s,
      'rate' => rate.to_s
  }
  if amount
    args['amount'] = amount.to_s
  end

  # Order type specified?
  if order_type
    # 'immediateOrCancel', 'postOnly'
    unless POSITION_TYPES[1,2].include? order_type
      raise Poloniex::PoloniexError.new("Invalid order type #{order_type.to_s}")
    end
    args[order_type] = 1
  end

  return self.call('moveOrder', args)
end

#return_24h_volumeObject

Returns the 24-hour volume for all markets, plus totals for primary currencies.



235
236
237
# File 'lib/poloniex.rb', line 235

def return_24h_volume
  return self.call('return24hVolume')
end

#return_active_loansObject

Returns your active loans for each currency.



637
638
639
# File 'lib/poloniex.rb', line 637

def return_active_loans
  return self.call('returnActiveLoans')
end

#return_available_account_balances(account = false) ⇒ Object

Returns your balances sorted by account. You may optionally specify

the "account" parameter if you wish to fetch only the balances of
one . Please note that balances in your margin  may not
be accessible if you have any open margin positions or orders.


512
513
514
515
516
517
518
519
520
521
# File 'lib/poloniex.rb', line 512

def ( = false)
  if 
    args = {
        'account' => .to_s.upcase
    }
    return self.call('returnAvailableAccountBalances', args)
  else
    return self.call('returnAvailableAccountBalances')
  end
end

#return_balancesObject

Returns all of your available balances.



310
311
312
# File 'lib/poloniex.rb', line 310

def return_balances
  self.call('returnBalances')
end

#return_chart_data(currency_pair, period: false, _start: false, _end: false) ⇒ Object

Returns candlestick chart data. Parameters are “currencyPair”,

"period" (candlestick period in seconds; valid values are 300, 900,
1800, 7200, 14400, and 86400), "_start", and "_end". "Start" and "end"
are given in UNIX timestamp format and used to specify the date range
for the data returned (default date range is _start='1 day ago' to
_end='now')


273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/poloniex.rb', line 273

def return_chart_data(currency_pair, period: false, _start: false, _end: false)
  unless [300, 900, 1800, 7200, 14400, 86400].include? period
    raise Poloniex::PoloniexError.new("#{period.to_s} invalid candle period")
  end

  unless _start
    _start = Time.now.to_i - DAY
  end
  unless _end
    _end = Time.now.to_i
  end
  args = {
      'currencyPair' => currency_pair.to_s.upcase,
      'period' => period.to_s,
      'start' => _start.to_s,
      'end' => _end.to_s
  }
  self.call('returnChartData', args)
end

#return_complete_balances(account = 'all') ⇒ Object

Returns all of your balances, including available balance, balance

on orders, and the estimated BTC value of your balance. By default,
this call is limited to your exchange ; set the "account"
parameter to "all" to include your margin and lending accounts.


318
319
320
321
322
323
# File 'lib/poloniex.rb', line 318

def return_complete_balances( = 'all')
  args = {
      'account' => .to_s
  }
  return self.call('returnCompleteBalances', args)
end

#return_currenciesObject

Returns information about all currencies.



294
295
296
# File 'lib/poloniex.rb', line 294

def return_currencies
  self.call('returnCurrencies')
end

#return_deposit_addressesObject

Returns all of your deposit addresses.



326
327
328
# File 'lib/poloniex.rb', line 326

def return_deposit_addresses
  return self.call('returnDepositAddresses')
end

#return_deposits_withdrawals(_start = false, _end = false) ⇒ Object

Returns your deposit and withdrawal history within a range,

specified by the "_start" and "_end" parameters, both of which should be
given as UNIX timestamps. (defaults to 1 month)


342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/poloniex.rb', line 342

def return_deposits_withdrawals(_start = false, _end = false)
  unless _start
    _start = Time.now.to_i - MONTH
  end
  unless _end
    _end = Time.now.to_i
  end
  args = {
      'start' => _start.to_s,
      'end' => _end.to_s
  }

  return self.call('returnDepositsWithdrawals', args)
end

#return_fee_infoObject

If you are enrolled in the maker-taker fee schedule, returns your

current trading fees and trailing 30-day volume in BTC. This
information is updated once every 24 hours.


504
505
506
# File 'lib/poloniex.rb', line 504

def return_fee_info
  return self.call('returnFeeInfo')
end

#return_lending_history(_start = false, _end = false, limit = false) ⇒ Object

Returns your lending history within a time range specified by the

"start" and "end" parameters as UNIX timestamps. "limit" may also
be specified to limit the number of rows returned. (defaults to the last
months history)


645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
# File 'lib/poloniex.rb', line 645

def return_lending_history(_start = false, _end = false, limit = false)
  unless _start
    _start = Time.now.to_i - Poloniex::MONTH
  end
  unless _end
    _end = Time.now.to_i
  end
  args = {
      'start' => _start.to_s,
      'end' => _end.to_s
  }
  if limit
    args['limit'] = limit.to_s
  end
  return self.call('returnLendingHistory', args)
end

#return_loan_orders(currency) ⇒ Object

Returns the list of loan offers and demands for a given currency,

specified by the "currency" parameter


300
301
302
303
304
305
# File 'lib/poloniex.rb', line 300

def return_loan_orders(currency)
  args = {
      'currency' => currency.to_s.upcase
  }
  self.call('returnLoanOrders', args )
end

#return_margin_account_summaryObject

Returns a summary of your entire margin account. This is the same

information you will find in the Margin  section of the Margin
Trading page, under the Markets list


550
551
552
# File 'lib/poloniex.rb', line 550

def 
  return self.call('returnMarginAccountSummary')
end

#return_open_loan_offersObject

Returns your open loan offers for each currency.



632
633
634
# File 'lib/poloniex.rb', line 632

def return_open_loan_offers
  return self.call('returnOpenLoanOffers')
end

#return_open_orders(currency_pair = 'all') ⇒ Object

Returns your open orders for a given market, specified by the

"currencyPair" parameter, e.g. "BTC_XCP". Set "currencyPair" to
"all" to return open orders for all markets.


360
361
362
363
364
365
# File 'lib/poloniex.rb', line 360

def return_open_orders(currency_pair = 'all')
  args = {
      'currencyPair' => currency_pair.to_s.upcase
  }
  return self.call('returnOpenOrders', args)
end

#return_order_book(currency_pair = 'all', depth = 20) ⇒ Object

Returns the order book for a given market as well as a sequence

number for use with the Push API and an indicator specifying whether the
market is frozen. (defaults to 'all' markets, at a 'depth' of 20 orders)


242
243
244
245
246
247
248
# File 'lib/poloniex.rb', line 242

def return_order_book(currency_pair='all', depth=20)
  args = {
      'currencyPair' => currency_pair.to_s.upcase,
      'depth' => depth.to_s
  }
  return self.call('returnOrderBook', args)
end

#return_order_trades(order_number) ⇒ Object

Returns all trades involving a given order, specified by the

"orderNumber" parameter. If no trades for the order have occurred
or you specify an order that does not belong to you, you will receive
an error.


390
391
392
393
394
395
# File 'lib/poloniex.rb', line 390

def return_order_trades(order_number)
  args = {
      'orderNumber' => order_number.to_s
  }
  return self.call('returnOrderTrades', args)
end

#return_tickerObject

Returns the ticker for all markets



230
231
232
# File 'lib/poloniex.rb', line 230

def return_ticker
  return self.call('returnTicker')
end

#return_tradable_balancesObject

Returns your current tradable balances for each currency in each

market for which margin trading is enabled. Please note that these
balances may vary continually with market conditions.


526
527
528
# File 'lib/poloniex.rb', line 526

def return_tradable_balances
  return self.call('returnTradableBalances')
end

#return_trade_history(currency_pair = 'all', _start = false, _end = false) ⇒ Object

Returns your trade history for a given market, specified by the

"currencyPair" parameter. You may specify "all" as the currencyPair to
receive your trade history for all markets. You may optionally specify
a range via "start" and/or "end" POST parameters, given in UNIX
timestamp format; if you do not specify a range, it will be limited to
one day.


373
374
375
376
377
378
379
380
381
382
383
384
# File 'lib/poloniex.rb', line 373

def return_trade_history(currency_pair = 'all', _start = false, _end = false)
  args = {
      'currencyPair' => currency_pair.to_s.upcase
  }
  if _start
    args['start'] = _start
  end
  if _end
    args['end'] = _end
  end
  return self.call('returnTradeHistory', args)
end

#sell(currency_pair, rate, amount, order_type = false) ⇒ Object

Places a sell order in a given market. Parameters and output are

the same as for the buy method.


426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
# File 'lib/poloniex.rb', line 426

def sell(currency_pair, rate, amount, order_type = false)
  args = {
      'currencyPair' => currency_pair.to_s.upcase,
      'rate' => rate.to_s,
      'amount' => amount.to_s
  }
  # Order type specified?
  if order_type
    unless POSITION_TYPES.include? order_type
      raise Poloniex::PoloniexError.new('Invalid order type.')
    end
    args[order_type] = 1
  end

  return self.call('sell', args)
end

#toggle_auto_renew(order_number) ⇒ Object

Toggles the autoRenew setting on an active loan, specified by the

"orderNumber" parameter. If successful, "message" will indicate
the new autoRenew setting.


665
666
667
668
669
670
# File 'lib/poloniex.rb', line 665

def toggle_auto_renew(order_number)
  args = {
      'orderNumber' => order_number.to_s
  }
  self.call('toggleAutoRenew', args)
end

#transfer_balance(currency, amount, from_account, to_account, confirmed = false) ⇒ Object

Transfers funds from one account to another (e.g. from your

exchange  to your margin ). Required parameters are
"currency", "amount", "fromAccount", and "toAccount"


533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/poloniex.rb', line 533

def transfer_balance(currency, amount, , , confirmed = false)
  args = {
      'currency' => currency.to_s.upcase,
      'amount' => amount.to_s,
      'fromAccount' => .to_s,
      'toAccount' => .to_s
  }
  if confirmed
    args['confirmed'] = 1
  end

  return self.call('transferBalance', args)
end

#withdraw(currency, amount, address, payment_id = false) ⇒ Object

Immediately places a withdrawal for a given currency, with no email

confirmation. In order to use this method, the withdrawal privilege
must be enabled for your API key. Required parameters are
"currency", "amount", and "address". For XMR withdrawals, you may

optionally specify “paymentId”.

TODO: UNTESTED



487
488
489
490
491
492
493
494
495
496
497
498
499
# File 'lib/poloniex.rb', line 487

def withdraw(currency, amount, address, payment_id = false)
  args = {
      'currency' => currency.to_s.upcase,
      'amount' => amount.to_s,
      'address' => address.to_s
  }

  if payment_id
    args['paymentId'] = payment_id.to_s
  end

  return self.call('withdraw', args)
end