Code Monkey home page Code Monkey logo

ssc2ce-python's Introduction

ssc2ce

A set of simple connectors for access to few cryptocurrency Exchanges via websocket based on aiohttp.

Supported Exchanges:

  • Bitfinex - only public API,
  • CEX.io,
  • Coinbase Pro
  • Deribit

This is more of a pilot project, if you have any wishes for adding exchanges or expanding functionality, please register issues.

Installation

Install ssc2ce with:

$ pip install ssc2ce

You can run some examples with

Bitfinex

Description

API description look at Websocket API v2

Basic example

import asyncio

from ssc2ce import Bitfinex

conn = Bitfinex()


def handle_subscription(data, connector: Bitfinex):
    print(data, f"received:{connector.receipt_time}")


async def subscribe():
    await conn.subscribe({
        "channel": "ticker",
        "symbol": "tBTCUSD"
    }, handler=handle_subscription)


conn.on_connect_ws = subscribe

loop = asyncio.get_event_loop()

try:
    loop.run_until_complete(conn.run_receiver())
except KeyboardInterrupt:
    print("Application closed by KeyboardInterrupt.")

Deribit

Description

API description look at Deribit API v2 websocket

Basic example

import asyncio
from ssc2ce import Deribit

conn = Deribit()


async def subscribe():
    await conn.send_public(request={
        "method": "public/subscribe",
        "params": {
            "channels": ["deribit_price_index.btc_usd"]
        }
    })


def handle_subscription(data):
    method = data.get("method")
    if method and method == "subscription":
        if data["params"]["channel"].startswith("deribit_price_index"):
            index_name = data["params"]["data"]["index_name"]
            price = data["params"]["data"]["price"]
            print(f" Deribit Price Index {index_name.upper()}: {price}")


conn.on_connect_ws = subscribe
conn.method_routes += [("subscription", handle_subscription)]

loop = asyncio.get_event_loop()


try:
    loop.run_until_complete(conn.run_receiver())
except KeyboardInterrupt:
    print("Application closed by KeyboardInterrupt.")

Run examples from a clone

If you clone repository you can run examples in docker container.

make run cmd='python examples/bitfinex/bitfinex_basic_example.py'

To run the private.py example, you must create and fill in the .env file, look at .env.example

make run cmd='python examples/deribit/deribit_private.py'

ssc2ce-python's People

Contributors

olned avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

ssc2ce-python's Issues

add public/get_instruments

Could you please add into ssc2ce a possibility to get "method":"public/get_instruments" it is necessary to add recieved instruments to a form

{ 
"method":"public/get_instruments"
"params":{ 
"currency":"BTC"
"kind":"option"
}
"jsonrpc":"2.0"
"id":2
}

app:

import sys
import asyncio
import qdarkstyle
import os
from dotenv import load_dotenv
from uuid import uuid4
from asyncqt import QEventLoop, asyncSlot, asyncClose
from ssc2ce.deribit import Deribit, AuthType
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QTextEdit, QPushButton, QVBoxLayout)

class MainWindowGli(QWidget):
    def __init__(self):
        super().__init__()
        self._initUI()

    def _initUI(self):
        self.setLayout(QVBoxLayout())
        self.lblStatus = QLabel('₿TC 0', self)
        self.layout().addWidget(self.lblStatus)

        self.btnFetch = QPushButton('Старт', self)
        self.layout().addWidget(self.btnFetch)
        self.btnFetch.clicked.connect(self.on_btnFetch_clicked)

        dotenv_path = os.path.join(os.path.dirname(__file__), 'key.env')
        load_dotenv(dotenv_path)
        client_id = os.environ.get('DERIBIT_CLIENT_ID')
        client_secret = os.environ.get('DERIBIT_CLIENT_SECRET')

        self.deribit = Deribit(client_id=client_id,
                               client_secret=client_secret,
                               auth_type=AuthType.CREDENTIALS,
                               scope=None,
                               get_id=lambda: str(uuid4()))

        self.loop = asyncio.get_event_loop()
        self.feed_task = None
        self.deribit.on_connect_ws = self.subscribe
        self.deribit.method_routes += [("subscription", self.handle_subscription)]

    @asyncSlot()
    async def on_btnFetch_clicked(self):
        self.btnFetch.setEnabled(False)

        try:
            self.feed_task = asyncio.ensure_future(self.deribit.run_receiver())
        except Exception as exc:
            self.lblStatus.setText(self.lblStatus.text() + '\nError: {}'.format(exc))
        finally:
            self.btnFetch.setEnabled(True)

    async def subscribe(self):
        await self.deribit.send_public(request={
            "method": "public/subscribe",
            "params": {
                "channels": ["deribit_price_index.btc_usd"]
            }
        })

    async def handle_subscription(self, data):
        method = data.get("method")
        if method and method == "subscription":
            if data["params"]["channel"].startswith("deribit_price_index"):
                index_name = data["params"]["data"]["index_name"]
                price = data["params"]["data"]["price"]
                self.lblStatus.setText('₿TC '+str(price))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    style = qdarkstyle.load_stylesheet()
    app.setStyleSheet(style)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)
    mainwindowgli = MainWindowGli()
    title = ("GLI")
    mainwindowgli.setWindowTitle(title)
    mainwindowgli.show()
    with loop:
        sys.exit(loop.run_forever())

