import asyncio
import json
import os
from pathlib import Path
from solders.keypair import Keypair
from lasersell_sdk.exit_api import ExitApiClient, BuildBuyTxRequest
from lasersell_sdk.stream.client import StreamClient, StreamConfigure
from lasersell_sdk.stream.session import StreamSession
from lasersell_sdk.tx import SendTargetHeliusSender, send_transaction, sign_unsigned_tx
async def run_agent(mint: str, amount_sol: float):
api_key = os.environ["LASERSELL_API_KEY"]
signer = Keypair.from_bytes(
bytes(json.loads(Path("./keypair.json").read_text()))
)
wallet_pubkey = str(signer.pubkey())
# --- 1. Connect the Exit Intelligence Stream ---
stream_client = StreamClient(api_key)
session = await StreamSession.connect(
stream_client,
StreamConfigure(
wallet_pubkeys=[wallet_pubkey],
strategy={
"target_profit_pct": 10.0,
"stop_loss_pct": 5.0,
"trailing_stop_pct": 3.0,
"sell_on_graduation": True,
},
deadline_timeout_sec=120,
),
)
# --- 2. Build and submit the buy ---
api_client = ExitApiClient.with_api_key(api_key)
buy_request = BuildBuyTxRequest(
mint=mint,
user_pubkey=wallet_pubkey,
amount=amount_sol,
slippage_bps=2_000,
)
response = await api_client.build_buy_tx(buy_request)
signed_tx = sign_unsigned_tx(response.tx, signer)
buy_sig = await send_transaction(SendTargetHeliusSender(), signed_tx)
print(f"Buy submitted: {buy_sig}")
# --- 3. Listen for events and handle exits ---
while True:
event = await session.recv()
if event is None:
print("Stream disconnected")
break
if event.type == "position_opened":
print(f"Tracking position: {event.handle.mint}")
elif event.type == "exit_signal_with_tx":
msg = event.message
print(f"Exit signal: {msg['reason']}")
signed_tx = sign_unsigned_tx(str(msg["unsigned_tx_b64"]), signer)
sig = await send_transaction(SendTargetHeliusSender(), signed_tx)
print(f"Exit submitted: {sig}")
break # Position exited, agent is done
elif event.type == "position_closed":
print(f"Position closed: {event.message['reason']}")
break
asyncio.run(run_agent(
mint="TOKEN_MINT_ADDRESS",
amount_sol=0.1, # 0.1 SOL
))