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 = nil, json_nums = false) ⇒ API

Returns a new instance of API.

Parameters:

  • key (String) (defaults to: false)

    api key supplied by Poloniex

  • secret (String) (defaults to: false)

    hash supplied by Poloniex

  • timeout (int) (defaults to: nil)

    time in sec to wait for an api response (otherwise ‘requests.exceptions.Timeout’ is raised)

  • json_nums (datatype) (defaults to: false)

    to use when parsing json ints and floats



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

def initialize(key = false, secret = false, timeout = nil, 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.



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

def key
  @key
end

#secretObject

Returns the value of attribute secret.



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

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.


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

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 """


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
# File 'lib/poloniex.rb', line 119

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

  # 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 = Digest::SHA512
    # Sign data with secret key
    sign = Digest::HMAC.hexdigest(
        URI.encode_www_form(args).encode(UTF_8),
        secret.encode(UTF_8),
        digest
    )

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

    # Send the call
    # FIXME
    ret = _post(PRIVATE_API_BASE, args, payload['headers'])

    # Return the data
    return self.handle_returned(ret.body)
  end
  if cmd_type == 'Public'

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

    # Send the call
    ret = _get(payload['url'])

    return self.handle_returned(ret)
  end
end

#cancel_loan_offer(order_number) ⇒ Object

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



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

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".


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

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


174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/poloniex.rb', line 174

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.


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

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').


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

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.


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

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')


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

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



189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/poloniex.rb', line 189

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



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

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.


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

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.

FIXME: Why is this performing it’s own GET? Can this use self.call()?



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/poloniex.rb', line 248

def market_trade_hist(currency_pair, _start: false, _end: false)
  args =  {
      "command" => 'returnTradeHistory',
      "currencyPair" => currency_pair.to_s.upcase
  }
  if _start
    args['start'] = _start
  end
  if _end
    args['end'] = _end
  end
  url = URI.parse(PUBLIC_API_BASE)
  url.query = URI.encode_www_form(args)
  ret = _get(url.to_s, timeout: self.timeout)

  self.handle_returned(ret)
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.


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

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

#retry(func) ⇒ Object

FIXME make this a decorator



92
93
# File 'lib/poloniex.rb', line 92

def retry(func)
end

#retrying(*args, **kwargs) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/poloniex.rb', line 95

def retrying(*args, **kwargs)
  problems = []
  RETRY_DELAYS.each do |delay|
    begin
      # attempt call
      return func(*args, **kwargs)
    rescue Poloniex::RequestException.new => problem
      problems.push problem
      if delay == RETRY_DELAYS.last
        raise Poloniex::RetryException.new "Retry delays exhausted #{problem}"
      end
    end
    if problems.any?
      LOGGER.debug problems.join("\n")
    end
  end
end

#return_24h_volumeObject

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



228
229
230
# File 'lib/poloniex.rb', line 228

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

#return_active_loansObject

Returns your active loans for each currency.



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

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 account. Please note that balances in your margin account may not
be accessible if you have any open margin positions or orders.


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

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.



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

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')


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

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 account; set the "account"
parameter to "all" to include your margin and lending accounts.


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

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

#return_currenciesObject

Returns information about all currencies.



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

def return_currencies
  self.call('returnCurrencies')
end

#return_deposit_addressesObject

Returns all of your deposit addresses.



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

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)


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

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.


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

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)


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

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


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

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 Account section of the Margin
Trading page, under the Markets list


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

def 
  return self.call('returnMarginAccountSummary')
end

#return_open_loan_offersObject

Returns your open loan offers for each currency.



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

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.


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

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)


235
236
237
238
239
240
241
# File 'lib/poloniex.rb', line 235

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.


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

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



223
224
225
# File 'lib/poloniex.rb', line 223

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.


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

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.


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

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.


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

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.


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

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 account to your margin account). Required parameters are
"currency", "amount", "fromAccount", and "toAccount"


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

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



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

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