Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

error start/stop #25

Closed
mrGreenS opened this issue Sep 18, 2020 · 1 comment
Closed

error start/stop #25

mrGreenS opened this issue Sep 18, 2020 · 1 comment
Labels
bug Something isn't working

Comments

@mrGreenS
Copy link

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())
@olned olned added the bug Something isn't working label Sep 18, 2020
@olned olned mentioned this issue Sep 18, 2020
@olned
Copy link
Owner

olned commented Sep 18, 2020

Fixed, look at 0.14.2
And I made a liitle changes in your example

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.btnStop.setEnabled(False)
        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):
        if self.conn and self.conn.is_connected():
            await self.conn.stop()

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

        try:
            if not self.feed_task:
                self.btnStop.setEnabled(True)
                await self.conn.run_receiver()
                self.btnStop.setEnabled(False)
        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:
            await self.conn.stop()
            self.feed_task = None
        except Exception as exc:
            self.lblStatus.setText(self.lblStatus.text() + '\nError: {}'.format(exc))

    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())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants