agent-loop / solana_quant.py
arudradey's picture
Fix trade_id formatting and torch import safety
1a051f9 verified
Raw History Blame Contribute Delete
5.98 kB
import json
import time
import random
from datetime import datetime
from typing import Dict, Any, List
from storage_manager import STORAGE_DIR
TRADES_FILE = STORAGE_DIR / "trades" / "trades.json"
TRADES_FILE.parent.mkdir(parents=True, exist_ok=True)
# Default Mock Portfolio
DEFAULT_PORTFOLIO = {
"total_aum_usdc": 14250000.0,
"cash_usdc": 3562500.0,
"pnl_24h_usdc": 482150.0,
"pnl_24h_percent": 3.49,
"sharpe_ratio": 3.42,
"max_drawdown": 4.1,
"positions": [
{"symbol": "SOL", "name": "Solana", "amount": 54200.0, "price": 148.50, "value_usdc": 8048700.0, "allocation": 56.5},
{"symbol": "JUP", "name": "Jupiter", "amount": 1350000.0, "price": 0.985, "value_usdc": 1329750.0, "allocation": 9.3},
{"symbol": "RAY", "name": "Raydium", "amount": 420000.0, "price": 2.15, "value_usdc": 903000.0, "allocation": 6.3},
{"symbol": "WIF", "name": "dogwifhat", "amount": 220000.0, "price": 1.84, "value_usdc": 404800.0, "allocation": 2.8},
{"symbol": "USDC", "name": "USD Coin", "amount": 3563750.0, "price": 1.00, "value_usdc": 3563750.0, "allocation": 25.1},
]
}
class SolanaQuantEngine:
def __init__(self):
self.prices = {
"SOL": 148.50,
"JUP": 0.985,
"RAY": 2.15,
"WIF": 1.84,
"BONK": 0.0000215,
}
def get_market_overview(self) -> Dict[str, Any]:
# Small dynamic drift for live feel
for k in self.prices:
drift = random.uniform(-0.002, 0.002)
self.prices[k] = round(self.prices[k] * (1 + drift), 4 if k != "BONK" else 8)
arb_spreads = [
{
"pair": "SOL/USDC",
"buy_venue": "Raydium CPMM",
"sell_venue": "Orca Whirlpool",
"buy_price": self.prices["SOL"],
"sell_price": round(self.prices["SOL"] * 1.0042, 2),
"spread_pct": 0.42,
"net_profit_est": "$6,230",
"confidence": "HIGH",
},
{
"pair": "RAY/SOL",
"buy_venue": "Phoenix CLOB",
"sell_venue": "Jupiter Route",
"buy_price": round(self.prices["RAY"] / self.prices["SOL"], 5),
"sell_price": round((self.prices["RAY"] / self.prices["SOL"]) * 1.0031, 5),
"spread_pct": 0.31,
"net_profit_est": "$2,140",
"confidence": "MEDIUM",
},
{
"pair": "JUP/USDC",
"buy_venue": "Meteora DLMM",
"sell_venue": "Raydium CLMM",
"buy_price": self.prices["JUP"],
"sell_price": round(self.prices["JUP"] * 1.0028, 4),
"spread_pct": 0.28,
"net_profit_est": "$1,890",
"confidence": "HIGH",
}
]
return {
"timestamp": datetime.utcnow().isoformat(),
"prices": self.prices,
"arbitrage_opportunities": arb_spreads,
"portfolio": DEFAULT_PORTFOLIO,
}
def execute_simulated_trade(self, symbol: str, side: str, amount_usdc: float, strategy: str = "AI_MOMENTUM") -> Dict[str, Any]:
px = self.prices.get(symbol.upper(), 100.0)
tokens = round(amount_usdc / px, 4)
trade = {
"trade_id": f"TX_{str(int(time.time() * 1000))[-8:]}",
"timestamp": datetime.utcnow().isoformat(),
"symbol": symbol.upper(),
"side": side.upper(),
"amount_usdc": amount_usdc,
"executed_tokens": tokens,
"execution_price": px,
"venue": "Jupiter Swap Aggregator v6",
"slippage_bps": random.randint(3, 12),
"priority_fee_lamports": 150000,
"strategy": strategy,
"status": "CONFIRMED_ON_CHAIN",
}
# Persist to storage
history = self.get_trade_history()
history.insert(0, trade)
try:
TRADES_FILE.write_text(json.dumps(history[:50], indent=2), encoding="utf-8")
except Exception:
pass
return trade
def get_trade_history(self) -> List[Dict[str, Any]]:
if TRADES_FILE.exists():
try:
return json.loads(TRADES_FILE.read_text(encoding="utf-8"))
except Exception:
pass
# Initial Seed Trades
seed = [
{
"trade_id": "TX_94827110",
"timestamp": "2026-09-14T12:45:10Z",
"symbol": "SOL",
"side": "BUY",
"amount_usdc": 250000.0,
"executed_tokens": 1683.5,
"execution_price": 148.50,
"venue": "Raydium CPMM",
"slippage_bps": 5,
"strategy": "AI_MOMENTUM",
"status": "CONFIRMED_ON_CHAIN"
},
{
"trade_id": "TX_94823419",
"timestamp": "2026-09-14T12:30:22Z",
"symbol": "JUP",
"side": "BUY",
"amount_usdc": 120000.0,
"executed_tokens": 121827.4,
"execution_price": 0.985,
"venue": "Jupiter Route",
"slippage_bps": 4,
"strategy": "DEX_ARBITRAGE",
"status": "CONFIRMED_ON_CHAIN"
},
{
"trade_id": "TX_94819201",
"timestamp": "2026-09-14T12:10:05Z",
"symbol": "RAY",
"side": "SELL",
"amount_usdc": 75000.0,
"executed_tokens": 34883.7,
"execution_price": 2.15,
"venue": "Orca Whirlpool",
"slippage_bps": 8,
"strategy": "RISK_REBALANCE",
"status": "CONFIRMED_ON_CHAIN"
}
]
return seed
solana_quant = SolanaQuantEngine()