forked from ChipaDevTeam/PocketOptionAPI
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
1403 lines (1205 loc) · 53.8 KB
/
client.py
File metadata and controls
1403 lines (1205 loc) · 53.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Professional Async PocketOption API Client
"""
import asyncio
import json
import time
import uuid
from typing import Optional, List, Dict, Any, Union, Callable
from datetime import datetime, timedelta
from collections import defaultdict
import pandas as pd
from loguru import logger
from .monitoring import error_monitor, health_checker, ErrorCategory, ErrorSeverity
from .websocket_client import AsyncWebSocketClient
from .models import (
Balance,
Candle,
Order,
OrderResult,
OrderStatus,
OrderDirection,
ServerTime,
)
from .constants import ASSETS, REGIONS, TIMEFRAMES, API_LIMITS
from .exceptions import (
PocketOptionError,
ConnectionError,
AuthenticationError,
OrderError,
InvalidParameterError,
)
class AsyncPocketOptionClient:
"""
Professional async PocketOption API client with modern Python practices
"""
def __init__(
self,
ssid: str,
is_demo: bool = True,
region: Optional[str] = None,
uid: int = 0,
platform: int = 1,
is_fast_history: bool = True,
persistent_connection: bool = False,
auto_reconnect: bool = True,
enable_logging: bool = True,
):
"""
Initialize async PocketOption client with enhanced monitoring
Args:
ssid: Complete SSID string or raw session ID for authentication
is_demo: Whether to use demo account
region: Preferred region for connection
uid: User ID (if providing raw session)
platform: Platform identifier (1=web, 3=mobile)
is_fast_history: Enable fast history loading
persistent_connection: Enable persistent connection with keep-alive (like old API)
auto_reconnect: Enable automatic reconnection on disconnection
enable_logging: Enable detailed logging (default: True)
"""
self.raw_ssid = ssid
self.is_demo = is_demo
self.preferred_region = region
self.uid = uid
self.platform = platform
self.is_fast_history = is_fast_history
self.persistent_connection = persistent_connection
self.auto_reconnect = auto_reconnect
self.enable_logging = enable_logging
# Configure logging based on preference
if not enable_logging:
logger.remove()
logger.add(lambda msg: None, level="CRITICAL") # Disable most logging
# Parse SSID if it's a complete auth message
self._original_demo = None # Store original demo value from SSID
if ssid.startswith('42["auth",'):
self._parse_complete_ssid(ssid)
else:
# Treat as raw session ID
self.session_id = ssid
self._complete_ssid = None
# Core components
self._websocket = AsyncWebSocketClient()
self._balance: Optional[Balance] = None
self._orders: Dict[str, OrderResult] = {}
self._active_orders: Dict[str, OrderResult] = {}
self._order_results: Dict[str, OrderResult] = {}
self._candles_cache: Dict[str, List[Candle]] = {}
self._server_time: Optional[ServerTime] = None
self._event_callbacks: Dict[str, List[Callable]] = defaultdict(list)
# Setup event handlers for websocket messages
self._setup_event_handlers()
# Add handler for JSON data messages (contains detailed order data)
self._websocket.add_event_handler("json_data", self._on_json_data)
# Enhanced monitoring and error handling
self._error_monitor = error_monitor
self._health_checker = health_checker
# Performance tracking
self._operation_metrics: Dict[str, List[float]] = defaultdict(list)
self._last_health_check = time.time()
# Keep-alive functionality (based on old API patterns)
self._keep_alive_manager = None
self._ping_task: Optional[asyncio.Task] = None
self._reconnect_task: Optional[asyncio.Task] = None
self._is_persistent = False
# Connection statistics (like old API)
self._connection_stats = {
"total_connections": 0,
"successful_connections": 0,
"total_reconnects": 0,
"last_ping_time": None,
"messages_sent": 0,
"messages_received": 0,
"connection_start_time": None,
}
logger.info(
f"Initialized PocketOption client (demo={is_demo}, uid={self.uid}, persistent={persistent_connection}) with enhanced monitoring"
if enable_logging
else ""
)
def _setup_event_handlers(self):
"""Setup WebSocket event handlers"""
self._websocket.add_event_handler("authenticated", self._on_authenticated)
self._websocket.add_event_handler("balance_updated", self._on_balance_updated)
self._websocket.add_event_handler(
"balance_data", self._on_balance_data
) # Add balance_data handler
self._websocket.add_event_handler("order_opened", self._on_order_opened)
self._websocket.add_event_handler("order_closed", self._on_order_closed)
self._websocket.add_event_handler("stream_update", self._on_stream_update)
self._websocket.add_event_handler("candles_received", self._on_candles_received)
self._websocket.add_event_handler("disconnected", self._on_disconnected)
async def connect(
self, regions: Optional[List[str]] = None, persistent: Optional[bool] = None
) -> bool:
"""
Connect to PocketOption with multiple region support
Args:
regions: List of regions to try (uses defaults if None)
persistent: Override persistent connection setting
Returns:
bool: True if connected successfully
"""
logger.info("Connecting to PocketOption...")
# Update persistent setting if provided
if persistent is not None:
self.persistent_connection = bool(persistent)
try:
if self.persistent_connection:
return await self._start_persistent_connection(regions)
else:
return await self._start_regular_connection(regions)
except Exception as e:
logger.error(f"Connection failed: {e}")
await self._error_monitor.record_error(
error_type="connection_failed",
severity=ErrorSeverity.HIGH,
category=ErrorCategory.CONNECTION,
message=f"Connection failed: {e}",
)
return False
async def _start_regular_connection(
self, regions: Optional[List[str]] = None
) -> bool:
"""Start regular connection (existing behavior)"""
logger.info("Starting regular connection...")
# Use appropriate regions based on demo mode
if not regions:
if self.is_demo:
# For demo mode, only use demo regions
demo_urls = REGIONS.get_demo_regions()
regions = []
all_regions = REGIONS.get_all_regions()
for name, url in all_regions.items():
if url in demo_urls:
regions.append(name)
logger.info(f"Demo mode: Using demo regions: {regions}")
else:
# For live mode, use all regions except demo
all_regions = REGIONS.get_all_regions()
regions = [
name
for name, url in all_regions.items()
if "DEMO" not in name.upper()
]
logger.info(f"Live mode: Using non-demo regions: {regions}")
# Update connection stats
self._connection_stats["total_connections"] += 1
self._connection_stats["connection_start_time"] = time.time()
for region in regions:
try:
region_url = REGIONS.get_region(region)
if not region_url:
continue
urls = [region_url] # Convert single URL to list
logger.info(f"Trying region: {region} with URL: {region_url}")
# Try to connect
ssid_message = self._format_session_message()
success = await self._websocket.connect(urls, ssid_message)
if success:
logger.info(f" Connected to region: {region}")
# Wait for authentication
await self._wait_for_authentication()
# Initialize data
await self._initialize_data()
# Start keep-alive tasks
await self._start_keep_alive_tasks()
self._connection_stats["successful_connections"] += 1
logger.info("Successfully connected and authenticated")
return True
except Exception as e:
logger.warning(f"Failed to connect to region {region}: {e}")
continue
return False
async def _start_persistent_connection(
self, regions: Optional[List[str]] = None
) -> bool:
"""Start persistent connection with keep-alive (like old API)"""
logger.info("Starting persistent connection with automatic keep-alive...")
# Import the keep-alive manager
from .connection_keep_alive import ConnectionKeepAlive
# Create keep-alive manager
complete_ssid = self.raw_ssid
self._keep_alive_manager = ConnectionKeepAlive(complete_ssid, self.is_demo)
# Add event handlers
self._keep_alive_manager.add_event_handler(
"connected", self._on_keep_alive_connected
)
self._keep_alive_manager.add_event_handler(
"reconnected", self._on_keep_alive_reconnected
)
self._keep_alive_manager.add_event_handler(
"message_received", self._on_keep_alive_message
)
# Add handlers for forwarded WebSocket events
self._keep_alive_manager.add_event_handler(
"balance_data", self._on_balance_data
)
self._keep_alive_manager.add_event_handler(
"balance_updated", self._on_balance_updated
)
self._keep_alive_manager.add_event_handler(
"authenticated", self._on_authenticated
)
self._keep_alive_manager.add_event_handler(
"order_opened", self._on_order_opened
)
self._keep_alive_manager.add_event_handler(
"order_closed", self._on_order_closed
)
self._keep_alive_manager.add_event_handler(
"stream_update", self._on_stream_update
)
self._keep_alive_manager.add_event_handler("json_data", self._on_json_data)
# Connect with keep-alive
success = await self._keep_alive_manager.connect_with_keep_alive(regions)
if success:
self._is_persistent = True
logger.info(" Persistent connection established successfully")
return True
else:
logger.error("Failed to establish persistent connection")
return False
async def _start_keep_alive_tasks(self):
"""Start keep-alive tasks for regular connection"""
logger.info("Starting keep-alive tasks for regular connection...")
# Start ping task (like old API)
self._ping_task = asyncio.create_task(self._ping_loop())
# Start reconnection monitor if auto_reconnect is enabled
if self.auto_reconnect:
self._reconnect_task = asyncio.create_task(self._reconnection_monitor())
async def _ping_loop(self):
"""Ping loop for regular connections (like old API)"""
while self.is_connected and not self._is_persistent:
try:
await self._websocket.send_message('42["ps"]')
self._connection_stats["last_ping_time"] = time.time()
await asyncio.sleep(20) # Ping every 20 seconds
except Exception as e:
logger.warning(f"Ping failed: {e}")
break
async def _reconnection_monitor(self):
"""Monitor and handle reconnections for regular connections"""
while self.auto_reconnect and not self._is_persistent:
await asyncio.sleep(30) # Check every 30 seconds
if not self.is_connected:
logger.info("Connection lost, attempting reconnection...")
self._connection_stats["total_reconnects"] += 1
try:
success = await self._start_regular_connection()
if success:
logger.info(" Reconnection successful")
else:
logger.error("Reconnection failed")
await asyncio.sleep(10) # Wait before next attempt
except Exception as e:
logger.error(f"Reconnection error: {e}")
await asyncio.sleep(10)
async def disconnect(self) -> None:
"""Disconnect from PocketOption and cleanup all resources"""
logger.info("Disconnecting from PocketOption...")
# Cancel tasks
if self._ping_task:
self._ping_task.cancel()
if self._reconnect_task:
self._reconnect_task.cancel()
# Disconnect based on connection type
if self._is_persistent and self._keep_alive_manager:
await self._keep_alive_manager.disconnect()
else:
await self._websocket.disconnect()
# Reset state
self._is_persistent = False
self._balance = None
self._orders.clear()
logger.info("Disconnected successfully")
async def get_balance(self) -> Balance:
"""
Get current account balance
Returns:
Balance: Current balance information
"""
if not self.is_connected:
raise ConnectionError("Not connected to PocketOption")
# Request balance update if needed
if (
not self._balance
or (datetime.now() - self._balance.last_updated).seconds > 60
):
await self._request_balance_update()
# Wait a bit for balance to be received
await asyncio.sleep(1)
if not self._balance:
raise PocketOptionError("Balance data not available")
return self._balance
async def place_order(
self, asset: str, amount: float, direction: OrderDirection, duration: int
) -> OrderResult:
"""
Place a binary options order
Args:
asset: Asset symbol (e.g., "EURUSD_otc")
amount: Order amount
direction: OrderDirection.CALL or OrderDirection.PUT
duration: Duration in seconds
Returns:
OrderResult: Order placement result
"""
if not self.is_connected:
raise ConnectionError("Not connected to PocketOption")
# Validate parameters
self._validate_order_parameters(asset, amount, direction, duration)
try:
# Create order
order_id = str(uuid.uuid4())
order = Order(
asset=asset,
amount=amount,
direction=direction,
duration=duration,
request_id=order_id, # Use request_id, not order_id
) # Send order
await self._send_order(order)
# Wait for result (this will either get the real server response or create a fallback)
result = await self._wait_for_order_result(order_id, order)
# Don't store again - _wait_for_order_result already handles storage
logger.info(f"Order placed: {result.order_id} - {result.status}")
return result
except Exception as e:
logger.error(f"Order placement failed: {e}")
raise OrderError(f"Failed to place order: {e}")
async def get_candles(
self,
asset: str,
timeframe: Union[str, int],
count: int = 100,
end_time: Optional[datetime] = None,
) -> List[Candle]:
"""
Get historical candle data with automatic reconnection
Args:
asset: Asset symbol
timeframe: Timeframe (e.g., "1m", "5m", 60)
count: Number of candles to retrieve
end_time: End time for data (defaults to now)
Returns:
List[Candle]: Historical candle data
"""
# Check connection and attempt reconnection if needed
if not self.is_connected:
if self.auto_reconnect:
logger.info(
f"Connection lost, attempting reconnection for {asset} candles..."
)
reconnected = await self._attempt_reconnection()
if not reconnected:
raise ConnectionError(
"Not connected to PocketOption and reconnection failed"
)
else:
raise ConnectionError("Not connected to PocketOption")
# Convert timeframe to seconds
if isinstance(timeframe, str):
timeframe_seconds = TIMEFRAMES.get(timeframe, 60)
else:
timeframe_seconds = timeframe
# Validate asset
if asset not in ASSETS:
raise InvalidParameterError(f"Invalid asset: {asset}")
# Set default end time
if not end_time:
end_time = datetime.now()
max_retries = 2
for attempt in range(max_retries):
try:
# Request candle data
candles = await self._request_candles(
asset, timeframe_seconds, count, end_time
)
# Cache results
cache_key = f"{asset}_{timeframe_seconds}"
self._candles_cache[cache_key] = candles
logger.info(f"Retrieved {len(candles)} candles for {asset}")
return candles
except Exception as e:
if "WebSocket is not connected" in str(e) and attempt < max_retries - 1:
logger.warning(
f"Connection lost during candle request for {asset}, attempting reconnection..."
)
if self.auto_reconnect:
reconnected = await self._attempt_reconnection()
if reconnected:
logger.info(
f" Reconnected, retrying candle request for {asset}"
)
continue
logger.error(f"Failed to get candles for {asset}: {e}")
raise PocketOptionError(f"Failed to get candles: {e}")
raise PocketOptionError(f"Failed to get candles after {max_retries} attempts")
async def get_candles_dataframe(
self,
asset: str,
timeframe: Union[str, int],
count: int = 100,
end_time: Optional[datetime] = None,
) -> pd.DataFrame:
"""
Get historical candle data as DataFrame
Args:
asset: Asset symbol
timeframe: Timeframe (e.g., "1m", "5m", 60)
count: Number of candles to retrieve
end_time: End time for data (defaults to now)
Returns:
pd.DataFrame: Historical candle data
"""
candles = await self.get_candles(asset, timeframe, count, end_time)
# Convert to DataFrame
data = []
for candle in candles:
data.append(
{
"timestamp": candle.timestamp,
"open": candle.open,
"high": candle.high,
"low": candle.low,
"close": candle.close,
"volume": candle.volume,
}
)
df = pd.DataFrame(data)
if not df.empty:
df.set_index("timestamp", inplace=True)
df.sort_index(inplace=True)
return df
async def check_order_result(self, order_id: str) -> Optional[OrderResult]:
"""
Check the result of a specific order
Args:
order_id: Order ID to check
Returns:
OrderResult: Order result or None if not found
"""
# First check active orders
if order_id in self._active_orders:
return self._active_orders[order_id]
# Then check completed orders
if order_id in self._order_results:
return self._order_results[order_id]
# Not found
return None
async def get_active_orders(self) -> List[OrderResult]:
"""
Get all active orders
Returns:
List[OrderResult]: Active orders
"""
return list(self._active_orders.values())
def add_event_callback(self, event: str, callback: Callable) -> None:
"""
Add event callback
Args:
event: Event name (e.g., 'order_closed', 'balance_updated')
callback: Callback function
"""
if event not in self._event_callbacks:
self._event_callbacks[event] = []
self._event_callbacks[event].append(callback)
def remove_event_callback(self, event: str, callback: Callable) -> None:
"""
Remove event callback
Args:
event: Event name
callback: Callback function to remove
"""
if event in self._event_callbacks:
try:
self._event_callbacks[event].remove(callback)
except ValueError:
pass
@property
def is_connected(self) -> bool:
"""Check if client is connected (including persistent connections)"""
if self._is_persistent and self._keep_alive_manager:
return self._keep_alive_manager.is_connected
else:
return self._websocket.is_connected
@property
def connection_info(self):
"""Get connection information (including persistent connections)"""
if self._is_persistent and self._keep_alive_manager:
return self._keep_alive_manager.connection_info
else:
return self._websocket.connection_info
async def send_message(self, message: str) -> bool:
"""Send message through active connection"""
try:
if self._is_persistent and self._keep_alive_manager:
return await self._keep_alive_manager.send_message(message)
else:
await self._websocket.send_message(message)
return True
except Exception as e:
logger.error(f"Failed to send message: {e}")
return False
def get_connection_stats(self) -> Dict[str, Any]:
"""Get comprehensive connection statistics"""
stats = self._connection_stats.copy()
if self._is_persistent and self._keep_alive_manager:
stats.update(self._keep_alive_manager.get_stats())
else:
stats.update(
{
"websocket_connected": self._websocket.is_connected,
"connection_info": self._websocket.connection_info,
}
)
return stats # Private methods
def _format_session_message(self) -> str:
"""Format session authentication message"""
# Always create auth message from components using constructor parameters
# This ensures is_demo parameter is respected regardless of SSID format
auth_data = {
"session": self.session_id,
"isDemo": 1 if self.is_demo else 0,
"uid": self.uid,
"platform": self.platform,
}
if self.is_fast_history:
auth_data["isFastHistory"] = True
return f'42["auth",{json.dumps(auth_data)}]'
def _parse_complete_ssid(self, ssid: str) -> None:
"""Parse complete SSID auth message to extract components"""
try:
# Extract JSON part
json_start = ssid.find("{")
json_end = ssid.rfind("}") + 1
if json_start != -1 and json_end > json_start:
json_part = ssid[json_start:json_end]
data = json.loads(json_part)
self.session_id = data.get("session", "")
# Store original demo value from SSID, but don't override the constructor parameter
self._original_demo = bool(data.get("isDemo", 1))
# Keep the is_demo value from constructor - don't override it
self.uid = data.get("uid", 0)
self.platform = data.get("platform", 1)
# Don't store complete SSID - we'll reconstruct it with correct demo value
self._complete_ssid = None
except Exception as e:
logger.warning(f"Failed to parse SSID: {e}")
self.session_id = ssid
self._complete_ssid = None
async def _wait_for_authentication(self, timeout: float = 10.0) -> None:
"""Wait for authentication to complete (like old API)"""
auth_received = False
def on_auth(data):
nonlocal auth_received
auth_received = True
# Add temporary handler
self._websocket.add_event_handler("authenticated", on_auth)
try:
# Wait for authentication
start_time = time.time()
while not auth_received and (time.time() - start_time) < timeout:
await asyncio.sleep(0.1)
if not auth_received:
raise AuthenticationError("Authentication timeout")
finally:
# Remove temporary handler
self._websocket.remove_event_handler("authenticated", on_auth)
async def _initialize_data(self) -> None:
"""Initialize client data after connection"""
# Request initial balance
await self._request_balance_update()
# Setup time synchronization
await self._setup_time_sync()
async def _request_balance_update(self) -> None:
"""Request balance update from server"""
message = '42["getBalance"]'
# Use appropriate connection method
if self._is_persistent and self._keep_alive_manager:
await self._keep_alive_manager.send_message(message)
else:
await self._websocket.send_message(message)
async def _setup_time_sync(self) -> None:
"""Setup server time synchronization"""
# This would typically involve getting server timestamp
# For now, create a basic time sync object
local_time = datetime.now().timestamp()
self._server_time = ServerTime(
server_timestamp=local_time, local_timestamp=local_time, offset=0.0
)
def _validate_order_parameters(
self, asset: str, amount: float, direction: OrderDirection, duration: int
) -> None:
"""Validate order parameters"""
if asset not in ASSETS:
raise InvalidParameterError(f"Invalid asset: {asset}")
if (
amount < API_LIMITS["min_order_amount"]
or amount > API_LIMITS["max_order_amount"]
):
raise InvalidParameterError(
f"Amount must be between {API_LIMITS['min_order_amount']} and {API_LIMITS['max_order_amount']}"
)
if (
duration < API_LIMITS["min_duration"]
or duration > API_LIMITS["max_duration"]
):
raise InvalidParameterError(
f"Duration must be between {API_LIMITS['min_duration']} and {API_LIMITS['max_duration']} seconds"
)
async def _send_order(self, order: Order) -> None:
"""Send order to server"""
# Format asset name with # prefix if not already present
asset_name = order.asset
# Create the message in the correct PocketOption format
message = f'42["openOrder",{{"asset":"{asset_name}","amount":{order.amount},"action":"{order.direction.value}","isDemo":{1 if self.is_demo else 0},"requestId":"{order.request_id}","optionType":100,"time":{order.duration}}}]'
# Send using appropriate connection
if self._is_persistent and self._keep_alive_manager:
await self._keep_alive_manager.send_message(message)
else:
await self._websocket.send_message(message)
if self.enable_logging:
logger.debug(f"Sent order: {message}")
async def _wait_for_order_result(
self, request_id: str, order: Order, timeout: float = 30.0
) -> OrderResult:
"""Wait for order execution result"""
start_time = time.time()
# Wait for order to appear in tracking system
while time.time() - start_time < timeout:
# Check if order was added to active orders (by _on_order_opened or _on_json_data)
if request_id in self._active_orders:
if self.enable_logging:
logger.success(f" Order {request_id} found in active tracking")
return self._active_orders[request_id]
# Check if order went directly to results (failed or completed)
if request_id in self._order_results:
if self.enable_logging:
logger.info(f"📋 Order {request_id} found in completed results")
return self._order_results[request_id]
await asyncio.sleep(0.2) # Check every 200ms
# Check one more time before creating fallback
if request_id in self._active_orders:
if self.enable_logging:
logger.success(
f" Order {request_id} found in active tracking (final check)"
)
return self._active_orders[request_id]
if request_id in self._order_results:
if self.enable_logging:
logger.info(
f"📋 Order {request_id} found in completed results (final check)"
)
return self._order_results[request_id]
# If timeout, create a fallback result with the original order data
if self.enable_logging:
logger.warning(
f"⏰ Order {request_id} timed out waiting for server response, creating fallback result"
)
fallback_result = OrderResult(
order_id=request_id,
asset=order.asset,
amount=order.amount,
direction=order.direction,
duration=order.duration,
status=OrderStatus.ACTIVE, # Assume it's active since it was placed
placed_at=datetime.now(),
expires_at=datetime.now() + timedelta(seconds=order.duration),
error_message="Timeout waiting for server confirmation",
) # Store it in active orders in case server responds later
self._active_orders[request_id] = fallback_result
if self.enable_logging:
logger.info(f"📝 Created fallback order result for {request_id}")
return fallback_result
async def check_win(
self, order_id: str, max_wait_time: float = 300.0
) -> Optional[Dict[str, Any]]:
"""
Check win functionality - waits for trade completion message
Args:
order_id: Order ID to check
max_wait_time: Maximum time to wait for result (default 5 minutes)
Returns:
Dictionary with trade result or None if timeout/error
"""
start_time = time.time()
if self.enable_logging:
logger.info(
f"🔍 Starting check_win for order {order_id}, max wait: {max_wait_time}s"
)
while time.time() - start_time < max_wait_time:
# Check if order is in completed results
if order_id in self._order_results:
result = self._order_results[order_id]
if self.enable_logging:
logger.success(
f" Order {order_id} completed - Status: {result.status.value}, Profit: ${result.profit:.2f}"
)
return {
"result": "win"
if result.status == OrderStatus.WIN
else "loss"
if result.status == OrderStatus.LOSE
else "draw",
"profit": result.profit if result.profit is not None else 0,
"order_id": order_id,
"completed": True,
"status": result.status.value,
}
# Check if order is still active (not expired yet)
if order_id in self._active_orders:
active_order = self._active_orders[order_id]
time_remaining = (
active_order.expires_at - datetime.now()
).total_seconds()
if time_remaining <= 0:
if self.enable_logging:
logger.info(
f"⏰ Order {order_id} expired but no result yet, continuing to wait..."
)
else:
if (
self.enable_logging and int(time.time() - start_time) % 10 == 0
): # Log every 10 seconds
logger.debug(
f"⌛ Order {order_id} still active, expires in {time_remaining:.0f}s"
)
await asyncio.sleep(1.0) # Check every second
# Timeout reached
if self.enable_logging:
logger.warning(
f"⏰ check_win timeout for order {order_id} after {max_wait_time}s"
)
return {
"result": "timeout",
"order_id": order_id,
"completed": False,
"timeout": True,
}
async def _request_candles(
self, asset: str, timeframe: int, count: int, end_time: datetime
):
"""Request candle data from server using the correct changeSymbol format"""
# Create message data in the format expected by PocketOption for real-time candles
data = {
"asset": str(asset),
"period": timeframe, # timeframe in seconds
}
# Create the full message using changeSymbol
message_data = ["changeSymbol", data]
message = f"42{json.dumps(message_data)}"
if self.enable_logging:
logger.debug(f"Requesting candles with changeSymbol: {message}")
# Create a future to wait for the response
candle_future = asyncio.Future()
request_id = f"{asset}_{timeframe}"
# Store the future for this request
if not hasattr(self, "_candle_requests"):
self._candle_requests = {}
self._candle_requests[request_id] = candle_future
# Send the request using appropriate connection
if self._is_persistent and self._keep_alive_manager:
await self._keep_alive_manager.send_message(message)
else:
await self._websocket.send_message(message)
try:
# Wait for the response (with timeout)
candles = await asyncio.wait_for(candle_future, timeout=10.0)
return candles
except asyncio.TimeoutError:
if self.enable_logging:
logger.warning(f"Candle request timed out for {asset}")
return []
finally:
# Clean up the request
if request_id in self._candle_requests:
del self._candle_requests[request_id]
def _parse_candles_data(self, candles_data: List[Any], asset: str, timeframe: int):
"""Parse candles data from server response"""
candles = []
try:
if isinstance(candles_data, list):
for candle_data in candles_data:
if isinstance(candle_data, (list, tuple)) and len(candle_data) >= 5:
# Server format: [timestamp, open, low, high, close]
# Note: Server sends low/high swapped compared to standard OHLC format
raw_high = float(candle_data[2])
raw_low = float(candle_data[3])
# Ensure high >= low by swapping if necessary
actual_high = max(raw_high, raw_low)
actual_low = min(raw_high, raw_low)
candle = Candle(
timestamp=datetime.fromtimestamp(candle_data[0]),
open=float(candle_data[1]),
high=actual_high,
low=actual_low,
close=float(candle_data[4]),
volume=float(candle_data[5])
if len(candle_data) > 5
else 0.0,
asset=asset,
timeframe=timeframe,
)
candles.append(candle)
except Exception as e:
if self.enable_logging: