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
10 changes: 10 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version: 2
updates:
- package-ecosystem: pip
directory: /
schedule:
interval: weekly
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
30 changes: 30 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
name: CodeQL

on:
push:
branches: [master]
pull_request:
branches: [master]
schedule:
- cron: '23 3 * * 1'

permissions:
contents: read

jobs:
analyze:
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
steps:
# v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
# v3
- uses: github/codeql-action/init@9418214df1f2c4b8128c770156c409013b07d6b9
with:
languages: python
# v3
- uses: github/codeql-action/analyze@9418214df1f2c4b8128c770156c409013b07d6b9
with:
category: '/language:python'
15 changes: 10 additions & 5 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@ jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
# v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
# v5
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
with:
python-version: '3.10'
- uses: astral-sh/setup-uv@v6
- uses: actions/setup-node@v4
# v6
- uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e
# v4
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020
with:
node-version: '22'
- run: uv sync --locked --python 3.10
Expand All @@ -24,5 +28,6 @@ jobs:
containers:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# v4
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
- run: python3 .github/scripts/docker-smoke.py
18 changes: 16 additions & 2 deletions fasttrade/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import os
import logging
import uuid
from threading import Lock
from threading import BoundedSemaphore, Lock
from time import monotonic
from typing import Any, Literal
from urllib.parse import urlsplit
Expand Down Expand Up @@ -437,7 +437,6 @@ def spy_signals(body: SpySignalsRequest):
return result


@app.post('/api/analyze', tags=['Analysis'], responses={200: {'model': AnalysisResponse, 'description': 'Model preference and risk-checked signal'}, 503: {'description': 'Market or model unavailable; no actionable signal'}})
async def analyze(body: AnalysisRequest):
"""Analyze completed candles; incomplete risk inputs produce signal-only results."""
args = parser().parse_args(['analyze', body.symbol.upper(), '--timeframe', body.timeframe])
Expand Down Expand Up @@ -485,6 +484,21 @@ async def analyze(body: AnalysisRequest):
return JSONResponse({'error': 'Analysis failed. Check data and settings.', 'actionable_signal': None}, status_code=503)


_analyze_gate = BoundedSemaphore(1)
_ANALYZE_GATE_SECONDS = 60


@app.post('/api/analyze', tags=['Analysis'], responses={200: {'model': AnalysisResponse, 'description': 'Model preference and risk-checked signal'}, 503: {'description': 'Market or model unavailable, or another local analysis is still running'}})
async def local_analyze(body: AnalysisRequest):
"""Queue overlapping local requests on one paid pipeline instead of running them in parallel."""
if not await run_in_threadpool(_analyze_gate.acquire, True, _ANALYZE_GATE_SECONDS):
return JSONResponse({'error': 'An analysis is already running. Wait for it to finish and try again.', 'actionable_signal': None}, status_code=503)
try:
return await analyze(body)
finally:
_analyze_gate.release()


@app.post('/v1/analyze', tags=['Analysis'])
async def versioned_analyze(body: AnalysisRequest, x_api_key: str = Security(APIKeyHeader(name='X-API-Key', auto_error=False))):
from .batch_api import _authenticate, reserve_single, record_single_usage
Expand Down
45 changes: 45 additions & 0 deletions tests/test_web.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,51 @@ def test_analysis_api_passes_provider_and_rejects_invalid_choice(monkeypatch):
assert client.post('/api/analyze', json={'symbol': 'SPY', 'source': 'other'}).status_code == 422


def test_local_analyze_reports_busy_when_another_analysis_is_running(monkeypatch):
import pytest
from fasttrade import web
monkeypatch.setattr(web, 'run_analysis', lambda args: pytest.fail('must not run while the gate is held'))
monkeypatch.setattr(web, '_ANALYZE_GATE_SECONDS', 0.2)
assert web._analyze_gate.acquire(timeout=0)
try:
client = TestClient(web.app, base_url='http://127.0.0.1:8765', client=('127.0.0.1', 50000))
response = client.post('/api/analyze', json={'symbol': 'SPY', 'timeframe': '5m'})
assert response.status_code == 503 and 'already running' in response.json()['error']
finally:
web._analyze_gate.release()


def test_local_analyze_queues_overlapping_requests_on_one_pipeline(monkeypatch):
import threading
from fasttrade import web
started, release = threading.Event(), threading.Event()
calls, state = [], {'active': 0, 'max': 0}
def slow(args):
calls.append(args)
state['active'] += 1
state['max'] = max(state['max'], state['active'])
if len(calls) == 1:
started.set()
release.wait(5)
state['active'] -= 1
return {'actionable_signal': 'HOLD', 'risk_rejections': []}
monkeypatch.setattr(web, 'run_analysis', slow)
results = []
def post():
client = TestClient(web.app, base_url='http://127.0.0.1:8765', client=('127.0.0.1', 50000))
results.append(client.post('/api/analyze', json={'symbol': 'SPY', 'timeframe': '5m'}))
first = threading.Thread(target=post)
first.start()
assert started.wait(5)
timer = threading.Timer(0.3, release.set)
timer.start()
post()
first.join(5)
timer.join()
assert len(results) == 2 and all(response.status_code == 200 for response in results)
assert state['max'] == 1 and len(calls) == 2


def test_spy_overview_uses_completed_bars_and_reports_news_failure(monkeypatch):
import pandas as pd
import pytest
Expand Down
Loading