Skip to content

response 41 after sending 42 auth session #4

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

Closed
vladdd183 opened this issue Feb 13, 2024 · 112 comments
Closed

response 41 after sending 42 auth session #4

vladdd183 opened this issue Feb 13, 2024 · 112 comments

Comments

@vladdd183
Copy link

vladdd183 commented Feb 13, 2024

Hello! I'm doing web socket reverse engineering too, ran into a problem, I'm doing the same as you:

  1. I connect to the web socket
  2. I get "0 sid..."
  3. Send "40" in response
  4. Receive message "40 sid..."
  5. I reply with "42 auth session"
  6. I get "41" in reply
async def process_message(message, websocket):
    print(message)
    if message.startswith('0{"sid":"'):
        message = message.lstrip("0")
        data = json.loads(message)
        print("got 0 sid send 40 ")
        await websocket.send("40")
    elif message == "2":
        print("got 2 send 3")
        await websocket.send("3")
    elif message.startswith('40{"sid":"'):
        print("got 40 sid send session")
        data = r"""42["auth",{"session":"a:4:{s:10:"session_id";s:32:"c53eec05c6f8a8be2d134d4fd55266f8";s:10:"ip_address";s:14:"46.138.176.190";s:10:"user_agent";s:101:"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";s:13:"last_activity";i:1707850603;}9f383935faff5a86bc1658bbde8c61e7","isDemo":1,"uid":72038016,"platform":3}]"""
        await websocket.send(data)

I don't understand what this is about, could you please advise me?
image

@theshadow76
Copy link
Collaborator

Yes, same here, I am getting the error of 41, I am going to try using webdriver, probably it's beeing blocked, so I will try that, but I am not giving up on this api that for sure :)

@theshadow76
Copy link
Collaborator

I'll tell you what happened, and if I recomend it.

@vladdd183
Copy link
Author

Okay, thank you very much. I'll keep trying and I'll tell you too if I find a solution :)

@vladdd183
Copy link
Author

vladdd183 commented Feb 13, 2024

image
image
image

@theshadow76
I've made progress.
It was the backslashes before the inverted commas.
Now we're getting binary data
However, after the first data is received, the disconnect occurs.

data = r'42["auth",{"session":"a:4:{s:10:\"session_id\";s:32:\"c53eec05c6f8a8be2d134d4fd55266f8\";s:10:\"ip_address\";s:14:\"46.138.176.190\";s:10:\"user_agent\";s:101:\"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36\";s:13:\"last_activity\";i:1707850603;}9f383935faff5a86bc1658bbde8c61e7","isDemo":1,"uid":72038016,"platform":3}]'

This is what the data should look like

Also you need "origin" header with website url, in my case: https://pocket-link19.co

            async with websockets.connect(
                "wss://api-eu.po.market/socket.io/?EIO=4&transport=websocket",
                extra_headers={
                    "Origin": "https://pocket-link19.co",
                },
            ) as websocket:

i am using "websockets" python library

so, to all you need:

  1. Backslashes
  2. Origin header

@vladdd183
Copy link
Author

i made a little mistake with reconnection, now it works good.
Also you need only Backslashes and Origin Header

@theshadow76
Copy link
Collaborator

Thank you very much!

@theshadow76
Copy link
Collaborator

I'll adjust the code

@theshadow76
Copy link
Collaborator

theshadow76 commented Feb 14, 2024

@vladdd183
Hello!
Sorry to bother you again, but here:

import urllib
import websocket
from pocketoptionapi.constants import REGION
import threading
import logging
import ssl

