Trr3 / r2.py
Riy777's picture
Create r2.py
f82903c verified
import boto3
import json
import os
from io import BytesIO
from botocore.exceptions import ClientError
class R2Manager:
def __init__(self):
self.account_id = os.environ.get("R2_ACCOUNT_ID")
self.access_key = os.environ.get("R2_ACCESS_KEY_ID")
self.secret_key = os.environ.get("R2_SECRET_ACCESS_KEY")
self.bucket_name = "trading-bot-data" # تأكد من إنشاء هذا الـ Bucket في R2
self.file_key = "portfolio_data.json"
self.s3 = boto3.client(
service_name='s3',
endpoint_url=f'https://{self.account_id}.r2.cloudflarestorage.com',
aws_access_key_id=self.access_key,
aws_secret_access_key=self.secret_key
)
# تهيئة مبدئية إذا لم يكن الملف موجوداً
self._initialize_if_not_exists()
def _initialize_if_not_exists(self):
try:
self.s3.head_object(Bucket=self.bucket_name, Key=self.file_key)
except ClientError:
# إنشاء هيكل أولي للمحفظة
initial_data = {
"balance": 1000.0, # رصيد افتراضي
"active_position": None, # {symbol, entry_price, amount, tp, sl, timestamp}
"history": [],
"stats": {"wins": 0, "losses": 0, "total_pnl": 0.0}
}
self.save_data(initial_data)
def get_data(self):
try:
response = self.s3.get_object(Bucket=self.bucket_name, Key=self.file_key)
return json.loads(response['Body'].read().decode('utf-8'))
except Exception as e:
print(f"Error reading from R2: {e}")
return None
def save_data(self, data):
try:
self.s3.put_object(
Bucket=self.bucket_name,
Key=self.file_key,
Body=json.dumps(data, indent=2)
)
return True
except Exception as e:
print(f"Error saving to R2: {e}")
return False