Coder Social home page Coder Social logo

s4w3d0ff / python-poloniex Goto Github PK

View Code? Open in Web Editor NEW
569.0 69.0 167.0 358 KB

Poloniex API wrapper for Python 2.7 & 3

Home Page: https://poloniex.com/support/api

License: GNU General Public License v2.0

Python 100.00%
python api-wrapper poloniex api bitcoin altcoin trading-api wrapper cryptocurrency cryptocoins

python-poloniex's Introduction

pythonlicence releaserelease build
mastermaster build devdev build

Inspired by this wrapper written by 'oipminer'

I (s4w3d0ff) am not affiliated with, nor paid by Poloniex. If you wish to contribute to the repository please read CONTRIBUTING.md. All and any help is appreciated.

Features:

  • Python 2.7 and 3+
  • Pypi
  • Travis
  • Websocket api support
  • Minimal amount of dependencies
  • Internal checks to reduce external api errors
  • Rate limiter to keep from going over call limits
  • Retries failed api calls during connection issues

Install:

pip install --upgrade poloniexapi

Usage:

See the wiki or help(poloniex) for more.

All api calls are done through an instance of poloniex.Poloniex. You can use the instance as follows:

# import this package
from poloniex import Poloniex

# make an instance of poloniex.Poloniex
polo = Poloniex()

# show the ticker
print(polo('returnTicker'))

Using the instances __call__ method (shown above) you can pass the command string as the first argument to make an api call. The poloniex.Poloniex class also has 'helper' methods for each command that will help 'sanitize' the commands arguments. For example, Poloniex.returnChartData('USDT_BTC', period=777) will raise PoloniexError("777 invalid candle period").

# using a 'helper' method
print(polo.returnChartData(currencyPair='BTC_LTC', period=900))
# bypassing 'helper'
print(polo(command='returnChartData', args={'currencyPair': 'BTC_LTC',
                                            'period': 900}))

Almost every api command can be called this way. This wrapper also checks that the command you pass to the command arg is a valid command to send to poloniex, this helps reduce api errors due to typos.

Private Commands:

To use the private api commands you first need an api key and secret (supplied by poloniex). When creating the instance of poloniex.Poloniex you can pass your api key and secret to the object like so:

import poloniex
polo = poloniex.Poloniex(key='your-Api-Key-Here-xxxx', secret='yourSecretKeyHere123456789')

# or this works
polo.key = 'your-Api-Key-Here-xxxx'
polo.secret = 'yourSecretKeyHere123456789'

# get your balances
balance = polo.returnBalances()
print("I have %s ETH!" % balance['ETH'])

# or use '__call__'
balance = polo('returnBalances')
print("I have %s BTC!" % balance['BTC'])

Trade History:

Poloniex has two api commands with the same name returnTradeHistory. To work around this without splitting up the commands or having to specify 'public' or 'private' we use the helper method Poloniex.marketTradeHist for public trade history and Poloniex.returnTradeHistory for private trades. If you try to bypass the helper method using Poloniex.__call__, it will call the private command.

Public trade history:

print(polo.marketTradeHist('BTC_ETH'))

Private trade history:

print(polo.returnTradeHistory('BTC_ETH'))

You can also not use the 'helper' methods at all and use poloniex.PoloniexBase which only has returnMarketHist and __call__ to make rest api calls.

Websocket Usage:

To connect to the websocket api use the PoloniexSocketed class like so:

import poloniex
import logging
from time import sleep

# helps show what is going on
logging.basicConfig()
poloniex.logger.setLevel(logging.DEBUG)

def on_volume(data):
    print(data)
# make instance
sock = poloniex.PoloniexSocketed()
# start the websocket thread and subscribe to '24hvolume' setting the callback to 'on_volume'
sock.startws(subscribe={'24hvolume': on_volume})
# give the socket some time to init
sleep(5)
# use the channel name str or id int to subscribe/unsubscribe
sock.subscribe(chan='ticker', callback=print)
sleep(1)
# unsub from ticker using id (str name can be use as well)
sock.unsubscribe(1002)
sleep(4)
# stop websocket
sock.stopws()
INFO:poloniex:Websocket thread started
DEBUG:poloniex:Subscribed to 24hvolume
[1010]
DEBUG:poloniex:Subscribed to ticker
[241, '86.59997298', '86.68262835', '85.69590501', '0.01882321', '22205.56419338', '258.30264061', 0, '87.31843098', '82.81638725']
...
...
[254, '5.89427014', '6.14542299', '5.92000026', '-0.03420118', '9978.11197201', '1649.83975863', 0, '6.19642428', '5.74631502']
DEBUG:poloniex:Unsubscribed to ticker
[1010]
[1010]
[1010]
['2019-06-07 04:16', 2331, {'BTC': '2182.115', 'ETH': '490.635', 'XMR': '368.983', 'USDT': '7751402.061', 'USDC': '5273463.730'}]
DEBUG:poloniex:Websocket Closed
INFO:poloniex:Websocket thread stopped/joined