class WebSocketClient:
    def __init__(self, url, pocket_api_instance=None):
        self.url = url
        self.pocket_api_instance = pocket_api_instance
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.INFO)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

        # Create file handler and add it to the logger
        file_handler = logging.FileHandler('pocket.log')
        file_handler.setFormatter(formatter)
        self.logger.addHandler(file_handler)
        self.header = "Origin: https://google.com"
        self.ws = websocket.WebSocketApp(self.url,
                                         on_open=self.on_open,
                                         on_message=self.on_message,
                                         on_error=self.on_error,
                                         on_close=self.on_close,
                                         header=[self.header])
        self.logger.info("Starting websocket client...")

    def on_message(self, ws, message):
        print(f"Message: {message}")
        self.logger.info(f"Recieved a message!: {message}")

        if str(message).startswith('0{"sid":'):
            ws.send("40")
        if str(message).startswith('40{"sid"'):
            data = r'42["auth",{"session":"a:4:{s:10:\"session_id\";s:32:\"da7a5a82c8f6c35a87b2ee31d4f5b3b4\";s:10:\"ip_address\";s:10:\"90.36.9.15\";s:10:\"user_agent\";s:120:\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OP\";s:13:\"last_activity\";i:1707667599;}3a0058a58a6df5e7b49f652f8e4f8249","isDemo":0,"uid":27658142,"platform":1}]'
            print(f"Sent the auth messaage!: {data}")
            ws.send(data)
        

    def on_error(self, ws, error):
        print(error)
        self.logger.error(f"Got a error: {error}")

    def on_close(self, ws, close_status_code, close_msg):
        print("### closed ###")
        self.logger.warning(f"Connection closed, conections status_code: {close_status_code} and the message is: {close_msg}")

    def on_open(self, ws):
        print("Opened connection")
        self.logger.info("Opened!")

    def run(self):
        self.ws.run_forever()  # Use dispatcher for automatic reconnection

ws = WebSocketClient(url="wss://api-l.po.market/socket.io/?EIO=4&transport=websocket")
ws.run()

I am getting this output:

Opened connection
Message: 0{"sid":"s-DtcnSjnIgXZFuoNKB7","upgrades":[],"pingInterval":25000,"pingTimeout":20000,"maxPayload":1000000}
Message: 40{"sid":"aSAnWTMPfgSv-DKNNKCG"}
Sent the auth messaage!: 42["auth",{"session":"a:4:{s:10:\"session_id\";s:32:\"da7a5a82c8f6c35a87b2ee31d4f5b3b4\";s:10:\"ip_address\";s:10:\"90.36.9.15\";s:10:\"user_agent\";s:120:\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OP\";s:13:\"last_activity\";i:1707667599;}3a0058a58a6df5e7b49f652f8e4f8249","isDemo":0,"uid":27658142,"platform":1}]
Message: 41
### closed ###

looks like I am still getting that issue even tho I've added the hedears, but can you check if the data variable is the way it should be?
Maybe it had to be formated in a diferent way.

Let me know what you think!

@theshadow76 theshadow76 reopened this Feb 14, 2024
@theshadow76
Copy link
Collaborator

or if you would like to share your code, that would help alot to.
thx

@vladdd183
Copy link
Author

self.header = "Origin: https://google.com"

you shoud to set origin with site you using, not google
try:
https://po.trade/ (official link) or https://pocket-link19.co (mirror link)
official is prefered, use mirror only if official link banned in your country

@theshadow76
Copy link
Collaborator

Okey, let me check and I'll let you know

@vladdd183
Copy link
Author

I use "websockets" library and "anyio" for async, also "rich" for better print formating
pip3 install websockets anyio rich

this is the code (try to use second origin, that commented):

import websockets
import anyio
from rich.pretty import pprint as print
import json

SESSION = r'session_string'


async def websocket_client(url, pro):
    while True:
        try:
            async with websockets.connect(
                url,
                extra_headers={
                    "Origin": "https://pocket-link19.co",
                    # "Origin": "https://po.trade/"
                },
            ) as websocket:
                async for message in websocket:
                    await pro(message, websocket, url)
        except KeyboardInterrupt:
            exit()
        except Exception as e:
            print(e)
            print("Connection lost... reconnecting")
            await anyio.sleep(5)
    return True


async def pro(message, websocket, url):
    # if byte data
    if type(message) == type(b""):
        # cut 100 first symbols of byte date to prevent spam
        print(str(message)[:100])
        return
    else:
        print(message)

    # Code to make order
    # data = r'42["openOrder",{"asset":"#AXP_otc","amount":1,"action":"call","isDemo":1,"requestId":14680035,"optionType":100,"time":20}]'
    # await websocket.send(data)

    if message.startswith('0{"sid":"'):
        print(f"{url.split('/')[2]} got 0 sid send 40 ")
        await websocket.send("40")
    elif message == "2":
        # ping-pong thing
        print(f"{url.split('/')[2]} got 2 send 3")
        await websocket.send("3")

    if message.startswith('40{"sid":"'):
        print(f"{url.split('/')[2]} got 40 sid send session")
        await websocket.send(SESSION)


