Skip to content

Commit 31b617b

Browse files
authored
Merge pull request #199 from s4w3d0ff/dev
v0.5.5
2 parents c964200 + 784f5f7 commit 31b617b

File tree

7 files changed

+155
-97
lines changed

7 files changed

+155
-97
lines changed

.travis.yml

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
1+
dist: xenial
12
language: python
23
python:
3-
- '2.7'
4-
- '3.5'
5-
- '3.6'
4+
- "2.7"
5+
- "3.5"
6+
- "3.5-dev"
7+
- "3.6"
8+
- "3.6-dev"
9+
- "3.7"
10+
- "3.7-dev"
611
install: python setup.py install
712
script: python test.py
813
deploy:

README.md

Lines changed: 38 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
[![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)
1+
[![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)
22
[![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)
33
Inspired by [this](http://pastebin.com/8fBVpjaj) wrapper written by 'oipminer'
44
> 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.
@@ -68,14 +68,17 @@ print(polo.marketTradeHist('BTC_ETH'))
6868
print(polo.returnTradeHistory('BTC_ETH'))
6969
```
7070

71+
You can also not use the 'helper' methods at all and use `poloniex.PoloniexBase` which only has `returnMarketHist`, `__call__` to make rest api calls.
72+
7173
#### Websocket Usage:
72-
Right now, the easiest way to use the websocket api is making a child class like so:
74+
To connect to the websocket api just create a child class of `PoloniexSocketed` like so:
7375
```python
76+
import poloniex
7477
import logging
7578

7679
logging.basicConfig()
7780

78-
class MySocket(poloniex.Poloniex):
81+
class MySocket(poloniex.PoloniexSocketed):
7982

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

8689
def on_volume(self, msg):
8790
"""
88-
Triggers whenever we get a ticker message
91+
Triggers whenever we get a 24hvolume message
8992
"""
9093
print(msg)
9194

9295
def on_ticker(self, msg):
9396
"""
94-
Triggers whenever we get a 24hvolume message
97+
Triggers whenever we get a ticker message
9598
"""
9699
print(msg)
97100

@@ -112,6 +115,36 @@ sock = MySocket()
112115
sock.logger.setLevel(logging.DEBUG)
113116
# start the websocket thread and subsribe to '24hvolume'
114117
sock.startws(subscribe=['24hvolume'])
118+
# give the socket some time init
119+
poloniex.sleep(5)
120+
# this won't work:
121+
#sock.subscribe('ticker')
122+
# use channel id to un/sub
123+
sock.subscribe('1002')
124+
poloniex.sleep(1)
125+
# unsub from ticker
126+
sock.unsubscribe('1002')
127+
poloniex.sleep(4)
128+
sock.stopws()
129+
130+
```
131+
132+
```
133+
INFO:poloniex:Websocket thread started
134+
DEBUG:poloniex:Subscribed to 24hvolume
135+
[1010]
136+
DEBUG:poloniex:Subscribed to ticker
137+
[241, '86.59997298', '86.68262835', '85.69590501', '0.01882321', '22205.56419338', '258.30264061', 0, '87.31843098', '82.81638725']
138+
...
139+
...
140+
[254, '5.89427014', '6.14542299', '5.92000026', '-0.03420118', '9978.11197201', '1649.83975863', 0, '6.19642428', '5.74631502']
141+
DEBUG:poloniex:Unsubscribed to ticker
142+
[1010]
143+
[1010]
144+
[1010]
145+
['2019-06-07 04:16', 2331, {'BTC': '2182.115', 'ETH': '490.635', 'XMR': '368.983', 'USDT': '7751402.061', 'USDC': '5273463.730'}]
146+
DEBUG:poloniex:Websocket Closed
147+
INFO:poloniex:Websocket thread stopped/joined
115148
```
116149

117150
**More examples of how to use websocket push API can be found [here](https://github.com/s4w3d0ff/python-poloniex/tree/master/examples).**

examples/websocket/dictTicker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import poloniex
22

3-
class TickPolo(poloniex.Poloniex):
3+
class TickPolo(poloniex.PoloniexSocketed):
44
def __init__(self, *args, **kwargs):
55
super(TickPolo, self).__init__(*args, **kwargs)
66
# tick holds ticker data

examples/websocket/mongoTicker.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import poloniex
22
from pymongo import MongoClient # pip install pymongo
33

4-
class TickPolo(poloniex.Poloniex):
4+
class TickPolo(poloniex.PoloniexSocketed):
55
def __init__(self, *args, **kwargs):
66
super(TickPolo, self).__init__(*args, **kwargs)
77
self.db = MongoClient().poloniex['ticker']

examples/websocket/stopLimit.py

Lines changed: 61 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,88 +1,101 @@
11
import poloniex
22

3-
class StopLimit(object):
4-
def __init__(self, market, amount, stop, limit, test=False):
5-
self.market = str(market)
6-
self.amount = float(amount)
7-
self.stop = float(stop)
8-
self.limit = float(limit)
9-
self.order = False
10-
self.logger = poloniex.logging.getLogger('StopLimit')
11-
self.logger.setLevel(poloniex.logging.DEBUG)
12-
self.test = test
3+
class StopPoloniex(poloniex.PoloniexSocketed):
4+
def __init__(self, *args, **kwargs):
5+
super(StopPoloniex, self).__init__(*args, **kwargs)
6+
# holds stop orders
7+
self.stopOrders = {}
8+
9+
def on_ticker(self, msg):
10+
data = [float(dat) for dat in msg]
11+
# check stop orders
12+
mkt = self.channels[str(int(data[0]))]['name']
13+
la = data[2]
14+
hb = data[3]
15+
for id in self.stopOrders:
16+
# market matches and the order hasnt triggered yet
17+
if str(self.stopOrders[id]['market']) == str(mkt) and not self.stopOrders[id]['order']:
18+
self.logger.debug('%s lowAsk=%s highBid=%s', mkt, str(la), str(hb))
19+
self._check_stop(id, la, hb)
1320

14-
def check(self, lowAsk, highBid):
21+
22+
23+
def _check_stop(self, id, lowAsk, highBid):
24+
amount = self.stopOrders[id]['amount']
25+
stop = self.stopOrders[id]['stop']
26+
test = self.stopOrders[id]['test']
1527
# sell
16-
if self.amount < 0 and self.stop >= float(highBid):
28+
if amount < 0 and stop >= float(highBid):
1729
# dont place order if we are testing
18-
if self.test:
19-
self.order = True
30+
if test:
31+
self.stopOrders[id]['order'] = True
2032
else:
2133
# sell amount at limit
22-
self.order = self.sell(self.market,
23-
self.limit,
24-
abs(self.amount))
34+
self.stopOrders[id]['order'] = self.sell(
35+
self.stopOrders[id]['market'],
36+
self.stopOrders[id]['limit'],
37+
abs(amount))
2538

2639
self.logger.info('%s sell stop order triggered! (%s)',
27-
self.market, str(self.stop))
40+
self.stopOrders[id]['market'],
41+
str(stop))
42+
if self.stopOrders[id]['callback']:
43+
self.stopOrders[id]['callback'](id)
44+
2845
# buy
29-
if self.amount > 0 and self.stop <= float(lowAsk):
46+
if amount > 0 and stop <= float(lowAsk):
3047
# dont place order if we are testing
31-
if self.test:
32-
self.order = True
48+
if test:
49+
self.stopOrders[id]['order'] = True
3350
else:
3451
# buy amount at limit
35-
self.order = self.buy(self.market, self.limit, self.amount)
52+
self.stopOrders[id]['order'] = self.buy(
53+
self.stopOrders[id]['market'],
54+
self.stopOrders[id]['limit'],
55+
amount)
3656

3757
self.logger.info('%s buy stop order triggered! (%s)',
38-
self.market, str(self.stop))
39-
40-
def __call__(self):
41-
return self.order
58+
self.stopOrders[id]['market'],
59+
str(stop))
60+
if self.stopOrders[id]['callback']:
61+
self.stopOrders[id]['callback'](id)
4262

4363

44-
class CPolo(poloniex.Poloniex):
45-
def __init__(self, *args, **kwargs):
46-
super(CPolo, self).__init__(*args, **kwargs)
47-
self.stopOrders = {}
48-
49-
def on_ticker(self, msg):
50-
self._checkStops(msg)
51-
52-
def _checkStops(self, msg):
53-
mktid = str(msg[0])
54-
mkt = self.channels[mktid]['name']
55-
la = msg[2]
56-
hb = msg[3]
57-
for order in self.stopOrders:
58-
if str(self.stopOrders[order].market) == str(mkt) and not self.stopOrders[order]():
59-
self.logger.debug('%s lowAsk=%s highBid=%s',
60-
mkt, str(la), str(hb))
61-
self.stopOrders[order].check(la, hb)
62-
63-
def addStopLimit(self, market, amount, stop, limit, test=False):
64+
def addStopLimit(self, market, amount, stop, limit, callback=None, test=False):
65+
self.stopOrders[market+str(stop)] = {'market': market,
66+
'amount': amount,
67+
'stop': stop,
68+
'limit': limit,
69+
'callback': callback,
70+
'test': test,
71+
'order': False
72+
}
6473
self.logger.debug('%s stop limit set: [Amount]%.8f [Stop]%.8f [Limit]%.8f',
6574
market, amount, stop, limit)
66-
self.stopOrders[market+str(stop)] = StopLimit(market, amount, stop, limit, test)
75+
6776

6877

6978
if __name__ == '__main__':
7079
import logging
7180
logging.basicConfig()
72-
test = CPolo('key', 'secret')
81+
test = StopPoloniex('key', 'secret')
82+
def callbk(id):
83+
print(test.stopOrders[id])
7384
test.logger.setLevel(logging.DEBUG)
7485
tick = test.returnTicker()
7586
test.addStopLimit(market='BTC_LTC',
7687
amount=0.5,
7788
stop=float(tick['BTC_LTC']['lowestAsk'])+0.000001,
7889
limit=float(0.004),
90+
callback=callbk,
7991
# remove or set 'test' to false to place real orders
8092
test=True)
8193

8294
test.addStopLimit(market='BTC_LTC',
8395
amount=-0.5,
8496
stop=float(tick['BTC_LTC']['highestBid'])-0.000001,
8597
limit=float(0.004),
98+
callback=callbk,
8699
# remove or set 'test' to false to place real orders
87100
test=True)
88101
test.startws(['ticker'])

0 commit comments

Comments
 (0)