You can also subscribe and start the websocket thread when creating an instance of PoloniexSocketed by using the subscribe and start args:

sock = poloniex.PoloniexSocketed(subscribe={'24hvolume': print}, start=True)

More examples of how to use websocket push API can be found here.

python-poloniex's People

Contributors

andrewshvv avatar cyzanfar avatar enricobacis avatar exvion avatar ferryschuller avatar kdb424 avatar klardotsh avatar l8nit3tr0ubl3 avatar metaperl avatar pisiiki avatar running-codebase avatar s4w3d0ff avatar skyl avatar sweco 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  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  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

python-poloniex's Issues

Simplify coach.py

Coach.py could be much simpler:

Instead of manually controlling the list of times in your code, you could use a collections.deque and set the length to 6.

The resulting coach.py could be much simpler. I cannot supply a pull request because my fork has deviated far too much. But for comparison check out my reimplementation of coach.py.

And also, coach should be enabled by default. Otherwise code using this module will get throttle errors. That's what led to me investigating this.

Push API

I have been attempting to get the Push API example to work. To be fair, I'm using Python 2.7 and 3.5. (Both are from Anaconda which comes with a bunch scientific tools already installed as well.) I am trying on Windows 7 & 10 as well as Ubuntu 14.04.

All of the Windows + Python 3.5 attempts fail with the error:'ImportError: cannot import name '_win32stdio''.

The Ubuntu 14.04 with Python 2.7 returns another ImportError from twisted for optionsForClientTLS for the TrollBox example and ReactorNotRestartable for the ticker example. Additionally, on my 2.7 machine I need to remove the import poloniex line and TICKER initialization (replaced by {}). Poloniex installed without error but Spyder refused to import it. Given that I thought I could still use the code with the modifications listed I didn't get hung up on getting the poloniex package to import.

I can't remember off the top of my head what the Ubuntu 14.04 with Python 3.5 or the Windows 10 with Python 2.7 failed on but they failed or I'd be using one of them.

I'd really like to get the Push API for the ticker working in Python 3.5 and dumping the data to memcache. But I can't get the example to work on any of my machines. Any suggestions?

v0.2 breaks my script/bot

When updating from v0.1.x to #27 (v0.2.x) the names of the poloniex.Poloniex methods have changed! This will most likely break your script/bot and you would need to manually change the names in your script to use the updated poloniex module.

I have added a workaround to fix "most" broken scripts by adding a simple extend=True in the Poloniex object.

Example:

import poloniex
polo = poloniex.Poloniex()

## Works v0.1.x (not v0.2.x by default):
polo.marketTicker()
polo.api('returnTicker')

## Works v0.2.x:
polo.returnTicker()
polo('returnTicker')

# define 'extend=True' to 'fix'
polo = poloniex.Poloniex(extend=True)
polo.marketTicker()
polo.api('returnTicker')

NOTE: I recommend that you still change the names in your script regardless if you use "extend" or not. Future updates may have this workaround removed (unless there is an interest for them)

Connection timeout

File "/usr/local/lib/python3.5/dist-packages/poloniex/__init__.py", line 279, in returnBalances
    return self.__call__('returnBalances')
  File "/usr/local/lib/python3.5/dist-packages/poloniex/retry.py", line 15, in wrapped
    return function(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/poloniex/__init__.py", line 175, in __call__
    return self.parseJson(ret.text)
  File "/usr/local/lib/python3.5/dist-packages/poloniex/__init__.py", line 197, in parseJson
    raise PoloniexError(jsonout['error'])
poloniex.PoloniexError: Connection timed out. Please try again.

Every other call I get an error like the above. I have tried making the timeout longer by doing Poloniex(key, secret, timeout=80) But this did not help. Any suggestions?

Coach.py must be str, not bytes

logging.info(
"Now: %d Oldest Call: %d Diff: %f sec" %
(now, self._timeBook[-1], now - self._timeBook[-1])
)

Is the error origin. Running python 3.6.0.

public TradeHistory method

import poloniex

polo = poloniex.Poloniex()
polo.timeout = 2

data = polo.marketTradeHist('USDT_ETH', 1410158341, 1410499372)
print(data)

throws:
poloniex.py, line 214, in <lambda> #L214
NameError: name 'urlopen' is not defined

AttributeError: 'Coach' object has no attribute 'semaphore'

Hello,

Fresh virtualenv install pip install git+https://github.com/s4w3d0ff/python-poloniex.git
Python Version: Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)] on win32
Simple test:

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

Error stack:

Traceback (most recent call last):
  File "D:/python_tutorials/poloniex_project/poloniex_api/polo_test.py", line 7, in <module>
    pprint(polo.returnTicker()['BTC_ETH'])
  File "D:\python_tutorials\poloniex_project\venv\lib\site-packages\poloniex\__init__.py", line 201, in returnTicker
    return self.__call__('returnTicker')
  File "D:\python_tutorials\poloniex_project\venv\lib\site-packages\poloniex\__init__.py", line 139, in __call__
    self.coach.wait()
  File "D:\python_tutorials\poloniex_project\venv\lib\site-packages\poloniex\coach.py", line 44, in wait
    self.semaphore.acquire()  # blocking call
AttributeError: 'Coach' object has no attribute 'semaphore'

Caused by commit 7d60109
commented line 39:

        #self.semaphore = Semaphore(callLimit)

Poloniex always return 'captcha require', how to solve it?

I just use the script, but it always issues error. When I change return _loads(ret.text, parse_float=unicode) to ret.text in function __call__, it prints out full HTML code of captcha page of poloniex.com. So, I cannot do anything.

How can we deal with that?

Please help.


This is the log for first time call (without any changes):

