Skip to content

Instantly share code, notes, and snippets.

@jonatack jonatack/poloniex.rb forked from b1nary/poloniex.rb
Created Aug 31, 2016

Embed
What would you like to do?
require 'json'
require 'uri'
require 'net/http'
require 'net/https'
##
# Poloniex Ruby API interface
#
# Documentation text is pretty much 1:1 from the official API documentation
# https://www.poloniex.com/support/api
#
# The naming sheme is near to identical. Except:
# * `return` is removed
# * methods are in `snake_case`
# * `24h_volume` is just `volume`
#
# Out of personal preference currencyPair always
# supports both formats:
# BTC_BTS and BTC/BTS
#
# Author:: Roman Pramberger (mailto:roman@pramberger.ch)
# License:: MIT
class Poloniex
API_URL = "https://poloniex.com/"
# Initialize with your key and secret
#
# If you keep them (or one) empty, you wont be
# able to make any account related api calls.
def initialize(key = nil, secret = nil)
@apis = [ :public, :tradingApi ]
if key.nil? || secret.nil?
@apis.delete(:tradingApi)
end
@key = key
@secret = secret
end
# Returns the ticker for all markets.
def ticker
get :public, :returnTicker
end
# Returns the 24-hour volume for all markets, plus totals for primary currencies.
def volume
get :public, :return24hVolume
end
# Returns the order book for a given market.
# default is all markets ("all").
def order_book currency_pair = "all", depth = 50
get :public, :returnOrderBook, [[ :currencyPair, currency_pair.gsub('/','_') ],[ :depth, depth ]]
end
# Returns the past 200 trades for a given market,
# or all of the trades between a range specified in UNIX timestamps
# by the "start" and "end" parameters.
def trade_history currency_pair, start_timestamp = nil, end_timestamp = nil
params = [[ :currencyPair, currency_pair.gsub('/','_') ]]
params << [ :start, start_timestamp ] if start_timestamp
params << [ :end, end_timestamp ] if end_timestamp
get :public, :returnOrderBook, params
end
# Returns candlestick chart data.
# Required GET 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.
def chart_data currency_pair, start_timestamp = nil, end_timestamp = nil
params = [[ :currencyPair, currency_pair.gsub('/','_') ]]
params << [ :start, start_timestamp ] if start_timestamp
params << [ :end, end_timestamp ] if end_timestamp
get :public, :returnChartData, params
end
# Returns information about currencies.
def currencies
get :public, :returnCurrencies
end
# Returns the list of loan offers and demands for a given currency,
def loan_orders currency
get :public, :returnLoanOrders, [[ currency: currency ]]
end
# Returns all of your available balances.
def balances
post :tradingApi, :returnBalances
end
# Returns all of your balances, including available balance,
# balance on orders, and the estimated BTC value of your balance
def complete_balances
post :tradingApi, :returnCompleteBalances
end
# Returns all of your deposit addresses.
def deposit_addresses currency
post :tradingApi, :returnDepositAddresses
end
# Generates a new deposit address for the currency specified.
# Addresses for some currencies do not generate immediately. For these, the output will be:
def generate_new_address currency
post :tradingApi, :generateNewAddress, { currency: currency }
end
# Returns your deposit and withdrawal history within a range, specified
# both of which should be given as UNIX timestamps.
def deposits_withdrawals start_timestamp = 0, end_timestamp = Time.now.to_i
post :tradingApi, :returnDepositsWithdrawals, { start: start_timestamp, 'end': end_timestamp }
end
# Returns your open orders for a given market
# Set "currencyPair" to "all" to return open orders for all markets. (default)
def open_orders currency_pair = "all"
post :tradingApi, :returnOpenOrders, { currencyPair: currency_pair.gsub('/','_') }
end
# Returns your trade history for a given market
# You may specify "all" as the currencyPair to receive your trade history for all markets. (default)
def trade_history currency_pair = "all", start_timestamp = nil, end_timestamp = nil
params = { currencyPair: currency_pair.gsub('/','_') }
params[:start] = start_timestamp if start_timestamp
params[:end] = end_timestamp if end_timestamp
post :tradingApi, :returnTradeHistory, params
end
# Places a buy order in a given market.
def buy currency_pair, rate, amount
post :tradingApi, :buy, { currencyPair: currency_pair.gsub('/','_'), rate: rate, amount: amount }
end
# Places a sell order in a given market.
def sell currency_pair, rate, amount
post :tradingApi, :sell, { currencyPair: currency_pair.gsub('/','_'), rate: rate, amount: amount }
end
# Cancels an order you have placed in a given market.
def cancel_order order_number
post :tradingApi, :cancelOrder, { orderNumber: order_number }
end
# 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.
def move_order order_number, rate, amount = nil
params = { orderNumber: order_number, rate: rate }
params[:amount] = amount if amount
post :tradingApi, :moveOrder, params
end
# 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
def withdraw currency, amount, address
post :tradingApi, :withdraw, { currency: currency, amount: amount, address: address }
end
# Returns your balances sorted by account.
# Please note that balances in your margin account may not be accessible if you
# have any open margin positions or orders.
def available_account_balances account = nil
params = {}
params[:account] = account if account
post :tradingApi, :returnAvailableAccountBalances, params
end
# 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.
def tradeable_balances
post :tradingApi, :returnTradableBalances
end
# Transfers funds from one account to another (e.g. from your exchange account to your margin account).
def transfer_balance currency, amount, from_account, to_account
post :tradingApi, :transferBalance, { currency: currency, amount: amount, fromAccount: from_account, toAccount: to_account }
end
# 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.
def margin_account_summary
post :tradingApi, :returnMarginAccountSummary
end
# Places a margin buy order in a given market.
# You may optionally specify a maximum lending rate using the "lendingRate" parameter.
# If successful, the method will return the order number and any trades immediately resulting from your order.
def margin_buy currency_pair, rate, amount, lending_rate = nil
params = { currencyPair: currency_pair.gsub('/','_'), rate: rate, amount: amount }
params[:lendingRate] = lending_rate if lending_rate
post :tradingApi, :marginBuy, params
end
# laces a margin sell order in a given market.
# see margin_buy
def margin_sell currency_pair, rate, amount, lending_rate = nil
params = { currencyPair: currency_pair.gsub('/','_'), rate: rate, amount: amount }
params[:lendingRate] = lending_rate if lending_rate
post :tradingApi, :marginSell, params
end
# Returns information about your margin position in a given market,
# You may set "currencyPair" to "all" if you wish to fetch all of your margin positions at once. (default)
# 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
def get_margin_position currency_pair = "all"
post :tradingApi, :getMarginPosition, { currencyPair: currency_pair.gsub('/','_') }
end
# Closes your margin position in a given market
# This call will also return success if you do not have an open position in the specified market.
def close_margin_position currency_pair
post :tradingApi, :closeMarginPosition, { currencyPair: currency_pair.gsub('/','_') }
end
# Creates a loan offer for a given currency.
def create_loan_offer currency, amount, duration, auto_renew, lending_rate
params = { currency: currency, amount: amount, duration: duration, autoRenew: auto_renew, lendingRate: lending_rate }
params[:autoRenew] = 1 if params[:autoRenew] = true
params[:autoRenew] = 0 if params[:autoRenew] = false
post :tradingApi, :createLoanOffer, params
end
# Cancels a loan offer specified by the "orderNumber"
def cancel_loan_offer order_number
post :tradingApi, :cancelLoanOffer, { orderNumber: order_number }
end
# Returns your open loan offers for each currency.
def open_loan_offers
post :tradingApi, :returnOpenLoanOffers
end
# Returns your active loans for each currency.
def active_loans
post :tradingApi, :returnActiveLoans
end
# Returns your active loans for each currency.
def toggle_auto_renew order_number
post :tradingApi, :toggleAutoRenew, { orderNumber: order_number }
end
private
def get api, command, params = []
params = params.map { |param| param.join("=") }.join("&")
params = "&#{params}".gsub("/","_") if !params.empty?
data = Net::HTTP.get(URI("#{API_URL}#{api}?command=#{command}#{params}"))
JSON.parse(data)
end
def post api, command, params = {}
raise "Please enter your API details to access the tade api" if !@apis.include?(api)
uri = URI("#{API_URL}#{api}")
https = Net::HTTP.new(uri.host,443)
https.use_ssl = true
params["command"] = command
params["nonce"] = (Time.now.to_f*1000).to_i
params = URI.encode_www_form(params)
headers = {
'Key' => @key,
'Sign' => OpenSSL::HMAC.hexdigest(OpenSSL::Digest::SHA512.new, @secret, params)
}
response = https.post(uri.path, params, headers)
JSON.parse(response.body)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.