Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions frontend/src/api/strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,13 @@ export const useCreateStrategy = () => {
});
};

export const useTestConnection = () => {
return useMutation({
mutationFn: (data: CreateStrategyRequest["exchange_config"]) =>
apiClient.post<ApiResponse<null>>("/strategies/test-connection", data),
});
};

export const useStopStrategy = () => {
const queryClient = useQueryClient();

Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { Wallet } from "lucide-react";
import { useState } from "react";
import { useTestConnection } from "@/api/strategy";
import { Button } from "@/components/ui/button";
import { FieldGroup } from "@/components/ui/field";
import { Label } from "@/components/ui/label";
import { RadioGroupItem } from "@/components/ui/radio-group";
import { SelectItem } from "@/components/ui/select";
import { Spinner } from "@/components/ui/spinner";
import PngIcon from "@/components/valuecell/icon/png-icon";
import { EXCHANGE_ICONS } from "@/constants/icons";
import { withForm } from "@/hooks/use-form";
Expand Down Expand Up @@ -48,8 +53,27 @@ export const ExchangeForm = withForm({
private_key: "",
},
render({ form }) {
const { mutateAsync: testConnection, isPending } = useTestConnection();
const [testStatus, setTestStatus] = useState<{
success: boolean;
message: string;
} | null>(null);

const handleTestConnection = async () => {
setTestStatus(null);
try {
await testConnection(form.state.values);
setTestStatus({ success: true, message: "Success!" });
} catch (_error) {
setTestStatus({
success: false,
message: "Failed, please check your API key",
});
}
};

return (
<FieldGroup className="gap-6">
<FieldGroup className="gap-4">
<form.AppField
listeners={{
onChange: ({ value }) => {
Expand Down Expand Up @@ -167,6 +191,32 @@ export const ExchangeForm = withForm({
);
}}
</form.Subscribe>

<div className="-mt-2 flex flex-col gap-2">
{testStatus && (
<p
className={`font-medium text-sm ${
testStatus.success ? "text-green-600" : "text-red-600"
}`}
>
{testStatus.message}
</p>
)}
<Button
variant="outline"
className="w-full gap-2 py-4 font-medium text-base"
onClick={handleTestConnection}
disabled={isPending}
type="button"
>
{isPending ? (
<Spinner className="size-5 text-gray-500" />
) : (
<Wallet className="size-5" />
)}
Test Connection
</Button>
</div>
</>
)
);
Expand Down
10 changes: 10 additions & 0 deletions python/valuecell/agents/common/trading/execution/ccxt_trading.py
Original file line number Diff line number Diff line change
Expand Up @@ -1280,6 +1280,16 @@ async def _exec_noop(self, inst: TradeInstruction) -> TxResult:
meta=inst.meta,
)

async def test_connection(self) -> bool:
"""Test connectivity and authentication with the exchange."""
try:
# Attempt to fetch balance which requires authentication
await self.fetch_balance()
return True
except Exception as e:
logger.warning(f"⚠️ Connection test failed for {self.exchange_id}: {e}")
return False

async def close(self) -> None:
"""Close the exchange connection and cleanup resources."""
if self._exchange is not None:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,15 @@ async def execute(

raise NotImplementedError

@abstractmethod
async def test_connection(self) -> bool:
"""Test the connection to the exchange/broker.

Returns:
True if connection is successful and credentials are valid, False otherwise.
"""
raise NotImplementedError

@abstractmethod
async def close(self) -> None:
"""Close the gateway and release any held resources.
Expand Down
48 changes: 48 additions & 0 deletions python/valuecell/server/api/routers/strategy_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from sqlalchemy.orm import Session

from valuecell.agents.common.trading.models import (
ExchangeConfig,
StrategyStatus,
StrategyStatusContent,
StrategyType,
Expand Down Expand Up @@ -315,6 +316,53 @@ async def create_strategy_agent(
strategy_id=fallback_strategy_id, status=StrategyStatus.ERROR
)

@router.post("/test-connection")
async def test_exchange_connection(request: ExchangeConfig):
"""Test connection to the exchange with provided credentials."""
try:
# If virtual trading, just return success immediately
if getattr(request, "trading_mode", None) == "virtual":
return SuccessResponse.create(msg="Success!")

from valuecell.agents.common.trading.execution.ccxt_trading import (
create_ccxt_gateway,
)

# Map ExchangeConfig fields to gateway args
# Note: ExchangeConfig might differ slightly from create_ccxt_gateway args
gateway = await create_ccxt_gateway(
exchange_id=request.exchange_id,
api_key=request.api_key or "",
secret_key=request.secret_key or "",
passphrase=request.passphrase,
wallet_address=request.wallet_address,
private_key=request.private_key,
# Ensure we pass a safe default for required args if missing in config
market_type="swap", # Default to swap/perpetual for testing
)

try:
is_connected = await gateway.test_connection()
if is_connected:
return SuccessResponse.create(msg="Success!")
else:
# Return 200 with error message or 400? User asked for "Failed..." return
# We'll throw 400 for UI to catch, or return success=False in body
# But SuccessResponse implies 200.
# If I raise HTTPException it shows as error.
raise HTTPException(
status_code=400, detail="Failed, please check your API key"
)
finally:
await gateway.close()

except Exception as e:
# If create_ccxt_gateway fails or other error
logger.warning(f"Connection test failed: {e}")
raise HTTPException(
status_code=400, detail=f"Failed, please check your API key: {str(e)}"
)

@router.delete("/delete")
async def delete_strategy_agent(
id: str = Query(..., description="Strategy ID"),
Expand Down