window program

Hi!
When I launch the code
loop.run_until_complete(app.run_receiver())
the button in the window program stalls. But the "run_receiver" works fine and gives data to log. What is the way to avoid those stalls?

error start/stop

It is required to turn on and turn off Deribit connection. In the code below it is evident that in case of pressing start stop and start again the connection will not reestablish.


import sys
import asyncio
from asyncqt import QEventLoop, asyncSlot, asyncClose
from ssc2ce import Deribit
from PyQt5.QtWidgets import (QApplication, QWidget, QLabel, QTextEdit, QPushButton,QVBoxLayout)

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setLayout(QVBoxLayout())

        self.lblStatus = QLabel('Idle', self)
        self.layout().addWidget(self.lblStatus)

        self.editResponse = QTextEdit('', self)
        self.layout().addWidget(self.editResponse)

        self.btnStart = QPushButton('Start', self)
        self.btnStart.clicked.connect(self.on_btnStart_clicked)
        self.layout().addWidget(self.btnStart)

        self.btnStop = QPushButton('Stop', self)
        self.btnStop.clicked.connect(self.on_btnStop_clicked)
        self.layout().addWidget(self.btnStop)

        self.conn = Deribit()
        self.loop = asyncio.get_event_loop()
        self.feed_task = None
        self.conn.on_connect_ws = self.subscribe
        self.conn.method_routes += [("subscription", self.handle_subscription)]

    @asyncClose
    async def closeEvent(self, event):
        await self.session.close()

    @asyncSlot()
    async def on_btnStart_clicked(self):
        self.btnStart.setEnabled(False)
        self.lblStatus.setText('Start...')

        try:
            self.feed_task = asyncio.ensure_future(self.conn.run_receiver())
        except Exception as exc:
            self.lblStatus.setText(self.lblStatus.text() + '\nError: {}'.format(exc))
        finally:
            self.btnStart.setEnabled(True)

    @asyncSlot()
    async def on_btnStop_clicked(self):
        self.btnStop.setEnabled(False)
        self.lblStatus.setText('Stop...')

        try:
            self.feed_task = asyncio.ensure_future(self.conn.stop())
        except Exception as exc:
            self.lblStatus.setText(self.lblStatus.text() + '\nError: {}'.format(exc))
        finally:
            self.btnStart.setEnabled(True)

    async def subscribe(self):
        await self.conn.send_public(request={
            "method": "public/subscribe",
            "params": {
                "channels": ["deribit_price_index.btc_usd"]
            }
        })

    async def handle_subscription(self, data):
        method = data.get("method")
        if method and method == "subscription":
            if data["params"]["channel"].startswith("deribit_price_index"):
                index_name = data["params"]["data"]["index_name"]
                price = data["params"]["data"]["price"]
                self.editResponse.append(f"Deribit Price Index {index_name.upper()}: {price}")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    loop = QEventLoop(app)
    asyncio.set_event_loop(loop)

    mainWindow = MainWindow()
    mainWindow.show()

    with loop:
        sys.exit(loop.run_forever())

self.deribit.send_public

Hello!
How can I add and delete subscriptions while the programm is working but not only after self.deribit.send_public is launched.

Connection to Deribit

Hi!

We need to add "is_connected()" function or variable to your library. So that we could understand if we have a connection to Deribit platform.

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.