2015-08-22 15 views
18

Sto provando a connettermi a wss: //api.poloniex.com e iscrivermi a ticker. Non riesco a trovare alcun esempio funzionante in python. Ho provato ad usare autobahn/twisted e websocket-client 0.32.0.Come connettersi a poloniex.com websocket api utilizzando una libreria python

Lo scopo è quello di ottenere dati di ticker in tempo reale e memorizzarli in un database mysql.

Finora ho provato a utilizzare gli esempi forniti nella documentazione della libreria. Funzionano per localhost o il server di test, ma se cambio in wss: //api.poloniex.com ottengo un sacco di errori.

Ecco il mio tentativo utilizzando websocket-client 0.32.0:

from websocket import create_connection 
ws = create_connection("wss://api.poloniex.com") 
ws.send("ticker") 
result = ws.recv() 
print "Received '%s'" % result 
ws.close() 

e questo sta usando autobahn/twisted:

from autobahn.twisted.websocket import WebSocketClientProtocol 
from autobahn.twisted.websocket import WebSocketClientFactory 


class MyClientProtocol(WebSocketClientProtocol): 

    def onConnect(self, response): 
     print("Server connected: {0}".format(response.peer)) 

    def onOpen(self): 
     print("WebSocket connection open.") 

     def hello(): 
      self.sendMessage(u"ticker".encode('utf8')) 
      self.sendMessage(b"\x00\x01\x03\x04", isBinary=True) 
      self.factory.reactor.callLater(1, hello) 

     # start sending messages every second .. 
     hello() 

    def onMessage(self, payload, isBinary): 
     if isBinary: 
      print("Binary message received: {0} bytes".format(len(payload))) 
     else: 
      print("Text message received: {0}".format(payload.decode('utf8'))) 

    def onClose(self, wasClean, code, reason): 
     print("WebSocket connection closed: {0}".format(reason)) 


if __name__ == '__main__': 

    import sys 

    from twisted.python import log 
    from twisted.internet import reactor 

    log.startLogging(sys.stdout) 

    factory = WebSocketClientFactory("wss://api.poloniex.com", debug=False) 
    factory.protocol = MyClientProtocol 

    reactor.connectTCP("wss://api.poloniex.com", 9000, factory) 
    reactor.run() 

Un esempio completo, ma semplice che mostra come collegarsi e iscriversi al ad una API push di websocket che usa qualsiasi libreria python sarebbe molto apprezzata.

risposta

12

È possibile eseguire ciò che si sta utilizzando utilizzando WAMP, in particolare utilizzando i moduli WAMP della libreria autobahn (che si sta già tentando di utilizzare).

Dopo aver seguito i loro documenti, sono riuscito a creare un semplice esempio utilizzando autobahn e asyncio. L'esempio seguente sottoscrive al feed 'ticker' e stampa i valori ricevuti:

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 onTicker(*args): 
      print("Ticker event received:", args) 

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


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


if __name__ == "__main__": 
    main() 

Potete trovare maggiori dettagli sulla programmazione WAMP con autostrada qui: http://autobahn.ws/python/wamp/programming.html

+0

resa da self.subscribe (onTicker, 'ticker') SyntaxError: sintassi non valida –

+4

In che versione di Python sei? Questo esempio è per Python 3.3+, poiché usa 'asyncio' e il costrutto' yield from' per delegare l'esecuzione a una diversa coroutine. Puoi trovare maggiori dettagli qui: https://docs.python.org/3/library/asyncio-task.html –

+0

Python 2.7.3, hai ragione. Grazie –

4

Attualmente, Contorto non usa correttamente Windows fiduciario Quindi la verifica del certificato TLS fallirà. Per ovviare a questo fino a quando ritorto o autostrada include una soluzione alternativa, è possibile:

  • installare certifi modulo (pip install certifi)
  • set ssl_cert_file, come export SSL_CERT_FILE="$(python -m certifi)"
+0

Grazie meejah. Ciò ha aiutato anche sotto Linux. – Andz

+0

Twisted * dovrebbe * utilizzare il trust store globale su Linux; forse sei su una minima installazione Linux che non li include per qualche motivo? – meejah

24

Questo utilizza l'endpoint websocket non documentata perché Poloniex ha tirato il supporto per l'endpoint del socket WAMP originale.

import websocket 
import thread 
import time 
import json 

def on_message(ws, message): 
    print(message) 

def on_error(ws, error): 
    print(error) 

def on_close(ws): 
    print("### closed ###") 

def on_open(ws): 
    print("ONOPEN") 
    def run(*args): 
     ws.send(json.dumps({'command':'subscribe','channel':1001})) 
     ws.send(json.dumps({'command':'subscribe','channel':1002})) 
     ws.send(json.dumps({'command':'subscribe','channel':1003})) 
     ws.send(json.dumps({'command':'subscribe','channel':'BTC_XMR'})) 
     while True: 
      time.sleep(1) 
     ws.close() 
     print("thread terminating...") 
    thread.start_new_thread(run,()) 


if __name__ == "__main__": 
    websocket.enableTrace(True) 
    ws = websocket.WebSocketApp("wss://api2.poloniex.com/", 
           on_message = on_message, 
           on_error = on_error, 
           on_close = on_close) 
    ws.on_open = on_open 
    ws.run_forever() 

I canali sono:

1001 = trollbox (you will get nothing but a heartbeat) 
1002 = ticker 
1003 = base coin 24h volume stats 
1010 = heartbeat 
'MARKET_PAIR' = market order books 
+0

Sono sicuro che la risposta precedente di @Ion Scerbatiuc funziona perfettamente, ma sto usando Python 2.7.x, quindi questa risposta è stata per me un'opzione migliore. La risposta di Ion è basata su Python 3.5 e versioni successive. Correzione – MikeyE

+0

: dopo aver riletto i commenti sulla risposta di Ion, sembra che la sua soluzione sia basata su Python 3.3. – MikeyE

+0

Contento di essere di aiuto –

6

Nel frattempo poloniex cambiato l'API ticker, così ora restituisce un simbolo-id invece di un nome, così forse qualcuno troverà questo utile:

7: BTC_BCN 
8: BTC_BELA 
10: BTC_BLK 
12: BTC_BTCD 
13: BTC_BTM 
14: BTC_BTS 
15: BTC_BURST 
20: BTC_CLAM 
24: BTC_DASH 
25: BTC_DGB 
27: BTC_DOGE 
28: BTC_EMC2 
31: BTC_FLDC 
32: BTC_FLO 
38: BTC_GAME 
40: BTC_GRC 
43: BTC_HUC 
50: BTC_LTC 
51: BTC_MAID 
58: BTC_OMNI 
61: BTC_NAV 
63: BTC_NEOS 
64: BTC_NMC 
69: BTC_NXT 
73: BTC_PINK 
74: BTC_POT 
75: BTC_PPC 
83: BTC_RIC 
89: BTC_STR 
92: BTC_SYS 
97: BTC_VIA 
98: BTC_XVC 
99: BTC_VRC 
100: BTC_VTC 
104: BTC_XBC 
108: BTC_XCP 
112: BTC_XEM 
114: BTC_XMR 
116: BTC_XPM 
117: BTC_XRP 
121: USDT_BTC 
122: USDT_DASH 
123: USDT_LTC 
124: USDT_NXT 
125: USDT_STR 
126: USDT_XMR 
127: USDT_XRP 
129: XMR_BCN 
130: XMR_BLK 
131: XMR_BTCD 
132: XMR_DASH 
137: XMR_LTC 
138: XMR_MAID 
140: XMR_NXT 
148: BTC_ETH 
149: USDT_ETH 
150: BTC_SC 
151: BTC_BCY 
153: BTC_EXP 
155: BTC_FCT 
158: BTC_RADS 
160: BTC_AMP 
162: BTC_DCR 
163: BTC_LSK 
166: ETH_LSK 
167: BTC_LBC 
168: BTC_STEEM 
169: ETH_STEEM 
170: BTC_SBD 
171: BTC_ETC 
172: ETH_ETC 
173: USDT_ETC 
174: BTC_REP 
175: USDT_REP 
176: ETH_REP 
177: BTC_ARDR 
178: BTC_ZEC 
179: ETH_ZEC 
180: USDT_ZEC 
181: XMR_ZEC 
182: BTC_STRAT 
183: BTC_NXC 
184: BTC_PASC 
185: BTC_GNT 
186: ETH_GNT 
187: BTC_GNO 
188: ETH_GNO 
189: BTC_BCH 
190: ETH_BCH 
191: USDT_BCH 
192: BTC_ZRX 
193: ETH_ZRX 
194: BTC_CVC 
195: ETH_CVC 
196: BTC_OMG 
197: ETH_OMG 
198: BTC_GAS 
199: ETH_GAS 
200: BTC_STORJ 
Problemi correlati