Compare commits
4
Commits
657c473e82
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d6028fbbf | ||
|
|
d92f152f9b | ||
|
|
ef895b6b9c | ||
|
|
57dcfe7adb |
No files matched your search
@@ -92,7 +92,7 @@ class MyStrategy(Strategy):
|
||||
| --- | --- |
|
||||
| Price / candles | `ctx.price`, `ctx.candles`, `ctx.closes`, `ctx.high(n)`, `ctx.low(n)` |
|
||||
| Portfolio | `ctx.is_flat`, `ctx.side`, `ctx.position`, `ctx.equity`, `ctx.cash` |
|
||||
| Indicators | `ctx.sma(p)`, `ctx.ema(p)`, `ctx.rsi(p)`, `ctx.atr(p)`, `ctx.std(p)`, `ctx.macd()`, `ctx.roc(p)`, `ctx.vwap(p)`, `ctx.supertrend(p, mult)` |
|
||||
| Indicators | `ctx.sma(p)`, `ctx.ema(p)`, `ctx.rsi(p)`, `ctx.atr(p)`, `ctx.std(p)`, `ctx.macd()`, `ctx.roc(p)`, `ctx.vwap(p)`, `ctx.supertrend(p, mult)`, `ctx.williams_r(p)` |
|
||||
| Orders | `ctx.enter_long(size, stop_loss, take_profit, trailing_stop_pct, reason)`, `ctx.enter_short(...)`, `ctx.close(reason)` |
|
||||
|
||||
Notes:
|
||||
|
||||
@@ -208,7 +208,8 @@ template and the `StrategyContext` API.
|
||||
|
||||
Bundled strategies: `sma_cross`, `ema_cross`, `macd_trend`,
|
||||
`bollinger_reversion`, `donchian_breakout`, `momentum`, `rsi_reversion`,
|
||||
`supertrend`, `vwap_reversion`, `ema_cross_short` (short-side example).
|
||||
`supertrend`, `vwap_reversion`, `ema_cross_short` (short-side example),
|
||||
`williams_r`.
|
||||
|
||||
## API
|
||||
|
||||
|
||||
@@ -151,6 +151,22 @@ def roc(values: Sequence[float], period: int = 10) -> list[Number]:
|
||||
return out
|
||||
|
||||
|
||||
def williams_r(candles: Sequence[Candle], period: int = 14) -> list[Number]:
|
||||
"""Williams %R, in [-100, 0]. Below -80 is oversold, above -20 overbought."""
|
||||
if period <= 0:
|
||||
raise ValueError("period must be positive")
|
||||
out: list[Number] = [None] * len(candles)
|
||||
for i in range(period - 1, len(candles)):
|
||||
window = candles[i - period + 1 : i + 1]
|
||||
highest = max(candle.high for candle in window)
|
||||
lowest = min(candle.low for candle in window)
|
||||
if highest == lowest:
|
||||
out[i] = -50.0
|
||||
else:
|
||||
out[i] = (highest - candles[i].close) / (highest - lowest) * -100
|
||||
return out
|
||||
|
||||
|
||||
def typical_price(candle: Candle) -> float:
|
||||
return (candle.high + candle.low + candle.close) / 3
|
||||
|
||||
|
||||
@@ -158,6 +158,8 @@ class MultiStrategyManager:
|
||||
halted=engine_status.halted,
|
||||
halt_reason=engine_status.halt_reason,
|
||||
trades_today=engine_status.trades_today,
|
||||
day_pnl=engine_status.day_pnl,
|
||||
drawdown_pct=engine_status.drawdown_pct,
|
||||
error=engine_status.error,
|
||||
)
|
||||
)
|
||||
|
||||
@@ -15,6 +15,7 @@ from app.engine.indicators import (
|
||||
sma,
|
||||
supertrend,
|
||||
vwap,
|
||||
williams_r,
|
||||
)
|
||||
from app.models import PositionSide
|
||||
from app.schemas import Candle, ParamSpec, StrategyOut
|
||||
@@ -129,6 +130,9 @@ class StrategyContext:
|
||||
def vwap(self, period: int | None = None) -> float | None:
|
||||
return vwap(self._candles, period)[-1]
|
||||
|
||||
def williams_r(self, period: int = 14) -> float | None:
|
||||
return williams_r(self._candles, period)[-1]
|
||||
|
||||
def supertrend(
|
||||
self, period: int = 10, multiplier: float = 3.0
|
||||
) -> tuple[float | None, bool | None]:
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import ClassVar
|
||||
|
||||
from app.engine.strategies.base import Strategy, StrategyContext, register
|
||||
from app.models import PositionSide
|
||||
|
||||
|
||||
@register
|
||||
class WilliamsR(Strategy):
|
||||
"""Williams %R mean reversion, long-only."""
|
||||
|
||||
key: ClassVar[str] = "williams_r"
|
||||
name: ClassVar[str] = "Williams %R"
|
||||
description: ClassVar[str] = (
|
||||
"Enter long when Williams %R is oversold (at or below the oversold "
|
||||
"level) and exit when it becomes overbought. Optional ATR stop."
|
||||
)
|
||||
default_params: ClassVar[dict] = {
|
||||
"period": 14,
|
||||
"oversold": -80.0,
|
||||
"overbought": -20.0,
|
||||
"atr_period": 14,
|
||||
"atr_stop_mult": 2.0,
|
||||
"size": 1.0,
|
||||
}
|
||||
param_help: ClassVar[dict] = {
|
||||
"period": "Williams %R lookback",
|
||||
"oversold": "Oversold level (e.g. -80)",
|
||||
"overbought": "Overbought level (e.g. -20)",
|
||||
"atr_period": "ATR lookback for the stop",
|
||||
"atr_stop_mult": "Stop distance in ATRs (0 disables)",
|
||||
"size": "Fraction of equity per trade",
|
||||
}
|
||||
param_bounds: ClassVar[dict] = {
|
||||
"period": (2, 100),
|
||||
"oversold": (-100.0, -50.0),
|
||||
"overbought": (-50.0, 0.0),
|
||||
"atr_stop_mult": (0.0, 10.0),
|
||||
"size": (0.01, 1.0),
|
||||
}
|
||||
|
||||
def on_candle(self, ctx: StrategyContext) -> None:
|
||||
value = ctx.williams_r(int(self.params["period"]))
|
||||
if value is None:
|
||||
return
|
||||
|
||||
if ctx.is_flat and value <= float(self.params["oversold"]):
|
||||
stop = None
|
||||
mult = float(self.params["atr_stop_mult"])
|
||||
if mult > 0:
|
||||
atr_value = ctx.atr(int(self.params["atr_period"]))
|
||||
if atr_value:
|
||||
stop = ctx.price - mult * atr_value
|
||||
ctx.enter_long(
|
||||
size=float(self.params["size"]),
|
||||
stop_loss=stop,
|
||||
reason=f"Williams %R {value:.1f} oversold",
|
||||
)
|
||||
elif ctx.side == PositionSide.LONG and value >= float(self.params["overbought"]):
|
||||
ctx.close(reason=f"Williams %R {value:.1f} overbought")
|
||||
@@ -177,6 +177,8 @@ class StrategyStatusOut(BaseModel):
|
||||
halted: bool = False
|
||||
halt_reason: str | None = None
|
||||
trades_today: int = 0
|
||||
day_pnl: float = 0.0
|
||||
drawdown_pct: float = 0.0
|
||||
error: str | None = None
|
||||
|
||||
|
||||
|
||||
@@ -134,6 +134,8 @@ def test_start_many_and_multi_status(runtime: Runtime, market: FakeMarketData) -
|
||||
assert status["running"] is True
|
||||
assert len(status["strategies"]) == 2
|
||||
assert status["equity"] == 10000
|
||||
# Per-strategy fields the dashboard aggregates must be present.
|
||||
assert {"day_pnl", "drawdown_pct"} <= set(status["strategies"][0])
|
||||
|
||||
client.post("/api/bot/stop")
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.engine.indicators import williams_r
|
||||
from app.engine.strategies import get_strategy
|
||||
from app.engine.strategies.base import StrategyContext
|
||||
from app.models import Position, PositionSide
|
||||
from app.schemas import Candle
|
||||
|
||||
|
||||
def candles(closes: list[float]) -> list[Candle]:
|
||||
return [
|
||||
Candle(ts=i, open=c, high=c * 1.001, low=c * 0.999, close=c, volume=1.0)
|
||||
for i, c in enumerate(closes)
|
||||
]
|
||||
|
||||
|
||||
def ctx(closes: list[float], position=None) -> StrategyContext:
|
||||
return StrategyContext(candles=candles(closes), position=position, equity=1000.0, cash=1000.0)
|
||||
|
||||
|
||||
# --- indicator ------------------------------------------------------------
|
||||
def test_williams_r_bounds() -> None:
|
||||
series = williams_r(candles([100, 102, 98, 101, 99, 103, 97, 100]), 5)
|
||||
for value in series:
|
||||
if value is not None:
|
||||
assert -100.0 <= value <= 0.0
|
||||
|
||||
|
||||
def test_williams_r_rising_is_overbought() -> None:
|
||||
rising = [float(i) for i in range(1, 30)]
|
||||
value = williams_r(candles(rising), 14)[-1]
|
||||
assert value is not None and value > -50 # near the top of the range
|
||||
|
||||
|
||||
def test_williams_r_falling_is_oversold() -> None:
|
||||
falling = [float(i) for i in range(30, 1, -1)]
|
||||
value = williams_r(candles(falling), 14)[-1]
|
||||
assert value is not None and value < -50 # near the bottom of the range
|
||||
|
||||
|
||||
def test_williams_r_flat_series_is_neutral() -> None:
|
||||
flat = [100.0] * 20
|
||||
assert williams_r(candles(flat), 14)[-1] == pytest.approx(-50.0)
|
||||
|
||||
|
||||
# --- strategy -------------------------------------------------------------
|
||||
def test_williams_r_registered() -> None:
|
||||
from app.engine.strategies import list_strategies
|
||||
|
||||
assert "williams_r" in {c.key for c in list_strategies()}
|
||||
|
||||
|
||||
def test_enters_long_when_oversold() -> None:
|
||||
strategy = get_strategy("williams_r")({"period": 5, "oversold": -80, "atr_stop_mult": 0})
|
||||
falling = [100 - i for i in range(15)]
|
||||
c = ctx([float(x) for x in falling])
|
||||
strategy.on_candle(c)
|
||||
intents = c.take_intents()
|
||||
assert intents and intents[0].action == "enter_long"
|
||||
|
||||
|
||||
def test_exits_when_overbought() -> None:
|
||||
strategy = get_strategy("williams_r")({"period": 5, "overbought": -20, "atr_stop_mult": 0})
|
||||
position = Position(
|
||||
strategy_key="williams_r",
|
||||
symbol="BTC/USDT",
|
||||
side=PositionSide.LONG,
|
||||
qty=1.0,
|
||||
entry_price=100.0,
|
||||
)
|
||||
rising = [100 + i for i in range(15)]
|
||||
c = ctx([float(x) for x in rising], position=position)
|
||||
strategy.on_candle(c)
|
||||
intents = c.take_intents()
|
||||
assert intents and intents[0].action == "close"
|
||||
|
||||
|
||||
def test_atr_stop_is_set_when_enabled() -> None:
|
||||
strategy = get_strategy("williams_r")({"period": 5, "oversold": -80, "atr_stop_mult": 2.0})
|
||||
falling = [float(100 - i) for i in range(15)]
|
||||
c = ctx(falling)
|
||||
strategy.on_candle(c)
|
||||
intents = c.take_intents()
|
||||
assert intents and intents[0].action == "enter_long"
|
||||
assert intents[0].stop_loss is not None
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup>
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { aggregateStatus } from './aggregate'
|
||||
import * as api from './api'
|
||||
import BacktestPanel from './components/BacktestPanel.vue'
|
||||
import EquityChart from './components/EquityChart.vue'
|
||||
@@ -44,6 +45,8 @@ const runningLabel = computed(() => {
|
||||
return `Running: ${list.length} strategies`
|
||||
})
|
||||
|
||||
const displayStatus = computed(() => aggregateStatus(status.value, multiStatus.value))
|
||||
|
||||
const scopeLabel = computed(() => {
|
||||
const list = multiStatus.value.strategies || []
|
||||
if (!list.length) {
|
||||
@@ -298,10 +301,10 @@ onUnmounted(() => {
|
||||
</header>
|
||||
|
||||
<div
|
||||
v-if="status.halted"
|
||||
v-if="displayStatus.halted"
|
||||
class="rounded-lg border border-rose-500 bg-rose-500/20 p-3 text-sm font-semibold text-rose-100"
|
||||
>
|
||||
HALTED — {{ status.halt_reason }}. Trading is stopped and any open position was
|
||||
HALTED — {{ displayStatus.halt_reason }}. Trading is stopped and any open position was
|
||||
flattened. Restart the bot to resume (limits reset).
|
||||
</div>
|
||||
|
||||
@@ -319,7 +322,7 @@ onUnmounted(() => {
|
||||
{{ status.error }}
|
||||
</div>
|
||||
|
||||
<StatusCards :status="status" />
|
||||
<StatusCards :status="displayStatus" />
|
||||
|
||||
<MultiStrategyPanel
|
||||
:strategies="strategies"
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* Top-of-dashboard status. With one strategy it is that strategy's status;
|
||||
* with several, the per-strategy numbers are aggregated for the whole account.
|
||||
*/
|
||||
export function aggregateStatus(status, multiStatus) {
|
||||
const list = multiStatus?.strategies || []
|
||||
if (list.length <= 1) return status
|
||||
|
||||
const sum = (field) => list.reduce((acc, s) => acc + (s[field] || 0), 0)
|
||||
const halted = list.filter((s) => s.halted)
|
||||
|
||||
return {
|
||||
...status,
|
||||
running: multiStatus.running,
|
||||
price: multiStatus.price ?? status.price,
|
||||
cash: sum('cash'),
|
||||
equity: multiStatus.equity,
|
||||
starting_balance: multiStatus.starting_balance,
|
||||
realized_pnl: sum('realized_pnl'),
|
||||
unrealized_pnl: sum('unrealized_pnl'),
|
||||
total_pnl: multiStatus.total_pnl,
|
||||
day_pnl: sum('day_pnl'),
|
||||
// Worst individual strategy drawdown; the portfolio peak is not tracked.
|
||||
drawdown_pct: Math.max(0, ...list.map((s) => s.drawdown_pct || 0)),
|
||||
trades_today: sum('trades_today'),
|
||||
open_positions: sum('open_positions'),
|
||||
halted: halted.length > 0,
|
||||
halt_reason:
|
||||
halted
|
||||
.map((s) => s.halt_reason)
|
||||
.filter(Boolean)
|
||||
.join('; ') || null,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { aggregateStatus } from './aggregate'
|
||||
|
||||
const SINGLE = { equity: 100, total_pnl: 5, strategies: [] }
|
||||
|
||||
function strategy(overrides = {}) {
|
||||
return {
|
||||
strategy_key: 'sma_cross',
|
||||
symbol: 'BTC/USDT',
|
||||
timeframe: '5m',
|
||||
allocation: 0.5,
|
||||
cash: 1000,
|
||||
equity: 1000,
|
||||
realized_pnl: 0,
|
||||
unrealized_pnl: 0,
|
||||
total_pnl: 0,
|
||||
open_positions: 0,
|
||||
halted: false,
|
||||
halt_reason: null,
|
||||
trades_today: 0,
|
||||
day_pnl: 0,
|
||||
drawdown_pct: 0,
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('aggregateStatus', () => {
|
||||
it('returns the plain status when there is at most one strategy', () => {
|
||||
expect(aggregateStatus(SINGLE, { strategies: [] })).toBe(SINGLE)
|
||||
expect(aggregateStatus(SINGLE, { strategies: [strategy()] })).toBe(SINGLE)
|
||||
})
|
||||
|
||||
it('sums the per-strategy numbers', () => {
|
||||
const multi = {
|
||||
running: true,
|
||||
equity: 2100,
|
||||
starting_balance: 2000,
|
||||
total_pnl: 100,
|
||||
price: 123,
|
||||
strategies: [
|
||||
strategy({ cash: 1000, equity: 1100, realized_pnl: 100, unrealized_pnl: 0, total_pnl: 100, trades_today: 2, open_positions: 1, day_pnl: 40 }),
|
||||
strategy({ cash: 1000, equity: 1000, realized_pnl: 0, unrealized_pnl: 0, total_pnl: 0, trades_today: 0, open_positions: 0, day_pnl: -10 }),
|
||||
],
|
||||
}
|
||||
const result = aggregateStatus(SINGLE, multi)
|
||||
expect(result.cash).toBe(2000)
|
||||
expect(result.equity).toBe(2100)
|
||||
expect(result.realized_pnl).toBe(100)
|
||||
expect(result.total_pnl).toBe(100)
|
||||
expect(result.day_pnl).toBe(30)
|
||||
expect(result.trades_today).toBe(2)
|
||||
expect(result.open_positions).toBe(1)
|
||||
expect(result.price).toBe(123)
|
||||
expect(result.running).toBe(true)
|
||||
})
|
||||
|
||||
it('reports the worst drawdown and any halt', () => {
|
||||
const multi = {
|
||||
running: true,
|
||||
equity: 2000,
|
||||
starting_balance: 2000,
|
||||
total_pnl: 0,
|
||||
price: null,
|
||||
strategies: [
|
||||
strategy({ drawdown_pct: 3, halted: false }),
|
||||
strategy({ drawdown_pct: 7.5, halted: true, halt_reason: 'daily loss limit hit' }),
|
||||
],
|
||||
}
|
||||
const result = aggregateStatus(SINGLE, multi)
|
||||
expect(result.drawdown_pct).toBe(7.5)
|
||||
expect(result.halted).toBe(true)
|
||||
expect(result.halt_reason).toBe('daily loss limit hit')
|
||||
})
|
||||
|
||||
it('falls back to the plain price when multi has none', () => {
|
||||
const multi = {
|
||||
running: false,
|
||||
equity: 2000,
|
||||
starting_balance: 2000,
|
||||
total_pnl: 0,
|
||||
price: null,
|
||||
strategies: [strategy(), strategy()],
|
||||
}
|
||||
const result = aggregateStatus({ ...SINGLE, price: 99 }, multi)
|
||||
expect(result.price).toBe(99)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user