Giter VIP home page Giter VIP logo

poloniex's Introduction

poloniex

Poloniex python API client for humans

image

Code coverage

Description

Poloniex API client for humans

Installation

The package has been uploaded to PyPI, so you can install it with pip:

$ pip install poloniex

Usage Examples

Documentation can be inspected by calling the python's help function with a Poloniex object as parameter:

from poloniex import Poloniex
polo = Poloniex()
help(polo)

Public APIs

from poloniex import Poloniex
polo = Poloniex()
ticker = polo.returnTicker()['BTC_ETH']
print(ticker)

Private APIs

from poloniex import Poloniex
import os

api_key = os.environ.get('POLONIEX_API_KEY')
api_secret = os.environ.get('POLONIEX_SECRET')
polo = Poloniex(api_key, api_secret)

ticker = polo.returnTicker()['BTC_ETH']
print(ticker)

balances = polo.returnBalances()
print(balances)

Used in

  • crypto_trader: Trading automation on poloniex cyriptocoin exchange

Common Errors

If you are having a nonce error or an exception like this one below, you probably need to generate a new api key-secret pair.

Traceback (most recent call last):
  File "C:/Users/name/.PyCharmCE2018.2/config/scratches/scratch.py", line 10, in <module>
    balances = polo.returnBalances()
  File "C:\Users\name\AppData\Roaming\Python\Python27\site-packages\poloniex\poloniex.py", line 183, in returnBalances
    return self._private('returnBalances')
  File "C:\Users\name\AppData\Roaming\Python\Python27\site-packages\poloniex\poloniex.py", line 50, in _fn
    raise PoloniexCommandException(respdata['error'])
poloniex.exceptions.PoloniexCommandException: Nonce must be greater than 1532206573738226. You provided 1533067257748.

Process finished with exit code 1

Donations

BTC 13NpLwXgEP8d9NpDUHptY6BypFRNXHL3tr

poloniex's People

Contributors

13steinj avatar bijan588 avatar booxter avatar dnlcrl avatar enricobacis avatar sanderbrauwers avatar sarunasazna avatar timoballard avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

poloniex's Issues

"I am not a robot" Captcha failure

every time I am doing:
"ticker = polo.returnTicker()['BTC_ETH']`

i get an error:

<title>Poloniex - Bitcoin/Cryptocurrency Exchange</title> <style>a,body{color:#323A3C}body,h1{padding:0}.footer,.wrapper{text-align:center}body{margin:0;background-color:#04272A;font-family:HelveticaNeue-Light,"Helvetica Neue Light","Helvetica Neue",Helvetica,Arial,"Lucida Grande",sans-serif;font-size:18px}a:hover{color:#A57211}h1{text-transform:uppercase;font-size:36px;margin-top:0;font-weight:400}.fine,.footer{font-size:.7em}#logo{min-width:100px;max-width:230px;margin:35px 10px}#content{border-bottom:3px solid #ffab06;background-color:#e5f0e6;padding:40px 10px}.wrapper{background-color:#fff}.fine{margin:22px 0 0}.footer{color:#fff;margin:40px 0}.footer a,.footer a:hover,.footer a:visited{color:#fff;display:inline-block}@media only screen and (max-width:350px){body{font-size:.9em}h1{font-size:1.6em}.fine{font-size:.75em}}p.cf-msg{margin:4px 0}#recaptcha_widget div div{width:auto!important;height:auto!important}</style>

One More Step

Please complete the security check to proceed.

  	<form class="challenge-form" id="challenge-form" action="/cdn-cgi/l/chk_captcha" method="get">
<script type="text/javascript" src="/cdn-cgi/scripts/cf.challenge.js" data-type="normal" data-ray="3d2825977b422aeb" async data-sitekey="6LfBixYUAAAAABhdHynFUIMA_sa4s-XsJvnjtgB0"></script>
<iframe src="https://www.google.com/recaptcha/api/fallback?k=6LfBixYUAAAAABhdHynFUIMA_sa4s-XsJvnjtgB0" frameborder="0" scrolling="no" style="width: 302px; height:422px; border-style: none;"></iframe>
<textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid #c1c1c1; margin: 10px 25px; padding: 0px; resize: none;"></textarea>
  </div>
© Poloniex, Inc. 2016 - Wilmington, DE, USA | Contact Support

returnBalances triggers PoloniexError: Invalid json response returned

<title>Poloniex - Crypto Asset Exchange</title> <style>body{margin:0;padding:0;background-color:#f7f7f7;font-family:roboto,sans-serif;font-size:14px;color:#323a3c}.main{padding:250px 10px 0;min-height:300px;text-align:center}.logo{width:191px;height:30px;margin:30px 20px 20px}.content{max-width:300px;padding:30px;background-color:#fff;margin:auto}.content h1{text-transform:capitalize;font-size:20px;margin:0;padding:0 0 10px}.content p{margin:0;line-height:18px}.content p a{color:#068485;text-decoration:none;white-space:nowrap}.content p a:hover{text-decoration:underline}.footer{font-size:14px;text-align:center;color:#818181;margin:50px 0}@media only screen and (max-width:500px){.main{padding:30px 10px}}</style>

Connection Error

Sorry, we're unable to connect to the server at the moment.

Please try again in a few minutes.

Access denied

You do not have access to poloniex.com.

The site owner may have set restrictions that prevent you from accessing the site.

  • Ray ID: 7a215e368931e3d3
  • Timestamp: 2023-03-03 10:59:05 UTC
  • Your IP address: 141.226.170.246
  • Requested URL: poloniex.com/tradingApi
  • Error reference number: 1020
  • Server ID: FL_149F22
  • User-Agent: python-requests/2.27.1
</div>
© Poloniex <script>document.write((new Date).getFullYear());</script> | Contact Support
Ray ID: 7a215e368931e3d3, IP: 141.226.170.246
<script>/** * Translate error page: * * This function assumes that the page has * "title" and "desc" DOM elements. * x-lang-override cookie is set when * the language selector is used. * * NOTE: Cloudflare collapsify dislikes ES6 * */ // eslint-disable-next-line no-unused-vars function translateErrorPage(translations) { if (!translations) { return; }

const xLanguageCookie = document.cookie.match(
/(; )?x-lang-override=([^;]*);?/
);
const xLanguage = xLanguageCookie && xLanguageCookie[2];
const title = document.getElementById("title");
const desc = document.getElementById("desc");

// eslint-disable-next-line no-prototype-builtins
if (xLanguage && translations.hasOwnProperty(xLanguage) && title && desc) {
title.innerHTML = translations[xLanguage].title;
desc.innerHTML = translations[xLanguage].desc;
}
}
</script>

<script> const translations = { "ru-ru": { "title": "Ошибка соединения", "desc": "К сожалению, в данный момент мы не можем подключиться к серверу.

Повторите попытку через несколько минут." }, "tr-tr": { "title": "Bağlantı Hatası", "desc": "Üzgünüz, şu anda sunucuya bağlanamıyoruz.

Lütfen birkaç dakika sonra tekrar deneyin." }, "vi-vn": { "title": "Lỗi kết nối", "desc": "Rất tiếc, chúng tôi không thể kết nối tới máy chủ vào lúc này.

Vui lòng thử lại sau ít phút." }, "zh-cn": { "title": "连接错误", "desc": "抱歉!目前无法连接服务器。

请在几分钟后再试一次。" } }; translateErrorPage(translations); </script> <script>for(var i=0;i --------------------------------------------------------------------------- JSONDecodeError Traceback (most recent call last) File ~/.local/lib/python3.10/site-packages/poloniex/__init__.py:268, in PoloniexBase._handleReturned(self, data) 267 if not self.jsonNums: --> 268 out = _loads(data.text, parse_float=str) 269 else:

File /usr/lib/python3.10/json/init.py:359, in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
358 kw['parse_constant'] = parse_constant
--> 359 return cls(**kw).decode(s)

File /usr/lib/python3.10/json/decoder.py:337, in JSONDecoder.decode(self, s, _w)
333 """Return the Python representation of s (a str instance
334 containing a JSON document).
335
336 """
--> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
338 end = _w(s, end).end()

File /usr/lib/python3.10/json/decoder.py:355, in JSONDecoder.raw_decode(self, s, idx)
354 except StopIteration as err:
--> 355 raise JSONDecodeError("Expecting value", s, err.value) from None
356 return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

PoloniexError Traceback (most recent call last)
Cell In[9], line 1
----> 1 POLO.returnBalances()

File ~/.local/lib/python3.10/site-packages/poloniex/init.py:373, in Poloniex.returnBalances(self)
371 def returnBalances(self):
372 """ Returns all of your available balances."""
--> 373 return self.call('returnBalances')

File ~/.local/lib/python3.10/site-packages/poloniex/init.py:156, in PoloniexBase._retry..retrying(*args, **kwargs)
153 for delay in _chain(retryDelays, [None]):
154 try:
155 # attempt call
--> 156 return func(*args, **kwargs)
158 # we need to try again
159 except RequestException as problem:

File ~/.local/lib/python3.10/site-packages/poloniex/init.py:220, in PoloniexBase.call(self, command, args)
217 ret = self.session.post(**payload)
219 # return data
--> 220 return self._handleReturned(ret)
222 # public?
223 if cmdType == 'Public':
224 # encode url

File ~/.local/lib/python3.10/site-packages/poloniex/init.py:275, in PoloniexBase._handleReturned(self, data)
273 except:
274 self.logger.error(data.text)
--> 275 raise PoloniexError('Invalid json response returned')
277 # check if poloniex returned an error
278 if 'error' in out:

PoloniexError: Invalid json response returned

expected bytes or bytearray, but got str

# This program prints Hello, world!import os
import os
from poloniex import Poloniex

os.environ["POLONIEX_API_KEY"] = "[REDACTED]"
os.environ["POLONIEX_SECRET"] = "[REDACTED]"
api_key =  os.environ.get('POLONIEX_API_KEY')
api_secret = os.environ.get('POLONIEX_SECRET')

polo = Poloniex(api_key, api_secret)

ticker = polo.returnTicker()['BTC_ETH']
print(ticker)
print (os.environ)
balances = polo.returnBalances()
print(balances)


Gives the error expected bytes or bytearray, but got str. . My real key is in the redacted bit. Any ideas?

Active thread

Hello

I use you library in my scripts ( https://github.com/iero/Crypto) but it appears that I cannot end my program because a thread from your lib is still running after the end of all computation.

Thread Thread-1:
  File "/Users/greg/anaconda/lib/python3.6/threading.py", line 884, in _bootstrap
    self._bootstrap_inner()
  File "/Users/greg/anaconda/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Users/greg/anaconda/lib/python3.6/site-packages/poloniex/concurrency.py", line 16, in run
    self.finished.wait(self.interval)
  File "/Users/greg/anaconda/lib/python3.6/threading.py", line 551, in wait
    signaled = self._cond.wait(timeout)
  File "/Users/greg/anaconda/lib/python3.6/threading.py", line 299, in wait
    gotit = waiter.acquire(True, timeout)

Any idea ?

Thanks for your work

returnTradeHistoryPublic does NOT work.

On Arch Linux x86_64
Python 2.7.13
Installed via sudo pip2 poloniex

polo=poloniex.Poloniex( apikey=...,secret=...)

polo.returnTradeHistory('ETH_BCH') works
but
polo.returnTradeHistoryPublic('ETH_BCH') does NOT work!

No module named 'poloniex'

environment:python3.6

>>> from poloniex import Poloniex
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'poloniex'

Issue with Private Calls

Whenever I'm issuing a call to the private api, I'm now getting errors. This has been happening since the 24th of July. Any thoughts on the cause of this?

Here's an error using the sample code from the readme:

Traceback (most recent call last):
  File "C:/Users/name/.PyCharmCE2018.2/config/scratches/scratch.py", line 10, in <module>
    balances = polo.returnBalances()
  File "C:\Users\name\AppData\Roaming\Python\Python27\site-packages\poloniex\poloniex.py", line 183, in returnBalances
    return self._private('returnBalances')
  File "C:\Users\name\AppData\Roaming\Python\Python27\site-packages\poloniex\poloniex.py", line 50, in _fn
    raise PoloniexCommandException(respdata['error'])
poloniex.exceptions.PoloniexCommandException: Nonce must be greater than 1532206573738226. You provided 1533067257748.

Process finished with exit code 1

I'm getting these errors whether I run this in 2.7 or 3.7.

Connection Timeout

Hi,

Since last week I experienced slow or down APIs with the error Connection Timeout.
Do you see the same thing? Is this a Poloniex issue or mine?

I have a trading bot and it stops because of this issue: trying to retrieve data from Poloniex and get back Connection Timeout error: urllib.error.URLError: <urlopen error [Errno 110] Connection timed out>

Do you have an idea how I would pass by this error and let the code run further?

Thanks

polo.returnTicker() execturion shows JSONDecodeError

from poloniex import Poloniex
polo = Poloniex()
ticker = polo.returnTicker()['BTC_ETH']
print(ticker)

JSONDecodeError Traceback (most recent call last)
in ()
6 polo = Poloniex('key', 'secret')
7
----> 8 ticker = polo.returnTicker()['BTC_ETH']
9 print(ticker)
10

~/miniconda2/envs/cryptocurrency-analysis/lib/python3.6/site-packages/poloniex/poloniex.py in returnTicker(self)
73 def returnTicker(self):
74 """Returns the ticker for all markets."""
---> 75 return self._public('returnTicker')
76
77 def return24hVolume(self):

~/miniconda2/envs/cryptocurrency-analysis/lib/python3.6/site-packages/poloniex/poloniex.py in _fn(self, command, **params)
37
38 self.semaphore.acquire()
---> 39 resp = fn(self, command, **params).json(object_hook=_AutoCastDict)
40 if 'error' in resp:
41 raise PoloniexCommandException(resp['error'])

~/miniconda2/envs/cryptocurrency-analysis/lib/python3.6/site-packages/requests/models.py in json(self, **kwargs)
883 # used.
884 pass
--> 885 return complexjson.loads(self.text, **kwargs)
886
887 @Property

~/miniconda2/envs/cryptocurrency-analysis/lib/python3.6/json/init.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
365 if parse_constant is not None:
366 kw['parse_constant'] = parse_constant
--> 367 return cls(**kw).decode(s)

~/miniconda2/envs/cryptocurrency-analysis/lib/python3.6/json/decoder.py in decode(self, s, _w)
337
338 """
--> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
340 end = _w(s, end).end()
341 if end != len(s):

~/miniconda2/envs/cryptocurrency-analysis/lib/python3.6/json/decoder.py in raw_decode(self, s, idx)
355 obj, end = self.scan_once(s, idx)
356 except StopIteration as err:
--> 357 raise JSONDecodeError("Expecting value", s, err.value) from None
358 return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

In [ ]:


What is this error please explain.....
And for every time i try to use different poloniex api it shows only error...
Why this is happening.... on poloniex api...

BUY/SELL: 422 Client Error: for url: https://poloniex.com/tradingApi

I am trying to place a boy or sell order but i get the exception: requests.exceptions.HTTPError: 422 Client Error: for url: https://poloniex.com/tradingApi
Here is a code snippet:

defaultCurrencyPair = 'USDT_BTC'

def make_satoshi(num):
    return decimal.Decimal(num).quantize(decimal.Decimal('1.00000000'))

def test():
    available_usd = polo.returnBalances()['USDT']
    print(available_usd)
    print(make_satoshi(available_usd))
    print(make_satoshi(1))
    polo.buy(currencyPair=defaultCurrencyPair,rate=make_satoshi(1),amount=make_satoshi(available_usd))

Internal error. Please try again

Getting this error. Perhaps it should silently retry?:

   trade_history_dict_raw = self.polo.returnTradeHistory(currencyPair='all', start=start_date_timestamp, end=end_date_timestamp, limit=10000)

  File "/opt/cryptocurrency_tools/lib/python3.4/site-packages/poloniex/poloniex.py", line 235, in returnTradeHistory

    start=start, end=end, limit=limit)

  File "/opt/cryptocurrency_tools/lib/python3.4/site-packages/poloniex/poloniex.py", line 50, in _fn

    raise PoloniexCommandException(respdata['error'])

poloniex.exceptions.PoloniexCommandException: Internal error. Please try again.

A simple trading tool using your library.

Hello,

I made a simple trading tool to automate trading and race with the bots on poloniex. Your library is the core component. I'd like to thank you for this library.

https://github.com/timucin/cyripto_trader

Maybe you may want to add a link to your readme showing my tool as an example.
I welcome edits and additions too. That's why I like free software.

Best Regards,

Tim.

Str Encoding Error on Python 2.7.13

File "/usr/local/lib/python2.7/site-packages/poloniex/poloniex.py", line 129, in call
bytes(self._secret, 'utf-8'),
TypeError: str() takes at most 1 argument (2 given)

Semaphore never releases when returnTicker() is called by a daemon thread

I'm not quite sure what's causing this, but it occurs under certain conditions when returnTicker() is called by a Process.

Stepping through in a debugger, Semaphore typically releases after leaving this with statement:

with self._cond:

However, when returnTicker() is called by a Poloniex class instance whose RecurrentTimer is a daemon thread, Semaphore never releases, and the program stalls after 6 calls to returnTicker(). I've attached two files with results from printing the __dict__ of a Poloniex class instance at the time of calling returnTicker(), for comparison.

Please let me know if I can provide any further information; I'm a bit out of my depth here!

instance.txt
instance_with_daemon_timer.txt

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.