Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added .DS_Store
Binary file not shown.
Binary file added pocketoptionapi/__pycache__/__init__.cpython-37.pyc
Binary file not shown.
Binary file added pocketoptionapi/__pycache__/__init__.cpython-38.pyc
Binary file not shown.
Binary file added pocketoptionapi/__pycache__/api.cpython-311.pyc
Binary file not shown.
Binary file added pocketoptionapi/__pycache__/api.cpython-37.pyc
Binary file not shown.
Binary file added pocketoptionapi/__pycache__/api.cpython-38.pyc
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
39 changes: 20 additions & 19 deletions pocketoptionapi/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,25 +137,26 @@

class REGION:
REGIONS = {
# "EUROPA": "wss://api-eu.po.market/socket.io/?EIO=4&transport=websocket",
# "SEYCHELLES": "wss://api-sc.po.market/socket.io/?EIO=4&transport=websocket",
# "HONGKONG": "wss://api-hk.po.market/socket.io/?EIO=4&transport=websocket",
# "SERVER1": "wss://api-spb.po.market/socket.io/?EIO=4&transport=websocket",
# "FRANCE2": "wss://api-fr2.po.market/socket.io/?EIO=4&transport=websocket",
# "UNITED_STATES4": "wss://api-us4.po.market/socket.io/?EIO=4&transport=websocket",
# "UNITED_STATES3": "wss://api-us3.po.market/socket.io/?EIO=4&transport=websocket",
# "UNITED_STATES2": "wss://api-us2.po.market/socket.io/?EIO=4&transport=websocket",
"DEMO": "wss://demo-api-eu.po.market/socket.io/?EIO=4&transport=websocket",
# "DEMO_2": "wss://try-demo-eu.po.market/socket.io/?EIO=4&transport=websocket",
# "UNITED_STATES": "wss://api-us-north.po.market/socket.io/?EIO=4&transport=websocket",
# "RUSSIA": "wss://api-msk.po.market/socket.io/?EIO=4&transport=websocket",
# "SERVER2": "wss://api-l.po.market/socket.io/?EIO=4&transport=websocket",
# "INDIA": "wss://api-in.po.market/socket.io/?EIO=4&transport=websocket",
# "FRANCE": "wss://api-fr.po.market/socket.io/?EIO=4&transport=websocket",
# "FINLAND": "wss://api-fin.po.market/socket.io/?EIO=4&transport=websocket",
# "SERVER3": "wss://api-c.po.market/socket.io/?EIO=4&transport=websocket",
# "ASIA": "wss://api-asia.po.market/socket.io/?EIO=4&transport=websocket",
# "SERVER4": "wss://api-us-south.po.market/socket.io/?EIO=4&transport=websocket"
"DEMO": "wss://demo-api-eu.po.market/socket.io/?EIO=4&transport=websocket",
"DEMO_2": "wss://try-demo-eu.po.market/socket.io/?EIO=4&transport=websocket",
"EUROPA": "wss://api-eu.po.market/socket.io/?EIO=4&transport=websocket",
"SEYCHELLES": "wss://api-sc.po.market/socket.io/?EIO=4&transport=websocket",
"HONGKONG": "wss://api-hk.po.market/socket.io/?EIO=4&transport=websocket",
"SERVER1": "wss://api-spb.po.market/socket.io/?EIO=4&transport=websocket",
"FRANCE2": "wss://api-fr2.po.market/socket.io/?EIO=4&transport=websocket",
"UNITED_STATES4": "wss://api-us4.po.market/socket.io/?EIO=4&transport=websocket",
"UNITED_STATES3": "wss://api-us3.po.market/socket.io/?EIO=4&transport=websocket",
"UNITED_STATES2": "wss://api-us2.po.market/socket.io/?EIO=4&transport=websocket",

"UNITED_STATES": "wss://api-us-north.po.market/socket.io/?EIO=4&transport=websocket",
"RUSSIA": "wss://api-msk.po.market/socket.io/?EIO=4&transport=websocket",
"SERVER2": "wss://api-l.po.market/socket.io/?EIO=4&transport=websocket",
"INDIA": "wss://api-in.po.market/socket.io/?EIO=4&transport=websocket",
"FRANCE": "wss://api-fr.po.market/socket.io/?EIO=4&transport=websocket",
"FINLAND": "wss://api-fin.po.market/socket.io/?EIO=4&transport=websocket",
"SERVER3": "wss://api-c.po.market/socket.io/?EIO=4&transport=websocket",
"ASIA": "wss://api-asia.po.market/socket.io/?EIO=4&transport=websocket",
"SERVER4": "wss://api-us-south.po.market/socket.io/?EIO=4&transport=websocket"
}