async def main():
    url = "wss://api-l.po.market/socket.io/?EIO=4&transport=websocket"
    await websocket_client(url, pro)


if __name__ == "__main__":
    anyio.run(main)

@theshadow76
Copy link
Collaborator

Thank you alot, I'll finish implementing it soon!
Thanks for your help!!!

@vladdd183
Copy link
Author

i tried to found error in your code, it's looks pretty similar to my. Headers has set, should work with the origin, but not working. I think it error with library, try to use "websockets" and async

@vladdd183
Copy link
Author

now i am working on login-password auth system

@vladdd183
Copy link
Author

write me after testing my version

@theshadow76
Copy link
Collaborator

Ok

@vladdd183
Copy link
Author

vladdd183 commented Feb 14, 2024

also write code for selenium to get session string by login+password

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import urllib.parse


def test_d():
    driver = webdriver.Firefox()
    driver.get("https://pocket-link19.co/ru/login")  # https://po.trade/login
    driver.set_window_size(550, 691)
    driver.find_element(By.NAME, "email").click()
    driver.find_element(By.NAME, "email").send_keys("email@mail.com")  # email@mail.com
    driver.find_element(By.NAME, "password").click()
    driver.find_element(By.NAME, "password").send_keys("password")  # password
    driver.find_element(By.CSS_SELECTOR, ".waves").click()
    WebDriverWait(driver, 30).until(
        expected_conditions.presence_of_element_located((By.CSS_SELECTOR, ".layer"))
    )
    # For demo:
    driver.get(
        "https://pocket-link19.co/ru/cabinet/demo-quick-high-low/"
    )  # https://po.trade/cabinet/demo-quick-high-low/
    WebDriverWait(driver, 30).until(
        expected_conditions.presence_of_element_located((By.CSS_SELECTOR, ".layer"))
    )
    cookies = driver.get_cookies()
    session_token = [x["value"] for x in cookies if x["name"] == "ci_session"][0]
    decoded_string = urllib.parse.unquote(session_token)
    print(decoded_string)

    driver.quit()


test_d()

tried to do it with requests, but have no successful

this code might help to get session string easily, but don't forget to add backslashes

@vladdd183
Copy link
Author

vladdd183 commented Feb 15, 2024

also to make order you need requestId, that make from current time + random number

        def generate_request_id():
            now = int(time.time()) + random.randint(1, 100)
            return now

        a = generate_request_id()
        data = '42["openOrder",{"asset":"BTCUSD","amount":10,"action":"call","isDemo":1,"requestId":{a},"optionType":100,"time":60}]'.replace('{a}', str(a))

@theshadow76
Copy link
Collaborator

Thank you so much.
As of right now I am with bad internet, so I don't think I'll be able to keep coding today, maybe tomorrow I will, not sure.

But thx.

@vladdd183
Copy link
Author

you are welcome

@theshadow76
Copy link
Collaborator

Hello! Sorry to bother you again
I am getting this error from cloudflare:

InvalidStatusCode(200, Headers([('Date', 'Thu, 11 Apr 2024 00:16:11 GMT'), ('Content-Type', 'text/html; charset=UTF-8'), ('Transfer-Encoding', 'chunked'), ('Connection', 'keep-alive'), ('X-Powered-By', 'PHP/8.3.4'), ('CF-Cache-Status', 'DYNAMIC'), ('Report-To', '{"endpoints":[{"url":"https:\\/\\/a.nel.cloudflare.com\\/report\\/v4?s=yJUynuTPCFrZNgmZpVgaDvlopmmCvS%2B59bldFgohoZ%2FijFTGdv2VL3R46Y5A02lCxhofJXp1b2UWx7Ov8mQEeq%2FTBOk2HGgdctK1H0Z13hOVzlxJALZkBOZ0bTZHD56d4rz9pQ7Ez%2FyVClrg84A%3D"}],"group":"cf-nel","max_age":604800}'), ('NEL', '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}'), ('Server', 'cloudflare'), ('CF-RAY', '8726c950ef9fd772-SCL'), ('alt-svc', 'h3=":443"; ma=86400')]))
'Connection lost... reconnecting'

in this code

@theshadow76 theshadow76 reopened this Apr 11, 2024
@theshadow76
Copy link
Collaborator

@vladdd183 do you know what could be the issue?

@vladdd183
Copy link
Author

vladdd183 commented Apr 11, 2024

@theshadow76 Hi!
you dont use "i" for url. You need change url to i

async def websocket_client(url, pro):
    for i in REGION.get_regions(REGION):
        print(f"Trying {i}...")
        try:
            async with websockets.connect(
 >>>>>    i, #url,
                extra_headers={
                    #"Origin": "https://pocket-link33.co",
                    "Origin": "https://po.trade/"
                },

@vladdd183
Copy link
Author

image
That error means that you cannot connect to websocket for this region, so you need find region able to connect, if you change "url" to "i" it will find correct region websocket

@chema2411
Copy link
Contributor

This function self.get_server_timestamp() returns the value of the websockets messages, which is obtained from a function called send_message with await from the asyncio library

@theshadow76
Copy link
Collaborator

Discord or telegram?

@chema2411
Copy link
Contributor

Discord

@theshadow76
Copy link
Collaborator

https://discord.com/invite/rZyaxYnd

@vladdd183
Copy link
Author

https://discord.com/invite/rZyaxYnd

Add this to readme

@theshadow76
Copy link
Collaborator

Ok

@theshadow76 theshadow76 pinned this issue May 9, 2024
@glaucoguima
Copy link

Can anyone help me, I would like to send a signal to the Telegram group with this API

@shadles404
Copy link

i got something and want to know what is it if possible

@theshadow76
Copy link
Collaborator

Talk to us here: https://discord.com/invite/rZyaxYnd

@shadles404
Copy link

Talk to us here: https://discord.com/invite/rZyaxYnd
invalid
send me the invitation again

@theshadow76
Copy link
Collaborator

@briancg42
Copy link

Hey @theshadow76, great work with this repo! I would like to join to the Discord server if possible. Thank you in advance!

@theshadow76
Copy link
Collaborator

https://discord.com/invite/Ge2yXheP

@theshadow76
Copy link
Collaborator

@briancg42

@thacku
Copy link

thacku commented Jun 10, 2024

https://discord.com/invite/Ge2yXheP

It's invalid, can you provide new link to this

@theshadow76
Copy link
Collaborator

https://discord.com/invite/Ge2yXheP

It's invalid, can you provide new link to this

https://discord.com/invite/XmQ6vzFQAT

@erfangnu
Copy link

@theshadow76 Hi, how can install this python package via pip?

@theshadow76
Copy link
Collaborator

You need to use git, talk to us in discord https://discord.com/invite/XmQ6vzFQAT

@briancg42
Copy link

Thank you! ⚡

@sumittale5654
Copy link

can anyone tell how i resolve the pocketoptionapi module not found

@WanuPhiri
Copy link

I have a problem and I do not know how big or how to proceed.... I created a bot but when I run it I get this error. I think the pocketoptionapi modules are not well installed or not correct or the websockets issue. I need help to connect to Pocket Option

WARNING:root:WebSocket connection closed: received 1005 (no status received [internal]); then sent 1005 (no status received [internal])
ERROR:root:Error sending ping: received 1005 (no status received [internal]); then sent 1005 (no status received [internal])

I do not have pocketoptionapi so I am trying to use ssid

AttributeError: 'PocketOption' object has no attribute 'change_balance'
ERROR:root:Error sending ping: received 1005 (no status received [internal]); then sent 1005 (no status received [internal])
ERROR:root:Error sending ping: received 1005 (no status received [internal]); then sent 1005 (no status received [internal])
botw

from pocketoptionapi import global_value
from pocketoptionapi.stable_api import PocketOption # Ensure this is correctly installed and imported
import time
import threading
import asyncio
import websockets
import ssl

Replace with your session ID

ssid = "mc4i2u7c721ajl9u0sr779jq8q" # Your valid session ID

Initialize PocketOption API with SSID

API = PocketOption(ssid)

Connect to the API

check = API.connect()
if not check:
print("Connection failed.")
exit()

THIS IS JUST THE SECTION OF THE CODE WHERE I HAD TO INPUT SSID

PLEASE HELP - THANK YOU

@theshadow76
Copy link
Collaborator

I have a problem and I do not know how big or how to proceed.... I created a bot but when I run it I get this error. I think the pocketoptionapi modules are not well installed or not correct or the websockets issue. I need help to connect to Pocket Option

WARNING:root:WebSocket connection closed: received 1005 (no status received [internal]); then sent 1005 (no status received [internal]) ERROR:root:Error sending ping: received 1005 (no status received [internal]); then sent 1005 (no status received [internal])

I do not have pocketoptionapi so I am trying to use ssid

AttributeError: 'PocketOption' object has no attribute 'change_balance' ERROR:root:Error sending ping: received 1005 (no status received [internal]); then sent 1005 (no status received [internal]) ERROR:root:Error sending ping: received 1005 (no status received [internal]); then sent 1005 (no status received [internal]) botw

from pocketoptionapi import global_value from pocketoptionapi.stable_api import PocketOption # Ensure this is correctly installed and imported import time import threading import asyncio import websockets import ssl

Replace with your session ID

ssid = "mc4i2u7c721ajl9u0sr779jq8q" # Your valid session ID

Initialize PocketOption API with SSID

API = PocketOption(ssid)

Connect to the API

check = API.connect() if not check: print("Connection failed.") exit()

THIS IS JUST THE SECTION OF THE CODE WHERE I HAD TO INPUT SSID

PLEASE HELP - THANK YOU

Hello! Please download the latest version here: https://github.com/theshadow76/PocketOptionAPI/releases/tag/v1.0.0

and if you still have issues, please enter to our discord server: https://discord.gg/H8er9mbF4V

@theshadow76 theshadow76 reopened this Sep 12, 2024
@theshadow76
Copy link
Collaborator

can anyone tell how i resolve the pocketoptionapi module not found

Please talk to us here: https://discord.gg/H8er9mbF4V

@WanuPhiri
Copy link

AttributeError: 'PocketOption' object has no attribute 'get_current_price'

how can i resolve this error I am stuck. please help

@Mdbaizidtanvir
Copy link

how can i get this real time candle : " from pocketoptionapi.stable_api import PocketOption
import time

SSID: The session ID to authenticate with PocketOption

ssid = r"""42["auth",{"session":"a:4:{s:10:"session_id";s:32:"47f30c18560908460f79392abb5e2ea0";s:10:"ip_address";s:15:"103.167.208.249";s:10:"user_agent";s:111:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36";s:13:"last_activity";i:1728768861;}52f0fbcaac716f54f471b6030a4434b9","isDemo":0,"uid":72758516,"platform":2}]"""

Initialize the PocketOption API, with demo set to True for safety

API = PocketOption(ssid, demo=True)

Connect to the API

check = API.connect()

if check:
try:
# Get the demo account balance
print(f'Demo Balance: {API.get_balance()}')

    # Define the asset, candle period, and offset to retrieve candles
    asset = "EURUSD"
    current_time = int(time.time())  # Current time as timestamp
    offset = 120  # Get candles from 120 seconds before current time
    period = 60  # Candle size of 60 seconds (1 minute)

    print(f"You will get the candle from: {current_time - offset} to: {current_time}")
    print("------\n")

    # Fetch the candle data for the specified asset and time period
    candle = API.get_candles(active=asset, period=period, start_time=current_time - offset, count=6000, count_request=1)
    
    # Output the candle data
    print(candle)

    # Place a Buy order (Call)
    amount = 1  # Define how much you want to trade (e.g., 1 unit)
    expiration = 1  # Trade expiration time in minutes (example: 1 minute)
    action = 'call'  # "call" for buy/up, "put" for sell/down

    # Execute the buy order
    buy_order = API.buy(amount=amount, active=asset, action=action, expirations=expiration)

    # Output the result of the buy order
    if buy_order:
        print(f"Buy order placed successfully: {buy_order}")
    else:
        print("Failed to place the buy order.")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Disconnect from the API
    API.disconnect()

else:
print("Failed to connect to PocketOption API.")
" " i am geting this error WARNING:root:Error occurred: 'isDemo'

@ALEXKODERODESSA
Copy link

Hi. I studied your project pocketoptionapi on githab. Tell me, did you manage to connect to pocketoption market data in real time? I have a ready-made program for automated trading on this broker. It remains only to connect directly to the broker's market data. At the moment, I use ticks from tradermade.com and I see a slight discrepancy in price movement compared to pocketoption. If you have a solution for connecting to real-time market data for pocketoption, then I will be very grateful for your help and will send you my program for automated trading. It will not be superfluous in the household. Here is a link to a video with my bot https://www.youtube.com/watch?v=wTnscfLpqjo&t=62s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests