Skip to content

Commit

Permalink
optimized code
Browse files Browse the repository at this point in the history
  • Loading branch information
SantiiRepair committed Jul 22, 2024
1 parent cad5cd6 commit 1a1f32d
Show file tree
Hide file tree
Showing 7 changed files with 121 additions and 191 deletions.
143 changes: 37 additions & 106 deletions example/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,121 +3,62 @@
import random
import asyncio
import datetime
from pathlib import Path
from termcolor import colored

from quotexpy import Quotex
from quotexpy.utils import asset_parse, asrun
from quotexpy.utils.account_type import AccountType
from quotexpy.utils.candles_period import CandlesPeriod
from quotexpy.utils.operation_type import OperationType
from quotexpy.utils import asset_parse, sessions_file_path

asset_current = "EURUSD"

asset_current = "EURGBP"

def pin_code_handler() -> str:

def on_pin_code() -> str:
code = input("Enter the code sent to your email: ")
return code


class SingletonDecorator:
"""
A decorator that turns a class into a singleton.
"""

def __init__(self, cls):
self.cls = cls
self.instance = None

def __call__(self, *args, **kwargs):
if self.instance is None:
self.instance = self.cls(*args, **kwargs)
return self.instance


@SingletonDecorator
class MyConnection:
"""
This class represents a connection object and provides methods for connecting to a client.
"""

def __init__(self, client_instance: Quotex):
self.client = client_instance

async def connect(self, attempts=5):
check = await self.client.connect()
if not check:
attempt = 0
while attempt <= attempts:
if not self.client.check_connect():
check = await self.client.connect()
if check:
print("Reconectado com sucesso!!!")
break
print("Erro ao reconectar.")
attempt += 1
if Path(sessions_file_path).is_file():
Path(sessions_file_path).unlink()
print(f"Tentando reconectar, tentativa {attempt} de {attempts}")
elif not check:
attempt += 1
else:
break
await asyncio.sleep(5)
return check
return check

def close(self):
"""
Closes the client connection.
"""
self.client.close()


def run(y):
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
z = loop.run_until_complete(y)
return z


client = Quotex(email="", password="", on_pin_code=pin_code_handler)
client.debug_ws_enable = False
client = Quotex(
email="",
password="",
headless=True,
on_pin_code=on_pin_code,
)


def check_asset(asset):
asset_query = asset_parse(asset)
asset_open = client.check_asset_open(asset_query)
asset_open = client.check_asset(asset_query)
if not asset_open or not asset_open[2]:
print(colored("[WARN]: ", "yellow"), "Asset is closed.")
asset = f"{asset}_otc"
print(colored("[WARN]: ", "yellow"), "Try OTC Asset -> " + asset)
asset_query = asset_parse(asset)
asset_open = client.check_asset_open(asset_query)
asset_open = client.check_asset(asset_query)
return asset, asset_open


async def get_balance():
prepare_connection = MyConnection(client)
check_connect = await prepare_connection.connect()
check_connect = await client.connect()
if check_connect:
client.change_account(AccountType.PRACTICE) # "REAL"
print(colored("[INFO]: ", "blue"), "Balance: ", client.get_balance())
print(colored("[INFO]: ", "blue"), "Exiting...")
prepare_connection.close()
client.close()


async def balance_refill():
prepare_connection = MyConnection(client)
check_connect = await prepare_connection.connect()
check_connect = await client.connect()
if check_connect:
result = await client.edit_practice_balance(100)
print(result)
prepare_connection.close()
client.close()


async def trade():
prepare_connection = MyConnection(client)
check_connect = await prepare_connection.connect()
check_connect = await client.connect()
if check_connect:
client.change_account(AccountType.PRACTICE)
amount = 1
Expand All @@ -134,7 +75,7 @@ async def trade():
print(colored("[WARN]: ", "yellow"), "Asset is closed.")
print(colored("[INFO]: ", "blue"), "Balance: ", await client.get_balance())
print(colored("[INFO]: ", "blue"), "Exiting...")
prepare_connection.close()
client.close()


async def wait_for_input_exceeding_x_seconds_limit(secounds=30):
Expand All @@ -146,8 +87,7 @@ async def wait_for_input_exceeding_x_seconds_limit(secounds=30):


async def trade_and_check_win():
prepare_connection = MyConnection(client)
check_connect = await prepare_connection.connect()
check_connect = await client.connect()
if check_connect:
client.change_account(AccountType.PRACTICE)
print(colored("[INFO]: ", "blue"), "Balance: ", await client.get_balance())
Expand All @@ -174,8 +114,7 @@ async def trade_and_check_win():


async def sell_option():
prepare_connection = MyConnection(client)
check_connect = await prepare_connection.connect()
check_connect = await client.connect()
if check_connect:
client.change_account(AccountType.PRACTICE)
amount = 30
Expand All @@ -187,50 +126,43 @@ async def sell_option():
await client.sell_option(buy_info["id"])
print(colored("[INFO]: ", "blue"), "Balance: ", await client.get_balance())
print(colored("[INFO]: ", "blue"), "Exiting...")
prepare_connection.close()
client.close()


async def assets_open():
prepare_connection = MyConnection(client)
check_connect = await prepare_connection.connect()
check_connect = await client.connect()
if check_connect:
for i in client.get_all_asset_name():
print(i, client.check_asset_open(i))
prepare_connection.close()
print(i, client.check_asset(i))
client.close()


async def get_payment():
prepare_connection = MyConnection(client)
check_connect = await prepare_connection.connect()
check_connect = await client.connect()
if check_connect:
all_data = client.get_payment()
for asset_name in all_data:
asset_data = all_data[asset_name]
print(asset_name, asset_data["payment"], asset_data["open"])
prepare_connection.close()
client.close()


# import numpy as np
async def get_candle_v2():
prepare_connection = MyConnection(client)
check_connect = await prepare_connection.connect()
period = 100
check_connect = await client.connect()
if check_connect:
global asset_current
asset, asset_open = check_asset(asset_current)
if asset_open[2]:
print(colored("[INFO]: ", "blue"), "Asset is open.")
# 60 at 180 seconds
candles = await client.get_candle_v2(asset, period)
candles = await client.get_candle_v2(asset, CandlesPeriod.ONE_MINUTE)
print(candles)
else:
print(colored("[INFO]: ", "blue"), "Asset is closed.")
prepare_connection.close()
client.close()


async def get_realtime_candle():
prepare_connection = MyConnection(client)
check_connect = await prepare_connection.connect()
check_connect = await client.connect()
if check_connect:
list_size = 10
global asset_current
Expand All @@ -240,34 +172,33 @@ async def get_realtime_candle():
if len(client.get_realtime_candles(asset)) == list_size:
break
print(client.get_realtime_candles(asset))
prepare_connection.close()
client.close()


async def get_signal_data():
prepare_connection = MyConnection(client)
check_connect = await prepare_connection.connect()
check_connect = await client.connect()
if check_connect:
while True:
print(client.get_signal_data())
time.sleep(1)
prepare_connection.close()
client.close()


async def main():
# await get_balance()
# await get_signal_data()
# await get_payment()
# await get_payments_payout_more_than()
# await get_candle_v2()
await get_candle_v2()
# await get_realtime_candle()
# await assets_open()
await trade_and_check_win()
# await trade_and_check_win()
# await balance_refill()


if __name__ == "__main__":
try:
run(main())
asrun(main())
except KeyboardInterrupt:
print("Aborted!")
sys.exit(0)
33 changes: 16 additions & 17 deletions quotexpy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def __init__(self, email: str, password: str, **kwargs):
self.subscribe_mood = []
self.websocket_client = None
self.websocket_thread = None
self.debug_ws_enable = False
self.trace_ws = False

self.logger = logging.getLogger(__name__)

Expand All @@ -51,8 +51,19 @@ def websocket(self):
"""
return self.websocket_client.wss

async def connect(self) -> bool:
self.api = QuotexAPI(self.email, self.password, **self.kwargs)
self.api.trace_ws = self.trace_ws
ok = await self.api.connect()
if ok:
self.api.send_ssid(max_attemps=10)
if self.api.check_accepted_connection == 0:
ok = await self.connect()

return ok

def check_connect(self):
if self.api.check_websocket_if_connect == 1:
if isinstance(self.api, QuotexAPI) and self.api.check_websocket_if_connect == 1:
return True
return False

Expand Down Expand Up @@ -84,15 +95,14 @@ async def get_instruments(self):
while self.api.instruments is None and time.time() - start < 10:
await asyncio.sleep(0.1)
except:
self.logger.error("api.get_instruments need reconnect")
await self.connect()
return self.api.instruments

def get_all_asset_name(self):
if self.api.instruments:
return [instrument[2].replace("\n", "") for instrument in self.api.instruments]

def check_asset_open(self, asset: str) -> typing.Union[typing.Tuple[int, str, bool], None]:
def check_asset(self, asset: str) -> typing.Union[typing.Tuple[int, str, bool], None]:
if isinstance(self.api, QuotexAPI) and self.api.instruments:
for i in self.api.instruments:
if asset == i[2]:
Expand All @@ -113,7 +123,6 @@ async def get_candles(self, asset: str, offset: int, period: int) -> typing.List
if self.api.candles.candles_data is not None:
break
except:
self.logger.error("get_candles need reconnect")
await self.connect()

return self.api.candles.candles_data
Expand All @@ -127,17 +136,6 @@ async def get_candle_v2(self, asset: str, period: int) -> typing.List[typing.Uni

return self.api.candle_v2_data[asset]

async def connect(self) -> bool:
self.api = QuotexAPI(self.email, self.password, **self.kwargs)
self.api.trace_ws = self.debug_ws_enable
ok = await self.api.connect()
if ok:
self.api.send_ssid(max_attemps=10)
if self.api.check_accepted_connection == 0:
ok = await self.connect()

return ok

def change_account(self, mode=AccountType.PRACTICE) -> None:
"""Change active account `real` or `practice`"""
if mode.upper() == AccountType.REAL:
Expand Down Expand Up @@ -321,7 +319,8 @@ async def start_mood_stream(self, asset, instrument="turbo-option"):
await asyncio.sleep(5)

def close(self):
self.api.close()
if isinstance(self.api, QuotexAPI):
self.api.close()


logging.basicConfig(
Expand Down
Loading

0 comments on commit 1a1f32d

Please sign in to comment.