Skip to content

Commit

Permalink
Merge pull request #199 from s4w3d0ff/dev
Browse files Browse the repository at this point in the history
v0.5.5
  • Loading branch information
s4w3d0ff authored Jun 7, 2019
2 parents c964200 + 784f5f7 commit 31b617b
Show file tree
Hide file tree
Showing 7 changed files with 155 additions and 97 deletions.
11 changes: 8 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
dist: xenial
language: python
python:
- '2.7'
- '3.5'
- '3.6'
- "2.7"
- "3.5"
- "3.5-dev"
- "3.6"
- "3.6-dev"
- "3.7"
- "3.7-dev"
install: python setup.py install
script: python test.py
deploy:
Expand Down
43 changes: 38 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
[![python](https://img.shields.io/badge/python-2.7%20%26%203-blue.svg)![licence](https://img.shields.io/badge/licence-GPL%20v2-blue.svg)](https://github.com/s4w3d0ff/python-poloniex/blob/master/LICENSE) [![release](https://img.shields.io/github/release/s4w3d0ff/python-poloniex.svg)![release build](https://travis-ci.org/s4w3d0ff/python-poloniex.svg?branch=v0.5.4)](https://github.com/s4w3d0ff/python-poloniex/releases)
[![python](https://img.shields.io/badge/python-2.7%20%26%203-blue.svg)![licence](https://img.shields.io/badge/licence-GPL%20v2-blue.svg)](https://github.com/s4w3d0ff/python-poloniex/blob/master/LICENSE) [![release](https://img.shields.io/github/release/s4w3d0ff/python-poloniex.svg)![release build](https://travis-ci.org/s4w3d0ff/python-poloniex.svg?branch=v0.5.5)](https://github.com/s4w3d0ff/python-poloniex/releases)
[![master](https://img.shields.io/badge/branch-master-blue.svg)![master build](https://api.travis-ci.org/s4w3d0ff/python-poloniex.svg?branch=master)](https://github.com/s4w3d0ff/python-poloniex/tree/master) [![dev](https://img.shields.io/badge/branch-dev-blue.svg)![dev build](https://api.travis-ci.org/s4w3d0ff/python-poloniex.svg?branch=dev)](https://github.com/s4w3d0ff/python-poloniex/tree/dev)
Inspired by [this](http://pastebin.com/8fBVpjaj) wrapper written by 'oipminer'
> I (s4w3d0ff) am not affiliated with, nor paid by [Poloniex](https://poloniex.com). I found the linked python wrapper on the poloniex support page to be incomplete and buggy so I decided to write this wrapper and create a git repository. If you wish to contribute to the repository please read [CONTRIBUTING.md](https://github.com/s4w3d0ff/python-poloniex/blob/master/CONTRIBUTING.md). All and any help is appreciated.
Expand Down Expand Up @@ -68,14 +68,17 @@ print(polo.marketTradeHist('BTC_ETH'))
print(polo.returnTradeHistory('BTC_ETH'))
```

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

#### Websocket Usage:
Right now, the easiest way to use the websocket api is making a child class like so:
To connect to the websocket api just create a child class of `PoloniexSocketed` like so:
```python
import poloniex
import logging

logging.basicConfig()

class MySocket(poloniex.Poloniex):
class MySocket(poloniex.PoloniexSocketed):

def on_heartbeat(self, msg):
"""
Expand All @@ -85,13 +88,13 @@ class MySocket(poloniex.Poloniex):

def on_volume(self, msg):
"""
Triggers whenever we get a ticker message
Triggers whenever we get a 24hvolume message
"""
print(msg)

def on_ticker(self, msg):
"""
Triggers whenever we get a 24hvolume message
Triggers whenever we get a ticker message
"""
print(msg)

Expand All @@ -112,6 +115,36 @@ sock = MySocket()
sock.logger.setLevel(logging.DEBUG)
# start the websocket thread and subsribe to '24hvolume'
sock.startws(subscribe=['24hvolume'])
# give the socket some time init
poloniex.sleep(5)
# this won't work:
#sock.subscribe('ticker')
# use channel id to un/sub
sock.subscribe('1002')
poloniex.sleep(1)
# unsub from ticker
sock.unsubscribe('1002')
poloniex.sleep(4)
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
```

**More examples of how to use websocket push API can be found [here](https://github.com/s4w3d0ff/python-poloniex/tree/master/examples).**
2 changes: 1 addition & 1 deletion examples/websocket/dictTicker.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import poloniex

class TickPolo(poloniex.Poloniex):
class TickPolo(poloniex.PoloniexSocketed):
def __init__(self, *args, **kwargs):
super(TickPolo, self).__init__(*args, **kwargs)
# tick holds ticker data
Expand Down
2 changes: 1 addition & 1 deletion examples/websocket/mongoTicker.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import poloniex
from pymongo import MongoClient # pip install pymongo

class TickPolo(poloniex.Poloniex):
class TickPolo(poloniex.PoloniexSocketed):
def __init__(self, *args, **kwargs):
super(TickPolo, self).__init__(*args, **kwargs)
self.db = MongoClient().poloniex['ticker']
Expand Down
109 changes: 61 additions & 48 deletions examples/websocket/stopLimit.py
Original file line number Diff line number Diff line change
@@ -1,88 +1,101 @@
import poloniex

class StopLimit(object):
def __init__(self, market, amount, stop, limit, test=False):
self.market = str(market)
self.amount = float(amount)
self.stop = float(stop)
self.limit = float(limit)
self.order = False
self.logger = poloniex.logging.getLogger('StopLimit')
self.logger.setLevel(poloniex.logging.DEBUG)
self.test = test
class StopPoloniex(poloniex.PoloniexSocketed):
def __init__(self, *args, **kwargs):
super(StopPoloniex, self).__init__(*args, **kwargs)
# holds stop orders
self.stopOrders = {}

def on_ticker(self, msg):
data = [float(dat) for dat in msg]
# check stop orders
mkt = self.channels[str(int(data[0]))]['name']
la = data[2]
hb = data[3]
for id in self.stopOrders:
# market matches and the order hasnt triggered yet
if str(self.stopOrders[id]['market']) == str(mkt) and not self.stopOrders[id]['order']:
self.logger.debug('%s lowAsk=%s highBid=%s', mkt, str(la), str(hb))
self._check_stop(id, la, hb)

def check(self, lowAsk, highBid):


def _check_stop(self, id, lowAsk, highBid):
amount = self.stopOrders[id]['amount']
stop = self.stopOrders[id]['stop']
test = self.stopOrders[id]['test']
# sell
if self.amount < 0 and self.stop >= float(highBid):
if amount < 0 and stop >= float(highBid):
# dont place order if we are testing
if self.test:
self.order = True
if test:
self.stopOrders[id]['order'] = True
else:
# sell amount at limit
self.order = self.sell(self.market,
self.limit,
abs(self.amount))
self.stopOrders[id]['order'] = self.sell(
self.stopOrders[id]['market'],
self.stopOrders[id]['limit'],
abs(amount))

self.logger.info('%s sell stop order triggered! (%s)',
self.market, str(self.stop))
self.stopOrders[id]['market'],
str(stop))
if self.stopOrders[id]['callback']:
self.stopOrders[id]['callback'](id)

# buy
if self.amount > 0 and self.stop <= float(lowAsk):
if amount > 0 and stop <= float(lowAsk):
# dont place order if we are testing
if self.test:
self.order = True
if test:
self.stopOrders[id]['order'] = True
else:
# buy amount at limit
self.order = self.buy(self.market, self.limit, self.amount)
self.stopOrders[id]['order'] = self.buy(
self.stopOrders[id]['market'],
self.stopOrders[id]['limit'],
amount)

self.logger.info('%s buy stop order triggered! (%s)',
self.market, str(self.stop))

def __call__(self):
return self.order
self.stopOrders[id]['market'],
str(stop))
if self.stopOrders[id]['callback']:
self.stopOrders[id]['callback'](id)


class CPolo(poloniex.Poloniex):
def __init__(self, *args, **kwargs):
super(CPolo, self).__init__(*args, **kwargs)
self.stopOrders = {}

def on_ticker(self, msg):
self._checkStops(msg)

def _checkStops(self, msg):
mktid = str(msg[0])
mkt = self.channels[mktid]['name']
la = msg[2]
hb = msg[3]
for order in self.stopOrders:
if str(self.stopOrders[order].market) == str(mkt) and not self.stopOrders[order]():
self.logger.debug('%s lowAsk=%s highBid=%s',
mkt, str(la), str(hb))
self.stopOrders[order].check(la, hb)

def addStopLimit(self, market, amount, stop, limit, test=False):
def addStopLimit(self, market, amount, stop, limit, callback=None, test=False):
self.stopOrders[market+str(stop)] = {'market': market,
'amount': amount,
'stop': stop,
'limit': limit,
'callback': callback,
'test': test,
'order': False
}
self.logger.debug('%s stop limit set: [Amount]%.8f [Stop]%.8f [Limit]%.8f',
market, amount, stop, limit)
self.stopOrders[market+str(stop)] = StopLimit(market, amount, stop, limit, test)



if __name__ == '__main__':
import logging
logging.basicConfig()
test = CPolo('key', 'secret')
test = StopPoloniex('key', 'secret')
def callbk(id):
print(test.stopOrders[id])
test.logger.setLevel(logging.DEBUG)
tick = test.returnTicker()
test.addStopLimit(market='BTC_LTC',
amount=0.5,
stop=float(tick['BTC_LTC']['lowestAsk'])+0.000001,
limit=float(0.004),
callback=callbk,
# remove or set 'test' to false to place real orders
test=True)

test.addStopLimit(market='BTC_LTC',
amount=-0.5,
stop=float(tick['BTC_LTC']['highestBid'])-0.000001,
limit=float(0.004),
callback=callbk,
# remove or set 'test' to false to place real orders
test=True)
test.startws(['ticker'])
Expand Down
Loading

0 comments on commit 31b617b

Please sign in to comment.