Strategy
The strategy API lets you build and backtest trading strategies with entry/exit signals, stop-loss, and take-profit.
Declaration
ts
strategy('My Strategy', { overlay: true })- name
string— strategy name shown in the legend - opts
{ overlay?: boolean }—trueto draw signals on the price chart (default:true)
strategy.entry(id, direction, opts?)
Open a new position. If a position in the opposite direction is open, it is closed first.
- id
string— position identifier - direction
'long' | 'short'— trade direction - opts
{ sl?: number, tp?: number, label?: string }- sl — stop-loss price level
- tp — take-profit price level
- label — custom label for the signal marker (defaults to
id)
ts
strategy.entry('Long', 'long', { sl: close - ta.atr(14) * 2, tp: close + ta.atr(14) * 3 })strategy.close(id?)
Close an existing position. If id is provided, only closes the position with that ID.
ts
strategy.close('Long') // close specific position
strategy.close() // close any open positionstrategy.position_size
Read-only property indicating the current position state:
| Value | Meaning |
|---|---|
0 | Flat (no position) |
1 | Long |
-1 | Short |
ts
if (strategy.position_size === 0) {
// No open position — look for entries
}Backtest Stats
After a strategy runs, Tradify Charts computes these statistics:
| Stat | Description |
|---|---|
totalTrades | Number of completed round-trip trades |
winRate | Fraction of winning trades (0–1) |
totalPnL | Sum of all trade PnLs |
maxDrawdown | Largest peak-to-trough equity decline |
sharpeRatio | Risk-adjusted return (mean / std dev) |
profitFactor | Gross profit / gross loss |
avgWin | Average profit on winning trades |
avgLoss | Average loss on losing trades |
Stats are displayed in the console output after execution.
Full Example
ts
strategy('RSI Mean Reversion', { overlay: true })
const rsi = ta.rsi(close, 14)
const atr = ta.atr(14)
if (rsi < 30 && strategy.position_size === 0) {
strategy.entry('Long', 'long', {
sl: close - atr * 2,
tp: close + atr * 3,
})
}
if (rsi > 70) strategy.close('Long')