def __getattr__(self, key):
Expand Down
4 changes: 4 additions & 0 deletions pocketoptionapi/global_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,7 @@
balance_updated = None
result = None
order_data = {}
order_open = []
order_closed = []
stat = []
DEMO = None
194 changes: 136 additions & 58 deletions pocketoptionapi/stable_api.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# This is a sample Python script.
import asyncio
import threading

import sys
from tzlocal import get_localzone

import json
from pocketoptionapi.api import PocketOptionAPI
import pocketoptionapi.constants as OP_code
# import pocketoptionapi.country_id as Country
Expand Down Expand Up @@ -36,10 +36,11 @@ def get_balance():
class PocketOption:
__version__ = "1.0.0"

def __init__(self, ssid):
def __init__(self, ssid,demo):
self.size = [1, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800,
3600, 7200, 14400, 28800, 43200, 86400, 604800, 2592000]
global_value.SSID = ssid
global_value.DEMO = demo
self.suspend = 0.5
self.thread = None
self.subscribe_candle = []
Expand All @@ -66,6 +67,8 @@ def __init__(self, ssid):

def get_server_timestamp(self):
return self.api.time_sync.server_timestamp
def Stop(self):
sys.exit()

def get_server_datetime(self):
return self.api.time_sync.server_datetime
Expand All @@ -86,6 +89,34 @@ def get_async_order_id(self, buy_order_id):

def start_async(self):
asyncio.run(self.api.connect())
def disconnect(self):
"""Gracefully close the WebSocket connection and clean up."""
try:
# Close the WebSocket connection
if global_value.websocket_is_connected:
asyncio.run(self.api.close()) # Use the close method from the PocketOptionAPI class
print("WebSocket connection closed successfully.")
else:
print("WebSocket was not connected.")

# Cancel any running asyncio tasks
if self.loop is not None:
for task in asyncio.all_tasks(self.loop):
task.cancel()

# If you were using a custom event loop, stop and close it
if not self.loop.is_closed():
self.loop.stop()
self.loop.close()
print("Event loop stopped and closed successfully.")

# Clean up the WebSocket thread if it's still running
if self.api.websocket_thread is not None and self.api.websocket_thread.is_alive():
self.api.websocket_thread.join()
print("WebSocket thread joined successfully.")

except Exception as e:
print(f"Error during disconnect: {e}")

def connect(self):
"""
Expand All @@ -101,6 +132,16 @@ def connect(self):
print(f"Error al conectar: {e}")
return False
return True

def GetPayout(self, pair):
data = self.api.GetPayoutData()
data = json.loads(data)
data2 = None
for i in data:
if i[1] == pair:
data2 = i

return data2[5]

@staticmethod
def check_connect():
Expand All @@ -121,7 +162,24 @@ def get_balance():
return global_value.balance
else:
return None

@staticmethod
def check_open():
#print(global_value.order_open)
return global_value.order_open
@staticmethod
def check_order_closed(ido):

while ido not in global_value.order_closed :
time.sleep(0.1)

for pack in global_value.stat :
if pack[0] == ido :
print('Order Closed',pack[1])

#print(global_value.order_closed)
return pack[0]


def buy(self, amount, active, action, expirations):
self.api.buy_multi_option = {}
self.api.buy_successful = None
Expand All @@ -139,6 +197,8 @@ def buy(self, amount, active, action, expirations):
global_value.order_data = None
global_value.result = None



self.api.buyv3(amount, active, action, expirations, req_id)

start_t = time.time()
Expand Down Expand Up @@ -202,59 +262,77 @@ def get_candles(self, active, period, start_time=None, count=6000, count_request
:param start_time: El tiempo final para la última vela.
:param count_request: El número de peticiones para obtener más datos históricos.
"""
if start_time is None:
time_sync = self.get_server_timestamp()
time_red = self.last_time(time_sync, period)
else:
time_red = start_time
time_sync = self.get_server_timestamp()

all_candles = []

for _ in range(count_request):
self.api.history_data = None

while True:
try:
# Enviar la petición de velas
self.api.getcandles(active, 30, count, time_red)

# Esperar hasta que history_data no sea None
while self.check_connect and self.api.history_data is None:
time.sleep(0.1)

if self.api.history_data is not None:
all_candles.extend(self.api.history_data)
break

except Exception as e:
logging.error(e)
# Puedes agregar lógica de reconexión aquí si es necesario

# Ordenar all_candles por 'index' para asegurar que estén en el orden correcto
all_candles = sorted(all_candles, key=lambda x: x["time"])

# Asegurarse de que se han recibido velas antes de actualizar time_red
if all_candles:
# Usar el tiempo de la última vela recibida para la próxima petición
time_red = all_candles[0]["time"]

# Crear un DataFrame con todas las velas obtenidas
df_candles = pd.DataFrame(all_candles)

# Ordenar por la columna 'time' de menor a mayor
df_candles = df_candles.sort_values(by='time').reset_index(drop=True)
df_candles['time'] = pd.to_datetime(df_candles['time'], unit='s')
df_candles.set_index('time', inplace=True)
df_candles.index = df_candles.index.floor('1s')

# Resamplear los datos en intervalos de 30 segundos y calcular open, high, low, close
df_resampled = df_candles['price'].resample(f'{period}s').ohlc()

# Resetear el índice para que 'time' vuelva a ser una columna
df_resampled.reset_index(inplace=True)

return df_resampled
try:
print("In try")
if start_time is None:
time_sync = self.get_server_timestamp()
time_red = self.last_time(time_sync, period)
else:
time_red = start_time
time_sync = self.get_server_timestamp()

all_candles = []

for _ in range(count_request):
self.api.history_data = None
print("In FOr Loop")

while True:
logging.info("Entered WHileloop in GetCandles")
print("In WHile loop")
try:
# Enviar la petición de velas
print("Before get candles")
self.api.getcandles(active, 30, count, time_red)
print("AFter get candles")

# Esperar hasta que history_data no sea None
for i in range(1, 100):
if self.api.history_data is None:
print(f"SLeeping, attempt: {i} / 100")
time.sleep(0.1)
if i == 99:
break

if self.api.history_data is not None:
print("In break")
all_candles.extend(self.api.history_data)
break

except Exception as e:
logging.error(e)
# Puedes agregar lógica de reconexión aquí si es necesario
#self.api.connect()

# Ordenar all_candles por 'index' para asegurar que estén en el orden correcto
all_candles = sorted(all_candles, key=lambda x: x["time"])

# Asegurarse de que se han recibido velas antes de actualizar time_red
if all_candles:
# Usar el tiempo de la última vela recibida para la próxima petición
time_red = all_candles[0]["time"]

# Crear un DataFrame con todas las velas obtenidas
df_candles = pd.DataFrame(all_candles)

# Ordenar por la columna 'time' de menor a mayor
df_candles = df_candles.sort_values(by='time').reset_index(drop=True)
df_candles['time'] = pd.to_datetime(df_candles['time'], unit='s')
df_candles.set_index('time', inplace=True)
df_candles.index = df_candles.index.floor('1s')

# Resamplear los datos en intervalos de 30 segundos y calcular open, high, low, close
df_resampled = df_candles['price'].resample(f'{period}s').ohlc()

# Resetear el índice para que 'time' vuelva a ser una columna
df_resampled.reset_index(inplace=True)

print("FINISHED!!!")

return df_resampled
except:
print("In except")
return None

@staticmethod
def process_data_history(data, period):
Expand Down Expand Up @@ -317,7 +395,7 @@ def process_candle(candle_data, period):
data_df.drop_duplicates(subset='time', keep="first", inplace=True)
data_df.reset_index(drop=True, inplace=True)
data_df.ffill(inplace=True)
data_df.drop(columns='symbol_id', inplace=True)
#data_df.drop(columns='symbol_id', inplace=True)
# Verificación opcional: Comprueba si las diferencias son todas de 60 segundos (excepto el primer valor NaN)
diferencias = data_df['time'].diff()
diff = (diferencias[1:] == period).all()
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.