>>> polo = Poloniex()
>>> print(polo.returnTicker())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "poloniex/__init__.py", line 232, in returnTicker
    return self.__call__('returnTicker')
  File "poloniex/__init__.py", line 221, in __call__
    return _loads(ret.text, parse_float=unicode)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 352, in loads
    return cls(encoding=encoding, **kw).decode(s)
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 382, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded```

invalid JSON response from Poloniex is not parsed correctly

Hello,
sometimes the requests could not be completed correctly (may be due to DDOS or rate limit violation?), and apparently Poloniex responds with something that could not be parsed by your wrapper:

balances = self.polo.returnAvailableAccountBalances()

File "/home/strky/anaconda3/envs/py36/lib/python3.6/site-packages/poloniex/init.py", line 449, in returnAvailableAccountBalances
return self.call('returnAvailableAccountBalances')
File "/home/strky/anaconda3/envs/py36/lib/python3.6/site-packages/poloniex/retry.py", line 15, in wrapped
return function(*args, **kwargs)
File "/home/strky/anaconda3/envs/py36/lib/python3.6/site-packages/poloniex/init.py", line 175, in call
jsonout = _loads(ret.text, parse_float=str)
File "/home/strky/anaconda3/envs/py36/lib/python3.6/json/init.py", line 367, in loads
return cls(**kw).decode(s)
File "/home/strky/anaconda3/envs/py36/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/home/strky/anaconda3/envs/py36/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Is it possible to wrap the json decoding into try/except and return the error with original text to aid troubleshooting?
Other solutions might be possible...

Buy method not actually buying

polo.buy('BTC_VRC', float(ticker['BTC_VRC']['lowestAsk']), (.1 * btcBal))

running that will not throw any errors, but wont actually buy anything. everything else seems to be working, and i have tried other coins in the arguments.

Any chance of help integrating with pyqt app?

This isn't really an issue with the code as it works great (thanks btw) but I'm trying to build a GUI app and I can't get any of the push stuff working. In fact it seems the onJoin callback never gets executed. Would anybody happen to have any ideas how to get it to work? I followed this guy's example to integrate the pyqt event loop with quamash and switched to autobahn.asyncio:

https://github.com/icefo/PyQt5-Wamp/blob/master/PyQt5_GUI.py

That was pretty straightforward and it works fine except for the callback problem. My QMainWindow also inherits from ApplicationSession so it should fire, right? It's weird because onConnect and onDisconnect both work as expected. If I call it manually in init with self.onJoin() it just doesn't do anything. I put a print statement in onJoin() and... nothing.

You can see my code in the issues section of his page (it's the only one).

nonce must be greater...

Sometimes the message appears requiring a retry:

  File "/home/strky/anaconda3/envs/py36/lib/python3.6/site-packages/poloniex/__init__.py", line 449, in returnAvailableAccountBalances
    return self.__call__('returnAvailableAccountBalances')
  File "/home/strky/anaconda3/envs/py36/lib/python3.6/site-packages/poloniex/retry.py", line 15, in wrapped
    return function(*args, **kwargs)
  File "/home/strky/anaconda3/envs/py36/lib/python3.6/site-packages/poloniex/__init__.py", line 182, in __call__
    raise PoloniexError(jsonout['error'])
poloniex.PoloniexError: Nonce must be greater than 1496733348197745. You provided 1496733348197661.

is is possible to adjust the nonce increase somehow? I believe it might happen because Polo is fighting DDOSes and might slow down some requests on the Cloudflare side

Ticker data through WAMP

I'm trying to get a continuous flow of ticker data for a currency pair (i.e BTC_USDT)

if __name__ == '__main__':
    from time import sleep
    ticker = Ticker()
    ticker.start()
    for i in range(100):
        sleep(3)
        print "BTC_USD: last= {} baseVolume= {}".format(ticker()['last'], ticker()["baseVolume"])

    ticker.stop()
    print("Done")

However when I print the output it shows me the same price everytime. Am I missing something ?

BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429
BTC_USD: last= 1949.64570488 baseVolume= 19152881.89583429

returnOrderTrades not working

When I try to implement the returnOrderTrades function I receive the response "Order not found, or you are not the person who placed it.' However, with the exact same orderNumber I tried with returnOrderTrades, I can cancel the order with no error.

Want to understand coach() a little deeper

@s4w3d0ff
Hi,
Firstly thanks for the api, its cool.
I have got this query to understand the Class- Coach()

Now that we all know the rate is 6 calls a second!
Please help me understand this-
Suppose , I call returnChartdata say every 300, 900 or any mentioned time interval for all the currencies in poloniex at once, how will it behave if Coach is True?
I m little new to programming and have encountered such situation first time alone with its solution but cant figure out how things will behave.
I went through Coach codes and I think the calls will delay every second once it hits 6 calls every second. Am i understanding it correctly?

Do I need to use some command in Coach class to delay calls?
Suppose there are 100 coins listed on Polo and I call returnChartdata command for all coins in any period, which means 100 calls.
So how will things happen?

Can you explain?

extend=True used in examples but doesn't exist in __init__

Traceback (most recent call last):
File "loanbot.py", line 156, in
bot = Loaner(args.config)
File "loanbot.py", line 21, in init
self.polo = poloniex.Poloniex(config['key'], config['secret'], extend=True)
TypeError: init() got an unexpected keyword argument 'extend'

Pypi / releases / tests

Hi s4w3d0ff,

This repository is pretty popular :)

Have you considered doing releases on pypi? Or releases in github? Is the code stable enough for general use? (I'm asking because I need a package to communicate with poloniex, and I'd like to depend on this to avoid reinventing the wheel or copy-pasting code).

Also, are unit tests planned / patches accepted?

Thanks!

Runned script not exit

I have simple script.py:

from poloniex import Poloniex
polo = Poloniex()
polo.returnChartData('BTC_ETH', 1800, 1405699200, 9999999999)

running this via command: python script.py execution can't be finished.
So I must stop it manually Ctr+C.

Hmac Library issue? Expected Bytes or ByteArray, but got string when creating "sign" function

bot.myAvailBalances()
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    bot.myAvailBalances()
  File "C:\Python35\lib\poloniex.py", line 46, in <lambda>
    self.myAvailBalances = lambda x=0: self.api('returnAvailableAccountBalances')
  File "C:\Python35\lib\poloniex.py", line 85, in api
    sign = hmac.new(self.Secret, post_data, hashlib.sha512).hexdigest()
  File "C:\Python35\lib\hmac.py", line 144, in new
    return HMAC(key, msg, digestmod)
  File "C:\Python35\lib\hmac.py", line 42, in __init__
    raise TypeError("key: expected bytes or bytearray, but got %r" % type(key).__name__)
TypeError: key: expected bytes or bytearray, but got 'str'

sos GET OPEN ORDERS

Hello i am a young developer this is my first time with the api of poloniex, I am developing a python bot for Poloniex , but is all the day that i try to make a request to get the open order but it fails!!
My code is very similar to your but I dont know, why it dosent works the request status is 200 but this is the reply:
{'error': 'Invalid command.'}

this is my code:
`# Returns open orders for a given market

def getOpenOrders(self,url,comand, market):

    nonce = int(time.time())
    urlrequest = url  + '?apikey=' + self.apiKey +'&command='+comand + '&nonce=' +str(nonce) + '&market=' + str(market)
    print(urlrequest)
    param =  'command='+comand + '&nonce=' +str(nonce) + "&market=" +str(market)
    signature =  hmac.new(self.Secret.encode(),param.encode(), hashlib.sha512).hexdigest()
    headers = {
            'Sign':signature,
            'Key': self.apiKey
        }

    self.r = requests.post(urlrequest,headers= headers,)
    print(self.r)
    print(self.r.json())

could you help me to fix??

i hope to receive your answear and sorry again`

chat messages printing twice

I changed the code slightly. It works but now every chat message gets printed twice, although the logging format is lost on the 2nd message. Any ideas?

    from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
    import logging, logging.handlers
    import sys
    from html import unescape
    
    
    logging.basicConfig(format='[%(asctime)s]%(message)s', datefmt="%H:%M:%S", level=logging.DEBUG)
    #trolllogger = logging.getLogger()
    #trolllogger.addHandler(logging.handlers.RotatingFileHandler('TrollBox.log', maxBytes=10 ** 9,
    #                                                            backupCount=5))  # makes 1Gb log files, 5 files max
    
    W = '\033[0m'  # white (normal)
    R = lambda text: '\033[31m' + text + W  # red
    G = lambda text: '\033[32m' + text + W  # green
    O = lambda text: '\033[33m' + text + W  # orange
    B = lambda text: '\033[34m' + text + W  # blue
    P = lambda text: '\033[35m' + text + W  # purp
    C = lambda text: '\033[36m' + text + W  # cyan
    GR = lambda text: '\033[37m' + text + W  # gray
    
    
    class Subscribe2Trollbox(ApplicationSession):
        async def onJoin(self, details):
            self.alter = True
            self.name = 'PulloutKing'
            self.mods = {
                "Xoblort": 1,
                "Chickenliver": 1,
                "MobyDick": 1,
                "cybiko123": 1,
                "SweetJohnDee": 1,
                "smallbit": 1,
                "Wizwa": 1,
                "OldManKidd": 1,
                "Quantum": 1,
                "busoni@poloniex": 1,
                "Thoth": 1,
                "wausboot": 1,
                "Mirai": 1,
                "qubix": 1,
                "Oldgamejunk": 1,
                "Chewpacabra": 1,
                "j33hopper": 1,
                "VenomGhost": 1,
                "ultim8um": 1,
                "TheDjentleman": 1,
                "Bigolas": 1,
                "Watchtower": 1
            }
            self.friends = []  # :.(
    
            def onTroll(*args):
                try:
                    #logging.debug(args[0].upper(), str(args[1]))
                    name = args[2]
                    message = unescape(args[3])
                    # Name coloring
                    if name == self.name:  # own name is green
                        name = G(name)
                    elif name in self.friends:  # friends are purple
                        name = P(name)
                    elif name in self.mods:  # mods are orange
                        name = O(name)
                    else:
                        name = C(name)  # others are cyan
                    # Message Coloring
                    if self.name in message:  # mentions are green
                        message = G(message)
                    elif 'POLO TIP' in message:  # (supposed) polo tips are blue
                        message = B(message)
                    # other messages alternate from 'normal' to gray
                    elif self.alter:
                        message = GR(message)
                        self.alter = False
                    else:
                        message = message
                        self.alter = True
                    logging.info('%s(%s): %s' % (name, B(str(args[4])), message))
                except IndexError:  # Sometimes its a banhammer!
                    # (u'trollboxMessage', 6943543, u'Banhammer', u'OldManKidd banned for 0 minutes by OldManKidd.')
                    logging.info('%s %s' % (R(name), R(message)))
    
            await self.subscribe(onTroll, 'trollbox')
    
    
    if __name__ == "__main__":
        subscriber = ApplicationRunner(u"wss://api.poloniex.com:443", u"realm1")
        subscriber.run(Subscribe2Trollbox)

Push Stops Receiving Updates after a Period of Time

Sorry to bug you again. However, I ran your tickercatcher example on a Virtual Machine and it worked for a couple of hours. Then it would stop working. Then I created a Droplet on DigitalOcean for doing this. Same thing - works for a few hours and then stops.

By stopping I don't mean the script exits or fails. This I could handle with Supervisor. But what happens is that it just stops receiving updates. The script continues to run but never outputs any new updates.

Admittedly I can't remember if I tested this on the Droplet without pylibmc but I do remember this being an issue immediately on the VM. That code was just your example without my modification. The first time I let tickercatcher example script, the version here not my version, run overnight I had this issue where it stopped receiving updates after a period of time. I have not timed the period before updates cease but I would say it is less than several hours.

I'm hoping this is something you are aware of, maybe a limitation of Poloniex's Push. If not I'll start quantifying it and add that data here.

Here's the modified code I'm using to test the connection:

from twisted.internet.defer import inlineCallbacks
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner
import json

import poloniex
import pylibmc
import time

client = pylibmc.Client(["xxx.xxx.xxx.xxx:ppppp"])

# Catches the push messages from polo ticker and saves them to a json file
class Subscribe2Ticker(ApplicationSession):
        @inlineCallbacks
        def onJoin(self, details):
                TICKER = poloniex.Poloniex().marketTicker() # fill the local ti$
                saveJSON(TICKER,'ticker') # save ticker as json file (for use i$
                def onTick(*args): # everytime we get a push message from the p$
                        # update local ticker with received data
                        start_time = time.time()
                        TICKER[args[0]] = {     'last':float(args[1]),
                                                'lowestAsk':float(args[2]),
                                                'highestBid':float(args[3]),
                                                'percentChange':float(args[4]),
                                                'baseVolume':float(args[5]),
                                                'quoteVolume':float(args[6]),
                                                'isFrozen':int(args[7]),
                                                '24hrHigh':float(args[8]),
                                                '24hrLow':args[9]}

                        eTime = time.time() - start_time
                        TICKER[args[0]]['eTime'] = eTime

                        # save/overwrite local ticker json file
                        saveJSON(TICKER,'ticker')

                        #print "Ticker: " + client.get('ticker')
                yield self.subscribe(onTick, 'ticker')


def saveJSON(data, fileName):
        client.set('ticker', json.dumps(data), 10)

        with open(fileName+'.json', 'w+') as f:
                json.dump(data, f, sort_keys=True, indent=4)

if __name__ == "__main__":
        subscriber = ApplicationRunner(u"wss://api.poloniex.com:443", u"realm1")
        subscriber.run(Subscribe2Ticker)

Is the coach reliable?

Hi, I'm writing a bot for polo with your fabulous wrapper.
Now the question if the coach is reliable?
If I send more than 6 requests per second to polo they will block my IP.
I dare not more than 6 requests per second to send to poloniex...

Dependencies

It woupd be usefull to add a list of the required dependencies. Or just add requirements.txt.

returnOrderBook

Can we make it return more than 20 orders? (default is 20 orders)

Push API orderbook not receiving all data

When I request orderbook data for a symbol, I appear to be missing data. Does anyone
else have this problem? Specifically, I get orderbookremove instructions on data that
doesn't exist.

sell orders not going through

I'm trying to test the sell function. when i run it it runs no problem, but no sell order opens on poloniex.
Im calling it by

polo.sell('BTC_VTC',0.00003879,vtcBal)
where vtcBal is set by
balance = polo.returnBalances()
vtcBal = balance['VTC']

am i formatting this wrong or is there something missing from my arguments?

'Poloniex' object has no attribute 'sell'

Hi there! First of all, thank you very much for your work.
I'm pretty new in coding, had some experience in bots in python but this one is something new.
I have a problem with "sell" method. When I try to use for polo. sell I get message:
'Poloniex' object has no attribute 'sell'
Also in init.py file, there is "def buy" but there is no "def sell" ?
Thank you for any help.

How do you place a market sell or buy order?

I see the following code

def buy(self, currencyPair, rate, amount, orderType=False):
        """ 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. """
        args = {
            'currencyPair': str(currencyPair).upper(),
            'rate': str(rate),
            'amount': str(amount),
        }
        # order type specified?
        if orderType:
            possTypes = ['fillOrKill', 'immediateOrCancel', 'postOnly']
            # check type
            if not orderType in possTypes:
                raise PoloniexError('Invalid orderType')
            args[orderType] = 1

        return self.__call__('buy', args)

What do you pass it for market order which obviously would have no rate specified?

mongoTicker.py doesn't return any values

When I run mongodb.py, I receive

" print("BTC_ETH: percentChange= %s" % ticker()['last'])
TypeError: 'NoneType' object has no attribute 'getitem'"

Any ideas here?

REQUEST: Advanced buy orders.

You may optionally set "fillOrKill", "immediateOrCancel", "postOnly" to 1. 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.

That comes from their docs on the API, but is not implemented here. It would be great if that could be added. If I have time I'll work on it and submit a pull request, but that will be a while. Thanks for considering.

Trollbox does not return continuous messages

Hi

I don't know why, but your example code for the Trollbox doesn't work. The programm runs, but returns nothing.

I use a very similar code which works, but unfortunately Poloniex doesn't return everytime continuous trollbox messages. Is there a reason for this behaviour? Sometimes I get continuous message numbers, but sometimes there are like 10 or 20 or 30 messages missing before the next message with the next number appears.

This is my code, its almost the same as yours:

from autobahn.asyncio.wamp import ApplicationSession
from autobahn.asyncio.wamp import ApplicationRunner
from asyncio import coroutine

class PoloniexComponent(ApplicationSession):
    def onConnect(self):
        self.join(self.config.realm)

    @coroutine
    def onJoin(self, details):
        def onTrollbox(*args):

            print("type: ", args[0])
            print("message_number: ", args[1])
            print("user_name: ", args[2])
            print("message: ", args[3])
            print("reputation: ", args[4])

        try:
            yield from self.subscribe(onTrollbox, 'trollbox')
        except Exception as e:
            print("Could not subscribe to topic:", e)

runner = ApplicationRunner("wss://api.poloniex.com", "realm1")
runner.run(PoloniexComponent)

Many thanks for ever help on this topic.

tickers do not appear to function

queuedTicker.py will output the last trade 1 time and then just repeat same 'last'.

I was unable to get any coin data out of any of the other 3 samples.
I edited the coin pair.

returnOrderbook raises issues when depth isn't far enough

I noticed that in the init.py, the depth for returnOrderbook is only 20. Can you set this value somewhere higher like 200-300? I set mine to 500 and I noticed no difference in execution speed - this is on a 10 year old computer. When using a script to calculate statistics based off of the data returned from returnOrderbook, I run into errors because of the short depth. I released my script to many others, they would have to change the value manually - not all of them are tech savvy,

Thanks in advance.

loanbot errors

I know the loanbot.py script is only an example, but I'm rubbish at python and loanbot is just what I wanted. However, it gives an error intermittently:

[14:30:06]Active Loans:-----------------------------
[14:30:06]2017-05-31 06:33:31|LTC:0.99999889-[rate:0.0007%]-[fees:0.00000202]
[14:30:06]2017-05-31 05:25:04|DOGE:16762.52933964-[rate:0.0007%]-[fees:0.03952270]
Exception in thread Thread-8 (most likely raised during interpreter shutdown):
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
File "/usr/lib/python2.7/threading.py", line 1073, in run
File "/usr/lib/python2.7/threading.py", line 491, in release
File "/usr/lib/python2.7/threading.py", line 384, in notify
<type 'exceptions.TypeError'>: 'NoneType' object is not callable

Any idea what I can do to stop it?

retry and default timeout

i use default timeout value, 1 sec. ping to poloniex.com <2ms. place some sell order. sleep time between order places is 2 sec. coach set to 1 call/1sec. some time i found sell order duplicates in order list.

{'orderNumber': '76671857444', 'type': 'sell', 'total': '0.00231183', 'date': '2017-05-06 08:39:18', 'margin': 0, 'amount': '0.10391764', 'startingAmount': '0.10391764', 'rate': '0.02224676'}, {'orderNumber': '76671858443', 'type': 'sell', 'total': '0.00231183', 'date': '2017-05-06 08:39:18', 'margin': 0, 'amount': '0.10391764', 'startingAmount': '0.10391764', 'rate': '0.02224676'}

conclusion (for me) at this time for poloniex 1 second is not perfect timeout value!

Parsing of numbers from json loses precision

For example, for a orderbook:

{"asks":[["0.00781195",0.12377319] ...

0.12377319 will be converted to a float, which is a lossy process. IMHO, this should be handled with Decimal, to avoid mangling the number
There's a nice overview of the matter on this blog

Basically, use json.loads(..., parse_float=Decimal)

If you agree with this, I can send a PR

Support for python3

A few adjustments are needed :
line 29 self.Secret = Secret.encode('utf8')
line 87 post_data = urlencode(args).encode('utf8')

Receive error "Invalid Command" for PRIVATE_COMMANDS

As the title states, I have been attempting to use this wrapper, and am able to properly make public calls without issues. However, when I attempt to make any private calls (eg. buy, getBalances, etc) using my api keys I receive an error stating invalid command. I have made my code spit out the key and secret being input into the wrapper and all seems well there. However I am still unable to make privileged calls.

Is this an issue with poloniex? Could they be updating their API calls? Or is it more likely my code is fudged up?

my code:
http://pastebin.com/WSj30Se2 <- edited to a more trustworthy website.

I have attempted your instructions, however no matter how i work it it always seems to give an error stating {u'error': u'Invalid command.'}
However I am 100% sure the issue is my own, I must be missing something or mistyping something. Thank you for responding, I will close as soon as I figure out where my issue is :)
apikey = (defined earlier in program)
apisecret = (same as above)
polo = poloniex.Poloniex(apikey, apisecret, extend=True)
print polo.returnBalances() or print polo.myBalances()
returns the error stated above within IDLE or within a program. Could my issue be that im using python2 and not python3?

How does one use returnDepositsWithdrawals() ?

Using the 2.x version, when I do the following:

import config
import poloniex

polo = poloniex.Poloniex(config.polo_api_key, config.polo_api_secret)

resp = polo.returnDepositsWithdrawals()
print resp

I get:

{u'error': u'Required parameter missing.'}

I believe it wants the "start" and "end" parameters mentioned here:

"Returns your deposit and withdrawal history within a range, specified by the "start" and "end" POST parameters, both of which should be given as UNIX timestamps."

Attempting to call it with parameters it doesn't like that:

resp = polo.returnDepositsWithdrawals(5,10)

TypeError: returnDepositsWithdrawals() takes exactly 1 argument (3 given)

Is this currently not supported?

returnTradeHistory being processed as private command

I think there is a bug in returnTradeHistory() method. I was getting [] return. after stepping through I noticed that 'returnTradeHistory' appears in both PUBLIC_COMMANDS and PRIVATE_COMMANDS list. I believe it is a public command, but was being processed by the private command conditional in the Poloniex class. This was causing it to silently fail.

Removing line 69 in the init.py resolved the issue.

please add new optional parameter for the 'transferBalance' method

polo.transferBalance(currency='BTC', fromAccount='margin', toAccount='lending',amount=0.01661075)

Traceback (most recent call last):
File "", line 1, in
File "/home/strky/anaconda3/envs/py36/lib/python3.6/site-packages/poloniex/init.py", line 525, in transferBalance
'toAccount': str(toAccount)
File "/home/strky/anaconda3/envs/py36/lib/python3.6/site-packages/poloniex/init.py", line 143, in retrying
return func(*args, **kwargs)
File "/home/strky/anaconda3/envs/py36/lib/python3.6/site-packages/poloniex/init.py", line 203, in call
return self.handleReturned(ret.text)
File "/home/strky/anaconda3/envs/py36/lib/python3.6/site-packages/poloniex/init.py", line 270, in handleReturned
raise PoloniexError(out['error'])

poloniex.PoloniexError: Transferring 0.01661075 BTC from your margin account would bring your current margin to 92.03%, putting you in greater danger of a forced liquidation. Please confirm this action by passing confirmed=1 with your request.

as there is no 'confirmed' parameter, please add this one with an empty default value

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.